ZTWHHH commited on
Commit
0ded69f
·
verified ·
1 Parent(s): d7e679d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. janus/lib/libtinfow.so +3 -0
  3. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/neighbor_degree.cpython-310.pyc +0 -0
  5. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/__init__.cpython-310.pyc +0 -0
  6. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc +0 -0
  7. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/greedy_coloring.cpython-310.pyc +0 -0
  8. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  9. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py +863 -0
  10. janus/lib/python3.10/site-packages/networkx/algorithms/components/__init__.py +6 -0
  11. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc +0 -0
  12. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc +0 -0
  13. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc +0 -0
  14. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc +0 -0
  15. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc +0 -0
  16. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc +0 -0
  17. janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc +0 -0
  18. janus/lib/python3.10/site-packages/networkx/algorithms/components/attracting.py +115 -0
  19. janus/lib/python3.10/site-packages/networkx/algorithms/components/biconnected.py +394 -0
  20. janus/lib/python3.10/site-packages/networkx/algorithms/components/connected.py +216 -0
  21. janus/lib/python3.10/site-packages/networkx/algorithms/components/semiconnected.py +71 -0
  22. janus/lib/python3.10/site-packages/networkx/algorithms/components/strongly_connected.py +351 -0
  23. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc +0 -0
  24. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_semiconnected.cpython-310.pyc +0 -0
  25. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc +0 -0
  26. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py +138 -0
  27. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_strongly_connected.py +193 -0
  28. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py +96 -0
  29. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 +3 -0
  30. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 +3 -0
  31. janus/lib/python3.10/site-packages/networkx/algorithms/operators/__init__.py +4 -0
  32. janus/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc +0 -0
  33. janus/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc +0 -0
  34. janus/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc +0 -0
  35. janus/lib/python3.10/site-packages/networkx/algorithms/operators/product.py +633 -0
  36. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py +0 -0
  37. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_binary.cpython-310.pyc +0 -0
  38. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_product.cpython-310.pyc +0 -0
  39. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_all.py +328 -0
  40. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_binary.py +453 -0
  41. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_product.py +491 -0
  42. janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_unary.py +55 -0
  43. janus/lib/python3.10/site-packages/networkx/algorithms/operators/unary.py +77 -0
  44. janus/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc +0 -0
  46. janus/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc +0 -0
  47. janus/lib/python3.10/site-packages/networkx/drawing/layout.py +1630 -0
  48. janus/lib/python3.10/site-packages/networkx/drawing/nx_latex.py +572 -0
  49. janus/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py +352 -0
  50. janus/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py +0 -0
.gitattributes CHANGED
@@ -437,3 +437,4 @@ deepseek/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x8
437
  deepseek/lib/python3.10/site-packages/timm/models/__pycache__/vision_transformer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
438
  deepseek/lib/python3.10/site-packages/pyarrow/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
439
  deepseek/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
437
  deepseek/lib/python3.10/site-packages/timm/models/__pycache__/vision_transformer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
438
  deepseek/lib/python3.10/site-packages/pyarrow/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
439
  deepseek/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
