applied-ai-018 commited on
Commit
885bfcf
·
verified ·
1 Parent(s): 0eb9aab

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_current_flow_betweenness_centrality_subset.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_current_flow_closeness.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_percolation_centrality.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_subgraph.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_closeness_centrality.py +306 -0
  6. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py +147 -0
  7. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_harmonic_centrality.py +115 -0
  8. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_katz_centrality.py +345 -0
  9. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_percolation_centrality.py +87 -0
  10. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_trophic.py +302 -0
  11. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__init__.py +0 -0
  12. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_communicability.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_covering.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_d_separation.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_distance_measures.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dominating.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_euler.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_hierarchy.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_hybrid.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_isolate.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_link_prediction.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_node_classification.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_reciprocity.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_smallworld.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_swap.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_wiener.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py +23 -0
  28. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py +154 -0
  29. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py +144 -0
  30. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py +81 -0
  31. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_chains.py +140 -0
  32. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py +129 -0
  33. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py +80 -0
  34. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_core.py +266 -0
  35. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_covering.py +85 -0
  36. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py +172 -0
  37. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_cycles.py +974 -0
  38. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_d_separation.py +348 -0
  39. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_dag.py +777 -0
  40. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_distance_measures.py +756 -0
  41. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominance.py +285 -0
  42. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py +46 -0
  43. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_efficiency.py +58 -0
  44. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_euler.py +314 -0
  45. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_graph_hashing.py +686 -0
  46. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_graphical.py +163 -0
  47. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_hierarchy.py +39 -0
  48. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_isolate.py +26 -0
  49. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_link_prediction.py +586 -0
  50. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_lowest_common_ancestors.py +427 -0
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_current_flow_betweenness_centrality_subset.cpython-310.pyc ADDED
Binary file (4.37 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_current_flow_closeness.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_percolation_centrality.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_subgraph.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_closeness_centrality.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for closeness centrality.
3
+ """
4
+ import pytest
5
+
6
+ import networkx as nx
7
+
8
+
9
+ class TestClosenessCentrality:
10
+ @classmethod
11
+ def setup_class(cls):
12
+ cls.K = nx.krackhardt_kite_graph()
13
+ cls.P3 = nx.path_graph(3)
14
+ cls.P4 = nx.path_graph(4)
15
+ cls.K5 = nx.complete_graph(5)
16
+
17
+ cls.C4 = nx.cycle_graph(4)
18
+ cls.T = nx.balanced_tree(r=2, h=2)
19
+ cls.Gb = nx.Graph()
20
+ cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
21
+
22
+ F = nx.florentine_families_graph()
23
+ cls.F = F
24
+
25
+ cls.LM = nx.les_miserables_graph()
26
+
27
+ # Create random undirected, unweighted graph for testing incremental version
28
+ cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123)
29
+ cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G)
30
+
31
+ def test_wf_improved(self):
32
+ G = nx.union(self.P4, nx.path_graph([4, 5, 6]))
33
+ c = nx.closeness_centrality(G)
34
+ cwf = nx.closeness_centrality(G, wf_improved=False)
35
+ res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222}
36
+ wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667}
37
+ for n in G:
38
+ assert c[n] == pytest.approx(res[n], abs=1e-3)
39
+ assert cwf[n] == pytest.approx(wf_res[n], abs=1e-3)
40
+
41
+ def test_digraph(self):
42
+ G = nx.path_graph(3, create_using=nx.DiGraph())
43
+ c = nx.closeness_centrality(G)
44
+ cr = nx.closeness_centrality(G.reverse())
45
+ d = {0: 0.0, 1: 0.500, 2: 0.667}
46
+ dr = {0: 0.667, 1: 0.500, 2: 0.0}
47
+ for n in sorted(self.P3):
48
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
49
+ assert cr[n] == pytest.approx(dr[n], abs=1e-3)
50
+
51
+ def test_k5_closeness(self):
52
+ c = nx.closeness_centrality(self.K5)
53
+ d = {0: 1.000, 1: 1.000, 2: 1.000, 3: 1.000, 4: 1.000}
54
+ for n in sorted(self.K5):
55
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
56
+
57
+ def test_p3_closeness(self):
58
+ c = nx.closeness_centrality(self.P3)
59
+ d = {0: 0.667, 1: 1.000, 2: 0.667}
60
+ for n in sorted(self.P3):
61
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
62
+
63
+ def test_krackhardt_closeness(self):
64
+ c = nx.closeness_centrality(self.K)
65
+ d = {
66
+ 0: 0.529,
67
+ 1: 0.529,
68
+ 2: 0.500,
69
+ 3: 0.600,
70
+ 4: 0.500,
71
+ 5: 0.643,
72
+ 6: 0.643,
73
+ 7: 0.600,
74
+ 8: 0.429,
75
+ 9: 0.310,
76
+ }
77
+ for n in sorted(self.K):
78
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
79
+
80
+ def test_florentine_families_closeness(self):
81
+ c = nx.closeness_centrality(self.F)
82
+ d = {
83
+ "Acciaiuoli": 0.368,
84
+ "Albizzi": 0.483,
85
+ "Barbadori": 0.4375,
86
+ "Bischeri": 0.400,
87
+ "Castellani": 0.389,
88
+ "Ginori": 0.333,
89
+ "Guadagni": 0.467,
90
+ "Lamberteschi": 0.326,
91
+ "Medici": 0.560,
92
+ "Pazzi": 0.286,
93
+ "Peruzzi": 0.368,
94
+ "Ridolfi": 0.500,
95
+ "Salviati": 0.389,
96
+ "Strozzi": 0.4375,
97
+ "Tornabuoni": 0.483,
98
+ }
99
+ for n in sorted(self.F):
100
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
101
+
102
+ def test_les_miserables_closeness(self):
103
+ c = nx.closeness_centrality(self.LM)
104
+ d = {
105
+ "Napoleon": 0.302,
106
+ "Myriel": 0.429,
107
+ "MlleBaptistine": 0.413,
108
+ "MmeMagloire": 0.413,
109
+ "CountessDeLo": 0.302,
110
+ "Geborand": 0.302,
111
+ "Champtercier": 0.302,
112
+ "Cravatte": 0.302,
113
+ "Count": 0.302,
114
+ "OldMan": 0.302,
115
+ "Valjean": 0.644,
116
+ "Labarre": 0.394,
117
+ "Marguerite": 0.413,
118
+ "MmeDeR": 0.394,
119
+ "Isabeau": 0.394,
120
+ "Gervais": 0.394,
121
+ "Listolier": 0.341,
122
+ "Tholomyes": 0.392,
123
+ "Fameuil": 0.341,
124
+ "Blacheville": 0.341,
125
+ "Favourite": 0.341,
126
+ "Dahlia": 0.341,
127
+ "Zephine": 0.341,
128
+ "Fantine": 0.461,
129
+ "MmeThenardier": 0.461,
130
+ "Thenardier": 0.517,
131
+ "Cosette": 0.478,
132
+ "Javert": 0.517,
133
+ "Fauchelevent": 0.402,
134
+ "Bamatabois": 0.427,
135
+ "Perpetue": 0.318,
136
+ "Simplice": 0.418,
137
+ "Scaufflaire": 0.394,
138
+ "Woman1": 0.396,
139
+ "Judge": 0.404,
140
+ "Champmathieu": 0.404,
141
+ "Brevet": 0.404,
142
+ "Chenildieu": 0.404,
143
+ "Cochepaille": 0.404,
144
+ "Pontmercy": 0.373,
145
+ "Boulatruelle": 0.342,
146
+ "Eponine": 0.396,
147
+ "Anzelma": 0.352,
148
+ "Woman2": 0.402,
149
+ "MotherInnocent": 0.398,
150
+ "Gribier": 0.288,
151
+ "MmeBurgon": 0.344,
152
+ "Jondrette": 0.257,
153
+ "Gavroche": 0.514,
154
+ "Gillenormand": 0.442,
155
+ "Magnon": 0.335,
156
+ "MlleGillenormand": 0.442,
157
+ "MmePontmercy": 0.315,
158
+ "MlleVaubois": 0.308,
159
+ "LtGillenormand": 0.365,
160
+ "Marius": 0.531,
161
+ "BaronessT": 0.352,
162
+ "Mabeuf": 0.396,
163
+ "Enjolras": 0.481,
164
+ "Combeferre": 0.392,
165
+ "Prouvaire": 0.357,
166
+ "Feuilly": 0.392,
167
+ "Courfeyrac": 0.400,
168
+ "Bahorel": 0.394,
169
+ "Bossuet": 0.475,
170
+ "Joly": 0.394,
171
+ "Grantaire": 0.358,
172
+ "MotherPlutarch": 0.285,
173
+ "Gueulemer": 0.463,
174
+ "Babet": 0.463,
175
+ "Claquesous": 0.452,
176
+ "Montparnasse": 0.458,
177
+ "Toussaint": 0.402,
178
+ "Child1": 0.342,
179
+ "Child2": 0.342,
180
+ "Brujon": 0.380,
181
+ "MmeHucheloup": 0.353,
182
+ }
183
+ for n in sorted(self.LM):
184
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
185
+
186
+ def test_weighted_closeness(self):
187
+ edges = [
188
+ ("s", "u", 10),
189
+ ("s", "x", 5),
190
+ ("u", "v", 1),
191
+ ("u", "x", 2),
192
+ ("v", "y", 1),
193
+ ("x", "u", 3),
194
+ ("x", "v", 5),
195
+ ("x", "y", 2),
196
+ ("y", "s", 7),
197
+ ("y", "v", 6),
198
+ ]
199
+ XG = nx.Graph()
200
+ XG.add_weighted_edges_from(edges)
201
+ c = nx.closeness_centrality(XG, distance="weight")
202
+ d = {"y": 0.200, "x": 0.286, "s": 0.138, "u": 0.235, "v": 0.200}
203
+ for n in sorted(XG):
204
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
205
+
206
+ #
207
+ # Tests for incremental closeness centrality.
208
+ #
209
+ @staticmethod
210
+ def pick_add_edge(g):
211
+ u = nx.utils.arbitrary_element(g)
212
+ possible_nodes = set(g.nodes())
213
+ neighbors = list(g.neighbors(u)) + [u]
214
+ possible_nodes.difference_update(neighbors)
215
+ v = nx.utils.arbitrary_element(possible_nodes)
216
+ return (u, v)
217
+
218
+ @staticmethod
219
+ def pick_remove_edge(g):
220
+ u = nx.utils.arbitrary_element(g)
221
+ possible_nodes = list(g.neighbors(u))
222
+ v = nx.utils.arbitrary_element(possible_nodes)
223
+ return (u, v)
224
+
225
+ def test_directed_raises(self):
226
+ with pytest.raises(nx.NetworkXNotImplemented):
227
+ dir_G = nx.gn_graph(n=5)
228
+ prev_cc = None
229
+ edge = self.pick_add_edge(dir_G)
230
+ insert = True
231
+ nx.incremental_closeness_centrality(dir_G, edge, prev_cc, insert)
232
+
233
+ def test_wrong_size_prev_cc_raises(self):
234
+ with pytest.raises(nx.NetworkXError):
235
+ G = self.undirected_G.copy()
236
+ edge = self.pick_add_edge(G)
237
+ insert = True
238
+ prev_cc = self.undirected_G_cc.copy()
239
+ prev_cc.pop(0)
240
+ nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
241
+
242
+ def test_wrong_nodes_prev_cc_raises(self):
243
+ with pytest.raises(nx.NetworkXError):
244
+ G = self.undirected_G.copy()
245
+ edge = self.pick_add_edge(G)
246
+ insert = True
247
+ prev_cc = self.undirected_G_cc.copy()
248
+ num_nodes = len(prev_cc)
249
+ prev_cc.pop(0)
250
+ prev_cc[num_nodes] = 0.5
251
+ nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
252
+
253
+ def test_zero_centrality(self):
254
+ G = nx.path_graph(3)
255
+ prev_cc = nx.closeness_centrality(G)
256
+ edge = self.pick_remove_edge(G)
257
+ test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insertion=False)
258
+ G.remove_edges_from([edge])
259
+ real_cc = nx.closeness_centrality(G)
260
+ shared_items = set(test_cc.items()) & set(real_cc.items())
261
+ assert len(shared_items) == len(real_cc)
262
+ assert 0 in test_cc.values()
263
+
264
+ def test_incremental(self):
265
+ # Check that incremental and regular give same output
266
+ G = self.undirected_G.copy()
267
+ prev_cc = None
268
+ for i in range(5):
269
+ if i % 2 == 0:
270
+ # Remove an edge
271
+ insert = False
272
+ edge = self.pick_remove_edge(G)
273
+ else:
274
+ # Add an edge
275
+ insert = True
276
+ edge = self.pick_add_edge(G)
277
+
278
+ # start = timeit.default_timer()
279
+ test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
280
+ # inc_elapsed = (timeit.default_timer() - start)
281
+ # print(f"incremental time: {inc_elapsed}")
282
+
283
+ if insert:
284
+ G.add_edges_from([edge])
285
+ else:
286
+ G.remove_edges_from([edge])
287
+
288
+ # start = timeit.default_timer()
289
+ real_cc = nx.closeness_centrality(G)
290
+ # reg_elapsed = (timeit.default_timer() - start)
291
+ # print(f"regular time: {reg_elapsed}")
292
+ # Example output:
293
+ # incremental time: 0.208
294
+ # regular time: 0.276
295
+ # incremental time: 0.00683
296
+ # regular time: 0.260
297
+ # incremental time: 0.0224
298
+ # regular time: 0.278
299
+ # incremental time: 0.00804
300
+ # regular time: 0.208
301
+ # incremental time: 0.00947
302
+ # regular time: 0.188
303
+
304
+ assert set(test_cc.items()) == set(real_cc.items())
305
+
306
+ prev_cc = test_cc
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ pytest.importorskip("numpy")
4
+ pytest.importorskip("scipy")
5
+
6
+ import networkx as nx
7
+ from networkx import edge_current_flow_betweenness_centrality as edge_current_flow
8
+ from networkx import (
9
+ edge_current_flow_betweenness_centrality_subset as edge_current_flow_subset,
10
+ )
11
+
12
+
13
+ class TestFlowBetweennessCentrality:
14
+ def test_K4_normalized(self):
15
+ """Betweenness centrality: K4"""
16
+ G = nx.complete_graph(4)
17
+ b = nx.current_flow_betweenness_centrality_subset(
18
+ G, list(G), list(G), normalized=True
19
+ )
20
+ b_answer = nx.current_flow_betweenness_centrality(G, normalized=True)
21
+ for n in sorted(G):
22
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
23
+
24
+ def test_K4(self):
25
+ """Betweenness centrality: K4"""
26
+ G = nx.complete_graph(4)
27
+ b = nx.current_flow_betweenness_centrality_subset(
28
+ G, list(G), list(G), normalized=True
29
+ )
30
+ b_answer = nx.current_flow_betweenness_centrality(G, normalized=True)
31
+ for n in sorted(G):
32
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
33
+ # test weighted network
34
+ G.add_edge(0, 1, weight=0.5, other=0.3)
35
+ b = nx.current_flow_betweenness_centrality_subset(
36
+ G, list(G), list(G), normalized=True, weight=None
37
+ )
38
+ for n in sorted(G):
39
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
40
+ b = nx.current_flow_betweenness_centrality_subset(
41
+ G, list(G), list(G), normalized=True
42
+ )
43
+ b_answer = nx.current_flow_betweenness_centrality(G, normalized=True)
44
+ for n in sorted(G):
45
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
46
+ b = nx.current_flow_betweenness_centrality_subset(
47
+ G, list(G), list(G), normalized=True, weight="other"
48
+ )
49
+ b_answer = nx.current_flow_betweenness_centrality(
50
+ G, normalized=True, weight="other"
51
+ )
52
+ for n in sorted(G):
53
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
54
+
55
+ def test_P4_normalized(self):
56
+ """Betweenness centrality: P4 normalized"""
57
+ G = nx.path_graph(4)
58
+ b = nx.current_flow_betweenness_centrality_subset(
59
+ G, list(G), list(G), normalized=True
60
+ )
61
+ b_answer = nx.current_flow_betweenness_centrality(G, normalized=True)
62
+ for n in sorted(G):
63
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
64
+
65
+ def test_P4(self):
66
+ """Betweenness centrality: P4"""
67
+ G = nx.path_graph(4)
68
+ b = nx.current_flow_betweenness_centrality_subset(
69
+ G, list(G), list(G), normalized=True
70
+ )
71
+ b_answer = nx.current_flow_betweenness_centrality(G, normalized=True)
72
+ for n in sorted(G):
73
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
74
+
75
+ def test_star(self):
76
+ """Betweenness centrality: star"""
77
+ G = nx.Graph()
78
+ nx.add_star(G, ["a", "b", "c", "d"])
79
+ b = nx.current_flow_betweenness_centrality_subset(
80
+ G, list(G), list(G), normalized=True
81
+ )
82
+ b_answer = nx.current_flow_betweenness_centrality(G, normalized=True)
83
+ for n in sorted(G):
84
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
85
+
86
+
87
+ # class TestWeightedFlowBetweennessCentrality():
88
+ # pass
89
+
90
+
91
+ class TestEdgeFlowBetweennessCentrality:
92
+ def test_K4_normalized(self):
93
+ """Betweenness centrality: K4"""
94
+ G = nx.complete_graph(4)
95
+ b = edge_current_flow_subset(G, list(G), list(G), normalized=True)
96
+ b_answer = edge_current_flow(G, normalized=True)
97
+ for (s, t), v1 in b_answer.items():
98
+ v2 = b.get((s, t), b.get((t, s)))
99
+ assert v1 == pytest.approx(v2, abs=1e-7)
100
+
101
+ def test_K4(self):
102
+ """Betweenness centrality: K4"""
103
+ G = nx.complete_graph(4)
104
+ b = edge_current_flow_subset(G, list(G), list(G), normalized=False)
105
+ b_answer = edge_current_flow(G, normalized=False)
106
+ for (s, t), v1 in b_answer.items():
107
+ v2 = b.get((s, t), b.get((t, s)))
108
+ assert v1 == pytest.approx(v2, abs=1e-7)
109
+ # test weighted network
110
+ G.add_edge(0, 1, weight=0.5, other=0.3)
111
+ b = edge_current_flow_subset(G, list(G), list(G), normalized=False, weight=None)
112
+ # weight is None => same as unweighted network
113
+ for (s, t), v1 in b_answer.items():
114
+ v2 = b.get((s, t), b.get((t, s)))
115
+ assert v1 == pytest.approx(v2, abs=1e-7)
116
+
117
+ b = edge_current_flow_subset(G, list(G), list(G), normalized=False)
118
+ b_answer = edge_current_flow(G, normalized=False)
119
+ for (s, t), v1 in b_answer.items():
120
+ v2 = b.get((s, t), b.get((t, s)))
121
+ assert v1 == pytest.approx(v2, abs=1e-7)
122
+
123
+ b = edge_current_flow_subset(
124
+ G, list(G), list(G), normalized=False, weight="other"
125
+ )
126
+ b_answer = edge_current_flow(G, normalized=False, weight="other")
127
+ for (s, t), v1 in b_answer.items():
128
+ v2 = b.get((s, t), b.get((t, s)))
129
+ assert v1 == pytest.approx(v2, abs=1e-7)
130
+
131
+ def test_C4(self):
132
+ """Edge betweenness centrality: C4"""
133
+ G = nx.cycle_graph(4)
134
+ b = edge_current_flow_subset(G, list(G), list(G), normalized=True)
135
+ b_answer = edge_current_flow(G, normalized=True)
136
+ for (s, t), v1 in b_answer.items():
137
+ v2 = b.get((s, t), b.get((t, s)))
138
+ assert v1 == pytest.approx(v2, abs=1e-7)
139
+
140
+ def test_P4(self):
141
+ """Edge betweenness centrality: P4"""
142
+ G = nx.path_graph(4)
143
+ b = edge_current_flow_subset(G, list(G), list(G), normalized=True)
144
+ b_answer = edge_current_flow(G, normalized=True)
145
+ for (s, t), v1 in b_answer.items():
146
+ v2 = b.get((s, t), b.get((t, s)))
147
+ assert v1 == pytest.approx(v2, abs=1e-7)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_harmonic_centrality.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for degree centrality.
3
+ """
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.algorithms.centrality import harmonic_centrality
8
+
9
+
10
+ class TestClosenessCentrality:
11
+ @classmethod
12
+ def setup_class(cls):
13
+ cls.P3 = nx.path_graph(3)
14
+ cls.P4 = nx.path_graph(4)
15
+ cls.K5 = nx.complete_graph(5)
16
+
17
+ cls.C4 = nx.cycle_graph(4)
18
+ cls.C4_directed = nx.cycle_graph(4, create_using=nx.DiGraph)
19
+
20
+ cls.C5 = nx.cycle_graph(5)
21
+
22
+ cls.T = nx.balanced_tree(r=2, h=2)
23
+
24
+ cls.Gb = nx.DiGraph()
25
+ cls.Gb.add_edges_from([(0, 1), (0, 2), (0, 4), (2, 1), (2, 3), (4, 3)])
26
+
27
+ def test_p3_harmonic(self):
28
+ c = harmonic_centrality(self.P3)
29
+ d = {0: 1.5, 1: 2, 2: 1.5}
30
+ for n in sorted(self.P3):
31
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
32
+
33
+ def test_p4_harmonic(self):
34
+ c = harmonic_centrality(self.P4)
35
+ d = {0: 1.8333333, 1: 2.5, 2: 2.5, 3: 1.8333333}
36
+ for n in sorted(self.P4):
37
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
38
+
39
+ def test_clique_complete(self):
40
+ c = harmonic_centrality(self.K5)
41
+ d = {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}
42
+ for n in sorted(self.P3):
43
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
44
+
45
+ def test_cycle_C4(self):
46
+ c = harmonic_centrality(self.C4)
47
+ d = {0: 2.5, 1: 2.5, 2: 2.5, 3: 2.5}
48
+ for n in sorted(self.C4):
49
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
50
+
51
+ def test_cycle_C5(self):
52
+ c = harmonic_centrality(self.C5)
53
+ d = {0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: 4}
54
+ for n in sorted(self.C5):
55
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
56
+
57
+ def test_bal_tree(self):
58
+ c = harmonic_centrality(self.T)
59
+ d = {0: 4.0, 1: 4.1666, 2: 4.1666, 3: 2.8333, 4: 2.8333, 5: 2.8333, 6: 2.8333}
60
+ for n in sorted(self.T):
61
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
62
+
63
+ def test_exampleGraph(self):
64
+ c = harmonic_centrality(self.Gb)
65
+ d = {0: 0, 1: 2, 2: 1, 3: 2.5, 4: 1}
66
+ for n in sorted(self.Gb):
67
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
68
+
69
+ def test_weighted_harmonic(self):
70
+ XG = nx.DiGraph()
71
+ XG.add_weighted_edges_from(
72
+ [
73
+ ("a", "b", 10),
74
+ ("d", "c", 5),
75
+ ("a", "c", 1),
76
+ ("e", "f", 2),
77
+ ("f", "c", 1),
78
+ ("a", "f", 3),
79
+ ]
80
+ )
81
+ c = harmonic_centrality(XG, distance="weight")
82
+ d = {"a": 0, "b": 0.1, "c": 2.533, "d": 0, "e": 0, "f": 0.83333}
83
+ for n in sorted(XG):
84
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
85
+
86
+ def test_empty(self):
87
+ G = nx.DiGraph()
88
+ c = harmonic_centrality(G, distance="weight")
89
+ d = {}
90
+ assert c == d
91
+
92
+ def test_singleton(self):
93
+ G = nx.DiGraph()
94
+ G.add_node(0)
95
+ c = harmonic_centrality(G, distance="weight")
96
+ d = {0: 0}
97
+ assert c == d
98
+
99
+ def test_cycle_c4_directed(self):
100
+ c = harmonic_centrality(self.C4_directed, nbunch=[0, 1], sources=[1, 2])
101
+ d = {0: 0.833, 1: 0.333}
102
+ for n in [0, 1]:
103
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
104
+
105
+ def test_p3_harmonic_subset(self):
106
+ c = harmonic_centrality(self.P3, sources=[0, 1])
107
+ d = {0: 1, 1: 1, 2: 1.5}
108
+ for n in self.P3:
109
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
110
+
111
+ def test_p4_harmonic_subset(self):
112
+ c = harmonic_centrality(self.P4, nbunch=[2, 3], sources=[0, 1])
113
+ d = {2: 1.5, 3: 0.8333333}
114
+ for n in [2, 3]:
115
+ assert c[n] == pytest.approx(d[n], abs=1e-3)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_katz_centrality.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestKatzCentrality:
9
+ def test_K5(self):
10
+ """Katz centrality: K5"""
11
+ G = nx.complete_graph(5)
12
+ alpha = 0.1
13
+ b = nx.katz_centrality(G, alpha)
14
+ v = math.sqrt(1 / 5.0)
15
+ b_answer = dict.fromkeys(G, v)
16
+ for n in sorted(G):
17
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
18
+ nstart = {n: 1 for n in G}
19
+ b = nx.katz_centrality(G, alpha, nstart=nstart)
20
+ for n in sorted(G):
21
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
22
+
23
+ def test_P3(self):
24
+ """Katz centrality: P3"""
25
+ alpha = 0.1
26
+ G = nx.path_graph(3)
27
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
28
+ b = nx.katz_centrality(G, alpha)
29
+ for n in sorted(G):
30
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
31
+
32
+ def test_maxiter(self):
33
+ with pytest.raises(nx.PowerIterationFailedConvergence):
34
+ nx.katz_centrality(nx.path_graph(3), 0.1, max_iter=0)
35
+
36
+ def test_beta_as_scalar(self):
37
+ alpha = 0.1
38
+ beta = 0.1
39
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
40
+ G = nx.path_graph(3)
41
+ b = nx.katz_centrality(G, alpha, beta)
42
+ for n in sorted(G):
43
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
44
+
45
+ def test_beta_as_dict(self):
46
+ alpha = 0.1
47
+ beta = {0: 1.0, 1: 1.0, 2: 1.0}
48
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
49
+ G = nx.path_graph(3)
50
+ b = nx.katz_centrality(G, alpha, beta)
51
+ for n in sorted(G):
52
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
53
+
54
+ def test_multiple_alpha(self):
55
+ alpha_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
56
+ for alpha in alpha_list:
57
+ b_answer = {
58
+ 0.1: {
59
+ 0: 0.5598852584152165,
60
+ 1: 0.6107839182711449,
61
+ 2: 0.5598852584152162,
62
+ },
63
+ 0.2: {
64
+ 0: 0.5454545454545454,
65
+ 1: 0.6363636363636365,
66
+ 2: 0.5454545454545454,
67
+ },
68
+ 0.3: {
69
+ 0: 0.5333964609104419,
70
+ 1: 0.6564879518897746,
71
+ 2: 0.5333964609104419,
72
+ },
73
+ 0.4: {
74
+ 0: 0.5232045649263551,
75
+ 1: 0.6726915834767423,
76
+ 2: 0.5232045649263551,
77
+ },
78
+ 0.5: {
79
+ 0: 0.5144957746691622,
80
+ 1: 0.6859943117075809,
81
+ 2: 0.5144957746691622,
82
+ },
83
+ 0.6: {
84
+ 0: 0.5069794004195823,
85
+ 1: 0.6970966755769258,
86
+ 2: 0.5069794004195823,
87
+ },
88
+ }
89
+ G = nx.path_graph(3)
90
+ b = nx.katz_centrality(G, alpha)
91
+ for n in sorted(G):
92
+ assert b[n] == pytest.approx(b_answer[alpha][n], abs=1e-4)
93
+
94
+ def test_multigraph(self):
95
+ with pytest.raises(nx.NetworkXException):
96
+ nx.katz_centrality(nx.MultiGraph(), 0.1)
97
+
98
+ def test_empty(self):
99
+ e = nx.katz_centrality(nx.Graph(), 0.1)
100
+ assert e == {}
101
+
102
+ def test_bad_beta(self):
103
+ with pytest.raises(nx.NetworkXException):
104
+ G = nx.Graph([(0, 1)])
105
+ beta = {0: 77}
106
+ nx.katz_centrality(G, 0.1, beta=beta)
107
+
108
+ def test_bad_beta_number(self):
109
+ with pytest.raises(nx.NetworkXException):
110
+ G = nx.Graph([(0, 1)])
111
+ nx.katz_centrality(G, 0.1, beta="foo")
112
+
113
+
114
+ class TestKatzCentralityNumpy:
115
+ @classmethod
116
+ def setup_class(cls):
117
+ global np
118
+ np = pytest.importorskip("numpy")
119
+ pytest.importorskip("scipy")
120
+
121
+ def test_K5(self):
122
+ """Katz centrality: K5"""
123
+ G = nx.complete_graph(5)
124
+ alpha = 0.1
125
+ b = nx.katz_centrality(G, alpha)
126
+ v = math.sqrt(1 / 5.0)
127
+ b_answer = dict.fromkeys(G, v)
128
+ for n in sorted(G):
129
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
130
+ b = nx.eigenvector_centrality_numpy(G)
131
+ for n in sorted(G):
132
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
133
+
134
+ def test_P3(self):
135
+ """Katz centrality: P3"""
136
+ alpha = 0.1
137
+ G = nx.path_graph(3)
138
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
139
+ b = nx.katz_centrality_numpy(G, alpha)
140
+ for n in sorted(G):
141
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
142
+
143
+ def test_beta_as_scalar(self):
144
+ alpha = 0.1
145
+ beta = 0.1
146
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
147
+ G = nx.path_graph(3)
148
+ b = nx.katz_centrality_numpy(G, alpha, beta)
149
+ for n in sorted(G):
150
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
151
+
152
+ def test_beta_as_dict(self):
153
+ alpha = 0.1
154
+ beta = {0: 1.0, 1: 1.0, 2: 1.0}
155
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
156
+ G = nx.path_graph(3)
157
+ b = nx.katz_centrality_numpy(G, alpha, beta)
158
+ for n in sorted(G):
159
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
160
+
161
+ def test_multiple_alpha(self):
162
+ alpha_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
163
+ for alpha in alpha_list:
164
+ b_answer = {
165
+ 0.1: {
166
+ 0: 0.5598852584152165,
167
+ 1: 0.6107839182711449,
168
+ 2: 0.5598852584152162,
169
+ },
170
+ 0.2: {
171
+ 0: 0.5454545454545454,
172
+ 1: 0.6363636363636365,
173
+ 2: 0.5454545454545454,
174
+ },
175
+ 0.3: {
176
+ 0: 0.5333964609104419,
177
+ 1: 0.6564879518897746,
178
+ 2: 0.5333964609104419,
179
+ },
180
+ 0.4: {
181
+ 0: 0.5232045649263551,
182
+ 1: 0.6726915834767423,
183
+ 2: 0.5232045649263551,
184
+ },
185
+ 0.5: {
186
+ 0: 0.5144957746691622,
187
+ 1: 0.6859943117075809,
188
+ 2: 0.5144957746691622,
189
+ },
190
+ 0.6: {
191
+ 0: 0.5069794004195823,
192
+ 1: 0.6970966755769258,
193
+ 2: 0.5069794004195823,
194
+ },
195
+ }
196
+ G = nx.path_graph(3)
197
+ b = nx.katz_centrality_numpy(G, alpha)
198
+ for n in sorted(G):
199
+ assert b[n] == pytest.approx(b_answer[alpha][n], abs=1e-4)
200
+
201
+ def test_multigraph(self):
202
+ with pytest.raises(nx.NetworkXException):
203
+ nx.katz_centrality(nx.MultiGraph(), 0.1)
204
+
205
+ def test_empty(self):
206
+ e = nx.katz_centrality(nx.Graph(), 0.1)
207
+ assert e == {}
208
+
209
+ def test_bad_beta(self):
210
+ with pytest.raises(nx.NetworkXException):
211
+ G = nx.Graph([(0, 1)])
212
+ beta = {0: 77}
213
+ nx.katz_centrality_numpy(G, 0.1, beta=beta)
214
+
215
+ def test_bad_beta_numbe(self):
216
+ with pytest.raises(nx.NetworkXException):
217
+ G = nx.Graph([(0, 1)])
218
+ nx.katz_centrality_numpy(G, 0.1, beta="foo")
219
+
220
+ def test_K5_unweighted(self):
221
+ """Katz centrality: K5"""
222
+ G = nx.complete_graph(5)
223
+ alpha = 0.1
224
+ b = nx.katz_centrality(G, alpha, weight=None)
225
+ v = math.sqrt(1 / 5.0)
226
+ b_answer = dict.fromkeys(G, v)
227
+ for n in sorted(G):
228
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
229
+ b = nx.eigenvector_centrality_numpy(G, weight=None)
230
+ for n in sorted(G):
231
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-3)
232
+
233
+ def test_P3_unweighted(self):
234
+ """Katz centrality: P3"""
235
+ alpha = 0.1
236
+ G = nx.path_graph(3)
237
+ b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449, 2: 0.5598852584152162}
238
+ b = nx.katz_centrality_numpy(G, alpha, weight=None)
239
+ for n in sorted(G):
240
+ assert b[n] == pytest.approx(b_answer[n], abs=1e-4)
241
+
242
+
243
+ class TestKatzCentralityDirected:
244
+ @classmethod
245
+ def setup_class(cls):
246
+ G = nx.DiGraph()
247
+ edges = [
248
+ (1, 2),
249
+ (1, 3),
250
+ (2, 4),
251
+ (3, 2),
252
+ (3, 5),
253
+ (4, 2),
254
+ (4, 5),
255
+ (4, 6),
256
+ (5, 6),
257
+ (5, 7),
258
+ (5, 8),
259
+ (6, 8),
260
+ (7, 1),
261
+ (7, 5),
262
+ (7, 8),
263
+ (8, 6),
264
+ (8, 7),
265
+ ]
266
+ G.add_edges_from(edges, weight=2.0)
267
+ cls.G = G.reverse()
268
+ cls.G.alpha = 0.1
269
+ cls.G.evc = [
270
+ 0.3289589783189635,
271
+ 0.2832077296243516,
272
+ 0.3425906003685471,
273
+ 0.3970420865198392,
274
+ 0.41074871061646284,
275
+ 0.272257430756461,
276
+ 0.4201989685435462,
277
+ 0.34229059218038554,
278
+ ]
279
+
280
+ H = nx.DiGraph(edges)
281
+ cls.H = G.reverse()
282
+ cls.H.alpha = 0.1
283
+ cls.H.evc = [
284
+ 0.3289589783189635,
285
+ 0.2832077296243516,
286
+ 0.3425906003685471,
287
+ 0.3970420865198392,
288
+ 0.41074871061646284,
289
+ 0.272257430756461,
290
+ 0.4201989685435462,
291
+ 0.34229059218038554,
292
+ ]
293
+
294
+ def test_katz_centrality_weighted(self):
295
+ G = self.G
296
+ alpha = self.G.alpha
297
+ p = nx.katz_centrality(G, alpha, weight="weight")
298
+ for a, b in zip(list(p.values()), self.G.evc):
299
+ assert a == pytest.approx(b, abs=1e-7)
300
+
301
+ def test_katz_centrality_unweighted(self):
302
+ H = self.H
303
+ alpha = self.H.alpha
304
+ p = nx.katz_centrality(H, alpha, weight="weight")
305
+ for a, b in zip(list(p.values()), self.H.evc):
306
+ assert a == pytest.approx(b, abs=1e-7)
307
+
308
+
309
+ class TestKatzCentralityDirectedNumpy(TestKatzCentralityDirected):
310
+ @classmethod
311
+ def setup_class(cls):
312
+ global np
313
+ np = pytest.importorskip("numpy")
314
+ pytest.importorskip("scipy")
315
+ super().setup_class()
316
+
317
+ def test_katz_centrality_weighted(self):
318
+ G = self.G
319
+ alpha = self.G.alpha
320
+ p = nx.katz_centrality_numpy(G, alpha, weight="weight")
321
+ for a, b in zip(list(p.values()), self.G.evc):
322
+ assert a == pytest.approx(b, abs=1e-7)
323
+
324
+ def test_katz_centrality_unweighted(self):
325
+ H = self.H
326
+ alpha = self.H.alpha
327
+ p = nx.katz_centrality_numpy(H, alpha, weight="weight")
328
+ for a, b in zip(list(p.values()), self.H.evc):
329
+ assert a == pytest.approx(b, abs=1e-7)
330
+
331
+
332
+ class TestKatzEigenvectorVKatz:
333
+ @classmethod
334
+ def setup_class(cls):
335
+ global np
336
+ np = pytest.importorskip("numpy")
337
+ pytest.importorskip("scipy")
338
+
339
+ def test_eigenvector_v_katz_random(self):
340
+ G = nx.gnp_random_graph(10, 0.5, seed=1234)
341
+ l = max(np.linalg.eigvals(nx.adjacency_matrix(G).todense()))
342
+ e = nx.eigenvector_centrality_numpy(G)
343
+ k = nx.katz_centrality_numpy(G, 1.0 / l)
344
+ for n in G:
345
+ assert e[n] == pytest.approx(k[n], abs=1e-7)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_percolation_centrality.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def example1a_G():
7
+ G = nx.Graph()
8
+ G.add_node(1, percolation=0.1)
9
+ G.add_node(2, percolation=0.2)
10
+ G.add_node(3, percolation=0.2)
11
+ G.add_node(4, percolation=0.2)
12
+ G.add_node(5, percolation=0.3)
13
+ G.add_node(6, percolation=0.2)
14
+ G.add_node(7, percolation=0.5)
15
+ G.add_node(8, percolation=0.5)
16
+ G.add_edges_from([(1, 4), (2, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8)])
17
+ return G
18
+
19
+
20
+ def example1b_G():
21
+ G = nx.Graph()
22
+ G.add_node(1, percolation=0.3)
23
+ G.add_node(2, percolation=0.5)
24
+ G.add_node(3, percolation=0.5)
25
+ G.add_node(4, percolation=0.2)
26
+ G.add_node(5, percolation=0.3)
27
+ G.add_node(6, percolation=0.2)
28
+ G.add_node(7, percolation=0.1)
29
+ G.add_node(8, percolation=0.1)
30
+ G.add_edges_from([(1, 4), (2, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8)])
31
+ return G
32
+
33
+
34
+ def test_percolation_example1a():
35
+ """percolation centrality: example 1a"""
36
+ G = example1a_G()
37
+ p = nx.percolation_centrality(G)
38
+ p_answer = {4: 0.625, 6: 0.667}
39
+ for n, k in p_answer.items():
40
+ assert p[n] == pytest.approx(k, abs=1e-3)
41
+
42
+
43
+ def test_percolation_example1b():
44
+ """percolation centrality: example 1a"""
45
+ G = example1b_G()
46
+ p = nx.percolation_centrality(G)
47
+ p_answer = {4: 0.825, 6: 0.4}
48
+ for n, k in p_answer.items():
49
+ assert p[n] == pytest.approx(k, abs=1e-3)
50
+
51
+
52
+ def test_converge_to_betweenness():
53
+ """percolation centrality: should converge to betweenness
54
+ centrality when all nodes are percolated the same"""
55
+ # taken from betweenness test test_florentine_families_graph
56
+ G = nx.florentine_families_graph()
57
+ b_answer = {
58
+ "Acciaiuoli": 0.000,
59
+ "Albizzi": 0.212,
60
+ "Barbadori": 0.093,
61
+ "Bischeri": 0.104,
62
+ "Castellani": 0.055,
63
+ "Ginori": 0.000,
64
+ "Guadagni": 0.255,
65
+ "Lamberteschi": 0.000,
66
+ "Medici": 0.522,
67
+ "Pazzi": 0.000,
68
+ "Peruzzi": 0.022,
69
+ "Ridolfi": 0.114,
70
+ "Salviati": 0.143,
71
+ "Strozzi": 0.103,
72
+ "Tornabuoni": 0.092,
73
+ }
74
+
75
+ # If no initial state is provided, state for
76
+ # every node defaults to 1
77
+ p_answer = nx.percolation_centrality(G)
78
+ assert p_answer == pytest.approx(b_answer, abs=1e-3)
79
+
80
+ p_states = {k: 0.3 for k, v in b_answer.items()}
81
+ p_answer = nx.percolation_centrality(G, states=p_states)
82
+ assert p_answer == pytest.approx(b_answer, abs=1e-3)
83
+
84
+
85
+ def test_default_percolation():
86
+ G = nx.erdos_renyi_graph(42, 0.42, seed=42)
87
+ assert nx.percolation_centrality(G) == pytest.approx(nx.betweenness_centrality(G))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/test_trophic.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test trophic levels, trophic differences and trophic coherence
2
+ """
3
+ import pytest
4
+
5
+ np = pytest.importorskip("numpy")
6
+ pytest.importorskip("scipy")
7
+
8
+ import networkx as nx
9
+
10
+
11
+ def test_trophic_levels():
12
+ """Trivial example"""
13
+ G = nx.DiGraph()
14
+ G.add_edge("a", "b")
15
+ G.add_edge("b", "c")
16
+
17
+ d = nx.trophic_levels(G)
18
+ assert d == {"a": 1, "b": 2, "c": 3}
19
+
20
+
21
+ def test_trophic_levels_levine():
22
+ """Example from Figure 5 in Stephen Levine (1980) J. theor. Biol. 83,
23
+ 195-207
24
+ """
25
+ S = nx.DiGraph()
26
+ S.add_edge(1, 2, weight=1.0)
27
+ S.add_edge(1, 3, weight=0.2)
28
+ S.add_edge(1, 4, weight=0.8)
29
+ S.add_edge(2, 3, weight=0.2)
30
+ S.add_edge(2, 5, weight=0.3)
31
+ S.add_edge(4, 3, weight=0.6)
32
+ S.add_edge(4, 5, weight=0.7)
33
+ S.add_edge(5, 4, weight=0.2)
34
+
35
+ # save copy for later, test intermediate implementation details first
36
+ S2 = S.copy()
37
+
38
+ # drop nodes of in-degree zero
39
+ z = [nid for nid, d in S.in_degree if d == 0]
40
+ for nid in z:
41
+ S.remove_node(nid)
42
+
43
+ # find adjacency matrix
44
+ q = nx.linalg.graphmatrix.adjacency_matrix(S).T
45
+
46
+ # fmt: off
47
+ expected_q = np.array([
48
+ [0, 0, 0., 0],
49
+ [0.2, 0, 0.6, 0],
50
+ [0, 0, 0, 0.2],
51
+ [0.3, 0, 0.7, 0]
52
+ ])
53
+ # fmt: on
54
+ assert np.array_equal(q.todense(), expected_q)
55
+
56
+ # must be square, size of number of nodes
57
+ assert len(q.shape) == 2
58
+ assert q.shape[0] == q.shape[1]
59
+ assert q.shape[0] == len(S)
60
+
61
+ nn = q.shape[0]
62
+
63
+ i = np.eye(nn)
64
+ n = np.linalg.inv(i - q)
65
+ y = np.asarray(n) @ np.ones(nn)
66
+
67
+ expected_y = np.array([1, 2.07906977, 1.46511628, 2.3255814])
68
+ assert np.allclose(y, expected_y)
69
+
70
+ expected_d = {1: 1, 2: 2, 3: 3.07906977, 4: 2.46511628, 5: 3.3255814}
71
+
72
+ d = nx.trophic_levels(S2)
73
+
74
+ for nid, level in d.items():
75
+ expected_level = expected_d[nid]
76
+ assert expected_level == pytest.approx(level, abs=1e-7)
77
+
78
+
79
+ def test_trophic_levels_simple():
80
+ matrix_a = np.array([[0, 0], [1, 0]])
81
+ G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
82
+ d = nx.trophic_levels(G)
83
+ assert d[0] == pytest.approx(2, abs=1e-7)
84
+ assert d[1] == pytest.approx(1, abs=1e-7)
85
+
86
+
87
+ def test_trophic_levels_more_complex():
88
+ # fmt: off
89
+ matrix = np.array([
90
+ [0, 1, 0, 0],
91
+ [0, 0, 1, 0],
92
+ [0, 0, 0, 1],
93
+ [0, 0, 0, 0]
94
+ ])
95
+ # fmt: on
96
+ G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
97
+ d = nx.trophic_levels(G)
98
+ expected_result = [1, 2, 3, 4]
99
+ for ind in range(4):
100
+ assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
101
+
102
+ # fmt: off
103
+ matrix = np.array([
104
+ [0, 1, 1, 0],
105
+ [0, 0, 1, 1],
106
+ [0, 0, 0, 1],
107
+ [0, 0, 0, 0]
108
+ ])
109
+ # fmt: on
110
+ G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
111
+ d = nx.trophic_levels(G)
112
+
113
+ expected_result = [1, 2, 2.5, 3.25]
114
+ print("Calculated result: ", d)
115
+ print("Expected Result: ", expected_result)
116
+
117
+ for ind in range(4):
118
+ assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
119
+
120
+
121
+ def test_trophic_levels_even_more_complex():
122
+ # fmt: off
123
+ # Another, bigger matrix
124
+ matrix = np.array([
125
+ [0, 0, 0, 0, 0],
126
+ [0, 1, 0, 1, 0],
127
+ [1, 0, 0, 0, 0],
128
+ [0, 1, 0, 0, 0],
129
+ [0, 0, 0, 1, 0]
130
+ ])
131
+ # Generated this linear system using pen and paper:
132
+ K = np.array([
133
+ [1, 0, -1, 0, 0],
134
+ [0, 0.5, 0, -0.5, 0],
135
+ [0, 0, 1, 0, 0],
136
+ [0, -0.5, 0, 1, -0.5],
137
+ [0, 0, 0, 0, 1],
138
+ ])
139
+ # fmt: on
140
+ result_1 = np.ravel(np.linalg.inv(K) @ np.ones(5))
141
+ G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
142
+ result_2 = nx.trophic_levels(G)
143
+
144
+ for ind in range(5):
145
+ assert result_1[ind] == pytest.approx(result_2[ind], abs=1e-7)
146
+
147
+
148
+ def test_trophic_levels_singular_matrix():
149
+ """Should raise an error with graphs with only non-basal nodes"""
150
+ matrix = np.identity(4)
151
+ G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
152
+ with pytest.raises(nx.NetworkXError) as e:
153
+ nx.trophic_levels(G)
154
+ msg = (
155
+ "Trophic levels are only defined for graphs where every node "
156
+ + "has a path from a basal node (basal nodes are nodes with no "
157
+ + "incoming edges)."
158
+ )
159
+ assert msg in str(e.value)
160
+
161
+
162
+ def test_trophic_levels_singular_with_basal():
163
+ """Should fail to compute if there are any parts of the graph which are not
164
+ reachable from any basal node (with in-degree zero).
165
+ """
166
+ G = nx.DiGraph()
167
+ # a has in-degree zero
168
+ G.add_edge("a", "b")
169
+
170
+ # b is one level above a, c and d
171
+ G.add_edge("c", "b")
172
+ G.add_edge("d", "b")
173
+
174
+ # c and d form a loop, neither are reachable from a
175
+ G.add_edge("c", "d")
176
+ G.add_edge("d", "c")
177
+
178
+ with pytest.raises(nx.NetworkXError) as e:
179
+ nx.trophic_levels(G)
180
+ msg = (
181
+ "Trophic levels are only defined for graphs where every node "
182
+ + "has a path from a basal node (basal nodes are nodes with no "
183
+ + "incoming edges)."
184
+ )
185
+ assert msg in str(e.value)
186
+
187
+ # if self-loops are allowed, smaller example:
188
+ G = nx.DiGraph()
189
+ G.add_edge("a", "b") # a has in-degree zero
190
+ G.add_edge("c", "b") # b is one level above a and c
191
+ G.add_edge("c", "c") # c has a self-loop
192
+ with pytest.raises(nx.NetworkXError) as e:
193
+ nx.trophic_levels(G)
194
+ msg = (
195
+ "Trophic levels are only defined for graphs where every node "
196
+ + "has a path from a basal node (basal nodes are nodes with no "
197
+ + "incoming edges)."
198
+ )
199
+ assert msg in str(e.value)
200
+
201
+
202
+ def test_trophic_differences():
203
+ matrix_a = np.array([[0, 1], [0, 0]])
204
+ G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
205
+ diffs = nx.trophic_differences(G)
206
+ assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
207
+
208
+ # fmt: off
209
+ matrix_b = np.array([
210
+ [0, 1, 1, 0],
211
+ [0, 0, 1, 1],
212
+ [0, 0, 0, 1],
213
+ [0, 0, 0, 0]
214
+ ])
215
+ # fmt: on
216
+ G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
217
+ diffs = nx.trophic_differences(G)
218
+
219
+ assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
220
+ assert diffs[(0, 2)] == pytest.approx(1.5, abs=1e-7)
221
+ assert diffs[(1, 2)] == pytest.approx(0.5, abs=1e-7)
222
+ assert diffs[(1, 3)] == pytest.approx(1.25, abs=1e-7)
223
+ assert diffs[(2, 3)] == pytest.approx(0.75, abs=1e-7)
224
+
225
+
226
+ def test_trophic_incoherence_parameter_no_cannibalism():
227
+ matrix_a = np.array([[0, 1], [0, 0]])
228
+ G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
229
+ q = nx.trophic_incoherence_parameter(G, cannibalism=False)
230
+ assert q == pytest.approx(0, abs=1e-7)
231
+
232
+ # fmt: off
233
+ matrix_b = np.array([
234
+ [0, 1, 1, 0],
235
+ [0, 0, 1, 1],
236
+ [0, 0, 0, 1],
237
+ [0, 0, 0, 0]
238
+ ])
239
+ # fmt: on
240
+ G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
241
+ q = nx.trophic_incoherence_parameter(G, cannibalism=False)
242
+ assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
243
+
244
+ # fmt: off
245
+ matrix_c = np.array([
246
+ [0, 1, 1, 0],
247
+ [0, 1, 1, 1],
248
+ [0, 0, 0, 1],
249
+ [0, 0, 0, 1]
250
+ ])
251
+ # fmt: on
252
+ G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
253
+ q = nx.trophic_incoherence_parameter(G, cannibalism=False)
254
+ # Ignore the -link
255
+ assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
256
+
257
+ # no self-loops case
258
+ # fmt: off
259
+ matrix_d = np.array([
260
+ [0, 1, 1, 0],
261
+ [0, 0, 1, 1],
262
+ [0, 0, 0, 1],
263
+ [0, 0, 0, 0]
264
+ ])
265
+ # fmt: on
266
+ G = nx.from_numpy_array(matrix_d, create_using=nx.DiGraph)
267
+ q = nx.trophic_incoherence_parameter(G, cannibalism=False)
268
+ # Ignore the -link
269
+ assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
270
+
271
+
272
+ def test_trophic_incoherence_parameter_cannibalism():
273
+ matrix_a = np.array([[0, 1], [0, 0]])
274
+ G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
275
+ q = nx.trophic_incoherence_parameter(G, cannibalism=True)
276
+ assert q == pytest.approx(0, abs=1e-7)
277
+
278
+ # fmt: off
279
+ matrix_b = np.array([
280
+ [0, 0, 0, 0, 0],
281
+ [0, 1, 0, 1, 0],
282
+ [1, 0, 0, 0, 0],
283
+ [0, 1, 0, 0, 0],
284
+ [0, 0, 0, 1, 0]
285
+ ])
286
+ # fmt: on
287
+ G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
288
+ q = nx.trophic_incoherence_parameter(G, cannibalism=True)
289
+ assert q == pytest.approx(2, abs=1e-7)
290
+
291
+ # fmt: off
292
+ matrix_c = np.array([
293
+ [0, 1, 1, 0],
294
+ [0, 0, 1, 1],
295
+ [0, 0, 0, 1],
296
+ [0, 0, 0, 0]
297
+ ])
298
+ # fmt: on
299
+ G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
300
+ q = nx.trophic_incoherence_parameter(G, cannibalism=True)
301
+ # Ignore the -link
302
+ assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_communicability.cpython-310.pyc ADDED
Binary file (2.17 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_covering.cpython-310.pyc ADDED
Binary file (3.73 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_d_separation.cpython-310.pyc ADDED
Binary file (9.23 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_distance_measures.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dominating.cpython-310.pyc ADDED
Binary file (1.76 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_euler.cpython-310.pyc ADDED
Binary file (13.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_hierarchy.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_hybrid.cpython-310.pyc ADDED
Binary file (840 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_isolate.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_link_prediction.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_node_classification.cpython-310.pyc ADDED
Binary file (4.67 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_reciprocity.cpython-310.pyc ADDED
Binary file (1.84 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_smallworld.cpython-310.pyc ADDED
Binary file (2.56 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_swap.cpython-310.pyc ADDED
Binary file (8.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_wiener.cpython-310.pyc ADDED
Binary file (3.17 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+
4
+ def test_is_at_free():
5
+ is_at_free = nx.asteroidal.is_at_free
6
+
7
+ cycle = nx.cycle_graph(6)
8
+ assert not is_at_free(cycle)
9
+
10
+ path = nx.path_graph(6)
11
+ assert is_at_free(path)
12
+
13
+ small_graph = nx.complete_graph(2)
14
+ assert is_at_free(small_graph)
15
+
16
+ petersen = nx.petersen_graph()
17
+ assert not is_at_free(petersen)
18
+
19
+ clique = nx.complete_graph(6)
20
+ assert is_at_free(clique)
21
+
22
+ line_clique = nx.line_graph(clique)
23
+ assert not is_at_free(line_clique)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.boundary` module."""
2
+
3
+ from itertools import combinations
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx import convert_node_labels_to_integers as cnlti
9
+ from networkx.utils import edges_equal
10
+
11
+
12
+ class TestNodeBoundary:
13
+ """Unit tests for the :func:`~networkx.node_boundary` function."""
14
+
15
+ def test_null_graph(self):
16
+ """Tests that the null graph has empty node boundaries."""
17
+ null = nx.null_graph()
18
+ assert nx.node_boundary(null, []) == set()
19
+ assert nx.node_boundary(null, [], []) == set()
20
+ assert nx.node_boundary(null, [1, 2, 3]) == set()
21
+ assert nx.node_boundary(null, [1, 2, 3], [4, 5, 6]) == set()
22
+ assert nx.node_boundary(null, [1, 2, 3], [3, 4, 5]) == set()
23
+
24
+ def test_path_graph(self):
25
+ P10 = cnlti(nx.path_graph(10), first_label=1)
26
+ assert nx.node_boundary(P10, []) == set()
27
+ assert nx.node_boundary(P10, [], []) == set()
28
+ assert nx.node_boundary(P10, [1, 2, 3]) == {4}
29
+ assert nx.node_boundary(P10, [4, 5, 6]) == {3, 7}
30
+ assert nx.node_boundary(P10, [3, 4, 5, 6, 7]) == {2, 8}
31
+ assert nx.node_boundary(P10, [8, 9, 10]) == {7}
32
+ assert nx.node_boundary(P10, [4, 5, 6], [9, 10]) == set()
33
+
34
+ def test_complete_graph(self):
35
+ K10 = cnlti(nx.complete_graph(10), first_label=1)
36
+ assert nx.node_boundary(K10, []) == set()
37
+ assert nx.node_boundary(K10, [], []) == set()
38
+ assert nx.node_boundary(K10, [1, 2, 3]) == {4, 5, 6, 7, 8, 9, 10}
39
+ assert nx.node_boundary(K10, [4, 5, 6]) == {1, 2, 3, 7, 8, 9, 10}
40
+ assert nx.node_boundary(K10, [3, 4, 5, 6, 7]) == {1, 2, 8, 9, 10}
41
+ assert nx.node_boundary(K10, [4, 5, 6], []) == set()
42
+ assert nx.node_boundary(K10, K10) == set()
43
+ assert nx.node_boundary(K10, [1, 2, 3], [3, 4, 5]) == {4, 5}
44
+
45
+ def test_petersen(self):
46
+ """Check boundaries in the petersen graph
47
+
48
+ cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0<k<=|V(G)|/2)
49
+
50
+ """
51
+
52
+ def cheeger(G, k):
53
+ return min(len(nx.node_boundary(G, nn)) / k for nn in combinations(G, k))
54
+
55
+ P = nx.petersen_graph()
56
+ assert cheeger(P, 1) == pytest.approx(3.00, abs=1e-2)
57
+ assert cheeger(P, 2) == pytest.approx(2.00, abs=1e-2)
58
+ assert cheeger(P, 3) == pytest.approx(1.67, abs=1e-2)
59
+ assert cheeger(P, 4) == pytest.approx(1.00, abs=1e-2)
60
+ assert cheeger(P, 5) == pytest.approx(0.80, abs=1e-2)
61
+
62
+ def test_directed(self):
63
+ """Tests the node boundary of a directed graph."""
64
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
65
+ S = {0, 1}
66
+ boundary = nx.node_boundary(G, S)
67
+ expected = {2}
68
+ assert boundary == expected
69
+
70
+ def test_multigraph(self):
71
+ """Tests the node boundary of a multigraph."""
72
+ G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
73
+ S = {0, 1}
74
+ boundary = nx.node_boundary(G, S)
75
+ expected = {2, 4}
76
+ assert boundary == expected
77
+
78
+ def test_multidigraph(self):
79
+ """Tests the edge boundary of a multidigraph."""
80
+ edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
81
+ G = nx.MultiDiGraph(edges * 2)
82
+ S = {0, 1}
83
+ boundary = nx.node_boundary(G, S)
84
+ expected = {2}
85
+ assert boundary == expected
86
+
87
+
88
+ class TestEdgeBoundary:
89
+ """Unit tests for the :func:`~networkx.edge_boundary` function."""
90
+
91
+ def test_null_graph(self):
92
+ null = nx.null_graph()
93
+ assert list(nx.edge_boundary(null, [])) == []
94
+ assert list(nx.edge_boundary(null, [], [])) == []
95
+ assert list(nx.edge_boundary(null, [1, 2, 3])) == []
96
+ assert list(nx.edge_boundary(null, [1, 2, 3], [4, 5, 6])) == []
97
+ assert list(nx.edge_boundary(null, [1, 2, 3], [3, 4, 5])) == []
98
+
99
+ def test_path_graph(self):
100
+ P10 = cnlti(nx.path_graph(10), first_label=1)
101
+ assert list(nx.edge_boundary(P10, [])) == []
102
+ assert list(nx.edge_boundary(P10, [], [])) == []
103
+ assert list(nx.edge_boundary(P10, [1, 2, 3])) == [(3, 4)]
104
+ assert sorted(nx.edge_boundary(P10, [4, 5, 6])) == [(4, 3), (6, 7)]
105
+ assert sorted(nx.edge_boundary(P10, [3, 4, 5, 6, 7])) == [(3, 2), (7, 8)]
106
+ assert list(nx.edge_boundary(P10, [8, 9, 10])) == [(8, 7)]
107
+ assert sorted(nx.edge_boundary(P10, [4, 5, 6], [9, 10])) == []
108
+ assert list(nx.edge_boundary(P10, [1, 2, 3], [3, 4, 5])) == [(2, 3), (3, 4)]
109
+
110
+ def test_complete_graph(self):
111
+ K10 = cnlti(nx.complete_graph(10), first_label=1)
112
+
113
+ def ilen(iterable):
114
+ return sum(1 for i in iterable)
115
+
116
+ assert list(nx.edge_boundary(K10, [])) == []
117
+ assert list(nx.edge_boundary(K10, [], [])) == []
118
+ assert ilen(nx.edge_boundary(K10, [1, 2, 3])) == 21
119
+ assert ilen(nx.edge_boundary(K10, [4, 5, 6, 7])) == 24
120
+ assert ilen(nx.edge_boundary(K10, [3, 4, 5, 6, 7])) == 25
121
+ assert ilen(nx.edge_boundary(K10, [8, 9, 10])) == 21
122
+ assert edges_equal(
123
+ nx.edge_boundary(K10, [4, 5, 6], [9, 10]),
124
+ [(4, 9), (4, 10), (5, 9), (5, 10), (6, 9), (6, 10)],
125
+ )
126
+ assert edges_equal(
127
+ nx.edge_boundary(K10, [1, 2, 3], [3, 4, 5]),
128
+ [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5)],
129
+ )
130
+
131
+ def test_directed(self):
132
+ """Tests the edge boundary of a directed graph."""
133
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
134
+ S = {0, 1}
135
+ boundary = list(nx.edge_boundary(G, S))
136
+ expected = [(1, 2)]
137
+ assert boundary == expected
138
+
139
+ def test_multigraph(self):
140
+ """Tests the edge boundary of a multigraph."""
141
+ G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
142
+ S = {0, 1}
143
+ boundary = list(nx.edge_boundary(G, S))
144
+ expected = [(0, 4), (0, 4), (1, 2), (1, 2)]
145
+ assert boundary == expected
146
+
147
+ def test_multidigraph(self):
148
+ """Tests the edge boundary of a multidigraph."""
149
+ edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
150
+ G = nx.MultiDiGraph(edges * 2)
151
+ S = {0, 1}
152
+ boundary = list(nx.edge_boundary(G, S))
153
+ expected = [(1, 2), (1, 2)]
154
+ assert boundary == expected
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for bridge-finding algorithms."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestBridges:
9
+ """Unit tests for the bridge-finding function."""
10
+
11
+ def test_single_bridge(self):
12
+ edges = [
13
+ # DFS tree edges.
14
+ (1, 2),
15
+ (2, 3),
16
+ (3, 4),
17
+ (3, 5),
18
+ (5, 6),
19
+ (6, 7),
20
+ (7, 8),
21
+ (5, 9),
22
+ (9, 10),
23
+ # Nontree edges.
24
+ (1, 3),
25
+ (1, 4),
26
+ (2, 5),
27
+ (5, 10),
28
+ (6, 8),
29
+ ]
30
+ G = nx.Graph(edges)
31
+ source = 1
32
+ bridges = list(nx.bridges(G, source))
33
+ assert bridges == [(5, 6)]
34
+
35
+ def test_barbell_graph(self):
36
+ # The (3, 0) barbell graph has two triangles joined by a single edge.
37
+ G = nx.barbell_graph(3, 0)
38
+ source = 0
39
+ bridges = list(nx.bridges(G, source))
40
+ assert bridges == [(2, 3)]
41
+
42
+ def test_multiedge_bridge(self):
43
+ edges = [
44
+ (0, 1),
45
+ (0, 2),
46
+ (1, 2),
47
+ (1, 2),
48
+ (2, 3),
49
+ (3, 4),
50
+ (3, 4),
51
+ ]
52
+ G = nx.MultiGraph(edges)
53
+ assert list(nx.bridges(G)) == [(2, 3)]
54
+
55
+
56
+ class TestHasBridges:
57
+ """Unit tests for the has bridges function."""
58
+
59
+ def test_single_bridge(self):
60
+ edges = [
61
+ # DFS tree edges.
62
+ (1, 2),
63
+ (2, 3),
64
+ (3, 4),
65
+ (3, 5),
66
+ (5, 6), # The only bridge edge
67
+ (6, 7),
68
+ (7, 8),
69
+ (5, 9),
70
+ (9, 10),
71
+ # Nontree edges.
72
+ (1, 3),
73
+ (1, 4),
74
+ (2, 5),
75
+ (5, 10),
76
+ (6, 8),
77
+ ]
78
+ G = nx.Graph(edges)
79
+ assert nx.has_bridges(G) # Default root
80
+ assert nx.has_bridges(G, root=1) # arbitrary root in G
81
+
82
+ def test_has_bridges_raises_root_not_in_G(self):
83
+ G = nx.Graph()
84
+ G.add_nodes_from([1, 2, 3])
85
+ with pytest.raises(nx.NodeNotFound):
86
+ nx.has_bridges(G, root=6)
87
+
88
+ def test_multiedge_bridge(self):
89
+ edges = [
90
+ (0, 1),
91
+ (0, 2),
92
+ (1, 2),
93
+ (1, 2),
94
+ (2, 3),
95
+ (3, 4),
96
+ (3, 4),
97
+ ]
98
+ G = nx.MultiGraph(edges)
99
+ assert nx.has_bridges(G)
100
+ # Make every edge a multiedge
101
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
102
+ assert not nx.has_bridges(G)
103
+
104
+ def test_bridges_multiple_components(self):
105
+ G = nx.Graph()
106
+ nx.add_path(G, [0, 1, 2]) # One connected component
107
+ nx.add_path(G, [4, 5, 6]) # Another connected component
108
+ assert list(nx.bridges(G, root=4)) == [(4, 5), (5, 6)]
109
+
110
+
111
+ class TestLocalBridges:
112
+ """Unit tests for the local_bridge function."""
113
+
114
+ @classmethod
115
+ def setup_class(cls):
116
+ cls.BB = nx.barbell_graph(4, 0)
117
+ cls.square = nx.cycle_graph(4)
118
+ cls.tri = nx.cycle_graph(3)
119
+
120
+ def test_nospan(self):
121
+ expected = {(3, 4), (4, 3)}
122
+ assert next(nx.local_bridges(self.BB, with_span=False)) in expected
123
+ assert set(nx.local_bridges(self.square, with_span=False)) == self.square.edges
124
+ assert list(nx.local_bridges(self.tri, with_span=False)) == []
125
+
126
+ def test_no_weight(self):
127
+ inf = float("inf")
128
+ expected = {(3, 4, inf), (4, 3, inf)}
129
+ assert next(nx.local_bridges(self.BB)) in expected
130
+ expected = {(u, v, 3) for u, v in self.square.edges}
131
+ assert set(nx.local_bridges(self.square)) == expected
132
+ assert list(nx.local_bridges(self.tri)) == []
133
+
134
+ def test_weight(self):
135
+ inf = float("inf")
136
+ G = self.square.copy()
137
+
138
+ G.edges[1, 2]["weight"] = 2
139
+ expected = {(u, v, 5 - wt) for u, v, wt in G.edges(data="weight", default=1)}
140
+ assert set(nx.local_bridges(G, weight="weight")) == expected
141
+
142
+ expected = {(u, v, 6) for u, v in G.edges}
143
+ lb = nx.local_bridges(G, weight=lambda u, v, d: 2)
144
+ assert set(lb) == expected
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the broadcasting module."""
2
+ import math
3
+
4
+ import networkx as nx
5
+
6
+
7
+ def test_example_tree_broadcast():
8
+ """
9
+ Test the BROADCAST algorithm on the example in the paper titled: "Information Dissemination in Trees"
10
+ """
11
+ edge_list = [
12
+ (0, 1),
13
+ (1, 2),
14
+ (2, 7),
15
+ (3, 4),
16
+ (5, 4),
17
+ (4, 7),
18
+ (6, 7),
19
+ (7, 9),
20
+ (8, 9),
21
+ (9, 13),
22
+ (13, 14),
23
+ (14, 15),
24
+ (14, 16),
25
+ (14, 17),
26
+ (13, 11),
27
+ (11, 10),
28
+ (11, 12),
29
+ (13, 18),
30
+ (18, 19),
31
+ (18, 20),
32
+ ]
33
+ G = nx.Graph(edge_list)
34
+ b_T, b_C = nx.tree_broadcast_center(G)
35
+ assert b_T == 6
36
+ assert b_C == {13, 9}
37
+ # test broadcast time from specific vertex
38
+ assert nx.tree_broadcast_time(G, 17) == 8
39
+ assert nx.tree_broadcast_time(G, 3) == 9
40
+ # test broadcast time of entire tree
41
+ assert nx.tree_broadcast_time(G) == 10
42
+
43
+
44
+ def test_path_broadcast():
45
+ for i in range(2, 12):
46
+ G = nx.path_graph(i)
47
+ b_T, b_C = nx.tree_broadcast_center(G)
48
+ assert b_T == math.ceil(i / 2)
49
+ assert b_C == {
50
+ math.ceil(i / 2),
51
+ math.floor(i / 2),
52
+ math.ceil(i / 2 - 1),
53
+ math.floor(i / 2 - 1),
54
+ }
55
+ assert nx.tree_broadcast_time(G) == i - 1
56
+
57
+
58
+ def test_empty_graph_broadcast():
59
+ H = nx.empty_graph(1)
60
+ b_T, b_C = nx.tree_broadcast_center(H)
61
+ assert b_T == 0
62
+ assert b_C == {0}
63
+ assert nx.tree_broadcast_time(H) == 0
64
+
65
+
66
+ def test_star_broadcast():
67
+ for i in range(4, 12):
68
+ G = nx.star_graph(i)
69
+ b_T, b_C = nx.tree_broadcast_center(G)
70
+ assert b_T == i
71
+ assert b_C == set(G.nodes())
72
+ assert nx.tree_broadcast_time(G) == b_T
73
+
74
+
75
+ def test_binomial_tree_broadcast():
76
+ for i in range(2, 8):
77
+ G = nx.binomial_tree(i)
78
+ b_T, b_C = nx.tree_broadcast_center(G)
79
+ assert b_T == i
80
+ assert b_C == {0, 2 ** (i - 1)}
81
+ assert nx.tree_broadcast_time(G) == 2 * i - 1
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_chains.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the chain decomposition functions."""
2
+ from itertools import cycle, islice
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+
8
+
9
+ def cycles(seq):
10
+ """Yields cyclic permutations of the given sequence.
11
+
12
+ For example::
13
+
14
+ >>> list(cycles("abc"))
15
+ [('a', 'b', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b')]
16
+
17
+ """
18
+ n = len(seq)
19
+ cycled_seq = cycle(seq)
20
+ for x in seq:
21
+ yield tuple(islice(cycled_seq, n))
22
+ next(cycled_seq)
23
+
24
+
25
+ def cyclic_equals(seq1, seq2):
26
+ """Decide whether two sequences are equal up to cyclic permutations.
27
+
28
+ For example::
29
+
30
+ >>> cyclic_equals("xyz", "zxy")
31
+ True
32
+ >>> cyclic_equals("xyz", "zyx")
33
+ False
34
+
35
+ """
36
+ # Cast seq2 to a tuple since `cycles()` yields tuples.
37
+ seq2 = tuple(seq2)
38
+ return any(x == tuple(seq2) for x in cycles(seq1))
39
+
40
+
41
+ class TestChainDecomposition:
42
+ """Unit tests for the chain decomposition function."""
43
+
44
+ def assertContainsChain(self, chain, expected):
45
+ # A cycle could be expressed in two different orientations, one
46
+ # forward and one backward, so we need to check for cyclic
47
+ # equality in both orientations.
48
+ reversed_chain = list(reversed([tuple(reversed(e)) for e in chain]))
49
+ for candidate in expected:
50
+ if cyclic_equals(chain, candidate):
51
+ break
52
+ if cyclic_equals(reversed_chain, candidate):
53
+ break
54
+ else:
55
+ self.fail("chain not found")
56
+
57
+ def test_decomposition(self):
58
+ edges = [
59
+ # DFS tree edges.
60
+ (1, 2),
61
+ (2, 3),
62
+ (3, 4),
63
+ (3, 5),
64
+ (5, 6),
65
+ (6, 7),
66
+ (7, 8),
67
+ (5, 9),
68
+ (9, 10),
69
+ # Nontree edges.
70
+ (1, 3),
71
+ (1, 4),
72
+ (2, 5),
73
+ (5, 10),
74
+ (6, 8),
75
+ ]
76
+ G = nx.Graph(edges)
77
+ expected = [
78
+ [(1, 3), (3, 2), (2, 1)],
79
+ [(1, 4), (4, 3)],
80
+ [(2, 5), (5, 3)],
81
+ [(5, 10), (10, 9), (9, 5)],
82
+ [(6, 8), (8, 7), (7, 6)],
83
+ ]
84
+ chains = list(nx.chain_decomposition(G, root=1))
85
+ assert len(chains) == len(expected)
86
+
87
+ # This chain decomposition isn't unique
88
+ # for chain in chains:
89
+ # print(chain)
90
+ # self.assertContainsChain(chain, expected)
91
+
92
+ def test_barbell_graph(self):
93
+ # The (3, 0) barbell graph has two triangles joined by a single edge.
94
+ G = nx.barbell_graph(3, 0)
95
+ chains = list(nx.chain_decomposition(G, root=0))
96
+ expected = [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]]
97
+ assert len(chains) == len(expected)
98
+ for chain in chains:
99
+ self.assertContainsChain(chain, expected)
100
+
101
+ def test_disconnected_graph(self):
102
+ """Test for a graph with multiple connected components."""
103
+ G = nx.barbell_graph(3, 0)
104
+ H = nx.barbell_graph(3, 0)
105
+ mapping = dict(zip(range(6), "abcdef"))
106
+ nx.relabel_nodes(H, mapping, copy=False)
107
+ G = nx.union(G, H)
108
+ chains = list(nx.chain_decomposition(G))
109
+ expected = [
110
+ [(0, 1), (1, 2), (2, 0)],
111
+ [(3, 4), (4, 5), (5, 3)],
112
+ [("a", "b"), ("b", "c"), ("c", "a")],
113
+ [("d", "e"), ("e", "f"), ("f", "d")],
114
+ ]
115
+ assert len(chains) == len(expected)
116
+ for chain in chains:
117
+ self.assertContainsChain(chain, expected)
118
+
119
+ def test_disconnected_graph_root_node(self):
120
+ """Test for a single component of a disconnected graph."""
121
+ G = nx.barbell_graph(3, 0)
122
+ H = nx.barbell_graph(3, 0)
123
+ mapping = dict(zip(range(6), "abcdef"))
124
+ nx.relabel_nodes(H, mapping, copy=False)
125
+ G = nx.union(G, H)
126
+ chains = list(nx.chain_decomposition(G, root="a"))
127
+ expected = [
128
+ [("a", "b"), ("b", "c"), ("c", "a")],
129
+ [("d", "e"), ("e", "f"), ("f", "d")],
130
+ ]
131
+ assert len(chains) == len(expected)
132
+ for chain in chains:
133
+ self.assertContainsChain(chain, expected)
134
+
135
+ def test_chain_decomposition_root_not_in_G(self):
136
+ """Test chain decomposition when root is not in graph"""
137
+ G = nx.Graph()
138
+ G.add_nodes_from([1, 2, 3])
139
+ with pytest.raises(nx.NodeNotFound):
140
+ nx.has_bridges(G, root=6)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestMCS:
7
+ @classmethod
8
+ def setup_class(cls):
9
+ # simple graph
10
+ connected_chordal_G = nx.Graph()
11
+ connected_chordal_G.add_edges_from(
12
+ [
13
+ (1, 2),
14
+ (1, 3),
15
+ (2, 3),
16
+ (2, 4),
17
+ (3, 4),
18
+ (3, 5),
19
+ (3, 6),
20
+ (4, 5),
21
+ (4, 6),
22
+ (5, 6),
23
+ ]
24
+ )
25
+ cls.connected_chordal_G = connected_chordal_G
26
+
27
+ chordal_G = nx.Graph()
28
+ chordal_G.add_edges_from(
29
+ [
30
+ (1, 2),
31
+ (1, 3),
32
+ (2, 3),
33
+ (2, 4),
34
+ (3, 4),
35
+ (3, 5),
36
+ (3, 6),
37
+ (4, 5),
38
+ (4, 6),
39
+ (5, 6),
40
+ (7, 8),
41
+ ]
42
+ )
43
+ chordal_G.add_node(9)
44
+ cls.chordal_G = chordal_G
45
+
46
+ non_chordal_G = nx.Graph()
47
+ non_chordal_G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5), (3, 4), (3, 5)])
48
+ cls.non_chordal_G = non_chordal_G
49
+
50
+ self_loop_G = nx.Graph()
51
+ self_loop_G.add_edges_from([(1, 1)])
52
+ cls.self_loop_G = self_loop_G
53
+
54
+ @pytest.mark.parametrize("G", (nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()))
55
+ def test_is_chordal_not_implemented(self, G):
56
+ with pytest.raises(nx.NetworkXNotImplemented):
57
+ nx.is_chordal(G)
58
+
59
+ def test_is_chordal(self):
60
+ assert not nx.is_chordal(self.non_chordal_G)
61
+ assert nx.is_chordal(self.chordal_G)
62
+ assert nx.is_chordal(self.connected_chordal_G)
63
+ assert nx.is_chordal(nx.Graph())
64
+ assert nx.is_chordal(nx.complete_graph(3))
65
+ assert nx.is_chordal(nx.cycle_graph(3))
66
+ assert not nx.is_chordal(nx.cycle_graph(5))
67
+ assert nx.is_chordal(self.self_loop_G)
68
+
69
+ def test_induced_nodes(self):
70
+ G = nx.generators.classic.path_graph(10)
71
+ Induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
72
+ assert Induced_nodes == {1, 2, 3, 4, 5, 6, 7, 8, 9}
73
+ pytest.raises(
74
+ nx.NetworkXTreewidthBoundExceeded, nx.find_induced_nodes, G, 1, 9, 1
75
+ )
76
+ Induced_nodes = nx.find_induced_nodes(self.chordal_G, 1, 6)
77
+ assert Induced_nodes == {1, 2, 4, 6}
78
+ pytest.raises(nx.NetworkXError, nx.find_induced_nodes, self.non_chordal_G, 1, 5)
79
+
80
+ def test_graph_treewidth(self):
81
+ with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
82
+ nx.chordal_graph_treewidth(self.non_chordal_G)
83
+
84
+ def test_chordal_find_cliques(self):
85
+ cliques = {
86
+ frozenset([9]),
87
+ frozenset([7, 8]),
88
+ frozenset([1, 2, 3]),
89
+ frozenset([2, 3, 4]),
90
+ frozenset([3, 4, 5, 6]),
91
+ }
92
+ assert set(nx.chordal_graph_cliques(self.chordal_G)) == cliques
93
+ with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
94
+ set(nx.chordal_graph_cliques(self.non_chordal_G))
95
+ with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
96
+ set(nx.chordal_graph_cliques(self.self_loop_G))
97
+
98
+ def test_chordal_find_cliques_path(self):
99
+ G = nx.path_graph(10)
100
+ cliqueset = nx.chordal_graph_cliques(G)
101
+ for u, v in G.edges():
102
+ assert frozenset([u, v]) in cliqueset or frozenset([v, u]) in cliqueset
103
+
104
+ def test_chordal_find_cliquesCC(self):
105
+ cliques = {frozenset([1, 2, 3]), frozenset([2, 3, 4]), frozenset([3, 4, 5, 6])}
106
+ cgc = nx.chordal_graph_cliques
107
+ assert set(cgc(self.connected_chordal_G)) == cliques
108
+
109
+ def test_complete_to_chordal_graph(self):
110
+ fgrg = nx.fast_gnp_random_graph
111
+ test_graphs = [
112
+ nx.barbell_graph(6, 2),
113
+ nx.cycle_graph(15),
114
+ nx.wheel_graph(20),
115
+ nx.grid_graph([10, 4]),
116
+ nx.ladder_graph(15),
117
+ nx.star_graph(5),
118
+ nx.bull_graph(),
119
+ fgrg(20, 0.3, seed=1),
120
+ ]
121
+ for G in test_graphs:
122
+ H, a = nx.complete_to_chordal_graph(G)
123
+ assert nx.is_chordal(H)
124
+ assert len(a) == H.number_of_nodes()
125
+ if nx.is_chordal(G):
126
+ assert G.number_of_edges() == H.number_of_edges()
127
+ assert set(a.values()) == {0}
128
+ else:
129
+ assert len(set(a.values())) == H.number_of_nodes()
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import pytest
4
+
5
+ pytest.importorskip("numpy")
6
+ pytest.importorskip("scipy")
7
+
8
+ import networkx as nx
9
+ from networkx.algorithms.communicability_alg import communicability, communicability_exp
10
+
11
+
12
+ class TestCommunicability:
13
+ def test_communicability(self):
14
+ answer = {
15
+ 0: {0: 1.5430806348152435, 1: 1.1752011936438012},
16
+ 1: {0: 1.1752011936438012, 1: 1.5430806348152435},
17
+ }
18
+ # answer={(0, 0): 1.5430806348152435,
19
+ # (0, 1): 1.1752011936438012,
20
+ # (1, 0): 1.1752011936438012,
21
+ # (1, 1): 1.5430806348152435}
22
+
23
+ result = communicability(nx.path_graph(2))
24
+ for k1, val in result.items():
25
+ for k2 in val:
26
+ assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
27
+
28
+ def test_communicability2(self):
29
+ answer_orig = {
30
+ ("1", "1"): 1.6445956054135658,
31
+ ("1", "Albert"): 0.7430186221096251,
32
+ ("1", "Aric"): 0.7430186221096251,
33
+ ("1", "Dan"): 1.6208126320442937,
34
+ ("1", "Franck"): 0.42639707170035257,
35
+ ("Albert", "1"): 0.7430186221096251,
36
+ ("Albert", "Albert"): 2.4368257358712189,
37
+ ("Albert", "Aric"): 1.4368257358712191,
38
+ ("Albert", "Dan"): 2.0472097037446453,
39
+ ("Albert", "Franck"): 1.8340111678944691,
40
+ ("Aric", "1"): 0.7430186221096251,
41
+ ("Aric", "Albert"): 1.4368257358712191,
42
+ ("Aric", "Aric"): 2.4368257358712193,
43
+ ("Aric", "Dan"): 2.0472097037446457,
44
+ ("Aric", "Franck"): 1.8340111678944691,
45
+ ("Dan", "1"): 1.6208126320442937,
46
+ ("Dan", "Albert"): 2.0472097037446453,
47
+ ("Dan", "Aric"): 2.0472097037446457,
48
+ ("Dan", "Dan"): 3.1306328496328168,
49
+ ("Dan", "Franck"): 1.4860372442192515,
50
+ ("Franck", "1"): 0.42639707170035257,
51
+ ("Franck", "Albert"): 1.8340111678944691,
52
+ ("Franck", "Aric"): 1.8340111678944691,
53
+ ("Franck", "Dan"): 1.4860372442192515,
54
+ ("Franck", "Franck"): 2.3876142275231915,
55
+ }
56
+
57
+ answer = defaultdict(dict)
58
+ for (k1, k2), v in answer_orig.items():
59
+ answer[k1][k2] = v
60
+
61
+ G1 = nx.Graph(
62
+ [
63
+ ("Franck", "Aric"),
64
+ ("Aric", "Dan"),
65
+ ("Dan", "Albert"),
66
+ ("Albert", "Franck"),
67
+ ("Dan", "1"),
68
+ ("Franck", "Albert"),
69
+ ]
70
+ )
71
+
72
+ result = communicability(G1)
73
+ for k1, val in result.items():
74
+ for k2 in val:
75
+ assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
76
+
77
+ result = communicability_exp(G1)
78
+ for k1, val in result.items():
79
+ for k2 in val:
80
+ assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_core.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import nodes_equal
5
+
6
+
7
+ class TestCore:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ # G is the example graph in Figure 1 from Batagelj and
11
+ # Zaversnik's paper titled An O(m) Algorithm for Cores
12
+ # Decomposition of Networks, 2003,
13
+ # http://arXiv.org/abs/cs/0310049. With nodes labeled as
14
+ # shown, the 3-core is given by nodes 1-8, the 2-core by nodes
15
+ # 9-16, the 1-core by nodes 17-20 and node 21 is in the
16
+ # 0-core.
17
+ t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1)
18
+ t2 = nx.convert_node_labels_to_integers(t1, 5)
19
+ G = nx.union(t1, t2)
20
+ G.add_edges_from(
21
+ [
22
+ (3, 7),
23
+ (2, 11),
24
+ (11, 5),
25
+ (11, 12),
26
+ (5, 12),
27
+ (12, 19),
28
+ (12, 18),
29
+ (3, 9),
30
+ (7, 9),
31
+ (7, 10),
32
+ (9, 10),
33
+ (9, 20),
34
+ (17, 13),
35
+ (13, 14),
36
+ (14, 15),
37
+ (15, 16),
38
+ (16, 13),
39
+ ]
40
+ )
41
+ G.add_node(21)
42
+ cls.G = G
43
+
44
+ # Create the graph H resulting from the degree sequence
45
+ # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm.
46
+
47
+ degseq = [0, 1, 2, 2, 2, 2, 3]
48
+ H = nx.havel_hakimi_graph(degseq)
49
+ mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5}
50
+ cls.H = nx.relabel_nodes(H, mapping)
51
+
52
+ def test_trivial(self):
53
+ """Empty graph"""
54
+ G = nx.Graph()
55
+ assert nx.core_number(G) == {}
56
+
57
+ def test_core_number(self):
58
+ core = nx.core_number(self.G)
59
+ nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(4)]
60
+ assert nodes_equal(nodes_by_core[0], [21])
61
+ assert nodes_equal(nodes_by_core[1], [17, 18, 19, 20])
62
+ assert nodes_equal(nodes_by_core[2], [9, 10, 11, 12, 13, 14, 15, 16])
63
+ assert nodes_equal(nodes_by_core[3], [1, 2, 3, 4, 5, 6, 7, 8])
64
+
65
+ def test_core_number2(self):
66
+ core = nx.core_number(self.H)
67
+ nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(3)]
68
+ assert nodes_equal(nodes_by_core[0], [0])
69
+ assert nodes_equal(nodes_by_core[1], [1, 3])
70
+ assert nodes_equal(nodes_by_core[2], [2, 4, 5, 6])
71
+
72
+ def test_core_number_multigraph(self):
73
+ G = nx.complete_graph(3)
74
+ G = nx.MultiGraph(G)
75
+ G.add_edge(1, 2)
76
+ with pytest.raises(
77
+ nx.NetworkXNotImplemented, match="not implemented for multigraph type"
78
+ ):
79
+ nx.core_number(G)
80
+
81
+ def test_core_number_self_loop(self):
82
+ G = nx.cycle_graph(3)
83
+ G.add_edge(0, 0)
84
+ with pytest.raises(
85
+ nx.NetworkXNotImplemented, match="Input graph has self loops"
86
+ ):
87
+ nx.core_number(G)
88
+
89
+ def test_directed_core_number(self):
90
+ """core number had a bug for directed graphs found in issue #1959"""
91
+ # small example where too timid edge removal can make cn[2] = 3
92
+ G = nx.DiGraph()
93
+ edges = [(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)]
94
+ G.add_edges_from(edges)
95
+ assert nx.core_number(G) == {1: 2, 2: 2, 3: 2, 4: 2}
96
+ # small example where too aggressive edge removal can make cn[2] = 2
97
+ more_edges = [(1, 5), (3, 5), (4, 5), (3, 6), (4, 6), (5, 6)]
98
+ G.add_edges_from(more_edges)
99
+ assert nx.core_number(G) == {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3}
100
+
101
+ def test_main_core(self):
102
+ main_core_subgraph = nx.k_core(self.H)
103
+ assert sorted(main_core_subgraph.nodes()) == [2, 4, 5, 6]
104
+
105
+ def test_k_core(self):
106
+ # k=0
107
+ k_core_subgraph = nx.k_core(self.H, k=0)
108
+ assert sorted(k_core_subgraph.nodes()) == sorted(self.H.nodes())
109
+ # k=1
110
+ k_core_subgraph = nx.k_core(self.H, k=1)
111
+ assert sorted(k_core_subgraph.nodes()) == [1, 2, 3, 4, 5, 6]
112
+ # k = 2
113
+ k_core_subgraph = nx.k_core(self.H, k=2)
114
+ assert sorted(k_core_subgraph.nodes()) == [2, 4, 5, 6]
115
+
116
+ def test_k_core_multigraph(self):
117
+ core_number = nx.core_number(self.H)
118
+ H = nx.MultiGraph(self.H)
119
+ with pytest.deprecated_call():
120
+ nx.k_core(H, k=0, core_number=core_number)
121
+
122
+ def test_main_crust(self):
123
+ main_crust_subgraph = nx.k_crust(self.H)
124
+ assert sorted(main_crust_subgraph.nodes()) == [0, 1, 3]
125
+
126
+ def test_k_crust(self):
127
+ # k = 0
128
+ k_crust_subgraph = nx.k_crust(self.H, k=2)
129
+ assert sorted(k_crust_subgraph.nodes()) == sorted(self.H.nodes())
130
+ # k=1
131
+ k_crust_subgraph = nx.k_crust(self.H, k=1)
132
+ assert sorted(k_crust_subgraph.nodes()) == [0, 1, 3]
133
+ # k=2
134
+ k_crust_subgraph = nx.k_crust(self.H, k=0)
135
+ assert sorted(k_crust_subgraph.nodes()) == [0]
136
+
137
+ def test_k_crust_multigraph(self):
138
+ core_number = nx.core_number(self.H)
139
+ H = nx.MultiGraph(self.H)
140
+ with pytest.deprecated_call():
141
+ nx.k_crust(H, k=0, core_number=core_number)
142
+
143
+ def test_main_shell(self):
144
+ main_shell_subgraph = nx.k_shell(self.H)
145
+ assert sorted(main_shell_subgraph.nodes()) == [2, 4, 5, 6]
146
+
147
+ def test_k_shell(self):
148
+ # k=0
149
+ k_shell_subgraph = nx.k_shell(self.H, k=2)
150
+ assert sorted(k_shell_subgraph.nodes()) == [2, 4, 5, 6]
151
+ # k=1
152
+ k_shell_subgraph = nx.k_shell(self.H, k=1)
153
+ assert sorted(k_shell_subgraph.nodes()) == [1, 3]
154
+ # k=2
155
+ k_shell_subgraph = nx.k_shell(self.H, k=0)
156
+ assert sorted(k_shell_subgraph.nodes()) == [0]
157
+
158
+ def test_k_shell_multigraph(self):
159
+ core_number = nx.core_number(self.H)
160
+ H = nx.MultiGraph(self.H)
161
+ with pytest.deprecated_call():
162
+ nx.k_shell(H, k=0, core_number=core_number)
163
+
164
+ def test_k_corona(self):
165
+ # k=0
166
+ k_corona_subgraph = nx.k_corona(self.H, k=2)
167
+ assert sorted(k_corona_subgraph.nodes()) == [2, 4, 5, 6]
168
+ # k=1
169
+ k_corona_subgraph = nx.k_corona(self.H, k=1)
170
+ assert sorted(k_corona_subgraph.nodes()) == [1]
171
+ # k=2
172
+ k_corona_subgraph = nx.k_corona(self.H, k=0)
173
+ assert sorted(k_corona_subgraph.nodes()) == [0]
174
+
175
+ def test_k_corona_multigraph(self):
176
+ core_number = nx.core_number(self.H)
177
+ H = nx.MultiGraph(self.H)
178
+ with pytest.deprecated_call():
179
+ nx.k_corona(H, k=0, core_number=core_number)
180
+
181
+ def test_k_truss(self):
182
+ # k=-1
183
+ k_truss_subgraph = nx.k_truss(self.G, -1)
184
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
185
+ # k=0
186
+ k_truss_subgraph = nx.k_truss(self.G, 0)
187
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
188
+ # k=1
189
+ k_truss_subgraph = nx.k_truss(self.G, 1)
190
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
191
+ # k=2
192
+ k_truss_subgraph = nx.k_truss(self.G, 2)
193
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
194
+ # k=3
195
+ k_truss_subgraph = nx.k_truss(self.G, 3)
196
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 13))
197
+
198
+ k_truss_subgraph = nx.k_truss(self.G, 4)
199
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 9))
200
+
201
+ k_truss_subgraph = nx.k_truss(self.G, 5)
202
+ assert sorted(k_truss_subgraph.nodes()) == []
203
+
204
+ def test_k_truss_digraph(self):
205
+ G = nx.complete_graph(3)
206
+ G = nx.DiGraph(G)
207
+ G.add_edge(2, 1)
208
+ with pytest.raises(
209
+ nx.NetworkXNotImplemented, match="not implemented for directed type"
210
+ ):
211
+ nx.k_truss(G, k=1)
212
+
213
+ def test_k_truss_multigraph(self):
214
+ G = nx.complete_graph(3)
215
+ G = nx.MultiGraph(G)
216
+ G.add_edge(1, 2)
217
+ with pytest.raises(
218
+ nx.NetworkXNotImplemented, match="not implemented for multigraph type"
219
+ ):
220
+ nx.k_truss(G, k=1)
221
+
222
+ def test_k_truss_self_loop(self):
223
+ G = nx.cycle_graph(3)
224
+ G.add_edge(0, 0)
225
+ with pytest.raises(
226
+ nx.NetworkXNotImplemented, match="Input graph has self loops"
227
+ ):
228
+ nx.k_truss(G, k=1)
229
+
230
+ def test_onion_layers(self):
231
+ layers = nx.onion_layers(self.G)
232
+ nodes_by_layer = [
233
+ sorted(n for n in layers if layers[n] == val) for val in range(1, 7)
234
+ ]
235
+ assert nodes_equal(nodes_by_layer[0], [21])
236
+ assert nodes_equal(nodes_by_layer[1], [17, 18, 19, 20])
237
+ assert nodes_equal(nodes_by_layer[2], [10, 12, 13, 14, 15, 16])
238
+ assert nodes_equal(nodes_by_layer[3], [9, 11])
239
+ assert nodes_equal(nodes_by_layer[4], [1, 2, 4, 5, 6, 8])
240
+ assert nodes_equal(nodes_by_layer[5], [3, 7])
241
+
242
+ def test_onion_digraph(self):
243
+ G = nx.complete_graph(3)
244
+ G = nx.DiGraph(G)
245
+ G.add_edge(2, 1)
246
+ with pytest.raises(
247
+ nx.NetworkXNotImplemented, match="not implemented for directed type"
248
+ ):
249
+ nx.onion_layers(G)
250
+
251
+ def test_onion_multigraph(self):
252
+ G = nx.complete_graph(3)
253
+ G = nx.MultiGraph(G)
254
+ G.add_edge(1, 2)
255
+ with pytest.raises(
256
+ nx.NetworkXNotImplemented, match="not implemented for multigraph type"
257
+ ):
258
+ nx.onion_layers(G)
259
+
260
+ def test_onion_self_loop(self):
261
+ G = nx.cycle_graph(3)
262
+ G.add_edge(0, 0)
263
+ with pytest.raises(
264
+ nx.NetworkXNotImplemented, match="Input graph contains self loops"
265
+ ):
266
+ nx.onion_layers(G)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_covering.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestMinEdgeCover:
7
+ """Tests for :func:`networkx.algorithms.min_edge_cover`"""
8
+
9
+ def test_empty_graph(self):
10
+ G = nx.Graph()
11
+ assert nx.min_edge_cover(G) == set()
12
+
13
+ def test_graph_with_loop(self):
14
+ G = nx.Graph()
15
+ G.add_edge(0, 0)
16
+ assert nx.min_edge_cover(G) == {(0, 0)}
17
+
18
+ def test_graph_with_isolated_v(self):
19
+ G = nx.Graph()
20
+ G.add_node(1)
21
+ with pytest.raises(
22
+ nx.NetworkXException,
23
+ match="Graph has a node with no edge incident on it, so no edge cover exists.",
24
+ ):
25
+ nx.min_edge_cover(G)
26
+
27
+ def test_graph_single_edge(self):
28
+ G = nx.Graph([(0, 1)])
29
+ assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
30
+
31
+ def test_graph_two_edge_path(self):
32
+ G = nx.path_graph(3)
33
+ min_cover = nx.min_edge_cover(G)
34
+ assert len(min_cover) == 2
35
+ for u, v in G.edges:
36
+ assert (u, v) in min_cover or (v, u) in min_cover
37
+
38
+ def test_bipartite_explicit(self):
39
+ G = nx.Graph()
40
+ G.add_nodes_from([1, 2, 3, 4], bipartite=0)
41
+ G.add_nodes_from(["a", "b", "c"], bipartite=1)
42
+ G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
43
+ # Use bipartite method by prescribing the algorithm
44
+ min_cover = nx.min_edge_cover(
45
+ G, nx.algorithms.bipartite.matching.eppstein_matching
46
+ )
47
+ assert nx.is_edge_cover(G, min_cover)
48
+ assert len(min_cover) == 8
49
+ # Use the default method which is not specialized for bipartite
50
+ min_cover2 = nx.min_edge_cover(G)
51
+ assert nx.is_edge_cover(G, min_cover2)
52
+ assert len(min_cover2) == 4
53
+
54
+ def test_complete_graph_even(self):
55
+ G = nx.complete_graph(10)
56
+ min_cover = nx.min_edge_cover(G)
57
+ assert nx.is_edge_cover(G, min_cover)
58
+ assert len(min_cover) == 5
59
+
60
+ def test_complete_graph_odd(self):
61
+ G = nx.complete_graph(11)
62
+ min_cover = nx.min_edge_cover(G)
63
+ assert nx.is_edge_cover(G, min_cover)
64
+ assert len(min_cover) == 6
65
+
66
+
67
+ class TestIsEdgeCover:
68
+ """Tests for :func:`networkx.algorithms.is_edge_cover`"""
69
+
70
+ def test_empty_graph(self):
71
+ G = nx.Graph()
72
+ assert nx.is_edge_cover(G, set())
73
+
74
+ def test_graph_with_loop(self):
75
+ G = nx.Graph()
76
+ G.add_edge(1, 1)
77
+ assert nx.is_edge_cover(G, {(1, 1)})
78
+
79
+ def test_graph_single_edge(self):
80
+ G = nx.Graph()
81
+ G.add_edge(0, 1)
82
+ assert nx.is_edge_cover(G, {(0, 0), (1, 1)})
83
+ assert nx.is_edge_cover(G, {(0, 1), (1, 0)})
84
+ assert nx.is_edge_cover(G, {(0, 1)})
85
+ assert not nx.is_edge_cover(G, {(0, 0)})
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.cuts` module."""
2
+
3
+
4
+ import networkx as nx
5
+
6
+
7
+ class TestCutSize:
8
+ """Unit tests for the :func:`~networkx.cut_size` function."""
9
+
10
+ def test_symmetric(self):
11
+ """Tests that the cut size is symmetric."""
12
+ G = nx.barbell_graph(3, 0)
13
+ S = {0, 1, 4}
14
+ T = {2, 3, 5}
15
+ assert nx.cut_size(G, S, T) == 4
16
+ assert nx.cut_size(G, T, S) == 4
17
+
18
+ def test_single_edge(self):
19
+ """Tests for a cut of a single edge."""
20
+ G = nx.barbell_graph(3, 0)
21
+ S = {0, 1, 2}
22
+ T = {3, 4, 5}
23
+ assert nx.cut_size(G, S, T) == 1
24
+ assert nx.cut_size(G, T, S) == 1
25
+
26
+ def test_directed(self):
27
+ """Tests that each directed edge is counted once in the cut."""
28
+ G = nx.barbell_graph(3, 0).to_directed()
29
+ S = {0, 1, 2}
30
+ T = {3, 4, 5}
31
+ assert nx.cut_size(G, S, T) == 2
32
+ assert nx.cut_size(G, T, S) == 2
33
+
34
+ def test_directed_symmetric(self):
35
+ """Tests that a cut in a directed graph is symmetric."""
36
+ G = nx.barbell_graph(3, 0).to_directed()
37
+ S = {0, 1, 4}
38
+ T = {2, 3, 5}
39
+ assert nx.cut_size(G, S, T) == 8
40
+ assert nx.cut_size(G, T, S) == 8
41
+
42
+ def test_multigraph(self):
43
+ """Tests that parallel edges are each counted for a cut."""
44
+ G = nx.MultiGraph(["ab", "ab"])
45
+ assert nx.cut_size(G, {"a"}, {"b"}) == 2
46
+
47
+
48
+ class TestVolume:
49
+ """Unit tests for the :func:`~networkx.volume` function."""
50
+
51
+ def test_graph(self):
52
+ G = nx.cycle_graph(4)
53
+ assert nx.volume(G, {0, 1}) == 4
54
+
55
+ def test_digraph(self):
56
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0)])
57
+ assert nx.volume(G, {0, 1}) == 2
58
+
59
+ def test_multigraph(self):
60
+ edges = list(nx.cycle_graph(4).edges())
61
+ G = nx.MultiGraph(edges * 2)
62
+ assert nx.volume(G, {0, 1}) == 8
63
+
64
+ def test_multidigraph(self):
65
+ edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
66
+ G = nx.MultiDiGraph(edges * 2)
67
+ assert nx.volume(G, {0, 1}) == 4
68
+
69
+ def test_barbell(self):
70
+ G = nx.barbell_graph(3, 0)
71
+ assert nx.volume(G, {0, 1, 2}) == 7
72
+ assert nx.volume(G, {3, 4, 5}) == 7
73
+
74
+
75
+ class TestNormalizedCutSize:
76
+ """Unit tests for the :func:`~networkx.normalized_cut_size` function."""
77
+
78
+ def test_graph(self):
79
+ G = nx.path_graph(4)
80
+ S = {1, 2}
81
+ T = set(G) - S
82
+ size = nx.normalized_cut_size(G, S, T)
83
+ # The cut looks like this: o-{-o--o-}-o
84
+ expected = 2 * ((1 / 4) + (1 / 2))
85
+ assert expected == size
86
+ # Test with no input T
87
+ assert expected == nx.normalized_cut_size(G, S)
88
+
89
+ def test_directed(self):
90
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
91
+ S = {1, 2}
92
+ T = set(G) - S
93
+ size = nx.normalized_cut_size(G, S, T)
94
+ # The cut looks like this: o-{->o-->o-}->o
95
+ expected = 2 * ((1 / 2) + (1 / 1))
96
+ assert expected == size
97
+ # Test with no input T
98
+ assert expected == nx.normalized_cut_size(G, S)
99
+
100
+
101
+ class TestConductance:
102
+ """Unit tests for the :func:`~networkx.conductance` function."""
103
+
104
+ def test_graph(self):
105
+ G = nx.barbell_graph(5, 0)
106
+ # Consider the singleton sets containing the "bridge" nodes.
107
+ # There is only one cut edge, and each set has volume five.
108
+ S = {4}
109
+ T = {5}
110
+ conductance = nx.conductance(G, S, T)
111
+ expected = 1 / 5
112
+ assert expected == conductance
113
+ # Test with no input T
114
+ G2 = nx.barbell_graph(3, 0)
115
+ # There is only one cut edge, and each set has volume seven.
116
+ S2 = {0, 1, 2}
117
+ assert nx.conductance(G2, S2) == 1 / 7
118
+
119
+
120
+ class TestEdgeExpansion:
121
+ """Unit tests for the :func:`~networkx.edge_expansion` function."""
122
+
123
+ def test_graph(self):
124
+ G = nx.barbell_graph(5, 0)
125
+ S = set(range(5))
126
+ T = set(G) - S
127
+ expansion = nx.edge_expansion(G, S, T)
128
+ expected = 1 / 5
129
+ assert expected == expansion
130
+ # Test with no input T
131
+ assert expected == nx.edge_expansion(G, S)
132
+
133
+
134
+ class TestNodeExpansion:
135
+ """Unit tests for the :func:`~networkx.node_expansion` function."""
136
+
137
+ def test_graph(self):
138
+ G = nx.path_graph(8)
139
+ S = {3, 4, 5}
140
+ expansion = nx.node_expansion(G, S)
141
+ # The neighborhood of S has cardinality five, and S has
142
+ # cardinality three.
143
+ expected = 5 / 3
144
+ assert expected == expansion
145
+
146
+
147
+ class TestBoundaryExpansion:
148
+ """Unit tests for the :func:`~networkx.boundary_expansion` function."""
149
+
150
+ def test_graph(self):
151
+ G = nx.complete_graph(10)
152
+ S = set(range(4))
153
+ expansion = nx.boundary_expansion(G, S)
154
+ # The node boundary of S has cardinality six, and S has
155
+ # cardinality three.
156
+ expected = 6 / 4
157
+ assert expected == expansion
158
+
159
+
160
+ class TestMixingExpansion:
161
+ """Unit tests for the :func:`~networkx.mixing_expansion` function."""
162
+
163
+ def test_graph(self):
164
+ G = nx.barbell_graph(5, 0)
165
+ S = set(range(5))
166
+ T = set(G) - S
167
+ expansion = nx.mixing_expansion(G, S, T)
168
+ # There is one cut edge, and the total number of edges in the
169
+ # graph is twice the total number of edges in a clique of size
170
+ # five, plus one more for the bridge.
171
+ expected = 1 / (2 * (5 * 4 + 1))
172
+ assert expected == expansion
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_cycles.py ADDED
@@ -0,0 +1,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain, islice, tee
2
+ from math import inf
3
+ from random import shuffle
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.traversal.edgedfs import FORWARD, REVERSE
9
+
10
+
11
+ def check_independent(basis):
12
+ if len(basis) == 0:
13
+ return
14
+
15
+ np = pytest.importorskip("numpy")
16
+ sp = pytest.importorskip("scipy") # Required by incidence_matrix
17
+
18
+ H = nx.Graph()
19
+ for b in basis:
20
+ nx.add_cycle(H, b)
21
+ inc = nx.incidence_matrix(H, oriented=True)
22
+ rank = np.linalg.matrix_rank(inc.toarray(), tol=None, hermitian=False)
23
+ assert inc.shape[1] - rank == len(basis)
24
+
25
+
26
+ class TestCycles:
27
+ @classmethod
28
+ def setup_class(cls):
29
+ G = nx.Graph()
30
+ nx.add_cycle(G, [0, 1, 2, 3])
31
+ nx.add_cycle(G, [0, 3, 4, 5])
32
+ nx.add_cycle(G, [0, 1, 6, 7, 8])
33
+ G.add_edge(8, 9)
34
+ cls.G = G
35
+
36
+ def is_cyclic_permutation(self, a, b):
37
+ n = len(a)
38
+ if len(b) != n:
39
+ return False
40
+ l = a + a
41
+ return any(l[i : i + n] == b for i in range(n))
42
+
43
+ def test_cycle_basis(self):
44
+ G = self.G
45
+ cy = nx.cycle_basis(G, 0)
46
+ sort_cy = sorted(sorted(c) for c in cy)
47
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
48
+ cy = nx.cycle_basis(G, 1)
49
+ sort_cy = sorted(sorted(c) for c in cy)
50
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
51
+ cy = nx.cycle_basis(G, 9)
52
+ sort_cy = sorted(sorted(c) for c in cy)
53
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
54
+ # test disconnected graphs
55
+ nx.add_cycle(G, "ABC")
56
+ cy = nx.cycle_basis(G, 9)
57
+ sort_cy = sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
58
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5], ["A", "B", "C"]]
59
+
60
+ def test_cycle_basis2(self):
61
+ with pytest.raises(nx.NetworkXNotImplemented):
62
+ G = nx.DiGraph()
63
+ cy = nx.cycle_basis(G, 0)
64
+
65
+ def test_cycle_basis3(self):
66
+ with pytest.raises(nx.NetworkXNotImplemented):
67
+ G = nx.MultiGraph()
68
+ cy = nx.cycle_basis(G, 0)
69
+
70
+ def test_cycle_basis_ordered(self):
71
+ # see gh-6654 replace sets with (ordered) dicts
72
+ G = nx.cycle_graph(5)
73
+ G.update(nx.cycle_graph(range(3, 8)))
74
+ cbG = nx.cycle_basis(G)
75
+
76
+ perm = {1: 0, 0: 1} # switch 0 and 1
77
+ H = nx.relabel_nodes(G, perm)
78
+ cbH = [[perm.get(n, n) for n in cyc] for cyc in nx.cycle_basis(H)]
79
+ assert cbG == cbH
80
+
81
+ def test_cycle_basis_self_loop(self):
82
+ """Tests the function for graphs with self loops"""
83
+ G = nx.Graph()
84
+ nx.add_cycle(G, [0, 1, 2, 3])
85
+ nx.add_cycle(G, [0, 0, 6, 2])
86
+ cy = nx.cycle_basis(G)
87
+ sort_cy = sorted(sorted(c) for c in cy)
88
+ assert sort_cy == [[0], [0, 1, 2], [0, 2, 3], [0, 2, 6]]
89
+
90
+ def test_simple_cycles(self):
91
+ edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
92
+ G = nx.DiGraph(edges)
93
+ cc = sorted(nx.simple_cycles(G))
94
+ ca = [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
95
+ assert len(cc) == len(ca)
96
+ for c in cc:
97
+ assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
98
+
99
+ def test_simple_cycles_singleton(self):
100
+ G = nx.Graph([(0, 0)]) # self-loop
101
+ assert list(nx.simple_cycles(G)) == [[0]]
102
+
103
+ def test_unsortable(self):
104
+ # this test ensures that graphs whose nodes without an intrinsic
105
+ # ordering do not cause issues
106
+ G = nx.DiGraph()
107
+ nx.add_cycle(G, ["a", 1])
108
+ c = list(nx.simple_cycles(G))
109
+ assert len(c) == 1
110
+
111
+ def test_simple_cycles_small(self):
112
+ G = nx.DiGraph()
113
+ nx.add_cycle(G, [1, 2, 3])
114
+ c = sorted(nx.simple_cycles(G))
115
+ assert len(c) == 1
116
+ assert self.is_cyclic_permutation(c[0], [1, 2, 3])
117
+ nx.add_cycle(G, [10, 20, 30])
118
+ cc = sorted(nx.simple_cycles(G))
119
+ assert len(cc) == 2
120
+ ca = [[1, 2, 3], [10, 20, 30]]
121
+ for c in cc:
122
+ assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
123
+
124
+ def test_simple_cycles_empty(self):
125
+ G = nx.DiGraph()
126
+ assert list(nx.simple_cycles(G)) == []
127
+
128
+ def worst_case_graph(self, k):
129
+ # see figure 1 in Johnson's paper
130
+ # this graph has exactly 3k simple cycles
131
+ G = nx.DiGraph()
132
+ for n in range(2, k + 2):
133
+ G.add_edge(1, n)
134
+ G.add_edge(n, k + 2)
135
+ G.add_edge(2 * k + 1, 1)
136
+ for n in range(k + 2, 2 * k + 2):
137
+ G.add_edge(n, 2 * k + 2)
138
+ G.add_edge(n, n + 1)
139
+ G.add_edge(2 * k + 3, k + 2)
140
+ for n in range(2 * k + 3, 3 * k + 3):
141
+ G.add_edge(2 * k + 2, n)
142
+ G.add_edge(n, 3 * k + 3)
143
+ G.add_edge(3 * k + 3, 2 * k + 2)
144
+ return G
145
+
146
+ def test_worst_case_graph(self):
147
+ # see figure 1 in Johnson's paper
148
+ for k in range(3, 10):
149
+ G = self.worst_case_graph(k)
150
+ l = len(list(nx.simple_cycles(G)))
151
+ assert l == 3 * k
152
+
153
+ def test_recursive_simple_and_not(self):
154
+ for k in range(2, 10):
155
+ G = self.worst_case_graph(k)
156
+ cc = sorted(nx.simple_cycles(G))
157
+ rcc = sorted(nx.recursive_simple_cycles(G))
158
+ assert len(cc) == len(rcc)
159
+ for c in cc:
160
+ assert any(self.is_cyclic_permutation(c, r) for r in rcc)
161
+ for rc in rcc:
162
+ assert any(self.is_cyclic_permutation(rc, c) for c in cc)
163
+
164
+ def test_simple_graph_with_reported_bug(self):
165
+ G = nx.DiGraph()
166
+ edges = [
167
+ (0, 2),
168
+ (0, 3),
169
+ (1, 0),
170
+ (1, 3),
171
+ (2, 1),
172
+ (2, 4),
173
+ (3, 2),
174
+ (3, 4),
175
+ (4, 0),
176
+ (4, 1),
177
+ (4, 5),
178
+ (5, 0),
179
+ (5, 1),
180
+ (5, 2),
181
+ (5, 3),
182
+ ]
183
+ G.add_edges_from(edges)
184
+ cc = sorted(nx.simple_cycles(G))
185
+ assert len(cc) == 26
186
+ rcc = sorted(nx.recursive_simple_cycles(G))
187
+ assert len(cc) == len(rcc)
188
+ for c in cc:
189
+ assert any(self.is_cyclic_permutation(c, rc) for rc in rcc)
190
+ for rc in rcc:
191
+ assert any(self.is_cyclic_permutation(rc, c) for c in cc)
192
+
193
+
194
+ def pairwise(iterable):
195
+ a, b = tee(iterable)
196
+ next(b, None)
197
+ return zip(a, b)
198
+
199
+
200
+ def cycle_edges(c):
201
+ return pairwise(chain(c, islice(c, 1)))
202
+
203
+
204
+ def directed_cycle_edgeset(c):
205
+ return frozenset(cycle_edges(c))
206
+
207
+
208
+ def undirected_cycle_edgeset(c):
209
+ if len(c) == 1:
210
+ return frozenset(cycle_edges(c))
211
+ return frozenset(map(frozenset, cycle_edges(c)))
212
+
213
+
214
+ def multigraph_cycle_edgeset(c):
215
+ if len(c) <= 2:
216
+ return frozenset(cycle_edges(c))
217
+ else:
218
+ return frozenset(map(frozenset, cycle_edges(c)))
219
+
220
+
221
+ class TestCycleEnumeration:
222
+ @staticmethod
223
+ def K(n):
224
+ return nx.complete_graph(n)
225
+
226
+ @staticmethod
227
+ def D(n):
228
+ return nx.complete_graph(n).to_directed()
229
+
230
+ @staticmethod
231
+ def edgeset_function(g):
232
+ if g.is_directed():
233
+ return directed_cycle_edgeset
234
+ elif g.is_multigraph():
235
+ return multigraph_cycle_edgeset
236
+ else:
237
+ return undirected_cycle_edgeset
238
+
239
+ def check_cycle(self, g, c, es, cache, source, original_c, length_bound, chordless):
240
+ if length_bound is not None and len(c) > length_bound:
241
+ raise RuntimeError(
242
+ f"computed cycle {original_c} exceeds length bound {length_bound}"
243
+ )
244
+ if source == "computed":
245
+ if es in cache:
246
+ raise RuntimeError(
247
+ f"computed cycle {original_c} has already been found!"
248
+ )
249
+ else:
250
+ cache[es] = tuple(original_c)
251
+ else:
252
+ if es in cache:
253
+ cache.pop(es)
254
+ else:
255
+ raise RuntimeError(f"expected cycle {original_c} was not computed")
256
+
257
+ if not all(g.has_edge(*e) for e in es):
258
+ raise RuntimeError(
259
+ f"{source} claimed cycle {original_c} is not a cycle of g"
260
+ )
261
+ if chordless and len(g.subgraph(c).edges) > len(c):
262
+ raise RuntimeError(f"{source} cycle {original_c} is not chordless")
263
+
264
+ def check_cycle_algorithm(
265
+ self,
266
+ g,
267
+ expected_cycles,
268
+ length_bound=None,
269
+ chordless=False,
270
+ algorithm=None,
271
+ ):
272
+ if algorithm is None:
273
+ algorithm = nx.chordless_cycles if chordless else nx.simple_cycles
274
+
275
+ # note: we shuffle the labels of g to rule out accidentally-correct
276
+ # behavior which occurred during the development of chordless cycle
277
+ # enumeration algorithms
278
+
279
+ relabel = list(range(len(g)))
280
+ shuffle(relabel)
281
+ label = dict(zip(g, relabel))
282
+ unlabel = dict(zip(relabel, g))
283
+ h = nx.relabel_nodes(g, label, copy=True)
284
+
285
+ edgeset = self.edgeset_function(h)
286
+
287
+ params = {}
288
+ if length_bound is not None:
289
+ params["length_bound"] = length_bound
290
+
291
+ cycle_cache = {}
292
+ for c in algorithm(h, **params):
293
+ original_c = [unlabel[x] for x in c]
294
+ es = edgeset(c)
295
+ self.check_cycle(
296
+ h, c, es, cycle_cache, "computed", original_c, length_bound, chordless
297
+ )
298
+
299
+ if isinstance(expected_cycles, int):
300
+ if len(cycle_cache) != expected_cycles:
301
+ raise RuntimeError(
302
+ f"expected {expected_cycles} cycles, got {len(cycle_cache)}"
303
+ )
304
+ return
305
+ for original_c in expected_cycles:
306
+ c = [label[x] for x in original_c]
307
+ es = edgeset(c)
308
+ self.check_cycle(
309
+ h, c, es, cycle_cache, "expected", original_c, length_bound, chordless
310
+ )
311
+
312
+ if len(cycle_cache):
313
+ for c in cycle_cache.values():
314
+ raise RuntimeError(
315
+ f"computed cycle {c} is valid but not in the expected cycle set!"
316
+ )
317
+
318
+ def check_cycle_enumeration_integer_sequence(
319
+ self,
320
+ g_family,
321
+ cycle_counts,
322
+ length_bound=None,
323
+ chordless=False,
324
+ algorithm=None,
325
+ ):
326
+ for g, num_cycles in zip(g_family, cycle_counts):
327
+ self.check_cycle_algorithm(
328
+ g,
329
+ num_cycles,
330
+ length_bound=length_bound,
331
+ chordless=chordless,
332
+ algorithm=algorithm,
333
+ )
334
+
335
+ def test_directed_chordless_cycle_digons(self):
336
+ g = nx.DiGraph()
337
+ nx.add_cycle(g, range(5))
338
+ nx.add_cycle(g, range(5)[::-1])
339
+ g.add_edge(0, 0)
340
+ expected_cycles = [(0,), (1, 2), (2, 3), (3, 4)]
341
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
342
+
343
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=2)
344
+
345
+ expected_cycles = [c for c in expected_cycles if len(c) < 2]
346
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=1)
347
+
348
+ def test_directed_chordless_cycle_undirected(self):
349
+ g = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (5, 1), (0, 2)])
350
+ expected_cycles = [(0, 2, 3, 4, 5), (1, 2, 3, 4, 5)]
351
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
352
+
353
+ g = nx.DiGraph()
354
+ nx.add_cycle(g, range(5))
355
+ nx.add_cycle(g, range(4, 9))
356
+ g.add_edge(7, 3)
357
+ expected_cycles = [(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (4, 5, 6, 7, 8)]
358
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
359
+
360
+ g.add_edge(3, 7)
361
+ expected_cycles = [(0, 1, 2, 3, 4), (3, 7), (4, 5, 6, 7, 8)]
362
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
363
+
364
+ expected_cycles = [(3, 7)]
365
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=4)
366
+
367
+ g.remove_edge(7, 3)
368
+ expected_cycles = [(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)]
369
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
370
+
371
+ g = nx.DiGraph((i, j) for i in range(10) for j in range(i))
372
+ expected_cycles = []
373
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
374
+
375
+ def test_chordless_cycles_directed(self):
376
+ G = nx.DiGraph()
377
+ nx.add_cycle(G, range(5))
378
+ nx.add_cycle(G, range(4, 12))
379
+ expected = [[*range(5)], [*range(4, 12)]]
380
+ self.check_cycle_algorithm(G, expected, chordless=True)
381
+ self.check_cycle_algorithm(
382
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
383
+ )
384
+
385
+ G.add_edge(7, 3)
386
+ expected.append([*range(3, 8)])
387
+ self.check_cycle_algorithm(G, expected, chordless=True)
388
+ self.check_cycle_algorithm(
389
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
390
+ )
391
+
392
+ G.add_edge(3, 7)
393
+ expected[-1] = [7, 3]
394
+ self.check_cycle_algorithm(G, expected, chordless=True)
395
+ self.check_cycle_algorithm(
396
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
397
+ )
398
+
399
+ expected.pop()
400
+ G.remove_edge(7, 3)
401
+ self.check_cycle_algorithm(G, expected, chordless=True)
402
+ self.check_cycle_algorithm(
403
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
404
+ )
405
+
406
+ def test_directed_chordless_cycle_diclique(self):
407
+ g_family = [self.D(n) for n in range(10)]
408
+ expected_cycles = [(n * n - n) // 2 for n in range(10)]
409
+ self.check_cycle_enumeration_integer_sequence(
410
+ g_family, expected_cycles, chordless=True
411
+ )
412
+
413
+ expected_cycles = [(n * n - n) // 2 for n in range(10)]
414
+ self.check_cycle_enumeration_integer_sequence(
415
+ g_family, expected_cycles, length_bound=2
416
+ )
417
+
418
+ def test_directed_chordless_loop_blockade(self):
419
+ g = nx.DiGraph((i, i) for i in range(10))
420
+ nx.add_cycle(g, range(10))
421
+ expected_cycles = [(i,) for i in range(10)]
422
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
423
+
424
+ self.check_cycle_algorithm(g, expected_cycles, length_bound=1)
425
+
426
+ g = nx.MultiDiGraph(g)
427
+ g.add_edges_from((i, i) for i in range(0, 10, 2))
428
+ expected_cycles = [(i,) for i in range(1, 10, 2)]
429
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
430
+
431
+ def test_simple_cycles_notable_clique_sequences(self):
432
+ # A000292: Number of labeled graphs on n+3 nodes that are triangles.
433
+ g_family = [self.K(n) for n in range(2, 12)]
434
+ expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220]
435
+ self.check_cycle_enumeration_integer_sequence(
436
+ g_family, expected, length_bound=3
437
+ )
438
+
439
+ def triangles(g, **kwargs):
440
+ yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 3)
441
+
442
+ # directed complete graphs have twice as many triangles thanks to reversal
443
+ g_family = [self.D(n) for n in range(2, 12)]
444
+ expected = [2 * e for e in expected]
445
+ self.check_cycle_enumeration_integer_sequence(
446
+ g_family, expected, length_bound=3, algorithm=triangles
447
+ )
448
+
449
+ def four_cycles(g, **kwargs):
450
+ yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 4)
451
+
452
+ # A050534: the number of 4-cycles in the complete graph K_{n+1}
453
+ expected = [0, 0, 0, 3, 15, 45, 105, 210, 378, 630, 990]
454
+ g_family = [self.K(n) for n in range(1, 12)]
455
+ self.check_cycle_enumeration_integer_sequence(
456
+ g_family, expected, length_bound=4, algorithm=four_cycles
457
+ )
458
+
459
+ # directed complete graphs have twice as many 4-cycles thanks to reversal
460
+ expected = [2 * e for e in expected]
461
+ g_family = [self.D(n) for n in range(1, 15)]
462
+ self.check_cycle_enumeration_integer_sequence(
463
+ g_family, expected, length_bound=4, algorithm=four_cycles
464
+ )
465
+
466
+ # A006231: the number of elementary circuits in a complete directed graph with n nodes
467
+ expected = [0, 1, 5, 20, 84, 409, 2365]
468
+ g_family = [self.D(n) for n in range(1, 8)]
469
+ self.check_cycle_enumeration_integer_sequence(g_family, expected)
470
+
471
+ # A002807: Number of cycles in the complete graph on n nodes K_{n}.
472
+ expected = [0, 0, 0, 1, 7, 37, 197, 1172]
473
+ g_family = [self.K(n) for n in range(8)]
474
+ self.check_cycle_enumeration_integer_sequence(g_family, expected)
475
+
476
+ def test_directed_chordless_cycle_parallel_multiedges(self):
477
+ g = nx.MultiGraph()
478
+
479
+ nx.add_cycle(g, range(5))
480
+ expected = [[*range(5)]]
481
+ self.check_cycle_algorithm(g, expected, chordless=True)
482
+
483
+ nx.add_cycle(g, range(5))
484
+ expected = [*cycle_edges(range(5))]
485
+ self.check_cycle_algorithm(g, expected, chordless=True)
486
+
487
+ nx.add_cycle(g, range(5))
488
+ expected = []
489
+ self.check_cycle_algorithm(g, expected, chordless=True)
490
+
491
+ g = nx.MultiDiGraph()
492
+
493
+ nx.add_cycle(g, range(5))
494
+ expected = [[*range(5)]]
495
+ self.check_cycle_algorithm(g, expected, chordless=True)
496
+
497
+ nx.add_cycle(g, range(5))
498
+ self.check_cycle_algorithm(g, [], chordless=True)
499
+
500
+ nx.add_cycle(g, range(5))
501
+ self.check_cycle_algorithm(g, [], chordless=True)
502
+
503
+ g = nx.MultiDiGraph()
504
+
505
+ nx.add_cycle(g, range(5))
506
+ nx.add_cycle(g, range(5)[::-1])
507
+ expected = [*cycle_edges(range(5))]
508
+ self.check_cycle_algorithm(g, expected, chordless=True)
509
+
510
+ nx.add_cycle(g, range(5))
511
+ self.check_cycle_algorithm(g, [], chordless=True)
512
+
513
+ def test_chordless_cycles_graph(self):
514
+ G = nx.Graph()
515
+ nx.add_cycle(G, range(5))
516
+ nx.add_cycle(G, range(4, 12))
517
+ expected = [[*range(5)], [*range(4, 12)]]
518
+ self.check_cycle_algorithm(G, expected, chordless=True)
519
+ self.check_cycle_algorithm(
520
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
521
+ )
522
+
523
+ G.add_edge(7, 3)
524
+ expected.append([*range(3, 8)])
525
+ expected.append([4, 3, 7, 8, 9, 10, 11])
526
+ self.check_cycle_algorithm(G, expected, chordless=True)
527
+ self.check_cycle_algorithm(
528
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
529
+ )
530
+
531
+ def test_chordless_cycles_giant_hamiltonian(self):
532
+ # ... o - e - o - e - o ... # o = odd, e = even
533
+ # ... ---/ \-----/ \--- ... # <-- "long" edges
534
+ #
535
+ # each long edge belongs to exactly one triangle, and one giant cycle
536
+ # of length n/2. The remaining edges each belong to a triangle
537
+
538
+ n = 1000
539
+ assert n % 2 == 0
540
+ G = nx.Graph()
541
+ for v in range(n):
542
+ if not v % 2:
543
+ G.add_edge(v, (v + 2) % n)
544
+ G.add_edge(v, (v + 1) % n)
545
+
546
+ expected = [[*range(0, n, 2)]] + [
547
+ [x % n for x in range(i, i + 3)] for i in range(0, n, 2)
548
+ ]
549
+ self.check_cycle_algorithm(G, expected, chordless=True)
550
+ self.check_cycle_algorithm(
551
+ G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
552
+ )
553
+
554
+ # ... o -> e -> o -> e -> o ... # o = odd, e = even
555
+ # ... <---/ \---<---/ \---< ... # <-- "long" edges
556
+ #
557
+ # this time, we orient the short and long edges in opposition
558
+ # the cycle structure of this graph is the same, but we need to reverse
559
+ # the long one in our representation. Also, we need to drop the size
560
+ # because our partitioning algorithm uses strongly connected components
561
+ # instead of separating graphs by their strong articulation points
562
+
563
+ n = 100
564
+ assert n % 2 == 0
565
+ G = nx.DiGraph()
566
+ for v in range(n):
567
+ G.add_edge(v, (v + 1) % n)
568
+ if not v % 2:
569
+ G.add_edge((v + 2) % n, v)
570
+
571
+ expected = [[*range(n - 2, -2, -2)]] + [
572
+ [x % n for x in range(i, i + 3)] for i in range(0, n, 2)
573
+ ]
574
+ self.check_cycle_algorithm(G, expected, chordless=True)
575
+ self.check_cycle_algorithm(
576
+ G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
577
+ )
578
+
579
+ def test_simple_cycles_acyclic_tournament(self):
580
+ n = 10
581
+ G = nx.DiGraph((x, y) for x in range(n) for y in range(x))
582
+ self.check_cycle_algorithm(G, [])
583
+ self.check_cycle_algorithm(G, [], chordless=True)
584
+
585
+ for k in range(n + 1):
586
+ self.check_cycle_algorithm(G, [], length_bound=k)
587
+ self.check_cycle_algorithm(G, [], length_bound=k, chordless=True)
588
+
589
+ def test_simple_cycles_graph(self):
590
+ testG = nx.cycle_graph(8)
591
+ cyc1 = tuple(range(8))
592
+ self.check_cycle_algorithm(testG, [cyc1])
593
+
594
+ testG.add_edge(4, -1)
595
+ nx.add_path(testG, [3, -2, -3, -4])
596
+ self.check_cycle_algorithm(testG, [cyc1])
597
+
598
+ testG.update(nx.cycle_graph(range(8, 16)))
599
+ cyc2 = tuple(range(8, 16))
600
+ self.check_cycle_algorithm(testG, [cyc1, cyc2])
601
+
602
+ testG.update(nx.cycle_graph(range(4, 12)))
603
+ cyc3 = tuple(range(4, 12))
604
+ expected = {
605
+ (0, 1, 2, 3, 4, 5, 6, 7), # cyc1
606
+ (8, 9, 10, 11, 12, 13, 14, 15), # cyc2
607
+ (4, 5, 6, 7, 8, 9, 10, 11), # cyc3
608
+ (4, 5, 6, 7, 8, 15, 14, 13, 12, 11), # cyc2 + cyc3
609
+ (0, 1, 2, 3, 4, 11, 10, 9, 8, 7), # cyc1 + cyc3
610
+ (0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 8, 7), # cyc1 + cyc2 + cyc3
611
+ }
612
+ self.check_cycle_algorithm(testG, expected)
613
+ assert len(expected) == (2**3 - 1) - 1 # 1 disjoint comb: cyc1 + cyc2
614
+
615
+ # Basis size = 5 (2 loops overlapping gives 5 small loops
616
+ # E
617
+ # / \ Note: A-F = 10-15
618
+ # 1-2-3-4-5
619
+ # / | | \ cyc1=012DAB -- left
620
+ # 0 D F 6 cyc2=234E -- top
621
+ # \ | | / cyc3=45678F -- right
622
+ # B-A-9-8-7 cyc4=89AC -- bottom
623
+ # \ / cyc5=234F89AD -- middle
624
+ # C
625
+ #
626
+ # combinations of 5 basis elements: 2^5 - 1 (one includes no cycles)
627
+ #
628
+ # disjoint combs: (11 total) not simple cycles
629
+ # Any pair not including cyc5 => choose(4, 2) = 6
630
+ # Any triple not including cyc5 => choose(4, 3) = 4
631
+ # Any quad not including cyc5 => choose(4, 4) = 1
632
+ #
633
+ # we expect 31 - 11 = 20 simple cycles
634
+ #
635
+ testG = nx.cycle_graph(12)
636
+ testG.update(nx.cycle_graph([12, 10, 13, 2, 14, 4, 15, 8]).edges)
637
+ expected = (2**5 - 1) - 11 # 11 disjoint combinations
638
+ self.check_cycle_algorithm(testG, expected)
639
+
640
+ def test_simple_cycles_bounded(self):
641
+ # iteratively construct a cluster of nested cycles running in the same direction
642
+ # there should be one cycle of every length
643
+ d = nx.DiGraph()
644
+ expected = []
645
+ for n in range(10):
646
+ nx.add_cycle(d, range(n))
647
+ expected.append(n)
648
+ for k, e in enumerate(expected):
649
+ self.check_cycle_algorithm(d, e, length_bound=k)
650
+
651
+ # iteratively construct a path of undirected cycles, connected at articulation
652
+ # points. there should be one cycle of every length except 2: no digons
653
+ g = nx.Graph()
654
+ top = 0
655
+ expected = []
656
+ for n in range(10):
657
+ expected.append(n if n < 2 else n - 1)
658
+ if n == 2:
659
+ # no digons in undirected graphs
660
+ continue
661
+ nx.add_cycle(g, range(top, top + n))
662
+ top += n
663
+ for k, e in enumerate(expected):
664
+ self.check_cycle_algorithm(g, e, length_bound=k)
665
+
666
+ def test_simple_cycles_bound_corner_cases(self):
667
+ G = nx.cycle_graph(4)
668
+ DG = nx.cycle_graph(4, create_using=nx.DiGraph)
669
+ assert list(nx.simple_cycles(G, length_bound=0)) == []
670
+ assert list(nx.simple_cycles(DG, length_bound=0)) == []
671
+ assert list(nx.chordless_cycles(G, length_bound=0)) == []
672
+ assert list(nx.chordless_cycles(DG, length_bound=0)) == []
673
+
674
+ def test_simple_cycles_bound_error(self):
675
+ with pytest.raises(ValueError):
676
+ G = nx.DiGraph()
677
+ for c in nx.simple_cycles(G, -1):
678
+ assert False
679
+
680
+ with pytest.raises(ValueError):
681
+ G = nx.Graph()
682
+ for c in nx.simple_cycles(G, -1):
683
+ assert False
684
+
685
+ with pytest.raises(ValueError):
686
+ G = nx.Graph()
687
+ for c in nx.chordless_cycles(G, -1):
688
+ assert False
689
+
690
+ with pytest.raises(ValueError):
691
+ G = nx.DiGraph()
692
+ for c in nx.chordless_cycles(G, -1):
693
+ assert False
694
+
695
+ def test_chordless_cycles_clique(self):
696
+ g_family = [self.K(n) for n in range(2, 15)]
697
+ expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364]
698
+ self.check_cycle_enumeration_integer_sequence(
699
+ g_family, expected, chordless=True
700
+ )
701
+
702
+ # directed cliques have as many digons as undirected graphs have edges
703
+ expected = [(n * n - n) // 2 for n in range(15)]
704
+ g_family = [self.D(n) for n in range(15)]
705
+ self.check_cycle_enumeration_integer_sequence(
706
+ g_family, expected, chordless=True
707
+ )
708
+
709
+
710
+ # These tests might fail with hash randomization since they depend on
711
+ # edge_dfs. For more information, see the comments in:
712
+ # networkx/algorithms/traversal/tests/test_edgedfs.py
713
+
714
+
715
+ class TestFindCycle:
716
+ @classmethod
717
+ def setup_class(cls):
718
+ cls.nodes = [0, 1, 2, 3]
719
+ cls.edges = [(-1, 0), (0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
720
+
721
+ def test_graph_nocycle(self):
722
+ G = nx.Graph(self.edges)
723
+ pytest.raises(nx.exception.NetworkXNoCycle, nx.find_cycle, G, self.nodes)
724
+
725
+ def test_graph_cycle(self):
726
+ G = nx.Graph(self.edges)
727
+ G.add_edge(2, 0)
728
+ x = list(nx.find_cycle(G, self.nodes))
729
+ x_ = [(0, 1), (1, 2), (2, 0)]
730
+ assert x == x_
731
+
732
+ def test_graph_orientation_none(self):
733
+ G = nx.Graph(self.edges)
734
+ G.add_edge(2, 0)
735
+ x = list(nx.find_cycle(G, self.nodes, orientation=None))
736
+ x_ = [(0, 1), (1, 2), (2, 0)]
737
+ assert x == x_
738
+
739
+ def test_graph_orientation_original(self):
740
+ G = nx.Graph(self.edges)
741
+ G.add_edge(2, 0)
742
+ x = list(nx.find_cycle(G, self.nodes, orientation="original"))
743
+ x_ = [(0, 1, FORWARD), (1, 2, FORWARD), (2, 0, FORWARD)]
744
+ assert x == x_
745
+
746
+ def test_digraph(self):
747
+ G = nx.DiGraph(self.edges)
748
+ x = list(nx.find_cycle(G, self.nodes))
749
+ x_ = [(0, 1), (1, 0)]
750
+ assert x == x_
751
+
752
+ def test_digraph_orientation_none(self):
753
+ G = nx.DiGraph(self.edges)
754
+ x = list(nx.find_cycle(G, self.nodes, orientation=None))
755
+ x_ = [(0, 1), (1, 0)]
756
+ assert x == x_
757
+
758
+ def test_digraph_orientation_original(self):
759
+ G = nx.DiGraph(self.edges)
760
+ x = list(nx.find_cycle(G, self.nodes, orientation="original"))
761
+ x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
762
+ assert x == x_
763
+
764
+ def test_multigraph(self):
765
+ G = nx.MultiGraph(self.edges)
766
+ x = list(nx.find_cycle(G, self.nodes))
767
+ x_ = [(0, 1, 0), (1, 0, 1)] # or (1, 0, 2)
768
+ # Hash randomization...could be any edge.
769
+ assert x[0] == x_[0]
770
+ assert x[1][:2] == x_[1][:2]
771
+
772
+ def test_multidigraph(self):
773
+ G = nx.MultiDiGraph(self.edges)
774
+ x = list(nx.find_cycle(G, self.nodes))
775
+ x_ = [(0, 1, 0), (1, 0, 0)] # (1, 0, 1)
776
+ assert x[0] == x_[0]
777
+ assert x[1][:2] == x_[1][:2]
778
+
779
+ def test_digraph_ignore(self):
780
+ G = nx.DiGraph(self.edges)
781
+ x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
782
+ x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
783
+ assert x == x_
784
+
785
+ def test_digraph_reverse(self):
786
+ G = nx.DiGraph(self.edges)
787
+ x = list(nx.find_cycle(G, self.nodes, orientation="reverse"))
788
+ x_ = [(1, 0, REVERSE), (0, 1, REVERSE)]
789
+ assert x == x_
790
+
791
+ def test_multidigraph_ignore(self):
792
+ G = nx.MultiDiGraph(self.edges)
793
+ x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
794
+ x_ = [(0, 1, 0, FORWARD), (1, 0, 0, FORWARD)] # or (1, 0, 1, 1)
795
+ assert x[0] == x_[0]
796
+ assert x[1][:2] == x_[1][:2]
797
+ assert x[1][3] == x_[1][3]
798
+
799
+ def test_multidigraph_ignore2(self):
800
+ # Loop traversed an edge while ignoring its orientation.
801
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (1, 2)])
802
+ x = list(nx.find_cycle(G, [0, 1, 2], orientation="ignore"))
803
+ x_ = [(1, 2, 0, FORWARD), (1, 2, 1, REVERSE)]
804
+ assert x == x_
805
+
806
+ def test_multidigraph_original(self):
807
+ # Node 2 doesn't need to be searched again from visited from 4.
808
+ # The goal here is to cover the case when 2 to be researched from 4,
809
+ # when 4 is visited from the first time (so we must make sure that 4
810
+ # is not visited from 2, and hence, we respect the edge orientation).
811
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 3), (4, 2)])
812
+ pytest.raises(
813
+ nx.exception.NetworkXNoCycle,
814
+ nx.find_cycle,
815
+ G,
816
+ [0, 1, 2, 3, 4],
817
+ orientation="original",
818
+ )
819
+
820
+ def test_dag(self):
821
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
822
+ pytest.raises(
823
+ nx.exception.NetworkXNoCycle, nx.find_cycle, G, orientation="original"
824
+ )
825
+ x = list(nx.find_cycle(G, orientation="ignore"))
826
+ assert x == [(0, 1, FORWARD), (1, 2, FORWARD), (0, 2, REVERSE)]
827
+
828
+ def test_prev_explored(self):
829
+ # https://github.com/networkx/networkx/issues/2323
830
+
831
+ G = nx.DiGraph()
832
+ G.add_edges_from([(1, 0), (2, 0), (1, 2), (2, 1)])
833
+ pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
834
+ x = list(nx.find_cycle(G, 1))
835
+ x_ = [(1, 2), (2, 1)]
836
+ assert x == x_
837
+
838
+ x = list(nx.find_cycle(G, 2))
839
+ x_ = [(2, 1), (1, 2)]
840
+ assert x == x_
841
+
842
+ x = list(nx.find_cycle(G))
843
+ x_ = [(1, 2), (2, 1)]
844
+ assert x == x_
845
+
846
+ def test_no_cycle(self):
847
+ # https://github.com/networkx/networkx/issues/2439
848
+
849
+ G = nx.DiGraph()
850
+ G.add_edges_from([(1, 2), (2, 0), (3, 1), (3, 2)])
851
+ pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
852
+ pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G)
853
+
854
+
855
+ def assert_basis_equal(a, b):
856
+ assert sorted(a) == sorted(b)
857
+
858
+
859
+ class TestMinimumCycleBasis:
860
+ @classmethod
861
+ def setup_class(cls):
862
+ T = nx.Graph()
863
+ nx.add_cycle(T, [1, 2, 3, 4], weight=1)
864
+ T.add_edge(2, 4, weight=5)
865
+ cls.diamond_graph = T
866
+
867
+ def test_unweighted_diamond(self):
868
+ mcb = nx.minimum_cycle_basis(self.diamond_graph)
869
+ assert_basis_equal(mcb, [[2, 4, 1], [3, 4, 2]])
870
+
871
+ def test_weighted_diamond(self):
872
+ mcb = nx.minimum_cycle_basis(self.diamond_graph, weight="weight")
873
+ assert_basis_equal(mcb, [[2, 4, 1], [4, 3, 2, 1]])
874
+
875
+ def test_dimensionality(self):
876
+ # checks |MCB|=|E|-|V|+|NC|
877
+ ntrial = 10
878
+ for seed in range(1234, 1234 + ntrial):
879
+ rg = nx.erdos_renyi_graph(10, 0.3, seed=seed)
880
+ nnodes = rg.number_of_nodes()
881
+ nedges = rg.number_of_edges()
882
+ ncomp = nx.number_connected_components(rg)
883
+
884
+ mcb = nx.minimum_cycle_basis(rg)
885
+ assert len(mcb) == nedges - nnodes + ncomp
886
+ check_independent(mcb)
887
+
888
+ def test_complete_graph(self):
889
+ cg = nx.complete_graph(5)
890
+ mcb = nx.minimum_cycle_basis(cg)
891
+ assert all(len(cycle) == 3 for cycle in mcb)
892
+ check_independent(mcb)
893
+
894
+ def test_tree_graph(self):
895
+ tg = nx.balanced_tree(3, 3)
896
+ assert not nx.minimum_cycle_basis(tg)
897
+
898
+ def test_petersen_graph(self):
899
+ G = nx.petersen_graph()
900
+ mcb = list(nx.minimum_cycle_basis(G))
901
+ expected = [
902
+ [4, 9, 7, 5, 0],
903
+ [1, 2, 3, 4, 0],
904
+ [1, 6, 8, 5, 0],
905
+ [4, 3, 8, 5, 0],
906
+ [1, 6, 9, 4, 0],
907
+ [1, 2, 7, 5, 0],
908
+ ]
909
+ assert len(mcb) == len(expected)
910
+ assert all(c in expected for c in mcb)
911
+
912
+ # check that order of the nodes is a path
913
+ for c in mcb:
914
+ assert all(G.has_edge(u, v) for u, v in nx.utils.pairwise(c, cyclic=True))
915
+ # check independence of the basis
916
+ check_independent(mcb)
917
+
918
+ def test_gh6787_variable_weighted_complete_graph(self):
919
+ N = 8
920
+ cg = nx.complete_graph(N)
921
+ cg.add_weighted_edges_from([(u, v, 9) for u, v in cg.edges])
922
+ cg.add_weighted_edges_from([(u, v, 1) for u, v in nx.cycle_graph(N).edges])
923
+ mcb = nx.minimum_cycle_basis(cg, weight="weight")
924
+ check_independent(mcb)
925
+
926
+ def test_gh6787_and_edge_attribute_names(self):
927
+ G = nx.cycle_graph(4)
928
+ G.add_weighted_edges_from([(0, 2, 10), (1, 3, 10)], weight="dist")
929
+ expected = [[1, 3, 0], [3, 2, 1, 0], [1, 2, 0]]
930
+ mcb = list(nx.minimum_cycle_basis(G, weight="dist"))
931
+ assert len(mcb) == len(expected)
932
+ assert all(c in expected for c in mcb)
933
+
934
+ # test not using a weight with weight attributes
935
+ expected = [[1, 3, 0], [1, 2, 0], [3, 2, 0]]
936
+ mcb = list(nx.minimum_cycle_basis(G))
937
+ assert len(mcb) == len(expected)
938
+ assert all(c in expected for c in mcb)
939
+
940
+
941
+ class TestGirth:
942
+ @pytest.mark.parametrize(
943
+ ("G", "expected"),
944
+ (
945
+ (nx.chvatal_graph(), 4),
946
+ (nx.tutte_graph(), 4),
947
+ (nx.petersen_graph(), 5),
948
+ (nx.heawood_graph(), 6),
949
+ (nx.pappus_graph(), 6),
950
+ (nx.random_tree(10, seed=42), inf),
951
+ (nx.empty_graph(10), inf),
952
+ (nx.Graph(chain(cycle_edges(range(5)), cycle_edges(range(6, 10)))), 4),
953
+ (
954
+ nx.Graph(
955
+ [
956
+ (0, 6),
957
+ (0, 8),
958
+ (0, 9),
959
+ (1, 8),
960
+ (2, 8),
961
+ (2, 9),
962
+ (4, 9),
963
+ (5, 9),
964
+ (6, 8),
965
+ (6, 9),
966
+ (7, 8),
967
+ ]
968
+ ),
969
+ 3,
970
+ ),
971
+ ),
972
+ )
973
+ def test_girth(self, G, expected):
974
+ assert nx.girth(G) == expected
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_d_separation.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def path_graph():
9
+ """Return a path graph of length three."""
10
+ G = nx.path_graph(3, create_using=nx.DiGraph)
11
+ G.graph["name"] = "path"
12
+ nx.freeze(G)
13
+ return G
14
+
15
+
16
+ def fork_graph():
17
+ """Return a three node fork graph."""
18
+ G = nx.DiGraph(name="fork")
19
+ G.add_edges_from([(0, 1), (0, 2)])
20
+ nx.freeze(G)
21
+ return G
22
+
23
+
24
+ def collider_graph():
25
+ """Return a collider/v-structure graph with three nodes."""
26
+ G = nx.DiGraph(name="collider")
27
+ G.add_edges_from([(0, 2), (1, 2)])
28
+ nx.freeze(G)
29
+ return G
30
+
31
+
32
+ def naive_bayes_graph():
33
+ """Return a simply Naive Bayes PGM graph."""
34
+ G = nx.DiGraph(name="naive_bayes")
35
+ G.add_edges_from([(0, 1), (0, 2), (0, 3), (0, 4)])
36
+ nx.freeze(G)
37
+ return G
38
+
39
+
40
+ def asia_graph():
41
+ """Return the 'Asia' PGM graph."""
42
+ G = nx.DiGraph(name="asia")
43
+ G.add_edges_from(
44
+ [
45
+ ("asia", "tuberculosis"),
46
+ ("smoking", "cancer"),
47
+ ("smoking", "bronchitis"),
48
+ ("tuberculosis", "either"),
49
+ ("cancer", "either"),
50
+ ("either", "xray"),
51
+ ("either", "dyspnea"),
52
+ ("bronchitis", "dyspnea"),
53
+ ]
54
+ )
55
+ nx.freeze(G)
56
+ return G
57
+
58
+
59
+ @pytest.fixture(name="path_graph")
60
+ def path_graph_fixture():
61
+ return path_graph()
62
+
63
+
64
+ @pytest.fixture(name="fork_graph")
65
+ def fork_graph_fixture():
66
+ return fork_graph()
67
+
68
+
69
+ @pytest.fixture(name="collider_graph")
70
+ def collider_graph_fixture():
71
+ return collider_graph()
72
+
73
+
74
+ @pytest.fixture(name="naive_bayes_graph")
75
+ def naive_bayes_graph_fixture():
76
+ return naive_bayes_graph()
77
+
78
+
79
+ @pytest.fixture(name="asia_graph")
80
+ def asia_graph_fixture():
81
+ return asia_graph()
82
+
83
+
84
+ @pytest.fixture()
85
+ def large_collider_graph():
86
+ edge_list = [("A", "B"), ("C", "B"), ("B", "D"), ("D", "E"), ("B", "F"), ("G", "E")]
87
+ G = nx.DiGraph(edge_list)
88
+ return G
89
+
90
+
91
+ @pytest.fixture()
92
+ def chain_and_fork_graph():
93
+ edge_list = [("A", "B"), ("B", "C"), ("B", "D"), ("D", "C")]
94
+ G = nx.DiGraph(edge_list)
95
+ return G
96
+
97
+
98
+ @pytest.fixture()
99
+ def no_separating_set_graph():
100
+ edge_list = [("A", "B")]
101
+ G = nx.DiGraph(edge_list)
102
+ return G
103
+
104
+
105
+ @pytest.fixture()
106
+ def large_no_separating_set_graph():
107
+ edge_list = [("A", "B"), ("C", "A"), ("C", "B")]
108
+ G = nx.DiGraph(edge_list)
109
+ return G
110
+
111
+
112
+ @pytest.fixture()
113
+ def collider_trek_graph():
114
+ edge_list = [("A", "B"), ("C", "B"), ("C", "D")]
115
+ G = nx.DiGraph(edge_list)
116
+ return G
117
+
118
+
119
+ @pytest.mark.parametrize(
120
+ "graph",
121
+ [path_graph(), fork_graph(), collider_graph(), naive_bayes_graph(), asia_graph()],
122
+ )
123
+ def test_markov_condition(graph):
124
+ """Test that the Markov condition holds for each PGM graph."""
125
+ for node in graph.nodes:
126
+ parents = set(graph.predecessors(node))
127
+ non_descendants = graph.nodes - nx.descendants(graph, node) - {node} - parents
128
+ assert nx.is_d_separator(graph, {node}, non_descendants, parents)
129
+
130
+
131
+ def test_path_graph_dsep(path_graph):
132
+ """Example-based test of d-separation for path_graph."""
133
+ assert nx.is_d_separator(path_graph, {0}, {2}, {1})
134
+ assert not nx.is_d_separator(path_graph, {0}, {2}, set())
135
+
136
+
137
+ def test_fork_graph_dsep(fork_graph):
138
+ """Example-based test of d-separation for fork_graph."""
139
+ assert nx.is_d_separator(fork_graph, {1}, {2}, {0})
140
+ assert not nx.is_d_separator(fork_graph, {1}, {2}, set())
141
+
142
+
143
+ def test_collider_graph_dsep(collider_graph):
144
+ """Example-based test of d-separation for collider_graph."""
145
+ assert nx.is_d_separator(collider_graph, {0}, {1}, set())
146
+ assert not nx.is_d_separator(collider_graph, {0}, {1}, {2})
147
+
148
+
149
+ def test_naive_bayes_dsep(naive_bayes_graph):
150
+ """Example-based test of d-separation for naive_bayes_graph."""
151
+ for u, v in combinations(range(1, 5), 2):
152
+ assert nx.is_d_separator(naive_bayes_graph, {u}, {v}, {0})
153
+ assert not nx.is_d_separator(naive_bayes_graph, {u}, {v}, set())
154
+
155
+
156
+ def test_asia_graph_dsep(asia_graph):
157
+ """Example-based test of d-separation for asia_graph."""
158
+ assert nx.is_d_separator(
159
+ asia_graph, {"asia", "smoking"}, {"dyspnea", "xray"}, {"bronchitis", "either"}
160
+ )
161
+ assert nx.is_d_separator(
162
+ asia_graph, {"tuberculosis", "cancer"}, {"bronchitis"}, {"smoking", "xray"}
163
+ )
164
+
165
+
166
+ def test_undirected_graphs_are_not_supported():
167
+ """
168
+ Test that undirected graphs are not supported.
169
+
170
+ d-separation and its related algorithms do not apply in
171
+ the case of undirected graphs.
172
+ """
173
+ g = nx.path_graph(3, nx.Graph)
174
+ with pytest.raises(nx.NetworkXNotImplemented):
175
+ nx.is_d_separator(g, {0}, {1}, {2})
176
+ with pytest.raises(nx.NetworkXNotImplemented):
177
+ nx.is_minimal_d_separator(g, {0}, {1}, {2})
178
+ with pytest.raises(nx.NetworkXNotImplemented):
179
+ nx.find_minimal_d_separator(g, {0}, {1})
180
+
181
+
182
+ def test_cyclic_graphs_raise_error():
183
+ """
184
+ Test that cycle graphs should cause erroring.
185
+
186
+ This is because PGMs assume a directed acyclic graph.
187
+ """
188
+ g = nx.cycle_graph(3, nx.DiGraph)
189
+ with pytest.raises(nx.NetworkXError):
190
+ nx.is_d_separator(g, {0}, {1}, {2})
191
+ with pytest.raises(nx.NetworkXError):
192
+ nx.find_minimal_d_separator(g, {0}, {1})
193
+ with pytest.raises(nx.NetworkXError):
194
+ nx.is_minimal_d_separator(g, {0}, {1}, {2})
195
+
196
+
197
+ def test_invalid_nodes_raise_error(asia_graph):
198
+ """
199
+ Test that graphs that have invalid nodes passed in raise errors.
200
+ """
201
+ # Check both set and node arguments
202
+ with pytest.raises(nx.NodeNotFound):
203
+ nx.is_d_separator(asia_graph, {0}, {1}, {2})
204
+ with pytest.raises(nx.NodeNotFound):
205
+ nx.is_d_separator(asia_graph, 0, 1, 2)
206
+ with pytest.raises(nx.NodeNotFound):
207
+ nx.is_minimal_d_separator(asia_graph, {0}, {1}, {2})
208
+ with pytest.raises(nx.NodeNotFound):
209
+ nx.is_minimal_d_separator(asia_graph, 0, 1, 2)
210
+ with pytest.raises(nx.NodeNotFound):
211
+ nx.find_minimal_d_separator(asia_graph, {0}, {1})
212
+ with pytest.raises(nx.NodeNotFound):
213
+ nx.find_minimal_d_separator(asia_graph, 0, 1)
214
+
215
+
216
+ def test_nondisjoint_node_sets_raise_error(collider_graph):
217
+ """
218
+ Test that error is raised when node sets aren't disjoint.
219
+ """
220
+ with pytest.raises(nx.NetworkXError):
221
+ nx.is_d_separator(collider_graph, 0, 1, 0)
222
+ with pytest.raises(nx.NetworkXError):
223
+ nx.is_d_separator(collider_graph, 0, 2, 0)
224
+ with pytest.raises(nx.NetworkXError):
225
+ nx.is_d_separator(collider_graph, 0, 0, 1)
226
+ with pytest.raises(nx.NetworkXError):
227
+ nx.is_d_separator(collider_graph, 1, 0, 0)
228
+ with pytest.raises(nx.NetworkXError):
229
+ nx.find_minimal_d_separator(collider_graph, 0, 0)
230
+ with pytest.raises(nx.NetworkXError):
231
+ nx.find_minimal_d_separator(collider_graph, 0, 1, included=0)
232
+ with pytest.raises(nx.NetworkXError):
233
+ nx.find_minimal_d_separator(collider_graph, 1, 0, included=0)
234
+ with pytest.raises(nx.NetworkXError):
235
+ nx.is_minimal_d_separator(collider_graph, 0, 0, set())
236
+ with pytest.raises(nx.NetworkXError):
237
+ nx.is_minimal_d_separator(collider_graph, 0, 1, set(), included=0)
238
+ with pytest.raises(nx.NetworkXError):
239
+ nx.is_minimal_d_separator(collider_graph, 1, 0, set(), included=0)
240
+
241
+
242
+ def test_is_minimal_d_separator(
243
+ large_collider_graph,
244
+ chain_and_fork_graph,
245
+ no_separating_set_graph,
246
+ large_no_separating_set_graph,
247
+ collider_trek_graph,
248
+ ):
249
+ # Case 1:
250
+ # create a graph A -> B <- C
251
+ # B -> D -> E;
252
+ # B -> F;
253
+ # G -> E;
254
+ assert not nx.is_d_separator(large_collider_graph, {"B"}, {"E"}, set())
255
+
256
+ # minimal set of the corresponding graph
257
+ # for B and E should be (D,)
258
+ Zmin = nx.find_minimal_d_separator(large_collider_graph, "B", "E")
259
+ # check that the minimal d-separator is a d-separating set
260
+ assert nx.is_d_separator(large_collider_graph, "B", "E", Zmin)
261
+ # the minimal separating set should also pass the test for minimality
262
+ assert nx.is_minimal_d_separator(large_collider_graph, "B", "E", Zmin)
263
+ # function should also work with set arguments
264
+ assert nx.is_minimal_d_separator(large_collider_graph, {"A", "B"}, {"G", "E"}, Zmin)
265
+ assert Zmin == {"D"}
266
+
267
+ # Case 2:
268
+ # create a graph A -> B -> C
269
+ # B -> D -> C;
270
+ assert not nx.is_d_separator(chain_and_fork_graph, {"A"}, {"C"}, set())
271
+ Zmin = nx.find_minimal_d_separator(chain_and_fork_graph, "A", "C")
272
+
273
+ # the minimal separating set should pass the test for minimality
274
+ assert nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Zmin)
275
+ assert Zmin == {"B"}
276
+ Znotmin = Zmin.union({"D"})
277
+ assert not nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Znotmin)
278
+
279
+ # Case 3:
280
+ # create a graph A -> B
281
+
282
+ # there is no m-separating set between A and B at all, so
283
+ # no minimal m-separating set can exist
284
+ assert not nx.is_d_separator(no_separating_set_graph, {"A"}, {"B"}, set())
285
+ assert nx.find_minimal_d_separator(no_separating_set_graph, "A", "B") is None
286
+
287
+ # Case 4:
288
+ # create a graph A -> B with A <- C -> B
289
+
290
+ # there is no m-separating set between A and B at all, so
291
+ # no minimal m-separating set can exist
292
+ # however, the algorithm will initially propose C as a
293
+ # minimal (but invalid) separating set
294
+ assert not nx.is_d_separator(large_no_separating_set_graph, {"A"}, {"B"}, {"C"})
295
+ assert nx.find_minimal_d_separator(large_no_separating_set_graph, "A", "B") is None
296
+
297
+ # Test `included` and `excluded` args
298
+ # create graph A -> B <- C -> D
299
+ assert nx.find_minimal_d_separator(collider_trek_graph, "A", "D", included="B") == {
300
+ "B",
301
+ "C",
302
+ }
303
+ assert (
304
+ nx.find_minimal_d_separator(
305
+ collider_trek_graph, "A", "D", included="B", restricted="B"
306
+ )
307
+ is None
308
+ )
309
+
310
+
311
+ def test_is_minimal_d_separator_checks_dsep():
312
+ """Test that is_minimal_d_separator checks for d-separation as well."""
313
+ g = nx.DiGraph()
314
+ g.add_edges_from(
315
+ [
316
+ ("A", "B"),
317
+ ("A", "E"),
318
+ ("B", "C"),
319
+ ("B", "D"),
320
+ ("D", "C"),
321
+ ("D", "F"),
322
+ ("E", "D"),
323
+ ("E", "F"),
324
+ ]
325
+ )
326
+
327
+ assert not nx.is_d_separator(g, {"C"}, {"F"}, {"D"})
328
+
329
+ # since {'D'} and {} are not d-separators, we return false
330
+ assert not nx.is_minimal_d_separator(g, "C", "F", {"D"})
331
+ assert not nx.is_minimal_d_separator(g, "C", "F", set())
332
+
333
+
334
+ def test__reachable(large_collider_graph):
335
+ reachable = nx.algorithms.d_separation._reachable
336
+ g = large_collider_graph
337
+ x = {"F", "D"}
338
+ ancestors = {"A", "B", "C", "D", "F"}
339
+ assert reachable(g, x, ancestors, {"B"}) == {"B", "F", "D"}
340
+ assert reachable(g, x, ancestors, set()) == ancestors
341
+
342
+
343
+ def test_deprecations():
344
+ G = nx.DiGraph([(0, 1), (1, 2)])
345
+ with pytest.deprecated_call():
346
+ nx.d_separated(G, 0, 2, {1})
347
+ with pytest.deprecated_call():
348
+ z = nx.minimal_d_separator(G, 0, 2)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_dag.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from itertools import combinations, permutations
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.utils import edges_equal, pairwise
8
+
9
+
10
+ # Recipe from the itertools documentation.
11
+ def _consume(iterator):
12
+ "Consume the iterator entirely."
13
+ # Feed the entire iterator into a zero-length deque.
14
+ deque(iterator, maxlen=0)
15
+
16
+
17
+ class TestDagLongestPath:
18
+ """Unit tests computing the longest path in a directed acyclic graph."""
19
+
20
+ def test_empty(self):
21
+ G = nx.DiGraph()
22
+ assert nx.dag_longest_path(G) == []
23
+
24
+ def test_unweighted1(self):
25
+ edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (3, 7)]
26
+ G = nx.DiGraph(edges)
27
+ assert nx.dag_longest_path(G) == [1, 2, 3, 5, 6]
28
+
29
+ def test_unweighted2(self):
30
+ edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
31
+ G = nx.DiGraph(edges)
32
+ assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
33
+
34
+ def test_weighted(self):
35
+ G = nx.DiGraph()
36
+ edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4), (1, 6, 2)]
37
+ G.add_weighted_edges_from(edges)
38
+ assert nx.dag_longest_path(G) == [2, 3, 5]
39
+
40
+ def test_undirected_not_implemented(self):
41
+ G = nx.Graph()
42
+ pytest.raises(nx.NetworkXNotImplemented, nx.dag_longest_path, G)
43
+
44
+ def test_unorderable_nodes(self):
45
+ """Tests that computing the longest path does not depend on
46
+ nodes being orderable.
47
+
48
+ For more information, see issue #1989.
49
+
50
+ """
51
+ # Create the directed path graph on four nodes in a diamond shape,
52
+ # with nodes represented as (unorderable) Python objects.
53
+ nodes = [object() for n in range(4)]
54
+ G = nx.DiGraph()
55
+ G.add_edge(nodes[0], nodes[1])
56
+ G.add_edge(nodes[0], nodes[2])
57
+ G.add_edge(nodes[2], nodes[3])
58
+ G.add_edge(nodes[1], nodes[3])
59
+
60
+ # this will raise NotImplementedError when nodes need to be ordered
61
+ nx.dag_longest_path(G)
62
+
63
+ def test_multigraph_unweighted(self):
64
+ edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
65
+ G = nx.MultiDiGraph(edges)
66
+ assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
67
+
68
+ def test_multigraph_weighted(self):
69
+ G = nx.MultiDiGraph()
70
+ edges = [
71
+ (1, 2, 2),
72
+ (2, 3, 2),
73
+ (1, 3, 1),
74
+ (1, 3, 5),
75
+ (1, 3, 2),
76
+ ]
77
+ G.add_weighted_edges_from(edges)
78
+ assert nx.dag_longest_path(G) == [1, 3]
79
+
80
+ def test_multigraph_weighted_default_weight(self):
81
+ G = nx.MultiDiGraph([(1, 2), (2, 3)]) # Unweighted edges
82
+ G.add_weighted_edges_from([(1, 3, 1), (1, 3, 5), (1, 3, 2)])
83
+
84
+ # Default value for default weight is 1
85
+ assert nx.dag_longest_path(G) == [1, 3]
86
+ assert nx.dag_longest_path(G, default_weight=3) == [1, 2, 3]
87
+
88
+
89
+ class TestDagLongestPathLength:
90
+ """Unit tests for computing the length of a longest path in a
91
+ directed acyclic graph.
92
+
93
+ """
94
+
95
+ def test_unweighted(self):
96
+ edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
97
+ G = nx.DiGraph(edges)
98
+ assert nx.dag_longest_path_length(G) == 4
99
+
100
+ edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
101
+ G = nx.DiGraph(edges)
102
+ assert nx.dag_longest_path_length(G) == 4
103
+
104
+ # test degenerate graphs
105
+ G = nx.DiGraph()
106
+ G.add_node(1)
107
+ assert nx.dag_longest_path_length(G) == 0
108
+
109
+ def test_undirected_not_implemented(self):
110
+ G = nx.Graph()
111
+ pytest.raises(nx.NetworkXNotImplemented, nx.dag_longest_path_length, G)
112
+
113
+ def test_weighted(self):
114
+ edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4), (1, 6, 2)]
115
+ G = nx.DiGraph()
116
+ G.add_weighted_edges_from(edges)
117
+ assert nx.dag_longest_path_length(G) == 5
118
+
119
+ def test_multigraph_unweighted(self):
120
+ edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
121
+ G = nx.MultiDiGraph(edges)
122
+ assert nx.dag_longest_path_length(G) == 4
123
+
124
+ def test_multigraph_weighted(self):
125
+ G = nx.MultiDiGraph()
126
+ edges = [
127
+ (1, 2, 2),
128
+ (2, 3, 2),
129
+ (1, 3, 1),
130
+ (1, 3, 5),
131
+ (1, 3, 2),
132
+ ]
133
+ G.add_weighted_edges_from(edges)
134
+ assert nx.dag_longest_path_length(G) == 5
135
+
136
+
137
+ class TestDAG:
138
+ @classmethod
139
+ def setup_class(cls):
140
+ pass
141
+
142
+ def test_topological_sort1(self):
143
+ DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
144
+
145
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
146
+ assert tuple(algorithm(DG)) == (1, 2, 3)
147
+
148
+ DG.add_edge(3, 2)
149
+
150
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
151
+ pytest.raises(nx.NetworkXUnfeasible, _consume, algorithm(DG))
152
+
153
+ DG.remove_edge(2, 3)
154
+
155
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
156
+ assert tuple(algorithm(DG)) == (1, 3, 2)
157
+
158
+ DG.remove_edge(3, 2)
159
+
160
+ assert tuple(nx.topological_sort(DG)) in {(1, 2, 3), (1, 3, 2)}
161
+ assert tuple(nx.lexicographical_topological_sort(DG)) == (1, 2, 3)
162
+
163
+ def test_is_directed_acyclic_graph(self):
164
+ G = nx.generators.complete_graph(2)
165
+ assert not nx.is_directed_acyclic_graph(G)
166
+ assert not nx.is_directed_acyclic_graph(G.to_directed())
167
+ assert not nx.is_directed_acyclic_graph(nx.Graph([(3, 4), (4, 5)]))
168
+ assert nx.is_directed_acyclic_graph(nx.DiGraph([(3, 4), (4, 5)]))
169
+
170
+ def test_topological_sort2(self):
171
+ DG = nx.DiGraph(
172
+ {
173
+ 1: [2],
174
+ 2: [3],
175
+ 3: [4],
176
+ 4: [5],
177
+ 5: [1],
178
+ 11: [12],
179
+ 12: [13],
180
+ 13: [14],
181
+ 14: [15],
182
+ }
183
+ )
184
+ pytest.raises(nx.NetworkXUnfeasible, _consume, nx.topological_sort(DG))
185
+
186
+ assert not nx.is_directed_acyclic_graph(DG)
187
+
188
+ DG.remove_edge(1, 2)
189
+ _consume(nx.topological_sort(DG))
190
+ assert nx.is_directed_acyclic_graph(DG)
191
+
192
+ def test_topological_sort3(self):
193
+ DG = nx.DiGraph()
194
+ DG.add_edges_from([(1, i) for i in range(2, 5)])
195
+ DG.add_edges_from([(2, i) for i in range(5, 9)])
196
+ DG.add_edges_from([(6, i) for i in range(9, 12)])
197
+ DG.add_edges_from([(4, i) for i in range(12, 15)])
198
+
199
+ def validate(order):
200
+ assert isinstance(order, list)
201
+ assert set(order) == set(DG)
202
+ for u, v in combinations(order, 2):
203
+ assert not nx.has_path(DG, v, u)
204
+
205
+ validate(list(nx.topological_sort(DG)))
206
+
207
+ DG.add_edge(14, 1)
208
+ pytest.raises(nx.NetworkXUnfeasible, _consume, nx.topological_sort(DG))
209
+
210
+ def test_topological_sort4(self):
211
+ G = nx.Graph()
212
+ G.add_edge(1, 2)
213
+ # Only directed graphs can be topologically sorted.
214
+ pytest.raises(nx.NetworkXError, _consume, nx.topological_sort(G))
215
+
216
+ def test_topological_sort5(self):
217
+ G = nx.DiGraph()
218
+ G.add_edge(0, 1)
219
+ assert list(nx.topological_sort(G)) == [0, 1]
220
+
221
+ def test_topological_sort6(self):
222
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
223
+
224
+ def runtime_error():
225
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
226
+ first = True
227
+ for x in algorithm(DG):
228
+ if first:
229
+ first = False
230
+ DG.add_edge(5 - x, 5)
231
+
232
+ def unfeasible_error():
233
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
234
+ first = True
235
+ for x in algorithm(DG):
236
+ if first:
237
+ first = False
238
+ DG.remove_node(4)
239
+
240
+ def runtime_error2():
241
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
242
+ first = True
243
+ for x in algorithm(DG):
244
+ if first:
245
+ first = False
246
+ DG.remove_node(2)
247
+
248
+ pytest.raises(RuntimeError, runtime_error)
249
+ pytest.raises(RuntimeError, runtime_error2)
250
+ pytest.raises(nx.NetworkXUnfeasible, unfeasible_error)
251
+
252
+ def test_all_topological_sorts_1(self):
253
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5)])
254
+ assert list(nx.all_topological_sorts(DG)) == [[1, 2, 3, 4, 5]]
255
+
256
+ def test_all_topological_sorts_2(self):
257
+ DG = nx.DiGraph([(1, 3), (2, 1), (2, 4), (4, 3), (4, 5)])
258
+ assert sorted(nx.all_topological_sorts(DG)) == [
259
+ [2, 1, 4, 3, 5],
260
+ [2, 1, 4, 5, 3],
261
+ [2, 4, 1, 3, 5],
262
+ [2, 4, 1, 5, 3],
263
+ [2, 4, 5, 1, 3],
264
+ ]
265
+
266
+ def test_all_topological_sorts_3(self):
267
+ def unfeasible():
268
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 2), (4, 5)])
269
+ # convert to list to execute generator
270
+ list(nx.all_topological_sorts(DG))
271
+
272
+ def not_implemented():
273
+ G = nx.Graph([(1, 2), (2, 3)])
274
+ # convert to list to execute generator
275
+ list(nx.all_topological_sorts(G))
276
+
277
+ def not_implemented_2():
278
+ G = nx.MultiGraph([(1, 2), (1, 2), (2, 3)])
279
+ list(nx.all_topological_sorts(G))
280
+
281
+ pytest.raises(nx.NetworkXUnfeasible, unfeasible)
282
+ pytest.raises(nx.NetworkXNotImplemented, not_implemented)
283
+ pytest.raises(nx.NetworkXNotImplemented, not_implemented_2)
284
+
285
+ def test_all_topological_sorts_4(self):
286
+ DG = nx.DiGraph()
287
+ for i in range(7):
288
+ DG.add_node(i)
289
+ assert sorted(map(list, permutations(DG.nodes))) == sorted(
290
+ nx.all_topological_sorts(DG)
291
+ )
292
+
293
+ def test_all_topological_sorts_multigraph_1(self):
294
+ DG = nx.MultiDiGraph([(1, 2), (1, 2), (2, 3), (3, 4), (3, 5), (3, 5), (3, 5)])
295
+ assert sorted(nx.all_topological_sorts(DG)) == sorted(
296
+ [[1, 2, 3, 4, 5], [1, 2, 3, 5, 4]]
297
+ )
298
+
299
+ def test_all_topological_sorts_multigraph_2(self):
300
+ N = 9
301
+ edges = []
302
+ for i in range(1, N):
303
+ edges.extend([(i, i + 1)] * i)
304
+ DG = nx.MultiDiGraph(edges)
305
+ assert list(nx.all_topological_sorts(DG)) == [list(range(1, N + 1))]
306
+
307
+ def test_ancestors(self):
308
+ G = nx.DiGraph()
309
+ ancestors = nx.algorithms.dag.ancestors
310
+ G.add_edges_from([(1, 2), (1, 3), (4, 2), (4, 3), (4, 5), (2, 6), (5, 6)])
311
+ assert ancestors(G, 6) == {1, 2, 4, 5}
312
+ assert ancestors(G, 3) == {1, 4}
313
+ assert ancestors(G, 1) == set()
314
+ pytest.raises(nx.NetworkXError, ancestors, G, 8)
315
+
316
+ def test_descendants(self):
317
+ G = nx.DiGraph()
318
+ descendants = nx.algorithms.dag.descendants
319
+ G.add_edges_from([(1, 2), (1, 3), (4, 2), (4, 3), (4, 5), (2, 6), (5, 6)])
320
+ assert descendants(G, 1) == {2, 3, 6}
321
+ assert descendants(G, 4) == {2, 3, 5, 6}
322
+ assert descendants(G, 3) == set()
323
+ pytest.raises(nx.NetworkXError, descendants, G, 8)
324
+
325
+ def test_transitive_closure(self):
326
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
327
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
328
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
329
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
330
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
331
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
332
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
333
+ solution = [(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)]
334
+ soln = sorted(solution + [(n, n) for n in G])
335
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), soln)
336
+
337
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
338
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
339
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
340
+
341
+ G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
342
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
343
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
344
+
345
+ G = nx.MultiDiGraph([(1, 2), (2, 3), (3, 4)])
346
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
347
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
348
+
349
+ # test if edge data is copied
350
+ G = nx.DiGraph([(1, 2, {"a": 3}), (2, 3, {"b": 0}), (3, 4)])
351
+ H = nx.transitive_closure(G)
352
+ for u, v in G.edges():
353
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
354
+
355
+ k = 10
356
+ G = nx.DiGraph((i, i + 1, {"f": "b", "weight": i}) for i in range(k))
357
+ H = nx.transitive_closure(G)
358
+ for u, v in G.edges():
359
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
360
+
361
+ G = nx.Graph()
362
+ with pytest.raises(nx.NetworkXError):
363
+ nx.transitive_closure(G, reflexive="wrong input")
364
+
365
+ def test_reflexive_transitive_closure(self):
366
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
367
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
368
+ soln = sorted(solution + [(n, n) for n in G])
369
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
370
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
371
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
372
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
373
+
374
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
375
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
376
+ soln = sorted(solution + [(n, n) for n in G])
377
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
378
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
379
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
380
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
381
+
382
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
383
+ solution = sorted([(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)])
384
+ soln = sorted(solution + [(n, n) for n in G])
385
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), soln)
386
+ assert edges_equal(sorted(nx.transitive_closure(G, False).edges()), soln)
387
+ assert edges_equal(sorted(nx.transitive_closure(G, None).edges()), solution)
388
+ assert edges_equal(sorted(nx.transitive_closure(G, True).edges()), soln)
389
+
390
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
391
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
392
+ soln = sorted(solution + [(n, n) for n in G])
393
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
394
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
395
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
396
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
397
+
398
+ G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
399
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
400
+ soln = sorted(solution + [(n, n) for n in G])
401
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
402
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
403
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
404
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
405
+
406
+ G = nx.MultiDiGraph([(1, 2), (2, 3), (3, 4)])
407
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
408
+ soln = sorted(solution + [(n, n) for n in G])
409
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
410
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
411
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
412
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
413
+
414
+ def test_transitive_closure_dag(self):
415
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
416
+ transitive_closure = nx.algorithms.dag.transitive_closure_dag
417
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
418
+ assert edges_equal(transitive_closure(G).edges(), solution)
419
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
420
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
421
+ assert edges_equal(transitive_closure(G).edges(), solution)
422
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
423
+ pytest.raises(nx.NetworkXNotImplemented, transitive_closure, G)
424
+
425
+ # test if edge data is copied
426
+ G = nx.DiGraph([(1, 2, {"a": 3}), (2, 3, {"b": 0}), (3, 4)])
427
+ H = transitive_closure(G)
428
+ for u, v in G.edges():
429
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
430
+
431
+ k = 10
432
+ G = nx.DiGraph((i, i + 1, {"foo": "bar", "weight": i}) for i in range(k))
433
+ H = transitive_closure(G)
434
+ for u, v in G.edges():
435
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
436
+
437
+ def test_transitive_reduction(self):
438
+ G = nx.DiGraph([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)])
439
+ transitive_reduction = nx.algorithms.dag.transitive_reduction
440
+ solution = [(1, 2), (2, 3), (3, 4)]
441
+ assert edges_equal(transitive_reduction(G).edges(), solution)
442
+ G = nx.DiGraph([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)])
443
+ transitive_reduction = nx.algorithms.dag.transitive_reduction
444
+ solution = [(1, 2), (2, 3), (2, 4)]
445
+ assert edges_equal(transitive_reduction(G).edges(), solution)
446
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
447
+ pytest.raises(nx.NetworkXNotImplemented, transitive_reduction, G)
448
+
449
+ def _check_antichains(self, solution, result):
450
+ sol = [frozenset(a) for a in solution]
451
+ res = [frozenset(a) for a in result]
452
+ assert set(sol) == set(res)
453
+
454
+ def test_antichains(self):
455
+ antichains = nx.algorithms.dag.antichains
456
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
457
+ solution = [[], [4], [3], [2], [1]]
458
+ self._check_antichains(list(antichains(G)), solution)
459
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)])
460
+ solution = [
461
+ [],
462
+ [4],
463
+ [7],
464
+ [7, 4],
465
+ [6],
466
+ [6, 4],
467
+ [6, 7],
468
+ [6, 7, 4],
469
+ [5],
470
+ [5, 4],
471
+ [3],
472
+ [3, 4],
473
+ [2],
474
+ [1],
475
+ ]
476
+ self._check_antichains(list(antichains(G)), solution)
477
+ G = nx.DiGraph([(1, 2), (1, 3), (3, 4), (3, 5), (5, 6)])
478
+ solution = [
479
+ [],
480
+ [6],
481
+ [5],
482
+ [4],
483
+ [4, 6],
484
+ [4, 5],
485
+ [3],
486
+ [2],
487
+ [2, 6],
488
+ [2, 5],
489
+ [2, 4],
490
+ [2, 4, 6],
491
+ [2, 4, 5],
492
+ [2, 3],
493
+ [1],
494
+ ]
495
+ self._check_antichains(list(antichains(G)), solution)
496
+ G = nx.DiGraph({0: [1, 2], 1: [4], 2: [3], 3: [4]})
497
+ solution = [[], [4], [3], [2], [1], [1, 3], [1, 2], [0]]
498
+ self._check_antichains(list(antichains(G)), solution)
499
+ G = nx.DiGraph()
500
+ self._check_antichains(list(antichains(G)), [[]])
501
+ G = nx.DiGraph()
502
+ G.add_nodes_from([0, 1, 2])
503
+ solution = [[], [0], [1], [1, 0], [2], [2, 0], [2, 1], [2, 1, 0]]
504
+ self._check_antichains(list(antichains(G)), solution)
505
+
506
+ def f(x):
507
+ return list(antichains(x))
508
+
509
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
510
+ pytest.raises(nx.NetworkXNotImplemented, f, G)
511
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
512
+ pytest.raises(nx.NetworkXUnfeasible, f, G)
513
+
514
+ def test_lexicographical_topological_sort(self):
515
+ G = nx.DiGraph([(1, 2), (2, 3), (1, 4), (1, 5), (2, 6)])
516
+ assert list(nx.lexicographical_topological_sort(G)) == [1, 2, 3, 4, 5, 6]
517
+ assert list(nx.lexicographical_topological_sort(G, key=lambda x: x)) == [
518
+ 1,
519
+ 2,
520
+ 3,
521
+ 4,
522
+ 5,
523
+ 6,
524
+ ]
525
+ assert list(nx.lexicographical_topological_sort(G, key=lambda x: -x)) == [
526
+ 1,
527
+ 5,
528
+ 4,
529
+ 2,
530
+ 6,
531
+ 3,
532
+ ]
533
+
534
+ def test_lexicographical_topological_sort2(self):
535
+ """
536
+ Check the case of two or more nodes with same key value.
537
+ Want to avoid exception raised due to comparing nodes directly.
538
+ See Issue #3493
539
+ """
540
+
541
+ class Test_Node:
542
+ def __init__(self, n):
543
+ self.label = n
544
+ self.priority = 1
545
+
546
+ def __repr__(self):
547
+ return f"Node({self.label})"
548
+
549
+ def sorting_key(node):
550
+ return node.priority
551
+
552
+ test_nodes = [Test_Node(n) for n in range(4)]
553
+ G = nx.DiGraph()
554
+ edges = [(0, 1), (0, 2), (0, 3), (2, 3)]
555
+ G.add_edges_from((test_nodes[a], test_nodes[b]) for a, b in edges)
556
+
557
+ sorting = list(nx.lexicographical_topological_sort(G, key=sorting_key))
558
+ assert sorting == test_nodes
559
+
560
+
561
+ def test_topological_generations():
562
+ G = nx.DiGraph(
563
+ {1: [2, 3], 2: [4, 5], 3: [7], 4: [], 5: [6, 7], 6: [], 7: []}
564
+ ).reverse()
565
+ # order within each generation is inconsequential
566
+ generations = [sorted(gen) for gen in nx.topological_generations(G)]
567
+ expected = [[4, 6, 7], [3, 5], [2], [1]]
568
+ assert generations == expected
569
+
570
+ MG = nx.MultiDiGraph(G.edges)
571
+ MG.add_edge(2, 1)
572
+ generations = [sorted(gen) for gen in nx.topological_generations(MG)]
573
+ assert generations == expected
574
+
575
+
576
+ def test_topological_generations_empty():
577
+ G = nx.DiGraph()
578
+ assert list(nx.topological_generations(G)) == []
579
+
580
+
581
+ def test_topological_generations_cycle():
582
+ G = nx.DiGraph([[2, 1], [3, 1], [1, 2]])
583
+ with pytest.raises(nx.NetworkXUnfeasible):
584
+ list(nx.topological_generations(G))
585
+
586
+
587
+ def test_is_aperiodic_cycle():
588
+ G = nx.DiGraph()
589
+ nx.add_cycle(G, [1, 2, 3, 4])
590
+ assert not nx.is_aperiodic(G)
591
+
592
+
593
+ def test_is_aperiodic_cycle2():
594
+ G = nx.DiGraph()
595
+ nx.add_cycle(G, [1, 2, 3, 4])
596
+ nx.add_cycle(G, [3, 4, 5, 6, 7])
597
+ assert nx.is_aperiodic(G)
598
+
599
+
600
+ def test_is_aperiodic_cycle3():
601
+ G = nx.DiGraph()
602
+ nx.add_cycle(G, [1, 2, 3, 4])
603
+ nx.add_cycle(G, [3, 4, 5, 6])
604
+ assert not nx.is_aperiodic(G)
605
+
606
+
607
+ def test_is_aperiodic_cycle4():
608
+ G = nx.DiGraph()
609
+ nx.add_cycle(G, [1, 2, 3, 4])
610
+ G.add_edge(1, 3)
611
+ assert nx.is_aperiodic(G)
612
+
613
+
614
+ def test_is_aperiodic_selfloop():
615
+ G = nx.DiGraph()
616
+ nx.add_cycle(G, [1, 2, 3, 4])
617
+ G.add_edge(1, 1)
618
+ assert nx.is_aperiodic(G)
619
+
620
+
621
+ def test_is_aperiodic_undirected_raises():
622
+ G = nx.Graph()
623
+ pytest.raises(nx.NetworkXError, nx.is_aperiodic, G)
624
+
625
+
626
+ def test_is_aperiodic_empty_graph():
627
+ G = nx.empty_graph(create_using=nx.DiGraph)
628
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes."):
629
+ nx.is_aperiodic(G)
630
+
631
+
632
+ def test_is_aperiodic_bipartite():
633
+ # Bipartite graph
634
+ G = nx.DiGraph(nx.davis_southern_women_graph())
635
+ assert not nx.is_aperiodic(G)
636
+
637
+
638
+ def test_is_aperiodic_rary_tree():
639
+ G = nx.full_rary_tree(3, 27, create_using=nx.DiGraph())
640
+ assert not nx.is_aperiodic(G)
641
+
642
+
643
+ def test_is_aperiodic_disconnected():
644
+ # disconnected graph
645
+ G = nx.DiGraph()
646
+ nx.add_cycle(G, [1, 2, 3, 4])
647
+ nx.add_cycle(G, [5, 6, 7, 8])
648
+ assert not nx.is_aperiodic(G)
649
+ G.add_edge(1, 3)
650
+ G.add_edge(5, 7)
651
+ assert nx.is_aperiodic(G)
652
+
653
+
654
+ def test_is_aperiodic_disconnected2():
655
+ G = nx.DiGraph()
656
+ nx.add_cycle(G, [0, 1, 2])
657
+ G.add_edge(3, 3)
658
+ assert not nx.is_aperiodic(G)
659
+
660
+
661
+ class TestDagToBranching:
662
+ """Unit tests for the :func:`networkx.dag_to_branching` function."""
663
+
664
+ def test_single_root(self):
665
+ """Tests that a directed acyclic graph with a single degree
666
+ zero node produces an arborescence.
667
+
668
+ """
669
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)])
670
+ B = nx.dag_to_branching(G)
671
+ expected = nx.DiGraph([(0, 1), (1, 3), (0, 2), (2, 4)])
672
+ assert nx.is_arborescence(B)
673
+ assert nx.is_isomorphic(B, expected)
674
+
675
+ def test_multiple_roots(self):
676
+ """Tests that a directed acyclic graph with multiple degree zero
677
+ nodes creates an arborescence with multiple (weakly) connected
678
+ components.
679
+
680
+ """
681
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3), (5, 2)])
682
+ B = nx.dag_to_branching(G)
683
+ expected = nx.DiGraph([(0, 1), (1, 3), (0, 2), (2, 4), (5, 6), (6, 7)])
684
+ assert nx.is_branching(B)
685
+ assert not nx.is_arborescence(B)
686
+ assert nx.is_isomorphic(B, expected)
687
+
688
+ # # Attributes are not copied by this function. If they were, this would
689
+ # # be a good test to uncomment.
690
+ # def test_copy_attributes(self):
691
+ # """Tests that node attributes are copied in the branching."""
692
+ # G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)])
693
+ # for v in G:
694
+ # G.node[v]['label'] = str(v)
695
+ # B = nx.dag_to_branching(G)
696
+ # # Determine the root node of the branching.
697
+ # root = next(v for v, d in B.in_degree() if d == 0)
698
+ # assert_equal(B.node[root]['label'], '0')
699
+ # children = B[root]
700
+ # # Get the left and right children, nodes 1 and 2, respectively.
701
+ # left, right = sorted(children, key=lambda v: B.node[v]['label'])
702
+ # assert_equal(B.node[left]['label'], '1')
703
+ # assert_equal(B.node[right]['label'], '2')
704
+ # # Get the left grandchild.
705
+ # children = B[left]
706
+ # assert_equal(len(children), 1)
707
+ # left_grandchild = arbitrary_element(children)
708
+ # assert_equal(B.node[left_grandchild]['label'], '3')
709
+ # # Get the right grandchild.
710
+ # children = B[right]
711
+ # assert_equal(len(children), 1)
712
+ # right_grandchild = arbitrary_element(children)
713
+ # assert_equal(B.node[right_grandchild]['label'], '3')
714
+
715
+ def test_already_arborescence(self):
716
+ """Tests that a directed acyclic graph that is already an
717
+ arborescence produces an isomorphic arborescence as output.
718
+
719
+ """
720
+ A = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
721
+ B = nx.dag_to_branching(A)
722
+ assert nx.is_isomorphic(A, B)
723
+
724
+ def test_already_branching(self):
725
+ """Tests that a directed acyclic graph that is already a
726
+ branching produces an isomorphic branching as output.
727
+
728
+ """
729
+ T1 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
730
+ T2 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
731
+ G = nx.disjoint_union(T1, T2)
732
+ B = nx.dag_to_branching(G)
733
+ assert nx.is_isomorphic(G, B)
734
+
735
+ def test_not_acyclic(self):
736
+ """Tests that a non-acyclic graph causes an exception."""
737
+ with pytest.raises(nx.HasACycle):
738
+ G = nx.DiGraph(pairwise("abc", cyclic=True))
739
+ nx.dag_to_branching(G)
740
+
741
+ def test_undirected(self):
742
+ with pytest.raises(nx.NetworkXNotImplemented):
743
+ nx.dag_to_branching(nx.Graph())
744
+
745
+ def test_multigraph(self):
746
+ with pytest.raises(nx.NetworkXNotImplemented):
747
+ nx.dag_to_branching(nx.MultiGraph())
748
+
749
+ def test_multidigraph(self):
750
+ with pytest.raises(nx.NetworkXNotImplemented):
751
+ nx.dag_to_branching(nx.MultiDiGraph())
752
+
753
+
754
+ def test_ancestors_descendants_undirected():
755
+ """Regression test to ensure ancestors and descendants work as expected on
756
+ undirected graphs."""
757
+ G = nx.path_graph(5)
758
+ nx.ancestors(G, 2) == nx.descendants(G, 2) == {0, 1, 3, 4}
759
+
760
+
761
+ def test_compute_v_structures_raise():
762
+ G = nx.Graph()
763
+ pytest.raises(nx.NetworkXNotImplemented, nx.compute_v_structures, G)
764
+
765
+
766
+ def test_compute_v_structures():
767
+ edges = [(0, 1), (0, 2), (3, 2)]
768
+ G = nx.DiGraph(edges)
769
+
770
+ v_structs = set(nx.compute_v_structures(G))
771
+ assert len(v_structs) == 1
772
+ assert (0, 2, 3) in v_structs
773
+
774
+ edges = [("A", "B"), ("C", "B"), ("B", "D"), ("D", "E"), ("G", "E")]
775
+ G = nx.DiGraph(edges)
776
+ v_structs = set(nx.compute_v_structures(G))
777
+ assert len(v_structs) == 2
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_distance_measures.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from random import Random
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx import convert_node_labels_to_integers as cnlti
7
+ from networkx.algorithms.distance_measures import _extrema_bounding
8
+
9
+
10
+ def test__extrema_bounding_invalid_compute_kwarg():
11
+ G = nx.path_graph(3)
12
+ with pytest.raises(ValueError, match="compute must be one of"):
13
+ _extrema_bounding(G, compute="spam")
14
+
15
+
16
+ class TestDistance:
17
+ def setup_method(self):
18
+ G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
19
+ self.G = G
20
+
21
+ def test_eccentricity(self):
22
+ assert nx.eccentricity(self.G, 1) == 6
23
+ e = nx.eccentricity(self.G)
24
+ assert e[1] == 6
25
+
26
+ sp = dict(nx.shortest_path_length(self.G))
27
+ e = nx.eccentricity(self.G, sp=sp)
28
+ assert e[1] == 6
29
+
30
+ e = nx.eccentricity(self.G, v=1)
31
+ assert e == 6
32
+
33
+ # This behavior changed in version 1.8 (ticket #739)
34
+ e = nx.eccentricity(self.G, v=[1, 1])
35
+ assert e[1] == 6
36
+ e = nx.eccentricity(self.G, v=[1, 2])
37
+ assert e[1] == 6
38
+
39
+ # test against graph with one node
40
+ G = nx.path_graph(1)
41
+ e = nx.eccentricity(G)
42
+ assert e[0] == 0
43
+ e = nx.eccentricity(G, v=0)
44
+ assert e == 0
45
+ pytest.raises(nx.NetworkXError, nx.eccentricity, G, 1)
46
+
47
+ # test against empty graph
48
+ G = nx.empty_graph()
49
+ e = nx.eccentricity(G)
50
+ assert e == {}
51
+
52
+ def test_diameter(self):
53
+ assert nx.diameter(self.G) == 6
54
+
55
+ def test_radius(self):
56
+ assert nx.radius(self.G) == 4
57
+
58
+ def test_periphery(self):
59
+ assert set(nx.periphery(self.G)) == {1, 4, 13, 16}
60
+
61
+ def test_center(self):
62
+ assert set(nx.center(self.G)) == {6, 7, 10, 11}
63
+
64
+ def test_bound_diameter(self):
65
+ assert nx.diameter(self.G, usebounds=True) == 6
66
+
67
+ def test_bound_radius(self):
68
+ assert nx.radius(self.G, usebounds=True) == 4
69
+
70
+ def test_bound_periphery(self):
71
+ result = {1, 4, 13, 16}
72
+ assert set(nx.periphery(self.G, usebounds=True)) == result
73
+
74
+ def test_bound_center(self):
75
+ result = {6, 7, 10, 11}
76
+ assert set(nx.center(self.G, usebounds=True)) == result
77
+
78
+ def test_radius_exception(self):
79
+ G = nx.Graph()
80
+ G.add_edge(1, 2)
81
+ G.add_edge(3, 4)
82
+ pytest.raises(nx.NetworkXError, nx.diameter, G)
83
+
84
+ def test_eccentricity_infinite(self):
85
+ with pytest.raises(nx.NetworkXError):
86
+ G = nx.Graph([(1, 2), (3, 4)])
87
+ e = nx.eccentricity(G)
88
+
89
+ def test_eccentricity_undirected_not_connected(self):
90
+ with pytest.raises(nx.NetworkXError):
91
+ G = nx.Graph([(1, 2), (3, 4)])
92
+ e = nx.eccentricity(G, sp=1)
93
+
94
+ def test_eccentricity_directed_weakly_connected(self):
95
+ with pytest.raises(nx.NetworkXError):
96
+ DG = nx.DiGraph([(1, 2), (1, 3)])
97
+ nx.eccentricity(DG)
98
+
99
+
100
+ class TestWeightedDistance:
101
+ def setup_method(self):
102
+ G = nx.Graph()
103
+ G.add_edge(0, 1, weight=0.6, cost=0.6, high_cost=6)
104
+ G.add_edge(0, 2, weight=0.2, cost=0.2, high_cost=2)
105
+ G.add_edge(2, 3, weight=0.1, cost=0.1, high_cost=1)
106
+ G.add_edge(2, 4, weight=0.7, cost=0.7, high_cost=7)
107
+ G.add_edge(2, 5, weight=0.9, cost=0.9, high_cost=9)
108
+ G.add_edge(1, 5, weight=0.3, cost=0.3, high_cost=3)
109
+ self.G = G
110
+ self.weight_fn = lambda v, u, e: 2
111
+
112
+ def test_eccentricity_weight_None(self):
113
+ assert nx.eccentricity(self.G, 1, weight=None) == 3
114
+ e = nx.eccentricity(self.G, weight=None)
115
+ assert e[1] == 3
116
+
117
+ e = nx.eccentricity(self.G, v=1, weight=None)
118
+ assert e == 3
119
+
120
+ # This behavior changed in version 1.8 (ticket #739)
121
+ e = nx.eccentricity(self.G, v=[1, 1], weight=None)
122
+ assert e[1] == 3
123
+ e = nx.eccentricity(self.G, v=[1, 2], weight=None)
124
+ assert e[1] == 3
125
+
126
+ def test_eccentricity_weight_attr(self):
127
+ assert nx.eccentricity(self.G, 1, weight="weight") == 1.5
128
+ e = nx.eccentricity(self.G, weight="weight")
129
+ assert (
130
+ e
131
+ == nx.eccentricity(self.G, weight="cost")
132
+ != nx.eccentricity(self.G, weight="high_cost")
133
+ )
134
+ assert e[1] == 1.5
135
+
136
+ e = nx.eccentricity(self.G, v=1, weight="weight")
137
+ assert e == 1.5
138
+
139
+ # This behavior changed in version 1.8 (ticket #739)
140
+ e = nx.eccentricity(self.G, v=[1, 1], weight="weight")
141
+ assert e[1] == 1.5
142
+ e = nx.eccentricity(self.G, v=[1, 2], weight="weight")
143
+ assert e[1] == 1.5
144
+
145
+ def test_eccentricity_weight_fn(self):
146
+ assert nx.eccentricity(self.G, 1, weight=self.weight_fn) == 6
147
+ e = nx.eccentricity(self.G, weight=self.weight_fn)
148
+ assert e[1] == 6
149
+
150
+ e = nx.eccentricity(self.G, v=1, weight=self.weight_fn)
151
+ assert e == 6
152
+
153
+ # This behavior changed in version 1.8 (ticket #739)
154
+ e = nx.eccentricity(self.G, v=[1, 1], weight=self.weight_fn)
155
+ assert e[1] == 6
156
+ e = nx.eccentricity(self.G, v=[1, 2], weight=self.weight_fn)
157
+ assert e[1] == 6
158
+
159
+ def test_diameter_weight_None(self):
160
+ assert nx.diameter(self.G, weight=None) == 3
161
+
162
+ def test_diameter_weight_attr(self):
163
+ assert (
164
+ nx.diameter(self.G, weight="weight")
165
+ == nx.diameter(self.G, weight="cost")
166
+ == 1.6
167
+ != nx.diameter(self.G, weight="high_cost")
168
+ )
169
+
170
+ def test_diameter_weight_fn(self):
171
+ assert nx.diameter(self.G, weight=self.weight_fn) == 6
172
+
173
+ def test_radius_weight_None(self):
174
+ assert pytest.approx(nx.radius(self.G, weight=None)) == 2
175
+
176
+ def test_radius_weight_attr(self):
177
+ assert (
178
+ pytest.approx(nx.radius(self.G, weight="weight"))
179
+ == pytest.approx(nx.radius(self.G, weight="cost"))
180
+ == 0.9
181
+ != nx.radius(self.G, weight="high_cost")
182
+ )
183
+
184
+ def test_radius_weight_fn(self):
185
+ assert nx.radius(self.G, weight=self.weight_fn) == 4
186
+
187
+ def test_periphery_weight_None(self):
188
+ for v in set(nx.periphery(self.G, weight=None)):
189
+ assert nx.eccentricity(self.G, v, weight=None) == nx.diameter(
190
+ self.G, weight=None
191
+ )
192
+
193
+ def test_periphery_weight_attr(self):
194
+ periphery = set(nx.periphery(self.G, weight="weight"))
195
+ assert (
196
+ periphery
197
+ == set(nx.periphery(self.G, weight="cost"))
198
+ == set(nx.periphery(self.G, weight="high_cost"))
199
+ )
200
+ for v in periphery:
201
+ assert (
202
+ nx.eccentricity(self.G, v, weight="high_cost")
203
+ != nx.eccentricity(self.G, v, weight="weight")
204
+ == nx.eccentricity(self.G, v, weight="cost")
205
+ == nx.diameter(self.G, weight="weight")
206
+ == nx.diameter(self.G, weight="cost")
207
+ != nx.diameter(self.G, weight="high_cost")
208
+ )
209
+ assert nx.eccentricity(self.G, v, weight="high_cost") == nx.diameter(
210
+ self.G, weight="high_cost"
211
+ )
212
+
213
+ def test_periphery_weight_fn(self):
214
+ for v in set(nx.periphery(self.G, weight=self.weight_fn)):
215
+ assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.diameter(
216
+ self.G, weight=self.weight_fn
217
+ )
218
+
219
+ def test_center_weight_None(self):
220
+ for v in set(nx.center(self.G, weight=None)):
221
+ assert pytest.approx(nx.eccentricity(self.G, v, weight=None)) == nx.radius(
222
+ self.G, weight=None
223
+ )
224
+
225
+ def test_center_weight_attr(self):
226
+ center = set(nx.center(self.G, weight="weight"))
227
+ assert (
228
+ center
229
+ == set(nx.center(self.G, weight="cost"))
230
+ != set(nx.center(self.G, weight="high_cost"))
231
+ )
232
+ for v in center:
233
+ assert (
234
+ nx.eccentricity(self.G, v, weight="high_cost")
235
+ != pytest.approx(nx.eccentricity(self.G, v, weight="weight"))
236
+ == pytest.approx(nx.eccentricity(self.G, v, weight="cost"))
237
+ == nx.radius(self.G, weight="weight")
238
+ == nx.radius(self.G, weight="cost")
239
+ != nx.radius(self.G, weight="high_cost")
240
+ )
241
+ assert nx.eccentricity(self.G, v, weight="high_cost") == nx.radius(
242
+ self.G, weight="high_cost"
243
+ )
244
+
245
+ def test_center_weight_fn(self):
246
+ for v in set(nx.center(self.G, weight=self.weight_fn)):
247
+ assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.radius(
248
+ self.G, weight=self.weight_fn
249
+ )
250
+
251
+ def test_bound_diameter_weight_None(self):
252
+ assert nx.diameter(self.G, usebounds=True, weight=None) == 3
253
+
254
+ def test_bound_diameter_weight_attr(self):
255
+ assert (
256
+ nx.diameter(self.G, usebounds=True, weight="high_cost")
257
+ != nx.diameter(self.G, usebounds=True, weight="weight")
258
+ == nx.diameter(self.G, usebounds=True, weight="cost")
259
+ == 1.6
260
+ != nx.diameter(self.G, usebounds=True, weight="high_cost")
261
+ )
262
+ assert nx.diameter(self.G, usebounds=True, weight="high_cost") == nx.diameter(
263
+ self.G, usebounds=True, weight="high_cost"
264
+ )
265
+
266
+ def test_bound_diameter_weight_fn(self):
267
+ assert nx.diameter(self.G, usebounds=True, weight=self.weight_fn) == 6
268
+
269
+ def test_bound_radius_weight_None(self):
270
+ assert pytest.approx(nx.radius(self.G, usebounds=True, weight=None)) == 2
271
+
272
+ def test_bound_radius_weight_attr(self):
273
+ assert (
274
+ nx.radius(self.G, usebounds=True, weight="high_cost")
275
+ != pytest.approx(nx.radius(self.G, usebounds=True, weight="weight"))
276
+ == pytest.approx(nx.radius(self.G, usebounds=True, weight="cost"))
277
+ == 0.9
278
+ != nx.radius(self.G, usebounds=True, weight="high_cost")
279
+ )
280
+ assert nx.radius(self.G, usebounds=True, weight="high_cost") == nx.radius(
281
+ self.G, usebounds=True, weight="high_cost"
282
+ )
283
+
284
+ def test_bound_radius_weight_fn(self):
285
+ assert nx.radius(self.G, usebounds=True, weight=self.weight_fn) == 4
286
+
287
+ def test_bound_periphery_weight_None(self):
288
+ result = {1, 3, 4}
289
+ assert set(nx.periphery(self.G, usebounds=True, weight=None)) == result
290
+
291
+ def test_bound_periphery_weight_attr(self):
292
+ result = {4, 5}
293
+ assert (
294
+ set(nx.periphery(self.G, usebounds=True, weight="weight"))
295
+ == set(nx.periphery(self.G, usebounds=True, weight="cost"))
296
+ == result
297
+ )
298
+
299
+ def test_bound_periphery_weight_fn(self):
300
+ result = {1, 3, 4}
301
+ assert (
302
+ set(nx.periphery(self.G, usebounds=True, weight=self.weight_fn)) == result
303
+ )
304
+
305
+ def test_bound_center_weight_None(self):
306
+ result = {0, 2, 5}
307
+ assert set(nx.center(self.G, usebounds=True, weight=None)) == result
308
+
309
+ def test_bound_center_weight_attr(self):
310
+ result = {0}
311
+ assert (
312
+ set(nx.center(self.G, usebounds=True, weight="weight"))
313
+ == set(nx.center(self.G, usebounds=True, weight="cost"))
314
+ == result
315
+ )
316
+
317
+ def test_bound_center_weight_fn(self):
318
+ result = {0, 2, 5}
319
+ assert set(nx.center(self.G, usebounds=True, weight=self.weight_fn)) == result
320
+
321
+
322
+ class TestResistanceDistance:
323
+ @classmethod
324
+ def setup_class(cls):
325
+ global np
326
+ np = pytest.importorskip("numpy")
327
+ sp = pytest.importorskip("scipy")
328
+
329
+ def setup_method(self):
330
+ G = nx.Graph()
331
+ G.add_edge(1, 2, weight=2)
332
+ G.add_edge(2, 3, weight=4)
333
+ G.add_edge(3, 4, weight=1)
334
+ G.add_edge(1, 4, weight=3)
335
+ self.G = G
336
+
337
+ def test_resistance_distance_directed_graph(self):
338
+ G = nx.DiGraph()
339
+ with pytest.raises(nx.NetworkXNotImplemented):
340
+ nx.resistance_distance(G)
341
+
342
+ def test_resistance_distance_empty(self):
343
+ G = nx.Graph()
344
+ with pytest.raises(nx.NetworkXError):
345
+ nx.resistance_distance(G)
346
+
347
+ def test_resistance_distance_not_connected(self):
348
+ with pytest.raises(nx.NetworkXError):
349
+ self.G.add_node(5)
350
+ nx.resistance_distance(self.G, 1, 5)
351
+
352
+ def test_resistance_distance_nodeA_not_in_graph(self):
353
+ with pytest.raises(nx.NetworkXError):
354
+ nx.resistance_distance(self.G, 9, 1)
355
+
356
+ def test_resistance_distance_nodeB_not_in_graph(self):
357
+ with pytest.raises(nx.NetworkXError):
358
+ nx.resistance_distance(self.G, 1, 9)
359
+
360
+ def test_resistance_distance(self):
361
+ rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
362
+ test_data = 1 / (1 / (2 + 4) + 1 / (1 + 3))
363
+ assert round(rd, 5) == round(test_data, 5)
364
+
365
+ def test_resistance_distance_noinv(self):
366
+ rd = nx.resistance_distance(self.G, 1, 3, "weight", False)
367
+ test_data = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1 + 1 / 3))
368
+ assert round(rd, 5) == round(test_data, 5)
369
+
370
+ def test_resistance_distance_no_weight(self):
371
+ rd = nx.resistance_distance(self.G, 1, 3)
372
+ assert round(rd, 5) == 1
373
+
374
+ def test_resistance_distance_neg_weight(self):
375
+ self.G[2][3]["weight"] = -4
376
+ rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
377
+ test_data = 1 / (1 / (2 + -4) + 1 / (1 + 3))
378
+ assert round(rd, 5) == round(test_data, 5)
379
+
380
+ def test_multigraph(self):
381
+ G = nx.MultiGraph()
382
+ G.add_edge(1, 2, weight=2)
383
+ G.add_edge(2, 3, weight=4)
384
+ G.add_edge(3, 4, weight=1)
385
+ G.add_edge(1, 4, weight=3)
386
+ rd = nx.resistance_distance(G, 1, 3, "weight", True)
387
+ assert np.isclose(rd, 1 / (1 / (2 + 4) + 1 / (1 + 3)))
388
+
389
+ def test_resistance_distance_div0(self):
390
+ with pytest.raises(ZeroDivisionError):
391
+ self.G[1][2]["weight"] = 0
392
+ nx.resistance_distance(self.G, 1, 3, "weight")
393
+
394
+ def test_resistance_distance_same_node(self):
395
+ assert nx.resistance_distance(self.G, 1, 1) == 0
396
+
397
+ def test_resistance_distance_only_nodeA(self):
398
+ rd = nx.resistance_distance(self.G, nodeA=1)
399
+ test_data = {}
400
+ test_data[1] = 0
401
+ test_data[2] = 0.75
402
+ test_data[3] = 1
403
+ test_data[4] = 0.75
404
+ assert type(rd) == dict
405
+ assert sorted(rd.keys()) == sorted(test_data.keys())
406
+ for key in rd:
407
+ assert np.isclose(rd[key], test_data[key])
408
+
409
+ def test_resistance_distance_only_nodeB(self):
410
+ rd = nx.resistance_distance(self.G, nodeB=1)
411
+ test_data = {}
412
+ test_data[1] = 0
413
+ test_data[2] = 0.75
414
+ test_data[3] = 1
415
+ test_data[4] = 0.75
416
+ assert type(rd) == dict
417
+ assert sorted(rd.keys()) == sorted(test_data.keys())
418
+ for key in rd:
419
+ assert np.isclose(rd[key], test_data[key])
420
+
421
+ def test_resistance_distance_all(self):
422
+ rd = nx.resistance_distance(self.G)
423
+ assert type(rd) == dict
424
+ assert round(rd[1][3], 5) == 1
425
+
426
+
427
+ class TestEffectiveGraphResistance:
428
+ @classmethod
429
+ def setup_class(cls):
430
+ global np
431
+ np = pytest.importorskip("numpy")
432
+ sp = pytest.importorskip("scipy")
433
+
434
+ def setup_method(self):
435
+ G = nx.Graph()
436
+ G.add_edge(1, 2, weight=2)
437
+ G.add_edge(1, 3, weight=1)
438
+ G.add_edge(2, 3, weight=4)
439
+ self.G = G
440
+
441
+ def test_effective_graph_resistance_directed_graph(self):
442
+ G = nx.DiGraph()
443
+ with pytest.raises(nx.NetworkXNotImplemented):
444
+ nx.effective_graph_resistance(G)
445
+
446
+ def test_effective_graph_resistance_empty(self):
447
+ G = nx.Graph()
448
+ with pytest.raises(nx.NetworkXError):
449
+ nx.effective_graph_resistance(G)
450
+
451
+ def test_effective_graph_resistance_not_connected(self):
452
+ G = nx.Graph([(1, 2), (3, 4)])
453
+ RG = nx.effective_graph_resistance(G)
454
+ assert np.isinf(RG)
455
+
456
+ def test_effective_graph_resistance(self):
457
+ RG = nx.effective_graph_resistance(self.G, "weight", True)
458
+ rd12 = 1 / (1 / (1 + 4) + 1 / 2)
459
+ rd13 = 1 / (1 / (1 + 2) + 1 / 4)
460
+ rd23 = 1 / (1 / (2 + 4) + 1 / 1)
461
+ assert np.isclose(RG, rd12 + rd13 + rd23)
462
+
463
+ def test_effective_graph_resistance_noinv(self):
464
+ RG = nx.effective_graph_resistance(self.G, "weight", False)
465
+ rd12 = 1 / (1 / (1 / 1 + 1 / 4) + 1 / (1 / 2))
466
+ rd13 = 1 / (1 / (1 / 1 + 1 / 2) + 1 / (1 / 4))
467
+ rd23 = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1))
468
+ assert np.isclose(RG, rd12 + rd13 + rd23)
469
+
470
+ def test_effective_graph_resistance_no_weight(self):
471
+ RG = nx.effective_graph_resistance(self.G)
472
+ assert np.isclose(RG, 2)
473
+
474
+ def test_effective_graph_resistance_neg_weight(self):
475
+ self.G[2][3]["weight"] = -4
476
+ RG = nx.effective_graph_resistance(self.G, "weight", True)
477
+ rd12 = 1 / (1 / (1 + -4) + 1 / 2)
478
+ rd13 = 1 / (1 / (1 + 2) + 1 / (-4))
479
+ rd23 = 1 / (1 / (2 + -4) + 1 / 1)
480
+ assert np.isclose(RG, rd12 + rd13 + rd23)
481
+
482
+ def test_effective_graph_resistance_multigraph(self):
483
+ G = nx.MultiGraph()
484
+ G.add_edge(1, 2, weight=2)
485
+ G.add_edge(1, 3, weight=1)
486
+ G.add_edge(2, 3, weight=1)
487
+ G.add_edge(2, 3, weight=3)
488
+ RG = nx.effective_graph_resistance(G, "weight", True)
489
+ edge23 = 1 / (1 / 1 + 1 / 3)
490
+ rd12 = 1 / (1 / (1 + edge23) + 1 / 2)
491
+ rd13 = 1 / (1 / (1 + 2) + 1 / edge23)
492
+ rd23 = 1 / (1 / (2 + edge23) + 1 / 1)
493
+ assert np.isclose(RG, rd12 + rd13 + rd23)
494
+
495
+ def test_effective_graph_resistance_div0(self):
496
+ with pytest.raises(ZeroDivisionError):
497
+ self.G[1][2]["weight"] = 0
498
+ nx.effective_graph_resistance(self.G, "weight")
499
+
500
+ def test_effective_graph_resistance_complete_graph(self):
501
+ N = 10
502
+ G = nx.complete_graph(N)
503
+ RG = nx.effective_graph_resistance(G)
504
+ assert np.isclose(RG, N - 1)
505
+
506
+ def test_effective_graph_resistance_path_graph(self):
507
+ N = 10
508
+ G = nx.path_graph(N)
509
+ RG = nx.effective_graph_resistance(G)
510
+ assert np.isclose(RG, (N - 1) * N * (N + 1) // 6)
511
+
512
+
513
+ class TestBarycenter:
514
+ """Test :func:`networkx.algorithms.distance_measures.barycenter`."""
515
+
516
+ def barycenter_as_subgraph(self, g, **kwargs):
517
+ """Return the subgraph induced on the barycenter of g"""
518
+ b = nx.barycenter(g, **kwargs)
519
+ assert isinstance(b, list)
520
+ assert set(b) <= set(g)
521
+ return g.subgraph(b)
522
+
523
+ def test_must_be_connected(self):
524
+ pytest.raises(nx.NetworkXNoPath, nx.barycenter, nx.empty_graph(5))
525
+
526
+ def test_sp_kwarg(self):
527
+ # Complete graph K_5. Normally it works...
528
+ K_5 = nx.complete_graph(5)
529
+ sp = dict(nx.shortest_path_length(K_5))
530
+ assert nx.barycenter(K_5, sp=sp) == list(K_5)
531
+
532
+ # ...but not with the weight argument
533
+ for u, v, data in K_5.edges.data():
534
+ data["weight"] = 1
535
+ pytest.raises(ValueError, nx.barycenter, K_5, sp=sp, weight="weight")
536
+
537
+ # ...and a corrupted sp can make it seem like K_5 is disconnected
538
+ del sp[0][1]
539
+ pytest.raises(nx.NetworkXNoPath, nx.barycenter, K_5, sp=sp)
540
+
541
+ def test_trees(self):
542
+ """The barycenter of a tree is a single vertex or an edge.
543
+
544
+ See [West01]_, p. 78.
545
+ """
546
+ prng = Random(0xDEADBEEF)
547
+ for i in range(50):
548
+ RT = nx.random_labeled_tree(prng.randint(1, 75), seed=prng)
549
+ b = self.barycenter_as_subgraph(RT)
550
+ if len(b) == 2:
551
+ assert b.size() == 1
552
+ else:
553
+ assert len(b) == 1
554
+ assert b.size() == 0
555
+
556
+ def test_this_one_specific_tree(self):
557
+ """Test the tree pictured at the bottom of [West01]_, p. 78."""
558
+ g = nx.Graph(
559
+ {
560
+ "a": ["b"],
561
+ "b": ["a", "x"],
562
+ "x": ["b", "y"],
563
+ "y": ["x", "z"],
564
+ "z": ["y", 0, 1, 2, 3, 4],
565
+ 0: ["z"],
566
+ 1: ["z"],
567
+ 2: ["z"],
568
+ 3: ["z"],
569
+ 4: ["z"],
570
+ }
571
+ )
572
+ b = self.barycenter_as_subgraph(g, attr="barycentricity")
573
+ assert list(b) == ["z"]
574
+ assert not b.edges
575
+ expected_barycentricity = {
576
+ 0: 23,
577
+ 1: 23,
578
+ 2: 23,
579
+ 3: 23,
580
+ 4: 23,
581
+ "a": 35,
582
+ "b": 27,
583
+ "x": 21,
584
+ "y": 17,
585
+ "z": 15,
586
+ }
587
+ for node, barycentricity in expected_barycentricity.items():
588
+ assert g.nodes[node]["barycentricity"] == barycentricity
589
+
590
+ # Doubling weights should do nothing but double the barycentricities
591
+ for edge in g.edges:
592
+ g.edges[edge]["weight"] = 2
593
+ b = self.barycenter_as_subgraph(g, weight="weight", attr="barycentricity2")
594
+ assert list(b) == ["z"]
595
+ assert not b.edges
596
+ for node, barycentricity in expected_barycentricity.items():
597
+ assert g.nodes[node]["barycentricity2"] == barycentricity * 2
598
+
599
+
600
+ class TestKemenyConstant:
601
+ @classmethod
602
+ def setup_class(cls):
603
+ global np
604
+ np = pytest.importorskip("numpy")
605
+ sp = pytest.importorskip("scipy")
606
+
607
+ def setup_method(self):
608
+ G = nx.Graph()
609
+ w12 = 2
610
+ w13 = 3
611
+ w23 = 4
612
+ G.add_edge(1, 2, weight=w12)
613
+ G.add_edge(1, 3, weight=w13)
614
+ G.add_edge(2, 3, weight=w23)
615
+ self.G = G
616
+
617
+ def test_kemeny_constant_directed(self):
618
+ G = nx.DiGraph()
619
+ G.add_edge(1, 2)
620
+ G.add_edge(1, 3)
621
+ G.add_edge(2, 3)
622
+ with pytest.raises(nx.NetworkXNotImplemented):
623
+ nx.kemeny_constant(G)
624
+
625
+ def test_kemeny_constant_not_connected(self):
626
+ self.G.add_node(5)
627
+ with pytest.raises(nx.NetworkXError):
628
+ nx.kemeny_constant(self.G)
629
+
630
+ def test_kemeny_constant_no_nodes(self):
631
+ G = nx.Graph()
632
+ with pytest.raises(nx.NetworkXError):
633
+ nx.kemeny_constant(G)
634
+
635
+ def test_kemeny_constant_negative_weight(self):
636
+ G = nx.Graph()
637
+ w12 = 2
638
+ w13 = 3
639
+ w23 = -10
640
+ G.add_edge(1, 2, weight=w12)
641
+ G.add_edge(1, 3, weight=w13)
642
+ G.add_edge(2, 3, weight=w23)
643
+ with pytest.raises(nx.NetworkXError):
644
+ nx.kemeny_constant(G, weight="weight")
645
+
646
+ def test_kemeny_constant(self):
647
+ K = nx.kemeny_constant(self.G, weight="weight")
648
+ w12 = 2
649
+ w13 = 3
650
+ w23 = 4
651
+ test_data = (
652
+ 3
653
+ / 2
654
+ * (w12 + w13)
655
+ * (w12 + w23)
656
+ * (w13 + w23)
657
+ / (
658
+ w12**2 * (w13 + w23)
659
+ + w13**2 * (w12 + w23)
660
+ + w23**2 * (w12 + w13)
661
+ + 3 * w12 * w13 * w23
662
+ )
663
+ )
664
+ assert np.isclose(K, test_data)
665
+
666
+ def test_kemeny_constant_no_weight(self):
667
+ K = nx.kemeny_constant(self.G)
668
+ assert np.isclose(K, 4 / 3)
669
+
670
+ def test_kemeny_constant_multigraph(self):
671
+ G = nx.MultiGraph()
672
+ w12_1 = 2
673
+ w12_2 = 1
674
+ w13 = 3
675
+ w23 = 4
676
+ G.add_edge(1, 2, weight=w12_1)
677
+ G.add_edge(1, 2, weight=w12_2)
678
+ G.add_edge(1, 3, weight=w13)
679
+ G.add_edge(2, 3, weight=w23)
680
+ K = nx.kemeny_constant(G, weight="weight")
681
+ w12 = w12_1 + w12_2
682
+ test_data = (
683
+ 3
684
+ / 2
685
+ * (w12 + w13)
686
+ * (w12 + w23)
687
+ * (w13 + w23)
688
+ / (
689
+ w12**2 * (w13 + w23)
690
+ + w13**2 * (w12 + w23)
691
+ + w23**2 * (w12 + w13)
692
+ + 3 * w12 * w13 * w23
693
+ )
694
+ )
695
+ assert np.isclose(K, test_data)
696
+
697
+ def test_kemeny_constant_weight0(self):
698
+ G = nx.Graph()
699
+ w12 = 0
700
+ w13 = 3
701
+ w23 = 4
702
+ G.add_edge(1, 2, weight=w12)
703
+ G.add_edge(1, 3, weight=w13)
704
+ G.add_edge(2, 3, weight=w23)
705
+ K = nx.kemeny_constant(G, weight="weight")
706
+ test_data = (
707
+ 3
708
+ / 2
709
+ * (w12 + w13)
710
+ * (w12 + w23)
711
+ * (w13 + w23)
712
+ / (
713
+ w12**2 * (w13 + w23)
714
+ + w13**2 * (w12 + w23)
715
+ + w23**2 * (w12 + w13)
716
+ + 3 * w12 * w13 * w23
717
+ )
718
+ )
719
+ assert np.isclose(K, test_data)
720
+
721
+ def test_kemeny_constant_selfloop(self):
722
+ G = nx.Graph()
723
+ w11 = 1
724
+ w12 = 2
725
+ w13 = 3
726
+ w23 = 4
727
+ G.add_edge(1, 1, weight=w11)
728
+ G.add_edge(1, 2, weight=w12)
729
+ G.add_edge(1, 3, weight=w13)
730
+ G.add_edge(2, 3, weight=w23)
731
+ K = nx.kemeny_constant(G, weight="weight")
732
+ test_data = (
733
+ (2 * w11 + 3 * w12 + 3 * w13)
734
+ * (w12 + w23)
735
+ * (w13 + w23)
736
+ / (
737
+ (w12 * w13 + w12 * w23 + w13 * w23)
738
+ * (w11 + 2 * w12 + 2 * w13 + 2 * w23)
739
+ )
740
+ )
741
+ assert np.isclose(K, test_data)
742
+
743
+ def test_kemeny_constant_complete_bipartite_graph(self):
744
+ # Theorem 1 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
745
+ n1 = 5
746
+ n2 = 4
747
+ G = nx.complete_bipartite_graph(n1, n2)
748
+ K = nx.kemeny_constant(G)
749
+ assert np.isclose(K, n1 + n2 - 3 / 2)
750
+
751
+ def test_kemeny_constant_path_graph(self):
752
+ # Theorem 2 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
753
+ n = 10
754
+ G = nx.path_graph(n)
755
+ K = nx.kemeny_constant(G)
756
+ assert np.isclose(K, n**2 / 3 - 2 * n / 3 + 1 / 2)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominance.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestImmediateDominators:
7
+ def test_exceptions(self):
8
+ G = nx.Graph()
9
+ G.add_node(0)
10
+ pytest.raises(nx.NetworkXNotImplemented, nx.immediate_dominators, G, 0)
11
+ G = nx.MultiGraph(G)
12
+ pytest.raises(nx.NetworkXNotImplemented, nx.immediate_dominators, G, 0)
13
+ G = nx.DiGraph([[0, 0]])
14
+ pytest.raises(nx.NetworkXError, nx.immediate_dominators, G, 1)
15
+
16
+ def test_singleton(self):
17
+ G = nx.DiGraph()
18
+ G.add_node(0)
19
+ assert nx.immediate_dominators(G, 0) == {0: 0}
20
+ G.add_edge(0, 0)
21
+ assert nx.immediate_dominators(G, 0) == {0: 0}
22
+
23
+ def test_path(self):
24
+ n = 5
25
+ G = nx.path_graph(n, create_using=nx.DiGraph())
26
+ assert nx.immediate_dominators(G, 0) == {i: max(i - 1, 0) for i in range(n)}
27
+
28
+ def test_cycle(self):
29
+ n = 5
30
+ G = nx.cycle_graph(n, create_using=nx.DiGraph())
31
+ assert nx.immediate_dominators(G, 0) == {i: max(i - 1, 0) for i in range(n)}
32
+
33
+ def test_unreachable(self):
34
+ n = 5
35
+ assert n > 1
36
+ G = nx.path_graph(n, create_using=nx.DiGraph())
37
+ assert nx.immediate_dominators(G, n // 2) == {
38
+ i: max(i - 1, n // 2) for i in range(n // 2, n)
39
+ }
40
+
41
+ def test_irreducible1(self):
42
+ # Graph taken from Figure 2 of
43
+ # K. D. Cooper, T. J. Harvey, and K. Kennedy.
44
+ # A simple, fast dominance algorithm.
45
+ # Software Practice & Experience, 4:110, 2001.
46
+ edges = [(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)]
47
+ G = nx.DiGraph(edges)
48
+ assert nx.immediate_dominators(G, 5) == {i: 5 for i in range(1, 6)}
49
+
50
+ def test_irreducible2(self):
51
+ # Graph taken from Figure 4 of
52
+ # K. D. Cooper, T. J. Harvey, and K. Kennedy.
53
+ # A simple, fast dominance algorithm.
54
+ # Software Practice & Experience, 4:110, 2001.
55
+ edges = [(1, 2), (2, 1), (2, 3), (3, 2), (4, 2), (4, 3), (5, 1), (6, 4), (6, 5)]
56
+ G = nx.DiGraph(edges)
57
+ result = nx.immediate_dominators(G, 6)
58
+ assert result == {i: 6 for i in range(1, 7)}
59
+
60
+ def test_domrel_png(self):
61
+ # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
62
+ edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
63
+ G = nx.DiGraph(edges)
64
+ result = nx.immediate_dominators(G, 1)
65
+ assert result == {1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 2}
66
+ # Test postdominance.
67
+ result = nx.immediate_dominators(G.reverse(copy=False), 6)
68
+ assert result == {1: 2, 2: 6, 3: 5, 4: 5, 5: 2, 6: 6}
69
+
70
+ def test_boost_example(self):
71
+ # Graph taken from Figure 1 of
72
+ # http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
73
+ edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
74
+ G = nx.DiGraph(edges)
75
+ result = nx.immediate_dominators(G, 0)
76
+ assert result == {0: 0, 1: 0, 2: 1, 3: 1, 4: 3, 5: 4, 6: 4, 7: 1}
77
+ # Test postdominance.
78
+ result = nx.immediate_dominators(G.reverse(copy=False), 7)
79
+ assert result == {0: 1, 1: 7, 2: 7, 3: 4, 4: 5, 5: 7, 6: 4, 7: 7}
80
+
81
+
82
+ class TestDominanceFrontiers:
83
+ def test_exceptions(self):
84
+ G = nx.Graph()
85
+ G.add_node(0)
86
+ pytest.raises(nx.NetworkXNotImplemented, nx.dominance_frontiers, G, 0)
87
+ G = nx.MultiGraph(G)
88
+ pytest.raises(nx.NetworkXNotImplemented, nx.dominance_frontiers, G, 0)
89
+ G = nx.DiGraph([[0, 0]])
90
+ pytest.raises(nx.NetworkXError, nx.dominance_frontiers, G, 1)
91
+
92
+ def test_singleton(self):
93
+ G = nx.DiGraph()
94
+ G.add_node(0)
95
+ assert nx.dominance_frontiers(G, 0) == {0: set()}
96
+ G.add_edge(0, 0)
97
+ assert nx.dominance_frontiers(G, 0) == {0: set()}
98
+
99
+ def test_path(self):
100
+ n = 5
101
+ G = nx.path_graph(n, create_using=nx.DiGraph())
102
+ assert nx.dominance_frontiers(G, 0) == {i: set() for i in range(n)}
103
+
104
+ def test_cycle(self):
105
+ n = 5
106
+ G = nx.cycle_graph(n, create_using=nx.DiGraph())
107
+ assert nx.dominance_frontiers(G, 0) == {i: set() for i in range(n)}
108
+
109
+ def test_unreachable(self):
110
+ n = 5
111
+ assert n > 1
112
+ G = nx.path_graph(n, create_using=nx.DiGraph())
113
+ assert nx.dominance_frontiers(G, n // 2) == {i: set() for i in range(n // 2, n)}
114
+
115
+ def test_irreducible1(self):
116
+ # Graph taken from Figure 2 of
117
+ # K. D. Cooper, T. J. Harvey, and K. Kennedy.
118
+ # A simple, fast dominance algorithm.
119
+ # Software Practice & Experience, 4:110, 2001.
120
+ edges = [(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)]
121
+ G = nx.DiGraph(edges)
122
+ assert dict(nx.dominance_frontiers(G, 5).items()) == {
123
+ 1: {2},
124
+ 2: {1},
125
+ 3: {2},
126
+ 4: {1},
127
+ 5: set(),
128
+ }
129
+
130
+ def test_irreducible2(self):
131
+ # Graph taken from Figure 4 of
132
+ # K. D. Cooper, T. J. Harvey, and K. Kennedy.
133
+ # A simple, fast dominance algorithm.
134
+ # Software Practice & Experience, 4:110, 2001.
135
+ edges = [(1, 2), (2, 1), (2, 3), (3, 2), (4, 2), (4, 3), (5, 1), (6, 4), (6, 5)]
136
+ G = nx.DiGraph(edges)
137
+ assert nx.dominance_frontiers(G, 6) == {
138
+ 1: {2},
139
+ 2: {1, 3},
140
+ 3: {2},
141
+ 4: {2, 3},
142
+ 5: {1},
143
+ 6: set(),
144
+ }
145
+
146
+ def test_domrel_png(self):
147
+ # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
148
+ edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
149
+ G = nx.DiGraph(edges)
150
+ assert nx.dominance_frontiers(G, 1) == {
151
+ 1: set(),
152
+ 2: {2},
153
+ 3: {5},
154
+ 4: {5},
155
+ 5: {2},
156
+ 6: set(),
157
+ }
158
+ # Test postdominance.
159
+ result = nx.dominance_frontiers(G.reverse(copy=False), 6)
160
+ assert result == {1: set(), 2: {2}, 3: {2}, 4: {2}, 5: {2}, 6: set()}
161
+
162
+ def test_boost_example(self):
163
+ # Graph taken from Figure 1 of
164
+ # http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
165
+ edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
166
+ G = nx.DiGraph(edges)
167
+ assert nx.dominance_frontiers(G, 0) == {
168
+ 0: set(),
169
+ 1: set(),
170
+ 2: {7},
171
+ 3: {7},
172
+ 4: {4, 7},
173
+ 5: {7},
174
+ 6: {4},
175
+ 7: set(),
176
+ }
177
+ # Test postdominance.
178
+ result = nx.dominance_frontiers(G.reverse(copy=False), 7)
179
+ expected = {
180
+ 0: set(),
181
+ 1: set(),
182
+ 2: {1},
183
+ 3: {1},
184
+ 4: {1, 4},
185
+ 5: {1},
186
+ 6: {4},
187
+ 7: set(),
188
+ }
189
+ assert result == expected
190
+
191
+ def test_discard_issue(self):
192
+ # https://github.com/networkx/networkx/issues/2071
193
+ g = nx.DiGraph()
194
+ g.add_edges_from(
195
+ [
196
+ ("b0", "b1"),
197
+ ("b1", "b2"),
198
+ ("b2", "b3"),
199
+ ("b3", "b1"),
200
+ ("b1", "b5"),
201
+ ("b5", "b6"),
202
+ ("b5", "b8"),
203
+ ("b6", "b7"),
204
+ ("b8", "b7"),
205
+ ("b7", "b3"),
206
+ ("b3", "b4"),
207
+ ]
208
+ )
209
+ df = nx.dominance_frontiers(g, "b0")
210
+ assert df == {
211
+ "b4": set(),
212
+ "b5": {"b3"},
213
+ "b6": {"b7"},
214
+ "b7": {"b3"},
215
+ "b0": set(),
216
+ "b1": {"b1"},
217
+ "b2": {"b3"},
218
+ "b3": {"b1"},
219
+ "b8": {"b7"},
220
+ }
221
+
222
+ def test_loop(self):
223
+ g = nx.DiGraph()
224
+ g.add_edges_from([("a", "b"), ("b", "c"), ("b", "a")])
225
+ df = nx.dominance_frontiers(g, "a")
226
+ assert df == {"a": set(), "b": set(), "c": set()}
227
+
228
+ def test_missing_immediate_doms(self):
229
+ # see https://github.com/networkx/networkx/issues/2070
230
+ g = nx.DiGraph()
231
+ edges = [
232
+ ("entry_1", "b1"),
233
+ ("b1", "b2"),
234
+ ("b2", "b3"),
235
+ ("b3", "exit"),
236
+ ("entry_2", "b3"),
237
+ ]
238
+
239
+ # entry_1
240
+ # |
241
+ # b1
242
+ # |
243
+ # b2 entry_2
244
+ # | /
245
+ # b3
246
+ # |
247
+ # exit
248
+
249
+ g.add_edges_from(edges)
250
+ # formerly raised KeyError on entry_2 when parsing b3
251
+ # because entry_2 does not have immediate doms (no path)
252
+ nx.dominance_frontiers(g, "entry_1")
253
+
254
+ def test_loops_larger(self):
255
+ # from
256
+ # http://ecee.colorado.edu/~waite/Darmstadt/motion.html
257
+ g = nx.DiGraph()
258
+ edges = [
259
+ ("entry", "exit"),
260
+ ("entry", "1"),
261
+ ("1", "2"),
262
+ ("2", "3"),
263
+ ("3", "4"),
264
+ ("4", "5"),
265
+ ("5", "6"),
266
+ ("6", "exit"),
267
+ ("6", "2"),
268
+ ("5", "3"),
269
+ ("4", "4"),
270
+ ]
271
+
272
+ g.add_edges_from(edges)
273
+ df = nx.dominance_frontiers(g, "entry")
274
+ answer = {
275
+ "entry": set(),
276
+ "1": {"exit"},
277
+ "2": {"exit", "2"},
278
+ "3": {"exit", "3", "2"},
279
+ "4": {"exit", "4", "3", "2"},
280
+ "5": {"exit", "3", "2"},
281
+ "6": {"exit", "2"},
282
+ "exit": set(),
283
+ }
284
+ for n in df:
285
+ assert set(df[n]) == set(answer[n])
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_dominating_set():
7
+ G = nx.gnp_random_graph(100, 0.1)
8
+ D = nx.dominating_set(G)
9
+ assert nx.is_dominating_set(G, D)
10
+ D = nx.dominating_set(G, start_with=0)
11
+ assert nx.is_dominating_set(G, D)
12
+
13
+
14
+ def test_complete():
15
+ """In complete graphs each node is a dominating set.
16
+ Thus the dominating set has to be of cardinality 1.
17
+ """
18
+ K4 = nx.complete_graph(4)
19
+ assert len(nx.dominating_set(K4)) == 1
20
+ K5 = nx.complete_graph(5)
21
+ assert len(nx.dominating_set(K5)) == 1
22
+
23
+
24
+ def test_raise_dominating_set():
25
+ with pytest.raises(nx.NetworkXError):
26
+ G = nx.path_graph(4)
27
+ D = nx.dominating_set(G, start_with=10)
28
+
29
+
30
+ def test_is_dominating_set():
31
+ G = nx.path_graph(4)
32
+ d = {1, 3}
33
+ assert nx.is_dominating_set(G, d)
34
+ d = {0, 2}
35
+ assert nx.is_dominating_set(G, d)
36
+ d = {1}
37
+ assert not nx.is_dominating_set(G, d)
38
+
39
+
40
+ def test_wikipedia_is_dominating_set():
41
+ """Example from https://en.wikipedia.org/wiki/Dominating_set"""
42
+ G = nx.cycle_graph(4)
43
+ G.add_edges_from([(0, 4), (1, 4), (2, 5)])
44
+ assert nx.is_dominating_set(G, {4, 3, 5})
45
+ assert nx.is_dominating_set(G, {0, 2})
46
+ assert nx.is_dominating_set(G, {1, 2})
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_efficiency.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.efficiency` module."""
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestEfficiency:
7
+ def setup_method(self):
8
+ # G1 is a disconnected graph
9
+ self.G1 = nx.Graph()
10
+ self.G1.add_nodes_from([1, 2, 3])
11
+ # G2 is a cycle graph
12
+ self.G2 = nx.cycle_graph(4)
13
+ # G3 is the triangle graph with one additional edge
14
+ self.G3 = nx.lollipop_graph(3, 1)
15
+
16
+ def test_efficiency_disconnected_nodes(self):
17
+ """
18
+ When nodes are disconnected, efficiency is 0
19
+ """
20
+ assert nx.efficiency(self.G1, 1, 2) == 0
21
+
22
+ def test_local_efficiency_disconnected_graph(self):
23
+ """
24
+ In a disconnected graph the efficiency is 0
25
+ """
26
+ assert nx.local_efficiency(self.G1) == 0
27
+
28
+ def test_efficiency(self):
29
+ assert nx.efficiency(self.G2, 0, 1) == 1
30
+ assert nx.efficiency(self.G2, 0, 2) == 1 / 2
31
+
32
+ def test_global_efficiency(self):
33
+ assert nx.global_efficiency(self.G2) == 5 / 6
34
+
35
+ def test_global_efficiency_complete_graph(self):
36
+ """
37
+ Tests that the average global efficiency of the complete graph is one.
38
+ """
39
+ for n in range(2, 10):
40
+ G = nx.complete_graph(n)
41
+ assert nx.global_efficiency(G) == 1
42
+
43
+ def test_local_efficiency_complete_graph(self):
44
+ """
45
+ Test that the local efficiency for a complete graph with at least 3
46
+ nodes should be one. For a graph with only 2 nodes, the induced
47
+ subgraph has no edges.
48
+ """
49
+ for n in range(3, 10):
50
+ G = nx.complete_graph(n)
51
+ assert nx.local_efficiency(G) == 1
52
+
53
+ def test_using_ego_graph(self):
54
+ """
55
+ Test that the ego graph is used when computing local efficiency.
56
+ For more information, see GitHub issue #2710.
57
+ """
58
+ assert nx.local_efficiency(self.G3) == 7 / 12
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_euler.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ @pytest.mark.parametrize("f", (nx.is_eulerian, nx.is_semieulerian))
9
+ def test_empty_graph_raises(f):
10
+ G = nx.Graph()
11
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
12
+ f(G)
13
+
14
+
15
+ class TestIsEulerian:
16
+ def test_is_eulerian(self):
17
+ assert nx.is_eulerian(nx.complete_graph(5))
18
+ assert nx.is_eulerian(nx.complete_graph(7))
19
+ assert nx.is_eulerian(nx.hypercube_graph(4))
20
+ assert nx.is_eulerian(nx.hypercube_graph(6))
21
+
22
+ assert not nx.is_eulerian(nx.complete_graph(4))
23
+ assert not nx.is_eulerian(nx.complete_graph(6))
24
+ assert not nx.is_eulerian(nx.hypercube_graph(3))
25
+ assert not nx.is_eulerian(nx.hypercube_graph(5))
26
+
27
+ assert not nx.is_eulerian(nx.petersen_graph())
28
+ assert not nx.is_eulerian(nx.path_graph(4))
29
+
30
+ def test_is_eulerian2(self):
31
+ # not connected
32
+ G = nx.Graph()
33
+ G.add_nodes_from([1, 2, 3])
34
+ assert not nx.is_eulerian(G)
35
+ # not strongly connected
36
+ G = nx.DiGraph()
37
+ G.add_nodes_from([1, 2, 3])
38
+ assert not nx.is_eulerian(G)
39
+ G = nx.MultiDiGraph()
40
+ G.add_edge(1, 2)
41
+ G.add_edge(2, 3)
42
+ G.add_edge(2, 3)
43
+ G.add_edge(3, 1)
44
+ assert not nx.is_eulerian(G)
45
+
46
+
47
+ class TestEulerianCircuit:
48
+ def test_eulerian_circuit_cycle(self):
49
+ G = nx.cycle_graph(4)
50
+
51
+ edges = list(nx.eulerian_circuit(G, source=0))
52
+ nodes = [u for u, v in edges]
53
+ assert nodes == [0, 3, 2, 1]
54
+ assert edges == [(0, 3), (3, 2), (2, 1), (1, 0)]
55
+
56
+ edges = list(nx.eulerian_circuit(G, source=1))
57
+ nodes = [u for u, v in edges]
58
+ assert nodes == [1, 2, 3, 0]
59
+ assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
60
+
61
+ G = nx.complete_graph(3)
62
+
63
+ edges = list(nx.eulerian_circuit(G, source=0))
64
+ nodes = [u for u, v in edges]
65
+ assert nodes == [0, 2, 1]
66
+ assert edges == [(0, 2), (2, 1), (1, 0)]
67
+
68
+ edges = list(nx.eulerian_circuit(G, source=1))
69
+ nodes = [u for u, v in edges]
70
+ assert nodes == [1, 2, 0]
71
+ assert edges == [(1, 2), (2, 0), (0, 1)]
72
+
73
+ def test_eulerian_circuit_digraph(self):
74
+ G = nx.DiGraph()
75
+ nx.add_cycle(G, [0, 1, 2, 3])
76
+
77
+ edges = list(nx.eulerian_circuit(G, source=0))
78
+ nodes = [u for u, v in edges]
79
+ assert nodes == [0, 1, 2, 3]
80
+ assert edges == [(0, 1), (1, 2), (2, 3), (3, 0)]
81
+
82
+ edges = list(nx.eulerian_circuit(G, source=1))
83
+ nodes = [u for u, v in edges]
84
+ assert nodes == [1, 2, 3, 0]
85
+ assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
86
+
87
+ def test_multigraph(self):
88
+ G = nx.MultiGraph()
89
+ nx.add_cycle(G, [0, 1, 2, 3])
90
+ G.add_edge(1, 2)
91
+ G.add_edge(1, 2)
92
+ edges = list(nx.eulerian_circuit(G, source=0))
93
+ nodes = [u for u, v in edges]
94
+ assert nodes == [0, 3, 2, 1, 2, 1]
95
+ assert edges == [(0, 3), (3, 2), (2, 1), (1, 2), (2, 1), (1, 0)]
96
+
97
+ def test_multigraph_with_keys(self):
98
+ G = nx.MultiGraph()
99
+ nx.add_cycle(G, [0, 1, 2, 3])
100
+ G.add_edge(1, 2)
101
+ G.add_edge(1, 2)
102
+ edges = list(nx.eulerian_circuit(G, source=0, keys=True))
103
+ nodes = [u for u, v, k in edges]
104
+ assert nodes == [0, 3, 2, 1, 2, 1]
105
+ assert edges[:2] == [(0, 3, 0), (3, 2, 0)]
106
+ assert collections.Counter(edges[2:5]) == collections.Counter(
107
+ [(2, 1, 0), (1, 2, 1), (2, 1, 2)]
108
+ )
109
+ assert edges[5:] == [(1, 0, 0)]
110
+
111
+ def test_not_eulerian(self):
112
+ with pytest.raises(nx.NetworkXError):
113
+ f = list(nx.eulerian_circuit(nx.complete_graph(4)))
114
+
115
+
116
+ class TestIsSemiEulerian:
117
+ def test_is_semieulerian(self):
118
+ # Test graphs with Eulerian paths but no cycles return True.
119
+ assert nx.is_semieulerian(nx.path_graph(4))
120
+ G = nx.path_graph(6, create_using=nx.DiGraph)
121
+ assert nx.is_semieulerian(G)
122
+
123
+ # Test graphs with Eulerian cycles return False.
124
+ assert not nx.is_semieulerian(nx.complete_graph(5))
125
+ assert not nx.is_semieulerian(nx.complete_graph(7))
126
+ assert not nx.is_semieulerian(nx.hypercube_graph(4))
127
+ assert not nx.is_semieulerian(nx.hypercube_graph(6))
128
+
129
+
130
+ class TestHasEulerianPath:
131
+ def test_has_eulerian_path_cyclic(self):
132
+ # Test graphs with Eulerian cycles return True.
133
+ assert nx.has_eulerian_path(nx.complete_graph(5))
134
+ assert nx.has_eulerian_path(nx.complete_graph(7))
135
+ assert nx.has_eulerian_path(nx.hypercube_graph(4))
136
+ assert nx.has_eulerian_path(nx.hypercube_graph(6))
137
+
138
+ def test_has_eulerian_path_non_cyclic(self):
139
+ # Test graphs with Eulerian paths but no cycles return True.
140
+ assert nx.has_eulerian_path(nx.path_graph(4))
141
+ G = nx.path_graph(6, create_using=nx.DiGraph)
142
+ assert nx.has_eulerian_path(G)
143
+
144
+ def test_has_eulerian_path_directed_graph(self):
145
+ # Test directed graphs and returns False
146
+ G = nx.DiGraph()
147
+ G.add_edges_from([(0, 1), (1, 2), (0, 2)])
148
+ assert not nx.has_eulerian_path(G)
149
+
150
+ # Test directed graphs without isolated node returns True
151
+ G = nx.DiGraph()
152
+ G.add_edges_from([(0, 1), (1, 2), (2, 0)])
153
+ assert nx.has_eulerian_path(G)
154
+
155
+ # Test directed graphs with isolated node returns False
156
+ G.add_node(3)
157
+ assert not nx.has_eulerian_path(G)
158
+
159
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
160
+ def test_has_eulerian_path_not_weakly_connected(self, G):
161
+ G.add_edges_from([(0, 1), (2, 3), (3, 2)])
162
+ assert not nx.has_eulerian_path(G)
163
+
164
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
165
+ def test_has_eulerian_path_unbalancedins_more_than_one(self, G):
166
+ G.add_edges_from([(0, 1), (2, 3)])
167
+ assert not nx.has_eulerian_path(G)
168
+
169
+
170
+ class TestFindPathStart:
171
+ def testfind_path_start(self):
172
+ find_path_start = nx.algorithms.euler._find_path_start
173
+ # Test digraphs return correct starting node.
174
+ G = nx.path_graph(6, create_using=nx.DiGraph)
175
+ assert find_path_start(G) == 0
176
+ edges = [(0, 1), (1, 2), (2, 0), (4, 0)]
177
+ assert find_path_start(nx.DiGraph(edges)) == 4
178
+
179
+ # Test graph with no Eulerian path return None.
180
+ edges = [(0, 1), (1, 2), (2, 3), (2, 4)]
181
+ assert find_path_start(nx.DiGraph(edges)) is None
182
+
183
+
184
+ class TestEulerianPath:
185
+ def test_eulerian_path(self):
186
+ x = [(4, 0), (0, 1), (1, 2), (2, 0)]
187
+ for e1, e2 in zip(x, nx.eulerian_path(nx.DiGraph(x))):
188
+ assert e1 == e2
189
+
190
+ def test_eulerian_path_straight_link(self):
191
+ G = nx.DiGraph()
192
+ result = [(1, 2), (2, 3), (3, 4), (4, 5)]
193
+ G.add_edges_from(result)
194
+ assert result == list(nx.eulerian_path(G))
195
+ assert result == list(nx.eulerian_path(G, source=1))
196
+ with pytest.raises(nx.NetworkXError):
197
+ list(nx.eulerian_path(G, source=3))
198
+ with pytest.raises(nx.NetworkXError):
199
+ list(nx.eulerian_path(G, source=4))
200
+ with pytest.raises(nx.NetworkXError):
201
+ list(nx.eulerian_path(G, source=5))
202
+
203
+ def test_eulerian_path_multigraph(self):
204
+ G = nx.MultiDiGraph()
205
+ result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4), (4, 3)]
206
+ G.add_edges_from(result)
207
+ assert result == list(nx.eulerian_path(G))
208
+ assert result == list(nx.eulerian_path(G, source=2))
209
+ with pytest.raises(nx.NetworkXError):
210
+ list(nx.eulerian_path(G, source=3))
211
+ with pytest.raises(nx.NetworkXError):
212
+ list(nx.eulerian_path(G, source=4))
213
+
214
+ def test_eulerian_path_eulerian_circuit(self):
215
+ G = nx.DiGraph()
216
+ result = [(1, 2), (2, 3), (3, 4), (4, 1)]
217
+ result2 = [(2, 3), (3, 4), (4, 1), (1, 2)]
218
+ result3 = [(3, 4), (4, 1), (1, 2), (2, 3)]
219
+ G.add_edges_from(result)
220
+ assert result == list(nx.eulerian_path(G))
221
+ assert result == list(nx.eulerian_path(G, source=1))
222
+ assert result2 == list(nx.eulerian_path(G, source=2))
223
+ assert result3 == list(nx.eulerian_path(G, source=3))
224
+
225
+ def test_eulerian_path_undirected(self):
226
+ G = nx.Graph()
227
+ result = [(1, 2), (2, 3), (3, 4), (4, 5)]
228
+ result2 = [(5, 4), (4, 3), (3, 2), (2, 1)]
229
+ G.add_edges_from(result)
230
+ assert list(nx.eulerian_path(G)) in (result, result2)
231
+ assert result == list(nx.eulerian_path(G, source=1))
232
+ assert result2 == list(nx.eulerian_path(G, source=5))
233
+ with pytest.raises(nx.NetworkXError):
234
+ list(nx.eulerian_path(G, source=3))
235
+ with pytest.raises(nx.NetworkXError):
236
+ list(nx.eulerian_path(G, source=2))
237
+
238
+ def test_eulerian_path_multigraph_undirected(self):
239
+ G = nx.MultiGraph()
240
+ result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4)]
241
+ G.add_edges_from(result)
242
+ assert result == list(nx.eulerian_path(G))
243
+ assert result == list(nx.eulerian_path(G, source=2))
244
+ with pytest.raises(nx.NetworkXError):
245
+ list(nx.eulerian_path(G, source=3))
246
+ with pytest.raises(nx.NetworkXError):
247
+ list(nx.eulerian_path(G, source=1))
248
+
249
+ @pytest.mark.parametrize(
250
+ ("graph_type", "result"),
251
+ (
252
+ (nx.MultiGraph, [(0, 1, 0), (1, 0, 1)]),
253
+ (nx.MultiDiGraph, [(0, 1, 0), (1, 0, 0)]),
254
+ ),
255
+ )
256
+ def test_eulerian_with_keys(self, graph_type, result):
257
+ G = graph_type([(0, 1), (1, 0)])
258
+ answer = nx.eulerian_path(G, keys=True)
259
+ assert list(answer) == result
260
+
261
+
262
+ class TestEulerize:
263
+ def test_disconnected(self):
264
+ with pytest.raises(nx.NetworkXError):
265
+ G = nx.from_edgelist([(0, 1), (2, 3)])
266
+ nx.eulerize(G)
267
+
268
+ def test_null_graph(self):
269
+ with pytest.raises(nx.NetworkXPointlessConcept):
270
+ nx.eulerize(nx.Graph())
271
+
272
+ def test_null_multigraph(self):
273
+ with pytest.raises(nx.NetworkXPointlessConcept):
274
+ nx.eulerize(nx.MultiGraph())
275
+
276
+ def test_on_empty_graph(self):
277
+ with pytest.raises(nx.NetworkXError):
278
+ nx.eulerize(nx.empty_graph(3))
279
+
280
+ def test_on_eulerian(self):
281
+ G = nx.cycle_graph(3)
282
+ H = nx.eulerize(G)
283
+ assert nx.is_isomorphic(G, H)
284
+
285
+ def test_on_eulerian_multigraph(self):
286
+ G = nx.MultiGraph(nx.cycle_graph(3))
287
+ G.add_edge(0, 1)
288
+ H = nx.eulerize(G)
289
+ assert nx.is_eulerian(H)
290
+
291
+ def test_on_complete_graph(self):
292
+ G = nx.complete_graph(4)
293
+ assert nx.is_eulerian(nx.eulerize(G))
294
+ assert nx.is_eulerian(nx.eulerize(nx.MultiGraph(G)))
295
+
296
+ def test_on_non_eulerian_graph(self):
297
+ G = nx.cycle_graph(18)
298
+ G.add_edge(0, 18)
299
+ G.add_edge(18, 19)
300
+ G.add_edge(17, 19)
301
+ G.add_edge(4, 20)
302
+ G.add_edge(20, 21)
303
+ G.add_edge(21, 22)
304
+ G.add_edge(22, 23)
305
+ G.add_edge(23, 24)
306
+ G.add_edge(24, 25)
307
+ G.add_edge(25, 26)
308
+ G.add_edge(26, 27)
309
+ G.add_edge(27, 28)
310
+ G.add_edge(28, 13)
311
+ assert not nx.is_eulerian(G)
312
+ G = nx.eulerize(G)
313
+ assert nx.is_eulerian(G)
314
+ assert nx.number_of_edges(G) == 39
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_graph_hashing.py ADDED
@@ -0,0 +1,686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.generators import directed
5
+
6
+ # Unit tests for the :func:`~networkx.weisfeiler_lehman_graph_hash` function
7
+
8
+
9
+ def test_empty_graph_hash():
10
+ """
11
+ empty graphs should give hashes regardless of other params
12
+ """
13
+ G1 = nx.empty_graph()
14
+ G2 = nx.empty_graph()
15
+
16
+ h1 = nx.weisfeiler_lehman_graph_hash(G1)
17
+ h2 = nx.weisfeiler_lehman_graph_hash(G2)
18
+ h3 = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="edge_attr1")
19
+ h4 = nx.weisfeiler_lehman_graph_hash(G2, node_attr="node_attr1")
20
+ h5 = nx.weisfeiler_lehman_graph_hash(
21
+ G2, edge_attr="edge_attr1", node_attr="node_attr1"
22
+ )
23
+ h6 = nx.weisfeiler_lehman_graph_hash(G2, iterations=10)
24
+
25
+ assert h1 == h2
26
+ assert h1 == h3
27
+ assert h1 == h4
28
+ assert h1 == h5
29
+ assert h1 == h6
30
+
31
+
32
+ def test_directed():
33
+ """
34
+ A directed graph with no bi-directional edges should yield different a graph hash
35
+ to the same graph taken as undirected if there are no hash collisions.
36
+ """
37
+ r = 10
38
+ for i in range(r):
39
+ G_directed = nx.gn_graph(10 + r, seed=100 + i)
40
+ G_undirected = nx.to_undirected(G_directed)
41
+
42
+ h_directed = nx.weisfeiler_lehman_graph_hash(G_directed)
43
+ h_undirected = nx.weisfeiler_lehman_graph_hash(G_undirected)
44
+
45
+ assert h_directed != h_undirected
46
+
47
+
48
+ def test_reversed():
49
+ """
50
+ A directed graph with no bi-directional edges should yield different a graph hash
51
+ to the same graph taken with edge directions reversed if there are no hash collisions.
52
+ Here we test a cycle graph which is the minimal counterexample
53
+ """
54
+ G = nx.cycle_graph(5, create_using=nx.DiGraph)
55
+ nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
56
+
57
+ G_reversed = G.reverse()
58
+
59
+ h = nx.weisfeiler_lehman_graph_hash(G, node_attr="label")
60
+ h_reversed = nx.weisfeiler_lehman_graph_hash(G_reversed, node_attr="label")
61
+
62
+ assert h != h_reversed
63
+
64
+
65
+ def test_isomorphic():
66
+ """
67
+ graph hashes should be invariant to node-relabeling (when the output is reindexed
68
+ by the same mapping)
69
+ """
70
+ n, r = 100, 10
71
+ p = 1.0 / r
72
+ for i in range(1, r + 1):
73
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
74
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
75
+
76
+ g1_hash = nx.weisfeiler_lehman_graph_hash(G1)
77
+ g2_hash = nx.weisfeiler_lehman_graph_hash(G2)
78
+
79
+ assert g1_hash == g2_hash
80
+
81
+
82
+ def test_isomorphic_edge_attr():
83
+ """
84
+ Isomorphic graphs with differing edge attributes should yield different graph
85
+ hashes if the 'edge_attr' argument is supplied and populated in the graph,
86
+ and there are no hash collisions.
87
+ The output should still be invariant to node-relabeling
88
+ """
89
+ n, r = 100, 10
90
+ p = 1.0 / r
91
+ for i in range(1, r + 1):
92
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
93
+
94
+ for a, b in G1.edges:
95
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
96
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
97
+
98
+ g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
99
+ G1, edge_attr="edge_attr1"
100
+ )
101
+ g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
102
+ G1, edge_attr="edge_attr2"
103
+ )
104
+ g1_hash_no_edge_attr = nx.weisfeiler_lehman_graph_hash(G1, edge_attr=None)
105
+
106
+ assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
107
+ assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
108
+ assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
109
+
110
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
111
+
112
+ g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
113
+ G2, edge_attr="edge_attr1"
114
+ )
115
+ g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
116
+ G2, edge_attr="edge_attr2"
117
+ )
118
+
119
+ assert g1_hash_with_edge_attr1 == g2_hash_with_edge_attr1
120
+ assert g1_hash_with_edge_attr2 == g2_hash_with_edge_attr2
121
+
122
+
123
+ def test_missing_edge_attr():
124
+ """
125
+ If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
126
+ we should raise a KeyError
127
+ """
128
+ G = nx.Graph()
129
+ G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
130
+ pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, edge_attr="edge_attr1")
131
+
132
+
133
+ def test_isomorphic_node_attr():
134
+ """
135
+ Isomorphic graphs with differing node attributes should yield different graph
136
+ hashes if the 'node_attr' argument is supplied and populated in the graph, and
137
+ there are no hash collisions.
138
+ The output should still be invariant to node-relabeling
139
+ """
140
+ n, r = 100, 10
141
+ p = 1.0 / r
142
+ for i in range(1, r + 1):
143
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
144
+
145
+ for u in G1.nodes():
146
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
147
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
148
+
149
+ g1_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
150
+ G1, node_attr="node_attr1"
151
+ )
152
+ g1_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
153
+ G1, node_attr="node_attr2"
154
+ )
155
+ g1_hash_no_node_attr = nx.weisfeiler_lehman_graph_hash(G1, node_attr=None)
156
+
157
+ assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
158
+ assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
159
+ assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
160
+
161
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
162
+
163
+ g2_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
164
+ G2, node_attr="node_attr1"
165
+ )
166
+ g2_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
167
+ G2, node_attr="node_attr2"
168
+ )
169
+
170
+ assert g1_hash_with_node_attr1 == g2_hash_with_node_attr1
171
+ assert g1_hash_with_node_attr2 == g2_hash_with_node_attr2
172
+
173
+
174
+ def test_missing_node_attr():
175
+ """
176
+ If the 'node_attr' argument is supplied but is missing from a node in the graph,
177
+ we should raise a KeyError
178
+ """
179
+ G = nx.Graph()
180
+ G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
181
+ G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
182
+ pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, node_attr="node_attr1")
183
+
184
+
185
+ def test_isomorphic_edge_attr_and_node_attr():
186
+ """
187
+ Isomorphic graphs with differing node attributes should yield different graph
188
+ hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
189
+ the graph, and there are no hash collisions.
190
+ The output should still be invariant to node-relabeling
191
+ """
192
+ n, r = 100, 10
193
+ p = 1.0 / r
194
+ for i in range(1, r + 1):
195
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
196
+
197
+ for u in G1.nodes():
198
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
199
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
200
+
201
+ for a, b in G1.edges:
202
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
203
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
204
+
205
+ g1_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
206
+ G1, edge_attr="edge_attr1", node_attr="node_attr1"
207
+ )
208
+ g1_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
209
+ G1, edge_attr="edge_attr2", node_attr="node_attr2"
210
+ )
211
+ g1_hash_edge1_node2 = nx.weisfeiler_lehman_graph_hash(
212
+ G1, edge_attr="edge_attr1", node_attr="node_attr2"
213
+ )
214
+ g1_hash_no_attr = nx.weisfeiler_lehman_graph_hash(G1)
215
+
216
+ assert g1_hash_edge1_node1 != g1_hash_no_attr
217
+ assert g1_hash_edge2_node2 != g1_hash_no_attr
218
+ assert g1_hash_edge1_node1 != g1_hash_edge2_node2
219
+ assert g1_hash_edge1_node2 != g1_hash_edge2_node2
220
+ assert g1_hash_edge1_node2 != g1_hash_edge1_node1
221
+
222
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
223
+
224
+ g2_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
225
+ G2, edge_attr="edge_attr1", node_attr="node_attr1"
226
+ )
227
+ g2_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
228
+ G2, edge_attr="edge_attr2", node_attr="node_attr2"
229
+ )
230
+
231
+ assert g1_hash_edge1_node1 == g2_hash_edge1_node1
232
+ assert g1_hash_edge2_node2 == g2_hash_edge2_node2
233
+
234
+
235
+ def test_digest_size():
236
+ """
237
+ The hash string lengths should be as expected for a variety of graphs and
238
+ digest sizes
239
+ """
240
+ n, r = 100, 10
241
+ p = 1.0 / r
242
+ for i in range(1, r + 1):
243
+ G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
244
+
245
+ h16 = nx.weisfeiler_lehman_graph_hash(G)
246
+ h32 = nx.weisfeiler_lehman_graph_hash(G, digest_size=32)
247
+
248
+ assert h16 != h32
249
+ assert len(h16) == 16 * 2
250
+ assert len(h32) == 32 * 2
251
+
252
+
253
+ # Unit tests for the :func:`~networkx.weisfeiler_lehman_hash_subgraphs` function
254
+
255
+
256
+ def is_subiteration(a, b):
257
+ """
258
+ returns True if that each hash sequence in 'a' is a prefix for
259
+ the corresponding sequence indexed by the same node in 'b'.
260
+ """
261
+ return all(b[node][: len(hashes)] == hashes for node, hashes in a.items())
262
+
263
+
264
+ def hexdigest_sizes_correct(a, digest_size):
265
+ """
266
+ returns True if all hex digest sizes are the expected length in a node:subgraph-hashes
267
+ dictionary. Hex digest string length == 2 * bytes digest length since each pair of hex
268
+ digits encodes 1 byte (https://docs.python.org/3/library/hashlib.html)
269
+ """
270
+ hexdigest_size = digest_size * 2
271
+ list_digest_sizes_correct = lambda l: all(len(x) == hexdigest_size for x in l)
272
+ return all(list_digest_sizes_correct(hashes) for hashes in a.values())
273
+
274
+
275
+ def test_empty_graph_subgraph_hash():
276
+ """ "
277
+ empty graphs should give empty dict subgraph hashes regardless of other params
278
+ """
279
+ G = nx.empty_graph()
280
+
281
+ subgraph_hashes1 = nx.weisfeiler_lehman_subgraph_hashes(G)
282
+ subgraph_hashes2 = nx.weisfeiler_lehman_subgraph_hashes(G, edge_attr="edge_attr")
283
+ subgraph_hashes3 = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="edge_attr")
284
+ subgraph_hashes4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=2)
285
+ subgraph_hashes5 = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=64)
286
+
287
+ assert subgraph_hashes1 == {}
288
+ assert subgraph_hashes2 == {}
289
+ assert subgraph_hashes3 == {}
290
+ assert subgraph_hashes4 == {}
291
+ assert subgraph_hashes5 == {}
292
+
293
+
294
+ def test_directed_subgraph_hash():
295
+ """
296
+ A directed graph with no bi-directional edges should yield different subgraph hashes
297
+ to the same graph taken as undirected, if all hashes don't collide.
298
+ """
299
+ r = 10
300
+ for i in range(r):
301
+ G_directed = nx.gn_graph(10 + r, seed=100 + i)
302
+ G_undirected = nx.to_undirected(G_directed)
303
+
304
+ directed_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_directed)
305
+ undirected_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_undirected)
306
+
307
+ assert directed_subgraph_hashes != undirected_subgraph_hashes
308
+
309
+
310
+ def test_reversed_subgraph_hash():
311
+ """
312
+ A directed graph with no bi-directional edges should yield different subgraph hashes
313
+ to the same graph taken with edge directions reversed if there are no hash collisions.
314
+ Here we test a cycle graph which is the minimal counterexample
315
+ """
316
+ G = nx.cycle_graph(5, create_using=nx.DiGraph)
317
+ nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
318
+
319
+ G_reversed = G.reverse()
320
+
321
+ h = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
322
+ h_reversed = nx.weisfeiler_lehman_subgraph_hashes(G_reversed, node_attr="label")
323
+
324
+ assert h != h_reversed
325
+
326
+
327
+ def test_isomorphic_subgraph_hash():
328
+ """
329
+ the subgraph hashes should be invariant to node-relabeling when the output is reindexed
330
+ by the same mapping and all hashes don't collide.
331
+ """
332
+ n, r = 100, 10
333
+ p = 1.0 / r
334
+ for i in range(1, r + 1):
335
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
336
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
337
+
338
+ g1_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G1)
339
+ g2_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G2)
340
+
341
+ assert g1_subgraph_hashes == {-1 * k: v for k, v in g2_subgraph_hashes.items()}
342
+
343
+
344
+ def test_isomorphic_edge_attr_subgraph_hash():
345
+ """
346
+ Isomorphic graphs with differing edge attributes should yield different subgraph
347
+ hashes if the 'edge_attr' argument is supplied and populated in the graph, and
348
+ all hashes don't collide.
349
+ The output should still be invariant to node-relabeling
350
+ """
351
+ n, r = 100, 10
352
+ p = 1.0 / r
353
+ for i in range(1, r + 1):
354
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
355
+
356
+ for a, b in G1.edges:
357
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
358
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
359
+
360
+ g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
361
+ G1, edge_attr="edge_attr1"
362
+ )
363
+ g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
364
+ G1, edge_attr="edge_attr2"
365
+ )
366
+ g1_hash_no_edge_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, edge_attr=None)
367
+
368
+ assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
369
+ assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
370
+ assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
371
+
372
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
373
+
374
+ g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
375
+ G2, edge_attr="edge_attr1"
376
+ )
377
+ g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
378
+ G2, edge_attr="edge_attr2"
379
+ )
380
+
381
+ assert g1_hash_with_edge_attr1 == {
382
+ -1 * k: v for k, v in g2_hash_with_edge_attr1.items()
383
+ }
384
+ assert g1_hash_with_edge_attr2 == {
385
+ -1 * k: v for k, v in g2_hash_with_edge_attr2.items()
386
+ }
387
+
388
+
389
+ def test_missing_edge_attr_subgraph_hash():
390
+ """
391
+ If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
392
+ we should raise a KeyError
393
+ """
394
+ G = nx.Graph()
395
+ G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
396
+ pytest.raises(
397
+ KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, edge_attr="edge_attr1"
398
+ )
399
+
400
+
401
+ def test_isomorphic_node_attr_subgraph_hash():
402
+ """
403
+ Isomorphic graphs with differing node attributes should yield different subgraph
404
+ hashes if the 'node_attr' argument is supplied and populated in the graph, and
405
+ all hashes don't collide.
406
+ The output should still be invariant to node-relabeling
407
+ """
408
+ n, r = 100, 10
409
+ p = 1.0 / r
410
+ for i in range(1, r + 1):
411
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
412
+
413
+ for u in G1.nodes():
414
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
415
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
416
+
417
+ g1_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
418
+ G1, node_attr="node_attr1"
419
+ )
420
+ g1_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
421
+ G1, node_attr="node_attr2"
422
+ )
423
+ g1_hash_no_node_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, node_attr=None)
424
+
425
+ assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
426
+ assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
427
+ assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
428
+
429
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
430
+
431
+ g2_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
432
+ G2, node_attr="node_attr1"
433
+ )
434
+ g2_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
435
+ G2, node_attr="node_attr2"
436
+ )
437
+
438
+ assert g1_hash_with_node_attr1 == {
439
+ -1 * k: v for k, v in g2_hash_with_node_attr1.items()
440
+ }
441
+ assert g1_hash_with_node_attr2 == {
442
+ -1 * k: v for k, v in g2_hash_with_node_attr2.items()
443
+ }
444
+
445
+
446
+ def test_missing_node_attr_subgraph_hash():
447
+ """
448
+ If the 'node_attr' argument is supplied but is missing from a node in the graph,
449
+ we should raise a KeyError
450
+ """
451
+ G = nx.Graph()
452
+ G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
453
+ G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
454
+ pytest.raises(
455
+ KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, node_attr="node_attr1"
456
+ )
457
+
458
+
459
+ def test_isomorphic_edge_attr_and_node_attr_subgraph_hash():
460
+ """
461
+ Isomorphic graphs with differing node attributes should yield different subgraph
462
+ hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
463
+ the graph, and all hashes don't collide
464
+ The output should still be invariant to node-relabeling
465
+ """
466
+ n, r = 100, 10
467
+ p = 1.0 / r
468
+ for i in range(1, r + 1):
469
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
470
+
471
+ for u in G1.nodes():
472
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
473
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
474
+
475
+ for a, b in G1.edges:
476
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
477
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
478
+
479
+ g1_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
480
+ G1, edge_attr="edge_attr1", node_attr="node_attr1"
481
+ )
482
+ g1_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
483
+ G1, edge_attr="edge_attr2", node_attr="node_attr2"
484
+ )
485
+ g1_hash_edge1_node2 = nx.weisfeiler_lehman_subgraph_hashes(
486
+ G1, edge_attr="edge_attr1", node_attr="node_attr2"
487
+ )
488
+ g1_hash_no_attr = nx.weisfeiler_lehman_subgraph_hashes(G1)
489
+
490
+ assert g1_hash_edge1_node1 != g1_hash_no_attr
491
+ assert g1_hash_edge2_node2 != g1_hash_no_attr
492
+ assert g1_hash_edge1_node1 != g1_hash_edge2_node2
493
+ assert g1_hash_edge1_node2 != g1_hash_edge2_node2
494
+ assert g1_hash_edge1_node2 != g1_hash_edge1_node1
495
+
496
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
497
+
498
+ g2_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
499
+ G2, edge_attr="edge_attr1", node_attr="node_attr1"
500
+ )
501
+ g2_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
502
+ G2, edge_attr="edge_attr2", node_attr="node_attr2"
503
+ )
504
+
505
+ assert g1_hash_edge1_node1 == {
506
+ -1 * k: v for k, v in g2_hash_edge1_node1.items()
507
+ }
508
+ assert g1_hash_edge2_node2 == {
509
+ -1 * k: v for k, v in g2_hash_edge2_node2.items()
510
+ }
511
+
512
+
513
+ def test_iteration_depth():
514
+ """
515
+ All nodes should have the correct number of subgraph hashes in the output when
516
+ using degree as initial node labels
517
+ Subsequent iteration depths for the same graph should be additive for each node
518
+ """
519
+ n, r = 100, 10
520
+ p = 1.0 / r
521
+ for i in range(1, r + 1):
522
+ G = nx.erdos_renyi_graph(n, p * i, seed=600 + i)
523
+
524
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=3)
525
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=4)
526
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=5)
527
+
528
+ assert all(len(hashes) == 3 for hashes in depth3.values())
529
+ assert all(len(hashes) == 4 for hashes in depth4.values())
530
+ assert all(len(hashes) == 5 for hashes in depth5.values())
531
+
532
+ assert is_subiteration(depth3, depth4)
533
+ assert is_subiteration(depth4, depth5)
534
+ assert is_subiteration(depth3, depth5)
535
+
536
+
537
+ def test_iteration_depth_edge_attr():
538
+ """
539
+ All nodes should have the correct number of subgraph hashes in the output when
540
+ setting initial node labels empty and using an edge attribute when aggregating
541
+ neighborhoods.
542
+ Subsequent iteration depths for the same graph should be additive for each node
543
+ """
544
+ n, r = 100, 10
545
+ p = 1.0 / r
546
+ for i in range(1, r + 1):
547
+ G = nx.erdos_renyi_graph(n, p * i, seed=700 + i)
548
+
549
+ for a, b in G.edges:
550
+ G[a][b]["edge_attr1"] = f"{a}-{b}-1"
551
+
552
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(
553
+ G, edge_attr="edge_attr1", iterations=3
554
+ )
555
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(
556
+ G, edge_attr="edge_attr1", iterations=4
557
+ )
558
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(
559
+ G, edge_attr="edge_attr1", iterations=5
560
+ )
561
+
562
+ assert all(len(hashes) == 3 for hashes in depth3.values())
563
+ assert all(len(hashes) == 4 for hashes in depth4.values())
564
+ assert all(len(hashes) == 5 for hashes in depth5.values())
565
+
566
+ assert is_subiteration(depth3, depth4)
567
+ assert is_subiteration(depth4, depth5)
568
+ assert is_subiteration(depth3, depth5)
569
+
570
+
571
+ def test_iteration_depth_node_attr():
572
+ """
573
+ All nodes should have the correct number of subgraph hashes in the output when
574
+ setting initial node labels to an attribute.
575
+ Subsequent iteration depths for the same graph should be additive for each node
576
+ """
577
+ n, r = 100, 10
578
+ p = 1.0 / r
579
+ for i in range(1, r + 1):
580
+ G = nx.erdos_renyi_graph(n, p * i, seed=800 + i)
581
+
582
+ for u in G.nodes():
583
+ G.nodes[u]["node_attr1"] = f"{u}-1"
584
+
585
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(
586
+ G, node_attr="node_attr1", iterations=3
587
+ )
588
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(
589
+ G, node_attr="node_attr1", iterations=4
590
+ )
591
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(
592
+ G, node_attr="node_attr1", iterations=5
593
+ )
594
+
595
+ assert all(len(hashes) == 3 for hashes in depth3.values())
596
+ assert all(len(hashes) == 4 for hashes in depth4.values())
597
+ assert all(len(hashes) == 5 for hashes in depth5.values())
598
+
599
+ assert is_subiteration(depth3, depth4)
600
+ assert is_subiteration(depth4, depth5)
601
+ assert is_subiteration(depth3, depth5)
602
+
603
+
604
+ def test_iteration_depth_node_edge_attr():
605
+ """
606
+ All nodes should have the correct number of subgraph hashes in the output when
607
+ setting initial node labels to an attribute and also using an edge attribute when
608
+ aggregating neighborhoods.
609
+ Subsequent iteration depths for the same graph should be additive for each node
610
+ """
611
+ n, r = 100, 10
612
+ p = 1.0 / r
613
+ for i in range(1, r + 1):
614
+ G = nx.erdos_renyi_graph(n, p * i, seed=900 + i)
615
+
616
+ for u in G.nodes():
617
+ G.nodes[u]["node_attr1"] = f"{u}-1"
618
+
619
+ for a, b in G.edges:
620
+ G[a][b]["edge_attr1"] = f"{a}-{b}-1"
621
+
622
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(
623
+ G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=3
624
+ )
625
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(
626
+ G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=4
627
+ )
628
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(
629
+ G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=5
630
+ )
631
+
632
+ assert all(len(hashes) == 3 for hashes in depth3.values())
633
+ assert all(len(hashes) == 4 for hashes in depth4.values())
634
+ assert all(len(hashes) == 5 for hashes in depth5.values())
635
+
636
+ assert is_subiteration(depth3, depth4)
637
+ assert is_subiteration(depth4, depth5)
638
+ assert is_subiteration(depth3, depth5)
639
+
640
+
641
+ def test_digest_size_subgraph_hash():
642
+ """
643
+ The hash string lengths should be as expected for a variety of graphs and
644
+ digest sizes
645
+ """
646
+ n, r = 100, 10
647
+ p = 1.0 / r
648
+ for i in range(1, r + 1):
649
+ G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
650
+
651
+ digest_size16_hashes = nx.weisfeiler_lehman_subgraph_hashes(G)
652
+ digest_size32_hashes = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=32)
653
+
654
+ assert digest_size16_hashes != digest_size32_hashes
655
+
656
+ assert hexdigest_sizes_correct(digest_size16_hashes, 16)
657
+ assert hexdigest_sizes_correct(digest_size32_hashes, 32)
658
+
659
+
660
+ def test_initial_node_labels_subgraph_hash():
661
+ """
662
+ Including the hashed initial label prepends an extra hash to the lists
663
+ """
664
+ G = nx.path_graph(5)
665
+ nx.set_node_attributes(G, {i: int(0 < i < 4) for i in G}, "label")
666
+ # initial node labels:
667
+ # 0--1--1--1--0
668
+
669
+ without_initial_label = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
670
+ assert all(len(v) == 3 for v in without_initial_label.values())
671
+ # 3 different 1 hop nhds
672
+ assert len({v[0] for v in without_initial_label.values()}) == 3
673
+
674
+ with_initial_label = nx.weisfeiler_lehman_subgraph_hashes(
675
+ G, node_attr="label", include_initial_labels=True
676
+ )
677
+ assert all(len(v) == 4 for v in with_initial_label.values())
678
+ # 2 different initial labels
679
+ assert len({v[0] for v in with_initial_label.values()}) == 2
680
+
681
+ # check hashes match otherwise
682
+ for u in G:
683
+ for a, b in zip(
684
+ with_initial_label[u][1:], without_initial_label[u], strict=True
685
+ ):
686
+ assert a == b
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_graphical.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_valid_degree_sequence1():
7
+ n = 100
8
+ p = 0.3
9
+ for i in range(10):
10
+ G = nx.erdos_renyi_graph(n, p)
11
+ deg = (d for n, d in G.degree())
12
+ assert nx.is_graphical(deg, method="eg")
13
+ assert nx.is_graphical(deg, method="hh")
14
+
15
+
16
+ def test_valid_degree_sequence2():
17
+ n = 100
18
+ for i in range(10):
19
+ G = nx.barabasi_albert_graph(n, 1)
20
+ deg = (d for n, d in G.degree())
21
+ assert nx.is_graphical(deg, method="eg")
22
+ assert nx.is_graphical(deg, method="hh")
23
+
24
+
25
+ def test_string_input():
26
+ pytest.raises(nx.NetworkXException, nx.is_graphical, [], "foo")
27
+ pytest.raises(nx.NetworkXException, nx.is_graphical, ["red"], "hh")
28
+ pytest.raises(nx.NetworkXException, nx.is_graphical, ["red"], "eg")
29
+
30
+
31
+ def test_non_integer_input():
32
+ pytest.raises(nx.NetworkXException, nx.is_graphical, [72.5], "eg")
33
+ pytest.raises(nx.NetworkXException, nx.is_graphical, [72.5], "hh")
34
+
35
+
36
+ def test_negative_input():
37
+ assert not nx.is_graphical([-1], "hh")
38
+ assert not nx.is_graphical([-1], "eg")
39
+
40
+
41
+ class TestAtlas:
42
+ @classmethod
43
+ def setup_class(cls):
44
+ global atlas
45
+ from networkx.generators import atlas
46
+
47
+ cls.GAG = atlas.graph_atlas_g()
48
+
49
+ def test_atlas(self):
50
+ for graph in self.GAG:
51
+ deg = (d for n, d in graph.degree())
52
+ assert nx.is_graphical(deg, method="eg")
53
+ assert nx.is_graphical(deg, method="hh")
54
+
55
+
56
+ def test_small_graph_true():
57
+ z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
58
+ assert nx.is_graphical(z, method="hh")
59
+ assert nx.is_graphical(z, method="eg")
60
+ z = [10, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
61
+ assert nx.is_graphical(z, method="hh")
62
+ assert nx.is_graphical(z, method="eg")
63
+ z = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
64
+ assert nx.is_graphical(z, method="hh")
65
+ assert nx.is_graphical(z, method="eg")
66
+
67
+
68
+ def test_small_graph_false():
69
+ z = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
70
+ assert not nx.is_graphical(z, method="hh")
71
+ assert not nx.is_graphical(z, method="eg")
72
+ z = [6, 5, 4, 4, 2, 1, 1, 1]
73
+ assert not nx.is_graphical(z, method="hh")
74
+ assert not nx.is_graphical(z, method="eg")
75
+ z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
76
+ assert not nx.is_graphical(z, method="hh")
77
+ assert not nx.is_graphical(z, method="eg")
78
+
79
+
80
+ def test_directed_degree_sequence():
81
+ # Test a range of valid directed degree sequences
82
+ n, r = 100, 10
83
+ p = 1.0 / r
84
+ for i in range(r):
85
+ G = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
86
+ din = (d for n, d in G.in_degree())
87
+ dout = (d for n, d in G.out_degree())
88
+ assert nx.is_digraphical(din, dout)
89
+
90
+
91
+ def test_small_directed_sequences():
92
+ dout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
93
+ din = [3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1]
94
+ assert nx.is_digraphical(din, dout)
95
+ # Test nongraphical directed sequence
96
+ dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
97
+ din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
98
+ assert not nx.is_digraphical(din, dout)
99
+ # Test digraphical small sequence
100
+ dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
101
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 1, 1]
102
+ assert nx.is_digraphical(din, dout)
103
+ # Test nonmatching sum
104
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1]
105
+ assert not nx.is_digraphical(din, dout)
106
+ # Test for negative integer in sequence
107
+ din = [2, 2, 2, -2, 2, 2, 2, 2, 1, 1, 4]
108
+ assert not nx.is_digraphical(din, dout)
109
+ # Test for noninteger
110
+ din = dout = [1, 1, 1.1, 1]
111
+ assert not nx.is_digraphical(din, dout)
112
+ din = dout = [1, 1, "rer", 1]
113
+ assert not nx.is_digraphical(din, dout)
114
+
115
+
116
+ def test_multi_sequence():
117
+ # Test nongraphical multi sequence
118
+ seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1]
119
+ assert not nx.is_multigraphical(seq)
120
+ # Test small graphical multi sequence
121
+ seq = [6, 5, 4, 4, 2, 1, 1, 1]
122
+ assert nx.is_multigraphical(seq)
123
+ # Test for negative integer in sequence
124
+ seq = [6, 5, 4, -4, 2, 1, 1, 1]
125
+ assert not nx.is_multigraphical(seq)
126
+ # Test for sequence with odd sum
127
+ seq = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
128
+ assert not nx.is_multigraphical(seq)
129
+ # Test for noninteger
130
+ seq = [1, 1, 1.1, 1]
131
+ assert not nx.is_multigraphical(seq)
132
+ seq = [1, 1, "rer", 1]
133
+ assert not nx.is_multigraphical(seq)
134
+
135
+
136
+ def test_pseudo_sequence():
137
+ # Test small valid pseudo sequence
138
+ seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1]
139
+ assert nx.is_pseudographical(seq)
140
+ # Test for sequence with odd sum
141
+ seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
142
+ assert not nx.is_pseudographical(seq)
143
+ # Test for negative integer in sequence
144
+ seq = [1000, 3, 3, 3, 3, 2, 2, -2, 1, 1]
145
+ assert not nx.is_pseudographical(seq)
146
+ # Test for noninteger
147
+ seq = [1, 1, 1.1, 1]
148
+ assert not nx.is_pseudographical(seq)
149
+ seq = [1, 1, "rer", 1]
150
+ assert not nx.is_pseudographical(seq)
151
+
152
+
153
+ def test_numpy_degree_sequence():
154
+ np = pytest.importorskip("numpy")
155
+ ds = np.array([1, 2, 2, 2, 1], dtype=np.int64)
156
+ assert nx.is_graphical(ds, "eg")
157
+ assert nx.is_graphical(ds, "hh")
158
+ ds = np.array([1, 2, 2, 2, 1], dtype=np.float64)
159
+ assert nx.is_graphical(ds, "eg")
160
+ assert nx.is_graphical(ds, "hh")
161
+ ds = np.array([1.1, 2, 2, 2, 1], dtype=np.float64)
162
+ pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "eg")
163
+ pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "hh")
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_hierarchy.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_hierarchy_exception():
7
+ G = nx.cycle_graph(5)
8
+ pytest.raises(nx.NetworkXError, nx.flow_hierarchy, G)
9
+
10
+
11
+ def test_hierarchy_cycle():
12
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
13
+ assert nx.flow_hierarchy(G) == 0.0
14
+
15
+
16
+ def test_hierarchy_tree():
17
+ G = nx.full_rary_tree(2, 16, create_using=nx.DiGraph())
18
+ assert nx.flow_hierarchy(G) == 1.0
19
+
20
+
21
+ def test_hierarchy_1():
22
+ G = nx.DiGraph()
23
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 1), (3, 4), (0, 4)])
24
+ assert nx.flow_hierarchy(G) == 0.5
25
+
26
+
27
+ def test_hierarchy_weight():
28
+ G = nx.DiGraph()
29
+ G.add_edges_from(
30
+ [
31
+ (0, 1, {"weight": 0.3}),
32
+ (1, 2, {"weight": 0.1}),
33
+ (2, 3, {"weight": 0.1}),
34
+ (3, 1, {"weight": 0.1}),
35
+ (3, 4, {"weight": 0.3}),
36
+ (0, 4, {"weight": 0.3}),
37
+ ]
38
+ )
39
+ assert nx.flow_hierarchy(G, weight="weight") == 0.75
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_isolate.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.isolates` module."""
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_is_isolate():
7
+ G = nx.Graph()
8
+ G.add_edge(0, 1)
9
+ G.add_node(2)
10
+ assert not nx.is_isolate(G, 0)
11
+ assert not nx.is_isolate(G, 1)
12
+ assert nx.is_isolate(G, 2)
13
+
14
+
15
+ def test_isolates():
16
+ G = nx.Graph()
17
+ G.add_edge(0, 1)
18
+ G.add_nodes_from([2, 3])
19
+ assert sorted(nx.isolates(G)) == [2, 3]
20
+
21
+
22
+ def test_number_of_isolates():
23
+ G = nx.Graph()
24
+ G.add_edge(0, 1)
25
+ G.add_nodes_from([2, 3])
26
+ assert nx.number_of_isolates(G) == 2
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_link_prediction.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from functools import partial
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+
8
+
9
+ def _test_func(G, ebunch, expected, predict_func, **kwargs):
10
+ result = predict_func(G, ebunch, **kwargs)
11
+ exp_dict = {tuple(sorted([u, v])): score for u, v, score in expected}
12
+ res_dict = {tuple(sorted([u, v])): score for u, v, score in result}
13
+
14
+ assert len(exp_dict) == len(res_dict)
15
+ for p in exp_dict:
16
+ assert exp_dict[p] == pytest.approx(res_dict[p], abs=1e-7)
17
+
18
+
19
+ class TestResourceAllocationIndex:
20
+ @classmethod
21
+ def setup_class(cls):
22
+ cls.func = staticmethod(nx.resource_allocation_index)
23
+ cls.test = partial(_test_func, predict_func=cls.func)
24
+
25
+ def test_K5(self):
26
+ G = nx.complete_graph(5)
27
+ self.test(G, [(0, 1)], [(0, 1, 0.75)])
28
+
29
+ def test_P3(self):
30
+ G = nx.path_graph(3)
31
+ self.test(G, [(0, 2)], [(0, 2, 0.5)])
32
+
33
+ def test_S4(self):
34
+ G = nx.star_graph(4)
35
+ self.test(G, [(1, 2)], [(1, 2, 0.25)])
36
+
37
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
38
+ def test_notimplemented(self, graph_type):
39
+ assert pytest.raises(
40
+ nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
41
+ )
42
+
43
+ def test_node_not_found(self):
44
+ G = nx.Graph()
45
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
46
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
47
+
48
+ def test_no_common_neighbor(self):
49
+ G = nx.Graph()
50
+ G.add_nodes_from([0, 1])
51
+ self.test(G, [(0, 1)], [(0, 1, 0)])
52
+
53
+ def test_equal_nodes(self):
54
+ G = nx.complete_graph(4)
55
+ self.test(G, [(0, 0)], [(0, 0, 1)])
56
+
57
+ def test_all_nonexistent_edges(self):
58
+ G = nx.Graph()
59
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
60
+ self.test(G, None, [(0, 3, 0.5), (1, 2, 0.5), (1, 3, 0)])
61
+
62
+
63
+ class TestJaccardCoefficient:
64
+ @classmethod
65
+ def setup_class(cls):
66
+ cls.func = staticmethod(nx.jaccard_coefficient)
67
+ cls.test = partial(_test_func, predict_func=cls.func)
68
+
69
+ def test_K5(self):
70
+ G = nx.complete_graph(5)
71
+ self.test(G, [(0, 1)], [(0, 1, 0.6)])
72
+
73
+ def test_P4(self):
74
+ G = nx.path_graph(4)
75
+ self.test(G, [(0, 2)], [(0, 2, 0.5)])
76
+
77
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
78
+ def test_notimplemented(self, graph_type):
79
+ assert pytest.raises(
80
+ nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
81
+ )
82
+
83
+ def test_node_not_found(self):
84
+ G = nx.Graph()
85
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
86
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
87
+
88
+ def test_no_common_neighbor(self):
89
+ G = nx.Graph()
90
+ G.add_edges_from([(0, 1), (2, 3)])
91
+ self.test(G, [(0, 2)], [(0, 2, 0)])
92
+
93
+ def test_isolated_nodes(self):
94
+ G = nx.Graph()
95
+ G.add_nodes_from([0, 1])
96
+ self.test(G, [(0, 1)], [(0, 1, 0)])
97
+
98
+ def test_all_nonexistent_edges(self):
99
+ G = nx.Graph()
100
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
101
+ self.test(G, None, [(0, 3, 0.5), (1, 2, 0.5), (1, 3, 0)])
102
+
103
+
104
+ class TestAdamicAdarIndex:
105
+ @classmethod
106
+ def setup_class(cls):
107
+ cls.func = staticmethod(nx.adamic_adar_index)
108
+ cls.test = partial(_test_func, predict_func=cls.func)
109
+
110
+ def test_K5(self):
111
+ G = nx.complete_graph(5)
112
+ self.test(G, [(0, 1)], [(0, 1, 3 / math.log(4))])
113
+
114
+ def test_P3(self):
115
+ G = nx.path_graph(3)
116
+ self.test(G, [(0, 2)], [(0, 2, 1 / math.log(2))])
117
+
118
+ def test_S4(self):
119
+ G = nx.star_graph(4)
120
+ self.test(G, [(1, 2)], [(1, 2, 1 / math.log(4))])
121
+
122
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
123
+ def test_notimplemented(self, graph_type):
124
+ assert pytest.raises(
125
+ nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
126
+ )
127
+
128
+ def test_node_not_found(self):
129
+ G = nx.Graph()
130
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
131
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
132
+
133
+ def test_no_common_neighbor(self):
134
+ G = nx.Graph()
135
+ G.add_nodes_from([0, 1])
136
+ self.test(G, [(0, 1)], [(0, 1, 0)])
137
+
138
+ def test_equal_nodes(self):
139
+ G = nx.complete_graph(4)
140
+ self.test(G, [(0, 0)], [(0, 0, 3 / math.log(3))])
141
+
142
+ def test_all_nonexistent_edges(self):
143
+ G = nx.Graph()
144
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
145
+ self.test(
146
+ G, None, [(0, 3, 1 / math.log(2)), (1, 2, 1 / math.log(2)), (1, 3, 0)]
147
+ )
148
+
149
+
150
+ class TestCommonNeighborCentrality:
151
+ @classmethod
152
+ def setup_class(cls):
153
+ cls.func = staticmethod(nx.common_neighbor_centrality)
154
+ cls.test = partial(_test_func, predict_func=cls.func)
155
+
156
+ def test_K5(self):
157
+ G = nx.complete_graph(5)
158
+ self.test(G, [(0, 1)], [(0, 1, 3.0)], alpha=1)
159
+ self.test(G, [(0, 1)], [(0, 1, 5.0)], alpha=0)
160
+
161
+ def test_P3(self):
162
+ G = nx.path_graph(3)
163
+ self.test(G, [(0, 2)], [(0, 2, 1.25)], alpha=0.5)
164
+
165
+ def test_S4(self):
166
+ G = nx.star_graph(4)
167
+ self.test(G, [(1, 2)], [(1, 2, 1.75)], alpha=0.5)
168
+
169
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
170
+ def test_notimplemented(self, graph_type):
171
+ assert pytest.raises(
172
+ nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
173
+ )
174
+
175
+ def test_node_u_not_found(self):
176
+ G = nx.Graph()
177
+ G.add_edges_from([(1, 3), (2, 3)])
178
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 1)])
179
+
180
+ def test_node_v_not_found(self):
181
+ G = nx.Graph()
182
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
183
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
184
+
185
+ def test_no_common_neighbor(self):
186
+ G = nx.Graph()
187
+ G.add_nodes_from([0, 1])
188
+ self.test(G, [(0, 1)], [(0, 1, 0)])
189
+
190
+ def test_equal_nodes(self):
191
+ G = nx.complete_graph(4)
192
+ assert pytest.raises(nx.NetworkXAlgorithmError, self.test, G, [(0, 0)], [])
193
+
194
+ def test_equal_nodes_with_alpha_one_raises_error(self):
195
+ G = nx.complete_graph(4)
196
+ assert pytest.raises(
197
+ nx.NetworkXAlgorithmError, self.test, G, [(0, 0)], [], alpha=1.0
198
+ )
199
+
200
+ def test_all_nonexistent_edges(self):
201
+ G = nx.Graph()
202
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
203
+ self.test(G, None, [(0, 3, 1.5), (1, 2, 1.5), (1, 3, 2 / 3)], alpha=0.5)
204
+
205
+
206
+ class TestPreferentialAttachment:
207
+ @classmethod
208
+ def setup_class(cls):
209
+ cls.func = staticmethod(nx.preferential_attachment)
210
+ cls.test = partial(_test_func, predict_func=cls.func)
211
+
212
+ def test_K5(self):
213
+ G = nx.complete_graph(5)
214
+ self.test(G, [(0, 1)], [(0, 1, 16)])
215
+
216
+ def test_P3(self):
217
+ G = nx.path_graph(3)
218
+ self.test(G, [(0, 1)], [(0, 1, 2)])
219
+
220
+ def test_S4(self):
221
+ G = nx.star_graph(4)
222
+ self.test(G, [(0, 2)], [(0, 2, 4)])
223
+
224
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
225
+ def test_notimplemented(self, graph_type):
226
+ assert pytest.raises(
227
+ nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
228
+ )
229
+
230
+ def test_node_not_found(self):
231
+ G = nx.Graph()
232
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
233
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
234
+
235
+ def test_zero_degrees(self):
236
+ G = nx.Graph()
237
+ G.add_nodes_from([0, 1])
238
+ self.test(G, [(0, 1)], [(0, 1, 0)])
239
+
240
+ def test_all_nonexistent_edges(self):
241
+ G = nx.Graph()
242
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
243
+ self.test(G, None, [(0, 3, 2), (1, 2, 2), (1, 3, 1)])
244
+
245
+
246
+ class TestCNSoundarajanHopcroft:
247
+ @classmethod
248
+ def setup_class(cls):
249
+ cls.func = staticmethod(nx.cn_soundarajan_hopcroft)
250
+ cls.test = partial(_test_func, predict_func=cls.func, community="community")
251
+
252
+ def test_K5(self):
253
+ G = nx.complete_graph(5)
254
+ G.nodes[0]["community"] = 0
255
+ G.nodes[1]["community"] = 0
256
+ G.nodes[2]["community"] = 0
257
+ G.nodes[3]["community"] = 0
258
+ G.nodes[4]["community"] = 1
259
+ self.test(G, [(0, 1)], [(0, 1, 5)])
260
+
261
+ def test_P3(self):
262
+ G = nx.path_graph(3)
263
+ G.nodes[0]["community"] = 0
264
+ G.nodes[1]["community"] = 1
265
+ G.nodes[2]["community"] = 0
266
+ self.test(G, [(0, 2)], [(0, 2, 1)])
267
+
268
+ def test_S4(self):
269
+ G = nx.star_graph(4)
270
+ G.nodes[0]["community"] = 1
271
+ G.nodes[1]["community"] = 1
272
+ G.nodes[2]["community"] = 1
273
+ G.nodes[3]["community"] = 0
274
+ G.nodes[4]["community"] = 0
275
+ self.test(G, [(1, 2)], [(1, 2, 2)])
276
+
277
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
278
+ def test_notimplemented(self, graph_type):
279
+ G = graph_type([(0, 1), (1, 2)])
280
+ G.add_nodes_from([0, 1, 2], community=0)
281
+ assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)])
282
+
283
+ def test_node_not_found(self):
284
+ G = nx.Graph()
285
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
286
+ G.nodes[0]["community"] = 0
287
+ G.nodes[1]["community"] = 1
288
+ G.nodes[2]["community"] = 0
289
+ G.nodes[3]["community"] = 0
290
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
291
+
292
+ def test_no_common_neighbor(self):
293
+ G = nx.Graph()
294
+ G.add_nodes_from([0, 1])
295
+ G.nodes[0]["community"] = 0
296
+ G.nodes[1]["community"] = 0
297
+ self.test(G, [(0, 1)], [(0, 1, 0)])
298
+
299
+ def test_equal_nodes(self):
300
+ G = nx.complete_graph(3)
301
+ G.nodes[0]["community"] = 0
302
+ G.nodes[1]["community"] = 0
303
+ G.nodes[2]["community"] = 0
304
+ self.test(G, [(0, 0)], [(0, 0, 4)])
305
+
306
+ def test_different_community(self):
307
+ G = nx.Graph()
308
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
309
+ G.nodes[0]["community"] = 0
310
+ G.nodes[1]["community"] = 0
311
+ G.nodes[2]["community"] = 0
312
+ G.nodes[3]["community"] = 1
313
+ self.test(G, [(0, 3)], [(0, 3, 2)])
314
+
315
+ def test_no_community_information(self):
316
+ G = nx.complete_graph(5)
317
+ assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 1)]))
318
+
319
+ def test_insufficient_community_information(self):
320
+ G = nx.Graph()
321
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
322
+ G.nodes[0]["community"] = 0
323
+ G.nodes[1]["community"] = 0
324
+ G.nodes[3]["community"] = 0
325
+ assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 3)]))
326
+
327
+ def test_sufficient_community_information(self):
328
+ G = nx.Graph()
329
+ G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
330
+ G.nodes[1]["community"] = 0
331
+ G.nodes[2]["community"] = 0
332
+ G.nodes[3]["community"] = 0
333
+ G.nodes[4]["community"] = 0
334
+ self.test(G, [(1, 4)], [(1, 4, 4)])
335
+
336
+ def test_custom_community_attribute_name(self):
337
+ G = nx.Graph()
338
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
339
+ G.nodes[0]["cmty"] = 0
340
+ G.nodes[1]["cmty"] = 0
341
+ G.nodes[2]["cmty"] = 0
342
+ G.nodes[3]["cmty"] = 1
343
+ self.test(G, [(0, 3)], [(0, 3, 2)], community="cmty")
344
+
345
+ def test_all_nonexistent_edges(self):
346
+ G = nx.Graph()
347
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
348
+ G.nodes[0]["community"] = 0
349
+ G.nodes[1]["community"] = 1
350
+ G.nodes[2]["community"] = 0
351
+ G.nodes[3]["community"] = 0
352
+ self.test(G, None, [(0, 3, 2), (1, 2, 1), (1, 3, 0)])
353
+
354
+
355
+ class TestRAIndexSoundarajanHopcroft:
356
+ @classmethod
357
+ def setup_class(cls):
358
+ cls.func = staticmethod(nx.ra_index_soundarajan_hopcroft)
359
+ cls.test = partial(_test_func, predict_func=cls.func, community="community")
360
+
361
+ def test_K5(self):
362
+ G = nx.complete_graph(5)
363
+ G.nodes[0]["community"] = 0
364
+ G.nodes[1]["community"] = 0
365
+ G.nodes[2]["community"] = 0
366
+ G.nodes[3]["community"] = 0
367
+ G.nodes[4]["community"] = 1
368
+ self.test(G, [(0, 1)], [(0, 1, 0.5)])
369
+
370
+ def test_P3(self):
371
+ G = nx.path_graph(3)
372
+ G.nodes[0]["community"] = 0
373
+ G.nodes[1]["community"] = 1
374
+ G.nodes[2]["community"] = 0
375
+ self.test(G, [(0, 2)], [(0, 2, 0)])
376
+
377
+ def test_S4(self):
378
+ G = nx.star_graph(4)
379
+ G.nodes[0]["community"] = 1
380
+ G.nodes[1]["community"] = 1
381
+ G.nodes[2]["community"] = 1
382
+ G.nodes[3]["community"] = 0
383
+ G.nodes[4]["community"] = 0
384
+ self.test(G, [(1, 2)], [(1, 2, 0.25)])
385
+
386
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
387
+ def test_notimplemented(self, graph_type):
388
+ G = graph_type([(0, 1), (1, 2)])
389
+ G.add_nodes_from([0, 1, 2], community=0)
390
+ assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)])
391
+
392
+ def test_node_not_found(self):
393
+ G = nx.Graph()
394
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
395
+ G.nodes[0]["community"] = 0
396
+ G.nodes[1]["community"] = 1
397
+ G.nodes[2]["community"] = 0
398
+ G.nodes[3]["community"] = 0
399
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
400
+
401
+ def test_no_common_neighbor(self):
402
+ G = nx.Graph()
403
+ G.add_nodes_from([0, 1])
404
+ G.nodes[0]["community"] = 0
405
+ G.nodes[1]["community"] = 0
406
+ self.test(G, [(0, 1)], [(0, 1, 0)])
407
+
408
+ def test_equal_nodes(self):
409
+ G = nx.complete_graph(3)
410
+ G.nodes[0]["community"] = 0
411
+ G.nodes[1]["community"] = 0
412
+ G.nodes[2]["community"] = 0
413
+ self.test(G, [(0, 0)], [(0, 0, 1)])
414
+
415
+ def test_different_community(self):
416
+ G = nx.Graph()
417
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
418
+ G.nodes[0]["community"] = 0
419
+ G.nodes[1]["community"] = 0
420
+ G.nodes[2]["community"] = 0
421
+ G.nodes[3]["community"] = 1
422
+ self.test(G, [(0, 3)], [(0, 3, 0)])
423
+
424
+ def test_no_community_information(self):
425
+ G = nx.complete_graph(5)
426
+ assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 1)]))
427
+
428
+ def test_insufficient_community_information(self):
429
+ G = nx.Graph()
430
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
431
+ G.nodes[0]["community"] = 0
432
+ G.nodes[1]["community"] = 0
433
+ G.nodes[3]["community"] = 0
434
+ assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 3)]))
435
+
436
+ def test_sufficient_community_information(self):
437
+ G = nx.Graph()
438
+ G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
439
+ G.nodes[1]["community"] = 0
440
+ G.nodes[2]["community"] = 0
441
+ G.nodes[3]["community"] = 0
442
+ G.nodes[4]["community"] = 0
443
+ self.test(G, [(1, 4)], [(1, 4, 1)])
444
+
445
+ def test_custom_community_attribute_name(self):
446
+ G = nx.Graph()
447
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
448
+ G.nodes[0]["cmty"] = 0
449
+ G.nodes[1]["cmty"] = 0
450
+ G.nodes[2]["cmty"] = 0
451
+ G.nodes[3]["cmty"] = 1
452
+ self.test(G, [(0, 3)], [(0, 3, 0)], community="cmty")
453
+
454
+ def test_all_nonexistent_edges(self):
455
+ G = nx.Graph()
456
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
457
+ G.nodes[0]["community"] = 0
458
+ G.nodes[1]["community"] = 1
459
+ G.nodes[2]["community"] = 0
460
+ G.nodes[3]["community"] = 0
461
+ self.test(G, None, [(0, 3, 0.5), (1, 2, 0), (1, 3, 0)])
462
+
463
+
464
+ class TestWithinInterCluster:
465
+ @classmethod
466
+ def setup_class(cls):
467
+ cls.delta = 0.001
468
+ cls.func = staticmethod(nx.within_inter_cluster)
469
+ cls.test = partial(
470
+ _test_func, predict_func=cls.func, delta=cls.delta, community="community"
471
+ )
472
+
473
+ def test_K5(self):
474
+ G = nx.complete_graph(5)
475
+ G.nodes[0]["community"] = 0
476
+ G.nodes[1]["community"] = 0
477
+ G.nodes[2]["community"] = 0
478
+ G.nodes[3]["community"] = 0
479
+ G.nodes[4]["community"] = 1
480
+ self.test(G, [(0, 1)], [(0, 1, 2 / (1 + self.delta))])
481
+
482
+ def test_P3(self):
483
+ G = nx.path_graph(3)
484
+ G.nodes[0]["community"] = 0
485
+ G.nodes[1]["community"] = 1
486
+ G.nodes[2]["community"] = 0
487
+ self.test(G, [(0, 2)], [(0, 2, 0)])
488
+
489
+ def test_S4(self):
490
+ G = nx.star_graph(4)
491
+ G.nodes[0]["community"] = 1
492
+ G.nodes[1]["community"] = 1
493
+ G.nodes[2]["community"] = 1
494
+ G.nodes[3]["community"] = 0
495
+ G.nodes[4]["community"] = 0
496
+ self.test(G, [(1, 2)], [(1, 2, 1 / self.delta)])
497
+
498
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
499
+ def test_notimplemented(self, graph_type):
500
+ G = graph_type([(0, 1), (1, 2)])
501
+ G.add_nodes_from([0, 1, 2], community=0)
502
+ assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)])
503
+
504
+ def test_node_not_found(self):
505
+ G = nx.Graph()
506
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
507
+ G.nodes[0]["community"] = 0
508
+ G.nodes[1]["community"] = 1
509
+ G.nodes[2]["community"] = 0
510
+ G.nodes[3]["community"] = 0
511
+ assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
512
+
513
+ def test_no_common_neighbor(self):
514
+ G = nx.Graph()
515
+ G.add_nodes_from([0, 1])
516
+ G.nodes[0]["community"] = 0
517
+ G.nodes[1]["community"] = 0
518
+ self.test(G, [(0, 1)], [(0, 1, 0)])
519
+
520
+ def test_equal_nodes(self):
521
+ G = nx.complete_graph(3)
522
+ G.nodes[0]["community"] = 0
523
+ G.nodes[1]["community"] = 0
524
+ G.nodes[2]["community"] = 0
525
+ self.test(G, [(0, 0)], [(0, 0, 2 / self.delta)])
526
+
527
+ def test_different_community(self):
528
+ G = nx.Graph()
529
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
530
+ G.nodes[0]["community"] = 0
531
+ G.nodes[1]["community"] = 0
532
+ G.nodes[2]["community"] = 0
533
+ G.nodes[3]["community"] = 1
534
+ self.test(G, [(0, 3)], [(0, 3, 0)])
535
+
536
+ def test_no_inter_cluster_common_neighbor(self):
537
+ G = nx.complete_graph(4)
538
+ G.nodes[0]["community"] = 0
539
+ G.nodes[1]["community"] = 0
540
+ G.nodes[2]["community"] = 0
541
+ G.nodes[3]["community"] = 0
542
+ self.test(G, [(0, 3)], [(0, 3, 2 / self.delta)])
543
+
544
+ def test_no_community_information(self):
545
+ G = nx.complete_graph(5)
546
+ assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 1)]))
547
+
548
+ def test_insufficient_community_information(self):
549
+ G = nx.Graph()
550
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
551
+ G.nodes[0]["community"] = 0
552
+ G.nodes[1]["community"] = 0
553
+ G.nodes[3]["community"] = 0
554
+ assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 3)]))
555
+
556
+ def test_sufficient_community_information(self):
557
+ G = nx.Graph()
558
+ G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
559
+ G.nodes[1]["community"] = 0
560
+ G.nodes[2]["community"] = 0
561
+ G.nodes[3]["community"] = 0
562
+ G.nodes[4]["community"] = 0
563
+ self.test(G, [(1, 4)], [(1, 4, 2 / self.delta)])
564
+
565
+ def test_invalid_delta(self):
566
+ G = nx.complete_graph(3)
567
+ G.add_nodes_from([0, 1, 2], community=0)
568
+ assert pytest.raises(nx.NetworkXAlgorithmError, self.func, G, [(0, 1)], 0)
569
+ assert pytest.raises(nx.NetworkXAlgorithmError, self.func, G, [(0, 1)], -0.5)
570
+
571
+ def test_custom_community_attribute_name(self):
572
+ G = nx.complete_graph(4)
573
+ G.nodes[0]["cmty"] = 0
574
+ G.nodes[1]["cmty"] = 0
575
+ G.nodes[2]["cmty"] = 0
576
+ G.nodes[3]["cmty"] = 0
577
+ self.test(G, [(0, 3)], [(0, 3, 2 / self.delta)], community="cmty")
578
+
579
+ def test_all_nonexistent_edges(self):
580
+ G = nx.Graph()
581
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
582
+ G.nodes[0]["community"] = 0
583
+ G.nodes[1]["community"] = 1
584
+ G.nodes[2]["community"] = 0
585
+ G.nodes[3]["community"] = 0
586
+ self.test(G, None, [(0, 3, 1 / self.delta), (1, 2, 0), (1, 3, 0)])
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/test_lowest_common_ancestors.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain, combinations, product
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+ tree_all_pairs_lca = nx.tree_all_pairs_lowest_common_ancestor
8
+ all_pairs_lca = nx.all_pairs_lowest_common_ancestor
9
+
10
+
11
+ def get_pair(dictionary, n1, n2):
12
+ if (n1, n2) in dictionary:
13
+ return dictionary[n1, n2]
14
+ else:
15
+ return dictionary[n2, n1]
16
+
17
+
18
+ class TestTreeLCA:
19
+ @classmethod
20
+ def setup_class(cls):
21
+ cls.DG = nx.DiGraph()
22
+ edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
23
+ cls.DG.add_edges_from(edges)
24
+ cls.ans = dict(tree_all_pairs_lca(cls.DG, 0))
25
+ gold = {(n, n): n for n in cls.DG}
26
+ gold.update({(0, i): 0 for i in range(1, 7)})
27
+ gold.update(
28
+ {
29
+ (1, 2): 0,
30
+ (1, 3): 1,
31
+ (1, 4): 1,
32
+ (1, 5): 0,
33
+ (1, 6): 0,
34
+ (2, 3): 0,
35
+ (2, 4): 0,
36
+ (2, 5): 2,
37
+ (2, 6): 2,
38
+ (3, 4): 1,
39
+ (3, 5): 0,
40
+ (3, 6): 0,
41
+ (4, 5): 0,
42
+ (4, 6): 0,
43
+ (5, 6): 2,
44
+ }
45
+ )
46
+
47
+ cls.gold = gold
48
+
49
+ @staticmethod
50
+ def assert_has_same_pairs(d1, d2):
51
+ for a, b in ((min(pair), max(pair)) for pair in chain(d1, d2)):
52
+ assert get_pair(d1, a, b) == get_pair(d2, a, b)
53
+
54
+ def test_tree_all_pairs_lca_default_root(self):
55
+ assert dict(tree_all_pairs_lca(self.DG)) == self.ans
56
+
57
+ def test_tree_all_pairs_lca_return_subset(self):
58
+ test_pairs = [(0, 1), (0, 1), (1, 0)]
59
+ ans = dict(tree_all_pairs_lca(self.DG, 0, test_pairs))
60
+ assert (0, 1) in ans and (1, 0) in ans
61
+ assert len(ans) == 2
62
+
63
+ def test_tree_all_pairs_lca(self):
64
+ all_pairs = chain(combinations(self.DG, 2), ((node, node) for node in self.DG))
65
+
66
+ ans = dict(tree_all_pairs_lca(self.DG, 0, all_pairs))
67
+ self.assert_has_same_pairs(ans, self.ans)
68
+
69
+ def test_tree_all_pairs_gold_example(self):
70
+ ans = dict(tree_all_pairs_lca(self.DG))
71
+ self.assert_has_same_pairs(self.gold, ans)
72
+
73
+ def test_tree_all_pairs_lca_invalid_input(self):
74
+ empty_digraph = tree_all_pairs_lca(nx.DiGraph())
75
+ pytest.raises(nx.NetworkXPointlessConcept, list, empty_digraph)
76
+
77
+ bad_pairs_digraph = tree_all_pairs_lca(self.DG, pairs=[(-1, -2)])
78
+ pytest.raises(nx.NodeNotFound, list, bad_pairs_digraph)
79
+
80
+ def test_tree_all_pairs_lca_subtrees(self):
81
+ ans = dict(tree_all_pairs_lca(self.DG, 1))
82
+ gold = {
83
+ pair: lca
84
+ for (pair, lca) in self.gold.items()
85
+ if all(n in (1, 3, 4) for n in pair)
86
+ }
87
+ self.assert_has_same_pairs(gold, ans)
88
+
89
+ def test_tree_all_pairs_lca_disconnected_nodes(self):
90
+ G = nx.DiGraph()
91
+ G.add_node(1)
92
+ assert {(1, 1): 1} == dict(tree_all_pairs_lca(G))
93
+
94
+ G.add_node(0)
95
+ assert {(1, 1): 1} == dict(tree_all_pairs_lca(G, 1))
96
+ assert {(0, 0): 0} == dict(tree_all_pairs_lca(G, 0))
97
+
98
+ pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
99
+
100
+ def test_tree_all_pairs_lca_error_if_input_not_tree(self):
101
+ # Cycle
102
+ G = nx.DiGraph([(1, 2), (2, 1)])
103
+ pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
104
+ # DAG
105
+ G = nx.DiGraph([(0, 2), (1, 2)])
106
+ pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
107
+
108
+ def test_tree_all_pairs_lca_generator(self):
109
+ pairs = iter([(0, 1), (0, 1), (1, 0)])
110
+ some_pairs = dict(tree_all_pairs_lca(self.DG, 0, pairs))
111
+ assert (0, 1) in some_pairs and (1, 0) in some_pairs
112
+ assert len(some_pairs) == 2
113
+
114
+ def test_tree_all_pairs_lca_nonexisting_pairs_exception(self):
115
+ lca = tree_all_pairs_lca(self.DG, 0, [(-1, -1)])
116
+ pytest.raises(nx.NodeNotFound, list, lca)
117
+ # check if node is None
118
+ lca = tree_all_pairs_lca(self.DG, None, [(-1, -1)])
119
+ pytest.raises(nx.NodeNotFound, list, lca)
120
+
121
+ def test_tree_all_pairs_lca_routine_bails_on_DAGs(self):
122
+ G = nx.DiGraph([(3, 4), (5, 4)])
123
+ pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
124
+
125
+ def test_tree_all_pairs_lca_not_implemented(self):
126
+ NNI = nx.NetworkXNotImplemented
127
+ G = nx.Graph([(0, 1)])
128
+ with pytest.raises(NNI):
129
+ next(tree_all_pairs_lca(G))
130
+ with pytest.raises(NNI):
131
+ next(all_pairs_lca(G))
132
+ pytest.raises(NNI, nx.lowest_common_ancestor, G, 0, 1)
133
+ G = nx.MultiGraph([(0, 1)])
134
+ with pytest.raises(NNI):
135
+ next(tree_all_pairs_lca(G))
136
+ with pytest.raises(NNI):
137
+ next(all_pairs_lca(G))
138
+ pytest.raises(NNI, nx.lowest_common_ancestor, G, 0, 1)
139
+
140
+ def test_tree_all_pairs_lca_trees_without_LCAs(self):
141
+ G = nx.DiGraph()
142
+ G.add_node(3)
143
+ ans = list(tree_all_pairs_lca(G))
144
+ assert ans == [((3, 3), 3)]
145
+
146
+
147
+ class TestMultiTreeLCA(TestTreeLCA):
148
+ @classmethod
149
+ def setup_class(cls):
150
+ cls.DG = nx.MultiDiGraph()
151
+ edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
152
+ cls.DG.add_edges_from(edges)
153
+ cls.ans = dict(tree_all_pairs_lca(cls.DG, 0))
154
+ # add multiedges
155
+ cls.DG.add_edges_from(edges)
156
+
157
+ gold = {(n, n): n for n in cls.DG}
158
+ gold.update({(0, i): 0 for i in range(1, 7)})
159
+ gold.update(
160
+ {
161
+ (1, 2): 0,
162
+ (1, 3): 1,
163
+ (1, 4): 1,
164
+ (1, 5): 0,
165
+ (1, 6): 0,
166
+ (2, 3): 0,
167
+ (2, 4): 0,
168
+ (2, 5): 2,
169
+ (2, 6): 2,
170
+ (3, 4): 1,
171
+ (3, 5): 0,
172
+ (3, 6): 0,
173
+ (4, 5): 0,
174
+ (4, 6): 0,
175
+ (5, 6): 2,
176
+ }
177
+ )
178
+
179
+ cls.gold = gold
180
+
181
+
182
+ class TestDAGLCA:
183
+ @classmethod
184
+ def setup_class(cls):
185
+ cls.DG = nx.DiGraph()
186
+ nx.add_path(cls.DG, (0, 1, 2, 3))
187
+ nx.add_path(cls.DG, (0, 4, 3))
188
+ nx.add_path(cls.DG, (0, 5, 6, 8, 3))
189
+ nx.add_path(cls.DG, (5, 7, 8))
190
+ cls.DG.add_edge(6, 2)
191
+ cls.DG.add_edge(7, 2)
192
+
193
+ cls.root_distance = nx.shortest_path_length(cls.DG, source=0)
194
+
195
+ cls.gold = {
196
+ (1, 1): 1,
197
+ (1, 2): 1,
198
+ (1, 3): 1,
199
+ (1, 4): 0,
200
+ (1, 5): 0,
201
+ (1, 6): 0,
202
+ (1, 7): 0,
203
+ (1, 8): 0,
204
+ (2, 2): 2,
205
+ (2, 3): 2,
206
+ (2, 4): 0,
207
+ (2, 5): 5,
208
+ (2, 6): 6,
209
+ (2, 7): 7,
210
+ (2, 8): 7,
211
+ (3, 3): 3,
212
+ (3, 4): 4,
213
+ (3, 5): 5,
214
+ (3, 6): 6,
215
+ (3, 7): 7,
216
+ (3, 8): 8,
217
+ (4, 4): 4,
218
+ (4, 5): 0,
219
+ (4, 6): 0,
220
+ (4, 7): 0,
221
+ (4, 8): 0,
222
+ (5, 5): 5,
223
+ (5, 6): 5,
224
+ (5, 7): 5,
225
+ (5, 8): 5,
226
+ (6, 6): 6,
227
+ (6, 7): 5,
228
+ (6, 8): 6,
229
+ (7, 7): 7,
230
+ (7, 8): 7,
231
+ (8, 8): 8,
232
+ }
233
+ cls.gold.update(((0, n), 0) for n in cls.DG)
234
+
235
+ def assert_lca_dicts_same(self, d1, d2, G=None):
236
+ """Checks if d1 and d2 contain the same pairs and
237
+ have a node at the same distance from root for each.
238
+ If G is None use self.DG."""
239
+ if G is None:
240
+ G = self.DG
241
+ root_distance = self.root_distance
242
+ else:
243
+ roots = [n for n, deg in G.in_degree if deg == 0]
244
+ assert len(roots) == 1
245
+ root_distance = nx.shortest_path_length(G, source=roots[0])
246
+
247
+ for a, b in ((min(pair), max(pair)) for pair in chain(d1, d2)):
248
+ assert (
249
+ root_distance[get_pair(d1, a, b)] == root_distance[get_pair(d2, a, b)]
250
+ )
251
+
252
+ def test_all_pairs_lca_gold_example(self):
253
+ self.assert_lca_dicts_same(dict(all_pairs_lca(self.DG)), self.gold)
254
+
255
+ def test_all_pairs_lca_all_pairs_given(self):
256
+ all_pairs = list(product(self.DG.nodes(), self.DG.nodes()))
257
+ ans = all_pairs_lca(self.DG, pairs=all_pairs)
258
+ self.assert_lca_dicts_same(dict(ans), self.gold)
259
+
260
+ def test_all_pairs_lca_generator(self):
261
+ all_pairs = product(self.DG.nodes(), self.DG.nodes())
262
+ ans = all_pairs_lca(self.DG, pairs=all_pairs)
263
+ self.assert_lca_dicts_same(dict(ans), self.gold)
264
+
265
+ def test_all_pairs_lca_input_graph_with_two_roots(self):
266
+ G = self.DG.copy()
267
+ G.add_edge(9, 10)
268
+ G.add_edge(9, 4)
269
+ gold = self.gold.copy()
270
+ gold[9, 9] = 9
271
+ gold[9, 10] = 9
272
+ gold[9, 4] = 9
273
+ gold[9, 3] = 9
274
+ gold[10, 4] = 9
275
+ gold[10, 3] = 9
276
+ gold[10, 10] = 10
277
+
278
+ testing = dict(all_pairs_lca(G))
279
+
280
+ G.add_edge(-1, 9)
281
+ G.add_edge(-1, 0)
282
+ self.assert_lca_dicts_same(testing, gold, G)
283
+
284
+ def test_all_pairs_lca_nonexisting_pairs_exception(self):
285
+ pytest.raises(nx.NodeNotFound, all_pairs_lca, self.DG, [(-1, -1)])
286
+
287
+ def test_all_pairs_lca_pairs_without_lca(self):
288
+ G = self.DG.copy()
289
+ G.add_node(-1)
290
+ gen = all_pairs_lca(G, [(-1, -1), (-1, 0)])
291
+ assert dict(gen) == {(-1, -1): -1}
292
+
293
+ def test_all_pairs_lca_null_graph(self):
294
+ pytest.raises(nx.NetworkXPointlessConcept, all_pairs_lca, nx.DiGraph())
295
+
296
+ def test_all_pairs_lca_non_dags(self):
297
+ pytest.raises(nx.NetworkXError, all_pairs_lca, nx.DiGraph([(3, 4), (4, 3)]))
298
+
299
+ def test_all_pairs_lca_nonempty_graph_without_lca(self):
300
+ G = nx.DiGraph()
301
+ G.add_node(3)
302
+ ans = list(all_pairs_lca(G))
303
+ assert ans == [((3, 3), 3)]
304
+
305
+ def test_all_pairs_lca_bug_gh4942(self):
306
+ G = nx.DiGraph([(0, 2), (1, 2), (2, 3)])
307
+ ans = list(all_pairs_lca(G))
308
+ assert len(ans) == 9
309
+
310
+ def test_all_pairs_lca_default_kwarg(self):
311
+ G = nx.DiGraph([(0, 1), (2, 1)])
312
+ sentinel = object()
313
+ assert nx.lowest_common_ancestor(G, 0, 2, default=sentinel) is sentinel
314
+
315
+ def test_all_pairs_lca_identity(self):
316
+ G = nx.DiGraph()
317
+ G.add_node(3)
318
+ assert nx.lowest_common_ancestor(G, 3, 3) == 3
319
+
320
+ def test_all_pairs_lca_issue_4574(self):
321
+ G = nx.DiGraph()
322
+ G.add_nodes_from(range(17))
323
+ G.add_edges_from(
324
+ [
325
+ (2, 0),
326
+ (1, 2),
327
+ (3, 2),
328
+ (5, 2),
329
+ (8, 2),
330
+ (11, 2),
331
+ (4, 5),
332
+ (6, 5),
333
+ (7, 8),
334
+ (10, 8),
335
+ (13, 11),
336
+ (14, 11),
337
+ (15, 11),
338
+ (9, 10),
339
+ (12, 13),
340
+ (16, 15),
341
+ ]
342
+ )
343
+
344
+ assert nx.lowest_common_ancestor(G, 7, 9) == None
345
+
346
+ def test_all_pairs_lca_one_pair_gh4942(self):
347
+ G = nx.DiGraph()
348
+ # Note: order edge addition is critical to the test
349
+ G.add_edge(0, 1)
350
+ G.add_edge(2, 0)
351
+ G.add_edge(2, 3)
352
+ G.add_edge(4, 0)
353
+ G.add_edge(5, 2)
354
+
355
+ assert nx.lowest_common_ancestor(G, 1, 3) == 2
356
+
357
+
358
+ class TestMultiDiGraph_DAGLCA(TestDAGLCA):
359
+ @classmethod
360
+ def setup_class(cls):
361
+ cls.DG = nx.MultiDiGraph()
362
+ nx.add_path(cls.DG, (0, 1, 2, 3))
363
+ # add multiedges
364
+ nx.add_path(cls.DG, (0, 1, 2, 3))
365
+ nx.add_path(cls.DG, (0, 4, 3))
366
+ nx.add_path(cls.DG, (0, 5, 6, 8, 3))
367
+ nx.add_path(cls.DG, (5, 7, 8))
368
+ cls.DG.add_edge(6, 2)
369
+ cls.DG.add_edge(7, 2)
370
+
371
+ cls.root_distance = nx.shortest_path_length(cls.DG, source=0)
372
+
373
+ cls.gold = {
374
+ (1, 1): 1,
375
+ (1, 2): 1,
376
+ (1, 3): 1,
377
+ (1, 4): 0,
378
+ (1, 5): 0,
379
+ (1, 6): 0,
380
+ (1, 7): 0,
381
+ (1, 8): 0,
382
+ (2, 2): 2,
383
+ (2, 3): 2,
384
+ (2, 4): 0,
385
+ (2, 5): 5,
386
+ (2, 6): 6,
387
+ (2, 7): 7,
388
+ (2, 8): 7,
389
+ (3, 3): 3,
390
+ (3, 4): 4,
391
+ (3, 5): 5,
392
+ (3, 6): 6,
393
+ (3, 7): 7,
394
+ (3, 8): 8,
395
+ (4, 4): 4,
396
+ (4, 5): 0,
397
+ (4, 6): 0,
398
+ (4, 7): 0,
399
+ (4, 8): 0,
400
+ (5, 5): 5,
401
+ (5, 6): 5,
402
+ (5, 7): 5,
403
+ (5, 8): 5,
404
+ (6, 6): 6,
405
+ (6, 7): 5,
406
+ (6, 8): 6,
407
+ (7, 7): 7,
408
+ (7, 8): 7,
409
+ (8, 8): 8,
410
+ }
411
+ cls.gold.update(((0, n), 0) for n in cls.DG)
412
+
413
+
414
+ def test_all_pairs_lca_self_ancestors():
415
+ """Self-ancestors should always be the node itself, i.e. lca of (0, 0) is 0.
416
+ See gh-4458."""
417
+ # DAG for test - note order of node/edge addition is relevant
418
+ G = nx.DiGraph()
419
+ G.add_nodes_from(range(5))
420
+ G.add_edges_from([(1, 0), (2, 0), (3, 2), (4, 1), (4, 3)])
421
+
422
+ ap_lca = nx.all_pairs_lowest_common_ancestor
423
+ assert all(u == v == a for (u, v), a in ap_lca(G) if u == v)
424
+ MG = nx.MultiDiGraph(G)
425
+ assert all(u == v == a for (u, v), a in ap_lca(MG) if u == v)
426
+ MG.add_edges_from([(1, 0), (2, 0)])
427
+ assert all(u == v == a for (u, v), a in ap_lca(MG) if u == v)