FaustDerLegende commited on
Commit
18a8dab
·
verified ·
1 Parent(s): 513beab

Upload folder using huggingface_hub (part 10)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/tournament.cpython-312.pyc +0 -0
  3. .venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/triads.cpython-312.pyc +0 -0
  4. .venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/vitality.cpython-312.pyc +0 -0
  5. .venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/voronoi.cpython-312.pyc +0 -0
  6. .venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/walks.cpython-312.pyc +0 -0
  7. .venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/wiener.cpython-312.pyc +0 -0
  8. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__init__.py +26 -0
  9. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-312.pyc +0 -0
  10. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/clique.cpython-312.pyc +0 -0
  11. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/clustering_coefficient.cpython-312.pyc +0 -0
  12. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/connectivity.cpython-312.pyc +0 -0
  13. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/density.cpython-312.pyc +0 -0
  14. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/distance_measures.cpython-312.pyc +0 -0
  15. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/dominating_set.cpython-312.pyc +0 -0
  16. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/kcomponents.cpython-312.pyc +0 -0
  17. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/matching.cpython-312.pyc +0 -0
  18. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/maxcut.cpython-312.pyc +0 -0
  19. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/ramsey.cpython-312.pyc +0 -0
  20. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/steinertree.cpython-312.pyc +0 -0
  21. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/traveling_salesman.cpython-312.pyc +0 -0
  22. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/treewidth.cpython-312.pyc +0 -0
  23. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/vertex_cover.cpython-312.pyc +0 -0
  24. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/clique.py +259 -0
  25. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/clustering_coefficient.py +71 -0
  26. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/connectivity.py +412 -0
  27. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/density.py +396 -0
  28. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/distance_measures.py +150 -0
  29. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/dominating_set.py +149 -0
  30. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/kcomponents.py +369 -0
  31. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/matching.py +44 -0
  32. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/maxcut.py +143 -0
  33. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/ramsey.py +53 -0
  34. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/steinertree.py +265 -0
  35. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__init__.py +0 -0
  36. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/__init__.cpython-312.pyc +0 -0
  37. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-312.pyc +0 -0
  38. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_clique.cpython-312.pyc +0 -0
  39. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_connectivity.cpython-312.pyc +0 -0
  40. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_density.cpython-312.pyc +0 -0
  41. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_distance_measures.cpython-312.pyc +0 -0
  42. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_dominating_set.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_matching.cpython-312.pyc +0 -0
  45. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-312.pyc +0 -0
  46. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_ramsey.cpython-312.pyc +0 -0
  47. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_traveling_salesman.cpython-312.pyc +0 -0
  49. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_treewidth.cpython-312.pyc +0 -0
  50. .venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_vertex_cover.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -230,3 +230,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
230
  .venv/lib/python3.12/site-packages/mpmath/__pycache__/function_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
231
  .venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_fp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
232
  .venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
230
  .venv/lib/python3.12/site-packages/mpmath/__pycache__/function_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
231
  .venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_fp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
232
  .venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
