ZTWHHH commited on
Commit
3dbc79f
·
verified ·
1 Parent(s): 9e778eb

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. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc +0 -0
  3. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc +0 -0
  4. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc +0 -0
  5. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc +0 -0
  6. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc +0 -0
  7. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc +0 -0
  8. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc +0 -0
  9. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/biconnected.py +394 -0
  10. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/connected.py +216 -0
  11. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/strongly_connected.py +351 -0
  12. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py +0 -0
  13. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  14. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc +0 -0
  15. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_biconnected.cpython-310.pyc +0 -0
  16. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_connected.cpython-310.pyc +0 -0
  17. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_semiconnected.cpython-310.pyc +0 -0
  18. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc +0 -0
  19. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc +0 -0
  20. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_attracting.py +70 -0
  21. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py +248 -0
  22. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py +138 -0
  23. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_semiconnected.py +55 -0
  24. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_strongly_connected.py +193 -0
  25. minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py +96 -0
  26. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__init__.py +4 -0
  27. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc +0 -0
  28. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/all.cpython-310.pyc +0 -0
  29. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/binary.cpython-310.pyc +0 -0
  30. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc +0 -0
  31. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc +0 -0
  32. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/all.py +321 -0
  33. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/binary.py +450 -0
  34. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/product.py +633 -0
  35. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py +0 -0
  36. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  37. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_all.cpython-310.pyc +0 -0
  38. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_binary.cpython-310.pyc +0 -0
  39. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_product.cpython-310.pyc +0 -0
  40. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_unary.cpython-310.pyc +0 -0
  41. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_all.py +328 -0
  42. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_binary.py +453 -0
  43. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_product.py +491 -0
  44. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_unary.py +55 -0
  45. minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/unary.py +77 -0
  46. minigpt2/lib/python3.10/site-packages/networkx/drawing/__init__.py +7 -0
  47. minigpt2/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc +0 -0
  48. minigpt2/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc +0 -0
  49. minigpt2/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc +0 -0
  50. minigpt2/lib/python3.10/site-packages/networkx/drawing/layout.py +1630 -0
.gitattributes CHANGED
@@ -1377,3 +1377,4 @@ minigpt2/lib/python3.10/site-packages/pillow.libs/liblcms2-e69eef39.so.2.0.16 fi
1377
  minigpt2/lib/python3.10/site-packages/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1378
  minigpt2/lib/python3.10/site-packages/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1379
  minigpt2/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-3ecfe81c.so.1 filter=lfs diff=lfs merge=lfs -text
 
 
1377
  minigpt2/lib/python3.10/site-packages/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1378
  minigpt2/lib/python3.10/site-packages/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1379
  minigpt2/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-3ecfe81c.so.1 filter=lfs diff=lfs merge=lfs -text
