ZAIDX11 commited on
Commit
aafbbaf
·
verified ·
1 Parent(s): fac481d

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/__init__.py +26 -0
  2. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/__init__.py +0 -0
  3. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py +41 -0
  4. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_clique.py +112 -0
  5. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py +199 -0
  6. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_density.py +138 -0
  7. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py +59 -0
  8. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py +78 -0
  9. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py +303 -0
  10. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_matching.py +8 -0
  11. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py +94 -0
  12. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py +31 -0
  13. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py +265 -0
  14. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py +1013 -0
  15. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py +274 -0
  16. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py +68 -0
  17. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/vertex_cover.py +83 -0
  18. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/assortativity/connectivity.py +122 -0
  19. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/assortativity/correlation.py +302 -0
  20. archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/assortativity/mixing.py +255 -0
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Approximations of graph properties and Heuristic methods for optimization.
2
+
3
+ The functions in this class are not imported into the top-level ``networkx``
4
+ namespace so the easiest way to use them is with::
5
+
6
+ >>> from networkx.algorithms import approximation
7
+
8
+ Another option is to import the specific function with
9
+ ``from networkx.algorithms.approximation import function_name``.
10
+
11
+ """
12
+
13
+ from networkx.algorithms.approximation.clustering_coefficient import *
14
+ from networkx.algorithms.approximation.clique import *
15
+ from networkx.algorithms.approximation.connectivity import *
16
+ from networkx.algorithms.approximation.distance_measures import *
17
+ from networkx.algorithms.approximation.dominating_set import *
18
+ from networkx.algorithms.approximation.kcomponents import *
19
+ from networkx.algorithms.approximation.matching import *
20
+ from networkx.algorithms.approximation.ramsey import *
21
+ from networkx.algorithms.approximation.steinertree import *
22
+ from networkx.algorithms.approximation.traveling_salesman import *
23
+ from networkx.algorithms.approximation.treewidth import *
24
+ from networkx.algorithms.approximation.vertex_cover import *
25
+ from networkx.algorithms.approximation.maxcut import *
26
+ from networkx.algorithms.approximation.density import *
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/__init__.py ADDED
File without changes
archive/Axiovorax/.venv/Lib/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
archive/Axiovorax/.venv/Lib/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
archive/Axiovorax/.venv/Lib/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)
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_density.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ import networkx.algorithms.approximation as approx
5
+
6
+
7
+ def close_cliques_example(d=12, D=300, h=24, k=2):
8
+ """
9
+ Hard example from Harb, Elfarouk, Kent Quanrud, and Chandra Chekuri.
10
+ "Faster and scalable algorithms for densest subgraph and decomposition."
11
+ Advances in Neural Information Processing Systems 35 (2022): 26966-26979.
12
+ """
13
+ Kh = nx.complete_graph(h)
14
+ KdD = nx.complete_bipartite_graph(d, D)
15
+ G = nx.disjoint_union_all([KdD] + [Kh for _ in range(k)])
16
+ best_density = d * D / (d + D) # of the complete bipartite graph
17
+ return G, best_density, set(KdD.nodes)
18
+
19
+
20
+ @pytest.mark.parametrize("iterations", (1, 3))
21
+ @pytest.mark.parametrize("n", range(4, 7))
22
+ @pytest.mark.parametrize("method", ("greedy++", "fista"))
23
+ def test_star(n, iterations, method):
24
+ if method == "fista":
25
+ pytest.importorskip("numpy")
26
+
27
+ G = nx.star_graph(n)
28
+ # The densest subgraph of a star network is the entire graph.
29
+ # The peeling algorithm would peel all the vertices with degree 1,
30
+ # and so should discover the densest subgraph in one iteration!
31
+ d, S = approx.densest_subgraph(G, iterations=iterations, method=method)
32
+
33
+ assert d == pytest.approx(G.number_of_edges() / G.number_of_nodes())
34
+ assert S == set(G) # The entire graph!
35
+
36
+
37
+ @pytest.mark.parametrize("method", ("greedy++", "fista"))
38
+ def test_greedy_plus_plus_complete_graph(method):
39
+ if method == "fista":
40
+ pytest.importorskip("numpy")
41
+
42
+ G = nx.complete_graph(4)
43
+ # The density of a complete graph network is the entire graph: C(4, 2)/4
44
+ # where C(n, 2) is n*(n-1)//2. The peeling algorithm would find
45
+ # the densest subgraph in one iteration!
46
+ d, S = approx.densest_subgraph(G, iterations=1, method=method)
47
+
48
+ assert d == pytest.approx(6 / 4) # The density, 4/5=0.8.
49
+ assert S == {0, 1, 2, 3} # The entire graph!
50
+
51
+
52
+ def test_greedy_plus_plus_close_cliques():
53
+ G, best_density, densest_set = close_cliques_example()
54
+ # NOTE: iterations=185 fails to ID the densest subgraph
55
+ greedy_pp, S_pp = approx.densest_subgraph(G, iterations=186, method="greedy++")
56
+
57
+ assert greedy_pp == pytest.approx(best_density)
58
+ assert S_pp == densest_set
59
+
60
+
61
+ def test_fista_close_cliques():
62
+ pytest.importorskip("numpy")
63
+ G, best_density, best_set = close_cliques_example()
64
+ # NOTE: iterations=12 fails to ID the densest subgraph
65
+ density, dense_set = approx.densest_subgraph(G, iterations=13, method="fista")
66
+
67
+ assert density == pytest.approx(best_density)
68
+ assert dense_set == best_set
69
+
70
+
71
+ def bipartite_and_clique_example(d=5, D=200, k=2):
72
+ """
73
+ Hard example from: Boob, Digvijay, Yu Gao, Richard Peng, Saurabh Sawlani,
74
+ Charalampos Tsourakakis, Di Wang, and Junxing Wang. "Flowless: Extracting
75
+ densest subgraphs without flow computations." In Proceedings of The Web
76
+ Conference 2020, pp. 573-583. 2020.
77
+ """
78
+ B = nx.complete_bipartite_graph(d, D)
79
+ H = [nx.complete_graph(d + 2) for _ in range(k)]
80
+ G = nx.disjoint_union_all([B] + H)
81
+
82
+ best_density = d * D / (d + D) # of the complete bipartite graph
83
+ correct_one_round_density = (2 * d * D + (d + 1) * (d + 2) * k) / (
84
+ 2 * d + 2 * D + 2 * k * (d + 2)
85
+ )
86
+ best_subgraph = set(B.nodes)
87
+ return G, best_density, best_subgraph, correct_one_round_density
88
+
89
+
90
+ def test_greedy_plus_plus_bipartite_and_clique():
91
+ G, best_density, best_subgraph, correct_one_iter_density = (
92
+ bipartite_and_clique_example()
93
+ )
94
+ one_round_density, S_one = approx.densest_subgraph(
95
+ G, iterations=1, method="greedy++"
96
+ )
97
+ assert one_round_density == pytest.approx(correct_one_iter_density)
98
+ assert S_one == set(G.nodes)
99
+
100
+ ten_round_density, S_ten = approx.densest_subgraph(
101
+ G, iterations=10, method="greedy++"
102
+ )
103
+ assert ten_round_density == pytest.approx(best_density)
104
+ assert S_ten == best_subgraph
105
+
106
+
107
+ def test_fista_bipartite_and_clique():
108
+ pytest.importorskip("numpy")
109
+ G, best_density, best_subgraph, _ = bipartite_and_clique_example()
110
+
111
+ ten_round_density, S_ten = approx.densest_subgraph(G, iterations=10, method="fista")
112
+ assert ten_round_density == pytest.approx(best_density)
113
+ assert S_ten == best_subgraph
114
+
115
+
116
+ def test_fista_big_dataset():
117
+ pytest.importorskip("numpy")
118
+ G, best_density, best_subgraph = close_cliques_example(d=30, D=2000, h=60, k=20)
119
+
120
+ # Note: iterations=12 fails to identify densest subgraph
121
+ density, dense_set = approx.densest_subgraph(G, iterations=13, method="fista")
122
+
123
+ assert density == pytest.approx(best_density)
124
+ assert dense_set == best_subgraph
125
+
126
+
127
+ @pytest.mark.parametrize("iterations", (1, 3))
128
+ def test_greedy_plus_plus_edgeless_cornercase(iterations):
129
+ G = nx.Graph()
130
+ assert approx.densest_subgraph(G, iterations=iterations, method="greedy++") == (
131
+ 0,
132
+ set(),
133
+ )
134
+ G.add_nodes_from(range(4))
135
+ assert approx.densest_subgraph(G, iterations=iterations, method="greedy++") == (
136
+ 0,
137
+ set(),
138
+ )
archive/Axiovorax/.venv/Lib/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
archive/Axiovorax/.venv/Lib/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)
archive/Axiovorax/.venv/Lib/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
+ )
archive/Axiovorax/.venv/Lib/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
archive/Axiovorax/.venv/Lib/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)
archive/Axiovorax/.venv/Lib/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
archive/Axiovorax/.venv/Lib/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, dict.fromkeys(G.edges, 10), 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, dict.fromkeys(G.edges, 10), 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]
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py ADDED
@@ -0,0 +1,1013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert cost > self.DG2_cost
253
+
254
+ # Try with an incorrect initial guess
255
+ initial_sol = ["D", "A", "B", "C", "D"]
256
+ cycle = self.tsp(
257
+ self.DG,
258
+ initial_sol,
259
+ source="D",
260
+ move="1-0",
261
+ alpha=0.1,
262
+ N_inner=1,
263
+ max_iterations=1,
264
+ seed=42,
265
+ )
266
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
267
+ assert cost > self.DG_cost
268
+
269
+
270
+ class TestThresholdAcceptingTSP(TestSimulatedAnnealingTSP):
271
+ tsp = staticmethod(nx_app.threshold_accepting_tsp)
272
+
273
+ def test_failure_of_costs_too_high_when_iterations_low(self):
274
+ # Threshold Version:
275
+ # set number of moves low and number of iterations low
276
+ cycle = self.tsp(
277
+ self.DG2,
278
+ "greedy",
279
+ source="D",
280
+ move="1-0",
281
+ N_inner=1,
282
+ max_iterations=1,
283
+ seed=4,
284
+ )
285
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
286
+ assert cost > self.DG2_cost
287
+
288
+ # set threshold too low
289
+ initial_sol = ["D", "A", "B", "C", "D"]
290
+ cycle = self.tsp(
291
+ self.DG, initial_sol, source="D", move="1-0", threshold=-3, seed=42
292
+ )
293
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
294
+ assert cost > self.DG_cost
295
+
296
+
297
+ # Tests for function traveling_salesman_problem
298
+ def test_TSP_method():
299
+ G = nx.cycle_graph(9)
300
+ G[4][5]["weight"] = 10
301
+
302
+ # Test using the old currying method
303
+ def sa_tsp(G, weight):
304
+ return nx_app.simulated_annealing_tsp(G, "greedy", weight, source=4, seed=1)
305
+
306
+ path = nx_app.traveling_salesman_problem(
307
+ G,
308
+ method=sa_tsp,
309
+ cycle=False,
310
+ )
311
+ assert path == [4, 3, 2, 1, 0, 8, 7, 6, 5]
312
+
313
+
314
+ def test_TSP_unweighted():
315
+ G = nx.cycle_graph(9)
316
+ path = nx_app.traveling_salesman_problem(G, nodes=[3, 6], cycle=False)
317
+ assert path in ([3, 4, 5, 6], [6, 5, 4, 3])
318
+
319
+ cycle = nx_app.traveling_salesman_problem(G, nodes=[3, 6])
320
+ assert cycle in ([3, 4, 5, 6, 5, 4, 3], [6, 5, 4, 3, 4, 5, 6])
321
+
322
+
323
+ def test_TSP_weighted():
324
+ G = nx.cycle_graph(9)
325
+ G[0][1]["weight"] = 2
326
+ G[1][2]["weight"] = 2
327
+ G[2][3]["weight"] = 2
328
+ G[3][4]["weight"] = 4
329
+ G[4][5]["weight"] = 5
330
+ G[5][6]["weight"] = 4
331
+ G[6][7]["weight"] = 2
332
+ G[7][8]["weight"] = 2
333
+ G[8][0]["weight"] = 2
334
+ tsp = nx_app.traveling_salesman_problem
335
+
336
+ # path between 3 and 6
337
+ expected_paths = ([3, 2, 1, 0, 8, 7, 6], [6, 7, 8, 0, 1, 2, 3])
338
+ # cycle between 3 and 6
339
+ expected_cycles = (
340
+ [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3],
341
+ [6, 7, 8, 0, 1, 2, 3, 2, 1, 0, 8, 7, 6],
342
+ )
343
+ # path through all nodes
344
+ expected_tourpaths = ([5, 6, 7, 8, 0, 1, 2, 3, 4], [4, 3, 2, 1, 0, 8, 7, 6, 5])
345
+
346
+ # Check default method
347
+ cycle = tsp(G, nodes=[3, 6], weight="weight")
348
+ assert cycle in expected_cycles
349
+
350
+ path = tsp(G, nodes=[3, 6], weight="weight", cycle=False)
351
+ assert path in expected_paths
352
+
353
+ tourpath = tsp(G, weight="weight", cycle=False)
354
+ assert tourpath in expected_tourpaths
355
+
356
+ # Check all methods
357
+ methods = [
358
+ (nx_app.christofides, {}),
359
+ (nx_app.greedy_tsp, {}),
360
+ (
361
+ nx_app.simulated_annealing_tsp,
362
+ {"init_cycle": "greedy"},
363
+ ),
364
+ (
365
+ nx_app.threshold_accepting_tsp,
366
+ {"init_cycle": "greedy"},
367
+ ),
368
+ ]
369
+ for method, kwargs in methods:
370
+ cycle = tsp(G, nodes=[3, 6], weight="weight", method=method, **kwargs)
371
+ assert cycle in expected_cycles
372
+
373
+ path = tsp(
374
+ G, nodes=[3, 6], weight="weight", method=method, cycle=False, **kwargs
375
+ )
376
+ assert path in expected_paths
377
+
378
+ tourpath = tsp(G, weight="weight", method=method, cycle=False, **kwargs)
379
+ assert tourpath in expected_tourpaths
380
+
381
+
382
+ def test_TSP_incomplete_graph_short_path():
383
+ G = nx.cycle_graph(9)
384
+ G.add_edges_from([(4, 9), (9, 10), (10, 11), (11, 0)])
385
+ G[4][5]["weight"] = 5
386
+
387
+ cycle = nx_app.traveling_salesman_problem(G)
388
+ assert len(cycle) == 17 and len(set(cycle)) == 12
389
+
390
+ # make sure that cutting one edge out of complete graph formulation
391
+ # cuts out many edges out of the path of the TSP
392
+ path = nx_app.traveling_salesman_problem(G, cycle=False)
393
+ assert len(path) == 13 and len(set(path)) == 12
394
+
395
+
396
+ def test_TSP_alternate_weight():
397
+ G = nx.complete_graph(9)
398
+ G[0][1]["weight"] = 2
399
+ G[1][2]["weight"] = 2
400
+ G[2][3]["weight"] = 2
401
+ G[3][4]["weight"] = 4
402
+ G[4][5]["weight"] = 5
403
+ G[5][6]["weight"] = 4
404
+ G[6][7]["weight"] = 2
405
+ G[7][8]["weight"] = 2
406
+ G[8][0]["weight"] = 2
407
+
408
+ H = nx.complete_graph(9)
409
+ H[0][1]["distance"] = 2
410
+ H[1][2]["distance"] = 2
411
+ H[2][3]["distance"] = 2
412
+ H[3][4]["distance"] = 4
413
+ H[4][5]["distance"] = 5
414
+ H[5][6]["distance"] = 4
415
+ H[6][7]["distance"] = 2
416
+ H[7][8]["distance"] = 2
417
+ H[8][0]["distance"] = 2
418
+
419
+ assert nx_app.traveling_salesman_problem(
420
+ G, weight="weight"
421
+ ) == nx_app.traveling_salesman_problem(H, weight="distance")
422
+
423
+
424
+ def test_held_karp_ascent():
425
+ """
426
+ Test the Held-Karp relaxation with the ascent method
427
+ """
428
+ import networkx.algorithms.approximation.traveling_salesman as tsp
429
+
430
+ np = pytest.importorskip("numpy")
431
+ pytest.importorskip("scipy")
432
+
433
+ # Adjacency matrix from page 1153 of the 1970 Held and Karp paper
434
+ # which have been edited to be directional, but also symmetric
435
+ G_array = np.array(
436
+ [
437
+ [0, 97, 60, 73, 17, 52],
438
+ [97, 0, 41, 52, 90, 30],
439
+ [60, 41, 0, 21, 35, 41],
440
+ [73, 52, 21, 0, 95, 46],
441
+ [17, 90, 35, 95, 0, 81],
442
+ [52, 30, 41, 46, 81, 0],
443
+ ]
444
+ )
445
+
446
+ solution_edges = [(1, 3), (2, 4), (3, 2), (4, 0), (5, 1), (0, 5)]
447
+
448
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
449
+ opt_hk, z_star = tsp.held_karp_ascent(G)
450
+
451
+ # Check that the optimal weights are the same
452
+ assert round(opt_hk, 2) == 207.00
453
+ # Check that the z_stars are the same
454
+ solution = nx.DiGraph()
455
+ solution.add_edges_from(solution_edges)
456
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
457
+
458
+
459
+ def test_ascent_fractional_solution():
460
+ """
461
+ Test the ascent method using a modified version of Figure 2 on page 1140
462
+ in 'The Traveling Salesman Problem and Minimum Spanning Trees' by Held and
463
+ Karp
464
+ """
465
+ import networkx.algorithms.approximation.traveling_salesman as tsp
466
+
467
+ np = pytest.importorskip("numpy")
468
+ pytest.importorskip("scipy")
469
+
470
+ # This version of Figure 2 has all of the edge weights multiplied by 100
471
+ # and is a complete directed graph with infinite edge weights for the
472
+ # edges not listed in the original graph
473
+ G_array = np.array(
474
+ [
475
+ [0, 100, 100, 100000, 100000, 1],
476
+ [100, 0, 100, 100000, 1, 100000],
477
+ [100, 100, 0, 1, 100000, 100000],
478
+ [100000, 100000, 1, 0, 100, 100],
479
+ [100000, 1, 100000, 100, 0, 100],
480
+ [1, 100000, 100000, 100, 100, 0],
481
+ ]
482
+ )
483
+
484
+ solution_z_star = {
485
+ (0, 1): 5 / 12,
486
+ (0, 2): 5 / 12,
487
+ (0, 5): 5 / 6,
488
+ (1, 0): 5 / 12,
489
+ (1, 2): 1 / 3,
490
+ (1, 4): 5 / 6,
491
+ (2, 0): 5 / 12,
492
+ (2, 1): 1 / 3,
493
+ (2, 3): 5 / 6,
494
+ (3, 2): 5 / 6,
495
+ (3, 4): 1 / 3,
496
+ (3, 5): 1 / 2,
497
+ (4, 1): 5 / 6,
498
+ (4, 3): 1 / 3,
499
+ (4, 5): 1 / 2,
500
+ (5, 0): 5 / 6,
501
+ (5, 3): 1 / 2,
502
+ (5, 4): 1 / 2,
503
+ }
504
+
505
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
506
+ opt_hk, z_star = tsp.held_karp_ascent(G)
507
+
508
+ # Check that the optimal weights are the same
509
+ assert round(opt_hk, 2) == 303.00
510
+ # Check that the z_stars are the same
511
+ assert {key: round(z_star[key], 4) for key in z_star} == {
512
+ key: round(solution_z_star[key], 4) for key in solution_z_star
513
+ }
514
+
515
+
516
+ def test_ascent_method_asymmetric():
517
+ """
518
+ Tests the ascent method using a truly asymmetric graph for which the
519
+ solution has been brute forced
520
+ """
521
+ import networkx.algorithms.approximation.traveling_salesman as tsp
522
+
523
+ np = pytest.importorskip("numpy")
524
+ pytest.importorskip("scipy")
525
+
526
+ G_array = np.array(
527
+ [
528
+ [0, 26, 63, 59, 69, 31, 41],
529
+ [62, 0, 91, 53, 75, 87, 47],
530
+ [47, 82, 0, 90, 15, 9, 18],
531
+ [68, 19, 5, 0, 58, 34, 93],
532
+ [11, 58, 53, 55, 0, 61, 79],
533
+ [88, 75, 13, 76, 98, 0, 40],
534
+ [41, 61, 55, 88, 46, 45, 0],
535
+ ]
536
+ )
537
+
538
+ solution_edges = [(0, 1), (1, 3), (3, 2), (2, 5), (5, 6), (4, 0), (6, 4)]
539
+
540
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
541
+ opt_hk, z_star = tsp.held_karp_ascent(G)
542
+
543
+ # Check that the optimal weights are the same
544
+ assert round(opt_hk, 2) == 190.00
545
+ # Check that the z_stars match.
546
+ solution = nx.DiGraph()
547
+ solution.add_edges_from(solution_edges)
548
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
549
+
550
+
551
+ def test_ascent_method_asymmetric_2():
552
+ """
553
+ Tests the ascent method using a truly asymmetric graph for which the
554
+ solution has been brute forced
555
+ """
556
+ import networkx.algorithms.approximation.traveling_salesman as tsp
557
+
558
+ np = pytest.importorskip("numpy")
559
+ pytest.importorskip("scipy")
560
+
561
+ G_array = np.array(
562
+ [
563
+ [0, 45, 39, 92, 29, 31],
564
+ [72, 0, 4, 12, 21, 60],
565
+ [81, 6, 0, 98, 70, 53],
566
+ [49, 71, 59, 0, 98, 94],
567
+ [74, 95, 24, 43, 0, 47],
568
+ [56, 43, 3, 65, 22, 0],
569
+ ]
570
+ )
571
+
572
+ solution_edges = [(0, 5), (5, 4), (1, 3), (3, 0), (2, 1), (4, 2)]
573
+
574
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
575
+ opt_hk, z_star = tsp.held_karp_ascent(G)
576
+
577
+ # Check that the optimal weights are the same
578
+ assert round(opt_hk, 2) == 144.00
579
+ # Check that the z_stars match.
580
+ solution = nx.DiGraph()
581
+ solution.add_edges_from(solution_edges)
582
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
583
+
584
+
585
+ def test_held_karp_ascent_asymmetric_3():
586
+ """
587
+ Tests the ascent method using a truly asymmetric graph with a fractional
588
+ solution for which the solution has been brute forced.
589
+
590
+ In this graph their are two different optimal, integral solutions (which
591
+ are also the overall atsp solutions) to the Held Karp relaxation. However,
592
+ this particular graph has two different tours of optimal value and the
593
+ possible solutions in the held_karp_ascent function are not stored in an
594
+ ordered data structure.
595
+ """
596
+ import networkx.algorithms.approximation.traveling_salesman as tsp
597
+
598
+ np = pytest.importorskip("numpy")
599
+ pytest.importorskip("scipy")
600
+
601
+ G_array = np.array(
602
+ [
603
+ [0, 1, 5, 2, 7, 4],
604
+ [7, 0, 7, 7, 1, 4],
605
+ [4, 7, 0, 9, 2, 1],
606
+ [7, 2, 7, 0, 4, 4],
607
+ [5, 5, 4, 4, 0, 3],
608
+ [3, 9, 1, 3, 4, 0],
609
+ ]
610
+ )
611
+
612
+ solution1_edges = [(0, 3), (1, 4), (2, 5), (3, 1), (4, 2), (5, 0)]
613
+
614
+ solution2_edges = [(0, 3), (3, 1), (1, 4), (4, 5), (2, 0), (5, 2)]
615
+
616
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
617
+ opt_hk, z_star = tsp.held_karp_ascent(G)
618
+
619
+ assert round(opt_hk, 2) == 13.00
620
+ # Check that the z_stars are the same
621
+ solution1 = nx.DiGraph()
622
+ solution1.add_edges_from(solution1_edges)
623
+ solution2 = nx.DiGraph()
624
+ solution2.add_edges_from(solution2_edges)
625
+ assert nx.utils.edges_equal(z_star.edges, solution1.edges) or nx.utils.edges_equal(
626
+ z_star.edges, solution2.edges
627
+ )
628
+
629
+
630
+ def test_held_karp_ascent_fractional_asymmetric():
631
+ """
632
+ Tests the ascent method using a truly asymmetric graph with a fractional
633
+ solution for which the solution has been brute forced
634
+ """
635
+ import networkx.algorithms.approximation.traveling_salesman as tsp
636
+
637
+ np = pytest.importorskip("numpy")
638
+ pytest.importorskip("scipy")
639
+
640
+ G_array = np.array(
641
+ [
642
+ [0, 100, 150, 100000, 100000, 1],
643
+ [150, 0, 100, 100000, 1, 100000],
644
+ [100, 150, 0, 1, 100000, 100000],
645
+ [100000, 100000, 1, 0, 150, 100],
646
+ [100000, 2, 100000, 100, 0, 150],
647
+ [2, 100000, 100000, 150, 100, 0],
648
+ ]
649
+ )
650
+
651
+ solution_z_star = {
652
+ (0, 1): 5 / 12,
653
+ (0, 2): 5 / 12,
654
+ (0, 5): 5 / 6,
655
+ (1, 0): 5 / 12,
656
+ (1, 2): 5 / 12,
657
+ (1, 4): 5 / 6,
658
+ (2, 0): 5 / 12,
659
+ (2, 1): 5 / 12,
660
+ (2, 3): 5 / 6,
661
+ (3, 2): 5 / 6,
662
+ (3, 4): 5 / 12,
663
+ (3, 5): 5 / 12,
664
+ (4, 1): 5 / 6,
665
+ (4, 3): 5 / 12,
666
+ (4, 5): 5 / 12,
667
+ (5, 0): 5 / 6,
668
+ (5, 3): 5 / 12,
669
+ (5, 4): 5 / 12,
670
+ }
671
+
672
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
673
+ opt_hk, z_star = tsp.held_karp_ascent(G)
674
+
675
+ # Check that the optimal weights are the same
676
+ assert round(opt_hk, 2) == 304.00
677
+ # Check that the z_stars are the same
678
+ assert {key: round(z_star[key], 4) for key in z_star} == {
679
+ key: round(solution_z_star[key], 4) for key in solution_z_star
680
+ }
681
+
682
+
683
+ def test_spanning_tree_distribution():
684
+ """
685
+ Test that we can create an exponential distribution of spanning trees such
686
+ that the probability of each tree is proportional to the product of edge
687
+ weights.
688
+
689
+ Results of this test have been confirmed with hypothesis testing from the
690
+ created distribution.
691
+
692
+ This test uses the symmetric, fractional Held Karp solution.
693
+ """
694
+ import networkx.algorithms.approximation.traveling_salesman as tsp
695
+
696
+ pytest.importorskip("numpy")
697
+ pytest.importorskip("scipy")
698
+
699
+ z_star = {
700
+ (0, 1): 5 / 12,
701
+ (0, 2): 5 / 12,
702
+ (0, 5): 5 / 6,
703
+ (1, 0): 5 / 12,
704
+ (1, 2): 1 / 3,
705
+ (1, 4): 5 / 6,
706
+ (2, 0): 5 / 12,
707
+ (2, 1): 1 / 3,
708
+ (2, 3): 5 / 6,
709
+ (3, 2): 5 / 6,
710
+ (3, 4): 1 / 3,
711
+ (3, 5): 1 / 2,
712
+ (4, 1): 5 / 6,
713
+ (4, 3): 1 / 3,
714
+ (4, 5): 1 / 2,
715
+ (5, 0): 5 / 6,
716
+ (5, 3): 1 / 2,
717
+ (5, 4): 1 / 2,
718
+ }
719
+
720
+ solution_gamma = {
721
+ (0, 1): -0.6383,
722
+ (0, 2): -0.6827,
723
+ (0, 5): 0,
724
+ (1, 2): -1.0781,
725
+ (1, 4): 0,
726
+ (2, 3): 0,
727
+ (5, 3): -0.2820,
728
+ (5, 4): -0.3327,
729
+ (4, 3): -0.9927,
730
+ }
731
+
732
+ # The undirected support of z_star
733
+ G = nx.MultiGraph()
734
+ for u, v in z_star:
735
+ if (u, v) in G.edges or (v, u) in G.edges:
736
+ continue
737
+ G.add_edge(u, v)
738
+
739
+ gamma = tsp.spanning_tree_distribution(G, z_star)
740
+
741
+ assert {key: round(gamma[key], 4) for key in gamma} == solution_gamma
742
+
743
+
744
+ def test_asadpour_tsp():
745
+ """
746
+ Test the complete asadpour tsp algorithm with the fractional, symmetric
747
+ Held Karp solution. This test also uses an incomplete graph as input.
748
+ """
749
+ # This version of Figure 2 has all of the edge weights multiplied by 100
750
+ # and the 0 weight edges have a weight of 1.
751
+ pytest.importorskip("numpy")
752
+ pytest.importorskip("scipy")
753
+
754
+ edge_list = [
755
+ (0, 1, 100),
756
+ (0, 2, 100),
757
+ (0, 5, 1),
758
+ (1, 2, 100),
759
+ (1, 4, 1),
760
+ (2, 3, 1),
761
+ (3, 4, 100),
762
+ (3, 5, 100),
763
+ (4, 5, 100),
764
+ (1, 0, 100),
765
+ (2, 0, 100),
766
+ (5, 0, 1),
767
+ (2, 1, 100),
768
+ (4, 1, 1),
769
+ (3, 2, 1),
770
+ (4, 3, 100),
771
+ (5, 3, 100),
772
+ (5, 4, 100),
773
+ ]
774
+
775
+ G = nx.DiGraph()
776
+ G.add_weighted_edges_from(edge_list)
777
+
778
+ tour = nx_app.traveling_salesman_problem(
779
+ G, weight="weight", method=nx_app.asadpour_atsp, seed=19
780
+ )
781
+
782
+ # Check that the returned list is a valid tour. Because this is an
783
+ # incomplete graph, the conditions are not as strict. We need the tour to
784
+ #
785
+ # Start and end at the same node
786
+ # Pass through every vertex at least once
787
+ # Have a total cost at most ln(6) / ln(ln(6)) = 3.0723 times the optimal
788
+ #
789
+ # For the second condition it is possible to have the tour pass through the
790
+ # same vertex more then. Imagine that the tour on the complete version takes
791
+ # an edge not in the original graph. In the output this is substituted with
792
+ # the shortest path between those vertices, allowing vertices to appear more
793
+ # than once.
794
+ #
795
+ # Even though we are using a fixed seed, multiple tours have been known to
796
+ # be returned. The first two are from the original development of this test,
797
+ # and the third one from issue #5913 on GitHub. If other tours are returned,
798
+ # add it on the list of expected tours.
799
+ expected_tours = [
800
+ [1, 4, 5, 0, 2, 3, 2, 1],
801
+ [3, 2, 0, 1, 4, 5, 3],
802
+ [3, 2, 1, 0, 5, 4, 3],
803
+ ]
804
+
805
+ assert tour in expected_tours
806
+
807
+
808
+ def test_asadpour_real_world():
809
+ """
810
+ This test uses airline prices between the six largest cities in the US.
811
+
812
+ * New York City -> JFK
813
+ * Los Angeles -> LAX
814
+ * Chicago -> ORD
815
+ * Houston -> IAH
816
+ * Phoenix -> PHX
817
+ * Philadelphia -> PHL
818
+
819
+ Flight prices from August 2021 using Delta or American airlines to get
820
+ nonstop flight. The brute force solution found the optimal tour to cost $872
821
+
822
+ This test also uses the `source` keyword argument to ensure that the tour
823
+ always starts at city 0.
824
+ """
825
+ np = pytest.importorskip("numpy")
826
+ pytest.importorskip("scipy")
827
+
828
+ G_array = np.array(
829
+ [
830
+ # JFK LAX ORD IAH PHX PHL
831
+ [0, 243, 199, 208, 169, 183], # JFK
832
+ [277, 0, 217, 123, 127, 252], # LAX
833
+ [297, 197, 0, 197, 123, 177], # ORD
834
+ [303, 169, 197, 0, 117, 117], # IAH
835
+ [257, 127, 160, 117, 0, 319], # PHX
836
+ [183, 332, 217, 117, 319, 0], # PHL
837
+ ]
838
+ )
839
+
840
+ node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"]
841
+
842
+ expected_tours = [
843
+ ["JFK", "LAX", "PHX", "ORD", "IAH", "PHL", "JFK"],
844
+ ["JFK", "ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
845
+ ]
846
+
847
+ G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph)
848
+
849
+ tour = nx_app.traveling_salesman_problem(
850
+ G, weight="weight", method=nx_app.asadpour_atsp, seed=37, source="JFK"
851
+ )
852
+
853
+ assert tour in expected_tours
854
+
855
+
856
+ def test_asadpour_real_world_path():
857
+ """
858
+ This test uses airline prices between the six largest cities in the US. This
859
+ time using a path, not a cycle.
860
+
861
+ * New York City -> JFK
862
+ * Los Angeles -> LAX
863
+ * Chicago -> ORD
864
+ * Houston -> IAH
865
+ * Phoenix -> PHX
866
+ * Philadelphia -> PHL
867
+
868
+ Flight prices from August 2021 using Delta or American airlines to get
869
+ nonstop flight. The brute force solution found the optimal tour to cost $872
870
+ """
871
+ np = pytest.importorskip("numpy")
872
+ pytest.importorskip("scipy")
873
+
874
+ G_array = np.array(
875
+ [
876
+ # JFK LAX ORD IAH PHX PHL
877
+ [0, 243, 199, 208, 169, 183], # JFK
878
+ [277, 0, 217, 123, 127, 252], # LAX
879
+ [297, 197, 0, 197, 123, 177], # ORD
880
+ [303, 169, 197, 0, 117, 117], # IAH
881
+ [257, 127, 160, 117, 0, 319], # PHX
882
+ [183, 332, 217, 117, 319, 0], # PHL
883
+ ]
884
+ )
885
+
886
+ node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"]
887
+
888
+ expected_paths = [
889
+ ["ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
890
+ ["JFK", "PHL", "IAH", "ORD", "PHX", "LAX"],
891
+ ]
892
+
893
+ G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph)
894
+
895
+ path = nx_app.traveling_salesman_problem(
896
+ G, weight="weight", cycle=False, method=nx_app.asadpour_atsp, seed=56
897
+ )
898
+
899
+ assert path in expected_paths
900
+
901
+
902
+ def test_asadpour_disconnected_graph():
903
+ """
904
+ Test that the proper exception is raised when asadpour_atsp is given an
905
+ disconnected graph.
906
+ """
907
+
908
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
909
+ # have to set edge weights so that if the exception is not raised, the
910
+ # function will complete and we will fail the test
911
+ nx.set_edge_attributes(G, 1, "weight")
912
+ G.add_node(5)
913
+
914
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
915
+
916
+
917
+ def test_asadpour_incomplete_graph():
918
+ """
919
+ Test that the proper exception is raised when asadpour_atsp is given an
920
+ incomplete graph
921
+ """
922
+
923
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
924
+ # have to set edge weights so that if the exception is not raised, the
925
+ # function will complete and we will fail the test
926
+ nx.set_edge_attributes(G, 1, "weight")
927
+ G.remove_edge(0, 1)
928
+
929
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
930
+
931
+
932
+ def test_asadpour_empty_graph():
933
+ """
934
+ Test the asadpour_atsp function with an empty graph
935
+ """
936
+ G = nx.DiGraph()
937
+
938
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
939
+
940
+
941
+ def test_asadpour_small_graphs():
942
+ # 1 node
943
+ G = nx.path_graph(1, create_using=nx.DiGraph)
944
+ with pytest.raises(nx.NetworkXError, match="at least two nodes"):
945
+ nx_app.asadpour_atsp(G)
946
+
947
+ # 2 nodes
948
+ G = nx.DiGraph()
949
+ G.add_weighted_edges_from([(0, 1, 7), (1, 0, 8)])
950
+ assert nx_app.asadpour_atsp(G) in [[0, 1], [1, 0]]
951
+ assert nx_app.asadpour_atsp(G, source=1) == [1, 0]
952
+ assert nx_app.asadpour_atsp(G, source=0) == [0, 1]
953
+
954
+
955
+ @pytest.mark.slow
956
+ def test_asadpour_integral_held_karp():
957
+ """
958
+ This test uses an integral held karp solution and the held karp function
959
+ will return a graph rather than a dict, bypassing most of the asadpour
960
+ algorithm.
961
+
962
+ At first glance, this test probably doesn't look like it ensures that we
963
+ skip the rest of the asadpour algorithm, but it does. We are not fixing a
964
+ see for the random number generator, so if we sample any spanning trees
965
+ the approximation would be different basically every time this test is
966
+ executed but it is not since held karp is deterministic and we do not
967
+ reach the portion of the code with the dependence on random numbers.
968
+ """
969
+ np = pytest.importorskip("numpy")
970
+
971
+ G_array = np.array(
972
+ [
973
+ [0, 26, 63, 59, 69, 31, 41],
974
+ [62, 0, 91, 53, 75, 87, 47],
975
+ [47, 82, 0, 90, 15, 9, 18],
976
+ [68, 19, 5, 0, 58, 34, 93],
977
+ [11, 58, 53, 55, 0, 61, 79],
978
+ [88, 75, 13, 76, 98, 0, 40],
979
+ [41, 61, 55, 88, 46, 45, 0],
980
+ ]
981
+ )
982
+
983
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
984
+
985
+ for _ in range(2):
986
+ tour = nx_app.traveling_salesman_problem(G, method=nx_app.asadpour_atsp)
987
+
988
+ assert [1, 3, 2, 5, 2, 6, 4, 0, 1] == tour
989
+
990
+
991
+ def test_directed_tsp_impossible():
992
+ """
993
+ Test the asadpour algorithm with a graph without a hamiltonian circuit
994
+ """
995
+ pytest.importorskip("numpy")
996
+
997
+ # In this graph, once we leave node 0 we cannot return
998
+ edges = [
999
+ (0, 1, 10),
1000
+ (0, 2, 11),
1001
+ (0, 3, 12),
1002
+ (1, 2, 4),
1003
+ (1, 3, 6),
1004
+ (2, 1, 3),
1005
+ (2, 3, 2),
1006
+ (3, 1, 5),
1007
+ (3, 2, 1),
1008
+ ]
1009
+
1010
+ G = nx.DiGraph()
1011
+ G.add_weighted_edges_from(edges)
1012
+
1013
+ pytest.raises(nx.NetworkXError, nx_app.traveling_salesman_problem, G)
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ steps = []
153
+
154
+ while elim_node is not None:
155
+ steps.append(elim_node)
156
+ nbrs = graph[elim_node]
157
+
158
+ for u, v in itertools.permutations(nbrs, 2):
159
+ if v not in graph[u]:
160
+ graph[u].add(v)
161
+
162
+ for u in graph:
163
+ if elim_node in graph[u]:
164
+ graph[u].remove(elim_node)
165
+
166
+ del graph[elim_node]
167
+ elim_node = deg_heuristic.best_node(graph)
168
+
169
+ # check only the first 5 elements for equality
170
+ assert steps[:5] == [0, 1, 2, 3, 4]
171
+
172
+
173
+ class TestTreewidthMinFillIn:
174
+ """Unit tests for the treewidth_min_fill_in function."""
175
+
176
+ @classmethod
177
+ def setup_class(cls):
178
+ """Setup for different kinds of trees"""
179
+ cls.complete = nx.Graph()
180
+ cls.complete.add_edge(1, 2)
181
+ cls.complete.add_edge(2, 3)
182
+ cls.complete.add_edge(1, 3)
183
+
184
+ cls.small_tree = nx.Graph()
185
+ cls.small_tree.add_edge(1, 2)
186
+ cls.small_tree.add_edge(2, 3)
187
+ cls.small_tree.add_edge(3, 4)
188
+ cls.small_tree.add_edge(1, 4)
189
+ cls.small_tree.add_edge(2, 4)
190
+ cls.small_tree.add_edge(4, 5)
191
+ cls.small_tree.add_edge(5, 6)
192
+ cls.small_tree.add_edge(5, 7)
193
+ cls.small_tree.add_edge(6, 7)
194
+
195
+ cls.deterministic_graph = nx.Graph()
196
+ cls.deterministic_graph.add_edge(1, 2)
197
+ cls.deterministic_graph.add_edge(1, 3)
198
+ cls.deterministic_graph.add_edge(3, 4)
199
+ cls.deterministic_graph.add_edge(2, 4)
200
+ cls.deterministic_graph.add_edge(3, 5)
201
+ cls.deterministic_graph.add_edge(4, 5)
202
+ cls.deterministic_graph.add_edge(3, 6)
203
+ cls.deterministic_graph.add_edge(5, 6)
204
+
205
+ def test_petersen_graph(self):
206
+ """Test Petersen graph tree decomposition result"""
207
+ G = nx.petersen_graph()
208
+ _, decomp = treewidth_min_fill_in(G)
209
+ is_tree_decomp(G, decomp)
210
+
211
+ def test_small_tree_treewidth(self):
212
+ """Test if the computed treewidth of the known self.small_tree is 2"""
213
+ G = self.small_tree
214
+ # the order of removal should be [1,2,4]3[5,6,7]
215
+ # (with [] denoting any order of the containing nodes)
216
+ # resulting in treewidth 2 for the heuristic
217
+ treewidth, _ = treewidth_min_fill_in(G)
218
+ assert treewidth == 2
219
+
220
+ def test_heuristic_abort(self):
221
+ """Test if min_fill_in returns None for fully connected graph"""
222
+ graph = {}
223
+ for u in self.complete:
224
+ graph[u] = set()
225
+ for v in self.complete[u]:
226
+ if u != v: # ignore self-loop
227
+ graph[u].add(v)
228
+ next_node = min_fill_in_heuristic(graph)
229
+ if next_node is None:
230
+ pass
231
+ else:
232
+ assert False
233
+
234
+ def test_empty_graph(self):
235
+ """Test empty graph"""
236
+ G = nx.Graph()
237
+ _, _ = treewidth_min_fill_in(G)
238
+
239
+ def test_two_component_graph(self):
240
+ G = nx.Graph()
241
+ G.add_node(1)
242
+ G.add_node(2)
243
+ treewidth, _ = treewidth_min_fill_in(G)
244
+ assert treewidth == 0
245
+
246
+ def test_not_sortable_nodes(self):
247
+ G = nx.Graph([(0, "a")])
248
+ treewidth_min_fill_in(G)
249
+
250
+ def test_heuristic_first_steps(self):
251
+ """Test first steps of min_fill_in heuristic"""
252
+ graph = {
253
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
254
+ }
255
+ elim_node = min_fill_in_heuristic(graph)
256
+ steps = []
257
+
258
+ while elim_node is not None:
259
+ steps.append(elim_node)
260
+ nbrs = graph[elim_node]
261
+
262
+ for u, v in itertools.permutations(nbrs, 2):
263
+ if v not in graph[u]:
264
+ graph[u].add(v)
265
+
266
+ for u in graph:
267
+ if elim_node in graph[u]:
268
+ graph[u].remove(elim_node)
269
+
270
+ del graph[elim_node]
271
+ elim_node = min_fill_in_heuristic(graph)
272
+
273
+ # check only the first 2 elements for equality
274
+ assert steps[:2] == [6, 5]
archive/Axiovorax/.venv/Lib/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)
archive/Axiovorax/.venv/Lib/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
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/assortativity/connectivity.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["average_degree_connectivity"]
6
+
7
+
8
+ @nx._dispatchable(edge_attrs="weight")
9
+ def average_degree_connectivity(
10
+ G, source="in+out", target="in+out", nodes=None, weight=None
11
+ ):
12
+ r"""Compute the average degree connectivity of graph.
13
+
14
+ The average degree connectivity is the average nearest neighbor degree of
15
+ nodes with degree k. For weighted graphs, an analogous measure can
16
+ be computed using the weighted average neighbors degree defined in
17
+ [1]_, for a node `i`, as
18
+
19
+ .. math::
20
+
21
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
22
+
23
+ where `s_i` is the weighted degree of node `i`,
24
+ `w_{ij}` is the weight of the edge that links `i` and `j`,
25
+ and `N(i)` are the neighbors of node `i`.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : "in"|"out"|"in+out" (default:"in+out")
32
+ Directed graphs only. Use "in"- or "out"-degree for source node.
33
+
34
+ target : "in"|"out"|"in+out" (default:"in+out"
35
+ Directed graphs only. Use "in"- or "out"-degree for target node.
36
+
37
+ nodes : list or iterable (optional)
38
+ Compute neighbor connectivity for these nodes. The default is all
39
+ nodes.
40
+
41
+ weight : string or None, optional (default=None)
42
+ The edge attribute that holds the numerical value used as a weight.
43
+ If None, then each edge has weight 1.
44
+
45
+ Returns
46
+ -------
47
+ d : dict
48
+ A dictionary keyed by degree k with the value of average connectivity.
49
+
50
+ Raises
51
+ ------
52
+ NetworkXError
53
+ If either `source` or `target` are not one of 'in',
54
+ 'out', or 'in+out'.
55
+ If either `source` or `target` is passed for an undirected graph.
56
+
57
+ Examples
58
+ --------
59
+ >>> G = nx.path_graph(4)
60
+ >>> G.edges[1, 2]["weight"] = 3
61
+ >>> nx.average_degree_connectivity(G)
62
+ {1: 2.0, 2: 1.5}
63
+ >>> nx.average_degree_connectivity(G, weight="weight")
64
+ {1: 2.0, 2: 1.75}
65
+
66
+ See Also
67
+ --------
68
+ average_neighbor_degree
69
+
70
+ References
71
+ ----------
72
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
73
+ "The architecture of complex weighted networks".
74
+ PNAS 101 (11): 3747–3752 (2004).
75
+ """
76
+ # First, determine the type of neighbors and the type of degree to use.
77
+ if G.is_directed():
78
+ if source not in ("in", "out", "in+out"):
79
+ raise nx.NetworkXError('source must be one of "in", "out", or "in+out"')
80
+ if target not in ("in", "out", "in+out"):
81
+ raise nx.NetworkXError('target must be one of "in", "out", or "in+out"')
82
+ direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree}
83
+ neighbor_funcs = {
84
+ "out": G.successors,
85
+ "in": G.predecessors,
86
+ "in+out": G.neighbors,
87
+ }
88
+ source_degree = direction[source]
89
+ target_degree = direction[target]
90
+ neighbors = neighbor_funcs[source]
91
+ # `reverse` indicates whether to look at the in-edge when
92
+ # computing the weight of an edge.
93
+ reverse = source == "in"
94
+ else:
95
+ if source != "in+out" or target != "in+out":
96
+ raise nx.NetworkXError(
97
+ f"source and target arguments are only supported for directed graphs"
98
+ )
99
+ source_degree = G.degree
100
+ target_degree = G.degree
101
+ neighbors = G.neighbors
102
+ reverse = False
103
+ dsum = defaultdict(int)
104
+ dnorm = defaultdict(int)
105
+ # Check if `source_nodes` is actually a single node in the graph.
106
+ source_nodes = source_degree(nodes)
107
+ if nodes in G:
108
+ source_nodes = [(nodes, source_degree(nodes))]
109
+ for n, k in source_nodes:
110
+ nbrdeg = target_degree(neighbors(n))
111
+ if weight is None:
112
+ s = sum(d for n, d in nbrdeg)
113
+ else: # weight nbr degree by weight of (n,nbr) edge
114
+ if reverse:
115
+ s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg)
116
+ else:
117
+ s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg)
118
+ dnorm[k] += source_degree(n, weight=weight)
119
+ dsum[k] += s
120
+
121
+ # normalize
122
+ return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/assortativity/correlation.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Node assortativity coefficients and correlation measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.assortativity.mixing import (
5
+ attribute_mixing_matrix,
6
+ degree_mixing_matrix,
7
+ )
8
+ from networkx.algorithms.assortativity.pairs import node_degree_xy
9
+
10
+ __all__ = [
11
+ "degree_pearson_correlation_coefficient",
12
+ "degree_assortativity_coefficient",
13
+ "attribute_assortativity_coefficient",
14
+ "numeric_assortativity_coefficient",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable(edge_attrs="weight")
19
+ def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
20
+ """Compute degree assortativity of graph.
21
+
22
+ Assortativity measures the similarity of connections
23
+ in the graph with respect to the node degree.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ x: string ('in','out')
30
+ The degree type for source node (directed graphs only).
31
+
32
+ y: string ('in','out')
33
+ The degree type for target node (directed graphs only).
34
+
35
+ weight: string or None, optional (default=None)
36
+ The edge attribute that holds the numerical value used
37
+ as a weight. If None, then each edge has weight 1.
38
+ The degree is the sum of the edge weights adjacent to the node.
39
+
40
+ nodes: list or iterable (optional)
41
+ Compute degree assortativity only for nodes in container.
42
+ The default is all nodes.
43
+
44
+ Returns
45
+ -------
46
+ r : float
47
+ Assortativity of graph by degree.
48
+
49
+ Examples
50
+ --------
51
+ >>> G = nx.path_graph(4)
52
+ >>> r = nx.degree_assortativity_coefficient(G)
53
+ >>> print(f"{r:3.1f}")
54
+ -0.5
55
+
56
+ See Also
57
+ --------
58
+ attribute_assortativity_coefficient
59
+ numeric_assortativity_coefficient
60
+ degree_mixing_dict
61
+ degree_mixing_matrix
62
+
63
+ Notes
64
+ -----
65
+ This computes Eq. (21) in Ref. [1]_ , where e is the joint
66
+ probability distribution (mixing matrix) of the degrees. If G is
67
+ directed than the matrix e is the joint probability of the
68
+ user-specified degree type for the source and target.
69
+
70
+ References
71
+ ----------
72
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
73
+ Physical Review E, 67 026126, 2003
74
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
75
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
76
+ """
77
+ if nodes is None:
78
+ nodes = G.nodes
79
+
80
+ degrees = None
81
+
82
+ if G.is_directed():
83
+ indeg = (
84
+ {d for _, d in G.in_degree(nodes, weight=weight)}
85
+ if "in" in (x, y)
86
+ else set()
87
+ )
88
+ outdeg = (
89
+ {d for _, d in G.out_degree(nodes, weight=weight)}
90
+ if "out" in (x, y)
91
+ else set()
92
+ )
93
+ degrees = set.union(indeg, outdeg)
94
+ else:
95
+ degrees = {d for _, d in G.degree(nodes, weight=weight)}
96
+
97
+ mapping = {d: i for i, d in enumerate(degrees)}
98
+ M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
99
+
100
+ return _numeric_ac(M, mapping=mapping)
101
+
102
+
103
+ @nx._dispatchable(edge_attrs="weight")
104
+ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
105
+ """Compute degree assortativity of graph.
106
+
107
+ Assortativity measures the similarity of connections
108
+ in the graph with respect to the node degree.
109
+
110
+ This is the same as degree_assortativity_coefficient but uses the
111
+ potentially faster scipy.stats.pearsonr function.
112
+
113
+ Parameters
114
+ ----------
115
+ G : NetworkX graph
116
+
117
+ x: string ('in','out')
118
+ The degree type for source node (directed graphs only).
119
+
120
+ y: string ('in','out')
121
+ The degree type for target node (directed graphs only).
122
+
123
+ weight: string or None, optional (default=None)
124
+ The edge attribute that holds the numerical value used
125
+ as a weight. If None, then each edge has weight 1.
126
+ The degree is the sum of the edge weights adjacent to the node.
127
+
128
+ nodes: list or iterable (optional)
129
+ Compute pearson correlation of degrees only for specified nodes.
130
+ The default is all nodes.
131
+
132
+ Returns
133
+ -------
134
+ r : float
135
+ Assortativity of graph by degree.
136
+
137
+ Examples
138
+ --------
139
+ >>> G = nx.path_graph(4)
140
+ >>> r = nx.degree_pearson_correlation_coefficient(G)
141
+ >>> print(f"{r:3.1f}")
142
+ -0.5
143
+
144
+ Notes
145
+ -----
146
+ This calls scipy.stats.pearsonr.
147
+
148
+ References
149
+ ----------
150
+ .. [1] M. E. J. Newman, Mixing patterns in networks
151
+ Physical Review E, 67 026126, 2003
152
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
153
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
154
+ """
155
+ import scipy as sp
156
+
157
+ xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
158
+ x, y = zip(*xy)
159
+ return float(sp.stats.pearsonr(x, y)[0])
160
+
161
+
162
+ @nx._dispatchable(node_attrs="attribute")
163
+ def attribute_assortativity_coefficient(G, attribute, nodes=None):
164
+ """Compute assortativity for node attributes.
165
+
166
+ Assortativity measures the similarity of connections
167
+ in the graph with respect to the given attribute.
168
+
169
+ Parameters
170
+ ----------
171
+ G : NetworkX graph
172
+
173
+ attribute : string
174
+ Node attribute key
175
+
176
+ nodes: list or iterable (optional)
177
+ Compute attribute assortativity for nodes in container.
178
+ The default is all nodes.
179
+
180
+ Returns
181
+ -------
182
+ r: float
183
+ Assortativity of graph for given attribute
184
+
185
+ Examples
186
+ --------
187
+ >>> G = nx.Graph()
188
+ >>> G.add_nodes_from([0, 1], color="red")
189
+ >>> G.add_nodes_from([2, 3], color="blue")
190
+ >>> G.add_edges_from([(0, 1), (2, 3)])
191
+ >>> print(nx.attribute_assortativity_coefficient(G, "color"))
192
+ 1.0
193
+
194
+ Notes
195
+ -----
196
+ This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
197
+ where M is the joint probability distribution (mixing matrix)
198
+ of the specified attribute.
199
+
200
+ References
201
+ ----------
202
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
203
+ Physical Review E, 67 026126, 2003
204
+ """
205
+ M = attribute_mixing_matrix(G, attribute, nodes)
206
+ return attribute_ac(M)
207
+
208
+
209
+ @nx._dispatchable(node_attrs="attribute")
210
+ def numeric_assortativity_coefficient(G, attribute, nodes=None):
211
+ """Compute assortativity for numerical node attributes.
212
+
213
+ Assortativity measures the similarity of connections
214
+ in the graph with respect to the given numeric attribute.
215
+
216
+ Parameters
217
+ ----------
218
+ G : NetworkX graph
219
+
220
+ attribute : string
221
+ Node attribute key.
222
+
223
+ nodes: list or iterable (optional)
224
+ Compute numeric assortativity only for attributes of nodes in
225
+ container. The default is all nodes.
226
+
227
+ Returns
228
+ -------
229
+ r: float
230
+ Assortativity of graph for given attribute
231
+
232
+ Examples
233
+ --------
234
+ >>> G = nx.Graph()
235
+ >>> G.add_nodes_from([0, 1], size=2)
236
+ >>> G.add_nodes_from([2, 3], size=3)
237
+ >>> G.add_edges_from([(0, 1), (2, 3)])
238
+ >>> print(nx.numeric_assortativity_coefficient(G, "size"))
239
+ 1.0
240
+
241
+ Notes
242
+ -----
243
+ This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
244
+ coefficient of the specified (scalar valued) attribute across edges.
245
+
246
+ References
247
+ ----------
248
+ .. [1] M. E. J. Newman, Mixing patterns in networks
249
+ Physical Review E, 67 026126, 2003
250
+ """
251
+ if nodes is None:
252
+ nodes = G.nodes
253
+ vals = {G.nodes[n][attribute] for n in nodes}
254
+ mapping = {d: i for i, d in enumerate(vals)}
255
+ M = attribute_mixing_matrix(G, attribute, nodes, mapping)
256
+ return _numeric_ac(M, mapping)
257
+
258
+
259
+ def attribute_ac(M):
260
+ """Compute assortativity for attribute matrix M.
261
+
262
+ Parameters
263
+ ----------
264
+ M : numpy.ndarray
265
+ 2D ndarray representing the attribute mixing matrix.
266
+
267
+ Notes
268
+ -----
269
+ This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
270
+ where e is the joint probability distribution (mixing matrix)
271
+ of the specified attribute.
272
+
273
+ References
274
+ ----------
275
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
276
+ Physical Review E, 67 026126, 2003
277
+ """
278
+ if M.sum() != 1.0:
279
+ M = M / M.sum()
280
+ s = (M @ M).sum()
281
+ t = M.trace()
282
+ r = (t - s) / (1 - s)
283
+ return float(r)
284
+
285
+
286
+ def _numeric_ac(M, mapping):
287
+ # M is a 2D numpy array
288
+ # numeric assortativity coefficient, pearsonr
289
+ import numpy as np
290
+
291
+ if M.sum() != 1.0:
292
+ M = M / M.sum()
293
+ x = np.array(list(mapping.keys()))
294
+ y = x # x and y have the same support
295
+ idx = list(mapping.values())
296
+ a = M.sum(axis=0)
297
+ b = M.sum(axis=1)
298
+ vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
299
+ varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
300
+ xy = np.outer(x, y)
301
+ ab = np.outer(a[idx], b[idx])
302
+ return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))
archive/Axiovorax/.venv/Lib/site-packages/networkx/algorithms/assortativity/mixing.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mixing matrices for node attributes and degree.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xy
7
+ from networkx.utils import dict_to_numpy_array
8
+
9
+ __all__ = [
10
+ "attribute_mixing_matrix",
11
+ "attribute_mixing_dict",
12
+ "degree_mixing_matrix",
13
+ "degree_mixing_dict",
14
+ "mixing_dict",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable(node_attrs="attribute")
19
+ def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
20
+ """Returns dictionary representation of mixing matrix for attribute.
21
+
22
+ Parameters
23
+ ----------
24
+ G : graph
25
+ NetworkX graph object.
26
+
27
+ attribute : string
28
+ Node attribute key.
29
+
30
+ nodes: list or iterable (optional)
31
+ Unse nodes in container to build the dict. The default is all nodes.
32
+
33
+ normalized : bool (default=False)
34
+ Return counts if False or probabilities if True.
35
+
36
+ Examples
37
+ --------
38
+ >>> G = nx.Graph()
39
+ >>> G.add_nodes_from([0, 1], color="red")
40
+ >>> G.add_nodes_from([2, 3], color="blue")
41
+ >>> G.add_edge(1, 3)
42
+ >>> d = nx.attribute_mixing_dict(G, "color")
43
+ >>> print(d["red"]["blue"])
44
+ 1
45
+ >>> print(d["blue"]["red"]) # d symmetric for undirected graphs
46
+ 1
47
+
48
+ Returns
49
+ -------
50
+ d : dictionary
51
+ Counts or joint probability of occurrence of attribute pairs.
52
+ """
53
+ xy_iter = node_attribute_xy(G, attribute, nodes)
54
+ return mixing_dict(xy_iter, normalized=normalized)
55
+
56
+
57
+ @nx._dispatchable(node_attrs="attribute")
58
+ def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True):
59
+ """Returns mixing matrix for attribute.
60
+
61
+ Parameters
62
+ ----------
63
+ G : graph
64
+ NetworkX graph object.
65
+
66
+ attribute : string
67
+ Node attribute key.
68
+
69
+ nodes: list or iterable (optional)
70
+ Use only nodes in container to build the matrix. The default is
71
+ all nodes.
72
+
73
+ mapping : dictionary, optional
74
+ Mapping from node attribute to integer index in matrix.
75
+ If not specified, an arbitrary ordering will be used.
76
+
77
+ normalized : bool (default=True)
78
+ Return counts if False or probabilities if True.
79
+
80
+ Returns
81
+ -------
82
+ m: numpy array
83
+ Counts or joint probability of occurrence of attribute pairs.
84
+
85
+ Notes
86
+ -----
87
+ If each node has a unique attribute value, the unnormalized mixing matrix
88
+ will be equal to the adjacency matrix. To get a denser mixing matrix,
89
+ the rounding can be performed to form groups of nodes with equal values.
90
+ For example, the exact height of persons in cm (180.79155222, 163.9080892,
91
+ 163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
92
+ 163, 168, 168, ...).
93
+
94
+ Definitions of attribute mixing matrix vary on whether the matrix
95
+ should include rows for attribute values that don't arise. Here we
96
+ do not include such empty-rows. But you can force them to appear
97
+ by inputting a `mapping` that includes those values.
98
+
99
+ Examples
100
+ --------
101
+ >>> G = nx.path_graph(3)
102
+ >>> gender = {0: "male", 1: "female", 2: "female"}
103
+ >>> nx.set_node_attributes(G, gender, "gender")
104
+ >>> mapping = {"male": 0, "female": 1}
105
+ >>> mix_mat = nx.attribute_mixing_matrix(G, "gender", mapping=mapping)
106
+ >>> mix_mat
107
+ array([[0. , 0.25],
108
+ [0.25, 0.5 ]])
109
+ """
110
+ d = attribute_mixing_dict(G, attribute, nodes)
111
+ a = dict_to_numpy_array(d, mapping=mapping)
112
+ if normalized:
113
+ a = a / a.sum()
114
+ return a
115
+
116
+
117
+ @nx._dispatchable(edge_attrs="weight")
118
+ def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False):
119
+ """Returns dictionary representation of mixing matrix for degree.
120
+
121
+ Parameters
122
+ ----------
123
+ G : graph
124
+ NetworkX graph object.
125
+
126
+ x: string ('in','out')
127
+ The degree type for source node (directed graphs only).
128
+
129
+ y: string ('in','out')
130
+ The degree type for target node (directed graphs only).
131
+
132
+ weight: string or None, optional (default=None)
133
+ The edge attribute that holds the numerical value used
134
+ as a weight. If None, then each edge has weight 1.
135
+ The degree is the sum of the edge weights adjacent to the node.
136
+
137
+ normalized : bool (default=False)
138
+ Return counts if False or probabilities if True.
139
+
140
+ Returns
141
+ -------
142
+ d: dictionary
143
+ Counts or joint probability of occurrence of degree pairs.
144
+ """
145
+ xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
146
+ return mixing_dict(xy_iter, normalized=normalized)
147
+
148
+
149
+ @nx._dispatchable(edge_attrs="weight")
150
+ def degree_mixing_matrix(
151
+ G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None
152
+ ):
153
+ """Returns mixing matrix for attribute.
154
+
155
+ Parameters
156
+ ----------
157
+ G : graph
158
+ NetworkX graph object.
159
+
160
+ x: string ('in','out')
161
+ The degree type for source node (directed graphs only).
162
+
163
+ y: string ('in','out')
164
+ The degree type for target node (directed graphs only).
165
+
166
+ nodes: list or iterable (optional)
167
+ Build the matrix using only nodes in container.
168
+ The default is all nodes.
169
+
170
+ weight: string or None, optional (default=None)
171
+ The edge attribute that holds the numerical value used
172
+ as a weight. If None, then each edge has weight 1.
173
+ The degree is the sum of the edge weights adjacent to the node.
174
+
175
+ normalized : bool (default=True)
176
+ Return counts if False or probabilities if True.
177
+
178
+ mapping : dictionary, optional
179
+ Mapping from node degree to integer index in matrix.
180
+ If not specified, an arbitrary ordering will be used.
181
+
182
+ Returns
183
+ -------
184
+ m: numpy array
185
+ Counts, or joint probability, of occurrence of node degree.
186
+
187
+ Notes
188
+ -----
189
+ Definitions of degree mixing matrix vary on whether the matrix
190
+ should include rows for degree values that don't arise. Here we
191
+ do not include such empty-rows. But you can force them to appear
192
+ by inputting a `mapping` that includes those values. See examples.
193
+
194
+ Examples
195
+ --------
196
+ >>> G = nx.star_graph(3)
197
+ >>> mix_mat = nx.degree_mixing_matrix(G)
198
+ >>> mix_mat
199
+ array([[0. , 0.5],
200
+ [0.5, 0. ]])
201
+
202
+ If you want every possible degree to appear as a row, even if no nodes
203
+ have that degree, use `mapping` as follows,
204
+
205
+ >>> max_degree = max(deg for n, deg in G.degree)
206
+ >>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping
207
+ >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping)
208
+ >>> mix_mat
209
+ array([[0. , 0. , 0. , 0. ],
210
+ [0. , 0. , 0. , 0.5],
211
+ [0. , 0. , 0. , 0. ],
212
+ [0. , 0.5, 0. , 0. ]])
213
+ """
214
+ d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
215
+ a = dict_to_numpy_array(d, mapping=mapping)
216
+ if normalized:
217
+ a = a / a.sum()
218
+ return a
219
+
220
+
221
+ def mixing_dict(xy, normalized=False):
222
+ """Returns a dictionary representation of mixing matrix.
223
+
224
+ Parameters
225
+ ----------
226
+ xy : list or container of two-tuples
227
+ Pairs of (x,y) items.
228
+
229
+ attribute : string
230
+ Node attribute key
231
+
232
+ normalized : bool (default=False)
233
+ Return counts if False or probabilities if True.
234
+
235
+ Returns
236
+ -------
237
+ d: dictionary
238
+ Counts or Joint probability of occurrence of values in xy.
239
+ """
240
+ d = {}
241
+ psum = 0.0
242
+ for x, y in xy:
243
+ if x not in d:
244
+ d[x] = {}
245
+ if y not in d:
246
+ d[y] = {}
247
+ v = d[x].get(y, 0)
248
+ d[x][y] = v + 1
249
+ psum += 1
250
+
251
+ if normalized:
252
+ for _, jdict in d.items():
253
+ for j in jdict:
254
+ jdict[j] /= psum
255
+ return d