koichi12 commited on
Commit
bb81abe
·
verified ·
1 Parent(s): 033aa1d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +6 -0
  2. .venv/lib/python3.11/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-311.pyc +3 -0
  3. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__init__.py +25 -0
  4. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-311.pyc +0 -0
  5. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/clique.cpython-311.pyc +0 -0
  6. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/clustering_coefficient.cpython-311.pyc +0 -0
  7. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/connectivity.cpython-311.pyc +0 -0
  8. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/distance_measures.cpython-311.pyc +0 -0
  9. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/dominating_set.cpython-311.pyc +0 -0
  10. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/kcomponents.cpython-311.pyc +0 -0
  11. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/matching.cpython-311.pyc +0 -0
  12. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/maxcut.cpython-311.pyc +0 -0
  13. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/ramsey.cpython-311.pyc +0 -0
  14. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/steinertree.cpython-311.pyc +0 -0
  15. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/traveling_salesman.cpython-311.pyc +0 -0
  16. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/treewidth.cpython-311.pyc +0 -0
  17. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/vertex_cover.cpython-311.pyc +0 -0
  18. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/dominating_set.py +149 -0
  19. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__init__.py +0 -0
  20. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/__init__.cpython-311.pyc +0 -0
  21. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-311.pyc +0 -0
  22. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_clique.cpython-311.pyc +0 -0
  23. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_connectivity.cpython-311.pyc +0 -0
  24. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_distance_measures.cpython-311.pyc +0 -0
  25. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_dominating_set.cpython-311.pyc +0 -0
  26. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-311.pyc +0 -0
  27. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_matching.cpython-311.pyc +0 -0
  28. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-311.pyc +0 -0
  29. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_ramsey.cpython-311.pyc +0 -0
  30. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-311.pyc +0 -0
  31. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_traveling_salesman.cpython-311.pyc +0 -0
  32. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_treewidth.cpython-311.pyc +0 -0
  33. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_vertex_cover.cpython-311.pyc +0 -0
  34. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py +41 -0
  35. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_clique.py +112 -0
  36. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py +199 -0
  37. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py +59 -0
  38. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py +78 -0
  39. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py +303 -0
  40. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_matching.py +8 -0
  41. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py +94 -0
  42. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py +31 -0
  43. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py +265 -0
  44. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py +977 -0
  45. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py +280 -0
  46. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py +68 -0
  47. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/treewidth.py +252 -0
  48. .venv/lib/python3.11/site-packages/networkx/algorithms/approximation/vertex_cover.py +83 -0
  49. .venv/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py +26 -0
  50. .venv/lib/python3.11/site-packages/networkx/algorithms/community/__pycache__/centrality.cpython-311.pyc +0 -0
.gitattributes CHANGED
@@ -309,3 +309,9 @@ tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cudnn/lib/
309
  .venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
310
  .venv/lib/python3.11/site-packages/PIL/__pycache__/Image.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
311
  .venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
309
  .venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
310
  .venv/lib/python3.11/site-packages/PIL/__pycache__/Image.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
311
  .venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