1380
+ videochat2/lib/python3.10/site-packages/torch/lib/libtorch_python.so filter=lfs diff=lfs merge=lfs -text
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (338 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc ADDED
Binary file (3.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc ADDED
Binary file (2.41 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc ADDED
Binary file (9.36 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc ADDED
Binary file (4.5 kB). View file
 
minigpt2/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
minigpt2/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
minigpt2/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
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py ADDED
File without changes
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_biconnected.cpython-310.pyc ADDED
Binary file (6.71 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_connected.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_semiconnected.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc ADDED
Binary file (6.58 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_attracting.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ class TestAttractingComponents:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ cls.G1 = nx.DiGraph()
11
+ cls.G1.add_edges_from(
12
+ [
13
+ (5, 11),
14
+ (11, 2),
15
+ (11, 9),
16
+ (11, 10),
17
+ (7, 11),
18
+ (7, 8),
19
+ (8, 9),
20
+ (3, 8),
21
+ (3, 10),
22
+ ]
23
+ )
24
+ cls.G2 = nx.DiGraph()
25
+ cls.G2.add_edges_from([(0, 1), (0, 2), (1, 1), (1, 2), (2, 1)])
26
+
27
+ cls.G3 = nx.DiGraph()
28
+ cls.G3.add_edges_from([(0, 1), (1, 2), (2, 1), (0, 3), (3, 4), (4, 3)])
29
+
30
+ cls.G4 = nx.DiGraph()
31
+
32
+ def test_attracting_components(self):
33
+ ac = list(nx.attracting_components(self.G1))
34
+ assert {2} in ac
35
+ assert {9} in ac
36
+ assert {10} in ac
37
+
38
+ ac = list(nx.attracting_components(self.G2))
39
+ ac = [tuple(sorted(x)) for x in ac]
40
+ assert ac == [(1, 2)]
41
+
42
+ ac = list(nx.attracting_components(self.G3))
43
+ ac = [tuple(sorted(x)) for x in ac]
44
+ assert (1, 2) in ac
45
+ assert (3, 4) in ac
46
+ assert len(ac) == 2
47
+
48
+ ac = list(nx.attracting_components(self.G4))
49
+ assert ac == []
50
+
51
+ def test_number_attacting_components(self):
52
+ assert nx.number_attracting_components(self.G1) == 3
53
+ assert nx.number_attracting_components(self.G2) == 1
54
+ assert nx.number_attracting_components(self.G3) == 2
55
+ assert nx.number_attracting_components(self.G4) == 0
56
+
57
+ def test_is_attracting_component(self):
58
+ assert not nx.is_attracting_component(self.G1)
59
+ assert not nx.is_attracting_component(self.G2)
60
+ assert not nx.is_attracting_component(self.G3)
61
+ g2 = self.G3.subgraph([1, 2])
62
+ assert nx.is_attracting_component(g2)
63
+ assert not nx.is_attracting_component(self.G4)
64
+
65
+ def test_connected_raise(self):
66
+ G = nx.Graph()
67
+ with pytest.raises(NetworkXNotImplemented):
68
+ next(nx.attracting_components(G))
69
+ pytest.raises(NetworkXNotImplemented, nx.number_attracting_components, G)
70
+ pytest.raises(NetworkXNotImplemented, nx.is_attracting_component, G)
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ def assert_components_edges_equal(x, y):
8
+ sx = {frozenset(frozenset(e) for e in c) for c in x}
9
+ sy = {frozenset(frozenset(e) for e in c) for c in y}
10
+ assert sx == sy
11
+
12
+
13
+ def assert_components_equal(x, y):
14
+ sx = {frozenset(c) for c in x}
15
+ sy = {frozenset(c) for c in y}
16
+ assert sx == sy
17
+
18
+
19
+ def test_barbell():
20
+ G = nx.barbell_graph(8, 4)
21
+ nx.add_path(G, [7, 20, 21, 22])
22
+ nx.add_cycle(G, [22, 23, 24, 25])
23
+ pts = set(nx.articulation_points(G))
24
+ assert pts == {7, 8, 9, 10, 11, 12, 20, 21, 22}
25
+
26
+ answer = [
27
+ {12, 13, 14, 15, 16, 17, 18, 19},
28
+ {0, 1, 2, 3, 4, 5, 6, 7},
29
+ {22, 23, 24, 25},
30
+ {11, 12},
31
+ {10, 11},
32
+ {9, 10},
33
+ {8, 9},
34
+ {7, 8},
35
+ {21, 22},
36
+ {20, 21},
37
+ {7, 20},
38
+ ]
39
+ assert_components_equal(list(nx.biconnected_components(G)), answer)
40
+
41
+ G.add_edge(2, 17)
42
+ pts = set(nx.articulation_points(G))
43
+ assert pts == {7, 20, 21, 22}
44
+
45
+
46
+ def test_articulation_points_repetitions():
47
+ G = nx.Graph()
48
+ G.add_edges_from([(0, 1), (1, 2), (1, 3)])
49
+ assert list(nx.articulation_points(G)) == [1]
50
+
51
+
52
+ def test_articulation_points_cycle():
53
+ G = nx.cycle_graph(3)
54
+ nx.add_cycle(G, [1, 3, 4])
55
+ pts = set(nx.articulation_points(G))
56
+ assert pts == {1}
57
+
58
+
59
+ def test_is_biconnected():
60
+ G = nx.cycle_graph(3)
61
+ assert nx.is_biconnected(G)
62
+ nx.add_cycle(G, [1, 3, 4])
63
+ assert not nx.is_biconnected(G)
64
+
65
+
66
+ def test_empty_is_biconnected():
67
+ G = nx.empty_graph(5)
68
+ assert not nx.is_biconnected(G)
69
+ G.add_edge(0, 1)
70
+ assert not nx.is_biconnected(G)
71
+
72
+
73
+ def test_biconnected_components_cycle():
74
+ G = nx.cycle_graph(3)
75
+ nx.add_cycle(G, [1, 3, 4])
76
+ answer = [{0, 1, 2}, {1, 3, 4}]
77
+ assert_components_equal(list(nx.biconnected_components(G)), answer)
78
+
79
+
80
+ def test_biconnected_components1():
81
+ # graph example from
82
+ # https://web.archive.org/web/20121229123447/http://www.ibluemojo.com/school/articul_algorithm.html
83
+ edges = [
84
+ (0, 1),
85
+ (0, 5),
86
+ (0, 6),
87
+ (0, 14),
88
+ (1, 5),
89
+ (1, 6),
90
+ (1, 14),
91
+ (2, 4),
92
+ (2, 10),
93
+ (3, 4),
94
+ (3, 15),
95
+ (4, 6),
96
+ (4, 7),
97
+ (4, 10),
98
+ (5, 14),
99
+ (6, 14),
100
+ (7, 9),
101
+ (8, 9),
102
+ (8, 12),
103
+ (8, 13),
104
+ (10, 15),
105
+ (11, 12),
106
+ (11, 13),
107
+ (12, 13),
108
+ ]
109
+ G = nx.Graph(edges)
110
+ pts = set(nx.articulation_points(G))
111
+ assert pts == {4, 6, 7, 8, 9}
112
+ comps = list(nx.biconnected_component_edges(G))
113
+ answer = [
114
+ [(3, 4), (15, 3), (10, 15), (10, 4), (2, 10), (4, 2)],
115
+ [(13, 12), (13, 8), (11, 13), (12, 11), (8, 12)],
116
+ [(9, 8)],
117
+ [(7, 9)],
118
+ [(4, 7)],
119
+ [(6, 4)],
120
+ [(14, 0), (5, 1), (5, 0), (14, 5), (14, 1), (6, 14), (6, 0), (1, 6), (0, 1)],
121
+ ]
122
+ assert_components_edges_equal(comps, answer)
123
+
124
+
125
+ def test_biconnected_components2():
126
+ G = nx.Graph()
127
+ nx.add_cycle(G, "ABC")
128
+ nx.add_cycle(G, "CDE")
129
+ nx.add_cycle(G, "FIJHG")
130
+ nx.add_cycle(G, "GIJ")
131
+ G.add_edge("E", "G")
132
+ comps = list(nx.biconnected_component_edges(G))
133
+ answer = [
134
+ [
135
+ tuple("GF"),
136
+ tuple("FI"),
137
+ tuple("IG"),
138
+ tuple("IJ"),
139
+ tuple("JG"),
140
+ tuple("JH"),
141
+ tuple("HG"),
142
+ ],
143
+ [tuple("EG")],
144
+ [tuple("CD"), tuple("DE"), tuple("CE")],
145
+ [tuple("AB"), tuple("BC"), tuple("AC")],
146
+ ]
147
+ assert_components_edges_equal(comps, answer)
148
+
149
+
150
+ def test_biconnected_davis():
151
+ D = nx.davis_southern_women_graph()
152
+ bcc = list(nx.biconnected_components(D))[0]
153
+ assert set(D) == bcc # All nodes in a giant bicomponent
154
+ # So no articulation points
155
+ assert len(list(nx.articulation_points(D))) == 0
156
+
157
+
158
+ def test_biconnected_karate():
159
+ K = nx.karate_club_graph()
160
+ answer = [
161
+ {
162
+ 0,
163
+ 1,
164
+ 2,
165
+ 3,
166
+ 7,
167
+ 8,
168
+ 9,
169
+ 12,
170
+ 13,
171
+ 14,
172
+ 15,
173
+ 17,
174
+ 18,
175
+ 19,
176
+ 20,
177
+ 21,
178
+ 22,
179
+ 23,
180
+ 24,
181
+ 25,
182
+ 26,
183
+ 27,
184
+ 28,
185
+ 29,
186
+ 30,
187
+ 31,
188
+ 32,
189
+ 33,
190
+ },
191
+ {0, 4, 5, 6, 10, 16},
192
+ {0, 11},
193
+ ]
194
+ bcc = list(nx.biconnected_components(K))
195
+ assert_components_equal(bcc, answer)
196
+ assert set(nx.articulation_points(K)) == {0}
197
+
198
+
199
+ def test_biconnected_eppstein():
200
+ # tests from http://www.ics.uci.edu/~eppstein/PADS/Biconnectivity.py
201
+ G1 = nx.Graph(
202
+ {
203
+ 0: [1, 2, 5],
204
+ 1: [0, 5],
205
+ 2: [0, 3, 4],
206
+ 3: [2, 4, 5, 6],
207
+ 4: [2, 3, 5, 6],
208
+ 5: [0, 1, 3, 4],
209
+ 6: [3, 4],
210
+ }
211
+ )
212
+ G2 = nx.Graph(
213
+ {
214
+ 0: [2, 5],
215
+ 1: [3, 8],
216
+ 2: [0, 3, 5],
217
+ 3: [1, 2, 6, 8],
218
+ 4: [7],
219
+ 5: [0, 2],
220
+ 6: [3, 8],
221
+ 7: [4],
222
+ 8: [1, 3, 6],
223
+ }
224
+ )
225
+ assert nx.is_biconnected(G1)
226
+ assert not nx.is_biconnected(G2)
227
+ answer_G2 = [{1, 3, 6, 8}, {0, 2, 5}, {2, 3}, {4, 7}]
228
+ bcc = list(nx.biconnected_components(G2))
229
+ assert_components_equal(bcc, answer_G2)
230
+
231
+
232
+ def test_null_graph():
233
+ G = nx.Graph()
234
+ assert not nx.is_biconnected(G)
235
+ assert list(nx.biconnected_components(G)) == []
236
+ assert list(nx.biconnected_component_edges(G)) == []
237
+ assert list(nx.articulation_points(G)) == []
238
+
239
+
240
+ def test_connected_raise():
241
+ DG = nx.DiGraph()
242
+ with pytest.raises(NetworkXNotImplemented):
243
+ next(nx.biconnected_components(DG))
244
+ with pytest.raises(NetworkXNotImplemented):
245
+ next(nx.biconnected_component_edges(DG))
246
+ with pytest.raises(NetworkXNotImplemented):
247
+ next(nx.articulation_points(DG))
248
+ pytest.raises(NetworkXNotImplemented, nx.is_biconnected, DG)
minigpt2/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()
minigpt2/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_semiconnected.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestIsSemiconnected:
9
+ def test_undirected(self):
10
+ pytest.raises(nx.NetworkXNotImplemented, nx.is_semiconnected, nx.Graph())
11
+ pytest.raises(nx.NetworkXNotImplemented, nx.is_semiconnected, nx.MultiGraph())
12
+
13
+ def test_empty(self):
14
+ pytest.raises(nx.NetworkXPointlessConcept, nx.is_semiconnected, nx.DiGraph())
15
+ pytest.raises(
16
+ nx.NetworkXPointlessConcept, nx.is_semiconnected, nx.MultiDiGraph()
17
+ )
18
+
19
+ def test_single_node_graph(self):
20
+ G = nx.DiGraph()
21
+ G.add_node(0)
22
+ assert nx.is_semiconnected(G)
23
+
24
+ def test_path(self):
25
+ G = nx.path_graph(100, create_using=nx.DiGraph())
26
+ assert nx.is_semiconnected(G)
27
+ G.add_edge(100, 99)
28
+ assert not nx.is_semiconnected(G)
29
+
30
+ def test_cycle(self):
31
+ G = nx.cycle_graph(100, create_using=nx.DiGraph())
32
+ assert nx.is_semiconnected(G)
33
+ G = nx.path_graph(100, create_using=nx.DiGraph())
34
+ G.add_edge(0, 99)
35
+ assert nx.is_semiconnected(G)
36
+
37
+ def test_tree(self):
38
+ G = nx.DiGraph()
39
+ G.add_edges_from(
40
+ chain.from_iterable([(i, 2 * i + 1), (i, 2 * i + 2)] for i in range(100))
41
+ )
42
+ assert not nx.is_semiconnected(G)
43
+
44
+ def test_dumbbell(self):
45
+ G = nx.cycle_graph(100, create_using=nx.DiGraph())
46
+ G.add_edges_from((i + 100, (i + 1) % 100 + 100) for i in range(100))
47
+ assert not nx.is_semiconnected(G) # G is disconnected.
48
+ G.add_edge(100, 99)
49
+ assert nx.is_semiconnected(G)
50
+
51
+ def test_alternating_path(self):
52
+ G = nx.DiGraph(
53
+ chain.from_iterable([(i, i - 1), (i, i + 1)] for i in range(0, 100, 2))
54
+ )
55
+ assert not nx.is_semiconnected(G)
minigpt2/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()
minigpt2/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)
minigpt2/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 *
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (377 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/all.cpython-310.pyc ADDED
Binary file (9.13 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/binary.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/all.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Operations on many graphs."""
2
+
3
+ from itertools import chain, repeat
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["union_all", "compose_all", "disjoint_union_all", "intersection_all"]
8
+
9
+
10
+ @nx._dispatchable(graphs="[graphs]", preserve_all_attrs=True, returns_graph=True)
11
+ def union_all(graphs, rename=()):
12
+ """Returns the union of all graphs.
13
+
14
+ The graphs must be disjoint, otherwise an exception is raised.
15
+
16
+ Parameters
17
+ ----------
18
+ graphs : iterable
19
+ Iterable of NetworkX graphs
20
+
21
+ rename : iterable , optional
22
+ Node names of graphs can be changed by specifying the tuple
23
+ rename=('G-','H-') (for example). Node "u" in G is then renamed
24
+ "G-u" and "v" in H is renamed "H-v". Infinite generators (like itertools.count)
25
+ are also supported.
26
+
27
+ Returns
28
+ -------
29
+ U : a graph with the same type as the first graph in list
30
+
31
+ Raises
32
+ ------
33
+ ValueError
34
+ If `graphs` is an empty list.
35
+
36
+ NetworkXError
37
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
38
+
39
+ Notes
40
+ -----
41
+ For operating on mixed type graphs, they should be converted to the same type.
42
+ >>> G = nx.Graph()
43
+ >>> H = nx.DiGraph()
44
+ >>> GH = union_all([nx.DiGraph(G), H])
45
+
46
+ To force a disjoint union with node relabeling, use
47
+ disjoint_union_all(G,H) or convert_node_labels_to integers().
48
+
49
+ Graph, edge, and node attributes are propagated to the union graph.
50
+ If a graph attribute is present in multiple graphs, then the value
51
+ from the last graph in the list with that attribute is used.
52
+
53
+ Examples
54
+ --------
55
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
56
+ >>> G2 = nx.Graph([(4, 5), (5, 6)])
57
+ >>> result_graph = nx.union_all([G1, G2])
58
+ >>> result_graph.nodes()
59
+ NodeView((1, 2, 3, 4, 5, 6))
60
+ >>> result_graph.edges()
61
+ EdgeView([(1, 2), (2, 3), (4, 5), (5, 6)])
62
+
63
+ See Also
64
+ --------
65
+ union
66
+ disjoint_union_all
67
+ """
68
+ R = None
69
+ seen_nodes = set()
70
+
71
+ # rename graph to obtain disjoint node labels
72
+ def add_prefix(graph, prefix):
73
+ if prefix is None:
74
+ return graph
75
+
76
+ def label(x):
77
+ return f"{prefix}{x}"
78
+
79
+ return nx.relabel_nodes(graph, label)
80
+
81
+ rename = chain(rename, repeat(None))
82
+ graphs = (add_prefix(G, name) for G, name in zip(graphs, rename))
83
+
84
+ for i, G in enumerate(graphs):
85
+ G_nodes_set = set(G.nodes)
86
+ if i == 0:
87
+ # Union is the same type as first graph
88
+ R = G.__class__()
89
+ elif G.is_directed() != R.is_directed():
90
+ raise nx.NetworkXError("All graphs must be directed or undirected.")
91
+ elif G.is_multigraph() != R.is_multigraph():
92
+ raise nx.NetworkXError("All graphs must be graphs or multigraphs.")
93
+ elif not seen_nodes.isdisjoint(G_nodes_set):
94
+ raise nx.NetworkXError(
95
+ "The node sets of the graphs are not disjoint.\n"
96
+ "Use `rename` to specify prefixes for the graphs or use\n"
97
+ "disjoint_union(G1, G2, ..., GN)."
98
+ )
99
+
100
+ seen_nodes |= G_nodes_set
101
+ R.graph.update(G.graph)
102
+ R.add_nodes_from(G.nodes(data=True))
103
+ R.add_edges_from(
104
+ G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
105
+ )
106
+
107
+ if R is None:
108
+ raise ValueError("cannot apply union_all to an empty list")
109
+
110
+ return R
111
+
112
+
113
+ @nx._dispatchable(graphs="[graphs]", preserve_all_attrs=True, returns_graph=True)
114
+ def disjoint_union_all(graphs):
115
+ """Returns the disjoint union of all graphs.
116
+
117
+ This operation forces distinct integer node labels starting with 0
118
+ for the first graph in the list and numbering consecutively.
119
+
120
+ Parameters
121
+ ----------
122
+ graphs : iterable
123
+ Iterable of NetworkX graphs
124
+
125
+ Returns
126
+ -------
127
+ U : A graph with the same type as the first graph in list
128
+
129
+ Raises
130
+ ------
131
+ ValueError
132
+ If `graphs` is an empty list.
133
+
134
+ NetworkXError
135
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
136
+
137
+ Examples
138
+ --------
139
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
140
+ >>> G2 = nx.Graph([(4, 5), (5, 6)])
141
+ >>> U = nx.disjoint_union_all([G1, G2])
142
+ >>> list(U.nodes())
143
+ [0, 1, 2, 3, 4, 5]
144
+ >>> list(U.edges())
145
+ [(0, 1), (1, 2), (3, 4), (4, 5)]
146
+
147
+ Notes
148
+ -----
149
+ For operating on mixed type graphs, they should be converted to the same type.
150
+
151
+ Graph, edge, and node attributes are propagated to the union graph.
152
+ If a graph attribute is present in multiple graphs, then the value
153
+ from the last graph in the list with that attribute is used.
154
+ """
155
+
156
+ def yield_relabeled(graphs):
157
+ first_label = 0
158
+ for G in graphs:
159
+ yield nx.convert_node_labels_to_integers(G, first_label=first_label)
160
+ first_label += len(G)
161
+
162
+ R = union_all(yield_relabeled(graphs))
163
+
164
+ return R
165
+
166
+
167
+ @nx._dispatchable(graphs="[graphs]", preserve_all_attrs=True, returns_graph=True)
168
+ def compose_all(graphs):
169
+ """Returns the composition of all graphs.
170
+
171
+ Composition is the simple union of the node sets and edge sets.
172
+ The node sets of the supplied graphs need not be disjoint.
173
+
174
+ Parameters
175
+ ----------
176
+ graphs : iterable
177
+ Iterable of NetworkX graphs
178
+
179
+ Returns
180
+ -------
181
+ C : A graph with the same type as the first graph in list
182
+
183
+ Raises
184
+ ------
185
+ ValueError
186
+ If `graphs` is an empty list.
187
+
188
+ NetworkXError
189
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
190
+
191
+ Examples
192
+ --------
193
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
194
+ >>> G2 = nx.Graph([(3, 4), (5, 6)])
195
+ >>> C = nx.compose_all([G1, G2])
196
+ >>> list(C.nodes())
197
+ [1, 2, 3, 4, 5, 6]
198
+ >>> list(C.edges())
199
+ [(1, 2), (2, 3), (3, 4), (5, 6)]
200
+
201
+ Notes
202
+ -----
203
+ For operating on mixed type graphs, they should be converted to the same type.
204
+
205
+ Graph, edge, and node attributes are propagated to the union graph.
206
+ If a graph attribute is present in multiple graphs, then the value
207
+ from the last graph in the list with that attribute is used.
208
+ """
209
+ R = None
210
+
211
+ # add graph attributes, H attributes take precedent over G attributes
212
+ for i, G in enumerate(graphs):
213
+ if i == 0:
214
+ # create new graph
215
+ R = G.__class__()
216
+ elif G.is_directed() != R.is_directed():
217
+ raise nx.NetworkXError("All graphs must be directed or undirected.")
218
+ elif G.is_multigraph() != R.is_multigraph():
219
+ raise nx.NetworkXError("All graphs must be graphs or multigraphs.")
220
+
221
+ R.graph.update(G.graph)
222
+ R.add_nodes_from(G.nodes(data=True))
223
+ R.add_edges_from(
224
+ G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
225
+ )
226
+
227
+ if R is None:
228
+ raise ValueError("cannot apply compose_all to an empty list")
229
+
230
+ return R
231
+
232
+
233
+ @nx._dispatchable(graphs="[graphs]", returns_graph=True)
234
+ def intersection_all(graphs):
235
+ """Returns a new graph that contains only the nodes and the edges that exist in
236
+ all graphs.
237
+
238
+ Parameters
239
+ ----------
240
+ graphs : iterable
241
+ Iterable of NetworkX graphs
242
+
243
+ Returns
244
+ -------
245
+ R : A new graph with the same type as the first graph in list
246
+
247
+ Raises
248
+ ------
249
+ ValueError
250
+ If `graphs` is an empty list.
251
+
252
+ NetworkXError
253
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
254
+
255
+ Notes
256
+ -----
257
+ For operating on mixed type graphs, they should be converted to the same type.
258
+
259
+ Attributes from the graph, nodes, and edges are not copied to the new
260
+ graph.
261
+
262
+ The resulting graph can be updated with attributes if desired. For example, code which adds the minimum attribute for each node across all graphs could work.
263
+ >>> g = nx.Graph()
264
+ >>> g.add_node(0, capacity=4)
265
+ >>> g.add_node(1, capacity=3)
266
+ >>> g.add_edge(0, 1)
267
+
268
+ >>> h = g.copy()
269
+ >>> h.nodes[0]["capacity"] = 2
270
+
271
+ >>> gh = nx.intersection_all([g, h])
272
+
273
+ >>> new_node_attr = {
274
+ ... n: min(*(anyG.nodes[n].get("capacity", float("inf")) for anyG in [g, h]))
275
+ ... for n in gh
276
+ ... }
277
+ >>> nx.set_node_attributes(gh, new_node_attr, "new_capacity")
278
+ >>> gh.nodes(data=True)
279
+ NodeDataView({0: {'new_capacity': 2}, 1: {'new_capacity': 3}})
280
+
281
+ Examples
282
+ --------
283
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
284
+ >>> G2 = nx.Graph([(2, 3), (3, 4)])
285
+ >>> R = nx.intersection_all([G1, G2])
286
+ >>> list(R.nodes())
287
+ [2, 3]
288
+ >>> list(R.edges())
289
+ [(2, 3)]
290
+
291
+ """
292
+ R = None
293
+
294
+ for i, G in enumerate(graphs):
295
+ G_nodes_set = set(G.nodes)
296
+ G_edges_set = set(G.edges)
297
+ if not G.is_directed():
298
+ if G.is_multigraph():
299
+ G_edges_set.update((v, u, k) for u, v, k in list(G_edges_set))
300
+ else:
301
+ G_edges_set.update((v, u) for u, v in list(G_edges_set))
302
+ if i == 0:
303
+ # create new graph
304
+ R = G.__class__()
305
+ node_intersection = G_nodes_set
306
+ edge_intersection = G_edges_set
307
+ elif G.is_directed() != R.is_directed():
308
+ raise nx.NetworkXError("All graphs must be directed or undirected.")
309
+ elif G.is_multigraph() != R.is_multigraph():
310
+ raise nx.NetworkXError("All graphs must be graphs or multigraphs.")
311
+ else:
312
+ node_intersection &= G_nodes_set
313
+ edge_intersection &= G_edges_set
314
+
315
+ if R is None:
316
+ raise ValueError("cannot apply intersection_all to an empty list")
317
+
318
+ R.add_nodes_from(node_intersection)
319
+ R.add_edges_from(edge_intersection)
320
+
321
+ return R
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/binary.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Operations on graphs including union, intersection, difference.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "union",
9
+ "compose",
10
+ "disjoint_union",
11
+ "intersection",
12
+ "difference",
13
+ "symmetric_difference",
14
+ "full_join",
15
+ ]
16
+ _G_H = {"G": 0, "H": 1}
17
+
18
+
19
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
20
+ def union(G, H, rename=()):
21
+ """Combine graphs G and H. The names of nodes must be unique.
22
+
23
+ A name collision between the graphs will raise an exception.
24
+
25
+ A renaming facility is provided to avoid name collisions.
26
+
27
+
28
+ Parameters
29
+ ----------
30
+ G, H : graph
31
+ A NetworkX graph
32
+
33
+ rename : iterable , optional
34
+ Node names of G and H can be changed by specifying the tuple
35
+ rename=('G-','H-') (for example). Node "u" in G is then renamed
36
+ "G-u" and "v" in H is renamed "H-v".
37
+
38
+ Returns
39
+ -------
40
+ U : A union graph with the same type as G.
41
+
42
+ See Also
43
+ --------
44
+ compose
45
+ :func:`~networkx.Graph.update`
46
+ disjoint_union
47
+
48
+ Notes
49
+ -----
50
+ To combine graphs that have common nodes, consider compose(G, H)
51
+ or the method, Graph.update().
52
+
53
+ disjoint_union() is similar to union() except that it avoids name clashes
54
+ by relabeling the nodes with sequential integers.
55
+
56
+ Edge and node attributes are propagated from G and H to the union graph.
57
+ Graph attributes are also propagated, but if they are present in both G and H,
58
+ then the value from H is used.
59
+
60
+ Examples
61
+ --------
62
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
63
+ >>> H = nx.Graph([(0, 1), (0, 3), (1, 3), (1, 2)])
64
+ >>> U = nx.union(G, H, rename=("G", "H"))
65
+ >>> U.nodes
66
+ NodeView(('G0', 'G1', 'G2', 'H0', 'H1', 'H3', 'H2'))
67
+ >>> U.edges
68
+ EdgeView([('G0', 'G1'), ('G0', 'G2'), ('G1', 'G2'), ('H0', 'H1'), ('H0', 'H3'), ('H1', 'H3'), ('H1', 'H2')])
69
+
70
+
71
+ """
72
+ return nx.union_all([G, H], rename)
73
+
74
+
75
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
76
+ def disjoint_union(G, H):
77
+ """Combine graphs G and H. The nodes are assumed to be unique (disjoint).
78
+
79
+ This algorithm automatically relabels nodes to avoid name collisions.
80
+
81
+ Parameters
82
+ ----------
83
+ G,H : graph
84
+ A NetworkX graph
85
+
86
+ Returns
87
+ -------
88
+ U : A union graph with the same type as G.
89
+
90
+ See Also
91
+ --------
92
+ union
93
+ compose
94
+ :func:`~networkx.Graph.update`
95
+
96
+ Notes
97
+ -----
98
+ A new graph is created, of the same class as G. It is recommended
99
+ that G and H be either both directed or both undirected.
100
+
101
+ The nodes of G are relabeled 0 to len(G)-1, and the nodes of H are
102
+ relabeled len(G) to len(G)+len(H)-1.
103
+
104
+ Renumbering forces G and H to be disjoint, so no exception is ever raised for a name collision.
105
+ To preserve the check for common nodes, use union().
106
+
107
+ Edge and node attributes are propagated from G and H to the union graph.
108
+ Graph attributes are also propagated, but if they are present in both G and H,
109
+ then the value from H is used.
110
+
111
+ To combine graphs that have common nodes, consider compose(G, H)
112
+ or the method, Graph.update().
113
+
114
+ Examples
115
+ --------
116
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
117
+ >>> H = nx.Graph([(0, 3), (1, 2), (2, 3)])
118
+ >>> G.nodes[0]["key1"] = 5
119
+ >>> H.nodes[0]["key2"] = 10
120
+ >>> U = nx.disjoint_union(G, H)
121
+ >>> U.nodes(data=True)
122
+ NodeDataView({0: {'key1': 5}, 1: {}, 2: {}, 3: {'key2': 10}, 4: {}, 5: {}, 6: {}})
123
+ >>> U.edges
124
+ EdgeView([(0, 1), (0, 2), (1, 2), (3, 4), (4, 6), (5, 6)])
125
+ """
126
+ return nx.disjoint_union_all([G, H])
127
+
128
+
129
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
130
+ def intersection(G, H):
131
+ """Returns a new graph that contains only the nodes and the edges that exist in
132
+ both G and H.
133
+
134
+ Parameters
135
+ ----------
136
+ G,H : graph
137
+ A NetworkX graph. G and H can have different node sets but must be both graphs or both multigraphs.
138
+
139
+ Raises
140
+ ------
141
+ NetworkXError
142
+ If one is a MultiGraph and the other one is a graph.
143
+
144
+ Returns
145
+ -------
146
+ GH : A new graph with the same type as G.
147
+
148
+ Notes
149
+ -----
150
+ Attributes from the graph, nodes, and edges are not copied to the new
151
+ graph. If you want a new graph of the intersection of G and H
152
+ with the attributes (including edge data) from G use remove_nodes_from()
153
+ as follows
154
+
155
+ >>> G = nx.path_graph(3)
156
+ >>> H = nx.path_graph(5)
157
+ >>> R = G.copy()
158
+ >>> R.remove_nodes_from(n for n in G if n not in H)
159
+ >>> R.remove_edges_from(e for e in G.edges if e not in H.edges)
160
+
161
+ Examples
162
+ --------
163
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
164
+ >>> H = nx.Graph([(0, 3), (1, 2), (2, 3)])
165
+ >>> R = nx.intersection(G, H)
166
+ >>> R.nodes
167
+ NodeView((0, 1, 2))
168
+ >>> R.edges
169
+ EdgeView([(1, 2)])
170
+ """
171
+ return nx.intersection_all([G, H])
172
+
173
+
174
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
175
+ def difference(G, H):
176
+ """Returns a new graph that contains the edges that exist in G but not in H.
177
+
178
+ The node sets of H and G must be the same.
179
+
180
+ Parameters
181
+ ----------
182
+ G,H : graph
183
+ A NetworkX graph. G and H must have the same node sets.
184
+
185
+ Returns
186
+ -------
187
+ D : A new graph with the same type as G.
188
+
189
+ Notes
190
+ -----
191
+ Attributes from the graph, nodes, and edges are not copied to the new
192
+ graph. If you want a new graph of the difference of G and H with
193
+ the attributes (including edge data) from G use remove_nodes_from()
194
+ as follows:
195
+
196
+ >>> G = nx.path_graph(3)
197
+ >>> H = nx.path_graph(5)
198
+ >>> R = G.copy()
199
+ >>> R.remove_nodes_from(n for n in G if n in H)
200
+
201
+ Examples
202
+ --------
203
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3)])
204
+ >>> H = nx.Graph([(0, 1), (1, 2), (0, 3)])
205
+ >>> R = nx.difference(G, H)
206
+ >>> R.nodes
207
+ NodeView((0, 1, 2, 3))
208
+ >>> R.edges
209
+ EdgeView([(0, 2), (1, 3)])
210
+ """
211
+ # create new graph
212
+ if not G.is_multigraph() == H.is_multigraph():
213
+ raise nx.NetworkXError("G and H must both be graphs or multigraphs.")
214
+ R = nx.create_empty_copy(G, with_data=False)
215
+
216
+ if set(G) != set(H):
217
+ raise nx.NetworkXError("Node sets of graphs not equal")
218
+
219
+ if G.is_multigraph():
220
+ edges = G.edges(keys=True)
221
+ else:
222
+ edges = G.edges()
223
+ for e in edges:
224
+ if not H.has_edge(*e):
225
+ R.add_edge(*e)
226
+ return R
227
+
228
+
229
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
230
+ def symmetric_difference(G, H):
231
+ """Returns new graph with edges that exist in either G or H but not both.
232
+
233
+ The node sets of H and G must be the same.
234
+
235
+ Parameters
236
+ ----------
237
+ G,H : graph
238
+ A NetworkX graph. G and H must have the same node sets.
239
+
240
+ Returns
241
+ -------
242
+ D : A new graph with the same type as G.
243
+
244
+ Notes
245
+ -----
246
+ Attributes from the graph, nodes, and edges are not copied to the new
247
+ graph.
248
+
249
+ Examples
250
+ --------
251
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3)])
252
+ >>> H = nx.Graph([(0, 1), (1, 2), (0, 3)])
253
+ >>> R = nx.symmetric_difference(G, H)
254
+ >>> R.nodes
255
+ NodeView((0, 1, 2, 3))
256
+ >>> R.edges
257
+ EdgeView([(0, 2), (0, 3), (1, 3)])
258
+ """
259
+ # create new graph
260
+ if not G.is_multigraph() == H.is_multigraph():
261
+ raise nx.NetworkXError("G and H must both be graphs or multigraphs.")
262
+ R = nx.create_empty_copy(G, with_data=False)
263
+
264
+ if set(G) != set(H):
265
+ raise nx.NetworkXError("Node sets of graphs not equal")
266
+
267
+ gnodes = set(G) # set of nodes in G
268
+ hnodes = set(H) # set of nodes in H
269
+ nodes = gnodes.symmetric_difference(hnodes)
270
+ R.add_nodes_from(nodes)
271
+
272
+ if G.is_multigraph():
273
+ edges = G.edges(keys=True)
274
+ else:
275
+ edges = G.edges()
276
+ # we could copy the data here but then this function doesn't
277
+ # match intersection and difference
278
+ for e in edges:
279
+ if not H.has_edge(*e):
280
+ R.add_edge(*e)
281
+
282
+ if H.is_multigraph():
283
+ edges = H.edges(keys=True)
284
+ else:
285
+ edges = H.edges()
286
+ for e in edges:
287
+ if not G.has_edge(*e):
288
+ R.add_edge(*e)
289
+ return R
290
+
291
+
292
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
293
+ def compose(G, H):
294
+ """Compose graph G with H by combining nodes and edges into a single graph.
295
+
296
+ The node sets and edges sets do not need to be disjoint.
297
+
298
+ Composing preserves the attributes of nodes and edges.
299
+ Attribute values from H take precedent over attribute values from G.
300
+
301
+ Parameters
302
+ ----------
303
+ G, H : graph
304
+ A NetworkX graph
305
+
306
+ Returns
307
+ -------
308
+ C: A new graph with the same type as G
309
+
310
+ See Also
311
+ --------
312
+ :func:`~networkx.Graph.update`
313
+ union
314
+ disjoint_union
315
+
316
+ Notes
317
+ -----
318
+ It is recommended that G and H be either both directed or both undirected.
319
+
320
+ For MultiGraphs, the edges are identified by incident nodes AND edge-key.
321
+ This can cause surprises (i.e., edge `(1, 2)` may or may not be the same
322
+ in two graphs) if you use MultiGraph without keeping track of edge keys.
323
+
324
+ If combining the attributes of common nodes is not desired, consider union(),
325
+ which raises an exception for name collisions.
326
+
327
+ Examples
328
+ --------
329
+ >>> G = nx.Graph([(0, 1), (0, 2)])
330
+ >>> H = nx.Graph([(0, 1), (1, 2)])
331
+ >>> R = nx.compose(G, H)
332
+ >>> R.nodes
333
+ NodeView((0, 1, 2))
334
+ >>> R.edges
335
+ EdgeView([(0, 1), (0, 2), (1, 2)])
336
+
337
+ By default, the attributes from `H` take precedent over attributes from `G`.
338
+ If you prefer another way of combining attributes, you can update them after the compose operation:
339
+
340
+ >>> G = nx.Graph([(0, 1, {"weight": 2.0}), (3, 0, {"weight": 100.0})])
341
+ >>> H = nx.Graph([(0, 1, {"weight": 10.0}), (1, 2, {"weight": -1.0})])
342
+ >>> nx.set_node_attributes(G, {0: "dark", 1: "light", 3: "black"}, name="color")
343
+ >>> nx.set_node_attributes(H, {0: "green", 1: "orange", 2: "yellow"}, name="color")
344
+ >>> GcomposeH = nx.compose(G, H)
345
+
346
+ Normally, color attribute values of nodes of GcomposeH come from H. We can workaround this as follows:
347
+
348
+ >>> node_data = {
349
+ ... n: G.nodes[n]["color"] + " " + H.nodes[n]["color"]
350
+ ... for n in G.nodes & H.nodes
351
+ ... }
352
+ >>> nx.set_node_attributes(GcomposeH, node_data, "color")
353
+ >>> print(GcomposeH.nodes[0]["color"])
354
+ dark green
355
+
356
+ >>> print(GcomposeH.nodes[3]["color"])
357
+ black
358
+
359
+ Similarly, we can update edge attributes after the compose operation in a way we prefer:
360
+
361
+ >>> edge_data = {
362
+ ... e: G.edges[e]["weight"] * H.edges[e]["weight"] for e in G.edges & H.edges
363
+ ... }
364
+ >>> nx.set_edge_attributes(GcomposeH, edge_data, "weight")
365
+ >>> print(GcomposeH.edges[(0, 1)]["weight"])
366
+ 20.0
367
+
368
+ >>> print(GcomposeH.edges[(3, 0)]["weight"])
369
+ 100.0
370
+ """
371
+ return nx.compose_all([G, H])
372
+
373
+
374
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
375
+ def full_join(G, H, rename=(None, None)):
376
+ """Returns the full join of graphs G and H.
377
+
378
+ Full join is the union of G and H in which all edges between
379
+ G and H are added.
380
+ The node sets of G and H must be disjoint,
381
+ otherwise an exception is raised.
382
+
383
+ Parameters
384
+ ----------
385
+ G, H : graph
386
+ A NetworkX graph
387
+
388
+ rename : tuple , default=(None, None)
389
+ Node names of G and H can be changed by specifying the tuple
390
+ rename=('G-','H-') (for example). Node "u" in G is then renamed
391
+ "G-u" and "v" in H is renamed "H-v".
392
+
393
+ Returns
394
+ -------
395
+ U : The full join graph with the same type as G.
396
+
397
+ Notes
398
+ -----
399
+ It is recommended that G and H be either both directed or both undirected.
400
+
401
+ If G is directed, then edges from G to H are added as well as from H to G.
402
+
403
+ Note that full_join() does not produce parallel edges for MultiGraphs.
404
+
405
+ The full join operation of graphs G and H is the same as getting
406
+ their complement, performing a disjoint union, and finally getting
407
+ the complement of the resulting graph.
408
+
409
+ Graph, edge, and node attributes are propagated from G and H
410
+ to the union graph. If a graph attribute is present in both
411
+ G and H the value from H is used.
412
+
413
+ Examples
414
+ --------
415
+ >>> G = nx.Graph([(0, 1), (0, 2)])
416
+ >>> H = nx.Graph([(3, 4)])
417
+ >>> R = nx.full_join(G, H, rename=("G", "H"))
418
+ >>> R.nodes
419
+ NodeView(('G0', 'G1', 'G2', 'H3', 'H4'))
420
+ >>> R.edges
421
+ EdgeView([('G0', 'G1'), ('G0', 'G2'), ('G0', 'H3'), ('G0', 'H4'), ('G1', 'H3'), ('G1', 'H4'), ('G2', 'H3'), ('G2', 'H4'), ('H3', 'H4')])
422
+
423
+ See Also
424
+ --------
425
+ union
426
+ disjoint_union
427
+ """
428
+ R = union(G, H, rename)
429
+
430
+ def add_prefix(graph, prefix):
431
+ if prefix is None:
432
+ return graph
433
+
434
+ def label(x):
435
+ return f"{prefix}{x}"
436
+
437
+ return nx.relabel_nodes(graph, label)
438
+
439
+ G = add_prefix(G, rename[0])
440
+ H = add_prefix(H, rename[1])
441
+
442
+ for i in G:
443
+ for j in H:
444
+ R.add_edge(i, j)
445
+ if R.is_directed():
446
+ for i in H:
447
+ for j in G:
448
+ R.add_edge(i, j)
449
+
450
+ return R
minigpt2/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
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py ADDED
File without changes
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (189 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_all.cpython-310.pyc ADDED
Binary file (7.85 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_binary.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_product.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_unary.cpython-310.pyc ADDED
Binary file (1.4 kB). View file
 
minigpt2/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([])
minigpt2/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)
minigpt2/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)
minigpt2/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)
minigpt2/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)
minigpt2/lib/python3.10/site-packages/networkx/drawing/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # graph drawing and interface to graphviz
2
+
3
+ from .layout import *
4
+ from .nx_latex import *
5
+ from .nx_pylab import *
6
+ from . import nx_agraph
7
+ from . import nx_pydot
minigpt2/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc ADDED
Binary file (22.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
minigpt2/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
+ )