440
+ janus/lib/libtinfow.so filter=lfs diff=lfs merge=lfs -text
janus/lib/libtinfow.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ce4e329189b38682e806046f803063f032d007c68737923b8362ce10570c653
3
+ size 287080
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (468 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/neighbor_degree.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (365 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/greedy_coloring.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Greedy coloring test suite."""
2
+
3
+ import itertools
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+
9
+ is_coloring = nx.algorithms.coloring.equitable_coloring.is_coloring
10
+ is_equitable = nx.algorithms.coloring.equitable_coloring.is_equitable
11
+
12
+
13
+ ALL_STRATEGIES = [
14
+ "largest_first",
15
+ "random_sequential",
16
+ "smallest_last",
17
+ "independent_set",
18
+ "connected_sequential_bfs",
19
+ "connected_sequential_dfs",
20
+ "connected_sequential",
21
+ "saturation_largest_first",
22
+ "DSATUR",
23
+ ]
24
+
25
+ # List of strategies where interchange=True results in an error
26
+ INTERCHANGE_INVALID = ["independent_set", "saturation_largest_first", "DSATUR"]
27
+
28
+
29
+ class TestColoring:
30
+ def test_basic_cases(self):
31
+ def check_basic_case(graph_func, n_nodes, strategy, interchange):
32
+ graph = graph_func()
33
+ coloring = nx.coloring.greedy_color(
34
+ graph, strategy=strategy, interchange=interchange
35
+ )
36
+ assert verify_length(coloring, n_nodes)
37
+ assert verify_coloring(graph, coloring)
38
+
39
+ for graph_func, n_nodes in BASIC_TEST_CASES.items():
40
+ for interchange in [True, False]:
41
+ for strategy in ALL_STRATEGIES:
42
+ check_basic_case(graph_func, n_nodes, strategy, False)
43
+ if strategy not in INTERCHANGE_INVALID:
44
+ check_basic_case(graph_func, n_nodes, strategy, True)
45
+
46
+ def test_special_cases(self):
47
+ def check_special_case(strategy, graph_func, interchange, colors):
48
+ graph = graph_func()
49
+ coloring = nx.coloring.greedy_color(
50
+ graph, strategy=strategy, interchange=interchange
51
+ )
52
+ if not hasattr(colors, "__len__"):
53
+ colors = [colors]
54
+ assert any(verify_length(coloring, n_colors) for n_colors in colors)
55
+ assert verify_coloring(graph, coloring)
56
+
57
+ for strategy, arglist in SPECIAL_TEST_CASES.items():
58
+ for args in arglist:
59
+ check_special_case(strategy, args[0], args[1], args[2])
60
+
61
+ def test_interchange_invalid(self):
62
+ graph = one_node_graph()
63
+ for strategy in INTERCHANGE_INVALID:
64
+ pytest.raises(
65
+ nx.NetworkXPointlessConcept,
66
+ nx.coloring.greedy_color,
67
+ graph,
68
+ strategy=strategy,
69
+ interchange=True,
70
+ )
71
+
72
+ def test_bad_inputs(self):
73
+ graph = one_node_graph()
74
+ pytest.raises(
75
+ nx.NetworkXError,
76
+ nx.coloring.greedy_color,
77
+ graph,
78
+ strategy="invalid strategy",
79
+ )
80
+
81
+ def test_strategy_as_function(self):
82
+ graph = lf_shc()
83
+ colors_1 = nx.coloring.greedy_color(graph, "largest_first")
84
+ colors_2 = nx.coloring.greedy_color(graph, nx.coloring.strategy_largest_first)
85
+ assert colors_1 == colors_2
86
+
87
+ def test_seed_argument(self):
88
+ graph = lf_shc()
89
+ rs = nx.coloring.strategy_random_sequential
90
+ c1 = nx.coloring.greedy_color(graph, lambda g, c: rs(g, c, seed=1))
91
+ for u, v in graph.edges:
92
+ assert c1[u] != c1[v]
93
+
94
+ def test_is_coloring(self):
95
+ G = nx.Graph()
96
+ G.add_edges_from([(0, 1), (1, 2)])
97
+ coloring = {0: 0, 1: 1, 2: 0}
98
+ assert is_coloring(G, coloring)
99
+
100
+ coloring[0] = 1
101
+ assert not is_coloring(G, coloring)
102
+ assert not is_equitable(G, coloring)
103
+
104
+ def test_is_equitable(self):
105
+ G = nx.Graph()
106
+ G.add_edges_from([(0, 1), (1, 2)])
107
+ coloring = {0: 0, 1: 1, 2: 0}
108
+ assert is_equitable(G, coloring)
109
+
110
+ G.add_edges_from([(2, 3), (2, 4), (2, 5)])
111
+ coloring[3] = 1
112
+ coloring[4] = 1
113
+ coloring[5] = 1
114
+ assert is_coloring(G, coloring)
115
+ assert not is_equitable(G, coloring)
116
+
117
+ def test_num_colors(self):
118
+ G = nx.Graph()
119
+ G.add_edges_from([(0, 1), (0, 2), (0, 3)])
120
+ pytest.raises(nx.NetworkXAlgorithmError, nx.coloring.equitable_color, G, 2)
121
+
122
+ def test_equitable_color(self):
123
+ G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
124
+ coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
125
+ assert is_equitable(G, coloring)
126
+
127
+ def test_equitable_color_empty(self):
128
+ G = nx.empty_graph()
129
+ coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
130
+ assert is_equitable(G, coloring)
131
+
132
+ def test_equitable_color_large(self):
133
+ G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
134
+ coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
135
+ assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
136
+
137
+ def test_case_V_plus_not_in_A_cal(self):
138
+ # Hand crafted case to avoid the easy case.
139
+ L = {
140
+ 0: [2, 5],
141
+ 1: [3, 4],
142
+ 2: [0, 8],
143
+ 3: [1, 7],
144
+ 4: [1, 6],
145
+ 5: [0, 6],
146
+ 6: [4, 5],
147
+ 7: [3],
148
+ 8: [2],
149
+ }
150
+
151
+ F = {
152
+ # Color 0
153
+ 0: 0,
154
+ 1: 0,
155
+ # Color 1
156
+ 2: 1,
157
+ 3: 1,
158
+ 4: 1,
159
+ 5: 1,
160
+ # Color 2
161
+ 6: 2,
162
+ 7: 2,
163
+ 8: 2,
164
+ }
165
+
166
+ C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
167
+ N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
168
+ H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
169
+
170
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
171
+ V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
172
+ )
173
+ check_state(L=L, N=N, H=H, F=F, C=C)
174
+
175
+ def test_cast_no_solo(self):
176
+ L = {
177
+ 0: [8, 9],
178
+ 1: [10, 11],
179
+ 2: [8],
180
+ 3: [9],
181
+ 4: [10, 11],
182
+ 5: [8],
183
+ 6: [9],
184
+ 7: [10, 11],
185
+ 8: [0, 2, 5],
186
+ 9: [0, 3, 6],
187
+ 10: [1, 4, 7],
188
+ 11: [1, 4, 7],
189
+ }
190
+
191
+ F = {0: 0, 1: 0, 2: 2, 3: 2, 4: 2, 5: 3, 6: 3, 7: 3, 8: 1, 9: 1, 10: 1, 11: 1}
192
+
193
+ C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
194
+ N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
195
+ H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
196
+
197
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
198
+ V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
199
+ )
200
+ check_state(L=L, N=N, H=H, F=F, C=C)
201
+
202
+ def test_hard_prob(self):
203
+ # Tests for two levels of recursion.
204
+ num_colors, s = 5, 5
205
+
206
+ G = nx.Graph()
207
+ G.add_edges_from(
208
+ [
209
+ (0, 10),
210
+ (0, 11),
211
+ (0, 12),
212
+ (0, 23),
213
+ (10, 4),
214
+ (10, 9),
215
+ (10, 20),
216
+ (11, 4),
217
+ (11, 8),
218
+ (11, 16),
219
+ (12, 9),
220
+ (12, 22),
221
+ (12, 23),
222
+ (23, 7),
223
+ (1, 17),
224
+ (1, 18),
225
+ (1, 19),
226
+ (1, 24),
227
+ (17, 5),
228
+ (17, 13),
229
+ (17, 22),
230
+ (18, 5),
231
+ (19, 5),
232
+ (19, 6),
233
+ (19, 8),
234
+ (24, 7),
235
+ (24, 16),
236
+ (2, 4),
237
+ (2, 13),
238
+ (2, 14),
239
+ (2, 15),
240
+ (4, 6),
241
+ (13, 5),
242
+ (13, 21),
243
+ (14, 6),
244
+ (14, 15),
245
+ (15, 6),
246
+ (15, 21),
247
+ (3, 16),
248
+ (3, 20),
249
+ (3, 21),
250
+ (3, 22),
251
+ (16, 8),
252
+ (20, 8),
253
+ (21, 9),
254
+ (22, 7),
255
+ ]
256
+ )
257
+ F = {node: node // s for node in range(num_colors * s)}
258
+ F[s - 1] = num_colors - 1
259
+
260
+ params = make_params_from_graph(G=G, F=F)
261
+
262
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
263
+ V_minus=0, V_plus=num_colors - 1, **params
264
+ )
265
+ check_state(**params)
266
+
267
+ def test_hardest_prob(self):
268
+ # Tests for two levels of recursion.
269
+ num_colors, s = 10, 4
270
+
271
+ G = nx.Graph()
272
+ G.add_edges_from(
273
+ [
274
+ (0, 19),
275
+ (0, 24),
276
+ (0, 29),
277
+ (0, 30),
278
+ (0, 35),
279
+ (19, 3),
280
+ (19, 7),
281
+ (19, 9),
282
+ (19, 15),
283
+ (19, 21),
284
+ (19, 24),
285
+ (19, 30),
286
+ (19, 38),
287
+ (24, 5),
288
+ (24, 11),
289
+ (24, 13),
290
+ (24, 20),
291
+ (24, 30),
292
+ (24, 37),
293
+ (24, 38),
294
+ (29, 6),
295
+ (29, 10),
296
+ (29, 13),
297
+ (29, 15),
298
+ (29, 16),
299
+ (29, 17),
300
+ (29, 20),
301
+ (29, 26),
302
+ (30, 6),
303
+ (30, 10),
304
+ (30, 15),
305
+ (30, 22),
306
+ (30, 23),
307
+ (30, 39),
308
+ (35, 6),
309
+ (35, 9),
310
+ (35, 14),
311
+ (35, 18),
312
+ (35, 22),
313
+ (35, 23),
314
+ (35, 25),
315
+ (35, 27),
316
+ (1, 20),
317
+ (1, 26),
318
+ (1, 31),
319
+ (1, 34),
320
+ (1, 38),
321
+ (20, 4),
322
+ (20, 8),
323
+ (20, 14),
324
+ (20, 18),
325
+ (20, 28),
326
+ (20, 33),
327
+ (26, 7),
328
+ (26, 10),
329
+ (26, 14),
330
+ (26, 18),
331
+ (26, 21),
332
+ (26, 32),
333
+ (26, 39),
334
+ (31, 5),
335
+ (31, 8),
336
+ (31, 13),
337
+ (31, 16),
338
+ (31, 17),
339
+ (31, 21),
340
+ (31, 25),
341
+ (31, 27),
342
+ (34, 7),
343
+ (34, 8),
344
+ (34, 13),
345
+ (34, 18),
346
+ (34, 22),
347
+ (34, 23),
348
+ (34, 25),
349
+ (34, 27),
350
+ (38, 4),
351
+ (38, 9),
352
+ (38, 12),
353
+ (38, 14),
354
+ (38, 21),
355
+ (38, 27),
356
+ (2, 3),
357
+ (2, 18),
358
+ (2, 21),
359
+ (2, 28),
360
+ (2, 32),
361
+ (2, 33),
362
+ (2, 36),
363
+ (2, 37),
364
+ (2, 39),
365
+ (3, 5),
366
+ (3, 9),
367
+ (3, 13),
368
+ (3, 22),
369
+ (3, 23),
370
+ (3, 25),
371
+ (3, 27),
372
+ (18, 6),
373
+ (18, 11),
374
+ (18, 15),
375
+ (18, 39),
376
+ (21, 4),
377
+ (21, 10),
378
+ (21, 14),
379
+ (21, 36),
380
+ (28, 6),
381
+ (28, 10),
382
+ (28, 14),
383
+ (28, 16),
384
+ (28, 17),
385
+ (28, 25),
386
+ (28, 27),
387
+ (32, 5),
388
+ (32, 10),
389
+ (32, 12),
390
+ (32, 16),
391
+ (32, 17),
392
+ (32, 22),
393
+ (32, 23),
394
+ (33, 7),
395
+ (33, 10),
396
+ (33, 12),
397
+ (33, 16),
398
+ (33, 17),
399
+ (33, 25),
400
+ (33, 27),
401
+ (36, 5),
402
+ (36, 8),
403
+ (36, 15),
404
+ (36, 16),
405
+ (36, 17),
406
+ (36, 25),
407
+ (36, 27),
408
+ (37, 5),
409
+ (37, 11),
410
+ (37, 15),
411
+ (37, 16),
412
+ (37, 17),
413
+ (37, 22),
414
+ (37, 23),
415
+ (39, 7),
416
+ (39, 8),
417
+ (39, 15),
418
+ (39, 22),
419
+ (39, 23),
420
+ ]
421
+ )
422
+ F = {node: node // s for node in range(num_colors * s)}
423
+ F[s - 1] = num_colors - 1 # V- = 0, V+ = num_colors - 1
424
+
425
+ params = make_params_from_graph(G=G, F=F)
426
+
427
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
428
+ V_minus=0, V_plus=num_colors - 1, **params
429
+ )
430
+ check_state(**params)
431
+
432
+ def test_strategy_saturation_largest_first(self):
433
+ def color_remaining_nodes(
434
+ G,
435
+ colored_nodes,
436
+ full_color_assignment=None,
437
+ nodes_to_add_between_calls=1,
438
+ ):
439
+ color_assignments = []
440
+ aux_colored_nodes = colored_nodes.copy()
441
+
442
+ node_iterator = nx.algorithms.coloring.greedy_coloring.strategy_saturation_largest_first(
443
+ G, aux_colored_nodes
444
+ )
445
+
446
+ for u in node_iterator:
447
+ # Set to keep track of colors of neighbors
448
+ nbr_colors = {
449
+ aux_colored_nodes[v] for v in G[u] if v in aux_colored_nodes
450
+ }
451
+ # Find the first unused color.
452
+ for color in itertools.count():
453
+ if color not in nbr_colors:
454
+ break
455
+ aux_colored_nodes[u] = color
456
+ color_assignments.append((u, color))
457
+
458
+ # Color nodes between iterations
459
+ for i in range(nodes_to_add_between_calls - 1):
460
+ if not len(color_assignments) + len(colored_nodes) >= len(
461
+ full_color_assignment
462
+ ):
463
+ full_color_assignment_node, color = full_color_assignment[
464
+ len(color_assignments) + len(colored_nodes)
465
+ ]
466
+
467
+ # Assign the new color to the current node.
468
+ aux_colored_nodes[full_color_assignment_node] = color
469
+ color_assignments.append((full_color_assignment_node, color))
470
+
471
+ return color_assignments, aux_colored_nodes
472
+
473
+ for G, _, _ in SPECIAL_TEST_CASES["saturation_largest_first"]:
474
+ G = G()
475
+
476
+ # Check that function still works when nodes are colored between iterations
477
+ for nodes_to_add_between_calls in range(1, 5):
478
+ # Get a full color assignment, (including the order in which nodes were colored)
479
+ colored_nodes = {}
480
+ full_color_assignment, full_colored_nodes = color_remaining_nodes(
481
+ G, colored_nodes
482
+ )
483
+
484
+ # For each node in the color assignment, add it to colored_nodes and re-run the function
485
+ for ind, (node, color) in enumerate(full_color_assignment):
486
+ colored_nodes[node] = color
487
+
488
+ (
489
+ partial_color_assignment,
490
+ partial_colored_nodes,
491
+ ) = color_remaining_nodes(
492
+ G,
493
+ colored_nodes,
494
+ full_color_assignment=full_color_assignment,
495
+ nodes_to_add_between_calls=nodes_to_add_between_calls,
496
+ )
497
+
498
+ # Check that the color assignment and order of remaining nodes are the same
499
+ assert full_color_assignment[ind + 1 :] == partial_color_assignment
500
+ assert full_colored_nodes == partial_colored_nodes
501
+
502
+
503
+ # ############################ Utility functions ############################
504
+ def verify_coloring(graph, coloring):
505
+ for node in graph.nodes():
506
+ if node not in coloring:
507
+ return False
508
+
509
+ color = coloring[node]
510
+ for neighbor in graph.neighbors(node):
511
+ if coloring[neighbor] == color:
512
+ return False
513
+
514
+ return True
515
+
516
+
517
+ def verify_length(coloring, expected):
518
+ coloring = dict_to_sets(coloring)
519
+ return len(coloring) == expected
520
+
521
+
522
+ def dict_to_sets(colors):
523
+ if len(colors) == 0:
524
+ return []
525
+
526
+ k = max(colors.values()) + 1
527
+ sets = [set() for _ in range(k)]
528
+
529
+ for node, color in colors.items():
530
+ sets[color].add(node)
531
+
532
+ return sets
533
+
534
+
535
+ # ############################ Graph Generation ############################
536
+
537
+
538
+ def empty_graph():
539
+ return nx.Graph()
540
+
541
+
542
+ def one_node_graph():
543
+ graph = nx.Graph()
544
+ graph.add_nodes_from([1])
545
+ return graph
546
+
547
+
548
+ def two_node_graph():
549
+ graph = nx.Graph()
550
+ graph.add_nodes_from([1, 2])
551
+ graph.add_edges_from([(1, 2)])
552
+ return graph
553
+
554
+
555
+ def three_node_clique():
556
+ graph = nx.Graph()
557
+ graph.add_nodes_from([1, 2, 3])
558
+ graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
559
+ return graph
560
+
561
+
562
+ def disconnected():
563
+ graph = nx.Graph()
564
+ graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
565
+ return graph
566
+
567
+
568
+ def rs_shc():
569
+ graph = nx.Graph()
570
+ graph.add_nodes_from([1, 2, 3, 4])
571
+ graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
572
+ return graph
573
+
574
+
575
+ def slf_shc():
576
+ graph = nx.Graph()
577
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
578
+ graph.add_edges_from(
579
+ [(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
580
+ )
581
+ return graph
582
+
583
+
584
+ def slf_hc():
585
+ graph = nx.Graph()
586
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
587
+ graph.add_edges_from(
588
+ [
589
+ (1, 2),
590
+ (1, 3),
591
+ (1, 4),
592
+ (1, 5),
593
+ (2, 3),
594
+ (2, 4),
595
+ (2, 6),
596
+ (5, 7),
597
+ (5, 8),
598
+ (6, 7),
599
+ (6, 8),
600
+ (7, 8),
601
+ ]
602
+ )
603
+ return graph
604
+
605
+
606
+ def lf_shc():
607
+ graph = nx.Graph()
608
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
609
+ graph.add_edges_from([(6, 1), (1, 4), (4, 3), (3, 2), (2, 5)])
610
+ return graph
611
+
612
+
613
+ def lf_hc():
614
+ graph = nx.Graph()
615
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
616
+ graph.add_edges_from(
617
+ [
618
+ (1, 7),
619
+ (1, 6),
620
+ (1, 3),
621
+ (1, 4),
622
+ (7, 2),
623
+ (2, 6),
624
+ (2, 3),
625
+ (2, 5),
626
+ (5, 3),
627
+ (5, 4),
628
+ (4, 3),
629
+ ]
630
+ )
631
+ return graph
632
+
633
+
634
+ def sl_shc():
635
+ graph = nx.Graph()
636
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
637
+ graph.add_edges_from(
638
+ [(1, 2), (1, 3), (2, 3), (1, 4), (2, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
639
+ )
640
+ return graph
641
+
642
+
643
+ def sl_hc():
644
+ graph = nx.Graph()
645
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
646
+ graph.add_edges_from(
647
+ [
648
+ (1, 2),
649
+ (1, 3),
650
+ (1, 5),
651
+ (1, 7),
652
+ (2, 3),
653
+ (2, 4),
654
+ (2, 8),
655
+ (8, 4),
656
+ (8, 6),
657
+ (8, 7),
658
+ (7, 5),
659
+ (7, 6),
660
+ (3, 4),
661
+ (4, 6),
662
+ (6, 5),
663
+ (5, 3),
664
+ ]
665
+ )
666
+ return graph
667
+
668
+
669
+ def gis_shc():
670
+ graph = nx.Graph()
671
+ graph.add_nodes_from([1, 2, 3, 4])
672
+ graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
673
+ return graph
674
+
675
+
676
+ def gis_hc():
677
+ graph = nx.Graph()
678
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
679
+ graph.add_edges_from([(1, 5), (2, 5), (3, 6), (4, 6), (5, 6)])
680
+ return graph
681
+
682
+
683
+ def cs_shc():
684
+ graph = nx.Graph()
685
+ graph.add_nodes_from([1, 2, 3, 4, 5])
686
+ graph.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)])
687
+ return graph
688
+
689
+
690
+ def rsi_shc():
691
+ graph = nx.Graph()
692
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
693
+ graph.add_edges_from(
694
+ [(1, 2), (1, 5), (1, 6), (2, 3), (3, 4), (4, 5), (4, 6), (5, 6)]
695
+ )
696
+ return graph
697
+
698
+
699
+ def lfi_shc():
700
+ graph = nx.Graph()
701
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
702
+ graph.add_edges_from(
703
+ [(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
704
+ )
705
+ return graph
706
+
707
+
708
+ def lfi_hc():
709
+ graph = nx.Graph()
710
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
711
+ graph.add_edges_from(
712
+ [
713
+ (1, 2),
714
+ (1, 5),
715
+ (1, 6),
716
+ (1, 7),
717
+ (2, 3),
718
+ (2, 8),
719
+ (2, 9),
720
+ (3, 4),
721
+ (3, 8),
722
+ (3, 9),
723
+ (4, 5),
724
+ (4, 6),
725
+ (4, 7),
726
+ (5, 6),
727
+ ]
728
+ )
729
+ return graph
730
+
731
+
732
+ def sli_shc():
733
+ graph = nx.Graph()
734
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
735
+ graph.add_edges_from(
736
+ [
737
+ (1, 2),
738
+ (1, 3),
739
+ (1, 5),
740
+ (1, 7),
741
+ (2, 3),
742
+ (2, 6),
743
+ (3, 4),
744
+ (4, 5),
745
+ (4, 6),
746
+ (5, 7),
747
+ (6, 7),
748
+ ]
749
+ )
750
+ return graph
751
+
752
+
753
+ def sli_hc():
754
+ graph = nx.Graph()
755
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
756
+ graph.add_edges_from(
757
+ [
758
+ (1, 2),
759
+ (1, 3),
760
+ (1, 4),
761
+ (1, 5),
762
+ (2, 3),
763
+ (2, 7),
764
+ (2, 8),
765
+ (2, 9),
766
+ (3, 6),
767
+ (3, 7),
768
+ (3, 9),
769
+ (4, 5),
770
+ (4, 6),
771
+ (4, 8),
772
+ (4, 9),
773
+ (5, 6),
774
+ (5, 7),
775
+ (5, 8),
776
+ (6, 7),
777
+ (6, 9),
778
+ (7, 8),
779
+ (8, 9),
780
+ ]
781
+ )
782
+ return graph
783
+
784
+
785
+ # --------------------------------------------------------------------------
786
+ # Basic tests for all strategies
787
+ # For each basic graph function, specify the number of expected colors.
788
+ BASIC_TEST_CASES = {
789
+ empty_graph: 0,
790
+ one_node_graph: 1,
791
+ two_node_graph: 2,
792
+ disconnected: 2,
793
+ three_node_clique: 3,
794
+ }
795
+
796
+
797
+ # --------------------------------------------------------------------------
798
+ # Special test cases. Each strategy has a list of tuples of the form
799
+ # (graph function, interchange, valid # of colors)
800
+ SPECIAL_TEST_CASES = {
801
+ "random_sequential": [
802
+ (rs_shc, False, (2, 3)),
803
+ (rs_shc, True, 2),
804
+ (rsi_shc, True, (3, 4)),
805
+ ],
806
+ "saturation_largest_first": [(slf_shc, False, (3, 4)), (slf_hc, False, 4)],
807
+ "largest_first": [
808
+ (lf_shc, False, (2, 3)),
809
+ (lf_hc, False, 4),
810
+ (lf_shc, True, 2),
811
+ (lf_hc, True, 3),
812
+ (lfi_shc, True, (3, 4)),
813
+ (lfi_hc, True, 4),
814
+ ],
815
+ "smallest_last": [
816
+ (sl_shc, False, (3, 4)),
817
+ (sl_hc, False, 5),
818
+ (sl_shc, True, 3),
819
+ (sl_hc, True, 4),
820
+ (sli_shc, True, (3, 4)),
821
+ (sli_hc, True, 5),
822
+ ],
823
+ "independent_set": [(gis_shc, False, (2, 3)), (gis_hc, False, 3)],
824
+ "connected_sequential": [(cs_shc, False, (3, 4)), (cs_shc, True, 3)],
825
+ "connected_sequential_dfs": [(cs_shc, False, (3, 4))],
826
+ }
827
+
828
+
829
+ # --------------------------------------------------------------------------
830
+ # Helper functions to test
831
+ # (graph function, interchange, valid # of colors)
832
+
833
+
834
+ def check_state(L, N, H, F, C):
835
+ s = len(C[0])
836
+ num_colors = len(C.keys())
837
+
838
+ assert all(u in L[v] for u in L for v in L[u])
839
+ assert all(F[u] != F[v] for u in L for v in L[u])
840
+ assert all(len(L[u]) < num_colors for u in L)
841
+ assert all(len(C[x]) == s for x in C)
842
+ assert all(H[(c1, c2)] >= 0 for c1 in C for c2 in C)
843
+ assert all(N[(u, F[u])] == 0 for u in F)
844
+
845
+
846
+ def max_degree(G):
847
+ """Get the maximum degree of any node in G."""
848
+ return max(G.degree(node) for node in G.nodes) if len(G.nodes) > 0 else 0
849
+
850
+
851
+ def make_params_from_graph(G, F):
852
+ """Returns {N, L, H, C} from the given graph."""
853
+ num_nodes = len(G)
854
+ L = {u: [] for u in range(num_nodes)}
855
+ for u, v in G.edges:
856
+ L[u].append(v)
857
+ L[v].append(u)
858
+
859
+ C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
860
+ N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
861
+ H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
862
+
863
+ return {"N": N, "F": F, "C": C, "H": H, "L": L}
janus/lib/python3.10/site-packages/networkx/algorithms/components/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .connected import *
2
+ from .strongly_connected import *
3
+ from .weakly_connected import *
4
+ from .attracting import *
5
+ from .biconnected import *
6
+ from .semiconnected import *
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (335 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc ADDED
Binary file (4.83 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc ADDED
Binary file (2.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc ADDED
Binary file (9.35 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc ADDED
Binary file (4.5 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/attracting.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attracting components."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import not_implemented_for
5
+
6
+ __all__ = [
7
+ "number_attracting_components",
8
+ "attracting_components",
9
+ "is_attracting_component",
10
+ ]
11
+
12
+
13
+ @not_implemented_for("undirected")
14
+ @nx._dispatchable
15
+ def attracting_components(G):
16
+ """Generates the attracting components in `G`.
17
+
18
+ An attracting component in a directed graph `G` is a strongly connected
19
+ component with the property that a random walker on the graph will never
20
+ leave the component, once it enters the component.
21
+
22
+ The nodes in attracting components can also be thought of as recurrent
23
+ nodes. If a random walker enters the attractor containing the node, then
24
+ the node will be visited infinitely often.
25
+
26
+ To obtain induced subgraphs on each component use:
27
+ ``(G.subgraph(c).copy() for c in attracting_components(G))``
28
+
29
+ Parameters
30
+ ----------
31
+ G : DiGraph, MultiDiGraph
32
+ The graph to be analyzed.
33
+
34
+ Returns
35
+ -------
36
+ attractors : generator of sets
37
+ A generator of sets of nodes, one for each attracting component of G.
38
+
39
+ Raises
40
+ ------
41
+ NetworkXNotImplemented
42
+ If the input graph is undirected.
43
+
44
+ See Also
45
+ --------
46
+ number_attracting_components
47
+ is_attracting_component
48
+
49
+ """
50
+ scc = list(nx.strongly_connected_components(G))
51
+ cG = nx.condensation(G, scc)
52
+ for n in cG:
53
+ if cG.out_degree(n) == 0:
54
+ yield scc[n]
55
+
56
+
57
+ @not_implemented_for("undirected")
58
+ @nx._dispatchable
59
+ def number_attracting_components(G):
60
+ """Returns the number of attracting components in `G`.
61
+
62
+ Parameters
63
+ ----------
64
+ G : DiGraph, MultiDiGraph
65
+ The graph to be analyzed.
66
+
67
+ Returns
68
+ -------
69
+ n : int
70
+ The number of attracting components in G.
71
+
72
+ Raises
73
+ ------
74
+ NetworkXNotImplemented
75
+ If the input graph is undirected.
76
+
77
+ See Also
78
+ --------
79
+ attracting_components
80
+ is_attracting_component
81
+
82
+ """
83
+ return sum(1 for ac in attracting_components(G))
84
+
85
+
86
+ @not_implemented_for("undirected")
87
+ @nx._dispatchable
88
+ def is_attracting_component(G):
89
+ """Returns True if `G` consists of a single attracting component.
90
+
91
+ Parameters
92
+ ----------
93
+ G : DiGraph, MultiDiGraph
94
+ The graph to be analyzed.
95
+
96
+ Returns
97
+ -------
98
+ attracting : bool
99
+ True if `G` has a single attracting component. Otherwise, False.
100
+
101
+ Raises
102
+ ------
103
+ NetworkXNotImplemented
104
+ If the input graph is undirected.
105
+
106
+ See Also
107
+ --------
108
+ attracting_components
109
+ number_attracting_components
110
+
111
+ """
112
+ ac = list(attracting_components(G))
113
+ if len(ac) == 1:
114
+ return len(ac[0]) == len(G)
115
+ return False
janus/lib/python3.10/site-packages/networkx/algorithms/components/biconnected.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Biconnected components and articulation points."""
2
+
3
+ from itertools import chain
4
+
5
+ import networkx as nx
6
+ from networkx.utils.decorators import not_implemented_for
7
+
8
+ __all__ = [
9
+ "biconnected_components",
10
+ "biconnected_component_edges",
11
+ "is_biconnected",
12
+ "articulation_points",
13
+ ]
14
+
15
+
16
+ @not_implemented_for("directed")
17
+ @nx._dispatchable
18
+ def is_biconnected(G):
19
+ """Returns True if the graph is biconnected, False otherwise.
20
+
21
+ A graph is biconnected if, and only if, it cannot be disconnected by
22
+ removing only one node (and all edges incident on that node). If
23
+ removing a node increases the number of disconnected components
24
+ in the graph, that node is called an articulation point, or cut
25
+ vertex. A biconnected graph has no articulation points.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX Graph
30
+ An undirected graph.
31
+
32
+ Returns
33
+ -------
34
+ biconnected : bool
35
+ True if the graph is biconnected, False otherwise.
36
+
37
+ Raises
38
+ ------
39
+ NetworkXNotImplemented
40
+ If the input graph is not undirected.
41
+
42
+ Examples
43
+ --------
44
+ >>> G = nx.path_graph(4)
45
+ >>> print(nx.is_biconnected(G))
46
+ False
47
+ >>> G.add_edge(0, 3)
48
+ >>> print(nx.is_biconnected(G))
49
+ True
50
+
51
+ See Also
52
+ --------
53
+ biconnected_components
54
+ articulation_points
55
+ biconnected_component_edges
56
+ is_strongly_connected
57
+ is_weakly_connected
58
+ is_connected
59
+ is_semiconnected
60
+
61
+ Notes
62
+ -----
63
+ The algorithm to find articulation points and biconnected
64
+ components is implemented using a non-recursive depth-first-search
65
+ (DFS) that keeps track of the highest level that back edges reach
66
+ in the DFS tree. A node `n` is an articulation point if, and only
67
+ if, there exists a subtree rooted at `n` such that there is no
68
+ back edge from any successor of `n` that links to a predecessor of
69
+ `n` in the DFS tree. By keeping track of all the edges traversed
70
+ by the DFS we can obtain the biconnected components because all
71
+ edges of a bicomponent will be traversed consecutively between
72
+ articulation points.
73
+
74
+ References
75
+ ----------
76
+ .. [1] Hopcroft, J.; Tarjan, R. (1973).
77
+ "Efficient algorithms for graph manipulation".
78
+ Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
79
+
80
+ """
81
+ bccs = biconnected_components(G)
82
+ try:
83
+ bcc = next(bccs)
84
+ except StopIteration:
85
+ # No bicomponents (empty graph?)
86
+ return False
87
+ try:
88
+ next(bccs)
89
+ except StopIteration:
90
+ # Only one bicomponent
91
+ return len(bcc) == len(G)
92
+ else:
93
+ # Multiple bicomponents
94
+ return False
95
+
96
+
97
+ @not_implemented_for("directed")
98
+ @nx._dispatchable
99
+ def biconnected_component_edges(G):
100
+ """Returns a generator of lists of edges, one list for each biconnected
101
+ component of the input graph.
102
+
103
+ Biconnected components are maximal subgraphs such that the removal of a
104
+ node (and all edges incident on that node) will not disconnect the
105
+ subgraph. Note that nodes may be part of more than one biconnected
106
+ component. Those nodes are articulation points, or cut vertices.
107
+ However, each edge belongs to one, and only one, biconnected component.
108
+
109
+ Notice that by convention a dyad is considered a biconnected component.
110
+
111
+ Parameters
112
+ ----------
113
+ G : NetworkX Graph
114
+ An undirected graph.
115
+
116
+ Returns
117
+ -------
118
+ edges : generator of lists
119
+ Generator of lists of edges, one list for each bicomponent.
120
+
121
+ Raises
122
+ ------
123
+ NetworkXNotImplemented
124
+ If the input graph is not undirected.
125
+
126
+ Examples
127
+ --------
128
+ >>> G = nx.barbell_graph(4, 2)
129
+ >>> print(nx.is_biconnected(G))
130
+ False
131
+ >>> bicomponents_edges = list(nx.biconnected_component_edges(G))
132
+ >>> len(bicomponents_edges)
133
+ 5
134
+ >>> G.add_edge(2, 8)
135
+ >>> print(nx.is_biconnected(G))
136
+ True
137
+ >>> bicomponents_edges = list(nx.biconnected_component_edges(G))
138
+ >>> len(bicomponents_edges)
139
+ 1
140
+
141
+ See Also
142
+ --------
143
+ is_biconnected,
144
+ biconnected_components,
145
+ articulation_points,
146
+
147
+ Notes
148
+ -----
149
+ The algorithm to find articulation points and biconnected
150
+ components is implemented using a non-recursive depth-first-search
151
+ (DFS) that keeps track of the highest level that back edges reach
152
+ in the DFS tree. A node `n` is an articulation point if, and only
153
+ if, there exists a subtree rooted at `n` such that there is no
154
+ back edge from any successor of `n` that links to a predecessor of
155
+ `n` in the DFS tree. By keeping track of all the edges traversed
156
+ by the DFS we can obtain the biconnected components because all
157
+ edges of a bicomponent will be traversed consecutively between
158
+ articulation points.
159
+
160
+ References
161
+ ----------
162
+ .. [1] Hopcroft, J.; Tarjan, R. (1973).
163
+ "Efficient algorithms for graph manipulation".
164
+ Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
165
+
166
+ """
167
+ yield from _biconnected_dfs(G, components=True)
168
+
169
+
170
+ @not_implemented_for("directed")
171
+ @nx._dispatchable
172
+ def biconnected_components(G):
173
+ """Returns a generator of sets of nodes, one set for each biconnected
174
+ component of the graph
175
+
176
+ Biconnected components are maximal subgraphs such that the removal of a
177
+ node (and all edges incident on that node) will not disconnect the
178
+ subgraph. Note that nodes may be part of more than one biconnected
179
+ component. Those nodes are articulation points, or cut vertices. The
180
+ removal of articulation points will increase the number of connected
181
+ components of the graph.
182
+
183
+ Notice that by convention a dyad is considered a biconnected component.
184
+
185
+ Parameters
186
+ ----------
187
+ G : NetworkX Graph
188
+ An undirected graph.
189
+
190
+ Returns
191
+ -------
192
+ nodes : generator
193
+ Generator of sets of nodes, one set for each biconnected component.
194
+
195
+ Raises
196
+ ------
197
+ NetworkXNotImplemented
198
+ If the input graph is not undirected.
199
+
200
+ Examples
201
+ --------
202
+ >>> G = nx.lollipop_graph(5, 1)
203
+ >>> print(nx.is_biconnected(G))
204
+ False
205
+ >>> bicomponents = list(nx.biconnected_components(G))
206
+ >>> len(bicomponents)
207
+ 2
208
+ >>> G.add_edge(0, 5)
209
+ >>> print(nx.is_biconnected(G))
210
+ True
211
+ >>> bicomponents = list(nx.biconnected_components(G))
212
+ >>> len(bicomponents)
213
+ 1
214
+
215
+ You can generate a sorted list of biconnected components, largest
216
+ first, using sort.
217
+
218
+ >>> G.remove_edge(0, 5)
219
+ >>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)]
220
+ [5, 2]
221
+
222
+ If you only want the largest connected component, it's more
223
+ efficient to use max instead of sort.
224
+
225
+ >>> Gc = max(nx.biconnected_components(G), key=len)
226
+
227
+ To create the components as subgraphs use:
228
+ ``(G.subgraph(c).copy() for c in biconnected_components(G))``
229
+
230
+ See Also
231
+ --------
232
+ is_biconnected
233
+ articulation_points
234
+ biconnected_component_edges
235
+ k_components : this function is a special case where k=2
236
+ bridge_components : similar to this function, but is defined using
237
+ 2-edge-connectivity instead of 2-node-connectivity.
238
+
239
+ Notes
240
+ -----
241
+ The algorithm to find articulation points and biconnected
242
+ components is implemented using a non-recursive depth-first-search
243
+ (DFS) that keeps track of the highest level that back edges reach
244
+ in the DFS tree. A node `n` is an articulation point if, and only
245
+ if, there exists a subtree rooted at `n` such that there is no
246
+ back edge from any successor of `n` that links to a predecessor of
247
+ `n` in the DFS tree. By keeping track of all the edges traversed
248
+ by the DFS we can obtain the biconnected components because all
249
+ edges of a bicomponent will be traversed consecutively between
250
+ articulation points.
251
+
252
+ References
253
+ ----------
254
+ .. [1] Hopcroft, J.; Tarjan, R. (1973).
255
+ "Efficient algorithms for graph manipulation".
256
+ Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
257
+
258
+ """
259
+ for comp in _biconnected_dfs(G, components=True):
260
+ yield set(chain.from_iterable(comp))
261
+
262
+
263
+ @not_implemented_for("directed")
264
+ @nx._dispatchable
265
+ def articulation_points(G):
266
+ """Yield the articulation points, or cut vertices, of a graph.
267
+
268
+ An articulation point or cut vertex is any node whose removal (along with
269
+ all its incident edges) increases the number of connected components of
270
+ a graph. An undirected connected graph without articulation points is
271
+ biconnected. Articulation points belong to more than one biconnected
272
+ component of a graph.
273
+
274
+ Notice that by convention a dyad is considered a biconnected component.
275
+
276
+ Parameters
277
+ ----------
278
+ G : NetworkX Graph
279
+ An undirected graph.
280
+
281
+ Yields
282
+ ------
283
+ node
284
+ An articulation point in the graph.
285
+
286
+ Raises
287
+ ------
288
+ NetworkXNotImplemented
289
+ If the input graph is not undirected.
290
+
291
+ Examples
292
+ --------
293
+
294
+ >>> G = nx.barbell_graph(4, 2)
295
+ >>> print(nx.is_biconnected(G))
296
+ False
297
+ >>> len(list(nx.articulation_points(G)))
298
+ 4
299
+ >>> G.add_edge(2, 8)
300
+ >>> print(nx.is_biconnected(G))
301
+ True
302
+ >>> len(list(nx.articulation_points(G)))
303
+ 0
304
+
305
+ See Also
306
+ --------
307
+ is_biconnected
308
+ biconnected_components
309
+ biconnected_component_edges
310
+
311
+ Notes
312
+ -----
313
+ The algorithm to find articulation points and biconnected
314
+ components is implemented using a non-recursive depth-first-search
315
+ (DFS) that keeps track of the highest level that back edges reach
316
+ in the DFS tree. A node `n` is an articulation point if, and only
317
+ if, there exists a subtree rooted at `n` such that there is no
318
+ back edge from any successor of `n` that links to a predecessor of
319
+ `n` in the DFS tree. By keeping track of all the edges traversed
320
+ by the DFS we can obtain the biconnected components because all
321
+ edges of a bicomponent will be traversed consecutively between
322
+ articulation points.
323
+
324
+ References
325
+ ----------
326
+ .. [1] Hopcroft, J.; Tarjan, R. (1973).
327
+ "Efficient algorithms for graph manipulation".
328
+ Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
329
+
330
+ """
331
+ seen = set()
332
+ for articulation in _biconnected_dfs(G, components=False):
333
+ if articulation not in seen:
334
+ seen.add(articulation)
335
+ yield articulation
336
+
337
+
338
+ @not_implemented_for("directed")
339
+ def _biconnected_dfs(G, components=True):
340
+ # depth-first search algorithm to generate articulation points
341
+ # and biconnected components
342
+ visited = set()
343
+ for start in G:
344
+ if start in visited:
345
+ continue
346
+ discovery = {start: 0} # time of first discovery of node during search
347
+ low = {start: 0}
348
+ root_children = 0
349
+ visited.add(start)
350
+ edge_stack = []
351
+ stack = [(start, start, iter(G[start]))]
352
+ edge_index = {}
353
+ while stack:
354
+ grandparent, parent, children = stack[-1]
355
+ try:
356
+ child = next(children)
357
+ if grandparent == child:
358
+ continue
359
+ if child in visited:
360
+ if discovery[child] <= discovery[parent]: # back edge
361
+ low[parent] = min(low[parent], discovery[child])
362
+ if components:
363
+ edge_index[parent, child] = len(edge_stack)
364
+ edge_stack.append((parent, child))
365
+ else:
366
+ low[child] = discovery[child] = len(discovery)
367
+ visited.add(child)
368
+ stack.append((parent, child, iter(G[child])))
369
+ if components:
370
+ edge_index[parent, child] = len(edge_stack)
371
+ edge_stack.append((parent, child))
372
+
373
+ except StopIteration:
374
+ stack.pop()
375
+ if len(stack) > 1:
376
+ if low[parent] >= discovery[grandparent]:
377
+ if components:
378
+ ind = edge_index[grandparent, parent]
379
+ yield edge_stack[ind:]
380
+ del edge_stack[ind:]
381
+
382
+ else:
383
+ yield grandparent
384
+ low[grandparent] = min(low[parent], low[grandparent])
385
+ elif stack: # length 1 so grandparent is root
386
+ root_children += 1
387
+ if components:
388
+ ind = edge_index[grandparent, parent]
389
+ yield edge_stack[ind:]
390
+ del edge_stack[ind:]
391
+ if not components:
392
+ # root node is articulation point if it has more than 1 child
393
+ if root_children > 1:
394
+ yield start
janus/lib/python3.10/site-packages/networkx/algorithms/components/connected.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Connected components."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import not_implemented_for
5
+
6
+ from ...utils import arbitrary_element
7
+
8
+ __all__ = [
9
+ "number_connected_components",
10
+ "connected_components",
11
+ "is_connected",
12
+ "node_connected_component",
13
+ ]
14
+
15
+
16
+ @not_implemented_for("directed")
17
+ @nx._dispatchable
18
+ def connected_components(G):
19
+ """Generate connected components.
20
+
21
+ Parameters
22
+ ----------
23
+ G : NetworkX graph
24
+ An undirected graph
25
+
26
+ Returns
27
+ -------
28
+ comp : generator of sets
29
+ A generator of sets of nodes, one for each component of G.
30
+
31
+ Raises
32
+ ------
33
+ NetworkXNotImplemented
34
+ If G is directed.
35
+
36
+ Examples
37
+ --------
38
+ Generate a sorted list of connected components, largest first.
39
+
40
+ >>> G = nx.path_graph(4)
41
+ >>> nx.add_path(G, [10, 11, 12])
42
+ >>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
43
+ [4, 3]
44
+
45
+ If you only want the largest connected component, it's more
46
+ efficient to use max instead of sort.
47
+
48
+ >>> largest_cc = max(nx.connected_components(G), key=len)
49
+
50
+ To create the induced subgraph of each component use:
51
+
52
+ >>> S = [G.subgraph(c).copy() for c in nx.connected_components(G)]
53
+
54
+ See Also
55
+ --------
56
+ strongly_connected_components
57
+ weakly_connected_components
58
+
59
+ Notes
60
+ -----
61
+ For undirected graphs only.
62
+
63
+ """
64
+ seen = set()
65
+ n = len(G)
66
+ for v in G:
67
+ if v not in seen:
68
+ c = _plain_bfs(G, n, v)
69
+ seen.update(c)
70
+ yield c
71
+
72
+
73
+ @not_implemented_for("directed")
74
+ @nx._dispatchable
75
+ def number_connected_components(G):
76
+ """Returns the number of connected components.
77
+
78
+ Parameters
79
+ ----------
80
+ G : NetworkX graph
81
+ An undirected graph.
82
+
83
+ Returns
84
+ -------
85
+ n : integer
86
+ Number of connected components
87
+
88
+ Raises
89
+ ------
90
+ NetworkXNotImplemented
91
+ If G is directed.
92
+
93
+ Examples
94
+ --------
95
+ >>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
96
+ >>> nx.number_connected_components(G)
97
+ 3
98
+
99
+ See Also
100
+ --------
101
+ connected_components
102
+ number_weakly_connected_components
103
+ number_strongly_connected_components
104
+
105
+ Notes
106
+ -----
107
+ For undirected graphs only.
108
+
109
+ """
110
+ return sum(1 for cc in connected_components(G))
111
+
112
+
113
+ @not_implemented_for("directed")
114
+ @nx._dispatchable
115
+ def is_connected(G):
116
+ """Returns True if the graph is connected, False otherwise.
117
+
118
+ Parameters
119
+ ----------
120
+ G : NetworkX Graph
121
+ An undirected graph.
122
+
123
+ Returns
124
+ -------
125
+ connected : bool
126
+ True if the graph is connected, false otherwise.
127
+
128
+ Raises
129
+ ------
130
+ NetworkXNotImplemented
131
+ If G is directed.
132
+
133
+ Examples
134
+ --------
135
+ >>> G = nx.path_graph(4)
136
+ >>> print(nx.is_connected(G))
137
+ True
138
+
139
+ See Also
140
+ --------
141
+ is_strongly_connected
142
+ is_weakly_connected
143
+ is_semiconnected
144
+ is_biconnected
145
+ connected_components
146
+
147
+ Notes
148
+ -----
149
+ For undirected graphs only.
150
+
151
+ """
152
+ n = len(G)
153
+ if n == 0:
154
+ raise nx.NetworkXPointlessConcept(
155
+ "Connectivity is undefined for the null graph."
156
+ )
157
+ return sum(1 for node in _plain_bfs(G, n, arbitrary_element(G))) == len(G)
158
+
159
+
160
+ @not_implemented_for("directed")
161
+ @nx._dispatchable
162
+ def node_connected_component(G, n):
163
+ """Returns the set of nodes in the component of graph containing node n.
164
+
165
+ Parameters
166
+ ----------
167
+ G : NetworkX Graph
168
+ An undirected graph.
169
+
170
+ n : node label
171
+ A node in G
172
+
173
+ Returns
174
+ -------
175
+ comp : set
176
+ A set of nodes in the component of G containing node n.
177
+
178
+ Raises
179
+ ------
180
+ NetworkXNotImplemented
181
+ If G is directed.
182
+
183
+ Examples
184
+ --------
185
+ >>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
186
+ >>> nx.node_connected_component(G, 0) # nodes of component that contains node 0
187
+ {0, 1, 2}
188
+
189
+ See Also
190
+ --------
191
+ connected_components
192
+
193
+ Notes
194
+ -----
195
+ For undirected graphs only.
196
+
197
+ """
198
+ return _plain_bfs(G, len(G), n)
199
+
200
+
201
+ def _plain_bfs(G, n, source):
202
+ """A fast BFS node generator"""
203
+ adj = G._adj
204
+ seen = {source}
205
+ nextlevel = [source]
206
+ while nextlevel:
207
+ thislevel = nextlevel
208
+ nextlevel = []
209
+ for v in thislevel:
210
+ for w in adj[v]:
211
+ if w not in seen:
212
+ seen.add(w)
213
+ nextlevel.append(w)
214
+ if len(seen) == n:
215
+ return seen
216
+ return seen
janus/lib/python3.10/site-packages/networkx/algorithms/components/semiconnected.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Semiconnectedness."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for, pairwise
5
+
6
+ __all__ = ["is_semiconnected"]
7
+
8
+
9
+ @not_implemented_for("undirected")
10
+ @nx._dispatchable
11
+ def is_semiconnected(G):
12
+ r"""Returns True if the graph is semiconnected, False otherwise.
13
+
14
+ A graph is semiconnected if and only if for any pair of nodes, either one
15
+ is reachable from the other, or they are mutually reachable.
16
+
17
+ This function uses a theorem that states that a DAG is semiconnected
18
+ if for any topological sort, for node $v_n$ in that sort, there is an
19
+ edge $(v_i, v_{i+1})$. That allows us to check if a non-DAG `G` is
20
+ semiconnected by condensing the graph: i.e. constructing a new graph `H`
21
+ with nodes being the strongly connected components of `G`, and edges
22
+ (scc_1, scc_2) if there is a edge $(v_1, v_2)$ in `G` for some
23
+ $v_1 \in scc_1$ and $v_2 \in scc_2$. That results in a DAG, so we compute
24
+ the topological sort of `H` and check if for every $n$ there is an edge
25
+ $(scc_n, scc_{n+1})$.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+ A directed graph.
31
+
32
+ Returns
33
+ -------
34
+ semiconnected : bool
35
+ True if the graph is semiconnected, False otherwise.
36
+
37
+ Raises
38
+ ------
39
+ NetworkXNotImplemented
40
+ If the input graph is undirected.
41
+
42
+ NetworkXPointlessConcept
43
+ If the graph is empty.
44
+
45
+ Examples
46
+ --------
47
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph())
48
+ >>> print(nx.is_semiconnected(G))
49
+ True
50
+ >>> G = nx.DiGraph([(1, 2), (3, 2)])
51
+ >>> print(nx.is_semiconnected(G))
52
+ False
53
+
54
+ See Also
55
+ --------
56
+ is_strongly_connected
57
+ is_weakly_connected
58
+ is_connected
59
+ is_biconnected
60
+ """
61
+ if len(G) == 0:
62
+ raise nx.NetworkXPointlessConcept(
63
+ "Connectivity is undefined for the null graph."
64
+ )
65
+
66
+ if not nx.is_weakly_connected(G):
67
+ return False
68
+
69
+ H = nx.condensation(G)
70
+
71
+ return all(H.has_edge(u, v) for u, v in pairwise(nx.topological_sort(H)))
janus/lib/python3.10/site-packages/networkx/algorithms/components/strongly_connected.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strongly connected components."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import not_implemented_for
5
+
6
+ __all__ = [
7
+ "number_strongly_connected_components",
8
+ "strongly_connected_components",
9
+ "is_strongly_connected",
10
+ "kosaraju_strongly_connected_components",
11
+ "condensation",
12
+ ]
13
+
14
+
15
+ @not_implemented_for("undirected")
16
+ @nx._dispatchable
17
+ def strongly_connected_components(G):
18
+ """Generate nodes in strongly connected components of graph.
19
+
20
+ Parameters
21
+ ----------
22
+ G : NetworkX Graph
23
+ A directed graph.
24
+
25
+ Returns
26
+ -------
27
+ comp : generator of sets
28
+ A generator of sets of nodes, one for each strongly connected
29
+ component of G.
30
+
31
+ Raises
32
+ ------
33
+ NetworkXNotImplemented
34
+ If G is undirected.
35
+
36
+ Examples
37
+ --------
38
+ Generate a sorted list of strongly connected components, largest first.
39
+
40
+ >>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
41
+ >>> nx.add_cycle(G, [10, 11, 12])
42
+ >>> [
43
+ ... len(c)
44
+ ... for c in sorted(nx.strongly_connected_components(G), key=len, reverse=True)
45
+ ... ]
46
+ [4, 3]
47
+
48
+ If you only want the largest component, it's more efficient to
49
+ use max instead of sort.
50
+
51
+ >>> largest = max(nx.strongly_connected_components(G), key=len)
52
+
53
+ See Also
54
+ --------
55
+ connected_components
56
+ weakly_connected_components
57
+ kosaraju_strongly_connected_components
58
+
59
+ Notes
60
+ -----
61
+ Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_.
62
+ Nonrecursive version of algorithm.
63
+
64
+ References
65
+ ----------
66
+ .. [1] Depth-first search and linear graph algorithms, R. Tarjan
67
+ SIAM Journal of Computing 1(2):146-160, (1972).
68
+
69
+ .. [2] On finding the strongly connected components in a directed graph.
70
+ E. Nuutila and E. Soisalon-Soinen
71
+ Information Processing Letters 49(1): 9-14, (1994)..
72
+
73
+ """
74
+ preorder = {}
75
+ lowlink = {}
76
+ scc_found = set()
77
+ scc_queue = []
78
+ i = 0 # Preorder counter
79
+ neighbors = {v: iter(G[v]) for v in G}
80
+ for source in G:
81
+ if source not in scc_found:
82
+ queue = [source]
83
+ while queue:
84
+ v = queue[-1]
85
+ if v not in preorder:
86
+ i = i + 1
87
+ preorder[v] = i
88
+ done = True
89
+ for w in neighbors[v]:
90
+ if w not in preorder:
91
+ queue.append(w)
92
+ done = False
93
+ break
94
+ if done:
95
+ lowlink[v] = preorder[v]
96
+ for w in G[v]:
97
+ if w not in scc_found:
98
+ if preorder[w] > preorder[v]:
99
+ lowlink[v] = min([lowlink[v], lowlink[w]])
100
+ else:
101
+ lowlink[v] = min([lowlink[v], preorder[w]])
102
+ queue.pop()
103
+ if lowlink[v] == preorder[v]:
104
+ scc = {v}
105
+ while scc_queue and preorder[scc_queue[-1]] > preorder[v]:
106
+ k = scc_queue.pop()
107
+ scc.add(k)
108
+ scc_found.update(scc)
109
+ yield scc
110
+ else:
111
+ scc_queue.append(v)
112
+
113
+
114
+ @not_implemented_for("undirected")
115
+ @nx._dispatchable
116
+ def kosaraju_strongly_connected_components(G, source=None):
117
+ """Generate nodes in strongly connected components of graph.
118
+
119
+ Parameters
120
+ ----------
121
+ G : NetworkX Graph
122
+ A directed graph.
123
+
124
+ Returns
125
+ -------
126
+ comp : generator of sets
127
+ A generator of sets of nodes, one for each strongly connected
128
+ component of G.
129
+
130
+ Raises
131
+ ------
132
+ NetworkXNotImplemented
133
+ If G is undirected.
134
+
135
+ Examples
136
+ --------
137
+ Generate a sorted list of strongly connected components, largest first.
138
+
139
+ >>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
140
+ >>> nx.add_cycle(G, [10, 11, 12])
141
+ >>> [
142
+ ... len(c)
143
+ ... for c in sorted(
144
+ ... nx.kosaraju_strongly_connected_components(G), key=len, reverse=True
145
+ ... )
146
+ ... ]
147
+ [4, 3]
148
+
149
+ If you only want the largest component, it's more efficient to
150
+ use max instead of sort.
151
+
152
+ >>> largest = max(nx.kosaraju_strongly_connected_components(G), key=len)
153
+
154
+ See Also
155
+ --------
156
+ strongly_connected_components
157
+
158
+ Notes
159
+ -----
160
+ Uses Kosaraju's algorithm.
161
+
162
+ """
163
+ post = list(nx.dfs_postorder_nodes(G.reverse(copy=False), source=source))
164
+
165
+ seen = set()
166
+ while post:
167
+ r = post.pop()
168
+ if r in seen:
169
+ continue
170
+ c = nx.dfs_preorder_nodes(G, r)
171
+ new = {v for v in c if v not in seen}
172
+ seen.update(new)
173
+ yield new
174
+
175
+
176
+ @not_implemented_for("undirected")
177
+ @nx._dispatchable
178
+ def number_strongly_connected_components(G):
179
+ """Returns number of strongly connected components in graph.
180
+
181
+ Parameters
182
+ ----------
183
+ G : NetworkX graph
184
+ A directed graph.
185
+
186
+ Returns
187
+ -------
188
+ n : integer
189
+ Number of strongly connected components
190
+
191
+ Raises
192
+ ------
193
+ NetworkXNotImplemented
194
+ If G is undirected.
195
+
196
+ Examples
197
+ --------
198
+ >>> G = nx.DiGraph(
199
+ ... [(0, 1), (1, 2), (2, 0), (2, 3), (4, 5), (3, 4), (5, 6), (6, 3), (6, 7)]
200
+ ... )
201
+ >>> nx.number_strongly_connected_components(G)
202
+ 3
203
+
204
+ See Also
205
+ --------
206
+ strongly_connected_components
207
+ number_connected_components
208
+ number_weakly_connected_components
209
+
210
+ Notes
211
+ -----
212
+ For directed graphs only.
213
+ """
214
+ return sum(1 for scc in strongly_connected_components(G))
215
+
216
+
217
+ @not_implemented_for("undirected")
218
+ @nx._dispatchable
219
+ def is_strongly_connected(G):
220
+ """Test directed graph for strong connectivity.
221
+
222
+ A directed graph is strongly connected if and only if every vertex in
223
+ the graph is reachable from every other vertex.
224
+
225
+ Parameters
226
+ ----------
227
+ G : NetworkX Graph
228
+ A directed graph.
229
+
230
+ Returns
231
+ -------
232
+ connected : bool
233
+ True if the graph is strongly connected, False otherwise.
234
+
235
+ Examples
236
+ --------
237
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 2)])
238
+ >>> nx.is_strongly_connected(G)
239
+ True
240
+ >>> G.remove_edge(2, 3)
241
+ >>> nx.is_strongly_connected(G)
242
+ False
243
+
244
+ Raises
245
+ ------
246
+ NetworkXNotImplemented
247
+ If G is undirected.
248
+
249
+ See Also
250
+ --------
251
+ is_weakly_connected
252
+ is_semiconnected
253
+ is_connected
254
+ is_biconnected
255
+ strongly_connected_components
256
+
257
+ Notes
258
+ -----
259
+ For directed graphs only.
260
+ """
261
+ if len(G) == 0:
262
+ raise nx.NetworkXPointlessConcept(
263
+ """Connectivity is undefined for the null graph."""
264
+ )
265
+
266
+ return len(next(strongly_connected_components(G))) == len(G)
267
+
268
+
269
+ @not_implemented_for("undirected")
270
+ @nx._dispatchable(returns_graph=True)
271
+ def condensation(G, scc=None):
272
+ """Returns the condensation of G.
273
+
274
+ The condensation of G is the graph with each of the strongly connected
275
+ components contracted into a single node.
276
+
277
+ Parameters
278
+ ----------
279
+ G : NetworkX DiGraph
280
+ A directed graph.
281
+
282
+ scc: list or generator (optional, default=None)
283
+ Strongly connected components. If provided, the elements in
284
+ `scc` must partition the nodes in `G`. If not provided, it will be
285
+ calculated as scc=nx.strongly_connected_components(G).
286
+
287
+ Returns
288
+ -------
289
+ C : NetworkX DiGraph
290
+ The condensation graph C of G. The node labels are integers
291
+ corresponding to the index of the component in the list of
292
+ strongly connected components of G. C has a graph attribute named
293
+ 'mapping' with a dictionary mapping the original nodes to the
294
+ nodes in C to which they belong. Each node in C also has a node
295
+ attribute 'members' with the set of original nodes in G that
296
+ form the SCC that the node in C represents.
297
+
298
+ Raises
299
+ ------
300
+ NetworkXNotImplemented
301
+ If G is undirected.
302
+
303
+ Examples
304
+ --------
305
+ Contracting two sets of strongly connected nodes into two distinct SCC
306
+ using the barbell graph.
307
+
308
+ >>> G = nx.barbell_graph(4, 0)
309
+ >>> G.remove_edge(3, 4)
310
+ >>> G = nx.DiGraph(G)
311
+ >>> H = nx.condensation(G)
312
+ >>> H.nodes.data()
313
+ NodeDataView({0: {'members': {0, 1, 2, 3}}, 1: {'members': {4, 5, 6, 7}}})
314
+ >>> H.graph["mapping"]
315
+ {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1}
316
+
317
+ Contracting a complete graph into one single SCC.
318
+
319
+ >>> G = nx.complete_graph(7, create_using=nx.DiGraph)
320
+ >>> H = nx.condensation(G)
321
+ >>> H.nodes
322
+ NodeView((0,))
323
+ >>> H.nodes.data()
324
+ NodeDataView({0: {'members': {0, 1, 2, 3, 4, 5, 6}}})
325
+
326
+ Notes
327
+ -----
328
+ After contracting all strongly connected components to a single node,
329
+ the resulting graph is a directed acyclic graph.
330
+
331
+ """
332
+ if scc is None:
333
+ scc = nx.strongly_connected_components(G)
334
+ mapping = {}
335
+ members = {}
336
+ C = nx.DiGraph()
337
+ # Add mapping dict as graph attribute
338
+ C.graph["mapping"] = mapping
339
+ if len(G) == 0:
340
+ return C
341
+ for i, component in enumerate(scc):
342
+ members[i] = component
343
+ mapping.update((n, i) for n in component)
344
+ number_of_components = i + 1
345
+ C.add_nodes_from(range(number_of_components))
346
+ C.add_edges_from(
347
+ (mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
348
+ )
349
+ # Add a list of members (ie original nodes) to each node (ie scc) in C.
350
+ nx.set_node_attributes(C, members, "members")
351
+ return C
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc ADDED
Binary file (2.74 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_semiconnected.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+ from networkx import convert_node_labels_to_integers as cnlti
6
+ from networkx.classes.tests import dispatch_interface
7
+
8
+
9
+ class TestConnected:
10
+ @classmethod
11
+ def setup_class(cls):
12
+ G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
13
+ G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
14
+ G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
15
+ cls.G = nx.union(G1, G2)
16
+ cls.G = nx.union(cls.G, G3)
17
+ cls.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
18
+ cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)
19
+
20
+ cls.gc = []
21
+ G = nx.DiGraph()
22
+ G.add_edges_from(
23
+ [
24
+ (1, 2),
25
+ (2, 3),
26
+ (2, 8),
27
+ (3, 4),
28
+ (3, 7),
29
+ (4, 5),
30
+ (5, 3),
31
+ (5, 6),
32
+ (7, 4),
33
+ (7, 6),
34
+ (8, 1),
35
+ (8, 7),
36
+ ]
37
+ )
38
+ C = [[3, 4, 5, 7], [1, 2, 8], [6]]
39
+ cls.gc.append((G, C))
40
+
41
+ G = nx.DiGraph()
42
+ G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
43
+ C = [[2, 3, 4], [1]]
44
+ cls.gc.append((G, C))
45
+
46
+ G = nx.DiGraph()
47
+ G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
48
+ C = [[1, 2, 3]]
49
+ cls.gc.append((G, C))
50
+
51
+ # Eppstein's tests
52
+ G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
53
+ C = [[0], [1], [2], [3], [4], [5], [6]]
54
+ cls.gc.append((G, C))
55
+
56
+ G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
57
+ C = [[0, 1, 2], [3, 4]]
58
+ cls.gc.append((G, C))
59
+
60
+ G = nx.DiGraph()
61
+ C = []
62
+ cls.gc.append((G, C))
63
+
64
+ def test_connected_components(self):
65
+ # Test duplicated below
66
+ cc = nx.connected_components
67
+ G = self.G
68
+ C = {
69
+ frozenset([0, 1, 2, 3]),
70
+ frozenset([4, 5, 6, 7, 8, 9]),
71
+ frozenset([10, 11, 12, 13, 14]),
72
+ }
73
+ assert {frozenset(g) for g in cc(G)} == C
74
+
75
+ def test_connected_components_nx_loopback(self):
76
+ # This tests the @nx._dispatchable mechanism, treating nx.connected_components
77
+ # as if it were a re-implementation from another package.
78
+ # Test duplicated from above
79
+ cc = nx.connected_components
80
+ G = dispatch_interface.convert(self.G)
81
+ C = {
82
+ frozenset([0, 1, 2, 3]),
83
+ frozenset([4, 5, 6, 7, 8, 9]),
84
+ frozenset([10, 11, 12, 13, 14]),
85
+ }
86
+ if "nx_loopback" in nx.config.backends or not nx.config.backends:
87
+ # If `nx.config.backends` is empty, then `_dispatchable.__call__` takes a
88
+ # "fast path" and does not check graph inputs, so using an unknown backend
89
+ # here will still work.
90
+ assert {frozenset(g) for g in cc(G)} == C
91
+ else:
92
+ # This raises, because "nx_loopback" is not registered as a backend.
93
+ with pytest.raises(
94
+ ImportError, match="'nx_loopback' backend is not installed"
95
+ ):
96
+ cc(G)
97
+
98
+ def test_number_connected_components(self):
99
+ ncc = nx.number_connected_components
100
+ assert ncc(self.G) == 3
101
+
102
+ def test_number_connected_components2(self):
103
+ ncc = nx.number_connected_components
104
+ assert ncc(self.grid) == 1
105
+
106
+ def test_connected_components2(self):
107
+ cc = nx.connected_components
108
+ G = self.grid
109
+ C = {frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])}
110
+ assert {frozenset(g) for g in cc(G)} == C
111
+
112
+ def test_node_connected_components(self):
113
+ ncc = nx.node_connected_component
114
+ G = self.grid
115
+ C = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
116
+ assert ncc(G, 1) == C
117
+
118
+ def test_is_connected(self):
119
+ assert nx.is_connected(self.grid)
120
+ G = nx.Graph()
121
+ G.add_nodes_from([1, 2])
122
+ assert not nx.is_connected(G)
123
+
124
+ def test_connected_raise(self):
125
+ with pytest.raises(NetworkXNotImplemented):
126
+ next(nx.connected_components(self.DG))
127
+ pytest.raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
128
+ pytest.raises(NetworkXNotImplemented, nx.node_connected_component, self.DG, 1)
129
+ pytest.raises(NetworkXNotImplemented, nx.is_connected, self.DG)
130
+ pytest.raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
131
+
132
+ def test_connected_mutability(self):
133
+ G = self.grid
134
+ seen = set()
135
+ for component in nx.connected_components(G):
136
+ assert len(seen & component) == 0
137
+ seen.update(component)
138
+ component.clear()
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_strongly_connected.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ class TestStronglyConnected:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ cls.gc = []
11
+ G = nx.DiGraph()
12
+ G.add_edges_from(
13
+ [
14
+ (1, 2),
15
+ (2, 3),
16
+ (2, 8),
17
+ (3, 4),
18
+ (3, 7),
19
+ (4, 5),
20
+ (5, 3),
21
+ (5, 6),
22
+ (7, 4),
23
+ (7, 6),
24
+ (8, 1),
25
+ (8, 7),
26
+ ]
27
+ )
28
+ C = {frozenset([3, 4, 5, 7]), frozenset([1, 2, 8]), frozenset([6])}
29
+ cls.gc.append((G, C))
30
+
31
+ G = nx.DiGraph()
32
+ G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
33
+ C = {frozenset([2, 3, 4]), frozenset([1])}
34
+ cls.gc.append((G, C))
35
+
36
+ G = nx.DiGraph()
37
+ G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
38
+ C = {frozenset([1, 2, 3])}
39
+ cls.gc.append((G, C))
40
+
41
+ # Eppstein's tests
42
+ G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
43
+ C = {
44
+ frozenset([0]),
45
+ frozenset([1]),
46
+ frozenset([2]),
47
+ frozenset([3]),
48
+ frozenset([4]),
49
+ frozenset([5]),
50
+ frozenset([6]),
51
+ }
52
+ cls.gc.append((G, C))
53
+
54
+ G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
55
+ C = {frozenset([0, 1, 2]), frozenset([3, 4])}
56
+ cls.gc.append((G, C))
57
+
58
+ def test_tarjan(self):
59
+ scc = nx.strongly_connected_components
60
+ for G, C in self.gc:
61
+ assert {frozenset(g) for g in scc(G)} == C
62
+
63
+ def test_kosaraju(self):
64
+ scc = nx.kosaraju_strongly_connected_components
65
+ for G, C in self.gc:
66
+ assert {frozenset(g) for g in scc(G)} == C
67
+
68
+ def test_number_strongly_connected_components(self):
69
+ ncc = nx.number_strongly_connected_components
70
+ for G, C in self.gc:
71
+ assert ncc(G) == len(C)
72
+
73
+ def test_is_strongly_connected(self):
74
+ for G, C in self.gc:
75
+ if len(C) == 1:
76
+ assert nx.is_strongly_connected(G)
77
+ else:
78
+ assert not nx.is_strongly_connected(G)
79
+
80
+ def test_contract_scc1(self):
81
+ G = nx.DiGraph()
82
+ G.add_edges_from(
83
+ [
84
+ (1, 2),
85
+ (2, 3),
86
+ (2, 11),
87
+ (2, 12),
88
+ (3, 4),
89
+ (4, 3),
90
+ (4, 5),
91
+ (5, 6),
92
+ (6, 5),
93
+ (6, 7),
94
+ (7, 8),
95
+ (7, 9),
96
+ (7, 10),
97
+ (8, 9),
98
+ (9, 7),
99
+ (10, 6),
100
+ (11, 2),
101
+ (11, 4),
102
+ (11, 6),
103
+ (12, 6),
104
+ (12, 11),
105
+ ]
106
+ )
107
+ scc = list(nx.strongly_connected_components(G))
108
+ cG = nx.condensation(G, scc)
109
+ # DAG
110
+ assert nx.is_directed_acyclic_graph(cG)
111
+ # nodes
112
+ assert sorted(cG.nodes()) == [0, 1, 2, 3]
113
+ # edges
114
+ mapping = {}
115
+ for i, component in enumerate(scc):
116
+ for n in component:
117
+ mapping[n] = i
118
+ edge = (mapping[2], mapping[3])
119
+ assert cG.has_edge(*edge)
120
+ edge = (mapping[2], mapping[5])
121
+ assert cG.has_edge(*edge)
122
+ edge = (mapping[3], mapping[5])
123
+ assert cG.has_edge(*edge)
124
+
125
+ def test_contract_scc_isolate(self):
126
+ # Bug found and fixed in [1687].
127
+ G = nx.DiGraph()
128
+ G.add_edge(1, 2)
129
+ G.add_edge(2, 1)
130
+ scc = list(nx.strongly_connected_components(G))
131
+ cG = nx.condensation(G, scc)
132
+ assert list(cG.nodes()) == [0]
133
+ assert list(cG.edges()) == []
134
+
135
+ def test_contract_scc_edge(self):
136
+ G = nx.DiGraph()
137
+ G.add_edge(1, 2)
138
+ G.add_edge(2, 1)
139
+ G.add_edge(2, 3)
140
+ G.add_edge(3, 4)
141
+ G.add_edge(4, 3)
142
+ scc = list(nx.strongly_connected_components(G))
143
+ cG = nx.condensation(G, scc)
144
+ assert sorted(cG.nodes()) == [0, 1]
145
+ if 1 in scc[0]:
146
+ edge = (0, 1)
147
+ else:
148
+ edge = (1, 0)
149
+ assert list(cG.edges()) == [edge]
150
+
151
+ def test_condensation_mapping_and_members(self):
152
+ G, C = self.gc[1]
153
+ C = sorted(C, key=len, reverse=True)
154
+ cG = nx.condensation(G)
155
+ mapping = cG.graph["mapping"]
156
+ assert all(n in G for n in mapping)
157
+ assert all(0 == cN for n, cN in mapping.items() if n in C[0])
158
+ assert all(1 == cN for n, cN in mapping.items() if n in C[1])
159
+ for n, d in cG.nodes(data=True):
160
+ assert set(C[n]) == cG.nodes[n]["members"]
161
+
162
+ def test_null_graph(self):
163
+ G = nx.DiGraph()
164
+ assert list(nx.strongly_connected_components(G)) == []
165
+ assert list(nx.kosaraju_strongly_connected_components(G)) == []
166
+ assert len(nx.condensation(G)) == 0
167
+ pytest.raises(
168
+ nx.NetworkXPointlessConcept, nx.is_strongly_connected, nx.DiGraph()
169
+ )
170
+
171
+ def test_connected_raise(self):
172
+ G = nx.Graph()
173
+ with pytest.raises(NetworkXNotImplemented):
174
+ next(nx.strongly_connected_components(G))
175
+ with pytest.raises(NetworkXNotImplemented):
176
+ next(nx.kosaraju_strongly_connected_components(G))
177
+ pytest.raises(NetworkXNotImplemented, nx.is_strongly_connected, G)
178
+ pytest.raises(NetworkXNotImplemented, nx.condensation, G)
179
+
180
+ strong_cc_methods = (
181
+ nx.strongly_connected_components,
182
+ nx.kosaraju_strongly_connected_components,
183
+ )
184
+
185
+ @pytest.mark.parametrize("get_components", strong_cc_methods)
186
+ def test_connected_mutability(self, get_components):
187
+ DG = nx.path_graph(5, create_using=nx.DiGraph)
188
+ G = nx.disjoint_union(DG, DG)
189
+ seen = set()
190
+ for component in get_components(G):
191
+ assert len(seen & component) == 0
192
+ seen.update(component)
193
+ component.clear()
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ class TestWeaklyConnected:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ cls.gc = []
11
+ G = nx.DiGraph()
12
+ G.add_edges_from(
13
+ [
14
+ (1, 2),
15
+ (2, 3),
16
+ (2, 8),
17
+ (3, 4),
18
+ (3, 7),
19
+ (4, 5),
20
+ (5, 3),
21
+ (5, 6),
22
+ (7, 4),
23
+ (7, 6),
24
+ (8, 1),
25
+ (8, 7),
26
+ ]
27
+ )
28
+ C = [[3, 4, 5, 7], [1, 2, 8], [6]]
29
+ cls.gc.append((G, C))
30
+
31
+ G = nx.DiGraph()
32
+ G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
33
+ C = [[2, 3, 4], [1]]
34
+ cls.gc.append((G, C))
35
+
36
+ G = nx.DiGraph()
37
+ G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
38
+ C = [[1, 2, 3]]
39
+ cls.gc.append((G, C))
40
+
41
+ # Eppstein's tests
42
+ G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
43
+ C = [[0], [1], [2], [3], [4], [5], [6]]
44
+ cls.gc.append((G, C))
45
+
46
+ G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
47
+ C = [[0, 1, 2], [3, 4]]
48
+ cls.gc.append((G, C))
49
+
50
+ def test_weakly_connected_components(self):
51
+ for G, C in self.gc:
52
+ U = G.to_undirected()
53
+ w = {frozenset(g) for g in nx.weakly_connected_components(G)}
54
+ c = {frozenset(g) for g in nx.connected_components(U)}
55
+ assert w == c
56
+
57
+ def test_number_weakly_connected_components(self):
58
+ for G, C in self.gc:
59
+ U = G.to_undirected()
60
+ w = nx.number_weakly_connected_components(G)
61
+ c = nx.number_connected_components(U)
62
+ assert w == c
63
+
64
+ def test_is_weakly_connected(self):
65
+ for G, C in self.gc:
66
+ U = G.to_undirected()
67
+ assert nx.is_weakly_connected(G) == nx.is_connected(U)
68
+
69
+ def test_null_graph(self):
70
+ G = nx.DiGraph()
71
+ assert list(nx.weakly_connected_components(G)) == []
72
+ assert nx.number_weakly_connected_components(G) == 0
73
+ with pytest.raises(nx.NetworkXPointlessConcept):
74
+ next(nx.is_weakly_connected(G))
75
+
76
+ def test_connected_raise(self):
77
+ G = nx.Graph()
78
+ with pytest.raises(NetworkXNotImplemented):
79
+ next(nx.weakly_connected_components(G))
80
+ pytest.raises(NetworkXNotImplemented, nx.number_weakly_connected_components, G)
81
+ pytest.raises(NetworkXNotImplemented, nx.is_weakly_connected, G)
82
+
83
+ def test_connected_mutability(self):
84
+ DG = nx.path_graph(5, create_using=nx.DiGraph)
85
+ G = nx.disjoint_union(DG, DG)
86
+ seen = set()
87
+ for component in nx.weakly_connected_components(G):
88
+ assert len(seen & component) == 0
89
+ seen.update(component)
90
+ component.clear()
91
+
92
+
93
+ def test_is_weakly_connected_empty_graph_raises():
94
+ G = nx.DiGraph()
95
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
96
+ nx.is_weakly_connected(G)
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b17e66cdeda8edb8d1dec72626c77f1f65dd4675e3f76dc2fc4fd84aa038e30
3
+ size 18972
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ccacba1e0fbfb30bec361f0e48ec88c999d3474fcda5ddf93bd444ace17cfa0e
3
+ size 88132
janus/lib/python3.10/site-packages/networkx/algorithms/operators/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from networkx.algorithms.operators.all import *
2
+ from networkx.algorithms.operators.binary import *
3
+ from networkx.algorithms.operators.product import *
4
+ from networkx.algorithms.operators.unary import *
janus/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (374 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/operators/product.py ADDED
@@ -0,0 +1,633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Graph products.
3
+ """
4
+
5
+ from itertools import product
6
+
7
+ import networkx as nx
8
+ from networkx.utils import not_implemented_for
9
+
10
+ __all__ = [
11
+ "tensor_product",
12
+ "cartesian_product",
13
+ "lexicographic_product",
14
+ "strong_product",
15
+ "power",
16
+ "rooted_product",
17
+ "corona_product",
18
+ "modular_product",
19
+ ]
20
+ _G_H = {"G": 0, "H": 1}
21
+
22
+
23
+ def _dict_product(d1, d2):
24
+ return {k: (d1.get(k), d2.get(k)) for k in set(d1) | set(d2)}
25
+
26
+
27
+ # Generators for producing graph products
28
+ def _node_product(G, H):
29
+ for u, v in product(G, H):
30
+ yield ((u, v), _dict_product(G.nodes[u], H.nodes[v]))
31
+
32
+
33
+ def _directed_edges_cross_edges(G, H):
34
+ if not G.is_multigraph() and not H.is_multigraph():
35
+ for u, v, c in G.edges(data=True):
36
+ for x, y, d in H.edges(data=True):
37
+ yield (u, x), (v, y), _dict_product(c, d)
38
+ if not G.is_multigraph() and H.is_multigraph():
39
+ for u, v, c in G.edges(data=True):
40
+ for x, y, k, d in H.edges(data=True, keys=True):
41
+ yield (u, x), (v, y), k, _dict_product(c, d)
42
+ if G.is_multigraph() and not H.is_multigraph():
43
+ for u, v, k, c in G.edges(data=True, keys=True):
44
+ for x, y, d in H.edges(data=True):
45
+ yield (u, x), (v, y), k, _dict_product(c, d)
46
+ if G.is_multigraph() and H.is_multigraph():
47
+ for u, v, j, c in G.edges(data=True, keys=True):
48
+ for x, y, k, d in H.edges(data=True, keys=True):
49
+ yield (u, x), (v, y), (j, k), _dict_product(c, d)
50
+
51
+
52
+ def _undirected_edges_cross_edges(G, H):
53
+ if not G.is_multigraph() and not H.is_multigraph():
54
+ for u, v, c in G.edges(data=True):
55
+ for x, y, d in H.edges(data=True):
56
+ yield (v, x), (u, y), _dict_product(c, d)
57
+ if not G.is_multigraph() and H.is_multigraph():
58
+ for u, v, c in G.edges(data=True):
59
+ for x, y, k, d in H.edges(data=True, keys=True):
60
+ yield (v, x), (u, y), k, _dict_product(c, d)
61
+ if G.is_multigraph() and not H.is_multigraph():
62
+ for u, v, k, c in G.edges(data=True, keys=True):
63
+ for x, y, d in H.edges(data=True):
64
+ yield (v, x), (u, y), k, _dict_product(c, d)
65
+ if G.is_multigraph() and H.is_multigraph():
66
+ for u, v, j, c in G.edges(data=True, keys=True):
67
+ for x, y, k, d in H.edges(data=True, keys=True):
68
+ yield (v, x), (u, y), (j, k), _dict_product(c, d)
69
+
70
+
71
+ def _edges_cross_nodes(G, H):
72
+ if G.is_multigraph():
73
+ for u, v, k, d in G.edges(data=True, keys=True):
74
+ for x in H:
75
+ yield (u, x), (v, x), k, d
76
+ else:
77
+ for u, v, d in G.edges(data=True):
78
+ for x in H:
79
+ if H.is_multigraph():
80
+ yield (u, x), (v, x), None, d
81
+ else:
82
+ yield (u, x), (v, x), d
83
+
84
+
85
+ def _nodes_cross_edges(G, H):
86
+ if H.is_multigraph():
87
+ for x in G:
88
+ for u, v, k, d in H.edges(data=True, keys=True):
89
+ yield (x, u), (x, v), k, d
90
+ else:
91
+ for x in G:
92
+ for u, v, d in H.edges(data=True):
93
+ if G.is_multigraph():
94
+ yield (x, u), (x, v), None, d
95
+ else:
96
+ yield (x, u), (x, v), d
97
+
98
+
99
+ def _edges_cross_nodes_and_nodes(G, H):
100
+ if G.is_multigraph():
101
+ for u, v, k, d in G.edges(data=True, keys=True):
102
+ for x in H:
103
+ for y in H:
104
+ yield (u, x), (v, y), k, d
105
+ else:
106
+ for u, v, d in G.edges(data=True):
107
+ for x in H:
108
+ for y in H:
109
+ if H.is_multigraph():
110
+ yield (u, x), (v, y), None, d
111
+ else:
112
+ yield (u, x), (v, y), d
113
+
114
+
115
+ def _init_product_graph(G, H):
116
+ if G.is_directed() != H.is_directed():
117
+ msg = "G and H must be both directed or both undirected"
118
+ raise nx.NetworkXError(msg)
119
+ if G.is_multigraph() or H.is_multigraph():
120
+ GH = nx.MultiGraph()
121
+ else:
122
+ GH = nx.Graph()
123
+ if G.is_directed():
124
+ GH = GH.to_directed()
125
+ return GH
126
+
127
+
128
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
129
+ def tensor_product(G, H):
130
+ r"""Returns the tensor product of G and H.
131
+
132
+ The tensor product $P$ of the graphs $G$ and $H$ has a node set that
133
+ is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
134
+ $P$ has an edge $((u,v), (x,y))$ if and only if $(u,x)$ is an edge in $G$
135
+ and $(v,y)$ is an edge in $H$.
136
+
137
+ Tensor product is sometimes also referred to as the categorical product,
138
+ direct product, cardinal product or conjunction.
139
+
140
+
141
+ Parameters
142
+ ----------
143
+ G, H: graphs
144
+ Networkx graphs.
145
+
146
+ Returns
147
+ -------
148
+ P: NetworkX graph
149
+ The tensor product of G and H. P will be a multi-graph if either G
150
+ or H is a multi-graph, will be a directed if G and H are directed,
151
+ and undirected if G and H are undirected.
152
+
153
+ Raises
154
+ ------
155
+ NetworkXError
156
+ If G and H are not both directed or both undirected.
157
+
158
+ Notes
159
+ -----
160
+ Node attributes in P are two-tuple of the G and H node attributes.
161
+ Missing attributes are assigned None.
162
+
163
+ Examples
164
+ --------
165
+ >>> G = nx.Graph()
166
+ >>> H = nx.Graph()
167
+ >>> G.add_node(0, a1=True)
168
+ >>> H.add_node("a", a2="Spam")
169
+ >>> P = nx.tensor_product(G, H)
170
+ >>> list(P)
171
+ [(0, 'a')]
172
+
173
+ Edge attributes and edge keys (for multigraphs) are also copied to the
174
+ new product graph
175
+ """
176
+ GH = _init_product_graph(G, H)
177
+ GH.add_nodes_from(_node_product(G, H))
178
+ GH.add_edges_from(_directed_edges_cross_edges(G, H))
179
+ if not GH.is_directed():
180
+ GH.add_edges_from(_undirected_edges_cross_edges(G, H))
181
+ return GH
182
+
183
+
184
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
185
+ def cartesian_product(G, H):
186
+ r"""Returns the Cartesian product of G and H.
187
+
188
+ The Cartesian product $P$ of the graphs $G$ and $H$ has a node set that
189
+ is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
190
+ $P$ has an edge $((u,v),(x,y))$ if and only if either $u$ is equal to $x$
191
+ and both $v$ and $y$ are adjacent in $H$ or if $v$ is equal to $y$ and
192
+ both $u$ and $x$ are adjacent in $G$.
193
+
194
+ Parameters
195
+ ----------
196
+ G, H: graphs
197
+ Networkx graphs.
198
+
199
+ Returns
200
+ -------
201
+ P: NetworkX graph
202
+ The Cartesian product of G and H. P will be a multi-graph if either G
203
+ or H is a multi-graph. Will be a directed if G and H are directed,
204
+ and undirected if G and H are undirected.
205
+
206
+ Raises
207
+ ------
208
+ NetworkXError
209
+ If G and H are not both directed or both undirected.
210
+
211
+ Notes
212
+ -----
213
+ Node attributes in P are two-tuple of the G and H node attributes.
214
+ Missing attributes are assigned None.
215
+
216
+ Examples
217
+ --------
218
+ >>> G = nx.Graph()
219
+ >>> H = nx.Graph()
220
+ >>> G.add_node(0, a1=True)
221
+ >>> H.add_node("a", a2="Spam")
222
+ >>> P = nx.cartesian_product(G, H)
223
+ >>> list(P)
224
+ [(0, 'a')]
225
+
226
+ Edge attributes and edge keys (for multigraphs) are also copied to the
227
+ new product graph
228
+ """
229
+ GH = _init_product_graph(G, H)
230
+ GH.add_nodes_from(_node_product(G, H))
231
+ GH.add_edges_from(_edges_cross_nodes(G, H))
232
+ GH.add_edges_from(_nodes_cross_edges(G, H))
233
+ return GH
234
+
235
+
236
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
237
+ def lexicographic_product(G, H):
238
+ r"""Returns the lexicographic product of G and H.
239
+
240
+ The lexicographical product $P$ of the graphs $G$ and $H$ has a node set
241
+ that is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
242
+ $P$ has an edge $((u,v), (x,y))$ if and only if $(u,v)$ is an edge in $G$
243
+ or $u==v$ and $(x,y)$ is an edge in $H$.
244
+
245
+ Parameters
246
+ ----------
247
+ G, H: graphs
248
+ Networkx graphs.
249
+
250
+ Returns
251
+ -------
252
+ P: NetworkX graph
253
+ The Cartesian product of G and H. P will be a multi-graph if either G
254
+ or H is a multi-graph. Will be a directed if G and H are directed,
255
+ and undirected if G and H are undirected.
256
+
257
+ Raises
258
+ ------
259
+ NetworkXError
260
+ If G and H are not both directed or both undirected.
261
+
262
+ Notes
263
+ -----
264
+ Node attributes in P are two-tuple of the G and H node attributes.
265
+ Missing attributes are assigned None.
266
+
267
+ Examples
268
+ --------
269
+ >>> G = nx.Graph()
270
+ >>> H = nx.Graph()
271
+ >>> G.add_node(0, a1=True)
272
+ >>> H.add_node("a", a2="Spam")
273
+ >>> P = nx.lexicographic_product(G, H)
274
+ >>> list(P)
275
+ [(0, 'a')]
276
+
277
+ Edge attributes and edge keys (for multigraphs) are also copied to the
278
+ new product graph
279
+ """
280
+ GH = _init_product_graph(G, H)
281
+ GH.add_nodes_from(_node_product(G, H))
282
+ # Edges in G regardless of H designation
283
+ GH.add_edges_from(_edges_cross_nodes_and_nodes(G, H))
284
+ # For each x in G, only if there is an edge in H
285
+ GH.add_edges_from(_nodes_cross_edges(G, H))
286
+ return GH
287
+
288
+
289
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
290
+ def strong_product(G, H):
291
+ r"""Returns the strong product of G and H.
292
+
293
+ The strong product $P$ of the graphs $G$ and $H$ has a node set that
294
+ is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
295
+ $P$ has an edge $((u,x), (v,y))$ if any of the following conditions
296
+ are met:
297
+
298
+ - $u=v$ and $(x,y)$ is an edge in $H$
299
+ - $x=y$ and $(u,v)$ is an edge in $G$
300
+ - $(u,v)$ is an edge in $G$ and $(x,y)$ is an edge in $H$
301
+
302
+ Parameters
303
+ ----------
304
+ G, H: graphs
305
+ Networkx graphs.
306
+
307
+ Returns
308
+ -------
309
+ P: NetworkX graph
310
+ The Cartesian product of G and H. P will be a multi-graph if either G
311
+ or H is a multi-graph. Will be a directed if G and H are directed,
312
+ and undirected if G and H are undirected.
313
+
314
+ Raises
315
+ ------
316
+ NetworkXError
317
+ If G and H are not both directed or both undirected.
318
+
319
+ Notes
320
+ -----
321
+ Node attributes in P are two-tuple of the G and H node attributes.
322
+ Missing attributes are assigned None.
323
+
324
+ Examples
325
+ --------
326
+ >>> G = nx.Graph()
327
+ >>> H = nx.Graph()
328
+ >>> G.add_node(0, a1=True)
329
+ >>> H.add_node("a", a2="Spam")
330
+ >>> P = nx.strong_product(G, H)
331
+ >>> list(P)
332
+ [(0, 'a')]
333
+
334
+ Edge attributes and edge keys (for multigraphs) are also copied to the
335
+ new product graph
336
+ """
337
+ GH = _init_product_graph(G, H)
338
+ GH.add_nodes_from(_node_product(G, H))
339
+ GH.add_edges_from(_nodes_cross_edges(G, H))
340
+ GH.add_edges_from(_edges_cross_nodes(G, H))
341
+ GH.add_edges_from(_directed_edges_cross_edges(G, H))
342
+ if not GH.is_directed():
343
+ GH.add_edges_from(_undirected_edges_cross_edges(G, H))
344
+ return GH
345
+
346
+
347
+ @not_implemented_for("directed")
348
+ @not_implemented_for("multigraph")
349
+ @nx._dispatchable(returns_graph=True)
350
+ def power(G, k):
351
+ """Returns the specified power of a graph.
352
+
353
+ The $k$th power of a simple graph $G$, denoted $G^k$, is a
354
+ graph on the same set of nodes in which two distinct nodes $u$ and
355
+ $v$ are adjacent in $G^k$ if and only if the shortest path
356
+ distance between $u$ and $v$ in $G$ is at most $k$.
357
+
358
+ Parameters
359
+ ----------
360
+ G : graph
361
+ A NetworkX simple graph object.
362
+
363
+ k : positive integer
364
+ The power to which to raise the graph `G`.
365
+
366
+ Returns
367
+ -------
368
+ NetworkX simple graph
369
+ `G` to the power `k`.
370
+
371
+ Raises
372
+ ------
373
+ ValueError
374
+ If the exponent `k` is not positive.
375
+
376
+ NetworkXNotImplemented
377
+ If `G` is not a simple graph.
378
+
379
+ Examples
380
+ --------
381
+ The number of edges will never decrease when taking successive
382
+ powers:
383
+
384
+ >>> G = nx.path_graph(4)
385
+ >>> list(nx.power(G, 2).edges)
386
+ [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
387
+ >>> list(nx.power(G, 3).edges)
388
+ [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
389
+
390
+ The `k` th power of a cycle graph on *n* nodes is the complete graph
391
+ on *n* nodes, if `k` is at least ``n // 2``:
392
+
393
+ >>> G = nx.cycle_graph(5)
394
+ >>> H = nx.complete_graph(5)
395
+ >>> nx.is_isomorphic(nx.power(G, 2), H)
396
+ True
397
+ >>> G = nx.cycle_graph(8)
398
+ >>> H = nx.complete_graph(8)
399
+ >>> nx.is_isomorphic(nx.power(G, 4), H)
400
+ True
401
+
402
+ References
403
+ ----------
404
+ .. [1] J. A. Bondy, U. S. R. Murty, *Graph Theory*. Springer, 2008.
405
+
406
+ Notes
407
+ -----
408
+ This definition of "power graph" comes from Exercise 3.1.6 of
409
+ *Graph Theory* by Bondy and Murty [1]_.
410
+
411
+ """
412
+ if k <= 0:
413
+ raise ValueError("k must be a positive integer")
414
+ H = nx.Graph()
415
+ H.add_nodes_from(G)
416
+ # update BFS code to ignore self loops.
417
+ for n in G:
418
+ seen = {} # level (number of hops) when seen in BFS
419
+ level = 1 # the current level
420
+ nextlevel = G[n]
421
+ while nextlevel:
422
+ thislevel = nextlevel # advance to next level
423
+ nextlevel = {} # and start a new list (fringe)
424
+ for v in thislevel:
425
+ if v == n: # avoid self loop
426
+ continue
427
+ if v not in seen:
428
+ seen[v] = level # set the level of vertex v
429
+ nextlevel.update(G[v]) # add neighbors of v
430
+ if k <= level:
431
+ break
432
+ level += 1
433
+ H.add_edges_from((n, nbr) for nbr in seen)
434
+ return H
435
+
436
+
437
+ @not_implemented_for("multigraph")
438
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
439
+ def rooted_product(G, H, root):
440
+ """Return the rooted product of graphs G and H rooted at root in H.
441
+
442
+ A new graph is constructed representing the rooted product of
443
+ the inputted graphs, G and H, with a root in H.
444
+ A rooted product duplicates H for each nodes in G with the root
445
+ of H corresponding to the node in G. Nodes are renamed as the direct
446
+ product of G and H. The result is a subgraph of the cartesian product.
447
+
448
+ Parameters
449
+ ----------
450
+ G,H : graph
451
+ A NetworkX graph
452
+ root : node
453
+ A node in H
454
+
455
+ Returns
456
+ -------
457
+ R : The rooted product of G and H with a specified root in H
458
+
459
+ Notes
460
+ -----
461
+ The nodes of R are the Cartesian Product of the nodes of G and H.
462
+ The nodes of G and H are not relabeled.
463
+ """
464
+ if root not in H:
465
+ raise nx.NodeNotFound("root must be a vertex in H")
466
+
467
+ R = nx.Graph()
468
+ R.add_nodes_from(product(G, H))
469
+
470
+ R.add_edges_from(((e[0], root), (e[1], root)) for e in G.edges())
471
+ R.add_edges_from(((g, e[0]), (g, e[1])) for g in G for e in H.edges())
472
+
473
+ return R
474
+
475
+
476
+ @not_implemented_for("directed")
477
+ @not_implemented_for("multigraph")
478
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
479
+ def corona_product(G, H):
480
+ r"""Returns the Corona product of G and H.
481
+
482
+ The corona product of $G$ and $H$ is the graph $C = G \circ H$ obtained by
483
+ taking one copy of $G$, called the center graph, $|V(G)|$ copies of $H$,
484
+ called the outer graph, and making the $i$-th vertex of $G$ adjacent to
485
+ every vertex of the $i$-th copy of $H$, where $1 ≤ i ≤ |V(G)|$.
486
+
487
+ Parameters
488
+ ----------
489
+ G, H: NetworkX graphs
490
+ The graphs to take the carona product of.
491
+ `G` is the center graph and `H` is the outer graph
492
+
493
+ Returns
494
+ -------
495
+ C: NetworkX graph
496
+ The Corona product of G and H.
497
+
498
+ Raises
499
+ ------
500
+ NetworkXError
501
+ If G and H are not both directed or both undirected.
502
+
503
+ Examples
504
+ --------
505
+ >>> G = nx.cycle_graph(4)
506
+ >>> H = nx.path_graph(2)
507
+ >>> C = nx.corona_product(G, H)
508
+ >>> list(C)
509
+ [0, 1, 2, 3, (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
510
+ >>> print(C)
511
+ Graph with 12 nodes and 16 edges
512
+
513
+ References
514
+ ----------
515
+ [1] M. Tavakoli, F. Rahbarnia, and A. R. Ashrafi,
516
+ "Studying the corona product of graphs under some graph invariants,"
517
+ Transactions on Combinatorics, vol. 3, no. 3, pp. 43–49, Sep. 2014,
518
+ doi: 10.22108/toc.2014.5542.
519
+ [2] A. Faraji, "Corona Product in Graph Theory," Ali Faraji, May 11, 2021.
520
+ https://blog.alifaraji.ir/math/graph-theory/corona-product.html (accessed Dec. 07, 2021).
521
+ """
522
+ GH = _init_product_graph(G, H)
523
+ GH.add_nodes_from(G)
524
+ GH.add_edges_from(G.edges)
525
+
526
+ for G_node in G:
527
+ # copy nodes of H in GH, call it H_i
528
+ GH.add_nodes_from((G_node, v) for v in H)
529
+
530
+ # copy edges of H_i based on H
531
+ GH.add_edges_from(
532
+ ((G_node, e0), (G_node, e1), d) for e0, e1, d in H.edges.data()
533
+ )
534
+
535
+ # creating new edges between H_i and a G's node
536
+ GH.add_edges_from((G_node, (G_node, H_node)) for H_node in H)
537
+
538
+ return GH
539
+
540
+
541
+ @nx._dispatchable(
542
+ graphs=_G_H, preserve_edge_attrs=True, preserve_node_attrs=True, returns_graph=True
543
+ )
544
+ def modular_product(G, H):
545
+ r"""Returns the Modular product of G and H.
546
+
547
+ The modular product of `G` and `H` is the graph $M = G \nabla H$,
548
+ consisting of the node set $V(M) = V(G) \times V(H)$ that is the Cartesian
549
+ product of the node sets of `G` and `H`. Further, M contains an edge ((u, v), (x, y)):
550
+
551
+ - if u is adjacent to x in `G` and v is adjacent to y in `H`, or
552
+ - if u is not adjacent to x in `G` and v is not adjacent to y in `H`.
553
+
554
+ More formally::
555
+
556
+ E(M) = {((u, v), (x, y)) | ((u, x) in E(G) and (v, y) in E(H)) or
557
+ ((u, x) not in E(G) and (v, y) not in E(H))}
558
+
559
+ Parameters
560
+ ----------
561
+ G, H: NetworkX graphs
562
+ The graphs to take the modular product of.
563
+
564
+ Returns
565
+ -------
566
+ M: NetworkX graph
567
+ The Modular product of `G` and `H`.
568
+
569
+ Raises
570
+ ------
571
+ NetworkXNotImplemented
572
+ If `G` is not a simple graph.
573
+
574
+ Examples
575
+ --------
576
+ >>> G = nx.cycle_graph(4)
577
+ >>> H = nx.path_graph(2)
578
+ >>> M = nx.modular_product(G, H)
579
+ >>> list(M)
580
+ [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
581
+ >>> print(M)
582
+ Graph with 8 nodes and 8 edges
583
+
584
+ Notes
585
+ -----
586
+ The *modular product* is defined in [1]_ and was first
587
+ introduced as the *weak modular product*.
588
+
589
+ The modular product reduces the problem of counting isomorphic subgraphs
590
+ in `G` and `H` to the problem of counting cliques in M. The subgraphs of
591
+ `G` and `H` that are induced by the nodes of a clique in M are
592
+ isomorphic [2]_ [3]_.
593
+
594
+ References
595
+ ----------
596
+ .. [1] R. Hammack, W. Imrich, and S. Klavžar,
597
+ "Handbook of Product Graphs", CRC Press, 2011.
598
+
599
+ .. [2] H. G. Barrow and R. M. Burstall,
600
+ "Subgraph isomorphism, matching relational structures and maximal
601
+ cliques", Information Processing Letters, vol. 4, issue 4, pp. 83-84,
602
+ 1976, https://doi.org/10.1016/0020-0190(76)90049-1.
603
+
604
+ .. [3] V. G. Vizing, "Reduction of the problem of isomorphism and isomorphic
605
+ entrance to the task of finding the nondensity of a graph." Proc. Third
606
+ All-Union Conference on Problems of Theoretical Cybernetics. 1974.
607
+ """
608
+ if G.is_directed() or H.is_directed():
609
+ raise nx.NetworkXNotImplemented(
610
+ "Modular product not implemented for directed graphs"
611
+ )
612
+ if G.is_multigraph() or H.is_multigraph():
613
+ raise nx.NetworkXNotImplemented(
614
+ "Modular product not implemented for multigraphs"
615
+ )
616
+
617
+ GH = _init_product_graph(G, H)
618
+ GH.add_nodes_from(_node_product(G, H))
619
+
620
+ for u, v, c in G.edges(data=True):
621
+ for x, y, d in H.edges(data=True):
622
+ GH.add_edge((u, x), (v, y), **_dict_product(c, d))
623
+ GH.add_edge((v, x), (u, y), **_dict_product(c, d))
624
+
625
+ G = nx.complement(G)
626
+ H = nx.complement(H)
627
+
628
+ for u, v, c in G.edges(data=True):
629
+ for x, y, d in H.edges(data=True):
630
+ GH.add_edge((u, x), (v, y), **_dict_product(c, d))
631
+ GH.add_edge((v, x), (u, y), **_dict_product(c, d))
632
+
633
+ return GH
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_binary.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_product.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_all.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ def test_union_all_attributes():
8
+ g = nx.Graph()
9
+ g.add_node(0, x=4)
10
+ g.add_node(1, x=5)
11
+ g.add_edge(0, 1, size=5)
12
+ g.graph["name"] = "g"
13
+
14
+ h = g.copy()
15
+ h.graph["name"] = "h"
16
+ h.graph["attr"] = "attr"
17
+ h.nodes[0]["x"] = 7
18
+
19
+ j = g.copy()
20
+ j.graph["name"] = "j"
21
+ j.graph["attr"] = "attr"
22
+ j.nodes[0]["x"] = 7
23
+
24
+ ghj = nx.union_all([g, h, j], rename=("g", "h", "j"))
25
+ assert set(ghj.nodes()) == {"h0", "h1", "g0", "g1", "j0", "j1"}
26
+ for n in ghj:
27
+ graph, node = n
28
+ assert ghj.nodes[n] == eval(graph).nodes[int(node)]
29
+
30
+ assert ghj.graph["attr"] == "attr"
31
+ assert ghj.graph["name"] == "j" # j graph attributes take precedent
32
+
33
+
34
+ def test_intersection_all():
35
+ G = nx.Graph()
36
+ H = nx.Graph()
37
+ R = nx.Graph(awesome=True)
38
+ G.add_nodes_from([1, 2, 3, 4])
39
+ G.add_edge(1, 2)
40
+ G.add_edge(2, 3)
41
+ H.add_nodes_from([1, 2, 3, 4])
42
+ H.add_edge(2, 3)
43
+ H.add_edge(3, 4)
44
+ R.add_nodes_from([1, 2, 3, 4])
45
+ R.add_edge(2, 3)
46
+ R.add_edge(4, 1)
47
+ I = nx.intersection_all([G, H, R])
48
+ assert set(I.nodes()) == {1, 2, 3, 4}
49
+ assert sorted(I.edges()) == [(2, 3)]
50
+ assert I.graph == {}
51
+
52
+
53
+ def test_intersection_all_different_node_sets():
54
+ G = nx.Graph()
55
+ H = nx.Graph()
56
+ R = nx.Graph()
57
+ G.add_nodes_from([1, 2, 3, 4, 6, 7])
58
+ G.add_edge(1, 2)
59
+ G.add_edge(2, 3)
60
+ G.add_edge(6, 7)
61
+ H.add_nodes_from([1, 2, 3, 4])
62
+ H.add_edge(2, 3)
63
+ H.add_edge(3, 4)
64
+ R.add_nodes_from([1, 2, 3, 4, 8, 9])
65
+ R.add_edge(2, 3)
66
+ R.add_edge(4, 1)
67
+ R.add_edge(8, 9)
68
+ I = nx.intersection_all([G, H, R])
69
+ assert set(I.nodes()) == {1, 2, 3, 4}
70
+ assert sorted(I.edges()) == [(2, 3)]
71
+
72
+
73
+ def test_intersection_all_attributes():
74
+ g = nx.Graph()
75
+ g.add_node(0, x=4)
76
+ g.add_node(1, x=5)
77
+ g.add_edge(0, 1, size=5)
78
+ g.graph["name"] = "g"
79
+
80
+ h = g.copy()
81
+ h.graph["name"] = "h"
82
+ h.graph["attr"] = "attr"
83
+ h.nodes[0]["x"] = 7
84
+
85
+ gh = nx.intersection_all([g, h])
86
+ assert set(gh.nodes()) == set(g.nodes())
87
+ assert set(gh.nodes()) == set(h.nodes())
88
+ assert sorted(gh.edges()) == sorted(g.edges())
89
+
90
+
91
+ def test_intersection_all_attributes_different_node_sets():
92
+ g = nx.Graph()
93
+ g.add_node(0, x=4)
94
+ g.add_node(1, x=5)
95
+ g.add_edge(0, 1, size=5)
96
+ g.graph["name"] = "g"
97
+
98
+ h = g.copy()
99
+ g.add_node(2)
100
+ h.graph["name"] = "h"
101
+ h.graph["attr"] = "attr"
102
+ h.nodes[0]["x"] = 7
103
+
104
+ gh = nx.intersection_all([g, h])
105
+ assert set(gh.nodes()) == set(h.nodes())
106
+ assert sorted(gh.edges()) == sorted(g.edges())
107
+
108
+
109
+ def test_intersection_all_multigraph_attributes():
110
+ g = nx.MultiGraph()
111
+ g.add_edge(0, 1, key=0)
112
+ g.add_edge(0, 1, key=1)
113
+ g.add_edge(0, 1, key=2)
114
+ h = nx.MultiGraph()
115
+ h.add_edge(0, 1, key=0)
116
+ h.add_edge(0, 1, key=3)
117
+ gh = nx.intersection_all([g, h])
118
+ assert set(gh.nodes()) == set(g.nodes())
119
+ assert set(gh.nodes()) == set(h.nodes())
120
+ assert sorted(gh.edges()) == [(0, 1)]
121
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
122
+
123
+
124
+ def test_intersection_all_multigraph_attributes_different_node_sets():
125
+ g = nx.MultiGraph()
126
+ g.add_edge(0, 1, key=0)
127
+ g.add_edge(0, 1, key=1)
128
+ g.add_edge(0, 1, key=2)
129
+ g.add_edge(1, 2, key=1)
130
+ g.add_edge(1, 2, key=2)
131
+ h = nx.MultiGraph()
132
+ h.add_edge(0, 1, key=0)
133
+ h.add_edge(0, 1, key=2)
134
+ h.add_edge(0, 1, key=3)
135
+ gh = nx.intersection_all([g, h])
136
+ assert set(gh.nodes()) == set(h.nodes())
137
+ assert sorted(gh.edges()) == [(0, 1), (0, 1)]
138
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0), (0, 1, 2)]
139
+
140
+
141
+ def test_intersection_all_digraph():
142
+ g = nx.DiGraph()
143
+ g.add_edges_from([(1, 2), (2, 3)])
144
+ h = nx.DiGraph()
145
+ h.add_edges_from([(2, 1), (2, 3)])
146
+ gh = nx.intersection_all([g, h])
147
+ assert sorted(gh.edges()) == [(2, 3)]
148
+
149
+
150
+ def test_union_all_and_compose_all():
151
+ K3 = nx.complete_graph(3)
152
+ P3 = nx.path_graph(3)
153
+
154
+ G1 = nx.DiGraph()
155
+ G1.add_edge("A", "B")
156
+ G1.add_edge("A", "C")
157
+ G1.add_edge("A", "D")
158
+ G2 = nx.DiGraph()
159
+ G2.add_edge("1", "2")
160
+ G2.add_edge("1", "3")
161
+ G2.add_edge("1", "4")
162
+
163
+ G = nx.union_all([G1, G2])
164
+ H = nx.compose_all([G1, G2])
165
+ assert edges_equal(G.edges(), H.edges())
166
+ assert not G.has_edge("A", "1")
167
+ pytest.raises(nx.NetworkXError, nx.union, K3, P3)
168
+ H1 = nx.union_all([H, G1], rename=("H", "G1"))
169
+ assert sorted(H1.nodes()) == [
170
+ "G1A",
171
+ "G1B",
172
+ "G1C",
173
+ "G1D",
174
+ "H1",
175
+ "H2",
176
+ "H3",
177
+ "H4",
178
+ "HA",
179
+ "HB",
180
+ "HC",
181
+ "HD",
182
+ ]
183
+
184
+ H2 = nx.union_all([H, G2], rename=("H", ""))
185
+ assert sorted(H2.nodes()) == [
186
+ "1",
187
+ "2",
188
+ "3",
189
+ "4",
190
+ "H1",
191
+ "H2",
192
+ "H3",
193
+ "H4",
194
+ "HA",
195
+ "HB",
196
+ "HC",
197
+ "HD",
198
+ ]
199
+
200
+ assert not H1.has_edge("NB", "NA")
201
+
202
+ G = nx.compose_all([G, G])
203
+ assert edges_equal(G.edges(), H.edges())
204
+
205
+ G2 = nx.union_all([G2, G2], rename=("", "copy"))
206
+ assert sorted(G2.nodes()) == [
207
+ "1",
208
+ "2",
209
+ "3",
210
+ "4",
211
+ "copy1",
212
+ "copy2",
213
+ "copy3",
214
+ "copy4",
215
+ ]
216
+
217
+ assert sorted(G2.neighbors("copy4")) == []
218
+ assert sorted(G2.neighbors("copy1")) == ["copy2", "copy3", "copy4"]
219
+ assert len(G) == 8
220
+ assert nx.number_of_edges(G) == 6
221
+
222
+ E = nx.disjoint_union_all([G, G])
223
+ assert len(E) == 16
224
+ assert nx.number_of_edges(E) == 12
225
+
226
+ E = nx.disjoint_union_all([G1, G2])
227
+ assert sorted(E.nodes()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
228
+
229
+ G1 = nx.DiGraph()
230
+ G1.add_edge("A", "B")
231
+ G2 = nx.DiGraph()
232
+ G2.add_edge(1, 2)
233
+ G3 = nx.DiGraph()
234
+ G3.add_edge(11, 22)
235
+ G4 = nx.union_all([G1, G2, G3], rename=("G1", "G2", "G3"))
236
+ assert sorted(G4.nodes()) == ["G1A", "G1B", "G21", "G22", "G311", "G322"]
237
+
238
+
239
+ def test_union_all_multigraph():
240
+ G = nx.MultiGraph()
241
+ G.add_edge(1, 2, key=0)
242
+ G.add_edge(1, 2, key=1)
243
+ H = nx.MultiGraph()
244
+ H.add_edge(3, 4, key=0)
245
+ H.add_edge(3, 4, key=1)
246
+ GH = nx.union_all([G, H])
247
+ assert set(GH) == set(G) | set(H)
248
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
249
+
250
+
251
+ def test_input_output():
252
+ l = [nx.Graph([(1, 2)]), nx.Graph([(3, 4)], awesome=True)]
253
+ U = nx.disjoint_union_all(l)
254
+ assert len(l) == 2
255
+ assert U.graph["awesome"]
256
+ C = nx.compose_all(l)
257
+ assert len(l) == 2
258
+ l = [nx.Graph([(1, 2)]), nx.Graph([(1, 2)])]
259
+ R = nx.intersection_all(l)
260
+ assert len(l) == 2
261
+
262
+
263
+ def test_mixed_type_union():
264
+ with pytest.raises(nx.NetworkXError):
265
+ G = nx.Graph()
266
+ H = nx.MultiGraph()
267
+ I = nx.Graph()
268
+ U = nx.union_all([G, H, I])
269
+ with pytest.raises(nx.NetworkXError):
270
+ X = nx.Graph()
271
+ Y = nx.DiGraph()
272
+ XY = nx.union_all([X, Y])
273
+
274
+
275
+ def test_mixed_type_disjoint_union():
276
+ with pytest.raises(nx.NetworkXError):
277
+ G = nx.Graph()
278
+ H = nx.MultiGraph()
279
+ I = nx.Graph()
280
+ U = nx.disjoint_union_all([G, H, I])
281
+ with pytest.raises(nx.NetworkXError):
282
+ X = nx.Graph()
283
+ Y = nx.DiGraph()
284
+ XY = nx.disjoint_union_all([X, Y])
285
+
286
+
287
+ def test_mixed_type_intersection():
288
+ with pytest.raises(nx.NetworkXError):
289
+ G = nx.Graph()
290
+ H = nx.MultiGraph()
291
+ I = nx.Graph()
292
+ U = nx.intersection_all([G, H, I])
293
+ with pytest.raises(nx.NetworkXError):
294
+ X = nx.Graph()
295
+ Y = nx.DiGraph()
296
+ XY = nx.intersection_all([X, Y])
297
+
298
+
299
+ def test_mixed_type_compose():
300
+ with pytest.raises(nx.NetworkXError):
301
+ G = nx.Graph()
302
+ H = nx.MultiGraph()
303
+ I = nx.Graph()
304
+ U = nx.compose_all([G, H, I])
305
+ with pytest.raises(nx.NetworkXError):
306
+ X = nx.Graph()
307
+ Y = nx.DiGraph()
308
+ XY = nx.compose_all([X, Y])
309
+
310
+
311
+ def test_empty_union():
312
+ with pytest.raises(ValueError):
313
+ nx.union_all([])
314
+
315
+
316
+ def test_empty_disjoint_union():
317
+ with pytest.raises(ValueError):
318
+ nx.disjoint_union_all([])
319
+
320
+
321
+ def test_empty_compose_all():
322
+ with pytest.raises(ValueError):
323
+ nx.compose_all([])
324
+
325
+
326
+ def test_empty_intersection_all():
327
+ with pytest.raises(ValueError):
328
+ nx.intersection_all([])
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_binary.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal
7
+
8
+
9
+ def test_union_attributes():
10
+ g = nx.Graph()
11
+ g.add_node(0, x=4)
12
+ g.add_node(1, x=5)
13
+ g.add_edge(0, 1, size=5)
14
+ g.graph["name"] = "g"
15
+
16
+ h = g.copy()
17
+ h.graph["name"] = "h"
18
+ h.graph["attr"] = "attr"
19
+ h.nodes[0]["x"] = 7
20
+
21
+ gh = nx.union(g, h, rename=("g", "h"))
22
+ assert set(gh.nodes()) == {"h0", "h1", "g0", "g1"}
23
+ for n in gh:
24
+ graph, node = n
25
+ assert gh.nodes[n] == eval(graph).nodes[int(node)]
26
+
27
+ assert gh.graph["attr"] == "attr"
28
+ assert gh.graph["name"] == "h" # h graph attributes take precedent
29
+
30
+
31
+ def test_intersection():
32
+ G = nx.Graph()
33
+ H = nx.Graph()
34
+ G.add_nodes_from([1, 2, 3, 4])
35
+ G.add_edge(1, 2)
36
+ G.add_edge(2, 3)
37
+ H.add_nodes_from([1, 2, 3, 4])
38
+ H.add_edge(2, 3)
39
+ H.add_edge(3, 4)
40
+ I = nx.intersection(G, H)
41
+ assert set(I.nodes()) == {1, 2, 3, 4}
42
+ assert sorted(I.edges()) == [(2, 3)]
43
+
44
+
45
+ def test_intersection_node_sets_different():
46
+ G = nx.Graph()
47
+ H = nx.Graph()
48
+ G.add_nodes_from([1, 2, 3, 4, 7])
49
+ G.add_edge(1, 2)
50
+ G.add_edge(2, 3)
51
+ H.add_nodes_from([1, 2, 3, 4, 5, 6])
52
+ H.add_edge(2, 3)
53
+ H.add_edge(3, 4)
54
+ H.add_edge(5, 6)
55
+ I = nx.intersection(G, H)
56
+ assert set(I.nodes()) == {1, 2, 3, 4}
57
+ assert sorted(I.edges()) == [(2, 3)]
58
+
59
+
60
+ def test_intersection_attributes():
61
+ g = nx.Graph()
62
+ g.add_node(0, x=4)
63
+ g.add_node(1, x=5)
64
+ g.add_edge(0, 1, size=5)
65
+ g.graph["name"] = "g"
66
+
67
+ h = g.copy()
68
+ h.graph["name"] = "h"
69
+ h.graph["attr"] = "attr"
70
+ h.nodes[0]["x"] = 7
71
+ gh = nx.intersection(g, h)
72
+
73
+ assert set(gh.nodes()) == set(g.nodes())
74
+ assert set(gh.nodes()) == set(h.nodes())
75
+ assert sorted(gh.edges()) == sorted(g.edges())
76
+
77
+
78
+ def test_intersection_attributes_node_sets_different():
79
+ g = nx.Graph()
80
+ g.add_node(0, x=4)
81
+ g.add_node(1, x=5)
82
+ g.add_node(2, x=3)
83
+ g.add_edge(0, 1, size=5)
84
+ g.graph["name"] = "g"
85
+
86
+ h = g.copy()
87
+ h.graph["name"] = "h"
88
+ h.graph["attr"] = "attr"
89
+ h.nodes[0]["x"] = 7
90
+ h.remove_node(2)
91
+
92
+ gh = nx.intersection(g, h)
93
+ assert set(gh.nodes()) == set(h.nodes())
94
+ assert sorted(gh.edges()) == sorted(g.edges())
95
+
96
+
97
+ def test_intersection_multigraph_attributes():
98
+ g = nx.MultiGraph()
99
+ g.add_edge(0, 1, key=0)
100
+ g.add_edge(0, 1, key=1)
101
+ g.add_edge(0, 1, key=2)
102
+ h = nx.MultiGraph()
103
+ h.add_edge(0, 1, key=0)
104
+ h.add_edge(0, 1, key=3)
105
+ gh = nx.intersection(g, h)
106
+ assert set(gh.nodes()) == set(g.nodes())
107
+ assert set(gh.nodes()) == set(h.nodes())
108
+ assert sorted(gh.edges()) == [(0, 1)]
109
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
110
+
111
+
112
+ def test_intersection_multigraph_attributes_node_set_different():
113
+ g = nx.MultiGraph()
114
+ g.add_edge(0, 1, key=0)
115
+ g.add_edge(0, 1, key=1)
116
+ g.add_edge(0, 1, key=2)
117
+ g.add_edge(0, 2, key=2)
118
+ g.add_edge(0, 2, key=1)
119
+ h = nx.MultiGraph()
120
+ h.add_edge(0, 1, key=0)
121
+ h.add_edge(0, 1, key=3)
122
+ gh = nx.intersection(g, h)
123
+ assert set(gh.nodes()) == set(h.nodes())
124
+ assert sorted(gh.edges()) == [(0, 1)]
125
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
126
+
127
+
128
+ def test_difference():
129
+ G = nx.Graph()
130
+ H = nx.Graph()
131
+ G.add_nodes_from([1, 2, 3, 4])
132
+ G.add_edge(1, 2)
133
+ G.add_edge(2, 3)
134
+ H.add_nodes_from([1, 2, 3, 4])
135
+ H.add_edge(2, 3)
136
+ H.add_edge(3, 4)
137
+ D = nx.difference(G, H)
138
+ assert set(D.nodes()) == {1, 2, 3, 4}
139
+ assert sorted(D.edges()) == [(1, 2)]
140
+ D = nx.difference(H, G)
141
+ assert set(D.nodes()) == {1, 2, 3, 4}
142
+ assert sorted(D.edges()) == [(3, 4)]
143
+ D = nx.symmetric_difference(G, H)
144
+ assert set(D.nodes()) == {1, 2, 3, 4}
145
+ assert sorted(D.edges()) == [(1, 2), (3, 4)]
146
+
147
+
148
+ def test_difference2():
149
+ G = nx.Graph()
150
+ H = nx.Graph()
151
+ G.add_nodes_from([1, 2, 3, 4])
152
+ H.add_nodes_from([1, 2, 3, 4])
153
+ G.add_edge(1, 2)
154
+ H.add_edge(1, 2)
155
+ G.add_edge(2, 3)
156
+ D = nx.difference(G, H)
157
+ assert set(D.nodes()) == {1, 2, 3, 4}
158
+ assert sorted(D.edges()) == [(2, 3)]
159
+ D = nx.difference(H, G)
160
+ assert set(D.nodes()) == {1, 2, 3, 4}
161
+ assert sorted(D.edges()) == []
162
+ H.add_edge(3, 4)
163
+ D = nx.difference(H, G)
164
+ assert set(D.nodes()) == {1, 2, 3, 4}
165
+ assert sorted(D.edges()) == [(3, 4)]
166
+
167
+
168
+ def test_difference_attributes():
169
+ g = nx.Graph()
170
+ g.add_node(0, x=4)
171
+ g.add_node(1, x=5)
172
+ g.add_edge(0, 1, size=5)
173
+ g.graph["name"] = "g"
174
+
175
+ h = g.copy()
176
+ h.graph["name"] = "h"
177
+ h.graph["attr"] = "attr"
178
+ h.nodes[0]["x"] = 7
179
+
180
+ gh = nx.difference(g, h)
181
+ assert set(gh.nodes()) == set(g.nodes())
182
+ assert set(gh.nodes()) == set(h.nodes())
183
+ assert sorted(gh.edges()) == []
184
+ # node and graph data should not be copied over
185
+ assert gh.nodes.data() != g.nodes.data()
186
+ assert gh.graph != g.graph
187
+
188
+
189
+ def test_difference_multigraph_attributes():
190
+ g = nx.MultiGraph()
191
+ g.add_edge(0, 1, key=0)
192
+ g.add_edge(0, 1, key=1)
193
+ g.add_edge(0, 1, key=2)
194
+ h = nx.MultiGraph()
195
+ h.add_edge(0, 1, key=0)
196
+ h.add_edge(0, 1, key=3)
197
+ gh = nx.difference(g, h)
198
+ assert set(gh.nodes()) == set(g.nodes())
199
+ assert set(gh.nodes()) == set(h.nodes())
200
+ assert sorted(gh.edges()) == [(0, 1), (0, 1)]
201
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 1), (0, 1, 2)]
202
+
203
+
204
+ def test_difference_raise():
205
+ G = nx.path_graph(4)
206
+ H = nx.path_graph(3)
207
+ pytest.raises(nx.NetworkXError, nx.difference, G, H)
208
+ pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H)
209
+
210
+
211
+ def test_symmetric_difference_multigraph():
212
+ g = nx.MultiGraph()
213
+ g.add_edge(0, 1, key=0)
214
+ g.add_edge(0, 1, key=1)
215
+ g.add_edge(0, 1, key=2)
216
+ h = nx.MultiGraph()
217
+ h.add_edge(0, 1, key=0)
218
+ h.add_edge(0, 1, key=3)
219
+ gh = nx.symmetric_difference(g, h)
220
+ assert set(gh.nodes()) == set(g.nodes())
221
+ assert set(gh.nodes()) == set(h.nodes())
222
+ assert sorted(gh.edges()) == 3 * [(0, 1)]
223
+ assert sorted(sorted(e) for e in gh.edges(keys=True)) == [
224
+ [0, 1, 1],
225
+ [0, 1, 2],
226
+ [0, 1, 3],
227
+ ]
228
+
229
+
230
+ def test_union_and_compose():
231
+ K3 = nx.complete_graph(3)
232
+ P3 = nx.path_graph(3)
233
+
234
+ G1 = nx.DiGraph()
235
+ G1.add_edge("A", "B")
236
+ G1.add_edge("A", "C")
237
+ G1.add_edge("A", "D")
238
+ G2 = nx.DiGraph()
239
+ G2.add_edge("1", "2")
240
+ G2.add_edge("1", "3")
241
+ G2.add_edge("1", "4")
242
+
243
+ G = nx.union(G1, G2)
244
+ H = nx.compose(G1, G2)
245
+ assert edges_equal(G.edges(), H.edges())
246
+ assert not G.has_edge("A", 1)
247
+ pytest.raises(nx.NetworkXError, nx.union, K3, P3)
248
+ H1 = nx.union(H, G1, rename=("H", "G1"))
249
+ assert sorted(H1.nodes()) == [
250
+ "G1A",
251
+ "G1B",
252
+ "G1C",
253
+ "G1D",
254
+ "H1",
255
+ "H2",
256
+ "H3",
257
+ "H4",
258
+ "HA",
259
+ "HB",
260
+ "HC",
261
+ "HD",
262
+ ]
263
+
264
+ H2 = nx.union(H, G2, rename=("H", ""))
265
+ assert sorted(H2.nodes()) == [
266
+ "1",
267
+ "2",
268
+ "3",
269
+ "4",
270
+ "H1",
271
+ "H2",
272
+ "H3",
273
+ "H4",
274
+ "HA",
275
+ "HB",
276
+ "HC",
277
+ "HD",
278
+ ]
279
+
280
+ assert not H1.has_edge("NB", "NA")
281
+
282
+ G = nx.compose(G, G)
283
+ assert edges_equal(G.edges(), H.edges())
284
+
285
+ G2 = nx.union(G2, G2, rename=("", "copy"))
286
+ assert sorted(G2.nodes()) == [
287
+ "1",
288
+ "2",
289
+ "3",
290
+ "4",
291
+ "copy1",
292
+ "copy2",
293
+ "copy3",
294
+ "copy4",
295
+ ]
296
+
297
+ assert sorted(G2.neighbors("copy4")) == []
298
+ assert sorted(G2.neighbors("copy1")) == ["copy2", "copy3", "copy4"]
299
+ assert len(G) == 8
300
+ assert nx.number_of_edges(G) == 6
301
+
302
+ E = nx.disjoint_union(G, G)
303
+ assert len(E) == 16
304
+ assert nx.number_of_edges(E) == 12
305
+
306
+ E = nx.disjoint_union(G1, G2)
307
+ assert sorted(E.nodes()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
308
+
309
+ G = nx.Graph()
310
+ H = nx.Graph()
311
+ G.add_nodes_from([(1, {"a1": 1})])
312
+ H.add_nodes_from([(1, {"b1": 1})])
313
+ R = nx.compose(G, H)
314
+ assert R.nodes == {1: {"a1": 1, "b1": 1}}
315
+
316
+
317
+ def test_union_multigraph():
318
+ G = nx.MultiGraph()
319
+ G.add_edge(1, 2, key=0)
320
+ G.add_edge(1, 2, key=1)
321
+ H = nx.MultiGraph()
322
+ H.add_edge(3, 4, key=0)
323
+ H.add_edge(3, 4, key=1)
324
+ GH = nx.union(G, H)
325
+ assert set(GH) == set(G) | set(H)
326
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
327
+
328
+
329
+ def test_disjoint_union_multigraph():
330
+ G = nx.MultiGraph()
331
+ G.add_edge(0, 1, key=0)
332
+ G.add_edge(0, 1, key=1)
333
+ H = nx.MultiGraph()
334
+ H.add_edge(2, 3, key=0)
335
+ H.add_edge(2, 3, key=1)
336
+ GH = nx.disjoint_union(G, H)
337
+ assert set(GH) == set(G) | set(H)
338
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
339
+
340
+
341
+ def test_compose_multigraph():
342
+ G = nx.MultiGraph()
343
+ G.add_edge(1, 2, key=0)
344
+ G.add_edge(1, 2, key=1)
345
+ H = nx.MultiGraph()
346
+ H.add_edge(3, 4, key=0)
347
+ H.add_edge(3, 4, key=1)
348
+ GH = nx.compose(G, H)
349
+ assert set(GH) == set(G) | set(H)
350
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
351
+ H.add_edge(1, 2, key=2)
352
+ GH = nx.compose(G, H)
353
+ assert set(GH) == set(G) | set(H)
354
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
355
+
356
+
357
+ def test_full_join_graph():
358
+ # Simple Graphs
359
+ G = nx.Graph()
360
+ G.add_node(0)
361
+ G.add_edge(1, 2)
362
+ H = nx.Graph()
363
+ H.add_edge(3, 4)
364
+
365
+ U = nx.full_join(G, H)
366
+ assert set(U) == set(G) | set(H)
367
+ assert len(U) == len(G) + len(H)
368
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
369
+
370
+ # Rename
371
+ U = nx.full_join(G, H, rename=("g", "h"))
372
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
373
+ assert len(U) == len(G) + len(H)
374
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
375
+
376
+ # Rename graphs with string-like nodes
377
+ G = nx.Graph()
378
+ G.add_node("a")
379
+ G.add_edge("b", "c")
380
+ H = nx.Graph()
381
+ H.add_edge("d", "e")
382
+
383
+ U = nx.full_join(G, H, rename=("g", "h"))
384
+ assert set(U) == {"ga", "gb", "gc", "hd", "he"}
385
+ assert len(U) == len(G) + len(H)
386
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
387
+
388
+ # DiGraphs
389
+ G = nx.DiGraph()
390
+ G.add_node(0)
391
+ G.add_edge(1, 2)
392
+ H = nx.DiGraph()
393
+ H.add_edge(3, 4)
394
+
395
+ U = nx.full_join(G, H)
396
+ assert set(U) == set(G) | set(H)
397
+ assert len(U) == len(G) + len(H)
398
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
399
+
400
+ # DiGraphs Rename
401
+ U = nx.full_join(G, H, rename=("g", "h"))
402
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
403
+ assert len(U) == len(G) + len(H)
404
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
405
+
406
+
407
+ def test_full_join_multigraph():
408
+ # MultiGraphs
409
+ G = nx.MultiGraph()
410
+ G.add_node(0)
411
+ G.add_edge(1, 2)
412
+ H = nx.MultiGraph()
413
+ H.add_edge(3, 4)
414
+
415
+ U = nx.full_join(G, H)
416
+ assert set(U) == set(G) | set(H)
417
+ assert len(U) == len(G) + len(H)
418
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
419
+
420
+ # MultiGraphs rename
421
+ U = nx.full_join(G, H, rename=("g", "h"))
422
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
423
+ assert len(U) == len(G) + len(H)
424
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
425
+
426
+ # MultiDiGraphs
427
+ G = nx.MultiDiGraph()
428
+ G.add_node(0)
429
+ G.add_edge(1, 2)
430
+ H = nx.MultiDiGraph()
431
+ H.add_edge(3, 4)
432
+
433
+ U = nx.full_join(G, H)
434
+ assert set(U) == set(G) | set(H)
435
+ assert len(U) == len(G) + len(H)
436
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
437
+
438
+ # MultiDiGraphs rename
439
+ U = nx.full_join(G, H, rename=("g", "h"))
440
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
441
+ assert len(U) == len(G) + len(H)
442
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
443
+
444
+
445
+ def test_mixed_type_union():
446
+ G = nx.Graph()
447
+ H = nx.MultiGraph()
448
+ pytest.raises(nx.NetworkXError, nx.union, G, H)
449
+ pytest.raises(nx.NetworkXError, nx.disjoint_union, G, H)
450
+ pytest.raises(nx.NetworkXError, nx.intersection, G, H)
451
+ pytest.raises(nx.NetworkXError, nx.difference, G, H)
452
+ pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H)
453
+ pytest.raises(nx.NetworkXError, nx.compose, G, H)
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_product.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ def test_tensor_product_raises():
8
+ with pytest.raises(nx.NetworkXError):
9
+ P = nx.tensor_product(nx.DiGraph(), nx.Graph())
10
+
11
+
12
+ def test_tensor_product_null():
13
+ null = nx.null_graph()
14
+ empty10 = nx.empty_graph(10)
15
+ K3 = nx.complete_graph(3)
16
+ K10 = nx.complete_graph(10)
17
+ P3 = nx.path_graph(3)
18
+ P10 = nx.path_graph(10)
19
+ # null graph
20
+ G = nx.tensor_product(null, null)
21
+ assert nx.is_isomorphic(G, null)
22
+ # null_graph X anything = null_graph and v.v.
23
+ G = nx.tensor_product(null, empty10)
24
+ assert nx.is_isomorphic(G, null)
25
+ G = nx.tensor_product(null, K3)
26
+ assert nx.is_isomorphic(G, null)
27
+ G = nx.tensor_product(null, K10)
28
+ assert nx.is_isomorphic(G, null)
29
+ G = nx.tensor_product(null, P3)
30
+ assert nx.is_isomorphic(G, null)
31
+ G = nx.tensor_product(null, P10)
32
+ assert nx.is_isomorphic(G, null)
33
+ G = nx.tensor_product(empty10, null)
34
+ assert nx.is_isomorphic(G, null)
35
+ G = nx.tensor_product(K3, null)
36
+ assert nx.is_isomorphic(G, null)
37
+ G = nx.tensor_product(K10, null)
38
+ assert nx.is_isomorphic(G, null)
39
+ G = nx.tensor_product(P3, null)
40
+ assert nx.is_isomorphic(G, null)
41
+ G = nx.tensor_product(P10, null)
42
+ assert nx.is_isomorphic(G, null)
43
+
44
+
45
+ def test_tensor_product_size():
46
+ P5 = nx.path_graph(5)
47
+ K3 = nx.complete_graph(3)
48
+ K5 = nx.complete_graph(5)
49
+
50
+ G = nx.tensor_product(P5, K3)
51
+ assert nx.number_of_nodes(G) == 5 * 3
52
+ G = nx.tensor_product(K3, K5)
53
+ assert nx.number_of_nodes(G) == 3 * 5
54
+
55
+
56
+ def test_tensor_product_combinations():
57
+ # basic smoke test, more realistic tests would be useful
58
+ P5 = nx.path_graph(5)
59
+ K3 = nx.complete_graph(3)
60
+ G = nx.tensor_product(P5, K3)
61
+ assert nx.number_of_nodes(G) == 5 * 3
62
+ G = nx.tensor_product(P5, nx.MultiGraph(K3))
63
+ assert nx.number_of_nodes(G) == 5 * 3
64
+ G = nx.tensor_product(nx.MultiGraph(P5), K3)
65
+ assert nx.number_of_nodes(G) == 5 * 3
66
+ G = nx.tensor_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
67
+ assert nx.number_of_nodes(G) == 5 * 3
68
+
69
+ G = nx.tensor_product(nx.DiGraph(P5), nx.DiGraph(K3))
70
+ assert nx.number_of_nodes(G) == 5 * 3
71
+
72
+
73
+ def test_tensor_product_classic_result():
74
+ K2 = nx.complete_graph(2)
75
+ G = nx.petersen_graph()
76
+ G = nx.tensor_product(G, K2)
77
+ assert nx.is_isomorphic(G, nx.desargues_graph())
78
+
79
+ G = nx.cycle_graph(5)
80
+ G = nx.tensor_product(G, K2)
81
+ assert nx.is_isomorphic(G, nx.cycle_graph(10))
82
+
83
+ G = nx.tetrahedral_graph()
84
+ G = nx.tensor_product(G, K2)
85
+ assert nx.is_isomorphic(G, nx.cubical_graph())
86
+
87
+
88
+ def test_tensor_product_random():
89
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
90
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
91
+ GH = nx.tensor_product(G, H)
92
+
93
+ for u_G, u_H in GH.nodes():
94
+ for v_G, v_H in GH.nodes():
95
+ if H.has_edge(u_H, v_H) and G.has_edge(u_G, v_G):
96
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
97
+ else:
98
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
99
+
100
+
101
+ def test_cartesian_product_multigraph():
102
+ G = nx.MultiGraph()
103
+ G.add_edge(1, 2, key=0)
104
+ G.add_edge(1, 2, key=1)
105
+ H = nx.MultiGraph()
106
+ H.add_edge(3, 4, key=0)
107
+ H.add_edge(3, 4, key=1)
108
+ GH = nx.cartesian_product(G, H)
109
+ assert set(GH) == {(1, 3), (2, 3), (2, 4), (1, 4)}
110
+ assert {(frozenset([u, v]), k) for u, v, k in GH.edges(keys=True)} == {
111
+ (frozenset([u, v]), k)
112
+ for u, v, k in [
113
+ ((1, 3), (2, 3), 0),
114
+ ((1, 3), (2, 3), 1),
115
+ ((1, 3), (1, 4), 0),
116
+ ((1, 3), (1, 4), 1),
117
+ ((2, 3), (2, 4), 0),
118
+ ((2, 3), (2, 4), 1),
119
+ ((2, 4), (1, 4), 0),
120
+ ((2, 4), (1, 4), 1),
121
+ ]
122
+ }
123
+
124
+
125
+ def test_cartesian_product_raises():
126
+ with pytest.raises(nx.NetworkXError):
127
+ P = nx.cartesian_product(nx.DiGraph(), nx.Graph())
128
+
129
+
130
+ def test_cartesian_product_null():
131
+ null = nx.null_graph()
132
+ empty10 = nx.empty_graph(10)
133
+ K3 = nx.complete_graph(3)
134
+ K10 = nx.complete_graph(10)
135
+ P3 = nx.path_graph(3)
136
+ P10 = nx.path_graph(10)
137
+ # null graph
138
+ G = nx.cartesian_product(null, null)
139
+ assert nx.is_isomorphic(G, null)
140
+ # null_graph X anything = null_graph and v.v.
141
+ G = nx.cartesian_product(null, empty10)
142
+ assert nx.is_isomorphic(G, null)
143
+ G = nx.cartesian_product(null, K3)
144
+ assert nx.is_isomorphic(G, null)
145
+ G = nx.cartesian_product(null, K10)
146
+ assert nx.is_isomorphic(G, null)
147
+ G = nx.cartesian_product(null, P3)
148
+ assert nx.is_isomorphic(G, null)
149
+ G = nx.cartesian_product(null, P10)
150
+ assert nx.is_isomorphic(G, null)
151
+ G = nx.cartesian_product(empty10, null)
152
+ assert nx.is_isomorphic(G, null)
153
+ G = nx.cartesian_product(K3, null)
154
+ assert nx.is_isomorphic(G, null)
155
+ G = nx.cartesian_product(K10, null)
156
+ assert nx.is_isomorphic(G, null)
157
+ G = nx.cartesian_product(P3, null)
158
+ assert nx.is_isomorphic(G, null)
159
+ G = nx.cartesian_product(P10, null)
160
+ assert nx.is_isomorphic(G, null)
161
+
162
+
163
+ def test_cartesian_product_size():
164
+ # order(GXH)=order(G)*order(H)
165
+ K5 = nx.complete_graph(5)
166
+ P5 = nx.path_graph(5)
167
+ K3 = nx.complete_graph(3)
168
+ G = nx.cartesian_product(P5, K3)
169
+ assert nx.number_of_nodes(G) == 5 * 3
170
+ assert nx.number_of_edges(G) == nx.number_of_edges(P5) * nx.number_of_nodes(
171
+ K3
172
+ ) + nx.number_of_edges(K3) * nx.number_of_nodes(P5)
173
+ G = nx.cartesian_product(K3, K5)
174
+ assert nx.number_of_nodes(G) == 3 * 5
175
+ assert nx.number_of_edges(G) == nx.number_of_edges(K5) * nx.number_of_nodes(
176
+ K3
177
+ ) + nx.number_of_edges(K3) * nx.number_of_nodes(K5)
178
+
179
+
180
+ def test_cartesian_product_classic():
181
+ # test some classic product graphs
182
+ P2 = nx.path_graph(2)
183
+ P3 = nx.path_graph(3)
184
+ # cube = 2-path X 2-path
185
+ G = nx.cartesian_product(P2, P2)
186
+ G = nx.cartesian_product(P2, G)
187
+ assert nx.is_isomorphic(G, nx.cubical_graph())
188
+
189
+ # 3x3 grid
190
+ G = nx.cartesian_product(P3, P3)
191
+ assert nx.is_isomorphic(G, nx.grid_2d_graph(3, 3))
192
+
193
+
194
+ def test_cartesian_product_random():
195
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
196
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
197
+ GH = nx.cartesian_product(G, H)
198
+
199
+ for u_G, u_H in GH.nodes():
200
+ for v_G, v_H in GH.nodes():
201
+ if (u_G == v_G and H.has_edge(u_H, v_H)) or (
202
+ u_H == v_H and G.has_edge(u_G, v_G)
203
+ ):
204
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
205
+ else:
206
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
207
+
208
+
209
+ def test_lexicographic_product_raises():
210
+ with pytest.raises(nx.NetworkXError):
211
+ P = nx.lexicographic_product(nx.DiGraph(), nx.Graph())
212
+
213
+
214
+ def test_lexicographic_product_null():
215
+ null = nx.null_graph()
216
+ empty10 = nx.empty_graph(10)
217
+ K3 = nx.complete_graph(3)
218
+ K10 = nx.complete_graph(10)
219
+ P3 = nx.path_graph(3)
220
+ P10 = nx.path_graph(10)
221
+ # null graph
222
+ G = nx.lexicographic_product(null, null)
223
+ assert nx.is_isomorphic(G, null)
224
+ # null_graph X anything = null_graph and v.v.
225
+ G = nx.lexicographic_product(null, empty10)
226
+ assert nx.is_isomorphic(G, null)
227
+ G = nx.lexicographic_product(null, K3)
228
+ assert nx.is_isomorphic(G, null)
229
+ G = nx.lexicographic_product(null, K10)
230
+ assert nx.is_isomorphic(G, null)
231
+ G = nx.lexicographic_product(null, P3)
232
+ assert nx.is_isomorphic(G, null)
233
+ G = nx.lexicographic_product(null, P10)
234
+ assert nx.is_isomorphic(G, null)
235
+ G = nx.lexicographic_product(empty10, null)
236
+ assert nx.is_isomorphic(G, null)
237
+ G = nx.lexicographic_product(K3, null)
238
+ assert nx.is_isomorphic(G, null)
239
+ G = nx.lexicographic_product(K10, null)
240
+ assert nx.is_isomorphic(G, null)
241
+ G = nx.lexicographic_product(P3, null)
242
+ assert nx.is_isomorphic(G, null)
243
+ G = nx.lexicographic_product(P10, null)
244
+ assert nx.is_isomorphic(G, null)
245
+
246
+
247
+ def test_lexicographic_product_size():
248
+ K5 = nx.complete_graph(5)
249
+ P5 = nx.path_graph(5)
250
+ K3 = nx.complete_graph(3)
251
+ G = nx.lexicographic_product(P5, K3)
252
+ assert nx.number_of_nodes(G) == 5 * 3
253
+ G = nx.lexicographic_product(K3, K5)
254
+ assert nx.number_of_nodes(G) == 3 * 5
255
+
256
+
257
+ def test_lexicographic_product_combinations():
258
+ P5 = nx.path_graph(5)
259
+ K3 = nx.complete_graph(3)
260
+ G = nx.lexicographic_product(P5, K3)
261
+ assert nx.number_of_nodes(G) == 5 * 3
262
+ G = nx.lexicographic_product(nx.MultiGraph(P5), K3)
263
+ assert nx.number_of_nodes(G) == 5 * 3
264
+ G = nx.lexicographic_product(P5, nx.MultiGraph(K3))
265
+ assert nx.number_of_nodes(G) == 5 * 3
266
+ G = nx.lexicographic_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
267
+ assert nx.number_of_nodes(G) == 5 * 3
268
+
269
+ # No classic easily found classic results for lexicographic product
270
+
271
+
272
+ def test_lexicographic_product_random():
273
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
274
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
275
+ GH = nx.lexicographic_product(G, H)
276
+
277
+ for u_G, u_H in GH.nodes():
278
+ for v_G, v_H in GH.nodes():
279
+ if G.has_edge(u_G, v_G) or (u_G == v_G and H.has_edge(u_H, v_H)):
280
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
281
+ else:
282
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
283
+
284
+
285
+ def test_strong_product_raises():
286
+ with pytest.raises(nx.NetworkXError):
287
+ P = nx.strong_product(nx.DiGraph(), nx.Graph())
288
+
289
+
290
+ def test_strong_product_null():
291
+ null = nx.null_graph()
292
+ empty10 = nx.empty_graph(10)
293
+ K3 = nx.complete_graph(3)
294
+ K10 = nx.complete_graph(10)
295
+ P3 = nx.path_graph(3)
296
+ P10 = nx.path_graph(10)
297
+ # null graph
298
+ G = nx.strong_product(null, null)
299
+ assert nx.is_isomorphic(G, null)
300
+ # null_graph X anything = null_graph and v.v.
301
+ G = nx.strong_product(null, empty10)
302
+ assert nx.is_isomorphic(G, null)
303
+ G = nx.strong_product(null, K3)
304
+ assert nx.is_isomorphic(G, null)
305
+ G = nx.strong_product(null, K10)
306
+ assert nx.is_isomorphic(G, null)
307
+ G = nx.strong_product(null, P3)
308
+ assert nx.is_isomorphic(G, null)
309
+ G = nx.strong_product(null, P10)
310
+ assert nx.is_isomorphic(G, null)
311
+ G = nx.strong_product(empty10, null)
312
+ assert nx.is_isomorphic(G, null)
313
+ G = nx.strong_product(K3, null)
314
+ assert nx.is_isomorphic(G, null)
315
+ G = nx.strong_product(K10, null)
316
+ assert nx.is_isomorphic(G, null)
317
+ G = nx.strong_product(P3, null)
318
+ assert nx.is_isomorphic(G, null)
319
+ G = nx.strong_product(P10, null)
320
+ assert nx.is_isomorphic(G, null)
321
+
322
+
323
+ def test_strong_product_size():
324
+ K5 = nx.complete_graph(5)
325
+ P5 = nx.path_graph(5)
326
+ K3 = nx.complete_graph(3)
327
+ G = nx.strong_product(P5, K3)
328
+ assert nx.number_of_nodes(G) == 5 * 3
329
+ G = nx.strong_product(K3, K5)
330
+ assert nx.number_of_nodes(G) == 3 * 5
331
+
332
+
333
+ def test_strong_product_combinations():
334
+ P5 = nx.path_graph(5)
335
+ K3 = nx.complete_graph(3)
336
+ G = nx.strong_product(P5, K3)
337
+ assert nx.number_of_nodes(G) == 5 * 3
338
+ G = nx.strong_product(nx.MultiGraph(P5), K3)
339
+ assert nx.number_of_nodes(G) == 5 * 3
340
+ G = nx.strong_product(P5, nx.MultiGraph(K3))
341
+ assert nx.number_of_nodes(G) == 5 * 3
342
+ G = nx.strong_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
343
+ assert nx.number_of_nodes(G) == 5 * 3
344
+
345
+ # No classic easily found classic results for strong product
346
+
347
+
348
+ def test_strong_product_random():
349
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
350
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
351
+ GH = nx.strong_product(G, H)
352
+
353
+ for u_G, u_H in GH.nodes():
354
+ for v_G, v_H in GH.nodes():
355
+ if (
356
+ (u_G == v_G and H.has_edge(u_H, v_H))
357
+ or (u_H == v_H and G.has_edge(u_G, v_G))
358
+ or (G.has_edge(u_G, v_G) and H.has_edge(u_H, v_H))
359
+ ):
360
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
361
+ else:
362
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
363
+
364
+
365
+ def test_graph_power_raises():
366
+ with pytest.raises(nx.NetworkXNotImplemented):
367
+ nx.power(nx.MultiDiGraph(), 2)
368
+
369
+
370
+ def test_graph_power():
371
+ # wikipedia example for graph power
372
+ G = nx.cycle_graph(7)
373
+ G.add_edge(6, 7)
374
+ G.add_edge(7, 8)
375
+ G.add_edge(8, 9)
376
+ G.add_edge(9, 2)
377
+ H = nx.power(G, 2)
378
+
379
+ assert edges_equal(
380
+ list(H.edges()),
381
+ [
382
+ (0, 1),
383
+ (0, 2),
384
+ (0, 5),
385
+ (0, 6),
386
+ (0, 7),
387
+ (1, 9),
388
+ (1, 2),
389
+ (1, 3),
390
+ (1, 6),
391
+ (2, 3),
392
+ (2, 4),
393
+ (2, 8),
394
+ (2, 9),
395
+ (3, 4),
396
+ (3, 5),
397
+ (3, 9),
398
+ (4, 5),
399
+ (4, 6),
400
+ (5, 6),
401
+ (5, 7),
402
+ (6, 7),
403
+ (6, 8),
404
+ (7, 8),
405
+ (7, 9),
406
+ (8, 9),
407
+ ],
408
+ )
409
+
410
+
411
+ def test_graph_power_negative():
412
+ with pytest.raises(ValueError):
413
+ nx.power(nx.Graph(), -1)
414
+
415
+
416
+ def test_rooted_product_raises():
417
+ with pytest.raises(nx.NodeNotFound):
418
+ nx.rooted_product(nx.Graph(), nx.path_graph(2), 10)
419
+
420
+
421
+ def test_rooted_product():
422
+ G = nx.cycle_graph(5)
423
+ H = nx.Graph()
424
+ H.add_edges_from([("a", "b"), ("b", "c"), ("b", "d")])
425
+ R = nx.rooted_product(G, H, "a")
426
+ assert len(R) == len(G) * len(H)
427
+ assert R.size() == G.size() + len(G) * H.size()
428
+
429
+
430
+ def test_corona_product():
431
+ G = nx.cycle_graph(3)
432
+ H = nx.path_graph(2)
433
+ C = nx.corona_product(G, H)
434
+ assert len(C) == (len(G) * len(H)) + len(G)
435
+ assert C.size() == G.size() + len(G) * H.size() + len(G) * len(H)
436
+
437
+
438
+ def test_modular_product():
439
+ G = nx.path_graph(3)
440
+ H = nx.path_graph(4)
441
+ M = nx.modular_product(G, H)
442
+ assert len(M) == len(G) * len(H)
443
+
444
+ assert edges_equal(
445
+ list(M.edges()),
446
+ [
447
+ ((0, 0), (1, 1)),
448
+ ((0, 0), (2, 2)),
449
+ ((0, 0), (2, 3)),
450
+ ((0, 1), (1, 0)),
451
+ ((0, 1), (1, 2)),
452
+ ((0, 1), (2, 3)),
453
+ ((0, 2), (1, 1)),
454
+ ((0, 2), (1, 3)),
455
+ ((0, 2), (2, 0)),
456
+ ((0, 3), (1, 2)),
457
+ ((0, 3), (2, 0)),
458
+ ((0, 3), (2, 1)),
459
+ ((1, 0), (2, 1)),
460
+ ((1, 1), (2, 0)),
461
+ ((1, 1), (2, 2)),
462
+ ((1, 2), (2, 1)),
463
+ ((1, 2), (2, 3)),
464
+ ((1, 3), (2, 2)),
465
+ ],
466
+ )
467
+
468
+
469
+ def test_modular_product_raises():
470
+ G = nx.Graph([(0, 1), (1, 2), (2, 0)])
471
+ H = nx.Graph([(0, 1), (1, 2), (2, 0)])
472
+ DG = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
473
+ DH = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
474
+ with pytest.raises(nx.NetworkXNotImplemented):
475
+ nx.modular_product(G, DH)
476
+ with pytest.raises(nx.NetworkXNotImplemented):
477
+ nx.modular_product(DG, H)
478
+ with pytest.raises(nx.NetworkXNotImplemented):
479
+ nx.modular_product(DG, DH)
480
+
481
+ MG = nx.MultiGraph([(0, 1), (1, 2), (2, 0), (0, 1)])
482
+ MH = nx.MultiGraph([(0, 1), (1, 2), (2, 0), (0, 1)])
483
+ with pytest.raises(nx.NetworkXNotImplemented):
484
+ nx.modular_product(G, MH)
485
+ with pytest.raises(nx.NetworkXNotImplemented):
486
+ nx.modular_product(MG, H)
487
+ with pytest.raises(nx.NetworkXNotImplemented):
488
+ nx.modular_product(MG, MH)
489
+ with pytest.raises(nx.NetworkXNotImplemented):
490
+ # check multigraph with no multiedges
491
+ nx.modular_product(nx.MultiGraph(G), H)
janus/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_unary.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_complement():
7
+ null = nx.null_graph()
8
+ empty1 = nx.empty_graph(1)
9
+ empty10 = nx.empty_graph(10)
10
+ K3 = nx.complete_graph(3)
11
+ K5 = nx.complete_graph(5)
12
+ K10 = nx.complete_graph(10)
13
+ P2 = nx.path_graph(2)
14
+ P3 = nx.path_graph(3)
15
+ P5 = nx.path_graph(5)
16
+ P10 = nx.path_graph(10)
17
+ # complement of the complete graph is empty
18
+
19
+ G = nx.complement(K3)
20
+ assert nx.is_isomorphic(G, nx.empty_graph(3))
21
+ G = nx.complement(K5)
22
+ assert nx.is_isomorphic(G, nx.empty_graph(5))
23
+ # for any G, G=complement(complement(G))
24
+ P3cc = nx.complement(nx.complement(P3))
25
+ assert nx.is_isomorphic(P3, P3cc)
26
+ nullcc = nx.complement(nx.complement(null))
27
+ assert nx.is_isomorphic(null, nullcc)
28
+ b = nx.bull_graph()
29
+ bcc = nx.complement(nx.complement(b))
30
+ assert nx.is_isomorphic(b, bcc)
31
+
32
+
33
+ def test_complement_2():
34
+ G1 = nx.DiGraph()
35
+ G1.add_edge("A", "B")
36
+ G1.add_edge("A", "C")
37
+ G1.add_edge("A", "D")
38
+ G1C = nx.complement(G1)
39
+ assert sorted(G1C.edges()) == [
40
+ ("B", "A"),
41
+ ("B", "C"),
42
+ ("B", "D"),
43
+ ("C", "A"),
44
+ ("C", "B"),
45
+ ("C", "D"),
46
+ ("D", "A"),
47
+ ("D", "B"),
48
+ ("D", "C"),
49
+ ]
50
+
51
+
52
+ def test_reverse1():
53
+ # Other tests for reverse are done by the DiGraph and MultiDigraph.
54
+ G1 = nx.Graph()
55
+ pytest.raises(nx.NetworkXError, nx.reverse, G1)
janus/lib/python3.10/site-packages/networkx/algorithms/operators/unary.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unary operations on graphs"""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["complement", "reverse"]
6
+
7
+
8
+ @nx._dispatchable(returns_graph=True)
9
+ def complement(G):
10
+ """Returns the graph complement of G.
11
+
12
+ Parameters
13
+ ----------
14
+ G : graph
15
+ A NetworkX graph
16
+
17
+ Returns
18
+ -------
19
+ GC : A new graph.
20
+
21
+ Notes
22
+ -----
23
+ Note that `complement` does not create self-loops and also
24
+ does not produce parallel edges for MultiGraphs.
25
+
26
+ Graph, node, and edge data are not propagated to the new graph.
27
+
28
+ Examples
29
+ --------
30
+ >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
31
+ >>> G_complement = nx.complement(G)
32
+ >>> G_complement.edges() # This shows the edges of the complemented graph
33
+ EdgeView([(1, 4), (1, 5), (2, 4), (2, 5), (4, 5)])
34
+
35
+ """
36
+ R = G.__class__()
37
+ R.add_nodes_from(G)
38
+ R.add_edges_from(
39
+ ((n, n2) for n, nbrs in G.adjacency() for n2 in G if n2 not in nbrs if n != n2)
40
+ )
41
+ return R
42
+
43
+
44
+ @nx._dispatchable(returns_graph=True)
45
+ def reverse(G, copy=True):
46
+ """Returns the reverse directed graph of G.
47
+
48
+ Parameters
49
+ ----------
50
+ G : directed graph
51
+ A NetworkX directed graph
52
+ copy : bool
53
+ If True, then a new graph is returned. If False, then the graph is
54
+ reversed in place.
55
+
56
+ Returns
57
+ -------
58
+ H : directed graph
59
+ The reversed G.
60
+
61
+ Raises
62
+ ------
63
+ NetworkXError
64
+ If graph is undirected.
65
+
66
+ Examples
67
+ --------
68
+ >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
69
+ >>> G_reversed = nx.reverse(G)
70
+ >>> G_reversed.edges()
71
+ OutEdgeView([(2, 1), (3, 1), (3, 2), (4, 3), (5, 3)])
72
+
73
+ """
74
+ if not G.is_directed():
75
+ raise nx.NetworkXError("Cannot reverse an undirected graph.")
76
+ else:
77
+ return G.reverse(copy=copy)
janus/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (295 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc ADDED
Binary file (40.9 kB). View file
 
janus/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc ADDED
Binary file (22.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/drawing/layout.py ADDED
@@ -0,0 +1,1630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ******
3
+ Layout
4
+ ******
5
+
6
+ Node positioning algorithms for graph drawing.
7
+
8
+ For `random_layout()` the possible resulting shape
9
+ is a square of side [0, scale] (default: [0, 1])
10
+ Changing `center` shifts the layout by that amount.
11
+
12
+ For the other layout routines, the extent is
13
+ [center - scale, center + scale] (default: [-1, 1]).
14
+
15
+ Warning: Most layout routines have only been tested in 2-dimensions.
16
+
17
+ """
18
+
19
+ import networkx as nx
20
+ from networkx.utils import np_random_state
21
+
22
+ __all__ = [
23
+ "bipartite_layout",
24
+ "circular_layout",
25
+ "forceatlas2_layout",
26
+ "kamada_kawai_layout",
27
+ "random_layout",
28
+ "rescale_layout",
29
+ "rescale_layout_dict",
30
+ "shell_layout",
31
+ "spring_layout",
32
+ "spectral_layout",
33
+ "planar_layout",
34
+ "fruchterman_reingold_layout",
35
+ "spiral_layout",
36
+ "multipartite_layout",
37
+ "bfs_layout",
38
+ "arf_layout",
39
+ ]
40
+
41
+
42
+ def _process_params(G, center, dim):
43
+ # Some boilerplate code.
44
+ import numpy as np
45
+
46
+ if not isinstance(G, nx.Graph):
47
+ empty_graph = nx.Graph()
48
+ empty_graph.add_nodes_from(G)
49
+ G = empty_graph
50
+
51
+ if center is None:
52
+ center = np.zeros(dim)
53
+ else:
54
+ center = np.asarray(center)
55
+
56
+ if len(center) != dim:
57
+ msg = "length of center coordinates must match dimension of layout"
58
+ raise ValueError(msg)
59
+
60
+ return G, center
61
+
62
+
63
+ @np_random_state(3)
64
+ def random_layout(G, center=None, dim=2, seed=None):
65
+ """Position nodes uniformly at random in the unit square.
66
+
67
+ For every node, a position is generated by choosing each of dim
68
+ coordinates uniformly at random on the interval [0.0, 1.0).
69
+
70
+ NumPy (http://scipy.org) is required for this function.
71
+
72
+ Parameters
73
+ ----------
74
+ G : NetworkX graph or list of nodes
75
+ A position will be assigned to every node in G.
76
+
77
+ center : array-like or None
78
+ Coordinate pair around which to center the layout.
79
+
80
+ dim : int
81
+ Dimension of layout.
82
+
83
+ seed : int, RandomState instance or None optional (default=None)
84
+ Set the random state for deterministic node layouts.
85
+ If int, `seed` is the seed used by the random number generator,
86
+ if numpy.random.RandomState instance, `seed` is the random
87
+ number generator,
88
+ if None, the random number generator is the RandomState instance used
89
+ by numpy.random.
90
+
91
+ Returns
92
+ -------
93
+ pos : dict
94
+ A dictionary of positions keyed by node
95
+
96
+ Examples
97
+ --------
98
+ >>> G = nx.lollipop_graph(4, 3)
99
+ >>> pos = nx.random_layout(G)
100
+
101
+ """
102
+ import numpy as np
103
+
104
+ G, center = _process_params(G, center, dim)
105
+ pos = seed.rand(len(G), dim) + center
106
+ pos = pos.astype(np.float32)
107
+ pos = dict(zip(G, pos))
108
+
109
+ return pos
110
+
111
+
112
+ def circular_layout(G, scale=1, center=None, dim=2):
113
+ # dim=2 only
114
+ """Position nodes on a circle.
115
+
116
+ Parameters
117
+ ----------
118
+ G : NetworkX graph or list of nodes
119
+ A position will be assigned to every node in G.
120
+
121
+ scale : number (default: 1)
122
+ Scale factor for positions.
123
+
124
+ center : array-like or None
125
+ Coordinate pair around which to center the layout.
126
+
127
+ dim : int
128
+ Dimension of layout.
129
+ If dim>2, the remaining dimensions are set to zero
130
+ in the returned positions.
131
+ If dim<2, a ValueError is raised.
132
+
133
+ Returns
134
+ -------
135
+ pos : dict
136
+ A dictionary of positions keyed by node
137
+
138
+ Raises
139
+ ------
140
+ ValueError
141
+ If dim < 2
142
+
143
+ Examples
144
+ --------
145
+ >>> G = nx.path_graph(4)
146
+ >>> pos = nx.circular_layout(G)
147
+
148
+ Notes
149
+ -----
150
+ This algorithm currently only works in two dimensions and does not
151
+ try to minimize edge crossings.
152
+
153
+ """
154
+ import numpy as np
155
+
156
+ if dim < 2:
157
+ raise ValueError("cannot handle dimensions < 2")
158
+
159
+ G, center = _process_params(G, center, dim)
160
+
161
+ paddims = max(0, (dim - 2))
162
+
163
+ if len(G) == 0:
164
+ pos = {}
165
+ elif len(G) == 1:
166
+ pos = {nx.utils.arbitrary_element(G): center}
167
+ else:
168
+ # Discard the extra angle since it matches 0 radians.
169
+ theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
170
+ theta = theta.astype(np.float32)
171
+ pos = np.column_stack(
172
+ [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
173
+ )
174
+ pos = rescale_layout(pos, scale=scale) + center
175
+ pos = dict(zip(G, pos))
176
+
177
+ return pos
178
+
179
+
180
+ def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2):
181
+ """Position nodes in concentric circles.
182
+
183
+ Parameters
184
+ ----------
185
+ G : NetworkX graph or list of nodes
186
+ A position will be assigned to every node in G.
187
+
188
+ nlist : list of lists
189
+ List of node lists for each shell.
190
+
191
+ rotate : angle in radians (default=pi/len(nlist))
192
+ Angle by which to rotate the starting position of each shell
193
+ relative to the starting position of the previous shell.
194
+ To recreate behavior before v2.5 use rotate=0.
195
+
196
+ scale : number (default: 1)
197
+ Scale factor for positions.
198
+
199
+ center : array-like or None
200
+ Coordinate pair around which to center the layout.
201
+
202
+ dim : int
203
+ Dimension of layout, currently only dim=2 is supported.
204
+ Other dimension values result in a ValueError.
205
+
206
+ Returns
207
+ -------
208
+ pos : dict
209
+ A dictionary of positions keyed by node
210
+
211
+ Raises
212
+ ------
213
+ ValueError
214
+ If dim != 2
215
+
216
+ Examples
217
+ --------
218
+ >>> G = nx.path_graph(4)
219
+ >>> shells = [[0], [1, 2, 3]]
220
+ >>> pos = nx.shell_layout(G, shells)
221
+
222
+ Notes
223
+ -----
224
+ This algorithm currently only works in two dimensions and does not
225
+ try to minimize edge crossings.
226
+
227
+ """
228
+ import numpy as np
229
+
230
+ if dim != 2:
231
+ raise ValueError("can only handle 2 dimensions")
232
+
233
+ G, center = _process_params(G, center, dim)
234
+
235
+ if len(G) == 0:
236
+ return {}
237
+ if len(G) == 1:
238
+ return {nx.utils.arbitrary_element(G): center}
239
+
240
+ if nlist is None:
241
+ # draw the whole graph in one shell
242
+ nlist = [list(G)]
243
+
244
+ radius_bump = scale / len(nlist)
245
+
246
+ if len(nlist[0]) == 1:
247
+ # single node at center
248
+ radius = 0.0
249
+ else:
250
+ # else start at r=1
251
+ radius = radius_bump
252
+
253
+ if rotate is None:
254
+ rotate = np.pi / len(nlist)
255
+ first_theta = rotate
256
+ npos = {}
257
+ for nodes in nlist:
258
+ # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
259
+ theta = (
260
+ np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
261
+ + first_theta
262
+ )
263
+ pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
264
+ npos.update(zip(nodes, pos))
265
+ radius += radius_bump
266
+ first_theta += rotate
267
+
268
+ return npos
269
+
270
+
271
+ def bipartite_layout(
272
+ G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3
273
+ ):
274
+ """Position nodes in two straight lines.
275
+
276
+ Parameters
277
+ ----------
278
+ G : NetworkX graph or list of nodes
279
+ A position will be assigned to every node in G.
280
+
281
+ nodes : list or container
282
+ Nodes in one node set of the bipartite graph.
283
+ This set will be placed on left or top.
284
+
285
+ align : string (default='vertical')
286
+ The alignment of nodes. Vertical or horizontal.
287
+
288
+ scale : number (default: 1)
289
+ Scale factor for positions.
290
+
291
+ center : array-like or None
292
+ Coordinate pair around which to center the layout.
293
+
294
+ aspect_ratio : number (default=4/3):
295
+ The ratio of the width to the height of the layout.
296
+
297
+ Returns
298
+ -------
299
+ pos : dict
300
+ A dictionary of positions keyed by node.
301
+
302
+ Examples
303
+ --------
304
+ >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
305
+ >>> top = nx.bipartite.sets(G)[0]
306
+ >>> pos = nx.bipartite_layout(G, top)
307
+
308
+ Notes
309
+ -----
310
+ This algorithm currently only works in two dimensions and does not
311
+ try to minimize edge crossings.
312
+
313
+ """
314
+
315
+ import numpy as np
316
+
317
+ if align not in ("vertical", "horizontal"):
318
+ msg = "align must be either vertical or horizontal."
319
+ raise ValueError(msg)
320
+
321
+ G, center = _process_params(G, center=center, dim=2)
322
+ if len(G) == 0:
323
+ return {}
324
+
325
+ height = 1
326
+ width = aspect_ratio * height
327
+ offset = (width / 2, height / 2)
328
+
329
+ top = dict.fromkeys(nodes)
330
+ bottom = [v for v in G if v not in top]
331
+ nodes = list(top) + bottom
332
+
333
+ left_xs = np.repeat(0, len(top))
334
+ right_xs = np.repeat(width, len(bottom))
335
+ left_ys = np.linspace(0, height, len(top))
336
+ right_ys = np.linspace(0, height, len(bottom))
337
+
338
+ top_pos = np.column_stack([left_xs, left_ys]) - offset
339
+ bottom_pos = np.column_stack([right_xs, right_ys]) - offset
340
+
341
+ pos = np.concatenate([top_pos, bottom_pos])
342
+ pos = rescale_layout(pos, scale=scale) + center
343
+ if align == "horizontal":
344
+ pos = pos[:, ::-1] # swap x and y coords
345
+ pos = dict(zip(nodes, pos))
346
+ return pos
347
+
348
+
349
+ @np_random_state(10)
350
+ def spring_layout(
351
+ G,
352
+ k=None,
353
+ pos=None,
354
+ fixed=None,
355
+ iterations=50,
356
+ threshold=1e-4,
357
+ weight="weight",
358
+ scale=1,
359
+ center=None,
360
+ dim=2,
361
+ seed=None,
362
+ ):
363
+ """Position nodes using Fruchterman-Reingold force-directed algorithm.
364
+
365
+ The algorithm simulates a force-directed representation of the network
366
+ treating edges as springs holding nodes close, while treating nodes
367
+ as repelling objects, sometimes called an anti-gravity force.
368
+ Simulation continues until the positions are close to an equilibrium.
369
+
370
+ There are some hard-coded values: minimal distance between
371
+ nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
372
+ During the simulation, `k` helps determine the distance between nodes,
373
+ though `scale` and `center` determine the size and place after
374
+ rescaling occurs at the end of the simulation.
375
+
376
+ Fixing some nodes doesn't allow them to move in the simulation.
377
+ It also turns off the rescaling feature at the simulation's end.
378
+ In addition, setting `scale` to `None` turns off rescaling.
379
+
380
+ Parameters
381
+ ----------
382
+ G : NetworkX graph or list of nodes
383
+ A position will be assigned to every node in G.
384
+
385
+ k : float (default=None)
386
+ Optimal distance between nodes. If None the distance is set to
387
+ 1/sqrt(n) where n is the number of nodes. Increase this value
388
+ to move nodes farther apart.
389
+
390
+ pos : dict or None optional (default=None)
391
+ Initial positions for nodes as a dictionary with node as keys
392
+ and values as a coordinate list or tuple. If None, then use
393
+ random initial positions.
394
+
395
+ fixed : list or None optional (default=None)
396
+ Nodes to keep fixed at initial position.
397
+ Nodes not in ``G.nodes`` are ignored.
398
+ ValueError raised if `fixed` specified and `pos` not.
399
+
400
+ iterations : int optional (default=50)
401
+ Maximum number of iterations taken
402
+
403
+ threshold: float optional (default = 1e-4)
404
+ Threshold for relative error in node position changes.
405
+ The iteration stops if the error is below this threshold.
406
+
407
+ weight : string or None optional (default='weight')
408
+ The edge attribute that holds the numerical value used for
409
+ the edge weight. Larger means a stronger attractive force.
410
+ If None, then all edge weights are 1.
411
+
412
+ scale : number or None (default: 1)
413
+ Scale factor for positions. Not used unless `fixed is None`.
414
+ If scale is None, no rescaling is performed.
415
+
416
+ center : array-like or None
417
+ Coordinate pair around which to center the layout.
418
+ Not used unless `fixed is None`.
419
+
420
+ dim : int
421
+ Dimension of layout.
422
+
423
+ seed : int, RandomState instance or None optional (default=None)
424
+ Used only for the initial positions in the algorithm.
425
+ Set the random state for deterministic node layouts.
426
+ If int, `seed` is the seed used by the random number generator,
427
+ if numpy.random.RandomState instance, `seed` is the random
428
+ number generator,
429
+ if None, the random number generator is the RandomState instance used
430
+ by numpy.random.
431
+
432
+ Returns
433
+ -------
434
+ pos : dict
435
+ A dictionary of positions keyed by node
436
+
437
+ Examples
438
+ --------
439
+ >>> G = nx.path_graph(4)
440
+ >>> pos = nx.spring_layout(G)
441
+
442
+ # The same using longer but equivalent function name
443
+ >>> pos = nx.fruchterman_reingold_layout(G)
444
+ """
445
+ import numpy as np
446
+
447
+ G, center = _process_params(G, center, dim)
448
+
449
+ if fixed is not None:
450
+ if pos is None:
451
+ raise ValueError("nodes are fixed without positions given")
452
+ for node in fixed:
453
+ if node not in pos:
454
+ raise ValueError("nodes are fixed without positions given")
455
+ nfixed = {node: i for i, node in enumerate(G)}
456
+ fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
457
+
458
+ if pos is not None:
459
+ # Determine size of existing domain to adjust initial positions
460
+ dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
461
+ if dom_size == 0:
462
+ dom_size = 1
463
+ pos_arr = seed.rand(len(G), dim) * dom_size + center
464
+
465
+ for i, n in enumerate(G):
466
+ if n in pos:
467
+ pos_arr[i] = np.asarray(pos[n])
468
+ else:
469
+ pos_arr = None
470
+ dom_size = 1
471
+
472
+ if len(G) == 0:
473
+ return {}
474
+ if len(G) == 1:
475
+ return {nx.utils.arbitrary_element(G.nodes()): center}
476
+
477
+ try:
478
+ # Sparse matrix
479
+ if len(G) < 500: # sparse solver for large graphs
480
+ raise ValueError
481
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
482
+ if k is None and fixed is not None:
483
+ # We must adjust k by domain size for layouts not near 1x1
484
+ nnodes, _ = A.shape
485
+ k = dom_size / np.sqrt(nnodes)
486
+ pos = _sparse_fruchterman_reingold(
487
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
488
+ )
489
+ except ValueError:
490
+ A = nx.to_numpy_array(G, weight=weight)
491
+ if k is None and fixed is not None:
492
+ # We must adjust k by domain size for layouts not near 1x1
493
+ nnodes, _ = A.shape
494
+ k = dom_size / np.sqrt(nnodes)
495
+ pos = _fruchterman_reingold(
496
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
497
+ )
498
+ if fixed is None and scale is not None:
499
+ pos = rescale_layout(pos, scale=scale) + center
500
+ pos = dict(zip(G, pos))
501
+ return pos
502
+
503
+
504
+ fruchterman_reingold_layout = spring_layout
505
+
506
+
507
+ @np_random_state(7)
508
+ def _fruchterman_reingold(
509
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
510
+ ):
511
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
512
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
513
+ import numpy as np
514
+
515
+ try:
516
+ nnodes, _ = A.shape
517
+ except AttributeError as err:
518
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
519
+ raise nx.NetworkXError(msg) from err
520
+
521
+ if pos is None:
522
+ # random initial positions
523
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
524
+ else:
525
+ # make sure positions are of same type as matrix
526
+ pos = pos.astype(A.dtype)
527
+
528
+ # optimal distance between nodes
529
+ if k is None:
530
+ k = np.sqrt(1.0 / nnodes)
531
+ # the initial "temperature" is about .1 of domain area (=1x1)
532
+ # this is the largest step allowed in the dynamics.
533
+ # We need to calculate this in case our fixed positions force our domain
534
+ # to be much bigger than 1x1
535
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
536
+ # simple cooling scheme.
537
+ # linearly step down by dt on each iteration so last iteration is size dt.
538
+ dt = t / (iterations + 1)
539
+ delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
540
+ # the inscrutable (but fast) version
541
+ # this is still O(V^2)
542
+ # could use multilevel methods to speed this up significantly
543
+ for iteration in range(iterations):
544
+ # matrix of difference between points
545
+ delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
546
+ # distance between points
547
+ distance = np.linalg.norm(delta, axis=-1)
548
+ # enforce minimum distance of 0.01
549
+ np.clip(distance, 0.01, None, out=distance)
550
+ # displacement "force"
551
+ displacement = np.einsum(
552
+ "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
553
+ )
554
+ # update positions
555
+ length = np.linalg.norm(displacement, axis=-1)
556
+ length = np.where(length < 0.01, 0.1, length)
557
+ delta_pos = np.einsum("ij,i->ij", displacement, t / length)
558
+ if fixed is not None:
559
+ # don't change positions of fixed nodes
560
+ delta_pos[fixed] = 0.0
561
+ pos += delta_pos
562
+ # cool temperature
563
+ t -= dt
564
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
565
+ break
566
+ return pos
567
+
568
+
569
+ @np_random_state(7)
570
+ def _sparse_fruchterman_reingold(
571
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
572
+ ):
573
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
574
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
575
+ # Sparse version
576
+ import numpy as np
577
+ import scipy as sp
578
+
579
+ try:
580
+ nnodes, _ = A.shape
581
+ except AttributeError as err:
582
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
583
+ raise nx.NetworkXError(msg) from err
584
+ # make sure we have a LIst of Lists representation
585
+ try:
586
+ A = A.tolil()
587
+ except AttributeError:
588
+ A = (sp.sparse.coo_array(A)).tolil()
589
+
590
+ if pos is None:
591
+ # random initial positions
592
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
593
+ else:
594
+ # make sure positions are of same type as matrix
595
+ pos = pos.astype(A.dtype)
596
+
597
+ # no fixed nodes
598
+ if fixed is None:
599
+ fixed = []
600
+
601
+ # optimal distance between nodes
602
+ if k is None:
603
+ k = np.sqrt(1.0 / nnodes)
604
+ # the initial "temperature" is about .1 of domain area (=1x1)
605
+ # this is the largest step allowed in the dynamics.
606
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
607
+ # simple cooling scheme.
608
+ # linearly step down by dt on each iteration so last iteration is size dt.
609
+ dt = t / (iterations + 1)
610
+
611
+ displacement = np.zeros((dim, nnodes))
612
+ for iteration in range(iterations):
613
+ displacement *= 0
614
+ # loop over rows
615
+ for i in range(A.shape[0]):
616
+ if i in fixed:
617
+ continue
618
+ # difference between this row's node position and all others
619
+ delta = (pos[i] - pos).T
620
+ # distance between points
621
+ distance = np.sqrt((delta**2).sum(axis=0))
622
+ # enforce minimum distance of 0.01
623
+ distance = np.where(distance < 0.01, 0.01, distance)
624
+ # the adjacency matrix row
625
+ Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
626
+ # displacement "force"
627
+ displacement[:, i] += (
628
+ delta * (k * k / distance**2 - Ai * distance / k)
629
+ ).sum(axis=1)
630
+ # update positions
631
+ length = np.sqrt((displacement**2).sum(axis=0))
632
+ length = np.where(length < 0.01, 0.1, length)
633
+ delta_pos = (displacement * t / length).T
634
+ pos += delta_pos
635
+ # cool temperature
636
+ t -= dt
637
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
638
+ break
639
+ return pos
640
+
641
+
642
+ def kamada_kawai_layout(
643
+ G, dist=None, pos=None, weight="weight", scale=1, center=None, dim=2
644
+ ):
645
+ """Position nodes using Kamada-Kawai path-length cost-function.
646
+
647
+ Parameters
648
+ ----------
649
+ G : NetworkX graph or list of nodes
650
+ A position will be assigned to every node in G.
651
+
652
+ dist : dict (default=None)
653
+ A two-level dictionary of optimal distances between nodes,
654
+ indexed by source and destination node.
655
+ If None, the distance is computed using shortest_path_length().
656
+
657
+ pos : dict or None optional (default=None)
658
+ Initial positions for nodes as a dictionary with node as keys
659
+ and values as a coordinate list or tuple. If None, then use
660
+ circular_layout() for dim >= 2 and a linear layout for dim == 1.
661
+
662
+ weight : string or None optional (default='weight')
663
+ The edge attribute that holds the numerical value used for
664
+ the edge weight. If None, then all edge weights are 1.
665
+
666
+ scale : number (default: 1)
667
+ Scale factor for positions.
668
+
669
+ center : array-like or None
670
+ Coordinate pair around which to center the layout.
671
+
672
+ dim : int
673
+ Dimension of layout.
674
+
675
+ Returns
676
+ -------
677
+ pos : dict
678
+ A dictionary of positions keyed by node
679
+
680
+ Examples
681
+ --------
682
+ >>> G = nx.path_graph(4)
683
+ >>> pos = nx.kamada_kawai_layout(G)
684
+ """
685
+ import numpy as np
686
+
687
+ G, center = _process_params(G, center, dim)
688
+ nNodes = len(G)
689
+ if nNodes == 0:
690
+ return {}
691
+
692
+ if dist is None:
693
+ dist = dict(nx.shortest_path_length(G, weight=weight))
694
+ dist_mtx = 1e6 * np.ones((nNodes, nNodes))
695
+ for row, nr in enumerate(G):
696
+ if nr not in dist:
697
+ continue
698
+ rdist = dist[nr]
699
+ for col, nc in enumerate(G):
700
+ if nc not in rdist:
701
+ continue
702
+ dist_mtx[row][col] = rdist[nc]
703
+
704
+ if pos is None:
705
+ if dim >= 3:
706
+ pos = random_layout(G, dim=dim)
707
+ elif dim == 2:
708
+ pos = circular_layout(G, dim=dim)
709
+ else:
710
+ pos = dict(zip(G, np.linspace(0, 1, len(G))))
711
+ pos_arr = np.array([pos[n] for n in G])
712
+
713
+ pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
714
+
715
+ pos = rescale_layout(pos, scale=scale) + center
716
+ return dict(zip(G, pos))
717
+
718
+
719
+ def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
720
+ # Anneal node locations based on the Kamada-Kawai cost-function,
721
+ # using the supplied matrix of preferred inter-node distances,
722
+ # and starting locations.
723
+
724
+ import numpy as np
725
+ import scipy as sp
726
+
727
+ meanwt = 1e-3
728
+ costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
729
+
730
+ optresult = sp.optimize.minimize(
731
+ _kamada_kawai_costfn,
732
+ pos_arr.ravel(),
733
+ method="L-BFGS-B",
734
+ args=costargs,
735
+ jac=True,
736
+ )
737
+
738
+ return optresult.x.reshape((-1, dim))
739
+
740
+
741
+ def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
742
+ # Cost-function and gradient for Kamada-Kawai layout algorithm
743
+ nNodes = invdist.shape[0]
744
+ pos_arr = pos_vec.reshape((nNodes, dim))
745
+
746
+ delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
747
+ nodesep = np.linalg.norm(delta, axis=-1)
748
+ direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
749
+
750
+ offset = nodesep * invdist - 1.0
751
+ offset[np.diag_indices(nNodes)] = 0
752
+
753
+ cost = 0.5 * np.sum(offset**2)
754
+ grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
755
+ "ij,ij,ijk->jk", invdist, offset, direction
756
+ )
757
+
758
+ # Additional parabolic term to encourage mean position to be near origin:
759
+ sumpos = np.sum(pos_arr, axis=0)
760
+ cost += 0.5 * meanweight * np.sum(sumpos**2)
761
+ grad += meanweight * sumpos
762
+
763
+ return (cost, grad.ravel())
764
+
765
+
766
+ def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
767
+ """Position nodes using the eigenvectors of the graph Laplacian.
768
+
769
+ Using the unnormalized Laplacian, the layout shows possible clusters of
770
+ nodes which are an approximation of the ratio cut. If dim is the number of
771
+ dimensions then the positions are the entries of the dim eigenvectors
772
+ corresponding to the ascending eigenvalues starting from the second one.
773
+
774
+ Parameters
775
+ ----------
776
+ G : NetworkX graph or list of nodes
777
+ A position will be assigned to every node in G.
778
+
779
+ weight : string or None optional (default='weight')
780
+ The edge attribute that holds the numerical value used for
781
+ the edge weight. If None, then all edge weights are 1.
782
+
783
+ scale : number (default: 1)
784
+ Scale factor for positions.
785
+
786
+ center : array-like or None
787
+ Coordinate pair around which to center the layout.
788
+
789
+ dim : int
790
+ Dimension of layout.
791
+
792
+ Returns
793
+ -------
794
+ pos : dict
795
+ A dictionary of positions keyed by node
796
+
797
+ Examples
798
+ --------
799
+ >>> G = nx.path_graph(4)
800
+ >>> pos = nx.spectral_layout(G)
801
+
802
+ Notes
803
+ -----
804
+ Directed graphs will be considered as undirected graphs when
805
+ positioning the nodes.
806
+
807
+ For larger graphs (>500 nodes) this will use the SciPy sparse
808
+ eigenvalue solver (ARPACK).
809
+ """
810
+ # handle some special cases that break the eigensolvers
811
+ import numpy as np
812
+
813
+ G, center = _process_params(G, center, dim)
814
+
815
+ if len(G) <= 2:
816
+ if len(G) == 0:
817
+ pos = np.array([])
818
+ elif len(G) == 1:
819
+ pos = np.array([center])
820
+ else:
821
+ pos = np.array([np.zeros(dim), np.array(center) * 2.0])
822
+ return dict(zip(G, pos))
823
+ try:
824
+ # Sparse matrix
825
+ if len(G) < 500: # dense solver is faster for small graphs
826
+ raise ValueError
827
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
828
+ # Symmetrize directed graphs
829
+ if G.is_directed():
830
+ A = A + np.transpose(A)
831
+ pos = _sparse_spectral(A, dim)
832
+ except (ImportError, ValueError):
833
+ # Dense matrix
834
+ A = nx.to_numpy_array(G, weight=weight)
835
+ # Symmetrize directed graphs
836
+ if G.is_directed():
837
+ A += A.T
838
+ pos = _spectral(A, dim)
839
+
840
+ pos = rescale_layout(pos, scale=scale) + center
841
+ pos = dict(zip(G, pos))
842
+ return pos
843
+
844
+
845
+ def _spectral(A, dim=2):
846
+ # Input adjacency matrix A
847
+ # Uses dense eigenvalue solver from numpy
848
+ import numpy as np
849
+
850
+ try:
851
+ nnodes, _ = A.shape
852
+ except AttributeError as err:
853
+ msg = "spectral() takes an adjacency matrix as input"
854
+ raise nx.NetworkXError(msg) from err
855
+
856
+ # form Laplacian matrix where D is diagonal of degrees
857
+ D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
858
+ L = D - A
859
+
860
+ eigenvalues, eigenvectors = np.linalg.eig(L)
861
+ # sort and keep smallest nonzero
862
+ index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
863
+ return np.real(eigenvectors[:, index])
864
+
865
+
866
+ def _sparse_spectral(A, dim=2):
867
+ # Input adjacency matrix A
868
+ # Uses sparse eigenvalue solver from scipy
869
+ # Could use multilevel methods here, see Koren "On spectral graph drawing"
870
+ import numpy as np
871
+ import scipy as sp
872
+
873
+ try:
874
+ nnodes, _ = A.shape
875
+ except AttributeError as err:
876
+ msg = "sparse_spectral() takes an adjacency matrix as input"
877
+ raise nx.NetworkXError(msg) from err
878
+
879
+ # form Laplacian matrix
880
+ # TODO: Rm csr_array wrapper in favor of spdiags array constructor when available
881
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, nnodes, nnodes))
882
+ L = D - A
883
+
884
+ k = dim + 1
885
+ # number of Lanczos vectors for ARPACK solver.What is the right scaling?
886
+ ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
887
+ # return smallest k eigenvalues and eigenvectors
888
+ eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
889
+ index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
890
+ return np.real(eigenvectors[:, index])
891
+
892
+
893
+ def planar_layout(G, scale=1, center=None, dim=2):
894
+ """Position nodes without edge intersections.
895
+
896
+ Parameters
897
+ ----------
898
+ G : NetworkX graph or list of nodes
899
+ A position will be assigned to every node in G. If G is of type
900
+ nx.PlanarEmbedding, the positions are selected accordingly.
901
+
902
+ scale : number (default: 1)
903
+ Scale factor for positions.
904
+
905
+ center : array-like or None
906
+ Coordinate pair around which to center the layout.
907
+
908
+ dim : int
909
+ Dimension of layout.
910
+
911
+ Returns
912
+ -------
913
+ pos : dict
914
+ A dictionary of positions keyed by node
915
+
916
+ Raises
917
+ ------
918
+ NetworkXException
919
+ If G is not planar
920
+
921
+ Examples
922
+ --------
923
+ >>> G = nx.path_graph(4)
924
+ >>> pos = nx.planar_layout(G)
925
+ """
926
+ import numpy as np
927
+
928
+ if dim != 2:
929
+ raise ValueError("can only handle 2 dimensions")
930
+
931
+ G, center = _process_params(G, center, dim)
932
+
933
+ if len(G) == 0:
934
+ return {}
935
+
936
+ if isinstance(G, nx.PlanarEmbedding):
937
+ embedding = G
938
+ else:
939
+ is_planar, embedding = nx.check_planarity(G)
940
+ if not is_planar:
941
+ raise nx.NetworkXException("G is not planar.")
942
+ pos = nx.combinatorial_embedding_to_pos(embedding)
943
+ node_list = list(embedding)
944
+ pos = np.vstack([pos[x] for x in node_list])
945
+ pos = pos.astype(np.float64)
946
+ pos = rescale_layout(pos, scale=scale) + center
947
+ return dict(zip(node_list, pos))
948
+
949
+
950
+ def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False):
951
+ """Position nodes in a spiral layout.
952
+
953
+ Parameters
954
+ ----------
955
+ G : NetworkX graph or list of nodes
956
+ A position will be assigned to every node in G.
957
+ scale : number (default: 1)
958
+ Scale factor for positions.
959
+ center : array-like or None
960
+ Coordinate pair around which to center the layout.
961
+ dim : int, default=2
962
+ Dimension of layout, currently only dim=2 is supported.
963
+ Other dimension values result in a ValueError.
964
+ resolution : float, default=0.35
965
+ The compactness of the spiral layout returned.
966
+ Lower values result in more compressed spiral layouts.
967
+ equidistant : bool, default=False
968
+ If True, nodes will be positioned equidistant from each other
969
+ by decreasing angle further from center.
970
+ If False, nodes will be positioned at equal angles
971
+ from each other by increasing separation further from center.
972
+
973
+ Returns
974
+ -------
975
+ pos : dict
976
+ A dictionary of positions keyed by node
977
+
978
+ Raises
979
+ ------
980
+ ValueError
981
+ If dim != 2
982
+
983
+ Examples
984
+ --------
985
+ >>> G = nx.path_graph(4)
986
+ >>> pos = nx.spiral_layout(G)
987
+ >>> nx.draw(G, pos=pos)
988
+
989
+ Notes
990
+ -----
991
+ This algorithm currently only works in two dimensions.
992
+
993
+ """
994
+ import numpy as np
995
+
996
+ if dim != 2:
997
+ raise ValueError("can only handle 2 dimensions")
998
+
999
+ G, center = _process_params(G, center, dim)
1000
+
1001
+ if len(G) == 0:
1002
+ return {}
1003
+ if len(G) == 1:
1004
+ return {nx.utils.arbitrary_element(G): center}
1005
+
1006
+ pos = []
1007
+ if equidistant:
1008
+ chord = 1
1009
+ step = 0.5
1010
+ theta = resolution
1011
+ theta += chord / (step * theta)
1012
+ for _ in range(len(G)):
1013
+ r = step * theta
1014
+ theta += chord / r
1015
+ pos.append([np.cos(theta) * r, np.sin(theta) * r])
1016
+
1017
+ else:
1018
+ dist = np.arange(len(G), dtype=float)
1019
+ angle = resolution * dist
1020
+ pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
1021
+
1022
+ pos = rescale_layout(np.array(pos), scale=scale) + center
1023
+
1024
+ pos = dict(zip(G, pos))
1025
+
1026
+ return pos
1027
+
1028
+
1029
+ def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
1030
+ """Position nodes in layers of straight lines.
1031
+
1032
+ Parameters
1033
+ ----------
1034
+ G : NetworkX graph or list of nodes
1035
+ A position will be assigned to every node in G.
1036
+
1037
+ subset_key : string or dict (default='subset')
1038
+ If a string, the key of node data in G that holds the node subset.
1039
+ If a dict, keyed by layer number to the nodes in that layer/subset.
1040
+
1041
+ align : string (default='vertical')
1042
+ The alignment of nodes. Vertical or horizontal.
1043
+
1044
+ scale : number (default: 1)
1045
+ Scale factor for positions.
1046
+
1047
+ center : array-like or None
1048
+ Coordinate pair around which to center the layout.
1049
+
1050
+ Returns
1051
+ -------
1052
+ pos : dict
1053
+ A dictionary of positions keyed by node.
1054
+
1055
+ Examples
1056
+ --------
1057
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1058
+ >>> pos = nx.multipartite_layout(G)
1059
+
1060
+ or use a dict to provide the layers of the layout
1061
+
1062
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
1063
+ >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
1064
+ >>> pos = nx.multipartite_layout(G, subset_key=layers)
1065
+
1066
+ Notes
1067
+ -----
1068
+ This algorithm currently only works in two dimensions and does not
1069
+ try to minimize edge crossings.
1070
+
1071
+ Network does not need to be a complete multipartite graph. As long as nodes
1072
+ have subset_key data, they will be placed in the corresponding layers.
1073
+
1074
+ """
1075
+ import numpy as np
1076
+
1077
+ if align not in ("vertical", "horizontal"):
1078
+ msg = "align must be either vertical or horizontal."
1079
+ raise ValueError(msg)
1080
+
1081
+ G, center = _process_params(G, center=center, dim=2)
1082
+ if len(G) == 0:
1083
+ return {}
1084
+
1085
+ try:
1086
+ # check if subset_key is dict-like
1087
+ if len(G) != sum(len(nodes) for nodes in subset_key.values()):
1088
+ raise nx.NetworkXError(
1089
+ "all nodes must be in one subset of `subset_key` dict"
1090
+ )
1091
+ except AttributeError:
1092
+ # subset_key is not a dict, hence a string
1093
+ node_to_subset = nx.get_node_attributes(G, subset_key)
1094
+ if len(node_to_subset) != len(G):
1095
+ raise nx.NetworkXError(
1096
+ f"all nodes need a subset_key attribute: {subset_key}"
1097
+ )
1098
+ subset_key = nx.utils.groups(node_to_subset)
1099
+
1100
+ # Sort by layer, if possible
1101
+ try:
1102
+ layers = dict(sorted(subset_key.items()))
1103
+ except TypeError:
1104
+ layers = subset_key
1105
+
1106
+ pos = None
1107
+ nodes = []
1108
+ width = len(layers)
1109
+ for i, layer in enumerate(layers.values()):
1110
+ height = len(layer)
1111
+ xs = np.repeat(i, height)
1112
+ ys = np.arange(0, height, dtype=float)
1113
+ offset = ((width - 1) / 2, (height - 1) / 2)
1114
+ layer_pos = np.column_stack([xs, ys]) - offset
1115
+ if pos is None:
1116
+ pos = layer_pos
1117
+ else:
1118
+ pos = np.concatenate([pos, layer_pos])
1119
+ nodes.extend(layer)
1120
+ pos = rescale_layout(pos, scale=scale) + center
1121
+ if align == "horizontal":
1122
+ pos = pos[:, ::-1] # swap x and y coords
1123
+ pos = dict(zip(nodes, pos))
1124
+ return pos
1125
+
1126
+
1127
+ @np_random_state("seed")
1128
+ def arf_layout(
1129
+ G,
1130
+ pos=None,
1131
+ scaling=1,
1132
+ a=1.1,
1133
+ etol=1e-6,
1134
+ dt=1e-3,
1135
+ max_iter=1000,
1136
+ *,
1137
+ seed=None,
1138
+ ):
1139
+ """Arf layout for networkx
1140
+
1141
+ The attractive and repulsive forces (arf) layout [1]
1142
+ improves the spring layout in three ways. First, it
1143
+ prevents congestion of highly connected nodes due to
1144
+ strong forcing between nodes. Second, it utilizes the
1145
+ layout space more effectively by preventing large gaps
1146
+ that spring layout tends to create. Lastly, the arf
1147
+ layout represents symmetries in the layout better than
1148
+ the default spring layout.
1149
+
1150
+ Parameters
1151
+ ----------
1152
+ G : nx.Graph or nx.DiGraph
1153
+ Networkx graph.
1154
+ pos : dict
1155
+ Initial position of the nodes. If set to None a
1156
+ random layout will be used.
1157
+ scaling : float
1158
+ Scales the radius of the circular layout space.
1159
+ a : float
1160
+ Strength of springs between connected nodes. Should be larger than 1. The greater a, the clearer the separation ofunconnected sub clusters.
1161
+ etol : float
1162
+ Gradient sum of spring forces must be larger than `etol` before successful termination.
1163
+ dt : float
1164
+ Time step for force differential equation simulations.
1165
+ max_iter : int
1166
+ Max iterations before termination of the algorithm.
1167
+ seed : int, RandomState instance or None optional (default=None)
1168
+ Set the random state for deterministic node layouts.
1169
+ If int, `seed` is the seed used by the random number generator,
1170
+ if numpy.random.RandomState instance, `seed` is the random
1171
+ number generator,
1172
+ if None, the random number generator is the RandomState instance used
1173
+ by numpy.random.
1174
+
1175
+ References
1176
+ .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
1177
+ International Journal of Modern Physics C, 2007, Vol 18, No 10, pp. 1537-1549.
1178
+ https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
1179
+
1180
+ Returns
1181
+ -------
1182
+ pos : dict
1183
+ A dictionary of positions keyed by node.
1184
+
1185
+ Examples
1186
+ --------
1187
+ >>> G = nx.grid_graph((5, 5))
1188
+ >>> pos = nx.arf_layout(G)
1189
+
1190
+ """
1191
+ import warnings
1192
+
1193
+ import numpy as np
1194
+
1195
+ if a <= 1:
1196
+ msg = "The parameter a should be larger than 1"
1197
+ raise ValueError(msg)
1198
+
1199
+ pos_tmp = nx.random_layout(G, seed=seed)
1200
+ if pos is None:
1201
+ pos = pos_tmp
1202
+ else:
1203
+ for node in G.nodes():
1204
+ if node not in pos:
1205
+ pos[node] = pos_tmp[node].copy()
1206
+
1207
+ # Initialize spring constant matrix
1208
+ N = len(G)
1209
+ # No nodes no computation
1210
+ if N == 0:
1211
+ return pos
1212
+
1213
+ # init force of springs
1214
+ K = np.ones((N, N)) - np.eye(N)
1215
+ node_order = {node: i for i, node in enumerate(G)}
1216
+ for x, y in G.edges():
1217
+ if x != y:
1218
+ idx, jdx = (node_order[i] for i in (x, y))
1219
+ K[idx, jdx] = a
1220
+
1221
+ # vectorize values
1222
+ p = np.asarray(list(pos.values()))
1223
+
1224
+ # equation 10 in [1]
1225
+ rho = scaling * np.sqrt(N)
1226
+
1227
+ # looping variables
1228
+ error = etol + 1
1229
+ n_iter = 0
1230
+ while error > etol:
1231
+ diff = p[:, np.newaxis] - p[np.newaxis]
1232
+ A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
1233
+ # attraction_force - repulsions force
1234
+ # suppress nans due to division; caused by diagonal set to zero.
1235
+ # Does not affect the computation due to nansum
1236
+ with warnings.catch_warnings():
1237
+ warnings.simplefilter("ignore")
1238
+ change = K[..., np.newaxis] * diff - rho / A * diff
1239
+ change = np.nansum(change, axis=0)
1240
+ p += change * dt
1241
+
1242
+ error = np.linalg.norm(change, axis=-1).sum()
1243
+ if n_iter > max_iter:
1244
+ break
1245
+ n_iter += 1
1246
+ return dict(zip(G.nodes(), p))
1247
+
1248
+
1249
+ @np_random_state("seed")
1250
+ def forceatlas2_layout(
1251
+ G,
1252
+ pos=None,
1253
+ *,
1254
+ max_iter=100,
1255
+ jitter_tolerance=1.0,
1256
+ scaling_ratio=2.0,
1257
+ gravity=1.0,
1258
+ distributed_action=False,
1259
+ strong_gravity=False,
1260
+ node_mass=None,
1261
+ node_size=None,
1262
+ weight=None,
1263
+ dissuade_hubs=False,
1264
+ linlog=False,
1265
+ seed=None,
1266
+ dim=2,
1267
+ ):
1268
+ """Position nodes using the ForceAtlas2 force-directed layout algorithm.
1269
+
1270
+ This function applies the ForceAtlas2 layout algorithm [1]_ to a NetworkX graph,
1271
+ positioning the nodes in a way that visually represents the structure of the graph.
1272
+ The algorithm uses physical simulation to minimize the energy of the system,
1273
+ resulting in a more readable layout.
1274
+
1275
+ Parameters
1276
+ ----------
1277
+ G : nx.Graph
1278
+ A NetworkX graph to be laid out.
1279
+ pos : dict or None, optional
1280
+ Initial positions of the nodes. If None, random initial positions are used.
1281
+ max_iter : int (default: 100)
1282
+ Number of iterations for the layout optimization.
1283
+ jitter_tolerance : float (default: 1.0)
1284
+ Controls the tolerance for adjusting the speed of layout generation.
1285
+ scaling_ratio : float (default: 2.0)
1286
+ Determines the scaling of attraction and repulsion forces.
1287
+ distributed_attraction : bool (default: False)
1288
+ Distributes the attraction force evenly among nodes.
1289
+ strong_gravity : bool (default: False)
1290
+ Applies a strong gravitational pull towards the center.
1291
+ node_mass : dict or None, optional
1292
+ Maps nodes to their masses, influencing the attraction to other nodes.
1293
+ node_size : dict or None, optional
1294
+ Maps nodes to their sizes, preventing crowding by creating a halo effect.
1295
+ dissuade_hubs : bool (default: False)
1296
+ Prevents the clustering of hub nodes.
1297
+ linlog : bool (default: False)
1298
+ Uses logarithmic attraction instead of linear.
1299
+ seed : int, RandomState instance or None optional (default=None)
1300
+ Used only for the initial positions in the algorithm.
1301
+ Set the random state for deterministic node layouts.
1302
+ If int, `seed` is the seed used by the random number generator,
1303
+ if numpy.random.RandomState instance, `seed` is the random
1304
+ number generator,
1305
+ if None, the random number generator is the RandomState instance used
1306
+ by numpy.random.
1307
+ dim : int (default: 2)
1308
+ Sets the dimensions for the layout. Ignored if `pos` is provided.
1309
+
1310
+ Examples
1311
+ --------
1312
+ >>> import networkx as nx
1313
+ >>> G = nx.florentine_families_graph()
1314
+ >>> pos = nx.forceatlas2_layout(G)
1315
+ >>> nx.draw(G, pos=pos)
1316
+
1317
+ References
1318
+ ----------
1319
+ .. [1] Jacomy, M., Venturini, T., Heymann, S., & Bastian, M. (2014).
1320
+ ForceAtlas2, a continuous graph layout algorithm for handy network
1321
+ visualization designed for the Gephi software. PloS one, 9(6), e98679.
1322
+ https://doi.org/10.1371/journal.pone.0098679
1323
+ """
1324
+ import numpy as np
1325
+
1326
+ if len(G) == 0:
1327
+ return {}
1328
+ # parse optional pos positions
1329
+ if pos is None:
1330
+ pos = nx.random_layout(G, dim=dim, seed=seed)
1331
+ pos_arr = np.array(list(pos.values()))
1332
+ else:
1333
+ # set default node interval within the initial pos values
1334
+ pos_init = np.array(list(pos.values()))
1335
+ max_pos = pos_init.max(axis=0)
1336
+ min_pos = pos_init.min(axis=0)
1337
+ dim = max_pos.size
1338
+ pos_arr = min_pos + seed.rand(len(G), dim) * (max_pos - min_pos)
1339
+ for idx, node in enumerate(G):
1340
+ if node in pos:
1341
+ pos_arr[idx] = pos[node].copy()
1342
+
1343
+ mass = np.zeros(len(G))
1344
+ size = np.zeros(len(G))
1345
+
1346
+ # Only adjust for size when the users specifies size other than default (1)
1347
+ adjust_sizes = False
1348
+ if node_size is None:
1349
+ node_size = {}
1350
+ else:
1351
+ adjust_sizes = True
1352
+
1353
+ if node_mass is None:
1354
+ node_mass = {}
1355
+
1356
+ for idx, node in enumerate(G):
1357
+ mass[idx] = node_mass.get(node, G.degree(node) + 1)
1358
+ size[idx] = node_size.get(node, 1)
1359
+
1360
+ n = len(G)
1361
+ gravities = np.zeros((n, dim))
1362
+ attraction = np.zeros((n, dim))
1363
+ repulsion = np.zeros((n, dim))
1364
+ A = nx.to_numpy_array(G, weight=weight)
1365
+
1366
+ def estimate_factor(n, swing, traction, speed, speed_efficiency, jitter_tolerance):
1367
+ """Computes the scaling factor for the force in the ForceAtlas2 layout algorithm.
1368
+
1369
+ This helper function adjusts the speed and
1370
+ efficiency of the layout generation based on the
1371
+ current state of the system, such as the number of
1372
+ nodes, current swing, and traction forces.
1373
+
1374
+ Parameters
1375
+ ----------
1376
+ n : int
1377
+ Number of nodes in the graph.
1378
+ swing : float
1379
+ The current swing, representing the oscillation of the nodes.
1380
+ traction : float
1381
+ The current traction force, representing the attraction between nodes.
1382
+ speed : float
1383
+ The current speed of the layout generation.
1384
+ speed_efficiency : float
1385
+ The efficiency of the current speed, influencing how fast the layout converges.
1386
+ jitter_tolerance : float
1387
+ The tolerance for jitter, affecting how much speed adjustment is allowed.
1388
+
1389
+ Returns
1390
+ -------
1391
+ tuple
1392
+ A tuple containing the updated speed and speed efficiency.
1393
+
1394
+ Notes
1395
+ -----
1396
+ This function is a part of the ForceAtlas2 layout algorithm and is used to dynamically adjust the
1397
+ layout parameters to achieve an optimal and stable visualization.
1398
+
1399
+ """
1400
+ import numpy as np
1401
+
1402
+ # estimate jitter
1403
+ opt_jitter = 0.05 * np.sqrt(n)
1404
+ min_jitter = np.sqrt(opt_jitter)
1405
+ max_jitter = 10
1406
+ min_speed_efficiency = 0.05
1407
+
1408
+ other = min(max_jitter, opt_jitter * traction / n**2)
1409
+ jitter = jitter_tolerance * max(min_jitter, other)
1410
+
1411
+ if swing / traction > 2.0:
1412
+ if speed_efficiency > min_speed_efficiency:
1413
+ speed_efficiency *= 0.5
1414
+ jitter = max(jitter, jitter_tolerance)
1415
+ if swing == 0:
1416
+ target_speed = np.inf
1417
+ else:
1418
+ target_speed = jitter * speed_efficiency * traction / swing
1419
+
1420
+ if swing > jitter * traction:
1421
+ if speed_efficiency > min_speed_efficiency:
1422
+ speed_efficiency *= 0.7
1423
+ elif speed < 1000:
1424
+ speed_efficiency *= 1.3
1425
+
1426
+ max_rise = 0.5
1427
+ speed = speed + min(target_speed - speed, max_rise * speed)
1428
+ return speed, speed_efficiency
1429
+
1430
+ speed = 1
1431
+ speed_efficiency = 1
1432
+ swing = 1
1433
+ traction = 1
1434
+ for _ in range(max_iter):
1435
+ # compute pairwise difference
1436
+ diff = pos_arr[:, None] - pos_arr[None]
1437
+ # compute pairwise distance
1438
+ distance = np.linalg.norm(diff, axis=-1)
1439
+
1440
+ # linear attraction
1441
+ if linlog:
1442
+ attraction = -np.log(1 + distance) / distance
1443
+ np.fill_diagonal(attraction, 0)
1444
+ attraction = np.einsum("ij, ij -> ij", attraction, A)
1445
+ attraction = np.einsum("ijk, ij -> ik", diff, attraction)
1446
+
1447
+ else:
1448
+ attraction = -np.einsum("ijk, ij -> ik", diff, A)
1449
+
1450
+ if distributed_action:
1451
+ attraction /= mass[:, None]
1452
+
1453
+ # repulsion
1454
+ tmp = mass[:, None] @ mass[None]
1455
+ if adjust_sizes:
1456
+ distance += -size[:, None] - size[None]
1457
+
1458
+ d2 = distance**2
1459
+ # remove self-interaction
1460
+ np.fill_diagonal(tmp, 0)
1461
+ np.fill_diagonal(d2, 1)
1462
+ factor = (tmp / d2) * scaling_ratio
1463
+ repulsion = np.einsum("ijk, ij -> ik", diff, factor)
1464
+
1465
+ # gravity
1466
+ gravities = (
1467
+ -gravity
1468
+ * mass[:, None]
1469
+ * pos_arr
1470
+ / np.linalg.norm(pos_arr, axis=-1)[:, None]
1471
+ )
1472
+
1473
+ if strong_gravity:
1474
+ gravities *= np.linalg.norm(pos_arr, axis=-1)[:, None]
1475
+ # total forces
1476
+ update = attraction + repulsion + gravities
1477
+
1478
+ # compute total swing and traction
1479
+ swing += (mass * np.linalg.norm(pos_arr - update, axis=-1)).sum()
1480
+ traction += (0.5 * mass * np.linalg.norm(pos_arr + update, axis=-1)).sum()
1481
+
1482
+ speed, speed_efficiency = estimate_factor(
1483
+ n,
1484
+ swing,
1485
+ traction,
1486
+ speed,
1487
+ speed_efficiency,
1488
+ jitter_tolerance,
1489
+ )
1490
+
1491
+ # update pos
1492
+ if adjust_sizes:
1493
+ swinging = mass * np.linalg.norm(update, axis=-1)
1494
+ factor = 0.1 * speed / (1 + np.sqrt(speed * swinging))
1495
+ df = np.linalg.norm(update, axis=-1)
1496
+ factor = np.minimum(factor * df, 10.0 * np.ones(df.shape)) / df
1497
+ else:
1498
+ swinging = mass * np.linalg.norm(update, axis=-1)
1499
+ factor = speed / (1 + np.sqrt(speed * swinging))
1500
+
1501
+ pos_arr += update * factor[:, None]
1502
+ if abs((update * factor[:, None]).sum()) < 1e-10:
1503
+ break
1504
+
1505
+ return dict(zip(G, pos_arr))
1506
+
1507
+
1508
+ def rescale_layout(pos, scale=1):
1509
+ """Returns scaled position array to (-scale, scale) in all axes.
1510
+
1511
+ The function acts on NumPy arrays which hold position information.
1512
+ Each position is one row of the array. The dimension of the space
1513
+ equals the number of columns. Each coordinate in one column.
1514
+
1515
+ To rescale, the mean (center) is subtracted from each axis separately.
1516
+ Then all values are scaled so that the largest magnitude value
1517
+ from all axes equals `scale` (thus, the aspect ratio is preserved).
1518
+ The resulting NumPy Array is returned (order of rows unchanged).
1519
+
1520
+ Parameters
1521
+ ----------
1522
+ pos : numpy array
1523
+ positions to be scaled. Each row is a position.
1524
+
1525
+ scale : number (default: 1)
1526
+ The size of the resulting extent in all directions.
1527
+
1528
+ Returns
1529
+ -------
1530
+ pos : numpy array
1531
+ scaled positions. Each row is a position.
1532
+
1533
+ See Also
1534
+ --------
1535
+ rescale_layout_dict
1536
+ """
1537
+ import numpy as np
1538
+
1539
+ # Find max length over all dimensions
1540
+ pos -= pos.mean(axis=0)
1541
+ lim = np.abs(pos).max() # max coordinate for all axes
1542
+ # rescale to (-scale, scale) in all directions, preserves aspect
1543
+ if lim > 0:
1544
+ pos *= scale / lim
1545
+ return pos
1546
+
1547
+
1548
+ def rescale_layout_dict(pos, scale=1):
1549
+ """Return a dictionary of scaled positions keyed by node
1550
+
1551
+ Parameters
1552
+ ----------
1553
+ pos : A dictionary of positions keyed by node
1554
+
1555
+ scale : number (default: 1)
1556
+ The size of the resulting extent in all directions.
1557
+
1558
+ Returns
1559
+ -------
1560
+ pos : A dictionary of positions keyed by node
1561
+
1562
+ Examples
1563
+ --------
1564
+ >>> import numpy as np
1565
+ >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
1566
+ >>> nx.rescale_layout_dict(pos)
1567
+ {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
1568
+
1569
+ >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
1570
+ >>> nx.rescale_layout_dict(pos, scale=2)
1571
+ {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
1572
+
1573
+ See Also
1574
+ --------
1575
+ rescale_layout
1576
+ """
1577
+ import numpy as np
1578
+
1579
+ if not pos: # empty_graph
1580
+ return {}
1581
+ pos_v = np.array(list(pos.values()))
1582
+ pos_v = rescale_layout(pos_v, scale=scale)
1583
+ return dict(zip(pos, pos_v))
1584
+
1585
+
1586
+ def bfs_layout(G, start, *, align="vertical", scale=1, center=None):
1587
+ """Position nodes according to breadth-first search algorithm.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ G : NetworkX graph
1592
+ A position will be assigned to every node in G.
1593
+
1594
+ start : node in `G`
1595
+ Starting node for bfs
1596
+
1597
+ center : array-like or None
1598
+ Coordinate pair around which to center the layout.
1599
+
1600
+ Returns
1601
+ -------
1602
+ pos : dict
1603
+ A dictionary of positions keyed by node.
1604
+
1605
+ Examples
1606
+ --------
1607
+ >>> G = nx.path_graph(4)
1608
+ >>> pos = nx.bfs_layout(G, 0)
1609
+
1610
+ Notes
1611
+ -----
1612
+ This algorithm currently only works in two dimensions and does not
1613
+ try to minimize edge crossings.
1614
+
1615
+ """
1616
+ G, center = _process_params(G, center, 2)
1617
+
1618
+ # Compute layers with BFS
1619
+ layers = dict(enumerate(nx.bfs_layers(G, start)))
1620
+
1621
+ if len(G) != sum(len(nodes) for nodes in layers.values()):
1622
+ raise nx.NetworkXError(
1623
+ "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
1624
+ " G.subgraph(nx.node_connected_component(G, start))"
1625
+ )
1626
+
1627
+ # Compute node positions with multipartite_layout
1628
+ return multipartite_layout(
1629
+ G, subset_key=layers, align=align, scale=scale, center=center
1630
+ )
janus/lib/python3.10/site-packages/networkx/drawing/nx_latex.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ *****
3
+ LaTeX
4
+ *****
5
+
6
+ Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
7
+ Usually, you will want the drawing to appear in a figure environment so
8
+ you use ``to_latex(G, caption="A caption")``. If you want the raw
9
+ drawing commands without a figure environment use :func:`to_latex_raw`.
10
+ And if you want to write to a file instead of just returning the latex
11
+ code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
12
+
13
+ To construct a figure with subfigures for each graph to be shown, provide
14
+ ``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
15
+ and a number of rows of subfigures inside the figure.
16
+
17
+ To be able to refer to the figures or subfigures in latex using ``\\ref``,
18
+ the keyword ``latex_label`` is available for figures and `sub_labels` for
19
+ a list of labels, one for each subfigure.
20
+
21
+ We intend to eventually provide an interface to the TikZ Graph
22
+ features which include e.g. layout algorithms.
23
+
24
+ Let us know via github what you'd like to see available, or better yet
25
+ give us some code to do it, or even better make a github pull request
26
+ to add the feature.
27
+
28
+ The TikZ approach
29
+ =================
30
+ Drawing options can be stored on the graph as node/edge attributes, or
31
+ can be provided as dicts keyed by node/edge to a string of the options
32
+ for that node/edge. Similarly a label can be shown for each node/edge
33
+ by specifying the labels as graph node/edge attributes or by providing
34
+ a dict keyed by node/edge to the text to be written for that node/edge.
35
+
36
+ Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
37
+ via a keyword argument. Similarly default node and edge options can be
38
+ provided through keywords arguments. The default node options are applied
39
+ to the single TikZ "path" that draws all nodes (and no edges). The default edge
40
+ options are applied to a TikZ "scope" which contains a path for each edge.
41
+
42
+ Examples
43
+ ========
44
+ >>> G = nx.path_graph(3)
45
+ >>> nx.write_latex(G, "just_my_figure.tex", as_document=True)
46
+ >>> nx.write_latex(G, "my_figure.tex", caption="A path graph", latex_label="fig1")
47
+ >>> latex_code = nx.to_latex(G) # a string rather than a file
48
+
49
+ You can change many features of the nodes and edges.
50
+
51
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph)
52
+ >>> pos = {n: (n, n) for n in G} # nodes set on a line
53
+
54
+ >>> G.nodes[0]["style"] = "blue"
55
+ >>> G.nodes[2]["style"] = "line width=3,draw"
56
+ >>> G.nodes[3]["label"] = "Stop"
57
+ >>> G.edges[(0, 1)]["label"] = "1st Step"
58
+ >>> G.edges[(0, 1)]["label_opts"] = "near start"
59
+ >>> G.edges[(1, 2)]["style"] = "line width=3"
60
+ >>> G.edges[(1, 2)]["label"] = "2nd Step"
61
+ >>> G.edges[(2, 3)]["style"] = "green"
62
+ >>> G.edges[(2, 3)]["label"] = "3rd Step"
63
+ >>> G.edges[(2, 3)]["label_opts"] = "near end"
64
+
65
+ >>> nx.write_latex(G, "latex_graph.tex", pos=pos, as_document=True)
66
+
67
+ Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
68
+ and view the pdf file created: ``latex_graph.pdf``.
69
+
70
+ If you want **subfigures** each containing one graph, you can input a list of graphs.
71
+
72
+ >>> H1 = nx.path_graph(4)
73
+ >>> H2 = nx.complete_graph(4)
74
+ >>> H3 = nx.path_graph(8)
75
+ >>> H4 = nx.complete_graph(8)
76
+ >>> graphs = [H1, H2, H3, H4]
77
+ >>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
78
+ >>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
79
+ >>> nx.write_latex(graphs, "subfigs.tex", n_rows=2, sub_captions=caps, sub_labels=lbls)
80
+ >>> latex_code = nx.to_latex(graphs, n_rows=2, sub_captions=caps, sub_labels=lbls)
81
+
82
+ >>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
83
+ >>> edge_width = {e: "line width=1.5" for e in H3.edges}
84
+ >>> pos = nx.circular_layout(H3)
85
+ >>> latex_code = nx.to_latex(H3, pos, node_options=node_color, edge_options=edge_width)
86
+ >>> print(latex_code)
87
+ \documentclass{report}
88
+ \usepackage{tikz}
89
+ \usepackage{subcaption}
90
+ <BLANKLINE>
91
+ \begin{document}
92
+ \begin{figure}
93
+ \begin{tikzpicture}
94
+ \draw
95
+ (1.0, 0.0) node[red] (0){0}
96
+ (0.707, 0.707) node[orange] (1){1}
97
+ (-0.0, 1.0) node[blue] (2){2}
98
+ (-0.707, 0.707) node[gray!90] (3){3}
99
+ (-1.0, -0.0) node (4){4}
100
+ (-0.707, -0.707) node (5){5}
101
+ (0.0, -1.0) node (6){6}
102
+ (0.707, -0.707) node (7){7};
103
+ \begin{scope}[-]
104
+ \draw[line width=1.5] (0) to (1);
105
+ \draw[line width=1.5] (1) to (2);
106
+ \draw[line width=1.5] (2) to (3);
107
+ \draw[line width=1.5] (3) to (4);
108
+ \draw[line width=1.5] (4) to (5);
109
+ \draw[line width=1.5] (5) to (6);
110
+ \draw[line width=1.5] (6) to (7);
111
+ \end{scope}
112
+ \end{tikzpicture}
113
+ \end{figure}
114
+ \end{document}
115
+
116
+ Notes
117
+ -----
118
+ If you want to change the preamble/postamble of the figure/document/subfigure
119
+ environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
120
+ `subfigure_wrapper`. The default values are stored in private variables
121
+ e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
122
+
123
+ References
124
+ ----------
125
+ TikZ: https://tikz.dev/
126
+
127
+ TikZ options details: https://tikz.dev/tikz-actions
128
+ """
129
+
130
+ import numbers
131
+ import os
132
+
133
+ import networkx as nx
134
+
135
+ __all__ = [
136
+ "to_latex_raw",
137
+ "to_latex",
138
+ "write_latex",
139
+ ]
140
+
141
+
142
+ @nx.utils.not_implemented_for("multigraph")
143
+ def to_latex_raw(
144
+ G,
145
+ pos="pos",
146
+ tikz_options="",
147
+ default_node_options="",
148
+ node_options="node_options",
149
+ node_label="label",
150
+ default_edge_options="",
151
+ edge_options="edge_options",
152
+ edge_label="label",
153
+ edge_label_options="edge_label_options",
154
+ ):
155
+ """Return a string of the LaTeX/TikZ code to draw `G`
156
+
157
+ This function produces just the code for the tikzpicture
158
+ without any enclosing environment.
159
+
160
+ Parameters
161
+ ==========
162
+ G : NetworkX graph
163
+ The NetworkX graph to be drawn
164
+ pos : string or dict (default "pos")
165
+ The name of the node attribute on `G` that holds the position of each node.
166
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
167
+ They can also be strings to denote positions in TikZ style, such as (x, y)
168
+ or (angle:radius).
169
+ If a dict, it should be keyed by node to a position.
170
+ If an empty dict, a circular layout is computed by TikZ.
171
+ tikz_options : string
172
+ The tikzpicture options description defining the options for the picture.
173
+ Often large scale options like `[scale=2]`.
174
+ default_node_options : string
175
+ The draw options for a path of nodes. Individual node options override these.
176
+ node_options : string or dict
177
+ The name of the node attribute on `G` that holds the options for each node.
178
+ Or a dict keyed by node to a string holding the options for that node.
179
+ node_label : string or dict
180
+ The name of the node attribute on `G` that holds the node label (text)
181
+ displayed for each node. If the attribute is "" or not present, the node
182
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
183
+ Or a dict keyed by node to a string holding the label for that node.
184
+ default_edge_options : string
185
+ The options for the scope drawing all edges. The default is "[-]" for
186
+ undirected graphs and "[->]" for directed graphs.
187
+ edge_options : string or dict
188
+ The name of the edge attribute on `G` that holds the options for each edge.
189
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
190
+ "loop," is added to the options for the self-loop edge. Hence you can
191
+ use "[loop above]" explicitly, but the default is "[loop]".
192
+ Or a dict keyed by edge to a string holding the options for that edge.
193
+ edge_label : string or dict
194
+ The name of the edge attribute on `G` that holds the edge label (text)
195
+ displayed for each edge. If the attribute is "" or not present, no edge
196
+ label is drawn.
197
+ Or a dict keyed by edge to a string holding the label for that edge.
198
+ edge_label_options : string or dict
199
+ The name of the edge attribute on `G` that holds the label options for
200
+ each edge. For example, "[sloped,above,blue]". The default is no options.
201
+ Or a dict keyed by edge to a string holding the label options for that edge.
202
+
203
+ Returns
204
+ =======
205
+ latex_code : string
206
+ The text string which draws the desired graph(s) when compiled by LaTeX.
207
+
208
+ See Also
209
+ ========
210
+ to_latex
211
+ write_latex
212
+ """
213
+ i4 = "\n "
214
+ i8 = "\n "
215
+
216
+ # set up position dict
217
+ # TODO allow pos to be None and use a nice TikZ default
218
+ if not isinstance(pos, dict):
219
+ pos = nx.get_node_attributes(G, pos)
220
+ if not pos:
221
+ # circular layout with radius 2
222
+ pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
223
+ for node in G:
224
+ if node not in pos:
225
+ raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
226
+ posnode = pos[node]
227
+ if not isinstance(posnode, str):
228
+ try:
229
+ posx, posy = posnode
230
+ pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
231
+ except (TypeError, ValueError):
232
+ msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
233
+ raise nx.NetworkXError(msg)
234
+
235
+ # set up all the dicts
236
+ if not isinstance(node_options, dict):
237
+ node_options = nx.get_node_attributes(G, node_options)
238
+ if not isinstance(node_label, dict):
239
+ node_label = nx.get_node_attributes(G, node_label)
240
+ if not isinstance(edge_options, dict):
241
+ edge_options = nx.get_edge_attributes(G, edge_options)
242
+ if not isinstance(edge_label, dict):
243
+ edge_label = nx.get_edge_attributes(G, edge_label)
244
+ if not isinstance(edge_label_options, dict):
245
+ edge_label_options = nx.get_edge_attributes(G, edge_label_options)
246
+
247
+ # process default options (add brackets or not)
248
+ topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
249
+ defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
250
+ linestyle = f"{'->' if G.is_directed() else '-'}"
251
+ if default_edge_options == "":
252
+ defe = "[" + linestyle + "]"
253
+ elif "-" in default_edge_options:
254
+ defe = default_edge_options
255
+ else:
256
+ defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
257
+
258
+ # Construct the string line by line
259
+ result = " \\begin{tikzpicture}" + topts
260
+ result += i4 + " \\draw" + defn
261
+ # load the nodes
262
+ for n in G:
263
+ # node options goes inside square brackets
264
+ nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
265
+ # node text goes inside curly brackets {}
266
+ ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
267
+
268
+ result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
269
+ result += ";\n"
270
+
271
+ # load the edges
272
+ result += " \\begin{scope}" + defe
273
+ for edge in G.edges:
274
+ u, v = edge[:2]
275
+ e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
276
+ # add loop options for selfloops if not present
277
+ if u == v and "loop" not in e_opts:
278
+ e_opts = "loop," + e_opts
279
+ e_opts = f"[{e_opts}]" if e_opts != "" else ""
280
+ # TODO -- handle bending of multiedges
281
+
282
+ els = edge_label_options[edge] if edge in edge_label_options else ""
283
+ # edge label options goes inside square brackets []
284
+ els = f"[{els.strip('[]')}]"
285
+ # edge text is drawn using the TikZ node command inside curly brackets {}
286
+ e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
287
+
288
+ result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
289
+
290
+ result += "\n \\end{scope}\n \\end{tikzpicture}\n"
291
+ return result
292
+
293
+
294
+ _DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
295
+ \usepackage{{tikz}}
296
+ \usepackage{{subcaption}}
297
+
298
+ \begin{{document}}
299
+ {content}
300
+ \end{{document}}"""
301
+
302
+
303
+ _FIG_WRAPPER = r"""\begin{{figure}}
304
+ {content}{caption}{label}
305
+ \end{{figure}}"""
306
+
307
+
308
+ _SUBFIG_WRAPPER = r""" \begin{{subfigure}}{{{size}\textwidth}}
309
+ {content}{caption}{label}
310
+ \end{{subfigure}}"""
311
+
312
+
313
+ def to_latex(
314
+ Gbunch,
315
+ pos="pos",
316
+ tikz_options="",
317
+ default_node_options="",
318
+ node_options="node_options",
319
+ node_label="node_label",
320
+ default_edge_options="",
321
+ edge_options="edge_options",
322
+ edge_label="edge_label",
323
+ edge_label_options="edge_label_options",
324
+ caption="",
325
+ latex_label="",
326
+ sub_captions=None,
327
+ sub_labels=None,
328
+ n_rows=1,
329
+ as_document=True,
330
+ document_wrapper=_DOC_WRAPPER_TIKZ,
331
+ figure_wrapper=_FIG_WRAPPER,
332
+ subfigure_wrapper=_SUBFIG_WRAPPER,
333
+ ):
334
+ """Return latex code to draw the graph(s) in `Gbunch`
335
+
336
+ The TikZ drawing utility in LaTeX is used to draw the graph(s).
337
+ If `Gbunch` is a graph, it is drawn in a figure environment.
338
+ If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
339
+ within a single figure environment.
340
+
341
+ If `as_document` is True, the figure is wrapped inside a document environment
342
+ so that the resulting string is ready to be compiled by LaTeX. Otherwise,
343
+ the string is ready for inclusion in a larger tex document using ``\\include``
344
+ or ``\\input`` statements.
345
+
346
+ Parameters
347
+ ==========
348
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
349
+ The NetworkX graph to be drawn or an iterable of graphs
350
+ to be drawn inside subfigures of a single figure.
351
+ pos : string or list of strings
352
+ The name of the node attribute on `G` that holds the position of each node.
353
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
354
+ They can also be strings to denote positions in TikZ style, such as (x, y)
355
+ or (angle:radius).
356
+ If a dict, it should be keyed by node to a position.
357
+ If an empty dict, a circular layout is computed by TikZ.
358
+ If you are drawing many graphs in subfigures, use a list of position dicts.
359
+ tikz_options : string
360
+ The tikzpicture options description defining the options for the picture.
361
+ Often large scale options like `[scale=2]`.
362
+ default_node_options : string
363
+ The draw options for a path of nodes. Individual node options override these.
364
+ node_options : string or dict
365
+ The name of the node attribute on `G` that holds the options for each node.
366
+ Or a dict keyed by node to a string holding the options for that node.
367
+ node_label : string or dict
368
+ The name of the node attribute on `G` that holds the node label (text)
369
+ displayed for each node. If the attribute is "" or not present, the node
370
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
371
+ Or a dict keyed by node to a string holding the label for that node.
372
+ default_edge_options : string
373
+ The options for the scope drawing all edges. The default is "[-]" for
374
+ undirected graphs and "[->]" for directed graphs.
375
+ edge_options : string or dict
376
+ The name of the edge attribute on `G` that holds the options for each edge.
377
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
378
+ "loop," is added to the options for the self-loop edge. Hence you can
379
+ use "[loop above]" explicitly, but the default is "[loop]".
380
+ Or a dict keyed by edge to a string holding the options for that edge.
381
+ edge_label : string or dict
382
+ The name of the edge attribute on `G` that holds the edge label (text)
383
+ displayed for each edge. If the attribute is "" or not present, no edge
384
+ label is drawn.
385
+ Or a dict keyed by edge to a string holding the label for that edge.
386
+ edge_label_options : string or dict
387
+ The name of the edge attribute on `G` that holds the label options for
388
+ each edge. For example, "[sloped,above,blue]". The default is no options.
389
+ Or a dict keyed by edge to a string holding the label options for that edge.
390
+ caption : string
391
+ The caption string for the figure environment
392
+ latex_label : string
393
+ The latex label used for the figure for easy referral from the main text
394
+ sub_captions : list of strings
395
+ The sub_caption string for each subfigure in the figure
396
+ sub_latex_labels : list of strings
397
+ The latex label for each subfigure in the figure
398
+ n_rows : int
399
+ The number of rows of subfigures to arrange for multiple graphs
400
+ as_document : bool
401
+ Whether to wrap the latex code in a document environment for compiling
402
+ document_wrapper : formatted text string with variable ``content``.
403
+ This text is called to evaluate the content embedded in a document
404
+ environment with a preamble setting up TikZ.
405
+ figure_wrapper : formatted text string
406
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
407
+ It wraps the content and if a caption is provided, adds the latex code for
408
+ that caption, and if a label is provided, adds the latex code for a label.
409
+ subfigure_wrapper : formatted text string
410
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
411
+ It wraps the content and if a caption is provided, adds the latex code for
412
+ that caption, and if a label is provided, adds the latex code for a label.
413
+ The size is the vertical size of each row of subfigures as a fraction.
414
+
415
+ Returns
416
+ =======
417
+ latex_code : string
418
+ The text string which draws the desired graph(s) when compiled by LaTeX.
419
+
420
+ See Also
421
+ ========
422
+ write_latex
423
+ to_latex_raw
424
+ """
425
+ if hasattr(Gbunch, "adj"):
426
+ raw = to_latex_raw(
427
+ Gbunch,
428
+ pos,
429
+ tikz_options,
430
+ default_node_options,
431
+ node_options,
432
+ node_label,
433
+ default_edge_options,
434
+ edge_options,
435
+ edge_label,
436
+ edge_label_options,
437
+ )
438
+ else: # iterator of graphs
439
+ sbf = subfigure_wrapper
440
+ size = 1 / n_rows
441
+
442
+ N = len(Gbunch)
443
+ if isinstance(pos, str | dict):
444
+ pos = [pos] * N
445
+ if sub_captions is None:
446
+ sub_captions = [""] * N
447
+ if sub_labels is None:
448
+ sub_labels = [""] * N
449
+ if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
450
+ raise nx.NetworkXError(
451
+ "length of Gbunch, sub_captions and sub_figures must agree"
452
+ )
453
+
454
+ raw = ""
455
+ for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
456
+ subraw = to_latex_raw(
457
+ G,
458
+ pos,
459
+ tikz_options,
460
+ default_node_options,
461
+ node_options,
462
+ node_label,
463
+ default_edge_options,
464
+ edge_options,
465
+ edge_label,
466
+ edge_label_options,
467
+ )
468
+ cap = f" \\caption{{{subcap}}}" if subcap else ""
469
+ lbl = f"\\label{{{sublbl}}}" if sublbl else ""
470
+ raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
471
+ raw += "\n"
472
+
473
+ # put raw latex code into a figure environment and optionally into a document
474
+ raw = raw[:-1]
475
+ cap = f"\n \\caption{{{caption}}}" if caption else ""
476
+ lbl = f"\\label{{{latex_label}}}" if latex_label else ""
477
+ fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
478
+ if as_document:
479
+ return document_wrapper.format(content=fig)
480
+ return fig
481
+
482
+
483
+ @nx.utils.open_file(1, mode="w")
484
+ def write_latex(Gbunch, path, **options):
485
+ """Write the latex code to draw the graph(s) onto `path`.
486
+
487
+ This convenience function creates the latex drawing code as a string
488
+ and writes that to a file ready to be compiled when `as_document` is True
489
+ or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
490
+
491
+ The `path` argument can be a string filename or a file handle to write to.
492
+
493
+ Parameters
494
+ ----------
495
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
496
+ If Gbunch is a graph, it is drawn in a figure environment.
497
+ If Gbunch is an iterable of graphs, each is drawn in a subfigure
498
+ environment within a single figure environment.
499
+ path : filename
500
+ Filename or file handle to write to
501
+ options : dict
502
+ By default, TikZ is used with options: (others are ignored)::
503
+
504
+ pos : string or dict or list
505
+ The name of the node attribute on `G` that holds the position of each node.
506
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
507
+ They can also be strings to denote positions in TikZ style, such as (x, y)
508
+ or (angle:radius).
509
+ If a dict, it should be keyed by node to a position.
510
+ If an empty dict, a circular layout is computed by TikZ.
511
+ If you are drawing many graphs in subfigures, use a list of position dicts.
512
+ tikz_options : string
513
+ The tikzpicture options description defining the options for the picture.
514
+ Often large scale options like `[scale=2]`.
515
+ default_node_options : string
516
+ The draw options for a path of nodes. Individual node options override these.
517
+ node_options : string or dict
518
+ The name of the node attribute on `G` that holds the options for each node.
519
+ Or a dict keyed by node to a string holding the options for that node.
520
+ node_label : string or dict
521
+ The name of the node attribute on `G` that holds the node label (text)
522
+ displayed for each node. If the attribute is "" or not present, the node
523
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
524
+ Or a dict keyed by node to a string holding the label for that node.
525
+ default_edge_options : string
526
+ The options for the scope drawing all edges. The default is "[-]" for
527
+ undirected graphs and "[->]" for directed graphs.
528
+ edge_options : string or dict
529
+ The name of the edge attribute on `G` that holds the options for each edge.
530
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
531
+ "loop," is added to the options for the self-loop edge. Hence you can
532
+ use "[loop above]" explicitly, but the default is "[loop]".
533
+ Or a dict keyed by edge to a string holding the options for that edge.
534
+ edge_label : string or dict
535
+ The name of the edge attribute on `G` that holds the edge label (text)
536
+ displayed for each edge. If the attribute is "" or not present, no edge
537
+ label is drawn.
538
+ Or a dict keyed by edge to a string holding the label for that edge.
539
+ edge_label_options : string or dict
540
+ The name of the edge attribute on `G` that holds the label options for
541
+ each edge. For example, "[sloped,above,blue]". The default is no options.
542
+ Or a dict keyed by edge to a string holding the label options for that edge.
543
+ caption : string
544
+ The caption string for the figure environment
545
+ latex_label : string
546
+ The latex label used for the figure for easy referral from the main text
547
+ sub_captions : list of strings
548
+ The sub_caption string for each subfigure in the figure
549
+ sub_latex_labels : list of strings
550
+ The latex label for each subfigure in the figure
551
+ n_rows : int
552
+ The number of rows of subfigures to arrange for multiple graphs
553
+ as_document : bool
554
+ Whether to wrap the latex code in a document environment for compiling
555
+ document_wrapper : formatted text string with variable ``content``.
556
+ This text is called to evaluate the content embedded in a document
557
+ environment with a preamble setting up the TikZ syntax.
558
+ figure_wrapper : formatted text string
559
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
560
+ It wraps the content and if a caption is provided, adds the latex code for
561
+ that caption, and if a label is provided, adds the latex code for a label.
562
+ subfigure_wrapper : formatted text string
563
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
564
+ It wraps the content and if a caption is provided, adds the latex code for
565
+ that caption, and if a label is provided, adds the latex code for a label.
566
+ The size is the vertical size of each row of subfigures as a fraction.
567
+
568
+ See Also
569
+ ========
570
+ to_latex
571
+ """
572
+ path.write(to_latex(Gbunch, **options))
janus/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ *****
3
+ Pydot
4
+ *****
5
+
6
+ Import and export NetworkX graphs in Graphviz dot format using pydot.
7
+
8
+ Either this module or nx_agraph can be used to interface with graphviz.
9
+
10
+ Examples
11
+ --------
12
+ >>> G = nx.complete_graph(5)
13
+ >>> PG = nx.nx_pydot.to_pydot(G)
14
+ >>> H = nx.nx_pydot.from_pydot(PG)
15
+
16
+ See Also
17
+ --------
18
+ - pydot: https://github.com/erocarrera/pydot
19
+ - Graphviz: https://www.graphviz.org
20
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
21
+ """
22
+
23
+ from locale import getpreferredencoding
24
+
25
+ import networkx as nx
26
+ from networkx.utils import open_file
27
+
28
+ __all__ = [
29
+ "write_dot",
30
+ "read_dot",
31
+ "graphviz_layout",
32
+ "pydot_layout",
33
+ "to_pydot",
34
+ "from_pydot",
35
+ ]
36
+
37
+
38
+ @open_file(1, mode="w")
39
+ def write_dot(G, path):
40
+ """Write NetworkX graph G to Graphviz dot format on path.
41
+
42
+ Path can be a string or a file handle.
43
+ """
44
+ P = to_pydot(G)
45
+ path.write(P.to_string())
46
+ return
47
+
48
+
49
+ @open_file(0, mode="r")
50
+ @nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
51
+ def read_dot(path):
52
+ """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
53
+ dot file with the passed path.
54
+
55
+ If this file contains multiple graphs, only the first such graph is
56
+ returned. All graphs _except_ the first are silently ignored.
57
+
58
+ Parameters
59
+ ----------
60
+ path : str or file
61
+ Filename or file handle.
62
+
63
+ Returns
64
+ -------
65
+ G : MultiGraph or MultiDiGraph
66
+ A :class:`MultiGraph` or :class:`MultiDiGraph`.
67
+
68
+ Notes
69
+ -----
70
+ Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
71
+ :class:`MultiGraph`.
72
+ """
73
+ import pydot
74
+
75
+ data = path.read()
76
+
77
+ # List of one or more "pydot.Dot" instances deserialized from this file.
78
+ P_list = pydot.graph_from_dot_data(data)
79
+
80
+ # Convert only the first such instance into a NetworkX graph.
81
+ return from_pydot(P_list[0])
82
+
83
+
84
+ @nx._dispatchable(graphs=None, returns_graph=True)
85
+ def from_pydot(P):
86
+ """Returns a NetworkX graph from a Pydot graph.
87
+
88
+ Parameters
89
+ ----------
90
+ P : Pydot graph
91
+ A graph created with Pydot
92
+
93
+ Returns
94
+ -------
95
+ G : NetworkX multigraph
96
+ A MultiGraph or MultiDiGraph.
97
+
98
+ Examples
99
+ --------
100
+ >>> K5 = nx.complete_graph(5)
101
+ >>> A = nx.nx_pydot.to_pydot(K5)
102
+ >>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
103
+
104
+ # make a Graph instead of MultiGraph
105
+ >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
106
+
107
+ """
108
+
109
+ if P.get_strict(None): # pydot bug: get_strict() shouldn't take argument
110
+ multiedges = False
111
+ else:
112
+ multiedges = True
113
+
114
+ if P.get_type() == "graph": # undirected
115
+ if multiedges:
116
+ N = nx.MultiGraph()
117
+ else:
118
+ N = nx.Graph()
119
+ else:
120
+ if multiedges:
121
+ N = nx.MultiDiGraph()
122
+ else:
123
+ N = nx.DiGraph()
124
+
125
+ # assign defaults
126
+ name = P.get_name().strip('"')
127
+ if name != "":
128
+ N.name = name
129
+
130
+ # add nodes, attributes to N.node_attr
131
+ for p in P.get_node_list():
132
+ n = p.get_name().strip('"')
133
+ if n in ("node", "graph", "edge"):
134
+ continue
135
+ N.add_node(n, **p.get_attributes())
136
+
137
+ # add edges
138
+ for e in P.get_edge_list():
139
+ u = e.get_source()
140
+ v = e.get_destination()
141
+ attr = e.get_attributes()
142
+ s = []
143
+ d = []
144
+
145
+ if isinstance(u, str):
146
+ s.append(u.strip('"'))
147
+ else:
148
+ for unodes in u["nodes"]:
149
+ s.append(unodes.strip('"'))
150
+
151
+ if isinstance(v, str):
152
+ d.append(v.strip('"'))
153
+ else:
154
+ for vnodes in v["nodes"]:
155
+ d.append(vnodes.strip('"'))
156
+
157
+ for source_node in s:
158
+ for destination_node in d:
159
+ N.add_edge(source_node, destination_node, **attr)
160
+
161
+ # add default attributes for graph, nodes, edges
162
+ pattr = P.get_attributes()
163
+ if pattr:
164
+ N.graph["graph"] = pattr
165
+ try:
166
+ N.graph["node"] = P.get_node_defaults()[0]
167
+ except (IndexError, TypeError):
168
+ pass # N.graph['node']={}
169
+ try:
170
+ N.graph["edge"] = P.get_edge_defaults()[0]
171
+ except (IndexError, TypeError):
172
+ pass # N.graph['edge']={}
173
+ return N
174
+
175
+
176
+ def to_pydot(N):
177
+ """Returns a pydot graph from a NetworkX graph N.
178
+
179
+ Parameters
180
+ ----------
181
+ N : NetworkX graph
182
+ A graph created with NetworkX
183
+
184
+ Examples
185
+ --------
186
+ >>> K5 = nx.complete_graph(5)
187
+ >>> P = nx.nx_pydot.to_pydot(K5)
188
+
189
+ Notes
190
+ -----
191
+
192
+ """
193
+ import pydot
194
+
195
+ # set Graphviz graph type
196
+ if N.is_directed():
197
+ graph_type = "digraph"
198
+ else:
199
+ graph_type = "graph"
200
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
201
+
202
+ name = N.name
203
+ graph_defaults = N.graph.get("graph", {})
204
+ if name == "":
205
+ P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
206
+ else:
207
+ P = pydot.Dot(
208
+ f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
209
+ )
210
+ try:
211
+ P.set_node_defaults(**N.graph["node"])
212
+ except KeyError:
213
+ pass
214
+ try:
215
+ P.set_edge_defaults(**N.graph["edge"])
216
+ except KeyError:
217
+ pass
218
+
219
+ for n, nodedata in N.nodes(data=True):
220
+ str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
221
+ n = str(n)
222
+ p = pydot.Node(n, **str_nodedata)
223
+ P.add_node(p)
224
+
225
+ if N.is_multigraph():
226
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
227
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
228
+ u, v = str(u), str(v)
229
+ edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
230
+ P.add_edge(edge)
231
+
232
+ else:
233
+ for u, v, edgedata in N.edges(data=True):
234
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
235
+ u, v = str(u), str(v)
236
+ edge = pydot.Edge(u, v, **str_edgedata)
237
+ P.add_edge(edge)
238
+ return P
239
+
240
+
241
+ def graphviz_layout(G, prog="neato", root=None):
242
+ """Create node positions using Pydot and Graphviz.
243
+
244
+ Returns a dictionary of positions keyed by node.
245
+
246
+ Parameters
247
+ ----------
248
+ G : NetworkX Graph
249
+ The graph for which the layout is computed.
250
+ prog : string (default: 'neato')
251
+ The name of the GraphViz program to use for layout.
252
+ Options depend on GraphViz version but may include:
253
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
254
+ root : Node from G or None (default: None)
255
+ The node of G from which to start some layout algorithms.
256
+
257
+ Returns
258
+ -------
259
+ Dictionary of (x, y) positions keyed by node.
260
+
261
+ Examples
262
+ --------
263
+ >>> G = nx.complete_graph(4)
264
+ >>> pos = nx.nx_pydot.graphviz_layout(G)
265
+ >>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
266
+
267
+ Notes
268
+ -----
269
+ This is a wrapper for pydot_layout.
270
+ """
271
+ return pydot_layout(G=G, prog=prog, root=root)
272
+
273
+
274
+ def pydot_layout(G, prog="neato", root=None):
275
+ """Create node positions using :mod:`pydot` and Graphviz.
276
+
277
+ Parameters
278
+ ----------
279
+ G : Graph
280
+ NetworkX graph to be laid out.
281
+ prog : string (default: 'neato')
282
+ Name of the GraphViz command to use for layout.
283
+ Options depend on GraphViz version but may include:
284
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
285
+ root : Node from G or None (default: None)
286
+ The node of G from which to start some layout algorithms.
287
+
288
+ Returns
289
+ -------
290
+ dict
291
+ Dictionary of positions keyed by node.
292
+
293
+ Examples
294
+ --------
295
+ >>> G = nx.complete_graph(4)
296
+ >>> pos = nx.nx_pydot.pydot_layout(G)
297
+ >>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
298
+
299
+ Notes
300
+ -----
301
+ If you use complex node objects, they may have the same string
302
+ representation and GraphViz could treat them as the same node.
303
+ The layout may assign both nodes a single location. See Issue #1568
304
+ If this occurs in your case, consider relabeling the nodes just
305
+ for the layout computation using something similar to::
306
+
307
+ H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
308
+ H_layout = nx.nx_pydot.pydot_layout(H, prog="dot")
309
+ G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
310
+
311
+ """
312
+ import pydot
313
+
314
+ P = to_pydot(G)
315
+ if root is not None:
316
+ P.set("root", str(root))
317
+
318
+ # List of low-level bytes comprising a string in the dot language converted
319
+ # from the passed graph with the passed external GraphViz command.
320
+ D_bytes = P.create_dot(prog=prog)
321
+
322
+ # Unique string decoded from these bytes with the preferred locale encoding
323
+ D = str(D_bytes, encoding=getpreferredencoding())
324
+
325
+ if D == "": # no data returned
326
+ print(f"Graphviz layout with {prog} failed")
327
+ print()
328
+ print("To debug what happened try:")
329
+ print("P = nx.nx_pydot.to_pydot(G)")
330
+ print('P.write_dot("file.dot")')
331
+ print(f"And then run {prog} on file.dot")
332
+ return
333
+
334
+ # List of one or more "pydot.Dot" instances deserialized from this string.
335
+ Q_list = pydot.graph_from_dot_data(D)
336
+ assert len(Q_list) == 1
337
+
338
+ # The first and only such instance, as guaranteed by the above assertion.
339
+ Q = Q_list[0]
340
+
341
+ node_pos = {}
342
+ for n in G.nodes():
343
+ str_n = str(n)
344
+ node = Q.get_node(pydot.quote_id_if_necessary(str_n))
345
+
346
+ if isinstance(node, list):
347
+ node = node[0]
348
+ pos = node.get_pos()[1:-1] # strip leading and trailing double quotes
349
+ if pos is not None:
350
+ xx, yy = pos.split(",")
351
+ node_pos[n] = (float(xx), float(yy))
352
+ return node_pos
janus/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py ADDED
File without changes