312
+ .venv/lib/python3.11/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
313
+ .venv/lib/python3.11/site-packages/torio/lib/_torio_ffmpeg6.so filter=lfs diff=lfs merge=lfs -text
314
+ .venv/lib/python3.11/site-packages/torio/lib/libtorio_ffmpeg6.so filter=lfs diff=lfs merge=lfs -text
315
+ .venv/lib/python3.11/site-packages/torio/lib/_torio_ffmpeg4.so filter=lfs diff=lfs merge=lfs -text
316
+ .venv/lib/python3.11/site-packages/torio/lib/libtorio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
317
+ .venv/lib/python3.11/site-packages/torio/lib/libtorio_ffmpeg4.so filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.11/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3416e1e96ef8d36ac802ef017e613c85af365d5b8a0c51ccd0b21831eddc89d0
3
+ size 101283
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Approximations of graph properties and Heuristic methods for optimization.
2
+
3
+ The functions in this class are not imported into the top-level ``networkx``
4
+ namespace so the easiest way to use them is with::
5
+
6
+ >>> from networkx.algorithms import approximation
7
+
8
+ Another option is to import the specific function with
9
+ ``from networkx.algorithms.approximation import function_name``.
10
+
11
+ """
12
+
13
+ from networkx.algorithms.approximation.clustering_coefficient import *
14
+ from networkx.algorithms.approximation.clique import *
15
+ from networkx.algorithms.approximation.connectivity import *
16
+ from networkx.algorithms.approximation.distance_measures import *
17
+ from networkx.algorithms.approximation.dominating_set import *
18
+ from networkx.algorithms.approximation.kcomponents import *
19
+ from networkx.algorithms.approximation.matching import *
20
+ from networkx.algorithms.approximation.ramsey import *
21
+ from networkx.algorithms.approximation.steinertree import *
22
+ from networkx.algorithms.approximation.traveling_salesman import *
23
+ from networkx.algorithms.approximation.treewidth import *
24
+ from networkx.algorithms.approximation.vertex_cover import *
25
+ from networkx.algorithms.approximation.maxcut import *
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.5 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/clique.cpython-311.pyc ADDED
Binary file (9.78 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/clustering_coefficient.cpython-311.pyc ADDED
Binary file (3.21 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/connectivity.cpython-311.pyc ADDED
Binary file (14.5 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/distance_measures.cpython-311.pyc ADDED
Binary file (6.29 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/dominating_set.cpython-311.pyc ADDED
Binary file (5.42 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/kcomponents.cpython-311.pyc ADDED
Binary file (20.5 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/matching.cpython-311.pyc ADDED
Binary file (1.58 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/maxcut.cpython-311.pyc ADDED
Binary file (5.84 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/ramsey.cpython-311.pyc ADDED
Binary file (2.52 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/steinertree.cpython-311.pyc ADDED
Binary file (12.6 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/traveling_salesman.cpython-311.pyc ADDED
Binary file (63.9 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/treewidth.cpython-311.pyc ADDED
Binary file (9.71 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/__pycache__/vertex_cover.cpython-311.pyc ADDED
Binary file (3.42 kB). View file
 
.venv/lib/python3.11/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.11/site-packages/networkx/algorithms/approximation/tests/__init__.py ADDED
File without changes
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (212 Bytes). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-311.pyc ADDED
Binary file (2.75 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_clique.cpython-311.pyc ADDED
Binary file (7.25 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_connectivity.cpython-311.pyc ADDED
Binary file (11.5 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_distance_measures.cpython-311.pyc ADDED
Binary file (4.9 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_dominating_set.cpython-311.pyc ADDED
Binary file (4.45 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-311.pyc ADDED
Binary file (20.6 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_matching.cpython-311.pyc ADDED
Binary file (708 Bytes). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-311.pyc ADDED
Binary file (6.2 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_ramsey.cpython-311.pyc ADDED
Binary file (2.37 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-311.pyc ADDED
Binary file (15.9 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_traveling_salesman.cpython-311.pyc ADDED
Binary file (48.4 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_treewidth.cpython-311.pyc ADDED
Binary file (15.1 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_vertex_cover.cpython-311.pyc ADDED
Binary file (5.19 kB). View file
 
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import average_clustering
3
+
4
+ # This approximation has to be exact in regular graphs
5
+ # with no triangles or with all possible triangles.
6
+
7
+
8
+ def test_petersen():
9
+ # Actual coefficient is 0
10
+ G = nx.petersen_graph()
11
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
12
+
13
+
14
+ def test_petersen_seed():
15
+ # Actual coefficient is 0
16
+ G = nx.petersen_graph()
17
+ assert average_clustering(G, trials=len(G) // 2, seed=1) == nx.average_clustering(G)
18
+
19
+
20
+ def test_tetrahedral():
21
+ # Actual coefficient is 1
22
+ G = nx.tetrahedral_graph()
23
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
24
+
25
+
26
+ def test_dodecahedral():
27
+ # Actual coefficient is 0
28
+ G = nx.dodecahedral_graph()
29
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
30
+
31
+
32
+ def test_empty():
33
+ G = nx.empty_graph(5)
34
+ assert average_clustering(G, trials=len(G) // 2) == 0
35
+
36
+
37
+ def test_complete():
38
+ G = nx.complete_graph(5)
39
+ assert average_clustering(G, trials=len(G) // 2) == 1
40
+ G = nx.complete_graph(7)
41
+ assert average_clustering(G, trials=len(G) // 2) == 1
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_clique.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.approximation.clique` module."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ clique_removal,
6
+ large_clique_size,
7
+ max_clique,
8
+ maximum_independent_set,
9
+ )
10
+
11
+
12
+ def is_independent_set(G, nodes):
13
+ """Returns True if and only if `nodes` is a clique in `G`.
14
+
15
+ `G` is a NetworkX graph. `nodes` is an iterable of nodes in
16
+ `G`.
17
+
18
+ """
19
+ return G.subgraph(nodes).number_of_edges() == 0
20
+
21
+
22
+ def is_clique(G, nodes):
23
+ """Returns True if and only if `nodes` is an independent set
24
+ in `G`.
25
+
26
+ `G` is an undirected simple graph. `nodes` is an iterable of
27
+ nodes in `G`.
28
+
29
+ """
30
+ H = G.subgraph(nodes)
31
+ n = len(H)
32
+ return H.number_of_edges() == n * (n - 1) // 2
33
+
34
+
35
+ class TestCliqueRemoval:
36
+ """Unit tests for the
37
+ :func:`~networkx.algorithms.approximation.clique_removal` function.
38
+
39
+ """
40
+
41
+ def test_trivial_graph(self):
42
+ G = nx.trivial_graph()
43
+ independent_set, cliques = clique_removal(G)
44
+ assert is_independent_set(G, independent_set)
45
+ assert all(is_clique(G, clique) for clique in cliques)
46
+ # In fact, we should only have 1-cliques, that is, singleton nodes.
47
+ assert all(len(clique) == 1 for clique in cliques)
48
+
49
+ def test_complete_graph(self):
50
+ G = nx.complete_graph(10)
51
+ independent_set, cliques = clique_removal(G)
52
+ assert is_independent_set(G, independent_set)
53
+ assert all(is_clique(G, clique) for clique in cliques)
54
+
55
+ def test_barbell_graph(self):
56
+ G = nx.barbell_graph(10, 5)
57
+ independent_set, cliques = clique_removal(G)
58
+ assert is_independent_set(G, independent_set)
59
+ assert all(is_clique(G, clique) for clique in cliques)
60
+
61
+
62
+ class TestMaxClique:
63
+ """Unit tests for the :func:`networkx.algorithms.approximation.max_clique`
64
+ function.
65
+
66
+ """
67
+
68
+ def test_null_graph(self):
69
+ G = nx.null_graph()
70
+ assert len(max_clique(G)) == 0
71
+
72
+ def test_complete_graph(self):
73
+ graph = nx.complete_graph(30)
74
+ # this should return the entire graph
75
+ mc = max_clique(graph)
76
+ assert 30 == len(mc)
77
+
78
+ def test_maximal_by_cardinality(self):
79
+ """Tests that the maximal clique is computed according to maximum
80
+ cardinality of the sets.
81
+
82
+ For more information, see pull request #1531.
83
+
84
+ """
85
+ G = nx.complete_graph(5)
86
+ G.add_edge(4, 5)
87
+ clique = max_clique(G)
88
+ assert len(clique) > 1
89
+
90
+ G = nx.lollipop_graph(30, 2)
91
+ clique = max_clique(G)
92
+ assert len(clique) > 2
93
+
94
+
95
+ def test_large_clique_size():
96
+ G = nx.complete_graph(9)
97
+ nx.add_cycle(G, [9, 10, 11])
98
+ G.add_edge(8, 9)
99
+ G.add_edge(1, 12)
100
+ G.add_node(13)
101
+
102
+ assert large_clique_size(G) == 9
103
+ G.remove_node(5)
104
+ assert large_clique_size(G) == 8
105
+ G.remove_edge(2, 3)
106
+ assert large_clique_size(G) == 7
107
+
108
+
109
+ def test_independent_set():
110
+ # smoke test
111
+ G = nx.Graph()
112
+ assert len(maximum_independent_set(G)) == 0
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms import approximation as approx
5
+
6
+
7
+ def test_global_node_connectivity():
8
+ # Figure 1 chapter on Connectivity
9
+ G = nx.Graph()
10
+ G.add_edges_from(
11
+ [
12
+ (1, 2),
13
+ (1, 3),
14
+ (1, 4),
15
+ (1, 5),
16
+ (2, 3),
17
+ (2, 6),
18
+ (3, 4),
19
+ (3, 6),
20
+ (4, 6),
21
+ (4, 7),
22
+ (5, 7),
23
+ (6, 8),
24
+ (6, 9),
25
+ (7, 8),
26
+ (7, 10),
27
+ (8, 11),
28
+ (9, 10),
29
+ (9, 11),
30
+ (10, 11),
31
+ ]
32
+ )
33
+ assert 2 == approx.local_node_connectivity(G, 1, 11)
34
+ assert 2 == approx.node_connectivity(G)
35
+ assert 2 == approx.node_connectivity(G, 1, 11)
36
+
37
+
38
+ def test_white_harary1():
39
+ # Figure 1b white and harary (2001)
40
+ # A graph with high adhesion (edge connectivity) and low cohesion
41
+ # (node connectivity)
42
+ G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
43
+ G.remove_node(7)
44
+ for i in range(4, 7):
45
+ G.add_edge(0, i)
46
+ G = nx.disjoint_union(G, nx.complete_graph(4))
47
+ G.remove_node(G.order() - 1)
48
+ for i in range(7, 10):
49
+ G.add_edge(0, i)
50
+ assert 1 == approx.node_connectivity(G)
51
+
52
+
53
+ def test_complete_graphs():
54
+ for n in range(5, 25, 5):
55
+ G = nx.complete_graph(n)
56
+ assert n - 1 == approx.node_connectivity(G)
57
+ assert n - 1 == approx.node_connectivity(G, 0, 3)
58
+
59
+
60
+ def test_empty_graphs():
61
+ for k in range(5, 25, 5):
62
+ G = nx.empty_graph(k)
63
+ assert 0 == approx.node_connectivity(G)
64
+ assert 0 == approx.node_connectivity(G, 0, 3)
65
+
66
+
67
+ def test_petersen():
68
+ G = nx.petersen_graph()
69
+ assert 3 == approx.node_connectivity(G)
70
+ assert 3 == approx.node_connectivity(G, 0, 5)
71
+
72
+
73
+ # Approximation fails with tutte graph
74
+ # def test_tutte():
75
+ # G = nx.tutte_graph()
76
+ # assert_equal(3, approx.node_connectivity(G))
77
+
78
+
79
+ def test_dodecahedral():
80
+ G = nx.dodecahedral_graph()
81
+ assert 3 == approx.node_connectivity(G)
82
+ assert 3 == approx.node_connectivity(G, 0, 5)
83
+
84
+
85
+ def test_octahedral():
86
+ G = nx.octahedral_graph()
87
+ assert 4 == approx.node_connectivity(G)
88
+ assert 4 == approx.node_connectivity(G, 0, 5)
89
+
90
+
91
+ # Approximation can fail with icosahedral graph depending
92
+ # on iteration order.
93
+ # def test_icosahedral():
94
+ # G=nx.icosahedral_graph()
95
+ # assert_equal(5, approx.node_connectivity(G))
96
+ # assert_equal(5, approx.node_connectivity(G, 0, 5))
97
+
98
+
99
+ def test_only_source():
100
+ G = nx.complete_graph(5)
101
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, s=0)
102
+
103
+
104
+ def test_only_target():
105
+ G = nx.complete_graph(5)
106
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, t=0)
107
+
108
+
109
+ def test_missing_source():
110
+ G = nx.path_graph(4)
111
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 10, 1)
112
+
113
+
114
+ def test_missing_target():
115
+ G = nx.path_graph(4)
116
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 1, 10)
117
+
118
+
119
+ def test_source_equals_target():
120
+ G = nx.complete_graph(5)
121
+ pytest.raises(nx.NetworkXError, approx.local_node_connectivity, G, 0, 0)
122
+
123
+
124
+ def test_directed_node_connectivity():
125
+ G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
126
+ D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
127
+ assert 1 == approx.node_connectivity(G)
128
+ assert 1 == approx.node_connectivity(G, 1, 4)
129
+ assert 2 == approx.node_connectivity(D)
130
+ assert 2 == approx.node_connectivity(D, 1, 4)
131
+
132
+
133
+ class TestAllPairsNodeConnectivityApprox:
134
+ @classmethod
135
+ def setup_class(cls):
136
+ cls.path = nx.path_graph(7)
137
+ cls.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
138
+ cls.cycle = nx.cycle_graph(7)
139
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
140
+ cls.gnp = nx.gnp_random_graph(30, 0.1)
141
+ cls.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
142
+ cls.K20 = nx.complete_graph(20)
143
+ cls.K10 = nx.complete_graph(10)
144
+ cls.K5 = nx.complete_graph(5)
145
+ cls.G_list = [
146
+ cls.path,
147
+ cls.directed_path,
148
+ cls.cycle,
149
+ cls.directed_cycle,
150
+ cls.gnp,
151
+ cls.directed_gnp,
152
+ cls.K10,
153
+ cls.K5,
154
+ cls.K20,
155
+ ]
156
+
157
+ def test_cycles(self):
158
+ K_undir = approx.all_pairs_node_connectivity(self.cycle)
159
+ for source in K_undir:
160
+ for target, k in K_undir[source].items():
161
+ assert k == 2
162
+ K_dir = approx.all_pairs_node_connectivity(self.directed_cycle)
163
+ for source in K_dir:
164
+ for target, k in K_dir[source].items():
165
+ assert k == 1
166
+
167
+ def test_complete(self):
168
+ for G in [self.K10, self.K5, self.K20]:
169
+ K = approx.all_pairs_node_connectivity(G)
170
+ for source in K:
171
+ for target, k in K[source].items():
172
+ assert k == len(G) - 1
173
+
174
+ def test_paths(self):
175
+ K_undir = approx.all_pairs_node_connectivity(self.path)
176
+ for source in K_undir:
177
+ for target, k in K_undir[source].items():
178
+ assert k == 1
179
+ K_dir = approx.all_pairs_node_connectivity(self.directed_path)
180
+ for source in K_dir:
181
+ for target, k in K_dir[source].items():
182
+ if source < target:
183
+ assert k == 1
184
+ else:
185
+ assert k == 0
186
+
187
+ def test_cutoff(self):
188
+ for G in [self.K10, self.K5, self.K20]:
189
+ for mp in [2, 3, 4]:
190
+ paths = approx.all_pairs_node_connectivity(G, cutoff=mp)
191
+ for source in paths:
192
+ for target, K in paths[source].items():
193
+ assert K == mp
194
+
195
+ def test_all_pairs_connectivity_nbunch(self):
196
+ G = nx.complete_graph(5)
197
+ nbunch = [0, 2, 3]
198
+ C = approx.all_pairs_node_connectivity(G, nbunch=nbunch)
199
+ assert len(C) == len(nbunch)
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.approximation.distance_measures` module."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.approximation import diameter
7
+
8
+
9
+ class TestDiameter:
10
+ """Unit tests for the approximate diameter function
11
+ :func:`~networkx.algorithms.approximation.distance_measures.diameter`.
12
+ """
13
+
14
+ def test_null_graph(self):
15
+ """Test empty graph."""
16
+ G = nx.null_graph()
17
+ with pytest.raises(
18
+ nx.NetworkXError, match="Expected non-empty NetworkX graph!"
19
+ ):
20
+ diameter(G)
21
+
22
+ def test_undirected_non_connected(self):
23
+ """Test an undirected disconnected graph."""
24
+ graph = nx.path_graph(10)
25
+ graph.remove_edge(3, 4)
26
+ with pytest.raises(nx.NetworkXError, match="Graph not connected."):
27
+ diameter(graph)
28
+
29
+ def test_directed_non_strongly_connected(self):
30
+ """Test a directed non strongly connected graph."""
31
+ graph = nx.path_graph(10, create_using=nx.DiGraph())
32
+ with pytest.raises(nx.NetworkXError, match="DiGraph not strongly connected."):
33
+ diameter(graph)
34
+
35
+ def test_complete_undirected_graph(self):
36
+ """Test a complete undirected graph."""
37
+ graph = nx.complete_graph(10)
38
+ assert diameter(graph) == 1
39
+
40
+ def test_complete_directed_graph(self):
41
+ """Test a complete directed graph."""
42
+ graph = nx.complete_graph(10, create_using=nx.DiGraph())
43
+ assert diameter(graph) == 1
44
+
45
+ def test_undirected_path_graph(self):
46
+ """Test an undirected path graph with 10 nodes."""
47
+ graph = nx.path_graph(10)
48
+ assert diameter(graph) == 9
49
+
50
+ def test_directed_path_graph(self):
51
+ """Test a directed path graph with 10 nodes."""
52
+ graph = nx.path_graph(10).to_directed()
53
+ assert diameter(graph) == 9
54
+
55
+ def test_single_node(self):
56
+ """Test a graph which contains just a node."""
57
+ graph = nx.Graph()
58
+ graph.add_node(1)
59
+ assert diameter(graph) == 0
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ min_edge_dominating_set,
6
+ min_weighted_dominating_set,
7
+ )
8
+
9
+
10
+ class TestMinWeightDominatingSet:
11
+ def test_min_weighted_dominating_set(self):
12
+ graph = nx.Graph()
13
+ graph.add_edge(1, 2)
14
+ graph.add_edge(1, 5)
15
+ graph.add_edge(2, 3)
16
+ graph.add_edge(2, 5)
17
+ graph.add_edge(3, 4)
18
+ graph.add_edge(3, 6)
19
+ graph.add_edge(5, 6)
20
+
21
+ vertices = {1, 2, 3, 4, 5, 6}
22
+ # due to ties, this might be hard to test tight bounds
23
+ dom_set = min_weighted_dominating_set(graph)
24
+ for vertex in vertices - dom_set:
25
+ neighbors = set(graph.neighbors(vertex))
26
+ assert len(neighbors & dom_set) > 0, "Non dominating set found!"
27
+
28
+ def test_star_graph(self):
29
+ """Tests that an approximate dominating set for the star graph,
30
+ even when the center node does not have the smallest integer
31
+ label, gives just the center node.
32
+
33
+ For more information, see #1527.
34
+
35
+ """
36
+ # Create a star graph in which the center node has the highest
37
+ # label instead of the lowest.
38
+ G = nx.star_graph(10)
39
+ G = nx.relabel_nodes(G, {0: 9, 9: 0})
40
+ assert min_weighted_dominating_set(G) == {9}
41
+
42
+ def test_null_graph(self):
43
+ """Tests that the unique dominating set for the null graph is an empty set"""
44
+ G = nx.Graph()
45
+ assert min_weighted_dominating_set(G) == set()
46
+
47
+ def test_min_edge_dominating_set(self):
48
+ graph = nx.path_graph(5)
49
+ dom_set = min_edge_dominating_set(graph)
50
+
51
+ # this is a crappy way to test, but good enough for now.
52
+ for edge in graph.edges():
53
+ if edge in dom_set:
54
+ continue
55
+ else:
56
+ u, v = edge
57
+ found = False
58
+ for dom_edge in dom_set:
59
+ found |= u == dom_edge[0] or u == dom_edge[1]
60
+ assert found, "Non adjacent edge found!"
61
+
62
+ graph = nx.complete_graph(10)
63
+ dom_set = min_edge_dominating_set(graph)
64
+
65
+ # this is a crappy way to test, but good enough for now.
66
+ for edge in graph.edges():
67
+ if edge in dom_set:
68
+ continue
69
+ else:
70
+ u, v = edge
71
+ found = False
72
+ for dom_edge in dom_set:
73
+ found |= u == dom_edge[0] or u == dom_edge[1]
74
+ assert found, "Non adjacent edge found!"
75
+
76
+ graph = nx.Graph() # empty Networkx graph
77
+ with pytest.raises(ValueError, match="Expected non-empty NetworkX graph!"):
78
+ min_edge_dominating_set(graph)
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Test for approximation to k-components algorithm
2
+ import pytest
3
+
4
+ import networkx as nx
5
+ from networkx.algorithms.approximation import k_components
6
+ from networkx.algorithms.approximation.kcomponents import _AntiGraph, _same
7
+
8
+
9
+ def build_k_number_dict(k_components):
10
+ k_num = {}
11
+ for k, comps in sorted(k_components.items()):
12
+ for comp in comps:
13
+ for node in comp:
14
+ k_num[node] = k
15
+ return k_num
16
+
17
+
18
+ ##
19
+ # Some nice synthetic graphs
20
+ ##
21
+
22
+
23
+ def graph_example_1():
24
+ G = nx.convert_node_labels_to_integers(
25
+ nx.grid_graph([5, 5]), label_attribute="labels"
26
+ )
27
+ rlabels = nx.get_node_attributes(G, "labels")
28
+ labels = {v: k for k, v in rlabels.items()}
29
+
30
+ for nodes in [
31
+ (labels[(0, 0)], labels[(1, 0)]),
32
+ (labels[(0, 4)], labels[(1, 4)]),
33
+ (labels[(3, 0)], labels[(4, 0)]),
34
+ (labels[(3, 4)], labels[(4, 4)]),
35
+ ]:
36
+ new_node = G.order() + 1
37
+ # Petersen graph is triconnected
38
+ P = nx.petersen_graph()
39
+ G = nx.disjoint_union(G, P)
40
+ # Add two edges between the grid and P
41
+ G.add_edge(new_node + 1, nodes[0])
42
+ G.add_edge(new_node, nodes[1])
43
+ # K5 is 4-connected
44
+ K = nx.complete_graph(5)
45
+ G = nx.disjoint_union(G, K)
46
+ # Add three edges between P and K5
47
+ G.add_edge(new_node + 2, new_node + 11)
48
+ G.add_edge(new_node + 3, new_node + 12)
49
+ G.add_edge(new_node + 4, new_node + 13)
50
+ # Add another K5 sharing a node
51
+ G = nx.disjoint_union(G, K)
52
+ nbrs = G[new_node + 10]
53
+ G.remove_node(new_node + 10)
54
+ for nbr in nbrs:
55
+ G.add_edge(new_node + 17, nbr)
56
+ G.add_edge(new_node + 16, new_node + 5)
57
+ return G
58
+
59
+
60
+ def torrents_and_ferraro_graph():
61
+ G = nx.convert_node_labels_to_integers(
62
+ nx.grid_graph([5, 5]), label_attribute="labels"
63
+ )
64
+ rlabels = nx.get_node_attributes(G, "labels")
65
+ labels = {v: k for k, v in rlabels.items()}
66
+
67
+ for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]:
68
+ new_node = G.order() + 1
69
+ # Petersen graph is triconnected
70
+ P = nx.petersen_graph()
71
+ G = nx.disjoint_union(G, P)
72
+ # Add two edges between the grid and P
73
+ G.add_edge(new_node + 1, nodes[0])
74
+ G.add_edge(new_node, nodes[1])
75
+ # K5 is 4-connected
76
+ K = nx.complete_graph(5)
77
+ G = nx.disjoint_union(G, K)
78
+ # Add three edges between P and K5
79
+ G.add_edge(new_node + 2, new_node + 11)
80
+ G.add_edge(new_node + 3, new_node + 12)
81
+ G.add_edge(new_node + 4, new_node + 13)
82
+ # Add another K5 sharing a node
83
+ G = nx.disjoint_union(G, K)
84
+ nbrs = G[new_node + 10]
85
+ G.remove_node(new_node + 10)
86
+ for nbr in nbrs:
87
+ G.add_edge(new_node + 17, nbr)
88
+ # Commenting this makes the graph not biconnected !!
89
+ # This stupid mistake make one reviewer very angry :P
90
+ G.add_edge(new_node + 16, new_node + 8)
91
+
92
+ for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]:
93
+ new_node = G.order() + 1
94
+ # Petersen graph is triconnected
95
+ P = nx.petersen_graph()
96
+ G = nx.disjoint_union(G, P)
97
+ # Add two edges between the grid and P
98
+ G.add_edge(new_node + 1, nodes[0])
99
+ G.add_edge(new_node, nodes[1])
100
+ # K5 is 4-connected
101
+ K = nx.complete_graph(5)
102
+ G = nx.disjoint_union(G, K)
103
+ # Add three edges between P and K5
104
+ G.add_edge(new_node + 2, new_node + 11)
105
+ G.add_edge(new_node + 3, new_node + 12)
106
+ G.add_edge(new_node + 4, new_node + 13)
107
+ # Add another K5 sharing two nodes
108
+ G = nx.disjoint_union(G, K)
109
+ nbrs = G[new_node + 10]
110
+ G.remove_node(new_node + 10)
111
+ for nbr in nbrs:
112
+ G.add_edge(new_node + 17, nbr)
113
+ nbrs2 = G[new_node + 9]
114
+ G.remove_node(new_node + 9)
115
+ for nbr in nbrs2:
116
+ G.add_edge(new_node + 18, nbr)
117
+ return G
118
+
119
+
120
+ # Helper function
121
+
122
+
123
+ def _check_connectivity(G):
124
+ result = k_components(G)
125
+ for k, components in result.items():
126
+ if k < 3:
127
+ continue
128
+ for component in components:
129
+ C = G.subgraph(component)
130
+ K = nx.node_connectivity(C)
131
+ assert K >= k
132
+
133
+
134
+ def test_torrents_and_ferraro_graph():
135
+ G = torrents_and_ferraro_graph()
136
+ _check_connectivity(G)
137
+
138
+
139
+ def test_example_1():
140
+ G = graph_example_1()
141
+ _check_connectivity(G)
142
+
143
+
144
+ def test_karate_0():
145
+ G = nx.karate_club_graph()
146
+ _check_connectivity(G)
147
+
148
+
149
+ def test_karate_1():
150
+ karate_k_num = {
151
+ 0: 4,
152
+ 1: 4,
153
+ 2: 4,
154
+ 3: 4,
155
+ 4: 3,
156
+ 5: 3,
157
+ 6: 3,
158
+ 7: 4,
159
+ 8: 4,
160
+ 9: 2,
161
+ 10: 3,
162
+ 11: 1,
163
+ 12: 2,
164
+ 13: 4,
165
+ 14: 2,
166
+ 15: 2,
167
+ 16: 2,
168
+ 17: 2,
169
+ 18: 2,
170
+ 19: 3,
171
+ 20: 2,
172
+ 21: 2,
173
+ 22: 2,
174
+ 23: 3,
175
+ 24: 3,
176
+ 25: 3,
177
+ 26: 2,
178
+ 27: 3,
179
+ 28: 3,
180
+ 29: 3,
181
+ 30: 4,
182
+ 31: 3,
183
+ 32: 4,
184
+ 33: 4,
185
+ }
186
+ approx_karate_k_num = karate_k_num.copy()
187
+ approx_karate_k_num[24] = 2
188
+ approx_karate_k_num[25] = 2
189
+ G = nx.karate_club_graph()
190
+ k_comps = k_components(G)
191
+ k_num = build_k_number_dict(k_comps)
192
+ assert k_num in (karate_k_num, approx_karate_k_num)
193
+
194
+
195
+ def test_example_1_detail_3_and_4():
196
+ G = graph_example_1()
197
+ result = k_components(G)
198
+ # In this example graph there are 8 3-components, 4 with 15 nodes
199
+ # and 4 with 5 nodes.
200
+ assert len(result[3]) == 8
201
+ assert len([c for c in result[3] if len(c) == 15]) == 4
202
+ assert len([c for c in result[3] if len(c) == 5]) == 4
203
+ # There are also 8 4-components all with 5 nodes.
204
+ assert len(result[4]) == 8
205
+ assert all(len(c) == 5 for c in result[4])
206
+ # Finally check that the k-components detected have actually node
207
+ # connectivity >= k.
208
+ for k, components in result.items():
209
+ if k < 3:
210
+ continue
211
+ for component in components:
212
+ K = nx.node_connectivity(G.subgraph(component))
213
+ assert K >= k
214
+
215
+
216
+ def test_directed():
217
+ with pytest.raises(nx.NetworkXNotImplemented):
218
+ G = nx.gnp_random_graph(10, 0.4, directed=True)
219
+ kc = k_components(G)
220
+
221
+
222
+ def test_same():
223
+ equal = {"A": 2, "B": 2, "C": 2}
224
+ slightly_different = {"A": 2, "B": 1, "C": 2}
225
+ different = {"A": 2, "B": 8, "C": 18}
226
+ assert _same(equal)
227
+ assert not _same(slightly_different)
228
+ assert _same(slightly_different, tol=1)
229
+ assert not _same(different)
230
+ assert not _same(different, tol=4)
231
+
232
+
233
+ class TestAntiGraph:
234
+ @classmethod
235
+ def setup_class(cls):
236
+ cls.Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
237
+ cls.Anp = _AntiGraph(nx.complement(cls.Gnp))
238
+ cls.Gd = nx.davis_southern_women_graph()
239
+ cls.Ad = _AntiGraph(nx.complement(cls.Gd))
240
+ cls.Gk = nx.karate_club_graph()
241
+ cls.Ak = _AntiGraph(nx.complement(cls.Gk))
242
+ cls.GA = [(cls.Gnp, cls.Anp), (cls.Gd, cls.Ad), (cls.Gk, cls.Ak)]
243
+
244
+ def test_size(self):
245
+ for G, A in self.GA:
246
+ n = G.order()
247
+ s = len(list(G.edges())) + len(list(A.edges()))
248
+ assert s == (n * (n - 1)) / 2
249
+
250
+ def test_degree(self):
251
+ for G, A in self.GA:
252
+ assert sorted(G.degree()) == sorted(A.degree())
253
+
254
+ def test_core_number(self):
255
+ for G, A in self.GA:
256
+ assert nx.core_number(G) == nx.core_number(A)
257
+
258
+ def test_connected_components(self):
259
+ # ccs are same unless isolated nodes or any node has degree=len(G)-1
260
+ # graphs in self.GA avoid this problem
261
+ for G, A in self.GA:
262
+ gc = [set(c) for c in nx.connected_components(G)]
263
+ ac = [set(c) for c in nx.connected_components(A)]
264
+ for comp in ac:
265
+ assert comp in gc
266
+
267
+ def test_adj(self):
268
+ for G, A in self.GA:
269
+ for n, nbrs in G.adj.items():
270
+ a_adj = sorted((n, sorted(ad)) for n, ad in A.adj.items())
271
+ g_adj = sorted((n, sorted(ad)) for n, ad in G.adj.items())
272
+ assert a_adj == g_adj
273
+
274
+ def test_adjacency(self):
275
+ for G, A in self.GA:
276
+ a_adj = list(A.adjacency())
277
+ for n, nbrs in G.adjacency():
278
+ assert (n, set(nbrs)) in a_adj
279
+
280
+ def test_neighbors(self):
281
+ for G, A in self.GA:
282
+ node = list(G.nodes())[0]
283
+ assert set(G.neighbors(node)) == set(A.neighbors(node))
284
+
285
+ def test_node_not_in_graph(self):
286
+ for G, A in self.GA:
287
+ node = "non_existent_node"
288
+ pytest.raises(nx.NetworkXError, A.neighbors, node)
289
+ pytest.raises(nx.NetworkXError, G.neighbors, node)
290
+
291
+ def test_degree_thingraph(self):
292
+ for G, A in self.GA:
293
+ node = list(G.nodes())[0]
294
+ nodes = list(G.nodes())[1:4]
295
+ assert G.degree(node) == A.degree(node)
296
+ assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
297
+ # AntiGraph is a ThinGraph, so all the weights are 1
298
+ assert sum(d for n, d in A.degree()) == sum(
299
+ d for n, d in A.degree(weight="weight")
300
+ )
301
+ assert sum(d for n, d in G.degree(nodes)) == sum(
302
+ d for n, d in A.degree(nodes)
303
+ )
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_matching.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import networkx.algorithms.approximation as a
3
+
4
+
5
+ def test_min_maximal_matching():
6
+ # smoke test
7
+ G = nx.Graph()
8
+ assert len(a.min_maximal_matching(G)) == 0
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.approximation import maxcut
7
+
8
+
9
+ @pytest.mark.parametrize(
10
+ "f", (nx.approximation.randomized_partitioning, nx.approximation.one_exchange)
11
+ )
12
+ @pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
13
+ def test_raises_on_directed_and_multigraphs(f, graph_constructor):
14
+ G = graph_constructor([(0, 1), (1, 2)])
15
+ with pytest.raises(nx.NetworkXNotImplemented):
16
+ f(G)
17
+
18
+
19
+ def _is_valid_cut(G, set1, set2):
20
+ union = set1.union(set2)
21
+ assert union == set(G.nodes)
22
+ assert len(set1) + len(set2) == G.number_of_nodes()
23
+
24
+
25
+ def _cut_is_locally_optimal(G, cut_size, set1):
26
+ # test if cut can be locally improved
27
+ for i, node in enumerate(set1):
28
+ cut_size_without_node = nx.algorithms.cut_size(
29
+ G, set1 - {node}, weight="weight"
30
+ )
31
+ assert cut_size_without_node <= cut_size
32
+
33
+
34
+ def test_random_partitioning():
35
+ G = nx.complete_graph(5)
36
+ _, (set1, set2) = maxcut.randomized_partitioning(G, seed=5)
37
+ _is_valid_cut(G, set1, set2)
38
+
39
+
40
+ def test_random_partitioning_all_to_one():
41
+ G = nx.complete_graph(5)
42
+ _, (set1, set2) = maxcut.randomized_partitioning(G, p=1)
43
+ _is_valid_cut(G, set1, set2)
44
+ assert len(set1) == G.number_of_nodes()
45
+ assert len(set2) == 0
46
+
47
+
48
+ def test_one_exchange_basic():
49
+ G = nx.complete_graph(5)
50
+ random.seed(5)
51
+ for u, v, w in G.edges(data=True):
52
+ w["weight"] = random.randrange(-100, 100, 1) / 10
53
+
54
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
55
+ cut_size, (set1, set2) = maxcut.one_exchange(
56
+ G, initial_cut, weight="weight", seed=5
57
+ )
58
+
59
+ _is_valid_cut(G, set1, set2)
60
+ _cut_is_locally_optimal(G, cut_size, set1)
61
+
62
+
63
+ def test_one_exchange_optimal():
64
+ # Greedy one exchange should find the optimal solution for this graph (14)
65
+ G = nx.Graph()
66
+ G.add_edge(1, 2, weight=3)
67
+ G.add_edge(1, 3, weight=3)
68
+ G.add_edge(1, 4, weight=3)
69
+ G.add_edge(1, 5, weight=3)
70
+ G.add_edge(2, 3, weight=5)
71
+
72
+ cut_size, (set1, set2) = maxcut.one_exchange(G, weight="weight", seed=5)
73
+
74
+ _is_valid_cut(G, set1, set2)
75
+ _cut_is_locally_optimal(G, cut_size, set1)
76
+ # check global optimality
77
+ assert cut_size == 14
78
+
79
+
80
+ def test_negative_weights():
81
+ G = nx.complete_graph(5)
82
+ random.seed(5)
83
+ for u, v, w in G.edges(data=True):
84
+ w["weight"] = -1 * random.random()
85
+
86
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
87
+ cut_size, (set1, set2) = maxcut.one_exchange(G, initial_cut, weight="weight")
88
+
89
+ # make sure it is a valid cut
90
+ _is_valid_cut(G, set1, set2)
91
+ # check local optimality
92
+ _cut_is_locally_optimal(G, cut_size, set1)
93
+ # test that all nodes are in the same partition
94
+ assert len(set1) == len(G.nodes) or len(set2) == len(G.nodes)
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import networkx.algorithms.approximation as apxa
3
+
4
+
5
+ def test_ramsey():
6
+ # this should only find the complete graph
7
+ graph = nx.complete_graph(10)
8
+ c, i = apxa.ramsey_R2(graph)
9
+ cdens = nx.density(graph.subgraph(c))
10
+ assert cdens == 1.0, "clique not correctly found by ramsey!"
11
+ idens = nx.density(graph.subgraph(i))
12
+ assert idens == 0.0, "i-set not correctly found by ramsey!"
13
+
14
+ # this trivial graph has no cliques. should just find i-sets
15
+ graph = nx.trivial_graph()
16
+ c, i = apxa.ramsey_R2(graph)
17
+ assert c == {0}, "clique not correctly found by ramsey!"
18
+ assert i == {0}, "i-set not correctly found by ramsey!"
19
+
20
+ graph = nx.barbell_graph(10, 5, nx.Graph())
21
+ c, i = apxa.ramsey_R2(graph)
22
+ cdens = nx.density(graph.subgraph(c))
23
+ assert cdens == 1.0, "clique not correctly found by ramsey!"
24
+ idens = nx.density(graph.subgraph(i))
25
+ assert idens == 0.0, "i-set not correctly found by ramsey!"
26
+
27
+ # add self-loops and test again
28
+ graph.add_edges_from([(n, n) for n in range(0, len(graph), 2)])
29
+ cc, ii = apxa.ramsey_R2(graph)
30
+ assert cc == c
31
+ assert ii == i
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation.steinertree import (
5
+ _remove_nonterminal_leaves,
6
+ metric_closure,
7
+ steiner_tree,
8
+ )
9
+ from networkx.utils import edges_equal
10
+
11
+
12
+ class TestSteinerTree:
13
+ @classmethod
14
+ def setup_class(cls):
15
+ G1 = nx.Graph()
16
+ G1.add_edge(1, 2, weight=10)
17
+ G1.add_edge(2, 3, weight=10)
18
+ G1.add_edge(3, 4, weight=10)
19
+ G1.add_edge(4, 5, weight=10)
20
+ G1.add_edge(5, 6, weight=10)
21
+ G1.add_edge(2, 7, weight=1)
22
+ G1.add_edge(7, 5, weight=1)
23
+
24
+ G2 = nx.Graph()
25
+ G2.add_edge(0, 5, weight=6)
26
+ G2.add_edge(1, 2, weight=2)
27
+ G2.add_edge(1, 5, weight=3)
28
+ G2.add_edge(2, 4, weight=4)
29
+ G2.add_edge(3, 5, weight=5)
30
+ G2.add_edge(4, 5, weight=1)
31
+
32
+ G3 = nx.Graph()
33
+ G3.add_edge(1, 2, weight=8)
34
+ G3.add_edge(1, 9, weight=3)
35
+ G3.add_edge(1, 8, weight=6)
36
+ G3.add_edge(1, 10, weight=2)
37
+ G3.add_edge(1, 14, weight=3)
38
+ G3.add_edge(2, 3, weight=6)
39
+ G3.add_edge(3, 4, weight=3)
40
+ G3.add_edge(3, 10, weight=2)
41
+ G3.add_edge(3, 11, weight=1)
42
+ G3.add_edge(4, 5, weight=1)
43
+ G3.add_edge(4, 11, weight=1)
44
+ G3.add_edge(5, 6, weight=4)
45
+ G3.add_edge(5, 11, weight=2)
46
+ G3.add_edge(5, 12, weight=1)
47
+ G3.add_edge(5, 13, weight=3)
48
+ G3.add_edge(6, 7, weight=2)
49
+ G3.add_edge(6, 12, weight=3)
50
+ G3.add_edge(6, 13, weight=1)
51
+ G3.add_edge(7, 8, weight=3)
52
+ G3.add_edge(7, 9, weight=3)
53
+ G3.add_edge(7, 11, weight=5)
54
+ G3.add_edge(7, 13, weight=2)
55
+ G3.add_edge(7, 14, weight=4)
56
+ G3.add_edge(8, 9, weight=2)
57
+ G3.add_edge(9, 14, weight=1)
58
+ G3.add_edge(10, 11, weight=2)
59
+ G3.add_edge(10, 14, weight=1)
60
+ G3.add_edge(11, 12, weight=1)
61
+ G3.add_edge(11, 14, weight=7)
62
+ G3.add_edge(12, 14, weight=3)
63
+ G3.add_edge(12, 15, weight=1)
64
+ G3.add_edge(13, 14, weight=4)
65
+ G3.add_edge(13, 15, weight=1)
66
+ G3.add_edge(14, 15, weight=2)
67
+
68
+ cls.G1 = G1
69
+ cls.G2 = G2
70
+ cls.G3 = G3
71
+ cls.G1_term_nodes = [1, 2, 3, 4, 5]
72
+ cls.G2_term_nodes = [0, 2, 3]
73
+ cls.G3_term_nodes = [1, 3, 5, 6, 8, 10, 11, 12, 13]
74
+
75
+ cls.methods = ["kou", "mehlhorn"]
76
+
77
+ def test_connected_metric_closure(self):
78
+ G = self.G1.copy()
79
+ G.add_node(100)
80
+ pytest.raises(nx.NetworkXError, metric_closure, G)
81
+
82
+ def test_metric_closure(self):
83
+ M = metric_closure(self.G1)
84
+ mc = [
85
+ (1, 2, {"distance": 10, "path": [1, 2]}),
86
+ (1, 3, {"distance": 20, "path": [1, 2, 3]}),
87
+ (1, 4, {"distance": 22, "path": [1, 2, 7, 5, 4]}),
88
+ (1, 5, {"distance": 12, "path": [1, 2, 7, 5]}),
89
+ (1, 6, {"distance": 22, "path": [1, 2, 7, 5, 6]}),
90
+ (1, 7, {"distance": 11, "path": [1, 2, 7]}),
91
+ (2, 3, {"distance": 10, "path": [2, 3]}),
92
+ (2, 4, {"distance": 12, "path": [2, 7, 5, 4]}),
93
+ (2, 5, {"distance": 2, "path": [2, 7, 5]}),
94
+ (2, 6, {"distance": 12, "path": [2, 7, 5, 6]}),
95
+ (2, 7, {"distance": 1, "path": [2, 7]}),
96
+ (3, 4, {"distance": 10, "path": [3, 4]}),
97
+ (3, 5, {"distance": 12, "path": [3, 2, 7, 5]}),
98
+ (3, 6, {"distance": 22, "path": [3, 2, 7, 5, 6]}),
99
+ (3, 7, {"distance": 11, "path": [3, 2, 7]}),
100
+ (4, 5, {"distance": 10, "path": [4, 5]}),
101
+ (4, 6, {"distance": 20, "path": [4, 5, 6]}),
102
+ (4, 7, {"distance": 11, "path": [4, 5, 7]}),
103
+ (5, 6, {"distance": 10, "path": [5, 6]}),
104
+ (5, 7, {"distance": 1, "path": [5, 7]}),
105
+ (6, 7, {"distance": 11, "path": [6, 5, 7]}),
106
+ ]
107
+ assert edges_equal(list(M.edges(data=True)), mc)
108
+
109
+ def test_steiner_tree(self):
110
+ valid_steiner_trees = [
111
+ [
112
+ [
113
+ (1, 2, {"weight": 10}),
114
+ (2, 3, {"weight": 10}),
115
+ (2, 7, {"weight": 1}),
116
+ (3, 4, {"weight": 10}),
117
+ (5, 7, {"weight": 1}),
118
+ ],
119
+ [
120
+ (1, 2, {"weight": 10}),
121
+ (2, 7, {"weight": 1}),
122
+ (3, 4, {"weight": 10}),
123
+ (4, 5, {"weight": 10}),
124
+ (5, 7, {"weight": 1}),
125
+ ],
126
+ [
127
+ (1, 2, {"weight": 10}),
128
+ (2, 3, {"weight": 10}),
129
+ (2, 7, {"weight": 1}),
130
+ (4, 5, {"weight": 10}),
131
+ (5, 7, {"weight": 1}),
132
+ ],
133
+ ],
134
+ [
135
+ [
136
+ (0, 5, {"weight": 6}),
137
+ (1, 2, {"weight": 2}),
138
+ (1, 5, {"weight": 3}),
139
+ (3, 5, {"weight": 5}),
140
+ ],
141
+ [
142
+ (0, 5, {"weight": 6}),
143
+ (4, 2, {"weight": 4}),
144
+ (4, 5, {"weight": 1}),
145
+ (3, 5, {"weight": 5}),
146
+ ],
147
+ ],
148
+ [
149
+ [
150
+ (1, 10, {"weight": 2}),
151
+ (3, 10, {"weight": 2}),
152
+ (3, 11, {"weight": 1}),
153
+ (5, 12, {"weight": 1}),
154
+ (6, 13, {"weight": 1}),
155
+ (8, 9, {"weight": 2}),
156
+ (9, 14, {"weight": 1}),
157
+ (10, 14, {"weight": 1}),
158
+ (11, 12, {"weight": 1}),
159
+ (12, 15, {"weight": 1}),
160
+ (13, 15, {"weight": 1}),
161
+ ]
162
+ ],
163
+ ]
164
+ for method in self.methods:
165
+ for G, term_nodes, valid_trees in zip(
166
+ [self.G1, self.G2, self.G3],
167
+ [self.G1_term_nodes, self.G2_term_nodes, self.G3_term_nodes],
168
+ valid_steiner_trees,
169
+ ):
170
+ S = steiner_tree(G, term_nodes, method=method)
171
+ assert any(
172
+ edges_equal(list(S.edges(data=True)), valid_tree)
173
+ for valid_tree in valid_trees
174
+ )
175
+
176
+ def test_multigraph_steiner_tree(self):
177
+ G = nx.MultiGraph()
178
+ G.add_edges_from(
179
+ [
180
+ (1, 2, 0, {"weight": 1}),
181
+ (2, 3, 0, {"weight": 999}),
182
+ (2, 3, 1, {"weight": 1}),
183
+ (3, 4, 0, {"weight": 1}),
184
+ (3, 5, 0, {"weight": 1}),
185
+ ]
186
+ )
187
+ terminal_nodes = [2, 4, 5]
188
+ expected_edges = [
189
+ (2, 3, 1, {"weight": 1}), # edge with key 1 has lower weight
190
+ (3, 4, 0, {"weight": 1}),
191
+ (3, 5, 0, {"weight": 1}),
192
+ ]
193
+ for method in self.methods:
194
+ S = steiner_tree(G, terminal_nodes, method=method)
195
+ assert edges_equal(S.edges(data=True, keys=True), expected_edges)
196
+
197
+ def test_remove_nonterminal_leaves(self):
198
+ G = nx.path_graph(10)
199
+ _remove_nonterminal_leaves(G, [4, 5, 6])
200
+
201
+ assert list(G) == [4, 5, 6] # only the terminal nodes are left
202
+
203
+
204
+ @pytest.mark.parametrize("method", ("kou", "mehlhorn"))
205
+ def test_steiner_tree_weight_attribute(method):
206
+ G = nx.star_graph(4)
207
+ # Add an edge attribute that is named something other than "weight"
208
+ nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
209
+ H = nx.approximation.steiner_tree(G, [1, 3], method=method, weight="distance")
210
+ assert nx.utils.edges_equal(H.edges, [(0, 1), (0, 3)])
211
+
212
+
213
+ @pytest.mark.parametrize("method", ("kou", "mehlhorn"))
214
+ def test_steiner_tree_multigraph_weight_attribute(method):
215
+ G = nx.cycle_graph(3, create_using=nx.MultiGraph)
216
+ nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
217
+ G.add_edge(2, 0, distance=5)
218
+ H = nx.approximation.steiner_tree(G, list(G), method=method, weight="distance")
219
+ assert len(H.edges) == 2 and H.has_edge(2, 0, key=1)
220
+ assert sum(dist for *_, dist in H.edges(data="distance")) == 15
221
+
222
+
223
+ @pytest.mark.parametrize("method", (None, "mehlhorn", "kou"))
224
+ def test_steiner_tree_methods(method):
225
+ G = nx.star_graph(4)
226
+ expected = nx.Graph([(0, 1), (0, 3)])
227
+ st = nx.approximation.steiner_tree(G, [1, 3], method=method)
228
+ assert nx.utils.edges_equal(st.edges, expected.edges)
229
+
230
+
231
+ def test_steiner_tree_method_invalid():
232
+ G = nx.star_graph(4)
233
+ with pytest.raises(
234
+ ValueError, match="invalid_method is not a valid choice for an algorithm."
235
+ ):
236
+ nx.approximation.steiner_tree(G, terminal_nodes=[1, 3], method="invalid_method")
237
+
238
+
239
+ def test_steiner_tree_remove_non_terminal_leaves_self_loop_edges():
240
+ # To verify that the last step of the steiner tree approximation
241
+ # behaves in the case where a non-terminal leaf has a self loop edge
242
+ G = nx.path_graph(10)
243
+
244
+ # Add self loops to the terminal nodes
245
+ G.add_edges_from([(2, 2), (3, 3), (4, 4), (7, 7), (8, 8)])
246
+
247
+ # Remove non-terminal leaves
248
+ _remove_nonterminal_leaves(G, [4, 5, 6, 7])
249
+
250
+ # The terminal nodes should be left
251
+ assert list(G) == [4, 5, 6, 7] # only the terminal nodes are left
252
+
253
+
254
+ def test_steiner_tree_non_terminal_leaves_multigraph_self_loop_edges():
255
+ # To verify that the last step of the steiner tree approximation
256
+ # behaves in the case where a non-terminal leaf has a self loop edge
257
+ G = nx.MultiGraph()
258
+ G.add_edges_from([(i, i + 1) for i in range(10)])
259
+ G.add_edges_from([(2, 2), (3, 3), (4, 4), (4, 4), (7, 7)])
260
+
261
+ # Remove non-terminal leaves
262
+ _remove_nonterminal_leaves(G, [4, 5, 6, 7])
263
+
264
+ # Only the terminal nodes should be left
265
+ assert list(G) == [4, 5, 6, 7]
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py ADDED
@@ -0,0 +1,977 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the traveling_salesman module."""
2
+
3
+ import random
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ import networkx.algorithms.approximation as nx_app
9
+
10
+ pairwise = nx.utils.pairwise
11
+
12
+
13
+ def test_christofides_hamiltonian():
14
+ random.seed(42)
15
+ G = nx.complete_graph(20)
16
+ for u, v in G.edges():
17
+ G[u][v]["weight"] = random.randint(0, 10)
18
+
19
+ H = nx.Graph()
20
+ H.add_edges_from(pairwise(nx_app.christofides(G)))
21
+ H.remove_edges_from(nx.find_cycle(H))
22
+ assert len(H.edges) == 0
23
+
24
+ tree = nx.minimum_spanning_tree(G, weight="weight")
25
+ H = nx.Graph()
26
+ H.add_edges_from(pairwise(nx_app.christofides(G, tree)))
27
+ H.remove_edges_from(nx.find_cycle(H))
28
+ assert len(H.edges) == 0
29
+
30
+
31
+ def test_christofides_incomplete_graph():
32
+ G = nx.complete_graph(10)
33
+ G.remove_edge(0, 1)
34
+ pytest.raises(nx.NetworkXError, nx_app.christofides, G)
35
+
36
+
37
+ def test_christofides_ignore_selfloops():
38
+ G = nx.complete_graph(5)
39
+ G.add_edge(3, 3)
40
+ cycle = nx_app.christofides(G)
41
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
42
+
43
+
44
+ # set up graphs for other tests
45
+ class TestBase:
46
+ @classmethod
47
+ def setup_class(cls):
48
+ cls.DG = nx.DiGraph()
49
+ cls.DG.add_weighted_edges_from(
50
+ {
51
+ ("A", "B", 3),
52
+ ("A", "C", 17),
53
+ ("A", "D", 14),
54
+ ("B", "A", 3),
55
+ ("B", "C", 12),
56
+ ("B", "D", 16),
57
+ ("C", "A", 13),
58
+ ("C", "B", 12),
59
+ ("C", "D", 4),
60
+ ("D", "A", 14),
61
+ ("D", "B", 15),
62
+ ("D", "C", 2),
63
+ }
64
+ )
65
+ cls.DG_cycle = ["D", "C", "B", "A", "D"]
66
+ cls.DG_cost = 31.0
67
+
68
+ cls.DG2 = nx.DiGraph()
69
+ cls.DG2.add_weighted_edges_from(
70
+ {
71
+ ("A", "B", 3),
72
+ ("A", "C", 17),
73
+ ("A", "D", 14),
74
+ ("B", "A", 30),
75
+ ("B", "C", 2),
76
+ ("B", "D", 16),
77
+ ("C", "A", 33),
78
+ ("C", "B", 32),
79
+ ("C", "D", 34),
80
+ ("D", "A", 14),
81
+ ("D", "B", 15),
82
+ ("D", "C", 2),
83
+ }
84
+ )
85
+ cls.DG2_cycle = ["D", "A", "B", "C", "D"]
86
+ cls.DG2_cost = 53.0
87
+
88
+ cls.unweightedUG = nx.complete_graph(5, nx.Graph())
89
+ cls.unweightedDG = nx.complete_graph(5, nx.DiGraph())
90
+
91
+ cls.incompleteUG = nx.Graph()
92
+ cls.incompleteUG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
93
+ cls.incompleteDG = nx.DiGraph()
94
+ cls.incompleteDG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
95
+
96
+ cls.UG = nx.Graph()
97
+ cls.UG.add_weighted_edges_from(
98
+ {
99
+ ("A", "B", 3),
100
+ ("A", "C", 17),
101
+ ("A", "D", 14),
102
+ ("B", "C", 12),
103
+ ("B", "D", 16),
104
+ ("C", "D", 4),
105
+ }
106
+ )
107
+ cls.UG_cycle = ["D", "C", "B", "A", "D"]
108
+ cls.UG_cost = 33.0
109
+
110
+ cls.UG2 = nx.Graph()
111
+ cls.UG2.add_weighted_edges_from(
112
+ {
113
+ ("A", "B", 1),
114
+ ("A", "C", 15),
115
+ ("A", "D", 5),
116
+ ("B", "C", 16),
117
+ ("B", "D", 8),
118
+ ("C", "D", 3),
119
+ }
120
+ )
121
+ cls.UG2_cycle = ["D", "C", "B", "A", "D"]
122
+ cls.UG2_cost = 25.0
123
+
124
+
125
+ def validate_solution(soln, cost, exp_soln, exp_cost):
126
+ assert soln == exp_soln
127
+ assert cost == exp_cost
128
+
129
+
130
+ def validate_symmetric_solution(soln, cost, exp_soln, exp_cost):
131
+ assert soln == exp_soln or soln == exp_soln[::-1]
132
+ assert cost == exp_cost
133
+
134
+
135
+ class TestGreedyTSP(TestBase):
136
+ def test_greedy(self):
137
+ cycle = nx_app.greedy_tsp(self.DG, source="D")
138
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
139
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 31.0)
140
+
141
+ cycle = nx_app.greedy_tsp(self.DG2, source="D")
142
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
143
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 78.0)
144
+
145
+ cycle = nx_app.greedy_tsp(self.UG, source="D")
146
+ cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
147
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 33.0)
148
+
149
+ cycle = nx_app.greedy_tsp(self.UG2, source="D")
150
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
151
+ validate_solution(cycle, cost, ["D", "C", "A", "B", "D"], 27.0)
152
+
153
+ def test_not_complete_graph(self):
154
+ pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteUG)
155
+ pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteDG)
156
+
157
+ def test_not_weighted_graph(self):
158
+ nx_app.greedy_tsp(self.unweightedUG)
159
+ nx_app.greedy_tsp(self.unweightedDG)
160
+
161
+ def test_two_nodes(self):
162
+ G = nx.Graph()
163
+ G.add_weighted_edges_from({(1, 2, 1)})
164
+ cycle = nx_app.greedy_tsp(G)
165
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
166
+ validate_solution(cycle, cost, [1, 2, 1], 2)
167
+
168
+ def test_ignore_selfloops(self):
169
+ G = nx.complete_graph(5)
170
+ G.add_edge(3, 3)
171
+ cycle = nx_app.greedy_tsp(G)
172
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
173
+
174
+
175
+ class TestSimulatedAnnealingTSP(TestBase):
176
+ tsp = staticmethod(nx_app.simulated_annealing_tsp)
177
+
178
+ def test_simulated_annealing_directed(self):
179
+ cycle = self.tsp(self.DG, "greedy", source="D", seed=42)
180
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
181
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
182
+
183
+ initial_sol = ["D", "B", "A", "C", "D"]
184
+ cycle = self.tsp(self.DG, initial_sol, source="D", seed=42)
185
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
186
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
187
+
188
+ initial_sol = ["D", "A", "C", "B", "D"]
189
+ cycle = self.tsp(self.DG, initial_sol, move="1-0", source="D", seed=42)
190
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
191
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
192
+
193
+ cycle = self.tsp(self.DG2, "greedy", source="D", seed=42)
194
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
195
+ validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
196
+
197
+ cycle = self.tsp(self.DG2, "greedy", move="1-0", source="D", seed=42)
198
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
199
+ validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
200
+
201
+ def test_simulated_annealing_undirected(self):
202
+ cycle = self.tsp(self.UG, "greedy", source="D", seed=42)
203
+ cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
204
+ validate_solution(cycle, cost, self.UG_cycle, self.UG_cost)
205
+
206
+ cycle = self.tsp(self.UG2, "greedy", source="D", seed=42)
207
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
208
+ validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
209
+
210
+ cycle = self.tsp(self.UG2, "greedy", move="1-0", source="D", seed=42)
211
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
212
+ validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
213
+
214
+ def test_error_on_input_order_mistake(self):
215
+ # see issue #4846 https://github.com/networkx/networkx/issues/4846
216
+ pytest.raises(TypeError, self.tsp, self.UG, weight="weight")
217
+ pytest.raises(nx.NetworkXError, self.tsp, self.UG, "weight")
218
+
219
+ def test_not_complete_graph(self):
220
+ pytest.raises(nx.NetworkXError, self.tsp, self.incompleteUG, "greedy", source=0)
221
+ pytest.raises(nx.NetworkXError, self.tsp, self.incompleteDG, "greedy", source=0)
222
+
223
+ def test_ignore_selfloops(self):
224
+ G = nx.complete_graph(5)
225
+ G.add_edge(3, 3)
226
+ cycle = self.tsp(G, "greedy")
227
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
228
+
229
+ def test_not_weighted_graph(self):
230
+ self.tsp(self.unweightedUG, "greedy")
231
+ self.tsp(self.unweightedDG, "greedy")
232
+
233
+ def test_two_nodes(self):
234
+ G = nx.Graph()
235
+ G.add_weighted_edges_from({(1, 2, 1)})
236
+
237
+ cycle = self.tsp(G, "greedy", source=1, seed=42)
238
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
239
+ validate_solution(cycle, cost, [1, 2, 1], 2)
240
+
241
+ cycle = self.tsp(G, [1, 2, 1], source=1, seed=42)
242
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
243
+ validate_solution(cycle, cost, [1, 2, 1], 2)
244
+
245
+ def test_failure_of_costs_too_high_when_iterations_low(self):
246
+ # Simulated Annealing Version:
247
+ # set number of moves low and alpha high
248
+ cycle = self.tsp(
249
+ self.DG2, "greedy", source="D", move="1-0", alpha=1, N_inner=1, seed=42
250
+ )
251
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
252
+ print(cycle, cost)
253
+ assert cost > self.DG2_cost
254
+
255
+ # Try with an incorrect initial guess
256
+ initial_sol = ["D", "A", "B", "C", "D"]
257
+ cycle = self.tsp(
258
+ self.DG,
259
+ initial_sol,
260
+ source="D",
261
+ move="1-0",
262
+ alpha=0.1,
263
+ N_inner=1,
264
+ max_iterations=1,
265
+ seed=42,
266
+ )
267
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
268
+ print(cycle, cost)
269
+ assert cost > self.DG_cost
270
+
271
+
272
+ class TestThresholdAcceptingTSP(TestSimulatedAnnealingTSP):
273
+ tsp = staticmethod(nx_app.threshold_accepting_tsp)
274
+
275
+ def test_failure_of_costs_too_high_when_iterations_low(self):
276
+ # Threshold Version:
277
+ # set number of moves low and number of iterations low
278
+ cycle = self.tsp(
279
+ self.DG2,
280
+ "greedy",
281
+ source="D",
282
+ move="1-0",
283
+ N_inner=1,
284
+ max_iterations=1,
285
+ seed=4,
286
+ )
287
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
288
+ assert cost > self.DG2_cost
289
+
290
+ # set threshold too low
291
+ initial_sol = ["D", "A", "B", "C", "D"]
292
+ cycle = self.tsp(
293
+ self.DG, initial_sol, source="D", move="1-0", threshold=-3, seed=42
294
+ )
295
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
296
+ assert cost > self.DG_cost
297
+
298
+
299
+ # Tests for function traveling_salesman_problem
300
+ def test_TSP_method():
301
+ G = nx.cycle_graph(9)
302
+ G[4][5]["weight"] = 10
303
+
304
+ # Test using the old currying method
305
+ sa_tsp = lambda G, weight: nx_app.simulated_annealing_tsp(
306
+ G, "greedy", weight, source=4, seed=1
307
+ )
308
+
309
+ path = nx_app.traveling_salesman_problem(
310
+ G,
311
+ method=sa_tsp,
312
+ cycle=False,
313
+ )
314
+ print(path)
315
+ assert path == [4, 3, 2, 1, 0, 8, 7, 6, 5]
316
+
317
+
318
+ def test_TSP_unweighted():
319
+ G = nx.cycle_graph(9)
320
+ path = nx_app.traveling_salesman_problem(G, nodes=[3, 6], cycle=False)
321
+ assert path in ([3, 4, 5, 6], [6, 5, 4, 3])
322
+
323
+ cycle = nx_app.traveling_salesman_problem(G, nodes=[3, 6])
324
+ assert cycle in ([3, 4, 5, 6, 5, 4, 3], [6, 5, 4, 3, 4, 5, 6])
325
+
326
+
327
+ def test_TSP_weighted():
328
+ G = nx.cycle_graph(9)
329
+ G[0][1]["weight"] = 2
330
+ G[1][2]["weight"] = 2
331
+ G[2][3]["weight"] = 2
332
+ G[3][4]["weight"] = 4
333
+ G[4][5]["weight"] = 5
334
+ G[5][6]["weight"] = 4
335
+ G[6][7]["weight"] = 2
336
+ G[7][8]["weight"] = 2
337
+ G[8][0]["weight"] = 2
338
+ tsp = nx_app.traveling_salesman_problem
339
+
340
+ # path between 3 and 6
341
+ expected_paths = ([3, 2, 1, 0, 8, 7, 6], [6, 7, 8, 0, 1, 2, 3])
342
+ # cycle between 3 and 6
343
+ expected_cycles = (
344
+ [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3],
345
+ [6, 7, 8, 0, 1, 2, 3, 2, 1, 0, 8, 7, 6],
346
+ )
347
+ # path through all nodes
348
+ expected_tourpaths = ([5, 6, 7, 8, 0, 1, 2, 3, 4], [4, 3, 2, 1, 0, 8, 7, 6, 5])
349
+
350
+ # Check default method
351
+ cycle = tsp(G, nodes=[3, 6], weight="weight")
352
+ assert cycle in expected_cycles
353
+
354
+ path = tsp(G, nodes=[3, 6], weight="weight", cycle=False)
355
+ assert path in expected_paths
356
+
357
+ tourpath = tsp(G, weight="weight", cycle=False)
358
+ assert tourpath in expected_tourpaths
359
+
360
+ # Check all methods
361
+ methods = [
362
+ (nx_app.christofides, {}),
363
+ (nx_app.greedy_tsp, {}),
364
+ (
365
+ nx_app.simulated_annealing_tsp,
366
+ {"init_cycle": "greedy"},
367
+ ),
368
+ (
369
+ nx_app.threshold_accepting_tsp,
370
+ {"init_cycle": "greedy"},
371
+ ),
372
+ ]
373
+ for method, kwargs in methods:
374
+ cycle = tsp(G, nodes=[3, 6], weight="weight", method=method, **kwargs)
375
+ assert cycle in expected_cycles
376
+
377
+ path = tsp(
378
+ G, nodes=[3, 6], weight="weight", method=method, cycle=False, **kwargs
379
+ )
380
+ assert path in expected_paths
381
+
382
+ tourpath = tsp(G, weight="weight", method=method, cycle=False, **kwargs)
383
+ assert tourpath in expected_tourpaths
384
+
385
+
386
+ def test_TSP_incomplete_graph_short_path():
387
+ G = nx.cycle_graph(9)
388
+ G.add_edges_from([(4, 9), (9, 10), (10, 11), (11, 0)])
389
+ G[4][5]["weight"] = 5
390
+
391
+ cycle = nx_app.traveling_salesman_problem(G)
392
+ print(cycle)
393
+ assert len(cycle) == 17 and len(set(cycle)) == 12
394
+
395
+ # make sure that cutting one edge out of complete graph formulation
396
+ # cuts out many edges out of the path of the TSP
397
+ path = nx_app.traveling_salesman_problem(G, cycle=False)
398
+ print(path)
399
+ assert len(path) == 13 and len(set(path)) == 12
400
+
401
+
402
+ def test_held_karp_ascent():
403
+ """
404
+ Test the Held-Karp relaxation with the ascent method
405
+ """
406
+ import networkx.algorithms.approximation.traveling_salesman as tsp
407
+
408
+ np = pytest.importorskip("numpy")
409
+ pytest.importorskip("scipy")
410
+
411
+ # Adjacency matrix from page 1153 of the 1970 Held and Karp paper
412
+ # which have been edited to be directional, but also symmetric
413
+ G_array = np.array(
414
+ [
415
+ [0, 97, 60, 73, 17, 52],
416
+ [97, 0, 41, 52, 90, 30],
417
+ [60, 41, 0, 21, 35, 41],
418
+ [73, 52, 21, 0, 95, 46],
419
+ [17, 90, 35, 95, 0, 81],
420
+ [52, 30, 41, 46, 81, 0],
421
+ ]
422
+ )
423
+
424
+ solution_edges = [(1, 3), (2, 4), (3, 2), (4, 0), (5, 1), (0, 5)]
425
+
426
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
427
+ opt_hk, z_star = tsp.held_karp_ascent(G)
428
+
429
+ # Check that the optimal weights are the same
430
+ assert round(opt_hk, 2) == 207.00
431
+ # Check that the z_stars are the same
432
+ solution = nx.DiGraph()
433
+ solution.add_edges_from(solution_edges)
434
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
435
+
436
+
437
+ def test_ascent_fractional_solution():
438
+ """
439
+ Test the ascent method using a modified version of Figure 2 on page 1140
440
+ in 'The Traveling Salesman Problem and Minimum Spanning Trees' by Held and
441
+ Karp
442
+ """
443
+ import networkx.algorithms.approximation.traveling_salesman as tsp
444
+
445
+ np = pytest.importorskip("numpy")
446
+ pytest.importorskip("scipy")
447
+
448
+ # This version of Figure 2 has all of the edge weights multiplied by 100
449
+ # and is a complete directed graph with infinite edge weights for the
450
+ # edges not listed in the original graph
451
+ G_array = np.array(
452
+ [
453
+ [0, 100, 100, 100000, 100000, 1],
454
+ [100, 0, 100, 100000, 1, 100000],
455
+ [100, 100, 0, 1, 100000, 100000],
456
+ [100000, 100000, 1, 0, 100, 100],
457
+ [100000, 1, 100000, 100, 0, 100],
458
+ [1, 100000, 100000, 100, 100, 0],
459
+ ]
460
+ )
461
+
462
+ solution_z_star = {
463
+ (0, 1): 5 / 12,
464
+ (0, 2): 5 / 12,
465
+ (0, 5): 5 / 6,
466
+ (1, 0): 5 / 12,
467
+ (1, 2): 1 / 3,
468
+ (1, 4): 5 / 6,
469
+ (2, 0): 5 / 12,
470
+ (2, 1): 1 / 3,
471
+ (2, 3): 5 / 6,
472
+ (3, 2): 5 / 6,
473
+ (3, 4): 1 / 3,
474
+ (3, 5): 1 / 2,
475
+ (4, 1): 5 / 6,
476
+ (4, 3): 1 / 3,
477
+ (4, 5): 1 / 2,
478
+ (5, 0): 5 / 6,
479
+ (5, 3): 1 / 2,
480
+ (5, 4): 1 / 2,
481
+ }
482
+
483
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
484
+ opt_hk, z_star = tsp.held_karp_ascent(G)
485
+
486
+ # Check that the optimal weights are the same
487
+ assert round(opt_hk, 2) == 303.00
488
+ # Check that the z_stars are the same
489
+ assert {key: round(z_star[key], 4) for key in z_star} == {
490
+ key: round(solution_z_star[key], 4) for key in solution_z_star
491
+ }
492
+
493
+
494
+ def test_ascent_method_asymmetric():
495
+ """
496
+ Tests the ascent method using a truly asymmetric graph for which the
497
+ solution has been brute forced
498
+ """
499
+ import networkx.algorithms.approximation.traveling_salesman as tsp
500
+
501
+ np = pytest.importorskip("numpy")
502
+ pytest.importorskip("scipy")
503
+
504
+ G_array = np.array(
505
+ [
506
+ [0, 26, 63, 59, 69, 31, 41],
507
+ [62, 0, 91, 53, 75, 87, 47],
508
+ [47, 82, 0, 90, 15, 9, 18],
509
+ [68, 19, 5, 0, 58, 34, 93],
510
+ [11, 58, 53, 55, 0, 61, 79],
511
+ [88, 75, 13, 76, 98, 0, 40],
512
+ [41, 61, 55, 88, 46, 45, 0],
513
+ ]
514
+ )
515
+
516
+ solution_edges = [(0, 1), (1, 3), (3, 2), (2, 5), (5, 6), (4, 0), (6, 4)]
517
+
518
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
519
+ opt_hk, z_star = tsp.held_karp_ascent(G)
520
+
521
+ # Check that the optimal weights are the same
522
+ assert round(opt_hk, 2) == 190.00
523
+ # Check that the z_stars match.
524
+ solution = nx.DiGraph()
525
+ solution.add_edges_from(solution_edges)
526
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
527
+
528
+
529
+ def test_ascent_method_asymmetric_2():
530
+ """
531
+ Tests the ascent method using a truly asymmetric graph for which the
532
+ solution has been brute forced
533
+ """
534
+ import networkx.algorithms.approximation.traveling_salesman as tsp
535
+
536
+ np = pytest.importorskip("numpy")
537
+ pytest.importorskip("scipy")
538
+
539
+ G_array = np.array(
540
+ [
541
+ [0, 45, 39, 92, 29, 31],
542
+ [72, 0, 4, 12, 21, 60],
543
+ [81, 6, 0, 98, 70, 53],
544
+ [49, 71, 59, 0, 98, 94],
545
+ [74, 95, 24, 43, 0, 47],
546
+ [56, 43, 3, 65, 22, 0],
547
+ ]
548
+ )
549
+
550
+ solution_edges = [(0, 5), (5, 4), (1, 3), (3, 0), (2, 1), (4, 2)]
551
+
552
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
553
+ opt_hk, z_star = tsp.held_karp_ascent(G)
554
+
555
+ # Check that the optimal weights are the same
556
+ assert round(opt_hk, 2) == 144.00
557
+ # Check that the z_stars match.
558
+ solution = nx.DiGraph()
559
+ solution.add_edges_from(solution_edges)
560
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
561
+
562
+
563
+ def test_held_karp_ascent_asymmetric_3():
564
+ """
565
+ Tests the ascent method using a truly asymmetric graph with a fractional
566
+ solution for which the solution has been brute forced.
567
+
568
+ In this graph their are two different optimal, integral solutions (which
569
+ are also the overall atsp solutions) to the Held Karp relaxation. However,
570
+ this particular graph has two different tours of optimal value and the
571
+ possible solutions in the held_karp_ascent function are not stored in an
572
+ ordered data structure.
573
+ """
574
+ import networkx.algorithms.approximation.traveling_salesman as tsp
575
+
576
+ np = pytest.importorskip("numpy")
577
+ pytest.importorskip("scipy")
578
+
579
+ G_array = np.array(
580
+ [
581
+ [0, 1, 5, 2, 7, 4],
582
+ [7, 0, 7, 7, 1, 4],
583
+ [4, 7, 0, 9, 2, 1],
584
+ [7, 2, 7, 0, 4, 4],
585
+ [5, 5, 4, 4, 0, 3],
586
+ [3, 9, 1, 3, 4, 0],
587
+ ]
588
+ )
589
+
590
+ solution1_edges = [(0, 3), (1, 4), (2, 5), (3, 1), (4, 2), (5, 0)]
591
+
592
+ solution2_edges = [(0, 3), (3, 1), (1, 4), (4, 5), (2, 0), (5, 2)]
593
+
594
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
595
+ opt_hk, z_star = tsp.held_karp_ascent(G)
596
+
597
+ assert round(opt_hk, 2) == 13.00
598
+ # Check that the z_stars are the same
599
+ solution1 = nx.DiGraph()
600
+ solution1.add_edges_from(solution1_edges)
601
+ solution2 = nx.DiGraph()
602
+ solution2.add_edges_from(solution2_edges)
603
+ assert nx.utils.edges_equal(z_star.edges, solution1.edges) or nx.utils.edges_equal(
604
+ z_star.edges, solution2.edges
605
+ )
606
+
607
+
608
+ def test_held_karp_ascent_fractional_asymmetric():
609
+ """
610
+ Tests the ascent method using a truly asymmetric graph with a fractional
611
+ solution for which the solution has been brute forced
612
+ """
613
+ import networkx.algorithms.approximation.traveling_salesman as tsp
614
+
615
+ np = pytest.importorskip("numpy")
616
+ pytest.importorskip("scipy")
617
+
618
+ G_array = np.array(
619
+ [
620
+ [0, 100, 150, 100000, 100000, 1],
621
+ [150, 0, 100, 100000, 1, 100000],
622
+ [100, 150, 0, 1, 100000, 100000],
623
+ [100000, 100000, 1, 0, 150, 100],
624
+ [100000, 2, 100000, 100, 0, 150],
625
+ [2, 100000, 100000, 150, 100, 0],
626
+ ]
627
+ )
628
+
629
+ solution_z_star = {
630
+ (0, 1): 5 / 12,
631
+ (0, 2): 5 / 12,
632
+ (0, 5): 5 / 6,
633
+ (1, 0): 5 / 12,
634
+ (1, 2): 5 / 12,
635
+ (1, 4): 5 / 6,
636
+ (2, 0): 5 / 12,
637
+ (2, 1): 5 / 12,
638
+ (2, 3): 5 / 6,
639
+ (3, 2): 5 / 6,
640
+ (3, 4): 5 / 12,
641
+ (3, 5): 5 / 12,
642
+ (4, 1): 5 / 6,
643
+ (4, 3): 5 / 12,
644
+ (4, 5): 5 / 12,
645
+ (5, 0): 5 / 6,
646
+ (5, 3): 5 / 12,
647
+ (5, 4): 5 / 12,
648
+ }
649
+
650
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
651
+ opt_hk, z_star = tsp.held_karp_ascent(G)
652
+
653
+ # Check that the optimal weights are the same
654
+ assert round(opt_hk, 2) == 304.00
655
+ # Check that the z_stars are the same
656
+ assert {key: round(z_star[key], 4) for key in z_star} == {
657
+ key: round(solution_z_star[key], 4) for key in solution_z_star
658
+ }
659
+
660
+
661
+ def test_spanning_tree_distribution():
662
+ """
663
+ Test that we can create an exponential distribution of spanning trees such
664
+ that the probability of each tree is proportional to the product of edge
665
+ weights.
666
+
667
+ Results of this test have been confirmed with hypothesis testing from the
668
+ created distribution.
669
+
670
+ This test uses the symmetric, fractional Held Karp solution.
671
+ """
672
+ import networkx.algorithms.approximation.traveling_salesman as tsp
673
+
674
+ pytest.importorskip("numpy")
675
+ pytest.importorskip("scipy")
676
+
677
+ z_star = {
678
+ (0, 1): 5 / 12,
679
+ (0, 2): 5 / 12,
680
+ (0, 5): 5 / 6,
681
+ (1, 0): 5 / 12,
682
+ (1, 2): 1 / 3,
683
+ (1, 4): 5 / 6,
684
+ (2, 0): 5 / 12,
685
+ (2, 1): 1 / 3,
686
+ (2, 3): 5 / 6,
687
+ (3, 2): 5 / 6,
688
+ (3, 4): 1 / 3,
689
+ (3, 5): 1 / 2,
690
+ (4, 1): 5 / 6,
691
+ (4, 3): 1 / 3,
692
+ (4, 5): 1 / 2,
693
+ (5, 0): 5 / 6,
694
+ (5, 3): 1 / 2,
695
+ (5, 4): 1 / 2,
696
+ }
697
+
698
+ solution_gamma = {
699
+ (0, 1): -0.6383,
700
+ (0, 2): -0.6827,
701
+ (0, 5): 0,
702
+ (1, 2): -1.0781,
703
+ (1, 4): 0,
704
+ (2, 3): 0,
705
+ (5, 3): -0.2820,
706
+ (5, 4): -0.3327,
707
+ (4, 3): -0.9927,
708
+ }
709
+
710
+ # The undirected support of z_star
711
+ G = nx.MultiGraph()
712
+ for u, v in z_star:
713
+ if (u, v) in G.edges or (v, u) in G.edges:
714
+ continue
715
+ G.add_edge(u, v)
716
+
717
+ gamma = tsp.spanning_tree_distribution(G, z_star)
718
+
719
+ assert {key: round(gamma[key], 4) for key in gamma} == solution_gamma
720
+
721
+
722
+ def test_asadpour_tsp():
723
+ """
724
+ Test the complete asadpour tsp algorithm with the fractional, symmetric
725
+ Held Karp solution. This test also uses an incomplete graph as input.
726
+ """
727
+ # This version of Figure 2 has all of the edge weights multiplied by 100
728
+ # and the 0 weight edges have a weight of 1.
729
+ pytest.importorskip("numpy")
730
+ pytest.importorskip("scipy")
731
+
732
+ edge_list = [
733
+ (0, 1, 100),
734
+ (0, 2, 100),
735
+ (0, 5, 1),
736
+ (1, 2, 100),
737
+ (1, 4, 1),
738
+ (2, 3, 1),
739
+ (3, 4, 100),
740
+ (3, 5, 100),
741
+ (4, 5, 100),
742
+ (1, 0, 100),
743
+ (2, 0, 100),
744
+ (5, 0, 1),
745
+ (2, 1, 100),
746
+ (4, 1, 1),
747
+ (3, 2, 1),
748
+ (4, 3, 100),
749
+ (5, 3, 100),
750
+ (5, 4, 100),
751
+ ]
752
+
753
+ G = nx.DiGraph()
754
+ G.add_weighted_edges_from(edge_list)
755
+
756
+ tour = nx_app.traveling_salesman_problem(
757
+ G, weight="weight", method=nx_app.asadpour_atsp, seed=19
758
+ )
759
+
760
+ # Check that the returned list is a valid tour. Because this is an
761
+ # incomplete graph, the conditions are not as strict. We need the tour to
762
+ #
763
+ # Start and end at the same node
764
+ # Pass through every vertex at least once
765
+ # Have a total cost at most ln(6) / ln(ln(6)) = 3.0723 times the optimal
766
+ #
767
+ # For the second condition it is possible to have the tour pass through the
768
+ # same vertex more then. Imagine that the tour on the complete version takes
769
+ # an edge not in the original graph. In the output this is substituted with
770
+ # the shortest path between those vertices, allowing vertices to appear more
771
+ # than once.
772
+ #
773
+ # Even though we are using a fixed seed, multiple tours have been known to
774
+ # be returned. The first two are from the original development of this test,
775
+ # and the third one from issue #5913 on GitHub. If other tours are returned,
776
+ # add it on the list of expected tours.
777
+ expected_tours = [
778
+ [1, 4, 5, 0, 2, 3, 2, 1],
779
+ [3, 2, 0, 1, 4, 5, 3],
780
+ [3, 2, 1, 0, 5, 4, 3],
781
+ ]
782
+
783
+ assert tour in expected_tours
784
+
785
+
786
+ def test_asadpour_real_world():
787
+ """
788
+ This test uses airline prices between the six largest cities in the US.
789
+
790
+ * New York City -> JFK
791
+ * Los Angeles -> LAX
792
+ * Chicago -> ORD
793
+ * Houston -> IAH
794
+ * Phoenix -> PHX
795
+ * Philadelphia -> PHL
796
+
797
+ Flight prices from August 2021 using Delta or American airlines to get
798
+ nonstop flight. The brute force solution found the optimal tour to cost $872
799
+
800
+ This test also uses the `source` keyword argument to ensure that the tour
801
+ always starts at city 0.
802
+ """
803
+ np = pytest.importorskip("numpy")
804
+ pytest.importorskip("scipy")
805
+
806
+ G_array = np.array(
807
+ [
808
+ # JFK LAX ORD IAH PHX PHL
809
+ [0, 243, 199, 208, 169, 183], # JFK
810
+ [277, 0, 217, 123, 127, 252], # LAX
811
+ [297, 197, 0, 197, 123, 177], # ORD
812
+ [303, 169, 197, 0, 117, 117], # IAH
813
+ [257, 127, 160, 117, 0, 319], # PHX
814
+ [183, 332, 217, 117, 319, 0], # PHL
815
+ ]
816
+ )
817
+
818
+ node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"]
819
+
820
+ expected_tours = [
821
+ ["JFK", "LAX", "PHX", "ORD", "IAH", "PHL", "JFK"],
822
+ ["JFK", "ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
823
+ ]
824
+
825
+ G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph)
826
+
827
+ tour = nx_app.traveling_salesman_problem(
828
+ G, weight="weight", method=nx_app.asadpour_atsp, seed=37, source="JFK"
829
+ )
830
+
831
+ assert tour in expected_tours
832
+
833
+
834
+ def test_asadpour_real_world_path():
835
+ """
836
+ This test uses airline prices between the six largest cities in the US. This
837
+ time using a path, not a cycle.
838
+
839
+ * New York City -> JFK
840
+ * Los Angeles -> LAX
841
+ * Chicago -> ORD
842
+ * Houston -> IAH
843
+ * Phoenix -> PHX
844
+ * Philadelphia -> PHL
845
+
846
+ Flight prices from August 2021 using Delta or American airlines to get
847
+ nonstop flight. The brute force solution found the optimal tour to cost $872
848
+ """
849
+ np = pytest.importorskip("numpy")
850
+ pytest.importorskip("scipy")
851
+
852
+ G_array = np.array(
853
+ [
854
+ # JFK LAX ORD IAH PHX PHL
855
+ [0, 243, 199, 208, 169, 183], # JFK
856
+ [277, 0, 217, 123, 127, 252], # LAX
857
+ [297, 197, 0, 197, 123, 177], # ORD
858
+ [303, 169, 197, 0, 117, 117], # IAH
859
+ [257, 127, 160, 117, 0, 319], # PHX
860
+ [183, 332, 217, 117, 319, 0], # PHL
861
+ ]
862
+ )
863
+
864
+ node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"]
865
+
866
+ expected_paths = [
867
+ ["ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
868
+ ["JFK", "PHL", "IAH", "ORD", "PHX", "LAX"],
869
+ ]
870
+
871
+ G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph)
872
+
873
+ path = nx_app.traveling_salesman_problem(
874
+ G, weight="weight", cycle=False, method=nx_app.asadpour_atsp, seed=56
875
+ )
876
+
877
+ assert path in expected_paths
878
+
879
+
880
+ def test_asadpour_disconnected_graph():
881
+ """
882
+ Test that the proper exception is raised when asadpour_atsp is given an
883
+ disconnected graph.
884
+ """
885
+
886
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
887
+ # have to set edge weights so that if the exception is not raised, the
888
+ # function will complete and we will fail the test
889
+ nx.set_edge_attributes(G, 1, "weight")
890
+ G.add_node(5)
891
+
892
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
893
+
894
+
895
+ def test_asadpour_incomplete_graph():
896
+ """
897
+ Test that the proper exception is raised when asadpour_atsp is given an
898
+ incomplete graph
899
+ """
900
+
901
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
902
+ # have to set edge weights so that if the exception is not raised, the
903
+ # function will complete and we will fail the test
904
+ nx.set_edge_attributes(G, 1, "weight")
905
+ G.remove_edge(0, 1)
906
+
907
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
908
+
909
+
910
+ def test_asadpour_empty_graph():
911
+ """
912
+ Test the asadpour_atsp function with an empty graph
913
+ """
914
+ G = nx.DiGraph()
915
+
916
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
917
+
918
+
919
+ @pytest.mark.slow
920
+ def test_asadpour_integral_held_karp():
921
+ """
922
+ This test uses an integral held karp solution and the held karp function
923
+ will return a graph rather than a dict, bypassing most of the asadpour
924
+ algorithm.
925
+
926
+ At first glance, this test probably doesn't look like it ensures that we
927
+ skip the rest of the asadpour algorithm, but it does. We are not fixing a
928
+ see for the random number generator, so if we sample any spanning trees
929
+ the approximation would be different basically every time this test is
930
+ executed but it is not since held karp is deterministic and we do not
931
+ reach the portion of the code with the dependence on random numbers.
932
+ """
933
+ np = pytest.importorskip("numpy")
934
+
935
+ G_array = np.array(
936
+ [
937
+ [0, 26, 63, 59, 69, 31, 41],
938
+ [62, 0, 91, 53, 75, 87, 47],
939
+ [47, 82, 0, 90, 15, 9, 18],
940
+ [68, 19, 5, 0, 58, 34, 93],
941
+ [11, 58, 53, 55, 0, 61, 79],
942
+ [88, 75, 13, 76, 98, 0, 40],
943
+ [41, 61, 55, 88, 46, 45, 0],
944
+ ]
945
+ )
946
+
947
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
948
+
949
+ for _ in range(2):
950
+ tour = nx_app.traveling_salesman_problem(G, method=nx_app.asadpour_atsp)
951
+
952
+ assert [1, 3, 2, 5, 2, 6, 4, 0, 1] == tour
953
+
954
+
955
+ def test_directed_tsp_impossible():
956
+ """
957
+ Test the asadpour algorithm with a graph without a hamiltonian circuit
958
+ """
959
+ pytest.importorskip("numpy")
960
+
961
+ # In this graph, once we leave node 0 we cannot return
962
+ edges = [
963
+ (0, 1, 10),
964
+ (0, 2, 11),
965
+ (0, 3, 12),
966
+ (1, 2, 4),
967
+ (1, 3, 6),
968
+ (2, 1, 3),
969
+ (2, 3, 2),
970
+ (3, 1, 5),
971
+ (3, 2, 1),
972
+ ]
973
+
974
+ G = nx.DiGraph()
975
+ G.add_weighted_edges_from(edges)
976
+
977
+ pytest.raises(nx.NetworkXError, nx_app.traveling_salesman_problem, G)
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ treewidth_min_degree,
6
+ treewidth_min_fill_in,
7
+ )
8
+ from networkx.algorithms.approximation.treewidth import (
9
+ MinDegreeHeuristic,
10
+ min_fill_in_heuristic,
11
+ )
12
+
13
+
14
+ def is_tree_decomp(graph, decomp):
15
+ """Check if the given tree decomposition is valid."""
16
+ for x in graph.nodes():
17
+ appear_once = False
18
+ for bag in decomp.nodes():
19
+ if x in bag:
20
+ appear_once = True
21
+ break
22
+ assert appear_once
23
+
24
+ # Check if each connected pair of nodes are at least once together in a bag
25
+ for x, y in graph.edges():
26
+ appear_together = False
27
+ for bag in decomp.nodes():
28
+ if x in bag and y in bag:
29
+ appear_together = True
30
+ break
31
+ assert appear_together
32
+
33
+ # Check if the nodes associated with vertex v form a connected subset of T
34
+ for v in graph.nodes():
35
+ subset = []
36
+ for bag in decomp.nodes():
37
+ if v in bag:
38
+ subset.append(bag)
39
+ sub_graph = decomp.subgraph(subset)
40
+ assert nx.is_connected(sub_graph)
41
+
42
+
43
+ class TestTreewidthMinDegree:
44
+ """Unit tests for the min_degree function"""
45
+
46
+ @classmethod
47
+ def setup_class(cls):
48
+ """Setup for different kinds of trees"""
49
+ cls.complete = nx.Graph()
50
+ cls.complete.add_edge(1, 2)
51
+ cls.complete.add_edge(2, 3)
52
+ cls.complete.add_edge(1, 3)
53
+
54
+ cls.small_tree = nx.Graph()
55
+ cls.small_tree.add_edge(1, 3)
56
+ cls.small_tree.add_edge(4, 3)
57
+ cls.small_tree.add_edge(2, 3)
58
+ cls.small_tree.add_edge(3, 5)
59
+ cls.small_tree.add_edge(5, 6)
60
+ cls.small_tree.add_edge(5, 7)
61
+ cls.small_tree.add_edge(6, 7)
62
+
63
+ cls.deterministic_graph = nx.Graph()
64
+ cls.deterministic_graph.add_edge(0, 1) # deg(0) = 1
65
+
66
+ cls.deterministic_graph.add_edge(1, 2) # deg(1) = 2
67
+
68
+ cls.deterministic_graph.add_edge(2, 3)
69
+ cls.deterministic_graph.add_edge(2, 4) # deg(2) = 3
70
+
71
+ cls.deterministic_graph.add_edge(3, 4)
72
+ cls.deterministic_graph.add_edge(3, 5)
73
+ cls.deterministic_graph.add_edge(3, 6) # deg(3) = 4
74
+
75
+ cls.deterministic_graph.add_edge(4, 5)
76
+ cls.deterministic_graph.add_edge(4, 6)
77
+ cls.deterministic_graph.add_edge(4, 7) # deg(4) = 5
78
+
79
+ cls.deterministic_graph.add_edge(5, 6)
80
+ cls.deterministic_graph.add_edge(5, 7)
81
+ cls.deterministic_graph.add_edge(5, 8)
82
+ cls.deterministic_graph.add_edge(5, 9) # deg(5) = 6
83
+
84
+ cls.deterministic_graph.add_edge(6, 7)
85
+ cls.deterministic_graph.add_edge(6, 8)
86
+ cls.deterministic_graph.add_edge(6, 9) # deg(6) = 6
87
+
88
+ cls.deterministic_graph.add_edge(7, 8)
89
+ cls.deterministic_graph.add_edge(7, 9) # deg(7) = 5
90
+
91
+ cls.deterministic_graph.add_edge(8, 9) # deg(8) = 4
92
+
93
+ def test_petersen_graph(self):
94
+ """Test Petersen graph tree decomposition result"""
95
+ G = nx.petersen_graph()
96
+ _, decomp = treewidth_min_degree(G)
97
+ is_tree_decomp(G, decomp)
98
+
99
+ def test_small_tree_treewidth(self):
100
+ """Test small tree
101
+
102
+ Test if the computed treewidth of the known self.small_tree is 2.
103
+ As we know which value we can expect from our heuristic, values other
104
+ than two are regressions
105
+ """
106
+ G = self.small_tree
107
+ # the order of removal should be [1,2,4]3[5,6,7]
108
+ # (with [] denoting any order of the containing nodes)
109
+ # resulting in treewidth 2 for the heuristic
110
+ treewidth, _ = treewidth_min_fill_in(G)
111
+ assert treewidth == 2
112
+
113
+ def test_heuristic_abort(self):
114
+ """Test heuristic abort condition for fully connected graph"""
115
+ graph = {}
116
+ for u in self.complete:
117
+ graph[u] = set()
118
+ for v in self.complete[u]:
119
+ if u != v: # ignore self-loop
120
+ graph[u].add(v)
121
+
122
+ deg_heuristic = MinDegreeHeuristic(graph)
123
+ node = deg_heuristic.best_node(graph)
124
+ if node is None:
125
+ pass
126
+ else:
127
+ assert False
128
+
129
+ def test_empty_graph(self):
130
+ """Test empty graph"""
131
+ G = nx.Graph()
132
+ _, _ = treewidth_min_degree(G)
133
+
134
+ def test_two_component_graph(self):
135
+ G = nx.Graph()
136
+ G.add_node(1)
137
+ G.add_node(2)
138
+ treewidth, _ = treewidth_min_degree(G)
139
+ assert treewidth == 0
140
+
141
+ def test_not_sortable_nodes(self):
142
+ G = nx.Graph([(0, "a")])
143
+ treewidth_min_degree(G)
144
+
145
+ def test_heuristic_first_steps(self):
146
+ """Test first steps of min_degree heuristic"""
147
+ graph = {
148
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
149
+ }
150
+ deg_heuristic = MinDegreeHeuristic(graph)
151
+ elim_node = deg_heuristic.best_node(graph)
152
+ print(f"Graph {graph}:")
153
+ steps = []
154
+
155
+ while elim_node is not None:
156
+ print(f"Removing {elim_node}:")
157
+ steps.append(elim_node)
158
+ nbrs = graph[elim_node]
159
+
160
+ for u, v in itertools.permutations(nbrs, 2):
161
+ if v not in graph[u]:
162
+ graph[u].add(v)
163
+
164
+ for u in graph:
165
+ if elim_node in graph[u]:
166
+ graph[u].remove(elim_node)
167
+
168
+ del graph[elim_node]
169
+ print(f"Graph {graph}:")
170
+ elim_node = deg_heuristic.best_node(graph)
171
+
172
+ # check only the first 5 elements for equality
173
+ assert steps[:5] == [0, 1, 2, 3, 4]
174
+
175
+
176
+ class TestTreewidthMinFillIn:
177
+ """Unit tests for the treewidth_min_fill_in function."""
178
+
179
+ @classmethod
180
+ def setup_class(cls):
181
+ """Setup for different kinds of trees"""
182
+ cls.complete = nx.Graph()
183
+ cls.complete.add_edge(1, 2)
184
+ cls.complete.add_edge(2, 3)
185
+ cls.complete.add_edge(1, 3)
186
+
187
+ cls.small_tree = nx.Graph()
188
+ cls.small_tree.add_edge(1, 2)
189
+ cls.small_tree.add_edge(2, 3)
190
+ cls.small_tree.add_edge(3, 4)
191
+ cls.small_tree.add_edge(1, 4)
192
+ cls.small_tree.add_edge(2, 4)
193
+ cls.small_tree.add_edge(4, 5)
194
+ cls.small_tree.add_edge(5, 6)
195
+ cls.small_tree.add_edge(5, 7)
196
+ cls.small_tree.add_edge(6, 7)
197
+
198
+ cls.deterministic_graph = nx.Graph()
199
+ cls.deterministic_graph.add_edge(1, 2)
200
+ cls.deterministic_graph.add_edge(1, 3)
201
+ cls.deterministic_graph.add_edge(3, 4)
202
+ cls.deterministic_graph.add_edge(2, 4)
203
+ cls.deterministic_graph.add_edge(3, 5)
204
+ cls.deterministic_graph.add_edge(4, 5)
205
+ cls.deterministic_graph.add_edge(3, 6)
206
+ cls.deterministic_graph.add_edge(5, 6)
207
+
208
+ def test_petersen_graph(self):
209
+ """Test Petersen graph tree decomposition result"""
210
+ G = nx.petersen_graph()
211
+ _, decomp = treewidth_min_fill_in(G)
212
+ is_tree_decomp(G, decomp)
213
+
214
+ def test_small_tree_treewidth(self):
215
+ """Test if the computed treewidth of the known self.small_tree is 2"""
216
+ G = self.small_tree
217
+ # the order of removal should be [1,2,4]3[5,6,7]
218
+ # (with [] denoting any order of the containing nodes)
219
+ # resulting in treewidth 2 for the heuristic
220
+ treewidth, _ = treewidth_min_fill_in(G)
221
+ assert treewidth == 2
222
+
223
+ def test_heuristic_abort(self):
224
+ """Test if min_fill_in returns None for fully connected graph"""
225
+ graph = {}
226
+ for u in self.complete:
227
+ graph[u] = set()
228
+ for v in self.complete[u]:
229
+ if u != v: # ignore self-loop
230
+ graph[u].add(v)
231
+ next_node = min_fill_in_heuristic(graph)
232
+ if next_node is None:
233
+ pass
234
+ else:
235
+ assert False
236
+
237
+ def test_empty_graph(self):
238
+ """Test empty graph"""
239
+ G = nx.Graph()
240
+ _, _ = treewidth_min_fill_in(G)
241
+
242
+ def test_two_component_graph(self):
243
+ G = nx.Graph()
244
+ G.add_node(1)
245
+ G.add_node(2)
246
+ treewidth, _ = treewidth_min_fill_in(G)
247
+ assert treewidth == 0
248
+
249
+ def test_not_sortable_nodes(self):
250
+ G = nx.Graph([(0, "a")])
251
+ treewidth_min_fill_in(G)
252
+
253
+ def test_heuristic_first_steps(self):
254
+ """Test first steps of min_fill_in heuristic"""
255
+ graph = {
256
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
257
+ }
258
+ print(f"Graph {graph}:")
259
+ elim_node = min_fill_in_heuristic(graph)
260
+ steps = []
261
+
262
+ while elim_node is not None:
263
+ print(f"Removing {elim_node}:")
264
+ steps.append(elim_node)
265
+ nbrs = graph[elim_node]
266
+
267
+ for u, v in itertools.permutations(nbrs, 2):
268
+ if v not in graph[u]:
269
+ graph[u].add(v)
270
+
271
+ for u in graph:
272
+ if elim_node in graph[u]:
273
+ graph[u].remove(elim_node)
274
+
275
+ del graph[elim_node]
276
+ print(f"Graph {graph}:")
277
+ elim_node = min_fill_in_heuristic(graph)
278
+
279
+ # check only the first 2 elements for equality
280
+ assert steps[:2] == [6, 5]
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import min_weighted_vertex_cover
3
+
4
+
5
+ def is_cover(G, node_cover):
6
+ return all({u, v} & node_cover for u, v in G.edges())
7
+
8
+
9
+ class TestMWVC:
10
+ """Unit tests for the approximate minimum weighted vertex cover
11
+ function,
12
+ :func:`~networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover`.
13
+
14
+ """
15
+
16
+ def test_unweighted_directed(self):
17
+ # Create a star graph in which half the nodes are directed in
18
+ # and half are directed out.
19
+ G = nx.DiGraph()
20
+ G.add_edges_from((0, v) for v in range(1, 26))
21
+ G.add_edges_from((v, 0) for v in range(26, 51))
22
+ cover = min_weighted_vertex_cover(G)
23
+ assert 1 == len(cover)
24
+ assert is_cover(G, cover)
25
+
26
+ def test_unweighted_undirected(self):
27
+ # create a simple star graph
28
+ size = 50
29
+ sg = nx.star_graph(size)
30
+ cover = min_weighted_vertex_cover(sg)
31
+ assert 1 == len(cover)
32
+ assert is_cover(sg, cover)
33
+
34
+ def test_weighted(self):
35
+ wg = nx.Graph()
36
+ wg.add_node(0, weight=10)
37
+ wg.add_node(1, weight=1)
38
+ wg.add_node(2, weight=1)
39
+ wg.add_node(3, weight=1)
40
+ wg.add_node(4, weight=1)
41
+
42
+ wg.add_edge(0, 1)
43
+ wg.add_edge(0, 2)
44
+ wg.add_edge(0, 3)
45
+ wg.add_edge(0, 4)
46
+
47
+ wg.add_edge(1, 2)
48
+ wg.add_edge(2, 3)
49
+ wg.add_edge(3, 4)
50
+ wg.add_edge(4, 1)
51
+
52
+ cover = min_weighted_vertex_cover(wg, weight="weight")
53
+ csum = sum(wg.nodes[node]["weight"] for node in cover)
54
+ assert 4 == csum
55
+ assert is_cover(wg, cover)
56
+
57
+ def test_unweighted_self_loop(self):
58
+ slg = nx.Graph()
59
+ slg.add_node(0)
60
+ slg.add_node(1)
61
+ slg.add_node(2)
62
+
63
+ slg.add_edge(0, 1)
64
+ slg.add_edge(2, 2)
65
+
66
+ cover = min_weighted_vertex_cover(slg)
67
+ assert 2 == len(cover)
68
+ assert is_cover(slg, cover)
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/treewidth.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing treewidth decomposition.
2
+
3
+ Treewidth of an undirected graph is a number associated with the graph.
4
+ It can be defined as the size of the largest vertex set (bag) in a tree
5
+ decomposition of the graph minus one.
6
+
7
+ `Wikipedia: Treewidth <https://en.wikipedia.org/wiki/Treewidth>`_
8
+
9
+ The notions of treewidth and tree decomposition have gained their
10
+ attractiveness partly because many graph and network problems that are
11
+ intractable (e.g., NP-hard) on arbitrary graphs become efficiently
12
+ solvable (e.g., with a linear time algorithm) when the treewidth of the
13
+ input graphs is bounded by a constant [1]_ [2]_.
14
+
15
+ There are two different functions for computing a tree decomposition:
16
+ :func:`treewidth_min_degree` and :func:`treewidth_min_fill_in`.
17
+
18
+ .. [1] Hans L. Bodlaender and Arie M. C. A. Koster. 2010. "Treewidth
19
+ computations I.Upper bounds". Inf. Comput. 208, 3 (March 2010),259-275.
20
+ http://dx.doi.org/10.1016/j.ic.2009.03.008
21
+
22
+ .. [2] Hans L. Bodlaender. "Discovering Treewidth". Institute of Information
23
+ and Computing Sciences, Utrecht University.
24
+ Technical Report UU-CS-2005-018.
25
+ http://www.cs.uu.nl
26
+
27
+ .. [3] K. Wang, Z. Lu, and J. Hicks *Treewidth*.
28
+ https://web.archive.org/web/20210507025929/http://web.eecs.utk.edu/~cphill25/cs594_spring2015_projects/treewidth.pdf
29
+
30
+ """
31
+
32
+ import itertools
33
+ import sys
34
+ from heapq import heapify, heappop, heappush
35
+
36
+ import networkx as nx
37
+ from networkx.utils import not_implemented_for
38
+
39
+ __all__ = ["treewidth_min_degree", "treewidth_min_fill_in"]
40
+
41
+
42
+ @not_implemented_for("directed")
43
+ @not_implemented_for("multigraph")
44
+ @nx._dispatchable(returns_graph=True)
45
+ def treewidth_min_degree(G):
46
+ """Returns a treewidth decomposition using the Minimum Degree heuristic.
47
+
48
+ The heuristic chooses the nodes according to their degree, i.e., first
49
+ the node with the lowest degree is chosen, then the graph is updated
50
+ and the corresponding node is removed. Next, a new node with the lowest
51
+ degree is chosen, and so on.
52
+
53
+ Parameters
54
+ ----------
55
+ G : NetworkX graph
56
+
57
+ Returns
58
+ -------
59
+ Treewidth decomposition : (int, Graph) tuple
60
+ 2-tuple with treewidth and the corresponding decomposed tree.
61
+ """
62
+ deg_heuristic = MinDegreeHeuristic(G)
63
+ return treewidth_decomp(G, lambda graph: deg_heuristic.best_node(graph))
64
+
65
+
66
+ @not_implemented_for("directed")
67
+ @not_implemented_for("multigraph")
68
+ @nx._dispatchable(returns_graph=True)
69
+ def treewidth_min_fill_in(G):
70
+ """Returns a treewidth decomposition using the Minimum Fill-in heuristic.
71
+
72
+ The heuristic chooses a node from the graph, where the number of edges
73
+ added turning the neighborhood of the chosen node into clique is as
74
+ small as possible.
75
+
76
+ Parameters
77
+ ----------
78
+ G : NetworkX graph
79
+
80
+ Returns
81
+ -------
82
+ Treewidth decomposition : (int, Graph) tuple
83
+ 2-tuple with treewidth and the corresponding decomposed tree.
84
+ """
85
+ return treewidth_decomp(G, min_fill_in_heuristic)
86
+
87
+
88
+ class MinDegreeHeuristic:
89
+ """Implements the Minimum Degree heuristic.
90
+
91
+ The heuristic chooses the nodes according to their degree
92
+ (number of neighbors), i.e., first the node with the lowest degree is
93
+ chosen, then the graph is updated and the corresponding node is
94
+ removed. Next, a new node with the lowest degree is chosen, and so on.
95
+ """
96
+
97
+ def __init__(self, graph):
98
+ self._graph = graph
99
+
100
+ # nodes that have to be updated in the heap before each iteration
101
+ self._update_nodes = []
102
+
103
+ self._degreeq = [] # a heapq with 3-tuples (degree,unique_id,node)
104
+ self.count = itertools.count()
105
+
106
+ # build heap with initial degrees
107
+ for n in graph:
108
+ self._degreeq.append((len(graph[n]), next(self.count), n))
109
+ heapify(self._degreeq)
110
+
111
+ def best_node(self, graph):
112
+ # update nodes in self._update_nodes
113
+ for n in self._update_nodes:
114
+ # insert changed degrees into degreeq
115
+ heappush(self._degreeq, (len(graph[n]), next(self.count), n))
116
+
117
+ # get the next valid (minimum degree) node
118
+ while self._degreeq:
119
+ (min_degree, _, elim_node) = heappop(self._degreeq)
120
+ if elim_node not in graph or len(graph[elim_node]) != min_degree:
121
+ # outdated entry in degreeq
122
+ continue
123
+ elif min_degree == len(graph) - 1:
124
+ # fully connected: abort condition
125
+ return None
126
+
127
+ # remember to update nodes in the heap before getting the next node
128
+ self._update_nodes = graph[elim_node]
129
+ return elim_node
130
+
131
+ # the heap is empty: abort
132
+ return None
133
+
134
+
135
+ def min_fill_in_heuristic(graph):
136
+ """Implements the Minimum Degree heuristic.
137
+
138
+ Returns the node from the graph, where the number of edges added when
139
+ turning the neighborhood of the chosen node into clique is as small as
140
+ possible. This algorithm chooses the nodes using the Minimum Fill-In
141
+ heuristic. The running time of the algorithm is :math:`O(V^3)` and it uses
142
+ additional constant memory."""
143
+
144
+ if len(graph) == 0:
145
+ return None
146
+
147
+ min_fill_in_node = None
148
+
149
+ min_fill_in = sys.maxsize
150
+
151
+ # sort nodes by degree
152
+ nodes_by_degree = sorted(graph, key=lambda x: len(graph[x]))
153
+ min_degree = len(graph[nodes_by_degree[0]])
154
+
155
+ # abort condition (handle complete graph)
156
+ if min_degree == len(graph) - 1:
157
+ return None
158
+
159
+ for node in nodes_by_degree:
160
+ num_fill_in = 0
161
+ nbrs = graph[node]
162
+ for nbr in nbrs:
163
+ # count how many nodes in nbrs current nbr is not connected to
164
+ # subtract 1 for the node itself
165
+ num_fill_in += len(nbrs - graph[nbr]) - 1
166
+ if num_fill_in >= 2 * min_fill_in:
167
+ break
168
+
169
+ num_fill_in /= 2 # divide by 2 because of double counting
170
+
171
+ if num_fill_in < min_fill_in: # update min-fill-in node
172
+ if num_fill_in == 0:
173
+ return node
174
+ min_fill_in = num_fill_in
175
+ min_fill_in_node = node
176
+
177
+ return min_fill_in_node
178
+
179
+
180
+ @nx._dispatchable(returns_graph=True)
181
+ def treewidth_decomp(G, heuristic=min_fill_in_heuristic):
182
+ """Returns a treewidth decomposition using the passed heuristic.
183
+
184
+ Parameters
185
+ ----------
186
+ G : NetworkX graph
187
+ heuristic : heuristic function
188
+
189
+ Returns
190
+ -------
191
+ Treewidth decomposition : (int, Graph) tuple
192
+ 2-tuple with treewidth and the corresponding decomposed tree.
193
+ """
194
+
195
+ # make dict-of-sets structure
196
+ graph = {n: set(G[n]) - {n} for n in G}
197
+
198
+ # stack containing nodes and neighbors in the order from the heuristic
199
+ node_stack = []
200
+
201
+ # get first node from heuristic
202
+ elim_node = heuristic(graph)
203
+ while elim_node is not None:
204
+ # connect all neighbors with each other
205
+ nbrs = graph[elim_node]
206
+ for u, v in itertools.permutations(nbrs, 2):
207
+ if v not in graph[u]:
208
+ graph[u].add(v)
209
+
210
+ # push node and its current neighbors on stack
211
+ node_stack.append((elim_node, nbrs))
212
+
213
+ # remove node from graph
214
+ for u in graph[elim_node]:
215
+ graph[u].remove(elim_node)
216
+
217
+ del graph[elim_node]
218
+ elim_node = heuristic(graph)
219
+
220
+ # the abort condition is met; put all remaining nodes into one bag
221
+ decomp = nx.Graph()
222
+ first_bag = frozenset(graph.keys())
223
+ decomp.add_node(first_bag)
224
+
225
+ treewidth = len(first_bag) - 1
226
+
227
+ while node_stack:
228
+ # get node and its neighbors from the stack
229
+ (curr_node, nbrs) = node_stack.pop()
230
+
231
+ # find a bag all neighbors are in
232
+ old_bag = None
233
+ for bag in decomp.nodes:
234
+ if nbrs <= bag:
235
+ old_bag = bag
236
+ break
237
+
238
+ if old_bag is None:
239
+ # no old_bag was found: just connect to the first_bag
240
+ old_bag = first_bag
241
+
242
+ # create new node for decomposition
243
+ nbrs.add(curr_node)
244
+ new_bag = frozenset(nbrs)
245
+
246
+ # update treewidth
247
+ treewidth = max(treewidth, len(new_bag) - 1)
248
+
249
+ # add edge to decomposition (implicitly also adds the new node)
250
+ decomp.add_edge(old_bag, new_bag)
251
+
252
+ return treewidth, decomp
.venv/lib/python3.11/site-packages/networkx/algorithms/approximation/vertex_cover.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing an approximate minimum weight vertex cover.
2
+
3
+ A |vertex cover|_ is a subset of nodes such that each edge in the graph
4
+ is incident to at least one node in the subset.
5
+
6
+ .. _vertex cover: https://en.wikipedia.org/wiki/Vertex_cover
7
+ .. |vertex cover| replace:: *vertex cover*
8
+
9
+ """
10
+
11
+ import networkx as nx
12
+
13
+ __all__ = ["min_weighted_vertex_cover"]
14
+
15
+
16
+ @nx._dispatchable(node_attrs="weight")
17
+ def min_weighted_vertex_cover(G, weight=None):
18
+ r"""Returns an approximate minimum weighted vertex cover.
19
+
20
+ The set of nodes returned by this function is guaranteed to be a
21
+ vertex cover, and the total weight of the set is guaranteed to be at
22
+ most twice the total weight of the minimum weight vertex cover. In
23
+ other words,
24
+
25
+ .. math::
26
+
27
+ w(S) \leq 2 * w(S^*),
28
+
29
+ where $S$ is the vertex cover returned by this function,
30
+ $S^*$ is the vertex cover of minimum weight out of all vertex
31
+ covers of the graph, and $w$ is the function that computes the
32
+ sum of the weights of each node in that given set.
33
+
34
+ Parameters
35
+ ----------
36
+ G : NetworkX graph
37
+
38
+ weight : string, optional (default = None)
39
+ If None, every node has weight 1. If a string, use this node
40
+ attribute as the node weight. A node without this attribute is
41
+ assumed to have weight 1.
42
+
43
+ Returns
44
+ -------
45
+ min_weighted_cover : set
46
+ Returns a set of nodes whose weight sum is no more than twice
47
+ the weight sum of the minimum weight vertex cover.
48
+
49
+ Notes
50
+ -----
51
+ For a directed graph, a vertex cover has the same definition: a set
52
+ of nodes such that each edge in the graph is incident to at least
53
+ one node in the set. Whether the node is the head or tail of the
54
+ directed edge is ignored.
55
+
56
+ This is the local-ratio algorithm for computing an approximate
57
+ vertex cover. The algorithm greedily reduces the costs over edges,
58
+ iteratively building a cover. The worst-case runtime of this
59
+ implementation is $O(m \log n)$, where $n$ is the number
60
+ of nodes and $m$ the number of edges in the graph.
61
+
62
+ References
63
+ ----------
64
+ .. [1] Bar-Yehuda, R., and Even, S. (1985). "A local-ratio theorem for
65
+ approximating the weighted vertex cover problem."
66
+ *Annals of Discrete Mathematics*, 25, 27–46
67
+ <http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf>
68
+
69
+ """
70
+ cost = dict(G.nodes(data=weight, default=1))
71
+ # While there are uncovered edges, choose an uncovered and update
72
+ # the cost of the remaining edges.
73
+ cover = set()
74
+ for u, v in G.edges():
75
+ if u in cover or v in cover:
76
+ continue
77
+ if cost[u] <= cost[v]:
78
+ cover.add(u)
79
+ cost[v] -= cost[u]
80
+ else:
81
+ cover.add(v)
82
+ cost[u] -= cost[v]
83
+ return cover
.venv/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing and measuring community structure.
2
+
3
+ The ``community`` subpackage can be accessed by using :mod:`networkx.community`, then accessing the
4
+ functions as attributes of ``community``. For example::
5
+
6
+ >>> import networkx as nx
7
+ >>> G = nx.barbell_graph(5, 1)
8
+ >>> communities_generator = nx.community.girvan_newman(G)
9
+ >>> top_level_communities = next(communities_generator)
10
+ >>> next_level_communities = next(communities_generator)
11
+ >>> sorted(map(sorted, next_level_communities))
12
+ [[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]]
13
+
14
+ """
15
+
16
+ from networkx.algorithms.community.asyn_fluid import *
17
+ from networkx.algorithms.community.centrality import *
18
+ from networkx.algorithms.community.divisive import *
19
+ from networkx.algorithms.community.kclique import *
20
+ from networkx.algorithms.community.kernighan_lin import *
21
+ from networkx.algorithms.community.label_propagation import *
22
+ from networkx.algorithms.community.lukes import *
23
+ from networkx.algorithms.community.modularity_max import *
24
+ from networkx.algorithms.community.quality import *
25
+ from networkx.algorithms.community.community_utils import *
26
+ from networkx.algorithms.community.louvain import *
.venv/lib/python3.11/site-packages/networkx/algorithms/community/__pycache__/centrality.cpython-311.pyc ADDED
Binary file (7.3 kB). View file