233
+ .venv/lib/python3.12/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/tournament.cpython-312.pyc ADDED
Binary file (15.5 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/triads.cpython-312.pyc ADDED
Binary file (16 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/vitality.cpython-312.pyc ADDED
Binary file (2.76 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/voronoi.cpython-312.pyc ADDED
Binary file (3.3 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/walks.cpython-312.pyc ADDED
Binary file (3.06 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/__pycache__/wiener.cpython-312.pyc ADDED
Binary file (11.7 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 *
26
+ from networkx.algorithms.approximation.density import *
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.47 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/clique.cpython-312.pyc ADDED
Binary file (8.99 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/clustering_coefficient.cpython-312.pyc ADDED
Binary file (2.85 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/connectivity.cpython-312.pyc ADDED
Binary file (13.7 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/density.cpython-312.pyc ADDED
Binary file (15.6 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/distance_measures.cpython-312.pyc ADDED
Binary file (6.03 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/dominating_set.cpython-312.pyc ADDED
Binary file (4.99 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/kcomponents.cpython-312.pyc ADDED
Binary file (18.6 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/matching.cpython-312.pyc ADDED
Binary file (1.56 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/maxcut.cpython-312.pyc ADDED
Binary file (5.32 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/ramsey.cpython-312.pyc ADDED
Binary file (2.26 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/steinertree.cpython-312.pyc ADDED
Binary file (12.5 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/traveling_salesman.cpython-312.pyc ADDED
Binary file (59.8 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/treewidth.cpython-312.pyc ADDED
Binary file (8.89 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/__pycache__/vertex_cover.cpython-312.pyc ADDED
Binary file (3.26 kB). View file
 
.venv/lib/python3.12/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.12/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.12/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.12/site-packages/networkx/algorithms/approximation/density.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast algorithms for the densest subgraph problem"""
2
+
3
+ import math
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["densest_subgraph"]
8
+
9
+
10
+ def _greedy_plus_plus(G, iterations):
11
+ if G.number_of_edges() == 0:
12
+ return 0.0, set()
13
+ if iterations < 1:
14
+ raise ValueError(
15
+ f"The number of iterations must be an integer >= 1. Provided: {iterations}"
16
+ )
17
+
18
+ loads = {node: 0 for node in G.nodes} # Load vector for Greedy++.
19
+ best_density = 0.0 # Highest density encountered.
20
+ best_subgraph = set() # Nodes of the best subgraph found.
21
+
22
+ for _ in range(iterations):
23
+ # Initialize heap for fast access to minimum weighted degree.
24
+ heap = nx.utils.BinaryHeap()
25
+
26
+ # Compute initial weighted degrees and add nodes to the heap.
27
+ for node, degree in G.degree:
28
+ heap.insert(node, loads[node] + degree)
29
+ # Set up tracking for current graph state.
30
+ remaining_nodes = set(G.nodes)
31
+ num_edges = G.number_of_edges()
32
+ current_degrees = dict(G.degree)
33
+
34
+ while remaining_nodes:
35
+ num_nodes = len(remaining_nodes)
36
+
37
+ # Current density of the (implicit) graph
38
+ current_density = num_edges / num_nodes
39
+
40
+ # Update the best density.
41
+ if current_density > best_density:
42
+ best_density = current_density
43
+ best_subgraph = set(remaining_nodes)
44
+
45
+ # Pop the node with the smallest weighted degree.
46
+ node, _ = heap.pop()
47
+ if node not in remaining_nodes:
48
+ continue # Skip nodes already removed.
49
+
50
+ # Update the load of the popped node.
51
+ loads[node] += current_degrees[node]
52
+
53
+ # Update neighbors' degrees and the heap.
54
+ for neighbor in G.neighbors(node):
55
+ if neighbor in remaining_nodes:
56
+ current_degrees[neighbor] -= 1
57
+ num_edges -= 1
58
+ heap.insert(neighbor, loads[neighbor] + current_degrees[neighbor])
59
+
60
+ # Remove the node from the remaining nodes.
61
+ remaining_nodes.remove(node)
62
+
63
+ return best_density, best_subgraph
64
+
65
+
66
+ def _fractional_peeling(G, b, x, node_to_idx, edge_to_idx):
67
+ """
68
+ Optimized fractional peeling using NumPy arrays.
69
+
70
+ Parameters
71
+ ----------
72
+ G : networkx.Graph
73
+ The input graph.
74
+ b : numpy.ndarray
75
+ Induced load vector.
76
+ x : numpy.ndarray
77
+ Fractional edge values.
78
+ node_to_idx : dict
79
+ Mapping from node to index.
80
+ edge_to_idx : dict
81
+ Mapping from edge to index.
82
+
83
+ Returns
84
+ -------
85
+ best_density : float
86
+ The best density found.
87
+ best_subgraph : set
88
+ The subset of nodes defining the densest subgraph.
89
+ """
90
+ heap = nx.utils.BinaryHeap()
91
+
92
+ remaining_nodes = set(G.nodes)
93
+
94
+ # Initialize heap with b values
95
+ for idx, node in enumerate(G):
96
+ heap.insert(node, b[idx])
97
+
98
+ num_edges = G.number_of_edges()
99
+
100
+ best_density = 0.0
101
+ best_subgraph = set()
102
+
103
+ while remaining_nodes:
104
+ num_nodes = len(remaining_nodes)
105
+ current_density = num_edges / num_nodes
106
+
107
+ if current_density > best_density:
108
+ best_density = current_density
109
+ best_subgraph = set(remaining_nodes)
110
+
111
+ # Pop the node with the smallest b
112
+ node, _ = heap.pop()
113
+ while node not in remaining_nodes:
114
+ node, _ = heap.pop() # Clean the heap from stale values
115
+
116
+ # Update neighbors b values by subtracting fractional x value
117
+ for neighbor in G.neighbors(node):
118
+ if neighbor in remaining_nodes:
119
+ neighbor_idx = node_to_idx[neighbor]
120
+ # Take off fractional value
121
+ b[neighbor_idx] -= x[edge_to_idx[(neighbor, node)]]
122
+ num_edges -= 1
123
+ heap.insert(neighbor, b[neighbor_idx])
124
+
125
+ remaining_nodes.remove(node) # peel off node
126
+
127
+ return best_density, best_subgraph
128
+
129
+
130
+ def _fista(G, iterations):
131
+ if G.number_of_edges() == 0:
132
+ return 0.0, set()
133
+ if iterations < 1:
134
+ raise ValueError(
135
+ f"The number of iterations must be an integer >= 1. Provided: {iterations}"
136
+ )
137
+ import numpy as np
138
+
139
+ # 1. Node Mapping: Assign a unique index to each node and edge
140
+ node_to_idx = {node: idx for idx, node in enumerate(G)}
141
+ num_nodes = G.number_of_nodes()
142
+ num_undirected_edges = G.number_of_edges()
143
+
144
+ # 2. Edge Mapping: Assign a unique index to each bidirectional edge
145
+ bidirectional_edges = [(u, v) for u, v in G.edges] + [(v, u) for u, v in G.edges]
146
+ edge_to_idx = {edge: idx for idx, edge in enumerate(bidirectional_edges)}
147
+
148
+ num_edges = len(bidirectional_edges)
149
+
150
+ # 3. Reverse Edge Mapping: Map each (bidirectional) edge to its reverse edge index
151
+ reverse_edge_idx = np.empty(num_edges, dtype=np.int32)
152
+ for idx in range(num_undirected_edges):
153
+ reverse_edge_idx[idx] = num_undirected_edges + idx
154
+ for idx in range(num_undirected_edges, 2 * num_undirected_edges):
155
+ reverse_edge_idx[idx] = idx - num_undirected_edges
156
+
157
+ # 4. Initialize Variables as NumPy Arrays
158
+ x = np.full(num_edges, 0.5, dtype=np.float32)
159
+ y = x.copy()
160
+ z = np.zeros(num_edges, dtype=np.float32)
161
+ b = np.zeros(num_nodes, dtype=np.float32) # Induced load vector
162
+ tk = 1.0 # Momentum term
163
+
164
+ # 5. Precompute Edge Source Indices
165
+ edge_src_indices = np.array(
166
+ [node_to_idx[u] for u, _ in bidirectional_edges], dtype=np.int32
167
+ )
168
+
169
+ # 6. Compute Learning Rate
170
+ max_degree = max(deg for _, deg in G.degree)
171
+ # 0.9 for floating point errs when max_degree is very large
172
+ learning_rate = 0.9 / max_degree
173
+
174
+ # 7. Iterative Updates
175
+ for _ in range(iterations):
176
+ # 7a. Update b: sum y over outgoing edges for each node
177
+ b[:] = 0.0 # Reset b to zero
178
+ np.add.at(b, edge_src_indices, y) # b_u = \sum_{v : (u,v) \in E(G)} y_{uv}
179
+
180
+ # 7b. Compute z, z_{uv} = y_{uv} - 2 * learning_rate * b_u
181
+ z = y - 2.0 * learning_rate * b[edge_src_indices]
182
+
183
+ # 7c. Update Momentum Term
184
+ tknew = (1.0 + math.sqrt(1 + 4.0 * tk**2)) / 2.0
185
+
186
+ # 7d. Update x in a vectorized manner, x_{uv} = (z_{uv} - z_{vu} + 1.0) / 2.0
187
+ new_xuv = (z - z[reverse_edge_idx] + 1.0) / 2.0
188
+ clamped_x = np.clip(new_xuv, 0.0, 1.0) # Clamp x_{uv} between 0 and 1
189
+
190
+ # Update y using the FISTA update formula (similar to gradient descent)
191
+ y = (
192
+ clamped_x
193
+ + ((tk - 1.0) / tknew) * (clamped_x - x)
194
+ + (tk / tknew) * (clamped_x - y)
195
+ )
196
+
197
+ # Update x
198
+ x = clamped_x
199
+
200
+ # Update tk, the momemntum term
201
+ tk = tknew
202
+
203
+ # Rebalance the b values! Otherwise performance is a bit suboptimal.
204
+ b[:] = 0.0
205
+ np.add.at(b, edge_src_indices, x) # b_u = \sum_{v : (u,v) \in E(G)} x_{uv}
206
+
207
+ # Extract the actual (approximate) dense subgraph.
208
+ return _fractional_peeling(G, b, x, node_to_idx, edge_to_idx)
209
+
210
+
211
+ ALGORITHMS = {"greedy++": _greedy_plus_plus, "fista": _fista}
212
+
213
+
214
+ @nx.utils.not_implemented_for("directed")
215
+ @nx.utils.not_implemented_for("multigraph")
216
+ @nx._dispatchable
217
+ def densest_subgraph(G, iterations=1, *, method="fista"):
218
+ r"""Returns an approximate densest subgraph for a graph `G`.
219
+
220
+ This function runs an iterative algorithm to find the densest subgraph,
221
+ and returns both the density and the subgraph. For a discussion on the
222
+ notion of density used and the different algorithms available on
223
+ networkx, please see the Notes section below.
224
+
225
+ Parameters
226
+ ----------
227
+ G : NetworkX graph
228
+ Undirected graph.
229
+
230
+ iterations : int, optional (default=1)
231
+ Number of iterations to use for the iterative algorithm. Can be
232
+ specified positionally or as a keyword argument.
233
+
234
+ method : string, optional (default='fista')
235
+ The algorithm to use to approximate the densest subgraph. Supported
236
+ options: 'greedy++' by Boob et al. [2]_ and 'fista' by Harb et al. [3]_.
237
+ Must be specified as a keyword argument. Other inputs produce a
238
+ ValueError.
239
+
240
+ Returns
241
+ -------
242
+ d : float
243
+ The density of the approximate subgraph found.
244
+
245
+ S : set
246
+ The subset of nodes defining the approximate densest subgraph.
247
+
248
+ Examples
249
+ --------
250
+ >>> G = nx.star_graph(4)
251
+ >>> nx.approximation.densest_subgraph(G, iterations=1)
252
+ (0.8, {0, 1, 2, 3, 4})
253
+
254
+ Notes
255
+ -----
256
+ **Problem Definition:**
257
+ The densest subgraph problem (DSG) asks to find the subgraph
258
+ $S \subseteq V(G)$ with maximum density. For a subset of the nodes of
259
+ $G$, $S \subseteq V(G)$, define $E(S) = \{ (u,v) : (u,v)\in E(G),
260
+ u\in S, v\in S \}$ as the set of edges with both endpoints in $S$.
261
+ The density of $S$ is defined as $|E(S)|/|S|$, the ratio between the
262
+ edges in the subgraph $G[S]$ and the number of nodes in that subgraph.
263
+ Note that this is different from the standard graph theoretic definition
264
+ of density, defined as $\frac{2|E(S)|}{|S|(|S|-1)}$, for historical
265
+ reasons.
266
+
267
+ **Exact Algorithms:**
268
+ The densest subgraph problem is polynomial time solvable using maximum
269
+ flow, commonly referred to as Goldberg's algorithm. However, the
270
+ algorithm is quite involved. It first binary searches on the optimal
271
+ density, $d^\ast$. For a guess of the density $d$, it sets up a flow
272
+ network $G'$ with size $O(m)$. The maximum flow solution either
273
+ informs the algorithm that no subgraph with density $d$ exists, or it
274
+ provides a subgraph with density at least $d$. However, this is
275
+ inherently bottlenecked by the maximum flow algorithm. For example, [2]_
276
+ notes that Goldberg’s algorithm was not feasible on many large graphs
277
+ even though they used a highly optimized maximum flow library.
278
+
279
+ **Charikar's Greedy Peeling:**
280
+ While exact solution algorithms are quite involved, there are several
281
+ known approximation algorithms for the densest subgraph problem.
282
+
283
+ Charikar [1]_ described a very simple 1/2-approximation algorithm for DSG
284
+ known as the greedy "peeling" algorithm. The algorithm creates an
285
+ ordering of the nodes as follows. The first node $v_1$ is the one with
286
+ the smallest degree in $G$ (ties broken arbitrarily). It selects
287
+ $v_2$ to be the smallest degree node in $G \setminus v_1$. Letting
288
+ $G_i$ be the graph after removing $v_1, ..., v_i$ (with $G_0=G$),
289
+ the algorithm returns the graph among $G_0, ..., G_n$ with the highest
290
+ density.
291
+
292
+ **Greedy++:**
293
+ Boob et al. [2]_ generalized this algorithm into Greedy++, an iterative
294
+ algorithm that runs several rounds of "peeling". In fact, Greedy++ with 1
295
+ iteration is precisely Charikar's algorithm. The algorithm converges to a
296
+ $(1-\epsilon)$ approximate densest subgraph in $O(\Delta(G)\log
297
+ n/\epsilon^2)$ iterations, where $\Delta(G)$ is the maximum degree,
298
+ and $n$ is the number of nodes in $G$. The algorithm also has other
299
+ desirable properties as shown by [4]_ and [5]_.
300
+
301
+ **FISTA Algorithm:**
302
+ Harb et al. [3]_ gave a faster and more scalable algorithm using ideas
303
+ from quadratic programming for the densest subgraph, which is based on a
304
+ fast iterative shrinkage-thresholding algorithm (FISTA) algorithm. It is
305
+ known that computing the densest subgraph can be formulated as the
306
+ following convex optimization problem:
307
+
308
+ Minimize $\sum_{u \in V(G)} b_u^2$
309
+
310
+ Subject to:
311
+
312
+ $b_u = \sum_{v: \{u,v\} \in E(G)} x_{uv}$ for all $u \in V(G)$
313
+
314
+ $x_{uv} + x_{vu} = 1.0$ for all $\{u,v\} \in E(G)$
315
+
316
+ $x_{uv} \geq 0, x_{vu} \geq 0$ for all $\{u,v\} \in E(G)$
317
+
318
+ Here, $x_{uv}$ represents the fraction of edge $\{u,v\}$ assigned to
319
+ $u$, and $x_{vu}$ to $v$.
320
+
321
+ The FISTA algorithm efficiently solves this convex program using gradient
322
+ descent with projections. For a learning rate $\alpha$, the algorithm
323
+ does:
324
+
325
+ 1. **Initialization**: Set $x^{(0)}_{uv} = x^{(0)}_{vu} = 0.5$ for all
326
+ edges as a feasible solution.
327
+
328
+ 2. **Gradient Update**: For iteration $k\geq 1$, set
329
+ $x^{(k+1)}_{uv} = x^{(k)}_{uv} - 2 \alpha \sum_{v: \{u,v\} \in E(G)}
330
+ x^{(k)}_{uv}$. However, now $x^{(k+1)}_{uv}$ might be infeasible!
331
+ To ensure feasibility, we project $x^{(k+1)}_{uv}$.
332
+
333
+ 3. **Projection to the Feasible Set**: Compute
334
+ $b^{(k+1)}_u = \sum_{v: \{u,v\} \in E(G)} x^{(k)}_{uv}$ for all
335
+ nodes $u$. Define $z^{(k+1)}_{uv} = x^{(k+1)}_{uv} - 2 \alpha
336
+ b^{(k+1)}_u$. Update $x^{(k+1)}_{uv} =
337
+ CLAMP((z^{(k+1)}_{uv} - z^{(k+1)}_{vu} + 1.0) / 2.0)$, where
338
+ $CLAMP(x) = \max(0, \min(1, x))$.
339
+
340
+ With a learning rate of $\alpha=1/\Delta(G)$, where $\Delta(G)$ is
341
+ the maximum degree, the algorithm converges to the optimum solution of
342
+ the convex program.
343
+
344
+ **Fractional Peeling:**
345
+ To obtain a **discrete** subgraph, we use fractional peeling, an
346
+ adaptation of the standard peeling algorithm which peels the minimum
347
+ degree vertex in each iteration, and returns the densest subgraph found
348
+ along the way. Here, we instead peel the vertex with the smallest
349
+ induced load $b_u$:
350
+
351
+ 1. Compute $b_u$ and $x_{uv}$.
352
+
353
+ 2. Iteratively remove the vertex with the smallest $b_u$, updating its
354
+ neighbors' load by $x_{vu}$.
355
+
356
+ Fractional peeling transforms the approximately optimal fractional
357
+ values $b_u, x_{uv}$ into a discrete subgraph. Unlike traditional
358
+ peeling, which removes the lowest-degree node, this method accounts for
359
+ fractional edge contributions from the convex program.
360
+
361
+ This approach is both scalable and theoretically sound, ensuring a quick
362
+ approximation of the densest subgraph while leveraging fractional load
363
+ balancing.
364
+
365
+ References
366
+ ----------
367
+ .. [1] Charikar, Moses. "Greedy approximation algorithms for finding dense
368
+ components in a graph." In International workshop on approximation
369
+ algorithms for combinatorial optimization, pp. 84-95. Berlin, Heidelberg:
370
+ Springer Berlin Heidelberg, 2000.
371
+
372
+ .. [2] Boob, Digvijay, Yu Gao, Richard Peng, Saurabh Sawlani, Charalampos
373
+ Tsourakakis, Di Wang, and Junxing Wang. "Flowless: Extracting densest
374
+ subgraphs without flow computations." In Proceedings of The Web Conference
375
+ 2020, pp. 573-583. 2020.
376
+
377
+ .. [3] Harb, Elfarouk, Kent Quanrud, and Chandra Chekuri. "Faster and scalable
378
+ algorithms for densest subgraph and decomposition." Advances in Neural
379
+ Information Processing Systems 35 (2022): 26966-26979.
380
+
381
+ .. [4] Harb, Elfarouk, Kent Quanrud, and Chandra Chekuri. "Convergence to
382
+ lexicographically optimal base in a (contra) polymatroid and applications
383
+ to densest subgraph and tree packing." arXiv preprint arXiv:2305.02987
384
+ (2023).
385
+
386
+ .. [5] Chekuri, Chandra, Kent Quanrud, and Manuel R. Torres. "Densest
387
+ subgraph: Supermodularity, iterative peeling, and flow." In Proceedings of
388
+ the 2022 Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), pp.
389
+ 1531-1555. Society for Industrial and Applied Mathematics, 2022.
390
+ """
391
+ try:
392
+ algo = ALGORITHMS[method]
393
+ except KeyError as e:
394
+ raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
395
+
396
+ return algo(G, iterations)
.venv/lib/python3.12/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.12/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.12/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.12/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.12/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.12/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.12/site-packages/networkx/algorithms/approximation/steinertree.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Notes
27
+ -----
28
+ .. deprecated:: 3.6
29
+ `metric_closure` is deprecated and will be removed in NetworkX 3.8.
30
+ Use :func:`networkx.all_pairs_shortest_path_length` instead.
31
+
32
+ """
33
+ import warnings
34
+
35
+ warnings.warn(
36
+ "metric_closure is deprecated and will be removed in NetworkX 3.8.\n"
37
+ "Use nx.all_pairs_shortest_path_length instead.",
38
+ category=DeprecationWarning,
39
+ stacklevel=5,
40
+ )
41
+
42
+ M = nx.Graph()
43
+
44
+ Gnodes = set(G)
45
+
46
+ # check for connected graph while processing first node
47
+ all_paths_iter = nx.all_pairs_dijkstra(G, weight=weight)
48
+ u, (distance, path) = next(all_paths_iter)
49
+ if len(G) != len(distance):
50
+ msg = "G is not a connected graph. metric_closure is not defined."
51
+ raise nx.NetworkXError(msg)
52
+ Gnodes.remove(u)
53
+ for v in Gnodes:
54
+ M.add_edge(u, v, distance=distance[v], path=path[v])
55
+
56
+ # first node done -- now process the rest
57
+ for u, (distance, path) in all_paths_iter:
58
+ Gnodes.remove(u)
59
+ for v in Gnodes:
60
+ M.add_edge(u, v, distance=distance[v], path=path[v])
61
+
62
+ return M
63
+
64
+
65
+ def _mehlhorn_steiner_tree(G, terminal_nodes, weight):
66
+ distances, paths = nx.multi_source_dijkstra(G, terminal_nodes, weight=weight)
67
+
68
+ d_1 = {}
69
+ s = {}
70
+ for v in G.nodes():
71
+ s[v] = paths[v][0]
72
+ d_1[(v, s[v])] = distances[v]
73
+
74
+ # G1-G4 names match those from the Mehlhorn 1988 paper.
75
+ G_1_prime = nx.Graph()
76
+ # iterate over all edges to complete d1
77
+ for u, v, data in G.edges(data=True):
78
+ su, sv = s[u], s[v]
79
+ weight_here = d_1[(u, su)] + data.get(weight, 1) + d_1[(v, sv)]
80
+ if not G_1_prime.has_edge(su, sv):
81
+ G_1_prime.add_edge(su, sv, weight_d1=weight_here)
82
+ else:
83
+ new_weight = min(weight_here, G_1_prime[su][sv]["weight_d1"])
84
+ G_1_prime.add_edge(su, sv, weight_d1=new_weight)
85
+
86
+ G_2 = nx.minimum_spanning_edges(G_1_prime, data=True, weight="weight_d1")
87
+
88
+ G_3 = nx.Graph()
89
+ for u, v, _ in G_2:
90
+ path = nx.shortest_path(G, u, v, weight=weight)
91
+ for n1, n2 in pairwise(path):
92
+ G_3.add_edge(n1, n2, weight=G[n1][n2].get(weight, 1))
93
+
94
+ G_3_mst = list(nx.minimum_spanning_edges(G_3, data=False, weight=weight))
95
+ if G.is_multigraph():
96
+ G_3_mst = (
97
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k].get(weight, 1)))
98
+ for u, v in G_3_mst
99
+ )
100
+ G_4 = G.edge_subgraph(G_3_mst).copy()
101
+ _remove_nonterminal_leaves(G_4, terminal_nodes)
102
+ return G_4.edges()
103
+
104
+
105
+ def _kou_steiner_tree(G, terminal_nodes, weight):
106
+ # Compute the metric closure only for terminal nodes
107
+ # Create a complete graph H from the metric edges
108
+ H = nx.Graph()
109
+ unvisited_terminals = set(terminal_nodes)
110
+
111
+ # check for connected graph while processing first node
112
+ u = unvisited_terminals.pop()
113
+ distances, paths = nx.single_source_dijkstra(G, source=u, weight=weight)
114
+ if len(G) != len(distances):
115
+ msg = "G is not a connected graph."
116
+ raise nx.NetworkXError(msg)
117
+ for v in unvisited_terminals:
118
+ H.add_edge(u, v, distance=distances[v], path=paths[v])
119
+
120
+ # first node done -- now process the rest
121
+ for u in unvisited_terminals.copy():
122
+ distances, paths = nx.single_source_dijkstra(G, source=u, weight=weight)
123
+ unvisited_terminals.remove(u)
124
+ for v in unvisited_terminals:
125
+ H.add_edge(u, v, distance=distances[v], path=paths[v])
126
+
127
+ # Use the 'distance' attribute of each edge provided by H.
128
+ mst_edges = nx.minimum_spanning_edges(H, weight="distance", data=True)
129
+
130
+ # Create an iterator over each edge in each shortest path; repeats are okay
131
+ mst_all_edges = chain.from_iterable(pairwise(d["path"]) for u, v, d in mst_edges)
132
+ if G.is_multigraph():
133
+ mst_all_edges = (
134
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k].get(weight, 1)))
135
+ for u, v in mst_all_edges
136
+ )
137
+
138
+ # Find the MST again, over this new set of edges
139
+ G_S = G.edge_subgraph(mst_all_edges)
140
+ T_S = nx.minimum_spanning_edges(G_S, weight="weight", data=False)
141
+
142
+ # Leaf nodes that are not terminal might still remain; remove them here
143
+ T_H = G.edge_subgraph(T_S).copy()
144
+ _remove_nonterminal_leaves(T_H, terminal_nodes)
145
+
146
+ return T_H.edges()
147
+
148
+
149
+ def _remove_nonterminal_leaves(G, terminals):
150
+ terminal_set = set(terminals)
151
+ leaves = {n for n in G if len(set(G[n]) - {n}) == 1}
152
+ nonterminal_leaves = leaves - terminal_set
153
+
154
+ while nonterminal_leaves:
155
+ # Removing a node may create new non-terminal leaves, so we limit
156
+ # search for candidate non-terminal nodes to neighbors of current
157
+ # non-terminal nodes
158
+ candidate_leaves = set.union(*(set(G[n]) for n in nonterminal_leaves))
159
+ candidate_leaves -= nonterminal_leaves | terminal_set
160
+ # Remove current set of non-terminal nodes
161
+ G.remove_nodes_from(nonterminal_leaves)
162
+ # Find any new non-terminal nodes from the set of candidates
163
+ leaves = {n for n in candidate_leaves if len(set(G[n]) - {n}) == 1}
164
+ nonterminal_leaves = leaves - terminal_set
165
+
166
+
167
+ ALGORITHMS = {
168
+ "kou": _kou_steiner_tree,
169
+ "mehlhorn": _mehlhorn_steiner_tree,
170
+ }
171
+
172
+
173
+ @not_implemented_for("directed")
174
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
175
+ def steiner_tree(G, terminal_nodes, weight="weight", method=None):
176
+ r"""Return an approximation to the minimum Steiner tree of a graph.
177
+
178
+ The minimum Steiner tree of `G` w.r.t a set of `terminal_nodes` (also *S*)
179
+ is a tree within `G` that spans those nodes and has minimum size (sum of
180
+ edge weights) among all such trees.
181
+
182
+ The approximation algorithm is specified with the `method` keyword
183
+ argument. All three available algorithms produce a tree whose weight is
184
+ within a ``(2 - (2 / l))`` factor of the weight of the optimal Steiner tree,
185
+ where ``l`` is the minimum number of leaf nodes across all possible Steiner
186
+ trees.
187
+
188
+ * ``"kou"`` [2]_ (runtime $O(|S| |V|^2)$) computes the minimum spanning tree of
189
+ the subgraph of the metric closure of *G* induced by the terminal nodes,
190
+ where the metric closure of *G* is the complete graph in which each edge is
191
+ weighted by the shortest path distance between the nodes in *G*.
192
+
193
+ * ``"mehlhorn"`` [3]_ (runtime $O(|E|+|V|\log|V|)$) modifies Kou et al.'s
194
+ algorithm, beginning by finding the closest terminal node for each
195
+ non-terminal. This data is used to create a complete graph containing only
196
+ the terminal nodes, in which edge is weighted with the shortest path
197
+ distance between them. The algorithm then proceeds in the same way as Kou
198
+ et al..
199
+
200
+ Parameters
201
+ ----------
202
+ G : NetworkX graph
203
+
204
+ terminal_nodes : list
205
+ A list of terminal nodes for which minimum steiner tree is
206
+ to be found.
207
+
208
+ weight : string (default = 'weight')
209
+ Use the edge attribute specified by this string as the edge weight.
210
+ Any edge attribute not present defaults to 1.
211
+
212
+ method : string, optional (default = 'mehlhorn')
213
+ The algorithm to use to approximate the Steiner tree.
214
+ Supported options: 'kou', 'mehlhorn'.
215
+ Other inputs produce a ValueError.
216
+
217
+ Returns
218
+ -------
219
+ NetworkX graph
220
+ Approximation to the minimum steiner tree of `G` induced by
221
+ `terminal_nodes` .
222
+
223
+ Raises
224
+ ------
225
+ NetworkXNotImplemented
226
+ If `G` is directed.
227
+
228
+ ValueError
229
+ If the specified `method` is not supported.
230
+
231
+ Notes
232
+ -----
233
+ For multigraphs, the edge between two nodes with minimum weight is the
234
+ edge put into the Steiner tree.
235
+
236
+
237
+ References
238
+ ----------
239
+ .. [1] Steiner_tree_problem on Wikipedia.
240
+ https://en.wikipedia.org/wiki/Steiner_tree_problem
241
+ .. [2] Kou, L., G. Markowsky, and L. Berman. 1981.
242
+ ‘A Fast Algorithm for Steiner Trees’.
243
+ Acta Informatica 15 (2): 141–45.
244
+ https://doi.org/10.1007/BF00288961.
245
+ .. [3] Mehlhorn, Kurt. 1988.
246
+ ‘A Faster Approximation Algorithm for the Steiner Problem in Graphs’.
247
+ Information Processing Letters 27 (3): 125–28.
248
+ https://doi.org/10.1016/0020-0190(88)90066-X.
249
+ """
250
+ if method is None:
251
+ method = "mehlhorn"
252
+
253
+ try:
254
+ algo = ALGORITHMS[method]
255
+ except KeyError as e:
256
+ raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
257
+
258
+ edges = algo(G, terminal_nodes, weight)
259
+ # For multigraph we should add the minimal weight edge keys
260
+ if G.is_multigraph():
261
+ edges = (
262
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k][weight])) for u, v in edges
263
+ )
264
+ T = G.edge_subgraph(edges)
265
+ return T
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__init__.py ADDED
File without changes
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (214 Bytes). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-312.pyc ADDED
Binary file (2.43 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_clique.cpython-312.pyc ADDED
Binary file (6.36 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_connectivity.cpython-312.pyc ADDED
Binary file (11 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_density.cpython-312.pyc ADDED
Binary file (7.97 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_distance_measures.cpython-312.pyc ADDED
Binary file (4.28 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_dominating_set.cpython-312.pyc ADDED
Binary file (3.87 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-312.pyc ADDED
Binary file (17.8 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_matching.cpython-312.pyc ADDED
Binary file (650 Bytes). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-312.pyc ADDED
Binary file (5.58 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_ramsey.cpython-312.pyc ADDED
Binary file (2.06 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-312.pyc ADDED
Binary file (15.4 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_traveling_salesman.cpython-312.pyc ADDED
Binary file (46.2 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_treewidth.cpython-312.pyc ADDED
Binary file (13.2 kB). View file
 
.venv/lib/python3.12/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_vertex_cover.cpython-312.pyc ADDED
Binary file (4.46 kB). View file