Sumitwarrior7 commited on
Commit
f4db5dd
·
verified ·
1 Parent(s): b05bcf6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__init__.py +25 -0
  2. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/clique.py +259 -0
  3. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/clustering_coefficient.py +71 -0
  4. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/connectivity.py +412 -0
  5. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/distance_measures.py +150 -0
  6. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/dominating_set.py +149 -0
  7. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/kcomponents.py +369 -0
  8. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/matching.py +44 -0
  9. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/maxcut.py +143 -0
  10. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/ramsey.py +53 -0
  11. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/steinertree.py +231 -0
  12. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__init__.py +0 -0
  13. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py +41 -0
  14. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_clique.py +112 -0
  15. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py +199 -0
  16. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py +59 -0
  17. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py +78 -0
  18. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py +303 -0
  19. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_matching.py +8 -0
  20. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py +94 -0
  21. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py +31 -0
  22. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py +265 -0
  23. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py +977 -0
  24. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py +280 -0
  25. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py +68 -0
  26. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/traveling_salesman.py +1501 -0
  27. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/treewidth.py +252 -0
  28. .venv/lib/python3.10/site-packages/networkx/algorithms/approximation/vertex_cover.py +83 -0
  29. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/__init__.py +20 -0
  30. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/betweenness.py +436 -0
  31. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/betweenness_subset.py +275 -0
  32. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/closeness.py +282 -0
  33. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/current_flow_betweenness.py +342 -0
  34. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/current_flow_betweenness_subset.py +227 -0
  35. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/current_flow_closeness.py +96 -0
  36. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/degree_alg.py +150 -0
  37. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/dispersion.py +107 -0
  38. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/eigenvector.py +357 -0
  39. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/flow_matrix.py +130 -0
  40. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/group.py +787 -0
  41. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/harmonic.py +89 -0
  42. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/katz.py +331 -0
  43. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/laplacian.py +150 -0
  44. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/load.py +200 -0
  45. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/percolation.py +128 -0
  46. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/reaching.py +209 -0
  47. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/second_order.py +141 -0
  48. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/subgraph_alg.py +340 -0
  49. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__init__.py +0 -0
  50. .venv/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_betweenness_centrality.py +780 -0
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Approximations of graph properties and Heuristic methods for optimization.
2
+
3
+ The functions in this class are not imported into the top-level ``networkx``
4
+ namespace so the easiest way to use them is with::
5
+
6
+ >>> from networkx.algorithms import approximation
7
+
8
+ Another option is to import the specific function with
9
+ ``from networkx.algorithms.approximation import function_name``.
10
+
11
+ """
12
+
13
+ from networkx.algorithms.approximation.clustering_coefficient import *
14
+ from networkx.algorithms.approximation.clique import *
15
+ from networkx.algorithms.approximation.connectivity import *
16
+ from networkx.algorithms.approximation.distance_measures import *
17
+ from networkx.algorithms.approximation.dominating_set import *
18
+ from networkx.algorithms.approximation.kcomponents import *
19
+ from networkx.algorithms.approximation.matching import *
20
+ from networkx.algorithms.approximation.ramsey import *
21
+ from networkx.algorithms.approximation.steinertree import *
22
+ from networkx.algorithms.approximation.traveling_salesman import *
23
+ from networkx.algorithms.approximation.treewidth import *
24
+ from networkx.algorithms.approximation.vertex_cover import *
25
+ from networkx.algorithms.approximation.maxcut import *
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/clique.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing large cliques and maximum independent sets."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import ramsey
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = [
8
+ "clique_removal",
9
+ "max_clique",
10
+ "large_clique_size",
11
+ "maximum_independent_set",
12
+ ]
13
+
14
+
15
+ @not_implemented_for("directed")
16
+ @not_implemented_for("multigraph")
17
+ @nx._dispatchable
18
+ def maximum_independent_set(G):
19
+ """Returns an approximate maximum independent set.
20
+
21
+ Independent set or stable set is a set of vertices in a graph, no two of
22
+ which are adjacent. That is, it is a set I of vertices such that for every
23
+ two vertices in I, there is no edge connecting the two. Equivalently, each
24
+ edge in the graph has at most one endpoint in I. The size of an independent
25
+ set is the number of vertices it contains [1]_.
26
+
27
+ A maximum independent set is a largest independent set for a given graph G
28
+ and its size is denoted $\\alpha(G)$. The problem of finding such a set is called
29
+ the maximum independent set problem and is an NP-hard optimization problem.
30
+ As such, it is unlikely that there exists an efficient algorithm for finding
31
+ a maximum independent set of a graph.
32
+
33
+ The Independent Set algorithm is based on [2]_.
34
+
35
+ Parameters
36
+ ----------
37
+ G : NetworkX graph
38
+ Undirected graph
39
+
40
+ Returns
41
+ -------
42
+ iset : Set
43
+ The apx-maximum independent set
44
+
45
+ Examples
46
+ --------
47
+ >>> G = nx.path_graph(10)
48
+ >>> nx.approximation.maximum_independent_set(G)
49
+ {0, 2, 4, 6, 9}
50
+
51
+ Raises
52
+ ------
53
+ NetworkXNotImplemented
54
+ If the graph is directed or is a multigraph.
55
+
56
+ Notes
57
+ -----
58
+ Finds the $O(|V|/(log|V|)^2)$ apx of independent set in the worst case.
59
+
60
+ References
61
+ ----------
62
+ .. [1] `Wikipedia: Independent set
63
+ <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
64
+ .. [2] Boppana, R., & Halldórsson, M. M. (1992).
65
+ Approximating maximum independent sets by excluding subgraphs.
66
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
67
+ """
68
+ iset, _ = clique_removal(G)
69
+ return iset
70
+
71
+
72
+ @not_implemented_for("directed")
73
+ @not_implemented_for("multigraph")
74
+ @nx._dispatchable
75
+ def max_clique(G):
76
+ r"""Find the Maximum Clique
77
+
78
+ Finds the $O(|V|/(log|V|)^2)$ apx of maximum clique/independent set
79
+ in the worst case.
80
+
81
+ Parameters
82
+ ----------
83
+ G : NetworkX graph
84
+ Undirected graph
85
+
86
+ Returns
87
+ -------
88
+ clique : set
89
+ The apx-maximum clique of the graph
90
+
91
+ Examples
92
+ --------
93
+ >>> G = nx.path_graph(10)
94
+ >>> nx.approximation.max_clique(G)
95
+ {8, 9}
96
+
97
+ Raises
98
+ ------
99
+ NetworkXNotImplemented
100
+ If the graph is directed or is a multigraph.
101
+
102
+ Notes
103
+ -----
104
+ A clique in an undirected graph G = (V, E) is a subset of the vertex set
105
+ `C \subseteq V` such that for every two vertices in C there exists an edge
106
+ connecting the two. This is equivalent to saying that the subgraph
107
+ induced by C is complete (in some cases, the term clique may also refer
108
+ to the subgraph).
109
+
110
+ A maximum clique is a clique of the largest possible size in a given graph.
111
+ The clique number `\omega(G)` of a graph G is the number of
112
+ vertices in a maximum clique in G. The intersection number of
113
+ G is the smallest number of cliques that together cover all edges of G.
114
+
115
+ https://en.wikipedia.org/wiki/Maximum_clique
116
+
117
+ References
118
+ ----------
119
+ .. [1] Boppana, R., & Halldórsson, M. M. (1992).
120
+ Approximating maximum independent sets by excluding subgraphs.
121
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
122
+ doi:10.1007/BF01994876
123
+ """
124
+ # finding the maximum clique in a graph is equivalent to finding
125
+ # the independent set in the complementary graph
126
+ cgraph = nx.complement(G)
127
+ iset, _ = clique_removal(cgraph)
128
+ return iset
129
+
130
+
131
+ @not_implemented_for("directed")
132
+ @not_implemented_for("multigraph")
133
+ @nx._dispatchable
134
+ def clique_removal(G):
135
+ r"""Repeatedly remove cliques from the graph.
136
+
137
+ Results in a $O(|V|/(\log |V|)^2)$ approximation of maximum clique
138
+ and independent set. Returns the largest independent set found, along
139
+ with found maximal cliques.
140
+
141
+ Parameters
142
+ ----------
143
+ G : NetworkX graph
144
+ Undirected graph
145
+
146
+ Returns
147
+ -------
148
+ max_ind_cliques : (set, list) tuple
149
+ 2-tuple of Maximal Independent Set and list of maximal cliques (sets).
150
+
151
+ Examples
152
+ --------
153
+ >>> G = nx.path_graph(10)
154
+ >>> nx.approximation.clique_removal(G)
155
+ ({0, 2, 4, 6, 9}, [{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}])
156
+
157
+ Raises
158
+ ------
159
+ NetworkXNotImplemented
160
+ If the graph is directed or is a multigraph.
161
+
162
+ References
163
+ ----------
164
+ .. [1] Boppana, R., & Halldórsson, M. M. (1992).
165
+ Approximating maximum independent sets by excluding subgraphs.
166
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
167
+ """
168
+ graph = G.copy()
169
+ c_i, i_i = ramsey.ramsey_R2(graph)
170
+ cliques = [c_i]
171
+ isets = [i_i]
172
+ while graph:
173
+ graph.remove_nodes_from(c_i)
174
+ c_i, i_i = ramsey.ramsey_R2(graph)
175
+ if c_i:
176
+ cliques.append(c_i)
177
+ if i_i:
178
+ isets.append(i_i)
179
+ # Determine the largest independent set as measured by cardinality.
180
+ maxiset = max(isets, key=len)
181
+ return maxiset, cliques
182
+
183
+
184
+ @not_implemented_for("directed")
185
+ @not_implemented_for("multigraph")
186
+ @nx._dispatchable
187
+ def large_clique_size(G):
188
+ """Find the size of a large clique in a graph.
189
+
190
+ A *clique* is a subset of nodes in which each pair of nodes is
191
+ adjacent. This function is a heuristic for finding the size of a
192
+ large clique in the graph.
193
+
194
+ Parameters
195
+ ----------
196
+ G : NetworkX graph
197
+
198
+ Returns
199
+ -------
200
+ k: integer
201
+ The size of a large clique in the graph.
202
+
203
+ Examples
204
+ --------
205
+ >>> G = nx.path_graph(10)
206
+ >>> nx.approximation.large_clique_size(G)
207
+ 2
208
+
209
+ Raises
210
+ ------
211
+ NetworkXNotImplemented
212
+ If the graph is directed or is a multigraph.
213
+
214
+ Notes
215
+ -----
216
+ This implementation is from [1]_. Its worst case time complexity is
217
+ :math:`O(n d^2)`, where *n* is the number of nodes in the graph and
218
+ *d* is the maximum degree.
219
+
220
+ This function is a heuristic, which means it may work well in
221
+ practice, but there is no rigorous mathematical guarantee on the
222
+ ratio between the returned number and the actual largest clique size
223
+ in the graph.
224
+
225
+ References
226
+ ----------
227
+ .. [1] Pattabiraman, Bharath, et al.
228
+ "Fast Algorithms for the Maximum Clique Problem on Massive Graphs
229
+ with Applications to Overlapping Community Detection."
230
+ *Internet Mathematics* 11.4-5 (2015): 421--448.
231
+ <https://doi.org/10.1080/15427951.2014.986778>
232
+
233
+ See also
234
+ --------
235
+
236
+ :func:`networkx.algorithms.approximation.clique.max_clique`
237
+ A function that returns an approximate maximum clique with a
238
+ guarantee on the approximation ratio.
239
+
240
+ :mod:`networkx.algorithms.clique`
241
+ Functions for finding the exact maximum clique in a graph.
242
+
243
+ """
244
+ degrees = G.degree
245
+
246
+ def _clique_heuristic(G, U, size, best_size):
247
+ if not U:
248
+ return max(best_size, size)
249
+ u = max(U, key=degrees)
250
+ U.remove(u)
251
+ N_prime = {v for v in G[u] if degrees[v] >= best_size}
252
+ return _clique_heuristic(G, U & N_prime, size + 1, best_size)
253
+
254
+ best_size = 0
255
+ nodes = (u for u in G if degrees[u] >= best_size)
256
+ for u in nodes:
257
+ neighbors = {v for v in G[u] if degrees[v] >= best_size}
258
+ best_size = _clique_heuristic(G, neighbors, 1, best_size)
259
+ return best_size
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/clustering_coefficient.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.utils import not_implemented_for, py_random_state
3
+
4
+ __all__ = ["average_clustering"]
5
+
6
+
7
+ @not_implemented_for("directed")
8
+ @py_random_state(2)
9
+ @nx._dispatchable(name="approximate_average_clustering")
10
+ def average_clustering(G, trials=1000, seed=None):
11
+ r"""Estimates the average clustering coefficient of G.
12
+
13
+ The local clustering of each node in `G` is the fraction of triangles
14
+ that actually exist over all possible triangles in its neighborhood.
15
+ The average clustering coefficient of a graph `G` is the mean of
16
+ local clusterings.
17
+
18
+ This function finds an approximate average clustering coefficient
19
+ for G by repeating `n` times (defined in `trials`) the following
20
+ experiment: choose a node at random, choose two of its neighbors
21
+ at random, and check if they are connected. The approximate
22
+ coefficient is the fraction of triangles found over the number
23
+ of trials [1]_.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ trials : integer
30
+ Number of trials to perform (default 1000).
31
+
32
+ seed : integer, random_state, or None (default)
33
+ Indicator of random number generation state.
34
+ See :ref:`Randomness<randomness>`.
35
+
36
+ Returns
37
+ -------
38
+ c : float
39
+ Approximated average clustering coefficient.
40
+
41
+ Examples
42
+ --------
43
+ >>> from networkx.algorithms import approximation
44
+ >>> G = nx.erdos_renyi_graph(10, 0.2, seed=10)
45
+ >>> approximation.average_clustering(G, trials=1000, seed=10)
46
+ 0.214
47
+
48
+ Raises
49
+ ------
50
+ NetworkXNotImplemented
51
+ If G is directed.
52
+
53
+ References
54
+ ----------
55
+ .. [1] Schank, Thomas, and Dorothea Wagner. Approximating clustering
56
+ coefficient and transitivity. Universität Karlsruhe, Fakultät für
57
+ Informatik, 2004.
58
+ https://doi.org/10.5445/IR/1000001239
59
+
60
+ """
61
+ n = len(G)
62
+ triangles = 0
63
+ nodes = list(G)
64
+ for i in [int(seed.random() * n) for i in range(trials)]:
65
+ nbrs = list(G[nodes[i]])
66
+ if len(nbrs) < 2:
67
+ continue
68
+ u, v = seed.sample(nbrs, 2)
69
+ if u in G[v]:
70
+ triangles += 1
71
+ return triangles / trials
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/connectivity.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast approximation for node connectivity"""
2
+
3
+ import itertools
4
+ from operator import itemgetter
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = [
9
+ "local_node_connectivity",
10
+ "node_connectivity",
11
+ "all_pairs_node_connectivity",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(name="approximate_local_node_connectivity")
16
+ def local_node_connectivity(G, source, target, cutoff=None):
17
+ """Compute node connectivity between source and target.
18
+
19
+ Pairwise or local node connectivity between two distinct and nonadjacent
20
+ nodes is the minimum number of nodes that must be removed (minimum
21
+ separating cutset) to disconnect them. By Menger's theorem, this is equal
22
+ to the number of node independent paths (paths that share no nodes other
23
+ than source and target). Which is what we compute in this function.
24
+
25
+ This algorithm is a fast approximation that gives an strict lower
26
+ bound on the actual number of node independent paths between two nodes [1]_.
27
+ It works for both directed and undirected graphs.
28
+
29
+ Parameters
30
+ ----------
31
+
32
+ G : NetworkX graph
33
+
34
+ source : node
35
+ Starting node for node connectivity
36
+
37
+ target : node
38
+ Ending node for node connectivity
39
+
40
+ cutoff : integer
41
+ Maximum node connectivity to consider. If None, the minimum degree
42
+ of source or target is used as a cutoff. Default value None.
43
+
44
+ Returns
45
+ -------
46
+ k: integer
47
+ pairwise node connectivity
48
+
49
+ Examples
50
+ --------
51
+ >>> # Platonic octahedral graph has node connectivity 4
52
+ >>> # for each non adjacent node pair
53
+ >>> from networkx.algorithms import approximation as approx
54
+ >>> G = nx.octahedral_graph()
55
+ >>> approx.local_node_connectivity(G, 0, 5)
56
+ 4
57
+
58
+ Notes
59
+ -----
60
+ This algorithm [1]_ finds node independents paths between two nodes by
61
+ computing their shortest path using BFS, marking the nodes of the path
62
+ found as 'used' and then searching other shortest paths excluding the
63
+ nodes marked as used until no more paths exist. It is not exact because
64
+ a shortest path could use nodes that, if the path were longer, may belong
65
+ to two different node independent paths. Thus it only guarantees an
66
+ strict lower bound on node connectivity.
67
+
68
+ Note that the authors propose a further refinement, losing accuracy and
69
+ gaining speed, which is not implemented yet.
70
+
71
+ See also
72
+ --------
73
+ all_pairs_node_connectivity
74
+ node_connectivity
75
+
76
+ References
77
+ ----------
78
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
79
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
80
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
81
+
82
+ """
83
+ if target == source:
84
+ raise nx.NetworkXError("source and target have to be different nodes.")
85
+
86
+ # Maximum possible node independent paths
87
+ if G.is_directed():
88
+ possible = min(G.out_degree(source), G.in_degree(target))
89
+ else:
90
+ possible = min(G.degree(source), G.degree(target))
91
+
92
+ K = 0
93
+ if not possible:
94
+ return K
95
+
96
+ if cutoff is None:
97
+ cutoff = float("inf")
98
+
99
+ exclude = set()
100
+ for i in range(min(possible, cutoff)):
101
+ try:
102
+ path = _bidirectional_shortest_path(G, source, target, exclude)
103
+ exclude.update(set(path))
104
+ K += 1
105
+ except nx.NetworkXNoPath:
106
+ break
107
+
108
+ return K
109
+
110
+
111
+ @nx._dispatchable(name="approximate_node_connectivity")
112
+ def node_connectivity(G, s=None, t=None):
113
+ r"""Returns an approximation for node connectivity for a graph or digraph G.
114
+
115
+ Node connectivity is equal to the minimum number of nodes that
116
+ must be removed to disconnect G or render it trivial. By Menger's theorem,
117
+ this is equal to the number of node independent paths (paths that
118
+ share no nodes other than source and target).
119
+
120
+ If source and target nodes are provided, this function returns the
121
+ local node connectivity: the minimum number of nodes that must be
122
+ removed to break all paths from source to target in G.
123
+
124
+ This algorithm is based on a fast approximation that gives an strict lower
125
+ bound on the actual number of node independent paths between two nodes [1]_.
126
+ It works for both directed and undirected graphs.
127
+
128
+ Parameters
129
+ ----------
130
+ G : NetworkX graph
131
+ Undirected graph
132
+
133
+ s : node
134
+ Source node. Optional. Default value: None.
135
+
136
+ t : node
137
+ Target node. Optional. Default value: None.
138
+
139
+ Returns
140
+ -------
141
+ K : integer
142
+ Node connectivity of G, or local node connectivity if source
143
+ and target are provided.
144
+
145
+ Examples
146
+ --------
147
+ >>> # Platonic octahedral graph is 4-node-connected
148
+ >>> from networkx.algorithms import approximation as approx
149
+ >>> G = nx.octahedral_graph()
150
+ >>> approx.node_connectivity(G)
151
+ 4
152
+
153
+ Notes
154
+ -----
155
+ This algorithm [1]_ finds node independents paths between two nodes by
156
+ computing their shortest path using BFS, marking the nodes of the path
157
+ found as 'used' and then searching other shortest paths excluding the
158
+ nodes marked as used until no more paths exist. It is not exact because
159
+ a shortest path could use nodes that, if the path were longer, may belong
160
+ to two different node independent paths. Thus it only guarantees an
161
+ strict lower bound on node connectivity.
162
+
163
+ See also
164
+ --------
165
+ all_pairs_node_connectivity
166
+ local_node_connectivity
167
+
168
+ References
169
+ ----------
170
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
171
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
172
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
173
+
174
+ """
175
+ if (s is not None and t is None) or (s is None and t is not None):
176
+ raise nx.NetworkXError("Both source and target must be specified.")
177
+
178
+ # Local node connectivity
179
+ if s is not None and t is not None:
180
+ if s not in G:
181
+ raise nx.NetworkXError(f"node {s} not in graph")
182
+ if t not in G:
183
+ raise nx.NetworkXError(f"node {t} not in graph")
184
+ return local_node_connectivity(G, s, t)
185
+
186
+ # Global node connectivity
187
+ if G.is_directed():
188
+ connected_func = nx.is_weakly_connected
189
+ iter_func = itertools.permutations
190
+
191
+ def neighbors(v):
192
+ return itertools.chain(G.predecessors(v), G.successors(v))
193
+
194
+ else:
195
+ connected_func = nx.is_connected
196
+ iter_func = itertools.combinations
197
+ neighbors = G.neighbors
198
+
199
+ if not connected_func(G):
200
+ return 0
201
+
202
+ # Choose a node with minimum degree
203
+ v, minimum_degree = min(G.degree(), key=itemgetter(1))
204
+ # Node connectivity is bounded by minimum degree
205
+ K = minimum_degree
206
+ # compute local node connectivity with all non-neighbors nodes
207
+ # and store the minimum
208
+ for w in set(G) - set(neighbors(v)) - {v}:
209
+ K = min(K, local_node_connectivity(G, v, w, cutoff=K))
210
+ # Same for non adjacent pairs of neighbors of v
211
+ for x, y in iter_func(neighbors(v), 2):
212
+ if y not in G[x] and x != y:
213
+ K = min(K, local_node_connectivity(G, x, y, cutoff=K))
214
+ return K
215
+
216
+
217
+ @nx._dispatchable(name="approximate_all_pairs_node_connectivity")
218
+ def all_pairs_node_connectivity(G, nbunch=None, cutoff=None):
219
+ """Compute node connectivity between all pairs of nodes.
220
+
221
+ Pairwise or local node connectivity between two distinct and nonadjacent
222
+ nodes is the minimum number of nodes that must be removed (minimum
223
+ separating cutset) to disconnect them. By Menger's theorem, this is equal
224
+ to the number of node independent paths (paths that share no nodes other
225
+ than source and target). Which is what we compute in this function.
226
+
227
+ This algorithm is a fast approximation that gives an strict lower
228
+ bound on the actual number of node independent paths between two nodes [1]_.
229
+ It works for both directed and undirected graphs.
230
+
231
+
232
+ Parameters
233
+ ----------
234
+ G : NetworkX graph
235
+
236
+ nbunch: container
237
+ Container of nodes. If provided node connectivity will be computed
238
+ only over pairs of nodes in nbunch.
239
+
240
+ cutoff : integer
241
+ Maximum node connectivity to consider. If None, the minimum degree
242
+ of source or target is used as a cutoff in each pair of nodes.
243
+ Default value None.
244
+
245
+ Returns
246
+ -------
247
+ K : dictionary
248
+ Dictionary, keyed by source and target, of pairwise node connectivity
249
+
250
+ Examples
251
+ --------
252
+ A 3 node cycle with one extra node attached has connectivity 2 between all
253
+ nodes in the cycle and connectivity 1 between the extra node and the rest:
254
+
255
+ >>> G = nx.cycle_graph(3)
256
+ >>> G.add_edge(2, 3)
257
+ >>> import pprint # for nice dictionary formatting
258
+ >>> pprint.pprint(nx.all_pairs_node_connectivity(G))
259
+ {0: {1: 2, 2: 2, 3: 1},
260
+ 1: {0: 2, 2: 2, 3: 1},
261
+ 2: {0: 2, 1: 2, 3: 1},
262
+ 3: {0: 1, 1: 1, 2: 1}}
263
+
264
+ See Also
265
+ --------
266
+ local_node_connectivity
267
+ node_connectivity
268
+
269
+ References
270
+ ----------
271
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
272
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
273
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
274
+ """
275
+ if nbunch is None:
276
+ nbunch = G
277
+ else:
278
+ nbunch = set(nbunch)
279
+
280
+ directed = G.is_directed()
281
+ if directed:
282
+ iter_func = itertools.permutations
283
+ else:
284
+ iter_func = itertools.combinations
285
+
286
+ all_pairs = {n: {} for n in nbunch}
287
+
288
+ for u, v in iter_func(nbunch, 2):
289
+ k = local_node_connectivity(G, u, v, cutoff=cutoff)
290
+ all_pairs[u][v] = k
291
+ if not directed:
292
+ all_pairs[v][u] = k
293
+
294
+ return all_pairs
295
+
296
+
297
+ def _bidirectional_shortest_path(G, source, target, exclude):
298
+ """Returns shortest path between source and target ignoring nodes in the
299
+ container 'exclude'.
300
+
301
+ Parameters
302
+ ----------
303
+
304
+ G : NetworkX graph
305
+
306
+ source : node
307
+ Starting node for path
308
+
309
+ target : node
310
+ Ending node for path
311
+
312
+ exclude: container
313
+ Container for nodes to exclude from the search for shortest paths
314
+
315
+ Returns
316
+ -------
317
+ path: list
318
+ Shortest path between source and target ignoring nodes in 'exclude'
319
+
320
+ Raises
321
+ ------
322
+ NetworkXNoPath
323
+ If there is no path or if nodes are adjacent and have only one path
324
+ between them
325
+
326
+ Notes
327
+ -----
328
+ This function and its helper are originally from
329
+ networkx.algorithms.shortest_paths.unweighted and are modified to
330
+ accept the extra parameter 'exclude', which is a container for nodes
331
+ already used in other paths that should be ignored.
332
+
333
+ References
334
+ ----------
335
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
336
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
337
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
338
+
339
+ """
340
+ # call helper to do the real work
341
+ results = _bidirectional_pred_succ(G, source, target, exclude)
342
+ pred, succ, w = results
343
+
344
+ # build path from pred+w+succ
345
+ path = []
346
+ # from source to w
347
+ while w is not None:
348
+ path.append(w)
349
+ w = pred[w]
350
+ path.reverse()
351
+ # from w to target
352
+ w = succ[path[-1]]
353
+ while w is not None:
354
+ path.append(w)
355
+ w = succ[w]
356
+
357
+ return path
358
+
359
+
360
+ def _bidirectional_pred_succ(G, source, target, exclude):
361
+ # does BFS from both source and target and meets in the middle
362
+ # excludes nodes in the container "exclude" from the search
363
+
364
+ # handle either directed or undirected
365
+ if G.is_directed():
366
+ Gpred = G.predecessors
367
+ Gsucc = G.successors
368
+ else:
369
+ Gpred = G.neighbors
370
+ Gsucc = G.neighbors
371
+
372
+ # predecessor and successors in search
373
+ pred = {source: None}
374
+ succ = {target: None}
375
+
376
+ # initialize fringes, start with forward
377
+ forward_fringe = [source]
378
+ reverse_fringe = [target]
379
+
380
+ level = 0
381
+
382
+ while forward_fringe and reverse_fringe:
383
+ # Make sure that we iterate one step forward and one step backwards
384
+ # thus source and target will only trigger "found path" when they are
385
+ # adjacent and then they can be safely included in the container 'exclude'
386
+ level += 1
387
+ if level % 2 != 0:
388
+ this_level = forward_fringe
389
+ forward_fringe = []
390
+ for v in this_level:
391
+ for w in Gsucc(v):
392
+ if w in exclude:
393
+ continue
394
+ if w not in pred:
395
+ forward_fringe.append(w)
396
+ pred[w] = v
397
+ if w in succ:
398
+ return pred, succ, w # found path
399
+ else:
400
+ this_level = reverse_fringe
401
+ reverse_fringe = []
402
+ for v in this_level:
403
+ for w in Gpred(v):
404
+ if w in exclude:
405
+ continue
406
+ if w not in succ:
407
+ succ[w] = v
408
+ reverse_fringe.append(w)
409
+ if w in pred:
410
+ return pred, succ, w # found path
411
+
412
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/distance_measures.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distance measures approximated metrics."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import py_random_state
5
+
6
+ __all__ = ["diameter"]
7
+
8
+
9
+ @py_random_state(1)
10
+ @nx._dispatchable(name="approximate_diameter")
11
+ def diameter(G, seed=None):
12
+ """Returns a lower bound on the diameter of the graph G.
13
+
14
+ The function computes a lower bound on the diameter (i.e., the maximum eccentricity)
15
+ of a directed or undirected graph G. The procedure used varies depending on the graph
16
+ being directed or not.
17
+
18
+ If G is an `undirected` graph, then the function uses the `2-sweep` algorithm [1]_.
19
+ The main idea is to pick the farthest node from a random node and return its eccentricity.
20
+
21
+ Otherwise, if G is a `directed` graph, the function uses the `2-dSweep` algorithm [2]_,
22
+ The procedure starts by selecting a random source node $s$ from which it performs a
23
+ forward and a backward BFS. Let $a_1$ and $a_2$ be the farthest nodes in the forward and
24
+ backward cases, respectively. Then, it computes the backward eccentricity of $a_1$ using
25
+ a backward BFS and the forward eccentricity of $a_2$ using a forward BFS.
26
+ Finally, it returns the best lower bound between the two.
27
+
28
+ In both cases, the time complexity is linear with respect to the size of G.
29
+
30
+ Parameters
31
+ ----------
32
+ G : NetworkX graph
33
+
34
+ seed : integer, random_state, or None (default)
35
+ Indicator of random number generation state.
36
+ See :ref:`Randomness<randomness>`.
37
+
38
+ Returns
39
+ -------
40
+ d : integer
41
+ Lower Bound on the Diameter of G
42
+
43
+ Examples
44
+ --------
45
+ >>> G = nx.path_graph(10) # undirected graph
46
+ >>> nx.diameter(G)
47
+ 9
48
+ >>> G = nx.cycle_graph(3, create_using=nx.DiGraph) # directed graph
49
+ >>> nx.diameter(G)
50
+ 2
51
+
52
+ Raises
53
+ ------
54
+ NetworkXError
55
+ If the graph is empty or
56
+ If the graph is undirected and not connected or
57
+ If the graph is directed and not strongly connected.
58
+
59
+ See Also
60
+ --------
61
+ networkx.algorithms.distance_measures.diameter
62
+
63
+ References
64
+ ----------
65
+ .. [1] Magnien, Clémence, Matthieu Latapy, and Michel Habib.
66
+ *Fast computation of empirically tight bounds for the diameter of massive graphs.*
67
+ Journal of Experimental Algorithmics (JEA), 2009.
68
+ https://arxiv.org/pdf/0904.2728.pdf
69
+ .. [2] Crescenzi, Pierluigi, Roberto Grossi, Leonardo Lanzi, and Andrea Marino.
70
+ *On computing the diameter of real-world directed (weighted) graphs.*
71
+ International Symposium on Experimental Algorithms. Springer, Berlin, Heidelberg, 2012.
72
+ https://courses.cs.ut.ee/MTAT.03.238/2014_fall/uploads/Main/diameter.pdf
73
+ """
74
+ # if G is empty
75
+ if not G:
76
+ raise nx.NetworkXError("Expected non-empty NetworkX graph!")
77
+ # if there's only a node
78
+ if G.number_of_nodes() == 1:
79
+ return 0
80
+ # if G is directed
81
+ if G.is_directed():
82
+ return _two_sweep_directed(G, seed)
83
+ # else if G is undirected
84
+ return _two_sweep_undirected(G, seed)
85
+
86
+
87
+ def _two_sweep_undirected(G, seed):
88
+ """Helper function for finding a lower bound on the diameter
89
+ for undirected Graphs.
90
+
91
+ The idea is to pick the farthest node from a random node
92
+ and return its eccentricity.
93
+
94
+ ``G`` is a NetworkX undirected graph.
95
+
96
+ .. note::
97
+
98
+ ``seed`` is a random.Random or numpy.random.RandomState instance
99
+ """
100
+ # select a random source node
101
+ source = seed.choice(list(G))
102
+ # get the distances to the other nodes
103
+ distances = nx.shortest_path_length(G, source)
104
+ # if some nodes have not been visited, then the graph is not connected
105
+ if len(distances) != len(G):
106
+ raise nx.NetworkXError("Graph not connected.")
107
+ # take a node that is (one of) the farthest nodes from the source
108
+ *_, node = distances
109
+ # return the eccentricity of the node
110
+ return nx.eccentricity(G, node)
111
+
112
+
113
+ def _two_sweep_directed(G, seed):
114
+ """Helper function for finding a lower bound on the diameter
115
+ for directed Graphs.
116
+
117
+ It implements 2-dSweep, the directed version of the 2-sweep algorithm.
118
+ The algorithm follows the following steps.
119
+ 1. Select a source node $s$ at random.
120
+ 2. Perform a forward BFS from $s$ to select a node $a_1$ at the maximum
121
+ distance from the source, and compute $LB_1$, the backward eccentricity of $a_1$.
122
+ 3. Perform a backward BFS from $s$ to select a node $a_2$ at the maximum
123
+ distance from the source, and compute $LB_2$, the forward eccentricity of $a_2$.
124
+ 4. Return the maximum between $LB_1$ and $LB_2$.
125
+
126
+ ``G`` is a NetworkX directed graph.
127
+
128
+ .. note::
129
+
130
+ ``seed`` is a random.Random or numpy.random.RandomState instance
131
+ """
132
+ # get a new digraph G' with the edges reversed in the opposite direction
133
+ G_reversed = G.reverse()
134
+ # select a random source node
135
+ source = seed.choice(list(G))
136
+ # compute forward distances from source
137
+ forward_distances = nx.shortest_path_length(G, source)
138
+ # compute backward distances from source
139
+ backward_distances = nx.shortest_path_length(G_reversed, source)
140
+ # if either the source can't reach every node or not every node
141
+ # can reach the source, then the graph is not strongly connected
142
+ n = len(G)
143
+ if len(forward_distances) != n or len(backward_distances) != n:
144
+ raise nx.NetworkXError("DiGraph not strongly connected.")
145
+ # take a node a_1 at the maximum distance from the source in G
146
+ *_, a_1 = forward_distances
147
+ # take a node a_2 at the maximum distance from the source in G_reversed
148
+ *_, a_2 = backward_distances
149
+ # return the max between the backward eccentricity of a_1 and the forward eccentricity of a_2
150
+ return max(nx.eccentricity(G_reversed, a_1), nx.eccentricity(G, a_2))
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/dominating_set.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for finding node and edge dominating sets.
2
+
3
+ A `dominating set`_ for an undirected graph *G* with vertex set *V*
4
+ and edge set *E* is a subset *D* of *V* such that every vertex not in
5
+ *D* is adjacent to at least one member of *D*. An `edge dominating set`_
6
+ is a subset *F* of *E* such that every edge not in *F* is
7
+ incident to an endpoint of at least one edge in *F*.
8
+
9
+ .. _dominating set: https://en.wikipedia.org/wiki/Dominating_set
10
+ .. _edge dominating set: https://en.wikipedia.org/wiki/Edge_dominating_set
11
+
12
+ """
13
+
14
+ import networkx as nx
15
+
16
+ from ...utils import not_implemented_for
17
+ from ..matching import maximal_matching
18
+
19
+ __all__ = ["min_weighted_dominating_set", "min_edge_dominating_set"]
20
+
21
+
22
+ # TODO Why doesn't this algorithm work for directed graphs?
23
+ @not_implemented_for("directed")
24
+ @nx._dispatchable(node_attrs="weight")
25
+ def min_weighted_dominating_set(G, weight=None):
26
+ r"""Returns a dominating set that approximates the minimum weight node
27
+ dominating set.
28
+
29
+ Parameters
30
+ ----------
31
+ G : NetworkX graph
32
+ Undirected graph.
33
+
34
+ weight : string
35
+ The node attribute storing the weight of an node. If provided,
36
+ the node attribute with this key must be a number for each
37
+ node. If not provided, each node is assumed to have weight one.
38
+
39
+ Returns
40
+ -------
41
+ min_weight_dominating_set : set
42
+ A set of nodes, the sum of whose weights is no more than `(\log
43
+ w(V)) w(V^*)`, where `w(V)` denotes the sum of the weights of
44
+ each node in the graph and `w(V^*)` denotes the sum of the
45
+ weights of each node in the minimum weight dominating set.
46
+
47
+ Examples
48
+ --------
49
+ >>> G = nx.Graph([(0, 1), (0, 4), (1, 4), (1, 2), (2, 3), (3, 4), (2, 5)])
50
+ >>> nx.approximation.min_weighted_dominating_set(G)
51
+ {1, 2, 4}
52
+
53
+ Raises
54
+ ------
55
+ NetworkXNotImplemented
56
+ If G is directed.
57
+
58
+ Notes
59
+ -----
60
+ This algorithm computes an approximate minimum weighted dominating
61
+ set for the graph `G`. The returned solution has weight `(\log
62
+ w(V)) w(V^*)`, where `w(V)` denotes the sum of the weights of each
63
+ node in the graph and `w(V^*)` denotes the sum of the weights of
64
+ each node in the minimum weight dominating set for the graph.
65
+
66
+ This implementation of the algorithm runs in $O(m)$ time, where $m$
67
+ is the number of edges in the graph.
68
+
69
+ References
70
+ ----------
71
+ .. [1] Vazirani, Vijay V.
72
+ *Approximation Algorithms*.
73
+ Springer Science & Business Media, 2001.
74
+
75
+ """
76
+ # The unique dominating set for the null graph is the empty set.
77
+ if len(G) == 0:
78
+ return set()
79
+
80
+ # This is the dominating set that will eventually be returned.
81
+ dom_set = set()
82
+
83
+ def _cost(node_and_neighborhood):
84
+ """Returns the cost-effectiveness of greedily choosing the given
85
+ node.
86
+
87
+ `node_and_neighborhood` is a two-tuple comprising a node and its
88
+ closed neighborhood.
89
+
90
+ """
91
+ v, neighborhood = node_and_neighborhood
92
+ return G.nodes[v].get(weight, 1) / len(neighborhood - dom_set)
93
+
94
+ # This is a set of all vertices not already covered by the
95
+ # dominating set.
96
+ vertices = set(G)
97
+ # This is a dictionary mapping each node to the closed neighborhood
98
+ # of that node.
99
+ neighborhoods = {v: {v} | set(G[v]) for v in G}
100
+
101
+ # Continue until all vertices are adjacent to some node in the
102
+ # dominating set.
103
+ while vertices:
104
+ # Find the most cost-effective node to add, along with its
105
+ # closed neighborhood.
106
+ dom_node, min_set = min(neighborhoods.items(), key=_cost)
107
+ # Add the node to the dominating set and reduce the remaining
108
+ # set of nodes to cover.
109
+ dom_set.add(dom_node)
110
+ del neighborhoods[dom_node]
111
+ vertices -= min_set
112
+
113
+ return dom_set
114
+
115
+
116
+ @nx._dispatchable
117
+ def min_edge_dominating_set(G):
118
+ r"""Returns minimum cardinality edge dominating set.
119
+
120
+ Parameters
121
+ ----------
122
+ G : NetworkX graph
123
+ Undirected graph
124
+
125
+ Returns
126
+ -------
127
+ min_edge_dominating_set : set
128
+ Returns a set of dominating edges whose size is no more than 2 * OPT.
129
+
130
+ Examples
131
+ --------
132
+ >>> G = nx.petersen_graph()
133
+ >>> nx.approximation.min_edge_dominating_set(G)
134
+ {(0, 1), (4, 9), (6, 8), (5, 7), (2, 3)}
135
+
136
+ Raises
137
+ ------
138
+ ValueError
139
+ If the input graph `G` is empty.
140
+
141
+ Notes
142
+ -----
143
+ The algorithm computes an approximate solution to the edge dominating set
144
+ problem. The result is no more than 2 * OPT in terms of size of the set.
145
+ Runtime of the algorithm is $O(|E|)$.
146
+ """
147
+ if not G:
148
+ raise ValueError("Expected non-empty NetworkX graph!")
149
+ return maximal_matching(G)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/kcomponents.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast approximation for k-component structure"""
2
+
3
+ import itertools
4
+ from collections import defaultdict
5
+ from collections.abc import Mapping
6
+ from functools import cached_property
7
+
8
+ import networkx as nx
9
+ from networkx.algorithms.approximation import local_node_connectivity
10
+ from networkx.exception import NetworkXError
11
+ from networkx.utils import not_implemented_for
12
+
13
+ __all__ = ["k_components"]
14
+
15
+
16
+ @not_implemented_for("directed")
17
+ @nx._dispatchable(name="approximate_k_components")
18
+ def k_components(G, min_density=0.95):
19
+ r"""Returns the approximate k-component structure of a graph G.
20
+
21
+ A `k`-component is a maximal subgraph of a graph G that has, at least,
22
+ node connectivity `k`: we need to remove at least `k` nodes to break it
23
+ into more components. `k`-components have an inherent hierarchical
24
+ structure because they are nested in terms of connectivity: a connected
25
+ graph can contain several 2-components, each of which can contain
26
+ one or more 3-components, and so forth.
27
+
28
+ This implementation is based on the fast heuristics to approximate
29
+ the `k`-component structure of a graph [1]_. Which, in turn, it is based on
30
+ a fast approximation algorithm for finding good lower bounds of the number
31
+ of node independent paths between two nodes [2]_.
32
+
33
+ Parameters
34
+ ----------
35
+ G : NetworkX graph
36
+ Undirected graph
37
+
38
+ min_density : Float
39
+ Density relaxation threshold. Default value 0.95
40
+
41
+ Returns
42
+ -------
43
+ k_components : dict
44
+ Dictionary with connectivity level `k` as key and a list of
45
+ sets of nodes that form a k-component of level `k` as values.
46
+
47
+ Raises
48
+ ------
49
+ NetworkXNotImplemented
50
+ If G is directed.
51
+
52
+ Examples
53
+ --------
54
+ >>> # Petersen graph has 10 nodes and it is triconnected, thus all
55
+ >>> # nodes are in a single component on all three connectivity levels
56
+ >>> from networkx.algorithms import approximation as apxa
57
+ >>> G = nx.petersen_graph()
58
+ >>> k_components = apxa.k_components(G)
59
+
60
+ Notes
61
+ -----
62
+ The logic of the approximation algorithm for computing the `k`-component
63
+ structure [1]_ is based on repeatedly applying simple and fast algorithms
64
+ for `k`-cores and biconnected components in order to narrow down the
65
+ number of pairs of nodes over which we have to compute White and Newman's
66
+ approximation algorithm for finding node independent paths [2]_. More
67
+ formally, this algorithm is based on Whitney's theorem, which states
68
+ an inclusion relation among node connectivity, edge connectivity, and
69
+ minimum degree for any graph G. This theorem implies that every
70
+ `k`-component is nested inside a `k`-edge-component, which in turn,
71
+ is contained in a `k`-core. Thus, this algorithm computes node independent
72
+ paths among pairs of nodes in each biconnected part of each `k`-core,
73
+ and repeats this procedure for each `k` from 3 to the maximal core number
74
+ of a node in the input graph.
75
+
76
+ Because, in practice, many nodes of the core of level `k` inside a
77
+ bicomponent actually are part of a component of level k, the auxiliary
78
+ graph needed for the algorithm is likely to be very dense. Thus, we use
79
+ a complement graph data structure (see `AntiGraph`) to save memory.
80
+ AntiGraph only stores information of the edges that are *not* present
81
+ in the actual auxiliary graph. When applying algorithms to this
82
+ complement graph data structure, it behaves as if it were the dense
83
+ version.
84
+
85
+ See also
86
+ --------
87
+ k_components
88
+
89
+ References
90
+ ----------
91
+ .. [1] Torrents, J. and F. Ferraro (2015) Structural Cohesion:
92
+ Visualization and Heuristics for Fast Computation.
93
+ https://arxiv.org/pdf/1503.04476v1
94
+
95
+ .. [2] White, Douglas R., and Mark Newman (2001) A Fast Algorithm for
96
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
97
+ https://www.santafe.edu/research/results/working-papers/fast-approximation-algorithms-for-finding-node-ind
98
+
99
+ .. [3] Moody, J. and D. White (2003). Social cohesion and embeddedness:
100
+ A hierarchical conception of social groups.
101
+ American Sociological Review 68(1), 103--28.
102
+ https://doi.org/10.2307/3088904
103
+
104
+ """
105
+ # Dictionary with connectivity level (k) as keys and a list of
106
+ # sets of nodes that form a k-component as values
107
+ k_components = defaultdict(list)
108
+ # make a few functions local for speed
109
+ node_connectivity = local_node_connectivity
110
+ k_core = nx.k_core
111
+ core_number = nx.core_number
112
+ biconnected_components = nx.biconnected_components
113
+ combinations = itertools.combinations
114
+ # Exact solution for k = {1,2}
115
+ # There is a linear time algorithm for triconnectivity, if we had an
116
+ # implementation available we could start from k = 4.
117
+ for component in nx.connected_components(G):
118
+ # isolated nodes have connectivity 0
119
+ comp = set(component)
120
+ if len(comp) > 1:
121
+ k_components[1].append(comp)
122
+ for bicomponent in nx.biconnected_components(G):
123
+ # avoid considering dyads as bicomponents
124
+ bicomp = set(bicomponent)
125
+ if len(bicomp) > 2:
126
+ k_components[2].append(bicomp)
127
+ # There is no k-component of k > maximum core number
128
+ # \kappa(G) <= \lambda(G) <= \delta(G)
129
+ g_cnumber = core_number(G)
130
+ max_core = max(g_cnumber.values())
131
+ for k in range(3, max_core + 1):
132
+ C = k_core(G, k, core_number=g_cnumber)
133
+ for nodes in biconnected_components(C):
134
+ # Build a subgraph SG induced by the nodes that are part of
135
+ # each biconnected component of the k-core subgraph C.
136
+ if len(nodes) < k:
137
+ continue
138
+ SG = G.subgraph(nodes)
139
+ # Build auxiliary graph
140
+ H = _AntiGraph()
141
+ H.add_nodes_from(SG.nodes())
142
+ for u, v in combinations(SG, 2):
143
+ K = node_connectivity(SG, u, v, cutoff=k)
144
+ if k > K:
145
+ H.add_edge(u, v)
146
+ for h_nodes in biconnected_components(H):
147
+ if len(h_nodes) <= k:
148
+ continue
149
+ SH = H.subgraph(h_nodes)
150
+ for Gc in _cliques_heuristic(SG, SH, k, min_density):
151
+ for k_nodes in biconnected_components(Gc):
152
+ Gk = nx.k_core(SG.subgraph(k_nodes), k)
153
+ if len(Gk) <= k:
154
+ continue
155
+ k_components[k].append(set(Gk))
156
+ return k_components
157
+
158
+
159
+ def _cliques_heuristic(G, H, k, min_density):
160
+ h_cnumber = nx.core_number(H)
161
+ for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)):
162
+ cands = {n for n, c in h_cnumber.items() if c == c_value}
163
+ # Skip checking for overlap for the highest core value
164
+ if i == 0:
165
+ overlap = False
166
+ else:
167
+ overlap = set.intersection(
168
+ *[{x for x in H[n] if x not in cands} for n in cands]
169
+ )
170
+ if overlap and len(overlap) < k:
171
+ SH = H.subgraph(cands | overlap)
172
+ else:
173
+ SH = H.subgraph(cands)
174
+ sh_cnumber = nx.core_number(SH)
175
+ SG = nx.k_core(G.subgraph(SH), k)
176
+ while not (_same(sh_cnumber) and nx.density(SH) >= min_density):
177
+ # This subgraph must be writable => .copy()
178
+ SH = H.subgraph(SG).copy()
179
+ if len(SH) <= k:
180
+ break
181
+ sh_cnumber = nx.core_number(SH)
182
+ sh_deg = dict(SH.degree())
183
+ min_deg = min(sh_deg.values())
184
+ SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg)
185
+ SG = nx.k_core(G.subgraph(SH), k)
186
+ else:
187
+ yield SG
188
+
189
+
190
+ def _same(measure, tol=0):
191
+ vals = set(measure.values())
192
+ if (max(vals) - min(vals)) <= tol:
193
+ return True
194
+ return False
195
+
196
+
197
+ class _AntiGraph(nx.Graph):
198
+ """
199
+ Class for complement graphs.
200
+
201
+ The main goal is to be able to work with big and dense graphs with
202
+ a low memory footprint.
203
+
204
+ In this class you add the edges that *do not exist* in the dense graph,
205
+ the report methods of the class return the neighbors, the edges and
206
+ the degree as if it was the dense graph. Thus it's possible to use
207
+ an instance of this class with some of NetworkX functions. In this
208
+ case we only use k-core, connected_components, and biconnected_components.
209
+ """
210
+
211
+ all_edge_dict = {"weight": 1}
212
+
213
+ def single_edge_dict(self):
214
+ return self.all_edge_dict
215
+
216
+ edge_attr_dict_factory = single_edge_dict # type: ignore[assignment]
217
+
218
+ def __getitem__(self, n):
219
+ """Returns a dict of neighbors of node n in the dense graph.
220
+
221
+ Parameters
222
+ ----------
223
+ n : node
224
+ A node in the graph.
225
+
226
+ Returns
227
+ -------
228
+ adj_dict : dictionary
229
+ The adjacency dictionary for nodes connected to n.
230
+
231
+ """
232
+ all_edge_dict = self.all_edge_dict
233
+ return {
234
+ node: all_edge_dict for node in set(self._adj) - set(self._adj[n]) - {n}
235
+ }
236
+
237
+ def neighbors(self, n):
238
+ """Returns an iterator over all neighbors of node n in the
239
+ dense graph.
240
+ """
241
+ try:
242
+ return iter(set(self._adj) - set(self._adj[n]) - {n})
243
+ except KeyError as err:
244
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
245
+
246
+ class AntiAtlasView(Mapping):
247
+ """An adjacency inner dict for AntiGraph"""
248
+
249
+ def __init__(self, graph, node):
250
+ self._graph = graph
251
+ self._atlas = graph._adj[node]
252
+ self._node = node
253
+
254
+ def __len__(self):
255
+ return len(self._graph) - len(self._atlas) - 1
256
+
257
+ def __iter__(self):
258
+ return (n for n in self._graph if n not in self._atlas and n != self._node)
259
+
260
+ def __getitem__(self, nbr):
261
+ nbrs = set(self._graph._adj) - set(self._atlas) - {self._node}
262
+ if nbr in nbrs:
263
+ return self._graph.all_edge_dict
264
+ raise KeyError(nbr)
265
+
266
+ class AntiAdjacencyView(AntiAtlasView):
267
+ """An adjacency outer dict for AntiGraph"""
268
+
269
+ def __init__(self, graph):
270
+ self._graph = graph
271
+ self._atlas = graph._adj
272
+
273
+ def __len__(self):
274
+ return len(self._atlas)
275
+
276
+ def __iter__(self):
277
+ return iter(self._graph)
278
+
279
+ def __getitem__(self, node):
280
+ if node not in self._graph:
281
+ raise KeyError(node)
282
+ return self._graph.AntiAtlasView(self._graph, node)
283
+
284
+ @cached_property
285
+ def adj(self):
286
+ return self.AntiAdjacencyView(self)
287
+
288
+ def subgraph(self, nodes):
289
+ """This subgraph method returns a full AntiGraph. Not a View"""
290
+ nodes = set(nodes)
291
+ G = _AntiGraph()
292
+ G.add_nodes_from(nodes)
293
+ for n in G:
294
+ Gnbrs = G.adjlist_inner_dict_factory()
295
+ G._adj[n] = Gnbrs
296
+ for nbr, d in self._adj[n].items():
297
+ if nbr in G._adj:
298
+ Gnbrs[nbr] = d
299
+ G._adj[nbr][n] = d
300
+ G.graph = self.graph
301
+ return G
302
+
303
+ class AntiDegreeView(nx.reportviews.DegreeView):
304
+ def __iter__(self):
305
+ all_nodes = set(self._succ)
306
+ for n in self._nodes:
307
+ nbrs = all_nodes - set(self._succ[n]) - {n}
308
+ yield (n, len(nbrs))
309
+
310
+ def __getitem__(self, n):
311
+ nbrs = set(self._succ) - set(self._succ[n]) - {n}
312
+ # AntiGraph is a ThinGraph so all edges have weight 1
313
+ return len(nbrs) + (n in nbrs)
314
+
315
+ @cached_property
316
+ def degree(self):
317
+ """Returns an iterator for (node, degree) and degree for single node.
318
+
319
+ The node degree is the number of edges adjacent to the node.
320
+
321
+ Parameters
322
+ ----------
323
+ nbunch : iterable container, optional (default=all nodes)
324
+ A container of nodes. The container will be iterated
325
+ through once.
326
+
327
+ weight : string or None, optional (default=None)
328
+ The edge attribute that holds the numerical value used
329
+ as a weight. If None, then each edge has weight 1.
330
+ The degree is the sum of the edge weights adjacent to the node.
331
+
332
+ Returns
333
+ -------
334
+ deg:
335
+ Degree of the node, if a single node is passed as argument.
336
+ nd_iter : an iterator
337
+ The iterator returns two-tuples of (node, degree).
338
+
339
+ See Also
340
+ --------
341
+ degree
342
+
343
+ Examples
344
+ --------
345
+ >>> G = nx.path_graph(4)
346
+ >>> G.degree(0) # node 0 with degree 1
347
+ 1
348
+ >>> list(G.degree([0, 1]))
349
+ [(0, 1), (1, 2)]
350
+
351
+ """
352
+ return self.AntiDegreeView(self)
353
+
354
+ def adjacency(self):
355
+ """Returns an iterator of (node, adjacency set) tuples for all nodes
356
+ in the dense graph.
357
+
358
+ This is the fastest way to look at every edge.
359
+ For directed graphs, only outgoing adjacencies are included.
360
+
361
+ Returns
362
+ -------
363
+ adj_iter : iterator
364
+ An iterator of (node, adjacency set) for all nodes in
365
+ the graph.
366
+
367
+ """
368
+ for n in self._adj:
369
+ yield (n, set(self._adj) - set(self._adj[n]) - {n})
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/matching.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **************
3
+ Graph Matching
4
+ **************
5
+
6
+ Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent
7
+ edges; that is, no two edges share a common vertex.
8
+
9
+ `Wikipedia: Matching <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
10
+ """
11
+
12
+ import networkx as nx
13
+
14
+ __all__ = ["min_maximal_matching"]
15
+
16
+
17
+ @nx._dispatchable
18
+ def min_maximal_matching(G):
19
+ r"""Returns the minimum maximal matching of G. That is, out of all maximal
20
+ matchings of the graph G, the smallest is returned.
21
+
22
+ Parameters
23
+ ----------
24
+ G : NetworkX graph
25
+ Undirected graph
26
+
27
+ Returns
28
+ -------
29
+ min_maximal_matching : set
30
+ Returns a set of edges such that no two edges share a common endpoint
31
+ and every edge not in the set shares some common endpoint in the set.
32
+ Cardinality will be 2*OPT in the worst case.
33
+
34
+ Notes
35
+ -----
36
+ The algorithm computes an approximate solution for the minimum maximal
37
+ cardinality matching problem. The solution is no more than 2 * OPT in size.
38
+ Runtime is $O(|E|)$.
39
+
40
+ References
41
+ ----------
42
+ .. [1] Vazirani, Vijay Approximation Algorithms (2001)
43
+ """
44
+ return nx.maximal_matching(G)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/maxcut.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.utils.decorators import not_implemented_for, py_random_state
3
+
4
+ __all__ = ["randomized_partitioning", "one_exchange"]
5
+
6
+
7
+ @not_implemented_for("directed")
8
+ @not_implemented_for("multigraph")
9
+ @py_random_state(1)
10
+ @nx._dispatchable(edge_attrs="weight")
11
+ def randomized_partitioning(G, seed=None, p=0.5, weight=None):
12
+ """Compute a random partitioning of the graph nodes and its cut value.
13
+
14
+ A partitioning is calculated by observing each node
15
+ and deciding to add it to the partition with probability `p`,
16
+ returning a random cut and its corresponding value (the
17
+ sum of weights of edges connecting different partitions).
18
+
19
+ Parameters
20
+ ----------
21
+ G : NetworkX graph
22
+
23
+ seed : integer, random_state, or None (default)
24
+ Indicator of random number generation state.
25
+ See :ref:`Randomness<randomness>`.
26
+
27
+ p : scalar
28
+ Probability for each node to be part of the first partition.
29
+ Should be in [0,1]
30
+
31
+ weight : object
32
+ Edge attribute key to use as weight. If not specified, edges
33
+ have weight one.
34
+
35
+ Returns
36
+ -------
37
+ cut_size : scalar
38
+ Value of the minimum cut.
39
+
40
+ partition : pair of node sets
41
+ A partitioning of the nodes that defines a minimum cut.
42
+
43
+ Examples
44
+ --------
45
+ >>> G = nx.complete_graph(5)
46
+ >>> cut_size, partition = nx.approximation.randomized_partitioning(G, seed=1)
47
+ >>> cut_size
48
+ 6
49
+ >>> partition
50
+ ({0, 3, 4}, {1, 2})
51
+
52
+ Raises
53
+ ------
54
+ NetworkXNotImplemented
55
+ If the graph is directed or is a multigraph.
56
+ """
57
+ cut = {node for node in G.nodes() if seed.random() < p}
58
+ cut_size = nx.algorithms.cut_size(G, cut, weight=weight)
59
+ partition = (cut, G.nodes - cut)
60
+ return cut_size, partition
61
+
62
+
63
+ def _swap_node_partition(cut, node):
64
+ return cut - {node} if node in cut else cut.union({node})
65
+
66
+
67
+ @not_implemented_for("directed")
68
+ @not_implemented_for("multigraph")
69
+ @py_random_state(2)
70
+ @nx._dispatchable(edge_attrs="weight")
71
+ def one_exchange(G, initial_cut=None, seed=None, weight=None):
72
+ """Compute a partitioning of the graphs nodes and the corresponding cut value.
73
+
74
+ Use a greedy one exchange strategy to find a locally maximal cut
75
+ and its value, it works by finding the best node (one that gives
76
+ the highest gain to the cut value) to add to the current cut
77
+ and repeats this process until no improvement can be made.
78
+
79
+ Parameters
80
+ ----------
81
+ G : networkx Graph
82
+ Graph to find a maximum cut for.
83
+
84
+ initial_cut : set
85
+ Cut to use as a starting point. If not supplied the algorithm
86
+ starts with an empty cut.
87
+
88
+ seed : integer, random_state, or None (default)
89
+ Indicator of random number generation state.
90
+ See :ref:`Randomness<randomness>`.
91
+
92
+ weight : object
93
+ Edge attribute key to use as weight. If not specified, edges
94
+ have weight one.
95
+
96
+ Returns
97
+ -------
98
+ cut_value : scalar
99
+ Value of the maximum cut.
100
+
101
+ partition : pair of node sets
102
+ A partitioning of the nodes that defines a maximum cut.
103
+
104
+ Examples
105
+ --------
106
+ >>> G = nx.complete_graph(5)
107
+ >>> curr_cut_size, partition = nx.approximation.one_exchange(G, seed=1)
108
+ >>> curr_cut_size
109
+ 6
110
+ >>> partition
111
+ ({0, 2}, {1, 3, 4})
112
+
113
+ Raises
114
+ ------
115
+ NetworkXNotImplemented
116
+ If the graph is directed or is a multigraph.
117
+ """
118
+ if initial_cut is None:
119
+ initial_cut = set()
120
+ cut = set(initial_cut)
121
+ current_cut_size = nx.algorithms.cut_size(G, cut, weight=weight)
122
+ while True:
123
+ nodes = list(G.nodes())
124
+ # Shuffling the nodes ensures random tie-breaks in the following call to max
125
+ seed.shuffle(nodes)
126
+ best_node_to_swap = max(
127
+ nodes,
128
+ key=lambda v: nx.algorithms.cut_size(
129
+ G, _swap_node_partition(cut, v), weight=weight
130
+ ),
131
+ default=None,
132
+ )
133
+ potential_cut = _swap_node_partition(cut, best_node_to_swap)
134
+ potential_cut_size = nx.algorithms.cut_size(G, potential_cut, weight=weight)
135
+
136
+ if potential_cut_size > current_cut_size:
137
+ cut = potential_cut
138
+ current_cut_size = potential_cut_size
139
+ else:
140
+ break
141
+
142
+ partition = (cut, G.nodes - cut)
143
+ return current_cut_size, partition
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/ramsey.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ramsey numbers.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ from ...utils import arbitrary_element
9
+
10
+ __all__ = ["ramsey_R2"]
11
+
12
+
13
+ @not_implemented_for("directed")
14
+ @not_implemented_for("multigraph")
15
+ @nx._dispatchable
16
+ def ramsey_R2(G):
17
+ r"""Compute the largest clique and largest independent set in `G`.
18
+
19
+ This can be used to estimate bounds for the 2-color
20
+ Ramsey number `R(2;s,t)` for `G`.
21
+
22
+ This is a recursive implementation which could run into trouble
23
+ for large recursions. Note that self-loop edges are ignored.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+ Undirected graph
29
+
30
+ Returns
31
+ -------
32
+ max_pair : (set, set) tuple
33
+ Maximum clique, Maximum independent set.
34
+
35
+ Raises
36
+ ------
37
+ NetworkXNotImplemented
38
+ If the graph is directed or is a multigraph.
39
+ """
40
+ if not G:
41
+ return set(), set()
42
+
43
+ node = arbitrary_element(G)
44
+ nbrs = (nbr for nbr in nx.all_neighbors(G, node) if nbr != node)
45
+ nnbrs = nx.non_neighbors(G, node)
46
+ c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
47
+ c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())
48
+
49
+ c_1.add(node)
50
+ i_2.add(node)
51
+ # Choose the larger of the two cliques and the larger of the two
52
+ # independent sets, according to cardinality.
53
+ return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/steinertree.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain
2
+
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for, pairwise
5
+
6
+ __all__ = ["metric_closure", "steiner_tree"]
7
+
8
+
9
+ @not_implemented_for("directed")
10
+ @nx._dispatchable(edge_attrs="weight", returns_graph=True)
11
+ def metric_closure(G, weight="weight"):
12
+ """Return the metric closure of a graph.
13
+
14
+ The metric closure of a graph *G* is the complete graph in which each edge
15
+ is weighted by the shortest path distance between the nodes in *G* .
16
+
17
+ Parameters
18
+ ----------
19
+ G : NetworkX graph
20
+
21
+ Returns
22
+ -------
23
+ NetworkX graph
24
+ Metric closure of the graph `G`.
25
+
26
+ """
27
+ M = nx.Graph()
28
+
29
+ Gnodes = set(G)
30
+
31
+ # check for connected graph while processing first node
32
+ all_paths_iter = nx.all_pairs_dijkstra(G, weight=weight)
33
+ u, (distance, path) = next(all_paths_iter)
34
+ if Gnodes - set(distance):
35
+ msg = "G is not a connected graph. metric_closure is not defined."
36
+ raise nx.NetworkXError(msg)
37
+ Gnodes.remove(u)
38
+ for v in Gnodes:
39
+ M.add_edge(u, v, distance=distance[v], path=path[v])
40
+
41
+ # first node done -- now process the rest
42
+ for u, (distance, path) in all_paths_iter:
43
+ Gnodes.remove(u)
44
+ for v in Gnodes:
45
+ M.add_edge(u, v, distance=distance[v], path=path[v])
46
+
47
+ return M
48
+
49
+
50
+ def _mehlhorn_steiner_tree(G, terminal_nodes, weight):
51
+ paths = nx.multi_source_dijkstra_path(G, terminal_nodes)
52
+
53
+ d_1 = {}
54
+ s = {}
55
+ for v in G.nodes():
56
+ s[v] = paths[v][0]
57
+ d_1[(v, s[v])] = len(paths[v]) - 1
58
+
59
+ # G1-G4 names match those from the Mehlhorn 1988 paper.
60
+ G_1_prime = nx.Graph()
61
+ for u, v, data in G.edges(data=True):
62
+ su, sv = s[u], s[v]
63
+ weight_here = d_1[(u, su)] + data.get(weight, 1) + d_1[(v, sv)]
64
+ if not G_1_prime.has_edge(su, sv):
65
+ G_1_prime.add_edge(su, sv, weight=weight_here)
66
+ else:
67
+ new_weight = min(weight_here, G_1_prime[su][sv]["weight"])
68
+ G_1_prime.add_edge(su, sv, weight=new_weight)
69
+
70
+ G_2 = nx.minimum_spanning_edges(G_1_prime, data=True)
71
+
72
+ G_3 = nx.Graph()
73
+ for u, v, d in G_2:
74
+ path = nx.shortest_path(G, u, v, weight)
75
+ for n1, n2 in pairwise(path):
76
+ G_3.add_edge(n1, n2)
77
+
78
+ G_3_mst = list(nx.minimum_spanning_edges(G_3, data=False))
79
+ if G.is_multigraph():
80
+ G_3_mst = (
81
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k][weight])) for u, v in G_3_mst
82
+ )
83
+ G_4 = G.edge_subgraph(G_3_mst).copy()
84
+ _remove_nonterminal_leaves(G_4, terminal_nodes)
85
+ return G_4.edges()
86
+
87
+
88
+ def _kou_steiner_tree(G, terminal_nodes, weight):
89
+ # H is the subgraph induced by terminal_nodes in the metric closure M of G.
90
+ M = metric_closure(G, weight=weight)
91
+ H = M.subgraph(terminal_nodes)
92
+
93
+ # Use the 'distance' attribute of each edge provided by M.
94
+ mst_edges = nx.minimum_spanning_edges(H, weight="distance", data=True)
95
+
96
+ # Create an iterator over each edge in each shortest path; repeats are okay
97
+ mst_all_edges = chain.from_iterable(pairwise(d["path"]) for u, v, d in mst_edges)
98
+ if G.is_multigraph():
99
+ mst_all_edges = (
100
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k][weight]))
101
+ for u, v in mst_all_edges
102
+ )
103
+
104
+ # Find the MST again, over this new set of edges
105
+ G_S = G.edge_subgraph(mst_all_edges)
106
+ T_S = nx.minimum_spanning_edges(G_S, weight="weight", data=False)
107
+
108
+ # Leaf nodes that are not terminal might still remain; remove them here
109
+ T_H = G.edge_subgraph(T_S).copy()
110
+ _remove_nonterminal_leaves(T_H, terminal_nodes)
111
+
112
+ return T_H.edges()
113
+
114
+
115
+ def _remove_nonterminal_leaves(G, terminals):
116
+ terminal_set = set(terminals)
117
+ leaves = {n for n in G if len(set(G[n]) - {n}) == 1}
118
+ nonterminal_leaves = leaves - terminal_set
119
+
120
+ while nonterminal_leaves:
121
+ # Removing a node may create new non-terminal leaves, so we limit
122
+ # search for candidate non-terminal nodes to neighbors of current
123
+ # non-terminal nodes
124
+ candidate_leaves = set.union(*(set(G[n]) for n in nonterminal_leaves))
125
+ candidate_leaves -= nonterminal_leaves | terminal_set
126
+ # Remove current set of non-terminal nodes
127
+ G.remove_nodes_from(nonterminal_leaves)
128
+ # Find any new non-terminal nodes from the set of candidates
129
+ leaves = {n for n in candidate_leaves if len(set(G[n]) - {n}) == 1}
130
+ nonterminal_leaves = leaves - terminal_set
131
+
132
+
133
+ ALGORITHMS = {
134
+ "kou": _kou_steiner_tree,
135
+ "mehlhorn": _mehlhorn_steiner_tree,
136
+ }
137
+
138
+
139
+ @not_implemented_for("directed")
140
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
141
+ def steiner_tree(G, terminal_nodes, weight="weight", method=None):
142
+ r"""Return an approximation to the minimum Steiner tree of a graph.
143
+
144
+ The minimum Steiner tree of `G` w.r.t a set of `terminal_nodes` (also *S*)
145
+ is a tree within `G` that spans those nodes and has minimum size (sum of
146
+ edge weights) among all such trees.
147
+
148
+ The approximation algorithm is specified with the `method` keyword
149
+ argument. All three available algorithms produce a tree whose weight is
150
+ within a ``(2 - (2 / l))`` factor of the weight of the optimal Steiner tree,
151
+ where ``l`` is the minimum number of leaf nodes across all possible Steiner
152
+ trees.
153
+
154
+ * ``"kou"`` [2]_ (runtime $O(|S| |V|^2)$) computes the minimum spanning tree of
155
+ the subgraph of the metric closure of *G* induced by the terminal nodes,
156
+ where the metric closure of *G* is the complete graph in which each edge is
157
+ weighted by the shortest path distance between the nodes in *G*.
158
+
159
+ * ``"mehlhorn"`` [3]_ (runtime $O(|E|+|V|\log|V|)$) modifies Kou et al.'s
160
+ algorithm, beginning by finding the closest terminal node for each
161
+ non-terminal. This data is used to create a complete graph containing only
162
+ the terminal nodes, in which edge is weighted with the shortest path
163
+ distance between them. The algorithm then proceeds in the same way as Kou
164
+ et al..
165
+
166
+ Parameters
167
+ ----------
168
+ G : NetworkX graph
169
+
170
+ terminal_nodes : list
171
+ A list of terminal nodes for which minimum steiner tree is
172
+ to be found.
173
+
174
+ weight : string (default = 'weight')
175
+ Use the edge attribute specified by this string as the edge weight.
176
+ Any edge attribute not present defaults to 1.
177
+
178
+ method : string, optional (default = 'mehlhorn')
179
+ The algorithm to use to approximate the Steiner tree.
180
+ Supported options: 'kou', 'mehlhorn'.
181
+ Other inputs produce a ValueError.
182
+
183
+ Returns
184
+ -------
185
+ NetworkX graph
186
+ Approximation to the minimum steiner tree of `G` induced by
187
+ `terminal_nodes` .
188
+
189
+ Raises
190
+ ------
191
+ NetworkXNotImplemented
192
+ If `G` is directed.
193
+
194
+ ValueError
195
+ If the specified `method` is not supported.
196
+
197
+ Notes
198
+ -----
199
+ For multigraphs, the edge between two nodes with minimum weight is the
200
+ edge put into the Steiner tree.
201
+
202
+
203
+ References
204
+ ----------
205
+ .. [1] Steiner_tree_problem on Wikipedia.
206
+ https://en.wikipedia.org/wiki/Steiner_tree_problem
207
+ .. [2] Kou, L., G. Markowsky, and L. Berman. 1981.
208
+ ‘A Fast Algorithm for Steiner Trees’.
209
+ Acta Informatica 15 (2): 141–45.
210
+ https://doi.org/10.1007/BF00288961.
211
+ .. [3] Mehlhorn, Kurt. 1988.
212
+ ‘A Faster Approximation Algorithm for the Steiner Problem in Graphs’.
213
+ Information Processing Letters 27 (3): 125–28.
214
+ https://doi.org/10.1016/0020-0190(88)90066-X.
215
+ """
216
+ if method is None:
217
+ method = "mehlhorn"
218
+
219
+ try:
220
+ algo = ALGORITHMS[method]
221
+ except KeyError as e:
222
+ raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
223
+
224
+ edges = algo(G, terminal_nodes, weight)
225
+ # For multigraph we should add the minimal weight edge keys
226
+ if G.is_multigraph():
227
+ edges = (
228
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k][weight])) for u, v in edges
229
+ )
230
+ T = G.edge_subgraph(edges)
231
+ return T
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import average_clustering
3
+
4
+ # This approximation has to be exact in regular graphs
5
+ # with no triangles or with all possible triangles.
6
+
7
+
8
+ def test_petersen():
9
+ # Actual coefficient is 0
10
+ G = nx.petersen_graph()
11
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
12
+
13
+
14
+ def test_petersen_seed():
15
+ # Actual coefficient is 0
16
+ G = nx.petersen_graph()
17
+ assert average_clustering(G, trials=len(G) // 2, seed=1) == nx.average_clustering(G)
18
+
19
+
20
+ def test_tetrahedral():
21
+ # Actual coefficient is 1
22
+ G = nx.tetrahedral_graph()
23
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
24
+
25
+
26
+ def test_dodecahedral():
27
+ # Actual coefficient is 0
28
+ G = nx.dodecahedral_graph()
29
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
30
+
31
+
32
+ def test_empty():
33
+ G = nx.empty_graph(5)
34
+ assert average_clustering(G, trials=len(G) // 2) == 0
35
+
36
+
37
+ def test_complete():
38
+ G = nx.complete_graph(5)
39
+ assert average_clustering(G, trials=len(G) // 2) == 1
40
+ G = nx.complete_graph(7)
41
+ assert average_clustering(G, trials=len(G) // 2) == 1
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_clique.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.approximation.clique` module."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ clique_removal,
6
+ large_clique_size,
7
+ max_clique,
8
+ maximum_independent_set,
9
+ )
10
+
11
+
12
+ def is_independent_set(G, nodes):
13
+ """Returns True if and only if `nodes` is a clique in `G`.
14
+
15
+ `G` is a NetworkX graph. `nodes` is an iterable of nodes in
16
+ `G`.
17
+
18
+ """
19
+ return G.subgraph(nodes).number_of_edges() == 0
20
+
21
+
22
+ def is_clique(G, nodes):
23
+ """Returns True if and only if `nodes` is an independent set
24
+ in `G`.
25
+
26
+ `G` is an undirected simple graph. `nodes` is an iterable of
27
+ nodes in `G`.
28
+
29
+ """
30
+ H = G.subgraph(nodes)
31
+ n = len(H)
32
+ return H.number_of_edges() == n * (n - 1) // 2
33
+
34
+
35
+ class TestCliqueRemoval:
36
+ """Unit tests for the
37
+ :func:`~networkx.algorithms.approximation.clique_removal` function.
38
+
39
+ """
40
+
41
+ def test_trivial_graph(self):
42
+ G = nx.trivial_graph()
43
+ independent_set, cliques = clique_removal(G)
44
+ assert is_independent_set(G, independent_set)
45
+ assert all(is_clique(G, clique) for clique in cliques)
46
+ # In fact, we should only have 1-cliques, that is, singleton nodes.
47
+ assert all(len(clique) == 1 for clique in cliques)
48
+
49
+ def test_complete_graph(self):
50
+ G = nx.complete_graph(10)
51
+ independent_set, cliques = clique_removal(G)
52
+ assert is_independent_set(G, independent_set)
53
+ assert all(is_clique(G, clique) for clique in cliques)
54
+
55
+ def test_barbell_graph(self):
56
+ G = nx.barbell_graph(10, 5)
57
+ independent_set, cliques = clique_removal(G)
58
+ assert is_independent_set(G, independent_set)
59
+ assert all(is_clique(G, clique) for clique in cliques)
60
+
61
+
62
+ class TestMaxClique:
63
+ """Unit tests for the :func:`networkx.algorithms.approximation.max_clique`
64
+ function.
65
+
66
+ """
67
+
68
+ def test_null_graph(self):
69
+ G = nx.null_graph()
70
+ assert len(max_clique(G)) == 0
71
+
72
+ def test_complete_graph(self):
73
+ graph = nx.complete_graph(30)
74
+ # this should return the entire graph
75
+ mc = max_clique(graph)
76
+ assert 30 == len(mc)
77
+
78
+ def test_maximal_by_cardinality(self):
79
+ """Tests that the maximal clique is computed according to maximum
80
+ cardinality of the sets.
81
+
82
+ For more information, see pull request #1531.
83
+
84
+ """
85
+ G = nx.complete_graph(5)
86
+ G.add_edge(4, 5)
87
+ clique = max_clique(G)
88
+ assert len(clique) > 1
89
+
90
+ G = nx.lollipop_graph(30, 2)
91
+ clique = max_clique(G)
92
+ assert len(clique) > 2
93
+
94
+
95
+ def test_large_clique_size():
96
+ G = nx.complete_graph(9)
97
+ nx.add_cycle(G, [9, 10, 11])
98
+ G.add_edge(8, 9)
99
+ G.add_edge(1, 12)
100
+ G.add_node(13)
101
+
102
+ assert large_clique_size(G) == 9
103
+ G.remove_node(5)
104
+ assert large_clique_size(G) == 8
105
+ G.remove_edge(2, 3)
106
+ assert large_clique_size(G) == 7
107
+
108
+
109
+ def test_independent_set():
110
+ # smoke test
111
+ G = nx.Graph()
112
+ assert len(maximum_independent_set(G)) == 0
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms import approximation as approx
5
+
6
+
7
+ def test_global_node_connectivity():
8
+ # Figure 1 chapter on Connectivity
9
+ G = nx.Graph()
10
+ G.add_edges_from(
11
+ [
12
+ (1, 2),
13
+ (1, 3),
14
+ (1, 4),
15
+ (1, 5),
16
+ (2, 3),
17
+ (2, 6),
18
+ (3, 4),
19
+ (3, 6),
20
+ (4, 6),
21
+ (4, 7),
22
+ (5, 7),
23
+ (6, 8),
24
+ (6, 9),
25
+ (7, 8),
26
+ (7, 10),
27
+ (8, 11),
28
+ (9, 10),
29
+ (9, 11),
30
+ (10, 11),
31
+ ]
32
+ )
33
+ assert 2 == approx.local_node_connectivity(G, 1, 11)
34
+ assert 2 == approx.node_connectivity(G)
35
+ assert 2 == approx.node_connectivity(G, 1, 11)
36
+
37
+
38
+ def test_white_harary1():
39
+ # Figure 1b white and harary (2001)
40
+ # A graph with high adhesion (edge connectivity) and low cohesion
41
+ # (node connectivity)
42
+ G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
43
+ G.remove_node(7)
44
+ for i in range(4, 7):
45
+ G.add_edge(0, i)
46
+ G = nx.disjoint_union(G, nx.complete_graph(4))
47
+ G.remove_node(G.order() - 1)
48
+ for i in range(7, 10):
49
+ G.add_edge(0, i)
50
+ assert 1 == approx.node_connectivity(G)
51
+
52
+
53
+ def test_complete_graphs():
54
+ for n in range(5, 25, 5):
55
+ G = nx.complete_graph(n)
56
+ assert n - 1 == approx.node_connectivity(G)
57
+ assert n - 1 == approx.node_connectivity(G, 0, 3)
58
+
59
+
60
+ def test_empty_graphs():
61
+ for k in range(5, 25, 5):
62
+ G = nx.empty_graph(k)
63
+ assert 0 == approx.node_connectivity(G)
64
+ assert 0 == approx.node_connectivity(G, 0, 3)
65
+
66
+
67
+ def test_petersen():
68
+ G = nx.petersen_graph()
69
+ assert 3 == approx.node_connectivity(G)
70
+ assert 3 == approx.node_connectivity(G, 0, 5)
71
+
72
+
73
+ # Approximation fails with tutte graph
74
+ # def test_tutte():
75
+ # G = nx.tutte_graph()
76
+ # assert_equal(3, approx.node_connectivity(G))
77
+
78
+
79
+ def test_dodecahedral():
80
+ G = nx.dodecahedral_graph()
81
+ assert 3 == approx.node_connectivity(G)
82
+ assert 3 == approx.node_connectivity(G, 0, 5)
83
+
84
+
85
+ def test_octahedral():
86
+ G = nx.octahedral_graph()
87
+ assert 4 == approx.node_connectivity(G)
88
+ assert 4 == approx.node_connectivity(G, 0, 5)
89
+
90
+
91
+ # Approximation can fail with icosahedral graph depending
92
+ # on iteration order.
93
+ # def test_icosahedral():
94
+ # G=nx.icosahedral_graph()
95
+ # assert_equal(5, approx.node_connectivity(G))
96
+ # assert_equal(5, approx.node_connectivity(G, 0, 5))
97
+
98
+
99
+ def test_only_source():
100
+ G = nx.complete_graph(5)
101
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, s=0)
102
+
103
+
104
+ def test_only_target():
105
+ G = nx.complete_graph(5)
106
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, t=0)
107
+
108
+
109
+ def test_missing_source():
110
+ G = nx.path_graph(4)
111
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 10, 1)
112
+
113
+
114
+ def test_missing_target():
115
+ G = nx.path_graph(4)
116
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 1, 10)
117
+
118
+
119
+ def test_source_equals_target():
120
+ G = nx.complete_graph(5)
121
+ pytest.raises(nx.NetworkXError, approx.local_node_connectivity, G, 0, 0)
122
+
123
+
124
+ def test_directed_node_connectivity():
125
+ G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
126
+ D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
127
+ assert 1 == approx.node_connectivity(G)
128
+ assert 1 == approx.node_connectivity(G, 1, 4)
129
+ assert 2 == approx.node_connectivity(D)
130
+ assert 2 == approx.node_connectivity(D, 1, 4)
131
+
132
+
133
+ class TestAllPairsNodeConnectivityApprox:
134
+ @classmethod
135
+ def setup_class(cls):
136
+ cls.path = nx.path_graph(7)
137
+ cls.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
138
+ cls.cycle = nx.cycle_graph(7)
139
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
140
+ cls.gnp = nx.gnp_random_graph(30, 0.1)
141
+ cls.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
142
+ cls.K20 = nx.complete_graph(20)
143
+ cls.K10 = nx.complete_graph(10)
144
+ cls.K5 = nx.complete_graph(5)
145
+ cls.G_list = [
146
+ cls.path,
147
+ cls.directed_path,
148
+ cls.cycle,
149
+ cls.directed_cycle,
150
+ cls.gnp,
151
+ cls.directed_gnp,
152
+ cls.K10,
153
+ cls.K5,
154
+ cls.K20,
155
+ ]
156
+
157
+ def test_cycles(self):
158
+ K_undir = approx.all_pairs_node_connectivity(self.cycle)
159
+ for source in K_undir:
160
+ for target, k in K_undir[source].items():
161
+ assert k == 2
162
+ K_dir = approx.all_pairs_node_connectivity(self.directed_cycle)
163
+ for source in K_dir:
164
+ for target, k in K_dir[source].items():
165
+ assert k == 1
166
+
167
+ def test_complete(self):
168
+ for G in [self.K10, self.K5, self.K20]:
169
+ K = approx.all_pairs_node_connectivity(G)
170
+ for source in K:
171
+ for target, k in K[source].items():
172
+ assert k == len(G) - 1
173
+
174
+ def test_paths(self):
175
+ K_undir = approx.all_pairs_node_connectivity(self.path)
176
+ for source in K_undir:
177
+ for target, k in K_undir[source].items():
178
+ assert k == 1
179
+ K_dir = approx.all_pairs_node_connectivity(self.directed_path)
180
+ for source in K_dir:
181
+ for target, k in K_dir[source].items():
182
+ if source < target:
183
+ assert k == 1
184
+ else:
185
+ assert k == 0
186
+
187
+ def test_cutoff(self):
188
+ for G in [self.K10, self.K5, self.K20]:
189
+ for mp in [2, 3, 4]:
190
+ paths = approx.all_pairs_node_connectivity(G, cutoff=mp)
191
+ for source in paths:
192
+ for target, K in paths[source].items():
193
+ assert K == mp
194
+
195
+ def test_all_pairs_connectivity_nbunch(self):
196
+ G = nx.complete_graph(5)
197
+ nbunch = [0, 2, 3]
198
+ C = approx.all_pairs_node_connectivity(G, nbunch=nbunch)
199
+ assert len(C) == len(nbunch)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.approximation.distance_measures` module."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.approximation import diameter
7
+
8
+
9
+ class TestDiameter:
10
+ """Unit tests for the approximate diameter function
11
+ :func:`~networkx.algorithms.approximation.distance_measures.diameter`.
12
+ """
13
+
14
+ def test_null_graph(self):
15
+ """Test empty graph."""
16
+ G = nx.null_graph()
17
+ with pytest.raises(
18
+ nx.NetworkXError, match="Expected non-empty NetworkX graph!"
19
+ ):
20
+ diameter(G)
21
+
22
+ def test_undirected_non_connected(self):
23
+ """Test an undirected disconnected graph."""
24
+ graph = nx.path_graph(10)
25
+ graph.remove_edge(3, 4)
26
+ with pytest.raises(nx.NetworkXError, match="Graph not connected."):
27
+ diameter(graph)
28
+
29
+ def test_directed_non_strongly_connected(self):
30
+ """Test a directed non strongly connected graph."""
31
+ graph = nx.path_graph(10, create_using=nx.DiGraph())
32
+ with pytest.raises(nx.NetworkXError, match="DiGraph not strongly connected."):
33
+ diameter(graph)
34
+
35
+ def test_complete_undirected_graph(self):
36
+ """Test a complete undirected graph."""
37
+ graph = nx.complete_graph(10)
38
+ assert diameter(graph) == 1
39
+
40
+ def test_complete_directed_graph(self):
41
+ """Test a complete directed graph."""
42
+ graph = nx.complete_graph(10, create_using=nx.DiGraph())
43
+ assert diameter(graph) == 1
44
+
45
+ def test_undirected_path_graph(self):
46
+ """Test an undirected path graph with 10 nodes."""
47
+ graph = nx.path_graph(10)
48
+ assert diameter(graph) == 9
49
+
50
+ def test_directed_path_graph(self):
51
+ """Test a directed path graph with 10 nodes."""
52
+ graph = nx.path_graph(10).to_directed()
53
+ assert diameter(graph) == 9
54
+
55
+ def test_single_node(self):
56
+ """Test a graph which contains just a node."""
57
+ graph = nx.Graph()
58
+ graph.add_node(1)
59
+ assert diameter(graph) == 0
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ min_edge_dominating_set,
6
+ min_weighted_dominating_set,
7
+ )
8
+
9
+
10
+ class TestMinWeightDominatingSet:
11
+ def test_min_weighted_dominating_set(self):
12
+ graph = nx.Graph()
13
+ graph.add_edge(1, 2)
14
+ graph.add_edge(1, 5)
15
+ graph.add_edge(2, 3)
16
+ graph.add_edge(2, 5)
17
+ graph.add_edge(3, 4)
18
+ graph.add_edge(3, 6)
19
+ graph.add_edge(5, 6)
20
+
21
+ vertices = {1, 2, 3, 4, 5, 6}
22
+ # due to ties, this might be hard to test tight bounds
23
+ dom_set = min_weighted_dominating_set(graph)
24
+ for vertex in vertices - dom_set:
25
+ neighbors = set(graph.neighbors(vertex))
26
+ assert len(neighbors & dom_set) > 0, "Non dominating set found!"
27
+
28
+ def test_star_graph(self):
29
+ """Tests that an approximate dominating set for the star graph,
30
+ even when the center node does not have the smallest integer
31
+ label, gives just the center node.
32
+
33
+ For more information, see #1527.
34
+
35
+ """
36
+ # Create a star graph in which the center node has the highest
37
+ # label instead of the lowest.
38
+ G = nx.star_graph(10)
39
+ G = nx.relabel_nodes(G, {0: 9, 9: 0})
40
+ assert min_weighted_dominating_set(G) == {9}
41
+
42
+ def test_null_graph(self):
43
+ """Tests that the unique dominating set for the null graph is an empty set"""
44
+ G = nx.Graph()
45
+ assert min_weighted_dominating_set(G) == set()
46
+
47
+ def test_min_edge_dominating_set(self):
48
+ graph = nx.path_graph(5)
49
+ dom_set = min_edge_dominating_set(graph)
50
+
51
+ # this is a crappy way to test, but good enough for now.
52
+ for edge in graph.edges():
53
+ if edge in dom_set:
54
+ continue
55
+ else:
56
+ u, v = edge
57
+ found = False
58
+ for dom_edge in dom_set:
59
+ found |= u == dom_edge[0] or u == dom_edge[1]
60
+ assert found, "Non adjacent edge found!"
61
+
62
+ graph = nx.complete_graph(10)
63
+ dom_set = min_edge_dominating_set(graph)
64
+
65
+ # this is a crappy way to test, but good enough for now.
66
+ for edge in graph.edges():
67
+ if edge in dom_set:
68
+ continue
69
+ else:
70
+ u, v = edge
71
+ found = False
72
+ for dom_edge in dom_set:
73
+ found |= u == dom_edge[0] or u == dom_edge[1]
74
+ assert found, "Non adjacent edge found!"
75
+
76
+ graph = nx.Graph() # empty Networkx graph
77
+ with pytest.raises(ValueError, match="Expected non-empty NetworkX graph!"):
78
+ min_edge_dominating_set(graph)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Test for approximation to k-components algorithm
2
+ import pytest
3
+
4
+ import networkx as nx
5
+ from networkx.algorithms.approximation import k_components
6
+ from networkx.algorithms.approximation.kcomponents import _AntiGraph, _same
7
+
8
+
9
+ def build_k_number_dict(k_components):
10
+ k_num = {}
11
+ for k, comps in sorted(k_components.items()):
12
+ for comp in comps:
13
+ for node in comp:
14
+ k_num[node] = k
15
+ return k_num
16
+
17
+
18
+ ##
19
+ # Some nice synthetic graphs
20
+ ##
21
+
22
+
23
+ def graph_example_1():
24
+ G = nx.convert_node_labels_to_integers(
25
+ nx.grid_graph([5, 5]), label_attribute="labels"
26
+ )
27
+ rlabels = nx.get_node_attributes(G, "labels")
28
+ labels = {v: k for k, v in rlabels.items()}
29
+
30
+ for nodes in [
31
+ (labels[(0, 0)], labels[(1, 0)]),
32
+ (labels[(0, 4)], labels[(1, 4)]),
33
+ (labels[(3, 0)], labels[(4, 0)]),
34
+ (labels[(3, 4)], labels[(4, 4)]),
35
+ ]:
36
+ new_node = G.order() + 1
37
+ # Petersen graph is triconnected
38
+ P = nx.petersen_graph()
39
+ G = nx.disjoint_union(G, P)
40
+ # Add two edges between the grid and P
41
+ G.add_edge(new_node + 1, nodes[0])
42
+ G.add_edge(new_node, nodes[1])
43
+ # K5 is 4-connected
44
+ K = nx.complete_graph(5)
45
+ G = nx.disjoint_union(G, K)
46
+ # Add three edges between P and K5
47
+ G.add_edge(new_node + 2, new_node + 11)
48
+ G.add_edge(new_node + 3, new_node + 12)
49
+ G.add_edge(new_node + 4, new_node + 13)
50
+ # Add another K5 sharing a node
51
+ G = nx.disjoint_union(G, K)
52
+ nbrs = G[new_node + 10]
53
+ G.remove_node(new_node + 10)
54
+ for nbr in nbrs:
55
+ G.add_edge(new_node + 17, nbr)
56
+ G.add_edge(new_node + 16, new_node + 5)
57
+ return G
58
+
59
+
60
+ def torrents_and_ferraro_graph():
61
+ G = nx.convert_node_labels_to_integers(
62
+ nx.grid_graph([5, 5]), label_attribute="labels"
63
+ )
64
+ rlabels = nx.get_node_attributes(G, "labels")
65
+ labels = {v: k for k, v in rlabels.items()}
66
+
67
+ for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]:
68
+ new_node = G.order() + 1
69
+ # Petersen graph is triconnected
70
+ P = nx.petersen_graph()
71
+ G = nx.disjoint_union(G, P)
72
+ # Add two edges between the grid and P
73
+ G.add_edge(new_node + 1, nodes[0])
74
+ G.add_edge(new_node, nodes[1])
75
+ # K5 is 4-connected
76
+ K = nx.complete_graph(5)
77
+ G = nx.disjoint_union(G, K)
78
+ # Add three edges between P and K5
79
+ G.add_edge(new_node + 2, new_node + 11)
80
+ G.add_edge(new_node + 3, new_node + 12)
81
+ G.add_edge(new_node + 4, new_node + 13)
82
+ # Add another K5 sharing a node
83
+ G = nx.disjoint_union(G, K)
84
+ nbrs = G[new_node + 10]
85
+ G.remove_node(new_node + 10)
86
+ for nbr in nbrs:
87
+ G.add_edge(new_node + 17, nbr)
88
+ # Commenting this makes the graph not biconnected !!
89
+ # This stupid mistake make one reviewer very angry :P
90
+ G.add_edge(new_node + 16, new_node + 8)
91
+
92
+ for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]:
93
+ new_node = G.order() + 1
94
+ # Petersen graph is triconnected
95
+ P = nx.petersen_graph()
96
+ G = nx.disjoint_union(G, P)
97
+ # Add two edges between the grid and P
98
+ G.add_edge(new_node + 1, nodes[0])
99
+ G.add_edge(new_node, nodes[1])
100
+ # K5 is 4-connected
101
+ K = nx.complete_graph(5)
102
+ G = nx.disjoint_union(G, K)
103
+ # Add three edges between P and K5
104
+ G.add_edge(new_node + 2, new_node + 11)
105
+ G.add_edge(new_node + 3, new_node + 12)
106
+ G.add_edge(new_node + 4, new_node + 13)
107
+ # Add another K5 sharing two nodes
108
+ G = nx.disjoint_union(G, K)
109
+ nbrs = G[new_node + 10]
110
+ G.remove_node(new_node + 10)
111
+ for nbr in nbrs:
112
+ G.add_edge(new_node + 17, nbr)
113
+ nbrs2 = G[new_node + 9]
114
+ G.remove_node(new_node + 9)
115
+ for nbr in nbrs2:
116
+ G.add_edge(new_node + 18, nbr)
117
+ return G
118
+
119
+
120
+ # Helper function
121
+
122
+
123
+ def _check_connectivity(G):
124
+ result = k_components(G)
125
+ for k, components in result.items():
126
+ if k < 3:
127
+ continue
128
+ for component in components:
129
+ C = G.subgraph(component)
130
+ K = nx.node_connectivity(C)
131
+ assert K >= k
132
+
133
+
134
+ def test_torrents_and_ferraro_graph():
135
+ G = torrents_and_ferraro_graph()
136
+ _check_connectivity(G)
137
+
138
+
139
+ def test_example_1():
140
+ G = graph_example_1()
141
+ _check_connectivity(G)
142
+
143
+
144
+ def test_karate_0():
145
+ G = nx.karate_club_graph()
146
+ _check_connectivity(G)
147
+
148
+
149
+ def test_karate_1():
150
+ karate_k_num = {
151
+ 0: 4,
152
+ 1: 4,
153
+ 2: 4,
154
+ 3: 4,
155
+ 4: 3,
156
+ 5: 3,
157
+ 6: 3,
158
+ 7: 4,
159
+ 8: 4,
160
+ 9: 2,
161
+ 10: 3,
162
+ 11: 1,
163
+ 12: 2,
164
+ 13: 4,
165
+ 14: 2,
166
+ 15: 2,
167
+ 16: 2,
168
+ 17: 2,
169
+ 18: 2,
170
+ 19: 3,
171
+ 20: 2,
172
+ 21: 2,
173
+ 22: 2,
174
+ 23: 3,
175
+ 24: 3,
176
+ 25: 3,
177
+ 26: 2,
178
+ 27: 3,
179
+ 28: 3,
180
+ 29: 3,
181
+ 30: 4,
182
+ 31: 3,
183
+ 32: 4,
184
+ 33: 4,
185
+ }
186
+ approx_karate_k_num = karate_k_num.copy()
187
+ approx_karate_k_num[24] = 2
188
+ approx_karate_k_num[25] = 2
189
+ G = nx.karate_club_graph()
190
+ k_comps = k_components(G)
191
+ k_num = build_k_number_dict(k_comps)
192
+ assert k_num in (karate_k_num, approx_karate_k_num)
193
+
194
+
195
+ def test_example_1_detail_3_and_4():
196
+ G = graph_example_1()
197
+ result = k_components(G)
198
+ # In this example graph there are 8 3-components, 4 with 15 nodes
199
+ # and 4 with 5 nodes.
200
+ assert len(result[3]) == 8
201
+ assert len([c for c in result[3] if len(c) == 15]) == 4
202
+ assert len([c for c in result[3] if len(c) == 5]) == 4
203
+ # There are also 8 4-components all with 5 nodes.
204
+ assert len(result[4]) == 8
205
+ assert all(len(c) == 5 for c in result[4])
206
+ # Finally check that the k-components detected have actually node
207
+ # connectivity >= k.
208
+ for k, components in result.items():
209
+ if k < 3:
210
+ continue
211
+ for component in components:
212
+ K = nx.node_connectivity(G.subgraph(component))
213
+ assert K >= k
214
+
215
+
216
+ def test_directed():
217
+ with pytest.raises(nx.NetworkXNotImplemented):
218
+ G = nx.gnp_random_graph(10, 0.4, directed=True)
219
+ kc = k_components(G)
220
+
221
+
222
+ def test_same():
223
+ equal = {"A": 2, "B": 2, "C": 2}
224
+ slightly_different = {"A": 2, "B": 1, "C": 2}
225
+ different = {"A": 2, "B": 8, "C": 18}
226
+ assert _same(equal)
227
+ assert not _same(slightly_different)
228
+ assert _same(slightly_different, tol=1)
229
+ assert not _same(different)
230
+ assert not _same(different, tol=4)
231
+
232
+
233
+ class TestAntiGraph:
234
+ @classmethod
235
+ def setup_class(cls):
236
+ cls.Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
237
+ cls.Anp = _AntiGraph(nx.complement(cls.Gnp))
238
+ cls.Gd = nx.davis_southern_women_graph()
239
+ cls.Ad = _AntiGraph(nx.complement(cls.Gd))
240
+ cls.Gk = nx.karate_club_graph()
241
+ cls.Ak = _AntiGraph(nx.complement(cls.Gk))
242
+ cls.GA = [(cls.Gnp, cls.Anp), (cls.Gd, cls.Ad), (cls.Gk, cls.Ak)]
243
+
244
+ def test_size(self):
245
+ for G, A in self.GA:
246
+ n = G.order()
247
+ s = len(list(G.edges())) + len(list(A.edges()))
248
+ assert s == (n * (n - 1)) / 2
249
+
250
+ def test_degree(self):
251
+ for G, A in self.GA:
252
+ assert sorted(G.degree()) == sorted(A.degree())
253
+
254
+ def test_core_number(self):
255
+ for G, A in self.GA:
256
+ assert nx.core_number(G) == nx.core_number(A)
257
+
258
+ def test_connected_components(self):
259
+ # ccs are same unless isolated nodes or any node has degree=len(G)-1
260
+ # graphs in self.GA avoid this problem
261
+ for G, A in self.GA:
262
+ gc = [set(c) for c in nx.connected_components(G)]
263
+ ac = [set(c) for c in nx.connected_components(A)]
264
+ for comp in ac:
265
+ assert comp in gc
266
+
267
+ def test_adj(self):
268
+ for G, A in self.GA:
269
+ for n, nbrs in G.adj.items():
270
+ a_adj = sorted((n, sorted(ad)) for n, ad in A.adj.items())
271
+ g_adj = sorted((n, sorted(ad)) for n, ad in G.adj.items())
272
+ assert a_adj == g_adj
273
+
274
+ def test_adjacency(self):
275
+ for G, A in self.GA:
276
+ a_adj = list(A.adjacency())
277
+ for n, nbrs in G.adjacency():
278
+ assert (n, set(nbrs)) in a_adj
279
+
280
+ def test_neighbors(self):
281
+ for G, A in self.GA:
282
+ node = list(G.nodes())[0]
283
+ assert set(G.neighbors(node)) == set(A.neighbors(node))
284
+
285
+ def test_node_not_in_graph(self):
286
+ for G, A in self.GA:
287
+ node = "non_existent_node"
288
+ pytest.raises(nx.NetworkXError, A.neighbors, node)
289
+ pytest.raises(nx.NetworkXError, G.neighbors, node)
290
+
291
+ def test_degree_thingraph(self):
292
+ for G, A in self.GA:
293
+ node = list(G.nodes())[0]
294
+ nodes = list(G.nodes())[1:4]
295
+ assert G.degree(node) == A.degree(node)
296
+ assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
297
+ # AntiGraph is a ThinGraph, so all the weights are 1
298
+ assert sum(d for n, d in A.degree()) == sum(
299
+ d for n, d in A.degree(weight="weight")
300
+ )
301
+ assert sum(d for n, d in G.degree(nodes)) == sum(
302
+ d for n, d in A.degree(nodes)
303
+ )
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_matching.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import networkx.algorithms.approximation as a
3
+
4
+
5
+ def test_min_maximal_matching():
6
+ # smoke test
7
+ G = nx.Graph()
8
+ assert len(a.min_maximal_matching(G)) == 0
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.approximation import maxcut
7
+
8
+
9
+ @pytest.mark.parametrize(
10
+ "f", (nx.approximation.randomized_partitioning, nx.approximation.one_exchange)
11
+ )
12
+ @pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
13
+ def test_raises_on_directed_and_multigraphs(f, graph_constructor):
14
+ G = graph_constructor([(0, 1), (1, 2)])
15
+ with pytest.raises(nx.NetworkXNotImplemented):
16
+ f(G)
17
+
18
+
19
+ def _is_valid_cut(G, set1, set2):
20
+ union = set1.union(set2)
21
+ assert union == set(G.nodes)
22
+ assert len(set1) + len(set2) == G.number_of_nodes()
23
+
24
+
25
+ def _cut_is_locally_optimal(G, cut_size, set1):
26
+ # test if cut can be locally improved
27
+ for i, node in enumerate(set1):
28
+ cut_size_without_node = nx.algorithms.cut_size(
29
+ G, set1 - {node}, weight="weight"
30
+ )
31
+ assert cut_size_without_node <= cut_size
32
+
33
+
34
+ def test_random_partitioning():
35
+ G = nx.complete_graph(5)
36
+ _, (set1, set2) = maxcut.randomized_partitioning(G, seed=5)
37
+ _is_valid_cut(G, set1, set2)
38
+
39
+
40
+ def test_random_partitioning_all_to_one():
41
+ G = nx.complete_graph(5)
42
+ _, (set1, set2) = maxcut.randomized_partitioning(G, p=1)
43
+ _is_valid_cut(G, set1, set2)
44
+ assert len(set1) == G.number_of_nodes()
45
+ assert len(set2) == 0
46
+
47
+
48
+ def test_one_exchange_basic():
49
+ G = nx.complete_graph(5)
50
+ random.seed(5)
51
+ for u, v, w in G.edges(data=True):
52
+ w["weight"] = random.randrange(-100, 100, 1) / 10
53
+
54
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
55
+ cut_size, (set1, set2) = maxcut.one_exchange(
56
+ G, initial_cut, weight="weight", seed=5
57
+ )
58
+
59
+ _is_valid_cut(G, set1, set2)
60
+ _cut_is_locally_optimal(G, cut_size, set1)
61
+
62
+
63
+ def test_one_exchange_optimal():
64
+ # Greedy one exchange should find the optimal solution for this graph (14)
65
+ G = nx.Graph()
66
+ G.add_edge(1, 2, weight=3)
67
+ G.add_edge(1, 3, weight=3)
68
+ G.add_edge(1, 4, weight=3)
69
+ G.add_edge(1, 5, weight=3)
70
+ G.add_edge(2, 3, weight=5)
71
+
72
+ cut_size, (set1, set2) = maxcut.one_exchange(G, weight="weight", seed=5)
73
+
74
+ _is_valid_cut(G, set1, set2)
75
+ _cut_is_locally_optimal(G, cut_size, set1)
76
+ # check global optimality
77
+ assert cut_size == 14
78
+
79
+
80
+ def test_negative_weights():
81
+ G = nx.complete_graph(5)
82
+ random.seed(5)
83
+ for u, v, w in G.edges(data=True):
84
+ w["weight"] = -1 * random.random()
85
+
86
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
87
+ cut_size, (set1, set2) = maxcut.one_exchange(G, initial_cut, weight="weight")
88
+
89
+ # make sure it is a valid cut
90
+ _is_valid_cut(G, set1, set2)
91
+ # check local optimality
92
+ _cut_is_locally_optimal(G, cut_size, set1)
93
+ # test that all nodes are in the same partition
94
+ assert len(set1) == len(G.nodes) or len(set2) == len(G.nodes)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import networkx.algorithms.approximation as apxa
3
+
4
+
5
+ def test_ramsey():
6
+ # this should only find the complete graph
7
+ graph = nx.complete_graph(10)
8
+ c, i = apxa.ramsey_R2(graph)
9
+ cdens = nx.density(graph.subgraph(c))
10
+ assert cdens == 1.0, "clique not correctly found by ramsey!"
11
+ idens = nx.density(graph.subgraph(i))
12
+ assert idens == 0.0, "i-set not correctly found by ramsey!"
13
+
14
+ # this trivial graph has no cliques. should just find i-sets
15
+ graph = nx.trivial_graph()
16
+ c, i = apxa.ramsey_R2(graph)
17
+ assert c == {0}, "clique not correctly found by ramsey!"
18
+ assert i == {0}, "i-set not correctly found by ramsey!"
19
+
20
+ graph = nx.barbell_graph(10, 5, nx.Graph())
21
+ c, i = apxa.ramsey_R2(graph)
22
+ cdens = nx.density(graph.subgraph(c))
23
+ assert cdens == 1.0, "clique not correctly found by ramsey!"
24
+ idens = nx.density(graph.subgraph(i))
25
+ assert idens == 0.0, "i-set not correctly found by ramsey!"
26
+
27
+ # add self-loops and test again
28
+ graph.add_edges_from([(n, n) for n in range(0, len(graph), 2)])
29
+ cc, ii = apxa.ramsey_R2(graph)
30
+ assert cc == c
31
+ assert ii == i
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation.steinertree import (
5
+ _remove_nonterminal_leaves,
6
+ metric_closure,
7
+ steiner_tree,
8
+ )
9
+ from networkx.utils import edges_equal
10
+
11
+
12
+ class TestSteinerTree:
13
+ @classmethod
14
+ def setup_class(cls):
15
+ G1 = nx.Graph()
16
+ G1.add_edge(1, 2, weight=10)
17
+ G1.add_edge(2, 3, weight=10)
18
+ G1.add_edge(3, 4, weight=10)
19
+ G1.add_edge(4, 5, weight=10)
20
+ G1.add_edge(5, 6, weight=10)
21
+ G1.add_edge(2, 7, weight=1)
22
+ G1.add_edge(7, 5, weight=1)
23
+
24
+ G2 = nx.Graph()
25
+ G2.add_edge(0, 5, weight=6)
26
+ G2.add_edge(1, 2, weight=2)
27
+ G2.add_edge(1, 5, weight=3)
28
+ G2.add_edge(2, 4, weight=4)
29
+ G2.add_edge(3, 5, weight=5)
30
+ G2.add_edge(4, 5, weight=1)
31
+
32
+ G3 = nx.Graph()
33
+ G3.add_edge(1, 2, weight=8)
34
+ G3.add_edge(1, 9, weight=3)
35
+ G3.add_edge(1, 8, weight=6)
36
+ G3.add_edge(1, 10, weight=2)
37
+ G3.add_edge(1, 14, weight=3)
38
+ G3.add_edge(2, 3, weight=6)
39
+ G3.add_edge(3, 4, weight=3)
40
+ G3.add_edge(3, 10, weight=2)
41
+ G3.add_edge(3, 11, weight=1)
42
+ G3.add_edge(4, 5, weight=1)
43
+ G3.add_edge(4, 11, weight=1)
44
+ G3.add_edge(5, 6, weight=4)
45
+ G3.add_edge(5, 11, weight=2)
46
+ G3.add_edge(5, 12, weight=1)
47
+ G3.add_edge(5, 13, weight=3)
48
+ G3.add_edge(6, 7, weight=2)
49
+ G3.add_edge(6, 12, weight=3)
50
+ G3.add_edge(6, 13, weight=1)
51
+ G3.add_edge(7, 8, weight=3)
52
+ G3.add_edge(7, 9, weight=3)
53
+ G3.add_edge(7, 11, weight=5)
54
+ G3.add_edge(7, 13, weight=2)
55
+ G3.add_edge(7, 14, weight=4)
56
+ G3.add_edge(8, 9, weight=2)
57
+ G3.add_edge(9, 14, weight=1)
58
+ G3.add_edge(10, 11, weight=2)
59
+ G3.add_edge(10, 14, weight=1)
60
+ G3.add_edge(11, 12, weight=1)
61
+ G3.add_edge(11, 14, weight=7)
62
+ G3.add_edge(12, 14, weight=3)
63
+ G3.add_edge(12, 15, weight=1)
64
+ G3.add_edge(13, 14, weight=4)
65
+ G3.add_edge(13, 15, weight=1)
66
+ G3.add_edge(14, 15, weight=2)
67
+
68
+ cls.G1 = G1
69
+ cls.G2 = G2
70
+ cls.G3 = G3
71
+ cls.G1_term_nodes = [1, 2, 3, 4, 5]
72
+ cls.G2_term_nodes = [0, 2, 3]
73
+ cls.G3_term_nodes = [1, 3, 5, 6, 8, 10, 11, 12, 13]
74
+
75
+ cls.methods = ["kou", "mehlhorn"]
76
+
77
+ def test_connected_metric_closure(self):
78
+ G = self.G1.copy()
79
+ G.add_node(100)
80
+ pytest.raises(nx.NetworkXError, metric_closure, G)
81
+
82
+ def test_metric_closure(self):
83
+ M = metric_closure(self.G1)
84
+ mc = [
85
+ (1, 2, {"distance": 10, "path": [1, 2]}),
86
+ (1, 3, {"distance": 20, "path": [1, 2, 3]}),
87
+ (1, 4, {"distance": 22, "path": [1, 2, 7, 5, 4]}),
88
+ (1, 5, {"distance": 12, "path": [1, 2, 7, 5]}),
89
+ (1, 6, {"distance": 22, "path": [1, 2, 7, 5, 6]}),
90
+ (1, 7, {"distance": 11, "path": [1, 2, 7]}),
91
+ (2, 3, {"distance": 10, "path": [2, 3]}),
92
+ (2, 4, {"distance": 12, "path": [2, 7, 5, 4]}),
93
+ (2, 5, {"distance": 2, "path": [2, 7, 5]}),
94
+ (2, 6, {"distance": 12, "path": [2, 7, 5, 6]}),
95
+ (2, 7, {"distance": 1, "path": [2, 7]}),
96
+ (3, 4, {"distance": 10, "path": [3, 4]}),
97
+ (3, 5, {"distance": 12, "path": [3, 2, 7, 5]}),
98
+ (3, 6, {"distance": 22, "path": [3, 2, 7, 5, 6]}),
99
+ (3, 7, {"distance": 11, "path": [3, 2, 7]}),
100
+ (4, 5, {"distance": 10, "path": [4, 5]}),
101
+ (4, 6, {"distance": 20, "path": [4, 5, 6]}),
102
+ (4, 7, {"distance": 11, "path": [4, 5, 7]}),
103
+ (5, 6, {"distance": 10, "path": [5, 6]}),
104
+ (5, 7, {"distance": 1, "path": [5, 7]}),
105
+ (6, 7, {"distance": 11, "path": [6, 5, 7]}),
106
+ ]
107
+ assert edges_equal(list(M.edges(data=True)), mc)
108
+
109
+ def test_steiner_tree(self):
110
+ valid_steiner_trees = [
111
+ [
112
+ [
113
+ (1, 2, {"weight": 10}),
114
+ (2, 3, {"weight": 10}),
115
+ (2, 7, {"weight": 1}),
116
+ (3, 4, {"weight": 10}),
117
+ (5, 7, {"weight": 1}),
118
+ ],
119
+ [
120
+ (1, 2, {"weight": 10}),
121
+ (2, 7, {"weight": 1}),
122
+ (3, 4, {"weight": 10}),
123
+ (4, 5, {"weight": 10}),
124
+ (5, 7, {"weight": 1}),
125
+ ],
126
+ [
127
+ (1, 2, {"weight": 10}),
128
+ (2, 3, {"weight": 10}),
129
+ (2, 7, {"weight": 1}),
130
+ (4, 5, {"weight": 10}),
131
+ (5, 7, {"weight": 1}),
132
+ ],
133
+ ],
134
+ [
135
+ [
136
+ (0, 5, {"weight": 6}),
137
+ (1, 2, {"weight": 2}),
138
+ (1, 5, {"weight": 3}),
139
+ (3, 5, {"weight": 5}),
140
+ ],
141
+ [
142
+ (0, 5, {"weight": 6}),
143
+ (4, 2, {"weight": 4}),
144
+ (4, 5, {"weight": 1}),
145
+ (3, 5, {"weight": 5}),
146
+ ],
147
+ ],
148
+ [
149
+ [
150
+ (1, 10, {"weight": 2}),
151
+ (3, 10, {"weight": 2}),
152
+ (3, 11, {"weight": 1}),
153
+ (5, 12, {"weight": 1}),
154
+ (6, 13, {"weight": 1}),
155
+ (8, 9, {"weight": 2}),
156
+ (9, 14, {"weight": 1}),
157
+ (10, 14, {"weight": 1}),
158
+ (11, 12, {"weight": 1}),
159
+ (12, 15, {"weight": 1}),
160
+ (13, 15, {"weight": 1}),
161
+ ]
162
+ ],
163
+ ]
164
+ for method in self.methods:
165
+ for G, term_nodes, valid_trees in zip(
166
+ [self.G1, self.G2, self.G3],
167
+ [self.G1_term_nodes, self.G2_term_nodes, self.G3_term_nodes],
168
+ valid_steiner_trees,
169
+ ):
170
+ S = steiner_tree(G, term_nodes, method=method)
171
+ assert any(
172
+ edges_equal(list(S.edges(data=True)), valid_tree)
173
+ for valid_tree in valid_trees
174
+ )
175
+
176
+ def test_multigraph_steiner_tree(self):
177
+ G = nx.MultiGraph()
178
+ G.add_edges_from(
179
+ [
180
+ (1, 2, 0, {"weight": 1}),
181
+ (2, 3, 0, {"weight": 999}),
182
+ (2, 3, 1, {"weight": 1}),
183
+ (3, 4, 0, {"weight": 1}),
184
+ (3, 5, 0, {"weight": 1}),
185
+ ]
186
+ )
187
+ terminal_nodes = [2, 4, 5]
188
+ expected_edges = [
189
+ (2, 3, 1, {"weight": 1}), # edge with key 1 has lower weight
190
+ (3, 4, 0, {"weight": 1}),
191
+ (3, 5, 0, {"weight": 1}),
192
+ ]
193
+ for method in self.methods:
194
+ S = steiner_tree(G, terminal_nodes, method=method)
195
+ assert edges_equal(S.edges(data=True, keys=True), expected_edges)
196
+
197
+ def test_remove_nonterminal_leaves(self):
198
+ G = nx.path_graph(10)
199
+ _remove_nonterminal_leaves(G, [4, 5, 6])
200
+
201
+ assert list(G) == [4, 5, 6] # only the terminal nodes are left
202
+
203
+
204
+ @pytest.mark.parametrize("method", ("kou", "mehlhorn"))
205
+ def test_steiner_tree_weight_attribute(method):
206
+ G = nx.star_graph(4)
207
+ # Add an edge attribute that is named something other than "weight"
208
+ nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
209
+ H = nx.approximation.steiner_tree(G, [1, 3], method=method, weight="distance")
210
+ assert nx.utils.edges_equal(H.edges, [(0, 1), (0, 3)])
211
+
212
+
213
+ @pytest.mark.parametrize("method", ("kou", "mehlhorn"))
214
+ def test_steiner_tree_multigraph_weight_attribute(method):
215
+ G = nx.cycle_graph(3, create_using=nx.MultiGraph)
216
+ nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
217
+ G.add_edge(2, 0, distance=5)
218
+ H = nx.approximation.steiner_tree(G, list(G), method=method, weight="distance")
219
+ assert len(H.edges) == 2 and H.has_edge(2, 0, key=1)
220
+ assert sum(dist for *_, dist in H.edges(data="distance")) == 15
221
+
222
+
223
+ @pytest.mark.parametrize("method", (None, "mehlhorn", "kou"))
224
+ def test_steiner_tree_methods(method):
225
+ G = nx.star_graph(4)
226
+ expected = nx.Graph([(0, 1), (0, 3)])
227
+ st = nx.approximation.steiner_tree(G, [1, 3], method=method)
228
+ assert nx.utils.edges_equal(st.edges, expected.edges)
229
+
230
+
231
+ def test_steiner_tree_method_invalid():
232
+ G = nx.star_graph(4)
233
+ with pytest.raises(
234
+ ValueError, match="invalid_method is not a valid choice for an algorithm."
235
+ ):
236
+ nx.approximation.steiner_tree(G, terminal_nodes=[1, 3], method="invalid_method")
237
+
238
+
239
+ def test_steiner_tree_remove_non_terminal_leaves_self_loop_edges():
240
+ # To verify that the last step of the steiner tree approximation
241
+ # behaves in the case where a non-terminal leaf has a self loop edge
242
+ G = nx.path_graph(10)
243
+
244
+ # Add self loops to the terminal nodes
245
+ G.add_edges_from([(2, 2), (3, 3), (4, 4), (7, 7), (8, 8)])
246
+
247
+ # Remove non-terminal leaves
248
+ _remove_nonterminal_leaves(G, [4, 5, 6, 7])
249
+
250
+ # The terminal nodes should be left
251
+ assert list(G) == [4, 5, 6, 7] # only the terminal nodes are left
252
+
253
+
254
+ def test_steiner_tree_non_terminal_leaves_multigraph_self_loop_edges():
255
+ # To verify that the last step of the steiner tree approximation
256
+ # behaves in the case where a non-terminal leaf has a self loop edge
257
+ G = nx.MultiGraph()
258
+ G.add_edges_from([(i, i + 1) for i in range(10)])
259
+ G.add_edges_from([(2, 2), (3, 3), (4, 4), (4, 4), (7, 7)])
260
+
261
+ # Remove non-terminal leaves
262
+ _remove_nonterminal_leaves(G, [4, 5, 6, 7])
263
+
264
+ # Only the terminal nodes should be left
265
+ assert list(G) == [4, 5, 6, 7]
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py ADDED
@@ -0,0 +1,977 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the traveling_salesman module."""
2
+
3
+ import random
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ import networkx.algorithms.approximation as nx_app
9
+
10
+ pairwise = nx.utils.pairwise
11
+
12
+
13
+ def test_christofides_hamiltonian():
14
+ random.seed(42)
15
+ G = nx.complete_graph(20)
16
+ for u, v in G.edges():
17
+ G[u][v]["weight"] = random.randint(0, 10)
18
+
19
+ H = nx.Graph()
20
+ H.add_edges_from(pairwise(nx_app.christofides(G)))
21
+ H.remove_edges_from(nx.find_cycle(H))
22
+ assert len(H.edges) == 0
23
+
24
+ tree = nx.minimum_spanning_tree(G, weight="weight")
25
+ H = nx.Graph()
26
+ H.add_edges_from(pairwise(nx_app.christofides(G, tree)))
27
+ H.remove_edges_from(nx.find_cycle(H))
28
+ assert len(H.edges) == 0
29
+
30
+
31
+ def test_christofides_incomplete_graph():
32
+ G = nx.complete_graph(10)
33
+ G.remove_edge(0, 1)
34
+ pytest.raises(nx.NetworkXError, nx_app.christofides, G)
35
+
36
+
37
+ def test_christofides_ignore_selfloops():
38
+ G = nx.complete_graph(5)
39
+ G.add_edge(3, 3)
40
+ cycle = nx_app.christofides(G)
41
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
42
+
43
+
44
+ # set up graphs for other tests
45
+ class TestBase:
46
+ @classmethod
47
+ def setup_class(cls):
48
+ cls.DG = nx.DiGraph()
49
+ cls.DG.add_weighted_edges_from(
50
+ {
51
+ ("A", "B", 3),
52
+ ("A", "C", 17),
53
+ ("A", "D", 14),
54
+ ("B", "A", 3),
55
+ ("B", "C", 12),
56
+ ("B", "D", 16),
57
+ ("C", "A", 13),
58
+ ("C", "B", 12),
59
+ ("C", "D", 4),
60
+ ("D", "A", 14),
61
+ ("D", "B", 15),
62
+ ("D", "C", 2),
63
+ }
64
+ )
65
+ cls.DG_cycle = ["D", "C", "B", "A", "D"]
66
+ cls.DG_cost = 31.0
67
+
68
+ cls.DG2 = nx.DiGraph()
69
+ cls.DG2.add_weighted_edges_from(
70
+ {
71
+ ("A", "B", 3),
72
+ ("A", "C", 17),
73
+ ("A", "D", 14),
74
+ ("B", "A", 30),
75
+ ("B", "C", 2),
76
+ ("B", "D", 16),
77
+ ("C", "A", 33),
78
+ ("C", "B", 32),
79
+ ("C", "D", 34),
80
+ ("D", "A", 14),
81
+ ("D", "B", 15),
82
+ ("D", "C", 2),
83
+ }
84
+ )
85
+ cls.DG2_cycle = ["D", "A", "B", "C", "D"]
86
+ cls.DG2_cost = 53.0
87
+
88
+ cls.unweightedUG = nx.complete_graph(5, nx.Graph())
89
+ cls.unweightedDG = nx.complete_graph(5, nx.DiGraph())
90
+
91
+ cls.incompleteUG = nx.Graph()
92
+ cls.incompleteUG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
93
+ cls.incompleteDG = nx.DiGraph()
94
+ cls.incompleteDG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
95
+
96
+ cls.UG = nx.Graph()
97
+ cls.UG.add_weighted_edges_from(
98
+ {
99
+ ("A", "B", 3),
100
+ ("A", "C", 17),
101
+ ("A", "D", 14),
102
+ ("B", "C", 12),
103
+ ("B", "D", 16),
104
+ ("C", "D", 4),
105
+ }
106
+ )
107
+ cls.UG_cycle = ["D", "C", "B", "A", "D"]
108
+ cls.UG_cost = 33.0
109
+
110
+ cls.UG2 = nx.Graph()
111
+ cls.UG2.add_weighted_edges_from(
112
+ {
113
+ ("A", "B", 1),
114
+ ("A", "C", 15),
115
+ ("A", "D", 5),
116
+ ("B", "C", 16),
117
+ ("B", "D", 8),
118
+ ("C", "D", 3),
119
+ }
120
+ )
121
+ cls.UG2_cycle = ["D", "C", "B", "A", "D"]
122
+ cls.UG2_cost = 25.0
123
+
124
+
125
+ def validate_solution(soln, cost, exp_soln, exp_cost):
126
+ assert soln == exp_soln
127
+ assert cost == exp_cost
128
+
129
+
130
+ def validate_symmetric_solution(soln, cost, exp_soln, exp_cost):
131
+ assert soln == exp_soln or soln == exp_soln[::-1]
132
+ assert cost == exp_cost
133
+
134
+
135
+ class TestGreedyTSP(TestBase):
136
+ def test_greedy(self):
137
+ cycle = nx_app.greedy_tsp(self.DG, source="D")
138
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
139
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 31.0)
140
+
141
+ cycle = nx_app.greedy_tsp(self.DG2, source="D")
142
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
143
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 78.0)
144
+
145
+ cycle = nx_app.greedy_tsp(self.UG, source="D")
146
+ cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
147
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 33.0)
148
+
149
+ cycle = nx_app.greedy_tsp(self.UG2, source="D")
150
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
151
+ validate_solution(cycle, cost, ["D", "C", "A", "B", "D"], 27.0)
152
+
153
+ def test_not_complete_graph(self):
154
+ pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteUG)
155
+ pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteDG)
156
+
157
+ def test_not_weighted_graph(self):
158
+ nx_app.greedy_tsp(self.unweightedUG)
159
+ nx_app.greedy_tsp(self.unweightedDG)
160
+
161
+ def test_two_nodes(self):
162
+ G = nx.Graph()
163
+ G.add_weighted_edges_from({(1, 2, 1)})
164
+ cycle = nx_app.greedy_tsp(G)
165
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
166
+ validate_solution(cycle, cost, [1, 2, 1], 2)
167
+
168
+ def test_ignore_selfloops(self):
169
+ G = nx.complete_graph(5)
170
+ G.add_edge(3, 3)
171
+ cycle = nx_app.greedy_tsp(G)
172
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
173
+
174
+
175
+ class TestSimulatedAnnealingTSP(TestBase):
176
+ tsp = staticmethod(nx_app.simulated_annealing_tsp)
177
+
178
+ def test_simulated_annealing_directed(self):
179
+ cycle = self.tsp(self.DG, "greedy", source="D", seed=42)
180
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
181
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
182
+
183
+ initial_sol = ["D", "B", "A", "C", "D"]
184
+ cycle = self.tsp(self.DG, initial_sol, source="D", seed=42)
185
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
186
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
187
+
188
+ initial_sol = ["D", "A", "C", "B", "D"]
189
+ cycle = self.tsp(self.DG, initial_sol, move="1-0", source="D", seed=42)
190
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
191
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
192
+
193
+ cycle = self.tsp(self.DG2, "greedy", source="D", seed=42)
194
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
195
+ validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
196
+
197
+ cycle = self.tsp(self.DG2, "greedy", move="1-0", source="D", seed=42)
198
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
199
+ validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
200
+
201
+ def test_simulated_annealing_undirected(self):
202
+ cycle = self.tsp(self.UG, "greedy", source="D", seed=42)
203
+ cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
204
+ validate_solution(cycle, cost, self.UG_cycle, self.UG_cost)
205
+
206
+ cycle = self.tsp(self.UG2, "greedy", source="D", seed=42)
207
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
208
+ validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
209
+
210
+ cycle = self.tsp(self.UG2, "greedy", move="1-0", source="D", seed=42)
211
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
212
+ validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
213
+
214
+ def test_error_on_input_order_mistake(self):
215
+ # see issue #4846 https://github.com/networkx/networkx/issues/4846
216
+ pytest.raises(TypeError, self.tsp, self.UG, weight="weight")
217
+ pytest.raises(nx.NetworkXError, self.tsp, self.UG, "weight")
218
+
219
+ def test_not_complete_graph(self):
220
+ pytest.raises(nx.NetworkXError, self.tsp, self.incompleteUG, "greedy", source=0)
221
+ pytest.raises(nx.NetworkXError, self.tsp, self.incompleteDG, "greedy", source=0)
222
+
223
+ def test_ignore_selfloops(self):
224
+ G = nx.complete_graph(5)
225
+ G.add_edge(3, 3)
226
+ cycle = self.tsp(G, "greedy")
227
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
228
+
229
+ def test_not_weighted_graph(self):
230
+ self.tsp(self.unweightedUG, "greedy")
231
+ self.tsp(self.unweightedDG, "greedy")
232
+
233
+ def test_two_nodes(self):
234
+ G = nx.Graph()
235
+ G.add_weighted_edges_from({(1, 2, 1)})
236
+
237
+ cycle = self.tsp(G, "greedy", source=1, seed=42)
238
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
239
+ validate_solution(cycle, cost, [1, 2, 1], 2)
240
+
241
+ cycle = self.tsp(G, [1, 2, 1], source=1, seed=42)
242
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
243
+ validate_solution(cycle, cost, [1, 2, 1], 2)
244
+
245
+ def test_failure_of_costs_too_high_when_iterations_low(self):
246
+ # Simulated Annealing Version:
247
+ # set number of moves low and alpha high
248
+ cycle = self.tsp(
249
+ self.DG2, "greedy", source="D", move="1-0", alpha=1, N_inner=1, seed=42
250
+ )
251
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
252
+ print(cycle, cost)
253
+ assert cost > self.DG2_cost
254
+
255
+ # Try with an incorrect initial guess
256
+ initial_sol = ["D", "A", "B", "C", "D"]
257
+ cycle = self.tsp(
258
+ self.DG,
259
+ initial_sol,
260
+ source="D",
261
+ move="1-0",
262
+ alpha=0.1,
263
+ N_inner=1,
264
+ max_iterations=1,
265
+ seed=42,
266
+ )
267
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
268
+ print(cycle, cost)
269
+ assert cost > self.DG_cost
270
+
271
+
272
+ class TestThresholdAcceptingTSP(TestSimulatedAnnealingTSP):
273
+ tsp = staticmethod(nx_app.threshold_accepting_tsp)
274
+
275
+ def test_failure_of_costs_too_high_when_iterations_low(self):
276
+ # Threshold Version:
277
+ # set number of moves low and number of iterations low
278
+ cycle = self.tsp(
279
+ self.DG2,
280
+ "greedy",
281
+ source="D",
282
+ move="1-0",
283
+ N_inner=1,
284
+ max_iterations=1,
285
+ seed=4,
286
+ )
287
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
288
+ assert cost > self.DG2_cost
289
+
290
+ # set threshold too low
291
+ initial_sol = ["D", "A", "B", "C", "D"]
292
+ cycle = self.tsp(
293
+ self.DG, initial_sol, source="D", move="1-0", threshold=-3, seed=42
294
+ )
295
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
296
+ assert cost > self.DG_cost
297
+
298
+
299
+ # Tests for function traveling_salesman_problem
300
+ def test_TSP_method():
301
+ G = nx.cycle_graph(9)
302
+ G[4][5]["weight"] = 10
303
+
304
+ # Test using the old currying method
305
+ sa_tsp = lambda G, weight: nx_app.simulated_annealing_tsp(
306
+ G, "greedy", weight, source=4, seed=1
307
+ )
308
+
309
+ path = nx_app.traveling_salesman_problem(
310
+ G,
311
+ method=sa_tsp,
312
+ cycle=False,
313
+ )
314
+ print(path)
315
+ assert path == [4, 3, 2, 1, 0, 8, 7, 6, 5]
316
+
317
+
318
+ def test_TSP_unweighted():
319
+ G = nx.cycle_graph(9)
320
+ path = nx_app.traveling_salesman_problem(G, nodes=[3, 6], cycle=False)
321
+ assert path in ([3, 4, 5, 6], [6, 5, 4, 3])
322
+
323
+ cycle = nx_app.traveling_salesman_problem(G, nodes=[3, 6])
324
+ assert cycle in ([3, 4, 5, 6, 5, 4, 3], [6, 5, 4, 3, 4, 5, 6])
325
+
326
+
327
+ def test_TSP_weighted():
328
+ G = nx.cycle_graph(9)
329
+ G[0][1]["weight"] = 2
330
+ G[1][2]["weight"] = 2
331
+ G[2][3]["weight"] = 2
332
+ G[3][4]["weight"] = 4
333
+ G[4][5]["weight"] = 5
334
+ G[5][6]["weight"] = 4
335
+ G[6][7]["weight"] = 2
336
+ G[7][8]["weight"] = 2
337
+ G[8][0]["weight"] = 2
338
+ tsp = nx_app.traveling_salesman_problem
339
+
340
+ # path between 3 and 6
341
+ expected_paths = ([3, 2, 1, 0, 8, 7, 6], [6, 7, 8, 0, 1, 2, 3])
342
+ # cycle between 3 and 6
343
+ expected_cycles = (
344
+ [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3],
345
+ [6, 7, 8, 0, 1, 2, 3, 2, 1, 0, 8, 7, 6],
346
+ )
347
+ # path through all nodes
348
+ expected_tourpaths = ([5, 6, 7, 8, 0, 1, 2, 3, 4], [4, 3, 2, 1, 0, 8, 7, 6, 5])
349
+
350
+ # Check default method
351
+ cycle = tsp(G, nodes=[3, 6], weight="weight")
352
+ assert cycle in expected_cycles
353
+
354
+ path = tsp(G, nodes=[3, 6], weight="weight", cycle=False)
355
+ assert path in expected_paths
356
+
357
+ tourpath = tsp(G, weight="weight", cycle=False)
358
+ assert tourpath in expected_tourpaths
359
+
360
+ # Check all methods
361
+ methods = [
362
+ (nx_app.christofides, {}),
363
+ (nx_app.greedy_tsp, {}),
364
+ (
365
+ nx_app.simulated_annealing_tsp,
366
+ {"init_cycle": "greedy"},
367
+ ),
368
+ (
369
+ nx_app.threshold_accepting_tsp,
370
+ {"init_cycle": "greedy"},
371
+ ),
372
+ ]
373
+ for method, kwargs in methods:
374
+ cycle = tsp(G, nodes=[3, 6], weight="weight", method=method, **kwargs)
375
+ assert cycle in expected_cycles
376
+
377
+ path = tsp(
378
+ G, nodes=[3, 6], weight="weight", method=method, cycle=False, **kwargs
379
+ )
380
+ assert path in expected_paths
381
+
382
+ tourpath = tsp(G, weight="weight", method=method, cycle=False, **kwargs)
383
+ assert tourpath in expected_tourpaths
384
+
385
+
386
+ def test_TSP_incomplete_graph_short_path():
387
+ G = nx.cycle_graph(9)
388
+ G.add_edges_from([(4, 9), (9, 10), (10, 11), (11, 0)])
389
+ G[4][5]["weight"] = 5
390
+
391
+ cycle = nx_app.traveling_salesman_problem(G)
392
+ print(cycle)
393
+ assert len(cycle) == 17 and len(set(cycle)) == 12
394
+
395
+ # make sure that cutting one edge out of complete graph formulation
396
+ # cuts out many edges out of the path of the TSP
397
+ path = nx_app.traveling_salesman_problem(G, cycle=False)
398
+ print(path)
399
+ assert len(path) == 13 and len(set(path)) == 12
400
+
401
+
402
+ def test_held_karp_ascent():
403
+ """
404
+ Test the Held-Karp relaxation with the ascent method
405
+ """
406
+ import networkx.algorithms.approximation.traveling_salesman as tsp
407
+
408
+ np = pytest.importorskip("numpy")
409
+ pytest.importorskip("scipy")
410
+
411
+ # Adjacency matrix from page 1153 of the 1970 Held and Karp paper
412
+ # which have been edited to be directional, but also symmetric
413
+ G_array = np.array(
414
+ [
415
+ [0, 97, 60, 73, 17, 52],
416
+ [97, 0, 41, 52, 90, 30],
417
+ [60, 41, 0, 21, 35, 41],
418
+ [73, 52, 21, 0, 95, 46],
419
+ [17, 90, 35, 95, 0, 81],
420
+ [52, 30, 41, 46, 81, 0],
421
+ ]
422
+ )
423
+
424
+ solution_edges = [(1, 3), (2, 4), (3, 2), (4, 0), (5, 1), (0, 5)]
425
+
426
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
427
+ opt_hk, z_star = tsp.held_karp_ascent(G)
428
+
429
+ # Check that the optimal weights are the same
430
+ assert round(opt_hk, 2) == 207.00
431
+ # Check that the z_stars are the same
432
+ solution = nx.DiGraph()
433
+ solution.add_edges_from(solution_edges)
434
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
435
+
436
+
437
+ def test_ascent_fractional_solution():
438
+ """
439
+ Test the ascent method using a modified version of Figure 2 on page 1140
440
+ in 'The Traveling Salesman Problem and Minimum Spanning Trees' by Held and
441
+ Karp
442
+ """
443
+ import networkx.algorithms.approximation.traveling_salesman as tsp
444
+
445
+ np = pytest.importorskip("numpy")
446
+ pytest.importorskip("scipy")
447
+
448
+ # This version of Figure 2 has all of the edge weights multiplied by 100
449
+ # and is a complete directed graph with infinite edge weights for the
450
+ # edges not listed in the original graph
451
+ G_array = np.array(
452
+ [
453
+ [0, 100, 100, 100000, 100000, 1],
454
+ [100, 0, 100, 100000, 1, 100000],
455
+ [100, 100, 0, 1, 100000, 100000],
456
+ [100000, 100000, 1, 0, 100, 100],
457
+ [100000, 1, 100000, 100, 0, 100],
458
+ [1, 100000, 100000, 100, 100, 0],
459
+ ]
460
+ )
461
+
462
+ solution_z_star = {
463
+ (0, 1): 5 / 12,
464
+ (0, 2): 5 / 12,
465
+ (0, 5): 5 / 6,
466
+ (1, 0): 5 / 12,
467
+ (1, 2): 1 / 3,
468
+ (1, 4): 5 / 6,
469
+ (2, 0): 5 / 12,
470
+ (2, 1): 1 / 3,
471
+ (2, 3): 5 / 6,
472
+ (3, 2): 5 / 6,
473
+ (3, 4): 1 / 3,
474
+ (3, 5): 1 / 2,
475
+ (4, 1): 5 / 6,
476
+ (4, 3): 1 / 3,
477
+ (4, 5): 1 / 2,
478
+ (5, 0): 5 / 6,
479
+ (5, 3): 1 / 2,
480
+ (5, 4): 1 / 2,
481
+ }
482
+
483
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
484
+ opt_hk, z_star = tsp.held_karp_ascent(G)
485
+
486
+ # Check that the optimal weights are the same
487
+ assert round(opt_hk, 2) == 303.00
488
+ # Check that the z_stars are the same
489
+ assert {key: round(z_star[key], 4) for key in z_star} == {
490
+ key: round(solution_z_star[key], 4) for key in solution_z_star
491
+ }
492
+
493
+
494
+ def test_ascent_method_asymmetric():
495
+ """
496
+ Tests the ascent method using a truly asymmetric graph for which the
497
+ solution has been brute forced
498
+ """
499
+ import networkx.algorithms.approximation.traveling_salesman as tsp
500
+
501
+ np = pytest.importorskip("numpy")
502
+ pytest.importorskip("scipy")
503
+
504
+ G_array = np.array(
505
+ [
506
+ [0, 26, 63, 59, 69, 31, 41],
507
+ [62, 0, 91, 53, 75, 87, 47],
508
+ [47, 82, 0, 90, 15, 9, 18],
509
+ [68, 19, 5, 0, 58, 34, 93],
510
+ [11, 58, 53, 55, 0, 61, 79],
511
+ [88, 75, 13, 76, 98, 0, 40],
512
+ [41, 61, 55, 88, 46, 45, 0],
513
+ ]
514
+ )
515
+
516
+ solution_edges = [(0, 1), (1, 3), (3, 2), (2, 5), (5, 6), (4, 0), (6, 4)]
517
+
518
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
519
+ opt_hk, z_star = tsp.held_karp_ascent(G)
520
+
521
+ # Check that the optimal weights are the same
522
+ assert round(opt_hk, 2) == 190.00
523
+ # Check that the z_stars match.
524
+ solution = nx.DiGraph()
525
+ solution.add_edges_from(solution_edges)
526
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
527
+
528
+
529
+ def test_ascent_method_asymmetric_2():
530
+ """
531
+ Tests the ascent method using a truly asymmetric graph for which the
532
+ solution has been brute forced
533
+ """
534
+ import networkx.algorithms.approximation.traveling_salesman as tsp
535
+
536
+ np = pytest.importorskip("numpy")
537
+ pytest.importorskip("scipy")
538
+
539
+ G_array = np.array(
540
+ [
541
+ [0, 45, 39, 92, 29, 31],
542
+ [72, 0, 4, 12, 21, 60],
543
+ [81, 6, 0, 98, 70, 53],
544
+ [49, 71, 59, 0, 98, 94],
545
+ [74, 95, 24, 43, 0, 47],
546
+ [56, 43, 3, 65, 22, 0],
547
+ ]
548
+ )
549
+
550
+ solution_edges = [(0, 5), (5, 4), (1, 3), (3, 0), (2, 1), (4, 2)]
551
+
552
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
553
+ opt_hk, z_star = tsp.held_karp_ascent(G)
554
+
555
+ # Check that the optimal weights are the same
556
+ assert round(opt_hk, 2) == 144.00
557
+ # Check that the z_stars match.
558
+ solution = nx.DiGraph()
559
+ solution.add_edges_from(solution_edges)
560
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
561
+
562
+
563
+ def test_held_karp_ascent_asymmetric_3():
564
+ """
565
+ Tests the ascent method using a truly asymmetric graph with a fractional
566
+ solution for which the solution has been brute forced.
567
+
568
+ In this graph their are two different optimal, integral solutions (which
569
+ are also the overall atsp solutions) to the Held Karp relaxation. However,
570
+ this particular graph has two different tours of optimal value and the
571
+ possible solutions in the held_karp_ascent function are not stored in an
572
+ ordered data structure.
573
+ """
574
+ import networkx.algorithms.approximation.traveling_salesman as tsp
575
+
576
+ np = pytest.importorskip("numpy")
577
+ pytest.importorskip("scipy")
578
+
579
+ G_array = np.array(
580
+ [
581
+ [0, 1, 5, 2, 7, 4],
582
+ [7, 0, 7, 7, 1, 4],
583
+ [4, 7, 0, 9, 2, 1],
584
+ [7, 2, 7, 0, 4, 4],
585
+ [5, 5, 4, 4, 0, 3],
586
+ [3, 9, 1, 3, 4, 0],
587
+ ]
588
+ )
589
+
590
+ solution1_edges = [(0, 3), (1, 4), (2, 5), (3, 1), (4, 2), (5, 0)]
591
+
592
+ solution2_edges = [(0, 3), (3, 1), (1, 4), (4, 5), (2, 0), (5, 2)]
593
+
594
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
595
+ opt_hk, z_star = tsp.held_karp_ascent(G)
596
+
597
+ assert round(opt_hk, 2) == 13.00
598
+ # Check that the z_stars are the same
599
+ solution1 = nx.DiGraph()
600
+ solution1.add_edges_from(solution1_edges)
601
+ solution2 = nx.DiGraph()
602
+ solution2.add_edges_from(solution2_edges)
603
+ assert nx.utils.edges_equal(z_star.edges, solution1.edges) or nx.utils.edges_equal(
604
+ z_star.edges, solution2.edges
605
+ )
606
+
607
+
608
+ def test_held_karp_ascent_fractional_asymmetric():
609
+ """
610
+ Tests the ascent method using a truly asymmetric graph with a fractional
611
+ solution for which the solution has been brute forced
612
+ """
613
+ import networkx.algorithms.approximation.traveling_salesman as tsp
614
+
615
+ np = pytest.importorskip("numpy")
616
+ pytest.importorskip("scipy")
617
+
618
+ G_array = np.array(
619
+ [
620
+ [0, 100, 150, 100000, 100000, 1],
621
+ [150, 0, 100, 100000, 1, 100000],
622
+ [100, 150, 0, 1, 100000, 100000],
623
+ [100000, 100000, 1, 0, 150, 100],
624
+ [100000, 2, 100000, 100, 0, 150],
625
+ [2, 100000, 100000, 150, 100, 0],
626
+ ]
627
+ )
628
+
629
+ solution_z_star = {
630
+ (0, 1): 5 / 12,
631
+ (0, 2): 5 / 12,
632
+ (0, 5): 5 / 6,
633
+ (1, 0): 5 / 12,
634
+ (1, 2): 5 / 12,
635
+ (1, 4): 5 / 6,
636
+ (2, 0): 5 / 12,
637
+ (2, 1): 5 / 12,
638
+ (2, 3): 5 / 6,
639
+ (3, 2): 5 / 6,
640
+ (3, 4): 5 / 12,
641
+ (3, 5): 5 / 12,
642
+ (4, 1): 5 / 6,
643
+ (4, 3): 5 / 12,
644
+ (4, 5): 5 / 12,
645
+ (5, 0): 5 / 6,
646
+ (5, 3): 5 / 12,
647
+ (5, 4): 5 / 12,
648
+ }
649
+
650
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
651
+ opt_hk, z_star = tsp.held_karp_ascent(G)
652
+
653
+ # Check that the optimal weights are the same
654
+ assert round(opt_hk, 2) == 304.00
655
+ # Check that the z_stars are the same
656
+ assert {key: round(z_star[key], 4) for key in z_star} == {
657
+ key: round(solution_z_star[key], 4) for key in solution_z_star
658
+ }
659
+
660
+
661
+ def test_spanning_tree_distribution():
662
+ """
663
+ Test that we can create an exponential distribution of spanning trees such
664
+ that the probability of each tree is proportional to the product of edge
665
+ weights.
666
+
667
+ Results of this test have been confirmed with hypothesis testing from the
668
+ created distribution.
669
+
670
+ This test uses the symmetric, fractional Held Karp solution.
671
+ """
672
+ import networkx.algorithms.approximation.traveling_salesman as tsp
673
+
674
+ pytest.importorskip("numpy")
675
+ pytest.importorskip("scipy")
676
+
677
+ z_star = {
678
+ (0, 1): 5 / 12,
679
+ (0, 2): 5 / 12,
680
+ (0, 5): 5 / 6,
681
+ (1, 0): 5 / 12,
682
+ (1, 2): 1 / 3,
683
+ (1, 4): 5 / 6,
684
+ (2, 0): 5 / 12,
685
+ (2, 1): 1 / 3,
686
+ (2, 3): 5 / 6,
687
+ (3, 2): 5 / 6,
688
+ (3, 4): 1 / 3,
689
+ (3, 5): 1 / 2,
690
+ (4, 1): 5 / 6,
691
+ (4, 3): 1 / 3,
692
+ (4, 5): 1 / 2,
693
+ (5, 0): 5 / 6,
694
+ (5, 3): 1 / 2,
695
+ (5, 4): 1 / 2,
696
+ }
697
+
698
+ solution_gamma = {
699
+ (0, 1): -0.6383,
700
+ (0, 2): -0.6827,
701
+ (0, 5): 0,
702
+ (1, 2): -1.0781,
703
+ (1, 4): 0,
704
+ (2, 3): 0,
705
+ (5, 3): -0.2820,
706
+ (5, 4): -0.3327,
707
+ (4, 3): -0.9927,
708
+ }
709
+
710
+ # The undirected support of z_star
711
+ G = nx.MultiGraph()
712
+ for u, v in z_star:
713
+ if (u, v) in G.edges or (v, u) in G.edges:
714
+ continue
715
+ G.add_edge(u, v)
716
+
717
+ gamma = tsp.spanning_tree_distribution(G, z_star)
718
+
719
+ assert {key: round(gamma[key], 4) for key in gamma} == solution_gamma
720
+
721
+
722
+ def test_asadpour_tsp():
723
+ """
724
+ Test the complete asadpour tsp algorithm with the fractional, symmetric
725
+ Held Karp solution. This test also uses an incomplete graph as input.
726
+ """
727
+ # This version of Figure 2 has all of the edge weights multiplied by 100
728
+ # and the 0 weight edges have a weight of 1.
729
+ pytest.importorskip("numpy")
730
+ pytest.importorskip("scipy")
731
+
732
+ edge_list = [
733
+ (0, 1, 100),
734
+ (0, 2, 100),
735
+ (0, 5, 1),
736
+ (1, 2, 100),
737
+ (1, 4, 1),
738
+ (2, 3, 1),
739
+ (3, 4, 100),
740
+ (3, 5, 100),
741
+ (4, 5, 100),
742
+ (1, 0, 100),
743
+ (2, 0, 100),
744
+ (5, 0, 1),
745
+ (2, 1, 100),
746
+ (4, 1, 1),
747
+ (3, 2, 1),
748
+ (4, 3, 100),
749
+ (5, 3, 100),
750
+ (5, 4, 100),
751
+ ]
752
+
753
+ G = nx.DiGraph()
754
+ G.add_weighted_edges_from(edge_list)
755
+
756
+ tour = nx_app.traveling_salesman_problem(
757
+ G, weight="weight", method=nx_app.asadpour_atsp, seed=19
758
+ )
759
+
760
+ # Check that the returned list is a valid tour. Because this is an
761
+ # incomplete graph, the conditions are not as strict. We need the tour to
762
+ #
763
+ # Start and end at the same node
764
+ # Pass through every vertex at least once
765
+ # Have a total cost at most ln(6) / ln(ln(6)) = 3.0723 times the optimal
766
+ #
767
+ # For the second condition it is possible to have the tour pass through the
768
+ # same vertex more then. Imagine that the tour on the complete version takes
769
+ # an edge not in the original graph. In the output this is substituted with
770
+ # the shortest path between those vertices, allowing vertices to appear more
771
+ # than once.
772
+ #
773
+ # Even though we are using a fixed seed, multiple tours have been known to
774
+ # be returned. The first two are from the original development of this test,
775
+ # and the third one from issue #5913 on GitHub. If other tours are returned,
776
+ # add it on the list of expected tours.
777
+ expected_tours = [
778
+ [1, 4, 5, 0, 2, 3, 2, 1],
779
+ [3, 2, 0, 1, 4, 5, 3],
780
+ [3, 2, 1, 0, 5, 4, 3],
781
+ ]
782
+
783
+ assert tour in expected_tours
784
+
785
+
786
+ def test_asadpour_real_world():
787
+ """
788
+ This test uses airline prices between the six largest cities in the US.
789
+
790
+ * New York City -> JFK
791
+ * Los Angeles -> LAX
792
+ * Chicago -> ORD
793
+ * Houston -> IAH
794
+ * Phoenix -> PHX
795
+ * Philadelphia -> PHL
796
+
797
+ Flight prices from August 2021 using Delta or American airlines to get
798
+ nonstop flight. The brute force solution found the optimal tour to cost $872
799
+
800
+ This test also uses the `source` keyword argument to ensure that the tour
801
+ always starts at city 0.
802
+ """
803
+ np = pytest.importorskip("numpy")
804
+ pytest.importorskip("scipy")
805
+
806
+ G_array = np.array(
807
+ [
808
+ # JFK LAX ORD IAH PHX PHL
809
+ [0, 243, 199, 208, 169, 183], # JFK
810
+ [277, 0, 217, 123, 127, 252], # LAX
811
+ [297, 197, 0, 197, 123, 177], # ORD
812
+ [303, 169, 197, 0, 117, 117], # IAH
813
+ [257, 127, 160, 117, 0, 319], # PHX
814
+ [183, 332, 217, 117, 319, 0], # PHL
815
+ ]
816
+ )
817
+
818
+ node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"]
819
+
820
+ expected_tours = [
821
+ ["JFK", "LAX", "PHX", "ORD", "IAH", "PHL", "JFK"],
822
+ ["JFK", "ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
823
+ ]
824
+
825
+ G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph)
826
+
827
+ tour = nx_app.traveling_salesman_problem(
828
+ G, weight="weight", method=nx_app.asadpour_atsp, seed=37, source="JFK"
829
+ )
830
+
831
+ assert tour in expected_tours
832
+
833
+
834
+ def test_asadpour_real_world_path():
835
+ """
836
+ This test uses airline prices between the six largest cities in the US. This
837
+ time using a path, not a cycle.
838
+
839
+ * New York City -> JFK
840
+ * Los Angeles -> LAX
841
+ * Chicago -> ORD
842
+ * Houston -> IAH
843
+ * Phoenix -> PHX
844
+ * Philadelphia -> PHL
845
+
846
+ Flight prices from August 2021 using Delta or American airlines to get
847
+ nonstop flight. The brute force solution found the optimal tour to cost $872
848
+ """
849
+ np = pytest.importorskip("numpy")
850
+ pytest.importorskip("scipy")
851
+
852
+ G_array = np.array(
853
+ [
854
+ # JFK LAX ORD IAH PHX PHL
855
+ [0, 243, 199, 208, 169, 183], # JFK
856
+ [277, 0, 217, 123, 127, 252], # LAX
857
+ [297, 197, 0, 197, 123, 177], # ORD
858
+ [303, 169, 197, 0, 117, 117], # IAH
859
+ [257, 127, 160, 117, 0, 319], # PHX
860
+ [183, 332, 217, 117, 319, 0], # PHL
861
+ ]
862
+ )
863
+
864
+ node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"]
865
+
866
+ expected_paths = [
867
+ ["ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
868
+ ["JFK", "PHL", "IAH", "ORD", "PHX", "LAX"],
869
+ ]
870
+
871
+ G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph)
872
+
873
+ path = nx_app.traveling_salesman_problem(
874
+ G, weight="weight", cycle=False, method=nx_app.asadpour_atsp, seed=56
875
+ )
876
+
877
+ assert path in expected_paths
878
+
879
+
880
+ def test_asadpour_disconnected_graph():
881
+ """
882
+ Test that the proper exception is raised when asadpour_atsp is given an
883
+ disconnected graph.
884
+ """
885
+
886
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
887
+ # have to set edge weights so that if the exception is not raised, the
888
+ # function will complete and we will fail the test
889
+ nx.set_edge_attributes(G, 1, "weight")
890
+ G.add_node(5)
891
+
892
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
893
+
894
+
895
+ def test_asadpour_incomplete_graph():
896
+ """
897
+ Test that the proper exception is raised when asadpour_atsp is given an
898
+ incomplete graph
899
+ """
900
+
901
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
902
+ # have to set edge weights so that if the exception is not raised, the
903
+ # function will complete and we will fail the test
904
+ nx.set_edge_attributes(G, 1, "weight")
905
+ G.remove_edge(0, 1)
906
+
907
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
908
+
909
+
910
+ def test_asadpour_empty_graph():
911
+ """
912
+ Test the asadpour_atsp function with an empty graph
913
+ """
914
+ G = nx.DiGraph()
915
+
916
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
917
+
918
+
919
+ @pytest.mark.slow
920
+ def test_asadpour_integral_held_karp():
921
+ """
922
+ This test uses an integral held karp solution and the held karp function
923
+ will return a graph rather than a dict, bypassing most of the asadpour
924
+ algorithm.
925
+
926
+ At first glance, this test probably doesn't look like it ensures that we
927
+ skip the rest of the asadpour algorithm, but it does. We are not fixing a
928
+ see for the random number generator, so if we sample any spanning trees
929
+ the approximation would be different basically every time this test is
930
+ executed but it is not since held karp is deterministic and we do not
931
+ reach the portion of the code with the dependence on random numbers.
932
+ """
933
+ np = pytest.importorskip("numpy")
934
+
935
+ G_array = np.array(
936
+ [
937
+ [0, 26, 63, 59, 69, 31, 41],
938
+ [62, 0, 91, 53, 75, 87, 47],
939
+ [47, 82, 0, 90, 15, 9, 18],
940
+ [68, 19, 5, 0, 58, 34, 93],
941
+ [11, 58, 53, 55, 0, 61, 79],
942
+ [88, 75, 13, 76, 98, 0, 40],
943
+ [41, 61, 55, 88, 46, 45, 0],
944
+ ]
945
+ )
946
+
947
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
948
+
949
+ for _ in range(2):
950
+ tour = nx_app.traveling_salesman_problem(G, method=nx_app.asadpour_atsp)
951
+
952
+ assert [1, 3, 2, 5, 2, 6, 4, 0, 1] == tour
953
+
954
+
955
+ def test_directed_tsp_impossible():
956
+ """
957
+ Test the asadpour algorithm with a graph without a hamiltonian circuit
958
+ """
959
+ pytest.importorskip("numpy")
960
+
961
+ # In this graph, once we leave node 0 we cannot return
962
+ edges = [
963
+ (0, 1, 10),
964
+ (0, 2, 11),
965
+ (0, 3, 12),
966
+ (1, 2, 4),
967
+ (1, 3, 6),
968
+ (2, 1, 3),
969
+ (2, 3, 2),
970
+ (3, 1, 5),
971
+ (3, 2, 1),
972
+ ]
973
+
974
+ G = nx.DiGraph()
975
+ G.add_weighted_edges_from(edges)
976
+
977
+ pytest.raises(nx.NetworkXError, nx_app.traveling_salesman_problem, G)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ treewidth_min_degree,
6
+ treewidth_min_fill_in,
7
+ )
8
+ from networkx.algorithms.approximation.treewidth import (
9
+ MinDegreeHeuristic,
10
+ min_fill_in_heuristic,
11
+ )
12
+
13
+
14
+ def is_tree_decomp(graph, decomp):
15
+ """Check if the given tree decomposition is valid."""
16
+ for x in graph.nodes():
17
+ appear_once = False
18
+ for bag in decomp.nodes():
19
+ if x in bag:
20
+ appear_once = True
21
+ break
22
+ assert appear_once
23
+
24
+ # Check if each connected pair of nodes are at least once together in a bag
25
+ for x, y in graph.edges():
26
+ appear_together = False
27
+ for bag in decomp.nodes():
28
+ if x in bag and y in bag:
29
+ appear_together = True
30
+ break
31
+ assert appear_together
32
+
33
+ # Check if the nodes associated with vertex v form a connected subset of T
34
+ for v in graph.nodes():
35
+ subset = []
36
+ for bag in decomp.nodes():
37
+ if v in bag:
38
+ subset.append(bag)
39
+ sub_graph = decomp.subgraph(subset)
40
+ assert nx.is_connected(sub_graph)
41
+
42
+
43
+ class TestTreewidthMinDegree:
44
+ """Unit tests for the min_degree function"""
45
+
46
+ @classmethod
47
+ def setup_class(cls):
48
+ """Setup for different kinds of trees"""
49
+ cls.complete = nx.Graph()
50
+ cls.complete.add_edge(1, 2)
51
+ cls.complete.add_edge(2, 3)
52
+ cls.complete.add_edge(1, 3)
53
+
54
+ cls.small_tree = nx.Graph()
55
+ cls.small_tree.add_edge(1, 3)
56
+ cls.small_tree.add_edge(4, 3)
57
+ cls.small_tree.add_edge(2, 3)
58
+ cls.small_tree.add_edge(3, 5)
59
+ cls.small_tree.add_edge(5, 6)
60
+ cls.small_tree.add_edge(5, 7)
61
+ cls.small_tree.add_edge(6, 7)
62
+
63
+ cls.deterministic_graph = nx.Graph()
64
+ cls.deterministic_graph.add_edge(0, 1) # deg(0) = 1
65
+
66
+ cls.deterministic_graph.add_edge(1, 2) # deg(1) = 2
67
+
68
+ cls.deterministic_graph.add_edge(2, 3)
69
+ cls.deterministic_graph.add_edge(2, 4) # deg(2) = 3
70
+
71
+ cls.deterministic_graph.add_edge(3, 4)
72
+ cls.deterministic_graph.add_edge(3, 5)
73
+ cls.deterministic_graph.add_edge(3, 6) # deg(3) = 4
74
+
75
+ cls.deterministic_graph.add_edge(4, 5)
76
+ cls.deterministic_graph.add_edge(4, 6)
77
+ cls.deterministic_graph.add_edge(4, 7) # deg(4) = 5
78
+
79
+ cls.deterministic_graph.add_edge(5, 6)
80
+ cls.deterministic_graph.add_edge(5, 7)
81
+ cls.deterministic_graph.add_edge(5, 8)
82
+ cls.deterministic_graph.add_edge(5, 9) # deg(5) = 6
83
+
84
+ cls.deterministic_graph.add_edge(6, 7)
85
+ cls.deterministic_graph.add_edge(6, 8)
86
+ cls.deterministic_graph.add_edge(6, 9) # deg(6) = 6
87
+
88
+ cls.deterministic_graph.add_edge(7, 8)
89
+ cls.deterministic_graph.add_edge(7, 9) # deg(7) = 5
90
+
91
+ cls.deterministic_graph.add_edge(8, 9) # deg(8) = 4
92
+
93
+ def test_petersen_graph(self):
94
+ """Test Petersen graph tree decomposition result"""
95
+ G = nx.petersen_graph()
96
+ _, decomp = treewidth_min_degree(G)
97
+ is_tree_decomp(G, decomp)
98
+
99
+ def test_small_tree_treewidth(self):
100
+ """Test small tree
101
+
102
+ Test if the computed treewidth of the known self.small_tree is 2.
103
+ As we know which value we can expect from our heuristic, values other
104
+ than two are regressions
105
+ """
106
+ G = self.small_tree
107
+ # the order of removal should be [1,2,4]3[5,6,7]
108
+ # (with [] denoting any order of the containing nodes)
109
+ # resulting in treewidth 2 for the heuristic
110
+ treewidth, _ = treewidth_min_fill_in(G)
111
+ assert treewidth == 2
112
+
113
+ def test_heuristic_abort(self):
114
+ """Test heuristic abort condition for fully connected graph"""
115
+ graph = {}
116
+ for u in self.complete:
117
+ graph[u] = set()
118
+ for v in self.complete[u]:
119
+ if u != v: # ignore self-loop
120
+ graph[u].add(v)
121
+
122
+ deg_heuristic = MinDegreeHeuristic(graph)
123
+ node = deg_heuristic.best_node(graph)
124
+ if node is None:
125
+ pass
126
+ else:
127
+ assert False
128
+
129
+ def test_empty_graph(self):
130
+ """Test empty graph"""
131
+ G = nx.Graph()
132
+ _, _ = treewidth_min_degree(G)
133
+
134
+ def test_two_component_graph(self):
135
+ G = nx.Graph()
136
+ G.add_node(1)
137
+ G.add_node(2)
138
+ treewidth, _ = treewidth_min_degree(G)
139
+ assert treewidth == 0
140
+
141
+ def test_not_sortable_nodes(self):
142
+ G = nx.Graph([(0, "a")])
143
+ treewidth_min_degree(G)
144
+
145
+ def test_heuristic_first_steps(self):
146
+ """Test first steps of min_degree heuristic"""
147
+ graph = {
148
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
149
+ }
150
+ deg_heuristic = MinDegreeHeuristic(graph)
151
+ elim_node = deg_heuristic.best_node(graph)
152
+ print(f"Graph {graph}:")
153
+ steps = []
154
+
155
+ while elim_node is not None:
156
+ print(f"Removing {elim_node}:")
157
+ steps.append(elim_node)
158
+ nbrs = graph[elim_node]
159
+
160
+ for u, v in itertools.permutations(nbrs, 2):
161
+ if v not in graph[u]:
162
+ graph[u].add(v)
163
+
164
+ for u in graph:
165
+ if elim_node in graph[u]:
166
+ graph[u].remove(elim_node)
167
+
168
+ del graph[elim_node]
169
+ print(f"Graph {graph}:")
170
+ elim_node = deg_heuristic.best_node(graph)
171
+
172
+ # check only the first 5 elements for equality
173
+ assert steps[:5] == [0, 1, 2, 3, 4]
174
+
175
+
176
+ class TestTreewidthMinFillIn:
177
+ """Unit tests for the treewidth_min_fill_in function."""
178
+
179
+ @classmethod
180
+ def setup_class(cls):
181
+ """Setup for different kinds of trees"""
182
+ cls.complete = nx.Graph()
183
+ cls.complete.add_edge(1, 2)
184
+ cls.complete.add_edge(2, 3)
185
+ cls.complete.add_edge(1, 3)
186
+
187
+ cls.small_tree = nx.Graph()
188
+ cls.small_tree.add_edge(1, 2)
189
+ cls.small_tree.add_edge(2, 3)
190
+ cls.small_tree.add_edge(3, 4)
191
+ cls.small_tree.add_edge(1, 4)
192
+ cls.small_tree.add_edge(2, 4)
193
+ cls.small_tree.add_edge(4, 5)
194
+ cls.small_tree.add_edge(5, 6)
195
+ cls.small_tree.add_edge(5, 7)
196
+ cls.small_tree.add_edge(6, 7)
197
+
198
+ cls.deterministic_graph = nx.Graph()
199
+ cls.deterministic_graph.add_edge(1, 2)
200
+ cls.deterministic_graph.add_edge(1, 3)
201
+ cls.deterministic_graph.add_edge(3, 4)
202
+ cls.deterministic_graph.add_edge(2, 4)
203
+ cls.deterministic_graph.add_edge(3, 5)
204
+ cls.deterministic_graph.add_edge(4, 5)
205
+ cls.deterministic_graph.add_edge(3, 6)
206
+ cls.deterministic_graph.add_edge(5, 6)
207
+
208
+ def test_petersen_graph(self):
209
+ """Test Petersen graph tree decomposition result"""
210
+ G = nx.petersen_graph()
211
+ _, decomp = treewidth_min_fill_in(G)
212
+ is_tree_decomp(G, decomp)
213
+
214
+ def test_small_tree_treewidth(self):
215
+ """Test if the computed treewidth of the known self.small_tree is 2"""
216
+ G = self.small_tree
217
+ # the order of removal should be [1,2,4]3[5,6,7]
218
+ # (with [] denoting any order of the containing nodes)
219
+ # resulting in treewidth 2 for the heuristic
220
+ treewidth, _ = treewidth_min_fill_in(G)
221
+ assert treewidth == 2
222
+
223
+ def test_heuristic_abort(self):
224
+ """Test if min_fill_in returns None for fully connected graph"""
225
+ graph = {}
226
+ for u in self.complete:
227
+ graph[u] = set()
228
+ for v in self.complete[u]:
229
+ if u != v: # ignore self-loop
230
+ graph[u].add(v)
231
+ next_node = min_fill_in_heuristic(graph)
232
+ if next_node is None:
233
+ pass
234
+ else:
235
+ assert False
236
+
237
+ def test_empty_graph(self):
238
+ """Test empty graph"""
239
+ G = nx.Graph()
240
+ _, _ = treewidth_min_fill_in(G)
241
+
242
+ def test_two_component_graph(self):
243
+ G = nx.Graph()
244
+ G.add_node(1)
245
+ G.add_node(2)
246
+ treewidth, _ = treewidth_min_fill_in(G)
247
+ assert treewidth == 0
248
+
249
+ def test_not_sortable_nodes(self):
250
+ G = nx.Graph([(0, "a")])
251
+ treewidth_min_fill_in(G)
252
+
253
+ def test_heuristic_first_steps(self):
254
+ """Test first steps of min_fill_in heuristic"""
255
+ graph = {
256
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
257
+ }
258
+ print(f"Graph {graph}:")
259
+ elim_node = min_fill_in_heuristic(graph)
260
+ steps = []
261
+
262
+ while elim_node is not None:
263
+ print(f"Removing {elim_node}:")
264
+ steps.append(elim_node)
265
+ nbrs = graph[elim_node]
266
+
267
+ for u, v in itertools.permutations(nbrs, 2):
268
+ if v not in graph[u]:
269
+ graph[u].add(v)
270
+
271
+ for u in graph:
272
+ if elim_node in graph[u]:
273
+ graph[u].remove(elim_node)
274
+
275
+ del graph[elim_node]
276
+ print(f"Graph {graph}:")
277
+ elim_node = min_fill_in_heuristic(graph)
278
+
279
+ # check only the first 2 elements for equality
280
+ assert steps[:2] == [6, 5]
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import min_weighted_vertex_cover
3
+
4
+
5
+ def is_cover(G, node_cover):
6
+ return all({u, v} & node_cover for u, v in G.edges())
7
+
8
+
9
+ class TestMWVC:
10
+ """Unit tests for the approximate minimum weighted vertex cover
11
+ function,
12
+ :func:`~networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover`.
13
+
14
+ """
15
+
16
+ def test_unweighted_directed(self):
17
+ # Create a star graph in which half the nodes are directed in
18
+ # and half are directed out.
19
+ G = nx.DiGraph()
20
+ G.add_edges_from((0, v) for v in range(1, 26))
21
+ G.add_edges_from((v, 0) for v in range(26, 51))
22
+ cover = min_weighted_vertex_cover(G)
23
+ assert 1 == len(cover)
24
+ assert is_cover(G, cover)
25
+
26
+ def test_unweighted_undirected(self):
27
+ # create a simple star graph
28
+ size = 50
29
+ sg = nx.star_graph(size)
30
+ cover = min_weighted_vertex_cover(sg)
31
+ assert 1 == len(cover)
32
+ assert is_cover(sg, cover)
33
+
34
+ def test_weighted(self):
35
+ wg = nx.Graph()
36
+ wg.add_node(0, weight=10)
37
+ wg.add_node(1, weight=1)
38
+ wg.add_node(2, weight=1)
39
+ wg.add_node(3, weight=1)
40
+ wg.add_node(4, weight=1)
41
+
42
+ wg.add_edge(0, 1)
43
+ wg.add_edge(0, 2)
44
+ wg.add_edge(0, 3)
45
+ wg.add_edge(0, 4)
46
+
47
+ wg.add_edge(1, 2)
48
+ wg.add_edge(2, 3)
49
+ wg.add_edge(3, 4)
50
+ wg.add_edge(4, 1)
51
+
52
+ cover = min_weighted_vertex_cover(wg, weight="weight")
53
+ csum = sum(wg.nodes[node]["weight"] for node in cover)
54
+ assert 4 == csum
55
+ assert is_cover(wg, cover)
56
+
57
+ def test_unweighted_self_loop(self):
58
+ slg = nx.Graph()
59
+ slg.add_node(0)
60
+ slg.add_node(1)
61
+ slg.add_node(2)
62
+
63
+ slg.add_edge(0, 1)
64
+ slg.add_edge(2, 2)
65
+
66
+ cover = min_weighted_vertex_cover(slg)
67
+ assert 2 == len(cover)
68
+ assert is_cover(slg, cover)
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/traveling_salesman.py ADDED
@@ -0,0 +1,1501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =================================
3
+ Travelling Salesman Problem (TSP)
4
+ =================================
5
+
6
+ Implementation of approximate algorithms
7
+ for solving and approximating the TSP problem.
8
+
9
+ Categories of algorithms which are implemented:
10
+
11
+ - Christofides (provides a 3/2-approximation of TSP)
12
+ - Greedy
13
+ - Simulated Annealing (SA)
14
+ - Threshold Accepting (TA)
15
+ - Asadpour Asymmetric Traveling Salesman Algorithm
16
+
17
+ The Travelling Salesman Problem tries to find, given the weight
18
+ (distance) between all points where a salesman has to visit, the
19
+ route so that:
20
+
21
+ - The total distance (cost) which the salesman travels is minimized.
22
+ - The salesman returns to the starting point.
23
+ - Note that for a complete graph, the salesman visits each point once.
24
+
25
+ The function `travelling_salesman_problem` allows for incomplete
26
+ graphs by finding all-pairs shortest paths, effectively converting
27
+ the problem to a complete graph problem. It calls one of the
28
+ approximate methods on that problem and then converts the result
29
+ back to the original graph using the previously found shortest paths.
30
+
31
+ TSP is an NP-hard problem in combinatorial optimization,
32
+ important in operations research and theoretical computer science.
33
+
34
+ http://en.wikipedia.org/wiki/Travelling_salesman_problem
35
+ """
36
+
37
+ import math
38
+
39
+ import networkx as nx
40
+ from networkx.algorithms.tree.mst import random_spanning_tree
41
+ from networkx.utils import not_implemented_for, pairwise, py_random_state
42
+
43
+ __all__ = [
44
+ "traveling_salesman_problem",
45
+ "christofides",
46
+ "asadpour_atsp",
47
+ "greedy_tsp",
48
+ "simulated_annealing_tsp",
49
+ "threshold_accepting_tsp",
50
+ ]
51
+
52
+
53
+ def swap_two_nodes(soln, seed):
54
+ """Swap two nodes in `soln` to give a neighbor solution.
55
+
56
+ Parameters
57
+ ----------
58
+ soln : list of nodes
59
+ Current cycle of nodes
60
+
61
+ seed : integer, random_state, or None (default)
62
+ Indicator of random number generation state.
63
+ See :ref:`Randomness<randomness>`.
64
+
65
+ Returns
66
+ -------
67
+ list
68
+ The solution after move is applied. (A neighbor solution.)
69
+
70
+ Notes
71
+ -----
72
+ This function assumes that the incoming list `soln` is a cycle
73
+ (that the first and last element are the same) and also that
74
+ we don't want any move to change the first node in the list
75
+ (and thus not the last node either).
76
+
77
+ The input list is changed as well as returned. Make a copy if needed.
78
+
79
+ See Also
80
+ --------
81
+ move_one_node
82
+ """
83
+ a, b = seed.sample(range(1, len(soln) - 1), k=2)
84
+ soln[a], soln[b] = soln[b], soln[a]
85
+ return soln
86
+
87
+
88
+ def move_one_node(soln, seed):
89
+ """Move one node to another position to give a neighbor solution.
90
+
91
+ The node to move and the position to move to are chosen randomly.
92
+ The first and last nodes are left untouched as soln must be a cycle
93
+ starting at that node.
94
+
95
+ Parameters
96
+ ----------
97
+ soln : list of nodes
98
+ Current cycle of nodes
99
+
100
+ seed : integer, random_state, or None (default)
101
+ Indicator of random number generation state.
102
+ See :ref:`Randomness<randomness>`.
103
+
104
+ Returns
105
+ -------
106
+ list
107
+ The solution after move is applied. (A neighbor solution.)
108
+
109
+ Notes
110
+ -----
111
+ This function assumes that the incoming list `soln` is a cycle
112
+ (that the first and last element are the same) and also that
113
+ we don't want any move to change the first node in the list
114
+ (and thus not the last node either).
115
+
116
+ The input list is changed as well as returned. Make a copy if needed.
117
+
118
+ See Also
119
+ --------
120
+ swap_two_nodes
121
+ """
122
+ a, b = seed.sample(range(1, len(soln) - 1), k=2)
123
+ soln.insert(b, soln.pop(a))
124
+ return soln
125
+
126
+
127
+ @not_implemented_for("directed")
128
+ @nx._dispatchable(edge_attrs="weight")
129
+ def christofides(G, weight="weight", tree=None):
130
+ """Approximate a solution of the traveling salesman problem
131
+
132
+ Compute a 3/2-approximation of the traveling salesman problem
133
+ in a complete undirected graph using Christofides [1]_ algorithm.
134
+
135
+ Parameters
136
+ ----------
137
+ G : Graph
138
+ `G` should be a complete weighted undirected graph.
139
+ The distance between all pairs of nodes should be included.
140
+
141
+ weight : string, optional (default="weight")
142
+ Edge data key corresponding to the edge weight.
143
+ If any edge does not have this attribute the weight is set to 1.
144
+
145
+ tree : NetworkX graph or None (default: None)
146
+ A minimum spanning tree of G. Or, if None, the minimum spanning
147
+ tree is computed using :func:`networkx.minimum_spanning_tree`
148
+
149
+ Returns
150
+ -------
151
+ list
152
+ List of nodes in `G` along a cycle with a 3/2-approximation of
153
+ the minimal Hamiltonian cycle.
154
+
155
+ References
156
+ ----------
157
+ .. [1] Christofides, Nicos. "Worst-case analysis of a new heuristic for
158
+ the travelling salesman problem." No. RR-388. Carnegie-Mellon Univ
159
+ Pittsburgh Pa Management Sciences Research Group, 1976.
160
+ """
161
+ # Remove selfloops if necessary
162
+ loop_nodes = nx.nodes_with_selfloops(G)
163
+ try:
164
+ node = next(loop_nodes)
165
+ except StopIteration:
166
+ pass
167
+ else:
168
+ G = G.copy()
169
+ G.remove_edge(node, node)
170
+ G.remove_edges_from((n, n) for n in loop_nodes)
171
+ # Check that G is a complete graph
172
+ N = len(G) - 1
173
+ # This check ignores selfloops which is what we want here.
174
+ if any(len(nbrdict) != N for n, nbrdict in G.adj.items()):
175
+ raise nx.NetworkXError("G must be a complete graph.")
176
+
177
+ if tree is None:
178
+ tree = nx.minimum_spanning_tree(G, weight=weight)
179
+ L = G.copy()
180
+ L.remove_nodes_from([v for v, degree in tree.degree if not (degree % 2)])
181
+ MG = nx.MultiGraph()
182
+ MG.add_edges_from(tree.edges)
183
+ edges = nx.min_weight_matching(L, weight=weight)
184
+ MG.add_edges_from(edges)
185
+ return _shortcutting(nx.eulerian_circuit(MG))
186
+
187
+
188
+ def _shortcutting(circuit):
189
+ """Remove duplicate nodes in the path"""
190
+ nodes = []
191
+ for u, v in circuit:
192
+ if v in nodes:
193
+ continue
194
+ if not nodes:
195
+ nodes.append(u)
196
+ nodes.append(v)
197
+ nodes.append(nodes[0])
198
+ return nodes
199
+
200
+
201
+ @nx._dispatchable(edge_attrs="weight")
202
+ def traveling_salesman_problem(
203
+ G, weight="weight", nodes=None, cycle=True, method=None, **kwargs
204
+ ):
205
+ """Find the shortest path in `G` connecting specified nodes
206
+
207
+ This function allows approximate solution to the traveling salesman
208
+ problem on networks that are not complete graphs and/or where the
209
+ salesman does not need to visit all nodes.
210
+
211
+ This function proceeds in two steps. First, it creates a complete
212
+ graph using the all-pairs shortest_paths between nodes in `nodes`.
213
+ Edge weights in the new graph are the lengths of the paths
214
+ between each pair of nodes in the original graph.
215
+ Second, an algorithm (default: `christofides` for undirected and
216
+ `asadpour_atsp` for directed) is used to approximate the minimal Hamiltonian
217
+ cycle on this new graph. The available algorithms are:
218
+
219
+ - christofides
220
+ - greedy_tsp
221
+ - simulated_annealing_tsp
222
+ - threshold_accepting_tsp
223
+ - asadpour_atsp
224
+
225
+ Once the Hamiltonian Cycle is found, this function post-processes to
226
+ accommodate the structure of the original graph. If `cycle` is ``False``,
227
+ the biggest weight edge is removed to make a Hamiltonian path.
228
+ Then each edge on the new complete graph used for that analysis is
229
+ replaced by the shortest_path between those nodes on the original graph.
230
+ If the input graph `G` includes edges with weights that do not adhere to
231
+ the triangle inequality, such as when `G` is not a complete graph (i.e
232
+ length of non-existent edges is infinity), then the returned path may
233
+ contain some repeating nodes (other than the starting node).
234
+
235
+ Parameters
236
+ ----------
237
+ G : NetworkX graph
238
+ A possibly weighted graph
239
+
240
+ nodes : collection of nodes (default=G.nodes)
241
+ collection (list, set, etc.) of nodes to visit
242
+
243
+ weight : string, optional (default="weight")
244
+ Edge data key corresponding to the edge weight.
245
+ If any edge does not have this attribute the weight is set to 1.
246
+
247
+ cycle : bool (default: True)
248
+ Indicates whether a cycle should be returned, or a path.
249
+ Note: the cycle is the approximate minimal cycle.
250
+ The path simply removes the biggest edge in that cycle.
251
+
252
+ method : function (default: None)
253
+ A function that returns a cycle on all nodes and approximates
254
+ the solution to the traveling salesman problem on a complete
255
+ graph. The returned cycle is then used to find a corresponding
256
+ solution on `G`. `method` should be callable; take inputs
257
+ `G`, and `weight`; and return a list of nodes along the cycle.
258
+
259
+ Provided options include :func:`christofides`, :func:`greedy_tsp`,
260
+ :func:`simulated_annealing_tsp` and :func:`threshold_accepting_tsp`.
261
+
262
+ If `method is None`: use :func:`christofides` for undirected `G` and
263
+ :func:`asadpour_atsp` for directed `G`.
264
+
265
+ **kwargs : dict
266
+ Other keyword arguments to be passed to the `method` function passed in.
267
+
268
+ Returns
269
+ -------
270
+ list
271
+ List of nodes in `G` along a path with an approximation of the minimal
272
+ path through `nodes`.
273
+
274
+ Raises
275
+ ------
276
+ NetworkXError
277
+ If `G` is a directed graph it has to be strongly connected or the
278
+ complete version cannot be generated.
279
+
280
+ Examples
281
+ --------
282
+ >>> tsp = nx.approximation.traveling_salesman_problem
283
+ >>> G = nx.cycle_graph(9)
284
+ >>> G[4][5]["weight"] = 5 # all other weights are 1
285
+ >>> tsp(G, nodes=[3, 6])
286
+ [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3]
287
+ >>> path = tsp(G, cycle=False)
288
+ >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
289
+ True
290
+
291
+ While no longer required, you can still build (curry) your own function
292
+ to provide parameter values to the methods.
293
+
294
+ >>> SA_tsp = nx.approximation.simulated_annealing_tsp
295
+ >>> method = lambda G, weight: SA_tsp(G, "greedy", weight=weight, temp=500)
296
+ >>> path = tsp(G, cycle=False, method=method)
297
+ >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
298
+ True
299
+
300
+ Otherwise, pass other keyword arguments directly into the tsp function.
301
+
302
+ >>> path = tsp(
303
+ ... G,
304
+ ... cycle=False,
305
+ ... method=nx.approximation.simulated_annealing_tsp,
306
+ ... init_cycle="greedy",
307
+ ... temp=500,
308
+ ... )
309
+ >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
310
+ True
311
+ """
312
+ if method is None:
313
+ if G.is_directed():
314
+ method = asadpour_atsp
315
+ else:
316
+ method = christofides
317
+ if nodes is None:
318
+ nodes = list(G.nodes)
319
+
320
+ dist = {}
321
+ path = {}
322
+ for n, (d, p) in nx.all_pairs_dijkstra(G, weight=weight):
323
+ dist[n] = d
324
+ path[n] = p
325
+
326
+ if G.is_directed():
327
+ # If the graph is not strongly connected, raise an exception
328
+ if not nx.is_strongly_connected(G):
329
+ raise nx.NetworkXError("G is not strongly connected")
330
+ GG = nx.DiGraph()
331
+ else:
332
+ GG = nx.Graph()
333
+ for u in nodes:
334
+ for v in nodes:
335
+ if u == v:
336
+ continue
337
+ GG.add_edge(u, v, weight=dist[u][v])
338
+
339
+ best_GG = method(GG, weight=weight, **kwargs)
340
+
341
+ if not cycle:
342
+ # find and remove the biggest edge
343
+ (u, v) = max(pairwise(best_GG), key=lambda x: dist[x[0]][x[1]])
344
+ pos = best_GG.index(u) + 1
345
+ while best_GG[pos] != v:
346
+ pos = best_GG[pos:].index(u) + 1
347
+ best_GG = best_GG[pos:-1] + best_GG[:pos]
348
+
349
+ best_path = []
350
+ for u, v in pairwise(best_GG):
351
+ best_path.extend(path[u][v][:-1])
352
+ best_path.append(v)
353
+ return best_path
354
+
355
+
356
+ @not_implemented_for("undirected")
357
+ @py_random_state(2)
358
+ @nx._dispatchable(edge_attrs="weight", mutates_input=True)
359
+ def asadpour_atsp(G, weight="weight", seed=None, source=None):
360
+ """
361
+ Returns an approximate solution to the traveling salesman problem.
362
+
363
+ This approximate solution is one of the best known approximations for the
364
+ asymmetric traveling salesman problem developed by Asadpour et al,
365
+ [1]_. The algorithm first solves the Held-Karp relaxation to find a lower
366
+ bound for the weight of the cycle. Next, it constructs an exponential
367
+ distribution of undirected spanning trees where the probability of an
368
+ edge being in the tree corresponds to the weight of that edge using a
369
+ maximum entropy rounding scheme. Next we sample that distribution
370
+ $2 \\lceil \\ln n \\rceil$ times and save the minimum sampled tree once the
371
+ direction of the arcs is added back to the edges. Finally, we augment
372
+ then short circuit that graph to find the approximate tour for the
373
+ salesman.
374
+
375
+ Parameters
376
+ ----------
377
+ G : nx.DiGraph
378
+ The graph should be a complete weighted directed graph. The
379
+ distance between all paris of nodes should be included and the triangle
380
+ inequality should hold. That is, the direct edge between any two nodes
381
+ should be the path of least cost.
382
+
383
+ weight : string, optional (default="weight")
384
+ Edge data key corresponding to the edge weight.
385
+ If any edge does not have this attribute the weight is set to 1.
386
+
387
+ seed : integer, random_state, or None (default)
388
+ Indicator of random number generation state.
389
+ See :ref:`Randomness<randomness>`.
390
+
391
+ source : node label (default=`None`)
392
+ If given, return the cycle starting and ending at the given node.
393
+
394
+ Returns
395
+ -------
396
+ cycle : list of nodes
397
+ Returns the cycle (list of nodes) that a salesman can follow to minimize
398
+ the total weight of the trip.
399
+
400
+ Raises
401
+ ------
402
+ NetworkXError
403
+ If `G` is not complete or has less than two nodes, the algorithm raises
404
+ an exception.
405
+
406
+ NetworkXError
407
+ If `source` is not `None` and is not a node in `G`, the algorithm raises
408
+ an exception.
409
+
410
+ NetworkXNotImplemented
411
+ If `G` is an undirected graph.
412
+
413
+ References
414
+ ----------
415
+ .. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
416
+ An o(log n/log log n)-approximation algorithm for the asymmetric
417
+ traveling salesman problem, Operations research, 65 (2017),
418
+ pp. 1043–1061
419
+
420
+ Examples
421
+ --------
422
+ >>> import networkx as nx
423
+ >>> import networkx.algorithms.approximation as approx
424
+ >>> G = nx.complete_graph(3, create_using=nx.DiGraph)
425
+ >>> nx.set_edge_attributes(
426
+ ... G,
427
+ ... {(0, 1): 2, (1, 2): 2, (2, 0): 2, (0, 2): 1, (2, 1): 1, (1, 0): 1},
428
+ ... "weight",
429
+ ... )
430
+ >>> tour = approx.asadpour_atsp(G, source=0)
431
+ >>> tour
432
+ [0, 2, 1, 0]
433
+ """
434
+ from math import ceil, exp
435
+ from math import log as ln
436
+
437
+ # Check that G is a complete graph
438
+ N = len(G) - 1
439
+ if N < 2:
440
+ raise nx.NetworkXError("G must have at least two nodes")
441
+ # This check ignores selfloops which is what we want here.
442
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
443
+ raise nx.NetworkXError("G is not a complete DiGraph")
444
+ # Check that the source vertex, if given, is in the graph
445
+ if source is not None and source not in G.nodes:
446
+ raise nx.NetworkXError("Given source node not in G.")
447
+
448
+ opt_hk, z_star = held_karp_ascent(G, weight)
449
+
450
+ # Test to see if the ascent method found an integer solution or a fractional
451
+ # solution. If it is integral then z_star is a nx.Graph, otherwise it is
452
+ # a dict
453
+ if not isinstance(z_star, dict):
454
+ # Here we are using the shortcutting method to go from the list of edges
455
+ # returned from eulerian_circuit to a list of nodes
456
+ return _shortcutting(nx.eulerian_circuit(z_star, source=source))
457
+
458
+ # Create the undirected support of z_star
459
+ z_support = nx.MultiGraph()
460
+ for u, v in z_star:
461
+ if (u, v) not in z_support.edges:
462
+ edge_weight = min(G[u][v][weight], G[v][u][weight])
463
+ z_support.add_edge(u, v, **{weight: edge_weight})
464
+
465
+ # Create the exponential distribution of spanning trees
466
+ gamma = spanning_tree_distribution(z_support, z_star)
467
+
468
+ # Write the lambda values to the edges of z_support
469
+ z_support = nx.Graph(z_support)
470
+ lambda_dict = {(u, v): exp(gamma[(u, v)]) for u, v in z_support.edges()}
471
+ nx.set_edge_attributes(z_support, lambda_dict, "weight")
472
+ del gamma, lambda_dict
473
+
474
+ # Sample 2 * ceil( ln(n) ) spanning trees and record the minimum one
475
+ minimum_sampled_tree = None
476
+ minimum_sampled_tree_weight = math.inf
477
+ for _ in range(2 * ceil(ln(G.number_of_nodes()))):
478
+ sampled_tree = random_spanning_tree(z_support, "weight", seed=seed)
479
+ sampled_tree_weight = sampled_tree.size(weight)
480
+ if sampled_tree_weight < minimum_sampled_tree_weight:
481
+ minimum_sampled_tree = sampled_tree.copy()
482
+ minimum_sampled_tree_weight = sampled_tree_weight
483
+
484
+ # Orient the edges in that tree to keep the cost of the tree the same.
485
+ t_star = nx.MultiDiGraph()
486
+ for u, v, d in minimum_sampled_tree.edges(data=weight):
487
+ if d == G[u][v][weight]:
488
+ t_star.add_edge(u, v, **{weight: d})
489
+ else:
490
+ t_star.add_edge(v, u, **{weight: d})
491
+
492
+ # Find the node demands needed to neutralize the flow of t_star in G
493
+ node_demands = {n: t_star.out_degree(n) - t_star.in_degree(n) for n in t_star}
494
+ nx.set_node_attributes(G, node_demands, "demand")
495
+
496
+ # Find the min_cost_flow
497
+ flow_dict = nx.min_cost_flow(G, "demand")
498
+
499
+ # Build the flow into t_star
500
+ for source, values in flow_dict.items():
501
+ for target in values:
502
+ if (source, target) not in t_star.edges and values[target] > 0:
503
+ # IF values[target] > 0 we have to add that many edges
504
+ for _ in range(values[target]):
505
+ t_star.add_edge(source, target)
506
+
507
+ # Return the shortcut eulerian circuit
508
+ circuit = nx.eulerian_circuit(t_star, source=source)
509
+ return _shortcutting(circuit)
510
+
511
+
512
+ @nx._dispatchable(edge_attrs="weight", mutates_input=True, returns_graph=True)
513
+ def held_karp_ascent(G, weight="weight"):
514
+ """
515
+ Minimizes the Held-Karp relaxation of the TSP for `G`
516
+
517
+ Solves the Held-Karp relaxation of the input complete digraph and scales
518
+ the output solution for use in the Asadpour [1]_ ASTP algorithm.
519
+
520
+ The Held-Karp relaxation defines the lower bound for solutions to the
521
+ ATSP, although it does return a fractional solution. This is used in the
522
+ Asadpour algorithm as an initial solution which is later rounded to a
523
+ integral tree within the spanning tree polytopes. This function solves
524
+ the relaxation with the branch and bound method in [2]_.
525
+
526
+ Parameters
527
+ ----------
528
+ G : nx.DiGraph
529
+ The graph should be a complete weighted directed graph.
530
+ The distance between all paris of nodes should be included.
531
+
532
+ weight : string, optional (default="weight")
533
+ Edge data key corresponding to the edge weight.
534
+ If any edge does not have this attribute the weight is set to 1.
535
+
536
+ Returns
537
+ -------
538
+ OPT : float
539
+ The cost for the optimal solution to the Held-Karp relaxation
540
+ z : dict or nx.Graph
541
+ A symmetrized and scaled version of the optimal solution to the
542
+ Held-Karp relaxation for use in the Asadpour algorithm.
543
+
544
+ If an integral solution is found, then that is an optimal solution for
545
+ the ATSP problem and that is returned instead.
546
+
547
+ References
548
+ ----------
549
+ .. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
550
+ An o(log n/log log n)-approximation algorithm for the asymmetric
551
+ traveling salesman problem, Operations research, 65 (2017),
552
+ pp. 1043–1061
553
+
554
+ .. [2] M. Held, R. M. Karp, The traveling-salesman problem and minimum
555
+ spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
556
+ pp.1138-1162
557
+ """
558
+ import numpy as np
559
+ from scipy import optimize
560
+
561
+ def k_pi():
562
+ """
563
+ Find the set of minimum 1-Arborescences for G at point pi.
564
+
565
+ Returns
566
+ -------
567
+ Set
568
+ The set of minimum 1-Arborescences
569
+ """
570
+ # Create a copy of G without vertex 1.
571
+ G_1 = G.copy()
572
+ minimum_1_arborescences = set()
573
+ minimum_1_arborescence_weight = math.inf
574
+
575
+ # node is node '1' in the Held and Karp paper
576
+ n = next(G.__iter__())
577
+ G_1.remove_node(n)
578
+
579
+ # Iterate over the spanning arborescences of the graph until we know
580
+ # that we have found the minimum 1-arborescences. My proposed strategy
581
+ # is to find the most extensive root to connect to from 'node 1' and
582
+ # the least expensive one. We then iterate over arborescences until
583
+ # the cost of the basic arborescence is the cost of the minimum one
584
+ # plus the difference between the most and least expensive roots,
585
+ # that way the cost of connecting 'node 1' will by definition not by
586
+ # minimum
587
+ min_root = {"node": None, weight: math.inf}
588
+ max_root = {"node": None, weight: -math.inf}
589
+ for u, v, d in G.edges(n, data=True):
590
+ if d[weight] < min_root[weight]:
591
+ min_root = {"node": v, weight: d[weight]}
592
+ if d[weight] > max_root[weight]:
593
+ max_root = {"node": v, weight: d[weight]}
594
+
595
+ min_in_edge = min(G.in_edges(n, data=True), key=lambda x: x[2][weight])
596
+ min_root[weight] = min_root[weight] + min_in_edge[2][weight]
597
+ max_root[weight] = max_root[weight] + min_in_edge[2][weight]
598
+
599
+ min_arb_weight = math.inf
600
+ for arb in nx.ArborescenceIterator(G_1):
601
+ arb_weight = arb.size(weight)
602
+ if min_arb_weight == math.inf:
603
+ min_arb_weight = arb_weight
604
+ elif arb_weight > min_arb_weight + max_root[weight] - min_root[weight]:
605
+ break
606
+ # We have to pick the root node of the arborescence for the out
607
+ # edge of the first vertex as that is the only node without an
608
+ # edge directed into it.
609
+ for N, deg in arb.in_degree:
610
+ if deg == 0:
611
+ # root found
612
+ arb.add_edge(n, N, **{weight: G[n][N][weight]})
613
+ arb_weight += G[n][N][weight]
614
+ break
615
+
616
+ # We can pick the minimum weight in-edge for the vertex with
617
+ # a cycle. If there are multiple edges with the same, minimum
618
+ # weight, We need to add all of them.
619
+ #
620
+ # Delete the edge (N, v) so that we cannot pick it.
621
+ edge_data = G[N][n]
622
+ G.remove_edge(N, n)
623
+ min_weight = min(G.in_edges(n, data=weight), key=lambda x: x[2])[2]
624
+ min_edges = [
625
+ (u, v, d) for u, v, d in G.in_edges(n, data=weight) if d == min_weight
626
+ ]
627
+ for u, v, d in min_edges:
628
+ new_arb = arb.copy()
629
+ new_arb.add_edge(u, v, **{weight: d})
630
+ new_arb_weight = arb_weight + d
631
+ # Check to see the weight of the arborescence, if it is a
632
+ # new minimum, clear all of the old potential minimum
633
+ # 1-arborescences and add this is the only one. If its
634
+ # weight is above the known minimum, do not add it.
635
+ if new_arb_weight < minimum_1_arborescence_weight:
636
+ minimum_1_arborescences.clear()
637
+ minimum_1_arborescence_weight = new_arb_weight
638
+ # We have a 1-arborescence, add it to the set
639
+ if new_arb_weight == minimum_1_arborescence_weight:
640
+ minimum_1_arborescences.add(new_arb)
641
+ G.add_edge(N, n, **edge_data)
642
+
643
+ return minimum_1_arborescences
644
+
645
+ def direction_of_ascent():
646
+ """
647
+ Find the direction of ascent at point pi.
648
+
649
+ See [1]_ for more information.
650
+
651
+ Returns
652
+ -------
653
+ dict
654
+ A mapping from the nodes of the graph which represents the direction
655
+ of ascent.
656
+
657
+ References
658
+ ----------
659
+ .. [1] M. Held, R. M. Karp, The traveling-salesman problem and minimum
660
+ spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
661
+ pp.1138-1162
662
+ """
663
+ # 1. Set d equal to the zero n-vector.
664
+ d = {}
665
+ for n in G:
666
+ d[n] = 0
667
+ del n
668
+ # 2. Find a 1-Arborescence T^k such that k is in K(pi, d).
669
+ minimum_1_arborescences = k_pi()
670
+ while True:
671
+ # Reduce K(pi) to K(pi, d)
672
+ # Find the arborescence in K(pi) which increases the lest in
673
+ # direction d
674
+ min_k_d_weight = math.inf
675
+ min_k_d = None
676
+ for arborescence in minimum_1_arborescences:
677
+ weighted_cost = 0
678
+ for n, deg in arborescence.degree:
679
+ weighted_cost += d[n] * (deg - 2)
680
+ if weighted_cost < min_k_d_weight:
681
+ min_k_d_weight = weighted_cost
682
+ min_k_d = arborescence
683
+
684
+ # 3. If sum of d_i * v_{i, k} is greater than zero, terminate
685
+ if min_k_d_weight > 0:
686
+ return d, min_k_d
687
+ # 4. d_i = d_i + v_{i, k}
688
+ for n, deg in min_k_d.degree:
689
+ d[n] += deg - 2
690
+ # Check that we do not need to terminate because the direction
691
+ # of ascent does not exist. This is done with linear
692
+ # programming.
693
+ c = np.full(len(minimum_1_arborescences), -1, dtype=int)
694
+ a_eq = np.empty((len(G) + 1, len(minimum_1_arborescences)), dtype=int)
695
+ b_eq = np.zeros(len(G) + 1, dtype=int)
696
+ b_eq[len(G)] = 1
697
+ for arb_count, arborescence in enumerate(minimum_1_arborescences):
698
+ n_count = len(G) - 1
699
+ for n, deg in arborescence.degree:
700
+ a_eq[n_count][arb_count] = deg - 2
701
+ n_count -= 1
702
+ a_eq[len(G)][arb_count] = 1
703
+ program_result = optimize.linprog(
704
+ c, A_eq=a_eq, b_eq=b_eq, method="highs-ipm"
705
+ )
706
+ # If the constants exist, then the direction of ascent doesn't
707
+ if program_result.success:
708
+ # There is no direction of ascent
709
+ return None, minimum_1_arborescences
710
+
711
+ # 5. GO TO 2
712
+
713
+ def find_epsilon(k, d):
714
+ """
715
+ Given the direction of ascent at pi, find the maximum distance we can go
716
+ in that direction.
717
+
718
+ Parameters
719
+ ----------
720
+ k_xy : set
721
+ The set of 1-arborescences which have the minimum rate of increase
722
+ in the direction of ascent
723
+
724
+ d : dict
725
+ The direction of ascent
726
+
727
+ Returns
728
+ -------
729
+ float
730
+ The distance we can travel in direction `d`
731
+ """
732
+ min_epsilon = math.inf
733
+ for e_u, e_v, e_w in G.edges(data=weight):
734
+ if (e_u, e_v) in k.edges:
735
+ continue
736
+ # Now, I have found a condition which MUST be true for the edges to
737
+ # be a valid substitute. The edge in the graph which is the
738
+ # substitute is the one with the same terminated end. This can be
739
+ # checked rather simply.
740
+ #
741
+ # Find the edge within k which is the substitute. Because k is a
742
+ # 1-arborescence, we know that they is only one such edges
743
+ # leading into every vertex.
744
+ if len(k.in_edges(e_v, data=weight)) > 1:
745
+ raise Exception
746
+ sub_u, sub_v, sub_w = next(k.in_edges(e_v, data=weight).__iter__())
747
+ k.add_edge(e_u, e_v, **{weight: e_w})
748
+ k.remove_edge(sub_u, sub_v)
749
+ if (
750
+ max(d for n, d in k.in_degree()) <= 1
751
+ and len(G) == k.number_of_edges()
752
+ and nx.is_weakly_connected(k)
753
+ ):
754
+ # Ascent method calculation
755
+ if d[sub_u] == d[e_u] or sub_w == e_w:
756
+ # Revert to the original graph
757
+ k.remove_edge(e_u, e_v)
758
+ k.add_edge(sub_u, sub_v, **{weight: sub_w})
759
+ continue
760
+ epsilon = (sub_w - e_w) / (d[e_u] - d[sub_u])
761
+ if 0 < epsilon < min_epsilon:
762
+ min_epsilon = epsilon
763
+ # Revert to the original graph
764
+ k.remove_edge(e_u, e_v)
765
+ k.add_edge(sub_u, sub_v, **{weight: sub_w})
766
+
767
+ return min_epsilon
768
+
769
+ # I have to know that the elements in pi correspond to the correct elements
770
+ # in the direction of ascent, even if the node labels are not integers.
771
+ # Thus, I will use dictionaries to made that mapping.
772
+ pi_dict = {}
773
+ for n in G:
774
+ pi_dict[n] = 0
775
+ del n
776
+ original_edge_weights = {}
777
+ for u, v, d in G.edges(data=True):
778
+ original_edge_weights[(u, v)] = d[weight]
779
+ dir_ascent, k_d = direction_of_ascent()
780
+ while dir_ascent is not None:
781
+ max_distance = find_epsilon(k_d, dir_ascent)
782
+ for n, v in dir_ascent.items():
783
+ pi_dict[n] += max_distance * v
784
+ for u, v, d in G.edges(data=True):
785
+ d[weight] = original_edge_weights[(u, v)] + pi_dict[u]
786
+ dir_ascent, k_d = direction_of_ascent()
787
+ nx._clear_cache(G)
788
+ # k_d is no longer an individual 1-arborescence but rather a set of
789
+ # minimal 1-arborescences at the maximum point of the polytope and should
790
+ # be reflected as such
791
+ k_max = k_d
792
+
793
+ # Search for a cycle within k_max. If a cycle exists, return it as the
794
+ # solution
795
+ for k in k_max:
796
+ if len([n for n in k if k.degree(n) == 2]) == G.order():
797
+ # Tour found
798
+ # TODO: this branch does not restore original_edge_weights of G!
799
+ return k.size(weight), k
800
+
801
+ # Write the original edge weights back to G and every member of k_max at
802
+ # the maximum point. Also average the number of times that edge appears in
803
+ # the set of minimal 1-arborescences.
804
+ x_star = {}
805
+ size_k_max = len(k_max)
806
+ for u, v, d in G.edges(data=True):
807
+ edge_count = 0
808
+ d[weight] = original_edge_weights[(u, v)]
809
+ for k in k_max:
810
+ if (u, v) in k.edges():
811
+ edge_count += 1
812
+ k[u][v][weight] = original_edge_weights[(u, v)]
813
+ x_star[(u, v)] = edge_count / size_k_max
814
+ # Now symmetrize the edges in x_star and scale them according to (5) in
815
+ # reference [1]
816
+ z_star = {}
817
+ scale_factor = (G.order() - 1) / G.order()
818
+ for u, v in x_star:
819
+ frequency = x_star[(u, v)] + x_star[(v, u)]
820
+ if frequency > 0:
821
+ z_star[(u, v)] = scale_factor * frequency
822
+ del x_star
823
+ # Return the optimal weight and the z dict
824
+ return next(k_max.__iter__()).size(weight), z_star
825
+
826
+
827
+ @nx._dispatchable
828
+ def spanning_tree_distribution(G, z):
829
+ """
830
+ Find the asadpour exponential distribution of spanning trees.
831
+
832
+ Solves the Maximum Entropy Convex Program in the Asadpour algorithm [1]_
833
+ using the approach in section 7 to build an exponential distribution of
834
+ undirected spanning trees.
835
+
836
+ This algorithm ensures that the probability of any edge in a spanning
837
+ tree is proportional to the sum of the probabilities of the tress
838
+ containing that edge over the sum of the probabilities of all spanning
839
+ trees of the graph.
840
+
841
+ Parameters
842
+ ----------
843
+ G : nx.MultiGraph
844
+ The undirected support graph for the Held Karp relaxation
845
+
846
+ z : dict
847
+ The output of `held_karp_ascent()`, a scaled version of the Held-Karp
848
+ solution.
849
+
850
+ Returns
851
+ -------
852
+ gamma : dict
853
+ The probability distribution which approximately preserves the marginal
854
+ probabilities of `z`.
855
+ """
856
+ from math import exp
857
+ from math import log as ln
858
+
859
+ def q(e):
860
+ """
861
+ The value of q(e) is described in the Asadpour paper is "the
862
+ probability that edge e will be included in a spanning tree T that is
863
+ chosen with probability proportional to exp(gamma(T))" which
864
+ basically means that it is the total probability of the edge appearing
865
+ across the whole distribution.
866
+
867
+ Parameters
868
+ ----------
869
+ e : tuple
870
+ The `(u, v)` tuple describing the edge we are interested in
871
+
872
+ Returns
873
+ -------
874
+ float
875
+ The probability that a spanning tree chosen according to the
876
+ current values of gamma will include edge `e`.
877
+ """
878
+ # Create the laplacian matrices
879
+ for u, v, d in G.edges(data=True):
880
+ d[lambda_key] = exp(gamma[(u, v)])
881
+ G_Kirchhoff = nx.total_spanning_tree_weight(G, lambda_key)
882
+ G_e = nx.contracted_edge(G, e, self_loops=False)
883
+ G_e_Kirchhoff = nx.total_spanning_tree_weight(G_e, lambda_key)
884
+
885
+ # Multiply by the weight of the contracted edge since it is not included
886
+ # in the total weight of the contracted graph.
887
+ return exp(gamma[(e[0], e[1])]) * G_e_Kirchhoff / G_Kirchhoff
888
+
889
+ # initialize gamma to the zero dict
890
+ gamma = {}
891
+ for u, v, _ in G.edges:
892
+ gamma[(u, v)] = 0
893
+
894
+ # set epsilon
895
+ EPSILON = 0.2
896
+
897
+ # pick an edge attribute name that is unlikely to be in the graph
898
+ lambda_key = "spanning_tree_distribution's secret attribute name for lambda"
899
+
900
+ while True:
901
+ # We need to know that know that no values of q_e are greater than
902
+ # (1 + epsilon) * z_e, however changing one gamma value can increase the
903
+ # value of a different q_e, so we have to complete the for loop without
904
+ # changing anything for the condition to be meet
905
+ in_range_count = 0
906
+ # Search for an edge with q_e > (1 + epsilon) * z_e
907
+ for u, v in gamma:
908
+ e = (u, v)
909
+ q_e = q(e)
910
+ z_e = z[e]
911
+ if q_e > (1 + EPSILON) * z_e:
912
+ delta = ln(
913
+ (q_e * (1 - (1 + EPSILON / 2) * z_e))
914
+ / ((1 - q_e) * (1 + EPSILON / 2) * z_e)
915
+ )
916
+ gamma[e] -= delta
917
+ # Check that delta had the desired effect
918
+ new_q_e = q(e)
919
+ desired_q_e = (1 + EPSILON / 2) * z_e
920
+ if round(new_q_e, 8) != round(desired_q_e, 8):
921
+ raise nx.NetworkXError(
922
+ f"Unable to modify probability for edge ({u}, {v})"
923
+ )
924
+ else:
925
+ in_range_count += 1
926
+ # Check if the for loop terminated without changing any gamma
927
+ if in_range_count == len(gamma):
928
+ break
929
+
930
+ # Remove the new edge attributes
931
+ for _, _, d in G.edges(data=True):
932
+ if lambda_key in d:
933
+ del d[lambda_key]
934
+
935
+ return gamma
936
+
937
+
938
+ @nx._dispatchable(edge_attrs="weight")
939
+ def greedy_tsp(G, weight="weight", source=None):
940
+ """Return a low cost cycle starting at `source` and its cost.
941
+
942
+ This approximates a solution to the traveling salesman problem.
943
+ It finds a cycle of all the nodes that a salesman can visit in order
944
+ to visit many nodes while minimizing total distance.
945
+ It uses a simple greedy algorithm.
946
+ In essence, this function returns a large cycle given a source point
947
+ for which the total cost of the cycle is minimized.
948
+
949
+ Parameters
950
+ ----------
951
+ G : Graph
952
+ The Graph should be a complete weighted undirected graph.
953
+ The distance between all pairs of nodes should be included.
954
+
955
+ weight : string, optional (default="weight")
956
+ Edge data key corresponding to the edge weight.
957
+ If any edge does not have this attribute the weight is set to 1.
958
+
959
+ source : node, optional (default: first node in list(G))
960
+ Starting node. If None, defaults to ``next(iter(G))``
961
+
962
+ Returns
963
+ -------
964
+ cycle : list of nodes
965
+ Returns the cycle (list of nodes) that a salesman
966
+ can follow to minimize total weight of the trip.
967
+
968
+ Raises
969
+ ------
970
+ NetworkXError
971
+ If `G` is not complete, the algorithm raises an exception.
972
+
973
+ Examples
974
+ --------
975
+ >>> from networkx.algorithms import approximation as approx
976
+ >>> G = nx.DiGraph()
977
+ >>> G.add_weighted_edges_from(
978
+ ... {
979
+ ... ("A", "B", 3),
980
+ ... ("A", "C", 17),
981
+ ... ("A", "D", 14),
982
+ ... ("B", "A", 3),
983
+ ... ("B", "C", 12),
984
+ ... ("B", "D", 16),
985
+ ... ("C", "A", 13),
986
+ ... ("C", "B", 12),
987
+ ... ("C", "D", 4),
988
+ ... ("D", "A", 14),
989
+ ... ("D", "B", 15),
990
+ ... ("D", "C", 2),
991
+ ... }
992
+ ... )
993
+ >>> cycle = approx.greedy_tsp(G, source="D")
994
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
995
+ >>> cycle
996
+ ['D', 'C', 'B', 'A', 'D']
997
+ >>> cost
998
+ 31
999
+
1000
+ Notes
1001
+ -----
1002
+ This implementation of a greedy algorithm is based on the following:
1003
+
1004
+ - The algorithm adds a node to the solution at every iteration.
1005
+ - The algorithm selects a node not already in the cycle whose connection
1006
+ to the previous node adds the least cost to the cycle.
1007
+
1008
+ A greedy algorithm does not always give the best solution.
1009
+ However, it can construct a first feasible solution which can
1010
+ be passed as a parameter to an iterative improvement algorithm such
1011
+ as Simulated Annealing, or Threshold Accepting.
1012
+
1013
+ Time complexity: It has a running time $O(|V|^2)$
1014
+ """
1015
+ # Check that G is a complete graph
1016
+ N = len(G) - 1
1017
+ # This check ignores selfloops which is what we want here.
1018
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
1019
+ raise nx.NetworkXError("G must be a complete graph.")
1020
+
1021
+ if source is None:
1022
+ source = nx.utils.arbitrary_element(G)
1023
+
1024
+ if G.number_of_nodes() == 2:
1025
+ neighbor = next(G.neighbors(source))
1026
+ return [source, neighbor, source]
1027
+
1028
+ nodeset = set(G)
1029
+ nodeset.remove(source)
1030
+ cycle = [source]
1031
+ next_node = source
1032
+ while nodeset:
1033
+ nbrdict = G[next_node]
1034
+ next_node = min(nodeset, key=lambda n: nbrdict[n].get(weight, 1))
1035
+ cycle.append(next_node)
1036
+ nodeset.remove(next_node)
1037
+ cycle.append(cycle[0])
1038
+ return cycle
1039
+
1040
+
1041
+ @py_random_state(9)
1042
+ @nx._dispatchable(edge_attrs="weight")
1043
+ def simulated_annealing_tsp(
1044
+ G,
1045
+ init_cycle,
1046
+ weight="weight",
1047
+ source=None,
1048
+ temp=100,
1049
+ move="1-1",
1050
+ max_iterations=10,
1051
+ N_inner=100,
1052
+ alpha=0.01,
1053
+ seed=None,
1054
+ ):
1055
+ """Returns an approximate solution to the traveling salesman problem.
1056
+
1057
+ This function uses simulated annealing to approximate the minimal cost
1058
+ cycle through the nodes. Starting from a suboptimal solution, simulated
1059
+ annealing perturbs that solution, occasionally accepting changes that make
1060
+ the solution worse to escape from a locally optimal solution. The chance
1061
+ of accepting such changes decreases over the iterations to encourage
1062
+ an optimal result. In summary, the function returns a cycle starting
1063
+ at `source` for which the total cost is minimized. It also returns the cost.
1064
+
1065
+ The chance of accepting a proposed change is related to a parameter called
1066
+ the temperature (annealing has a physical analogue of steel hardening
1067
+ as it cools). As the temperature is reduced, the chance of moves that
1068
+ increase cost goes down.
1069
+
1070
+ Parameters
1071
+ ----------
1072
+ G : Graph
1073
+ `G` should be a complete weighted graph.
1074
+ The distance between all pairs of nodes should be included.
1075
+
1076
+ init_cycle : list of all nodes or "greedy"
1077
+ The initial solution (a cycle through all nodes returning to the start).
1078
+ This argument has no default to make you think about it.
1079
+ If "greedy", use `greedy_tsp(G, weight)`.
1080
+ Other common starting cycles are `list(G) + [next(iter(G))]` or the final
1081
+ result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.
1082
+
1083
+ weight : string, optional (default="weight")
1084
+ Edge data key corresponding to the edge weight.
1085
+ If any edge does not have this attribute the weight is set to 1.
1086
+
1087
+ source : node, optional (default: first node in list(G))
1088
+ Starting node. If None, defaults to ``next(iter(G))``
1089
+
1090
+ temp : int, optional (default=100)
1091
+ The algorithm's temperature parameter. It represents the initial
1092
+ value of temperature
1093
+
1094
+ move : "1-1" or "1-0" or function, optional (default="1-1")
1095
+ Indicator of what move to use when finding new trial solutions.
1096
+ Strings indicate two special built-in moves:
1097
+
1098
+ - "1-1": 1-1 exchange which transposes the position
1099
+ of two elements of the current solution.
1100
+ The function called is :func:`swap_two_nodes`.
1101
+ For example if we apply 1-1 exchange in the solution
1102
+ ``A = [3, 2, 1, 4, 3]``
1103
+ we can get the following by the transposition of 1 and 4 elements:
1104
+ ``A' = [3, 2, 4, 1, 3]``
1105
+ - "1-0": 1-0 exchange which moves an node in the solution
1106
+ to a new position.
1107
+ The function called is :func:`move_one_node`.
1108
+ For example if we apply 1-0 exchange in the solution
1109
+ ``A = [3, 2, 1, 4, 3]``
1110
+ we can transfer the fourth element to the second position:
1111
+ ``A' = [3, 4, 2, 1, 3]``
1112
+
1113
+ You may provide your own functions to enact a move from
1114
+ one solution to a neighbor solution. The function must take
1115
+ the solution as input along with a `seed` input to control
1116
+ random number generation (see the `seed` input here).
1117
+ Your function should maintain the solution as a cycle with
1118
+ equal first and last node and all others appearing once.
1119
+ Your function should return the new solution.
1120
+
1121
+ max_iterations : int, optional (default=10)
1122
+ Declared done when this number of consecutive iterations of
1123
+ the outer loop occurs without any change in the best cost solution.
1124
+
1125
+ N_inner : int, optional (default=100)
1126
+ The number of iterations of the inner loop.
1127
+
1128
+ alpha : float between (0, 1), optional (default=0.01)
1129
+ Percentage of temperature decrease in each iteration
1130
+ of outer loop
1131
+
1132
+ seed : integer, random_state, or None (default)
1133
+ Indicator of random number generation state.
1134
+ See :ref:`Randomness<randomness>`.
1135
+
1136
+ Returns
1137
+ -------
1138
+ cycle : list of nodes
1139
+ Returns the cycle (list of nodes) that a salesman
1140
+ can follow to minimize total weight of the trip.
1141
+
1142
+ Raises
1143
+ ------
1144
+ NetworkXError
1145
+ If `G` is not complete the algorithm raises an exception.
1146
+
1147
+ Examples
1148
+ --------
1149
+ >>> from networkx.algorithms import approximation as approx
1150
+ >>> G = nx.DiGraph()
1151
+ >>> G.add_weighted_edges_from(
1152
+ ... {
1153
+ ... ("A", "B", 3),
1154
+ ... ("A", "C", 17),
1155
+ ... ("A", "D", 14),
1156
+ ... ("B", "A", 3),
1157
+ ... ("B", "C", 12),
1158
+ ... ("B", "D", 16),
1159
+ ... ("C", "A", 13),
1160
+ ... ("C", "B", 12),
1161
+ ... ("C", "D", 4),
1162
+ ... ("D", "A", 14),
1163
+ ... ("D", "B", 15),
1164
+ ... ("D", "C", 2),
1165
+ ... }
1166
+ ... )
1167
+ >>> cycle = approx.simulated_annealing_tsp(G, "greedy", source="D")
1168
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1169
+ >>> cycle
1170
+ ['D', 'C', 'B', 'A', 'D']
1171
+ >>> cost
1172
+ 31
1173
+ >>> incycle = ["D", "B", "A", "C", "D"]
1174
+ >>> cycle = approx.simulated_annealing_tsp(G, incycle, source="D")
1175
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1176
+ >>> cycle
1177
+ ['D', 'C', 'B', 'A', 'D']
1178
+ >>> cost
1179
+ 31
1180
+
1181
+ Notes
1182
+ -----
1183
+ Simulated Annealing is a metaheuristic local search algorithm.
1184
+ The main characteristic of this algorithm is that it accepts
1185
+ even solutions which lead to the increase of the cost in order
1186
+ to escape from low quality local optimal solutions.
1187
+
1188
+ This algorithm needs an initial solution. If not provided, it is
1189
+ constructed by a simple greedy algorithm. At every iteration, the
1190
+ algorithm selects thoughtfully a neighbor solution.
1191
+ Consider $c(x)$ cost of current solution and $c(x')$ cost of a
1192
+ neighbor solution.
1193
+ If $c(x') - c(x) <= 0$ then the neighbor solution becomes the current
1194
+ solution for the next iteration. Otherwise, the algorithm accepts
1195
+ the neighbor solution with probability $p = exp - ([c(x') - c(x)] / temp)$.
1196
+ Otherwise the current solution is retained.
1197
+
1198
+ `temp` is a parameter of the algorithm and represents temperature.
1199
+
1200
+ Time complexity:
1201
+ For $N_i$ iterations of the inner loop and $N_o$ iterations of the
1202
+ outer loop, this algorithm has running time $O(N_i * N_o * |V|)$.
1203
+
1204
+ For more information and how the algorithm is inspired see:
1205
+ http://en.wikipedia.org/wiki/Simulated_annealing
1206
+ """
1207
+ if move == "1-1":
1208
+ move = swap_two_nodes
1209
+ elif move == "1-0":
1210
+ move = move_one_node
1211
+ if init_cycle == "greedy":
1212
+ # Construct an initial solution using a greedy algorithm.
1213
+ cycle = greedy_tsp(G, weight=weight, source=source)
1214
+ if G.number_of_nodes() == 2:
1215
+ return cycle
1216
+
1217
+ else:
1218
+ cycle = list(init_cycle)
1219
+ if source is None:
1220
+ source = cycle[0]
1221
+ elif source != cycle[0]:
1222
+ raise nx.NetworkXError("source must be first node in init_cycle")
1223
+ if cycle[0] != cycle[-1]:
1224
+ raise nx.NetworkXError("init_cycle must be a cycle. (return to start)")
1225
+
1226
+ if len(cycle) - 1 != len(G) or len(set(G.nbunch_iter(cycle))) != len(G):
1227
+ raise nx.NetworkXError("init_cycle should be a cycle over all nodes in G.")
1228
+
1229
+ # Check that G is a complete graph
1230
+ N = len(G) - 1
1231
+ # This check ignores selfloops which is what we want here.
1232
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
1233
+ raise nx.NetworkXError("G must be a complete graph.")
1234
+
1235
+ if G.number_of_nodes() == 2:
1236
+ neighbor = next(G.neighbors(source))
1237
+ return [source, neighbor, source]
1238
+
1239
+ # Find the cost of initial solution
1240
+ cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(cycle))
1241
+
1242
+ count = 0
1243
+ best_cycle = cycle.copy()
1244
+ best_cost = cost
1245
+ while count <= max_iterations and temp > 0:
1246
+ count += 1
1247
+ for i in range(N_inner):
1248
+ adj_sol = move(cycle, seed)
1249
+ adj_cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(adj_sol))
1250
+ delta = adj_cost - cost
1251
+ if delta <= 0:
1252
+ # Set current solution the adjacent solution.
1253
+ cycle = adj_sol
1254
+ cost = adj_cost
1255
+
1256
+ if cost < best_cost:
1257
+ count = 0
1258
+ best_cycle = cycle.copy()
1259
+ best_cost = cost
1260
+ else:
1261
+ # Accept even a worse solution with probability p.
1262
+ p = math.exp(-delta / temp)
1263
+ if p >= seed.random():
1264
+ cycle = adj_sol
1265
+ cost = adj_cost
1266
+ temp -= temp * alpha
1267
+
1268
+ return best_cycle
1269
+
1270
+
1271
+ @py_random_state(9)
1272
+ @nx._dispatchable(edge_attrs="weight")
1273
+ def threshold_accepting_tsp(
1274
+ G,
1275
+ init_cycle,
1276
+ weight="weight",
1277
+ source=None,
1278
+ threshold=1,
1279
+ move="1-1",
1280
+ max_iterations=10,
1281
+ N_inner=100,
1282
+ alpha=0.1,
1283
+ seed=None,
1284
+ ):
1285
+ """Returns an approximate solution to the traveling salesman problem.
1286
+
1287
+ This function uses threshold accepting methods to approximate the minimal cost
1288
+ cycle through the nodes. Starting from a suboptimal solution, threshold
1289
+ accepting methods perturb that solution, accepting any changes that make
1290
+ the solution no worse than increasing by a threshold amount. Improvements
1291
+ in cost are accepted, but so are changes leading to small increases in cost.
1292
+ This allows the solution to leave suboptimal local minima in solution space.
1293
+ The threshold is decreased slowly as iterations proceed helping to ensure
1294
+ an optimum. In summary, the function returns a cycle starting at `source`
1295
+ for which the total cost is minimized.
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ G : Graph
1300
+ `G` should be a complete weighted graph.
1301
+ The distance between all pairs of nodes should be included.
1302
+
1303
+ init_cycle : list or "greedy"
1304
+ The initial solution (a cycle through all nodes returning to the start).
1305
+ This argument has no default to make you think about it.
1306
+ If "greedy", use `greedy_tsp(G, weight)`.
1307
+ Other common starting cycles are `list(G) + [next(iter(G))]` or the final
1308
+ result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.
1309
+
1310
+ weight : string, optional (default="weight")
1311
+ Edge data key corresponding to the edge weight.
1312
+ If any edge does not have this attribute the weight is set to 1.
1313
+
1314
+ source : node, optional (default: first node in list(G))
1315
+ Starting node. If None, defaults to ``next(iter(G))``
1316
+
1317
+ threshold : int, optional (default=1)
1318
+ The algorithm's threshold parameter. It represents the initial
1319
+ threshold's value
1320
+
1321
+ move : "1-1" or "1-0" or function, optional (default="1-1")
1322
+ Indicator of what move to use when finding new trial solutions.
1323
+ Strings indicate two special built-in moves:
1324
+
1325
+ - "1-1": 1-1 exchange which transposes the position
1326
+ of two elements of the current solution.
1327
+ The function called is :func:`swap_two_nodes`.
1328
+ For example if we apply 1-1 exchange in the solution
1329
+ ``A = [3, 2, 1, 4, 3]``
1330
+ we can get the following by the transposition of 1 and 4 elements:
1331
+ ``A' = [3, 2, 4, 1, 3]``
1332
+ - "1-0": 1-0 exchange which moves an node in the solution
1333
+ to a new position.
1334
+ The function called is :func:`move_one_node`.
1335
+ For example if we apply 1-0 exchange in the solution
1336
+ ``A = [3, 2, 1, 4, 3]``
1337
+ we can transfer the fourth element to the second position:
1338
+ ``A' = [3, 4, 2, 1, 3]``
1339
+
1340
+ You may provide your own functions to enact a move from
1341
+ one solution to a neighbor solution. The function must take
1342
+ the solution as input along with a `seed` input to control
1343
+ random number generation (see the `seed` input here).
1344
+ Your function should maintain the solution as a cycle with
1345
+ equal first and last node and all others appearing once.
1346
+ Your function should return the new solution.
1347
+
1348
+ max_iterations : int, optional (default=10)
1349
+ Declared done when this number of consecutive iterations of
1350
+ the outer loop occurs without any change in the best cost solution.
1351
+
1352
+ N_inner : int, optional (default=100)
1353
+ The number of iterations of the inner loop.
1354
+
1355
+ alpha : float between (0, 1), optional (default=0.1)
1356
+ Percentage of threshold decrease when there is at
1357
+ least one acceptance of a neighbor solution.
1358
+ If no inner loop moves are accepted the threshold remains unchanged.
1359
+
1360
+ seed : integer, random_state, or None (default)
1361
+ Indicator of random number generation state.
1362
+ See :ref:`Randomness<randomness>`.
1363
+
1364
+ Returns
1365
+ -------
1366
+ cycle : list of nodes
1367
+ Returns the cycle (list of nodes) that a salesman
1368
+ can follow to minimize total weight of the trip.
1369
+
1370
+ Raises
1371
+ ------
1372
+ NetworkXError
1373
+ If `G` is not complete the algorithm raises an exception.
1374
+
1375
+ Examples
1376
+ --------
1377
+ >>> from networkx.algorithms import approximation as approx
1378
+ >>> G = nx.DiGraph()
1379
+ >>> G.add_weighted_edges_from(
1380
+ ... {
1381
+ ... ("A", "B", 3),
1382
+ ... ("A", "C", 17),
1383
+ ... ("A", "D", 14),
1384
+ ... ("B", "A", 3),
1385
+ ... ("B", "C", 12),
1386
+ ... ("B", "D", 16),
1387
+ ... ("C", "A", 13),
1388
+ ... ("C", "B", 12),
1389
+ ... ("C", "D", 4),
1390
+ ... ("D", "A", 14),
1391
+ ... ("D", "B", 15),
1392
+ ... ("D", "C", 2),
1393
+ ... }
1394
+ ... )
1395
+ >>> cycle = approx.threshold_accepting_tsp(G, "greedy", source="D")
1396
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1397
+ >>> cycle
1398
+ ['D', 'C', 'B', 'A', 'D']
1399
+ >>> cost
1400
+ 31
1401
+ >>> incycle = ["D", "B", "A", "C", "D"]
1402
+ >>> cycle = approx.threshold_accepting_tsp(G, incycle, source="D")
1403
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1404
+ >>> cycle
1405
+ ['D', 'C', 'B', 'A', 'D']
1406
+ >>> cost
1407
+ 31
1408
+
1409
+ Notes
1410
+ -----
1411
+ Threshold Accepting is a metaheuristic local search algorithm.
1412
+ The main characteristic of this algorithm is that it accepts
1413
+ even solutions which lead to the increase of the cost in order
1414
+ to escape from low quality local optimal solutions.
1415
+
1416
+ This algorithm needs an initial solution. This solution can be
1417
+ constructed by a simple greedy algorithm. At every iteration, it
1418
+ selects thoughtfully a neighbor solution.
1419
+ Consider $c(x)$ cost of current solution and $c(x')$ cost of
1420
+ neighbor solution.
1421
+ If $c(x') - c(x) <= threshold$ then the neighbor solution becomes the current
1422
+ solution for the next iteration, where the threshold is named threshold.
1423
+
1424
+ In comparison to the Simulated Annealing algorithm, the Threshold
1425
+ Accepting algorithm does not accept very low quality solutions
1426
+ (due to the presence of the threshold value). In the case of
1427
+ Simulated Annealing, even a very low quality solution can
1428
+ be accepted with probability $p$.
1429
+
1430
+ Time complexity:
1431
+ It has a running time $O(m * n * |V|)$ where $m$ and $n$ are the number
1432
+ of times the outer and inner loop run respectively.
1433
+
1434
+ For more information and how algorithm is inspired see:
1435
+ https://doi.org/10.1016/0021-9991(90)90201-B
1436
+
1437
+ See Also
1438
+ --------
1439
+ simulated_annealing_tsp
1440
+
1441
+ """
1442
+ if move == "1-1":
1443
+ move = swap_two_nodes
1444
+ elif move == "1-0":
1445
+ move = move_one_node
1446
+ if init_cycle == "greedy":
1447
+ # Construct an initial solution using a greedy algorithm.
1448
+ cycle = greedy_tsp(G, weight=weight, source=source)
1449
+ if G.number_of_nodes() == 2:
1450
+ return cycle
1451
+
1452
+ else:
1453
+ cycle = list(init_cycle)
1454
+ if source is None:
1455
+ source = cycle[0]
1456
+ elif source != cycle[0]:
1457
+ raise nx.NetworkXError("source must be first node in init_cycle")
1458
+ if cycle[0] != cycle[-1]:
1459
+ raise nx.NetworkXError("init_cycle must be a cycle. (return to start)")
1460
+
1461
+ if len(cycle) - 1 != len(G) or len(set(G.nbunch_iter(cycle))) != len(G):
1462
+ raise nx.NetworkXError("init_cycle is not all and only nodes.")
1463
+
1464
+ # Check that G is a complete graph
1465
+ N = len(G) - 1
1466
+ # This check ignores selfloops which is what we want here.
1467
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
1468
+ raise nx.NetworkXError("G must be a complete graph.")
1469
+
1470
+ if G.number_of_nodes() == 2:
1471
+ neighbor = list(G.neighbors(source))[0]
1472
+ return [source, neighbor, source]
1473
+
1474
+ # Find the cost of initial solution
1475
+ cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(cycle))
1476
+
1477
+ count = 0
1478
+ best_cycle = cycle.copy()
1479
+ best_cost = cost
1480
+ while count <= max_iterations:
1481
+ count += 1
1482
+ accepted = False
1483
+ for i in range(N_inner):
1484
+ adj_sol = move(cycle, seed)
1485
+ adj_cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(adj_sol))
1486
+ delta = adj_cost - cost
1487
+ if delta <= threshold:
1488
+ accepted = True
1489
+
1490
+ # Set current solution the adjacent solution.
1491
+ cycle = adj_sol
1492
+ cost = adj_cost
1493
+
1494
+ if cost < best_cost:
1495
+ count = 0
1496
+ best_cycle = cycle.copy()
1497
+ best_cost = cost
1498
+ if accepted:
1499
+ threshold -= threshold * alpha
1500
+
1501
+ return best_cycle
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/treewidth.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing treewidth decomposition.
2
+
3
+ Treewidth of an undirected graph is a number associated with the graph.
4
+ It can be defined as the size of the largest vertex set (bag) in a tree
5
+ decomposition of the graph minus one.
6
+
7
+ `Wikipedia: Treewidth <https://en.wikipedia.org/wiki/Treewidth>`_
8
+
9
+ The notions of treewidth and tree decomposition have gained their
10
+ attractiveness partly because many graph and network problems that are
11
+ intractable (e.g., NP-hard) on arbitrary graphs become efficiently
12
+ solvable (e.g., with a linear time algorithm) when the treewidth of the
13
+ input graphs is bounded by a constant [1]_ [2]_.
14
+
15
+ There are two different functions for computing a tree decomposition:
16
+ :func:`treewidth_min_degree` and :func:`treewidth_min_fill_in`.
17
+
18
+ .. [1] Hans L. Bodlaender and Arie M. C. A. Koster. 2010. "Treewidth
19
+ computations I.Upper bounds". Inf. Comput. 208, 3 (March 2010),259-275.
20
+ http://dx.doi.org/10.1016/j.ic.2009.03.008
21
+
22
+ .. [2] Hans L. Bodlaender. "Discovering Treewidth". Institute of Information
23
+ and Computing Sciences, Utrecht University.
24
+ Technical Report UU-CS-2005-018.
25
+ http://www.cs.uu.nl
26
+
27
+ .. [3] K. Wang, Z. Lu, and J. Hicks *Treewidth*.
28
+ https://web.archive.org/web/20210507025929/http://web.eecs.utk.edu/~cphill25/cs594_spring2015_projects/treewidth.pdf
29
+
30
+ """
31
+
32
+ import itertools
33
+ import sys
34
+ from heapq import heapify, heappop, heappush
35
+
36
+ import networkx as nx
37
+ from networkx.utils import not_implemented_for
38
+
39
+ __all__ = ["treewidth_min_degree", "treewidth_min_fill_in"]
40
+
41
+
42
+ @not_implemented_for("directed")
43
+ @not_implemented_for("multigraph")
44
+ @nx._dispatchable(returns_graph=True)
45
+ def treewidth_min_degree(G):
46
+ """Returns a treewidth decomposition using the Minimum Degree heuristic.
47
+
48
+ The heuristic chooses the nodes according to their degree, i.e., first
49
+ the node with the lowest degree is chosen, then the graph is updated
50
+ and the corresponding node is removed. Next, a new node with the lowest
51
+ degree is chosen, and so on.
52
+
53
+ Parameters
54
+ ----------
55
+ G : NetworkX graph
56
+
57
+ Returns
58
+ -------
59
+ Treewidth decomposition : (int, Graph) tuple
60
+ 2-tuple with treewidth and the corresponding decomposed tree.
61
+ """
62
+ deg_heuristic = MinDegreeHeuristic(G)
63
+ return treewidth_decomp(G, lambda graph: deg_heuristic.best_node(graph))
64
+
65
+
66
+ @not_implemented_for("directed")
67
+ @not_implemented_for("multigraph")
68
+ @nx._dispatchable(returns_graph=True)
69
+ def treewidth_min_fill_in(G):
70
+ """Returns a treewidth decomposition using the Minimum Fill-in heuristic.
71
+
72
+ The heuristic chooses a node from the graph, where the number of edges
73
+ added turning the neighborhood of the chosen node into clique is as
74
+ small as possible.
75
+
76
+ Parameters
77
+ ----------
78
+ G : NetworkX graph
79
+
80
+ Returns
81
+ -------
82
+ Treewidth decomposition : (int, Graph) tuple
83
+ 2-tuple with treewidth and the corresponding decomposed tree.
84
+ """
85
+ return treewidth_decomp(G, min_fill_in_heuristic)
86
+
87
+
88
+ class MinDegreeHeuristic:
89
+ """Implements the Minimum Degree heuristic.
90
+
91
+ The heuristic chooses the nodes according to their degree
92
+ (number of neighbors), i.e., first the node with the lowest degree is
93
+ chosen, then the graph is updated and the corresponding node is
94
+ removed. Next, a new node with the lowest degree is chosen, and so on.
95
+ """
96
+
97
+ def __init__(self, graph):
98
+ self._graph = graph
99
+
100
+ # nodes that have to be updated in the heap before each iteration
101
+ self._update_nodes = []
102
+
103
+ self._degreeq = [] # a heapq with 3-tuples (degree,unique_id,node)
104
+ self.count = itertools.count()
105
+
106
+ # build heap with initial degrees
107
+ for n in graph:
108
+ self._degreeq.append((len(graph[n]), next(self.count), n))
109
+ heapify(self._degreeq)
110
+
111
+ def best_node(self, graph):
112
+ # update nodes in self._update_nodes
113
+ for n in self._update_nodes:
114
+ # insert changed degrees into degreeq
115
+ heappush(self._degreeq, (len(graph[n]), next(self.count), n))
116
+
117
+ # get the next valid (minimum degree) node
118
+ while self._degreeq:
119
+ (min_degree, _, elim_node) = heappop(self._degreeq)
120
+ if elim_node not in graph or len(graph[elim_node]) != min_degree:
121
+ # outdated entry in degreeq
122
+ continue
123
+ elif min_degree == len(graph) - 1:
124
+ # fully connected: abort condition
125
+ return None
126
+
127
+ # remember to update nodes in the heap before getting the next node
128
+ self._update_nodes = graph[elim_node]
129
+ return elim_node
130
+
131
+ # the heap is empty: abort
132
+ return None
133
+
134
+
135
+ def min_fill_in_heuristic(graph):
136
+ """Implements the Minimum Degree heuristic.
137
+
138
+ Returns the node from the graph, where the number of edges added when
139
+ turning the neighborhood of the chosen node into clique is as small as
140
+ possible. This algorithm chooses the nodes using the Minimum Fill-In
141
+ heuristic. The running time of the algorithm is :math:`O(V^3)` and it uses
142
+ additional constant memory."""
143
+
144
+ if len(graph) == 0:
145
+ return None
146
+
147
+ min_fill_in_node = None
148
+
149
+ min_fill_in = sys.maxsize
150
+
151
+ # sort nodes by degree
152
+ nodes_by_degree = sorted(graph, key=lambda x: len(graph[x]))
153
+ min_degree = len(graph[nodes_by_degree[0]])
154
+
155
+ # abort condition (handle complete graph)
156
+ if min_degree == len(graph) - 1:
157
+ return None
158
+
159
+ for node in nodes_by_degree:
160
+ num_fill_in = 0
161
+ nbrs = graph[node]
162
+ for nbr in nbrs:
163
+ # count how many nodes in nbrs current nbr is not connected to
164
+ # subtract 1 for the node itself
165
+ num_fill_in += len(nbrs - graph[nbr]) - 1
166
+ if num_fill_in >= 2 * min_fill_in:
167
+ break
168
+
169
+ num_fill_in /= 2 # divide by 2 because of double counting
170
+
171
+ if num_fill_in < min_fill_in: # update min-fill-in node
172
+ if num_fill_in == 0:
173
+ return node
174
+ min_fill_in = num_fill_in
175
+ min_fill_in_node = node
176
+
177
+ return min_fill_in_node
178
+
179
+
180
+ @nx._dispatchable(returns_graph=True)
181
+ def treewidth_decomp(G, heuristic=min_fill_in_heuristic):
182
+ """Returns a treewidth decomposition using the passed heuristic.
183
+
184
+ Parameters
185
+ ----------
186
+ G : NetworkX graph
187
+ heuristic : heuristic function
188
+
189
+ Returns
190
+ -------
191
+ Treewidth decomposition : (int, Graph) tuple
192
+ 2-tuple with treewidth and the corresponding decomposed tree.
193
+ """
194
+
195
+ # make dict-of-sets structure
196
+ graph = {n: set(G[n]) - {n} for n in G}
197
+
198
+ # stack containing nodes and neighbors in the order from the heuristic
199
+ node_stack = []
200
+
201
+ # get first node from heuristic
202
+ elim_node = heuristic(graph)
203
+ while elim_node is not None:
204
+ # connect all neighbors with each other
205
+ nbrs = graph[elim_node]
206
+ for u, v in itertools.permutations(nbrs, 2):
207
+ if v not in graph[u]:
208
+ graph[u].add(v)
209
+
210
+ # push node and its current neighbors on stack
211
+ node_stack.append((elim_node, nbrs))
212
+
213
+ # remove node from graph
214
+ for u in graph[elim_node]:
215
+ graph[u].remove(elim_node)
216
+
217
+ del graph[elim_node]
218
+ elim_node = heuristic(graph)
219
+
220
+ # the abort condition is met; put all remaining nodes into one bag
221
+ decomp = nx.Graph()
222
+ first_bag = frozenset(graph.keys())
223
+ decomp.add_node(first_bag)
224
+
225
+ treewidth = len(first_bag) - 1
226
+
227
+ while node_stack:
228
+ # get node and its neighbors from the stack
229
+ (curr_node, nbrs) = node_stack.pop()
230
+
231
+ # find a bag all neighbors are in
232
+ old_bag = None
233
+ for bag in decomp.nodes:
234
+ if nbrs <= bag:
235
+ old_bag = bag
236
+ break
237
+
238
+ if old_bag is None:
239
+ # no old_bag was found: just connect to the first_bag
240
+ old_bag = first_bag
241
+
242
+ # create new node for decomposition
243
+ nbrs.add(curr_node)
244
+ new_bag = frozenset(nbrs)
245
+
246
+ # update treewidth
247
+ treewidth = max(treewidth, len(new_bag) - 1)
248
+
249
+ # add edge to decomposition (implicitly also adds the new node)
250
+ decomp.add_edge(old_bag, new_bag)
251
+
252
+ return treewidth, decomp
.venv/lib/python3.10/site-packages/networkx/algorithms/approximation/vertex_cover.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing an approximate minimum weight vertex cover.
2
+
3
+ A |vertex cover|_ is a subset of nodes such that each edge in the graph
4
+ is incident to at least one node in the subset.
5
+
6
+ .. _vertex cover: https://en.wikipedia.org/wiki/Vertex_cover
7
+ .. |vertex cover| replace:: *vertex cover*
8
+
9
+ """
10
+
11
+ import networkx as nx
12
+
13
+ __all__ = ["min_weighted_vertex_cover"]
14
+
15
+
16
+ @nx._dispatchable(node_attrs="weight")
17
+ def min_weighted_vertex_cover(G, weight=None):
18
+ r"""Returns an approximate minimum weighted vertex cover.
19
+
20
+ The set of nodes returned by this function is guaranteed to be a
21
+ vertex cover, and the total weight of the set is guaranteed to be at
22
+ most twice the total weight of the minimum weight vertex cover. In
23
+ other words,
24
+
25
+ .. math::
26
+
27
+ w(S) \leq 2 * w(S^*),
28
+
29
+ where $S$ is the vertex cover returned by this function,
30
+ $S^*$ is the vertex cover of minimum weight out of all vertex
31
+ covers of the graph, and $w$ is the function that computes the
32
+ sum of the weights of each node in that given set.
33
+
34
+ Parameters
35
+ ----------
36
+ G : NetworkX graph
37
+
38
+ weight : string, optional (default = None)
39
+ If None, every node has weight 1. If a string, use this node
40
+ attribute as the node weight. A node without this attribute is
41
+ assumed to have weight 1.
42
+
43
+ Returns
44
+ -------
45
+ min_weighted_cover : set
46
+ Returns a set of nodes whose weight sum is no more than twice
47
+ the weight sum of the minimum weight vertex cover.
48
+
49
+ Notes
50
+ -----
51
+ For a directed graph, a vertex cover has the same definition: a set
52
+ of nodes such that each edge in the graph is incident to at least
53
+ one node in the set. Whether the node is the head or tail of the
54
+ directed edge is ignored.
55
+
56
+ This is the local-ratio algorithm for computing an approximate
57
+ vertex cover. The algorithm greedily reduces the costs over edges,
58
+ iteratively building a cover. The worst-case runtime of this
59
+ implementation is $O(m \log n)$, where $n$ is the number
60
+ of nodes and $m$ the number of edges in the graph.
61
+
62
+ References
63
+ ----------
64
+ .. [1] Bar-Yehuda, R., and Even, S. (1985). "A local-ratio theorem for
65
+ approximating the weighted vertex cover problem."
66
+ *Annals of Discrete Mathematics*, 25, 27–46
67
+ <http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf>
68
+
69
+ """
70
+ cost = dict(G.nodes(data=weight, default=1))
71
+ # While there are uncovered edges, choose an uncovered and update
72
+ # the cost of the remaining edges.
73
+ cover = set()
74
+ for u, v in G.edges():
75
+ if u in cover or v in cover:
76
+ continue
77
+ if cost[u] <= cost[v]:
78
+ cover.add(u)
79
+ cost[v] -= cost[u]
80
+ else:
81
+ cover.add(v)
82
+ cost[u] -= cost[v]
83
+ return cover
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .betweenness import *
2
+ from .betweenness_subset import *
3
+ from .closeness import *
4
+ from .current_flow_betweenness import *
5
+ from .current_flow_betweenness_subset import *
6
+ from .current_flow_closeness import *
7
+ from .degree_alg import *
8
+ from .dispersion import *
9
+ from .eigenvector import *
10
+ from .group import *
11
+ from .harmonic import *
12
+ from .katz import *
13
+ from .load import *
14
+ from .percolation import *
15
+ from .reaching import *
16
+ from .second_order import *
17
+ from .subgraph_alg import *
18
+ from .trophic import *
19
+ from .voterank_alg import *
20
+ from .laplacian import *
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/betweenness.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Betweenness centrality measures."""
2
+
3
+ from collections import deque
4
+ from heapq import heappop, heappush
5
+ from itertools import count
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.shortest_paths.weighted import _weight_function
9
+ from networkx.utils import py_random_state
10
+ from networkx.utils.decorators import not_implemented_for
11
+
12
+ __all__ = ["betweenness_centrality", "edge_betweenness_centrality"]
13
+
14
+
15
+ @py_random_state(5)
16
+ @nx._dispatchable(edge_attrs="weight")
17
+ def betweenness_centrality(
18
+ G, k=None, normalized=True, weight=None, endpoints=False, seed=None
19
+ ):
20
+ r"""Compute the shortest-path betweenness centrality for nodes.
21
+
22
+ Betweenness centrality of a node $v$ is the sum of the
23
+ fraction of all-pairs shortest paths that pass through $v$
24
+
25
+ .. math::
26
+
27
+ c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
28
+
29
+ where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
30
+ shortest $(s, t)$-paths, and $\sigma(s, t|v)$ is the number of
31
+ those paths passing through some node $v$ other than $s, t$.
32
+ If $s = t$, $\sigma(s, t) = 1$, and if $v \in {s, t}$,
33
+ $\sigma(s, t|v) = 0$ [2]_.
34
+
35
+ Parameters
36
+ ----------
37
+ G : graph
38
+ A NetworkX graph.
39
+
40
+ k : int, optional (default=None)
41
+ If k is not None use k node samples to estimate betweenness.
42
+ The value of k <= n where n is the number of nodes in the graph.
43
+ Higher values give better approximation.
44
+
45
+ normalized : bool, optional
46
+ If True the betweenness values are normalized by `2/((n-1)(n-2))`
47
+ for graphs, and `1/((n-1)(n-2))` for directed graphs where `n`
48
+ is the number of nodes in G.
49
+
50
+ weight : None or string, optional (default=None)
51
+ If None, all edge weights are considered equal.
52
+ Otherwise holds the name of the edge attribute used as weight.
53
+ Weights are used to calculate weighted shortest paths, so they are
54
+ interpreted as distances.
55
+
56
+ endpoints : bool, optional
57
+ If True include the endpoints in the shortest path counts.
58
+
59
+ seed : integer, random_state, or None (default)
60
+ Indicator of random number generation state.
61
+ See :ref:`Randomness<randomness>`.
62
+ Note that this is only used if k is not None.
63
+
64
+ Returns
65
+ -------
66
+ nodes : dictionary
67
+ Dictionary of nodes with betweenness centrality as the value.
68
+
69
+ See Also
70
+ --------
71
+ edge_betweenness_centrality
72
+ load_centrality
73
+
74
+ Notes
75
+ -----
76
+ The algorithm is from Ulrik Brandes [1]_.
77
+ See [4]_ for the original first published version and [2]_ for details on
78
+ algorithms for variations and related metrics.
79
+
80
+ For approximate betweenness calculations set k=#samples to use
81
+ k nodes ("pivots") to estimate the betweenness values. For an estimate
82
+ of the number of pivots needed see [3]_.
83
+
84
+ For weighted graphs the edge weights must be greater than zero.
85
+ Zero edge weights can produce an infinite number of equal length
86
+ paths between pairs of nodes.
87
+
88
+ The total number of paths between source and target is counted
89
+ differently for directed and undirected graphs. Directed paths
90
+ are easy to count. Undirected paths are tricky: should a path
91
+ from "u" to "v" count as 1 undirected path or as 2 directed paths?
92
+
93
+ For betweenness_centrality we report the number of undirected
94
+ paths when G is undirected.
95
+
96
+ For betweenness_centrality_subset the reporting is different.
97
+ If the source and target subsets are the same, then we want
98
+ to count undirected paths. But if the source and target subsets
99
+ differ -- for example, if sources is {0} and targets is {1},
100
+ then we are only counting the paths in one direction. They are
101
+ undirected paths but we are counting them in a directed way.
102
+ To count them as undirected paths, each should count as half a path.
103
+
104
+ This algorithm is not guaranteed to be correct if edge weights
105
+ are floating point numbers. As a workaround you can use integer
106
+ numbers by multiplying the relevant edge attributes by a convenient
107
+ constant factor (eg 100) and converting to integers.
108
+
109
+ References
110
+ ----------
111
+ .. [1] Ulrik Brandes:
112
+ A Faster Algorithm for Betweenness Centrality.
113
+ Journal of Mathematical Sociology 25(2):163-177, 2001.
114
+ https://doi.org/10.1080/0022250X.2001.9990249
115
+ .. [2] Ulrik Brandes:
116
+ On Variants of Shortest-Path Betweenness
117
+ Centrality and their Generic Computation.
118
+ Social Networks 30(2):136-145, 2008.
119
+ https://doi.org/10.1016/j.socnet.2007.11.001
120
+ .. [3] Ulrik Brandes and Christian Pich:
121
+ Centrality Estimation in Large Networks.
122
+ International Journal of Bifurcation and Chaos 17(7):2303-2318, 2007.
123
+ https://dx.doi.org/10.1142/S0218127407018403
124
+ .. [4] Linton C. Freeman:
125
+ A set of measures of centrality based on betweenness.
126
+ Sociometry 40: 35–41, 1977
127
+ https://doi.org/10.2307/3033543
128
+ """
129
+ betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
130
+ if k is None:
131
+ nodes = G
132
+ else:
133
+ nodes = seed.sample(list(G.nodes()), k)
134
+ for s in nodes:
135
+ # single source shortest paths
136
+ if weight is None: # use BFS
137
+ S, P, sigma, _ = _single_source_shortest_path_basic(G, s)
138
+ else: # use Dijkstra's algorithm
139
+ S, P, sigma, _ = _single_source_dijkstra_path_basic(G, s, weight)
140
+ # accumulation
141
+ if endpoints:
142
+ betweenness, _ = _accumulate_endpoints(betweenness, S, P, sigma, s)
143
+ else:
144
+ betweenness, _ = _accumulate_basic(betweenness, S, P, sigma, s)
145
+ # rescaling
146
+ betweenness = _rescale(
147
+ betweenness,
148
+ len(G),
149
+ normalized=normalized,
150
+ directed=G.is_directed(),
151
+ k=k,
152
+ endpoints=endpoints,
153
+ )
154
+ return betweenness
155
+
156
+
157
+ @py_random_state(4)
158
+ @nx._dispatchable(edge_attrs="weight")
159
+ def edge_betweenness_centrality(G, k=None, normalized=True, weight=None, seed=None):
160
+ r"""Compute betweenness centrality for edges.
161
+
162
+ Betweenness centrality of an edge $e$ is the sum of the
163
+ fraction of all-pairs shortest paths that pass through $e$
164
+
165
+ .. math::
166
+
167
+ c_B(e) =\sum_{s,t \in V} \frac{\sigma(s, t|e)}{\sigma(s, t)}
168
+
169
+ where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
170
+ shortest $(s, t)$-paths, and $\sigma(s, t|e)$ is the number of
171
+ those paths passing through edge $e$ [2]_.
172
+
173
+ Parameters
174
+ ----------
175
+ G : graph
176
+ A NetworkX graph.
177
+
178
+ k : int, optional (default=None)
179
+ If k is not None use k node samples to estimate betweenness.
180
+ The value of k <= n where n is the number of nodes in the graph.
181
+ Higher values give better approximation.
182
+
183
+ normalized : bool, optional
184
+ If True the betweenness values are normalized by $2/(n(n-1))$
185
+ for graphs, and $1/(n(n-1))$ for directed graphs where $n$
186
+ is the number of nodes in G.
187
+
188
+ weight : None or string, optional (default=None)
189
+ If None, all edge weights are considered equal.
190
+ Otherwise holds the name of the edge attribute used as weight.
191
+ Weights are used to calculate weighted shortest paths, so they are
192
+ interpreted as distances.
193
+
194
+ seed : integer, random_state, or None (default)
195
+ Indicator of random number generation state.
196
+ See :ref:`Randomness<randomness>`.
197
+ Note that this is only used if k is not None.
198
+
199
+ Returns
200
+ -------
201
+ edges : dictionary
202
+ Dictionary of edges with betweenness centrality as the value.
203
+
204
+ See Also
205
+ --------
206
+ betweenness_centrality
207
+ edge_load
208
+
209
+ Notes
210
+ -----
211
+ The algorithm is from Ulrik Brandes [1]_.
212
+
213
+ For weighted graphs the edge weights must be greater than zero.
214
+ Zero edge weights can produce an infinite number of equal length
215
+ paths between pairs of nodes.
216
+
217
+ References
218
+ ----------
219
+ .. [1] A Faster Algorithm for Betweenness Centrality. Ulrik Brandes,
220
+ Journal of Mathematical Sociology 25(2):163-177, 2001.
221
+ https://doi.org/10.1080/0022250X.2001.9990249
222
+ .. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
223
+ Centrality and their Generic Computation.
224
+ Social Networks 30(2):136-145, 2008.
225
+ https://doi.org/10.1016/j.socnet.2007.11.001
226
+ """
227
+ betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
228
+ # b[e]=0 for e in G.edges()
229
+ betweenness.update(dict.fromkeys(G.edges(), 0.0))
230
+ if k is None:
231
+ nodes = G
232
+ else:
233
+ nodes = seed.sample(list(G.nodes()), k)
234
+ for s in nodes:
235
+ # single source shortest paths
236
+ if weight is None: # use BFS
237
+ S, P, sigma, _ = _single_source_shortest_path_basic(G, s)
238
+ else: # use Dijkstra's algorithm
239
+ S, P, sigma, _ = _single_source_dijkstra_path_basic(G, s, weight)
240
+ # accumulation
241
+ betweenness = _accumulate_edges(betweenness, S, P, sigma, s)
242
+ # rescaling
243
+ for n in G: # remove nodes to only return edges
244
+ del betweenness[n]
245
+ betweenness = _rescale_e(
246
+ betweenness, len(G), normalized=normalized, directed=G.is_directed()
247
+ )
248
+ if G.is_multigraph():
249
+ betweenness = _add_edge_keys(G, betweenness, weight=weight)
250
+ return betweenness
251
+
252
+
253
+ # helpers for betweenness centrality
254
+
255
+
256
+ def _single_source_shortest_path_basic(G, s):
257
+ S = []
258
+ P = {}
259
+ for v in G:
260
+ P[v] = []
261
+ sigma = dict.fromkeys(G, 0.0) # sigma[v]=0 for v in G
262
+ D = {}
263
+ sigma[s] = 1.0
264
+ D[s] = 0
265
+ Q = deque([s])
266
+ while Q: # use BFS to find shortest paths
267
+ v = Q.popleft()
268
+ S.append(v)
269
+ Dv = D[v]
270
+ sigmav = sigma[v]
271
+ for w in G[v]:
272
+ if w not in D:
273
+ Q.append(w)
274
+ D[w] = Dv + 1
275
+ if D[w] == Dv + 1: # this is a shortest path, count paths
276
+ sigma[w] += sigmav
277
+ P[w].append(v) # predecessors
278
+ return S, P, sigma, D
279
+
280
+
281
+ def _single_source_dijkstra_path_basic(G, s, weight):
282
+ weight = _weight_function(G, weight)
283
+ # modified from Eppstein
284
+ S = []
285
+ P = {}
286
+ for v in G:
287
+ P[v] = []
288
+ sigma = dict.fromkeys(G, 0.0) # sigma[v]=0 for v in G
289
+ D = {}
290
+ sigma[s] = 1.0
291
+ push = heappush
292
+ pop = heappop
293
+ seen = {s: 0}
294
+ c = count()
295
+ Q = [] # use Q as heap with (distance,node id) tuples
296
+ push(Q, (0, next(c), s, s))
297
+ while Q:
298
+ (dist, _, pred, v) = pop(Q)
299
+ if v in D:
300
+ continue # already searched this node.
301
+ sigma[v] += sigma[pred] # count paths
302
+ S.append(v)
303
+ D[v] = dist
304
+ for w, edgedata in G[v].items():
305
+ vw_dist = dist + weight(v, w, edgedata)
306
+ if w not in D and (w not in seen or vw_dist < seen[w]):
307
+ seen[w] = vw_dist
308
+ push(Q, (vw_dist, next(c), v, w))
309
+ sigma[w] = 0.0
310
+ P[w] = [v]
311
+ elif vw_dist == seen[w]: # handle equal paths
312
+ sigma[w] += sigma[v]
313
+ P[w].append(v)
314
+ return S, P, sigma, D
315
+
316
+
317
+ def _accumulate_basic(betweenness, S, P, sigma, s):
318
+ delta = dict.fromkeys(S, 0)
319
+ while S:
320
+ w = S.pop()
321
+ coeff = (1 + delta[w]) / sigma[w]
322
+ for v in P[w]:
323
+ delta[v] += sigma[v] * coeff
324
+ if w != s:
325
+ betweenness[w] += delta[w]
326
+ return betweenness, delta
327
+
328
+
329
+ def _accumulate_endpoints(betweenness, S, P, sigma, s):
330
+ betweenness[s] += len(S) - 1
331
+ delta = dict.fromkeys(S, 0)
332
+ while S:
333
+ w = S.pop()
334
+ coeff = (1 + delta[w]) / sigma[w]
335
+ for v in P[w]:
336
+ delta[v] += sigma[v] * coeff
337
+ if w != s:
338
+ betweenness[w] += delta[w] + 1
339
+ return betweenness, delta
340
+
341
+
342
+ def _accumulate_edges(betweenness, S, P, sigma, s):
343
+ delta = dict.fromkeys(S, 0)
344
+ while S:
345
+ w = S.pop()
346
+ coeff = (1 + delta[w]) / sigma[w]
347
+ for v in P[w]:
348
+ c = sigma[v] * coeff
349
+ if (v, w) not in betweenness:
350
+ betweenness[(w, v)] += c
351
+ else:
352
+ betweenness[(v, w)] += c
353
+ delta[v] += c
354
+ if w != s:
355
+ betweenness[w] += delta[w]
356
+ return betweenness
357
+
358
+
359
+ def _rescale(betweenness, n, normalized, directed=False, k=None, endpoints=False):
360
+ if normalized:
361
+ if endpoints:
362
+ if n < 2:
363
+ scale = None # no normalization
364
+ else:
365
+ # Scale factor should include endpoint nodes
366
+ scale = 1 / (n * (n - 1))
367
+ elif n <= 2:
368
+ scale = None # no normalization b=0 for all nodes
369
+ else:
370
+ scale = 1 / ((n - 1) * (n - 2))
371
+ else: # rescale by 2 for undirected graphs
372
+ if not directed:
373
+ scale = 0.5
374
+ else:
375
+ scale = None
376
+ if scale is not None:
377
+ if k is not None:
378
+ scale = scale * n / k
379
+ for v in betweenness:
380
+ betweenness[v] *= scale
381
+ return betweenness
382
+
383
+
384
+ def _rescale_e(betweenness, n, normalized, directed=False, k=None):
385
+ if normalized:
386
+ if n <= 1:
387
+ scale = None # no normalization b=0 for all nodes
388
+ else:
389
+ scale = 1 / (n * (n - 1))
390
+ else: # rescale by 2 for undirected graphs
391
+ if not directed:
392
+ scale = 0.5
393
+ else:
394
+ scale = None
395
+ if scale is not None:
396
+ if k is not None:
397
+ scale = scale * n / k
398
+ for v in betweenness:
399
+ betweenness[v] *= scale
400
+ return betweenness
401
+
402
+
403
+ @not_implemented_for("graph")
404
+ def _add_edge_keys(G, betweenness, weight=None):
405
+ r"""Adds the corrected betweenness centrality (BC) values for multigraphs.
406
+
407
+ Parameters
408
+ ----------
409
+ G : NetworkX graph.
410
+
411
+ betweenness : dictionary
412
+ Dictionary mapping adjacent node tuples to betweenness centrality values.
413
+
414
+ weight : string or function
415
+ See `_weight_function` for details. Defaults to `None`.
416
+
417
+ Returns
418
+ -------
419
+ edges : dictionary
420
+ The parameter `betweenness` including edges with keys and their
421
+ betweenness centrality values.
422
+
423
+ The BC value is divided among edges of equal weight.
424
+ """
425
+ _weight = _weight_function(G, weight)
426
+
427
+ edge_bc = dict.fromkeys(G.edges, 0.0)
428
+ for u, v in betweenness:
429
+ d = G[u][v]
430
+ wt = _weight(u, v, d)
431
+ keys = [k for k in d if _weight(u, v, {k: d[k]}) == wt]
432
+ bc = betweenness[(u, v)] / len(keys)
433
+ for k in keys:
434
+ edge_bc[(u, v, k)] = bc
435
+
436
+ return edge_bc
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/betweenness_subset.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Betweenness centrality measures for subsets of nodes."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.centrality.betweenness import (
5
+ _add_edge_keys,
6
+ )
7
+ from networkx.algorithms.centrality.betweenness import (
8
+ _single_source_dijkstra_path_basic as dijkstra,
9
+ )
10
+ from networkx.algorithms.centrality.betweenness import (
11
+ _single_source_shortest_path_basic as shortest_path,
12
+ )
13
+
14
+ __all__ = [
15
+ "betweenness_centrality_subset",
16
+ "edge_betweenness_centrality_subset",
17
+ ]
18
+
19
+
20
+ @nx._dispatchable(edge_attrs="weight")
21
+ def betweenness_centrality_subset(G, sources, targets, normalized=False, weight=None):
22
+ r"""Compute betweenness centrality for a subset of nodes.
23
+
24
+ .. math::
25
+
26
+ c_B(v) =\sum_{s\in S, t \in T} \frac{\sigma(s, t|v)}{\sigma(s, t)}
27
+
28
+ where $S$ is the set of sources, $T$ is the set of targets,
29
+ $\sigma(s, t)$ is the number of shortest $(s, t)$-paths,
30
+ and $\sigma(s, t|v)$ is the number of those paths
31
+ passing through some node $v$ other than $s, t$.
32
+ If $s = t$, $\sigma(s, t) = 1$,
33
+ and if $v \in {s, t}$, $\sigma(s, t|v) = 0$ [2]_.
34
+
35
+
36
+ Parameters
37
+ ----------
38
+ G : graph
39
+ A NetworkX graph.
40
+
41
+ sources: list of nodes
42
+ Nodes to use as sources for shortest paths in betweenness
43
+
44
+ targets: list of nodes
45
+ Nodes to use as targets for shortest paths in betweenness
46
+
47
+ normalized : bool, optional
48
+ If True the betweenness values are normalized by $2/((n-1)(n-2))$
49
+ for graphs, and $1/((n-1)(n-2))$ for directed graphs where $n$
50
+ is the number of nodes in G.
51
+
52
+ weight : None or string, optional (default=None)
53
+ If None, all edge weights are considered equal.
54
+ Otherwise holds the name of the edge attribute used as weight.
55
+ Weights are used to calculate weighted shortest paths, so they are
56
+ interpreted as distances.
57
+
58
+ Returns
59
+ -------
60
+ nodes : dictionary
61
+ Dictionary of nodes with betweenness centrality as the value.
62
+
63
+ See Also
64
+ --------
65
+ edge_betweenness_centrality
66
+ load_centrality
67
+
68
+ Notes
69
+ -----
70
+ The basic algorithm is from [1]_.
71
+
72
+ For weighted graphs the edge weights must be greater than zero.
73
+ Zero edge weights can produce an infinite number of equal length
74
+ paths between pairs of nodes.
75
+
76
+ The normalization might seem a little strange but it is
77
+ designed to make betweenness_centrality(G) be the same as
78
+ betweenness_centrality_subset(G,sources=G.nodes(),targets=G.nodes()).
79
+
80
+ The total number of paths between source and target is counted
81
+ differently for directed and undirected graphs. Directed paths
82
+ are easy to count. Undirected paths are tricky: should a path
83
+ from "u" to "v" count as 1 undirected path or as 2 directed paths?
84
+
85
+ For betweenness_centrality we report the number of undirected
86
+ paths when G is undirected.
87
+
88
+ For betweenness_centrality_subset the reporting is different.
89
+ If the source and target subsets are the same, then we want
90
+ to count undirected paths. But if the source and target subsets
91
+ differ -- for example, if sources is {0} and targets is {1},
92
+ then we are only counting the paths in one direction. They are
93
+ undirected paths but we are counting them in a directed way.
94
+ To count them as undirected paths, each should count as half a path.
95
+
96
+ References
97
+ ----------
98
+ .. [1] Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
99
+ Journal of Mathematical Sociology 25(2):163-177, 2001.
100
+ https://doi.org/10.1080/0022250X.2001.9990249
101
+ .. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
102
+ Centrality and their Generic Computation.
103
+ Social Networks 30(2):136-145, 2008.
104
+ https://doi.org/10.1016/j.socnet.2007.11.001
105
+ """
106
+ b = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
107
+ for s in sources:
108
+ # single source shortest paths
109
+ if weight is None: # use BFS
110
+ S, P, sigma, _ = shortest_path(G, s)
111
+ else: # use Dijkstra's algorithm
112
+ S, P, sigma, _ = dijkstra(G, s, weight)
113
+ b = _accumulate_subset(b, S, P, sigma, s, targets)
114
+ b = _rescale(b, len(G), normalized=normalized, directed=G.is_directed())
115
+ return b
116
+
117
+
118
+ @nx._dispatchable(edge_attrs="weight")
119
+ def edge_betweenness_centrality_subset(
120
+ G, sources, targets, normalized=False, weight=None
121
+ ):
122
+ r"""Compute betweenness centrality for edges for a subset of nodes.
123
+
124
+ .. math::
125
+
126
+ c_B(v) =\sum_{s\in S,t \in T} \frac{\sigma(s, t|e)}{\sigma(s, t)}
127
+
128
+ where $S$ is the set of sources, $T$ is the set of targets,
129
+ $\sigma(s, t)$ is the number of shortest $(s, t)$-paths,
130
+ and $\sigma(s, t|e)$ is the number of those paths
131
+ passing through edge $e$ [2]_.
132
+
133
+ Parameters
134
+ ----------
135
+ G : graph
136
+ A networkx graph.
137
+
138
+ sources: list of nodes
139
+ Nodes to use as sources for shortest paths in betweenness
140
+
141
+ targets: list of nodes
142
+ Nodes to use as targets for shortest paths in betweenness
143
+
144
+ normalized : bool, optional
145
+ If True the betweenness values are normalized by `2/(n(n-1))`
146
+ for graphs, and `1/(n(n-1))` for directed graphs where `n`
147
+ is the number of nodes in G.
148
+
149
+ weight : None or string, optional (default=None)
150
+ If None, all edge weights are considered equal.
151
+ Otherwise holds the name of the edge attribute used as weight.
152
+ Weights are used to calculate weighted shortest paths, so they are
153
+ interpreted as distances.
154
+
155
+ Returns
156
+ -------
157
+ edges : dictionary
158
+ Dictionary of edges with Betweenness centrality as the value.
159
+
160
+ See Also
161
+ --------
162
+ betweenness_centrality
163
+ edge_load
164
+
165
+ Notes
166
+ -----
167
+ The basic algorithm is from [1]_.
168
+
169
+ For weighted graphs the edge weights must be greater than zero.
170
+ Zero edge weights can produce an infinite number of equal length
171
+ paths between pairs of nodes.
172
+
173
+ The normalization might seem a little strange but it is the same
174
+ as in edge_betweenness_centrality() and is designed to make
175
+ edge_betweenness_centrality(G) be the same as
176
+ edge_betweenness_centrality_subset(G,sources=G.nodes(),targets=G.nodes()).
177
+
178
+ References
179
+ ----------
180
+ .. [1] Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
181
+ Journal of Mathematical Sociology 25(2):163-177, 2001.
182
+ https://doi.org/10.1080/0022250X.2001.9990249
183
+ .. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
184
+ Centrality and their Generic Computation.
185
+ Social Networks 30(2):136-145, 2008.
186
+ https://doi.org/10.1016/j.socnet.2007.11.001
187
+ """
188
+ b = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
189
+ b.update(dict.fromkeys(G.edges(), 0.0)) # b[e] for e in G.edges()
190
+ for s in sources:
191
+ # single source shortest paths
192
+ if weight is None: # use BFS
193
+ S, P, sigma, _ = shortest_path(G, s)
194
+ else: # use Dijkstra's algorithm
195
+ S, P, sigma, _ = dijkstra(G, s, weight)
196
+ b = _accumulate_edges_subset(b, S, P, sigma, s, targets)
197
+ for n in G: # remove nodes to only return edges
198
+ del b[n]
199
+ b = _rescale_e(b, len(G), normalized=normalized, directed=G.is_directed())
200
+ if G.is_multigraph():
201
+ b = _add_edge_keys(G, b, weight=weight)
202
+ return b
203
+
204
+
205
+ def _accumulate_subset(betweenness, S, P, sigma, s, targets):
206
+ delta = dict.fromkeys(S, 0.0)
207
+ target_set = set(targets) - {s}
208
+ while S:
209
+ w = S.pop()
210
+ if w in target_set:
211
+ coeff = (delta[w] + 1.0) / sigma[w]
212
+ else:
213
+ coeff = delta[w] / sigma[w]
214
+ for v in P[w]:
215
+ delta[v] += sigma[v] * coeff
216
+ if w != s:
217
+ betweenness[w] += delta[w]
218
+ return betweenness
219
+
220
+
221
+ def _accumulate_edges_subset(betweenness, S, P, sigma, s, targets):
222
+ """edge_betweenness_centrality_subset helper."""
223
+ delta = dict.fromkeys(S, 0)
224
+ target_set = set(targets)
225
+ while S:
226
+ w = S.pop()
227
+ for v in P[w]:
228
+ if w in target_set:
229
+ c = (sigma[v] / sigma[w]) * (1.0 + delta[w])
230
+ else:
231
+ c = delta[w] / len(P[w])
232
+ if (v, w) not in betweenness:
233
+ betweenness[(w, v)] += c
234
+ else:
235
+ betweenness[(v, w)] += c
236
+ delta[v] += c
237
+ if w != s:
238
+ betweenness[w] += delta[w]
239
+ return betweenness
240
+
241
+
242
+ def _rescale(betweenness, n, normalized, directed=False):
243
+ """betweenness_centrality_subset helper."""
244
+ if normalized:
245
+ if n <= 2:
246
+ scale = None # no normalization b=0 for all nodes
247
+ else:
248
+ scale = 1.0 / ((n - 1) * (n - 2))
249
+ else: # rescale by 2 for undirected graphs
250
+ if not directed:
251
+ scale = 0.5
252
+ else:
253
+ scale = None
254
+ if scale is not None:
255
+ for v in betweenness:
256
+ betweenness[v] *= scale
257
+ return betweenness
258
+
259
+
260
+ def _rescale_e(betweenness, n, normalized, directed=False):
261
+ """edge_betweenness_centrality_subset helper."""
262
+ if normalized:
263
+ if n <= 1:
264
+ scale = None # no normalization b=0 for all nodes
265
+ else:
266
+ scale = 1.0 / (n * (n - 1))
267
+ else: # rescale by 2 for undirected graphs
268
+ if not directed:
269
+ scale = 0.5
270
+ else:
271
+ scale = None
272
+ if scale is not None:
273
+ for v in betweenness:
274
+ betweenness[v] *= scale
275
+ return betweenness
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/closeness.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Closeness centrality measures.
3
+ """
4
+
5
+ import functools
6
+
7
+ import networkx as nx
8
+ from networkx.exception import NetworkXError
9
+ from networkx.utils.decorators import not_implemented_for
10
+
11
+ __all__ = ["closeness_centrality", "incremental_closeness_centrality"]
12
+
13
+
14
+ @nx._dispatchable(edge_attrs="distance")
15
+ def closeness_centrality(G, u=None, distance=None, wf_improved=True):
16
+ r"""Compute closeness centrality for nodes.
17
+
18
+ Closeness centrality [1]_ of a node `u` is the reciprocal of the
19
+ average shortest path distance to `u` over all `n-1` reachable nodes.
20
+
21
+ .. math::
22
+
23
+ C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
24
+
25
+ where `d(v, u)` is the shortest-path distance between `v` and `u`,
26
+ and `n-1` is the number of nodes reachable from `u`. Notice that the
27
+ closeness distance function computes the incoming distance to `u`
28
+ for directed graphs. To use outward distance, act on `G.reverse()`.
29
+
30
+ Notice that higher values of closeness indicate higher centrality.
31
+
32
+ Wasserman and Faust propose an improved formula for graphs with
33
+ more than one connected component. The result is "a ratio of the
34
+ fraction of actors in the group who are reachable, to the average
35
+ distance" from the reachable actors [2]_. You might think this
36
+ scale factor is inverted but it is not. As is, nodes from small
37
+ components receive a smaller closeness value. Letting `N` denote
38
+ the number of nodes in the graph,
39
+
40
+ .. math::
41
+
42
+ C_{WF}(u) = \frac{n-1}{N-1} \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
43
+
44
+ Parameters
45
+ ----------
46
+ G : graph
47
+ A NetworkX graph
48
+
49
+ u : node, optional
50
+ Return only the value for node u
51
+
52
+ distance : edge attribute key, optional (default=None)
53
+ Use the specified edge attribute as the edge distance in shortest
54
+ path calculations. If `None` (the default) all edges have a distance of 1.
55
+ Absent edge attributes are assigned a distance of 1. Note that no check
56
+ is performed to ensure that edges have the provided attribute.
57
+
58
+ wf_improved : bool, optional (default=True)
59
+ If True, scale by the fraction of nodes reachable. This gives the
60
+ Wasserman and Faust improved formula. For single component graphs
61
+ it is the same as the original formula.
62
+
63
+ Returns
64
+ -------
65
+ nodes : dictionary
66
+ Dictionary of nodes with closeness centrality as the value.
67
+
68
+ Examples
69
+ --------
70
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
71
+ >>> nx.closeness_centrality(G)
72
+ {0: 1.0, 1: 1.0, 2: 0.75, 3: 0.75}
73
+
74
+ See Also
75
+ --------
76
+ betweenness_centrality, load_centrality, eigenvector_centrality,
77
+ degree_centrality, incremental_closeness_centrality
78
+
79
+ Notes
80
+ -----
81
+ The closeness centrality is normalized to `(n-1)/(|G|-1)` where
82
+ `n` is the number of nodes in the connected part of graph
83
+ containing the node. If the graph is not completely connected,
84
+ this algorithm computes the closeness centrality for each
85
+ connected part separately scaled by that parts size.
86
+
87
+ If the 'distance' keyword is set to an edge attribute key then the
88
+ shortest-path length will be computed using Dijkstra's algorithm with
89
+ that edge attribute as the edge weight.
90
+
91
+ The closeness centrality uses *inward* distance to a node, not outward.
92
+ If you want to use outword distances apply the function to `G.reverse()`
93
+
94
+ In NetworkX 2.2 and earlier a bug caused Dijkstra's algorithm to use the
95
+ outward distance rather than the inward distance. If you use a 'distance'
96
+ keyword and a DiGraph, your results will change between v2.2 and v2.3.
97
+
98
+ References
99
+ ----------
100
+ .. [1] Linton C. Freeman: Centrality in networks: I.
101
+ Conceptual clarification. Social Networks 1:215-239, 1979.
102
+ https://doi.org/10.1016/0378-8733(78)90021-7
103
+ .. [2] pg. 201 of Wasserman, S. and Faust, K.,
104
+ Social Network Analysis: Methods and Applications, 1994,
105
+ Cambridge University Press.
106
+ """
107
+ if G.is_directed():
108
+ G = G.reverse() # create a reversed graph view
109
+
110
+ if distance is not None:
111
+ # use Dijkstra's algorithm with specified attribute as edge weight
112
+ path_length = functools.partial(
113
+ nx.single_source_dijkstra_path_length, weight=distance
114
+ )
115
+ else:
116
+ path_length = nx.single_source_shortest_path_length
117
+
118
+ if u is None:
119
+ nodes = G.nodes
120
+ else:
121
+ nodes = [u]
122
+ closeness_dict = {}
123
+ for n in nodes:
124
+ sp = path_length(G, n)
125
+ totsp = sum(sp.values())
126
+ len_G = len(G)
127
+ _closeness_centrality = 0.0
128
+ if totsp > 0.0 and len_G > 1:
129
+ _closeness_centrality = (len(sp) - 1.0) / totsp
130
+ # normalize to number of nodes-1 in connected part
131
+ if wf_improved:
132
+ s = (len(sp) - 1.0) / (len_G - 1)
133
+ _closeness_centrality *= s
134
+ closeness_dict[n] = _closeness_centrality
135
+ if u is not None:
136
+ return closeness_dict[u]
137
+ return closeness_dict
138
+
139
+
140
+ @not_implemented_for("directed")
141
+ @nx._dispatchable(mutates_input=True)
142
+ def incremental_closeness_centrality(
143
+ G, edge, prev_cc=None, insertion=True, wf_improved=True
144
+ ):
145
+ r"""Incremental closeness centrality for nodes.
146
+
147
+ Compute closeness centrality for nodes using level-based work filtering
148
+ as described in Incremental Algorithms for Closeness Centrality by Sariyuce et al.
149
+
150
+ Level-based work filtering detects unnecessary updates to the closeness
151
+ centrality and filters them out.
152
+
153
+ ---
154
+ From "Incremental Algorithms for Closeness Centrality":
155
+
156
+ Theorem 1: Let :math:`G = (V, E)` be a graph and u and v be two vertices in V
157
+ such that there is no edge (u, v) in E. Let :math:`G' = (V, E \cup uv)`
158
+ Then :math:`cc[s] = cc'[s]` if and only if :math:`\left|dG(s, u) - dG(s, v)\right| \leq 1`.
159
+
160
+ Where :math:`dG(u, v)` denotes the length of the shortest path between
161
+ two vertices u, v in a graph G, cc[s] is the closeness centrality for a
162
+ vertex s in V, and cc'[s] is the closeness centrality for a
163
+ vertex s in V, with the (u, v) edge added.
164
+ ---
165
+
166
+ We use Theorem 1 to filter out updates when adding or removing an edge.
167
+ When adding an edge (u, v), we compute the shortest path lengths from all
168
+ other nodes to u and to v before the node is added. When removing an edge,
169
+ we compute the shortest path lengths after the edge is removed. Then we
170
+ apply Theorem 1 to use previously computed closeness centrality for nodes
171
+ where :math:`\left|dG(s, u) - dG(s, v)\right| \leq 1`. This works only for
172
+ undirected, unweighted graphs; the distance argument is not supported.
173
+
174
+ Closeness centrality [1]_ of a node `u` is the reciprocal of the
175
+ sum of the shortest path distances from `u` to all `n-1` other nodes.
176
+ Since the sum of distances depends on the number of nodes in the
177
+ graph, closeness is normalized by the sum of minimum possible
178
+ distances `n-1`.
179
+
180
+ .. math::
181
+
182
+ C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
183
+
184
+ where `d(v, u)` is the shortest-path distance between `v` and `u`,
185
+ and `n` is the number of nodes in the graph.
186
+
187
+ Notice that higher values of closeness indicate higher centrality.
188
+
189
+ Parameters
190
+ ----------
191
+ G : graph
192
+ A NetworkX graph
193
+
194
+ edge : tuple
195
+ The modified edge (u, v) in the graph.
196
+
197
+ prev_cc : dictionary
198
+ The previous closeness centrality for all nodes in the graph.
199
+
200
+ insertion : bool, optional
201
+ If True (default) the edge was inserted, otherwise it was deleted from the graph.
202
+
203
+ wf_improved : bool, optional (default=True)
204
+ If True, scale by the fraction of nodes reachable. This gives the
205
+ Wasserman and Faust improved formula. For single component graphs
206
+ it is the same as the original formula.
207
+
208
+ Returns
209
+ -------
210
+ nodes : dictionary
211
+ Dictionary of nodes with closeness centrality as the value.
212
+
213
+ See Also
214
+ --------
215
+ betweenness_centrality, load_centrality, eigenvector_centrality,
216
+ degree_centrality, closeness_centrality
217
+
218
+ Notes
219
+ -----
220
+ The closeness centrality is normalized to `(n-1)/(|G|-1)` where
221
+ `n` is the number of nodes in the connected part of graph
222
+ containing the node. If the graph is not completely connected,
223
+ this algorithm computes the closeness centrality for each
224
+ connected part separately.
225
+
226
+ References
227
+ ----------
228
+ .. [1] Freeman, L.C., 1979. Centrality in networks: I.
229
+ Conceptual clarification. Social Networks 1, 215--239.
230
+ https://doi.org/10.1016/0378-8733(78)90021-7
231
+ .. [2] Sariyuce, A.E. ; Kaya, K. ; Saule, E. ; Catalyiirek, U.V. Incremental
232
+ Algorithms for Closeness Centrality. 2013 IEEE International Conference on Big Data
233
+ http://sariyuce.com/papers/bigdata13.pdf
234
+ """
235
+ if prev_cc is not None and set(prev_cc.keys()) != set(G.nodes()):
236
+ raise NetworkXError("prev_cc and G do not have the same nodes")
237
+
238
+ # Unpack edge
239
+ (u, v) = edge
240
+ path_length = nx.single_source_shortest_path_length
241
+
242
+ if insertion:
243
+ # For edge insertion, we want shortest paths before the edge is inserted
244
+ du = path_length(G, u)
245
+ dv = path_length(G, v)
246
+
247
+ G.add_edge(u, v)
248
+ else:
249
+ G.remove_edge(u, v)
250
+
251
+ # For edge removal, we want shortest paths after the edge is removed
252
+ du = path_length(G, u)
253
+ dv = path_length(G, v)
254
+
255
+ if prev_cc is None:
256
+ return nx.closeness_centrality(G)
257
+
258
+ nodes = G.nodes()
259
+ closeness_dict = {}
260
+ for n in nodes:
261
+ if n in du and n in dv and abs(du[n] - dv[n]) <= 1:
262
+ closeness_dict[n] = prev_cc[n]
263
+ else:
264
+ sp = path_length(G, n)
265
+ totsp = sum(sp.values())
266
+ len_G = len(G)
267
+ _closeness_centrality = 0.0
268
+ if totsp > 0.0 and len_G > 1:
269
+ _closeness_centrality = (len(sp) - 1.0) / totsp
270
+ # normalize to number of nodes-1 in connected part
271
+ if wf_improved:
272
+ s = (len(sp) - 1.0) / (len_G - 1)
273
+ _closeness_centrality *= s
274
+ closeness_dict[n] = _closeness_centrality
275
+
276
+ # Leave the graph as we found it
277
+ if insertion:
278
+ G.remove_edge(u, v)
279
+ else:
280
+ G.add_edge(u, v)
281
+
282
+ return closeness_dict
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/current_flow_betweenness.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Current-flow betweenness centrality measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.centrality.flow_matrix import (
5
+ CGInverseLaplacian,
6
+ FullInverseLaplacian,
7
+ SuperLUInverseLaplacian,
8
+ flow_matrix_row,
9
+ )
10
+ from networkx.utils import (
11
+ not_implemented_for,
12
+ py_random_state,
13
+ reverse_cuthill_mckee_ordering,
14
+ )
15
+
16
+ __all__ = [
17
+ "current_flow_betweenness_centrality",
18
+ "approximate_current_flow_betweenness_centrality",
19
+ "edge_current_flow_betweenness_centrality",
20
+ ]
21
+
22
+
23
+ @not_implemented_for("directed")
24
+ @py_random_state(7)
25
+ @nx._dispatchable(edge_attrs="weight")
26
+ def approximate_current_flow_betweenness_centrality(
27
+ G,
28
+ normalized=True,
29
+ weight=None,
30
+ dtype=float,
31
+ solver="full",
32
+ epsilon=0.5,
33
+ kmax=10000,
34
+ seed=None,
35
+ ):
36
+ r"""Compute the approximate current-flow betweenness centrality for nodes.
37
+
38
+ Approximates the current-flow betweenness centrality within absolute
39
+ error of epsilon with high probability [1]_.
40
+
41
+
42
+ Parameters
43
+ ----------
44
+ G : graph
45
+ A NetworkX graph
46
+
47
+ normalized : bool, optional (default=True)
48
+ If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
49
+ n is the number of nodes in G.
50
+
51
+ weight : string or None, optional (default=None)
52
+ Key for edge data used as the edge weight.
53
+ If None, then use 1 as each edge weight.
54
+ The weight reflects the capacity or the strength of the
55
+ edge.
56
+
57
+ dtype : data type (float)
58
+ Default data type for internal matrices.
59
+ Set to np.float32 for lower memory consumption.
60
+
61
+ solver : string (default='full')
62
+ Type of linear solver to use for computing the flow matrix.
63
+ Options are "full" (uses most memory), "lu" (recommended), and
64
+ "cg" (uses least memory).
65
+
66
+ epsilon: float
67
+ Absolute error tolerance.
68
+
69
+ kmax: int
70
+ Maximum number of sample node pairs to use for approximation.
71
+
72
+ seed : integer, random_state, or None (default)
73
+ Indicator of random number generation state.
74
+ See :ref:`Randomness<randomness>`.
75
+
76
+ Returns
77
+ -------
78
+ nodes : dictionary
79
+ Dictionary of nodes with betweenness centrality as the value.
80
+
81
+ See Also
82
+ --------
83
+ current_flow_betweenness_centrality
84
+
85
+ Notes
86
+ -----
87
+ The running time is $O((1/\epsilon^2)m{\sqrt k} \log n)$
88
+ and the space required is $O(m)$ for $n$ nodes and $m$ edges.
89
+
90
+ If the edges have a 'weight' attribute they will be used as
91
+ weights in this algorithm. Unspecified weights are set to 1.
92
+
93
+ References
94
+ ----------
95
+ .. [1] Ulrik Brandes and Daniel Fleischer:
96
+ Centrality Measures Based on Current Flow.
97
+ Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
98
+ LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
99
+ https://doi.org/10.1007/978-3-540-31856-9_44
100
+ """
101
+ import numpy as np
102
+
103
+ if not nx.is_connected(G):
104
+ raise nx.NetworkXError("Graph not connected.")
105
+ solvername = {
106
+ "full": FullInverseLaplacian,
107
+ "lu": SuperLUInverseLaplacian,
108
+ "cg": CGInverseLaplacian,
109
+ }
110
+ n = G.number_of_nodes()
111
+ ordering = list(reverse_cuthill_mckee_ordering(G))
112
+ # make a copy with integer labels according to rcm ordering
113
+ # this could be done without a copy if we really wanted to
114
+ H = nx.relabel_nodes(G, dict(zip(ordering, range(n))))
115
+ L = nx.laplacian_matrix(H, nodelist=range(n), weight=weight).asformat("csc")
116
+ L = L.astype(dtype)
117
+ C = solvername[solver](L, dtype=dtype) # initialize solver
118
+ betweenness = dict.fromkeys(H, 0.0)
119
+ nb = (n - 1.0) * (n - 2.0) # normalization factor
120
+ cstar = n * (n - 1) / nb
121
+ l = 1 # parameter in approximation, adjustable
122
+ k = l * int(np.ceil((cstar / epsilon) ** 2 * np.log(n)))
123
+ if k > kmax:
124
+ msg = f"Number random pairs k>kmax ({k}>{kmax}) "
125
+ raise nx.NetworkXError(msg, "Increase kmax or epsilon")
126
+ cstar2k = cstar / (2 * k)
127
+ for _ in range(k):
128
+ s, t = pair = seed.sample(range(n), 2)
129
+ b = np.zeros(n, dtype=dtype)
130
+ b[s] = 1
131
+ b[t] = -1
132
+ p = C.solve(b)
133
+ for v in H:
134
+ if v in pair:
135
+ continue
136
+ for nbr in H[v]:
137
+ w = H[v][nbr].get(weight, 1.0)
138
+ betweenness[v] += float(w * np.abs(p[v] - p[nbr]) * cstar2k)
139
+ if normalized:
140
+ factor = 1.0
141
+ else:
142
+ factor = nb / 2.0
143
+ # remap to original node names and "unnormalize" if required
144
+ return {ordering[k]: v * factor for k, v in betweenness.items()}
145
+
146
+
147
+ @not_implemented_for("directed")
148
+ @nx._dispatchable(edge_attrs="weight")
149
+ def current_flow_betweenness_centrality(
150
+ G, normalized=True, weight=None, dtype=float, solver="full"
151
+ ):
152
+ r"""Compute current-flow betweenness centrality for nodes.
153
+
154
+ Current-flow betweenness centrality uses an electrical current
155
+ model for information spreading in contrast to betweenness
156
+ centrality which uses shortest paths.
157
+
158
+ Current-flow betweenness centrality is also known as
159
+ random-walk betweenness centrality [2]_.
160
+
161
+ Parameters
162
+ ----------
163
+ G : graph
164
+ A NetworkX graph
165
+
166
+ normalized : bool, optional (default=True)
167
+ If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
168
+ n is the number of nodes in G.
169
+
170
+ weight : string or None, optional (default=None)
171
+ Key for edge data used as the edge weight.
172
+ If None, then use 1 as each edge weight.
173
+ The weight reflects the capacity or the strength of the
174
+ edge.
175
+
176
+ dtype : data type (float)
177
+ Default data type for internal matrices.
178
+ Set to np.float32 for lower memory consumption.
179
+
180
+ solver : string (default='full')
181
+ Type of linear solver to use for computing the flow matrix.
182
+ Options are "full" (uses most memory), "lu" (recommended), and
183
+ "cg" (uses least memory).
184
+
185
+ Returns
186
+ -------
187
+ nodes : dictionary
188
+ Dictionary of nodes with betweenness centrality as the value.
189
+
190
+ See Also
191
+ --------
192
+ approximate_current_flow_betweenness_centrality
193
+ betweenness_centrality
194
+ edge_betweenness_centrality
195
+ edge_current_flow_betweenness_centrality
196
+
197
+ Notes
198
+ -----
199
+ Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
200
+ time [1]_, where $I(n-1)$ is the time needed to compute the
201
+ inverse Laplacian. For a full matrix this is $O(n^3)$ but using
202
+ sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
203
+ Laplacian matrix condition number.
204
+
205
+ The space required is $O(nw)$ where $w$ is the width of the sparse
206
+ Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
207
+
208
+ If the edges have a 'weight' attribute they will be used as
209
+ weights in this algorithm. Unspecified weights are set to 1.
210
+
211
+ References
212
+ ----------
213
+ .. [1] Centrality Measures Based on Current Flow.
214
+ Ulrik Brandes and Daniel Fleischer,
215
+ Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
216
+ LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
217
+ https://doi.org/10.1007/978-3-540-31856-9_44
218
+
219
+ .. [2] A measure of betweenness centrality based on random walks,
220
+ M. E. J. Newman, Social Networks 27, 39-54 (2005).
221
+ """
222
+ if not nx.is_connected(G):
223
+ raise nx.NetworkXError("Graph not connected.")
224
+ N = G.number_of_nodes()
225
+ ordering = list(reverse_cuthill_mckee_ordering(G))
226
+ # make a copy with integer labels according to rcm ordering
227
+ # this could be done without a copy if we really wanted to
228
+ H = nx.relabel_nodes(G, dict(zip(ordering, range(N))))
229
+ betweenness = dict.fromkeys(H, 0.0) # b[n]=0 for n in H
230
+ for row, (s, t) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
231
+ pos = dict(zip(row.argsort()[::-1], range(N)))
232
+ for i in range(N):
233
+ betweenness[s] += (i - pos[i]) * row.item(i)
234
+ betweenness[t] += (N - i - 1 - pos[i]) * row.item(i)
235
+ if normalized:
236
+ nb = (N - 1.0) * (N - 2.0) # normalization factor
237
+ else:
238
+ nb = 2.0
239
+ return {ordering[n]: (b - n) * 2.0 / nb for n, b in betweenness.items()}
240
+
241
+
242
+ @not_implemented_for("directed")
243
+ @nx._dispatchable(edge_attrs="weight")
244
+ def edge_current_flow_betweenness_centrality(
245
+ G, normalized=True, weight=None, dtype=float, solver="full"
246
+ ):
247
+ r"""Compute current-flow betweenness centrality for edges.
248
+
249
+ Current-flow betweenness centrality uses an electrical current
250
+ model for information spreading in contrast to betweenness
251
+ centrality which uses shortest paths.
252
+
253
+ Current-flow betweenness centrality is also known as
254
+ random-walk betweenness centrality [2]_.
255
+
256
+ Parameters
257
+ ----------
258
+ G : graph
259
+ A NetworkX graph
260
+
261
+ normalized : bool, optional (default=True)
262
+ If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
263
+ n is the number of nodes in G.
264
+
265
+ weight : string or None, optional (default=None)
266
+ Key for edge data used as the edge weight.
267
+ If None, then use 1 as each edge weight.
268
+ The weight reflects the capacity or the strength of the
269
+ edge.
270
+
271
+ dtype : data type (default=float)
272
+ Default data type for internal matrices.
273
+ Set to np.float32 for lower memory consumption.
274
+
275
+ solver : string (default='full')
276
+ Type of linear solver to use for computing the flow matrix.
277
+ Options are "full" (uses most memory), "lu" (recommended), and
278
+ "cg" (uses least memory).
279
+
280
+ Returns
281
+ -------
282
+ nodes : dictionary
283
+ Dictionary of edge tuples with betweenness centrality as the value.
284
+
285
+ Raises
286
+ ------
287
+ NetworkXError
288
+ The algorithm does not support DiGraphs.
289
+ If the input graph is an instance of DiGraph class, NetworkXError
290
+ is raised.
291
+
292
+ See Also
293
+ --------
294
+ betweenness_centrality
295
+ edge_betweenness_centrality
296
+ current_flow_betweenness_centrality
297
+
298
+ Notes
299
+ -----
300
+ Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
301
+ time [1]_, where $I(n-1)$ is the time needed to compute the
302
+ inverse Laplacian. For a full matrix this is $O(n^3)$ but using
303
+ sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
304
+ Laplacian matrix condition number.
305
+
306
+ The space required is $O(nw)$ where $w$ is the width of the sparse
307
+ Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
308
+
309
+ If the edges have a 'weight' attribute they will be used as
310
+ weights in this algorithm. Unspecified weights are set to 1.
311
+
312
+ References
313
+ ----------
314
+ .. [1] Centrality Measures Based on Current Flow.
315
+ Ulrik Brandes and Daniel Fleischer,
316
+ Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
317
+ LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
318
+ https://doi.org/10.1007/978-3-540-31856-9_44
319
+
320
+ .. [2] A measure of betweenness centrality based on random walks,
321
+ M. E. J. Newman, Social Networks 27, 39-54 (2005).
322
+ """
323
+ if not nx.is_connected(G):
324
+ raise nx.NetworkXError("Graph not connected.")
325
+ N = G.number_of_nodes()
326
+ ordering = list(reverse_cuthill_mckee_ordering(G))
327
+ # make a copy with integer labels according to rcm ordering
328
+ # this could be done without a copy if we really wanted to
329
+ H = nx.relabel_nodes(G, dict(zip(ordering, range(N))))
330
+ edges = (tuple(sorted((u, v))) for u, v in H.edges())
331
+ betweenness = dict.fromkeys(edges, 0.0)
332
+ if normalized:
333
+ nb = (N - 1.0) * (N - 2.0) # normalization factor
334
+ else:
335
+ nb = 2.0
336
+ for row, (e) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
337
+ pos = dict(zip(row.argsort()[::-1], range(1, N + 1)))
338
+ for i in range(N):
339
+ betweenness[e] += (i + 1 - pos[i]) * row.item(i)
340
+ betweenness[e] += (N - i - pos[i]) * row.item(i)
341
+ betweenness[e] /= nb
342
+ return {(ordering[s], ordering[t]): b for (s, t), b in betweenness.items()}
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/current_flow_betweenness_subset.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Current-flow betweenness centrality measures for subsets of nodes."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.centrality.flow_matrix import flow_matrix_row
5
+ from networkx.utils import not_implemented_for, reverse_cuthill_mckee_ordering
6
+
7
+ __all__ = [
8
+ "current_flow_betweenness_centrality_subset",
9
+ "edge_current_flow_betweenness_centrality_subset",
10
+ ]
11
+
12
+
13
+ @not_implemented_for("directed")
14
+ @nx._dispatchable(edge_attrs="weight")
15
+ def current_flow_betweenness_centrality_subset(
16
+ G, sources, targets, normalized=True, weight=None, dtype=float, solver="lu"
17
+ ):
18
+ r"""Compute current-flow betweenness centrality for subsets of nodes.
19
+
20
+ Current-flow betweenness centrality uses an electrical current
21
+ model for information spreading in contrast to betweenness
22
+ centrality which uses shortest paths.
23
+
24
+ Current-flow betweenness centrality is also known as
25
+ random-walk betweenness centrality [2]_.
26
+
27
+ Parameters
28
+ ----------
29
+ G : graph
30
+ A NetworkX graph
31
+
32
+ sources: list of nodes
33
+ Nodes to use as sources for current
34
+
35
+ targets: list of nodes
36
+ Nodes to use as sinks for current
37
+
38
+ normalized : bool, optional (default=True)
39
+ If True the betweenness values are normalized by b=b/(n-1)(n-2) where
40
+ n is the number of nodes in G.
41
+
42
+ weight : string or None, optional (default=None)
43
+ Key for edge data used as the edge weight.
44
+ If None, then use 1 as each edge weight.
45
+ The weight reflects the capacity or the strength of the
46
+ edge.
47
+
48
+ dtype: data type (float)
49
+ Default data type for internal matrices.
50
+ Set to np.float32 for lower memory consumption.
51
+
52
+ solver: string (default='lu')
53
+ Type of linear solver to use for computing the flow matrix.
54
+ Options are "full" (uses most memory), "lu" (recommended), and
55
+ "cg" (uses least memory).
56
+
57
+ Returns
58
+ -------
59
+ nodes : dictionary
60
+ Dictionary of nodes with betweenness centrality as the value.
61
+
62
+ See Also
63
+ --------
64
+ approximate_current_flow_betweenness_centrality
65
+ betweenness_centrality
66
+ edge_betweenness_centrality
67
+ edge_current_flow_betweenness_centrality
68
+
69
+ Notes
70
+ -----
71
+ Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
72
+ time [1]_, where $I(n-1)$ is the time needed to compute the
73
+ inverse Laplacian. For a full matrix this is $O(n^3)$ but using
74
+ sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
75
+ Laplacian matrix condition number.
76
+
77
+ The space required is $O(nw)$ where $w$ is the width of the sparse
78
+ Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
79
+
80
+ If the edges have a 'weight' attribute they will be used as
81
+ weights in this algorithm. Unspecified weights are set to 1.
82
+
83
+ References
84
+ ----------
85
+ .. [1] Centrality Measures Based on Current Flow.
86
+ Ulrik Brandes and Daniel Fleischer,
87
+ Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
88
+ LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
89
+ https://doi.org/10.1007/978-3-540-31856-9_44
90
+
91
+ .. [2] A measure of betweenness centrality based on random walks,
92
+ M. E. J. Newman, Social Networks 27, 39-54 (2005).
93
+ """
94
+ import numpy as np
95
+
96
+ from networkx.utils import reverse_cuthill_mckee_ordering
97
+
98
+ if not nx.is_connected(G):
99
+ raise nx.NetworkXError("Graph not connected.")
100
+ N = G.number_of_nodes()
101
+ ordering = list(reverse_cuthill_mckee_ordering(G))
102
+ # make a copy with integer labels according to rcm ordering
103
+ # this could be done without a copy if we really wanted to
104
+ mapping = dict(zip(ordering, range(N)))
105
+ H = nx.relabel_nodes(G, mapping)
106
+ betweenness = dict.fromkeys(H, 0.0) # b[n]=0 for n in H
107
+ for row, (s, t) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
108
+ for ss in sources:
109
+ i = mapping[ss]
110
+ for tt in targets:
111
+ j = mapping[tt]
112
+ betweenness[s] += 0.5 * abs(row.item(i) - row.item(j))
113
+ betweenness[t] += 0.5 * abs(row.item(i) - row.item(j))
114
+ if normalized:
115
+ nb = (N - 1.0) * (N - 2.0) # normalization factor
116
+ else:
117
+ nb = 2.0
118
+ for node in H:
119
+ betweenness[node] = betweenness[node] / nb + 1.0 / (2 - N)
120
+ return {ordering[node]: value for node, value in betweenness.items()}
121
+
122
+
123
+ @not_implemented_for("directed")
124
+ @nx._dispatchable(edge_attrs="weight")
125
+ def edge_current_flow_betweenness_centrality_subset(
126
+ G, sources, targets, normalized=True, weight=None, dtype=float, solver="lu"
127
+ ):
128
+ r"""Compute current-flow betweenness centrality for edges using subsets
129
+ of nodes.
130
+
131
+ Current-flow betweenness centrality uses an electrical current
132
+ model for information spreading in contrast to betweenness
133
+ centrality which uses shortest paths.
134
+
135
+ Current-flow betweenness centrality is also known as
136
+ random-walk betweenness centrality [2]_.
137
+
138
+ Parameters
139
+ ----------
140
+ G : graph
141
+ A NetworkX graph
142
+
143
+ sources: list of nodes
144
+ Nodes to use as sources for current
145
+
146
+ targets: list of nodes
147
+ Nodes to use as sinks for current
148
+
149
+ normalized : bool, optional (default=True)
150
+ If True the betweenness values are normalized by b=b/(n-1)(n-2) where
151
+ n is the number of nodes in G.
152
+
153
+ weight : string or None, optional (default=None)
154
+ Key for edge data used as the edge weight.
155
+ If None, then use 1 as each edge weight.
156
+ The weight reflects the capacity or the strength of the
157
+ edge.
158
+
159
+ dtype: data type (float)
160
+ Default data type for internal matrices.
161
+ Set to np.float32 for lower memory consumption.
162
+
163
+ solver: string (default='lu')
164
+ Type of linear solver to use for computing the flow matrix.
165
+ Options are "full" (uses most memory), "lu" (recommended), and
166
+ "cg" (uses least memory).
167
+
168
+ Returns
169
+ -------
170
+ nodes : dict
171
+ Dictionary of edge tuples with betweenness centrality as the value.
172
+
173
+ See Also
174
+ --------
175
+ betweenness_centrality
176
+ edge_betweenness_centrality
177
+ current_flow_betweenness_centrality
178
+
179
+ Notes
180
+ -----
181
+ Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
182
+ time [1]_, where $I(n-1)$ is the time needed to compute the
183
+ inverse Laplacian. For a full matrix this is $O(n^3)$ but using
184
+ sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
185
+ Laplacian matrix condition number.
186
+
187
+ The space required is $O(nw)$ where $w$ is the width of the sparse
188
+ Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
189
+
190
+ If the edges have a 'weight' attribute they will be used as
191
+ weights in this algorithm. Unspecified weights are set to 1.
192
+
193
+ References
194
+ ----------
195
+ .. [1] Centrality Measures Based on Current Flow.
196
+ Ulrik Brandes and Daniel Fleischer,
197
+ Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
198
+ LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
199
+ https://doi.org/10.1007/978-3-540-31856-9_44
200
+
201
+ .. [2] A measure of betweenness centrality based on random walks,
202
+ M. E. J. Newman, Social Networks 27, 39-54 (2005).
203
+ """
204
+ import numpy as np
205
+
206
+ if not nx.is_connected(G):
207
+ raise nx.NetworkXError("Graph not connected.")
208
+ N = G.number_of_nodes()
209
+ ordering = list(reverse_cuthill_mckee_ordering(G))
210
+ # make a copy with integer labels according to rcm ordering
211
+ # this could be done without a copy if we really wanted to
212
+ mapping = dict(zip(ordering, range(N)))
213
+ H = nx.relabel_nodes(G, mapping)
214
+ edges = (tuple(sorted((u, v))) for u, v in H.edges())
215
+ betweenness = dict.fromkeys(edges, 0.0)
216
+ if normalized:
217
+ nb = (N - 1.0) * (N - 2.0) # normalization factor
218
+ else:
219
+ nb = 2.0
220
+ for row, (e) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
221
+ for ss in sources:
222
+ i = mapping[ss]
223
+ for tt in targets:
224
+ j = mapping[tt]
225
+ betweenness[e] += 0.5 * abs(row.item(i) - row.item(j))
226
+ betweenness[e] /= nb
227
+ return {(ordering[s], ordering[t]): value for (s, t), value in betweenness.items()}
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/current_flow_closeness.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Current-flow closeness centrality measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.centrality.flow_matrix import (
5
+ CGInverseLaplacian,
6
+ FullInverseLaplacian,
7
+ SuperLUInverseLaplacian,
8
+ )
9
+ from networkx.utils import not_implemented_for, reverse_cuthill_mckee_ordering
10
+
11
+ __all__ = ["current_flow_closeness_centrality", "information_centrality"]
12
+
13
+
14
+ @not_implemented_for("directed")
15
+ @nx._dispatchable(edge_attrs="weight")
16
+ def current_flow_closeness_centrality(G, weight=None, dtype=float, solver="lu"):
17
+ """Compute current-flow closeness centrality for nodes.
18
+
19
+ Current-flow closeness centrality is variant of closeness
20
+ centrality based on effective resistance between nodes in
21
+ a network. This metric is also known as information centrality.
22
+
23
+ Parameters
24
+ ----------
25
+ G : graph
26
+ A NetworkX graph.
27
+
28
+ weight : None or string, optional (default=None)
29
+ If None, all edge weights are considered equal.
30
+ Otherwise holds the name of the edge attribute used as weight.
31
+ The weight reflects the capacity or the strength of the
32
+ edge.
33
+
34
+ dtype: data type (default=float)
35
+ Default data type for internal matrices.
36
+ Set to np.float32 for lower memory consumption.
37
+
38
+ solver: string (default='lu')
39
+ Type of linear solver to use for computing the flow matrix.
40
+ Options are "full" (uses most memory), "lu" (recommended), and
41
+ "cg" (uses least memory).
42
+
43
+ Returns
44
+ -------
45
+ nodes : dictionary
46
+ Dictionary of nodes with current flow closeness centrality as the value.
47
+
48
+ See Also
49
+ --------
50
+ closeness_centrality
51
+
52
+ Notes
53
+ -----
54
+ The algorithm is from Brandes [1]_.
55
+
56
+ See also [2]_ for the original definition of information centrality.
57
+
58
+ References
59
+ ----------
60
+ .. [1] Ulrik Brandes and Daniel Fleischer,
61
+ Centrality Measures Based on Current Flow.
62
+ Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
63
+ LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
64
+ https://doi.org/10.1007/978-3-540-31856-9_44
65
+
66
+ .. [2] Karen Stephenson and Marvin Zelen:
67
+ Rethinking centrality: Methods and examples.
68
+ Social Networks 11(1):1-37, 1989.
69
+ https://doi.org/10.1016/0378-8733(89)90016-6
70
+ """
71
+ if not nx.is_connected(G):
72
+ raise nx.NetworkXError("Graph not connected.")
73
+ solvername = {
74
+ "full": FullInverseLaplacian,
75
+ "lu": SuperLUInverseLaplacian,
76
+ "cg": CGInverseLaplacian,
77
+ }
78
+ N = G.number_of_nodes()
79
+ ordering = list(reverse_cuthill_mckee_ordering(G))
80
+ # make a copy with integer labels according to rcm ordering
81
+ # this could be done without a copy if we really wanted to
82
+ H = nx.relabel_nodes(G, dict(zip(ordering, range(N))))
83
+ betweenness = dict.fromkeys(H, 0.0) # b[n]=0 for n in H
84
+ N = H.number_of_nodes()
85
+ L = nx.laplacian_matrix(H, nodelist=range(N), weight=weight).asformat("csc")
86
+ L = L.astype(dtype)
87
+ C2 = solvername[solver](L, width=1, dtype=dtype) # initialize solver
88
+ for v in H:
89
+ col = C2.get_row(v)
90
+ for w in H:
91
+ betweenness[v] += col.item(v) - 2 * col.item(w)
92
+ betweenness[w] += col.item(v)
93
+ return {ordering[node]: 1 / value for node, value in betweenness.items()}
94
+
95
+
96
+ information_centrality = current_flow_closeness_centrality
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/degree_alg.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Degree centrality measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import not_implemented_for
5
+
6
+ __all__ = ["degree_centrality", "in_degree_centrality", "out_degree_centrality"]
7
+
8
+
9
+ @nx._dispatchable
10
+ def degree_centrality(G):
11
+ """Compute the degree centrality for nodes.
12
+
13
+ The degree centrality for a node v is the fraction of nodes it
14
+ is connected to.
15
+
16
+ Parameters
17
+ ----------
18
+ G : graph
19
+ A networkx graph
20
+
21
+ Returns
22
+ -------
23
+ nodes : dictionary
24
+ Dictionary of nodes with degree centrality as the value.
25
+
26
+ Examples
27
+ --------
28
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
29
+ >>> nx.degree_centrality(G)
30
+ {0: 1.0, 1: 1.0, 2: 0.6666666666666666, 3: 0.6666666666666666}
31
+
32
+ See Also
33
+ --------
34
+ betweenness_centrality, load_centrality, eigenvector_centrality
35
+
36
+ Notes
37
+ -----
38
+ The degree centrality values are normalized by dividing by the maximum
39
+ possible degree in a simple graph n-1 where n is the number of nodes in G.
40
+
41
+ For multigraphs or graphs with self loops the maximum degree might
42
+ be higher than n-1 and values of degree centrality greater than 1
43
+ are possible.
44
+ """
45
+ if len(G) <= 1:
46
+ return {n: 1 for n in G}
47
+
48
+ s = 1.0 / (len(G) - 1.0)
49
+ centrality = {n: d * s for n, d in G.degree()}
50
+ return centrality
51
+
52
+
53
+ @not_implemented_for("undirected")
54
+ @nx._dispatchable
55
+ def in_degree_centrality(G):
56
+ """Compute the in-degree centrality for nodes.
57
+
58
+ The in-degree centrality for a node v is the fraction of nodes its
59
+ incoming edges are connected to.
60
+
61
+ Parameters
62
+ ----------
63
+ G : graph
64
+ A NetworkX graph
65
+
66
+ Returns
67
+ -------
68
+ nodes : dictionary
69
+ Dictionary of nodes with in-degree centrality as values.
70
+
71
+ Raises
72
+ ------
73
+ NetworkXNotImplemented
74
+ If G is undirected.
75
+
76
+ Examples
77
+ --------
78
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
79
+ >>> nx.in_degree_centrality(G)
80
+ {0: 0.0, 1: 0.3333333333333333, 2: 0.6666666666666666, 3: 0.6666666666666666}
81
+
82
+ See Also
83
+ --------
84
+ degree_centrality, out_degree_centrality
85
+
86
+ Notes
87
+ -----
88
+ The degree centrality values are normalized by dividing by the maximum
89
+ possible degree in a simple graph n-1 where n is the number of nodes in G.
90
+
91
+ For multigraphs or graphs with self loops the maximum degree might
92
+ be higher than n-1 and values of degree centrality greater than 1
93
+ are possible.
94
+ """
95
+ if len(G) <= 1:
96
+ return {n: 1 for n in G}
97
+
98
+ s = 1.0 / (len(G) - 1.0)
99
+ centrality = {n: d * s for n, d in G.in_degree()}
100
+ return centrality
101
+
102
+
103
+ @not_implemented_for("undirected")
104
+ @nx._dispatchable
105
+ def out_degree_centrality(G):
106
+ """Compute the out-degree centrality for nodes.
107
+
108
+ The out-degree centrality for a node v is the fraction of nodes its
109
+ outgoing edges are connected to.
110
+
111
+ Parameters
112
+ ----------
113
+ G : graph
114
+ A NetworkX graph
115
+
116
+ Returns
117
+ -------
118
+ nodes : dictionary
119
+ Dictionary of nodes with out-degree centrality as values.
120
+
121
+ Raises
122
+ ------
123
+ NetworkXNotImplemented
124
+ If G is undirected.
125
+
126
+ Examples
127
+ --------
128
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
129
+ >>> nx.out_degree_centrality(G)
130
+ {0: 1.0, 1: 0.6666666666666666, 2: 0.0, 3: 0.0}
131
+
132
+ See Also
133
+ --------
134
+ degree_centrality, in_degree_centrality
135
+
136
+ Notes
137
+ -----
138
+ The degree centrality values are normalized by dividing by the maximum
139
+ possible degree in a simple graph n-1 where n is the number of nodes in G.
140
+
141
+ For multigraphs or graphs with self loops the maximum degree might
142
+ be higher than n-1 and values of degree centrality greater than 1
143
+ are possible.
144
+ """
145
+ if len(G) <= 1:
146
+ return {n: 1 for n in G}
147
+
148
+ s = 1.0 / (len(G) - 1.0)
149
+ centrality = {n: d * s for n, d in G.out_degree()}
150
+ return centrality
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/dispersion.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["dispersion"]
6
+
7
+
8
+ @nx._dispatchable
9
+ def dispersion(G, u=None, v=None, normalized=True, alpha=1.0, b=0.0, c=0.0):
10
+ r"""Calculate dispersion between `u` and `v` in `G`.
11
+
12
+ A link between two actors (`u` and `v`) has a high dispersion when their
13
+ mutual ties (`s` and `t`) are not well connected with each other.
14
+
15
+ Parameters
16
+ ----------
17
+ G : graph
18
+ A NetworkX graph.
19
+ u : node, optional
20
+ The source for the dispersion score (e.g. ego node of the network).
21
+ v : node, optional
22
+ The target of the dispersion score if specified.
23
+ normalized : bool
24
+ If True (default) normalize by the embeddedness of the nodes (u and v).
25
+ alpha, b, c : float
26
+ Parameters for the normalization procedure. When `normalized` is True,
27
+ the dispersion value is normalized by::
28
+
29
+ result = ((dispersion + b) ** alpha) / (embeddedness + c)
30
+
31
+ as long as the denominator is nonzero.
32
+
33
+ Returns
34
+ -------
35
+ nodes : dictionary
36
+ If u (v) is specified, returns a dictionary of nodes with dispersion
37
+ score for all "target" ("source") nodes. If neither u nor v is
38
+ specified, returns a dictionary of dictionaries for all nodes 'u' in the
39
+ graph with a dispersion score for each node 'v'.
40
+
41
+ Notes
42
+ -----
43
+ This implementation follows Lars Backstrom and Jon Kleinberg [1]_. Typical
44
+ usage would be to run dispersion on the ego network $G_u$ if $u$ were
45
+ specified. Running :func:`dispersion` with neither $u$ nor $v$ specified
46
+ can take some time to complete.
47
+
48
+ References
49
+ ----------
50
+ .. [1] Romantic Partnerships and the Dispersion of Social Ties:
51
+ A Network Analysis of Relationship Status on Facebook.
52
+ Lars Backstrom, Jon Kleinberg.
53
+ https://arxiv.org/pdf/1310.6753v1.pdf
54
+
55
+ """
56
+
57
+ def _dispersion(G_u, u, v):
58
+ """dispersion for all nodes 'v' in a ego network G_u of node 'u'"""
59
+ u_nbrs = set(G_u[u])
60
+ ST = {n for n in G_u[v] if n in u_nbrs}
61
+ set_uv = {u, v}
62
+ # all possible ties of connections that u and b share
63
+ possib = combinations(ST, 2)
64
+ total = 0
65
+ for s, t in possib:
66
+ # neighbors of s that are in G_u, not including u and v
67
+ nbrs_s = u_nbrs.intersection(G_u[s]) - set_uv
68
+ # s and t are not directly connected
69
+ if t not in nbrs_s:
70
+ # s and t do not share a connection
71
+ if nbrs_s.isdisjoint(G_u[t]):
72
+ # tick for disp(u, v)
73
+ total += 1
74
+ # neighbors that u and v share
75
+ embeddedness = len(ST)
76
+
77
+ dispersion_val = total
78
+ if normalized:
79
+ dispersion_val = (total + b) ** alpha
80
+ if embeddedness + c != 0:
81
+ dispersion_val /= embeddedness + c
82
+
83
+ return dispersion_val
84
+
85
+ if u is None:
86
+ # v and u are not specified
87
+ if v is None:
88
+ results = {n: {} for n in G}
89
+ for u in G:
90
+ for v in G[u]:
91
+ results[u][v] = _dispersion(G, u, v)
92
+ # u is not specified, but v is
93
+ else:
94
+ results = dict.fromkeys(G[v], {})
95
+ for u in G[v]:
96
+ results[u] = _dispersion(G, v, u)
97
+ else:
98
+ # u is specified with no target v
99
+ if v is None:
100
+ results = dict.fromkeys(G[u], {})
101
+ for v in G[u]:
102
+ results[v] = _dispersion(G, u, v)
103
+ # both u and v are specified
104
+ else:
105
+ results = _dispersion(G, u, v)
106
+
107
+ return results
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/eigenvector.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing eigenvector centrality."""
2
+
3
+ import math
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = ["eigenvector_centrality", "eigenvector_centrality_numpy"]
9
+
10
+
11
+ @not_implemented_for("multigraph")
12
+ @nx._dispatchable(edge_attrs="weight")
13
+ def eigenvector_centrality(G, max_iter=100, tol=1.0e-6, nstart=None, weight=None):
14
+ r"""Compute the eigenvector centrality for the graph G.
15
+
16
+ Eigenvector centrality computes the centrality for a node by adding
17
+ the centrality of its predecessors. The centrality for node $i$ is the
18
+ $i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
19
+ of maximum modulus that is positive. Such an eigenvector $x$ is
20
+ defined up to a multiplicative constant by the equation
21
+
22
+ .. math::
23
+
24
+ \lambda x^T = x^T A,
25
+
26
+ where $A$ is the adjacency matrix of the graph G. By definition of
27
+ row-column product, the equation above is equivalent to
28
+
29
+ .. math::
30
+
31
+ \lambda x_i = \sum_{j\to i}x_j.
32
+
33
+ That is, adding the eigenvector centralities of the predecessors of
34
+ $i$ one obtains the eigenvector centrality of $i$ multiplied by
35
+ $\lambda$. In the case of undirected graphs, $x$ also solves the familiar
36
+ right-eigenvector equation $Ax = \lambda x$.
37
+
38
+ By virtue of the Perron–Frobenius theorem [1]_, if G is strongly
39
+ connected there is a unique eigenvector $x$, and all its entries
40
+ are strictly positive.
41
+
42
+ If G is not strongly connected there might be several left
43
+ eigenvectors associated with $\lambda$, and some of their elements
44
+ might be zero.
45
+
46
+ Parameters
47
+ ----------
48
+ G : graph
49
+ A networkx graph.
50
+
51
+ max_iter : integer, optional (default=100)
52
+ Maximum number of power iterations.
53
+
54
+ tol : float, optional (default=1.0e-6)
55
+ Error tolerance (in Euclidean norm) used to check convergence in
56
+ power iteration.
57
+
58
+ nstart : dictionary, optional (default=None)
59
+ Starting value of power iteration for each node. Must have a nonzero
60
+ projection on the desired eigenvector for the power method to converge.
61
+ If None, this implementation uses an all-ones vector, which is a safe
62
+ choice.
63
+
64
+ weight : None or string, optional (default=None)
65
+ If None, all edge weights are considered equal. Otherwise holds the
66
+ name of the edge attribute used as weight. In this measure the
67
+ weight is interpreted as the connection strength.
68
+
69
+ Returns
70
+ -------
71
+ nodes : dictionary
72
+ Dictionary of nodes with eigenvector centrality as the value. The
73
+ associated vector has unit Euclidean norm and the values are
74
+ nonegative.
75
+
76
+ Examples
77
+ --------
78
+ >>> G = nx.path_graph(4)
79
+ >>> centrality = nx.eigenvector_centrality(G)
80
+ >>> sorted((v, f"{c:0.2f}") for v, c in centrality.items())
81
+ [(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
82
+
83
+ Raises
84
+ ------
85
+ NetworkXPointlessConcept
86
+ If the graph G is the null graph.
87
+
88
+ NetworkXError
89
+ If each value in `nstart` is zero.
90
+
91
+ PowerIterationFailedConvergence
92
+ If the algorithm fails to converge to the specified tolerance
93
+ within the specified number of iterations of the power iteration
94
+ method.
95
+
96
+ See Also
97
+ --------
98
+ eigenvector_centrality_numpy
99
+ :func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
100
+ :func:`~networkx.algorithms.link_analysis.hits_alg.hits`
101
+
102
+ Notes
103
+ -----
104
+ Eigenvector centrality was introduced by Landau [2]_ for chess
105
+ tournaments. It was later rediscovered by Wei [3]_ and then
106
+ popularized by Kendall [4]_ in the context of sport ranking. Berge
107
+ introduced a general definition for graphs based on social connections
108
+ [5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
109
+ it popular in link analysis.
110
+
111
+ This function computes the left dominant eigenvector, which corresponds
112
+ to adding the centrality of predecessors: this is the usual approach.
113
+ To add the centrality of successors first reverse the graph with
114
+ ``G.reverse()``.
115
+
116
+ The implementation uses power iteration [7]_ to compute a dominant
117
+ eigenvector starting from the provided vector `nstart`. Convergence is
118
+ guaranteed as long as `nstart` has a nonzero projection on a dominant
119
+ eigenvector, which certainly happens using the default value.
120
+
121
+ The method stops when the change in the computed vector between two
122
+ iterations is smaller than an error tolerance of ``G.number_of_nodes()
123
+ * tol`` or after ``max_iter`` iterations, but in the second case it
124
+ raises an exception.
125
+
126
+ This implementation uses $(A + I)$ rather than the adjacency matrix
127
+ $A$ because the change preserves eigenvectors, but it shifts the
128
+ spectrum, thus guaranteeing convergence even for networks with
129
+ negative eigenvalues of maximum modulus.
130
+
131
+ References
132
+ ----------
133
+ .. [1] Abraham Berman and Robert J. Plemmons.
134
+ "Nonnegative Matrices in the Mathematical Sciences."
135
+ Classics in Applied Mathematics. SIAM, 1994.
136
+
137
+ .. [2] Edmund Landau.
138
+ "Zur relativen Wertbemessung der Turnierresultate."
139
+ Deutsches Wochenschach, 11:366–369, 1895.
140
+
141
+ .. [3] Teh-Hsing Wei.
142
+ "The Algebraic Foundations of Ranking Theory."
143
+ PhD thesis, University of Cambridge, 1952.
144
+
145
+ .. [4] Maurice G. Kendall.
146
+ "Further contributions to the theory of paired comparisons."
147
+ Biometrics, 11(1):43–62, 1955.
148
+ https://www.jstor.org/stable/3001479
149
+
150
+ .. [5] Claude Berge
151
+ "Théorie des graphes et ses applications."
152
+ Dunod, Paris, France, 1958.
153
+
154
+ .. [6] Phillip Bonacich.
155
+ "Technique for analyzing overlapping memberships."
156
+ Sociological Methodology, 4:176–185, 1972.
157
+ https://www.jstor.org/stable/270732
158
+
159
+ .. [7] Power iteration:: https://en.wikipedia.org/wiki/Power_iteration
160
+
161
+ """
162
+ if len(G) == 0:
163
+ raise nx.NetworkXPointlessConcept(
164
+ "cannot compute centrality for the null graph"
165
+ )
166
+ # If no initial vector is provided, start with the all-ones vector.
167
+ if nstart is None:
168
+ nstart = {v: 1 for v in G}
169
+ if all(v == 0 for v in nstart.values()):
170
+ raise nx.NetworkXError("initial vector cannot have all zero values")
171
+ # Normalize the initial vector so that each entry is in [0, 1]. This is
172
+ # guaranteed to never have a divide-by-zero error by the previous line.
173
+ nstart_sum = sum(nstart.values())
174
+ x = {k: v / nstart_sum for k, v in nstart.items()}
175
+ nnodes = G.number_of_nodes()
176
+ # make up to max_iter iterations
177
+ for _ in range(max_iter):
178
+ xlast = x
179
+ x = xlast.copy() # Start with xlast times I to iterate with (A+I)
180
+ # do the multiplication y^T = x^T A (left eigenvector)
181
+ for n in x:
182
+ for nbr in G[n]:
183
+ w = G[n][nbr].get(weight, 1) if weight else 1
184
+ x[nbr] += xlast[n] * w
185
+ # Normalize the vector. The normalization denominator `norm`
186
+ # should never be zero by the Perron--Frobenius
187
+ # theorem. However, in case it is due to numerical error, we
188
+ # assume the norm to be one instead.
189
+ norm = math.hypot(*x.values()) or 1
190
+ x = {k: v / norm for k, v in x.items()}
191
+ # Check for convergence (in the L_1 norm).
192
+ if sum(abs(x[n] - xlast[n]) for n in x) < nnodes * tol:
193
+ return x
194
+ raise nx.PowerIterationFailedConvergence(max_iter)
195
+
196
+
197
+ @nx._dispatchable(edge_attrs="weight")
198
+ def eigenvector_centrality_numpy(G, weight=None, max_iter=50, tol=0):
199
+ r"""Compute the eigenvector centrality for the graph `G`.
200
+
201
+ Eigenvector centrality computes the centrality for a node by adding
202
+ the centrality of its predecessors. The centrality for node $i$ is the
203
+ $i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
204
+ of maximum modulus that is positive. Such an eigenvector $x$ is
205
+ defined up to a multiplicative constant by the equation
206
+
207
+ .. math::
208
+
209
+ \lambda x^T = x^T A,
210
+
211
+ where $A$ is the adjacency matrix of the graph `G`. By definition of
212
+ row-column product, the equation above is equivalent to
213
+
214
+ .. math::
215
+
216
+ \lambda x_i = \sum_{j\to i}x_j.
217
+
218
+ That is, adding the eigenvector centralities of the predecessors of
219
+ $i$ one obtains the eigenvector centrality of $i$ multiplied by
220
+ $\lambda$. In the case of undirected graphs, $x$ also solves the familiar
221
+ right-eigenvector equation $Ax = \lambda x$.
222
+
223
+ By virtue of the Perron--Frobenius theorem [1]_, if `G` is (strongly)
224
+ connected, there is a unique eigenvector $x$, and all its entries
225
+ are strictly positive.
226
+
227
+ However, if `G` is not (strongly) connected, there might be several left
228
+ eigenvectors associated with $\lambda$, and some of their elements
229
+ might be zero.
230
+ Depending on the method used to choose eigenvectors, round-off error can affect
231
+ which of the infinitely many eigenvectors is reported.
232
+ This can lead to inconsistent results for the same graph,
233
+ which the underlying implementation is not robust to.
234
+ For this reason, only (strongly) connected graphs are accepted.
235
+
236
+ Parameters
237
+ ----------
238
+ G : graph
239
+ A connected NetworkX graph.
240
+
241
+ weight : None or string, optional (default=None)
242
+ If ``None``, all edge weights are considered equal. Otherwise holds the
243
+ name of the edge attribute used as weight. In this measure the
244
+ weight is interpreted as the connection strength.
245
+
246
+ max_iter : integer, optional (default=50)
247
+ Maximum number of Arnoldi update iterations allowed.
248
+
249
+ tol : float, optional (default=0)
250
+ Relative accuracy for eigenvalues (stopping criterion).
251
+ The default value of 0 implies machine precision.
252
+
253
+ Returns
254
+ -------
255
+ nodes : dict of nodes
256
+ Dictionary of nodes with eigenvector centrality as the value. The
257
+ associated vector has unit Euclidean norm and the values are
258
+ nonnegative.
259
+
260
+ Examples
261
+ --------
262
+ >>> G = nx.path_graph(4)
263
+ >>> centrality = nx.eigenvector_centrality_numpy(G)
264
+ >>> print([f"{node} {centrality[node]:0.2f}" for node in centrality])
265
+ ['0 0.37', '1 0.60', '2 0.60', '3 0.37']
266
+
267
+ Raises
268
+ ------
269
+ NetworkXPointlessConcept
270
+ If the graph `G` is the null graph.
271
+
272
+ ArpackNoConvergence
273
+ When the requested convergence is not obtained. The currently
274
+ converged eigenvalues and eigenvectors can be found as
275
+ eigenvalues and eigenvectors attributes of the exception object.
276
+
277
+ AmbiguousSolution
278
+ If `G` is not connected.
279
+
280
+ See Also
281
+ --------
282
+ :func:`scipy.sparse.linalg.eigs`
283
+ eigenvector_centrality
284
+ :func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
285
+ :func:`~networkx.algorithms.link_analysis.hits_alg.hits`
286
+
287
+ Notes
288
+ -----
289
+ Eigenvector centrality was introduced by Landau [2]_ for chess
290
+ tournaments. It was later rediscovered by Wei [3]_ and then
291
+ popularized by Kendall [4]_ in the context of sport ranking. Berge
292
+ introduced a general definition for graphs based on social connections
293
+ [5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
294
+ it popular in link analysis.
295
+
296
+ This function computes the left dominant eigenvector, which corresponds
297
+ to adding the centrality of predecessors: this is the usual approach.
298
+ To add the centrality of successors first reverse the graph with
299
+ ``G.reverse()``.
300
+
301
+ This implementation uses the
302
+ :func:`SciPy sparse eigenvalue solver<scipy.sparse.linalg.eigs>` (ARPACK)
303
+ to find the largest eigenvalue/eigenvector pair using Arnoldi iterations
304
+ [7]_.
305
+
306
+ References
307
+ ----------
308
+ .. [1] Abraham Berman and Robert J. Plemmons.
309
+ "Nonnegative Matrices in the Mathematical Sciences".
310
+ Classics in Applied Mathematics. SIAM, 1994.
311
+
312
+ .. [2] Edmund Landau.
313
+ "Zur relativen Wertbemessung der Turnierresultate".
314
+ Deutsches Wochenschach, 11:366--369, 1895.
315
+
316
+ .. [3] Teh-Hsing Wei.
317
+ "The Algebraic Foundations of Ranking Theory".
318
+ PhD thesis, University of Cambridge, 1952.
319
+
320
+ .. [4] Maurice G. Kendall.
321
+ "Further contributions to the theory of paired comparisons".
322
+ Biometrics, 11(1):43--62, 1955.
323
+ https://www.jstor.org/stable/3001479
324
+
325
+ .. [5] Claude Berge.
326
+ "Théorie des graphes et ses applications".
327
+ Dunod, Paris, France, 1958.
328
+
329
+ .. [6] Phillip Bonacich.
330
+ "Technique for analyzing overlapping memberships".
331
+ Sociological Methodology, 4:176--185, 1972.
332
+ https://www.jstor.org/stable/270732
333
+
334
+ .. [7] Arnoldi, W. E. (1951).
335
+ "The principle of minimized iterations in the solution of the matrix eigenvalue problem".
336
+ Quarterly of Applied Mathematics. 9 (1): 17--29.
337
+ https://doi.org/10.1090/qam/42792
338
+ """
339
+ import numpy as np
340
+ import scipy as sp
341
+
342
+ if len(G) == 0:
343
+ raise nx.NetworkXPointlessConcept(
344
+ "cannot compute centrality for the null graph"
345
+ )
346
+ connected = nx.is_strongly_connected(G) if G.is_directed() else nx.is_connected(G)
347
+ if not connected: # See gh-6888.
348
+ raise nx.AmbiguousSolution(
349
+ "`eigenvector_centrality_numpy` does not give consistent results for disconnected graphs"
350
+ )
351
+ M = nx.to_scipy_sparse_array(G, nodelist=list(G), weight=weight, dtype=float)
352
+ _, eigenvector = sp.sparse.linalg.eigs(
353
+ M.T, k=1, which="LR", maxiter=max_iter, tol=tol
354
+ )
355
+ largest = eigenvector.flatten().real
356
+ norm = np.sign(largest.sum()) * sp.linalg.norm(largest)
357
+ return dict(zip(G, (largest / norm).tolist()))
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/flow_matrix.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Helpers for current-flow betweenness and current-flow closeness
2
+ # Lazy computations for inverse Laplacian and flow-matrix rows.
3
+ import networkx as nx
4
+
5
+
6
+ @nx._dispatchable(edge_attrs="weight")
7
+ def flow_matrix_row(G, weight=None, dtype=float, solver="lu"):
8
+ # Generate a row of the current-flow matrix
9
+ import numpy as np
10
+
11
+ solvername = {
12
+ "full": FullInverseLaplacian,
13
+ "lu": SuperLUInverseLaplacian,
14
+ "cg": CGInverseLaplacian,
15
+ }
16
+ n = G.number_of_nodes()
17
+ L = nx.laplacian_matrix(G, nodelist=range(n), weight=weight).asformat("csc")
18
+ L = L.astype(dtype)
19
+ C = solvername[solver](L, dtype=dtype) # initialize solver
20
+ w = C.w # w is the Laplacian matrix width
21
+ # row-by-row flow matrix
22
+ for u, v in sorted(sorted((u, v)) for u, v in G.edges()):
23
+ B = np.zeros(w, dtype=dtype)
24
+ c = G[u][v].get(weight, 1.0)
25
+ B[u % w] = c
26
+ B[v % w] = -c
27
+ # get only the rows needed in the inverse laplacian
28
+ # and multiply to get the flow matrix row
29
+ row = B @ C.get_rows(u, v)
30
+ yield row, (u, v)
31
+
32
+
33
+ # Class to compute the inverse laplacian only for specified rows
34
+ # Allows computation of the current-flow matrix without storing entire
35
+ # inverse laplacian matrix
36
+ class InverseLaplacian:
37
+ def __init__(self, L, width=None, dtype=None):
38
+ global np
39
+ import numpy as np
40
+
41
+ (n, n) = L.shape
42
+ self.dtype = dtype
43
+ self.n = n
44
+ if width is None:
45
+ self.w = self.width(L)
46
+ else:
47
+ self.w = width
48
+ self.C = np.zeros((self.w, n), dtype=dtype)
49
+ self.L1 = L[1:, 1:]
50
+ self.init_solver(L)
51
+
52
+ def init_solver(self, L):
53
+ pass
54
+
55
+ def solve(self, r):
56
+ raise nx.NetworkXError("Implement solver")
57
+
58
+ def solve_inverse(self, r):
59
+ raise nx.NetworkXError("Implement solver")
60
+
61
+ def get_rows(self, r1, r2):
62
+ for r in range(r1, r2 + 1):
63
+ self.C[r % self.w, 1:] = self.solve_inverse(r)
64
+ return self.C
65
+
66
+ def get_row(self, r):
67
+ self.C[r % self.w, 1:] = self.solve_inverse(r)
68
+ return self.C[r % self.w]
69
+
70
+ def width(self, L):
71
+ m = 0
72
+ for i, row in enumerate(L):
73
+ w = 0
74
+ y = np.nonzero(row)[-1]
75
+ if len(y) > 0:
76
+ v = y - i
77
+ w = v.max() - v.min() + 1
78
+ m = max(w, m)
79
+ return m
80
+
81
+
82
+ class FullInverseLaplacian(InverseLaplacian):
83
+ def init_solver(self, L):
84
+ self.IL = np.zeros(L.shape, dtype=self.dtype)
85
+ self.IL[1:, 1:] = np.linalg.inv(self.L1.todense())
86
+
87
+ def solve(self, rhs):
88
+ s = np.zeros(rhs.shape, dtype=self.dtype)
89
+ s = self.IL @ rhs
90
+ return s
91
+
92
+ def solve_inverse(self, r):
93
+ return self.IL[r, 1:]
94
+
95
+
96
+ class SuperLUInverseLaplacian(InverseLaplacian):
97
+ def init_solver(self, L):
98
+ import scipy as sp
99
+
100
+ self.lusolve = sp.sparse.linalg.factorized(self.L1.tocsc())
101
+
102
+ def solve_inverse(self, r):
103
+ rhs = np.zeros(self.n, dtype=self.dtype)
104
+ rhs[r] = 1
105
+ return self.lusolve(rhs[1:])
106
+
107
+ def solve(self, rhs):
108
+ s = np.zeros(rhs.shape, dtype=self.dtype)
109
+ s[1:] = self.lusolve(rhs[1:])
110
+ return s
111
+
112
+
113
+ class CGInverseLaplacian(InverseLaplacian):
114
+ def init_solver(self, L):
115
+ global sp
116
+ import scipy as sp
117
+
118
+ ilu = sp.sparse.linalg.spilu(self.L1.tocsc())
119
+ n = self.n - 1
120
+ self.M = sp.sparse.linalg.LinearOperator(shape=(n, n), matvec=ilu.solve)
121
+
122
+ def solve(self, rhs):
123
+ s = np.zeros(rhs.shape, dtype=self.dtype)
124
+ s[1:] = sp.sparse.linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0]
125
+ return s
126
+
127
+ def solve_inverse(self, r):
128
+ rhs = np.zeros(self.n, self.dtype)
129
+ rhs[r] = 1
130
+ return sp.sparse.linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0]
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/group.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Group centrality measures."""
2
+
3
+ from copy import deepcopy
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.centrality.betweenness import (
7
+ _accumulate_endpoints,
8
+ _single_source_dijkstra_path_basic,
9
+ _single_source_shortest_path_basic,
10
+ )
11
+ from networkx.utils.decorators import not_implemented_for
12
+
13
+ __all__ = [
14
+ "group_betweenness_centrality",
15
+ "group_closeness_centrality",
16
+ "group_degree_centrality",
17
+ "group_in_degree_centrality",
18
+ "group_out_degree_centrality",
19
+ "prominent_group",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(edge_attrs="weight")
24
+ def group_betweenness_centrality(G, C, normalized=True, weight=None, endpoints=False):
25
+ r"""Compute the group betweenness centrality for a group of nodes.
26
+
27
+ Group betweenness centrality of a group of nodes $C$ is the sum of the
28
+ fraction of all-pairs shortest paths that pass through any vertex in $C$
29
+
30
+ .. math::
31
+
32
+ c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
33
+
34
+ where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
35
+ shortest $(s, t)$-paths, and $\sigma(s, t|C)$ is the number of
36
+ those paths passing through some node in group $C$. Note that
37
+ $(s, t)$ are not members of the group ($V-C$ is the set of nodes
38
+ in $V$ that are not in $C$).
39
+
40
+ Parameters
41
+ ----------
42
+ G : graph
43
+ A NetworkX graph.
44
+
45
+ C : list or set or list of lists or list of sets
46
+ A group or a list of groups containing nodes which belong to G, for which group betweenness
47
+ centrality is to be calculated.
48
+
49
+ normalized : bool, optional (default=True)
50
+ If True, group betweenness is normalized by `1/((|V|-|C|)(|V|-|C|-1))`
51
+ where `|V|` is the number of nodes in G and `|C|` is the number of nodes in C.
52
+
53
+ weight : None or string, optional (default=None)
54
+ If None, all edge weights are considered equal.
55
+ Otherwise holds the name of the edge attribute used as weight.
56
+ The weight of an edge is treated as the length or distance between the two sides.
57
+
58
+ endpoints : bool, optional (default=False)
59
+ If True include the endpoints in the shortest path counts.
60
+
61
+ Raises
62
+ ------
63
+ NodeNotFound
64
+ If node(s) in C are not present in G.
65
+
66
+ Returns
67
+ -------
68
+ betweenness : list of floats or float
69
+ If C is a single group then return a float. If C is a list with
70
+ several groups then return a list of group betweenness centralities.
71
+
72
+ See Also
73
+ --------
74
+ betweenness_centrality
75
+
76
+ Notes
77
+ -----
78
+ Group betweenness centrality is described in [1]_ and its importance discussed in [3]_.
79
+ The initial implementation of the algorithm is mentioned in [2]_. This function uses
80
+ an improved algorithm presented in [4]_.
81
+
82
+ The number of nodes in the group must be a maximum of n - 2 where `n`
83
+ is the total number of nodes in the graph.
84
+
85
+ For weighted graphs the edge weights must be greater than zero.
86
+ Zero edge weights can produce an infinite number of equal length
87
+ paths between pairs of nodes.
88
+
89
+ The total number of paths between source and target is counted
90
+ differently for directed and undirected graphs. Directed paths
91
+ between "u" and "v" are counted as two possible paths (one each
92
+ direction) while undirected paths between "u" and "v" are counted
93
+ as one path. Said another way, the sum in the expression above is
94
+ over all ``s != t`` for directed graphs and for ``s < t`` for undirected graphs.
95
+
96
+
97
+ References
98
+ ----------
99
+ .. [1] M G Everett and S P Borgatti:
100
+ The Centrality of Groups and Classes.
101
+ Journal of Mathematical Sociology. 23(3): 181-201. 1999.
102
+ http://www.analytictech.com/borgatti/group_centrality.htm
103
+ .. [2] Ulrik Brandes:
104
+ On Variants of Shortest-Path Betweenness
105
+ Centrality and their Generic Computation.
106
+ Social Networks 30(2):136-145, 2008.
107
+ http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.9610&rep=rep1&type=pdf
108
+ .. [3] Sourav Medya et. al.:
109
+ Group Centrality Maximization via Network Design.
110
+ SIAM International Conference on Data Mining, SDM 2018, 126–134.
111
+ https://sites.cs.ucsb.edu/~arlei/pubs/sdm18.pdf
112
+ .. [4] Rami Puzis, Yuval Elovici, and Shlomi Dolev.
113
+ "Fast algorithm for successive computation of group betweenness centrality."
114
+ https://journals.aps.org/pre/pdf/10.1103/PhysRevE.76.056709
115
+
116
+ """
117
+ GBC = [] # initialize betweenness
118
+ list_of_groups = True
119
+ # check weather C contains one or many groups
120
+ if any(el in G for el in C):
121
+ C = [C]
122
+ list_of_groups = False
123
+ set_v = {node for group in C for node in group}
124
+ if set_v - G.nodes: # element(s) of C not in G
125
+ raise nx.NodeNotFound(f"The node(s) {set_v - G.nodes} are in C but not in G.")
126
+
127
+ # pre-processing
128
+ PB, sigma, D = _group_preprocessing(G, set_v, weight)
129
+
130
+ # the algorithm for each group
131
+ for group in C:
132
+ group = set(group) # set of nodes in group
133
+ # initialize the matrices of the sigma and the PB
134
+ GBC_group = 0
135
+ sigma_m = deepcopy(sigma)
136
+ PB_m = deepcopy(PB)
137
+ sigma_m_v = deepcopy(sigma_m)
138
+ PB_m_v = deepcopy(PB_m)
139
+ for v in group:
140
+ GBC_group += PB_m[v][v]
141
+ for x in group:
142
+ for y in group:
143
+ dxvy = 0
144
+ dxyv = 0
145
+ dvxy = 0
146
+ if not (
147
+ sigma_m[x][y] == 0 or sigma_m[x][v] == 0 or sigma_m[v][y] == 0
148
+ ):
149
+ if D[x][v] == D[x][y] + D[y][v]:
150
+ dxyv = sigma_m[x][y] * sigma_m[y][v] / sigma_m[x][v]
151
+ if D[x][y] == D[x][v] + D[v][y]:
152
+ dxvy = sigma_m[x][v] * sigma_m[v][y] / sigma_m[x][y]
153
+ if D[v][y] == D[v][x] + D[x][y]:
154
+ dvxy = sigma_m[v][x] * sigma[x][y] / sigma[v][y]
155
+ sigma_m_v[x][y] = sigma_m[x][y] * (1 - dxvy)
156
+ PB_m_v[x][y] = PB_m[x][y] - PB_m[x][y] * dxvy
157
+ if y != v:
158
+ PB_m_v[x][y] -= PB_m[x][v] * dxyv
159
+ if x != v:
160
+ PB_m_v[x][y] -= PB_m[v][y] * dvxy
161
+ sigma_m, sigma_m_v = sigma_m_v, sigma_m
162
+ PB_m, PB_m_v = PB_m_v, PB_m
163
+
164
+ # endpoints
165
+ v, c = len(G), len(group)
166
+ if not endpoints:
167
+ scale = 0
168
+ # if the graph is connected then subtract the endpoints from
169
+ # the count for all the nodes in the graph. else count how many
170
+ # nodes are connected to the group's nodes and subtract that.
171
+ if nx.is_directed(G):
172
+ if nx.is_strongly_connected(G):
173
+ scale = c * (2 * v - c - 1)
174
+ elif nx.is_connected(G):
175
+ scale = c * (2 * v - c - 1)
176
+ if scale == 0:
177
+ for group_node1 in group:
178
+ for node in D[group_node1]:
179
+ if node != group_node1:
180
+ if node in group:
181
+ scale += 1
182
+ else:
183
+ scale += 2
184
+ GBC_group -= scale
185
+
186
+ # normalized
187
+ if normalized:
188
+ scale = 1 / ((v - c) * (v - c - 1))
189
+ GBC_group *= scale
190
+
191
+ # If undirected than count only the undirected edges
192
+ elif not G.is_directed():
193
+ GBC_group /= 2
194
+
195
+ GBC.append(GBC_group)
196
+ if list_of_groups:
197
+ return GBC
198
+ return GBC[0]
199
+
200
+
201
+ def _group_preprocessing(G, set_v, weight):
202
+ sigma = {}
203
+ delta = {}
204
+ D = {}
205
+ betweenness = dict.fromkeys(G, 0)
206
+ for s in G:
207
+ if weight is None: # use BFS
208
+ S, P, sigma[s], D[s] = _single_source_shortest_path_basic(G, s)
209
+ else: # use Dijkstra's algorithm
210
+ S, P, sigma[s], D[s] = _single_source_dijkstra_path_basic(G, s, weight)
211
+ betweenness, delta[s] = _accumulate_endpoints(betweenness, S, P, sigma[s], s)
212
+ for i in delta[s]: # add the paths from s to i and rescale sigma
213
+ if s != i:
214
+ delta[s][i] += 1
215
+ if weight is not None:
216
+ sigma[s][i] = sigma[s][i] / 2
217
+ # building the path betweenness matrix only for nodes that appear in the group
218
+ PB = dict.fromkeys(G)
219
+ for group_node1 in set_v:
220
+ PB[group_node1] = dict.fromkeys(G, 0.0)
221
+ for group_node2 in set_v:
222
+ if group_node2 not in D[group_node1]:
223
+ continue
224
+ for node in G:
225
+ # if node is connected to the two group nodes than continue
226
+ if group_node2 in D[node] and group_node1 in D[node]:
227
+ if (
228
+ D[node][group_node2]
229
+ == D[node][group_node1] + D[group_node1][group_node2]
230
+ ):
231
+ PB[group_node1][group_node2] += (
232
+ delta[node][group_node2]
233
+ * sigma[node][group_node1]
234
+ * sigma[group_node1][group_node2]
235
+ / sigma[node][group_node2]
236
+ )
237
+ return PB, sigma, D
238
+
239
+
240
+ @nx._dispatchable(edge_attrs="weight")
241
+ def prominent_group(
242
+ G, k, weight=None, C=None, endpoints=False, normalized=True, greedy=False
243
+ ):
244
+ r"""Find the prominent group of size $k$ in graph $G$. The prominence of the
245
+ group is evaluated by the group betweenness centrality.
246
+
247
+ Group betweenness centrality of a group of nodes $C$ is the sum of the
248
+ fraction of all-pairs shortest paths that pass through any vertex in $C$
249
+
250
+ .. math::
251
+
252
+ c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
253
+
254
+ where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
255
+ shortest $(s, t)$-paths, and $\sigma(s, t|C)$ is the number of
256
+ those paths passing through some node in group $C$. Note that
257
+ $(s, t)$ are not members of the group ($V-C$ is the set of nodes
258
+ in $V$ that are not in $C$).
259
+
260
+ Parameters
261
+ ----------
262
+ G : graph
263
+ A NetworkX graph.
264
+
265
+ k : int
266
+ The number of nodes in the group.
267
+
268
+ normalized : bool, optional (default=True)
269
+ If True, group betweenness is normalized by ``1/((|V|-|C|)(|V|-|C|-1))``
270
+ where ``|V|`` is the number of nodes in G and ``|C|`` is the number of
271
+ nodes in C.
272
+
273
+ weight : None or string, optional (default=None)
274
+ If None, all edge weights are considered equal.
275
+ Otherwise holds the name of the edge attribute used as weight.
276
+ The weight of an edge is treated as the length or distance between the two sides.
277
+
278
+ endpoints : bool, optional (default=False)
279
+ If True include the endpoints in the shortest path counts.
280
+
281
+ C : list or set, optional (default=None)
282
+ list of nodes which won't be candidates of the prominent group.
283
+
284
+ greedy : bool, optional (default=False)
285
+ Using a naive greedy algorithm in order to find non-optimal prominent
286
+ group. For scale free networks the results are negligibly below the optimal
287
+ results.
288
+
289
+ Raises
290
+ ------
291
+ NodeNotFound
292
+ If node(s) in C are not present in G.
293
+
294
+ Returns
295
+ -------
296
+ max_GBC : float
297
+ The group betweenness centrality of the prominent group.
298
+
299
+ max_group : list
300
+ The list of nodes in the prominent group.
301
+
302
+ See Also
303
+ --------
304
+ betweenness_centrality, group_betweenness_centrality
305
+
306
+ Notes
307
+ -----
308
+ Group betweenness centrality is described in [1]_ and its importance discussed in [3]_.
309
+ The algorithm is described in [2]_ and is based on techniques mentioned in [4]_.
310
+
311
+ The number of nodes in the group must be a maximum of ``n - 2`` where ``n``
312
+ is the total number of nodes in the graph.
313
+
314
+ For weighted graphs the edge weights must be greater than zero.
315
+ Zero edge weights can produce an infinite number of equal length
316
+ paths between pairs of nodes.
317
+
318
+ The total number of paths between source and target is counted
319
+ differently for directed and undirected graphs. Directed paths
320
+ between "u" and "v" are counted as two possible paths (one each
321
+ direction) while undirected paths between "u" and "v" are counted
322
+ as one path. Said another way, the sum in the expression above is
323
+ over all ``s != t`` for directed graphs and for ``s < t`` for undirected graphs.
324
+
325
+ References
326
+ ----------
327
+ .. [1] M G Everett and S P Borgatti:
328
+ The Centrality of Groups and Classes.
329
+ Journal of Mathematical Sociology. 23(3): 181-201. 1999.
330
+ http://www.analytictech.com/borgatti/group_centrality.htm
331
+ .. [2] Rami Puzis, Yuval Elovici, and Shlomi Dolev:
332
+ "Finding the Most Prominent Group in Complex Networks"
333
+ AI communications 20(4): 287-296, 2007.
334
+ https://www.researchgate.net/profile/Rami_Puzis2/publication/220308855
335
+ .. [3] Sourav Medya et. al.:
336
+ Group Centrality Maximization via Network Design.
337
+ SIAM International Conference on Data Mining, SDM 2018, 126–134.
338
+ https://sites.cs.ucsb.edu/~arlei/pubs/sdm18.pdf
339
+ .. [4] Rami Puzis, Yuval Elovici, and Shlomi Dolev.
340
+ "Fast algorithm for successive computation of group betweenness centrality."
341
+ https://journals.aps.org/pre/pdf/10.1103/PhysRevE.76.056709
342
+ """
343
+ import numpy as np
344
+ import pandas as pd
345
+
346
+ if C is not None:
347
+ C = set(C)
348
+ if C - G.nodes: # element(s) of C not in G
349
+ raise nx.NodeNotFound(f"The node(s) {C - G.nodes} are in C but not in G.")
350
+ nodes = list(G.nodes - C)
351
+ else:
352
+ nodes = list(G.nodes)
353
+ DF_tree = nx.Graph()
354
+ DF_tree.__networkx_cache__ = None # Disable caching
355
+ PB, sigma, D = _group_preprocessing(G, nodes, weight)
356
+ betweenness = pd.DataFrame.from_dict(PB)
357
+ if C is not None:
358
+ for node in C:
359
+ # remove from the betweenness all the nodes not part of the group
360
+ betweenness.drop(index=node, inplace=True)
361
+ betweenness.drop(columns=node, inplace=True)
362
+ CL = [node for _, node in sorted(zip(np.diag(betweenness), nodes), reverse=True)]
363
+ max_GBC = 0
364
+ max_group = []
365
+ DF_tree.add_node(
366
+ 1,
367
+ CL=CL,
368
+ betweenness=betweenness,
369
+ GBC=0,
370
+ GM=[],
371
+ sigma=sigma,
372
+ cont=dict(zip(nodes, np.diag(betweenness))),
373
+ )
374
+
375
+ # the algorithm
376
+ DF_tree.nodes[1]["heu"] = 0
377
+ for i in range(k):
378
+ DF_tree.nodes[1]["heu"] += DF_tree.nodes[1]["cont"][DF_tree.nodes[1]["CL"][i]]
379
+ max_GBC, DF_tree, max_group = _dfbnb(
380
+ G, k, DF_tree, max_GBC, 1, D, max_group, nodes, greedy
381
+ )
382
+
383
+ v = len(G)
384
+ if not endpoints:
385
+ scale = 0
386
+ # if the graph is connected then subtract the endpoints from
387
+ # the count for all the nodes in the graph. else count how many
388
+ # nodes are connected to the group's nodes and subtract that.
389
+ if nx.is_directed(G):
390
+ if nx.is_strongly_connected(G):
391
+ scale = k * (2 * v - k - 1)
392
+ elif nx.is_connected(G):
393
+ scale = k * (2 * v - k - 1)
394
+ if scale == 0:
395
+ for group_node1 in max_group:
396
+ for node in D[group_node1]:
397
+ if node != group_node1:
398
+ if node in max_group:
399
+ scale += 1
400
+ else:
401
+ scale += 2
402
+ max_GBC -= scale
403
+
404
+ # normalized
405
+ if normalized:
406
+ scale = 1 / ((v - k) * (v - k - 1))
407
+ max_GBC *= scale
408
+
409
+ # If undirected then count only the undirected edges
410
+ elif not G.is_directed():
411
+ max_GBC /= 2
412
+ max_GBC = float(f"{max_GBC:.2f}")
413
+ return max_GBC, max_group
414
+
415
+
416
+ def _dfbnb(G, k, DF_tree, max_GBC, root, D, max_group, nodes, greedy):
417
+ # stopping condition - if we found a group of size k and with higher GBC then prune
418
+ if len(DF_tree.nodes[root]["GM"]) == k and DF_tree.nodes[root]["GBC"] > max_GBC:
419
+ return DF_tree.nodes[root]["GBC"], DF_tree, DF_tree.nodes[root]["GM"]
420
+ # stopping condition - if the size of group members equal to k or there are less than
421
+ # k - |GM| in the candidate list or the heuristic function plus the GBC is below the
422
+ # maximal GBC found then prune
423
+ if (
424
+ len(DF_tree.nodes[root]["GM"]) == k
425
+ or len(DF_tree.nodes[root]["CL"]) <= k - len(DF_tree.nodes[root]["GM"])
426
+ or DF_tree.nodes[root]["GBC"] + DF_tree.nodes[root]["heu"] <= max_GBC
427
+ ):
428
+ return max_GBC, DF_tree, max_group
429
+
430
+ # finding the heuristic of both children
431
+ node_p, node_m, DF_tree = _heuristic(k, root, DF_tree, D, nodes, greedy)
432
+
433
+ # finding the child with the bigger heuristic + GBC and expand
434
+ # that node first if greedy then only expand the plus node
435
+ if greedy:
436
+ max_GBC, DF_tree, max_group = _dfbnb(
437
+ G, k, DF_tree, max_GBC, node_p, D, max_group, nodes, greedy
438
+ )
439
+
440
+ elif (
441
+ DF_tree.nodes[node_p]["GBC"] + DF_tree.nodes[node_p]["heu"]
442
+ > DF_tree.nodes[node_m]["GBC"] + DF_tree.nodes[node_m]["heu"]
443
+ ):
444
+ max_GBC, DF_tree, max_group = _dfbnb(
445
+ G, k, DF_tree, max_GBC, node_p, D, max_group, nodes, greedy
446
+ )
447
+ max_GBC, DF_tree, max_group = _dfbnb(
448
+ G, k, DF_tree, max_GBC, node_m, D, max_group, nodes, greedy
449
+ )
450
+ else:
451
+ max_GBC, DF_tree, max_group = _dfbnb(
452
+ G, k, DF_tree, max_GBC, node_m, D, max_group, nodes, greedy
453
+ )
454
+ max_GBC, DF_tree, max_group = _dfbnb(
455
+ G, k, DF_tree, max_GBC, node_p, D, max_group, nodes, greedy
456
+ )
457
+ return max_GBC, DF_tree, max_group
458
+
459
+
460
+ def _heuristic(k, root, DF_tree, D, nodes, greedy):
461
+ import numpy as np
462
+
463
+ # This helper function add two nodes to DF_tree - one left son and the
464
+ # other right son, finds their heuristic, CL, GBC, and GM
465
+ node_p = DF_tree.number_of_nodes() + 1
466
+ node_m = DF_tree.number_of_nodes() + 2
467
+ added_node = DF_tree.nodes[root]["CL"][0]
468
+
469
+ # adding the plus node
470
+ DF_tree.add_nodes_from([(node_p, deepcopy(DF_tree.nodes[root]))])
471
+ DF_tree.nodes[node_p]["GM"].append(added_node)
472
+ DF_tree.nodes[node_p]["GBC"] += DF_tree.nodes[node_p]["cont"][added_node]
473
+ root_node = DF_tree.nodes[root]
474
+ for x in nodes:
475
+ for y in nodes:
476
+ dxvy = 0
477
+ dxyv = 0
478
+ dvxy = 0
479
+ if not (
480
+ root_node["sigma"][x][y] == 0
481
+ or root_node["sigma"][x][added_node] == 0
482
+ or root_node["sigma"][added_node][y] == 0
483
+ ):
484
+ if D[x][added_node] == D[x][y] + D[y][added_node]:
485
+ dxyv = (
486
+ root_node["sigma"][x][y]
487
+ * root_node["sigma"][y][added_node]
488
+ / root_node["sigma"][x][added_node]
489
+ )
490
+ if D[x][y] == D[x][added_node] + D[added_node][y]:
491
+ dxvy = (
492
+ root_node["sigma"][x][added_node]
493
+ * root_node["sigma"][added_node][y]
494
+ / root_node["sigma"][x][y]
495
+ )
496
+ if D[added_node][y] == D[added_node][x] + D[x][y]:
497
+ dvxy = (
498
+ root_node["sigma"][added_node][x]
499
+ * root_node["sigma"][x][y]
500
+ / root_node["sigma"][added_node][y]
501
+ )
502
+ DF_tree.nodes[node_p]["sigma"][x][y] = root_node["sigma"][x][y] * (1 - dxvy)
503
+ DF_tree.nodes[node_p]["betweenness"].loc[y, x] = (
504
+ root_node["betweenness"][x][y] - root_node["betweenness"][x][y] * dxvy
505
+ )
506
+ if y != added_node:
507
+ DF_tree.nodes[node_p]["betweenness"].loc[y, x] -= (
508
+ root_node["betweenness"][x][added_node] * dxyv
509
+ )
510
+ if x != added_node:
511
+ DF_tree.nodes[node_p]["betweenness"].loc[y, x] -= (
512
+ root_node["betweenness"][added_node][y] * dvxy
513
+ )
514
+
515
+ DF_tree.nodes[node_p]["CL"] = [
516
+ node
517
+ for _, node in sorted(
518
+ zip(np.diag(DF_tree.nodes[node_p]["betweenness"]), nodes), reverse=True
519
+ )
520
+ if node not in DF_tree.nodes[node_p]["GM"]
521
+ ]
522
+ DF_tree.nodes[node_p]["cont"] = dict(
523
+ zip(nodes, np.diag(DF_tree.nodes[node_p]["betweenness"]))
524
+ )
525
+ DF_tree.nodes[node_p]["heu"] = 0
526
+ for i in range(k - len(DF_tree.nodes[node_p]["GM"])):
527
+ DF_tree.nodes[node_p]["heu"] += DF_tree.nodes[node_p]["cont"][
528
+ DF_tree.nodes[node_p]["CL"][i]
529
+ ]
530
+
531
+ # adding the minus node - don't insert the first node in the CL to GM
532
+ # Insert minus node only if isn't greedy type algorithm
533
+ if not greedy:
534
+ DF_tree.add_nodes_from([(node_m, deepcopy(DF_tree.nodes[root]))])
535
+ DF_tree.nodes[node_m]["CL"].pop(0)
536
+ DF_tree.nodes[node_m]["cont"].pop(added_node)
537
+ DF_tree.nodes[node_m]["heu"] = 0
538
+ for i in range(k - len(DF_tree.nodes[node_m]["GM"])):
539
+ DF_tree.nodes[node_m]["heu"] += DF_tree.nodes[node_m]["cont"][
540
+ DF_tree.nodes[node_m]["CL"][i]
541
+ ]
542
+ else:
543
+ node_m = None
544
+
545
+ return node_p, node_m, DF_tree
546
+
547
+
548
+ @nx._dispatchable(edge_attrs="weight")
549
+ def group_closeness_centrality(G, S, weight=None):
550
+ r"""Compute the group closeness centrality for a group of nodes.
551
+
552
+ Group closeness centrality of a group of nodes $S$ is a measure
553
+ of how close the group is to the other nodes in the graph.
554
+
555
+ .. math::
556
+
557
+ c_{close}(S) = \frac{|V-S|}{\sum_{v \in V-S} d_{S, v}}
558
+
559
+ d_{S, v} = min_{u \in S} (d_{u, v})
560
+
561
+ where $V$ is the set of nodes, $d_{S, v}$ is the distance of
562
+ the group $S$ from $v$ defined as above. ($V-S$ is the set of nodes
563
+ in $V$ that are not in $S$).
564
+
565
+ Parameters
566
+ ----------
567
+ G : graph
568
+ A NetworkX graph.
569
+
570
+ S : list or set
571
+ S is a group of nodes which belong to G, for which group closeness
572
+ centrality is to be calculated.
573
+
574
+ weight : None or string, optional (default=None)
575
+ If None, all edge weights are considered equal.
576
+ Otherwise holds the name of the edge attribute used as weight.
577
+ The weight of an edge is treated as the length or distance between the two sides.
578
+
579
+ Raises
580
+ ------
581
+ NodeNotFound
582
+ If node(s) in S are not present in G.
583
+
584
+ Returns
585
+ -------
586
+ closeness : float
587
+ Group closeness centrality of the group S.
588
+
589
+ See Also
590
+ --------
591
+ closeness_centrality
592
+
593
+ Notes
594
+ -----
595
+ The measure was introduced in [1]_.
596
+ The formula implemented here is described in [2]_.
597
+
598
+ Higher values of closeness indicate greater centrality.
599
+
600
+ It is assumed that 1 / 0 is 0 (required in the case of directed graphs,
601
+ or when a shortest path length is 0).
602
+
603
+ The number of nodes in the group must be a maximum of n - 1 where `n`
604
+ is the total number of nodes in the graph.
605
+
606
+ For directed graphs, the incoming distance is utilized here. To use the
607
+ outward distance, act on `G.reverse()`.
608
+
609
+ For weighted graphs the edge weights must be greater than zero.
610
+ Zero edge weights can produce an infinite number of equal length
611
+ paths between pairs of nodes.
612
+
613
+ References
614
+ ----------
615
+ .. [1] M G Everett and S P Borgatti:
616
+ The Centrality of Groups and Classes.
617
+ Journal of Mathematical Sociology. 23(3): 181-201. 1999.
618
+ http://www.analytictech.com/borgatti/group_centrality.htm
619
+ .. [2] J. Zhao et. al.:
620
+ Measuring and Maximizing Group Closeness Centrality over
621
+ Disk Resident Graphs.
622
+ WWWConference Proceedings, 2014. 689-694.
623
+ https://doi.org/10.1145/2567948.2579356
624
+ """
625
+ if G.is_directed():
626
+ G = G.reverse() # reverse view
627
+ closeness = 0 # initialize to 0
628
+ V = set(G) # set of nodes in G
629
+ S = set(S) # set of nodes in group S
630
+ V_S = V - S # set of nodes in V but not S
631
+ shortest_path_lengths = nx.multi_source_dijkstra_path_length(G, S, weight=weight)
632
+ # accumulation
633
+ for v in V_S:
634
+ try:
635
+ closeness += shortest_path_lengths[v]
636
+ except KeyError: # no path exists
637
+ closeness += 0
638
+ try:
639
+ closeness = len(V_S) / closeness
640
+ except ZeroDivisionError: # 1 / 0 assumed as 0
641
+ closeness = 0
642
+ return closeness
643
+
644
+
645
+ @nx._dispatchable
646
+ def group_degree_centrality(G, S):
647
+ """Compute the group degree centrality for a group of nodes.
648
+
649
+ Group degree centrality of a group of nodes $S$ is the fraction
650
+ of non-group members connected to group members.
651
+
652
+ Parameters
653
+ ----------
654
+ G : graph
655
+ A NetworkX graph.
656
+
657
+ S : list or set
658
+ S is a group of nodes which belong to G, for which group degree
659
+ centrality is to be calculated.
660
+
661
+ Raises
662
+ ------
663
+ NetworkXError
664
+ If node(s) in S are not in G.
665
+
666
+ Returns
667
+ -------
668
+ centrality : float
669
+ Group degree centrality of the group S.
670
+
671
+ See Also
672
+ --------
673
+ degree_centrality
674
+ group_in_degree_centrality
675
+ group_out_degree_centrality
676
+
677
+ Notes
678
+ -----
679
+ The measure was introduced in [1]_.
680
+
681
+ The number of nodes in the group must be a maximum of n - 1 where `n`
682
+ is the total number of nodes in the graph.
683
+
684
+ References
685
+ ----------
686
+ .. [1] M G Everett and S P Borgatti:
687
+ The Centrality of Groups and Classes.
688
+ Journal of Mathematical Sociology. 23(3): 181-201. 1999.
689
+ http://www.analytictech.com/borgatti/group_centrality.htm
690
+ """
691
+ centrality = len(set().union(*[set(G.neighbors(i)) for i in S]) - set(S))
692
+ centrality /= len(G.nodes()) - len(S)
693
+ return centrality
694
+
695
+
696
+ @not_implemented_for("undirected")
697
+ @nx._dispatchable
698
+ def group_in_degree_centrality(G, S):
699
+ """Compute the group in-degree centrality for a group of nodes.
700
+
701
+ Group in-degree centrality of a group of nodes $S$ is the fraction
702
+ of non-group members connected to group members by incoming edges.
703
+
704
+ Parameters
705
+ ----------
706
+ G : graph
707
+ A NetworkX graph.
708
+
709
+ S : list or set
710
+ S is a group of nodes which belong to G, for which group in-degree
711
+ centrality is to be calculated.
712
+
713
+ Returns
714
+ -------
715
+ centrality : float
716
+ Group in-degree centrality of the group S.
717
+
718
+ Raises
719
+ ------
720
+ NetworkXNotImplemented
721
+ If G is undirected.
722
+
723
+ NodeNotFound
724
+ If node(s) in S are not in G.
725
+
726
+ See Also
727
+ --------
728
+ degree_centrality
729
+ group_degree_centrality
730
+ group_out_degree_centrality
731
+
732
+ Notes
733
+ -----
734
+ The number of nodes in the group must be a maximum of n - 1 where `n`
735
+ is the total number of nodes in the graph.
736
+
737
+ `G.neighbors(i)` gives nodes with an outward edge from i, in a DiGraph,
738
+ so for group in-degree centrality, the reverse graph is used.
739
+ """
740
+ return group_degree_centrality(G.reverse(), S)
741
+
742
+
743
+ @not_implemented_for("undirected")
744
+ @nx._dispatchable
745
+ def group_out_degree_centrality(G, S):
746
+ """Compute the group out-degree centrality for a group of nodes.
747
+
748
+ Group out-degree centrality of a group of nodes $S$ is the fraction
749
+ of non-group members connected to group members by outgoing edges.
750
+
751
+ Parameters
752
+ ----------
753
+ G : graph
754
+ A NetworkX graph.
755
+
756
+ S : list or set
757
+ S is a group of nodes which belong to G, for which group in-degree
758
+ centrality is to be calculated.
759
+
760
+ Returns
761
+ -------
762
+ centrality : float
763
+ Group out-degree centrality of the group S.
764
+
765
+ Raises
766
+ ------
767
+ NetworkXNotImplemented
768
+ If G is undirected.
769
+
770
+ NodeNotFound
771
+ If node(s) in S are not in G.
772
+
773
+ See Also
774
+ --------
775
+ degree_centrality
776
+ group_degree_centrality
777
+ group_in_degree_centrality
778
+
779
+ Notes
780
+ -----
781
+ The number of nodes in the group must be a maximum of n - 1 where `n`
782
+ is the total number of nodes in the graph.
783
+
784
+ `G.neighbors(i)` gives nodes with an outward edge from i, in a DiGraph,
785
+ so for group out-degree centrality, the graph itself is used.
786
+ """
787
+ return group_degree_centrality(G, S)
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/harmonic.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing the harmonic centrality of a graph."""
2
+
3
+ from functools import partial
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["harmonic_centrality"]
8
+
9
+
10
+ @nx._dispatchable(edge_attrs="distance")
11
+ def harmonic_centrality(G, nbunch=None, distance=None, sources=None):
12
+ r"""Compute harmonic centrality for nodes.
13
+
14
+ Harmonic centrality [1]_ of a node `u` is the sum of the reciprocal
15
+ of the shortest path distances from all other nodes to `u`
16
+
17
+ .. math::
18
+
19
+ C(u) = \sum_{v \neq u} \frac{1}{d(v, u)}
20
+
21
+ where `d(v, u)` is the shortest-path distance between `v` and `u`.
22
+
23
+ If `sources` is given as an argument, the returned harmonic centrality
24
+ values are calculated as the sum of the reciprocals of the shortest
25
+ path distances from the nodes specified in `sources` to `u` instead
26
+ of from all nodes to `u`.
27
+
28
+ Notice that higher values indicate higher centrality.
29
+
30
+ Parameters
31
+ ----------
32
+ G : graph
33
+ A NetworkX graph
34
+
35
+ nbunch : container (default: all nodes in G)
36
+ Container of nodes for which harmonic centrality values are calculated.
37
+
38
+ sources : container (default: all nodes in G)
39
+ Container of nodes `v` over which reciprocal distances are computed.
40
+ Nodes not in `G` are silently ignored.
41
+
42
+ distance : edge attribute key, optional (default=None)
43
+ Use the specified edge attribute as the edge distance in shortest
44
+ path calculations. If `None`, then each edge will have distance equal to 1.
45
+
46
+ Returns
47
+ -------
48
+ nodes : dictionary
49
+ Dictionary of nodes with harmonic centrality as the value.
50
+
51
+ See Also
52
+ --------
53
+ betweenness_centrality, load_centrality, eigenvector_centrality,
54
+ degree_centrality, closeness_centrality
55
+
56
+ Notes
57
+ -----
58
+ If the 'distance' keyword is set to an edge attribute key then the
59
+ shortest-path length will be computed using Dijkstra's algorithm with
60
+ that edge attribute as the edge weight.
61
+
62
+ References
63
+ ----------
64
+ .. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality."
65
+ Internet Mathematics 10.3-4 (2014): 222-262.
66
+ """
67
+
68
+ nbunch = set(G.nbunch_iter(nbunch) if nbunch is not None else G.nodes)
69
+ sources = set(G.nbunch_iter(sources) if sources is not None else G.nodes)
70
+
71
+ centrality = {u: 0 for u in nbunch}
72
+
73
+ transposed = False
74
+ if len(nbunch) < len(sources):
75
+ transposed = True
76
+ nbunch, sources = sources, nbunch
77
+ if nx.is_directed(G):
78
+ G = nx.reverse(G, copy=False)
79
+
80
+ spl = partial(nx.shortest_path_length, G, weight=distance)
81
+ for v in sources:
82
+ dist = spl(v)
83
+ for u in nbunch.intersection(dist):
84
+ d = dist[u]
85
+ if d == 0: # handle u == v and edges with 0 weight
86
+ continue
87
+ centrality[v if transposed else u] += 1 / d
88
+
89
+ return centrality
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/katz.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Katz centrality."""
2
+
3
+ import math
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = ["katz_centrality", "katz_centrality_numpy"]
9
+
10
+
11
+ @not_implemented_for("multigraph")
12
+ @nx._dispatchable(edge_attrs="weight")
13
+ def katz_centrality(
14
+ G,
15
+ alpha=0.1,
16
+ beta=1.0,
17
+ max_iter=1000,
18
+ tol=1.0e-6,
19
+ nstart=None,
20
+ normalized=True,
21
+ weight=None,
22
+ ):
23
+ r"""Compute the Katz centrality for the nodes of the graph G.
24
+
25
+ Katz centrality computes the centrality for a node based on the centrality
26
+ of its neighbors. It is a generalization of the eigenvector centrality. The
27
+ Katz centrality for node $i$ is
28
+
29
+ .. math::
30
+
31
+ x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
32
+
33
+ where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
34
+
35
+ The parameter $\beta$ controls the initial centrality and
36
+
37
+ .. math::
38
+
39
+ \alpha < \frac{1}{\lambda_{\max}}.
40
+
41
+ Katz centrality computes the relative influence of a node within a
42
+ network by measuring the number of the immediate neighbors (first
43
+ degree nodes) and also all other nodes in the network that connect
44
+ to the node under consideration through these immediate neighbors.
45
+
46
+ Extra weight can be provided to immediate neighbors through the
47
+ parameter $\beta$. Connections made with distant neighbors
48
+ are, however, penalized by an attenuation factor $\alpha$ which
49
+ should be strictly less than the inverse largest eigenvalue of the
50
+ adjacency matrix in order for the Katz centrality to be computed
51
+ correctly. More information is provided in [1]_.
52
+
53
+ Parameters
54
+ ----------
55
+ G : graph
56
+ A NetworkX graph.
57
+
58
+ alpha : float, optional (default=0.1)
59
+ Attenuation factor
60
+
61
+ beta : scalar or dictionary, optional (default=1.0)
62
+ Weight attributed to the immediate neighborhood. If not a scalar, the
63
+ dictionary must have a value for every node.
64
+
65
+ max_iter : integer, optional (default=1000)
66
+ Maximum number of iterations in power method.
67
+
68
+ tol : float, optional (default=1.0e-6)
69
+ Error tolerance used to check convergence in power method iteration.
70
+
71
+ nstart : dictionary, optional
72
+ Starting value of Katz iteration for each node.
73
+
74
+ normalized : bool, optional (default=True)
75
+ If True normalize the resulting values.
76
+
77
+ weight : None or string, optional (default=None)
78
+ If None, all edge weights are considered equal.
79
+ Otherwise holds the name of the edge attribute used as weight.
80
+ In this measure the weight is interpreted as the connection strength.
81
+
82
+ Returns
83
+ -------
84
+ nodes : dictionary
85
+ Dictionary of nodes with Katz centrality as the value.
86
+
87
+ Raises
88
+ ------
89
+ NetworkXError
90
+ If the parameter `beta` is not a scalar but lacks a value for at least
91
+ one node
92
+
93
+ PowerIterationFailedConvergence
94
+ If the algorithm fails to converge to the specified tolerance
95
+ within the specified number of iterations of the power iteration
96
+ method.
97
+
98
+ Examples
99
+ --------
100
+ >>> import math
101
+ >>> G = nx.path_graph(4)
102
+ >>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
103
+ >>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
104
+ >>> for n, c in sorted(centrality.items()):
105
+ ... print(f"{n} {c:.2f}")
106
+ 0 0.37
107
+ 1 0.60
108
+ 2 0.60
109
+ 3 0.37
110
+
111
+ See Also
112
+ --------
113
+ katz_centrality_numpy
114
+ eigenvector_centrality
115
+ eigenvector_centrality_numpy
116
+ :func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
117
+ :func:`~networkx.algorithms.link_analysis.hits_alg.hits`
118
+
119
+ Notes
120
+ -----
121
+ Katz centrality was introduced by [2]_.
122
+
123
+ This algorithm it uses the power method to find the eigenvector
124
+ corresponding to the largest eigenvalue of the adjacency matrix of ``G``.
125
+ The parameter ``alpha`` should be strictly less than the inverse of largest
126
+ eigenvalue of the adjacency matrix for the algorithm to converge.
127
+ You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
128
+ eigenvalue of the adjacency matrix.
129
+ The iteration will stop after ``max_iter`` iterations or an error tolerance of
130
+ ``number_of_nodes(G) * tol`` has been reached.
131
+
132
+ For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
133
+ Katz centrality approaches the results for eigenvector centrality.
134
+
135
+ For directed graphs this finds "left" eigenvectors which corresponds
136
+ to the in-edges in the graph. For out-edges Katz centrality,
137
+ first reverse the graph with ``G.reverse()``.
138
+
139
+ References
140
+ ----------
141
+ .. [1] Mark E. J. Newman:
142
+ Networks: An Introduction.
143
+ Oxford University Press, USA, 2010, p. 720.
144
+ .. [2] Leo Katz:
145
+ A New Status Index Derived from Sociometric Index.
146
+ Psychometrika 18(1):39–43, 1953
147
+ https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
148
+ """
149
+ if len(G) == 0:
150
+ return {}
151
+
152
+ nnodes = G.number_of_nodes()
153
+
154
+ if nstart is None:
155
+ # choose starting vector with entries of 0
156
+ x = {n: 0 for n in G}
157
+ else:
158
+ x = nstart
159
+
160
+ try:
161
+ b = dict.fromkeys(G, float(beta))
162
+ except (TypeError, ValueError, AttributeError) as err:
163
+ b = beta
164
+ if set(beta) != set(G):
165
+ raise nx.NetworkXError(
166
+ "beta dictionary must have a value for every node"
167
+ ) from err
168
+
169
+ # make up to max_iter iterations
170
+ for _ in range(max_iter):
171
+ xlast = x
172
+ x = dict.fromkeys(xlast, 0)
173
+ # do the multiplication y^T = Alpha * x^T A + Beta
174
+ for n in x:
175
+ for nbr in G[n]:
176
+ x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)
177
+ for n in x:
178
+ x[n] = alpha * x[n] + b[n]
179
+
180
+ # check convergence
181
+ error = sum(abs(x[n] - xlast[n]) for n in x)
182
+ if error < nnodes * tol:
183
+ if normalized:
184
+ # normalize vector
185
+ try:
186
+ s = 1.0 / math.hypot(*x.values())
187
+ except ZeroDivisionError:
188
+ s = 1.0
189
+ else:
190
+ s = 1
191
+ for n in x:
192
+ x[n] *= s
193
+ return x
194
+ raise nx.PowerIterationFailedConvergence(max_iter)
195
+
196
+
197
+ @not_implemented_for("multigraph")
198
+ @nx._dispatchable(edge_attrs="weight")
199
+ def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):
200
+ r"""Compute the Katz centrality for the graph G.
201
+
202
+ Katz centrality computes the centrality for a node based on the centrality
203
+ of its neighbors. It is a generalization of the eigenvector centrality. The
204
+ Katz centrality for node $i$ is
205
+
206
+ .. math::
207
+
208
+ x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
209
+
210
+ where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
211
+
212
+ The parameter $\beta$ controls the initial centrality and
213
+
214
+ .. math::
215
+
216
+ \alpha < \frac{1}{\lambda_{\max}}.
217
+
218
+ Katz centrality computes the relative influence of a node within a
219
+ network by measuring the number of the immediate neighbors (first
220
+ degree nodes) and also all other nodes in the network that connect
221
+ to the node under consideration through these immediate neighbors.
222
+
223
+ Extra weight can be provided to immediate neighbors through the
224
+ parameter $\beta$. Connections made with distant neighbors
225
+ are, however, penalized by an attenuation factor $\alpha$ which
226
+ should be strictly less than the inverse largest eigenvalue of the
227
+ adjacency matrix in order for the Katz centrality to be computed
228
+ correctly. More information is provided in [1]_.
229
+
230
+ Parameters
231
+ ----------
232
+ G : graph
233
+ A NetworkX graph
234
+
235
+ alpha : float
236
+ Attenuation factor
237
+
238
+ beta : scalar or dictionary, optional (default=1.0)
239
+ Weight attributed to the immediate neighborhood. If not a scalar the
240
+ dictionary must have an value for every node.
241
+
242
+ normalized : bool
243
+ If True normalize the resulting values.
244
+
245
+ weight : None or string, optional
246
+ If None, all edge weights are considered equal.
247
+ Otherwise holds the name of the edge attribute used as weight.
248
+ In this measure the weight is interpreted as the connection strength.
249
+
250
+ Returns
251
+ -------
252
+ nodes : dictionary
253
+ Dictionary of nodes with Katz centrality as the value.
254
+
255
+ Raises
256
+ ------
257
+ NetworkXError
258
+ If the parameter `beta` is not a scalar but lacks a value for at least
259
+ one node
260
+
261
+ Examples
262
+ --------
263
+ >>> import math
264
+ >>> G = nx.path_graph(4)
265
+ >>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
266
+ >>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
267
+ >>> for n, c in sorted(centrality.items()):
268
+ ... print(f"{n} {c:.2f}")
269
+ 0 0.37
270
+ 1 0.60
271
+ 2 0.60
272
+ 3 0.37
273
+
274
+ See Also
275
+ --------
276
+ katz_centrality
277
+ eigenvector_centrality_numpy
278
+ eigenvector_centrality
279
+ :func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
280
+ :func:`~networkx.algorithms.link_analysis.hits_alg.hits`
281
+
282
+ Notes
283
+ -----
284
+ Katz centrality was introduced by [2]_.
285
+
286
+ This algorithm uses a direct linear solver to solve the above equation.
287
+ The parameter ``alpha`` should be strictly less than the inverse of largest
288
+ eigenvalue of the adjacency matrix for there to be a solution.
289
+ You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
290
+ eigenvalue of the adjacency matrix.
291
+
292
+ For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
293
+ Katz centrality approaches the results for eigenvector centrality.
294
+
295
+ For directed graphs this finds "left" eigenvectors which corresponds
296
+ to the in-edges in the graph. For out-edges Katz centrality,
297
+ first reverse the graph with ``G.reverse()``.
298
+
299
+ References
300
+ ----------
301
+ .. [1] Mark E. J. Newman:
302
+ Networks: An Introduction.
303
+ Oxford University Press, USA, 2010, p. 173.
304
+ .. [2] Leo Katz:
305
+ A New Status Index Derived from Sociometric Index.
306
+ Psychometrika 18(1):39–43, 1953
307
+ https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
308
+ """
309
+ import numpy as np
310
+
311
+ if len(G) == 0:
312
+ return {}
313
+ try:
314
+ nodelist = beta.keys()
315
+ if set(nodelist) != set(G):
316
+ raise nx.NetworkXError("beta dictionary must have a value for every node")
317
+ b = np.array(list(beta.values()), dtype=float)
318
+ except AttributeError:
319
+ nodelist = list(G)
320
+ try:
321
+ b = np.ones((len(nodelist), 1)) * beta
322
+ except (TypeError, ValueError, AttributeError) as err:
323
+ raise nx.NetworkXError("beta must be a number") from err
324
+
325
+ A = nx.adjacency_matrix(G, nodelist=nodelist, weight=weight).todense().T
326
+ n = A.shape[0]
327
+ centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b).squeeze()
328
+
329
+ # Normalize: rely on truediv to cast to float, then tolist to make Python numbers
330
+ norm = np.sign(sum(centrality)) * np.linalg.norm(centrality) if normalized else 1
331
+ return dict(zip(nodelist, (centrality / norm).tolist()))
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/laplacian.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Laplacian centrality measures.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["laplacian_centrality"]
8
+
9
+
10
+ @nx._dispatchable(edge_attrs="weight")
11
+ def laplacian_centrality(
12
+ G, normalized=True, nodelist=None, weight="weight", walk_type=None, alpha=0.95
13
+ ):
14
+ r"""Compute the Laplacian centrality for nodes in the graph `G`.
15
+
16
+ The Laplacian Centrality of a node ``i`` is measured by the drop in the
17
+ Laplacian Energy after deleting node ``i`` from the graph. The Laplacian Energy
18
+ is the sum of the squared eigenvalues of a graph's Laplacian matrix.
19
+
20
+ .. math::
21
+
22
+ C_L(u_i,G) = \frac{(\Delta E)_i}{E_L (G)} = \frac{E_L (G)-E_L (G_i)}{E_L (G)}
23
+
24
+ E_L (G) = \sum_{i=0}^n \lambda_i^2
25
+
26
+ Where $E_L (G)$ is the Laplacian energy of graph `G`,
27
+ E_L (G_i) is the Laplacian energy of graph `G` after deleting node ``i``
28
+ and $\lambda_i$ are the eigenvalues of `G`'s Laplacian matrix.
29
+ This formula shows the normalized value. Without normalization,
30
+ the numerator on the right side is returned.
31
+
32
+ Parameters
33
+ ----------
34
+ G : graph
35
+ A networkx graph
36
+
37
+ normalized : bool (default = True)
38
+ If True the centrality score is scaled so the sum over all nodes is 1.
39
+ If False the centrality score for each node is the drop in Laplacian
40
+ energy when that node is removed.
41
+
42
+ nodelist : list, optional (default = None)
43
+ The rows and columns are ordered according to the nodes in nodelist.
44
+ If nodelist is None, then the ordering is produced by G.nodes().
45
+
46
+ weight: string or None, optional (default=`weight`)
47
+ Optional parameter `weight` to compute the Laplacian matrix.
48
+ The edge data key used to compute each value in the matrix.
49
+ If None, then each edge has weight 1.
50
+
51
+ walk_type : string or None, optional (default=None)
52
+ Optional parameter `walk_type` used when calling
53
+ :func:`directed_laplacian_matrix <networkx.directed_laplacian_matrix>`.
54
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
55
+ (the default), then a value is selected according to the properties of `G`:
56
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
57
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
58
+ - ``walk_type="pagerank"`` for all other cases.
59
+
60
+ alpha : real (default = 0.95)
61
+ Optional parameter `alpha` used when calling
62
+ :func:`directed_laplacian_matrix <networkx.directed_laplacian_matrix>`.
63
+ (1 - alpha) is the teleportation probability used with pagerank.
64
+
65
+ Returns
66
+ -------
67
+ nodes : dictionary
68
+ Dictionary of nodes with Laplacian centrality as the value.
69
+
70
+ Examples
71
+ --------
72
+ >>> G = nx.Graph()
73
+ >>> edges = [(0, 1, 4), (0, 2, 2), (2, 1, 1), (1, 3, 2), (1, 4, 2), (4, 5, 1)]
74
+ >>> G.add_weighted_edges_from(edges)
75
+ >>> sorted((v, f"{c:0.2f}") for v, c in laplacian_centrality(G).items())
76
+ [(0, '0.70'), (1, '0.90'), (2, '0.28'), (3, '0.22'), (4, '0.26'), (5, '0.04')]
77
+
78
+ Notes
79
+ -----
80
+ The algorithm is implemented based on [1]_ with an extension to directed graphs
81
+ using the ``directed_laplacian_matrix`` function.
82
+
83
+ Raises
84
+ ------
85
+ NetworkXPointlessConcept
86
+ If the graph `G` is the null graph.
87
+ ZeroDivisionError
88
+ If the graph `G` has no edges (is empty) and normalization is requested.
89
+
90
+ References
91
+ ----------
92
+ .. [1] Qi, X., Fuller, E., Wu, Q., Wu, Y., and Zhang, C.-Q. (2012).
93
+ Laplacian centrality: A new centrality measure for weighted networks.
94
+ Information Sciences, 194:240-253.
95
+ https://math.wvu.edu/~cqzhang/Publication-files/my-paper/INS-2012-Laplacian-W.pdf
96
+
97
+ See Also
98
+ --------
99
+ :func:`~networkx.linalg.laplacianmatrix.directed_laplacian_matrix`
100
+ :func:`~networkx.linalg.laplacianmatrix.laplacian_matrix`
101
+ """
102
+ import numpy as np
103
+ import scipy as sp
104
+
105
+ if len(G) == 0:
106
+ raise nx.NetworkXPointlessConcept("null graph has no centrality defined")
107
+ if G.size(weight=weight) == 0:
108
+ if normalized:
109
+ raise ZeroDivisionError("graph with no edges has zero full energy")
110
+ return {n: 0 for n in G}
111
+
112
+ if nodelist is not None:
113
+ nodeset = set(G.nbunch_iter(nodelist))
114
+ if len(nodeset) != len(nodelist):
115
+ raise nx.NetworkXError("nodelist has duplicate nodes or nodes not in G")
116
+ nodes = nodelist + [n for n in G if n not in nodeset]
117
+ else:
118
+ nodelist = nodes = list(G)
119
+
120
+ if G.is_directed():
121
+ lap_matrix = nx.directed_laplacian_matrix(G, nodes, weight, walk_type, alpha)
122
+ else:
123
+ lap_matrix = nx.laplacian_matrix(G, nodes, weight).toarray()
124
+
125
+ full_energy = np.power(sp.linalg.eigh(lap_matrix, eigvals_only=True), 2).sum()
126
+
127
+ # calculate laplacian centrality
128
+ laplace_centralities_dict = {}
129
+ for i, node in enumerate(nodelist):
130
+ # remove row and col i from lap_matrix
131
+ all_but_i = list(np.arange(lap_matrix.shape[0]))
132
+ all_but_i.remove(i)
133
+ A_2 = lap_matrix[all_but_i, :][:, all_but_i]
134
+
135
+ # Adjust diagonal for removed row
136
+ new_diag = lap_matrix.diagonal() - abs(lap_matrix[:, i])
137
+ np.fill_diagonal(A_2, new_diag[all_but_i])
138
+
139
+ if len(all_but_i) > 0: # catches degenerate case of single node
140
+ new_energy = np.power(sp.linalg.eigh(A_2, eigvals_only=True), 2).sum()
141
+ else:
142
+ new_energy = 0.0
143
+
144
+ lapl_cent = full_energy - new_energy
145
+ if normalized:
146
+ lapl_cent = lapl_cent / full_energy
147
+
148
+ laplace_centralities_dict[node] = float(lapl_cent)
149
+
150
+ return laplace_centralities_dict
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/load.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load centrality."""
2
+
3
+ from operator import itemgetter
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["load_centrality", "edge_load_centrality"]
8
+
9
+
10
+ @nx._dispatchable(edge_attrs="weight")
11
+ def newman_betweenness_centrality(G, v=None, cutoff=None, normalized=True, weight=None):
12
+ """Compute load centrality for nodes.
13
+
14
+ The load centrality of a node is the fraction of all shortest
15
+ paths that pass through that node.
16
+
17
+ Parameters
18
+ ----------
19
+ G : graph
20
+ A networkx graph.
21
+
22
+ normalized : bool, optional (default=True)
23
+ If True the betweenness values are normalized by b=b/(n-1)(n-2) where
24
+ n is the number of nodes in G.
25
+
26
+ weight : None or string, optional (default=None)
27
+ If None, edge weights are ignored.
28
+ Otherwise holds the name of the edge attribute used as weight.
29
+ The weight of an edge is treated as the length or distance between the two sides.
30
+
31
+ cutoff : bool, optional (default=None)
32
+ If specified, only consider paths of length <= cutoff.
33
+
34
+ Returns
35
+ -------
36
+ nodes : dictionary
37
+ Dictionary of nodes with centrality as the value.
38
+
39
+ See Also
40
+ --------
41
+ betweenness_centrality
42
+
43
+ Notes
44
+ -----
45
+ Load centrality is slightly different than betweenness. It was originally
46
+ introduced by [2]_. For this load algorithm see [1]_.
47
+
48
+ References
49
+ ----------
50
+ .. [1] Mark E. J. Newman:
51
+ Scientific collaboration networks. II.
52
+ Shortest paths, weighted networks, and centrality.
53
+ Physical Review E 64, 016132, 2001.
54
+ http://journals.aps.org/pre/abstract/10.1103/PhysRevE.64.016132
55
+ .. [2] Kwang-Il Goh, Byungnam Kahng and Doochul Kim
56
+ Universal behavior of Load Distribution in Scale-Free Networks.
57
+ Physical Review Letters 87(27):1–4, 2001.
58
+ https://doi.org/10.1103/PhysRevLett.87.278701
59
+ """
60
+ if v is not None: # only one node
61
+ betweenness = 0.0
62
+ for source in G:
63
+ ubetween = _node_betweenness(G, source, cutoff, False, weight)
64
+ betweenness += ubetween[v] if v in ubetween else 0
65
+ if normalized:
66
+ order = G.order()
67
+ if order <= 2:
68
+ return betweenness # no normalization b=0 for all nodes
69
+ betweenness *= 1.0 / ((order - 1) * (order - 2))
70
+ else:
71
+ betweenness = {}.fromkeys(G, 0.0)
72
+ for source in betweenness:
73
+ ubetween = _node_betweenness(G, source, cutoff, False, weight)
74
+ for vk in ubetween:
75
+ betweenness[vk] += ubetween[vk]
76
+ if normalized:
77
+ order = G.order()
78
+ if order <= 2:
79
+ return betweenness # no normalization b=0 for all nodes
80
+ scale = 1.0 / ((order - 1) * (order - 2))
81
+ for v in betweenness:
82
+ betweenness[v] *= scale
83
+ return betweenness # all nodes
84
+
85
+
86
+ def _node_betweenness(G, source, cutoff=False, normalized=True, weight=None):
87
+ """Node betweenness_centrality helper:
88
+
89
+ See betweenness_centrality for what you probably want.
90
+ This actually computes "load" and not betweenness.
91
+ See https://networkx.lanl.gov/ticket/103
92
+
93
+ This calculates the load of each node for paths from a single source.
94
+ (The fraction of number of shortests paths from source that go
95
+ through each node.)
96
+
97
+ To get the load for a node you need to do all-pairs shortest paths.
98
+
99
+ If weight is not None then use Dijkstra for finding shortest paths.
100
+ """
101
+ # get the predecessor and path length data
102
+ if weight is None:
103
+ (pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
104
+ else:
105
+ (pred, length) = nx.dijkstra_predecessor_and_distance(G, source, cutoff, weight)
106
+
107
+ # order the nodes by path length
108
+ onodes = [(l, vert) for (vert, l) in length.items()]
109
+ onodes.sort()
110
+ onodes[:] = [vert for (l, vert) in onodes if l > 0]
111
+
112
+ # initialize betweenness
113
+ between = {}.fromkeys(length, 1.0)
114
+
115
+ while onodes:
116
+ v = onodes.pop()
117
+ if v in pred:
118
+ num_paths = len(pred[v]) # Discount betweenness if more than
119
+ for x in pred[v]: # one shortest path.
120
+ if x == source: # stop if hit source because all remaining v
121
+ break # also have pred[v]==[source]
122
+ between[x] += between[v] / num_paths
123
+ # remove source
124
+ for v in between:
125
+ between[v] -= 1
126
+ # rescale to be between 0 and 1
127
+ if normalized:
128
+ l = len(between)
129
+ if l > 2:
130
+ # scale by 1/the number of possible paths
131
+ scale = 1 / ((l - 1) * (l - 2))
132
+ for v in between:
133
+ between[v] *= scale
134
+ return between
135
+
136
+
137
+ load_centrality = newman_betweenness_centrality
138
+
139
+
140
+ @nx._dispatchable
141
+ def edge_load_centrality(G, cutoff=False):
142
+ """Compute edge load.
143
+
144
+ WARNING: This concept of edge load has not been analysed
145
+ or discussed outside of NetworkX that we know of.
146
+ It is based loosely on load_centrality in the sense that
147
+ it counts the number of shortest paths which cross each edge.
148
+ This function is for demonstration and testing purposes.
149
+
150
+ Parameters
151
+ ----------
152
+ G : graph
153
+ A networkx graph
154
+
155
+ cutoff : bool, optional (default=False)
156
+ If specified, only consider paths of length <= cutoff.
157
+
158
+ Returns
159
+ -------
160
+ A dict keyed by edge 2-tuple to the number of shortest paths
161
+ which use that edge. Where more than one path is shortest
162
+ the count is divided equally among paths.
163
+ """
164
+ betweenness = {}
165
+ for u, v in G.edges():
166
+ betweenness[(u, v)] = 0.0
167
+ betweenness[(v, u)] = 0.0
168
+
169
+ for source in G:
170
+ ubetween = _edge_betweenness(G, source, cutoff=cutoff)
171
+ for e, ubetweenv in ubetween.items():
172
+ betweenness[e] += ubetweenv # cumulative total
173
+ return betweenness
174
+
175
+
176
+ def _edge_betweenness(G, source, nodes=None, cutoff=False):
177
+ """Edge betweenness helper."""
178
+ # get the predecessor data
179
+ (pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
180
+ # order the nodes by path length
181
+ onodes = [n for n, d in sorted(length.items(), key=itemgetter(1))]
182
+ # initialize betweenness, doesn't account for any edge weights
183
+ between = {}
184
+ for u, v in G.edges(nodes):
185
+ between[(u, v)] = 1.0
186
+ between[(v, u)] = 1.0
187
+
188
+ while onodes: # work through all paths
189
+ v = onodes.pop()
190
+ if v in pred:
191
+ # Discount betweenness if more than one shortest path.
192
+ num_paths = len(pred[v])
193
+ for w in pred[v]:
194
+ if w in pred:
195
+ # Discount betweenness, mult path
196
+ num_paths = len(pred[w])
197
+ for x in pred[w]:
198
+ between[(w, x)] += between[(v, w)] / num_paths
199
+ between[(x, w)] += between[(w, v)] / num_paths
200
+ return between
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/percolation.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Percolation centrality measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.centrality.betweenness import (
5
+ _single_source_dijkstra_path_basic as dijkstra,
6
+ )
7
+ from networkx.algorithms.centrality.betweenness import (
8
+ _single_source_shortest_path_basic as shortest_path,
9
+ )
10
+
11
+ __all__ = ["percolation_centrality"]
12
+
13
+
14
+ @nx._dispatchable(node_attrs="attribute", edge_attrs="weight")
15
+ def percolation_centrality(G, attribute="percolation", states=None, weight=None):
16
+ r"""Compute the percolation centrality for nodes.
17
+
18
+ Percolation centrality of a node $v$, at a given time, is defined
19
+ as the proportion of ‘percolated paths’ that go through that node.
20
+
21
+ This measure quantifies relative impact of nodes based on their
22
+ topological connectivity, as well as their percolation states.
23
+
24
+ Percolation states of nodes are used to depict network percolation
25
+ scenarios (such as during infection transmission in a social network
26
+ of individuals, spreading of computer viruses on computer networks, or
27
+ transmission of disease over a network of towns) over time. In this
28
+ measure usually the percolation state is expressed as a decimal
29
+ between 0.0 and 1.0.
30
+
31
+ When all nodes are in the same percolated state this measure is
32
+ equivalent to betweenness centrality.
33
+
34
+ Parameters
35
+ ----------
36
+ G : graph
37
+ A NetworkX graph.
38
+
39
+ attribute : None or string, optional (default='percolation')
40
+ Name of the node attribute to use for percolation state, used
41
+ if `states` is None. If a node does not set the attribute the
42
+ state of that node will be set to the default value of 1.
43
+ If all nodes do not have the attribute all nodes will be set to
44
+ 1 and the centrality measure will be equivalent to betweenness centrality.
45
+
46
+ states : None or dict, optional (default=None)
47
+ Specify percolation states for the nodes, nodes as keys states
48
+ as values.
49
+
50
+ weight : None or string, optional (default=None)
51
+ If None, all edge weights are considered equal.
52
+ Otherwise holds the name of the edge attribute used as weight.
53
+ The weight of an edge is treated as the length or distance between the two sides.
54
+
55
+
56
+ Returns
57
+ -------
58
+ nodes : dictionary
59
+ Dictionary of nodes with percolation centrality as the value.
60
+
61
+ See Also
62
+ --------
63
+ betweenness_centrality
64
+
65
+ Notes
66
+ -----
67
+ The algorithm is from Mahendra Piraveenan, Mikhail Prokopenko, and
68
+ Liaquat Hossain [1]_
69
+ Pair dependencies are calculated and accumulated using [2]_
70
+
71
+ For weighted graphs the edge weights must be greater than zero.
72
+ Zero edge weights can produce an infinite number of equal length
73
+ paths between pairs of nodes.
74
+
75
+ References
76
+ ----------
77
+ .. [1] Mahendra Piraveenan, Mikhail Prokopenko, Liaquat Hossain
78
+ Percolation Centrality: Quantifying Graph-Theoretic Impact of Nodes
79
+ during Percolation in Networks
80
+ http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0053095
81
+ .. [2] Ulrik Brandes:
82
+ A Faster Algorithm for Betweenness Centrality.
83
+ Journal of Mathematical Sociology 25(2):163-177, 2001.
84
+ https://doi.org/10.1080/0022250X.2001.9990249
85
+ """
86
+ percolation = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
87
+
88
+ nodes = G
89
+
90
+ if states is None:
91
+ states = nx.get_node_attributes(nodes, attribute, default=1)
92
+
93
+ # sum of all percolation states
94
+ p_sigma_x_t = 0.0
95
+ for v in states.values():
96
+ p_sigma_x_t += v
97
+
98
+ for s in nodes:
99
+ # single source shortest paths
100
+ if weight is None: # use BFS
101
+ S, P, sigma, _ = shortest_path(G, s)
102
+ else: # use Dijkstra's algorithm
103
+ S, P, sigma, _ = dijkstra(G, s, weight)
104
+ # accumulation
105
+ percolation = _accumulate_percolation(
106
+ percolation, S, P, sigma, s, states, p_sigma_x_t
107
+ )
108
+
109
+ n = len(G)
110
+
111
+ for v in percolation:
112
+ percolation[v] *= 1 / (n - 2)
113
+
114
+ return percolation
115
+
116
+
117
+ def _accumulate_percolation(percolation, S, P, sigma, s, states, p_sigma_x_t):
118
+ delta = dict.fromkeys(S, 0)
119
+ while S:
120
+ w = S.pop()
121
+ coeff = (1 + delta[w]) / sigma[w]
122
+ for v in P[w]:
123
+ delta[v] += sigma[v] * coeff
124
+ if w != s:
125
+ # percolation weight
126
+ pw_s_w = states[s] / (p_sigma_x_t - states[w])
127
+ percolation[w] += delta[w] * pw_s_w
128
+ return percolation
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/reaching.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing reaching centrality of a node or a graph."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+ __all__ = ["global_reaching_centrality", "local_reaching_centrality"]
7
+
8
+
9
+ def _average_weight(G, path, weight=None):
10
+ """Returns the average weight of an edge in a weighted path.
11
+
12
+ Parameters
13
+ ----------
14
+ G : graph
15
+ A networkx graph.
16
+
17
+ path: list
18
+ A list of vertices that define the path.
19
+
20
+ weight : None or string, optional (default=None)
21
+ If None, edge weights are ignored. Then the average weight of an edge
22
+ is assumed to be the multiplicative inverse of the length of the path.
23
+ Otherwise holds the name of the edge attribute used as weight.
24
+ """
25
+ path_length = len(path) - 1
26
+ if path_length <= 0:
27
+ return 0
28
+ if weight is None:
29
+ return 1 / path_length
30
+ total_weight = sum(G.edges[i, j][weight] for i, j in pairwise(path))
31
+ return total_weight / path_length
32
+
33
+
34
+ @nx._dispatchable(edge_attrs="weight")
35
+ def global_reaching_centrality(G, weight=None, normalized=True):
36
+ """Returns the global reaching centrality of a directed graph.
37
+
38
+ The *global reaching centrality* of a weighted directed graph is the
39
+ average over all nodes of the difference between the local reaching
40
+ centrality of the node and the greatest local reaching centrality of
41
+ any node in the graph [1]_. For more information on the local
42
+ reaching centrality, see :func:`local_reaching_centrality`.
43
+ Informally, the local reaching centrality is the proportion of the
44
+ graph that is reachable from the neighbors of the node.
45
+
46
+ Parameters
47
+ ----------
48
+ G : DiGraph
49
+ A networkx DiGraph.
50
+
51
+ weight : None or string, optional (default=None)
52
+ Attribute to use for edge weights. If ``None``, each edge weight
53
+ is assumed to be one. A higher weight implies a stronger
54
+ connection between nodes and a *shorter* path length.
55
+
56
+ normalized : bool, optional (default=True)
57
+ Whether to normalize the edge weights by the total sum of edge
58
+ weights.
59
+
60
+ Returns
61
+ -------
62
+ h : float
63
+ The global reaching centrality of the graph.
64
+
65
+ Examples
66
+ --------
67
+ >>> G = nx.DiGraph()
68
+ >>> G.add_edge(1, 2)
69
+ >>> G.add_edge(1, 3)
70
+ >>> nx.global_reaching_centrality(G)
71
+ 1.0
72
+ >>> G.add_edge(3, 2)
73
+ >>> nx.global_reaching_centrality(G)
74
+ 0.75
75
+
76
+ See also
77
+ --------
78
+ local_reaching_centrality
79
+
80
+ References
81
+ ----------
82
+ .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
83
+ "Hierarchy Measure for Complex Networks."
84
+ *PLoS ONE* 7.3 (2012): e33799.
85
+ https://doi.org/10.1371/journal.pone.0033799
86
+ """
87
+ if nx.is_negatively_weighted(G, weight=weight):
88
+ raise nx.NetworkXError("edge weights must be positive")
89
+ total_weight = G.size(weight=weight)
90
+ if total_weight <= 0:
91
+ raise nx.NetworkXError("Size of G must be positive")
92
+ # If provided, weights must be interpreted as connection strength
93
+ # (so higher weights are more likely to be chosen). However, the
94
+ # shortest path algorithms in NetworkX assume the provided "weight"
95
+ # is actually a distance (so edges with higher weight are less
96
+ # likely to be chosen). Therefore we need to invert the weights when
97
+ # computing shortest paths.
98
+ #
99
+ # If weight is None, we leave it as-is so that the shortest path
100
+ # algorithm can use a faster, unweighted algorithm.
101
+ if weight is not None:
102
+
103
+ def as_distance(u, v, d):
104
+ return total_weight / d.get(weight, 1)
105
+
106
+ shortest_paths = nx.shortest_path(G, weight=as_distance)
107
+ else:
108
+ shortest_paths = nx.shortest_path(G)
109
+
110
+ centrality = local_reaching_centrality
111
+ # TODO This can be trivially parallelized.
112
+ lrc = [
113
+ centrality(G, node, paths=paths, weight=weight, normalized=normalized)
114
+ for node, paths in shortest_paths.items()
115
+ ]
116
+
117
+ max_lrc = max(lrc)
118
+ return sum(max_lrc - c for c in lrc) / (len(G) - 1)
119
+
120
+
121
+ @nx._dispatchable(edge_attrs="weight")
122
+ def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True):
123
+ """Returns the local reaching centrality of a node in a directed
124
+ graph.
125
+
126
+ The *local reaching centrality* of a node in a directed graph is the
127
+ proportion of other nodes reachable from that node [1]_.
128
+
129
+ Parameters
130
+ ----------
131
+ G : DiGraph
132
+ A NetworkX DiGraph.
133
+
134
+ v : node
135
+ A node in the directed graph `G`.
136
+
137
+ paths : dictionary (default=None)
138
+ If this is not `None` it must be a dictionary representation
139
+ of single-source shortest paths, as computed by, for example,
140
+ :func:`networkx.shortest_path` with source node `v`. Use this
141
+ keyword argument if you intend to invoke this function many
142
+ times but don't want the paths to be recomputed each time.
143
+
144
+ weight : None or string, optional (default=None)
145
+ Attribute to use for edge weights. If `None`, each edge weight
146
+ is assumed to be one. A higher weight implies a stronger
147
+ connection between nodes and a *shorter* path length.
148
+
149
+ normalized : bool, optional (default=True)
150
+ Whether to normalize the edge weights by the total sum of edge
151
+ weights.
152
+
153
+ Returns
154
+ -------
155
+ h : float
156
+ The local reaching centrality of the node ``v`` in the graph
157
+ ``G``.
158
+
159
+ Examples
160
+ --------
161
+ >>> G = nx.DiGraph()
162
+ >>> G.add_edges_from([(1, 2), (1, 3)])
163
+ >>> nx.local_reaching_centrality(G, 3)
164
+ 0.0
165
+ >>> G.add_edge(3, 2)
166
+ >>> nx.local_reaching_centrality(G, 3)
167
+ 0.5
168
+
169
+ See also
170
+ --------
171
+ global_reaching_centrality
172
+
173
+ References
174
+ ----------
175
+ .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
176
+ "Hierarchy Measure for Complex Networks."
177
+ *PLoS ONE* 7.3 (2012): e33799.
178
+ https://doi.org/10.1371/journal.pone.0033799
179
+ """
180
+ # Corner case: graph with single node containing a self-loop
181
+ if (total_weight := G.size(weight=weight)) > 0 and len(G) == 1:
182
+ raise nx.NetworkXError(
183
+ "local_reaching_centrality of a single node with self-loop not well-defined"
184
+ )
185
+ if paths is None:
186
+ if nx.is_negatively_weighted(G, weight=weight):
187
+ raise nx.NetworkXError("edge weights must be positive")
188
+ if total_weight <= 0:
189
+ raise nx.NetworkXError("Size of G must be positive")
190
+ if weight is not None:
191
+ # Interpret weights as lengths.
192
+ def as_distance(u, v, d):
193
+ return total_weight / d.get(weight, 1)
194
+
195
+ paths = nx.shortest_path(G, source=v, weight=as_distance)
196
+ else:
197
+ paths = nx.shortest_path(G, source=v)
198
+ # If the graph is unweighted, simply return the proportion of nodes
199
+ # reachable from the source node ``v``.
200
+ if weight is None and G.is_directed():
201
+ return (len(paths) - 1) / (len(G) - 1)
202
+ if normalized and weight is not None:
203
+ norm = G.size(weight=weight) / G.size()
204
+ else:
205
+ norm = 1
206
+ # TODO This can be trivially parallelized.
207
+ avgw = (_average_weight(G, path, weight=weight) for path in paths.values())
208
+ sum_avg_weight = sum(avgw) / norm
209
+ return sum_avg_weight / (len(G) - 1)
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/second_order.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Copyright (c) 2015 – Thomson Licensing, SAS
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted (subject to the limitations in the
5
+ disclaimer below) provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of Thomson Licensing, or Technicolor, nor the names
15
+ of its contributors may be used to endorse or promote products derived
16
+ from this software without specific prior written permission.
17
+
18
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
19
+ GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
20
+ HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
21
+ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29
+ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
30
+ IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+ """
32
+
33
+ import networkx as nx
34
+ from networkx.utils import not_implemented_for
35
+
36
+ # Authors: Erwan Le Merrer (erwan.lemerrer@technicolor.com)
37
+
38
+ __all__ = ["second_order_centrality"]
39
+
40
+
41
+ @not_implemented_for("directed")
42
+ @nx._dispatchable(edge_attrs="weight")
43
+ def second_order_centrality(G, weight="weight"):
44
+ """Compute the second order centrality for nodes of G.
45
+
46
+ The second order centrality of a given node is the standard deviation of
47
+ the return times to that node of a perpetual random walk on G:
48
+
49
+ Parameters
50
+ ----------
51
+ G : graph
52
+ A NetworkX connected and undirected graph.
53
+
54
+ weight : string or None, optional (default="weight")
55
+ The name of an edge attribute that holds the numerical value
56
+ used as a weight. If None then each edge has weight 1.
57
+
58
+ Returns
59
+ -------
60
+ nodes : dictionary
61
+ Dictionary keyed by node with second order centrality as the value.
62
+
63
+ Examples
64
+ --------
65
+ >>> G = nx.star_graph(10)
66
+ >>> soc = nx.second_order_centrality(G)
67
+ >>> print(sorted(soc.items(), key=lambda x: x[1])[0][0]) # pick first id
68
+ 0
69
+
70
+ Raises
71
+ ------
72
+ NetworkXException
73
+ If the graph G is empty, non connected or has negative weights.
74
+
75
+ See Also
76
+ --------
77
+ betweenness_centrality
78
+
79
+ Notes
80
+ -----
81
+ Lower values of second order centrality indicate higher centrality.
82
+
83
+ The algorithm is from Kermarrec, Le Merrer, Sericola and Trédan [1]_.
84
+
85
+ This code implements the analytical version of the algorithm, i.e.,
86
+ there is no simulation of a random walk process involved. The random walk
87
+ is here unbiased (corresponding to eq 6 of the paper [1]_), thus the
88
+ centrality values are the standard deviations for random walk return times
89
+ on the transformed input graph G (equal in-degree at each nodes by adding
90
+ self-loops).
91
+
92
+ Complexity of this implementation, made to run locally on a single machine,
93
+ is O(n^3), with n the size of G, which makes it viable only for small
94
+ graphs.
95
+
96
+ References
97
+ ----------
98
+ .. [1] Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan
99
+ "Second order centrality: Distributed assessment of nodes criticity in
100
+ complex networks", Elsevier Computer Communications 34(5):619-628, 2011.
101
+ """
102
+ import numpy as np
103
+
104
+ n = len(G)
105
+
106
+ if n == 0:
107
+ raise nx.NetworkXException("Empty graph.")
108
+ if not nx.is_connected(G):
109
+ raise nx.NetworkXException("Non connected graph.")
110
+ if any(d.get(weight, 0) < 0 for u, v, d in G.edges(data=True)):
111
+ raise nx.NetworkXException("Graph has negative edge weights.")
112
+
113
+ # balancing G for Metropolis-Hastings random walks
114
+ G = nx.DiGraph(G)
115
+ in_deg = dict(G.in_degree(weight=weight))
116
+ d_max = max(in_deg.values())
117
+ for i, deg in in_deg.items():
118
+ if deg < d_max:
119
+ G.add_edge(i, i, weight=d_max - deg)
120
+
121
+ P = nx.to_numpy_array(G)
122
+ P /= P.sum(axis=1)[:, np.newaxis] # to transition probability matrix
123
+
124
+ def _Qj(P, j):
125
+ P = P.copy()
126
+ P[:, j] = 0
127
+ return P
128
+
129
+ M = np.empty([n, n])
130
+
131
+ for i in range(n):
132
+ M[:, i] = np.linalg.solve(
133
+ np.identity(n) - _Qj(P, i), np.ones([n, 1])[:, 0]
134
+ ) # eq 3
135
+
136
+ return dict(
137
+ zip(
138
+ G.nodes,
139
+ (float(np.sqrt(2 * np.sum(M[:, i]) - n * (n + 1))) for i in range(n)),
140
+ )
141
+ ) # eq 6
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/subgraph_alg.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Subraph centrality and communicability betweenness.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = [
9
+ "subgraph_centrality_exp",
10
+ "subgraph_centrality",
11
+ "communicability_betweenness_centrality",
12
+ "estrada_index",
13
+ ]
14
+
15
+
16
+ @not_implemented_for("directed")
17
+ @not_implemented_for("multigraph")
18
+ @nx._dispatchable
19
+ def subgraph_centrality_exp(G):
20
+ r"""Returns the subgraph centrality for each node of G.
21
+
22
+ Subgraph centrality of a node `n` is the sum of weighted closed
23
+ walks of all lengths starting and ending at node `n`. The weights
24
+ decrease with path length. Each closed walk is associated with a
25
+ connected subgraph ([1]_).
26
+
27
+ Parameters
28
+ ----------
29
+ G: graph
30
+
31
+ Returns
32
+ -------
33
+ nodes:dictionary
34
+ Dictionary of nodes with subgraph centrality as the value.
35
+
36
+ Raises
37
+ ------
38
+ NetworkXError
39
+ If the graph is not undirected and simple.
40
+
41
+ See Also
42
+ --------
43
+ subgraph_centrality:
44
+ Alternative algorithm of the subgraph centrality for each node of G.
45
+
46
+ Notes
47
+ -----
48
+ This version of the algorithm exponentiates the adjacency matrix.
49
+
50
+ The subgraph centrality of a node `u` in G can be found using
51
+ the matrix exponential of the adjacency matrix of G [1]_,
52
+
53
+ .. math::
54
+
55
+ SC(u)=(e^A)_{uu} .
56
+
57
+ References
58
+ ----------
59
+ .. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez,
60
+ "Subgraph centrality in complex networks",
61
+ Physical Review E 71, 056103 (2005).
62
+ https://arxiv.org/abs/cond-mat/0504730
63
+
64
+ Examples
65
+ --------
66
+ (Example from [1]_)
67
+ >>> G = nx.Graph(
68
+ ... [
69
+ ... (1, 2),
70
+ ... (1, 5),
71
+ ... (1, 8),
72
+ ... (2, 3),
73
+ ... (2, 8),
74
+ ... (3, 4),
75
+ ... (3, 6),
76
+ ... (4, 5),
77
+ ... (4, 7),
78
+ ... (5, 6),
79
+ ... (6, 7),
80
+ ... (7, 8),
81
+ ... ]
82
+ ... )
83
+ >>> sc = nx.subgraph_centrality_exp(G)
84
+ >>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)])
85
+ ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
86
+ """
87
+ # alternative implementation that calculates the matrix exponential
88
+ import scipy as sp
89
+
90
+ nodelist = list(G) # ordering of nodes in matrix
91
+ A = nx.to_numpy_array(G, nodelist)
92
+ # convert to 0-1 matrix
93
+ A[A != 0.0] = 1
94
+ expA = sp.linalg.expm(A)
95
+ # convert diagonal to dictionary keyed by node
96
+ sc = dict(zip(nodelist, map(float, expA.diagonal())))
97
+ return sc
98
+
99
+
100
+ @not_implemented_for("directed")
101
+ @not_implemented_for("multigraph")
102
+ @nx._dispatchable
103
+ def subgraph_centrality(G):
104
+ r"""Returns subgraph centrality for each node in G.
105
+
106
+ Subgraph centrality of a node `n` is the sum of weighted closed
107
+ walks of all lengths starting and ending at node `n`. The weights
108
+ decrease with path length. Each closed walk is associated with a
109
+ connected subgraph ([1]_).
110
+
111
+ Parameters
112
+ ----------
113
+ G: graph
114
+
115
+ Returns
116
+ -------
117
+ nodes : dictionary
118
+ Dictionary of nodes with subgraph centrality as the value.
119
+
120
+ Raises
121
+ ------
122
+ NetworkXError
123
+ If the graph is not undirected and simple.
124
+
125
+ See Also
126
+ --------
127
+ subgraph_centrality_exp:
128
+ Alternative algorithm of the subgraph centrality for each node of G.
129
+
130
+ Notes
131
+ -----
132
+ This version of the algorithm computes eigenvalues and eigenvectors
133
+ of the adjacency matrix.
134
+
135
+ Subgraph centrality of a node `u` in G can be found using
136
+ a spectral decomposition of the adjacency matrix [1]_,
137
+
138
+ .. math::
139
+
140
+ SC(u)=\sum_{j=1}^{N}(v_{j}^{u})^2 e^{\lambda_{j}},
141
+
142
+ where `v_j` is an eigenvector of the adjacency matrix `A` of G
143
+ corresponding to the eigenvalue `\lambda_j`.
144
+
145
+ Examples
146
+ --------
147
+ (Example from [1]_)
148
+ >>> G = nx.Graph(
149
+ ... [
150
+ ... (1, 2),
151
+ ... (1, 5),
152
+ ... (1, 8),
153
+ ... (2, 3),
154
+ ... (2, 8),
155
+ ... (3, 4),
156
+ ... (3, 6),
157
+ ... (4, 5),
158
+ ... (4, 7),
159
+ ... (5, 6),
160
+ ... (6, 7),
161
+ ... (7, 8),
162
+ ... ]
163
+ ... )
164
+ >>> sc = nx.subgraph_centrality(G)
165
+ >>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)])
166
+ ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
167
+
168
+ References
169
+ ----------
170
+ .. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez,
171
+ "Subgraph centrality in complex networks",
172
+ Physical Review E 71, 056103 (2005).
173
+ https://arxiv.org/abs/cond-mat/0504730
174
+
175
+ """
176
+ import numpy as np
177
+
178
+ nodelist = list(G) # ordering of nodes in matrix
179
+ A = nx.to_numpy_array(G, nodelist)
180
+ # convert to 0-1 matrix
181
+ A[np.nonzero(A)] = 1
182
+ w, v = np.linalg.eigh(A)
183
+ vsquare = np.array(v) ** 2
184
+ expw = np.exp(w)
185
+ xg = vsquare @ expw
186
+ # convert vector dictionary keyed by node
187
+ sc = dict(zip(nodelist, map(float, xg)))
188
+ return sc
189
+
190
+
191
+ @not_implemented_for("directed")
192
+ @not_implemented_for("multigraph")
193
+ @nx._dispatchable
194
+ def communicability_betweenness_centrality(G):
195
+ r"""Returns subgraph communicability for all pairs of nodes in G.
196
+
197
+ Communicability betweenness measure makes use of the number of walks
198
+ connecting every pair of nodes as the basis of a betweenness centrality
199
+ measure.
200
+
201
+ Parameters
202
+ ----------
203
+ G: graph
204
+
205
+ Returns
206
+ -------
207
+ nodes : dictionary
208
+ Dictionary of nodes with communicability betweenness as the value.
209
+
210
+ Raises
211
+ ------
212
+ NetworkXError
213
+ If the graph is not undirected and simple.
214
+
215
+ Notes
216
+ -----
217
+ Let `G=(V,E)` be a simple undirected graph with `n` nodes and `m` edges,
218
+ and `A` denote the adjacency matrix of `G`.
219
+
220
+ Let `G(r)=(V,E(r))` be the graph resulting from
221
+ removing all edges connected to node `r` but not the node itself.
222
+
223
+ The adjacency matrix for `G(r)` is `A+E(r)`, where `E(r)` has nonzeros
224
+ only in row and column `r`.
225
+
226
+ The subraph betweenness of a node `r` is [1]_
227
+
228
+ .. math::
229
+
230
+ \omega_{r} = \frac{1}{C}\sum_{p}\sum_{q}\frac{G_{prq}}{G_{pq}},
231
+ p\neq q, q\neq r,
232
+
233
+ where
234
+ `G_{prq}=(e^{A}_{pq} - (e^{A+E(r)})_{pq}` is the number of walks
235
+ involving node r,
236
+ `G_{pq}=(e^{A})_{pq}` is the number of closed walks starting
237
+ at node `p` and ending at node `q`,
238
+ and `C=(n-1)^{2}-(n-1)` is a normalization factor equal to the
239
+ number of terms in the sum.
240
+
241
+ The resulting `\omega_{r}` takes values between zero and one.
242
+ The lower bound cannot be attained for a connected
243
+ graph, and the upper bound is attained in the star graph.
244
+
245
+ References
246
+ ----------
247
+ .. [1] Ernesto Estrada, Desmond J. Higham, Naomichi Hatano,
248
+ "Communicability Betweenness in Complex Networks"
249
+ Physica A 388 (2009) 764-774.
250
+ https://arxiv.org/abs/0905.4102
251
+
252
+ Examples
253
+ --------
254
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
255
+ >>> cbc = nx.communicability_betweenness_centrality(G)
256
+ >>> print([f"{node} {cbc[node]:0.2f}" for node in sorted(cbc)])
257
+ ['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03']
258
+ """
259
+ import numpy as np
260
+ import scipy as sp
261
+
262
+ nodelist = list(G) # ordering of nodes in matrix
263
+ n = len(nodelist)
264
+ A = nx.to_numpy_array(G, nodelist)
265
+ # convert to 0-1 matrix
266
+ A[np.nonzero(A)] = 1
267
+ expA = sp.linalg.expm(A)
268
+ mapping = dict(zip(nodelist, range(n)))
269
+ cbc = {}
270
+ for v in G:
271
+ # remove row and col of node v
272
+ i = mapping[v]
273
+ row = A[i, :].copy()
274
+ col = A[:, i].copy()
275
+ A[i, :] = 0
276
+ A[:, i] = 0
277
+ B = (expA - sp.linalg.expm(A)) / expA
278
+ # sum with row/col of node v and diag set to zero
279
+ B[i, :] = 0
280
+ B[:, i] = 0
281
+ B -= np.diag(np.diag(B))
282
+ cbc[v] = float(B.sum())
283
+ # put row and col back
284
+ A[i, :] = row
285
+ A[:, i] = col
286
+ # rescale when more than two nodes
287
+ order = len(cbc)
288
+ if order > 2:
289
+ scale = 1.0 / ((order - 1.0) ** 2 - (order - 1.0))
290
+ cbc = {node: value * scale for node, value in cbc.items()}
291
+ return cbc
292
+
293
+
294
+ @nx._dispatchable
295
+ def estrada_index(G):
296
+ r"""Returns the Estrada index of a the graph G.
297
+
298
+ The Estrada Index is a topological index of folding or 3D "compactness" ([1]_).
299
+
300
+ Parameters
301
+ ----------
302
+ G: graph
303
+
304
+ Returns
305
+ -------
306
+ estrada index: float
307
+
308
+ Raises
309
+ ------
310
+ NetworkXError
311
+ If the graph is not undirected and simple.
312
+
313
+ Notes
314
+ -----
315
+ Let `G=(V,E)` be a simple undirected graph with `n` nodes and let
316
+ `\lambda_{1}\leq\lambda_{2}\leq\cdots\lambda_{n}`
317
+ be a non-increasing ordering of the eigenvalues of its adjacency
318
+ matrix `A`. The Estrada index is ([1]_, [2]_)
319
+
320
+ .. math::
321
+ EE(G)=\sum_{j=1}^n e^{\lambda _j}.
322
+
323
+ References
324
+ ----------
325
+ .. [1] E. Estrada, "Characterization of 3D molecular structure",
326
+ Chem. Phys. Lett. 319, 713 (2000).
327
+ https://doi.org/10.1016/S0009-2614(00)00158-5
328
+ .. [2] José Antonio de la Peñaa, Ivan Gutman, Juan Rada,
329
+ "Estimating the Estrada index",
330
+ Linear Algebra and its Applications. 427, 1 (2007).
331
+ https://doi.org/10.1016/j.laa.2007.06.020
332
+
333
+ Examples
334
+ --------
335
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
336
+ >>> ei = nx.estrada_index(G)
337
+ >>> print(f"{ei:0.5}")
338
+ 20.55
339
+ """
340
+ return sum(subgraph_centrality(G).values())
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_betweenness_centrality.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def weighted_G():
7
+ G = nx.Graph()
8
+ G.add_edge(0, 1, weight=3)
9
+ G.add_edge(0, 2, weight=2)
10
+ G.add_edge(0, 3, weight=6)
11
+ G.add_edge(0, 4, weight=4)
12
+ G.add_edge(1, 3, weight=5)
13
+ G.add_edge(1, 5, weight=5)
14
+ G.add_edge(2, 4, weight=1)
15
+ G.add_edge(3, 4, weight=2)
16
+ G.add_edge(3, 5, weight=1)
17
+ G.add_edge(4, 5, weight=4)
18
+ return G
19
+
20
+
21
+ class TestBetweennessCentrality:
22
+ def test_K5(self):
23
+ """Betweenness centrality: K5"""
24
+ G = nx.complete_graph(5)
25
+ b = nx.betweenness_centrality(G, weight=None, normalized=False)
26
+ b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
27
+ for n in sorted(G):
28
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
29
+
30
+ def test_K5_endpoints(self):
31
+ """Betweenness centrality: K5 endpoints"""
32
+ G = nx.complete_graph(5)
33
+ b = nx.betweenness_centrality(G, weight=None, normalized=False, endpoints=True)
34
+ b_answer = {0: 4.0, 1: 4.0, 2: 4.0, 3: 4.0, 4: 4.0}
35
+ for n in sorted(G):
36
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
37
+ # normalized = True case
38
+ b = nx.betweenness_centrality(G, weight=None, normalized=True, endpoints=True)
39
+ b_answer = {0: 0.4, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}
40
+ for n in sorted(G):
41
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
42
+
43
+ def test_P3_normalized(self):
44
+ """Betweenness centrality: P3 normalized"""
45
+ G = nx.path_graph(3)
46
+ b = nx.betweenness_centrality(G, weight=None, normalized=True)
47
+ b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
48
+ for n in sorted(G):
49
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
50
+
51
+ def test_P3(self):
52
+ """Betweenness centrality: P3"""
53
+ G = nx.path_graph(3)
54
+ b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
55
+ b = nx.betweenness_centrality(G, weight=None, normalized=False)
56
+ for n in sorted(G):
57
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
58
+
59
+ def test_sample_from_P3(self):
60
+ """Betweenness centrality: P3 sample"""
61
+ G = nx.path_graph(3)
62
+ b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
63
+ b = nx.betweenness_centrality(G, k=3, weight=None, normalized=False, seed=1)
64
+ for n in sorted(G):
65
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
66
+ b = nx.betweenness_centrality(G, k=2, weight=None, normalized=False, seed=1)
67
+ # python versions give different results with same seed
68
+ b_approx1 = {0: 0.0, 1: 1.5, 2: 0.0}
69
+ b_approx2 = {0: 0.0, 1: 0.75, 2: 0.0}
70
+ for n in sorted(G):
71
+ assert b[n] in (b_approx1[n], b_approx2[n])
72
+
73
+ def test_P3_endpoints(self):
74
+ """Betweenness centrality: P3 endpoints"""
75
+ G = nx.path_graph(3)
76
+ b_answer = {0: 2.0, 1: 3.0, 2: 2.0}
77
+ b = nx.betweenness_centrality(G, weight=None, normalized=False, endpoints=True)
78
+ for n in sorted(G):
79
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
80
+ # normalized = True case
81
+ b_answer = {0: 2 / 3, 1: 1.0, 2: 2 / 3}
82
+ b = nx.betweenness_centrality(G, weight=None, normalized=True, endpoints=True)
83
+ for n in sorted(G):
84
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
85
+
86
+ def test_krackhardt_kite_graph(self):
87
+ """Betweenness centrality: Krackhardt kite graph"""
88
+ G = nx.krackhardt_kite_graph()
89
+ b_answer = {
90
+ 0: 1.667,
91
+ 1: 1.667,
92
+ 2: 0.000,
93
+ 3: 7.333,
94
+ 4: 0.000,
95
+ 5: 16.667,
96
+ 6: 16.667,
97
+ 7: 28.000,
98
+ 8: 16.000,
99
+ 9: 0.000,
100
+ }
101
+ for b in b_answer:
102
+ b_answer[b] /= 2
103
+ b = nx.betweenness_centrality(G, weight=None, normalized=False)
104
+ for n in sorted(G):
105
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
106
+
107
+ def test_krackhardt_kite_graph_normalized(self):
108
+ """Betweenness centrality: Krackhardt kite graph normalized"""
109
+ G = nx.krackhardt_kite_graph()
110
+ b_answer = {
111
+ 0: 0.023,
112
+ 1: 0.023,
113
+ 2: 0.000,
114
+ 3: 0.102,
115
+ 4: 0.000,
116
+ 5: 0.231,
117
+ 6: 0.231,
118
+ 7: 0.389,
119
+ 8: 0.222,
120
+ 9: 0.000,
121
+ }
122
+ b = nx.betweenness_centrality(G, weight=None, normalized=True)
123
+ for n in sorted(G):
124
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
125
+
126
+ def test_florentine_families_graph(self):
127
+ """Betweenness centrality: Florentine families graph"""
128
+ G = nx.florentine_families_graph()
129
+ b_answer = {
130
+ "Acciaiuoli": 0.000,
131
+ "Albizzi": 0.212,
132
+ "Barbadori": 0.093,
133
+ "Bischeri": 0.104,
134
+ "Castellani": 0.055,
135
+ "Ginori": 0.000,
136
+ "Guadagni": 0.255,
137
+ "Lamberteschi": 0.000,
138
+ "Medici": 0.522,
139
+ "Pazzi": 0.000,
140
+ "Peruzzi": 0.022,
141
+ "Ridolfi": 0.114,
142
+ "Salviati": 0.143,
143
+ "Strozzi": 0.103,
144
+ "Tornabuoni": 0.092,
145
+ }
146
+
147
+ b = nx.betweenness_centrality(G, weight=None, normalized=True)
148
+ for n in sorted(G):
149
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
150
+
151
+ def test_les_miserables_graph(self):
152
+ """Betweenness centrality: Les Miserables graph"""
153
+ G = nx.les_miserables_graph()
154
+ b_answer = {
155
+ "Napoleon": 0.000,
156
+ "Myriel": 0.177,
157
+ "MlleBaptistine": 0.000,
158
+ "MmeMagloire": 0.000,
159
+ "CountessDeLo": 0.000,
160
+ "Geborand": 0.000,
161
+ "Champtercier": 0.000,
162
+ "Cravatte": 0.000,
163
+ "Count": 0.000,
164
+ "OldMan": 0.000,
165
+ "Valjean": 0.570,
166
+ "Labarre": 0.000,
167
+ "Marguerite": 0.000,
168
+ "MmeDeR": 0.000,
169
+ "Isabeau": 0.000,
170
+ "Gervais": 0.000,
171
+ "Listolier": 0.000,
172
+ "Tholomyes": 0.041,
173
+ "Fameuil": 0.000,
174
+ "Blacheville": 0.000,
175
+ "Favourite": 0.000,
176
+ "Dahlia": 0.000,
177
+ "Zephine": 0.000,
178
+ "Fantine": 0.130,
179
+ "MmeThenardier": 0.029,
180
+ "Thenardier": 0.075,
181
+ "Cosette": 0.024,
182
+ "Javert": 0.054,
183
+ "Fauchelevent": 0.026,
184
+ "Bamatabois": 0.008,
185
+ "Perpetue": 0.000,
186
+ "Simplice": 0.009,
187
+ "Scaufflaire": 0.000,
188
+ "Woman1": 0.000,
189
+ "Judge": 0.000,
190
+ "Champmathieu": 0.000,
191
+ "Brevet": 0.000,
192
+ "Chenildieu": 0.000,
193
+ "Cochepaille": 0.000,
194
+ "Pontmercy": 0.007,
195
+ "Boulatruelle": 0.000,
196
+ "Eponine": 0.011,
197
+ "Anzelma": 0.000,
198
+ "Woman2": 0.000,
199
+ "MotherInnocent": 0.000,
200
+ "Gribier": 0.000,
201
+ "MmeBurgon": 0.026,
202
+ "Jondrette": 0.000,
203
+ "Gavroche": 0.165,
204
+ "Gillenormand": 0.020,
205
+ "Magnon": 0.000,
206
+ "MlleGillenormand": 0.048,
207
+ "MmePontmercy": 0.000,
208
+ "MlleVaubois": 0.000,
209
+ "LtGillenormand": 0.000,
210
+ "Marius": 0.132,
211
+ "BaronessT": 0.000,
212
+ "Mabeuf": 0.028,
213
+ "Enjolras": 0.043,
214
+ "Combeferre": 0.001,
215
+ "Prouvaire": 0.000,
216
+ "Feuilly": 0.001,
217
+ "Courfeyrac": 0.005,
218
+ "Bahorel": 0.002,
219
+ "Bossuet": 0.031,
220
+ "Joly": 0.002,
221
+ "Grantaire": 0.000,
222
+ "MotherPlutarch": 0.000,
223
+ "Gueulemer": 0.005,
224
+ "Babet": 0.005,
225
+ "Claquesous": 0.005,
226
+ "Montparnasse": 0.004,
227
+ "Toussaint": 0.000,
228
+ "Child1": 0.000,
229
+ "Child2": 0.000,
230
+ "Brujon": 0.000,
231
+ "MmeHucheloup": 0.000,
232
+ }
233
+
234
+ b = nx.betweenness_centrality(G, weight=None, normalized=True)
235
+ for n in sorted(G):
236
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
237
+
238
+ def test_ladder_graph(self):
239
+ """Betweenness centrality: Ladder graph"""
240
+ G = nx.Graph() # ladder_graph(3)
241
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
242
+ b_answer = {0: 1.667, 1: 1.667, 2: 6.667, 3: 6.667, 4: 1.667, 5: 1.667}
243
+ for b in b_answer:
244
+ b_answer[b] /= 2
245
+ b = nx.betweenness_centrality(G, weight=None, normalized=False)
246
+ for n in sorted(G):
247
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
248
+
249
+ def test_disconnected_path(self):
250
+ """Betweenness centrality: disconnected path"""
251
+ G = nx.Graph()
252
+ nx.add_path(G, [0, 1, 2])
253
+ nx.add_path(G, [3, 4, 5, 6])
254
+ b_answer = {0: 0, 1: 1, 2: 0, 3: 0, 4: 2, 5: 2, 6: 0}
255
+ b = nx.betweenness_centrality(G, weight=None, normalized=False)
256
+ for n in sorted(G):
257
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
258
+
259
+ def test_disconnected_path_endpoints(self):
260
+ """Betweenness centrality: disconnected path endpoints"""
261
+ G = nx.Graph()
262
+ nx.add_path(G, [0, 1, 2])
263
+ nx.add_path(G, [3, 4, 5, 6])
264
+ b_answer = {0: 2, 1: 3, 2: 2, 3: 3, 4: 5, 5: 5, 6: 3}
265
+ b = nx.betweenness_centrality(G, weight=None, normalized=False, endpoints=True)
266
+ for n in sorted(G):
267
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
268
+ # normalized = True case
269
+ b = nx.betweenness_centrality(G, weight=None, normalized=True, endpoints=True)
270
+ for n in sorted(G):
271
+ assert b[n] == pytest.approx(b_answer[n] / 21, abs=1e-7)
272
+
273
+ def test_directed_path(self):
274
+ """Betweenness centrality: directed path"""
275
+ G = nx.DiGraph()
276
+ nx.add_path(G, [0, 1, 2])
277
+ b = nx.betweenness_centrality(G, weight=None, normalized=False)
278
+ b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
279
+ for n in sorted(G):
280
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
281
+
282
+ def test_directed_path_normalized(self):
283
+ """Betweenness centrality: directed path normalized"""
284
+ G = nx.DiGraph()
285
+ nx.add_path(G, [0, 1, 2])
286
+ b = nx.betweenness_centrality(G, weight=None, normalized=True)
287
+ b_answer = {0: 0.0, 1: 0.5, 2: 0.0}
288
+ for n in sorted(G):
289
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
290
+
291
+
292
+ class TestWeightedBetweennessCentrality:
293
+ def test_K5(self):
294
+ """Weighted betweenness centrality: K5"""
295
+ G = nx.complete_graph(5)
296
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
297
+ b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
298
+ for n in sorted(G):
299
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
300
+
301
+ def test_P3_normalized(self):
302
+ """Weighted betweenness centrality: P3 normalized"""
303
+ G = nx.path_graph(3)
304
+ b = nx.betweenness_centrality(G, weight="weight", normalized=True)
305
+ b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
306
+ for n in sorted(G):
307
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
308
+
309
+ def test_P3(self):
310
+ """Weighted betweenness centrality: P3"""
311
+ G = nx.path_graph(3)
312
+ b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
313
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
314
+ for n in sorted(G):
315
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
316
+
317
+ def test_krackhardt_kite_graph(self):
318
+ """Weighted betweenness centrality: Krackhardt kite graph"""
319
+ G = nx.krackhardt_kite_graph()
320
+ b_answer = {
321
+ 0: 1.667,
322
+ 1: 1.667,
323
+ 2: 0.000,
324
+ 3: 7.333,
325
+ 4: 0.000,
326
+ 5: 16.667,
327
+ 6: 16.667,
328
+ 7: 28.000,
329
+ 8: 16.000,
330
+ 9: 0.000,
331
+ }
332
+ for b in b_answer:
333
+ b_answer[b] /= 2
334
+
335
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
336
+
337
+ for n in sorted(G):
338
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
339
+
340
+ def test_krackhardt_kite_graph_normalized(self):
341
+ """Weighted betweenness centrality:
342
+ Krackhardt kite graph normalized
343
+ """
344
+ G = nx.krackhardt_kite_graph()
345
+ b_answer = {
346
+ 0: 0.023,
347
+ 1: 0.023,
348
+ 2: 0.000,
349
+ 3: 0.102,
350
+ 4: 0.000,
351
+ 5: 0.231,
352
+ 6: 0.231,
353
+ 7: 0.389,
354
+ 8: 0.222,
355
+ 9: 0.000,
356
+ }
357
+ b = nx.betweenness_centrality(G, weight="weight", normalized=True)
358
+
359
+ for n in sorted(G):
360
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
361
+
362
+ def test_florentine_families_graph(self):
363
+ """Weighted betweenness centrality:
364
+ Florentine families graph"""
365
+ G = nx.florentine_families_graph()
366
+ b_answer = {
367
+ "Acciaiuoli": 0.000,
368
+ "Albizzi": 0.212,
369
+ "Barbadori": 0.093,
370
+ "Bischeri": 0.104,
371
+ "Castellani": 0.055,
372
+ "Ginori": 0.000,
373
+ "Guadagni": 0.255,
374
+ "Lamberteschi": 0.000,
375
+ "Medici": 0.522,
376
+ "Pazzi": 0.000,
377
+ "Peruzzi": 0.022,
378
+ "Ridolfi": 0.114,
379
+ "Salviati": 0.143,
380
+ "Strozzi": 0.103,
381
+ "Tornabuoni": 0.092,
382
+ }
383
+
384
+ b = nx.betweenness_centrality(G, weight="weight", normalized=True)
385
+ for n in sorted(G):
386
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
387
+
388
+ def test_les_miserables_graph(self):
389
+ """Weighted betweenness centrality: Les Miserables graph"""
390
+ G = nx.les_miserables_graph()
391
+ b_answer = {
392
+ "Napoleon": 0.000,
393
+ "Myriel": 0.177,
394
+ "MlleBaptistine": 0.000,
395
+ "MmeMagloire": 0.000,
396
+ "CountessDeLo": 0.000,
397
+ "Geborand": 0.000,
398
+ "Champtercier": 0.000,
399
+ "Cravatte": 0.000,
400
+ "Count": 0.000,
401
+ "OldMan": 0.000,
402
+ "Valjean": 0.454,
403
+ "Labarre": 0.000,
404
+ "Marguerite": 0.009,
405
+ "MmeDeR": 0.000,
406
+ "Isabeau": 0.000,
407
+ "Gervais": 0.000,
408
+ "Listolier": 0.000,
409
+ "Tholomyes": 0.066,
410
+ "Fameuil": 0.000,
411
+ "Blacheville": 0.000,
412
+ "Favourite": 0.000,
413
+ "Dahlia": 0.000,
414
+ "Zephine": 0.000,
415
+ "Fantine": 0.114,
416
+ "MmeThenardier": 0.046,
417
+ "Thenardier": 0.129,
418
+ "Cosette": 0.075,
419
+ "Javert": 0.193,
420
+ "Fauchelevent": 0.026,
421
+ "Bamatabois": 0.080,
422
+ "Perpetue": 0.000,
423
+ "Simplice": 0.001,
424
+ "Scaufflaire": 0.000,
425
+ "Woman1": 0.000,
426
+ "Judge": 0.000,
427
+ "Champmathieu": 0.000,
428
+ "Brevet": 0.000,
429
+ "Chenildieu": 0.000,
430
+ "Cochepaille": 0.000,
431
+ "Pontmercy": 0.023,
432
+ "Boulatruelle": 0.000,
433
+ "Eponine": 0.023,
434
+ "Anzelma": 0.000,
435
+ "Woman2": 0.000,
436
+ "MotherInnocent": 0.000,
437
+ "Gribier": 0.000,
438
+ "MmeBurgon": 0.026,
439
+ "Jondrette": 0.000,
440
+ "Gavroche": 0.285,
441
+ "Gillenormand": 0.024,
442
+ "Magnon": 0.005,
443
+ "MlleGillenormand": 0.036,
444
+ "MmePontmercy": 0.005,
445
+ "MlleVaubois": 0.000,
446
+ "LtGillenormand": 0.015,
447
+ "Marius": 0.072,
448
+ "BaronessT": 0.004,
449
+ "Mabeuf": 0.089,
450
+ "Enjolras": 0.003,
451
+ "Combeferre": 0.000,
452
+ "Prouvaire": 0.000,
453
+ "Feuilly": 0.004,
454
+ "Courfeyrac": 0.001,
455
+ "Bahorel": 0.007,
456
+ "Bossuet": 0.028,
457
+ "Joly": 0.000,
458
+ "Grantaire": 0.036,
459
+ "MotherPlutarch": 0.000,
460
+ "Gueulemer": 0.025,
461
+ "Babet": 0.015,
462
+ "Claquesous": 0.042,
463
+ "Montparnasse": 0.050,
464
+ "Toussaint": 0.011,
465
+ "Child1": 0.000,
466
+ "Child2": 0.000,
467
+ "Brujon": 0.002,
468
+ "MmeHucheloup": 0.034,
469
+ }
470
+
471
+ b = nx.betweenness_centrality(G, weight="weight", normalized=True)
472
+ for n in sorted(G):
473
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
474
+
475
+ def test_ladder_graph(self):
476
+ """Weighted betweenness centrality: Ladder graph"""
477
+ G = nx.Graph() # ladder_graph(3)
478
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
479
+ b_answer = {0: 1.667, 1: 1.667, 2: 6.667, 3: 6.667, 4: 1.667, 5: 1.667}
480
+ for b in b_answer:
481
+ b_answer[b] /= 2
482
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
483
+ for n in sorted(G):
484
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
485
+
486
+ def test_G(self):
487
+ """Weighted betweenness centrality: G"""
488
+ G = weighted_G()
489
+ b_answer = {0: 2.0, 1: 0.0, 2: 4.0, 3: 3.0, 4: 4.0, 5: 0.0}
490
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
491
+ for n in sorted(G):
492
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
493
+
494
+ def test_G2(self):
495
+ """Weighted betweenness centrality: G2"""
496
+ G = nx.DiGraph()
497
+ G.add_weighted_edges_from(
498
+ [
499
+ ("s", "u", 10),
500
+ ("s", "x", 5),
501
+ ("u", "v", 1),
502
+ ("u", "x", 2),
503
+ ("v", "y", 1),
504
+ ("x", "u", 3),
505
+ ("x", "v", 5),
506
+ ("x", "y", 2),
507
+ ("y", "s", 7),
508
+ ("y", "v", 6),
509
+ ]
510
+ )
511
+
512
+ b_answer = {"y": 5.0, "x": 5.0, "s": 4.0, "u": 2.0, "v": 2.0}
513
+
514
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
515
+ for n in sorted(G):
516
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
517
+
518
+ def test_G3(self):
519
+ """Weighted betweenness centrality: G3"""
520
+ G = nx.MultiGraph(weighted_G())
521
+ es = list(G.edges(data=True))[::2] # duplicate every other edge
522
+ G.add_edges_from(es)
523
+ b_answer = {0: 2.0, 1: 0.0, 2: 4.0, 3: 3.0, 4: 4.0, 5: 0.0}
524
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
525
+ for n in sorted(G):
526
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
527
+
528
+ def test_G4(self):
529
+ """Weighted betweenness centrality: G4"""
530
+ G = nx.MultiDiGraph()
531
+ G.add_weighted_edges_from(
532
+ [
533
+ ("s", "u", 10),
534
+ ("s", "x", 5),
535
+ ("s", "x", 6),
536
+ ("u", "v", 1),
537
+ ("u", "x", 2),
538
+ ("v", "y", 1),
539
+ ("v", "y", 1),
540
+ ("x", "u", 3),
541
+ ("x", "v", 5),
542
+ ("x", "y", 2),
543
+ ("x", "y", 3),
544
+ ("y", "s", 7),
545
+ ("y", "v", 6),
546
+ ("y", "v", 6),
547
+ ]
548
+ )
549
+
550
+ b_answer = {"y": 5.0, "x": 5.0, "s": 4.0, "u": 2.0, "v": 2.0}
551
+
552
+ b = nx.betweenness_centrality(G, weight="weight", normalized=False)
553
+ for n in sorted(G):
554
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
555
+
556
+
557
+ class TestEdgeBetweennessCentrality:
558
+ def test_K5(self):
559
+ """Edge betweenness centrality: K5"""
560
+ G = nx.complete_graph(5)
561
+ b = nx.edge_betweenness_centrality(G, weight=None, normalized=False)
562
+ b_answer = dict.fromkeys(G.edges(), 1)
563
+ for n in sorted(G.edges()):
564
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
565
+
566
+ def test_normalized_K5(self):
567
+ """Edge betweenness centrality: K5"""
568
+ G = nx.complete_graph(5)
569
+ b = nx.edge_betweenness_centrality(G, weight=None, normalized=True)
570
+ b_answer = dict.fromkeys(G.edges(), 1 / 10)
571
+ for n in sorted(G.edges()):
572
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
573
+
574
+ def test_C4(self):
575
+ """Edge betweenness centrality: C4"""
576
+ G = nx.cycle_graph(4)
577
+ b = nx.edge_betweenness_centrality(G, weight=None, normalized=True)
578
+ b_answer = {(0, 1): 2, (0, 3): 2, (1, 2): 2, (2, 3): 2}
579
+ for n in sorted(G.edges()):
580
+ assert b[n] == pytest.approx(b_answer[n] / 6, abs=1e-7)
581
+
582
+ def test_P4(self):
583
+ """Edge betweenness centrality: P4"""
584
+ G = nx.path_graph(4)
585
+ b = nx.edge_betweenness_centrality(G, weight=None, normalized=False)
586
+ b_answer = {(0, 1): 3, (1, 2): 4, (2, 3): 3}
587
+ for n in sorted(G.edges()):
588
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
589
+
590
+ def test_normalized_P4(self):
591
+ """Edge betweenness centrality: P4"""
592
+ G = nx.path_graph(4)
593
+ b = nx.edge_betweenness_centrality(G, weight=None, normalized=True)
594
+ b_answer = {(0, 1): 3, (1, 2): 4, (2, 3): 3}
595
+ for n in sorted(G.edges()):
596
+ assert b[n] == pytest.approx(b_answer[n] / 6, abs=1e-7)
597
+
598
+ def test_balanced_tree(self):
599
+ """Edge betweenness centrality: balanced tree"""
600
+ G = nx.balanced_tree(r=2, h=2)
601
+ b = nx.edge_betweenness_centrality(G, weight=None, normalized=False)
602
+ b_answer = {(0, 1): 12, (0, 2): 12, (1, 3): 6, (1, 4): 6, (2, 5): 6, (2, 6): 6}
603
+ for n in sorted(G.edges()):
604
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
605
+
606
+
607
+ class TestWeightedEdgeBetweennessCentrality:
608
+ def test_K5(self):
609
+ """Edge betweenness centrality: K5"""
610
+ G = nx.complete_graph(5)
611
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False)
612
+ b_answer = dict.fromkeys(G.edges(), 1)
613
+ for n in sorted(G.edges()):
614
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
615
+
616
+ def test_C4(self):
617
+ """Edge betweenness centrality: C4"""
618
+ G = nx.cycle_graph(4)
619
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False)
620
+ b_answer = {(0, 1): 2, (0, 3): 2, (1, 2): 2, (2, 3): 2}
621
+ for n in sorted(G.edges()):
622
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
623
+
624
+ def test_P4(self):
625
+ """Edge betweenness centrality: P4"""
626
+ G = nx.path_graph(4)
627
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False)
628
+ b_answer = {(0, 1): 3, (1, 2): 4, (2, 3): 3}
629
+ for n in sorted(G.edges()):
630
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
631
+
632
+ def test_balanced_tree(self):
633
+ """Edge betweenness centrality: balanced tree"""
634
+ G = nx.balanced_tree(r=2, h=2)
635
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False)
636
+ b_answer = {(0, 1): 12, (0, 2): 12, (1, 3): 6, (1, 4): 6, (2, 5): 6, (2, 6): 6}
637
+ for n in sorted(G.edges()):
638
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
639
+
640
+ def test_weighted_graph(self):
641
+ """Edge betweenness centrality: weighted"""
642
+ eList = [
643
+ (0, 1, 5),
644
+ (0, 2, 4),
645
+ (0, 3, 3),
646
+ (0, 4, 2),
647
+ (1, 2, 4),
648
+ (1, 3, 1),
649
+ (1, 4, 3),
650
+ (2, 4, 5),
651
+ (3, 4, 4),
652
+ ]
653
+ G = nx.Graph()
654
+ G.add_weighted_edges_from(eList)
655
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False)
656
+ b_answer = {
657
+ (0, 1): 0.0,
658
+ (0, 2): 1.0,
659
+ (0, 3): 2.0,
660
+ (0, 4): 1.0,
661
+ (1, 2): 2.0,
662
+ (1, 3): 3.5,
663
+ (1, 4): 1.5,
664
+ (2, 4): 1.0,
665
+ (3, 4): 0.5,
666
+ }
667
+ for n in sorted(G.edges()):
668
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
669
+
670
+ def test_normalized_weighted_graph(self):
671
+ """Edge betweenness centrality: normalized weighted"""
672
+ eList = [
673
+ (0, 1, 5),
674
+ (0, 2, 4),
675
+ (0, 3, 3),
676
+ (0, 4, 2),
677
+ (1, 2, 4),
678
+ (1, 3, 1),
679
+ (1, 4, 3),
680
+ (2, 4, 5),
681
+ (3, 4, 4),
682
+ ]
683
+ G = nx.Graph()
684
+ G.add_weighted_edges_from(eList)
685
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=True)
686
+ b_answer = {
687
+ (0, 1): 0.0,
688
+ (0, 2): 1.0,
689
+ (0, 3): 2.0,
690
+ (0, 4): 1.0,
691
+ (1, 2): 2.0,
692
+ (1, 3): 3.5,
693
+ (1, 4): 1.5,
694
+ (2, 4): 1.0,
695
+ (3, 4): 0.5,
696
+ }
697
+ norm = len(G) * (len(G) - 1) / 2
698
+ for n in sorted(G.edges()):
699
+ assert b[n] == pytest.approx(b_answer[n] / norm, abs=1e-7)
700
+
701
+ def test_weighted_multigraph(self):
702
+ """Edge betweenness centrality: weighted multigraph"""
703
+ eList = [
704
+ (0, 1, 5),
705
+ (0, 1, 4),
706
+ (0, 2, 4),
707
+ (0, 3, 3),
708
+ (0, 3, 3),
709
+ (0, 4, 2),
710
+ (1, 2, 4),
711
+ (1, 3, 1),
712
+ (1, 3, 2),
713
+ (1, 4, 3),
714
+ (1, 4, 4),
715
+ (2, 4, 5),
716
+ (3, 4, 4),
717
+ (3, 4, 4),
718
+ ]
719
+ G = nx.MultiGraph()
720
+ G.add_weighted_edges_from(eList)
721
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False)
722
+ b_answer = {
723
+ (0, 1, 0): 0.0,
724
+ (0, 1, 1): 0.5,
725
+ (0, 2, 0): 1.0,
726
+ (0, 3, 0): 0.75,
727
+ (0, 3, 1): 0.75,
728
+ (0, 4, 0): 1.0,
729
+ (1, 2, 0): 2.0,
730
+ (1, 3, 0): 3.0,
731
+ (1, 3, 1): 0.0,
732
+ (1, 4, 0): 1.5,
733
+ (1, 4, 1): 0.0,
734
+ (2, 4, 0): 1.0,
735
+ (3, 4, 0): 0.25,
736
+ (3, 4, 1): 0.25,
737
+ }
738
+ for n in sorted(G.edges(keys=True)):
739
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
740
+
741
+ def test_normalized_weighted_multigraph(self):
742
+ """Edge betweenness centrality: normalized weighted multigraph"""
743
+ eList = [
744
+ (0, 1, 5),
745
+ (0, 1, 4),
746
+ (0, 2, 4),
747
+ (0, 3, 3),
748
+ (0, 3, 3),
749
+ (0, 4, 2),
750
+ (1, 2, 4),
751
+ (1, 3, 1),
752
+ (1, 3, 2),
753
+ (1, 4, 3),
754
+ (1, 4, 4),
755
+ (2, 4, 5),
756
+ (3, 4, 4),
757
+ (3, 4, 4),
758
+ ]
759
+ G = nx.MultiGraph()
760
+ G.add_weighted_edges_from(eList)
761
+ b = nx.edge_betweenness_centrality(G, weight="weight", normalized=True)
762
+ b_answer = {
763
+ (0, 1, 0): 0.0,
764
+ (0, 1, 1): 0.5,
765
+ (0, 2, 0): 1.0,
766
+ (0, 3, 0): 0.75,
767
+ (0, 3, 1): 0.75,
768
+ (0, 4, 0): 1.0,
769
+ (1, 2, 0): 2.0,
770
+ (1, 3, 0): 3.0,
771
+ (1, 3, 1): 0.0,
772
+ (1, 4, 0): 1.5,
773
+ (1, 4, 1): 0.0,
774
+ (2, 4, 0): 1.0,
775
+ (3, 4, 0): 0.25,
776
+ (3, 4, 1): 0.25,
777
+ }
778
+ norm = len(G) * (len(G) - 1) / 2
779
+ for n in sorted(G.edges(keys=True)):
780
+ assert b[n] == pytest.approx(b_answer[n] / norm, abs=1e-7)