jasonfan commited on
Commit
fd4a555
·
verified ·
1 Parent(s): b7d0d6f

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 +2 -0
  2. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/INSTALLER +1 -0
  3. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/LICENSE.txt +37 -0
  4. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/METADATA +165 -0
  5. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/RECORD +0 -0
  6. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/WHEEL +5 -0
  7. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/entry_points.txt +2 -0
  8. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/top_level.txt +1 -0
  9. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py +0 -0
  10. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/tests/test_all.py +328 -0
  11. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/tests/test_binary.py +453 -0
  12. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/tests/test_product.py +491 -0
  13. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/tests/test_unary.py +55 -0
  14. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/unary.py +77 -0
  15. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/__init__.py +5 -0
  16. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/astar.py +241 -0
  17. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/dense.py +260 -0
  18. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/generic.py +730 -0
  19. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__init__.py +0 -0
  20. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_astar.py +248 -0
  21. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense.py +212 -0
  22. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py +89 -0
  23. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_generic.py +450 -0
  24. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_unweighted.py +149 -0
  25. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_weighted.py +972 -0
  26. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/unweighted.py +579 -0
  27. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/weighted.py +2520 -0
  28. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/__init__.py +0 -0
  29. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py +23 -0
  30. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py +154 -0
  31. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py +144 -0
  32. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py +82 -0
  33. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_chains.py +141 -0
  34. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py +129 -0
  35. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_clique.py +291 -0
  36. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_cluster.py +549 -0
  37. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py +80 -0
  38. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_core.py +266 -0
  39. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_covering.py +85 -0
  40. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py +171 -0
  41. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_cycles.py +974 -0
  42. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_d_separation.py +348 -0
  43. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_dag.py +835 -0
  44. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_distance_measures.py +774 -0
  45. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_distance_regular.py +85 -0
  46. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_dominance.py +286 -0
  47. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py +46 -0
  48. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_efficiency.py +58 -0
  49. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_euler.py +314 -0
  50. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_graph_hashing.py +686 -0
.gitattributes CHANGED
@@ -212,3 +212,5 @@ code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packag
212
  code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/google/_upb/_message.abi3.so filter=lfs diff=lfs merge=lfs -text
213
  code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
214
  code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/multidict/_multidict.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
212
  code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/google/_upb/_message.abi3.so filter=lfs diff=lfs merge=lfs -text
213
  code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
214
  code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/multidict/_multidict.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
215
+ code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/numpy/fft/_pocketfft_umath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
216
+ code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NetworkX is distributed with the 3-clause BSD license.
2
+
3
+ ::
4
+
5
+ Copyright (C) 2004-2024, NetworkX Developers
6
+ Aric Hagberg <hagberg@lanl.gov>
7
+ Dan Schult <dschult@colgate.edu>
8
+ Pieter Swart <swart@lanl.gov>
9
+ All rights reserved.
10
+
11
+ Redistribution and use in source and binary forms, with or without
12
+ modification, are permitted provided that the following conditions are
13
+ met:
14
+
15
+ * Redistributions of source code must retain the above copyright
16
+ notice, this list of conditions and the following disclaimer.
17
+
18
+ * Redistributions in binary form must reproduce the above
19
+ copyright notice, this list of conditions and the following
20
+ disclaimer in the documentation and/or other materials provided
21
+ with the distribution.
22
+
23
+ * Neither the name of the NetworkX Developers nor the names of its
24
+ contributors may be used to endorse or promote products derived
25
+ from this software without specific prior written permission.
26
+
27
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/METADATA ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: networkx
3
+ Version: 3.4.2
4
+ Summary: Python package for creating and manipulating graphs and networks
5
+ Author-email: Aric Hagberg <hagberg@lanl.gov>
6
+ Maintainer-email: NetworkX Developers <networkx-discuss@googlegroups.com>
7
+ Project-URL: Homepage, https://networkx.org/
8
+ Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues
9
+ Project-URL: Documentation, https://networkx.org/documentation/stable/
10
+ Project-URL: Source Code, https://github.com/networkx/networkx
11
+ Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math
12
+ Platform: Linux
13
+ Platform: Mac OSX
14
+ Platform: Windows
15
+ Platform: Unix
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: License :: OSI Approved :: BSD License
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Programming Language :: Python :: 3 :: Only
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
28
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
29
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
30
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
31
+ Classifier: Topic :: Scientific/Engineering :: Physics
32
+ Requires-Python: >=3.10
33
+ Description-Content-Type: text/x-rst
34
+ License-File: LICENSE.txt
35
+ Provides-Extra: default
36
+ Requires-Dist: numpy >=1.24 ; extra == 'default'
37
+ Requires-Dist: scipy !=1.11.0,!=1.11.1,>=1.10 ; extra == 'default'
38
+ Requires-Dist: matplotlib >=3.7 ; extra == 'default'
39
+ Requires-Dist: pandas >=2.0 ; extra == 'default'
40
+ Provides-Extra: developer
41
+ Requires-Dist: changelist ==0.5 ; extra == 'developer'
42
+ Requires-Dist: pre-commit >=3.2 ; extra == 'developer'
43
+ Requires-Dist: mypy >=1.1 ; extra == 'developer'
44
+ Requires-Dist: rtoml ; extra == 'developer'
45
+ Provides-Extra: doc
46
+ Requires-Dist: sphinx >=7.3 ; extra == 'doc'
47
+ Requires-Dist: pydata-sphinx-theme >=0.15 ; extra == 'doc'
48
+ Requires-Dist: sphinx-gallery >=0.16 ; extra == 'doc'
49
+ Requires-Dist: numpydoc >=1.8.0 ; extra == 'doc'
50
+ Requires-Dist: pillow >=9.4 ; extra == 'doc'
51
+ Requires-Dist: texext >=0.6.7 ; extra == 'doc'
52
+ Requires-Dist: myst-nb >=1.1 ; extra == 'doc'
53
+ Requires-Dist: intersphinx-registry ; extra == 'doc'
54
+ Provides-Extra: example
55
+ Requires-Dist: osmnx >=1.9 ; extra == 'example'
56
+ Requires-Dist: momepy >=0.7.2 ; extra == 'example'
57
+ Requires-Dist: contextily >=1.6 ; extra == 'example'
58
+ Requires-Dist: seaborn >=0.13 ; extra == 'example'
59
+ Requires-Dist: cairocffi >=1.7 ; extra == 'example'
60
+ Requires-Dist: igraph >=0.11 ; extra == 'example'
61
+ Requires-Dist: scikit-learn >=1.5 ; extra == 'example'
62
+ Provides-Extra: extra
63
+ Requires-Dist: lxml >=4.6 ; extra == 'extra'
64
+ Requires-Dist: pygraphviz >=1.14 ; extra == 'extra'
65
+ Requires-Dist: pydot >=3.0.1 ; extra == 'extra'
66
+ Requires-Dist: sympy >=1.10 ; extra == 'extra'
67
+ Provides-Extra: test
68
+ Requires-Dist: pytest >=7.2 ; extra == 'test'
69
+ Requires-Dist: pytest-cov >=4.0 ; extra == 'test'
70
+
71
+ NetworkX
72
+ ========
73
+
74
+
75
+ .. image::
76
+ https://github.com/networkx/networkx/workflows/test/badge.svg?branch=main
77
+ :target: https://github.com/networkx/networkx/actions?query=workflow%3Atest
78
+
79
+ .. image::
80
+ https://codecov.io/gh/networkx/networkx/branch/main/graph/badge.svg?
81
+ :target: https://app.codecov.io/gh/networkx/networkx/branch/main
82
+
83
+ .. image::
84
+ https://img.shields.io/pypi/v/networkx.svg?
85
+ :target: https://pypi.python.org/pypi/networkx
86
+
87
+ .. image::
88
+ https://img.shields.io/pypi/l/networkx.svg?
89
+ :target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
90
+
91
+ .. image::
92
+ https://img.shields.io/pypi/pyversions/networkx.svg?
93
+ :target: https://pypi.python.org/pypi/networkx
94
+
95
+ .. image::
96
+ https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute
97
+ :target: https://github.com/networkx/networkx/contribute
98
+
99
+
100
+ NetworkX is a Python package for the creation, manipulation,
101
+ and study of the structure, dynamics, and functions
102
+ of complex networks.
103
+
104
+ - **Website (including documentation):** https://networkx.org
105
+ - **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
106
+ - **Source:** https://github.com/networkx/networkx
107
+ - **Bug reports:** https://github.com/networkx/networkx/issues
108
+ - **Report a security vulnerability:** https://tidelift.com/security
109
+ - **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
110
+ - **GitHub Discussions:** https://github.com/networkx/networkx/discussions
111
+ - **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz
112
+ - **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
113
+
114
+ Simple example
115
+ --------------
116
+
117
+ Find the shortest path between two nodes in an undirected graph:
118
+
119
+ .. code:: pycon
120
+
121
+ >>> import networkx as nx
122
+ >>> G = nx.Graph()
123
+ >>> G.add_edge("A", "B", weight=4)
124
+ >>> G.add_edge("B", "D", weight=2)
125
+ >>> G.add_edge("A", "C", weight=3)
126
+ >>> G.add_edge("C", "D", weight=4)
127
+ >>> nx.shortest_path(G, "A", "D", weight="weight")
128
+ ['A', 'B', 'D']
129
+
130
+ Install
131
+ -------
132
+
133
+ Install the latest released version of NetworkX:
134
+
135
+ .. code:: shell
136
+
137
+ $ pip install networkx
138
+
139
+ Install with all optional dependencies:
140
+
141
+ .. code:: shell
142
+
143
+ $ pip install networkx[default]
144
+
145
+ For additional details,
146
+ please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
147
+
148
+ Bugs
149
+ ----
150
+
151
+ Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
152
+ Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
153
+ and create a pull request (PR). We welcome all changes, big or small, and we
154
+ will help you make the PR if you are new to `git` (just ask on the issue and/or
155
+ see the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
156
+
157
+ License
158
+ -------
159
+
160
+ Released under the `3-Clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
161
+
162
+ Copyright (C) 2004-2024 NetworkX Developers
163
+ Aric Hagberg <hagberg@lanl.gov>
164
+ Dan Schult <dschult@colgate.edu>
165
+ Pieter Swart <swart@lanl.gov>
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [networkx.backends]
2
+ nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx-3.4.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ networkx
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/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([])
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/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)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/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)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/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)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/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)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from networkx.algorithms.shortest_paths.generic import *
2
+ from networkx.algorithms.shortest_paths.unweighted import *
3
+ from networkx.algorithms.shortest_paths.weighted import *
4
+ from networkx.algorithms.shortest_paths.astar import *
5
+ from networkx.algorithms.shortest_paths.dense import *
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/astar.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shortest paths and path lengths using the A* ("A star") algorithm."""
2
+
3
+ from heapq import heappop, heappush
4
+ from itertools import count
5
+
6
+ import networkx as nx
7
+ from networkx.algorithms.shortest_paths.weighted import _weight_function
8
+
9
+ __all__ = ["astar_path", "astar_path_length"]
10
+
11
+
12
+ @nx._dispatchable(edge_attrs="weight", preserve_node_attrs="heuristic")
13
+ def astar_path(G, source, target, heuristic=None, weight="weight", *, cutoff=None):
14
+ """Returns a list of nodes in a shortest path between source and target
15
+ using the A* ("A-star") algorithm.
16
+
17
+ There may be more than one shortest path. This returns only one.
18
+
19
+ Parameters
20
+ ----------
21
+ G : NetworkX graph
22
+
23
+ source : node
24
+ Starting node for path
25
+
26
+ target : node
27
+ Ending node for path
28
+
29
+ heuristic : function
30
+ A function to evaluate the estimate of the distance
31
+ from the a node to the target. The function takes
32
+ two nodes arguments and must return a number.
33
+ If the heuristic is inadmissible (if it might
34
+ overestimate the cost of reaching the goal from a node),
35
+ the result may not be a shortest path.
36
+ The algorithm does not support updating heuristic
37
+ values for the same node due to caching the first
38
+ heuristic calculation per node.
39
+
40
+ weight : string or function
41
+ If this is a string, then edge weights will be accessed via the
42
+ edge attribute with this key (that is, the weight of the edge
43
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
44
+ such edge attribute exists, the weight of the edge is assumed to
45
+ be one.
46
+ If this is a function, the weight of an edge is the value
47
+ returned by the function. The function must accept exactly three
48
+ positional arguments: the two endpoints of an edge and the
49
+ dictionary of edge attributes for that edge. The function must
50
+ return a number or None to indicate a hidden edge.
51
+
52
+ cutoff : float, optional
53
+ If this is provided, the search will be bounded to this value. I.e. if
54
+ the evaluation function surpasses this value for a node n, the node will not
55
+ be expanded further and will be ignored. More formally, let h'(n) be the
56
+ heuristic function, and g(n) be the cost of reaching n from the source node. Then,
57
+ if g(n) + h'(n) > cutoff, the node will not be explored further.
58
+ Note that if the heuristic is inadmissible, it is possible that paths
59
+ are ignored even though they satisfy the cutoff.
60
+
61
+ Raises
62
+ ------
63
+ NetworkXNoPath
64
+ If no path exists between source and target.
65
+
66
+ Examples
67
+ --------
68
+ >>> G = nx.path_graph(5)
69
+ >>> print(nx.astar_path(G, 0, 4))
70
+ [0, 1, 2, 3, 4]
71
+ >>> G = nx.grid_graph(dim=[3, 3]) # nodes are two-tuples (x,y)
72
+ >>> nx.set_edge_attributes(G, {e: e[1][0] * 2 for e in G.edges()}, "cost")
73
+ >>> def dist(a, b):
74
+ ... (x1, y1) = a
75
+ ... (x2, y2) = b
76
+ ... return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
77
+ >>> print(nx.astar_path(G, (0, 0), (2, 2), heuristic=dist, weight="cost"))
78
+ [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
79
+
80
+ Notes
81
+ -----
82
+ Edge weight attributes must be numerical.
83
+ Distances are calculated as sums of weighted edges traversed.
84
+
85
+ The weight function can be used to hide edges by returning None.
86
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
87
+ will find the shortest red path.
88
+
89
+ See Also
90
+ --------
91
+ shortest_path, dijkstra_path
92
+
93
+ """
94
+ if source not in G:
95
+ raise nx.NodeNotFound(f"Source {source} is not in G")
96
+
97
+ if target not in G:
98
+ raise nx.NodeNotFound(f"Target {target} is not in G")
99
+
100
+ if heuristic is None:
101
+ # The default heuristic is h=0 - same as Dijkstra's algorithm
102
+ def heuristic(u, v):
103
+ return 0
104
+
105
+ push = heappush
106
+ pop = heappop
107
+ weight = _weight_function(G, weight)
108
+
109
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
110
+
111
+ # The queue stores priority, node, cost to reach, and parent.
112
+ # Uses Python heapq to keep in priority order.
113
+ # Add a counter to the queue to prevent the underlying heap from
114
+ # attempting to compare the nodes themselves. The hash breaks ties in the
115
+ # priority and is guaranteed unique for all nodes in the graph.
116
+ c = count()
117
+ queue = [(0, next(c), source, 0, None)]
118
+
119
+ # Maps enqueued nodes to distance of discovered paths and the
120
+ # computed heuristics to target. We avoid computing the heuristics
121
+ # more than once and inserting the node into the queue too many times.
122
+ enqueued = {}
123
+ # Maps explored nodes to parent closest to the source.
124
+ explored = {}
125
+
126
+ while queue:
127
+ # Pop the smallest item from queue.
128
+ _, __, curnode, dist, parent = pop(queue)
129
+
130
+ if curnode == target:
131
+ path = [curnode]
132
+ node = parent
133
+ while node is not None:
134
+ path.append(node)
135
+ node = explored[node]
136
+ path.reverse()
137
+ return path
138
+
139
+ if curnode in explored:
140
+ # Do not override the parent of starting node
141
+ if explored[curnode] is None:
142
+ continue
143
+
144
+ # Skip bad paths that were enqueued before finding a better one
145
+ qcost, h = enqueued[curnode]
146
+ if qcost < dist:
147
+ continue
148
+
149
+ explored[curnode] = parent
150
+
151
+ for neighbor, w in G_succ[curnode].items():
152
+ cost = weight(curnode, neighbor, w)
153
+ if cost is None:
154
+ continue
155
+ ncost = dist + cost
156
+ if neighbor in enqueued:
157
+ qcost, h = enqueued[neighbor]
158
+ # if qcost <= ncost, a less costly path from the
159
+ # neighbor to the source was already determined.
160
+ # Therefore, we won't attempt to push this neighbor
161
+ # to the queue
162
+ if qcost <= ncost:
163
+ continue
164
+ else:
165
+ h = heuristic(neighbor, target)
166
+
167
+ if cutoff and ncost + h > cutoff:
168
+ continue
169
+
170
+ enqueued[neighbor] = ncost, h
171
+ push(queue, (ncost + h, next(c), neighbor, ncost, curnode))
172
+
173
+ raise nx.NetworkXNoPath(f"Node {target} not reachable from {source}")
174
+
175
+
176
+ @nx._dispatchable(edge_attrs="weight", preserve_node_attrs="heuristic")
177
+ def astar_path_length(
178
+ G, source, target, heuristic=None, weight="weight", *, cutoff=None
179
+ ):
180
+ """Returns the length of the shortest path between source and target using
181
+ the A* ("A-star") algorithm.
182
+
183
+ Parameters
184
+ ----------
185
+ G : NetworkX graph
186
+
187
+ source : node
188
+ Starting node for path
189
+
190
+ target : node
191
+ Ending node for path
192
+
193
+ heuristic : function
194
+ A function to evaluate the estimate of the distance
195
+ from the a node to the target. The function takes
196
+ two nodes arguments and must return a number.
197
+ If the heuristic is inadmissible (if it might
198
+ overestimate the cost of reaching the goal from a node),
199
+ the result may not be a shortest path.
200
+ The algorithm does not support updating heuristic
201
+ values for the same node due to caching the first
202
+ heuristic calculation per node.
203
+
204
+ weight : string or function
205
+ If this is a string, then edge weights will be accessed via the
206
+ edge attribute with this key (that is, the weight of the edge
207
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
208
+ such edge attribute exists, the weight of the edge is assumed to
209
+ be one.
210
+ If this is a function, the weight of an edge is the value
211
+ returned by the function. The function must accept exactly three
212
+ positional arguments: the two endpoints of an edge and the
213
+ dictionary of edge attributes for that edge. The function must
214
+ return a number or None to indicate a hidden edge.
215
+
216
+ cutoff : float, optional
217
+ If this is provided, the search will be bounded to this value. I.e. if
218
+ the evaluation function surpasses this value for a node n, the node will not
219
+ be expanded further and will be ignored. More formally, let h'(n) be the
220
+ heuristic function, and g(n) be the cost of reaching n from the source node. Then,
221
+ if g(n) + h'(n) > cutoff, the node will not be explored further.
222
+ Note that if the heuristic is inadmissible, it is possible that paths
223
+ are ignored even though they satisfy the cutoff.
224
+
225
+ Raises
226
+ ------
227
+ NetworkXNoPath
228
+ If no path exists between source and target.
229
+
230
+ See Also
231
+ --------
232
+ astar_path
233
+
234
+ """
235
+ if source not in G or target not in G:
236
+ msg = f"Either source {source} or target {target} is not in G"
237
+ raise nx.NodeNotFound(msg)
238
+
239
+ weight = _weight_function(G, weight)
240
+ path = astar_path(G, source, target, heuristic, weight, cutoff=cutoff)
241
+ return sum(weight(u, v, G[u][v]) for u, v in zip(path[:-1], path[1:]))
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/dense.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floyd-Warshall algorithm for shortest paths."""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = [
6
+ "floyd_warshall",
7
+ "floyd_warshall_predecessor_and_distance",
8
+ "reconstruct_path",
9
+ "floyd_warshall_numpy",
10
+ ]
11
+
12
+
13
+ @nx._dispatchable(edge_attrs="weight")
14
+ def floyd_warshall_numpy(G, nodelist=None, weight="weight"):
15
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
16
+
17
+ This algorithm for finding shortest paths takes advantage of
18
+ matrix representations of a graph and works well for dense
19
+ graphs where all-pairs shortest path lengths are desired.
20
+ The results are returned as a NumPy array, distance[i, j],
21
+ where i and j are the indexes of two nodes in nodelist.
22
+ The entry distance[i, j] is the distance along a shortest
23
+ path from i to j. If no path exists the distance is Inf.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ nodelist : list, optional (default=G.nodes)
30
+ The rows and columns are ordered by the nodes in nodelist.
31
+ If nodelist is None then the ordering is produced by G.nodes.
32
+ Nodelist should include all nodes in G.
33
+
34
+ weight: string, optional (default='weight')
35
+ Edge data key corresponding to the edge weight.
36
+
37
+ Returns
38
+ -------
39
+ distance : 2D numpy.ndarray
40
+ A numpy array of shortest path distances between nodes.
41
+ If there is no path between two nodes the value is Inf.
42
+
43
+ Examples
44
+ --------
45
+ >>> G = nx.DiGraph()
46
+ >>> G.add_weighted_edges_from(
47
+ ... [(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)]
48
+ ... )
49
+ >>> nx.floyd_warshall_numpy(G)
50
+ array([[ 0., 5., 7., 4.],
51
+ [inf, 0., 2., -1.],
52
+ [inf, inf, 0., -3.],
53
+ [inf, inf, 8., 0.]])
54
+
55
+ Notes
56
+ -----
57
+ Floyd's algorithm is appropriate for finding shortest paths in
58
+ dense graphs or graphs with negative weights when Dijkstra's
59
+ algorithm fails. This algorithm can still fail if there are negative
60
+ cycles. It has running time $O(n^3)$ with running space of $O(n^2)$.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXError
65
+ If nodelist is not a list of the nodes in G.
66
+ """
67
+ import numpy as np
68
+
69
+ if nodelist is not None:
70
+ if not (len(nodelist) == len(G) == len(set(nodelist))):
71
+ raise nx.NetworkXError(
72
+ "nodelist must contain every node in G with no repeats."
73
+ "If you wanted a subgraph of G use G.subgraph(nodelist)"
74
+ )
75
+
76
+ # To handle cases when an edge has weight=0, we must make sure that
77
+ # nonedges are not given the value 0 as well.
78
+ A = nx.to_numpy_array(
79
+ G, nodelist, multigraph_weight=min, weight=weight, nonedge=np.inf
80
+ )
81
+ n, m = A.shape
82
+ np.fill_diagonal(A, 0) # diagonal elements should be zero
83
+ for i in range(n):
84
+ # The second term has the same shape as A due to broadcasting
85
+ A = np.minimum(A, A[i, :][np.newaxis, :] + A[:, i][:, np.newaxis])
86
+ return A
87
+
88
+
89
+ @nx._dispatchable(edge_attrs="weight")
90
+ def floyd_warshall_predecessor_and_distance(G, weight="weight"):
91
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
92
+
93
+ Parameters
94
+ ----------
95
+ G : NetworkX graph
96
+
97
+ weight: string, optional (default= 'weight')
98
+ Edge data key corresponding to the edge weight.
99
+
100
+ Returns
101
+ -------
102
+ predecessor,distance : dictionaries
103
+ Dictionaries, keyed by source and target, of predecessors and distances
104
+ in the shortest path.
105
+
106
+ Examples
107
+ --------
108
+ >>> G = nx.DiGraph()
109
+ >>> G.add_weighted_edges_from(
110
+ ... [
111
+ ... ("s", "u", 10),
112
+ ... ("s", "x", 5),
113
+ ... ("u", "v", 1),
114
+ ... ("u", "x", 2),
115
+ ... ("v", "y", 1),
116
+ ... ("x", "u", 3),
117
+ ... ("x", "v", 5),
118
+ ... ("x", "y", 2),
119
+ ... ("y", "s", 7),
120
+ ... ("y", "v", 6),
121
+ ... ]
122
+ ... )
123
+ >>> predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
124
+ >>> print(nx.reconstruct_path("s", "v", predecessors))
125
+ ['s', 'x', 'u', 'v']
126
+
127
+ Notes
128
+ -----
129
+ Floyd's algorithm is appropriate for finding shortest paths
130
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
131
+ fails. This algorithm can still fail if there are negative cycles.
132
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
133
+
134
+ See Also
135
+ --------
136
+ floyd_warshall
137
+ floyd_warshall_numpy
138
+ all_pairs_shortest_path
139
+ all_pairs_shortest_path_length
140
+ """
141
+ from collections import defaultdict
142
+
143
+ # dictionary-of-dictionaries representation for dist and pred
144
+ # use some defaultdict magick here
145
+ # for dist the default is the floating point inf value
146
+ dist = defaultdict(lambda: defaultdict(lambda: float("inf")))
147
+ for u in G:
148
+ dist[u][u] = 0
149
+ pred = defaultdict(dict)
150
+ # initialize path distance dictionary to be the adjacency matrix
151
+ # also set the distance to self to 0 (zero diagonal)
152
+ undirected = not G.is_directed()
153
+ for u, v, d in G.edges(data=True):
154
+ e_weight = d.get(weight, 1.0)
155
+ dist[u][v] = min(e_weight, dist[u][v])
156
+ pred[u][v] = u
157
+ if undirected:
158
+ dist[v][u] = min(e_weight, dist[v][u])
159
+ pred[v][u] = v
160
+ for w in G:
161
+ dist_w = dist[w] # save recomputation
162
+ for u in G:
163
+ dist_u = dist[u] # save recomputation
164
+ for v in G:
165
+ d = dist_u[w] + dist_w[v]
166
+ if dist_u[v] > d:
167
+ dist_u[v] = d
168
+ pred[u][v] = pred[w][v]
169
+ return dict(pred), dict(dist)
170
+
171
+
172
+ @nx._dispatchable(graphs=None)
173
+ def reconstruct_path(source, target, predecessors):
174
+ """Reconstruct a path from source to target using the predecessors
175
+ dict as returned by floyd_warshall_predecessor_and_distance
176
+
177
+ Parameters
178
+ ----------
179
+ source : node
180
+ Starting node for path
181
+
182
+ target : node
183
+ Ending node for path
184
+
185
+ predecessors: dictionary
186
+ Dictionary, keyed by source and target, of predecessors in the
187
+ shortest path, as returned by floyd_warshall_predecessor_and_distance
188
+
189
+ Returns
190
+ -------
191
+ path : list
192
+ A list of nodes containing the shortest path from source to target
193
+
194
+ If source and target are the same, an empty list is returned
195
+
196
+ Notes
197
+ -----
198
+ This function is meant to give more applicability to the
199
+ floyd_warshall_predecessor_and_distance function
200
+
201
+ See Also
202
+ --------
203
+ floyd_warshall_predecessor_and_distance
204
+ """
205
+ if source == target:
206
+ return []
207
+ prev = predecessors[source]
208
+ curr = prev[target]
209
+ path = [target, curr]
210
+ while curr != source:
211
+ curr = prev[curr]
212
+ path.append(curr)
213
+ return list(reversed(path))
214
+
215
+
216
+ @nx._dispatchable(edge_attrs="weight")
217
+ def floyd_warshall(G, weight="weight"):
218
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
219
+
220
+ Parameters
221
+ ----------
222
+ G : NetworkX graph
223
+
224
+ weight: string, optional (default= 'weight')
225
+ Edge data key corresponding to the edge weight.
226
+
227
+
228
+ Returns
229
+ -------
230
+ distance : dict
231
+ A dictionary, keyed by source and target, of shortest paths distances
232
+ between nodes.
233
+
234
+ Examples
235
+ --------
236
+ >>> G = nx.DiGraph()
237
+ >>> G.add_weighted_edges_from(
238
+ ... [(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)]
239
+ ... )
240
+ >>> fw = nx.floyd_warshall(G, weight="weight")
241
+ >>> results = {a: dict(b) for a, b in fw.items()}
242
+ >>> print(results)
243
+ {0: {0: 0, 1: 5, 2: 7, 3: 4}, 1: {1: 0, 2: 2, 3: -1, 0: inf}, 2: {2: 0, 3: -3, 0: inf, 1: inf}, 3: {3: 0, 2: 8, 0: inf, 1: inf}}
244
+
245
+ Notes
246
+ -----
247
+ Floyd's algorithm is appropriate for finding shortest paths
248
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
249
+ fails. This algorithm can still fail if there are negative cycles.
250
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
251
+
252
+ See Also
253
+ --------
254
+ floyd_warshall_predecessor_and_distance
255
+ floyd_warshall_numpy
256
+ all_pairs_shortest_path
257
+ all_pairs_shortest_path_length
258
+ """
259
+ # could make this its own function to reduce memory costs
260
+ return floyd_warshall_predecessor_and_distance(G, weight=weight)[1]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/generic.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Compute the shortest paths and path lengths between nodes in the graph.
3
+
4
+ These algorithms work with undirected and directed graphs.
5
+
6
+ """
7
+
8
+ import warnings
9
+
10
+ import networkx as nx
11
+
12
+ __all__ = [
13
+ "shortest_path",
14
+ "all_shortest_paths",
15
+ "single_source_all_shortest_paths",
16
+ "all_pairs_all_shortest_paths",
17
+ "shortest_path_length",
18
+ "average_shortest_path_length",
19
+ "has_path",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable
24
+ def has_path(G, source, target):
25
+ """Returns *True* if *G* has a path from *source* to *target*.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : node
32
+ Starting node for path
33
+
34
+ target : node
35
+ Ending node for path
36
+ """
37
+ try:
38
+ nx.shortest_path(G, source, target)
39
+ except nx.NetworkXNoPath:
40
+ return False
41
+ return True
42
+
43
+
44
+ @nx._dispatchable(edge_attrs="weight")
45
+ def shortest_path(G, source=None, target=None, weight=None, method="dijkstra"):
46
+ """Compute shortest paths in the graph.
47
+
48
+ Parameters
49
+ ----------
50
+ G : NetworkX graph
51
+
52
+ source : node, optional
53
+ Starting node for path. If not specified, compute shortest
54
+ paths for each possible starting node.
55
+
56
+ target : node, optional
57
+ Ending node for path. If not specified, compute shortest
58
+ paths to all possible nodes.
59
+
60
+ weight : None, string or function, optional (default = None)
61
+ If None, every edge has weight/distance/cost 1.
62
+ If a string, use this edge attribute as the edge weight.
63
+ Any edge attribute not present defaults to 1.
64
+ If this is a function, the weight of an edge is the value
65
+ returned by the function. The function must accept exactly
66
+ three positional arguments: the two endpoints of an edge and
67
+ the dictionary of edge attributes for that edge.
68
+ The function must return a number.
69
+
70
+ method : string, optional (default = 'dijkstra')
71
+ The algorithm to use to compute the path.
72
+ Supported options: 'dijkstra', 'bellman-ford'.
73
+ Other inputs produce a ValueError.
74
+ If `weight` is None, unweighted graph methods are used, and this
75
+ suggestion is ignored.
76
+
77
+ Returns
78
+ -------
79
+ path: list or dictionary
80
+ All returned paths include both the source and target in the path.
81
+
82
+ If the source and target are both specified, return a single list
83
+ of nodes in a shortest path from the source to the target.
84
+
85
+ If only the source is specified, return a dictionary keyed by
86
+ targets with a list of nodes in a shortest path from the source
87
+ to one of the targets.
88
+
89
+ If only the target is specified, return a dictionary keyed by
90
+ sources with a list of nodes in a shortest path from one of the
91
+ sources to the target.
92
+
93
+ If neither the source nor target are specified return a dictionary
94
+ of dictionaries with path[source][target]=[list of nodes in path].
95
+
96
+ Raises
97
+ ------
98
+ NodeNotFound
99
+ If `source` is not in `G`.
100
+
101
+ ValueError
102
+ If `method` is not among the supported options.
103
+
104
+ Examples
105
+ --------
106
+ >>> G = nx.path_graph(5)
107
+ >>> print(nx.shortest_path(G, source=0, target=4))
108
+ [0, 1, 2, 3, 4]
109
+ >>> p = nx.shortest_path(G, source=0) # target not specified
110
+ >>> p[3] # shortest path from source=0 to target=3
111
+ [0, 1, 2, 3]
112
+ >>> p = nx.shortest_path(G, target=4) # source not specified
113
+ >>> p[1] # shortest path from source=1 to target=4
114
+ [1, 2, 3, 4]
115
+ >>> p = dict(nx.shortest_path(G)) # source, target not specified
116
+ >>> p[2][4] # shortest path from source=2 to target=4
117
+ [2, 3, 4]
118
+
119
+ Notes
120
+ -----
121
+ There may be more than one shortest path between a source and target.
122
+ This returns only one of them.
123
+
124
+ See Also
125
+ --------
126
+ all_pairs_shortest_path
127
+ all_pairs_dijkstra_path
128
+ all_pairs_bellman_ford_path
129
+ single_source_shortest_path
130
+ single_source_dijkstra_path
131
+ single_source_bellman_ford_path
132
+ """
133
+ if method not in ("dijkstra", "bellman-ford"):
134
+ # so we don't need to check in each branch later
135
+ raise ValueError(f"method not supported: {method}")
136
+ method = "unweighted" if weight is None else method
137
+ if source is None:
138
+ if target is None:
139
+ warnings.warn(
140
+ (
141
+ "\n\nshortest_path will return an iterator that yields\n"
142
+ "(node, path) pairs instead of a dictionary when source\n"
143
+ "and target are unspecified beginning in version 3.5\n\n"
144
+ "To keep the current behavior, use:\n\n"
145
+ "\tdict(nx.shortest_path(G))"
146
+ ),
147
+ FutureWarning,
148
+ stacklevel=3,
149
+ )
150
+
151
+ # Find paths between all pairs.
152
+ if method == "unweighted":
153
+ paths = dict(nx.all_pairs_shortest_path(G))
154
+ elif method == "dijkstra":
155
+ paths = dict(nx.all_pairs_dijkstra_path(G, weight=weight))
156
+ else: # method == 'bellman-ford':
157
+ paths = dict(nx.all_pairs_bellman_ford_path(G, weight=weight))
158
+ else:
159
+ # Find paths from all nodes co-accessible to the target.
160
+ if G.is_directed():
161
+ G = G.reverse(copy=False)
162
+ if method == "unweighted":
163
+ paths = nx.single_source_shortest_path(G, target)
164
+ elif method == "dijkstra":
165
+ paths = nx.single_source_dijkstra_path(G, target, weight=weight)
166
+ else: # method == 'bellman-ford':
167
+ paths = nx.single_source_bellman_ford_path(G, target, weight=weight)
168
+ # Now flip the paths so they go from a source to the target.
169
+ for target in paths:
170
+ paths[target] = list(reversed(paths[target]))
171
+ else:
172
+ if target is None:
173
+ # Find paths to all nodes accessible from the source.
174
+ if method == "unweighted":
175
+ paths = nx.single_source_shortest_path(G, source)
176
+ elif method == "dijkstra":
177
+ paths = nx.single_source_dijkstra_path(G, source, weight=weight)
178
+ else: # method == 'bellman-ford':
179
+ paths = nx.single_source_bellman_ford_path(G, source, weight=weight)
180
+ else:
181
+ # Find shortest source-target path.
182
+ if method == "unweighted":
183
+ paths = nx.bidirectional_shortest_path(G, source, target)
184
+ elif method == "dijkstra":
185
+ _, paths = nx.bidirectional_dijkstra(G, source, target, weight)
186
+ else: # method == 'bellman-ford':
187
+ paths = nx.bellman_ford_path(G, source, target, weight)
188
+ return paths
189
+
190
+
191
+ @nx._dispatchable(edge_attrs="weight")
192
+ def shortest_path_length(G, source=None, target=None, weight=None, method="dijkstra"):
193
+ """Compute shortest path lengths in the graph.
194
+
195
+ Parameters
196
+ ----------
197
+ G : NetworkX graph
198
+
199
+ source : node, optional
200
+ Starting node for path.
201
+ If not specified, compute shortest path lengths using all nodes as
202
+ source nodes.
203
+
204
+ target : node, optional
205
+ Ending node for path.
206
+ If not specified, compute shortest path lengths using all nodes as
207
+ target nodes.
208
+
209
+ weight : None, string or function, optional (default = None)
210
+ If None, every edge has weight/distance/cost 1.
211
+ If a string, use this edge attribute as the edge weight.
212
+ Any edge attribute not present defaults to 1.
213
+ If this is a function, the weight of an edge is the value
214
+ returned by the function. The function must accept exactly
215
+ three positional arguments: the two endpoints of an edge and
216
+ the dictionary of edge attributes for that edge.
217
+ The function must return a number.
218
+
219
+ method : string, optional (default = 'dijkstra')
220
+ The algorithm to use to compute the path length.
221
+ Supported options: 'dijkstra', 'bellman-ford'.
222
+ Other inputs produce a ValueError.
223
+ If `weight` is None, unweighted graph methods are used, and this
224
+ suggestion is ignored.
225
+
226
+ Returns
227
+ -------
228
+ length: number or iterator
229
+ If the source and target are both specified, return the length of
230
+ the shortest path from the source to the target.
231
+
232
+ If only the source is specified, return a dict keyed by target
233
+ to the shortest path length from the source to that target.
234
+
235
+ If only the target is specified, return a dict keyed by source
236
+ to the shortest path length from that source to the target.
237
+
238
+ If neither the source nor target are specified, return an iterator
239
+ over (source, dictionary) where dictionary is keyed by target to
240
+ shortest path length from source to that target.
241
+
242
+ Raises
243
+ ------
244
+ NodeNotFound
245
+ If `source` is not in `G`.
246
+
247
+ NetworkXNoPath
248
+ If no path exists between source and target.
249
+
250
+ ValueError
251
+ If `method` is not among the supported options.
252
+
253
+ Examples
254
+ --------
255
+ >>> G = nx.path_graph(5)
256
+ >>> nx.shortest_path_length(G, source=0, target=4)
257
+ 4
258
+ >>> p = nx.shortest_path_length(G, source=0) # target not specified
259
+ >>> p[4]
260
+ 4
261
+ >>> p = nx.shortest_path_length(G, target=4) # source not specified
262
+ >>> p[0]
263
+ 4
264
+ >>> p = dict(nx.shortest_path_length(G)) # source,target not specified
265
+ >>> p[0][4]
266
+ 4
267
+
268
+ Notes
269
+ -----
270
+ The length of the path is always 1 less than the number of nodes involved
271
+ in the path since the length measures the number of edges followed.
272
+
273
+ For digraphs this returns the shortest directed path length. To find path
274
+ lengths in the reverse direction use G.reverse(copy=False) first to flip
275
+ the edge orientation.
276
+
277
+ See Also
278
+ --------
279
+ all_pairs_shortest_path_length
280
+ all_pairs_dijkstra_path_length
281
+ all_pairs_bellman_ford_path_length
282
+ single_source_shortest_path_length
283
+ single_source_dijkstra_path_length
284
+ single_source_bellman_ford_path_length
285
+ """
286
+ if method not in ("dijkstra", "bellman-ford"):
287
+ # so we don't need to check in each branch later
288
+ raise ValueError(f"method not supported: {method}")
289
+ method = "unweighted" if weight is None else method
290
+ if source is None:
291
+ if target is None:
292
+ # Find paths between all pairs.
293
+ if method == "unweighted":
294
+ paths = nx.all_pairs_shortest_path_length(G)
295
+ elif method == "dijkstra":
296
+ paths = nx.all_pairs_dijkstra_path_length(G, weight=weight)
297
+ else: # method == 'bellman-ford':
298
+ paths = nx.all_pairs_bellman_ford_path_length(G, weight=weight)
299
+ else:
300
+ # Find paths from all nodes co-accessible to the target.
301
+ if G.is_directed():
302
+ G = G.reverse(copy=False)
303
+ if method == "unweighted":
304
+ path_length = nx.single_source_shortest_path_length
305
+ paths = path_length(G, target)
306
+ elif method == "dijkstra":
307
+ path_length = nx.single_source_dijkstra_path_length
308
+ paths = path_length(G, target, weight=weight)
309
+ else: # method == 'bellman-ford':
310
+ path_length = nx.single_source_bellman_ford_path_length
311
+ paths = path_length(G, target, weight=weight)
312
+ else:
313
+ if target is None:
314
+ # Find paths to all nodes accessible from the source.
315
+ if method == "unweighted":
316
+ paths = nx.single_source_shortest_path_length(G, source)
317
+ elif method == "dijkstra":
318
+ path_length = nx.single_source_dijkstra_path_length
319
+ paths = path_length(G, source, weight=weight)
320
+ else: # method == 'bellman-ford':
321
+ path_length = nx.single_source_bellman_ford_path_length
322
+ paths = path_length(G, source, weight=weight)
323
+ else:
324
+ # Find shortest source-target path.
325
+ if method == "unweighted":
326
+ p = nx.bidirectional_shortest_path(G, source, target)
327
+ paths = len(p) - 1
328
+ elif method == "dijkstra":
329
+ paths = nx.dijkstra_path_length(G, source, target, weight)
330
+ else: # method == 'bellman-ford':
331
+ paths = nx.bellman_ford_path_length(G, source, target, weight)
332
+ return paths
333
+
334
+
335
+ @nx._dispatchable(edge_attrs="weight")
336
+ def average_shortest_path_length(G, weight=None, method=None):
337
+ r"""Returns the average shortest path length.
338
+
339
+ The average shortest path length is
340
+
341
+ .. math::
342
+
343
+ a =\sum_{\substack{s,t \in V \\ s\neq t}} \frac{d(s, t)}{n(n-1)}
344
+
345
+ where `V` is the set of nodes in `G`,
346
+ `d(s, t)` is the shortest path from `s` to `t`,
347
+ and `n` is the number of nodes in `G`.
348
+
349
+ .. versionchanged:: 3.0
350
+ An exception is raised for directed graphs that are not strongly
351
+ connected.
352
+
353
+ Parameters
354
+ ----------
355
+ G : NetworkX graph
356
+
357
+ weight : None, string or function, optional (default = None)
358
+ If None, every edge has weight/distance/cost 1.
359
+ If a string, use this edge attribute as the edge weight.
360
+ Any edge attribute not present defaults to 1.
361
+ If this is a function, the weight of an edge is the value
362
+ returned by the function. The function must accept exactly
363
+ three positional arguments: the two endpoints of an edge and
364
+ the dictionary of edge attributes for that edge.
365
+ The function must return a number.
366
+
367
+ method : string, optional (default = 'unweighted' or 'dijkstra')
368
+ The algorithm to use to compute the path lengths.
369
+ Supported options are 'unweighted', 'dijkstra', 'bellman-ford',
370
+ 'floyd-warshall' and 'floyd-warshall-numpy'.
371
+ Other method values produce a ValueError.
372
+ The default method is 'unweighted' if `weight` is None,
373
+ otherwise the default method is 'dijkstra'.
374
+
375
+ Raises
376
+ ------
377
+ NetworkXPointlessConcept
378
+ If `G` is the null graph (that is, the graph on zero nodes).
379
+
380
+ NetworkXError
381
+ If `G` is not connected (or not strongly connected, in the case
382
+ of a directed graph).
383
+
384
+ ValueError
385
+ If `method` is not among the supported options.
386
+
387
+ Examples
388
+ --------
389
+ >>> G = nx.path_graph(5)
390
+ >>> nx.average_shortest_path_length(G)
391
+ 2.0
392
+
393
+ For disconnected graphs, you can compute the average shortest path
394
+ length for each component
395
+
396
+ >>> G = nx.Graph([(1, 2), (3, 4)])
397
+ >>> for C in (G.subgraph(c).copy() for c in nx.connected_components(G)):
398
+ ... print(nx.average_shortest_path_length(C))
399
+ 1.0
400
+ 1.0
401
+
402
+ """
403
+ single_source_methods = ["unweighted", "dijkstra", "bellman-ford"]
404
+ all_pairs_methods = ["floyd-warshall", "floyd-warshall-numpy"]
405
+ supported_methods = single_source_methods + all_pairs_methods
406
+
407
+ if method is None:
408
+ method = "unweighted" if weight is None else "dijkstra"
409
+ if method not in supported_methods:
410
+ raise ValueError(f"method not supported: {method}")
411
+
412
+ n = len(G)
413
+ # For the special case of the null graph, raise an exception, since
414
+ # there are no paths in the null graph.
415
+ if n == 0:
416
+ msg = (
417
+ "the null graph has no paths, thus there is no average "
418
+ "shortest path length"
419
+ )
420
+ raise nx.NetworkXPointlessConcept(msg)
421
+ # For the special case of the trivial graph, return zero immediately.
422
+ if n == 1:
423
+ return 0
424
+ # Shortest path length is undefined if the graph is not strongly connected.
425
+ if G.is_directed() and not nx.is_strongly_connected(G):
426
+ raise nx.NetworkXError("Graph is not strongly connected.")
427
+ # Shortest path length is undefined if the graph is not connected.
428
+ if not G.is_directed() and not nx.is_connected(G):
429
+ raise nx.NetworkXError("Graph is not connected.")
430
+
431
+ # Compute all-pairs shortest paths.
432
+ def path_length(v):
433
+ if method == "unweighted":
434
+ return nx.single_source_shortest_path_length(G, v)
435
+ elif method == "dijkstra":
436
+ return nx.single_source_dijkstra_path_length(G, v, weight=weight)
437
+ elif method == "bellman-ford":
438
+ return nx.single_source_bellman_ford_path_length(G, v, weight=weight)
439
+
440
+ if method in single_source_methods:
441
+ # Sum the distances for each (ordered) pair of source and target node.
442
+ s = sum(l for u in G for l in path_length(u).values())
443
+ else:
444
+ if method == "floyd-warshall":
445
+ all_pairs = nx.floyd_warshall(G, weight=weight)
446
+ s = sum(sum(t.values()) for t in all_pairs.values())
447
+ elif method == "floyd-warshall-numpy":
448
+ s = float(nx.floyd_warshall_numpy(G, weight=weight).sum())
449
+ return s / (n * (n - 1))
450
+
451
+
452
+ @nx._dispatchable(edge_attrs="weight")
453
+ def all_shortest_paths(G, source, target, weight=None, method="dijkstra"):
454
+ """Compute all shortest simple paths in the graph.
455
+
456
+ Parameters
457
+ ----------
458
+ G : NetworkX graph
459
+
460
+ source : node
461
+ Starting node for path.
462
+
463
+ target : node
464
+ Ending node for path.
465
+
466
+ weight : None, string or function, optional (default = None)
467
+ If None, every edge has weight/distance/cost 1.
468
+ If a string, use this edge attribute as the edge weight.
469
+ Any edge attribute not present defaults to 1.
470
+ If this is a function, the weight of an edge is the value
471
+ returned by the function. The function must accept exactly
472
+ three positional arguments: the two endpoints of an edge and
473
+ the dictionary of edge attributes for that edge.
474
+ The function must return a number.
475
+
476
+ method : string, optional (default = 'dijkstra')
477
+ The algorithm to use to compute the path lengths.
478
+ Supported options: 'dijkstra', 'bellman-ford'.
479
+ Other inputs produce a ValueError.
480
+ If `weight` is None, unweighted graph methods are used, and this
481
+ suggestion is ignored.
482
+
483
+ Returns
484
+ -------
485
+ paths : generator of lists
486
+ A generator of all paths between source and target.
487
+
488
+ Raises
489
+ ------
490
+ ValueError
491
+ If `method` is not among the supported options.
492
+
493
+ NetworkXNoPath
494
+ If `target` cannot be reached from `source`.
495
+
496
+ Examples
497
+ --------
498
+ >>> G = nx.Graph()
499
+ >>> nx.add_path(G, [0, 1, 2])
500
+ >>> nx.add_path(G, [0, 10, 2])
501
+ >>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)])
502
+ [[0, 1, 2], [0, 10, 2]]
503
+
504
+ Notes
505
+ -----
506
+ There may be many shortest paths between the source and target. If G
507
+ contains zero-weight cycles, this function will not produce all shortest
508
+ paths because doing so would produce infinitely many paths of unbounded
509
+ length -- instead, we only produce the shortest simple paths.
510
+
511
+ See Also
512
+ --------
513
+ shortest_path
514
+ single_source_shortest_path
515
+ all_pairs_shortest_path
516
+ """
517
+ method = "unweighted" if weight is None else method
518
+ if method == "unweighted":
519
+ pred = nx.predecessor(G, source)
520
+ elif method == "dijkstra":
521
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight)
522
+ elif method == "bellman-ford":
523
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight)
524
+ else:
525
+ raise ValueError(f"method not supported: {method}")
526
+
527
+ return _build_paths_from_predecessors({source}, target, pred)
528
+
529
+
530
+ @nx._dispatchable(edge_attrs="weight")
531
+ def single_source_all_shortest_paths(G, source, weight=None, method="dijkstra"):
532
+ """Compute all shortest simple paths from the given source in the graph.
533
+
534
+ Parameters
535
+ ----------
536
+ G : NetworkX graph
537
+
538
+ source : node
539
+ Starting node for path.
540
+
541
+ weight : None, string or function, optional (default = None)
542
+ If None, every edge has weight/distance/cost 1.
543
+ If a string, use this edge attribute as the edge weight.
544
+ Any edge attribute not present defaults to 1.
545
+ If this is a function, the weight of an edge is the value
546
+ returned by the function. The function must accept exactly
547
+ three positional arguments: the two endpoints of an edge and
548
+ the dictionary of edge attributes for that edge.
549
+ The function must return a number.
550
+
551
+ method : string, optional (default = 'dijkstra')
552
+ The algorithm to use to compute the path lengths.
553
+ Supported options: 'dijkstra', 'bellman-ford'.
554
+ Other inputs produce a ValueError.
555
+ If `weight` is None, unweighted graph methods are used, and this
556
+ suggestion is ignored.
557
+
558
+ Returns
559
+ -------
560
+ paths : generator of dictionary
561
+ A generator of all paths between source and all nodes in the graph.
562
+
563
+ Raises
564
+ ------
565
+ ValueError
566
+ If `method` is not among the supported options.
567
+
568
+ Examples
569
+ --------
570
+ >>> G = nx.Graph()
571
+ >>> nx.add_path(G, [0, 1, 2, 3, 0])
572
+ >>> dict(nx.single_source_all_shortest_paths(G, source=0))
573
+ {0: [[0]], 1: [[0, 1]], 2: [[0, 1, 2], [0, 3, 2]], 3: [[0, 3]]}
574
+
575
+ Notes
576
+ -----
577
+ There may be many shortest paths between the source and target. If G
578
+ contains zero-weight cycles, this function will not produce all shortest
579
+ paths because doing so would produce infinitely many paths of unbounded
580
+ length -- instead, we only produce the shortest simple paths.
581
+
582
+ See Also
583
+ --------
584
+ shortest_path
585
+ all_shortest_paths
586
+ single_source_shortest_path
587
+ all_pairs_shortest_path
588
+ all_pairs_all_shortest_paths
589
+ """
590
+ method = "unweighted" if weight is None else method
591
+ if method == "unweighted":
592
+ pred = nx.predecessor(G, source)
593
+ elif method == "dijkstra":
594
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight)
595
+ elif method == "bellman-ford":
596
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight)
597
+ else:
598
+ raise ValueError(f"method not supported: {method}")
599
+ for n in G:
600
+ try:
601
+ yield n, list(_build_paths_from_predecessors({source}, n, pred))
602
+ except nx.NetworkXNoPath:
603
+ pass
604
+
605
+
606
+ @nx._dispatchable(edge_attrs="weight")
607
+ def all_pairs_all_shortest_paths(G, weight=None, method="dijkstra"):
608
+ """Compute all shortest paths between all nodes.
609
+
610
+ Parameters
611
+ ----------
612
+ G : NetworkX graph
613
+
614
+ weight : None, string or function, optional (default = None)
615
+ If None, every edge has weight/distance/cost 1.
616
+ If a string, use this edge attribute as the edge weight.
617
+ Any edge attribute not present defaults to 1.
618
+ If this is a function, the weight of an edge is the value
619
+ returned by the function. The function must accept exactly
620
+ three positional arguments: the two endpoints of an edge and
621
+ the dictionary of edge attributes for that edge.
622
+ The function must return a number.
623
+
624
+ method : string, optional (default = 'dijkstra')
625
+ The algorithm to use to compute the path lengths.
626
+ Supported options: 'dijkstra', 'bellman-ford'.
627
+ Other inputs produce a ValueError.
628
+ If `weight` is None, unweighted graph methods are used, and this
629
+ suggestion is ignored.
630
+
631
+ Returns
632
+ -------
633
+ paths : generator of dictionary
634
+ Dictionary of arrays, keyed by source and target, of all shortest paths.
635
+
636
+ Raises
637
+ ------
638
+ ValueError
639
+ If `method` is not among the supported options.
640
+
641
+ Examples
642
+ --------
643
+ >>> G = nx.cycle_graph(4)
644
+ >>> dict(nx.all_pairs_all_shortest_paths(G))[0][2]
645
+ [[0, 1, 2], [0, 3, 2]]
646
+ >>> dict(nx.all_pairs_all_shortest_paths(G))[0][3]
647
+ [[0, 3]]
648
+
649
+ Notes
650
+ -----
651
+ There may be multiple shortest paths with equal lengths. Unlike
652
+ all_pairs_shortest_path, this method returns all shortest paths.
653
+
654
+ See Also
655
+ --------
656
+ all_pairs_shortest_path
657
+ single_source_all_shortest_paths
658
+ """
659
+ for n in G:
660
+ yield (
661
+ n,
662
+ dict(single_source_all_shortest_paths(G, n, weight=weight, method=method)),
663
+ )
664
+
665
+
666
+ def _build_paths_from_predecessors(sources, target, pred):
667
+ """Compute all simple paths to target, given the predecessors found in
668
+ pred, terminating when any source in sources is found.
669
+
670
+ Parameters
671
+ ----------
672
+ sources : set
673
+ Starting nodes for path.
674
+
675
+ target : node
676
+ Ending node for path.
677
+
678
+ pred : dict
679
+ A dictionary of predecessor lists, keyed by node
680
+
681
+ Returns
682
+ -------
683
+ paths : generator of lists
684
+ A generator of all paths between source and target.
685
+
686
+ Raises
687
+ ------
688
+ NetworkXNoPath
689
+ If `target` cannot be reached from `source`.
690
+
691
+ Notes
692
+ -----
693
+ There may be many paths between the sources and target. If there are
694
+ cycles among the predecessors, this function will not produce all
695
+ possible paths because doing so would produce infinitely many paths
696
+ of unbounded length -- instead, we only produce simple paths.
697
+
698
+ See Also
699
+ --------
700
+ shortest_path
701
+ single_source_shortest_path
702
+ all_pairs_shortest_path
703
+ all_shortest_paths
704
+ bellman_ford_path
705
+ """
706
+ if target not in pred:
707
+ raise nx.NetworkXNoPath(f"Target {target} cannot be reached from given sources")
708
+
709
+ seen = {target}
710
+ stack = [[target, 0]]
711
+ top = 0
712
+ while top >= 0:
713
+ node, i = stack[top]
714
+ if node in sources:
715
+ yield [p for p, n in reversed(stack[: top + 1])]
716
+ if len(pred[node]) > i:
717
+ stack[top][1] = i + 1
718
+ next = pred[node][i]
719
+ if next in seen:
720
+ continue
721
+ else:
722
+ seen.add(next)
723
+ top += 1
724
+ if top == len(stack):
725
+ stack.append([next, 0])
726
+ else:
727
+ stack[top][:] = [next, 0]
728
+ else:
729
+ seen.discard(node)
730
+ top -= 1
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_astar.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+
7
+ class TestAStar:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ edges = [
11
+ ("s", "u", 10),
12
+ ("s", "x", 5),
13
+ ("u", "v", 1),
14
+ ("u", "x", 2),
15
+ ("v", "y", 1),
16
+ ("x", "u", 3),
17
+ ("x", "v", 5),
18
+ ("x", "y", 2),
19
+ ("y", "s", 7),
20
+ ("y", "v", 6),
21
+ ]
22
+ cls.XG = nx.DiGraph()
23
+ cls.XG.add_weighted_edges_from(edges)
24
+
25
+ def test_multiple_optimal_paths(self):
26
+ """Tests that A* algorithm finds any of multiple optimal paths"""
27
+ heuristic_values = {"a": 1.35, "b": 1.18, "c": 0.67, "d": 0}
28
+
29
+ def h(u, v):
30
+ return heuristic_values[u]
31
+
32
+ graph = nx.Graph()
33
+ points = ["a", "b", "c", "d"]
34
+ edges = [("a", "b", 0.18), ("a", "c", 0.68), ("b", "c", 0.50), ("c", "d", 0.67)]
35
+
36
+ graph.add_nodes_from(points)
37
+ graph.add_weighted_edges_from(edges)
38
+
39
+ path1 = ["a", "c", "d"]
40
+ path2 = ["a", "b", "c", "d"]
41
+ assert nx.astar_path(graph, "a", "d", h) in (path1, path2)
42
+
43
+ def test_astar_directed(self):
44
+ assert nx.astar_path(self.XG, "s", "v") == ["s", "x", "u", "v"]
45
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
46
+
47
+ def test_astar_directed_weight_function(self):
48
+ w1 = lambda u, v, d: d["weight"]
49
+ assert nx.astar_path(self.XG, "x", "u", weight=w1) == ["x", "u"]
50
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w1) == 3
51
+ assert nx.astar_path(self.XG, "s", "v", weight=w1) == ["s", "x", "u", "v"]
52
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w1) == 9
53
+
54
+ w2 = lambda u, v, d: None if (u, v) == ("x", "u") else d["weight"]
55
+ assert nx.astar_path(self.XG, "x", "u", weight=w2) == ["x", "y", "s", "u"]
56
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w2) == 19
57
+ assert nx.astar_path(self.XG, "s", "v", weight=w2) == ["s", "x", "v"]
58
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w2) == 10
59
+
60
+ w3 = lambda u, v, d: d["weight"] + 10
61
+ assert nx.astar_path(self.XG, "x", "u", weight=w3) == ["x", "u"]
62
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w3) == 13
63
+ assert nx.astar_path(self.XG, "s", "v", weight=w3) == ["s", "x", "v"]
64
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w3) == 30
65
+
66
+ def test_astar_multigraph(self):
67
+ G = nx.MultiDiGraph(self.XG)
68
+ G.add_weighted_edges_from((u, v, 1000) for (u, v) in list(G.edges()))
69
+ assert nx.astar_path(G, "s", "v") == ["s", "x", "u", "v"]
70
+ assert nx.astar_path_length(G, "s", "v") == 9
71
+
72
+ def test_astar_undirected(self):
73
+ GG = self.XG.to_undirected()
74
+ # make sure we get lower weight
75
+ # to_undirected might choose either edge with weight 2 or weight 3
76
+ GG["u"]["x"]["weight"] = 2
77
+ GG["y"]["v"]["weight"] = 2
78
+ assert nx.astar_path(GG, "s", "v") == ["s", "x", "u", "v"]
79
+ assert nx.astar_path_length(GG, "s", "v") == 8
80
+
81
+ def test_astar_directed2(self):
82
+ XG2 = nx.DiGraph()
83
+ edges = [
84
+ (1, 4, 1),
85
+ (4, 5, 1),
86
+ (5, 6, 1),
87
+ (6, 3, 1),
88
+ (1, 3, 50),
89
+ (1, 2, 100),
90
+ (2, 3, 100),
91
+ ]
92
+ XG2.add_weighted_edges_from(edges)
93
+ assert nx.astar_path(XG2, 1, 3) == [1, 4, 5, 6, 3]
94
+
95
+ def test_astar_undirected2(self):
96
+ XG3 = nx.Graph()
97
+ edges = [(0, 1, 2), (1, 2, 12), (2, 3, 1), (3, 4, 5), (4, 5, 1), (5, 0, 10)]
98
+ XG3.add_weighted_edges_from(edges)
99
+ assert nx.astar_path(XG3, 0, 3) == [0, 1, 2, 3]
100
+ assert nx.astar_path_length(XG3, 0, 3) == 15
101
+
102
+ def test_astar_undirected3(self):
103
+ XG4 = nx.Graph()
104
+ edges = [
105
+ (0, 1, 2),
106
+ (1, 2, 2),
107
+ (2, 3, 1),
108
+ (3, 4, 1),
109
+ (4, 5, 1),
110
+ (5, 6, 1),
111
+ (6, 7, 1),
112
+ (7, 0, 1),
113
+ ]
114
+ XG4.add_weighted_edges_from(edges)
115
+ assert nx.astar_path(XG4, 0, 2) == [0, 1, 2]
116
+ assert nx.astar_path_length(XG4, 0, 2) == 4
117
+
118
+ """ Tests that A* finds correct path when multiple paths exist
119
+ and the best one is not expanded first (GH issue #3464)
120
+ """
121
+
122
+ def test_astar_directed3(self):
123
+ heuristic_values = {"n5": 36, "n2": 4, "n1": 0, "n0": 0}
124
+
125
+ def h(u, v):
126
+ return heuristic_values[u]
127
+
128
+ edges = [("n5", "n1", 11), ("n5", "n2", 9), ("n2", "n1", 1), ("n1", "n0", 32)]
129
+ graph = nx.DiGraph()
130
+ graph.add_weighted_edges_from(edges)
131
+ answer = ["n5", "n2", "n1", "n0"]
132
+ assert nx.astar_path(graph, "n5", "n0", h) == answer
133
+
134
+ """ Tests that parent is not wrongly overridden when a node
135
+ is re-explored multiple times.
136
+ """
137
+
138
+ def test_astar_directed4(self):
139
+ edges = [
140
+ ("a", "b", 1),
141
+ ("a", "c", 1),
142
+ ("b", "d", 2),
143
+ ("c", "d", 1),
144
+ ("d", "e", 1),
145
+ ]
146
+ graph = nx.DiGraph()
147
+ graph.add_weighted_edges_from(edges)
148
+ assert nx.astar_path(graph, "a", "e") == ["a", "c", "d", "e"]
149
+
150
+ # >>> MXG4=NX.MultiGraph(XG4)
151
+ # >>> MXG4.add_edge(0,1,3)
152
+ # >>> NX.dijkstra_path(MXG4,0,2)
153
+ # [0, 1, 2]
154
+
155
+ def test_astar_w1(self):
156
+ G = nx.DiGraph()
157
+ G.add_edges_from(
158
+ [
159
+ ("s", "u"),
160
+ ("s", "x"),
161
+ ("u", "v"),
162
+ ("u", "x"),
163
+ ("v", "y"),
164
+ ("x", "u"),
165
+ ("x", "w"),
166
+ ("w", "v"),
167
+ ("x", "y"),
168
+ ("y", "s"),
169
+ ("y", "v"),
170
+ ]
171
+ )
172
+ assert nx.astar_path(G, "s", "v") == ["s", "u", "v"]
173
+ assert nx.astar_path_length(G, "s", "v") == 2
174
+
175
+ def test_astar_nopath(self):
176
+ with pytest.raises(nx.NodeNotFound):
177
+ nx.astar_path(self.XG, "s", "moon")
178
+
179
+ def test_astar_cutoff(self):
180
+ with pytest.raises(nx.NetworkXNoPath):
181
+ # optimal path_length in XG is 9
182
+ nx.astar_path(self.XG, "s", "v", cutoff=8.0)
183
+ with pytest.raises(nx.NetworkXNoPath):
184
+ nx.astar_path_length(self.XG, "s", "v", cutoff=8.0)
185
+
186
+ def test_astar_admissible_heuristic_with_cutoff(self):
187
+ heuristic_values = {"s": 36, "y": 4, "x": 0, "u": 0, "v": 0}
188
+
189
+ def h(u, v):
190
+ return heuristic_values[u]
191
+
192
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
193
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h) == 9
194
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=12) == 9
195
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=9) == 9
196
+ with pytest.raises(nx.NetworkXNoPath):
197
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=8)
198
+
199
+ def test_astar_inadmissible_heuristic_with_cutoff(self):
200
+ heuristic_values = {"s": 36, "y": 14, "x": 10, "u": 10, "v": 0}
201
+
202
+ def h(u, v):
203
+ return heuristic_values[u]
204
+
205
+ # optimal path_length in XG is 9. This heuristic gives over-estimate.
206
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h) == 10
207
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=15) == 10
208
+ with pytest.raises(nx.NetworkXNoPath):
209
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=9)
210
+ with pytest.raises(nx.NetworkXNoPath):
211
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=12)
212
+
213
+ def test_astar_cutoff2(self):
214
+ assert nx.astar_path(self.XG, "s", "v", cutoff=10.0) == ["s", "x", "u", "v"]
215
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
216
+
217
+ def test_cycle(self):
218
+ C = nx.cycle_graph(7)
219
+ assert nx.astar_path(C, 0, 3) == [0, 1, 2, 3]
220
+ assert nx.dijkstra_path(C, 0, 4) == [0, 6, 5, 4]
221
+
222
+ def test_unorderable_nodes(self):
223
+ """Tests that A* accommodates nodes that are not orderable.
224
+
225
+ For more information, see issue #554.
226
+
227
+ """
228
+ # Create the cycle graph on four nodes, with nodes represented
229
+ # as (unorderable) Python objects.
230
+ nodes = [object() for n in range(4)]
231
+ G = nx.Graph()
232
+ G.add_edges_from(pairwise(nodes, cyclic=True))
233
+ path = nx.astar_path(G, nodes[0], nodes[2])
234
+ assert len(path) == 3
235
+
236
+ def test_astar_NetworkXNoPath(self):
237
+ """Tests that exception is raised when there exists no
238
+ path between source and target"""
239
+ G = nx.gnp_random_graph(10, 0.2, seed=10)
240
+ with pytest.raises(nx.NetworkXNoPath):
241
+ nx.astar_path(G, 4, 9)
242
+
243
+ def test_astar_NodeNotFound(self):
244
+ """Tests that exception is raised when either
245
+ source or target is not in graph"""
246
+ G = nx.gnp_random_graph(10, 0.2, seed=10)
247
+ with pytest.raises(nx.NodeNotFound):
248
+ nx.astar_path_length(G, 11, 9)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestFloyd:
7
+ @classmethod
8
+ def setup_class(cls):
9
+ pass
10
+
11
+ def test_floyd_warshall_predecessor_and_distance(self):
12
+ XG = nx.DiGraph()
13
+ XG.add_weighted_edges_from(
14
+ [
15
+ ("s", "u", 10),
16
+ ("s", "x", 5),
17
+ ("u", "v", 1),
18
+ ("u", "x", 2),
19
+ ("v", "y", 1),
20
+ ("x", "u", 3),
21
+ ("x", "v", 5),
22
+ ("x", "y", 2),
23
+ ("y", "s", 7),
24
+ ("y", "v", 6),
25
+ ]
26
+ )
27
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
28
+ assert dist["s"]["v"] == 9
29
+ assert path["s"]["v"] == "u"
30
+ assert dist == {
31
+ "y": {"y": 0, "x": 12, "s": 7, "u": 15, "v": 6},
32
+ "x": {"y": 2, "x": 0, "s": 9, "u": 3, "v": 4},
33
+ "s": {"y": 7, "x": 5, "s": 0, "u": 8, "v": 9},
34
+ "u": {"y": 2, "x": 2, "s": 9, "u": 0, "v": 1},
35
+ "v": {"y": 1, "x": 13, "s": 8, "u": 16, "v": 0},
36
+ }
37
+
38
+ GG = XG.to_undirected()
39
+ # make sure we get lower weight
40
+ # to_undirected might choose either edge with weight 2 or weight 3
41
+ GG["u"]["x"]["weight"] = 2
42
+ path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
43
+ assert dist["s"]["v"] == 8
44
+ # skip this test, could be alternate path s-u-v
45
+ # assert_equal(path['s']['v'],'y')
46
+
47
+ G = nx.DiGraph() # no weights
48
+ G.add_edges_from(
49
+ [
50
+ ("s", "u"),
51
+ ("s", "x"),
52
+ ("u", "v"),
53
+ ("u", "x"),
54
+ ("v", "y"),
55
+ ("x", "u"),
56
+ ("x", "v"),
57
+ ("x", "y"),
58
+ ("y", "s"),
59
+ ("y", "v"),
60
+ ]
61
+ )
62
+ path, dist = nx.floyd_warshall_predecessor_and_distance(G)
63
+ assert dist["s"]["v"] == 2
64
+ # skip this test, could be alternate path s-u-v
65
+ # assert_equal(path['s']['v'],'x')
66
+
67
+ # alternate interface
68
+ dist = nx.floyd_warshall(G)
69
+ assert dist["s"]["v"] == 2
70
+
71
+ # floyd_warshall_predecessor_and_distance returns
72
+ # dicts-of-defautdicts
73
+ # make sure we don't get empty dictionary
74
+ XG = nx.DiGraph()
75
+ XG.add_weighted_edges_from(
76
+ [("v", "x", 5.0), ("y", "x", 5.0), ("v", "y", 6.0), ("x", "u", 2.0)]
77
+ )
78
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
79
+ inf = float("inf")
80
+ assert dist == {
81
+ "v": {"v": 0, "x": 5.0, "y": 6.0, "u": 7.0},
82
+ "x": {"x": 0, "u": 2.0, "v": inf, "y": inf},
83
+ "y": {"y": 0, "x": 5.0, "v": inf, "u": 7.0},
84
+ "u": {"u": 0, "v": inf, "x": inf, "y": inf},
85
+ }
86
+ assert path == {
87
+ "v": {"x": "v", "y": "v", "u": "x"},
88
+ "x": {"u": "x"},
89
+ "y": {"x": "y", "u": "x"},
90
+ }
91
+
92
+ def test_reconstruct_path(self):
93
+ with pytest.raises(KeyError):
94
+ XG = nx.DiGraph()
95
+ XG.add_weighted_edges_from(
96
+ [
97
+ ("s", "u", 10),
98
+ ("s", "x", 5),
99
+ ("u", "v", 1),
100
+ ("u", "x", 2),
101
+ ("v", "y", 1),
102
+ ("x", "u", 3),
103
+ ("x", "v", 5),
104
+ ("x", "y", 2),
105
+ ("y", "s", 7),
106
+ ("y", "v", 6),
107
+ ]
108
+ )
109
+ predecessors, _ = nx.floyd_warshall_predecessor_and_distance(XG)
110
+
111
+ path = nx.reconstruct_path("s", "v", predecessors)
112
+ assert path == ["s", "x", "u", "v"]
113
+
114
+ path = nx.reconstruct_path("s", "s", predecessors)
115
+ assert path == []
116
+
117
+ # this part raises the keyError
118
+ nx.reconstruct_path("1", "2", predecessors)
119
+
120
+ def test_cycle(self):
121
+ path, dist = nx.floyd_warshall_predecessor_and_distance(nx.cycle_graph(7))
122
+ assert dist[0][3] == 3
123
+ assert path[0][3] == 2
124
+ assert dist[0][4] == 3
125
+
126
+ def test_weighted(self):
127
+ XG3 = nx.Graph()
128
+ XG3.add_weighted_edges_from(
129
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
130
+ )
131
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG3)
132
+ assert dist[0][3] == 15
133
+ assert path[0][3] == 2
134
+
135
+ def test_weighted2(self):
136
+ XG4 = nx.Graph()
137
+ XG4.add_weighted_edges_from(
138
+ [
139
+ [0, 1, 2],
140
+ [1, 2, 2],
141
+ [2, 3, 1],
142
+ [3, 4, 1],
143
+ [4, 5, 1],
144
+ [5, 6, 1],
145
+ [6, 7, 1],
146
+ [7, 0, 1],
147
+ ]
148
+ )
149
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG4)
150
+ assert dist[0][2] == 4
151
+ assert path[0][2] == 1
152
+
153
+ def test_weight_parameter(self):
154
+ XG4 = nx.Graph()
155
+ XG4.add_edges_from(
156
+ [
157
+ (0, 1, {"heavy": 2}),
158
+ (1, 2, {"heavy": 2}),
159
+ (2, 3, {"heavy": 1}),
160
+ (3, 4, {"heavy": 1}),
161
+ (4, 5, {"heavy": 1}),
162
+ (5, 6, {"heavy": 1}),
163
+ (6, 7, {"heavy": 1}),
164
+ (7, 0, {"heavy": 1}),
165
+ ]
166
+ )
167
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG4, weight="heavy")
168
+ assert dist[0][2] == 4
169
+ assert path[0][2] == 1
170
+
171
+ def test_zero_distance(self):
172
+ XG = nx.DiGraph()
173
+ XG.add_weighted_edges_from(
174
+ [
175
+ ("s", "u", 10),
176
+ ("s", "x", 5),
177
+ ("u", "v", 1),
178
+ ("u", "x", 2),
179
+ ("v", "y", 1),
180
+ ("x", "u", 3),
181
+ ("x", "v", 5),
182
+ ("x", "y", 2),
183
+ ("y", "s", 7),
184
+ ("y", "v", 6),
185
+ ]
186
+ )
187
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
188
+
189
+ for u in XG:
190
+ assert dist[u][u] == 0
191
+
192
+ GG = XG.to_undirected()
193
+ # make sure we get lower weight
194
+ # to_undirected might choose either edge with weight 2 or weight 3
195
+ GG["u"]["x"]["weight"] = 2
196
+ path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
197
+
198
+ for u in GG:
199
+ dist[u][u] = 0
200
+
201
+ def test_zero_weight(self):
202
+ G = nx.DiGraph()
203
+ edges = [(1, 2, -2), (2, 3, -4), (1, 5, 1), (5, 4, 0), (4, 3, -5), (2, 5, -7)]
204
+ G.add_weighted_edges_from(edges)
205
+ dist = nx.floyd_warshall(G)
206
+ assert dist[1][3] == -14
207
+
208
+ G = nx.MultiDiGraph()
209
+ edges.append((2, 5, -7))
210
+ G.add_weighted_edges_from(edges)
211
+ dist = nx.floyd_warshall(G)
212
+ assert dist[1][3] == -14
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+
6
+ import networkx as nx
7
+
8
+
9
+ def test_cycle_numpy():
10
+ dist = nx.floyd_warshall_numpy(nx.cycle_graph(7))
11
+ assert dist[0, 3] == 3
12
+ assert dist[0, 4] == 3
13
+
14
+
15
+ def test_weighted_numpy_three_edges():
16
+ XG3 = nx.Graph()
17
+ XG3.add_weighted_edges_from(
18
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
19
+ )
20
+ dist = nx.floyd_warshall_numpy(XG3)
21
+ assert dist[0, 3] == 15
22
+
23
+
24
+ def test_weighted_numpy_two_edges():
25
+ XG4 = nx.Graph()
26
+ XG4.add_weighted_edges_from(
27
+ [
28
+ [0, 1, 2],
29
+ [1, 2, 2],
30
+ [2, 3, 1],
31
+ [3, 4, 1],
32
+ [4, 5, 1],
33
+ [5, 6, 1],
34
+ [6, 7, 1],
35
+ [7, 0, 1],
36
+ ]
37
+ )
38
+ dist = nx.floyd_warshall_numpy(XG4)
39
+ assert dist[0, 2] == 4
40
+
41
+
42
+ def test_weight_parameter_numpy():
43
+ XG4 = nx.Graph()
44
+ XG4.add_edges_from(
45
+ [
46
+ (0, 1, {"heavy": 2}),
47
+ (1, 2, {"heavy": 2}),
48
+ (2, 3, {"heavy": 1}),
49
+ (3, 4, {"heavy": 1}),
50
+ (4, 5, {"heavy": 1}),
51
+ (5, 6, {"heavy": 1}),
52
+ (6, 7, {"heavy": 1}),
53
+ (7, 0, {"heavy": 1}),
54
+ ]
55
+ )
56
+ dist = nx.floyd_warshall_numpy(XG4, weight="heavy")
57
+ assert dist[0, 2] == 4
58
+
59
+
60
+ def test_directed_cycle_numpy():
61
+ G = nx.DiGraph()
62
+ nx.add_cycle(G, [0, 1, 2, 3])
63
+ pred, dist = nx.floyd_warshall_predecessor_and_distance(G)
64
+ D = nx.utils.dict_to_numpy_array(dist)
65
+ np.testing.assert_equal(nx.floyd_warshall_numpy(G), D)
66
+
67
+
68
+ def test_zero_weight():
69
+ G = nx.DiGraph()
70
+ edges = [(1, 2, -2), (2, 3, -4), (1, 5, 1), (5, 4, 0), (4, 3, -5), (2, 5, -7)]
71
+ G.add_weighted_edges_from(edges)
72
+ dist = nx.floyd_warshall_numpy(G)
73
+ assert int(np.min(dist)) == -14
74
+
75
+ G = nx.MultiDiGraph()
76
+ edges.append((2, 5, -7))
77
+ G.add_weighted_edges_from(edges)
78
+ dist = nx.floyd_warshall_numpy(G)
79
+ assert int(np.min(dist)) == -14
80
+
81
+
82
+ def test_nodelist():
83
+ G = nx.path_graph(7)
84
+ dist = nx.floyd_warshall_numpy(G, nodelist=[3, 5, 4, 6, 2, 1, 0])
85
+ assert dist[0, 3] == 3
86
+ assert dist[0, 1] == 2
87
+ assert dist[6, 2] == 4
88
+ pytest.raises(nx.NetworkXError, nx.floyd_warshall_numpy, G, [1, 3])
89
+ pytest.raises(nx.NetworkXError, nx.floyd_warshall_numpy, G, list(range(9)))
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_generic.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def validate_grid_path(r, c, s, t, p):
7
+ assert isinstance(p, list)
8
+ assert p[0] == s
9
+ assert p[-1] == t
10
+ s = ((s - 1) // c, (s - 1) % c)
11
+ t = ((t - 1) // c, (t - 1) % c)
12
+ assert len(p) == abs(t[0] - s[0]) + abs(t[1] - s[1]) + 1
13
+ p = [((u - 1) // c, (u - 1) % c) for u in p]
14
+ for u in p:
15
+ assert 0 <= u[0] < r
16
+ assert 0 <= u[1] < c
17
+ for u, v in zip(p[:-1], p[1:]):
18
+ assert (abs(v[0] - u[0]), abs(v[1] - u[1])) in [(0, 1), (1, 0)]
19
+
20
+
21
+ class TestGenericPath:
22
+ @classmethod
23
+ def setup_class(cls):
24
+ from networkx import convert_node_labels_to_integers as cnlti
25
+
26
+ cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
27
+ cls.cycle = nx.cycle_graph(7)
28
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
29
+ cls.neg_weights = nx.DiGraph()
30
+ cls.neg_weights.add_edge(0, 1, weight=1)
31
+ cls.neg_weights.add_edge(0, 2, weight=3)
32
+ cls.neg_weights.add_edge(1, 3, weight=1)
33
+ cls.neg_weights.add_edge(2, 3, weight=-2)
34
+
35
+ def test_shortest_path(self):
36
+ assert nx.shortest_path(self.cycle, 0, 3) == [0, 1, 2, 3]
37
+ assert nx.shortest_path(self.cycle, 0, 4) == [0, 6, 5, 4]
38
+ validate_grid_path(4, 4, 1, 12, nx.shortest_path(self.grid, 1, 12))
39
+ assert nx.shortest_path(self.directed_cycle, 0, 3) == [0, 1, 2, 3]
40
+ # now with weights
41
+ assert nx.shortest_path(self.cycle, 0, 3, weight="weight") == [0, 1, 2, 3]
42
+ assert nx.shortest_path(self.cycle, 0, 4, weight="weight") == [0, 6, 5, 4]
43
+ validate_grid_path(
44
+ 4, 4, 1, 12, nx.shortest_path(self.grid, 1, 12, weight="weight")
45
+ )
46
+ assert nx.shortest_path(self.directed_cycle, 0, 3, weight="weight") == [
47
+ 0,
48
+ 1,
49
+ 2,
50
+ 3,
51
+ ]
52
+ # weights and method specified
53
+ assert nx.shortest_path(
54
+ self.directed_cycle, 0, 3, weight="weight", method="dijkstra"
55
+ ) == [0, 1, 2, 3]
56
+ assert nx.shortest_path(
57
+ self.directed_cycle, 0, 3, weight="weight", method="bellman-ford"
58
+ ) == [0, 1, 2, 3]
59
+ # when Dijkstra's will probably (depending on precise implementation)
60
+ # incorrectly return [0, 1, 3] instead
61
+ assert nx.shortest_path(
62
+ self.neg_weights, 0, 3, weight="weight", method="bellman-ford"
63
+ ) == [0, 2, 3]
64
+ # confirm bad method rejection
65
+ pytest.raises(ValueError, nx.shortest_path, self.cycle, method="SPAM")
66
+ # confirm absent source rejection
67
+ pytest.raises(nx.NodeNotFound, nx.shortest_path, self.cycle, 8)
68
+
69
+ def test_shortest_path_target(self):
70
+ answer = {0: [0, 1], 1: [1], 2: [2, 1]}
71
+ sp = nx.shortest_path(nx.path_graph(3), target=1)
72
+ assert sp == answer
73
+ # with weights
74
+ sp = nx.shortest_path(nx.path_graph(3), target=1, weight="weight")
75
+ assert sp == answer
76
+ # weights and method specified
77
+ sp = nx.shortest_path(
78
+ nx.path_graph(3), target=1, weight="weight", method="dijkstra"
79
+ )
80
+ assert sp == answer
81
+ sp = nx.shortest_path(
82
+ nx.path_graph(3), target=1, weight="weight", method="bellman-ford"
83
+ )
84
+ assert sp == answer
85
+
86
+ def test_shortest_path_length(self):
87
+ assert nx.shortest_path_length(self.cycle, 0, 3) == 3
88
+ assert nx.shortest_path_length(self.grid, 1, 12) == 5
89
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4) == 4
90
+ # now with weights
91
+ assert nx.shortest_path_length(self.cycle, 0, 3, weight="weight") == 3
92
+ assert nx.shortest_path_length(self.grid, 1, 12, weight="weight") == 5
93
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4, weight="weight") == 4
94
+ # weights and method specified
95
+ assert (
96
+ nx.shortest_path_length(
97
+ self.cycle, 0, 3, weight="weight", method="dijkstra"
98
+ )
99
+ == 3
100
+ )
101
+ assert (
102
+ nx.shortest_path_length(
103
+ self.cycle, 0, 3, weight="weight", method="bellman-ford"
104
+ )
105
+ == 3
106
+ )
107
+ # confirm bad method rejection
108
+ pytest.raises(ValueError, nx.shortest_path_length, self.cycle, method="SPAM")
109
+ # confirm absent source rejection
110
+ pytest.raises(nx.NodeNotFound, nx.shortest_path_length, self.cycle, 8)
111
+
112
+ def test_shortest_path_length_target(self):
113
+ answer = {0: 1, 1: 0, 2: 1}
114
+ sp = dict(nx.shortest_path_length(nx.path_graph(3), target=1))
115
+ assert sp == answer
116
+ # with weights
117
+ sp = nx.shortest_path_length(nx.path_graph(3), target=1, weight="weight")
118
+ assert sp == answer
119
+ # weights and method specified
120
+ sp = nx.shortest_path_length(
121
+ nx.path_graph(3), target=1, weight="weight", method="dijkstra"
122
+ )
123
+ assert sp == answer
124
+ sp = nx.shortest_path_length(
125
+ nx.path_graph(3), target=1, weight="weight", method="bellman-ford"
126
+ )
127
+ assert sp == answer
128
+
129
+ def test_single_source_shortest_path(self):
130
+ p = nx.shortest_path(self.cycle, 0)
131
+ assert p[3] == [0, 1, 2, 3]
132
+ assert p == nx.single_source_shortest_path(self.cycle, 0)
133
+ p = nx.shortest_path(self.grid, 1)
134
+ validate_grid_path(4, 4, 1, 12, p[12])
135
+ # now with weights
136
+ p = nx.shortest_path(self.cycle, 0, weight="weight")
137
+ assert p[3] == [0, 1, 2, 3]
138
+ assert p == nx.single_source_dijkstra_path(self.cycle, 0)
139
+ p = nx.shortest_path(self.grid, 1, weight="weight")
140
+ validate_grid_path(4, 4, 1, 12, p[12])
141
+ # weights and method specified
142
+ p = nx.shortest_path(self.cycle, 0, method="dijkstra", weight="weight")
143
+ assert p[3] == [0, 1, 2, 3]
144
+ assert p == nx.single_source_shortest_path(self.cycle, 0)
145
+ p = nx.shortest_path(self.cycle, 0, method="bellman-ford", weight="weight")
146
+ assert p[3] == [0, 1, 2, 3]
147
+ assert p == nx.single_source_shortest_path(self.cycle, 0)
148
+
149
+ def test_single_source_shortest_path_length(self):
150
+ ans = dict(nx.shortest_path_length(self.cycle, 0))
151
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
152
+ assert ans == dict(nx.single_source_shortest_path_length(self.cycle, 0))
153
+ ans = dict(nx.shortest_path_length(self.grid, 1))
154
+ assert ans[16] == 6
155
+ # now with weights
156
+ ans = dict(nx.shortest_path_length(self.cycle, 0, weight="weight"))
157
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
158
+ assert ans == dict(nx.single_source_dijkstra_path_length(self.cycle, 0))
159
+ ans = dict(nx.shortest_path_length(self.grid, 1, weight="weight"))
160
+ assert ans[16] == 6
161
+ # weights and method specified
162
+ ans = dict(
163
+ nx.shortest_path_length(self.cycle, 0, weight="weight", method="dijkstra")
164
+ )
165
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
166
+ assert ans == dict(nx.single_source_dijkstra_path_length(self.cycle, 0))
167
+ ans = dict(
168
+ nx.shortest_path_length(
169
+ self.cycle, 0, weight="weight", method="bellman-ford"
170
+ )
171
+ )
172
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
173
+ assert ans == dict(nx.single_source_bellman_ford_path_length(self.cycle, 0))
174
+
175
+ def test_single_source_all_shortest_paths(self):
176
+ cycle_ans = {0: [[0]], 1: [[0, 1]], 2: [[0, 1, 2], [0, 3, 2]], 3: [[0, 3]]}
177
+ ans = dict(nx.single_source_all_shortest_paths(nx.cycle_graph(4), 0))
178
+ assert sorted(ans[2]) == cycle_ans[2]
179
+ ans = dict(nx.single_source_all_shortest_paths(self.grid, 1))
180
+ grid_ans = [
181
+ [1, 2, 3, 7, 11],
182
+ [1, 2, 6, 7, 11],
183
+ [1, 2, 6, 10, 11],
184
+ [1, 5, 6, 7, 11],
185
+ [1, 5, 6, 10, 11],
186
+ [1, 5, 9, 10, 11],
187
+ ]
188
+ assert sorted(ans[11]) == grid_ans
189
+ ans = dict(
190
+ nx.single_source_all_shortest_paths(nx.cycle_graph(4), 0, weight="weight")
191
+ )
192
+ assert sorted(ans[2]) == cycle_ans[2]
193
+ ans = dict(
194
+ nx.single_source_all_shortest_paths(
195
+ nx.cycle_graph(4), 0, method="bellman-ford", weight="weight"
196
+ )
197
+ )
198
+ assert sorted(ans[2]) == cycle_ans[2]
199
+ ans = dict(nx.single_source_all_shortest_paths(self.grid, 1, weight="weight"))
200
+ assert sorted(ans[11]) == grid_ans
201
+ ans = dict(
202
+ nx.single_source_all_shortest_paths(
203
+ self.grid, 1, method="bellman-ford", weight="weight"
204
+ )
205
+ )
206
+ assert sorted(ans[11]) == grid_ans
207
+ G = nx.cycle_graph(4)
208
+ G.add_node(4)
209
+ ans = dict(nx.single_source_all_shortest_paths(G, 0))
210
+ assert sorted(ans[2]) == [[0, 1, 2], [0, 3, 2]]
211
+ ans = dict(nx.single_source_all_shortest_paths(G, 4))
212
+ assert sorted(ans[4]) == [[4]]
213
+
214
+ def test_all_pairs_shortest_path(self):
215
+ # shortest_path w/o source and target will return a generator instead of
216
+ # a dict beginning in version 3.5. Only the first call needs changed here.
217
+ p = nx.shortest_path(self.cycle)
218
+ assert p[0][3] == [0, 1, 2, 3]
219
+ assert p == dict(nx.all_pairs_shortest_path(self.cycle))
220
+ p = dict(nx.shortest_path(self.grid))
221
+ validate_grid_path(4, 4, 1, 12, p[1][12])
222
+ # now with weights
223
+ p = dict(nx.shortest_path(self.cycle, weight="weight"))
224
+ assert p[0][3] == [0, 1, 2, 3]
225
+ assert p == dict(nx.all_pairs_dijkstra_path(self.cycle))
226
+ p = dict(nx.shortest_path(self.grid, weight="weight"))
227
+ validate_grid_path(4, 4, 1, 12, p[1][12])
228
+ # weights and method specified
229
+ p = dict(nx.shortest_path(self.cycle, weight="weight", method="dijkstra"))
230
+ assert p[0][3] == [0, 1, 2, 3]
231
+ assert p == dict(nx.all_pairs_dijkstra_path(self.cycle))
232
+ p = dict(nx.shortest_path(self.cycle, weight="weight", method="bellman-ford"))
233
+ assert p[0][3] == [0, 1, 2, 3]
234
+ assert p == dict(nx.all_pairs_bellman_ford_path(self.cycle))
235
+
236
+ def test_all_pairs_shortest_path_length(self):
237
+ ans = dict(nx.shortest_path_length(self.cycle))
238
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
239
+ assert ans == dict(nx.all_pairs_shortest_path_length(self.cycle))
240
+ ans = dict(nx.shortest_path_length(self.grid))
241
+ assert ans[1][16] == 6
242
+ # now with weights
243
+ ans = dict(nx.shortest_path_length(self.cycle, weight="weight"))
244
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
245
+ assert ans == dict(nx.all_pairs_dijkstra_path_length(self.cycle))
246
+ ans = dict(nx.shortest_path_length(self.grid, weight="weight"))
247
+ assert ans[1][16] == 6
248
+ # weights and method specified
249
+ ans = dict(
250
+ nx.shortest_path_length(self.cycle, weight="weight", method="dijkstra")
251
+ )
252
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
253
+ assert ans == dict(nx.all_pairs_dijkstra_path_length(self.cycle))
254
+ ans = dict(
255
+ nx.shortest_path_length(self.cycle, weight="weight", method="bellman-ford")
256
+ )
257
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
258
+ assert ans == dict(nx.all_pairs_bellman_ford_path_length(self.cycle))
259
+
260
+ def test_all_pairs_all_shortest_paths(self):
261
+ ans = dict(nx.all_pairs_all_shortest_paths(nx.cycle_graph(4)))
262
+ assert sorted(ans[1][3]) == [[1, 0, 3], [1, 2, 3]]
263
+ ans = dict(nx.all_pairs_all_shortest_paths(nx.cycle_graph(4)), weight="weight")
264
+ assert sorted(ans[1][3]) == [[1, 0, 3], [1, 2, 3]]
265
+ ans = dict(
266
+ nx.all_pairs_all_shortest_paths(nx.cycle_graph(4)),
267
+ method="bellman-ford",
268
+ weight="weight",
269
+ )
270
+ assert sorted(ans[1][3]) == [[1, 0, 3], [1, 2, 3]]
271
+ G = nx.cycle_graph(4)
272
+ G.add_node(4)
273
+ ans = dict(nx.all_pairs_all_shortest_paths(G))
274
+ assert sorted(ans[4][4]) == [[4]]
275
+
276
+ def test_has_path(self):
277
+ G = nx.Graph()
278
+ nx.add_path(G, range(3))
279
+ nx.add_path(G, range(3, 5))
280
+ assert nx.has_path(G, 0, 2)
281
+ assert not nx.has_path(G, 0, 4)
282
+
283
+ def test_has_path_singleton(self):
284
+ G = nx.empty_graph(1)
285
+ assert nx.has_path(G, 0, 0)
286
+
287
+ def test_all_shortest_paths(self):
288
+ G = nx.Graph()
289
+ nx.add_path(G, [0, 1, 2, 3])
290
+ nx.add_path(G, [0, 10, 20, 3])
291
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(nx.all_shortest_paths(G, 0, 3))
292
+ # with weights
293
+ G = nx.Graph()
294
+ nx.add_path(G, [0, 1, 2, 3])
295
+ nx.add_path(G, [0, 10, 20, 3])
296
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(
297
+ nx.all_shortest_paths(G, 0, 3, weight="weight")
298
+ )
299
+ # weights and method specified
300
+ G = nx.Graph()
301
+ nx.add_path(G, [0, 1, 2, 3])
302
+ nx.add_path(G, [0, 10, 20, 3])
303
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(
304
+ nx.all_shortest_paths(G, 0, 3, weight="weight", method="dijkstra")
305
+ )
306
+ G = nx.Graph()
307
+ nx.add_path(G, [0, 1, 2, 3])
308
+ nx.add_path(G, [0, 10, 20, 3])
309
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(
310
+ nx.all_shortest_paths(G, 0, 3, weight="weight", method="bellman-ford")
311
+ )
312
+
313
+ def test_all_shortest_paths_raise(self):
314
+ with pytest.raises(nx.NetworkXNoPath):
315
+ G = nx.path_graph(4)
316
+ G.add_node(4)
317
+ list(nx.all_shortest_paths(G, 0, 4))
318
+
319
+ def test_bad_method(self):
320
+ with pytest.raises(ValueError):
321
+ G = nx.path_graph(2)
322
+ list(nx.all_shortest_paths(G, 0, 1, weight="weight", method="SPAM"))
323
+
324
+ def test_single_source_all_shortest_paths_bad_method(self):
325
+ with pytest.raises(ValueError):
326
+ G = nx.path_graph(2)
327
+ dict(
328
+ nx.single_source_all_shortest_paths(
329
+ G, 0, weight="weight", method="SPAM"
330
+ )
331
+ )
332
+
333
+ def test_all_shortest_paths_zero_weight_edge(self):
334
+ g = nx.Graph()
335
+ nx.add_path(g, [0, 1, 3])
336
+ nx.add_path(g, [0, 1, 2, 3])
337
+ g.edges[1, 2]["weight"] = 0
338
+ paths30d = list(
339
+ nx.all_shortest_paths(g, 3, 0, weight="weight", method="dijkstra")
340
+ )
341
+ paths03d = list(
342
+ nx.all_shortest_paths(g, 0, 3, weight="weight", method="dijkstra")
343
+ )
344
+ paths30b = list(
345
+ nx.all_shortest_paths(g, 3, 0, weight="weight", method="bellman-ford")
346
+ )
347
+ paths03b = list(
348
+ nx.all_shortest_paths(g, 0, 3, weight="weight", method="bellman-ford")
349
+ )
350
+ assert sorted(paths03d) == sorted(p[::-1] for p in paths30d)
351
+ assert sorted(paths03d) == sorted(p[::-1] for p in paths30b)
352
+ assert sorted(paths03b) == sorted(p[::-1] for p in paths30b)
353
+
354
+
355
+ class TestAverageShortestPathLength:
356
+ def test_cycle_graph(self):
357
+ ans = nx.average_shortest_path_length(nx.cycle_graph(7))
358
+ assert ans == pytest.approx(2, abs=1e-7)
359
+
360
+ def test_path_graph(self):
361
+ ans = nx.average_shortest_path_length(nx.path_graph(5))
362
+ assert ans == pytest.approx(2, abs=1e-7)
363
+
364
+ def test_weighted(self):
365
+ G = nx.Graph()
366
+ nx.add_cycle(G, range(7), weight=2)
367
+ ans = nx.average_shortest_path_length(G, weight="weight")
368
+ assert ans == pytest.approx(4, abs=1e-7)
369
+ G = nx.Graph()
370
+ nx.add_path(G, range(5), weight=2)
371
+ ans = nx.average_shortest_path_length(G, weight="weight")
372
+ assert ans == pytest.approx(4, abs=1e-7)
373
+
374
+ def test_specified_methods(self):
375
+ G = nx.Graph()
376
+ nx.add_cycle(G, range(7), weight=2)
377
+ ans = nx.average_shortest_path_length(G, weight="weight", method="dijkstra")
378
+ assert ans == pytest.approx(4, abs=1e-7)
379
+ ans = nx.average_shortest_path_length(G, weight="weight", method="bellman-ford")
380
+ assert ans == pytest.approx(4, abs=1e-7)
381
+ ans = nx.average_shortest_path_length(
382
+ G, weight="weight", method="floyd-warshall"
383
+ )
384
+ assert ans == pytest.approx(4, abs=1e-7)
385
+
386
+ G = nx.Graph()
387
+ nx.add_path(G, range(5), weight=2)
388
+ ans = nx.average_shortest_path_length(G, weight="weight", method="dijkstra")
389
+ assert ans == pytest.approx(4, abs=1e-7)
390
+ ans = nx.average_shortest_path_length(G, weight="weight", method="bellman-ford")
391
+ assert ans == pytest.approx(4, abs=1e-7)
392
+ ans = nx.average_shortest_path_length(
393
+ G, weight="weight", method="floyd-warshall"
394
+ )
395
+ assert ans == pytest.approx(4, abs=1e-7)
396
+
397
+ def test_directed_not_strongly_connected(self):
398
+ G = nx.DiGraph([(0, 1)])
399
+ with pytest.raises(nx.NetworkXError, match="Graph is not strongly connected"):
400
+ nx.average_shortest_path_length(G)
401
+
402
+ def test_undirected_not_connected(self):
403
+ g = nx.Graph()
404
+ g.add_nodes_from(range(3))
405
+ g.add_edge(0, 1)
406
+ pytest.raises(nx.NetworkXError, nx.average_shortest_path_length, g)
407
+
408
+ def test_trivial_graph(self):
409
+ """Tests that the trivial graph has average path length zero,
410
+ since there is exactly one path of length zero in the trivial
411
+ graph.
412
+
413
+ For more information, see issue #1960.
414
+
415
+ """
416
+ G = nx.trivial_graph()
417
+ assert nx.average_shortest_path_length(G) == 0
418
+
419
+ def test_null_graph(self):
420
+ with pytest.raises(nx.NetworkXPointlessConcept):
421
+ nx.average_shortest_path_length(nx.null_graph())
422
+
423
+ def test_bad_method(self):
424
+ with pytest.raises(ValueError):
425
+ G = nx.path_graph(2)
426
+ nx.average_shortest_path_length(G, weight="weight", method="SPAM")
427
+
428
+
429
+ class TestAverageShortestPathLengthNumpy:
430
+ @classmethod
431
+ def setup_class(cls):
432
+ global np
433
+ import pytest
434
+
435
+ np = pytest.importorskip("numpy")
436
+
437
+ def test_specified_methods_numpy(self):
438
+ G = nx.Graph()
439
+ nx.add_cycle(G, range(7), weight=2)
440
+ ans = nx.average_shortest_path_length(
441
+ G, weight="weight", method="floyd-warshall-numpy"
442
+ )
443
+ np.testing.assert_almost_equal(ans, 4)
444
+
445
+ G = nx.Graph()
446
+ nx.add_path(G, range(5), weight=2)
447
+ ans = nx.average_shortest_path_length(
448
+ G, weight="weight", method="floyd-warshall-numpy"
449
+ )
450
+ np.testing.assert_almost_equal(ans, 4)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_unweighted.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def validate_grid_path(r, c, s, t, p):
7
+ assert isinstance(p, list)
8
+ assert p[0] == s
9
+ assert p[-1] == t
10
+ s = ((s - 1) // c, (s - 1) % c)
11
+ t = ((t - 1) // c, (t - 1) % c)
12
+ assert len(p) == abs(t[0] - s[0]) + abs(t[1] - s[1]) + 1
13
+ p = [((u - 1) // c, (u - 1) % c) for u in p]
14
+ for u in p:
15
+ assert 0 <= u[0] < r
16
+ assert 0 <= u[1] < c
17
+ for u, v in zip(p[:-1], p[1:]):
18
+ assert (abs(v[0] - u[0]), abs(v[1] - u[1])) in [(0, 1), (1, 0)]
19
+
20
+
21
+ class TestUnweightedPath:
22
+ @classmethod
23
+ def setup_class(cls):
24
+ from networkx import convert_node_labels_to_integers as cnlti
25
+
26
+ cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
27
+ cls.cycle = nx.cycle_graph(7)
28
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
29
+
30
+ def test_bidirectional_shortest_path(self):
31
+ assert nx.bidirectional_shortest_path(self.cycle, 0, 3) == [0, 1, 2, 3]
32
+ assert nx.bidirectional_shortest_path(self.cycle, 0, 4) == [0, 6, 5, 4]
33
+ validate_grid_path(
34
+ 4, 4, 1, 12, nx.bidirectional_shortest_path(self.grid, 1, 12)
35
+ )
36
+ assert nx.bidirectional_shortest_path(self.directed_cycle, 0, 3) == [0, 1, 2, 3]
37
+ # test source = target
38
+ assert nx.bidirectional_shortest_path(self.cycle, 3, 3) == [3]
39
+
40
+ @pytest.mark.parametrize(
41
+ ("src", "tgt"),
42
+ (
43
+ (8, 3), # source not in graph
44
+ (3, 8), # target not in graph
45
+ (8, 10), # neither source nor target in graph
46
+ (8, 8), # src == tgt, neither in graph - tests order of input checks
47
+ ),
48
+ )
49
+ def test_bidirectional_shortest_path_src_tgt_not_in_graph(self, src, tgt):
50
+ with pytest.raises(
51
+ nx.NodeNotFound,
52
+ match=f"(Source {src}|Target {tgt}) is not in G",
53
+ ):
54
+ nx.bidirectional_shortest_path(self.cycle, src, tgt)
55
+
56
+ def test_shortest_path_length(self):
57
+ assert nx.shortest_path_length(self.cycle, 0, 3) == 3
58
+ assert nx.shortest_path_length(self.grid, 1, 12) == 5
59
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4) == 4
60
+ # now with weights
61
+ assert nx.shortest_path_length(self.cycle, 0, 3, weight=True) == 3
62
+ assert nx.shortest_path_length(self.grid, 1, 12, weight=True) == 5
63
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4, weight=True) == 4
64
+
65
+ def test_single_source_shortest_path(self):
66
+ p = nx.single_source_shortest_path(self.directed_cycle, 3)
67
+ assert p[0] == [3, 4, 5, 6, 0]
68
+ p = nx.single_source_shortest_path(self.cycle, 0)
69
+ assert p[3] == [0, 1, 2, 3]
70
+ p = nx.single_source_shortest_path(self.cycle, 0, cutoff=0)
71
+ assert p == {0: [0]}
72
+
73
+ def test_single_source_shortest_path_length(self):
74
+ pl = nx.single_source_shortest_path_length
75
+ lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
76
+ assert dict(pl(self.cycle, 0)) == lengths
77
+ lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
78
+ assert dict(pl(self.directed_cycle, 0)) == lengths
79
+
80
+ def test_single_target_shortest_path(self):
81
+ p = nx.single_target_shortest_path(self.directed_cycle, 0)
82
+ assert p[3] == [3, 4, 5, 6, 0]
83
+ p = nx.single_target_shortest_path(self.cycle, 0)
84
+ assert p[3] == [3, 2, 1, 0]
85
+ p = nx.single_target_shortest_path(self.cycle, 0, cutoff=0)
86
+ assert p == {0: [0]}
87
+ # test missing targets
88
+ target = 8
89
+ with pytest.raises(nx.NodeNotFound, match=f"Target {target} not in G"):
90
+ nx.single_target_shortest_path(self.cycle, target)
91
+
92
+ def test_single_target_shortest_path_length(self):
93
+ pl = nx.single_target_shortest_path_length
94
+ lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
95
+ assert dict(pl(self.cycle, 0)) == lengths
96
+ lengths = {0: 0, 1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
97
+ assert dict(pl(self.directed_cycle, 0)) == lengths
98
+ # test missing targets
99
+ target = 8
100
+ with pytest.raises(nx.NodeNotFound, match=f"Target {target} is not in G"):
101
+ nx.single_target_shortest_path_length(self.cycle, target)
102
+
103
+ def test_all_pairs_shortest_path(self):
104
+ p = dict(nx.all_pairs_shortest_path(self.cycle))
105
+ assert p[0][3] == [0, 1, 2, 3]
106
+ p = dict(nx.all_pairs_shortest_path(self.grid))
107
+ validate_grid_path(4, 4, 1, 12, p[1][12])
108
+
109
+ def test_all_pairs_shortest_path_length(self):
110
+ l = dict(nx.all_pairs_shortest_path_length(self.cycle))
111
+ assert l[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
112
+ l = dict(nx.all_pairs_shortest_path_length(self.grid))
113
+ assert l[1][16] == 6
114
+
115
+ def test_predecessor_path(self):
116
+ G = nx.path_graph(4)
117
+ assert nx.predecessor(G, 0) == {0: [], 1: [0], 2: [1], 3: [2]}
118
+ assert nx.predecessor(G, 0, 3) == [2]
119
+
120
+ def test_predecessor_cycle(self):
121
+ G = nx.cycle_graph(4)
122
+ pred = nx.predecessor(G, 0)
123
+ assert pred[0] == []
124
+ assert pred[1] == [0]
125
+ assert pred[2] in [[1, 3], [3, 1]]
126
+ assert pred[3] == [0]
127
+
128
+ def test_predecessor_cutoff(self):
129
+ G = nx.path_graph(4)
130
+ p = nx.predecessor(G, 0, 3)
131
+ assert 4 not in p
132
+
133
+ def test_predecessor_target(self):
134
+ G = nx.path_graph(4)
135
+ p = nx.predecessor(G, 0, 3)
136
+ assert p == [2]
137
+ p = nx.predecessor(G, 0, 3, cutoff=2)
138
+ assert p == []
139
+ p, s = nx.predecessor(G, 0, 3, return_seen=True)
140
+ assert p == [2]
141
+ assert s == 3
142
+ p, s = nx.predecessor(G, 0, 3, cutoff=2, return_seen=True)
143
+ assert p == []
144
+ assert s == -1
145
+
146
+ def test_predecessor_missing_source(self):
147
+ source = 8
148
+ with pytest.raises(nx.NodeNotFound, match=f"Source {source} not in G"):
149
+ nx.predecessor(self.cycle, source)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_weighted.py ADDED
@@ -0,0 +1,972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+
7
+ def validate_path(G, s, t, soln_len, path, weight="weight"):
8
+ assert path[0] == s
9
+ assert path[-1] == t
10
+
11
+ if callable(weight):
12
+ weight_f = weight
13
+ else:
14
+ if G.is_multigraph():
15
+
16
+ def weight_f(u, v, d):
17
+ return min(e.get(weight, 1) for e in d.values())
18
+
19
+ else:
20
+
21
+ def weight_f(u, v, d):
22
+ return d.get(weight, 1)
23
+
24
+ computed = sum(weight_f(u, v, G[u][v]) for u, v in pairwise(path))
25
+ assert soln_len == computed
26
+
27
+
28
+ def validate_length_path(G, s, t, soln_len, length, path, weight="weight"):
29
+ assert soln_len == length
30
+ validate_path(G, s, t, length, path, weight=weight)
31
+
32
+
33
+ class WeightedTestBase:
34
+ """Base class for test classes that test functions for computing
35
+ shortest paths in weighted graphs.
36
+
37
+ """
38
+
39
+ def setup_method(self):
40
+ """Creates some graphs for use in the unit tests."""
41
+ cnlti = nx.convert_node_labels_to_integers
42
+ self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
43
+ self.cycle = nx.cycle_graph(7)
44
+ self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
45
+ self.XG = nx.DiGraph()
46
+ self.XG.add_weighted_edges_from(
47
+ [
48
+ ("s", "u", 10),
49
+ ("s", "x", 5),
50
+ ("u", "v", 1),
51
+ ("u", "x", 2),
52
+ ("v", "y", 1),
53
+ ("x", "u", 3),
54
+ ("x", "v", 5),
55
+ ("x", "y", 2),
56
+ ("y", "s", 7),
57
+ ("y", "v", 6),
58
+ ]
59
+ )
60
+ self.MXG = nx.MultiDiGraph(self.XG)
61
+ self.MXG.add_edge("s", "u", weight=15)
62
+ self.XG2 = nx.DiGraph()
63
+ self.XG2.add_weighted_edges_from(
64
+ [
65
+ [1, 4, 1],
66
+ [4, 5, 1],
67
+ [5, 6, 1],
68
+ [6, 3, 1],
69
+ [1, 3, 50],
70
+ [1, 2, 100],
71
+ [2, 3, 100],
72
+ ]
73
+ )
74
+
75
+ self.XG3 = nx.Graph()
76
+ self.XG3.add_weighted_edges_from(
77
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
78
+ )
79
+
80
+ self.XG4 = nx.Graph()
81
+ self.XG4.add_weighted_edges_from(
82
+ [
83
+ [0, 1, 2],
84
+ [1, 2, 2],
85
+ [2, 3, 1],
86
+ [3, 4, 1],
87
+ [4, 5, 1],
88
+ [5, 6, 1],
89
+ [6, 7, 1],
90
+ [7, 0, 1],
91
+ ]
92
+ )
93
+ self.MXG4 = nx.MultiGraph(self.XG4)
94
+ self.MXG4.add_edge(0, 1, weight=3)
95
+ self.G = nx.DiGraph() # no weights
96
+ self.G.add_edges_from(
97
+ [
98
+ ("s", "u"),
99
+ ("s", "x"),
100
+ ("u", "v"),
101
+ ("u", "x"),
102
+ ("v", "y"),
103
+ ("x", "u"),
104
+ ("x", "v"),
105
+ ("x", "y"),
106
+ ("y", "s"),
107
+ ("y", "v"),
108
+ ]
109
+ )
110
+
111
+
112
+ class TestWeightedPath(WeightedTestBase):
113
+ def test_dijkstra(self):
114
+ (D, P) = nx.single_source_dijkstra(self.XG, "s")
115
+ validate_path(self.XG, "s", "v", 9, P["v"])
116
+ assert D["v"] == 9
117
+
118
+ validate_path(
119
+ self.XG, "s", "v", 9, nx.single_source_dijkstra_path(self.XG, "s")["v"]
120
+ )
121
+ assert dict(nx.single_source_dijkstra_path_length(self.XG, "s"))["v"] == 9
122
+
123
+ validate_path(
124
+ self.XG, "s", "v", 9, nx.single_source_dijkstra(self.XG, "s")[1]["v"]
125
+ )
126
+ validate_path(
127
+ self.MXG, "s", "v", 9, nx.single_source_dijkstra_path(self.MXG, "s")["v"]
128
+ )
129
+
130
+ GG = self.XG.to_undirected()
131
+ # make sure we get lower weight
132
+ # to_undirected might choose either edge with weight 2 or weight 3
133
+ GG["u"]["x"]["weight"] = 2
134
+ (D, P) = nx.single_source_dijkstra(GG, "s")
135
+ validate_path(GG, "s", "v", 8, P["v"])
136
+ assert D["v"] == 8 # uses lower weight of 2 on u<->x edge
137
+ validate_path(GG, "s", "v", 8, nx.dijkstra_path(GG, "s", "v"))
138
+ assert nx.dijkstra_path_length(GG, "s", "v") == 8
139
+
140
+ validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3))
141
+ validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3))
142
+ assert nx.dijkstra_path_length(self.XG3, 0, 3) == 15
143
+ validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2))
144
+ assert nx.dijkstra_path_length(self.XG4, 0, 2) == 4
145
+ validate_path(self.MXG4, 0, 2, 4, nx.dijkstra_path(self.MXG4, 0, 2))
146
+ validate_path(
147
+ self.G, "s", "v", 2, nx.single_source_dijkstra(self.G, "s", "v")[1]
148
+ )
149
+ validate_path(
150
+ self.G, "s", "v", 2, nx.single_source_dijkstra(self.G, "s")[1]["v"]
151
+ )
152
+
153
+ validate_path(self.G, "s", "v", 2, nx.dijkstra_path(self.G, "s", "v"))
154
+ assert nx.dijkstra_path_length(self.G, "s", "v") == 2
155
+
156
+ # NetworkXError: node s not reachable from moon
157
+ pytest.raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, "s", "moon")
158
+ pytest.raises(nx.NetworkXNoPath, nx.dijkstra_path_length, self.G, "s", "moon")
159
+
160
+ validate_path(self.cycle, 0, 3, 3, nx.dijkstra_path(self.cycle, 0, 3))
161
+ validate_path(self.cycle, 0, 4, 3, nx.dijkstra_path(self.cycle, 0, 4))
162
+
163
+ assert nx.single_source_dijkstra(self.cycle, 0, 0) == (0, [0])
164
+
165
+ def test_bidirectional_dijkstra(self):
166
+ validate_length_path(
167
+ self.XG, "s", "v", 9, *nx.bidirectional_dijkstra(self.XG, "s", "v")
168
+ )
169
+ validate_length_path(
170
+ self.G, "s", "v", 2, *nx.bidirectional_dijkstra(self.G, "s", "v")
171
+ )
172
+ validate_length_path(
173
+ self.cycle, 0, 3, 3, *nx.bidirectional_dijkstra(self.cycle, 0, 3)
174
+ )
175
+ validate_length_path(
176
+ self.cycle, 0, 4, 3, *nx.bidirectional_dijkstra(self.cycle, 0, 4)
177
+ )
178
+ validate_length_path(
179
+ self.XG3, 0, 3, 15, *nx.bidirectional_dijkstra(self.XG3, 0, 3)
180
+ )
181
+ validate_length_path(
182
+ self.XG4, 0, 2, 4, *nx.bidirectional_dijkstra(self.XG4, 0, 2)
183
+ )
184
+
185
+ # need more tests here
186
+ P = nx.single_source_dijkstra_path(self.XG, "s")["v"]
187
+ validate_path(
188
+ self.XG,
189
+ "s",
190
+ "v",
191
+ sum(self.XG[u][v]["weight"] for u, v in zip(P[:-1], P[1:])),
192
+ nx.dijkstra_path(self.XG, "s", "v"),
193
+ )
194
+
195
+ # check absent source
196
+ G = nx.path_graph(2)
197
+ pytest.raises(nx.NodeNotFound, nx.bidirectional_dijkstra, G, 3, 0)
198
+
199
+ def test_weight_functions(self):
200
+ def heuristic(*z):
201
+ return sum(val**2 for val in z)
202
+
203
+ def getpath(pred, v, s):
204
+ return [v] if v == s else getpath(pred, pred[v], s) + [v]
205
+
206
+ def goldberg_radzik(g, s, t, weight="weight"):
207
+ pred, dist = nx.goldberg_radzik(g, s, weight=weight)
208
+ dist = dist[t]
209
+ return dist, getpath(pred, t, s)
210
+
211
+ def astar(g, s, t, weight="weight"):
212
+ path = nx.astar_path(g, s, t, heuristic, weight=weight)
213
+ dist = nx.astar_path_length(g, s, t, heuristic, weight=weight)
214
+ return dist, path
215
+
216
+ def vlp(G, s, t, l, F, w):
217
+ res = F(G, s, t, weight=w)
218
+ validate_length_path(G, s, t, l, *res, weight=w)
219
+
220
+ G = self.cycle
221
+ s = 6
222
+ t = 4
223
+ path = [6] + list(range(t + 1))
224
+
225
+ def weight(u, v, _):
226
+ return 1 + v**2
227
+
228
+ length = sum(weight(u, v, None) for u, v in pairwise(path))
229
+ vlp(G, s, t, length, nx.bidirectional_dijkstra, weight)
230
+ vlp(G, s, t, length, nx.single_source_dijkstra, weight)
231
+ vlp(G, s, t, length, nx.single_source_bellman_ford, weight)
232
+ vlp(G, s, t, length, goldberg_radzik, weight)
233
+ vlp(G, s, t, length, astar, weight)
234
+
235
+ def weight(u, v, _):
236
+ return 2 ** (u * v)
237
+
238
+ length = sum(weight(u, v, None) for u, v in pairwise(path))
239
+ vlp(G, s, t, length, nx.bidirectional_dijkstra, weight)
240
+ vlp(G, s, t, length, nx.single_source_dijkstra, weight)
241
+ vlp(G, s, t, length, nx.single_source_bellman_ford, weight)
242
+ vlp(G, s, t, length, goldberg_radzik, weight)
243
+ vlp(G, s, t, length, astar, weight)
244
+
245
+ def test_bidirectional_dijkstra_no_path(self):
246
+ with pytest.raises(nx.NetworkXNoPath):
247
+ G = nx.Graph()
248
+ nx.add_path(G, [1, 2, 3])
249
+ nx.add_path(G, [4, 5, 6])
250
+ path = nx.bidirectional_dijkstra(G, 1, 6)
251
+
252
+ @pytest.mark.parametrize(
253
+ "fn",
254
+ (
255
+ nx.dijkstra_path,
256
+ nx.dijkstra_path_length,
257
+ nx.single_source_dijkstra_path,
258
+ nx.single_source_dijkstra_path_length,
259
+ nx.single_source_dijkstra,
260
+ nx.dijkstra_predecessor_and_distance,
261
+ ),
262
+ )
263
+ def test_absent_source(self, fn):
264
+ G = nx.path_graph(2)
265
+ with pytest.raises(nx.NodeNotFound):
266
+ fn(G, 3, 0)
267
+ # Test when source == target, which is handled specially by some functions
268
+ with pytest.raises(nx.NodeNotFound):
269
+ fn(G, 3, 3)
270
+
271
+ def test_dijkstra_predecessor1(self):
272
+ G = nx.path_graph(4)
273
+ assert nx.dijkstra_predecessor_and_distance(G, 0) == (
274
+ {0: [], 1: [0], 2: [1], 3: [2]},
275
+ {0: 0, 1: 1, 2: 2, 3: 3},
276
+ )
277
+
278
+ def test_dijkstra_predecessor2(self):
279
+ # 4-cycle
280
+ G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)])
281
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, (0))
282
+ assert pred[0] == []
283
+ assert pred[1] == [0]
284
+ assert pred[2] in [[1, 3], [3, 1]]
285
+ assert pred[3] == [0]
286
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
287
+
288
+ def test_dijkstra_predecessor3(self):
289
+ XG = nx.DiGraph()
290
+ XG.add_weighted_edges_from(
291
+ [
292
+ ("s", "u", 10),
293
+ ("s", "x", 5),
294
+ ("u", "v", 1),
295
+ ("u", "x", 2),
296
+ ("v", "y", 1),
297
+ ("x", "u", 3),
298
+ ("x", "v", 5),
299
+ ("x", "y", 2),
300
+ ("y", "s", 7),
301
+ ("y", "v", 6),
302
+ ]
303
+ )
304
+ (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s")
305
+ assert P["v"] == ["u"]
306
+ assert D["v"] == 9
307
+ (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s", cutoff=8)
308
+ assert "v" not in D
309
+
310
+ def test_single_source_dijkstra_path_length(self):
311
+ pl = nx.single_source_dijkstra_path_length
312
+ assert dict(pl(self.MXG4, 0))[2] == 4
313
+ spl = pl(self.MXG4, 0, cutoff=2)
314
+ assert 2 not in spl
315
+
316
+ def test_bidirectional_dijkstra_multigraph(self):
317
+ G = nx.MultiGraph()
318
+ G.add_edge("a", "b", weight=10)
319
+ G.add_edge("a", "b", weight=100)
320
+ dp = nx.bidirectional_dijkstra(G, "a", "b")
321
+ assert dp == (10, ["a", "b"])
322
+
323
+ def test_dijkstra_pred_distance_multigraph(self):
324
+ G = nx.MultiGraph()
325
+ G.add_edge("a", "b", key="short", foo=5, weight=100)
326
+ G.add_edge("a", "b", key="long", bar=1, weight=110)
327
+ p, d = nx.dijkstra_predecessor_and_distance(G, "a")
328
+ assert p == {"a": [], "b": ["a"]}
329
+ assert d == {"a": 0, "b": 100}
330
+
331
+ def test_negative_edge_cycle(self):
332
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
333
+ assert not nx.negative_edge_cycle(G)
334
+ G.add_edge(8, 9, weight=-7)
335
+ G.add_edge(9, 8, weight=3)
336
+ graph_size = len(G)
337
+ assert nx.negative_edge_cycle(G)
338
+ assert graph_size == len(G)
339
+ pytest.raises(ValueError, nx.single_source_dijkstra_path_length, G, 8)
340
+ pytest.raises(ValueError, nx.single_source_dijkstra, G, 8)
341
+ pytest.raises(ValueError, nx.dijkstra_predecessor_and_distance, G, 8)
342
+ G.add_edge(9, 10)
343
+ pytest.raises(ValueError, nx.bidirectional_dijkstra, G, 8, 10)
344
+ G = nx.MultiDiGraph()
345
+ G.add_edge(2, 2, weight=-1)
346
+ assert nx.negative_edge_cycle(G)
347
+
348
+ def test_negative_edge_cycle_empty(self):
349
+ G = nx.DiGraph()
350
+ assert not nx.negative_edge_cycle(G)
351
+
352
+ def test_negative_edge_cycle_custom_weight_key(self):
353
+ d = nx.DiGraph()
354
+ d.add_edge("a", "b", w=-2)
355
+ d.add_edge("b", "a", w=-1)
356
+ assert nx.negative_edge_cycle(d, weight="w")
357
+
358
+ def test_weight_function(self):
359
+ """Tests that a callable weight is interpreted as a weight
360
+ function instead of an edge attribute.
361
+
362
+ """
363
+ # Create a triangle in which the edge from node 0 to node 2 has
364
+ # a large weight and the other two edges have a small weight.
365
+ G = nx.complete_graph(3)
366
+ G.adj[0][2]["weight"] = 10
367
+ G.adj[0][1]["weight"] = 1
368
+ G.adj[1][2]["weight"] = 1
369
+
370
+ # The weight function will take the multiplicative inverse of
371
+ # the weights on the edges. This way, weights that were large
372
+ # before now become small and vice versa.
373
+
374
+ def weight(u, v, d):
375
+ return 1 / d["weight"]
376
+
377
+ # The shortest path from 0 to 2 using the actual weights on the
378
+ # edges should be [0, 1, 2].
379
+ distance, path = nx.single_source_dijkstra(G, 0, 2)
380
+ assert distance == 2
381
+ assert path == [0, 1, 2]
382
+ # However, with the above weight function, the shortest path
383
+ # should be [0, 2], since that has a very small weight.
384
+ distance, path = nx.single_source_dijkstra(G, 0, 2, weight=weight)
385
+ assert distance == 1 / 10
386
+ assert path == [0, 2]
387
+
388
+ def test_all_pairs_dijkstra_path(self):
389
+ cycle = nx.cycle_graph(7)
390
+ p = dict(nx.all_pairs_dijkstra_path(cycle))
391
+ assert p[0][3] == [0, 1, 2, 3]
392
+
393
+ cycle[1][2]["weight"] = 10
394
+ p = dict(nx.all_pairs_dijkstra_path(cycle))
395
+ assert p[0][3] == [0, 6, 5, 4, 3]
396
+
397
+ def test_all_pairs_dijkstra_path_length(self):
398
+ cycle = nx.cycle_graph(7)
399
+ pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
400
+ assert pl[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
401
+
402
+ cycle[1][2]["weight"] = 10
403
+ pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
404
+ assert pl[0] == {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
405
+
406
+ def test_all_pairs_dijkstra(self):
407
+ cycle = nx.cycle_graph(7)
408
+ out = dict(nx.all_pairs_dijkstra(cycle))
409
+ assert out[0][0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
410
+ assert out[0][1][3] == [0, 1, 2, 3]
411
+
412
+ cycle[1][2]["weight"] = 10
413
+ out = dict(nx.all_pairs_dijkstra(cycle))
414
+ assert out[0][0] == {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
415
+ assert out[0][1][3] == [0, 6, 5, 4, 3]
416
+
417
+
418
+ class TestDijkstraPathLength:
419
+ """Unit tests for the :func:`networkx.dijkstra_path_length`
420
+ function.
421
+
422
+ """
423
+
424
+ def test_weight_function(self):
425
+ """Tests for computing the length of the shortest path using
426
+ Dijkstra's algorithm with a user-defined weight function.
427
+
428
+ """
429
+ # Create a triangle in which the edge from node 0 to node 2 has
430
+ # a large weight and the other two edges have a small weight.
431
+ G = nx.complete_graph(3)
432
+ G.adj[0][2]["weight"] = 10
433
+ G.adj[0][1]["weight"] = 1
434
+ G.adj[1][2]["weight"] = 1
435
+
436
+ # The weight function will take the multiplicative inverse of
437
+ # the weights on the edges. This way, weights that were large
438
+ # before now become small and vice versa.
439
+
440
+ def weight(u, v, d):
441
+ return 1 / d["weight"]
442
+
443
+ # The shortest path from 0 to 2 using the actual weights on the
444
+ # edges should be [0, 1, 2]. However, with the above weight
445
+ # function, the shortest path should be [0, 2], since that has a
446
+ # very small weight.
447
+ length = nx.dijkstra_path_length(G, 0, 2, weight=weight)
448
+ assert length == 1 / 10
449
+
450
+
451
+ class TestMultiSourceDijkstra:
452
+ """Unit tests for the multi-source dialect of Dijkstra's shortest
453
+ path algorithms.
454
+
455
+ """
456
+
457
+ def test_no_sources(self):
458
+ with pytest.raises(ValueError):
459
+ nx.multi_source_dijkstra(nx.Graph(), {})
460
+
461
+ def test_path_no_sources(self):
462
+ with pytest.raises(ValueError):
463
+ nx.multi_source_dijkstra_path(nx.Graph(), {})
464
+
465
+ def test_path_length_no_sources(self):
466
+ with pytest.raises(ValueError):
467
+ nx.multi_source_dijkstra_path_length(nx.Graph(), {})
468
+
469
+ @pytest.mark.parametrize(
470
+ "fn",
471
+ (
472
+ nx.multi_source_dijkstra_path,
473
+ nx.multi_source_dijkstra_path_length,
474
+ nx.multi_source_dijkstra,
475
+ ),
476
+ )
477
+ def test_absent_source(self, fn):
478
+ G = nx.path_graph(2)
479
+ with pytest.raises(nx.NodeNotFound):
480
+ fn(G, [3], 0)
481
+ with pytest.raises(nx.NodeNotFound):
482
+ fn(G, [3], 3)
483
+
484
+ def test_two_sources(self):
485
+ edges = [(0, 1, 1), (1, 2, 1), (2, 3, 10), (3, 4, 1)]
486
+ G = nx.Graph()
487
+ G.add_weighted_edges_from(edges)
488
+ sources = {0, 4}
489
+ distances, paths = nx.multi_source_dijkstra(G, sources)
490
+ expected_distances = {0: 0, 1: 1, 2: 2, 3: 1, 4: 0}
491
+ expected_paths = {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [4, 3], 4: [4]}
492
+ assert distances == expected_distances
493
+ assert paths == expected_paths
494
+
495
+ def test_simple_paths(self):
496
+ G = nx.path_graph(4)
497
+ lengths = nx.multi_source_dijkstra_path_length(G, [0])
498
+ assert lengths == {n: n for n in G}
499
+ paths = nx.multi_source_dijkstra_path(G, [0])
500
+ assert paths == {n: list(range(n + 1)) for n in G}
501
+
502
+
503
+ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
504
+ def test_single_node_graph(self):
505
+ G = nx.DiGraph()
506
+ G.add_node(0)
507
+ assert nx.single_source_bellman_ford_path(G, 0) == {0: [0]}
508
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {0: 0}
509
+ assert nx.single_source_bellman_ford(G, 0) == ({0: 0}, {0: [0]})
510
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == ({0: []}, {0: 0})
511
+ assert nx.goldberg_radzik(G, 0) == ({0: None}, {0: 0})
512
+
513
+ def test_absent_source_bellman_ford(self):
514
+ # the check is in _bellman_ford; this provides regression testing
515
+ # against later changes to "client" Bellman-Ford functions
516
+ G = nx.path_graph(2)
517
+ for fn in (
518
+ nx.bellman_ford_predecessor_and_distance,
519
+ nx.bellman_ford_path,
520
+ nx.bellman_ford_path_length,
521
+ nx.single_source_bellman_ford_path,
522
+ nx.single_source_bellman_ford_path_length,
523
+ nx.single_source_bellman_ford,
524
+ ):
525
+ pytest.raises(nx.NodeNotFound, fn, G, 3, 0)
526
+ pytest.raises(nx.NodeNotFound, fn, G, 3, 3)
527
+
528
+ def test_absent_source_goldberg_radzik(self):
529
+ with pytest.raises(nx.NodeNotFound):
530
+ G = nx.path_graph(2)
531
+ nx.goldberg_radzik(G, 3, 0)
532
+
533
+ def test_negative_cycle_heuristic(self):
534
+ G = nx.DiGraph()
535
+ G.add_edge(0, 1, weight=-1)
536
+ G.add_edge(1, 2, weight=-1)
537
+ G.add_edge(2, 3, weight=-1)
538
+ G.add_edge(3, 0, weight=3)
539
+ assert not nx.negative_edge_cycle(G, heuristic=True)
540
+ G.add_edge(2, 0, weight=1.999)
541
+ assert nx.negative_edge_cycle(G, heuristic=True)
542
+ G.edges[2, 0]["weight"] = 2
543
+ assert not nx.negative_edge_cycle(G, heuristic=True)
544
+
545
+ def test_negative_cycle_consistency(self):
546
+ import random
547
+
548
+ unif = random.uniform
549
+ for random_seed in range(2): # range(20):
550
+ random.seed(random_seed)
551
+ for density in [0.1, 0.9]: # .3, .7, .9]:
552
+ for N in [1, 10, 20]: # range(1, 60 - int(30 * density)):
553
+ for max_cost in [1, 90]: # [1, 10, 40, 90]:
554
+ G = nx.binomial_graph(N, density, seed=4, directed=True)
555
+ edges = ((u, v, unif(-1, max_cost)) for u, v in G.edges)
556
+ G.add_weighted_edges_from(edges)
557
+
558
+ no_heuristic = nx.negative_edge_cycle(G, heuristic=False)
559
+ with_heuristic = nx.negative_edge_cycle(G, heuristic=True)
560
+ assert no_heuristic == with_heuristic
561
+
562
+ def test_negative_cycle(self):
563
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
564
+ G.add_edge(1, 2, weight=-7)
565
+ for i in range(5):
566
+ pytest.raises(
567
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, i
568
+ )
569
+ pytest.raises(
570
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i
571
+ )
572
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i)
573
+ pytest.raises(
574
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i
575
+ )
576
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
577
+ G = nx.cycle_graph(5) # undirected Graph
578
+ G.add_edge(1, 2, weight=-3)
579
+ for i in range(5):
580
+ pytest.raises(
581
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, i
582
+ )
583
+ pytest.raises(
584
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i
585
+ )
586
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i)
587
+ pytest.raises(
588
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i
589
+ )
590
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
591
+ G = nx.DiGraph([(1, 1, {"weight": -1})])
592
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1)
593
+ pytest.raises(
594
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1
595
+ )
596
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1)
597
+ pytest.raises(
598
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1
599
+ )
600
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
601
+ G = nx.MultiDiGraph([(1, 1, {"weight": -1})])
602
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1)
603
+ pytest.raises(
604
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1
605
+ )
606
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1)
607
+ pytest.raises(
608
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1
609
+ )
610
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
611
+
612
+ def test_zero_cycle(self):
613
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
614
+ G.add_edge(2, 3, weight=-4)
615
+ # check that zero cycle doesn't raise
616
+ nx.goldberg_radzik(G, 1)
617
+ nx.bellman_ford_predecessor_and_distance(G, 1)
618
+
619
+ G.add_edge(2, 3, weight=-4.0001)
620
+ # check that negative cycle does raise
621
+ pytest.raises(
622
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1
623
+ )
624
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
625
+
626
+ def test_find_negative_cycle_longer_cycle(self):
627
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
628
+ nx.add_cycle(G, [3, 5, 6, 7, 8, 9])
629
+ G.add_edge(1, 2, weight=-30)
630
+ assert nx.find_negative_cycle(G, 1) == [0, 1, 2, 3, 4, 0]
631
+ assert nx.find_negative_cycle(G, 7) == [2, 3, 4, 0, 1, 2]
632
+
633
+ def test_find_negative_cycle_no_cycle(self):
634
+ G = nx.path_graph(5, create_using=nx.DiGraph())
635
+ pytest.raises(nx.NetworkXError, nx.find_negative_cycle, G, 3)
636
+
637
+ def test_find_negative_cycle_single_edge(self):
638
+ G = nx.Graph()
639
+ G.add_edge(0, 1, weight=-1)
640
+ assert nx.find_negative_cycle(G, 1) == [1, 0, 1]
641
+
642
+ def test_negative_weight(self):
643
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
644
+ G.add_edge(1, 2, weight=-3)
645
+ assert nx.single_source_bellman_ford_path(G, 0) == {
646
+ 0: [0],
647
+ 1: [0, 1],
648
+ 2: [0, 1, 2],
649
+ 3: [0, 1, 2, 3],
650
+ 4: [0, 1, 2, 3, 4],
651
+ }
652
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {
653
+ 0: 0,
654
+ 1: 1,
655
+ 2: -2,
656
+ 3: -1,
657
+ 4: 0,
658
+ }
659
+ assert nx.single_source_bellman_ford(G, 0) == (
660
+ {0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
661
+ {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]},
662
+ )
663
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
664
+ {0: [], 1: [0], 2: [1], 3: [2], 4: [3]},
665
+ {0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
666
+ )
667
+ assert nx.goldberg_radzik(G, 0) == (
668
+ {0: None, 1: 0, 2: 1, 3: 2, 4: 3},
669
+ {0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
670
+ )
671
+
672
+ def test_not_connected(self):
673
+ G = nx.complete_graph(6)
674
+ G.add_edge(10, 11)
675
+ G.add_edge(10, 12)
676
+ assert nx.single_source_bellman_ford_path(G, 0) == {
677
+ 0: [0],
678
+ 1: [0, 1],
679
+ 2: [0, 2],
680
+ 3: [0, 3],
681
+ 4: [0, 4],
682
+ 5: [0, 5],
683
+ }
684
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {
685
+ 0: 0,
686
+ 1: 1,
687
+ 2: 1,
688
+ 3: 1,
689
+ 4: 1,
690
+ 5: 1,
691
+ }
692
+ assert nx.single_source_bellman_ford(G, 0) == (
693
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
694
+ {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]},
695
+ )
696
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
697
+ {0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
698
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
699
+ )
700
+ assert nx.goldberg_radzik(G, 0) == (
701
+ {0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
702
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
703
+ )
704
+
705
+ # not connected, with a component not containing the source that
706
+ # contains a negative cycle.
707
+ G = nx.complete_graph(6)
708
+ G.add_edges_from(
709
+ [
710
+ ("A", "B", {"load": 3}),
711
+ ("B", "C", {"load": -10}),
712
+ ("C", "A", {"load": 2}),
713
+ ]
714
+ )
715
+ assert nx.single_source_bellman_ford_path(G, 0, weight="load") == {
716
+ 0: [0],
717
+ 1: [0, 1],
718
+ 2: [0, 2],
719
+ 3: [0, 3],
720
+ 4: [0, 4],
721
+ 5: [0, 5],
722
+ }
723
+ assert nx.single_source_bellman_ford_path_length(G, 0, weight="load") == {
724
+ 0: 0,
725
+ 1: 1,
726
+ 2: 1,
727
+ 3: 1,
728
+ 4: 1,
729
+ 5: 1,
730
+ }
731
+ assert nx.single_source_bellman_ford(G, 0, weight="load") == (
732
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
733
+ {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]},
734
+ )
735
+ assert nx.bellman_ford_predecessor_and_distance(G, 0, weight="load") == (
736
+ {0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
737
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
738
+ )
739
+ assert nx.goldberg_radzik(G, 0, weight="load") == (
740
+ {0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
741
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
742
+ )
743
+
744
+ def test_multigraph(self):
745
+ assert nx.bellman_ford_path(self.MXG, "s", "v") == ["s", "x", "u", "v"]
746
+ assert nx.bellman_ford_path_length(self.MXG, "s", "v") == 9
747
+ assert nx.single_source_bellman_ford_path(self.MXG, "s")["v"] == [
748
+ "s",
749
+ "x",
750
+ "u",
751
+ "v",
752
+ ]
753
+ assert nx.single_source_bellman_ford_path_length(self.MXG, "s")["v"] == 9
754
+ D, P = nx.single_source_bellman_ford(self.MXG, "s", target="v")
755
+ assert D == 9
756
+ assert P == ["s", "x", "u", "v"]
757
+ P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, "s")
758
+ assert P["v"] == ["u"]
759
+ assert D["v"] == 9
760
+ P, D = nx.goldberg_radzik(self.MXG, "s")
761
+ assert P["v"] == "u"
762
+ assert D["v"] == 9
763
+ assert nx.bellman_ford_path(self.MXG4, 0, 2) == [0, 1, 2]
764
+ assert nx.bellman_ford_path_length(self.MXG4, 0, 2) == 4
765
+ assert nx.single_source_bellman_ford_path(self.MXG4, 0)[2] == [0, 1, 2]
766
+ assert nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2] == 4
767
+ D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
768
+ assert D == 4
769
+ assert P == [0, 1, 2]
770
+ P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0)
771
+ assert P[2] == [1]
772
+ assert D[2] == 4
773
+ P, D = nx.goldberg_radzik(self.MXG4, 0)
774
+ assert P[2] == 1
775
+ assert D[2] == 4
776
+
777
+ def test_others(self):
778
+ assert nx.bellman_ford_path(self.XG, "s", "v") == ["s", "x", "u", "v"]
779
+ assert nx.bellman_ford_path_length(self.XG, "s", "v") == 9
780
+ assert nx.single_source_bellman_ford_path(self.XG, "s")["v"] == [
781
+ "s",
782
+ "x",
783
+ "u",
784
+ "v",
785
+ ]
786
+ assert nx.single_source_bellman_ford_path_length(self.XG, "s")["v"] == 9
787
+ D, P = nx.single_source_bellman_ford(self.XG, "s", target="v")
788
+ assert D == 9
789
+ assert P == ["s", "x", "u", "v"]
790
+ (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, "s")
791
+ assert P["v"] == ["u"]
792
+ assert D["v"] == 9
793
+ (P, D) = nx.goldberg_radzik(self.XG, "s")
794
+ assert P["v"] == "u"
795
+ assert D["v"] == 9
796
+
797
+ def test_path_graph(self):
798
+ G = nx.path_graph(4)
799
+ assert nx.single_source_bellman_ford_path(G, 0) == {
800
+ 0: [0],
801
+ 1: [0, 1],
802
+ 2: [0, 1, 2],
803
+ 3: [0, 1, 2, 3],
804
+ }
805
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {
806
+ 0: 0,
807
+ 1: 1,
808
+ 2: 2,
809
+ 3: 3,
810
+ }
811
+ assert nx.single_source_bellman_ford(G, 0) == (
812
+ {0: 0, 1: 1, 2: 2, 3: 3},
813
+ {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]},
814
+ )
815
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
816
+ {0: [], 1: [0], 2: [1], 3: [2]},
817
+ {0: 0, 1: 1, 2: 2, 3: 3},
818
+ )
819
+ assert nx.goldberg_radzik(G, 0) == (
820
+ {0: None, 1: 0, 2: 1, 3: 2},
821
+ {0: 0, 1: 1, 2: 2, 3: 3},
822
+ )
823
+ assert nx.single_source_bellman_ford_path(G, 3) == {
824
+ 0: [3, 2, 1, 0],
825
+ 1: [3, 2, 1],
826
+ 2: [3, 2],
827
+ 3: [3],
828
+ }
829
+ assert nx.single_source_bellman_ford_path_length(G, 3) == {
830
+ 0: 3,
831
+ 1: 2,
832
+ 2: 1,
833
+ 3: 0,
834
+ }
835
+ assert nx.single_source_bellman_ford(G, 3) == (
836
+ {0: 3, 1: 2, 2: 1, 3: 0},
837
+ {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]},
838
+ )
839
+ assert nx.bellman_ford_predecessor_and_distance(G, 3) == (
840
+ {0: [1], 1: [2], 2: [3], 3: []},
841
+ {0: 3, 1: 2, 2: 1, 3: 0},
842
+ )
843
+ assert nx.goldberg_radzik(G, 3) == (
844
+ {0: 1, 1: 2, 2: 3, 3: None},
845
+ {0: 3, 1: 2, 2: 1, 3: 0},
846
+ )
847
+
848
+ def test_4_cycle(self):
849
+ # 4-cycle
850
+ G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)])
851
+ dist, path = nx.single_source_bellman_ford(G, 0)
852
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
853
+ assert path[0] == [0]
854
+ assert path[1] == [0, 1]
855
+ assert path[2] in [[0, 1, 2], [0, 3, 2]]
856
+ assert path[3] == [0, 3]
857
+
858
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0)
859
+ assert pred[0] == []
860
+ assert pred[1] == [0]
861
+ assert pred[2] in [[1, 3], [3, 1]]
862
+ assert pred[3] == [0]
863
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
864
+
865
+ pred, dist = nx.goldberg_radzik(G, 0)
866
+ assert pred[0] is None
867
+ assert pred[1] == 0
868
+ assert pred[2] in [1, 3]
869
+ assert pred[3] == 0
870
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
871
+
872
+ def test_negative_weight_bf_path(self):
873
+ G = nx.DiGraph()
874
+ G.add_nodes_from("abcd")
875
+ G.add_edge("a", "d", weight=0)
876
+ G.add_edge("a", "b", weight=1)
877
+ G.add_edge("b", "c", weight=-3)
878
+ G.add_edge("c", "d", weight=1)
879
+
880
+ assert nx.bellman_ford_path(G, "a", "d") == ["a", "b", "c", "d"]
881
+ assert nx.bellman_ford_path_length(G, "a", "d") == -1
882
+
883
+ def test_zero_cycle_smoke(self):
884
+ D = nx.DiGraph()
885
+ D.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 1, -2)])
886
+
887
+ nx.bellman_ford_path(D, 1, 3)
888
+ nx.dijkstra_path(D, 1, 3)
889
+ nx.bidirectional_dijkstra(D, 1, 3)
890
+ # FIXME nx.goldberg_radzik(D, 1)
891
+
892
+
893
+ class TestJohnsonAlgorithm(WeightedTestBase):
894
+ def test_single_node_graph(self):
895
+ G = nx.DiGraph()
896
+ G.add_node(0)
897
+ assert nx.johnson(G) == {0: {0: [0]}}
898
+
899
+ def test_negative_cycle(self):
900
+ G = nx.DiGraph()
901
+ G.add_weighted_edges_from(
902
+ [
903
+ ("0", "3", 3),
904
+ ("0", "1", -5),
905
+ ("1", "0", -5),
906
+ ("0", "2", 2),
907
+ ("1", "2", 4),
908
+ ("2", "3", 1),
909
+ ]
910
+ )
911
+ pytest.raises(nx.NetworkXUnbounded, nx.johnson, G)
912
+ G = nx.Graph()
913
+ G.add_weighted_edges_from(
914
+ [
915
+ ("0", "3", 3),
916
+ ("0", "1", -5),
917
+ ("1", "0", -5),
918
+ ("0", "2", 2),
919
+ ("1", "2", 4),
920
+ ("2", "3", 1),
921
+ ]
922
+ )
923
+ pytest.raises(nx.NetworkXUnbounded, nx.johnson, G)
924
+
925
+ def test_negative_weights(self):
926
+ G = nx.DiGraph()
927
+ G.add_weighted_edges_from(
928
+ [("0", "3", 3), ("0", "1", -5), ("0", "2", 2), ("1", "2", 4), ("2", "3", 1)]
929
+ )
930
+ paths = nx.johnson(G)
931
+ assert paths == {
932
+ "1": {"1": ["1"], "3": ["1", "2", "3"], "2": ["1", "2"]},
933
+ "0": {
934
+ "1": ["0", "1"],
935
+ "0": ["0"],
936
+ "3": ["0", "1", "2", "3"],
937
+ "2": ["0", "1", "2"],
938
+ },
939
+ "3": {"3": ["3"]},
940
+ "2": {"3": ["2", "3"], "2": ["2"]},
941
+ }
942
+
943
+ def test_unweighted_graph(self):
944
+ G = nx.Graph()
945
+ G.add_edges_from([(1, 0), (2, 1)])
946
+ H = G.copy()
947
+ nx.set_edge_attributes(H, values=1, name="weight")
948
+ assert nx.johnson(G) == nx.johnson(H)
949
+
950
+ def test_partially_weighted_graph_with_negative_edges(self):
951
+ G = nx.DiGraph()
952
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (1, 0)])
953
+ G[1][0]["weight"] = -2
954
+ G[0][1]["weight"] = 3
955
+ G[1][2]["weight"] = -4
956
+
957
+ H = G.copy()
958
+ H[2][0]["weight"] = 1
959
+
960
+ I = G.copy()
961
+ I[2][0]["weight"] = 8
962
+
963
+ assert nx.johnson(G) == nx.johnson(H)
964
+ assert nx.johnson(G) != nx.johnson(I)
965
+
966
+ def test_graphs(self):
967
+ validate_path(self.XG, "s", "v", 9, nx.johnson(self.XG)["s"]["v"])
968
+ validate_path(self.MXG, "s", "v", 9, nx.johnson(self.MXG)["s"]["v"])
969
+ validate_path(self.XG2, 1, 3, 4, nx.johnson(self.XG2)[1][3])
970
+ validate_path(self.XG3, 0, 3, 15, nx.johnson(self.XG3)[0][3])
971
+ validate_path(self.XG4, 0, 2, 4, nx.johnson(self.XG4)[0][2])
972
+ validate_path(self.MXG4, 0, 2, 4, nx.johnson(self.MXG4)[0][2])
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/unweighted.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shortest path algorithms for unweighted graphs.
3
+ """
4
+
5
+ import warnings
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = [
10
+ "bidirectional_shortest_path",
11
+ "single_source_shortest_path",
12
+ "single_source_shortest_path_length",
13
+ "single_target_shortest_path",
14
+ "single_target_shortest_path_length",
15
+ "all_pairs_shortest_path",
16
+ "all_pairs_shortest_path_length",
17
+ "predecessor",
18
+ ]
19
+
20
+
21
+ @nx._dispatchable
22
+ def single_source_shortest_path_length(G, source, cutoff=None):
23
+ """Compute the shortest path lengths from source to all reachable nodes.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ source : node
30
+ Starting node for path
31
+
32
+ cutoff : integer, optional
33
+ Depth to stop the search. Only paths of length <= cutoff are returned.
34
+
35
+ Returns
36
+ -------
37
+ lengths : dict
38
+ Dict keyed by node to shortest path length to source.
39
+
40
+ Examples
41
+ --------
42
+ >>> G = nx.path_graph(5)
43
+ >>> length = nx.single_source_shortest_path_length(G, 0)
44
+ >>> length[4]
45
+ 4
46
+ >>> for node in length:
47
+ ... print(f"{node}: {length[node]}")
48
+ 0: 0
49
+ 1: 1
50
+ 2: 2
51
+ 3: 3
52
+ 4: 4
53
+
54
+ See Also
55
+ --------
56
+ shortest_path_length
57
+ """
58
+ if source not in G:
59
+ raise nx.NodeNotFound(f"Source {source} is not in G")
60
+ if cutoff is None:
61
+ cutoff = float("inf")
62
+ nextlevel = [source]
63
+ return dict(_single_shortest_path_length(G._adj, nextlevel, cutoff))
64
+
65
+
66
+ def _single_shortest_path_length(adj, firstlevel, cutoff):
67
+ """Yields (node, level) in a breadth first search
68
+
69
+ Shortest Path Length helper function
70
+ Parameters
71
+ ----------
72
+ adj : dict
73
+ Adjacency dict or view
74
+ firstlevel : list
75
+ starting nodes, e.g. [source] or [target]
76
+ cutoff : int or float
77
+ level at which we stop the process
78
+ """
79
+ seen = set(firstlevel)
80
+ nextlevel = firstlevel
81
+ level = 0
82
+ n = len(adj)
83
+ for v in nextlevel:
84
+ yield (v, level)
85
+ while nextlevel and cutoff > level:
86
+ level += 1
87
+ thislevel = nextlevel
88
+ nextlevel = []
89
+ for v in thislevel:
90
+ for w in adj[v]:
91
+ if w not in seen:
92
+ seen.add(w)
93
+ nextlevel.append(w)
94
+ yield (w, level)
95
+ if len(seen) == n:
96
+ return
97
+
98
+
99
+ @nx._dispatchable
100
+ def single_target_shortest_path_length(G, target, cutoff=None):
101
+ """Compute the shortest path lengths to target from all reachable nodes.
102
+
103
+ Parameters
104
+ ----------
105
+ G : NetworkX graph
106
+
107
+ target : node
108
+ Target node for path
109
+
110
+ cutoff : integer, optional
111
+ Depth to stop the search. Only paths of length <= cutoff are returned.
112
+
113
+ Returns
114
+ -------
115
+ lengths : iterator
116
+ (source, shortest path length) iterator
117
+
118
+ Examples
119
+ --------
120
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
121
+ >>> length = dict(nx.single_target_shortest_path_length(G, 4))
122
+ >>> length[0]
123
+ 4
124
+ >>> for node in range(5):
125
+ ... print(f"{node}: {length[node]}")
126
+ 0: 4
127
+ 1: 3
128
+ 2: 2
129
+ 3: 1
130
+ 4: 0
131
+
132
+ See Also
133
+ --------
134
+ single_source_shortest_path_length, shortest_path_length
135
+ """
136
+ if target not in G:
137
+ raise nx.NodeNotFound(f"Target {target} is not in G")
138
+
139
+ warnings.warn(
140
+ (
141
+ "\n\nsingle_target_shortest_path_length will return a dict instead of"
142
+ "\nan iterator in version 3.5"
143
+ ),
144
+ FutureWarning,
145
+ stacklevel=3,
146
+ )
147
+
148
+ if cutoff is None:
149
+ cutoff = float("inf")
150
+ # handle either directed or undirected
151
+ adj = G._pred if G.is_directed() else G._adj
152
+ nextlevel = [target]
153
+ # for version 3.3 we will return a dict like this:
154
+ # return dict(_single_shortest_path_length(adj, nextlevel, cutoff))
155
+ return _single_shortest_path_length(adj, nextlevel, cutoff)
156
+
157
+
158
+ @nx._dispatchable
159
+ def all_pairs_shortest_path_length(G, cutoff=None):
160
+ """Computes the shortest path lengths between all nodes in `G`.
161
+
162
+ Parameters
163
+ ----------
164
+ G : NetworkX graph
165
+
166
+ cutoff : integer, optional
167
+ Depth at which to stop the search. Only paths of length at most
168
+ `cutoff` are returned.
169
+
170
+ Returns
171
+ -------
172
+ lengths : iterator
173
+ (source, dictionary) iterator with dictionary keyed by target and
174
+ shortest path length as the key value.
175
+
176
+ Notes
177
+ -----
178
+ The iterator returned only has reachable node pairs.
179
+
180
+ Examples
181
+ --------
182
+ >>> G = nx.path_graph(5)
183
+ >>> length = dict(nx.all_pairs_shortest_path_length(G))
184
+ >>> for node in [0, 1, 2, 3, 4]:
185
+ ... print(f"1 - {node}: {length[1][node]}")
186
+ 1 - 0: 1
187
+ 1 - 1: 0
188
+ 1 - 2: 1
189
+ 1 - 3: 2
190
+ 1 - 4: 3
191
+ >>> length[3][2]
192
+ 1
193
+ >>> length[2][2]
194
+ 0
195
+
196
+ """
197
+ length = single_source_shortest_path_length
198
+ # TODO This can be trivially parallelized.
199
+ for n in G:
200
+ yield (n, length(G, n, cutoff=cutoff))
201
+
202
+
203
+ @nx._dispatchable
204
+ def bidirectional_shortest_path(G, source, target):
205
+ """Returns a list of nodes in a shortest path between source and target.
206
+
207
+ Parameters
208
+ ----------
209
+ G : NetworkX graph
210
+
211
+ source : node label
212
+ starting node for path
213
+
214
+ target : node label
215
+ ending node for path
216
+
217
+ Returns
218
+ -------
219
+ path: list
220
+ List of nodes in a path from source to target.
221
+
222
+ Raises
223
+ ------
224
+ NetworkXNoPath
225
+ If no path exists between source and target.
226
+
227
+ Examples
228
+ --------
229
+ >>> G = nx.Graph()
230
+ >>> nx.add_path(G, [0, 1, 2, 3, 0, 4, 5, 6, 7, 4])
231
+ >>> nx.bidirectional_shortest_path(G, 2, 6)
232
+ [2, 1, 0, 4, 5, 6]
233
+
234
+ See Also
235
+ --------
236
+ shortest_path
237
+
238
+ Notes
239
+ -----
240
+ This algorithm is used by shortest_path(G, source, target).
241
+ """
242
+
243
+ if source not in G:
244
+ raise nx.NodeNotFound(f"Source {source} is not in G")
245
+
246
+ if target not in G:
247
+ raise nx.NodeNotFound(f"Target {target} is not in G")
248
+
249
+ # call helper to do the real work
250
+ results = _bidirectional_pred_succ(G, source, target)
251
+ pred, succ, w = results
252
+
253
+ # build path from pred+w+succ
254
+ path = []
255
+ # from source to w
256
+ while w is not None:
257
+ path.append(w)
258
+ w = pred[w]
259
+ path.reverse()
260
+ # from w to target
261
+ w = succ[path[-1]]
262
+ while w is not None:
263
+ path.append(w)
264
+ w = succ[w]
265
+
266
+ return path
267
+
268
+
269
+ def _bidirectional_pred_succ(G, source, target):
270
+ """Bidirectional shortest path helper.
271
+
272
+ Returns (pred, succ, w) where
273
+ pred is a dictionary of predecessors from w to the source, and
274
+ succ is a dictionary of successors from w to the target.
275
+ """
276
+ # does BFS from both source and target and meets in the middle
277
+ if target == source:
278
+ return ({target: None}, {source: None}, source)
279
+
280
+ # handle either directed or undirected
281
+ if G.is_directed():
282
+ Gpred = G.pred
283
+ Gsucc = G.succ
284
+ else:
285
+ Gpred = G.adj
286
+ Gsucc = G.adj
287
+
288
+ # predecessor and successors in search
289
+ pred = {source: None}
290
+ succ = {target: None}
291
+
292
+ # initialize fringes, start with forward
293
+ forward_fringe = [source]
294
+ reverse_fringe = [target]
295
+
296
+ while forward_fringe and reverse_fringe:
297
+ if len(forward_fringe) <= len(reverse_fringe):
298
+ this_level = forward_fringe
299
+ forward_fringe = []
300
+ for v in this_level:
301
+ for w in Gsucc[v]:
302
+ if w not in pred:
303
+ forward_fringe.append(w)
304
+ pred[w] = v
305
+ if w in succ: # path found
306
+ return pred, succ, w
307
+ else:
308
+ this_level = reverse_fringe
309
+ reverse_fringe = []
310
+ for v in this_level:
311
+ for w in Gpred[v]:
312
+ if w not in succ:
313
+ succ[w] = v
314
+ reverse_fringe.append(w)
315
+ if w in pred: # found path
316
+ return pred, succ, w
317
+
318
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
319
+
320
+
321
+ @nx._dispatchable
322
+ def single_source_shortest_path(G, source, cutoff=None):
323
+ """Compute shortest path between source
324
+ and all other nodes reachable from source.
325
+
326
+ Parameters
327
+ ----------
328
+ G : NetworkX graph
329
+
330
+ source : node label
331
+ Starting node for path
332
+
333
+ cutoff : integer, optional
334
+ Depth to stop the search. Only paths of length <= cutoff are returned.
335
+
336
+ Returns
337
+ -------
338
+ paths : dictionary
339
+ Dictionary, keyed by target, of shortest paths.
340
+
341
+ Examples
342
+ --------
343
+ >>> G = nx.path_graph(5)
344
+ >>> path = nx.single_source_shortest_path(G, 0)
345
+ >>> path[4]
346
+ [0, 1, 2, 3, 4]
347
+
348
+ Notes
349
+ -----
350
+ The shortest path is not necessarily unique. So there can be multiple
351
+ paths between the source and each target node, all of which have the
352
+ same 'shortest' length. For each target node, this function returns
353
+ only one of those paths.
354
+
355
+ See Also
356
+ --------
357
+ shortest_path
358
+ """
359
+ if source not in G:
360
+ raise nx.NodeNotFound(f"Source {source} not in G")
361
+
362
+ def join(p1, p2):
363
+ return p1 + p2
364
+
365
+ if cutoff is None:
366
+ cutoff = float("inf")
367
+ nextlevel = {source: 1} # list of nodes to check at next level
368
+ paths = {source: [source]} # paths dictionary (paths to key from source)
369
+ return dict(_single_shortest_path(G.adj, nextlevel, paths, cutoff, join))
370
+
371
+
372
+ def _single_shortest_path(adj, firstlevel, paths, cutoff, join):
373
+ """Returns shortest paths
374
+
375
+ Shortest Path helper function
376
+ Parameters
377
+ ----------
378
+ adj : dict
379
+ Adjacency dict or view
380
+ firstlevel : dict
381
+ starting nodes, e.g. {source: 1} or {target: 1}
382
+ paths : dict
383
+ paths for starting nodes, e.g. {source: [source]}
384
+ cutoff : int or float
385
+ level at which we stop the process
386
+ join : function
387
+ function to construct a path from two partial paths. Requires two
388
+ list inputs `p1` and `p2`, and returns a list. Usually returns
389
+ `p1 + p2` (forward from source) or `p2 + p1` (backward from target)
390
+ """
391
+ level = 0 # the current level
392
+ nextlevel = firstlevel
393
+ while nextlevel and cutoff > level:
394
+ thislevel = nextlevel
395
+ nextlevel = {}
396
+ for v in thislevel:
397
+ for w in adj[v]:
398
+ if w not in paths:
399
+ paths[w] = join(paths[v], [w])
400
+ nextlevel[w] = 1
401
+ level += 1
402
+ return paths
403
+
404
+
405
+ @nx._dispatchable
406
+ def single_target_shortest_path(G, target, cutoff=None):
407
+ """Compute shortest path to target from all nodes that reach target.
408
+
409
+ Parameters
410
+ ----------
411
+ G : NetworkX graph
412
+
413
+ target : node label
414
+ Target node for path
415
+
416
+ cutoff : integer, optional
417
+ Depth to stop the search. Only paths of length <= cutoff are returned.
418
+
419
+ Returns
420
+ -------
421
+ paths : dictionary
422
+ Dictionary, keyed by target, of shortest paths.
423
+
424
+ Examples
425
+ --------
426
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
427
+ >>> path = nx.single_target_shortest_path(G, 4)
428
+ >>> path[0]
429
+ [0, 1, 2, 3, 4]
430
+
431
+ Notes
432
+ -----
433
+ The shortest path is not necessarily unique. So there can be multiple
434
+ paths between the source and each target node, all of which have the
435
+ same 'shortest' length. For each target node, this function returns
436
+ only one of those paths.
437
+
438
+ See Also
439
+ --------
440
+ shortest_path, single_source_shortest_path
441
+ """
442
+ if target not in G:
443
+ raise nx.NodeNotFound(f"Target {target} not in G")
444
+
445
+ def join(p1, p2):
446
+ return p2 + p1
447
+
448
+ # handle undirected graphs
449
+ adj = G.pred if G.is_directed() else G.adj
450
+ if cutoff is None:
451
+ cutoff = float("inf")
452
+ nextlevel = {target: 1} # list of nodes to check at next level
453
+ paths = {target: [target]} # paths dictionary (paths to key from source)
454
+ return dict(_single_shortest_path(adj, nextlevel, paths, cutoff, join))
455
+
456
+
457
+ @nx._dispatchable
458
+ def all_pairs_shortest_path(G, cutoff=None):
459
+ """Compute shortest paths between all nodes.
460
+
461
+ Parameters
462
+ ----------
463
+ G : NetworkX graph
464
+
465
+ cutoff : integer, optional
466
+ Depth at which to stop the search. Only paths of length at most
467
+ `cutoff` are returned.
468
+
469
+ Returns
470
+ -------
471
+ paths : iterator
472
+ Dictionary, keyed by source and target, of shortest paths.
473
+
474
+ Examples
475
+ --------
476
+ >>> G = nx.path_graph(5)
477
+ >>> path = dict(nx.all_pairs_shortest_path(G))
478
+ >>> print(path[0][4])
479
+ [0, 1, 2, 3, 4]
480
+
481
+ Notes
482
+ -----
483
+ There may be multiple shortest paths with the same length between
484
+ two nodes. For each pair, this function returns only one of those paths.
485
+
486
+ See Also
487
+ --------
488
+ floyd_warshall
489
+ all_pairs_all_shortest_paths
490
+
491
+ """
492
+ # TODO This can be trivially parallelized.
493
+ for n in G:
494
+ yield (n, single_source_shortest_path(G, n, cutoff=cutoff))
495
+
496
+
497
+ @nx._dispatchable
498
+ def predecessor(G, source, target=None, cutoff=None, return_seen=None):
499
+ """Returns dict of predecessors for the path from source to all nodes in G.
500
+
501
+ Parameters
502
+ ----------
503
+ G : NetworkX graph
504
+
505
+ source : node label
506
+ Starting node for path
507
+
508
+ target : node label, optional
509
+ Ending node for path. If provided only predecessors between
510
+ source and target are returned
511
+
512
+ cutoff : integer, optional
513
+ Depth to stop the search. Only paths of length <= cutoff are returned.
514
+
515
+ return_seen : bool, optional (default=None)
516
+ Whether to return a dictionary, keyed by node, of the level (number of
517
+ hops) to reach the node (as seen during breadth-first-search).
518
+
519
+ Returns
520
+ -------
521
+ pred : dictionary
522
+ Dictionary, keyed by node, of predecessors in the shortest path.
523
+
524
+
525
+ (pred, seen): tuple of dictionaries
526
+ If `return_seen` argument is set to `True`, then a tuple of dictionaries
527
+ is returned. The first element is the dictionary, keyed by node, of
528
+ predecessors in the shortest path. The second element is the dictionary,
529
+ keyed by node, of the level (number of hops) to reach the node (as seen
530
+ during breadth-first-search).
531
+
532
+ Examples
533
+ --------
534
+ >>> G = nx.path_graph(4)
535
+ >>> list(G)
536
+ [0, 1, 2, 3]
537
+ >>> nx.predecessor(G, 0)
538
+ {0: [], 1: [0], 2: [1], 3: [2]}
539
+ >>> nx.predecessor(G, 0, return_seen=True)
540
+ ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})
541
+
542
+
543
+ """
544
+ if source not in G:
545
+ raise nx.NodeNotFound(f"Source {source} not in G")
546
+
547
+ level = 0 # the current level
548
+ nextlevel = [source] # list of nodes to check at next level
549
+ seen = {source: level} # level (number of hops) when seen in BFS
550
+ pred = {source: []} # predecessor dictionary
551
+ while nextlevel:
552
+ level = level + 1
553
+ thislevel = nextlevel
554
+ nextlevel = []
555
+ for v in thislevel:
556
+ for w in G[v]:
557
+ if w not in seen:
558
+ pred[w] = [v]
559
+ seen[w] = level
560
+ nextlevel.append(w)
561
+ elif seen[w] == level: # add v to predecessor list if it
562
+ pred[w].append(v) # is at the correct level
563
+ if cutoff and cutoff <= level:
564
+ break
565
+
566
+ if target is not None:
567
+ if return_seen:
568
+ if target not in pred:
569
+ return ([], -1) # No predecessor
570
+ return (pred[target], seen[target])
571
+ else:
572
+ if target not in pred:
573
+ return [] # No predecessor
574
+ return pred[target]
575
+ else:
576
+ if return_seen:
577
+ return (pred, seen)
578
+ else:
579
+ return pred
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/shortest_paths/weighted.py ADDED
@@ -0,0 +1,2520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shortest path algorithms for weighted graphs.
3
+ """
4
+
5
+ from collections import deque
6
+ from heapq import heappop, heappush
7
+ from itertools import count
8
+
9
+ import networkx as nx
10
+ from networkx.algorithms.shortest_paths.generic import _build_paths_from_predecessors
11
+
12
+ __all__ = [
13
+ "dijkstra_path",
14
+ "dijkstra_path_length",
15
+ "bidirectional_dijkstra",
16
+ "single_source_dijkstra",
17
+ "single_source_dijkstra_path",
18
+ "single_source_dijkstra_path_length",
19
+ "multi_source_dijkstra",
20
+ "multi_source_dijkstra_path",
21
+ "multi_source_dijkstra_path_length",
22
+ "all_pairs_dijkstra",
23
+ "all_pairs_dijkstra_path",
24
+ "all_pairs_dijkstra_path_length",
25
+ "dijkstra_predecessor_and_distance",
26
+ "bellman_ford_path",
27
+ "bellman_ford_path_length",
28
+ "single_source_bellman_ford",
29
+ "single_source_bellman_ford_path",
30
+ "single_source_bellman_ford_path_length",
31
+ "all_pairs_bellman_ford_path",
32
+ "all_pairs_bellman_ford_path_length",
33
+ "bellman_ford_predecessor_and_distance",
34
+ "negative_edge_cycle",
35
+ "find_negative_cycle",
36
+ "goldberg_radzik",
37
+ "johnson",
38
+ ]
39
+
40
+
41
+ def _weight_function(G, weight):
42
+ """Returns a function that returns the weight of an edge.
43
+
44
+ The returned function is specifically suitable for input to
45
+ functions :func:`_dijkstra` and :func:`_bellman_ford_relaxation`.
46
+
47
+ Parameters
48
+ ----------
49
+ G : NetworkX graph.
50
+
51
+ weight : string or function
52
+ If it is callable, `weight` itself is returned. If it is a string,
53
+ it is assumed to be the name of the edge attribute that represents
54
+ the weight of an edge. In that case, a function is returned that
55
+ gets the edge weight according to the specified edge attribute.
56
+
57
+ Returns
58
+ -------
59
+ function
60
+ This function returns a callable that accepts exactly three inputs:
61
+ a node, an node adjacent to the first one, and the edge attribute
62
+ dictionary for the eedge joining those nodes. That function returns
63
+ a number representing the weight of an edge.
64
+
65
+ If `G` is a multigraph, and `weight` is not callable, the
66
+ minimum edge weight over all parallel edges is returned. If any edge
67
+ does not have an attribute with key `weight`, it is assumed to
68
+ have weight one.
69
+
70
+ """
71
+ if callable(weight):
72
+ return weight
73
+ # If the weight keyword argument is not callable, we assume it is a
74
+ # string representing the edge attribute containing the weight of
75
+ # the edge.
76
+ if G.is_multigraph():
77
+ return lambda u, v, d: min(attr.get(weight, 1) for attr in d.values())
78
+ return lambda u, v, data: data.get(weight, 1)
79
+
80
+
81
+ @nx._dispatchable(edge_attrs="weight")
82
+ def dijkstra_path(G, source, target, weight="weight"):
83
+ """Returns the shortest weighted path from source to target in G.
84
+
85
+ Uses Dijkstra's Method to compute the shortest weighted path
86
+ between two nodes in a graph.
87
+
88
+ Parameters
89
+ ----------
90
+ G : NetworkX graph
91
+
92
+ source : node
93
+ Starting node
94
+
95
+ target : node
96
+ Ending node
97
+
98
+ weight : string or function
99
+ If this is a string, then edge weights will be accessed via the
100
+ edge attribute with this key (that is, the weight of the edge
101
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
102
+ such edge attribute exists, the weight of the edge is assumed to
103
+ be one.
104
+
105
+ If this is a function, the weight of an edge is the value
106
+ returned by the function. The function must accept exactly three
107
+ positional arguments: the two endpoints of an edge and the
108
+ dictionary of edge attributes for that edge. The function must
109
+ return a number or None to indicate a hidden edge.
110
+
111
+ Returns
112
+ -------
113
+ path : list
114
+ List of nodes in a shortest path.
115
+
116
+ Raises
117
+ ------
118
+ NodeNotFound
119
+ If `source` is not in `G`.
120
+
121
+ NetworkXNoPath
122
+ If no path exists between source and target.
123
+
124
+ Examples
125
+ --------
126
+ >>> G = nx.path_graph(5)
127
+ >>> print(nx.dijkstra_path(G, 0, 4))
128
+ [0, 1, 2, 3, 4]
129
+
130
+ Find edges of shortest path in Multigraph
131
+
132
+ >>> G = nx.MultiDiGraph()
133
+ >>> G.add_weighted_edges_from([(1, 2, 0.75), (1, 2, 0.5), (2, 3, 0.5), (1, 3, 1.5)])
134
+ >>> nodes = nx.dijkstra_path(G, 1, 3)
135
+ >>> edges = nx.utils.pairwise(nodes)
136
+ >>> list(
137
+ ... (u, v, min(G[u][v], key=lambda k: G[u][v][k].get("weight", 1)))
138
+ ... for u, v in edges
139
+ ... )
140
+ [(1, 2, 1), (2, 3, 0)]
141
+
142
+ Notes
143
+ -----
144
+ Edge weight attributes must be numerical.
145
+ Distances are calculated as sums of weighted edges traversed.
146
+
147
+ The weight function can be used to hide edges by returning None.
148
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
149
+ will find the shortest red path.
150
+
151
+ The weight function can be used to include node weights.
152
+
153
+ >>> def func(u, v, d):
154
+ ... node_u_wt = G.nodes[u].get("node_weight", 1)
155
+ ... node_v_wt = G.nodes[v].get("node_weight", 1)
156
+ ... edge_wt = d.get("weight", 1)
157
+ ... return node_u_wt / 2 + node_v_wt / 2 + edge_wt
158
+
159
+ In this example we take the average of start and end node
160
+ weights of an edge and add it to the weight of the edge.
161
+
162
+ The function :func:`single_source_dijkstra` computes both
163
+ path and length-of-path if you need both, use that.
164
+
165
+ See Also
166
+ --------
167
+ bidirectional_dijkstra
168
+ bellman_ford_path
169
+ single_source_dijkstra
170
+ """
171
+ (length, path) = single_source_dijkstra(G, source, target=target, weight=weight)
172
+ return path
173
+
174
+
175
+ @nx._dispatchable(edge_attrs="weight")
176
+ def dijkstra_path_length(G, source, target, weight="weight"):
177
+ """Returns the shortest weighted path length in G from source to target.
178
+
179
+ Uses Dijkstra's Method to compute the shortest weighted path length
180
+ between two nodes in a graph.
181
+
182
+ Parameters
183
+ ----------
184
+ G : NetworkX graph
185
+
186
+ source : node label
187
+ starting node for path
188
+
189
+ target : node label
190
+ ending node for path
191
+
192
+ weight : string or function
193
+ If this is a string, then edge weights will be accessed via the
194
+ edge attribute with this key (that is, the weight of the edge
195
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
196
+ such edge attribute exists, the weight of the edge is assumed to
197
+ be one.
198
+
199
+ If this is a function, the weight of an edge is the value
200
+ returned by the function. The function must accept exactly three
201
+ positional arguments: the two endpoints of an edge and the
202
+ dictionary of edge attributes for that edge. The function must
203
+ return a number or None to indicate a hidden edge.
204
+
205
+ Returns
206
+ -------
207
+ length : number
208
+ Shortest path length.
209
+
210
+ Raises
211
+ ------
212
+ NodeNotFound
213
+ If `source` is not in `G`.
214
+
215
+ NetworkXNoPath
216
+ If no path exists between source and target.
217
+
218
+ Examples
219
+ --------
220
+ >>> G = nx.path_graph(5)
221
+ >>> nx.dijkstra_path_length(G, 0, 4)
222
+ 4
223
+
224
+ Notes
225
+ -----
226
+ Edge weight attributes must be numerical.
227
+ Distances are calculated as sums of weighted edges traversed.
228
+
229
+ The weight function can be used to hide edges by returning None.
230
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
231
+ will find the shortest red path.
232
+
233
+ The function :func:`single_source_dijkstra` computes both
234
+ path and length-of-path if you need both, use that.
235
+
236
+ See Also
237
+ --------
238
+ bidirectional_dijkstra
239
+ bellman_ford_path_length
240
+ single_source_dijkstra
241
+
242
+ """
243
+ if source not in G:
244
+ raise nx.NodeNotFound(f"Node {source} not found in graph")
245
+ if source == target:
246
+ return 0
247
+ weight = _weight_function(G, weight)
248
+ length = _dijkstra(G, source, weight, target=target)
249
+ try:
250
+ return length[target]
251
+ except KeyError as err:
252
+ raise nx.NetworkXNoPath(f"Node {target} not reachable from {source}") from err
253
+
254
+
255
+ @nx._dispatchable(edge_attrs="weight")
256
+ def single_source_dijkstra_path(G, source, cutoff=None, weight="weight"):
257
+ """Find shortest weighted paths in G from a source node.
258
+
259
+ Compute shortest path between source and all other reachable
260
+ nodes for a weighted graph.
261
+
262
+ Parameters
263
+ ----------
264
+ G : NetworkX graph
265
+
266
+ source : node
267
+ Starting node for path.
268
+
269
+ cutoff : integer or float, optional
270
+ Length (sum of edge weights) at which the search is stopped.
271
+ If cutoff is provided, only return paths with summed weight <= cutoff.
272
+
273
+ weight : string or function
274
+ If this is a string, then edge weights will be accessed via the
275
+ edge attribute with this key (that is, the weight of the edge
276
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
277
+ such edge attribute exists, the weight of the edge is assumed to
278
+ be one.
279
+
280
+ If this is a function, the weight of an edge is the value
281
+ returned by the function. The function must accept exactly three
282
+ positional arguments: the two endpoints of an edge and the
283
+ dictionary of edge attributes for that edge. The function must
284
+ return a number or None to indicate a hidden edge.
285
+
286
+ Returns
287
+ -------
288
+ paths : dictionary
289
+ Dictionary of shortest path lengths keyed by target.
290
+
291
+ Raises
292
+ ------
293
+ NodeNotFound
294
+ If `source` is not in `G`.
295
+
296
+ Examples
297
+ --------
298
+ >>> G = nx.path_graph(5)
299
+ >>> path = nx.single_source_dijkstra_path(G, 0)
300
+ >>> path[4]
301
+ [0, 1, 2, 3, 4]
302
+
303
+ Notes
304
+ -----
305
+ Edge weight attributes must be numerical.
306
+ Distances are calculated as sums of weighted edges traversed.
307
+
308
+ The weight function can be used to hide edges by returning None.
309
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
310
+ will find the shortest red path.
311
+
312
+ See Also
313
+ --------
314
+ single_source_dijkstra, single_source_bellman_ford
315
+
316
+ """
317
+ return multi_source_dijkstra_path(G, {source}, cutoff=cutoff, weight=weight)
318
+
319
+
320
+ @nx._dispatchable(edge_attrs="weight")
321
+ def single_source_dijkstra_path_length(G, source, cutoff=None, weight="weight"):
322
+ """Find shortest weighted path lengths in G from a source node.
323
+
324
+ Compute the shortest path length between source and all other
325
+ reachable nodes for a weighted graph.
326
+
327
+ Parameters
328
+ ----------
329
+ G : NetworkX graph
330
+
331
+ source : node label
332
+ Starting node for path
333
+
334
+ cutoff : integer or float, optional
335
+ Length (sum of edge weights) at which the search is stopped.
336
+ If cutoff is provided, only return paths with summed weight <= cutoff.
337
+
338
+ weight : string or function
339
+ If this is a string, then edge weights will be accessed via the
340
+ edge attribute with this key (that is, the weight of the edge
341
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
342
+ such edge attribute exists, the weight of the edge is assumed to
343
+ be one.
344
+
345
+ If this is a function, the weight of an edge is the value
346
+ returned by the function. The function must accept exactly three
347
+ positional arguments: the two endpoints of an edge and the
348
+ dictionary of edge attributes for that edge. The function must
349
+ return a number or None to indicate a hidden edge.
350
+
351
+ Returns
352
+ -------
353
+ length : dict
354
+ Dict keyed by node to shortest path length from source.
355
+
356
+ Raises
357
+ ------
358
+ NodeNotFound
359
+ If `source` is not in `G`.
360
+
361
+ Examples
362
+ --------
363
+ >>> G = nx.path_graph(5)
364
+ >>> length = nx.single_source_dijkstra_path_length(G, 0)
365
+ >>> length[4]
366
+ 4
367
+ >>> for node in [0, 1, 2, 3, 4]:
368
+ ... print(f"{node}: {length[node]}")
369
+ 0: 0
370
+ 1: 1
371
+ 2: 2
372
+ 3: 3
373
+ 4: 4
374
+
375
+ Notes
376
+ -----
377
+ Edge weight attributes must be numerical.
378
+ Distances are calculated as sums of weighted edges traversed.
379
+
380
+ The weight function can be used to hide edges by returning None.
381
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
382
+ will find the shortest red path.
383
+
384
+ See Also
385
+ --------
386
+ single_source_dijkstra, single_source_bellman_ford_path_length
387
+
388
+ """
389
+ return multi_source_dijkstra_path_length(G, {source}, cutoff=cutoff, weight=weight)
390
+
391
+
392
+ @nx._dispatchable(edge_attrs="weight")
393
+ def single_source_dijkstra(G, source, target=None, cutoff=None, weight="weight"):
394
+ """Find shortest weighted paths and lengths from a source node.
395
+
396
+ Compute the shortest path length between source and all other
397
+ reachable nodes for a weighted graph.
398
+
399
+ Uses Dijkstra's algorithm to compute shortest paths and lengths
400
+ between a source and all other reachable nodes in a weighted graph.
401
+
402
+ Parameters
403
+ ----------
404
+ G : NetworkX graph
405
+
406
+ source : node label
407
+ Starting node for path
408
+
409
+ target : node label, optional
410
+ Ending node for path
411
+
412
+ cutoff : integer or float, optional
413
+ Length (sum of edge weights) at which the search is stopped.
414
+ If cutoff is provided, only return paths with summed weight <= cutoff.
415
+
416
+
417
+ weight : string or function
418
+ If this is a string, then edge weights will be accessed via the
419
+ edge attribute with this key (that is, the weight of the edge
420
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
421
+ such edge attribute exists, the weight of the edge is assumed to
422
+ be one.
423
+
424
+ If this is a function, the weight of an edge is the value
425
+ returned by the function. The function must accept exactly three
426
+ positional arguments: the two endpoints of an edge and the
427
+ dictionary of edge attributes for that edge. The function must
428
+ return a number or None to indicate a hidden edge.
429
+
430
+ Returns
431
+ -------
432
+ distance, path : pair of dictionaries, or numeric and list.
433
+ If target is None, paths and lengths to all nodes are computed.
434
+ The return value is a tuple of two dictionaries keyed by target nodes.
435
+ The first dictionary stores distance to each target node.
436
+ The second stores the path to each target node.
437
+ If target is not None, returns a tuple (distance, path), where
438
+ distance is the distance from source to target and path is a list
439
+ representing the path from source to target.
440
+
441
+ Raises
442
+ ------
443
+ NodeNotFound
444
+ If `source` is not in `G`.
445
+
446
+ Examples
447
+ --------
448
+ >>> G = nx.path_graph(5)
449
+ >>> length, path = nx.single_source_dijkstra(G, 0)
450
+ >>> length[4]
451
+ 4
452
+ >>> for node in [0, 1, 2, 3, 4]:
453
+ ... print(f"{node}: {length[node]}")
454
+ 0: 0
455
+ 1: 1
456
+ 2: 2
457
+ 3: 3
458
+ 4: 4
459
+ >>> path[4]
460
+ [0, 1, 2, 3, 4]
461
+ >>> length, path = nx.single_source_dijkstra(G, 0, 1)
462
+ >>> length
463
+ 1
464
+ >>> path
465
+ [0, 1]
466
+
467
+ Notes
468
+ -----
469
+ Edge weight attributes must be numerical.
470
+ Distances are calculated as sums of weighted edges traversed.
471
+
472
+ The weight function can be used to hide edges by returning None.
473
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
474
+ will find the shortest red path.
475
+
476
+ Based on the Python cookbook recipe (119466) at
477
+ https://code.activestate.com/recipes/119466/
478
+
479
+ This algorithm is not guaranteed to work if edge weights
480
+ are negative or are floating point numbers
481
+ (overflows and roundoff errors can cause problems).
482
+
483
+ See Also
484
+ --------
485
+ single_source_dijkstra_path
486
+ single_source_dijkstra_path_length
487
+ single_source_bellman_ford
488
+ """
489
+ return multi_source_dijkstra(
490
+ G, {source}, cutoff=cutoff, target=target, weight=weight
491
+ )
492
+
493
+
494
+ @nx._dispatchable(edge_attrs="weight")
495
+ def multi_source_dijkstra_path(G, sources, cutoff=None, weight="weight"):
496
+ """Find shortest weighted paths in G from a given set of source
497
+ nodes.
498
+
499
+ Compute shortest path between any of the source nodes and all other
500
+ reachable nodes for a weighted graph.
501
+
502
+ Parameters
503
+ ----------
504
+ G : NetworkX graph
505
+
506
+ sources : non-empty set of nodes
507
+ Starting nodes for paths. If this is just a set containing a
508
+ single node, then all paths computed by this function will start
509
+ from that node. If there are two or more nodes in the set, the
510
+ computed paths may begin from any one of the start nodes.
511
+
512
+ cutoff : integer or float, optional
513
+ Length (sum of edge weights) at which the search is stopped.
514
+ If cutoff is provided, only return paths with summed weight <= cutoff.
515
+
516
+ weight : string or function
517
+ If this is a string, then edge weights will be accessed via the
518
+ edge attribute with this key (that is, the weight of the edge
519
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
520
+ such edge attribute exists, the weight of the edge is assumed to
521
+ be one.
522
+
523
+ If this is a function, the weight of an edge is the value
524
+ returned by the function. The function must accept exactly three
525
+ positional arguments: the two endpoints of an edge and the
526
+ dictionary of edge attributes for that edge. The function must
527
+ return a number or None to indicate a hidden edge.
528
+
529
+ Returns
530
+ -------
531
+ paths : dictionary
532
+ Dictionary of shortest paths keyed by target.
533
+
534
+ Examples
535
+ --------
536
+ >>> G = nx.path_graph(5)
537
+ >>> path = nx.multi_source_dijkstra_path(G, {0, 4})
538
+ >>> path[1]
539
+ [0, 1]
540
+ >>> path[3]
541
+ [4, 3]
542
+
543
+ Notes
544
+ -----
545
+ Edge weight attributes must be numerical.
546
+ Distances are calculated as sums of weighted edges traversed.
547
+
548
+ The weight function can be used to hide edges by returning None.
549
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
550
+ will find the shortest red path.
551
+
552
+ Raises
553
+ ------
554
+ ValueError
555
+ If `sources` is empty.
556
+ NodeNotFound
557
+ If any of `sources` is not in `G`.
558
+
559
+ See Also
560
+ --------
561
+ multi_source_dijkstra, multi_source_bellman_ford
562
+
563
+ """
564
+ length, path = multi_source_dijkstra(G, sources, cutoff=cutoff, weight=weight)
565
+ return path
566
+
567
+
568
+ @nx._dispatchable(edge_attrs="weight")
569
+ def multi_source_dijkstra_path_length(G, sources, cutoff=None, weight="weight"):
570
+ """Find shortest weighted path lengths in G from a given set of
571
+ source nodes.
572
+
573
+ Compute the shortest path length between any of the source nodes and
574
+ all other reachable nodes for a weighted graph.
575
+
576
+ Parameters
577
+ ----------
578
+ G : NetworkX graph
579
+
580
+ sources : non-empty set of nodes
581
+ Starting nodes for paths. If this is just a set containing a
582
+ single node, then all paths computed by this function will start
583
+ from that node. If there are two or more nodes in the set, the
584
+ computed paths may begin from any one of the start nodes.
585
+
586
+ cutoff : integer or float, optional
587
+ Length (sum of edge weights) at which the search is stopped.
588
+ If cutoff is provided, only return paths with summed weight <= cutoff.
589
+
590
+ weight : string or function
591
+ If this is a string, then edge weights will be accessed via the
592
+ edge attribute with this key (that is, the weight of the edge
593
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
594
+ such edge attribute exists, the weight of the edge is assumed to
595
+ be one.
596
+
597
+ If this is a function, the weight of an edge is the value
598
+ returned by the function. The function must accept exactly three
599
+ positional arguments: the two endpoints of an edge and the
600
+ dictionary of edge attributes for that edge. The function must
601
+ return a number or None to indicate a hidden edge.
602
+
603
+ Returns
604
+ -------
605
+ length : dict
606
+ Dict keyed by node to shortest path length to nearest source.
607
+
608
+ Examples
609
+ --------
610
+ >>> G = nx.path_graph(5)
611
+ >>> length = nx.multi_source_dijkstra_path_length(G, {0, 4})
612
+ >>> for node in [0, 1, 2, 3, 4]:
613
+ ... print(f"{node}: {length[node]}")
614
+ 0: 0
615
+ 1: 1
616
+ 2: 2
617
+ 3: 1
618
+ 4: 0
619
+
620
+ Notes
621
+ -----
622
+ Edge weight attributes must be numerical.
623
+ Distances are calculated as sums of weighted edges traversed.
624
+
625
+ The weight function can be used to hide edges by returning None.
626
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
627
+ will find the shortest red path.
628
+
629
+ Raises
630
+ ------
631
+ ValueError
632
+ If `sources` is empty.
633
+ NodeNotFound
634
+ If any of `sources` is not in `G`.
635
+
636
+ See Also
637
+ --------
638
+ multi_source_dijkstra
639
+
640
+ """
641
+ if not sources:
642
+ raise ValueError("sources must not be empty")
643
+ for s in sources:
644
+ if s not in G:
645
+ raise nx.NodeNotFound(f"Node {s} not found in graph")
646
+ weight = _weight_function(G, weight)
647
+ return _dijkstra_multisource(G, sources, weight, cutoff=cutoff)
648
+
649
+
650
+ @nx._dispatchable(edge_attrs="weight")
651
+ def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight="weight"):
652
+ """Find shortest weighted paths and lengths from a given set of
653
+ source nodes.
654
+
655
+ Uses Dijkstra's algorithm to compute the shortest paths and lengths
656
+ between one of the source nodes and the given `target`, or all other
657
+ reachable nodes if not specified, for a weighted graph.
658
+
659
+ Parameters
660
+ ----------
661
+ G : NetworkX graph
662
+
663
+ sources : non-empty set of nodes
664
+ Starting nodes for paths. If this is just a set containing a
665
+ single node, then all paths computed by this function will start
666
+ from that node. If there are two or more nodes in the set, the
667
+ computed paths may begin from any one of the start nodes.
668
+
669
+ target : node label, optional
670
+ Ending node for path
671
+
672
+ cutoff : integer or float, optional
673
+ Length (sum of edge weights) at which the search is stopped.
674
+ If cutoff is provided, only return paths with summed weight <= cutoff.
675
+
676
+ weight : string or function
677
+ If this is a string, then edge weights will be accessed via the
678
+ edge attribute with this key (that is, the weight of the edge
679
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
680
+ such edge attribute exists, the weight of the edge is assumed to
681
+ be one.
682
+
683
+ If this is a function, the weight of an edge is the value
684
+ returned by the function. The function must accept exactly three
685
+ positional arguments: the two endpoints of an edge and the
686
+ dictionary of edge attributes for that edge. The function must
687
+ return a number or None to indicate a hidden edge.
688
+
689
+ Returns
690
+ -------
691
+ distance, path : pair of dictionaries, or numeric and list
692
+ If target is None, returns a tuple of two dictionaries keyed by node.
693
+ The first dictionary stores distance from one of the source nodes.
694
+ The second stores the path from one of the sources to that node.
695
+ If target is not None, returns a tuple of (distance, path) where
696
+ distance is the distance from source to target and path is a list
697
+ representing the path from source to target.
698
+
699
+ Examples
700
+ --------
701
+ >>> G = nx.path_graph(5)
702
+ >>> length, path = nx.multi_source_dijkstra(G, {0, 4})
703
+ >>> for node in [0, 1, 2, 3, 4]:
704
+ ... print(f"{node}: {length[node]}")
705
+ 0: 0
706
+ 1: 1
707
+ 2: 2
708
+ 3: 1
709
+ 4: 0
710
+ >>> path[1]
711
+ [0, 1]
712
+ >>> path[3]
713
+ [4, 3]
714
+
715
+ >>> length, path = nx.multi_source_dijkstra(G, {0, 4}, 1)
716
+ >>> length
717
+ 1
718
+ >>> path
719
+ [0, 1]
720
+
721
+ Notes
722
+ -----
723
+ Edge weight attributes must be numerical.
724
+ Distances are calculated as sums of weighted edges traversed.
725
+
726
+ The weight function can be used to hide edges by returning None.
727
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
728
+ will find the shortest red path.
729
+
730
+ Based on the Python cookbook recipe (119466) at
731
+ https://code.activestate.com/recipes/119466/
732
+
733
+ This algorithm is not guaranteed to work if edge weights
734
+ are negative or are floating point numbers
735
+ (overflows and roundoff errors can cause problems).
736
+
737
+ Raises
738
+ ------
739
+ ValueError
740
+ If `sources` is empty.
741
+ NodeNotFound
742
+ If any of `sources` is not in `G`.
743
+
744
+ See Also
745
+ --------
746
+ multi_source_dijkstra_path
747
+ multi_source_dijkstra_path_length
748
+
749
+ """
750
+ if not sources:
751
+ raise ValueError("sources must not be empty")
752
+ for s in sources:
753
+ if s not in G:
754
+ raise nx.NodeNotFound(f"Node {s} not found in graph")
755
+ if target in sources:
756
+ return (0, [target])
757
+ weight = _weight_function(G, weight)
758
+ paths = {source: [source] for source in sources} # dictionary of paths
759
+ dist = _dijkstra_multisource(
760
+ G, sources, weight, paths=paths, cutoff=cutoff, target=target
761
+ )
762
+ if target is None:
763
+ return (dist, paths)
764
+ try:
765
+ return (dist[target], paths[target])
766
+ except KeyError as err:
767
+ raise nx.NetworkXNoPath(f"No path to {target}.") from err
768
+
769
+
770
+ def _dijkstra(G, source, weight, pred=None, paths=None, cutoff=None, target=None):
771
+ """Uses Dijkstra's algorithm to find shortest weighted paths from a
772
+ single source.
773
+
774
+ This is a convenience function for :func:`_dijkstra_multisource`
775
+ with all the arguments the same, except the keyword argument
776
+ `sources` set to ``[source]``.
777
+
778
+ """
779
+ return _dijkstra_multisource(
780
+ G, [source], weight, pred=pred, paths=paths, cutoff=cutoff, target=target
781
+ )
782
+
783
+
784
+ def _dijkstra_multisource(
785
+ G, sources, weight, pred=None, paths=None, cutoff=None, target=None
786
+ ):
787
+ """Uses Dijkstra's algorithm to find shortest weighted paths
788
+
789
+ Parameters
790
+ ----------
791
+ G : NetworkX graph
792
+
793
+ sources : non-empty iterable of nodes
794
+ Starting nodes for paths. If this is just an iterable containing
795
+ a single node, then all paths computed by this function will
796
+ start from that node. If there are two or more nodes in this
797
+ iterable, the computed paths may begin from any one of the start
798
+ nodes.
799
+
800
+ weight: function
801
+ Function with (u, v, data) input that returns that edge's weight
802
+ or None to indicate a hidden edge
803
+
804
+ pred: dict of lists, optional(default=None)
805
+ dict to store a list of predecessors keyed by that node
806
+ If None, predecessors are not stored.
807
+
808
+ paths: dict, optional (default=None)
809
+ dict to store the path list from source to each node, keyed by node.
810
+ If None, paths are not stored.
811
+
812
+ target : node label, optional
813
+ Ending node for path. Search is halted when target is found.
814
+
815
+ cutoff : integer or float, optional
816
+ Length (sum of edge weights) at which the search is stopped.
817
+ If cutoff is provided, only return paths with summed weight <= cutoff.
818
+
819
+ Returns
820
+ -------
821
+ distance : dictionary
822
+ A mapping from node to shortest distance to that node from one
823
+ of the source nodes.
824
+
825
+ Raises
826
+ ------
827
+ NodeNotFound
828
+ If any of `sources` is not in `G`.
829
+
830
+ Notes
831
+ -----
832
+ The optional predecessor and path dictionaries can be accessed by
833
+ the caller through the original pred and paths objects passed
834
+ as arguments. No need to explicitly return pred or paths.
835
+
836
+ """
837
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
838
+
839
+ push = heappush
840
+ pop = heappop
841
+ dist = {} # dictionary of final distances
842
+ seen = {}
843
+ # fringe is heapq with 3-tuples (distance,c,node)
844
+ # use the count c to avoid comparing nodes (may not be able to)
845
+ c = count()
846
+ fringe = []
847
+ for source in sources:
848
+ seen[source] = 0
849
+ push(fringe, (0, next(c), source))
850
+ while fringe:
851
+ (d, _, v) = pop(fringe)
852
+ if v in dist:
853
+ continue # already searched this node.
854
+ dist[v] = d
855
+ if v == target:
856
+ break
857
+ for u, e in G_succ[v].items():
858
+ cost = weight(v, u, e)
859
+ if cost is None:
860
+ continue
861
+ vu_dist = dist[v] + cost
862
+ if cutoff is not None:
863
+ if vu_dist > cutoff:
864
+ continue
865
+ if u in dist:
866
+ u_dist = dist[u]
867
+ if vu_dist < u_dist:
868
+ raise ValueError("Contradictory paths found:", "negative weights?")
869
+ elif pred is not None and vu_dist == u_dist:
870
+ pred[u].append(v)
871
+ elif u not in seen or vu_dist < seen[u]:
872
+ seen[u] = vu_dist
873
+ push(fringe, (vu_dist, next(c), u))
874
+ if paths is not None:
875
+ paths[u] = paths[v] + [u]
876
+ if pred is not None:
877
+ pred[u] = [v]
878
+ elif vu_dist == seen[u]:
879
+ if pred is not None:
880
+ pred[u].append(v)
881
+
882
+ # The optional predecessor and path dictionaries can be accessed
883
+ # by the caller via the pred and paths objects passed as arguments.
884
+ return dist
885
+
886
+
887
+ @nx._dispatchable(edge_attrs="weight")
888
+ def dijkstra_predecessor_and_distance(G, source, cutoff=None, weight="weight"):
889
+ """Compute weighted shortest path length and predecessors.
890
+
891
+ Uses Dijkstra's Method to obtain the shortest weighted paths
892
+ and return dictionaries of predecessors for each node and
893
+ distance for each node from the `source`.
894
+
895
+ Parameters
896
+ ----------
897
+ G : NetworkX graph
898
+
899
+ source : node label
900
+ Starting node for path
901
+
902
+ cutoff : integer or float, optional
903
+ Length (sum of edge weights) at which the search is stopped.
904
+ If cutoff is provided, only return paths with summed weight <= cutoff.
905
+
906
+ weight : string or function
907
+ If this is a string, then edge weights will be accessed via the
908
+ edge attribute with this key (that is, the weight of the edge
909
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
910
+ such edge attribute exists, the weight of the edge is assumed to
911
+ be one.
912
+
913
+ If this is a function, the weight of an edge is the value
914
+ returned by the function. The function must accept exactly three
915
+ positional arguments: the two endpoints of an edge and the
916
+ dictionary of edge attributes for that edge. The function must
917
+ return a number or None to indicate a hidden edge.
918
+
919
+ Returns
920
+ -------
921
+ pred, distance : dictionaries
922
+ Returns two dictionaries representing a list of predecessors
923
+ of a node and the distance to each node.
924
+
925
+ Raises
926
+ ------
927
+ NodeNotFound
928
+ If `source` is not in `G`.
929
+
930
+ Notes
931
+ -----
932
+ Edge weight attributes must be numerical.
933
+ Distances are calculated as sums of weighted edges traversed.
934
+
935
+ The list of predecessors contains more than one element only when
936
+ there are more than one shortest paths to the key node.
937
+
938
+ Examples
939
+ --------
940
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
941
+ >>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0)
942
+ >>> sorted(pred.items())
943
+ [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
944
+ >>> sorted(dist.items())
945
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
946
+
947
+ >>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0, 1)
948
+ >>> sorted(pred.items())
949
+ [(0, []), (1, [0])]
950
+ >>> sorted(dist.items())
951
+ [(0, 0), (1, 1)]
952
+ """
953
+ if source not in G:
954
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
955
+ weight = _weight_function(G, weight)
956
+ pred = {source: []} # dictionary of predecessors
957
+ return (pred, _dijkstra(G, source, weight, pred=pred, cutoff=cutoff))
958
+
959
+
960
+ @nx._dispatchable(edge_attrs="weight")
961
+ def all_pairs_dijkstra(G, cutoff=None, weight="weight"):
962
+ """Find shortest weighted paths and lengths between all nodes.
963
+
964
+ Parameters
965
+ ----------
966
+ G : NetworkX graph
967
+
968
+ cutoff : integer or float, optional
969
+ Length (sum of edge weights) at which the search is stopped.
970
+ If cutoff is provided, only return paths with summed weight <= cutoff.
971
+
972
+ weight : string or function
973
+ If this is a string, then edge weights will be accessed via the
974
+ edge attribute with this key (that is, the weight of the edge
975
+ joining `u` to `v` will be ``G.edge[u][v][weight]``). If no
976
+ such edge attribute exists, the weight of the edge is assumed to
977
+ be one.
978
+
979
+ If this is a function, the weight of an edge is the value
980
+ returned by the function. The function must accept exactly three
981
+ positional arguments: the two endpoints of an edge and the
982
+ dictionary of edge attributes for that edge. The function must
983
+ return a number or None to indicate a hidden edge.
984
+
985
+ Yields
986
+ ------
987
+ (node, (distance, path)) : (node obj, (dict, dict))
988
+ Each source node has two associated dicts. The first holds distance
989
+ keyed by target and the second holds paths keyed by target.
990
+ (See single_source_dijkstra for the source/target node terminology.)
991
+ If desired you can apply `dict()` to this function to create a dict
992
+ keyed by source node to the two dicts.
993
+
994
+ Examples
995
+ --------
996
+ >>> G = nx.path_graph(5)
997
+ >>> len_path = dict(nx.all_pairs_dijkstra(G))
998
+ >>> len_path[3][0][1]
999
+ 2
1000
+ >>> for node in [0, 1, 2, 3, 4]:
1001
+ ... print(f"3 - {node}: {len_path[3][0][node]}")
1002
+ 3 - 0: 3
1003
+ 3 - 1: 2
1004
+ 3 - 2: 1
1005
+ 3 - 3: 0
1006
+ 3 - 4: 1
1007
+ >>> len_path[3][1][1]
1008
+ [3, 2, 1]
1009
+ >>> for n, (dist, path) in nx.all_pairs_dijkstra(G):
1010
+ ... print(path[1])
1011
+ [0, 1]
1012
+ [1]
1013
+ [2, 1]
1014
+ [3, 2, 1]
1015
+ [4, 3, 2, 1]
1016
+
1017
+ Notes
1018
+ -----
1019
+ Edge weight attributes must be numerical.
1020
+ Distances are calculated as sums of weighted edges traversed.
1021
+
1022
+ The yielded dicts only have keys for reachable nodes.
1023
+ """
1024
+ for n in G:
1025
+ dist, path = single_source_dijkstra(G, n, cutoff=cutoff, weight=weight)
1026
+ yield (n, (dist, path))
1027
+
1028
+
1029
+ @nx._dispatchable(edge_attrs="weight")
1030
+ def all_pairs_dijkstra_path_length(G, cutoff=None, weight="weight"):
1031
+ """Compute shortest path lengths between all nodes in a weighted graph.
1032
+
1033
+ Parameters
1034
+ ----------
1035
+ G : NetworkX graph
1036
+
1037
+ cutoff : integer or float, optional
1038
+ Length (sum of edge weights) at which the search is stopped.
1039
+ If cutoff is provided, only return paths with summed weight <= cutoff.
1040
+
1041
+ weight : string or function
1042
+ If this is a string, then edge weights will be accessed via the
1043
+ edge attribute with this key (that is, the weight of the edge
1044
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1045
+ such edge attribute exists, the weight of the edge is assumed to
1046
+ be one.
1047
+
1048
+ If this is a function, the weight of an edge is the value
1049
+ returned by the function. The function must accept exactly three
1050
+ positional arguments: the two endpoints of an edge and the
1051
+ dictionary of edge attributes for that edge. The function must
1052
+ return a number or None to indicate a hidden edge.
1053
+
1054
+ Returns
1055
+ -------
1056
+ distance : iterator
1057
+ (source, dictionary) iterator with dictionary keyed by target and
1058
+ shortest path length as the key value.
1059
+
1060
+ Examples
1061
+ --------
1062
+ >>> G = nx.path_graph(5)
1063
+ >>> length = dict(nx.all_pairs_dijkstra_path_length(G))
1064
+ >>> for node in [0, 1, 2, 3, 4]:
1065
+ ... print(f"1 - {node}: {length[1][node]}")
1066
+ 1 - 0: 1
1067
+ 1 - 1: 0
1068
+ 1 - 2: 1
1069
+ 1 - 3: 2
1070
+ 1 - 4: 3
1071
+ >>> length[3][2]
1072
+ 1
1073
+ >>> length[2][2]
1074
+ 0
1075
+
1076
+ Notes
1077
+ -----
1078
+ Edge weight attributes must be numerical.
1079
+ Distances are calculated as sums of weighted edges traversed.
1080
+
1081
+ The dictionary returned only has keys for reachable node pairs.
1082
+ """
1083
+ length = single_source_dijkstra_path_length
1084
+ for n in G:
1085
+ yield (n, length(G, n, cutoff=cutoff, weight=weight))
1086
+
1087
+
1088
+ @nx._dispatchable(edge_attrs="weight")
1089
+ def all_pairs_dijkstra_path(G, cutoff=None, weight="weight"):
1090
+ """Compute shortest paths between all nodes in a weighted graph.
1091
+
1092
+ Parameters
1093
+ ----------
1094
+ G : NetworkX graph
1095
+
1096
+ cutoff : integer or float, optional
1097
+ Length (sum of edge weights) at which the search is stopped.
1098
+ If cutoff is provided, only return paths with summed weight <= cutoff.
1099
+
1100
+ weight : string or function
1101
+ If this is a string, then edge weights will be accessed via the
1102
+ edge attribute with this key (that is, the weight of the edge
1103
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1104
+ such edge attribute exists, the weight of the edge is assumed to
1105
+ be one.
1106
+
1107
+ If this is a function, the weight of an edge is the value
1108
+ returned by the function. The function must accept exactly three
1109
+ positional arguments: the two endpoints of an edge and the
1110
+ dictionary of edge attributes for that edge. The function must
1111
+ return a number or None to indicate a hidden edge.
1112
+
1113
+ Returns
1114
+ -------
1115
+ paths : iterator
1116
+ (source, dictionary) iterator with dictionary keyed by target and
1117
+ shortest path as the key value.
1118
+
1119
+ Examples
1120
+ --------
1121
+ >>> G = nx.path_graph(5)
1122
+ >>> path = dict(nx.all_pairs_dijkstra_path(G))
1123
+ >>> path[0][4]
1124
+ [0, 1, 2, 3, 4]
1125
+
1126
+ Notes
1127
+ -----
1128
+ Edge weight attributes must be numerical.
1129
+ Distances are calculated as sums of weighted edges traversed.
1130
+
1131
+ See Also
1132
+ --------
1133
+ floyd_warshall, all_pairs_bellman_ford_path
1134
+
1135
+ """
1136
+ path = single_source_dijkstra_path
1137
+ # TODO This can be trivially parallelized.
1138
+ for n in G:
1139
+ yield (n, path(G, n, cutoff=cutoff, weight=weight))
1140
+
1141
+
1142
+ @nx._dispatchable(edge_attrs="weight")
1143
+ def bellman_ford_predecessor_and_distance(
1144
+ G, source, target=None, weight="weight", heuristic=False
1145
+ ):
1146
+ """Compute shortest path lengths and predecessors on shortest paths
1147
+ in weighted graphs.
1148
+
1149
+ The algorithm has a running time of $O(mn)$ where $n$ is the number of
1150
+ nodes and $m$ is the number of edges. It is slower than Dijkstra but
1151
+ can handle negative edge weights.
1152
+
1153
+ If a negative cycle is detected, you can use :func:`find_negative_cycle`
1154
+ to return the cycle and examine it. Shortest paths are not defined when
1155
+ a negative cycle exists because once reached, the path can cycle forever
1156
+ to build up arbitrarily low weights.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ G : NetworkX graph
1161
+ The algorithm works for all types of graphs, including directed
1162
+ graphs and multigraphs.
1163
+
1164
+ source: node label
1165
+ Starting node for path
1166
+
1167
+ target : node label, optional
1168
+ Ending node for path
1169
+
1170
+ weight : string or function
1171
+ If this is a string, then edge weights will be accessed via the
1172
+ edge attribute with this key (that is, the weight of the edge
1173
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1174
+ such edge attribute exists, the weight of the edge is assumed to
1175
+ be one.
1176
+
1177
+ If this is a function, the weight of an edge is the value
1178
+ returned by the function. The function must accept exactly three
1179
+ positional arguments: the two endpoints of an edge and the
1180
+ dictionary of edge attributes for that edge. The function must
1181
+ return a number.
1182
+
1183
+ heuristic : bool
1184
+ Determines whether to use a heuristic to early detect negative
1185
+ cycles at a hopefully negligible cost.
1186
+
1187
+ Returns
1188
+ -------
1189
+ pred, dist : dictionaries
1190
+ Returns two dictionaries keyed by node to predecessor in the
1191
+ path and to the distance from the source respectively.
1192
+
1193
+ Raises
1194
+ ------
1195
+ NodeNotFound
1196
+ If `source` is not in `G`.
1197
+
1198
+ NetworkXUnbounded
1199
+ If the (di)graph contains a negative (di)cycle, the
1200
+ algorithm raises an exception to indicate the presence of the
1201
+ negative (di)cycle. Note: any negative weight edge in an
1202
+ undirected graph is a negative cycle.
1203
+
1204
+ Examples
1205
+ --------
1206
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
1207
+ >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0)
1208
+ >>> sorted(pred.items())
1209
+ [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
1210
+ >>> sorted(dist.items())
1211
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
1212
+
1213
+ >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0, 1)
1214
+ >>> sorted(pred.items())
1215
+ [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
1216
+ >>> sorted(dist.items())
1217
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
1218
+
1219
+ >>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
1220
+ >>> G[1][2]["weight"] = -7
1221
+ >>> nx.bellman_ford_predecessor_and_distance(G, 0)
1222
+ Traceback (most recent call last):
1223
+ ...
1224
+ networkx.exception.NetworkXUnbounded: Negative cycle detected.
1225
+
1226
+ See Also
1227
+ --------
1228
+ find_negative_cycle
1229
+
1230
+ Notes
1231
+ -----
1232
+ Edge weight attributes must be numerical.
1233
+ Distances are calculated as sums of weighted edges traversed.
1234
+
1235
+ The dictionaries returned only have keys for nodes reachable from
1236
+ the source.
1237
+
1238
+ In the case where the (di)graph is not connected, if a component
1239
+ not containing the source contains a negative (di)cycle, it
1240
+ will not be detected.
1241
+
1242
+ In NetworkX v2.1 and prior, the source node had predecessor `[None]`.
1243
+ In NetworkX v2.2 this changed to the source node having predecessor `[]`
1244
+ """
1245
+ if source not in G:
1246
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
1247
+ weight = _weight_function(G, weight)
1248
+ if G.is_multigraph():
1249
+ if any(
1250
+ weight(u, v, {k: d}) < 0
1251
+ for u, v, k, d in nx.selfloop_edges(G, keys=True, data=True)
1252
+ ):
1253
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
1254
+ else:
1255
+ if any(weight(u, v, d) < 0 for u, v, d in nx.selfloop_edges(G, data=True)):
1256
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
1257
+
1258
+ dist = {source: 0}
1259
+ pred = {source: []}
1260
+
1261
+ if len(G) == 1:
1262
+ return pred, dist
1263
+
1264
+ weight = _weight_function(G, weight)
1265
+
1266
+ dist = _bellman_ford(
1267
+ G, [source], weight, pred=pred, dist=dist, target=target, heuristic=heuristic
1268
+ )
1269
+ return (pred, dist)
1270
+
1271
+
1272
+ def _bellman_ford(
1273
+ G,
1274
+ source,
1275
+ weight,
1276
+ pred=None,
1277
+ paths=None,
1278
+ dist=None,
1279
+ target=None,
1280
+ heuristic=True,
1281
+ ):
1282
+ """Calls relaxation loop for Bellman–Ford algorithm and builds paths
1283
+
1284
+ This is an implementation of the SPFA variant.
1285
+ See https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
1286
+
1287
+ Parameters
1288
+ ----------
1289
+ G : NetworkX graph
1290
+
1291
+ source: list
1292
+ List of source nodes. The shortest path from any of the source
1293
+ nodes will be found if multiple sources are provided.
1294
+
1295
+ weight : function
1296
+ The weight of an edge is the value returned by the function. The
1297
+ function must accept exactly three positional arguments: the two
1298
+ endpoints of an edge and the dictionary of edge attributes for
1299
+ that edge. The function must return a number.
1300
+
1301
+ pred: dict of lists, optional (default=None)
1302
+ dict to store a list of predecessors keyed by that node
1303
+ If None, predecessors are not stored
1304
+
1305
+ paths: dict, optional (default=None)
1306
+ dict to store the path list from source to each node, keyed by node
1307
+ If None, paths are not stored
1308
+
1309
+ dist: dict, optional (default=None)
1310
+ dict to store distance from source to the keyed node
1311
+ If None, returned dist dict contents default to 0 for every node in the
1312
+ source list
1313
+
1314
+ target: node label, optional
1315
+ Ending node for path. Path lengths to other destinations may (and
1316
+ probably will) be incorrect.
1317
+
1318
+ heuristic : bool
1319
+ Determines whether to use a heuristic to early detect negative
1320
+ cycles at a hopefully negligible cost.
1321
+
1322
+ Returns
1323
+ -------
1324
+ dist : dict
1325
+ Returns a dict keyed by node to the distance from the source.
1326
+ Dicts for paths and pred are in the mutated input dicts by those names.
1327
+
1328
+ Raises
1329
+ ------
1330
+ NodeNotFound
1331
+ If any of `source` is not in `G`.
1332
+
1333
+ NetworkXUnbounded
1334
+ If the (di)graph contains a negative (di)cycle, the
1335
+ algorithm raises an exception to indicate the presence of the
1336
+ negative (di)cycle. Note: any negative weight edge in an
1337
+ undirected graph is a negative cycle
1338
+ """
1339
+ if pred is None:
1340
+ pred = {v: [] for v in source}
1341
+
1342
+ if dist is None:
1343
+ dist = {v: 0 for v in source}
1344
+
1345
+ negative_cycle_found = _inner_bellman_ford(
1346
+ G,
1347
+ source,
1348
+ weight,
1349
+ pred,
1350
+ dist,
1351
+ heuristic,
1352
+ )
1353
+ if negative_cycle_found is not None:
1354
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
1355
+
1356
+ if paths is not None:
1357
+ sources = set(source)
1358
+ dsts = [target] if target is not None else pred
1359
+ for dst in dsts:
1360
+ gen = _build_paths_from_predecessors(sources, dst, pred)
1361
+ paths[dst] = next(gen)
1362
+
1363
+ return dist
1364
+
1365
+
1366
+ def _inner_bellman_ford(
1367
+ G,
1368
+ sources,
1369
+ weight,
1370
+ pred,
1371
+ dist=None,
1372
+ heuristic=True,
1373
+ ):
1374
+ """Inner Relaxation loop for Bellman–Ford algorithm.
1375
+
1376
+ This is an implementation of the SPFA variant.
1377
+ See https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
1378
+
1379
+ Parameters
1380
+ ----------
1381
+ G : NetworkX graph
1382
+
1383
+ source: list
1384
+ List of source nodes. The shortest path from any of the source
1385
+ nodes will be found if multiple sources are provided.
1386
+
1387
+ weight : function
1388
+ The weight of an edge is the value returned by the function. The
1389
+ function must accept exactly three positional arguments: the two
1390
+ endpoints of an edge and the dictionary of edge attributes for
1391
+ that edge. The function must return a number.
1392
+
1393
+ pred: dict of lists
1394
+ dict to store a list of predecessors keyed by that node
1395
+
1396
+ dist: dict, optional (default=None)
1397
+ dict to store distance from source to the keyed node
1398
+ If None, returned dist dict contents default to 0 for every node in the
1399
+ source list
1400
+
1401
+ heuristic : bool
1402
+ Determines whether to use a heuristic to early detect negative
1403
+ cycles at a hopefully negligible cost.
1404
+
1405
+ Returns
1406
+ -------
1407
+ node or None
1408
+ Return a node `v` where processing discovered a negative cycle.
1409
+ If no negative cycle found, return None.
1410
+
1411
+ Raises
1412
+ ------
1413
+ NodeNotFound
1414
+ If any of `source` is not in `G`.
1415
+ """
1416
+ for s in sources:
1417
+ if s not in G:
1418
+ raise nx.NodeNotFound(f"Source {s} not in G")
1419
+
1420
+ if pred is None:
1421
+ pred = {v: [] for v in sources}
1422
+
1423
+ if dist is None:
1424
+ dist = {v: 0 for v in sources}
1425
+
1426
+ # Heuristic Storage setup. Note: use None because nodes cannot be None
1427
+ nonexistent_edge = (None, None)
1428
+ pred_edge = {v: None for v in sources}
1429
+ recent_update = {v: nonexistent_edge for v in sources}
1430
+
1431
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
1432
+ inf = float("inf")
1433
+ n = len(G)
1434
+
1435
+ count = {}
1436
+ q = deque(sources)
1437
+ in_q = set(sources)
1438
+ while q:
1439
+ u = q.popleft()
1440
+ in_q.remove(u)
1441
+
1442
+ # Skip relaxations if any of the predecessors of u is in the queue.
1443
+ if all(pred_u not in in_q for pred_u in pred[u]):
1444
+ dist_u = dist[u]
1445
+ for v, e in G_succ[u].items():
1446
+ dist_v = dist_u + weight(u, v, e)
1447
+
1448
+ if dist_v < dist.get(v, inf):
1449
+ # In this conditional branch we are updating the path with v.
1450
+ # If it happens that some earlier update also added node v
1451
+ # that implies the existence of a negative cycle since
1452
+ # after the update node v would lie on the update path twice.
1453
+ # The update path is stored up to one of the source nodes,
1454
+ # therefore u is always in the dict recent_update
1455
+ if heuristic:
1456
+ if v in recent_update[u]:
1457
+ # Negative cycle found!
1458
+ pred[v].append(u)
1459
+ return v
1460
+
1461
+ # Transfer the recent update info from u to v if the
1462
+ # same source node is the head of the update path.
1463
+ # If the source node is responsible for the cost update,
1464
+ # then clear the history and use it instead.
1465
+ if v in pred_edge and pred_edge[v] == u:
1466
+ recent_update[v] = recent_update[u]
1467
+ else:
1468
+ recent_update[v] = (u, v)
1469
+
1470
+ if v not in in_q:
1471
+ q.append(v)
1472
+ in_q.add(v)
1473
+ count_v = count.get(v, 0) + 1
1474
+ if count_v == n:
1475
+ # Negative cycle found!
1476
+ return v
1477
+
1478
+ count[v] = count_v
1479
+ dist[v] = dist_v
1480
+ pred[v] = [u]
1481
+ pred_edge[v] = u
1482
+
1483
+ elif dist.get(v) is not None and dist_v == dist.get(v):
1484
+ pred[v].append(u)
1485
+
1486
+ # successfully found shortest_path. No negative cycles found.
1487
+ return None
1488
+
1489
+
1490
+ @nx._dispatchable(edge_attrs="weight")
1491
+ def bellman_ford_path(G, source, target, weight="weight"):
1492
+ """Returns the shortest path from source to target in a weighted graph G.
1493
+
1494
+ Parameters
1495
+ ----------
1496
+ G : NetworkX graph
1497
+
1498
+ source : node
1499
+ Starting node
1500
+
1501
+ target : node
1502
+ Ending node
1503
+
1504
+ weight : string or function (default="weight")
1505
+ If this is a string, then edge weights will be accessed via the
1506
+ edge attribute with this key (that is, the weight of the edge
1507
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1508
+ such edge attribute exists, the weight of the edge is assumed to
1509
+ be one.
1510
+
1511
+ If this is a function, the weight of an edge is the value
1512
+ returned by the function. The function must accept exactly three
1513
+ positional arguments: the two endpoints of an edge and the
1514
+ dictionary of edge attributes for that edge. The function must
1515
+ return a number.
1516
+
1517
+ Returns
1518
+ -------
1519
+ path : list
1520
+ List of nodes in a shortest path.
1521
+
1522
+ Raises
1523
+ ------
1524
+ NodeNotFound
1525
+ If `source` is not in `G`.
1526
+
1527
+ NetworkXNoPath
1528
+ If no path exists between source and target.
1529
+
1530
+ Examples
1531
+ --------
1532
+ >>> G = nx.path_graph(5)
1533
+ >>> nx.bellman_ford_path(G, 0, 4)
1534
+ [0, 1, 2, 3, 4]
1535
+
1536
+ Notes
1537
+ -----
1538
+ Edge weight attributes must be numerical.
1539
+ Distances are calculated as sums of weighted edges traversed.
1540
+
1541
+ See Also
1542
+ --------
1543
+ dijkstra_path, bellman_ford_path_length
1544
+ """
1545
+ length, path = single_source_bellman_ford(G, source, target=target, weight=weight)
1546
+ return path
1547
+
1548
+
1549
+ @nx._dispatchable(edge_attrs="weight")
1550
+ def bellman_ford_path_length(G, source, target, weight="weight"):
1551
+ """Returns the shortest path length from source to target
1552
+ in a weighted graph.
1553
+
1554
+ Parameters
1555
+ ----------
1556
+ G : NetworkX graph
1557
+
1558
+ source : node label
1559
+ starting node for path
1560
+
1561
+ target : node label
1562
+ ending node for path
1563
+
1564
+ weight : string or function (default="weight")
1565
+ If this is a string, then edge weights will be accessed via the
1566
+ edge attribute with this key (that is, the weight of the edge
1567
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1568
+ such edge attribute exists, the weight of the edge is assumed to
1569
+ be one.
1570
+
1571
+ If this is a function, the weight of an edge is the value
1572
+ returned by the function. The function must accept exactly three
1573
+ positional arguments: the two endpoints of an edge and the
1574
+ dictionary of edge attributes for that edge. The function must
1575
+ return a number.
1576
+
1577
+ Returns
1578
+ -------
1579
+ length : number
1580
+ Shortest path length.
1581
+
1582
+ Raises
1583
+ ------
1584
+ NodeNotFound
1585
+ If `source` is not in `G`.
1586
+
1587
+ NetworkXNoPath
1588
+ If no path exists between source and target.
1589
+
1590
+ Examples
1591
+ --------
1592
+ >>> G = nx.path_graph(5)
1593
+ >>> nx.bellman_ford_path_length(G, 0, 4)
1594
+ 4
1595
+
1596
+ Notes
1597
+ -----
1598
+ Edge weight attributes must be numerical.
1599
+ Distances are calculated as sums of weighted edges traversed.
1600
+
1601
+ See Also
1602
+ --------
1603
+ dijkstra_path_length, bellman_ford_path
1604
+ """
1605
+ if source == target:
1606
+ if source not in G:
1607
+ raise nx.NodeNotFound(f"Node {source} not found in graph")
1608
+ return 0
1609
+
1610
+ weight = _weight_function(G, weight)
1611
+
1612
+ length = _bellman_ford(G, [source], weight, target=target)
1613
+
1614
+ try:
1615
+ return length[target]
1616
+ except KeyError as err:
1617
+ raise nx.NetworkXNoPath(f"node {target} not reachable from {source}") from err
1618
+
1619
+
1620
+ @nx._dispatchable(edge_attrs="weight")
1621
+ def single_source_bellman_ford_path(G, source, weight="weight"):
1622
+ """Compute shortest path between source and all other reachable
1623
+ nodes for a weighted graph.
1624
+
1625
+ Parameters
1626
+ ----------
1627
+ G : NetworkX graph
1628
+
1629
+ source : node
1630
+ Starting node for path.
1631
+
1632
+ weight : string or function (default="weight")
1633
+ If this is a string, then edge weights will be accessed via the
1634
+ edge attribute with this key (that is, the weight of the edge
1635
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1636
+ such edge attribute exists, the weight of the edge is assumed to
1637
+ be one.
1638
+
1639
+ If this is a function, the weight of an edge is the value
1640
+ returned by the function. The function must accept exactly three
1641
+ positional arguments: the two endpoints of an edge and the
1642
+ dictionary of edge attributes for that edge. The function must
1643
+ return a number.
1644
+
1645
+ Returns
1646
+ -------
1647
+ paths : dictionary
1648
+ Dictionary of shortest path lengths keyed by target.
1649
+
1650
+ Raises
1651
+ ------
1652
+ NodeNotFound
1653
+ If `source` is not in `G`.
1654
+
1655
+ Examples
1656
+ --------
1657
+ >>> G = nx.path_graph(5)
1658
+ >>> path = nx.single_source_bellman_ford_path(G, 0)
1659
+ >>> path[4]
1660
+ [0, 1, 2, 3, 4]
1661
+
1662
+ Notes
1663
+ -----
1664
+ Edge weight attributes must be numerical.
1665
+ Distances are calculated as sums of weighted edges traversed.
1666
+
1667
+ See Also
1668
+ --------
1669
+ single_source_dijkstra, single_source_bellman_ford
1670
+
1671
+ """
1672
+ (length, path) = single_source_bellman_ford(G, source, weight=weight)
1673
+ return path
1674
+
1675
+
1676
+ @nx._dispatchable(edge_attrs="weight")
1677
+ def single_source_bellman_ford_path_length(G, source, weight="weight"):
1678
+ """Compute the shortest path length between source and all other
1679
+ reachable nodes for a weighted graph.
1680
+
1681
+ Parameters
1682
+ ----------
1683
+ G : NetworkX graph
1684
+
1685
+ source : node label
1686
+ Starting node for path
1687
+
1688
+ weight : string or function (default="weight")
1689
+ If this is a string, then edge weights will be accessed via the
1690
+ edge attribute with this key (that is, the weight of the edge
1691
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1692
+ such edge attribute exists, the weight of the edge is assumed to
1693
+ be one.
1694
+
1695
+ If this is a function, the weight of an edge is the value
1696
+ returned by the function. The function must accept exactly three
1697
+ positional arguments: the two endpoints of an edge and the
1698
+ dictionary of edge attributes for that edge. The function must
1699
+ return a number.
1700
+
1701
+ Returns
1702
+ -------
1703
+ length : dictionary
1704
+ Dictionary of shortest path length keyed by target
1705
+
1706
+ Raises
1707
+ ------
1708
+ NodeNotFound
1709
+ If `source` is not in `G`.
1710
+
1711
+ Examples
1712
+ --------
1713
+ >>> G = nx.path_graph(5)
1714
+ >>> length = nx.single_source_bellman_ford_path_length(G, 0)
1715
+ >>> length[4]
1716
+ 4
1717
+ >>> for node in [0, 1, 2, 3, 4]:
1718
+ ... print(f"{node}: {length[node]}")
1719
+ 0: 0
1720
+ 1: 1
1721
+ 2: 2
1722
+ 3: 3
1723
+ 4: 4
1724
+
1725
+ Notes
1726
+ -----
1727
+ Edge weight attributes must be numerical.
1728
+ Distances are calculated as sums of weighted edges traversed.
1729
+
1730
+ See Also
1731
+ --------
1732
+ single_source_dijkstra, single_source_bellman_ford
1733
+
1734
+ """
1735
+ weight = _weight_function(G, weight)
1736
+ return _bellman_ford(G, [source], weight)
1737
+
1738
+
1739
+ @nx._dispatchable(edge_attrs="weight")
1740
+ def single_source_bellman_ford(G, source, target=None, weight="weight"):
1741
+ """Compute shortest paths and lengths in a weighted graph G.
1742
+
1743
+ Uses Bellman-Ford algorithm for shortest paths.
1744
+
1745
+ Parameters
1746
+ ----------
1747
+ G : NetworkX graph
1748
+
1749
+ source : node label
1750
+ Starting node for path
1751
+
1752
+ target : node label, optional
1753
+ Ending node for path
1754
+
1755
+ weight : string or function
1756
+ If this is a string, then edge weights will be accessed via the
1757
+ edge attribute with this key (that is, the weight of the edge
1758
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1759
+ such edge attribute exists, the weight of the edge is assumed to
1760
+ be one.
1761
+
1762
+ If this is a function, the weight of an edge is the value
1763
+ returned by the function. The function must accept exactly three
1764
+ positional arguments: the two endpoints of an edge and the
1765
+ dictionary of edge attributes for that edge. The function must
1766
+ return a number.
1767
+
1768
+ Returns
1769
+ -------
1770
+ distance, path : pair of dictionaries, or numeric and list
1771
+ If target is None, returns a tuple of two dictionaries keyed by node.
1772
+ The first dictionary stores distance from one of the source nodes.
1773
+ The second stores the path from one of the sources to that node.
1774
+ If target is not None, returns a tuple of (distance, path) where
1775
+ distance is the distance from source to target and path is a list
1776
+ representing the path from source to target.
1777
+
1778
+ Raises
1779
+ ------
1780
+ NodeNotFound
1781
+ If `source` is not in `G`.
1782
+
1783
+ Examples
1784
+ --------
1785
+ >>> G = nx.path_graph(5)
1786
+ >>> length, path = nx.single_source_bellman_ford(G, 0)
1787
+ >>> length[4]
1788
+ 4
1789
+ >>> for node in [0, 1, 2, 3, 4]:
1790
+ ... print(f"{node}: {length[node]}")
1791
+ 0: 0
1792
+ 1: 1
1793
+ 2: 2
1794
+ 3: 3
1795
+ 4: 4
1796
+ >>> path[4]
1797
+ [0, 1, 2, 3, 4]
1798
+ >>> length, path = nx.single_source_bellman_ford(G, 0, 1)
1799
+ >>> length
1800
+ 1
1801
+ >>> path
1802
+ [0, 1]
1803
+
1804
+ Notes
1805
+ -----
1806
+ Edge weight attributes must be numerical.
1807
+ Distances are calculated as sums of weighted edges traversed.
1808
+
1809
+ See Also
1810
+ --------
1811
+ single_source_dijkstra
1812
+ single_source_bellman_ford_path
1813
+ single_source_bellman_ford_path_length
1814
+ """
1815
+ if source == target:
1816
+ if source not in G:
1817
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
1818
+ return (0, [source])
1819
+
1820
+ weight = _weight_function(G, weight)
1821
+
1822
+ paths = {source: [source]} # dictionary of paths
1823
+ dist = _bellman_ford(G, [source], weight, paths=paths, target=target)
1824
+ if target is None:
1825
+ return (dist, paths)
1826
+ try:
1827
+ return (dist[target], paths[target])
1828
+ except KeyError as err:
1829
+ msg = f"Node {target} not reachable from {source}"
1830
+ raise nx.NetworkXNoPath(msg) from err
1831
+
1832
+
1833
+ @nx._dispatchable(edge_attrs="weight")
1834
+ def all_pairs_bellman_ford_path_length(G, weight="weight"):
1835
+ """Compute shortest path lengths between all nodes in a weighted graph.
1836
+
1837
+ Parameters
1838
+ ----------
1839
+ G : NetworkX graph
1840
+
1841
+ weight : string or function (default="weight")
1842
+ If this is a string, then edge weights will be accessed via the
1843
+ edge attribute with this key (that is, the weight of the edge
1844
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1845
+ such edge attribute exists, the weight of the edge is assumed to
1846
+ be one.
1847
+
1848
+ If this is a function, the weight of an edge is the value
1849
+ returned by the function. The function must accept exactly three
1850
+ positional arguments: the two endpoints of an edge and the
1851
+ dictionary of edge attributes for that edge. The function must
1852
+ return a number.
1853
+
1854
+ Returns
1855
+ -------
1856
+ distance : iterator
1857
+ (source, dictionary) iterator with dictionary keyed by target and
1858
+ shortest path length as the key value.
1859
+
1860
+ Examples
1861
+ --------
1862
+ >>> G = nx.path_graph(5)
1863
+ >>> length = dict(nx.all_pairs_bellman_ford_path_length(G))
1864
+ >>> for node in [0, 1, 2, 3, 4]:
1865
+ ... print(f"1 - {node}: {length[1][node]}")
1866
+ 1 - 0: 1
1867
+ 1 - 1: 0
1868
+ 1 - 2: 1
1869
+ 1 - 3: 2
1870
+ 1 - 4: 3
1871
+ >>> length[3][2]
1872
+ 1
1873
+ >>> length[2][2]
1874
+ 0
1875
+
1876
+ Notes
1877
+ -----
1878
+ Edge weight attributes must be numerical.
1879
+ Distances are calculated as sums of weighted edges traversed.
1880
+
1881
+ The dictionary returned only has keys for reachable node pairs.
1882
+ """
1883
+ length = single_source_bellman_ford_path_length
1884
+ for n in G:
1885
+ yield (n, dict(length(G, n, weight=weight)))
1886
+
1887
+
1888
+ @nx._dispatchable(edge_attrs="weight")
1889
+ def all_pairs_bellman_ford_path(G, weight="weight"):
1890
+ """Compute shortest paths between all nodes in a weighted graph.
1891
+
1892
+ Parameters
1893
+ ----------
1894
+ G : NetworkX graph
1895
+
1896
+ weight : string or function (default="weight")
1897
+ If this is a string, then edge weights will be accessed via the
1898
+ edge attribute with this key (that is, the weight of the edge
1899
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1900
+ such edge attribute exists, the weight of the edge is assumed to
1901
+ be one.
1902
+
1903
+ If this is a function, the weight of an edge is the value
1904
+ returned by the function. The function must accept exactly three
1905
+ positional arguments: the two endpoints of an edge and the
1906
+ dictionary of edge attributes for that edge. The function must
1907
+ return a number.
1908
+
1909
+ Returns
1910
+ -------
1911
+ paths : iterator
1912
+ (source, dictionary) iterator with dictionary keyed by target and
1913
+ shortest path as the key value.
1914
+
1915
+ Examples
1916
+ --------
1917
+ >>> G = nx.path_graph(5)
1918
+ >>> path = dict(nx.all_pairs_bellman_ford_path(G))
1919
+ >>> path[0][4]
1920
+ [0, 1, 2, 3, 4]
1921
+
1922
+ Notes
1923
+ -----
1924
+ Edge weight attributes must be numerical.
1925
+ Distances are calculated as sums of weighted edges traversed.
1926
+
1927
+ See Also
1928
+ --------
1929
+ floyd_warshall, all_pairs_dijkstra_path
1930
+
1931
+ """
1932
+ path = single_source_bellman_ford_path
1933
+ for n in G:
1934
+ yield (n, path(G, n, weight=weight))
1935
+
1936
+
1937
+ @nx._dispatchable(edge_attrs="weight")
1938
+ def goldberg_radzik(G, source, weight="weight"):
1939
+ """Compute shortest path lengths and predecessors on shortest paths
1940
+ in weighted graphs.
1941
+
1942
+ The algorithm has a running time of $O(mn)$ where $n$ is the number of
1943
+ nodes and $m$ is the number of edges. It is slower than Dijkstra but
1944
+ can handle negative edge weights.
1945
+
1946
+ Parameters
1947
+ ----------
1948
+ G : NetworkX graph
1949
+ The algorithm works for all types of graphs, including directed
1950
+ graphs and multigraphs.
1951
+
1952
+ source: node label
1953
+ Starting node for path
1954
+
1955
+ weight : string or function
1956
+ If this is a string, then edge weights will be accessed via the
1957
+ edge attribute with this key (that is, the weight of the edge
1958
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1959
+ such edge attribute exists, the weight of the edge is assumed to
1960
+ be one.
1961
+
1962
+ If this is a function, the weight of an edge is the value
1963
+ returned by the function. The function must accept exactly three
1964
+ positional arguments: the two endpoints of an edge and the
1965
+ dictionary of edge attributes for that edge. The function must
1966
+ return a number.
1967
+
1968
+ Returns
1969
+ -------
1970
+ pred, dist : dictionaries
1971
+ Returns two dictionaries keyed by node to predecessor in the
1972
+ path and to the distance from the source respectively.
1973
+
1974
+ Raises
1975
+ ------
1976
+ NodeNotFound
1977
+ If `source` is not in `G`.
1978
+
1979
+ NetworkXUnbounded
1980
+ If the (di)graph contains a negative (di)cycle, the
1981
+ algorithm raises an exception to indicate the presence of the
1982
+ negative (di)cycle. Note: any negative weight edge in an
1983
+ undirected graph is a negative cycle.
1984
+
1985
+ As of NetworkX v3.2, a zero weight cycle is no longer
1986
+ incorrectly reported as a negative weight cycle.
1987
+
1988
+
1989
+ Examples
1990
+ --------
1991
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
1992
+ >>> pred, dist = nx.goldberg_radzik(G, 0)
1993
+ >>> sorted(pred.items())
1994
+ [(0, None), (1, 0), (2, 1), (3, 2), (4, 3)]
1995
+ >>> sorted(dist.items())
1996
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
1997
+
1998
+ >>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
1999
+ >>> G[1][2]["weight"] = -7
2000
+ >>> nx.goldberg_radzik(G, 0)
2001
+ Traceback (most recent call last):
2002
+ ...
2003
+ networkx.exception.NetworkXUnbounded: Negative cycle detected.
2004
+
2005
+ Notes
2006
+ -----
2007
+ Edge weight attributes must be numerical.
2008
+ Distances are calculated as sums of weighted edges traversed.
2009
+
2010
+ The dictionaries returned only have keys for nodes reachable from
2011
+ the source.
2012
+
2013
+ In the case where the (di)graph is not connected, if a component
2014
+ not containing the source contains a negative (di)cycle, it
2015
+ will not be detected.
2016
+
2017
+ """
2018
+ if source not in G:
2019
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
2020
+ weight = _weight_function(G, weight)
2021
+ if G.is_multigraph():
2022
+ if any(
2023
+ weight(u, v, {k: d}) < 0
2024
+ for u, v, k, d in nx.selfloop_edges(G, keys=True, data=True)
2025
+ ):
2026
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
2027
+ else:
2028
+ if any(weight(u, v, d) < 0 for u, v, d in nx.selfloop_edges(G, data=True)):
2029
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
2030
+
2031
+ if len(G) == 1:
2032
+ return {source: None}, {source: 0}
2033
+
2034
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
2035
+
2036
+ inf = float("inf")
2037
+ d = {u: inf for u in G}
2038
+ d[source] = 0
2039
+ pred = {source: None}
2040
+
2041
+ def topo_sort(relabeled):
2042
+ """Topologically sort nodes relabeled in the previous round and detect
2043
+ negative cycles.
2044
+ """
2045
+ # List of nodes to scan in this round. Denoted by A in Goldberg and
2046
+ # Radzik's paper.
2047
+ to_scan = []
2048
+ # In the DFS in the loop below, neg_count records for each node the
2049
+ # number of edges of negative reduced costs on the path from a DFS root
2050
+ # to the node in the DFS forest. The reduced cost of an edge (u, v) is
2051
+ # defined as d[u] + weight[u][v] - d[v].
2052
+ #
2053
+ # neg_count also doubles as the DFS visit marker array.
2054
+ neg_count = {}
2055
+ for u in relabeled:
2056
+ # Skip visited nodes.
2057
+ if u in neg_count:
2058
+ continue
2059
+ d_u = d[u]
2060
+ # Skip nodes without out-edges of negative reduced costs.
2061
+ if all(d_u + weight(u, v, e) >= d[v] for v, e in G_succ[u].items()):
2062
+ continue
2063
+ # Nonrecursive DFS that inserts nodes reachable from u via edges of
2064
+ # nonpositive reduced costs into to_scan in (reverse) topological
2065
+ # order.
2066
+ stack = [(u, iter(G_succ[u].items()))]
2067
+ in_stack = {u}
2068
+ neg_count[u] = 0
2069
+ while stack:
2070
+ u, it = stack[-1]
2071
+ try:
2072
+ v, e = next(it)
2073
+ except StopIteration:
2074
+ to_scan.append(u)
2075
+ stack.pop()
2076
+ in_stack.remove(u)
2077
+ continue
2078
+ t = d[u] + weight(u, v, e)
2079
+ d_v = d[v]
2080
+ if t < d_v:
2081
+ is_neg = t < d_v
2082
+ d[v] = t
2083
+ pred[v] = u
2084
+ if v not in neg_count:
2085
+ neg_count[v] = neg_count[u] + int(is_neg)
2086
+ stack.append((v, iter(G_succ[v].items())))
2087
+ in_stack.add(v)
2088
+ elif v in in_stack and neg_count[u] + int(is_neg) > neg_count[v]:
2089
+ # (u, v) is a back edge, and the cycle formed by the
2090
+ # path v to u and (u, v) contains at least one edge of
2091
+ # negative reduced cost. The cycle must be of negative
2092
+ # cost.
2093
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
2094
+ to_scan.reverse()
2095
+ return to_scan
2096
+
2097
+ def relax(to_scan):
2098
+ """Relax out-edges of relabeled nodes."""
2099
+ relabeled = set()
2100
+ # Scan nodes in to_scan in topological order and relax incident
2101
+ # out-edges. Add the relabled nodes to labeled.
2102
+ for u in to_scan:
2103
+ d_u = d[u]
2104
+ for v, e in G_succ[u].items():
2105
+ w_e = weight(u, v, e)
2106
+ if d_u + w_e < d[v]:
2107
+ d[v] = d_u + w_e
2108
+ pred[v] = u
2109
+ relabeled.add(v)
2110
+ return relabeled
2111
+
2112
+ # Set of nodes relabled in the last round of scan operations. Denoted by B
2113
+ # in Goldberg and Radzik's paper.
2114
+ relabeled = {source}
2115
+
2116
+ while relabeled:
2117
+ to_scan = topo_sort(relabeled)
2118
+ relabeled = relax(to_scan)
2119
+
2120
+ d = {u: d[u] for u in pred}
2121
+ return pred, d
2122
+
2123
+
2124
+ @nx._dispatchable(edge_attrs="weight")
2125
+ def negative_edge_cycle(G, weight="weight", heuristic=True):
2126
+ """Returns True if there exists a negative edge cycle anywhere in G.
2127
+
2128
+ Parameters
2129
+ ----------
2130
+ G : NetworkX graph
2131
+
2132
+ weight : string or function
2133
+ If this is a string, then edge weights will be accessed via the
2134
+ edge attribute with this key (that is, the weight of the edge
2135
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2136
+ such edge attribute exists, the weight of the edge is assumed to
2137
+ be one.
2138
+
2139
+ If this is a function, the weight of an edge is the value
2140
+ returned by the function. The function must accept exactly three
2141
+ positional arguments: the two endpoints of an edge and the
2142
+ dictionary of edge attributes for that edge. The function must
2143
+ return a number.
2144
+
2145
+ heuristic : bool
2146
+ Determines whether to use a heuristic to early detect negative
2147
+ cycles at a negligible cost. In case of graphs with a negative cycle,
2148
+ the performance of detection increases by at least an order of magnitude.
2149
+
2150
+ Returns
2151
+ -------
2152
+ negative_cycle : bool
2153
+ True if a negative edge cycle exists, otherwise False.
2154
+
2155
+ Examples
2156
+ --------
2157
+ >>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
2158
+ >>> print(nx.negative_edge_cycle(G))
2159
+ False
2160
+ >>> G[1][2]["weight"] = -7
2161
+ >>> print(nx.negative_edge_cycle(G))
2162
+ True
2163
+
2164
+ Notes
2165
+ -----
2166
+ Edge weight attributes must be numerical.
2167
+ Distances are calculated as sums of weighted edges traversed.
2168
+
2169
+ This algorithm uses bellman_ford_predecessor_and_distance() but finds
2170
+ negative cycles on any component by first adding a new node connected to
2171
+ every node, and starting bellman_ford_predecessor_and_distance on that
2172
+ node. It then removes that extra node.
2173
+ """
2174
+ if G.size() == 0:
2175
+ return False
2176
+
2177
+ # find unused node to use temporarily
2178
+ newnode = -1
2179
+ while newnode in G:
2180
+ newnode -= 1
2181
+ # connect it to all nodes
2182
+ G.add_edges_from([(newnode, n) for n in G])
2183
+
2184
+ try:
2185
+ bellman_ford_predecessor_and_distance(
2186
+ G, newnode, weight=weight, heuristic=heuristic
2187
+ )
2188
+ except nx.NetworkXUnbounded:
2189
+ return True
2190
+ finally:
2191
+ G.remove_node(newnode)
2192
+ return False
2193
+
2194
+
2195
+ @nx._dispatchable(edge_attrs="weight")
2196
+ def find_negative_cycle(G, source, weight="weight"):
2197
+ """Returns a cycle with negative total weight if it exists.
2198
+
2199
+ Bellman-Ford is used to find shortest_paths. That algorithm
2200
+ stops if there exists a negative cycle. This algorithm
2201
+ picks up from there and returns the found negative cycle.
2202
+
2203
+ The cycle consists of a list of nodes in the cycle order. The last
2204
+ node equals the first to make it a cycle.
2205
+ You can look up the edge weights in the original graph. In the case
2206
+ of multigraphs the relevant edge is the minimal weight edge between
2207
+ the nodes in the 2-tuple.
2208
+
2209
+ If the graph has no negative cycle, a NetworkXError is raised.
2210
+
2211
+ Parameters
2212
+ ----------
2213
+ G : NetworkX graph
2214
+
2215
+ source: node label
2216
+ The search for the negative cycle will start from this node.
2217
+
2218
+ weight : string or function
2219
+ If this is a string, then edge weights will be accessed via the
2220
+ edge attribute with this key (that is, the weight of the edge
2221
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2222
+ such edge attribute exists, the weight of the edge is assumed to
2223
+ be one.
2224
+
2225
+ If this is a function, the weight of an edge is the value
2226
+ returned by the function. The function must accept exactly three
2227
+ positional arguments: the two endpoints of an edge and the
2228
+ dictionary of edge attributes for that edge. The function must
2229
+ return a number.
2230
+
2231
+ Examples
2232
+ --------
2233
+ >>> G = nx.DiGraph()
2234
+ >>> G.add_weighted_edges_from(
2235
+ ... [(0, 1, 2), (1, 2, 2), (2, 0, 1), (1, 4, 2), (4, 0, -5)]
2236
+ ... )
2237
+ >>> nx.find_negative_cycle(G, 0)
2238
+ [4, 0, 1, 4]
2239
+
2240
+ Returns
2241
+ -------
2242
+ cycle : list
2243
+ A list of nodes in the order of the cycle found. The last node
2244
+ equals the first to indicate a cycle.
2245
+
2246
+ Raises
2247
+ ------
2248
+ NetworkXError
2249
+ If no negative cycle is found.
2250
+ """
2251
+ weight = _weight_function(G, weight)
2252
+ pred = {source: []}
2253
+
2254
+ v = _inner_bellman_ford(G, [source], weight, pred=pred)
2255
+ if v is None:
2256
+ raise nx.NetworkXError("No negative cycles detected.")
2257
+
2258
+ # negative cycle detected... find it
2259
+ neg_cycle = []
2260
+ stack = [(v, list(pred[v]))]
2261
+ seen = {v}
2262
+ while stack:
2263
+ node, preds = stack[-1]
2264
+ if v in preds:
2265
+ # found the cycle
2266
+ neg_cycle.extend([node, v])
2267
+ neg_cycle = list(reversed(neg_cycle))
2268
+ return neg_cycle
2269
+
2270
+ if preds:
2271
+ nbr = preds.pop()
2272
+ if nbr not in seen:
2273
+ stack.append((nbr, list(pred[nbr])))
2274
+ neg_cycle.append(node)
2275
+ seen.add(nbr)
2276
+ else:
2277
+ stack.pop()
2278
+ if neg_cycle:
2279
+ neg_cycle.pop()
2280
+ else:
2281
+ if v in G[v] and weight(G, v, v) < 0:
2282
+ return [v, v]
2283
+ # should not reach here
2284
+ raise nx.NetworkXError("Negative cycle is detected but not found")
2285
+ # should not get here...
2286
+ msg = "negative cycle detected but not identified"
2287
+ raise nx.NetworkXUnbounded(msg)
2288
+
2289
+
2290
+ @nx._dispatchable(edge_attrs="weight")
2291
+ def bidirectional_dijkstra(G, source, target, weight="weight"):
2292
+ r"""Dijkstra's algorithm for shortest paths using bidirectional search.
2293
+
2294
+ Parameters
2295
+ ----------
2296
+ G : NetworkX graph
2297
+
2298
+ source : node
2299
+ Starting node.
2300
+
2301
+ target : node
2302
+ Ending node.
2303
+
2304
+ weight : string or function
2305
+ If this is a string, then edge weights will be accessed via the
2306
+ edge attribute with this key (that is, the weight of the edge
2307
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2308
+ such edge attribute exists, the weight of the edge is assumed to
2309
+ be one.
2310
+
2311
+ If this is a function, the weight of an edge is the value
2312
+ returned by the function. The function must accept exactly three
2313
+ positional arguments: the two endpoints of an edge and the
2314
+ dictionary of edge attributes for that edge. The function must
2315
+ return a number or None to indicate a hidden edge.
2316
+
2317
+ Returns
2318
+ -------
2319
+ length, path : number and list
2320
+ length is the distance from source to target.
2321
+ path is a list of nodes on a path from source to target.
2322
+
2323
+ Raises
2324
+ ------
2325
+ NodeNotFound
2326
+ If `source` or `target` is not in `G`.
2327
+
2328
+ NetworkXNoPath
2329
+ If no path exists between source and target.
2330
+
2331
+ Examples
2332
+ --------
2333
+ >>> G = nx.path_graph(5)
2334
+ >>> length, path = nx.bidirectional_dijkstra(G, 0, 4)
2335
+ >>> print(length)
2336
+ 4
2337
+ >>> print(path)
2338
+ [0, 1, 2, 3, 4]
2339
+
2340
+ Notes
2341
+ -----
2342
+ Edge weight attributes must be numerical.
2343
+ Distances are calculated as sums of weighted edges traversed.
2344
+
2345
+ The weight function can be used to hide edges by returning None.
2346
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
2347
+ will find the shortest red path.
2348
+
2349
+ In practice bidirectional Dijkstra is much more than twice as fast as
2350
+ ordinary Dijkstra.
2351
+
2352
+ Ordinary Dijkstra expands nodes in a sphere-like manner from the
2353
+ source. The radius of this sphere will eventually be the length
2354
+ of the shortest path. Bidirectional Dijkstra will expand nodes
2355
+ from both the source and the target, making two spheres of half
2356
+ this radius. Volume of the first sphere is `\pi*r*r` while the
2357
+ others are `2*\pi*r/2*r/2`, making up half the volume.
2358
+
2359
+ This algorithm is not guaranteed to work if edge weights
2360
+ are negative or are floating point numbers
2361
+ (overflows and roundoff errors can cause problems).
2362
+
2363
+ See Also
2364
+ --------
2365
+ shortest_path
2366
+ shortest_path_length
2367
+ """
2368
+ if source not in G:
2369
+ raise nx.NodeNotFound(f"Source {source} is not in G")
2370
+
2371
+ if target not in G:
2372
+ raise nx.NodeNotFound(f"Target {target} is not in G")
2373
+
2374
+ if source == target:
2375
+ return (0, [source])
2376
+
2377
+ weight = _weight_function(G, weight)
2378
+ push = heappush
2379
+ pop = heappop
2380
+ # Init: [Forward, Backward]
2381
+ dists = [{}, {}] # dictionary of final distances
2382
+ paths = [{source: [source]}, {target: [target]}] # dictionary of paths
2383
+ fringe = [[], []] # heap of (distance, node) for choosing node to expand
2384
+ seen = [{source: 0}, {target: 0}] # dict of distances to seen nodes
2385
+ c = count()
2386
+ # initialize fringe heap
2387
+ push(fringe[0], (0, next(c), source))
2388
+ push(fringe[1], (0, next(c), target))
2389
+ # neighs for extracting correct neighbor information
2390
+ if G.is_directed():
2391
+ neighs = [G._succ, G._pred]
2392
+ else:
2393
+ neighs = [G._adj, G._adj]
2394
+ # variables to hold shortest discovered path
2395
+ # finaldist = 1e30000
2396
+ finalpath = []
2397
+ dir = 1
2398
+ while fringe[0] and fringe[1]:
2399
+ # choose direction
2400
+ # dir == 0 is forward direction and dir == 1 is back
2401
+ dir = 1 - dir
2402
+ # extract closest to expand
2403
+ (dist, _, v) = pop(fringe[dir])
2404
+ if v in dists[dir]:
2405
+ # Shortest path to v has already been found
2406
+ continue
2407
+ # update distance
2408
+ dists[dir][v] = dist # equal to seen[dir][v]
2409
+ if v in dists[1 - dir]:
2410
+ # if we have scanned v in both directions we are done
2411
+ # we have now discovered the shortest path
2412
+ return (finaldist, finalpath)
2413
+
2414
+ for w, d in neighs[dir][v].items():
2415
+ # weight(v, w, d) for forward and weight(w, v, d) for back direction
2416
+ cost = weight(v, w, d) if dir == 0 else weight(w, v, d)
2417
+ if cost is None:
2418
+ continue
2419
+ vwLength = dists[dir][v] + cost
2420
+ if w in dists[dir]:
2421
+ if vwLength < dists[dir][w]:
2422
+ raise ValueError("Contradictory paths found: negative weights?")
2423
+ elif w not in seen[dir] or vwLength < seen[dir][w]:
2424
+ # relaxing
2425
+ seen[dir][w] = vwLength
2426
+ push(fringe[dir], (vwLength, next(c), w))
2427
+ paths[dir][w] = paths[dir][v] + [w]
2428
+ if w in seen[0] and w in seen[1]:
2429
+ # see if this path is better than the already
2430
+ # discovered shortest path
2431
+ totaldist = seen[0][w] + seen[1][w]
2432
+ if finalpath == [] or finaldist > totaldist:
2433
+ finaldist = totaldist
2434
+ revpath = paths[1][w][:]
2435
+ revpath.reverse()
2436
+ finalpath = paths[0][w] + revpath[1:]
2437
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
2438
+
2439
+
2440
+ @nx._dispatchable(edge_attrs="weight")
2441
+ def johnson(G, weight="weight"):
2442
+ r"""Uses Johnson's Algorithm to compute shortest paths.
2443
+
2444
+ Johnson's Algorithm finds a shortest path between each pair of
2445
+ nodes in a weighted graph even if negative weights are present.
2446
+
2447
+ Parameters
2448
+ ----------
2449
+ G : NetworkX graph
2450
+
2451
+ weight : string or function
2452
+ If this is a string, then edge weights will be accessed via the
2453
+ edge attribute with this key (that is, the weight of the edge
2454
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2455
+ such edge attribute exists, the weight of the edge is assumed to
2456
+ be one.
2457
+
2458
+ If this is a function, the weight of an edge is the value
2459
+ returned by the function. The function must accept exactly three
2460
+ positional arguments: the two endpoints of an edge and the
2461
+ dictionary of edge attributes for that edge. The function must
2462
+ return a number.
2463
+
2464
+ Returns
2465
+ -------
2466
+ distance : dictionary
2467
+ Dictionary, keyed by source and target, of shortest paths.
2468
+
2469
+ Examples
2470
+ --------
2471
+ >>> graph = nx.DiGraph()
2472
+ >>> graph.add_weighted_edges_from(
2473
+ ... [("0", "3", 3), ("0", "1", -5), ("0", "2", 2), ("1", "2", 4), ("2", "3", 1)]
2474
+ ... )
2475
+ >>> paths = nx.johnson(graph, weight="weight")
2476
+ >>> paths["0"]["2"]
2477
+ ['0', '1', '2']
2478
+
2479
+ Notes
2480
+ -----
2481
+ Johnson's algorithm is suitable even for graphs with negative weights. It
2482
+ works by using the Bellman–Ford algorithm to compute a transformation of
2483
+ the input graph that removes all negative weights, allowing Dijkstra's
2484
+ algorithm to be used on the transformed graph.
2485
+
2486
+ The time complexity of this algorithm is $O(n^2 \log n + n m)$,
2487
+ where $n$ is the number of nodes and $m$ the number of edges in the
2488
+ graph. For dense graphs, this may be faster than the Floyd–Warshall
2489
+ algorithm.
2490
+
2491
+ See Also
2492
+ --------
2493
+ floyd_warshall_predecessor_and_distance
2494
+ floyd_warshall_numpy
2495
+ all_pairs_shortest_path
2496
+ all_pairs_shortest_path_length
2497
+ all_pairs_dijkstra_path
2498
+ bellman_ford_predecessor_and_distance
2499
+ all_pairs_bellman_ford_path
2500
+ all_pairs_bellman_ford_path_length
2501
+
2502
+ """
2503
+ dist = {v: 0 for v in G}
2504
+ pred = {v: [] for v in G}
2505
+ weight = _weight_function(G, weight)
2506
+
2507
+ # Calculate distance of shortest paths
2508
+ dist_bellman = _bellman_ford(G, list(G), weight, pred=pred, dist=dist)
2509
+
2510
+ # Update the weight function to take into account the Bellman--Ford
2511
+ # relaxation distances.
2512
+ def new_weight(u, v, d):
2513
+ return weight(u, v, d) + dist_bellman[u] - dist_bellman[v]
2514
+
2515
+ def dist_path(v):
2516
+ paths = {v: [v]}
2517
+ _dijkstra(G, v, new_weight, paths=paths)
2518
+ return paths
2519
+
2520
+ return {v: dist_path(v) for v in G}
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+
4
+ def test_is_at_free():
5
+ is_at_free = nx.asteroidal.is_at_free
6
+
7
+ cycle = nx.cycle_graph(6)
8
+ assert not is_at_free(cycle)
9
+
10
+ path = nx.path_graph(6)
11
+ assert is_at_free(path)
12
+
13
+ small_graph = nx.complete_graph(2)
14
+ assert is_at_free(small_graph)
15
+
16
+ petersen = nx.petersen_graph()
17
+ assert not is_at_free(petersen)
18
+
19
+ clique = nx.complete_graph(6)
20
+ assert is_at_free(clique)
21
+
22
+ line_clique = nx.line_graph(clique)
23
+ assert not is_at_free(line_clique)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.boundary` module."""
2
+
3
+ from itertools import combinations
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx import convert_node_labels_to_integers as cnlti
9
+ from networkx.utils import edges_equal
10
+
11
+
12
+ class TestNodeBoundary:
13
+ """Unit tests for the :func:`~networkx.node_boundary` function."""
14
+
15
+ def test_null_graph(self):
16
+ """Tests that the null graph has empty node boundaries."""
17
+ null = nx.null_graph()
18
+ assert nx.node_boundary(null, []) == set()
19
+ assert nx.node_boundary(null, [], []) == set()
20
+ assert nx.node_boundary(null, [1, 2, 3]) == set()
21
+ assert nx.node_boundary(null, [1, 2, 3], [4, 5, 6]) == set()
22
+ assert nx.node_boundary(null, [1, 2, 3], [3, 4, 5]) == set()
23
+
24
+ def test_path_graph(self):
25
+ P10 = cnlti(nx.path_graph(10), first_label=1)
26
+ assert nx.node_boundary(P10, []) == set()
27
+ assert nx.node_boundary(P10, [], []) == set()
28
+ assert nx.node_boundary(P10, [1, 2, 3]) == {4}
29
+ assert nx.node_boundary(P10, [4, 5, 6]) == {3, 7}
30
+ assert nx.node_boundary(P10, [3, 4, 5, 6, 7]) == {2, 8}
31
+ assert nx.node_boundary(P10, [8, 9, 10]) == {7}
32
+ assert nx.node_boundary(P10, [4, 5, 6], [9, 10]) == set()
33
+
34
+ def test_complete_graph(self):
35
+ K10 = cnlti(nx.complete_graph(10), first_label=1)
36
+ assert nx.node_boundary(K10, []) == set()
37
+ assert nx.node_boundary(K10, [], []) == set()
38
+ assert nx.node_boundary(K10, [1, 2, 3]) == {4, 5, 6, 7, 8, 9, 10}
39
+ assert nx.node_boundary(K10, [4, 5, 6]) == {1, 2, 3, 7, 8, 9, 10}
40
+ assert nx.node_boundary(K10, [3, 4, 5, 6, 7]) == {1, 2, 8, 9, 10}
41
+ assert nx.node_boundary(K10, [4, 5, 6], []) == set()
42
+ assert nx.node_boundary(K10, K10) == set()
43
+ assert nx.node_boundary(K10, [1, 2, 3], [3, 4, 5]) == {4, 5}
44
+
45
+ def test_petersen(self):
46
+ """Check boundaries in the petersen graph
47
+
48
+ cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0<k<=|V(G)|/2)
49
+
50
+ """
51
+
52
+ def cheeger(G, k):
53
+ return min(len(nx.node_boundary(G, nn)) / k for nn in combinations(G, k))
54
+
55
+ P = nx.petersen_graph()
56
+ assert cheeger(P, 1) == pytest.approx(3.00, abs=1e-2)
57
+ assert cheeger(P, 2) == pytest.approx(2.00, abs=1e-2)
58
+ assert cheeger(P, 3) == pytest.approx(1.67, abs=1e-2)
59
+ assert cheeger(P, 4) == pytest.approx(1.00, abs=1e-2)
60
+ assert cheeger(P, 5) == pytest.approx(0.80, abs=1e-2)
61
+
62
+ def test_directed(self):
63
+ """Tests the node boundary of a directed graph."""
64
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
65
+ S = {0, 1}
66
+ boundary = nx.node_boundary(G, S)
67
+ expected = {2}
68
+ assert boundary == expected
69
+
70
+ def test_multigraph(self):
71
+ """Tests the node boundary of a multigraph."""
72
+ G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
73
+ S = {0, 1}
74
+ boundary = nx.node_boundary(G, S)
75
+ expected = {2, 4}
76
+ assert boundary == expected
77
+
78
+ def test_multidigraph(self):
79
+ """Tests the edge boundary of a multidigraph."""
80
+ edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
81
+ G = nx.MultiDiGraph(edges * 2)
82
+ S = {0, 1}
83
+ boundary = nx.node_boundary(G, S)
84
+ expected = {2}
85
+ assert boundary == expected
86
+
87
+
88
+ class TestEdgeBoundary:
89
+ """Unit tests for the :func:`~networkx.edge_boundary` function."""
90
+
91
+ def test_null_graph(self):
92
+ null = nx.null_graph()
93
+ assert list(nx.edge_boundary(null, [])) == []
94
+ assert list(nx.edge_boundary(null, [], [])) == []
95
+ assert list(nx.edge_boundary(null, [1, 2, 3])) == []
96
+ assert list(nx.edge_boundary(null, [1, 2, 3], [4, 5, 6])) == []
97
+ assert list(nx.edge_boundary(null, [1, 2, 3], [3, 4, 5])) == []
98
+
99
+ def test_path_graph(self):
100
+ P10 = cnlti(nx.path_graph(10), first_label=1)
101
+ assert list(nx.edge_boundary(P10, [])) == []
102
+ assert list(nx.edge_boundary(P10, [], [])) == []
103
+ assert list(nx.edge_boundary(P10, [1, 2, 3])) == [(3, 4)]
104
+ assert sorted(nx.edge_boundary(P10, [4, 5, 6])) == [(4, 3), (6, 7)]
105
+ assert sorted(nx.edge_boundary(P10, [3, 4, 5, 6, 7])) == [(3, 2), (7, 8)]
106
+ assert list(nx.edge_boundary(P10, [8, 9, 10])) == [(8, 7)]
107
+ assert sorted(nx.edge_boundary(P10, [4, 5, 6], [9, 10])) == []
108
+ assert list(nx.edge_boundary(P10, [1, 2, 3], [3, 4, 5])) == [(2, 3), (3, 4)]
109
+
110
+ def test_complete_graph(self):
111
+ K10 = cnlti(nx.complete_graph(10), first_label=1)
112
+
113
+ def ilen(iterable):
114
+ return sum(1 for i in iterable)
115
+
116
+ assert list(nx.edge_boundary(K10, [])) == []
117
+ assert list(nx.edge_boundary(K10, [], [])) == []
118
+ assert ilen(nx.edge_boundary(K10, [1, 2, 3])) == 21
119
+ assert ilen(nx.edge_boundary(K10, [4, 5, 6, 7])) == 24
120
+ assert ilen(nx.edge_boundary(K10, [3, 4, 5, 6, 7])) == 25
121
+ assert ilen(nx.edge_boundary(K10, [8, 9, 10])) == 21
122
+ assert edges_equal(
123
+ nx.edge_boundary(K10, [4, 5, 6], [9, 10]),
124
+ [(4, 9), (4, 10), (5, 9), (5, 10), (6, 9), (6, 10)],
125
+ )
126
+ assert edges_equal(
127
+ nx.edge_boundary(K10, [1, 2, 3], [3, 4, 5]),
128
+ [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5)],
129
+ )
130
+
131
+ def test_directed(self):
132
+ """Tests the edge boundary of a directed graph."""
133
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
134
+ S = {0, 1}
135
+ boundary = list(nx.edge_boundary(G, S))
136
+ expected = [(1, 2)]
137
+ assert boundary == expected
138
+
139
+ def test_multigraph(self):
140
+ """Tests the edge boundary of a multigraph."""
141
+ G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
142
+ S = {0, 1}
143
+ boundary = list(nx.edge_boundary(G, S))
144
+ expected = [(0, 4), (0, 4), (1, 2), (1, 2)]
145
+ assert boundary == expected
146
+
147
+ def test_multidigraph(self):
148
+ """Tests the edge boundary of a multidigraph."""
149
+ edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
150
+ G = nx.MultiDiGraph(edges * 2)
151
+ S = {0, 1}
152
+ boundary = list(nx.edge_boundary(G, S))
153
+ expected = [(1, 2), (1, 2)]
154
+ assert boundary == expected
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for bridge-finding algorithms."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestBridges:
9
+ """Unit tests for the bridge-finding function."""
10
+
11
+ def test_single_bridge(self):
12
+ edges = [
13
+ # DFS tree edges.
14
+ (1, 2),
15
+ (2, 3),
16
+ (3, 4),
17
+ (3, 5),
18
+ (5, 6),
19
+ (6, 7),
20
+ (7, 8),
21
+ (5, 9),
22
+ (9, 10),
23
+ # Nontree edges.
24
+ (1, 3),
25
+ (1, 4),
26
+ (2, 5),
27
+ (5, 10),
28
+ (6, 8),
29
+ ]
30
+ G = nx.Graph(edges)
31
+ source = 1
32
+ bridges = list(nx.bridges(G, source))
33
+ assert bridges == [(5, 6)]
34
+
35
+ def test_barbell_graph(self):
36
+ # The (3, 0) barbell graph has two triangles joined by a single edge.
37
+ G = nx.barbell_graph(3, 0)
38
+ source = 0
39
+ bridges = list(nx.bridges(G, source))
40
+ assert bridges == [(2, 3)]
41
+
42
+ def test_multiedge_bridge(self):
43
+ edges = [
44
+ (0, 1),
45
+ (0, 2),
46
+ (1, 2),
47
+ (1, 2),
48
+ (2, 3),
49
+ (3, 4),
50
+ (3, 4),
51
+ ]
52
+ G = nx.MultiGraph(edges)
53
+ assert list(nx.bridges(G)) == [(2, 3)]
54
+
55
+
56
+ class TestHasBridges:
57
+ """Unit tests for the has bridges function."""
58
+
59
+ def test_single_bridge(self):
60
+ edges = [
61
+ # DFS tree edges.
62
+ (1, 2),
63
+ (2, 3),
64
+ (3, 4),
65
+ (3, 5),
66
+ (5, 6), # The only bridge edge
67
+ (6, 7),
68
+ (7, 8),
69
+ (5, 9),
70
+ (9, 10),
71
+ # Nontree edges.
72
+ (1, 3),
73
+ (1, 4),
74
+ (2, 5),
75
+ (5, 10),
76
+ (6, 8),
77
+ ]
78
+ G = nx.Graph(edges)
79
+ assert nx.has_bridges(G) # Default root
80
+ assert nx.has_bridges(G, root=1) # arbitrary root in G
81
+
82
+ def test_has_bridges_raises_root_not_in_G(self):
83
+ G = nx.Graph()
84
+ G.add_nodes_from([1, 2, 3])
85
+ with pytest.raises(nx.NodeNotFound):
86
+ nx.has_bridges(G, root=6)
87
+
88
+ def test_multiedge_bridge(self):
89
+ edges = [
90
+ (0, 1),
91
+ (0, 2),
92
+ (1, 2),
93
+ (1, 2),
94
+ (2, 3),
95
+ (3, 4),
96
+ (3, 4),
97
+ ]
98
+ G = nx.MultiGraph(edges)
99
+ assert nx.has_bridges(G)
100
+ # Make every edge a multiedge
101
+ G.add_edges_from([(0, 1), (0, 2), (2, 3)])
102
+ assert not nx.has_bridges(G)
103
+
104
+ def test_bridges_multiple_components(self):
105
+ G = nx.Graph()
106
+ nx.add_path(G, [0, 1, 2]) # One connected component
107
+ nx.add_path(G, [4, 5, 6]) # Another connected component
108
+ assert list(nx.bridges(G, root=4)) == [(4, 5), (5, 6)]
109
+
110
+
111
+ class TestLocalBridges:
112
+ """Unit tests for the local_bridge function."""
113
+
114
+ @classmethod
115
+ def setup_class(cls):
116
+ cls.BB = nx.barbell_graph(4, 0)
117
+ cls.square = nx.cycle_graph(4)
118
+ cls.tri = nx.cycle_graph(3)
119
+
120
+ def test_nospan(self):
121
+ expected = {(3, 4), (4, 3)}
122
+ assert next(nx.local_bridges(self.BB, with_span=False)) in expected
123
+ assert set(nx.local_bridges(self.square, with_span=False)) == self.square.edges
124
+ assert list(nx.local_bridges(self.tri, with_span=False)) == []
125
+
126
+ def test_no_weight(self):
127
+ inf = float("inf")
128
+ expected = {(3, 4, inf), (4, 3, inf)}
129
+ assert next(nx.local_bridges(self.BB)) in expected
130
+ expected = {(u, v, 3) for u, v in self.square.edges}
131
+ assert set(nx.local_bridges(self.square)) == expected
132
+ assert list(nx.local_bridges(self.tri)) == []
133
+
134
+ def test_weight(self):
135
+ inf = float("inf")
136
+ G = self.square.copy()
137
+
138
+ G.edges[1, 2]["weight"] = 2
139
+ expected = {(u, v, 5 - wt) for u, v, wt in G.edges(data="weight", default=1)}
140
+ assert set(nx.local_bridges(G, weight="weight")) == expected
141
+
142
+ expected = {(u, v, 6) for u, v in G.edges}
143
+ lb = nx.local_bridges(G, weight=lambda u, v, d: 2)
144
+ assert set(lb) == expected
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the broadcasting module."""
2
+
3
+ import math
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def test_example_tree_broadcast():
9
+ """
10
+ Test the BROADCAST algorithm on the example in the paper titled: "Information Dissemination in Trees"
11
+ """
12
+ edge_list = [
13
+ (0, 1),
14
+ (1, 2),
15
+ (2, 7),
16
+ (3, 4),
17
+ (5, 4),
18
+ (4, 7),
19
+ (6, 7),
20
+ (7, 9),
21
+ (8, 9),
22
+ (9, 13),
23
+ (13, 14),
24
+ (14, 15),
25
+ (14, 16),
26
+ (14, 17),
27
+ (13, 11),
28
+ (11, 10),
29
+ (11, 12),
30
+ (13, 18),
31
+ (18, 19),
32
+ (18, 20),
33
+ ]
34
+ G = nx.Graph(edge_list)
35
+ b_T, b_C = nx.tree_broadcast_center(G)
36
+ assert b_T == 6
37
+ assert b_C == {13, 9}
38
+ # test broadcast time from specific vertex
39
+ assert nx.tree_broadcast_time(G, 17) == 8
40
+ assert nx.tree_broadcast_time(G, 3) == 9
41
+ # test broadcast time of entire tree
42
+ assert nx.tree_broadcast_time(G) == 10
43
+
44
+
45
+ def test_path_broadcast():
46
+ for i in range(2, 12):
47
+ G = nx.path_graph(i)
48
+ b_T, b_C = nx.tree_broadcast_center(G)
49
+ assert b_T == math.ceil(i / 2)
50
+ assert b_C == {
51
+ math.ceil(i / 2),
52
+ math.floor(i / 2),
53
+ math.ceil(i / 2 - 1),
54
+ math.floor(i / 2 - 1),
55
+ }
56
+ assert nx.tree_broadcast_time(G) == i - 1
57
+
58
+
59
+ def test_empty_graph_broadcast():
60
+ H = nx.empty_graph(1)
61
+ b_T, b_C = nx.tree_broadcast_center(H)
62
+ assert b_T == 0
63
+ assert b_C == {0}
64
+ assert nx.tree_broadcast_time(H) == 0
65
+
66
+
67
+ def test_star_broadcast():
68
+ for i in range(4, 12):
69
+ G = nx.star_graph(i)
70
+ b_T, b_C = nx.tree_broadcast_center(G)
71
+ assert b_T == i
72
+ assert b_C == set(G.nodes())
73
+ assert nx.tree_broadcast_time(G) == b_T
74
+
75
+
76
+ def test_binomial_tree_broadcast():
77
+ for i in range(2, 8):
78
+ G = nx.binomial_tree(i)
79
+ b_T, b_C = nx.tree_broadcast_center(G)
80
+ assert b_T == i
81
+ assert b_C == {0, 2 ** (i - 1)}
82
+ assert nx.tree_broadcast_time(G) == 2 * i - 1
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_chains.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the chain decomposition functions."""
2
+
3
+ from itertools import cycle, islice
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+
9
+
10
+ def cycles(seq):
11
+ """Yields cyclic permutations of the given sequence.
12
+
13
+ For example::
14
+
15
+ >>> list(cycles("abc"))
16
+ [('a', 'b', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b')]
17
+
18
+ """
19
+ n = len(seq)
20
+ cycled_seq = cycle(seq)
21
+ for x in seq:
22
+ yield tuple(islice(cycled_seq, n))
23
+ next(cycled_seq)
24
+
25
+
26
+ def cyclic_equals(seq1, seq2):
27
+ """Decide whether two sequences are equal up to cyclic permutations.
28
+
29
+ For example::
30
+
31
+ >>> cyclic_equals("xyz", "zxy")
32
+ True
33
+ >>> cyclic_equals("xyz", "zyx")
34
+ False
35
+
36
+ """
37
+ # Cast seq2 to a tuple since `cycles()` yields tuples.
38
+ seq2 = tuple(seq2)
39
+ return any(x == tuple(seq2) for x in cycles(seq1))
40
+
41
+
42
+ class TestChainDecomposition:
43
+ """Unit tests for the chain decomposition function."""
44
+
45
+ def assertContainsChain(self, chain, expected):
46
+ # A cycle could be expressed in two different orientations, one
47
+ # forward and one backward, so we need to check for cyclic
48
+ # equality in both orientations.
49
+ reversed_chain = list(reversed([tuple(reversed(e)) for e in chain]))
50
+ for candidate in expected:
51
+ if cyclic_equals(chain, candidate):
52
+ break
53
+ if cyclic_equals(reversed_chain, candidate):
54
+ break
55
+ else:
56
+ self.fail("chain not found")
57
+
58
+ def test_decomposition(self):
59
+ edges = [
60
+ # DFS tree edges.
61
+ (1, 2),
62
+ (2, 3),
63
+ (3, 4),
64
+ (3, 5),
65
+ (5, 6),
66
+ (6, 7),
67
+ (7, 8),
68
+ (5, 9),
69
+ (9, 10),
70
+ # Nontree edges.
71
+ (1, 3),
72
+ (1, 4),
73
+ (2, 5),
74
+ (5, 10),
75
+ (6, 8),
76
+ ]
77
+ G = nx.Graph(edges)
78
+ expected = [
79
+ [(1, 3), (3, 2), (2, 1)],
80
+ [(1, 4), (4, 3)],
81
+ [(2, 5), (5, 3)],
82
+ [(5, 10), (10, 9), (9, 5)],
83
+ [(6, 8), (8, 7), (7, 6)],
84
+ ]
85
+ chains = list(nx.chain_decomposition(G, root=1))
86
+ assert len(chains) == len(expected)
87
+
88
+ # This chain decomposition isn't unique
89
+ # for chain in chains:
90
+ # print(chain)
91
+ # self.assertContainsChain(chain, expected)
92
+
93
+ def test_barbell_graph(self):
94
+ # The (3, 0) barbell graph has two triangles joined by a single edge.
95
+ G = nx.barbell_graph(3, 0)
96
+ chains = list(nx.chain_decomposition(G, root=0))
97
+ expected = [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]]
98
+ assert len(chains) == len(expected)
99
+ for chain in chains:
100
+ self.assertContainsChain(chain, expected)
101
+
102
+ def test_disconnected_graph(self):
103
+ """Test for a graph with multiple connected components."""
104
+ G = nx.barbell_graph(3, 0)
105
+ H = nx.barbell_graph(3, 0)
106
+ mapping = dict(zip(range(6), "abcdef"))
107
+ nx.relabel_nodes(H, mapping, copy=False)
108
+ G = nx.union(G, H)
109
+ chains = list(nx.chain_decomposition(G))
110
+ expected = [
111
+ [(0, 1), (1, 2), (2, 0)],
112
+ [(3, 4), (4, 5), (5, 3)],
113
+ [("a", "b"), ("b", "c"), ("c", "a")],
114
+ [("d", "e"), ("e", "f"), ("f", "d")],
115
+ ]
116
+ assert len(chains) == len(expected)
117
+ for chain in chains:
118
+ self.assertContainsChain(chain, expected)
119
+
120
+ def test_disconnected_graph_root_node(self):
121
+ """Test for a single component of a disconnected graph."""
122
+ G = nx.barbell_graph(3, 0)
123
+ H = nx.barbell_graph(3, 0)
124
+ mapping = dict(zip(range(6), "abcdef"))
125
+ nx.relabel_nodes(H, mapping, copy=False)
126
+ G = nx.union(G, H)
127
+ chains = list(nx.chain_decomposition(G, root="a"))
128
+ expected = [
129
+ [("a", "b"), ("b", "c"), ("c", "a")],
130
+ [("d", "e"), ("e", "f"), ("f", "d")],
131
+ ]
132
+ assert len(chains) == len(expected)
133
+ for chain in chains:
134
+ self.assertContainsChain(chain, expected)
135
+
136
+ def test_chain_decomposition_root_not_in_G(self):
137
+ """Test chain decomposition when root is not in graph"""
138
+ G = nx.Graph()
139
+ G.add_nodes_from([1, 2, 3])
140
+ with pytest.raises(nx.NodeNotFound):
141
+ nx.has_bridges(G, root=6)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestMCS:
7
+ @classmethod
8
+ def setup_class(cls):
9
+ # simple graph
10
+ connected_chordal_G = nx.Graph()
11
+ connected_chordal_G.add_edges_from(
12
+ [
13
+ (1, 2),
14
+ (1, 3),
15
+ (2, 3),
16
+ (2, 4),
17
+ (3, 4),
18
+ (3, 5),
19
+ (3, 6),
20
+ (4, 5),
21
+ (4, 6),
22
+ (5, 6),
23
+ ]
24
+ )
25
+ cls.connected_chordal_G = connected_chordal_G
26
+
27
+ chordal_G = nx.Graph()
28
+ chordal_G.add_edges_from(
29
+ [
30
+ (1, 2),
31
+ (1, 3),
32
+ (2, 3),
33
+ (2, 4),
34
+ (3, 4),
35
+ (3, 5),
36
+ (3, 6),
37
+ (4, 5),
38
+ (4, 6),
39
+ (5, 6),
40
+ (7, 8),
41
+ ]
42
+ )
43
+ chordal_G.add_node(9)
44
+ cls.chordal_G = chordal_G
45
+
46
+ non_chordal_G = nx.Graph()
47
+ non_chordal_G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5), (3, 4), (3, 5)])
48
+ cls.non_chordal_G = non_chordal_G
49
+
50
+ self_loop_G = nx.Graph()
51
+ self_loop_G.add_edges_from([(1, 1)])
52
+ cls.self_loop_G = self_loop_G
53
+
54
+ @pytest.mark.parametrize("G", (nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()))
55
+ def test_is_chordal_not_implemented(self, G):
56
+ with pytest.raises(nx.NetworkXNotImplemented):
57
+ nx.is_chordal(G)
58
+
59
+ def test_is_chordal(self):
60
+ assert not nx.is_chordal(self.non_chordal_G)
61
+ assert nx.is_chordal(self.chordal_G)
62
+ assert nx.is_chordal(self.connected_chordal_G)
63
+ assert nx.is_chordal(nx.Graph())
64
+ assert nx.is_chordal(nx.complete_graph(3))
65
+ assert nx.is_chordal(nx.cycle_graph(3))
66
+ assert not nx.is_chordal(nx.cycle_graph(5))
67
+ assert nx.is_chordal(self.self_loop_G)
68
+
69
+ def test_induced_nodes(self):
70
+ G = nx.generators.classic.path_graph(10)
71
+ Induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
72
+ assert Induced_nodes == {1, 2, 3, 4, 5, 6, 7, 8, 9}
73
+ pytest.raises(
74
+ nx.NetworkXTreewidthBoundExceeded, nx.find_induced_nodes, G, 1, 9, 1
75
+ )
76
+ Induced_nodes = nx.find_induced_nodes(self.chordal_G, 1, 6)
77
+ assert Induced_nodes == {1, 2, 4, 6}
78
+ pytest.raises(nx.NetworkXError, nx.find_induced_nodes, self.non_chordal_G, 1, 5)
79
+
80
+ def test_graph_treewidth(self):
81
+ with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
82
+ nx.chordal_graph_treewidth(self.non_chordal_G)
83
+
84
+ def test_chordal_find_cliques(self):
85
+ cliques = {
86
+ frozenset([9]),
87
+ frozenset([7, 8]),
88
+ frozenset([1, 2, 3]),
89
+ frozenset([2, 3, 4]),
90
+ frozenset([3, 4, 5, 6]),
91
+ }
92
+ assert set(nx.chordal_graph_cliques(self.chordal_G)) == cliques
93
+ with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
94
+ set(nx.chordal_graph_cliques(self.non_chordal_G))
95
+ with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
96
+ set(nx.chordal_graph_cliques(self.self_loop_G))
97
+
98
+ def test_chordal_find_cliques_path(self):
99
+ G = nx.path_graph(10)
100
+ cliqueset = nx.chordal_graph_cliques(G)
101
+ for u, v in G.edges():
102
+ assert frozenset([u, v]) in cliqueset or frozenset([v, u]) in cliqueset
103
+
104
+ def test_chordal_find_cliquesCC(self):
105
+ cliques = {frozenset([1, 2, 3]), frozenset([2, 3, 4]), frozenset([3, 4, 5, 6])}
106
+ cgc = nx.chordal_graph_cliques
107
+ assert set(cgc(self.connected_chordal_G)) == cliques
108
+
109
+ def test_complete_to_chordal_graph(self):
110
+ fgrg = nx.fast_gnp_random_graph
111
+ test_graphs = [
112
+ nx.barbell_graph(6, 2),
113
+ nx.cycle_graph(15),
114
+ nx.wheel_graph(20),
115
+ nx.grid_graph([10, 4]),
116
+ nx.ladder_graph(15),
117
+ nx.star_graph(5),
118
+ nx.bull_graph(),
119
+ fgrg(20, 0.3, seed=1),
120
+ ]
121
+ for G in test_graphs:
122
+ H, a = nx.complete_to_chordal_graph(G)
123
+ assert nx.is_chordal(H)
124
+ assert len(a) == H.number_of_nodes()
125
+ if nx.is_chordal(G):
126
+ assert G.number_of_edges() == H.number_of_edges()
127
+ assert set(a.values()) == {0}
128
+ else:
129
+ assert len(set(a.values())) == H.number_of_nodes()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_clique.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import convert_node_labels_to_integers as cnlti
5
+
6
+
7
+ class TestCliques:
8
+ def setup_method(self):
9
+ z = [3, 4, 3, 4, 2, 4, 2, 1, 1, 1, 1]
10
+ self.G = cnlti(nx.generators.havel_hakimi_graph(z), first_label=1)
11
+ self.cl = list(nx.find_cliques(self.G))
12
+ H = nx.complete_graph(6)
13
+ H = nx.relabel_nodes(H, {i: i + 1 for i in range(6)})
14
+ H.remove_edges_from([(2, 6), (2, 5), (2, 4), (1, 3), (5, 3)])
15
+ self.H = H
16
+
17
+ def test_find_cliques1(self):
18
+ cl = list(nx.find_cliques(self.G))
19
+ rcl = nx.find_cliques_recursive(self.G)
20
+ expected = [[2, 6, 1, 3], [2, 6, 4], [5, 4, 7], [8, 9], [10, 11]]
21
+ assert sorted(map(sorted, cl)) == sorted(map(sorted, rcl))
22
+ assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
23
+
24
+ def test_selfloops(self):
25
+ self.G.add_edge(1, 1)
26
+ cl = list(nx.find_cliques(self.G))
27
+ rcl = list(nx.find_cliques_recursive(self.G))
28
+ assert set(map(frozenset, cl)) == set(map(frozenset, rcl))
29
+ answer = [{2, 6, 1, 3}, {2, 6, 4}, {5, 4, 7}, {8, 9}, {10, 11}]
30
+ assert len(answer) == len(cl)
31
+ assert all(set(c) in answer for c in cl)
32
+
33
+ def test_find_cliques2(self):
34
+ hcl = list(nx.find_cliques(self.H))
35
+ assert sorted(map(sorted, hcl)) == [[1, 2], [1, 4, 5, 6], [2, 3], [3, 4, 6]]
36
+
37
+ def test_find_cliques3(self):
38
+ # all cliques are [[2, 6, 1, 3], [2, 6, 4], [5, 4, 7], [8, 9], [10, 11]]
39
+
40
+ cl = list(nx.find_cliques(self.G, [2]))
41
+ rcl = nx.find_cliques_recursive(self.G, [2])
42
+ expected = [[2, 6, 1, 3], [2, 6, 4]]
43
+ assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
44
+ assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
45
+
46
+ cl = list(nx.find_cliques(self.G, [2, 3]))
47
+ rcl = nx.find_cliques_recursive(self.G, [2, 3])
48
+ expected = [[2, 6, 1, 3]]
49
+ assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
50
+ assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
51
+
52
+ cl = list(nx.find_cliques(self.G, [2, 6, 4]))
53
+ rcl = nx.find_cliques_recursive(self.G, [2, 6, 4])
54
+ expected = [[2, 6, 4]]
55
+ assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
56
+ assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
57
+
58
+ cl = list(nx.find_cliques(self.G, [2, 6, 4]))
59
+ rcl = nx.find_cliques_recursive(self.G, [2, 6, 4])
60
+ expected = [[2, 6, 4]]
61
+ assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
62
+ assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
63
+
64
+ with pytest.raises(ValueError):
65
+ list(nx.find_cliques(self.G, [2, 6, 4, 1]))
66
+
67
+ with pytest.raises(ValueError):
68
+ list(nx.find_cliques_recursive(self.G, [2, 6, 4, 1]))
69
+
70
+ def test_number_of_cliques(self):
71
+ G = self.G
72
+ assert nx.number_of_cliques(G, 1) == 1
73
+ assert list(nx.number_of_cliques(G, [1]).values()) == [1]
74
+ assert list(nx.number_of_cliques(G, [1, 2]).values()) == [1, 2]
75
+ assert nx.number_of_cliques(G, [1, 2]) == {1: 1, 2: 2}
76
+ assert nx.number_of_cliques(G, 2) == 2
77
+ assert nx.number_of_cliques(G) == {
78
+ 1: 1,
79
+ 2: 2,
80
+ 3: 1,
81
+ 4: 2,
82
+ 5: 1,
83
+ 6: 2,
84
+ 7: 1,
85
+ 8: 1,
86
+ 9: 1,
87
+ 10: 1,
88
+ 11: 1,
89
+ }
90
+ assert nx.number_of_cliques(G, nodes=list(G)) == {
91
+ 1: 1,
92
+ 2: 2,
93
+ 3: 1,
94
+ 4: 2,
95
+ 5: 1,
96
+ 6: 2,
97
+ 7: 1,
98
+ 8: 1,
99
+ 9: 1,
100
+ 10: 1,
101
+ 11: 1,
102
+ }
103
+ assert nx.number_of_cliques(G, nodes=[2, 3, 4]) == {2: 2, 3: 1, 4: 2}
104
+ assert nx.number_of_cliques(G, cliques=self.cl) == {
105
+ 1: 1,
106
+ 2: 2,
107
+ 3: 1,
108
+ 4: 2,
109
+ 5: 1,
110
+ 6: 2,
111
+ 7: 1,
112
+ 8: 1,
113
+ 9: 1,
114
+ 10: 1,
115
+ 11: 1,
116
+ }
117
+ assert nx.number_of_cliques(G, list(G), cliques=self.cl) == {
118
+ 1: 1,
119
+ 2: 2,
120
+ 3: 1,
121
+ 4: 2,
122
+ 5: 1,
123
+ 6: 2,
124
+ 7: 1,
125
+ 8: 1,
126
+ 9: 1,
127
+ 10: 1,
128
+ 11: 1,
129
+ }
130
+
131
+ def test_node_clique_number(self):
132
+ G = self.G
133
+ assert nx.node_clique_number(G, 1) == 4
134
+ assert list(nx.node_clique_number(G, [1]).values()) == [4]
135
+ assert list(nx.node_clique_number(G, [1, 2]).values()) == [4, 4]
136
+ assert nx.node_clique_number(G, [1, 2]) == {1: 4, 2: 4}
137
+ assert nx.node_clique_number(G, 1) == 4
138
+ assert nx.node_clique_number(G) == {
139
+ 1: 4,
140
+ 2: 4,
141
+ 3: 4,
142
+ 4: 3,
143
+ 5: 3,
144
+ 6: 4,
145
+ 7: 3,
146
+ 8: 2,
147
+ 9: 2,
148
+ 10: 2,
149
+ 11: 2,
150
+ }
151
+ assert nx.node_clique_number(G, cliques=self.cl) == {
152
+ 1: 4,
153
+ 2: 4,
154
+ 3: 4,
155
+ 4: 3,
156
+ 5: 3,
157
+ 6: 4,
158
+ 7: 3,
159
+ 8: 2,
160
+ 9: 2,
161
+ 10: 2,
162
+ 11: 2,
163
+ }
164
+ assert nx.node_clique_number(G, [1, 2], cliques=self.cl) == {1: 4, 2: 4}
165
+ assert nx.node_clique_number(G, 1, cliques=self.cl) == 4
166
+
167
+ def test_make_clique_bipartite(self):
168
+ G = self.G
169
+ B = nx.make_clique_bipartite(G)
170
+ assert sorted(B) == [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
171
+ # Project onto the nodes of the original graph.
172
+ H = nx.projected_graph(B, range(1, 12))
173
+ assert H.adj == G.adj
174
+ # Project onto the nodes representing the cliques.
175
+ H1 = nx.projected_graph(B, range(-5, 0))
176
+ # Relabel the negative numbers as positive ones.
177
+ H1 = nx.relabel_nodes(H1, {-v: v for v in range(1, 6)})
178
+ assert sorted(H1) == [1, 2, 3, 4, 5]
179
+
180
+ def test_make_max_clique_graph(self):
181
+ """Tests that the maximal clique graph is the same as the bipartite
182
+ clique graph after being projected onto the nodes representing the
183
+ cliques.
184
+
185
+ """
186
+ G = self.G
187
+ B = nx.make_clique_bipartite(G)
188
+ # Project onto the nodes representing the cliques.
189
+ H1 = nx.projected_graph(B, range(-5, 0))
190
+ # Relabel the negative numbers as nonnegative ones, starting at
191
+ # 0.
192
+ H1 = nx.relabel_nodes(H1, {-v: v - 1 for v in range(1, 6)})
193
+ H2 = nx.make_max_clique_graph(G)
194
+ assert H1.adj == H2.adj
195
+
196
+ def test_directed(self):
197
+ with pytest.raises(nx.NetworkXNotImplemented):
198
+ next(nx.find_cliques(nx.DiGraph()))
199
+
200
+ def test_find_cliques_trivial(self):
201
+ G = nx.Graph()
202
+ assert sorted(nx.find_cliques(G)) == []
203
+ assert sorted(nx.find_cliques_recursive(G)) == []
204
+
205
+ def test_make_max_clique_graph_create_using(self):
206
+ G = nx.Graph([(1, 2), (3, 1), (4, 1), (5, 6)])
207
+ E = nx.Graph([(0, 1), (0, 2), (1, 2)])
208
+ E.add_node(3)
209
+ assert nx.is_isomorphic(nx.make_max_clique_graph(G, create_using=nx.Graph), E)
210
+
211
+
212
+ class TestEnumerateAllCliques:
213
+ def test_paper_figure_4(self):
214
+ # Same graph as given in Fig. 4 of paper enumerate_all_cliques is
215
+ # based on.
216
+ # http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1559964&isnumber=33129
217
+ G = nx.Graph()
218
+ edges_fig_4 = [
219
+ ("a", "b"),
220
+ ("a", "c"),
221
+ ("a", "d"),
222
+ ("a", "e"),
223
+ ("b", "c"),
224
+ ("b", "d"),
225
+ ("b", "e"),
226
+ ("c", "d"),
227
+ ("c", "e"),
228
+ ("d", "e"),
229
+ ("f", "b"),
230
+ ("f", "c"),
231
+ ("f", "g"),
232
+ ("g", "f"),
233
+ ("g", "c"),
234
+ ("g", "d"),
235
+ ("g", "e"),
236
+ ]
237
+ G.add_edges_from(edges_fig_4)
238
+
239
+ cliques = list(nx.enumerate_all_cliques(G))
240
+ clique_sizes = list(map(len, cliques))
241
+ assert sorted(clique_sizes) == clique_sizes
242
+
243
+ expected_cliques = [
244
+ ["a"],
245
+ ["b"],
246
+ ["c"],
247
+ ["d"],
248
+ ["e"],
249
+ ["f"],
250
+ ["g"],
251
+ ["a", "b"],
252
+ ["a", "b", "d"],
253
+ ["a", "b", "d", "e"],
254
+ ["a", "b", "e"],
255
+ ["a", "c"],
256
+ ["a", "c", "d"],
257
+ ["a", "c", "d", "e"],
258
+ ["a", "c", "e"],
259
+ ["a", "d"],
260
+ ["a", "d", "e"],
261
+ ["a", "e"],
262
+ ["b", "c"],
263
+ ["b", "c", "d"],
264
+ ["b", "c", "d", "e"],
265
+ ["b", "c", "e"],
266
+ ["b", "c", "f"],
267
+ ["b", "d"],
268
+ ["b", "d", "e"],
269
+ ["b", "e"],
270
+ ["b", "f"],
271
+ ["c", "d"],
272
+ ["c", "d", "e"],
273
+ ["c", "d", "e", "g"],
274
+ ["c", "d", "g"],
275
+ ["c", "e"],
276
+ ["c", "e", "g"],
277
+ ["c", "f"],
278
+ ["c", "f", "g"],
279
+ ["c", "g"],
280
+ ["d", "e"],
281
+ ["d", "e", "g"],
282
+ ["d", "g"],
283
+ ["e", "g"],
284
+ ["f", "g"],
285
+ ["a", "b", "c"],
286
+ ["a", "b", "c", "d"],
287
+ ["a", "b", "c", "d", "e"],
288
+ ["a", "b", "c", "e"],
289
+ ]
290
+
291
+ assert sorted(map(sorted, cliques)) == sorted(map(sorted, expected_cliques))
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_cluster.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestTriangles:
7
+ def test_empty(self):
8
+ G = nx.Graph()
9
+ assert list(nx.triangles(G).values()) == []
10
+
11
+ def test_path(self):
12
+ G = nx.path_graph(10)
13
+ assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
14
+ assert nx.triangles(G) == {
15
+ 0: 0,
16
+ 1: 0,
17
+ 2: 0,
18
+ 3: 0,
19
+ 4: 0,
20
+ 5: 0,
21
+ 6: 0,
22
+ 7: 0,
23
+ 8: 0,
24
+ 9: 0,
25
+ }
26
+
27
+ def test_cubical(self):
28
+ G = nx.cubical_graph()
29
+ assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
30
+ assert nx.triangles(G, 1) == 0
31
+ assert list(nx.triangles(G, [1, 2]).values()) == [0, 0]
32
+ assert nx.triangles(G, 1) == 0
33
+ assert nx.triangles(G, [1, 2]) == {1: 0, 2: 0}
34
+
35
+ def test_k5(self):
36
+ G = nx.complete_graph(5)
37
+ assert list(nx.triangles(G).values()) == [6, 6, 6, 6, 6]
38
+ assert sum(nx.triangles(G).values()) / 3 == 10
39
+ assert nx.triangles(G, 1) == 6
40
+ G.remove_edge(1, 2)
41
+ assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
42
+ assert nx.triangles(G, 1) == 3
43
+ G.add_edge(3, 3) # ignore self-edges
44
+ assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
45
+ assert nx.triangles(G, 3) == 5
46
+
47
+
48
+ class TestDirectedClustering:
49
+ def test_clustering(self):
50
+ G = nx.DiGraph()
51
+ assert list(nx.clustering(G).values()) == []
52
+ assert nx.clustering(G) == {}
53
+
54
+ def test_path(self):
55
+ G = nx.path_graph(10, create_using=nx.DiGraph())
56
+ assert list(nx.clustering(G).values()) == [
57
+ 0,
58
+ 0,
59
+ 0,
60
+ 0,
61
+ 0,
62
+ 0,
63
+ 0,
64
+ 0,
65
+ 0,
66
+ 0,
67
+ ]
68
+ assert nx.clustering(G) == {
69
+ 0: 0,
70
+ 1: 0,
71
+ 2: 0,
72
+ 3: 0,
73
+ 4: 0,
74
+ 5: 0,
75
+ 6: 0,
76
+ 7: 0,
77
+ 8: 0,
78
+ 9: 0,
79
+ }
80
+ assert nx.clustering(G, 0) == 0
81
+
82
+ def test_k5(self):
83
+ G = nx.complete_graph(5, create_using=nx.DiGraph())
84
+ assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
85
+ assert nx.average_clustering(G) == 1
86
+ G.remove_edge(1, 2)
87
+ assert list(nx.clustering(G).values()) == [
88
+ 11 / 12,
89
+ 1,
90
+ 1,
91
+ 11 / 12,
92
+ 11 / 12,
93
+ ]
94
+ assert nx.clustering(G, [1, 4]) == {1: 1, 4: 11 / 12}
95
+ G.remove_edge(2, 1)
96
+ assert list(nx.clustering(G).values()) == [
97
+ 5 / 6,
98
+ 1,
99
+ 1,
100
+ 5 / 6,
101
+ 5 / 6,
102
+ ]
103
+ assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
104
+ assert nx.clustering(G, 4) == 5 / 6
105
+
106
+ def test_triangle_and_edge(self):
107
+ G = nx.cycle_graph(3, create_using=nx.DiGraph())
108
+ G.add_edge(0, 4)
109
+ assert nx.clustering(G)[0] == 1 / 6
110
+
111
+
112
+ class TestDirectedWeightedClustering:
113
+ @classmethod
114
+ def setup_class(cls):
115
+ global np
116
+ np = pytest.importorskip("numpy")
117
+
118
+ def test_clustering(self):
119
+ G = nx.DiGraph()
120
+ assert list(nx.clustering(G, weight="weight").values()) == []
121
+ assert nx.clustering(G) == {}
122
+
123
+ def test_path(self):
124
+ G = nx.path_graph(10, create_using=nx.DiGraph())
125
+ assert list(nx.clustering(G, weight="weight").values()) == [
126
+ 0,
127
+ 0,
128
+ 0,
129
+ 0,
130
+ 0,
131
+ 0,
132
+ 0,
133
+ 0,
134
+ 0,
135
+ 0,
136
+ ]
137
+ assert nx.clustering(G, weight="weight") == {
138
+ 0: 0,
139
+ 1: 0,
140
+ 2: 0,
141
+ 3: 0,
142
+ 4: 0,
143
+ 5: 0,
144
+ 6: 0,
145
+ 7: 0,
146
+ 8: 0,
147
+ 9: 0,
148
+ }
149
+
150
+ def test_k5(self):
151
+ G = nx.complete_graph(5, create_using=nx.DiGraph())
152
+ assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
153
+ assert nx.average_clustering(G, weight="weight") == 1
154
+ G.remove_edge(1, 2)
155
+ assert list(nx.clustering(G, weight="weight").values()) == [
156
+ 11 / 12,
157
+ 1,
158
+ 1,
159
+ 11 / 12,
160
+ 11 / 12,
161
+ ]
162
+ assert nx.clustering(G, [1, 4], weight="weight") == {1: 1, 4: 11 / 12}
163
+ G.remove_edge(2, 1)
164
+ assert list(nx.clustering(G, weight="weight").values()) == [
165
+ 5 / 6,
166
+ 1,
167
+ 1,
168
+ 5 / 6,
169
+ 5 / 6,
170
+ ]
171
+ assert nx.clustering(G, [1, 4], weight="weight") == {
172
+ 1: 1,
173
+ 4: 0.83333333333333337,
174
+ }
175
+
176
+ def test_triangle_and_edge(self):
177
+ G = nx.cycle_graph(3, create_using=nx.DiGraph())
178
+ G.add_edge(0, 4, weight=2)
179
+ assert nx.clustering(G)[0] == 1 / 6
180
+ # Relaxed comparisons to allow graphblas-algorithms to pass tests
181
+ np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 12)
182
+ np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 12)
183
+
184
+
185
+ class TestWeightedClustering:
186
+ @classmethod
187
+ def setup_class(cls):
188
+ global np
189
+ np = pytest.importorskip("numpy")
190
+
191
+ def test_clustering(self):
192
+ G = nx.Graph()
193
+ assert list(nx.clustering(G, weight="weight").values()) == []
194
+ assert nx.clustering(G) == {}
195
+
196
+ def test_path(self):
197
+ G = nx.path_graph(10)
198
+ assert list(nx.clustering(G, weight="weight").values()) == [
199
+ 0,
200
+ 0,
201
+ 0,
202
+ 0,
203
+ 0,
204
+ 0,
205
+ 0,
206
+ 0,
207
+ 0,
208
+ 0,
209
+ ]
210
+ assert nx.clustering(G, weight="weight") == {
211
+ 0: 0,
212
+ 1: 0,
213
+ 2: 0,
214
+ 3: 0,
215
+ 4: 0,
216
+ 5: 0,
217
+ 6: 0,
218
+ 7: 0,
219
+ 8: 0,
220
+ 9: 0,
221
+ }
222
+
223
+ def test_cubical(self):
224
+ G = nx.cubical_graph()
225
+ assert list(nx.clustering(G, weight="weight").values()) == [
226
+ 0,
227
+ 0,
228
+ 0,
229
+ 0,
230
+ 0,
231
+ 0,
232
+ 0,
233
+ 0,
234
+ ]
235
+ assert nx.clustering(G, 1) == 0
236
+ assert list(nx.clustering(G, [1, 2], weight="weight").values()) == [0, 0]
237
+ assert nx.clustering(G, 1, weight="weight") == 0
238
+ assert nx.clustering(G, [1, 2], weight="weight") == {1: 0, 2: 0}
239
+
240
+ def test_k5(self):
241
+ G = nx.complete_graph(5)
242
+ assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
243
+ assert nx.average_clustering(G, weight="weight") == 1
244
+ G.remove_edge(1, 2)
245
+ assert list(nx.clustering(G, weight="weight").values()) == [
246
+ 5 / 6,
247
+ 1,
248
+ 1,
249
+ 5 / 6,
250
+ 5 / 6,
251
+ ]
252
+ assert nx.clustering(G, [1, 4], weight="weight") == {
253
+ 1: 1,
254
+ 4: 0.83333333333333337,
255
+ }
256
+
257
+ def test_triangle_and_edge(self):
258
+ G = nx.cycle_graph(3)
259
+ G.add_edge(0, 4, weight=2)
260
+ assert nx.clustering(G)[0] == 1 / 3
261
+ np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 6)
262
+ np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 6)
263
+
264
+ def test_triangle_and_signed_edge(self):
265
+ G = nx.cycle_graph(3)
266
+ G.add_edge(0, 1, weight=-1)
267
+ G.add_edge(3, 0, weight=0)
268
+ assert nx.clustering(G)[0] == 1 / 3
269
+ assert nx.clustering(G, weight="weight")[0] == -1 / 3
270
+
271
+
272
+ class TestClustering:
273
+ @classmethod
274
+ def setup_class(cls):
275
+ pytest.importorskip("numpy")
276
+
277
+ def test_clustering(self):
278
+ G = nx.Graph()
279
+ assert list(nx.clustering(G).values()) == []
280
+ assert nx.clustering(G) == {}
281
+
282
+ def test_path(self):
283
+ G = nx.path_graph(10)
284
+ assert list(nx.clustering(G).values()) == [
285
+ 0,
286
+ 0,
287
+ 0,
288
+ 0,
289
+ 0,
290
+ 0,
291
+ 0,
292
+ 0,
293
+ 0,
294
+ 0,
295
+ ]
296
+ assert nx.clustering(G) == {
297
+ 0: 0,
298
+ 1: 0,
299
+ 2: 0,
300
+ 3: 0,
301
+ 4: 0,
302
+ 5: 0,
303
+ 6: 0,
304
+ 7: 0,
305
+ 8: 0,
306
+ 9: 0,
307
+ }
308
+
309
+ def test_cubical(self):
310
+ G = nx.cubical_graph()
311
+ assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
312
+ assert nx.clustering(G, 1) == 0
313
+ assert list(nx.clustering(G, [1, 2]).values()) == [0, 0]
314
+ assert nx.clustering(G, 1) == 0
315
+ assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0}
316
+
317
+ def test_k5(self):
318
+ G = nx.complete_graph(5)
319
+ assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
320
+ assert nx.average_clustering(G) == 1
321
+ G.remove_edge(1, 2)
322
+ assert list(nx.clustering(G).values()) == [
323
+ 5 / 6,
324
+ 1,
325
+ 1,
326
+ 5 / 6,
327
+ 5 / 6,
328
+ ]
329
+ assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
330
+
331
+ def test_k5_signed(self):
332
+ G = nx.complete_graph(5)
333
+ assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
334
+ assert nx.average_clustering(G) == 1
335
+ G.remove_edge(1, 2)
336
+ G.add_edge(0, 1, weight=-1)
337
+ assert list(nx.clustering(G, weight="weight").values()) == [
338
+ 1 / 6,
339
+ -1 / 3,
340
+ 1,
341
+ 3 / 6,
342
+ 3 / 6,
343
+ ]
344
+
345
+
346
+ class TestTransitivity:
347
+ def test_transitivity(self):
348
+ G = nx.Graph()
349
+ assert nx.transitivity(G) == 0
350
+
351
+ def test_path(self):
352
+ G = nx.path_graph(10)
353
+ assert nx.transitivity(G) == 0
354
+
355
+ def test_cubical(self):
356
+ G = nx.cubical_graph()
357
+ assert nx.transitivity(G) == 0
358
+
359
+ def test_k5(self):
360
+ G = nx.complete_graph(5)
361
+ assert nx.transitivity(G) == 1
362
+ G.remove_edge(1, 2)
363
+ assert nx.transitivity(G) == 0.875
364
+
365
+
366
+ class TestSquareClustering:
367
+ def test_clustering(self):
368
+ G = nx.Graph()
369
+ assert list(nx.square_clustering(G).values()) == []
370
+ assert nx.square_clustering(G) == {}
371
+
372
+ def test_path(self):
373
+ G = nx.path_graph(10)
374
+ assert list(nx.square_clustering(G).values()) == [
375
+ 0,
376
+ 0,
377
+ 0,
378
+ 0,
379
+ 0,
380
+ 0,
381
+ 0,
382
+ 0,
383
+ 0,
384
+ 0,
385
+ ]
386
+ assert nx.square_clustering(G) == {
387
+ 0: 0,
388
+ 1: 0,
389
+ 2: 0,
390
+ 3: 0,
391
+ 4: 0,
392
+ 5: 0,
393
+ 6: 0,
394
+ 7: 0,
395
+ 8: 0,
396
+ 9: 0,
397
+ }
398
+
399
+ def test_cubical(self):
400
+ G = nx.cubical_graph()
401
+ assert list(nx.square_clustering(G).values()) == [
402
+ 1 / 3,
403
+ 1 / 3,
404
+ 1 / 3,
405
+ 1 / 3,
406
+ 1 / 3,
407
+ 1 / 3,
408
+ 1 / 3,
409
+ 1 / 3,
410
+ ]
411
+ assert list(nx.square_clustering(G, [1, 2]).values()) == [1 / 3, 1 / 3]
412
+ assert nx.square_clustering(G, [1])[1] == 1 / 3
413
+ assert nx.square_clustering(G, 1) == 1 / 3
414
+ assert nx.square_clustering(G, [1, 2]) == {1: 1 / 3, 2: 1 / 3}
415
+
416
+ def test_k5(self):
417
+ G = nx.complete_graph(5)
418
+ assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1]
419
+
420
+ def test_bipartite_k5(self):
421
+ G = nx.complete_bipartite_graph(5, 5)
422
+ assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
423
+
424
+ def test_lind_square_clustering(self):
425
+ """Test C4 for figure 1 Lind et al (2005)"""
426
+ G = nx.Graph(
427
+ [
428
+ (1, 2),
429
+ (1, 3),
430
+ (1, 6),
431
+ (1, 7),
432
+ (2, 4),
433
+ (2, 5),
434
+ (3, 4),
435
+ (3, 5),
436
+ (6, 7),
437
+ (7, 8),
438
+ (6, 8),
439
+ (7, 9),
440
+ (7, 10),
441
+ (6, 11),
442
+ (6, 12),
443
+ (2, 13),
444
+ (2, 14),
445
+ (3, 15),
446
+ (3, 16),
447
+ ]
448
+ )
449
+ G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16])
450
+ G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12])
451
+ assert nx.square_clustering(G, [1])[1] == 3 / 43
452
+ assert nx.square_clustering(G1, [1])[1] == 2 / 6
453
+ assert nx.square_clustering(G2, [1])[1] == 1 / 5
454
+
455
+ def test_peng_square_clustering(self):
456
+ """Test eq2 for figure 1 Peng et al (2008)"""
457
+ G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (3, 6)])
458
+ assert nx.square_clustering(G, [1])[1] == 1 / 3
459
+
460
+ def test_self_loops_square_clustering(self):
461
+ G = nx.path_graph(5)
462
+ assert nx.square_clustering(G) == {0: 0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0}
463
+ G.add_edges_from([(0, 0), (1, 1), (2, 2)])
464
+ assert nx.square_clustering(G) == {0: 1, 1: 0.5, 2: 0.2, 3: 0.0, 4: 0}
465
+
466
+
467
+ class TestAverageClustering:
468
+ @classmethod
469
+ def setup_class(cls):
470
+ pytest.importorskip("numpy")
471
+
472
+ def test_empty(self):
473
+ G = nx.Graph()
474
+ with pytest.raises(ZeroDivisionError):
475
+ nx.average_clustering(G)
476
+
477
+ def test_average_clustering(self):
478
+ G = nx.cycle_graph(3)
479
+ G.add_edge(2, 3)
480
+ assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 4
481
+ assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 4
482
+ assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 3
483
+ assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 3
484
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 3
485
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 2
486
+
487
+ def test_average_clustering_signed(self):
488
+ G = nx.cycle_graph(3)
489
+ G.add_edge(2, 3)
490
+ G.add_edge(0, 1, weight=-1)
491
+ assert nx.average_clustering(G, weight="weight") == (-1 - 1 - 1 / 3) / 4
492
+ assert (
493
+ nx.average_clustering(G, weight="weight", count_zeros=True)
494
+ == (-1 - 1 - 1 / 3) / 4
495
+ )
496
+ assert (
497
+ nx.average_clustering(G, weight="weight", count_zeros=False)
498
+ == (-1 - 1 - 1 / 3) / 3
499
+ )
500
+
501
+
502
+ class TestDirectedAverageClustering:
503
+ @classmethod
504
+ def setup_class(cls):
505
+ pytest.importorskip("numpy")
506
+
507
+ def test_empty(self):
508
+ G = nx.DiGraph()
509
+ with pytest.raises(ZeroDivisionError):
510
+ nx.average_clustering(G)
511
+
512
+ def test_average_clustering(self):
513
+ G = nx.cycle_graph(3, create_using=nx.DiGraph())
514
+ G.add_edge(2, 3)
515
+ assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 8
516
+ assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 8
517
+ assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 6
518
+ assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 6
519
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 6
520
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 4
521
+
522
+
523
+ class TestGeneralizedDegree:
524
+ def test_generalized_degree(self):
525
+ G = nx.Graph()
526
+ assert nx.generalized_degree(G) == {}
527
+
528
+ def test_path(self):
529
+ G = nx.path_graph(5)
530
+ assert nx.generalized_degree(G, 0) == {0: 1}
531
+ assert nx.generalized_degree(G, 1) == {0: 2}
532
+
533
+ def test_cubical(self):
534
+ G = nx.cubical_graph()
535
+ assert nx.generalized_degree(G, 0) == {0: 3}
536
+
537
+ def test_k5(self):
538
+ G = nx.complete_graph(5)
539
+ assert nx.generalized_degree(G, 0) == {3: 4}
540
+ G.remove_edge(0, 1)
541
+ assert nx.generalized_degree(G, 0) == {2: 3}
542
+ assert nx.generalized_degree(G, [1, 2]) == {1: {2: 3}, 2: {2: 2, 3: 2}}
543
+ assert nx.generalized_degree(G) == {
544
+ 0: {2: 3},
545
+ 1: {2: 3},
546
+ 2: {2: 2, 3: 2},
547
+ 3: {2: 2, 3: 2},
548
+ 4: {2: 2, 3: 2},
549
+ }
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import pytest
4
+
5
+ pytest.importorskip("numpy")
6
+ pytest.importorskip("scipy")
7
+
8
+ import networkx as nx
9
+ from networkx.algorithms.communicability_alg import communicability, communicability_exp
10
+
11
+
12
+ class TestCommunicability:
13
+ def test_communicability(self):
14
+ answer = {
15
+ 0: {0: 1.5430806348152435, 1: 1.1752011936438012},
16
+ 1: {0: 1.1752011936438012, 1: 1.5430806348152435},
17
+ }
18
+ # answer={(0, 0): 1.5430806348152435,
19
+ # (0, 1): 1.1752011936438012,
20
+ # (1, 0): 1.1752011936438012,
21
+ # (1, 1): 1.5430806348152435}
22
+
23
+ result = communicability(nx.path_graph(2))
24
+ for k1, val in result.items():
25
+ for k2 in val:
26
+ assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
27
+
28
+ def test_communicability2(self):
29
+ answer_orig = {
30
+ ("1", "1"): 1.6445956054135658,
31
+ ("1", "Albert"): 0.7430186221096251,
32
+ ("1", "Aric"): 0.7430186221096251,
33
+ ("1", "Dan"): 1.6208126320442937,
34
+ ("1", "Franck"): 0.42639707170035257,
35
+ ("Albert", "1"): 0.7430186221096251,
36
+ ("Albert", "Albert"): 2.4368257358712189,
37
+ ("Albert", "Aric"): 1.4368257358712191,
38
+ ("Albert", "Dan"): 2.0472097037446453,
39
+ ("Albert", "Franck"): 1.8340111678944691,
40
+ ("Aric", "1"): 0.7430186221096251,
41
+ ("Aric", "Albert"): 1.4368257358712191,
42
+ ("Aric", "Aric"): 2.4368257358712193,
43
+ ("Aric", "Dan"): 2.0472097037446457,
44
+ ("Aric", "Franck"): 1.8340111678944691,
45
+ ("Dan", "1"): 1.6208126320442937,
46
+ ("Dan", "Albert"): 2.0472097037446453,
47
+ ("Dan", "Aric"): 2.0472097037446457,
48
+ ("Dan", "Dan"): 3.1306328496328168,
49
+ ("Dan", "Franck"): 1.4860372442192515,
50
+ ("Franck", "1"): 0.42639707170035257,
51
+ ("Franck", "Albert"): 1.8340111678944691,
52
+ ("Franck", "Aric"): 1.8340111678944691,
53
+ ("Franck", "Dan"): 1.4860372442192515,
54
+ ("Franck", "Franck"): 2.3876142275231915,
55
+ }
56
+
57
+ answer = defaultdict(dict)
58
+ for (k1, k2), v in answer_orig.items():
59
+ answer[k1][k2] = v
60
+
61
+ G1 = nx.Graph(
62
+ [
63
+ ("Franck", "Aric"),
64
+ ("Aric", "Dan"),
65
+ ("Dan", "Albert"),
66
+ ("Albert", "Franck"),
67
+ ("Dan", "1"),
68
+ ("Franck", "Albert"),
69
+ ]
70
+ )
71
+
72
+ result = communicability(G1)
73
+ for k1, val in result.items():
74
+ for k2 in val:
75
+ assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
76
+
77
+ result = communicability_exp(G1)
78
+ for k1, val in result.items():
79
+ for k2 in val:
80
+ assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_core.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import nodes_equal
5
+
6
+
7
+ class TestCore:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ # G is the example graph in Figure 1 from Batagelj and
11
+ # Zaversnik's paper titled An O(m) Algorithm for Cores
12
+ # Decomposition of Networks, 2003,
13
+ # http://arXiv.org/abs/cs/0310049. With nodes labeled as
14
+ # shown, the 3-core is given by nodes 1-8, the 2-core by nodes
15
+ # 9-16, the 1-core by nodes 17-20 and node 21 is in the
16
+ # 0-core.
17
+ t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1)
18
+ t2 = nx.convert_node_labels_to_integers(t1, 5)
19
+ G = nx.union(t1, t2)
20
+ G.add_edges_from(
21
+ [
22
+ (3, 7),
23
+ (2, 11),
24
+ (11, 5),
25
+ (11, 12),
26
+ (5, 12),
27
+ (12, 19),
28
+ (12, 18),
29
+ (3, 9),
30
+ (7, 9),
31
+ (7, 10),
32
+ (9, 10),
33
+ (9, 20),
34
+ (17, 13),
35
+ (13, 14),
36
+ (14, 15),
37
+ (15, 16),
38
+ (16, 13),
39
+ ]
40
+ )
41
+ G.add_node(21)
42
+ cls.G = G
43
+
44
+ # Create the graph H resulting from the degree sequence
45
+ # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm.
46
+
47
+ degseq = [0, 1, 2, 2, 2, 2, 3]
48
+ H = nx.havel_hakimi_graph(degseq)
49
+ mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5}
50
+ cls.H = nx.relabel_nodes(H, mapping)
51
+
52
+ def test_trivial(self):
53
+ """Empty graph"""
54
+ G = nx.Graph()
55
+ assert nx.core_number(G) == {}
56
+
57
+ def test_core_number(self):
58
+ core = nx.core_number(self.G)
59
+ nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(4)]
60
+ assert nodes_equal(nodes_by_core[0], [21])
61
+ assert nodes_equal(nodes_by_core[1], [17, 18, 19, 20])
62
+ assert nodes_equal(nodes_by_core[2], [9, 10, 11, 12, 13, 14, 15, 16])
63
+ assert nodes_equal(nodes_by_core[3], [1, 2, 3, 4, 5, 6, 7, 8])
64
+
65
+ def test_core_number2(self):
66
+ core = nx.core_number(self.H)
67
+ nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(3)]
68
+ assert nodes_equal(nodes_by_core[0], [0])
69
+ assert nodes_equal(nodes_by_core[1], [1, 3])
70
+ assert nodes_equal(nodes_by_core[2], [2, 4, 5, 6])
71
+
72
+ def test_core_number_multigraph(self):
73
+ G = nx.complete_graph(3)
74
+ G = nx.MultiGraph(G)
75
+ G.add_edge(1, 2)
76
+ with pytest.raises(
77
+ nx.NetworkXNotImplemented, match="not implemented for multigraph type"
78
+ ):
79
+ nx.core_number(G)
80
+
81
+ def test_core_number_self_loop(self):
82
+ G = nx.cycle_graph(3)
83
+ G.add_edge(0, 0)
84
+ with pytest.raises(
85
+ nx.NetworkXNotImplemented, match="Input graph has self loops"
86
+ ):
87
+ nx.core_number(G)
88
+
89
+ def test_directed_core_number(self):
90
+ """core number had a bug for directed graphs found in issue #1959"""
91
+ # small example where too timid edge removal can make cn[2] = 3
92
+ G = nx.DiGraph()
93
+ edges = [(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)]
94
+ G.add_edges_from(edges)
95
+ assert nx.core_number(G) == {1: 2, 2: 2, 3: 2, 4: 2}
96
+ # small example where too aggressive edge removal can make cn[2] = 2
97
+ more_edges = [(1, 5), (3, 5), (4, 5), (3, 6), (4, 6), (5, 6)]
98
+ G.add_edges_from(more_edges)
99
+ assert nx.core_number(G) == {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3}
100
+
101
+ def test_main_core(self):
102
+ main_core_subgraph = nx.k_core(self.H)
103
+ assert sorted(main_core_subgraph.nodes()) == [2, 4, 5, 6]
104
+
105
+ def test_k_core(self):
106
+ # k=0
107
+ k_core_subgraph = nx.k_core(self.H, k=0)
108
+ assert sorted(k_core_subgraph.nodes()) == sorted(self.H.nodes())
109
+ # k=1
110
+ k_core_subgraph = nx.k_core(self.H, k=1)
111
+ assert sorted(k_core_subgraph.nodes()) == [1, 2, 3, 4, 5, 6]
112
+ # k = 2
113
+ k_core_subgraph = nx.k_core(self.H, k=2)
114
+ assert sorted(k_core_subgraph.nodes()) == [2, 4, 5, 6]
115
+
116
+ def test_k_core_multigraph(self):
117
+ core_number = nx.core_number(self.H)
118
+ H = nx.MultiGraph(self.H)
119
+ with pytest.deprecated_call():
120
+ nx.k_core(H, k=0, core_number=core_number)
121
+
122
+ def test_main_crust(self):
123
+ main_crust_subgraph = nx.k_crust(self.H)
124
+ assert sorted(main_crust_subgraph.nodes()) == [0, 1, 3]
125
+
126
+ def test_k_crust(self):
127
+ # k = 0
128
+ k_crust_subgraph = nx.k_crust(self.H, k=2)
129
+ assert sorted(k_crust_subgraph.nodes()) == sorted(self.H.nodes())
130
+ # k=1
131
+ k_crust_subgraph = nx.k_crust(self.H, k=1)
132
+ assert sorted(k_crust_subgraph.nodes()) == [0, 1, 3]
133
+ # k=2
134
+ k_crust_subgraph = nx.k_crust(self.H, k=0)
135
+ assert sorted(k_crust_subgraph.nodes()) == [0]
136
+
137
+ def test_k_crust_multigraph(self):
138
+ core_number = nx.core_number(self.H)
139
+ H = nx.MultiGraph(self.H)
140
+ with pytest.deprecated_call():
141
+ nx.k_crust(H, k=0, core_number=core_number)
142
+
143
+ def test_main_shell(self):
144
+ main_shell_subgraph = nx.k_shell(self.H)
145
+ assert sorted(main_shell_subgraph.nodes()) == [2, 4, 5, 6]
146
+
147
+ def test_k_shell(self):
148
+ # k=0
149
+ k_shell_subgraph = nx.k_shell(self.H, k=2)
150
+ assert sorted(k_shell_subgraph.nodes()) == [2, 4, 5, 6]
151
+ # k=1
152
+ k_shell_subgraph = nx.k_shell(self.H, k=1)
153
+ assert sorted(k_shell_subgraph.nodes()) == [1, 3]
154
+ # k=2
155
+ k_shell_subgraph = nx.k_shell(self.H, k=0)
156
+ assert sorted(k_shell_subgraph.nodes()) == [0]
157
+
158
+ def test_k_shell_multigraph(self):
159
+ core_number = nx.core_number(self.H)
160
+ H = nx.MultiGraph(self.H)
161
+ with pytest.deprecated_call():
162
+ nx.k_shell(H, k=0, core_number=core_number)
163
+
164
+ def test_k_corona(self):
165
+ # k=0
166
+ k_corona_subgraph = nx.k_corona(self.H, k=2)
167
+ assert sorted(k_corona_subgraph.nodes()) == [2, 4, 5, 6]
168
+ # k=1
169
+ k_corona_subgraph = nx.k_corona(self.H, k=1)
170
+ assert sorted(k_corona_subgraph.nodes()) == [1]
171
+ # k=2
172
+ k_corona_subgraph = nx.k_corona(self.H, k=0)
173
+ assert sorted(k_corona_subgraph.nodes()) == [0]
174
+
175
+ def test_k_corona_multigraph(self):
176
+ core_number = nx.core_number(self.H)
177
+ H = nx.MultiGraph(self.H)
178
+ with pytest.deprecated_call():
179
+ nx.k_corona(H, k=0, core_number=core_number)
180
+
181
+ def test_k_truss(self):
182
+ # k=-1
183
+ k_truss_subgraph = nx.k_truss(self.G, -1)
184
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
185
+ # k=0
186
+ k_truss_subgraph = nx.k_truss(self.G, 0)
187
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
188
+ # k=1
189
+ k_truss_subgraph = nx.k_truss(self.G, 1)
190
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
191
+ # k=2
192
+ k_truss_subgraph = nx.k_truss(self.G, 2)
193
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
194
+ # k=3
195
+ k_truss_subgraph = nx.k_truss(self.G, 3)
196
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 13))
197
+
198
+ k_truss_subgraph = nx.k_truss(self.G, 4)
199
+ assert sorted(k_truss_subgraph.nodes()) == list(range(1, 9))
200
+
201
+ k_truss_subgraph = nx.k_truss(self.G, 5)
202
+ assert sorted(k_truss_subgraph.nodes()) == []
203
+
204
+ def test_k_truss_digraph(self):
205
+ G = nx.complete_graph(3)
206
+ G = nx.DiGraph(G)
207
+ G.add_edge(2, 1)
208
+ with pytest.raises(
209
+ nx.NetworkXNotImplemented, match="not implemented for directed type"
210
+ ):
211
+ nx.k_truss(G, k=1)
212
+
213
+ def test_k_truss_multigraph(self):
214
+ G = nx.complete_graph(3)
215
+ G = nx.MultiGraph(G)
216
+ G.add_edge(1, 2)
217
+ with pytest.raises(
218
+ nx.NetworkXNotImplemented, match="not implemented for multigraph type"
219
+ ):
220
+ nx.k_truss(G, k=1)
221
+
222
+ def test_k_truss_self_loop(self):
223
+ G = nx.cycle_graph(3)
224
+ G.add_edge(0, 0)
225
+ with pytest.raises(
226
+ nx.NetworkXNotImplemented, match="Input graph has self loops"
227
+ ):
228
+ nx.k_truss(G, k=1)
229
+
230
+ def test_onion_layers(self):
231
+ layers = nx.onion_layers(self.G)
232
+ nodes_by_layer = [
233
+ sorted(n for n in layers if layers[n] == val) for val in range(1, 7)
234
+ ]
235
+ assert nodes_equal(nodes_by_layer[0], [21])
236
+ assert nodes_equal(nodes_by_layer[1], [17, 18, 19, 20])
237
+ assert nodes_equal(nodes_by_layer[2], [10, 12, 13, 14, 15, 16])
238
+ assert nodes_equal(nodes_by_layer[3], [9, 11])
239
+ assert nodes_equal(nodes_by_layer[4], [1, 2, 4, 5, 6, 8])
240
+ assert nodes_equal(nodes_by_layer[5], [3, 7])
241
+
242
+ def test_onion_digraph(self):
243
+ G = nx.complete_graph(3)
244
+ G = nx.DiGraph(G)
245
+ G.add_edge(2, 1)
246
+ with pytest.raises(
247
+ nx.NetworkXNotImplemented, match="not implemented for directed type"
248
+ ):
249
+ nx.onion_layers(G)
250
+
251
+ def test_onion_multigraph(self):
252
+ G = nx.complete_graph(3)
253
+ G = nx.MultiGraph(G)
254
+ G.add_edge(1, 2)
255
+ with pytest.raises(
256
+ nx.NetworkXNotImplemented, match="not implemented for multigraph type"
257
+ ):
258
+ nx.onion_layers(G)
259
+
260
+ def test_onion_self_loop(self):
261
+ G = nx.cycle_graph(3)
262
+ G.add_edge(0, 0)
263
+ with pytest.raises(
264
+ nx.NetworkXNotImplemented, match="Input graph contains self loops"
265
+ ):
266
+ nx.onion_layers(G)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_covering.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestMinEdgeCover:
7
+ """Tests for :func:`networkx.algorithms.min_edge_cover`"""
8
+
9
+ def test_empty_graph(self):
10
+ G = nx.Graph()
11
+ assert nx.min_edge_cover(G) == set()
12
+
13
+ def test_graph_with_loop(self):
14
+ G = nx.Graph()
15
+ G.add_edge(0, 0)
16
+ assert nx.min_edge_cover(G) == {(0, 0)}
17
+
18
+ def test_graph_with_isolated_v(self):
19
+ G = nx.Graph()
20
+ G.add_node(1)
21
+ with pytest.raises(
22
+ nx.NetworkXException,
23
+ match="Graph has a node with no edge incident on it, so no edge cover exists.",
24
+ ):
25
+ nx.min_edge_cover(G)
26
+
27
+ def test_graph_single_edge(self):
28
+ G = nx.Graph([(0, 1)])
29
+ assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
30
+
31
+ def test_graph_two_edge_path(self):
32
+ G = nx.path_graph(3)
33
+ min_cover = nx.min_edge_cover(G)
34
+ assert len(min_cover) == 2
35
+ for u, v in G.edges:
36
+ assert (u, v) in min_cover or (v, u) in min_cover
37
+
38
+ def test_bipartite_explicit(self):
39
+ G = nx.Graph()
40
+ G.add_nodes_from([1, 2, 3, 4], bipartite=0)
41
+ G.add_nodes_from(["a", "b", "c"], bipartite=1)
42
+ G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
43
+ # Use bipartite method by prescribing the algorithm
44
+ min_cover = nx.min_edge_cover(
45
+ G, nx.algorithms.bipartite.matching.eppstein_matching
46
+ )
47
+ assert nx.is_edge_cover(G, min_cover)
48
+ assert len(min_cover) == 8
49
+ # Use the default method which is not specialized for bipartite
50
+ min_cover2 = nx.min_edge_cover(G)
51
+ assert nx.is_edge_cover(G, min_cover2)
52
+ assert len(min_cover2) == 4
53
+
54
+ def test_complete_graph_even(self):
55
+ G = nx.complete_graph(10)
56
+ min_cover = nx.min_edge_cover(G)
57
+ assert nx.is_edge_cover(G, min_cover)
58
+ assert len(min_cover) == 5
59
+
60
+ def test_complete_graph_odd(self):
61
+ G = nx.complete_graph(11)
62
+ min_cover = nx.min_edge_cover(G)
63
+ assert nx.is_edge_cover(G, min_cover)
64
+ assert len(min_cover) == 6
65
+
66
+
67
+ class TestIsEdgeCover:
68
+ """Tests for :func:`networkx.algorithms.is_edge_cover`"""
69
+
70
+ def test_empty_graph(self):
71
+ G = nx.Graph()
72
+ assert nx.is_edge_cover(G, set())
73
+
74
+ def test_graph_with_loop(self):
75
+ G = nx.Graph()
76
+ G.add_edge(1, 1)
77
+ assert nx.is_edge_cover(G, {(1, 1)})
78
+
79
+ def test_graph_single_edge(self):
80
+ G = nx.Graph()
81
+ G.add_edge(0, 1)
82
+ assert nx.is_edge_cover(G, {(0, 0), (1, 1)})
83
+ assert nx.is_edge_cover(G, {(0, 1), (1, 0)})
84
+ assert nx.is_edge_cover(G, {(0, 1)})
85
+ assert not nx.is_edge_cover(G, {(0, 0)})
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.cuts` module."""
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestCutSize:
7
+ """Unit tests for the :func:`~networkx.cut_size` function."""
8
+
9
+ def test_symmetric(self):
10
+ """Tests that the cut size is symmetric."""
11
+ G = nx.barbell_graph(3, 0)
12
+ S = {0, 1, 4}
13
+ T = {2, 3, 5}
14
+ assert nx.cut_size(G, S, T) == 4
15
+ assert nx.cut_size(G, T, S) == 4
16
+
17
+ def test_single_edge(self):
18
+ """Tests for a cut of a single edge."""
19
+ G = nx.barbell_graph(3, 0)
20
+ S = {0, 1, 2}
21
+ T = {3, 4, 5}
22
+ assert nx.cut_size(G, S, T) == 1
23
+ assert nx.cut_size(G, T, S) == 1
24
+
25
+ def test_directed(self):
26
+ """Tests that each directed edge is counted once in the cut."""
27
+ G = nx.barbell_graph(3, 0).to_directed()
28
+ S = {0, 1, 2}
29
+ T = {3, 4, 5}
30
+ assert nx.cut_size(G, S, T) == 2
31
+ assert nx.cut_size(G, T, S) == 2
32
+
33
+ def test_directed_symmetric(self):
34
+ """Tests that a cut in a directed graph is symmetric."""
35
+ G = nx.barbell_graph(3, 0).to_directed()
36
+ S = {0, 1, 4}
37
+ T = {2, 3, 5}
38
+ assert nx.cut_size(G, S, T) == 8
39
+ assert nx.cut_size(G, T, S) == 8
40
+
41
+ def test_multigraph(self):
42
+ """Tests that parallel edges are each counted for a cut."""
43
+ G = nx.MultiGraph(["ab", "ab"])
44
+ assert nx.cut_size(G, {"a"}, {"b"}) == 2
45
+
46
+
47
+ class TestVolume:
48
+ """Unit tests for the :func:`~networkx.volume` function."""
49
+
50
+ def test_graph(self):
51
+ G = nx.cycle_graph(4)
52
+ assert nx.volume(G, {0, 1}) == 4
53
+
54
+ def test_digraph(self):
55
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0)])
56
+ assert nx.volume(G, {0, 1}) == 2
57
+
58
+ def test_multigraph(self):
59
+ edges = list(nx.cycle_graph(4).edges())
60
+ G = nx.MultiGraph(edges * 2)
61
+ assert nx.volume(G, {0, 1}) == 8
62
+
63
+ def test_multidigraph(self):
64
+ edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
65
+ G = nx.MultiDiGraph(edges * 2)
66
+ assert nx.volume(G, {0, 1}) == 4
67
+
68
+ def test_barbell(self):
69
+ G = nx.barbell_graph(3, 0)
70
+ assert nx.volume(G, {0, 1, 2}) == 7
71
+ assert nx.volume(G, {3, 4, 5}) == 7
72
+
73
+
74
+ class TestNormalizedCutSize:
75
+ """Unit tests for the :func:`~networkx.normalized_cut_size` function."""
76
+
77
+ def test_graph(self):
78
+ G = nx.path_graph(4)
79
+ S = {1, 2}
80
+ T = set(G) - S
81
+ size = nx.normalized_cut_size(G, S, T)
82
+ # The cut looks like this: o-{-o--o-}-o
83
+ expected = 2 * ((1 / 4) + (1 / 2))
84
+ assert expected == size
85
+ # Test with no input T
86
+ assert expected == nx.normalized_cut_size(G, S)
87
+
88
+ def test_directed(self):
89
+ G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
90
+ S = {1, 2}
91
+ T = set(G) - S
92
+ size = nx.normalized_cut_size(G, S, T)
93
+ # The cut looks like this: o-{->o-->o-}->o
94
+ expected = 2 * ((1 / 2) + (1 / 1))
95
+ assert expected == size
96
+ # Test with no input T
97
+ assert expected == nx.normalized_cut_size(G, S)
98
+
99
+
100
+ class TestConductance:
101
+ """Unit tests for the :func:`~networkx.conductance` function."""
102
+
103
+ def test_graph(self):
104
+ G = nx.barbell_graph(5, 0)
105
+ # Consider the singleton sets containing the "bridge" nodes.
106
+ # There is only one cut edge, and each set has volume five.
107
+ S = {4}
108
+ T = {5}
109
+ conductance = nx.conductance(G, S, T)
110
+ expected = 1 / 5
111
+ assert expected == conductance
112
+ # Test with no input T
113
+ G2 = nx.barbell_graph(3, 0)
114
+ # There is only one cut edge, and each set has volume seven.
115
+ S2 = {0, 1, 2}
116
+ assert nx.conductance(G2, S2) == 1 / 7
117
+
118
+
119
+ class TestEdgeExpansion:
120
+ """Unit tests for the :func:`~networkx.edge_expansion` function."""
121
+
122
+ def test_graph(self):
123
+ G = nx.barbell_graph(5, 0)
124
+ S = set(range(5))
125
+ T = set(G) - S
126
+ expansion = nx.edge_expansion(G, S, T)
127
+ expected = 1 / 5
128
+ assert expected == expansion
129
+ # Test with no input T
130
+ assert expected == nx.edge_expansion(G, S)
131
+
132
+
133
+ class TestNodeExpansion:
134
+ """Unit tests for the :func:`~networkx.node_expansion` function."""
135
+
136
+ def test_graph(self):
137
+ G = nx.path_graph(8)
138
+ S = {3, 4, 5}
139
+ expansion = nx.node_expansion(G, S)
140
+ # The neighborhood of S has cardinality five, and S has
141
+ # cardinality three.
142
+ expected = 5 / 3
143
+ assert expected == expansion
144
+
145
+
146
+ class TestBoundaryExpansion:
147
+ """Unit tests for the :func:`~networkx.boundary_expansion` function."""
148
+
149
+ def test_graph(self):
150
+ G = nx.complete_graph(10)
151
+ S = set(range(4))
152
+ expansion = nx.boundary_expansion(G, S)
153
+ # The node boundary of S has cardinality six, and S has
154
+ # cardinality three.
155
+ expected = 6 / 4
156
+ assert expected == expansion
157
+
158
+
159
+ class TestMixingExpansion:
160
+ """Unit tests for the :func:`~networkx.mixing_expansion` function."""
161
+
162
+ def test_graph(self):
163
+ G = nx.barbell_graph(5, 0)
164
+ S = set(range(5))
165
+ T = set(G) - S
166
+ expansion = nx.mixing_expansion(G, S, T)
167
+ # There is one cut edge, and the total number of edges in the
168
+ # graph is twice the total number of edges in a clique of size
169
+ # five, plus one more for the bridge.
170
+ expected = 1 / (2 * (5 * 4 + 1))
171
+ assert expected == expansion
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_cycles.py ADDED
@@ -0,0 +1,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain, islice, tee
2
+ from math import inf
3
+ from random import shuffle
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.traversal.edgedfs import FORWARD, REVERSE
9
+
10
+
11
+ def check_independent(basis):
12
+ if len(basis) == 0:
13
+ return
14
+
15
+ np = pytest.importorskip("numpy")
16
+ sp = pytest.importorskip("scipy") # Required by incidence_matrix
17
+
18
+ H = nx.Graph()
19
+ for b in basis:
20
+ nx.add_cycle(H, b)
21
+ inc = nx.incidence_matrix(H, oriented=True)
22
+ rank = np.linalg.matrix_rank(inc.toarray(), tol=None, hermitian=False)
23
+ assert inc.shape[1] - rank == len(basis)
24
+
25
+
26
+ class TestCycles:
27
+ @classmethod
28
+ def setup_class(cls):
29
+ G = nx.Graph()
30
+ nx.add_cycle(G, [0, 1, 2, 3])
31
+ nx.add_cycle(G, [0, 3, 4, 5])
32
+ nx.add_cycle(G, [0, 1, 6, 7, 8])
33
+ G.add_edge(8, 9)
34
+ cls.G = G
35
+
36
+ def is_cyclic_permutation(self, a, b):
37
+ n = len(a)
38
+ if len(b) != n:
39
+ return False
40
+ l = a + a
41
+ return any(l[i : i + n] == b for i in range(n))
42
+
43
+ def test_cycle_basis(self):
44
+ G = self.G
45
+ cy = nx.cycle_basis(G, 0)
46
+ sort_cy = sorted(sorted(c) for c in cy)
47
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
48
+ cy = nx.cycle_basis(G, 1)
49
+ sort_cy = sorted(sorted(c) for c in cy)
50
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
51
+ cy = nx.cycle_basis(G, 9)
52
+ sort_cy = sorted(sorted(c) for c in cy)
53
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
54
+ # test disconnected graphs
55
+ nx.add_cycle(G, "ABC")
56
+ cy = nx.cycle_basis(G, 9)
57
+ sort_cy = sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
58
+ assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5], ["A", "B", "C"]]
59
+
60
+ def test_cycle_basis2(self):
61
+ with pytest.raises(nx.NetworkXNotImplemented):
62
+ G = nx.DiGraph()
63
+ cy = nx.cycle_basis(G, 0)
64
+
65
+ def test_cycle_basis3(self):
66
+ with pytest.raises(nx.NetworkXNotImplemented):
67
+ G = nx.MultiGraph()
68
+ cy = nx.cycle_basis(G, 0)
69
+
70
+ def test_cycle_basis_ordered(self):
71
+ # see gh-6654 replace sets with (ordered) dicts
72
+ G = nx.cycle_graph(5)
73
+ G.update(nx.cycle_graph(range(3, 8)))
74
+ cbG = nx.cycle_basis(G)
75
+
76
+ perm = {1: 0, 0: 1} # switch 0 and 1
77
+ H = nx.relabel_nodes(G, perm)
78
+ cbH = [[perm.get(n, n) for n in cyc] for cyc in nx.cycle_basis(H)]
79
+ assert cbG == cbH
80
+
81
+ def test_cycle_basis_self_loop(self):
82
+ """Tests the function for graphs with self loops"""
83
+ G = nx.Graph()
84
+ nx.add_cycle(G, [0, 1, 2, 3])
85
+ nx.add_cycle(G, [0, 0, 6, 2])
86
+ cy = nx.cycle_basis(G)
87
+ sort_cy = sorted(sorted(c) for c in cy)
88
+ assert sort_cy == [[0], [0, 1, 2], [0, 2, 3], [0, 2, 6]]
89
+
90
+ def test_simple_cycles(self):
91
+ edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
92
+ G = nx.DiGraph(edges)
93
+ cc = sorted(nx.simple_cycles(G))
94
+ ca = [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
95
+ assert len(cc) == len(ca)
96
+ for c in cc:
97
+ assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
98
+
99
+ def test_simple_cycles_singleton(self):
100
+ G = nx.Graph([(0, 0)]) # self-loop
101
+ assert list(nx.simple_cycles(G)) == [[0]]
102
+
103
+ def test_unsortable(self):
104
+ # this test ensures that graphs whose nodes without an intrinsic
105
+ # ordering do not cause issues
106
+ G = nx.DiGraph()
107
+ nx.add_cycle(G, ["a", 1])
108
+ c = list(nx.simple_cycles(G))
109
+ assert len(c) == 1
110
+
111
+ def test_simple_cycles_small(self):
112
+ G = nx.DiGraph()
113
+ nx.add_cycle(G, [1, 2, 3])
114
+ c = sorted(nx.simple_cycles(G))
115
+ assert len(c) == 1
116
+ assert self.is_cyclic_permutation(c[0], [1, 2, 3])
117
+ nx.add_cycle(G, [10, 20, 30])
118
+ cc = sorted(nx.simple_cycles(G))
119
+ assert len(cc) == 2
120
+ ca = [[1, 2, 3], [10, 20, 30]]
121
+ for c in cc:
122
+ assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
123
+
124
+ def test_simple_cycles_empty(self):
125
+ G = nx.DiGraph()
126
+ assert list(nx.simple_cycles(G)) == []
127
+
128
+ def worst_case_graph(self, k):
129
+ # see figure 1 in Johnson's paper
130
+ # this graph has exactly 3k simple cycles
131
+ G = nx.DiGraph()
132
+ for n in range(2, k + 2):
133
+ G.add_edge(1, n)
134
+ G.add_edge(n, k + 2)
135
+ G.add_edge(2 * k + 1, 1)
136
+ for n in range(k + 2, 2 * k + 2):
137
+ G.add_edge(n, 2 * k + 2)
138
+ G.add_edge(n, n + 1)
139
+ G.add_edge(2 * k + 3, k + 2)
140
+ for n in range(2 * k + 3, 3 * k + 3):
141
+ G.add_edge(2 * k + 2, n)
142
+ G.add_edge(n, 3 * k + 3)
143
+ G.add_edge(3 * k + 3, 2 * k + 2)
144
+ return G
145
+
146
+ def test_worst_case_graph(self):
147
+ # see figure 1 in Johnson's paper
148
+ for k in range(3, 10):
149
+ G = self.worst_case_graph(k)
150
+ l = len(list(nx.simple_cycles(G)))
151
+ assert l == 3 * k
152
+
153
+ def test_recursive_simple_and_not(self):
154
+ for k in range(2, 10):
155
+ G = self.worst_case_graph(k)
156
+ cc = sorted(nx.simple_cycles(G))
157
+ rcc = sorted(nx.recursive_simple_cycles(G))
158
+ assert len(cc) == len(rcc)
159
+ for c in cc:
160
+ assert any(self.is_cyclic_permutation(c, r) for r in rcc)
161
+ for rc in rcc:
162
+ assert any(self.is_cyclic_permutation(rc, c) for c in cc)
163
+
164
+ def test_simple_graph_with_reported_bug(self):
165
+ G = nx.DiGraph()
166
+ edges = [
167
+ (0, 2),
168
+ (0, 3),
169
+ (1, 0),
170
+ (1, 3),
171
+ (2, 1),
172
+ (2, 4),
173
+ (3, 2),
174
+ (3, 4),
175
+ (4, 0),
176
+ (4, 1),
177
+ (4, 5),
178
+ (5, 0),
179
+ (5, 1),
180
+ (5, 2),
181
+ (5, 3),
182
+ ]
183
+ G.add_edges_from(edges)
184
+ cc = sorted(nx.simple_cycles(G))
185
+ assert len(cc) == 26
186
+ rcc = sorted(nx.recursive_simple_cycles(G))
187
+ assert len(cc) == len(rcc)
188
+ for c in cc:
189
+ assert any(self.is_cyclic_permutation(c, rc) for rc in rcc)
190
+ for rc in rcc:
191
+ assert any(self.is_cyclic_permutation(rc, c) for c in cc)
192
+
193
+
194
+ def pairwise(iterable):
195
+ a, b = tee(iterable)
196
+ next(b, None)
197
+ return zip(a, b)
198
+
199
+
200
+ def cycle_edges(c):
201
+ return pairwise(chain(c, islice(c, 1)))
202
+
203
+
204
+ def directed_cycle_edgeset(c):
205
+ return frozenset(cycle_edges(c))
206
+
207
+
208
+ def undirected_cycle_edgeset(c):
209
+ if len(c) == 1:
210
+ return frozenset(cycle_edges(c))
211
+ return frozenset(map(frozenset, cycle_edges(c)))
212
+
213
+
214
+ def multigraph_cycle_edgeset(c):
215
+ if len(c) <= 2:
216
+ return frozenset(cycle_edges(c))
217
+ else:
218
+ return frozenset(map(frozenset, cycle_edges(c)))
219
+
220
+
221
+ class TestCycleEnumeration:
222
+ @staticmethod
223
+ def K(n):
224
+ return nx.complete_graph(n)
225
+
226
+ @staticmethod
227
+ def D(n):
228
+ return nx.complete_graph(n).to_directed()
229
+
230
+ @staticmethod
231
+ def edgeset_function(g):
232
+ if g.is_directed():
233
+ return directed_cycle_edgeset
234
+ elif g.is_multigraph():
235
+ return multigraph_cycle_edgeset
236
+ else:
237
+ return undirected_cycle_edgeset
238
+
239
+ def check_cycle(self, g, c, es, cache, source, original_c, length_bound, chordless):
240
+ if length_bound is not None and len(c) > length_bound:
241
+ raise RuntimeError(
242
+ f"computed cycle {original_c} exceeds length bound {length_bound}"
243
+ )
244
+ if source == "computed":
245
+ if es in cache:
246
+ raise RuntimeError(
247
+ f"computed cycle {original_c} has already been found!"
248
+ )
249
+ else:
250
+ cache[es] = tuple(original_c)
251
+ else:
252
+ if es in cache:
253
+ cache.pop(es)
254
+ else:
255
+ raise RuntimeError(f"expected cycle {original_c} was not computed")
256
+
257
+ if not all(g.has_edge(*e) for e in es):
258
+ raise RuntimeError(
259
+ f"{source} claimed cycle {original_c} is not a cycle of g"
260
+ )
261
+ if chordless and len(g.subgraph(c).edges) > len(c):
262
+ raise RuntimeError(f"{source} cycle {original_c} is not chordless")
263
+
264
+ def check_cycle_algorithm(
265
+ self,
266
+ g,
267
+ expected_cycles,
268
+ length_bound=None,
269
+ chordless=False,
270
+ algorithm=None,
271
+ ):
272
+ if algorithm is None:
273
+ algorithm = nx.chordless_cycles if chordless else nx.simple_cycles
274
+
275
+ # note: we shuffle the labels of g to rule out accidentally-correct
276
+ # behavior which occurred during the development of chordless cycle
277
+ # enumeration algorithms
278
+
279
+ relabel = list(range(len(g)))
280
+ shuffle(relabel)
281
+ label = dict(zip(g, relabel))
282
+ unlabel = dict(zip(relabel, g))
283
+ h = nx.relabel_nodes(g, label, copy=True)
284
+
285
+ edgeset = self.edgeset_function(h)
286
+
287
+ params = {}
288
+ if length_bound is not None:
289
+ params["length_bound"] = length_bound
290
+
291
+ cycle_cache = {}
292
+ for c in algorithm(h, **params):
293
+ original_c = [unlabel[x] for x in c]
294
+ es = edgeset(c)
295
+ self.check_cycle(
296
+ h, c, es, cycle_cache, "computed", original_c, length_bound, chordless
297
+ )
298
+
299
+ if isinstance(expected_cycles, int):
300
+ if len(cycle_cache) != expected_cycles:
301
+ raise RuntimeError(
302
+ f"expected {expected_cycles} cycles, got {len(cycle_cache)}"
303
+ )
304
+ return
305
+ for original_c in expected_cycles:
306
+ c = [label[x] for x in original_c]
307
+ es = edgeset(c)
308
+ self.check_cycle(
309
+ h, c, es, cycle_cache, "expected", original_c, length_bound, chordless
310
+ )
311
+
312
+ if len(cycle_cache):
313
+ for c in cycle_cache.values():
314
+ raise RuntimeError(
315
+ f"computed cycle {c} is valid but not in the expected cycle set!"
316
+ )
317
+
318
+ def check_cycle_enumeration_integer_sequence(
319
+ self,
320
+ g_family,
321
+ cycle_counts,
322
+ length_bound=None,
323
+ chordless=False,
324
+ algorithm=None,
325
+ ):
326
+ for g, num_cycles in zip(g_family, cycle_counts):
327
+ self.check_cycle_algorithm(
328
+ g,
329
+ num_cycles,
330
+ length_bound=length_bound,
331
+ chordless=chordless,
332
+ algorithm=algorithm,
333
+ )
334
+
335
+ def test_directed_chordless_cycle_digons(self):
336
+ g = nx.DiGraph()
337
+ nx.add_cycle(g, range(5))
338
+ nx.add_cycle(g, range(5)[::-1])
339
+ g.add_edge(0, 0)
340
+ expected_cycles = [(0,), (1, 2), (2, 3), (3, 4)]
341
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
342
+
343
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=2)
344
+
345
+ expected_cycles = [c for c in expected_cycles if len(c) < 2]
346
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=1)
347
+
348
+ def test_directed_chordless_cycle_undirected(self):
349
+ g = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (5, 1), (0, 2)])
350
+ expected_cycles = [(0, 2, 3, 4, 5), (1, 2, 3, 4, 5)]
351
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
352
+
353
+ g = nx.DiGraph()
354
+ nx.add_cycle(g, range(5))
355
+ nx.add_cycle(g, range(4, 9))
356
+ g.add_edge(7, 3)
357
+ expected_cycles = [(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (4, 5, 6, 7, 8)]
358
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
359
+
360
+ g.add_edge(3, 7)
361
+ expected_cycles = [(0, 1, 2, 3, 4), (3, 7), (4, 5, 6, 7, 8)]
362
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
363
+
364
+ expected_cycles = [(3, 7)]
365
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=4)
366
+
367
+ g.remove_edge(7, 3)
368
+ expected_cycles = [(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)]
369
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
370
+
371
+ g = nx.DiGraph((i, j) for i in range(10) for j in range(i))
372
+ expected_cycles = []
373
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
374
+
375
+ def test_chordless_cycles_directed(self):
376
+ G = nx.DiGraph()
377
+ nx.add_cycle(G, range(5))
378
+ nx.add_cycle(G, range(4, 12))
379
+ expected = [[*range(5)], [*range(4, 12)]]
380
+ self.check_cycle_algorithm(G, expected, chordless=True)
381
+ self.check_cycle_algorithm(
382
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
383
+ )
384
+
385
+ G.add_edge(7, 3)
386
+ expected.append([*range(3, 8)])
387
+ self.check_cycle_algorithm(G, expected, chordless=True)
388
+ self.check_cycle_algorithm(
389
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
390
+ )
391
+
392
+ G.add_edge(3, 7)
393
+ expected[-1] = [7, 3]
394
+ self.check_cycle_algorithm(G, expected, chordless=True)
395
+ self.check_cycle_algorithm(
396
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
397
+ )
398
+
399
+ expected.pop()
400
+ G.remove_edge(7, 3)
401
+ self.check_cycle_algorithm(G, expected, chordless=True)
402
+ self.check_cycle_algorithm(
403
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
404
+ )
405
+
406
+ def test_directed_chordless_cycle_diclique(self):
407
+ g_family = [self.D(n) for n in range(10)]
408
+ expected_cycles = [(n * n - n) // 2 for n in range(10)]
409
+ self.check_cycle_enumeration_integer_sequence(
410
+ g_family, expected_cycles, chordless=True
411
+ )
412
+
413
+ expected_cycles = [(n * n - n) // 2 for n in range(10)]
414
+ self.check_cycle_enumeration_integer_sequence(
415
+ g_family, expected_cycles, length_bound=2
416
+ )
417
+
418
+ def test_directed_chordless_loop_blockade(self):
419
+ g = nx.DiGraph((i, i) for i in range(10))
420
+ nx.add_cycle(g, range(10))
421
+ expected_cycles = [(i,) for i in range(10)]
422
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
423
+
424
+ self.check_cycle_algorithm(g, expected_cycles, length_bound=1)
425
+
426
+ g = nx.MultiDiGraph(g)
427
+ g.add_edges_from((i, i) for i in range(0, 10, 2))
428
+ expected_cycles = [(i,) for i in range(1, 10, 2)]
429
+ self.check_cycle_algorithm(g, expected_cycles, chordless=True)
430
+
431
+ def test_simple_cycles_notable_clique_sequences(self):
432
+ # A000292: Number of labeled graphs on n+3 nodes that are triangles.
433
+ g_family = [self.K(n) for n in range(2, 12)]
434
+ expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220]
435
+ self.check_cycle_enumeration_integer_sequence(
436
+ g_family, expected, length_bound=3
437
+ )
438
+
439
+ def triangles(g, **kwargs):
440
+ yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 3)
441
+
442
+ # directed complete graphs have twice as many triangles thanks to reversal
443
+ g_family = [self.D(n) for n in range(2, 12)]
444
+ expected = [2 * e for e in expected]
445
+ self.check_cycle_enumeration_integer_sequence(
446
+ g_family, expected, length_bound=3, algorithm=triangles
447
+ )
448
+
449
+ def four_cycles(g, **kwargs):
450
+ yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 4)
451
+
452
+ # A050534: the number of 4-cycles in the complete graph K_{n+1}
453
+ expected = [0, 0, 0, 3, 15, 45, 105, 210, 378, 630, 990]
454
+ g_family = [self.K(n) for n in range(1, 12)]
455
+ self.check_cycle_enumeration_integer_sequence(
456
+ g_family, expected, length_bound=4, algorithm=four_cycles
457
+ )
458
+
459
+ # directed complete graphs have twice as many 4-cycles thanks to reversal
460
+ expected = [2 * e for e in expected]
461
+ g_family = [self.D(n) for n in range(1, 15)]
462
+ self.check_cycle_enumeration_integer_sequence(
463
+ g_family, expected, length_bound=4, algorithm=four_cycles
464
+ )
465
+
466
+ # A006231: the number of elementary circuits in a complete directed graph with n nodes
467
+ expected = [0, 1, 5, 20, 84, 409, 2365]
468
+ g_family = [self.D(n) for n in range(1, 8)]
469
+ self.check_cycle_enumeration_integer_sequence(g_family, expected)
470
+
471
+ # A002807: Number of cycles in the complete graph on n nodes K_{n}.
472
+ expected = [0, 0, 0, 1, 7, 37, 197, 1172]
473
+ g_family = [self.K(n) for n in range(8)]
474
+ self.check_cycle_enumeration_integer_sequence(g_family, expected)
475
+
476
+ def test_directed_chordless_cycle_parallel_multiedges(self):
477
+ g = nx.MultiGraph()
478
+
479
+ nx.add_cycle(g, range(5))
480
+ expected = [[*range(5)]]
481
+ self.check_cycle_algorithm(g, expected, chordless=True)
482
+
483
+ nx.add_cycle(g, range(5))
484
+ expected = [*cycle_edges(range(5))]
485
+ self.check_cycle_algorithm(g, expected, chordless=True)
486
+
487
+ nx.add_cycle(g, range(5))
488
+ expected = []
489
+ self.check_cycle_algorithm(g, expected, chordless=True)
490
+
491
+ g = nx.MultiDiGraph()
492
+
493
+ nx.add_cycle(g, range(5))
494
+ expected = [[*range(5)]]
495
+ self.check_cycle_algorithm(g, expected, chordless=True)
496
+
497
+ nx.add_cycle(g, range(5))
498
+ self.check_cycle_algorithm(g, [], chordless=True)
499
+
500
+ nx.add_cycle(g, range(5))
501
+ self.check_cycle_algorithm(g, [], chordless=True)
502
+
503
+ g = nx.MultiDiGraph()
504
+
505
+ nx.add_cycle(g, range(5))
506
+ nx.add_cycle(g, range(5)[::-1])
507
+ expected = [*cycle_edges(range(5))]
508
+ self.check_cycle_algorithm(g, expected, chordless=True)
509
+
510
+ nx.add_cycle(g, range(5))
511
+ self.check_cycle_algorithm(g, [], chordless=True)
512
+
513
+ def test_chordless_cycles_graph(self):
514
+ G = nx.Graph()
515
+ nx.add_cycle(G, range(5))
516
+ nx.add_cycle(G, range(4, 12))
517
+ expected = [[*range(5)], [*range(4, 12)]]
518
+ self.check_cycle_algorithm(G, expected, chordless=True)
519
+ self.check_cycle_algorithm(
520
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
521
+ )
522
+
523
+ G.add_edge(7, 3)
524
+ expected.append([*range(3, 8)])
525
+ expected.append([4, 3, 7, 8, 9, 10, 11])
526
+ self.check_cycle_algorithm(G, expected, chordless=True)
527
+ self.check_cycle_algorithm(
528
+ G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
529
+ )
530
+
531
+ def test_chordless_cycles_giant_hamiltonian(self):
532
+ # ... o - e - o - e - o ... # o = odd, e = even
533
+ # ... ---/ \-----/ \--- ... # <-- "long" edges
534
+ #
535
+ # each long edge belongs to exactly one triangle, and one giant cycle
536
+ # of length n/2. The remaining edges each belong to a triangle
537
+
538
+ n = 1000
539
+ assert n % 2 == 0
540
+ G = nx.Graph()
541
+ for v in range(n):
542
+ if not v % 2:
543
+ G.add_edge(v, (v + 2) % n)
544
+ G.add_edge(v, (v + 1) % n)
545
+
546
+ expected = [[*range(0, n, 2)]] + [
547
+ [x % n for x in range(i, i + 3)] for i in range(0, n, 2)
548
+ ]
549
+ self.check_cycle_algorithm(G, expected, chordless=True)
550
+ self.check_cycle_algorithm(
551
+ G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
552
+ )
553
+
554
+ # ... o -> e -> o -> e -> o ... # o = odd, e = even
555
+ # ... <---/ \---<---/ \---< ... # <-- "long" edges
556
+ #
557
+ # this time, we orient the short and long edges in opposition
558
+ # the cycle structure of this graph is the same, but we need to reverse
559
+ # the long one in our representation. Also, we need to drop the size
560
+ # because our partitioning algorithm uses strongly connected components
561
+ # instead of separating graphs by their strong articulation points
562
+
563
+ n = 100
564
+ assert n % 2 == 0
565
+ G = nx.DiGraph()
566
+ for v in range(n):
567
+ G.add_edge(v, (v + 1) % n)
568
+ if not v % 2:
569
+ G.add_edge((v + 2) % n, v)
570
+
571
+ expected = [[*range(n - 2, -2, -2)]] + [
572
+ [x % n for x in range(i, i + 3)] for i in range(0, n, 2)
573
+ ]
574
+ self.check_cycle_algorithm(G, expected, chordless=True)
575
+ self.check_cycle_algorithm(
576
+ G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
577
+ )
578
+
579
+ def test_simple_cycles_acyclic_tournament(self):
580
+ n = 10
581
+ G = nx.DiGraph((x, y) for x in range(n) for y in range(x))
582
+ self.check_cycle_algorithm(G, [])
583
+ self.check_cycle_algorithm(G, [], chordless=True)
584
+
585
+ for k in range(n + 1):
586
+ self.check_cycle_algorithm(G, [], length_bound=k)
587
+ self.check_cycle_algorithm(G, [], length_bound=k, chordless=True)
588
+
589
+ def test_simple_cycles_graph(self):
590
+ testG = nx.cycle_graph(8)
591
+ cyc1 = tuple(range(8))
592
+ self.check_cycle_algorithm(testG, [cyc1])
593
+
594
+ testG.add_edge(4, -1)
595
+ nx.add_path(testG, [3, -2, -3, -4])
596
+ self.check_cycle_algorithm(testG, [cyc1])
597
+
598
+ testG.update(nx.cycle_graph(range(8, 16)))
599
+ cyc2 = tuple(range(8, 16))
600
+ self.check_cycle_algorithm(testG, [cyc1, cyc2])
601
+
602
+ testG.update(nx.cycle_graph(range(4, 12)))
603
+ cyc3 = tuple(range(4, 12))
604
+ expected = {
605
+ (0, 1, 2, 3, 4, 5, 6, 7), # cyc1
606
+ (8, 9, 10, 11, 12, 13, 14, 15), # cyc2
607
+ (4, 5, 6, 7, 8, 9, 10, 11), # cyc3
608
+ (4, 5, 6, 7, 8, 15, 14, 13, 12, 11), # cyc2 + cyc3
609
+ (0, 1, 2, 3, 4, 11, 10, 9, 8, 7), # cyc1 + cyc3
610
+ (0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 8, 7), # cyc1 + cyc2 + cyc3
611
+ }
612
+ self.check_cycle_algorithm(testG, expected)
613
+ assert len(expected) == (2**3 - 1) - 1 # 1 disjoint comb: cyc1 + cyc2
614
+
615
+ # Basis size = 5 (2 loops overlapping gives 5 small loops
616
+ # E
617
+ # / \ Note: A-F = 10-15
618
+ # 1-2-3-4-5
619
+ # / | | \ cyc1=012DAB -- left
620
+ # 0 D F 6 cyc2=234E -- top
621
+ # \ | | / cyc3=45678F -- right
622
+ # B-A-9-8-7 cyc4=89AC -- bottom
623
+ # \ / cyc5=234F89AD -- middle
624
+ # C
625
+ #
626
+ # combinations of 5 basis elements: 2^5 - 1 (one includes no cycles)
627
+ #
628
+ # disjoint combs: (11 total) not simple cycles
629
+ # Any pair not including cyc5 => choose(4, 2) = 6
630
+ # Any triple not including cyc5 => choose(4, 3) = 4
631
+ # Any quad not including cyc5 => choose(4, 4) = 1
632
+ #
633
+ # we expect 31 - 11 = 20 simple cycles
634
+ #
635
+ testG = nx.cycle_graph(12)
636
+ testG.update(nx.cycle_graph([12, 10, 13, 2, 14, 4, 15, 8]).edges)
637
+ expected = (2**5 - 1) - 11 # 11 disjoint combinations
638
+ self.check_cycle_algorithm(testG, expected)
639
+
640
+ def test_simple_cycles_bounded(self):
641
+ # iteratively construct a cluster of nested cycles running in the same direction
642
+ # there should be one cycle of every length
643
+ d = nx.DiGraph()
644
+ expected = []
645
+ for n in range(10):
646
+ nx.add_cycle(d, range(n))
647
+ expected.append(n)
648
+ for k, e in enumerate(expected):
649
+ self.check_cycle_algorithm(d, e, length_bound=k)
650
+
651
+ # iteratively construct a path of undirected cycles, connected at articulation
652
+ # points. there should be one cycle of every length except 2: no digons
653
+ g = nx.Graph()
654
+ top = 0
655
+ expected = []
656
+ for n in range(10):
657
+ expected.append(n if n < 2 else n - 1)
658
+ if n == 2:
659
+ # no digons in undirected graphs
660
+ continue
661
+ nx.add_cycle(g, range(top, top + n))
662
+ top += n
663
+ for k, e in enumerate(expected):
664
+ self.check_cycle_algorithm(g, e, length_bound=k)
665
+
666
+ def test_simple_cycles_bound_corner_cases(self):
667
+ G = nx.cycle_graph(4)
668
+ DG = nx.cycle_graph(4, create_using=nx.DiGraph)
669
+ assert list(nx.simple_cycles(G, length_bound=0)) == []
670
+ assert list(nx.simple_cycles(DG, length_bound=0)) == []
671
+ assert list(nx.chordless_cycles(G, length_bound=0)) == []
672
+ assert list(nx.chordless_cycles(DG, length_bound=0)) == []
673
+
674
+ def test_simple_cycles_bound_error(self):
675
+ with pytest.raises(ValueError):
676
+ G = nx.DiGraph()
677
+ for c in nx.simple_cycles(G, -1):
678
+ assert False
679
+
680
+ with pytest.raises(ValueError):
681
+ G = nx.Graph()
682
+ for c in nx.simple_cycles(G, -1):
683
+ assert False
684
+
685
+ with pytest.raises(ValueError):
686
+ G = nx.Graph()
687
+ for c in nx.chordless_cycles(G, -1):
688
+ assert False
689
+
690
+ with pytest.raises(ValueError):
691
+ G = nx.DiGraph()
692
+ for c in nx.chordless_cycles(G, -1):
693
+ assert False
694
+
695
+ def test_chordless_cycles_clique(self):
696
+ g_family = [self.K(n) for n in range(2, 15)]
697
+ expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364]
698
+ self.check_cycle_enumeration_integer_sequence(
699
+ g_family, expected, chordless=True
700
+ )
701
+
702
+ # directed cliques have as many digons as undirected graphs have edges
703
+ expected = [(n * n - n) // 2 for n in range(15)]
704
+ g_family = [self.D(n) for n in range(15)]
705
+ self.check_cycle_enumeration_integer_sequence(
706
+ g_family, expected, chordless=True
707
+ )
708
+
709
+
710
+ # These tests might fail with hash randomization since they depend on
711
+ # edge_dfs. For more information, see the comments in:
712
+ # networkx/algorithms/traversal/tests/test_edgedfs.py
713
+
714
+
715
+ class TestFindCycle:
716
+ @classmethod
717
+ def setup_class(cls):
718
+ cls.nodes = [0, 1, 2, 3]
719
+ cls.edges = [(-1, 0), (0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
720
+
721
+ def test_graph_nocycle(self):
722
+ G = nx.Graph(self.edges)
723
+ pytest.raises(nx.exception.NetworkXNoCycle, nx.find_cycle, G, self.nodes)
724
+
725
+ def test_graph_cycle(self):
726
+ G = nx.Graph(self.edges)
727
+ G.add_edge(2, 0)
728
+ x = list(nx.find_cycle(G, self.nodes))
729
+ x_ = [(0, 1), (1, 2), (2, 0)]
730
+ assert x == x_
731
+
732
+ def test_graph_orientation_none(self):
733
+ G = nx.Graph(self.edges)
734
+ G.add_edge(2, 0)
735
+ x = list(nx.find_cycle(G, self.nodes, orientation=None))
736
+ x_ = [(0, 1), (1, 2), (2, 0)]
737
+ assert x == x_
738
+
739
+ def test_graph_orientation_original(self):
740
+ G = nx.Graph(self.edges)
741
+ G.add_edge(2, 0)
742
+ x = list(nx.find_cycle(G, self.nodes, orientation="original"))
743
+ x_ = [(0, 1, FORWARD), (1, 2, FORWARD), (2, 0, FORWARD)]
744
+ assert x == x_
745
+
746
+ def test_digraph(self):
747
+ G = nx.DiGraph(self.edges)
748
+ x = list(nx.find_cycle(G, self.nodes))
749
+ x_ = [(0, 1), (1, 0)]
750
+ assert x == x_
751
+
752
+ def test_digraph_orientation_none(self):
753
+ G = nx.DiGraph(self.edges)
754
+ x = list(nx.find_cycle(G, self.nodes, orientation=None))
755
+ x_ = [(0, 1), (1, 0)]
756
+ assert x == x_
757
+
758
+ def test_digraph_orientation_original(self):
759
+ G = nx.DiGraph(self.edges)
760
+ x = list(nx.find_cycle(G, self.nodes, orientation="original"))
761
+ x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
762
+ assert x == x_
763
+
764
+ def test_multigraph(self):
765
+ G = nx.MultiGraph(self.edges)
766
+ x = list(nx.find_cycle(G, self.nodes))
767
+ x_ = [(0, 1, 0), (1, 0, 1)] # or (1, 0, 2)
768
+ # Hash randomization...could be any edge.
769
+ assert x[0] == x_[0]
770
+ assert x[1][:2] == x_[1][:2]
771
+
772
+ def test_multidigraph(self):
773
+ G = nx.MultiDiGraph(self.edges)
774
+ x = list(nx.find_cycle(G, self.nodes))
775
+ x_ = [(0, 1, 0), (1, 0, 0)] # (1, 0, 1)
776
+ assert x[0] == x_[0]
777
+ assert x[1][:2] == x_[1][:2]
778
+
779
+ def test_digraph_ignore(self):
780
+ G = nx.DiGraph(self.edges)
781
+ x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
782
+ x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
783
+ assert x == x_
784
+
785
+ def test_digraph_reverse(self):
786
+ G = nx.DiGraph(self.edges)
787
+ x = list(nx.find_cycle(G, self.nodes, orientation="reverse"))
788
+ x_ = [(1, 0, REVERSE), (0, 1, REVERSE)]
789
+ assert x == x_
790
+
791
+ def test_multidigraph_ignore(self):
792
+ G = nx.MultiDiGraph(self.edges)
793
+ x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
794
+ x_ = [(0, 1, 0, FORWARD), (1, 0, 0, FORWARD)] # or (1, 0, 1, 1)
795
+ assert x[0] == x_[0]
796
+ assert x[1][:2] == x_[1][:2]
797
+ assert x[1][3] == x_[1][3]
798
+
799
+ def test_multidigraph_ignore2(self):
800
+ # Loop traversed an edge while ignoring its orientation.
801
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (1, 2)])
802
+ x = list(nx.find_cycle(G, [0, 1, 2], orientation="ignore"))
803
+ x_ = [(1, 2, 0, FORWARD), (1, 2, 1, REVERSE)]
804
+ assert x == x_
805
+
806
+ def test_multidigraph_original(self):
807
+ # Node 2 doesn't need to be searched again from visited from 4.
808
+ # The goal here is to cover the case when 2 to be researched from 4,
809
+ # when 4 is visited from the first time (so we must make sure that 4
810
+ # is not visited from 2, and hence, we respect the edge orientation).
811
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 3), (4, 2)])
812
+ pytest.raises(
813
+ nx.exception.NetworkXNoCycle,
814
+ nx.find_cycle,
815
+ G,
816
+ [0, 1, 2, 3, 4],
817
+ orientation="original",
818
+ )
819
+
820
+ def test_dag(self):
821
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
822
+ pytest.raises(
823
+ nx.exception.NetworkXNoCycle, nx.find_cycle, G, orientation="original"
824
+ )
825
+ x = list(nx.find_cycle(G, orientation="ignore"))
826
+ assert x == [(0, 1, FORWARD), (1, 2, FORWARD), (0, 2, REVERSE)]
827
+
828
+ def test_prev_explored(self):
829
+ # https://github.com/networkx/networkx/issues/2323
830
+
831
+ G = nx.DiGraph()
832
+ G.add_edges_from([(1, 0), (2, 0), (1, 2), (2, 1)])
833
+ pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
834
+ x = list(nx.find_cycle(G, 1))
835
+ x_ = [(1, 2), (2, 1)]
836
+ assert x == x_
837
+
838
+ x = list(nx.find_cycle(G, 2))
839
+ x_ = [(2, 1), (1, 2)]
840
+ assert x == x_
841
+
842
+ x = list(nx.find_cycle(G))
843
+ x_ = [(1, 2), (2, 1)]
844
+ assert x == x_
845
+
846
+ def test_no_cycle(self):
847
+ # https://github.com/networkx/networkx/issues/2439
848
+
849
+ G = nx.DiGraph()
850
+ G.add_edges_from([(1, 2), (2, 0), (3, 1), (3, 2)])
851
+ pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
852
+ pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G)
853
+
854
+
855
+ def assert_basis_equal(a, b):
856
+ assert sorted(a) == sorted(b)
857
+
858
+
859
+ class TestMinimumCycleBasis:
860
+ @classmethod
861
+ def setup_class(cls):
862
+ T = nx.Graph()
863
+ nx.add_cycle(T, [1, 2, 3, 4], weight=1)
864
+ T.add_edge(2, 4, weight=5)
865
+ cls.diamond_graph = T
866
+
867
+ def test_unweighted_diamond(self):
868
+ mcb = nx.minimum_cycle_basis(self.diamond_graph)
869
+ assert_basis_equal(mcb, [[2, 4, 1], [3, 4, 2]])
870
+
871
+ def test_weighted_diamond(self):
872
+ mcb = nx.minimum_cycle_basis(self.diamond_graph, weight="weight")
873
+ assert_basis_equal(mcb, [[2, 4, 1], [4, 3, 2, 1]])
874
+
875
+ def test_dimensionality(self):
876
+ # checks |MCB|=|E|-|V|+|NC|
877
+ ntrial = 10
878
+ for seed in range(1234, 1234 + ntrial):
879
+ rg = nx.erdos_renyi_graph(10, 0.3, seed=seed)
880
+ nnodes = rg.number_of_nodes()
881
+ nedges = rg.number_of_edges()
882
+ ncomp = nx.number_connected_components(rg)
883
+
884
+ mcb = nx.minimum_cycle_basis(rg)
885
+ assert len(mcb) == nedges - nnodes + ncomp
886
+ check_independent(mcb)
887
+
888
+ def test_complete_graph(self):
889
+ cg = nx.complete_graph(5)
890
+ mcb = nx.minimum_cycle_basis(cg)
891
+ assert all(len(cycle) == 3 for cycle in mcb)
892
+ check_independent(mcb)
893
+
894
+ def test_tree_graph(self):
895
+ tg = nx.balanced_tree(3, 3)
896
+ assert not nx.minimum_cycle_basis(tg)
897
+
898
+ def test_petersen_graph(self):
899
+ G = nx.petersen_graph()
900
+ mcb = list(nx.minimum_cycle_basis(G))
901
+ expected = [
902
+ [4, 9, 7, 5, 0],
903
+ [1, 2, 3, 4, 0],
904
+ [1, 6, 8, 5, 0],
905
+ [4, 3, 8, 5, 0],
906
+ [1, 6, 9, 4, 0],
907
+ [1, 2, 7, 5, 0],
908
+ ]
909
+ assert len(mcb) == len(expected)
910
+ assert all(c in expected for c in mcb)
911
+
912
+ # check that order of the nodes is a path
913
+ for c in mcb:
914
+ assert all(G.has_edge(u, v) for u, v in nx.utils.pairwise(c, cyclic=True))
915
+ # check independence of the basis
916
+ check_independent(mcb)
917
+
918
+ def test_gh6787_variable_weighted_complete_graph(self):
919
+ N = 8
920
+ cg = nx.complete_graph(N)
921
+ cg.add_weighted_edges_from([(u, v, 9) for u, v in cg.edges])
922
+ cg.add_weighted_edges_from([(u, v, 1) for u, v in nx.cycle_graph(N).edges])
923
+ mcb = nx.minimum_cycle_basis(cg, weight="weight")
924
+ check_independent(mcb)
925
+
926
+ def test_gh6787_and_edge_attribute_names(self):
927
+ G = nx.cycle_graph(4)
928
+ G.add_weighted_edges_from([(0, 2, 10), (1, 3, 10)], weight="dist")
929
+ expected = [[1, 3, 0], [3, 2, 1, 0], [1, 2, 0]]
930
+ mcb = list(nx.minimum_cycle_basis(G, weight="dist"))
931
+ assert len(mcb) == len(expected)
932
+ assert all(c in expected for c in mcb)
933
+
934
+ # test not using a weight with weight attributes
935
+ expected = [[1, 3, 0], [1, 2, 0], [3, 2, 0]]
936
+ mcb = list(nx.minimum_cycle_basis(G))
937
+ assert len(mcb) == len(expected)
938
+ assert all(c in expected for c in mcb)
939
+
940
+
941
+ class TestGirth:
942
+ @pytest.mark.parametrize(
943
+ ("G", "expected"),
944
+ (
945
+ (nx.chvatal_graph(), 4),
946
+ (nx.tutte_graph(), 4),
947
+ (nx.petersen_graph(), 5),
948
+ (nx.heawood_graph(), 6),
949
+ (nx.pappus_graph(), 6),
950
+ (nx.random_labeled_tree(10, seed=42), inf),
951
+ (nx.empty_graph(10), inf),
952
+ (nx.Graph(chain(cycle_edges(range(5)), cycle_edges(range(6, 10)))), 4),
953
+ (
954
+ nx.Graph(
955
+ [
956
+ (0, 6),
957
+ (0, 8),
958
+ (0, 9),
959
+ (1, 8),
960
+ (2, 8),
961
+ (2, 9),
962
+ (4, 9),
963
+ (5, 9),
964
+ (6, 8),
965
+ (6, 9),
966
+ (7, 8),
967
+ ]
968
+ ),
969
+ 3,
970
+ ),
971
+ ),
972
+ )
973
+ def test_girth(self, G, expected):
974
+ assert nx.girth(G) == expected
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_d_separation.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def path_graph():
9
+ """Return a path graph of length three."""
10
+ G = nx.path_graph(3, create_using=nx.DiGraph)
11
+ G.graph["name"] = "path"
12
+ nx.freeze(G)
13
+ return G
14
+
15
+
16
+ def fork_graph():
17
+ """Return a three node fork graph."""
18
+ G = nx.DiGraph(name="fork")
19
+ G.add_edges_from([(0, 1), (0, 2)])
20
+ nx.freeze(G)
21
+ return G
22
+
23
+
24
+ def collider_graph():
25
+ """Return a collider/v-structure graph with three nodes."""
26
+ G = nx.DiGraph(name="collider")
27
+ G.add_edges_from([(0, 2), (1, 2)])
28
+ nx.freeze(G)
29
+ return G
30
+
31
+
32
+ def naive_bayes_graph():
33
+ """Return a simply Naive Bayes PGM graph."""
34
+ G = nx.DiGraph(name="naive_bayes")
35
+ G.add_edges_from([(0, 1), (0, 2), (0, 3), (0, 4)])
36
+ nx.freeze(G)
37
+ return G
38
+
39
+
40
+ def asia_graph():
41
+ """Return the 'Asia' PGM graph."""
42
+ G = nx.DiGraph(name="asia")
43
+ G.add_edges_from(
44
+ [
45
+ ("asia", "tuberculosis"),
46
+ ("smoking", "cancer"),
47
+ ("smoking", "bronchitis"),
48
+ ("tuberculosis", "either"),
49
+ ("cancer", "either"),
50
+ ("either", "xray"),
51
+ ("either", "dyspnea"),
52
+ ("bronchitis", "dyspnea"),
53
+ ]
54
+ )
55
+ nx.freeze(G)
56
+ return G
57
+
58
+
59
+ @pytest.fixture(name="path_graph")
60
+ def path_graph_fixture():
61
+ return path_graph()
62
+
63
+
64
+ @pytest.fixture(name="fork_graph")
65
+ def fork_graph_fixture():
66
+ return fork_graph()
67
+
68
+
69
+ @pytest.fixture(name="collider_graph")
70
+ def collider_graph_fixture():
71
+ return collider_graph()
72
+
73
+
74
+ @pytest.fixture(name="naive_bayes_graph")
75
+ def naive_bayes_graph_fixture():
76
+ return naive_bayes_graph()
77
+
78
+
79
+ @pytest.fixture(name="asia_graph")
80
+ def asia_graph_fixture():
81
+ return asia_graph()
82
+
83
+
84
+ @pytest.fixture()
85
+ def large_collider_graph():
86
+ edge_list = [("A", "B"), ("C", "B"), ("B", "D"), ("D", "E"), ("B", "F"), ("G", "E")]
87
+ G = nx.DiGraph(edge_list)
88
+ return G
89
+
90
+
91
+ @pytest.fixture()
92
+ def chain_and_fork_graph():
93
+ edge_list = [("A", "B"), ("B", "C"), ("B", "D"), ("D", "C")]
94
+ G = nx.DiGraph(edge_list)
95
+ return G
96
+
97
+
98
+ @pytest.fixture()
99
+ def no_separating_set_graph():
100
+ edge_list = [("A", "B")]
101
+ G = nx.DiGraph(edge_list)
102
+ return G
103
+
104
+
105
+ @pytest.fixture()
106
+ def large_no_separating_set_graph():
107
+ edge_list = [("A", "B"), ("C", "A"), ("C", "B")]
108
+ G = nx.DiGraph(edge_list)
109
+ return G
110
+
111
+
112
+ @pytest.fixture()
113
+ def collider_trek_graph():
114
+ edge_list = [("A", "B"), ("C", "B"), ("C", "D")]
115
+ G = nx.DiGraph(edge_list)
116
+ return G
117
+
118
+
119
+ @pytest.mark.parametrize(
120
+ "graph",
121
+ [path_graph(), fork_graph(), collider_graph(), naive_bayes_graph(), asia_graph()],
122
+ )
123
+ def test_markov_condition(graph):
124
+ """Test that the Markov condition holds for each PGM graph."""
125
+ for node in graph.nodes:
126
+ parents = set(graph.predecessors(node))
127
+ non_descendants = graph.nodes - nx.descendants(graph, node) - {node} - parents
128
+ assert nx.is_d_separator(graph, {node}, non_descendants, parents)
129
+
130
+
131
+ def test_path_graph_dsep(path_graph):
132
+ """Example-based test of d-separation for path_graph."""
133
+ assert nx.is_d_separator(path_graph, {0}, {2}, {1})
134
+ assert not nx.is_d_separator(path_graph, {0}, {2}, set())
135
+
136
+
137
+ def test_fork_graph_dsep(fork_graph):
138
+ """Example-based test of d-separation for fork_graph."""
139
+ assert nx.is_d_separator(fork_graph, {1}, {2}, {0})
140
+ assert not nx.is_d_separator(fork_graph, {1}, {2}, set())
141
+
142
+
143
+ def test_collider_graph_dsep(collider_graph):
144
+ """Example-based test of d-separation for collider_graph."""
145
+ assert nx.is_d_separator(collider_graph, {0}, {1}, set())
146
+ assert not nx.is_d_separator(collider_graph, {0}, {1}, {2})
147
+
148
+
149
+ def test_naive_bayes_dsep(naive_bayes_graph):
150
+ """Example-based test of d-separation for naive_bayes_graph."""
151
+ for u, v in combinations(range(1, 5), 2):
152
+ assert nx.is_d_separator(naive_bayes_graph, {u}, {v}, {0})
153
+ assert not nx.is_d_separator(naive_bayes_graph, {u}, {v}, set())
154
+
155
+
156
+ def test_asia_graph_dsep(asia_graph):
157
+ """Example-based test of d-separation for asia_graph."""
158
+ assert nx.is_d_separator(
159
+ asia_graph, {"asia", "smoking"}, {"dyspnea", "xray"}, {"bronchitis", "either"}
160
+ )
161
+ assert nx.is_d_separator(
162
+ asia_graph, {"tuberculosis", "cancer"}, {"bronchitis"}, {"smoking", "xray"}
163
+ )
164
+
165
+
166
+ def test_undirected_graphs_are_not_supported():
167
+ """
168
+ Test that undirected graphs are not supported.
169
+
170
+ d-separation and its related algorithms do not apply in
171
+ the case of undirected graphs.
172
+ """
173
+ g = nx.path_graph(3, nx.Graph)
174
+ with pytest.raises(nx.NetworkXNotImplemented):
175
+ nx.is_d_separator(g, {0}, {1}, {2})
176
+ with pytest.raises(nx.NetworkXNotImplemented):
177
+ nx.is_minimal_d_separator(g, {0}, {1}, {2})
178
+ with pytest.raises(nx.NetworkXNotImplemented):
179
+ nx.find_minimal_d_separator(g, {0}, {1})
180
+
181
+
182
+ def test_cyclic_graphs_raise_error():
183
+ """
184
+ Test that cycle graphs should cause erroring.
185
+
186
+ This is because PGMs assume a directed acyclic graph.
187
+ """
188
+ g = nx.cycle_graph(3, nx.DiGraph)
189
+ with pytest.raises(nx.NetworkXError):
190
+ nx.is_d_separator(g, {0}, {1}, {2})
191
+ with pytest.raises(nx.NetworkXError):
192
+ nx.find_minimal_d_separator(g, {0}, {1})
193
+ with pytest.raises(nx.NetworkXError):
194
+ nx.is_minimal_d_separator(g, {0}, {1}, {2})
195
+
196
+
197
+ def test_invalid_nodes_raise_error(asia_graph):
198
+ """
199
+ Test that graphs that have invalid nodes passed in raise errors.
200
+ """
201
+ # Check both set and node arguments
202
+ with pytest.raises(nx.NodeNotFound):
203
+ nx.is_d_separator(asia_graph, {0}, {1}, {2})
204
+ with pytest.raises(nx.NodeNotFound):
205
+ nx.is_d_separator(asia_graph, 0, 1, 2)
206
+ with pytest.raises(nx.NodeNotFound):
207
+ nx.is_minimal_d_separator(asia_graph, {0}, {1}, {2})
208
+ with pytest.raises(nx.NodeNotFound):
209
+ nx.is_minimal_d_separator(asia_graph, 0, 1, 2)
210
+ with pytest.raises(nx.NodeNotFound):
211
+ nx.find_minimal_d_separator(asia_graph, {0}, {1})
212
+ with pytest.raises(nx.NodeNotFound):
213
+ nx.find_minimal_d_separator(asia_graph, 0, 1)
214
+
215
+
216
+ def test_nondisjoint_node_sets_raise_error(collider_graph):
217
+ """
218
+ Test that error is raised when node sets aren't disjoint.
219
+ """
220
+ with pytest.raises(nx.NetworkXError):
221
+ nx.is_d_separator(collider_graph, 0, 1, 0)
222
+ with pytest.raises(nx.NetworkXError):
223
+ nx.is_d_separator(collider_graph, 0, 2, 0)
224
+ with pytest.raises(nx.NetworkXError):
225
+ nx.is_d_separator(collider_graph, 0, 0, 1)
226
+ with pytest.raises(nx.NetworkXError):
227
+ nx.is_d_separator(collider_graph, 1, 0, 0)
228
+ with pytest.raises(nx.NetworkXError):
229
+ nx.find_minimal_d_separator(collider_graph, 0, 0)
230
+ with pytest.raises(nx.NetworkXError):
231
+ nx.find_minimal_d_separator(collider_graph, 0, 1, included=0)
232
+ with pytest.raises(nx.NetworkXError):
233
+ nx.find_minimal_d_separator(collider_graph, 1, 0, included=0)
234
+ with pytest.raises(nx.NetworkXError):
235
+ nx.is_minimal_d_separator(collider_graph, 0, 0, set())
236
+ with pytest.raises(nx.NetworkXError):
237
+ nx.is_minimal_d_separator(collider_graph, 0, 1, set(), included=0)
238
+ with pytest.raises(nx.NetworkXError):
239
+ nx.is_minimal_d_separator(collider_graph, 1, 0, set(), included=0)
240
+
241
+
242
+ def test_is_minimal_d_separator(
243
+ large_collider_graph,
244
+ chain_and_fork_graph,
245
+ no_separating_set_graph,
246
+ large_no_separating_set_graph,
247
+ collider_trek_graph,
248
+ ):
249
+ # Case 1:
250
+ # create a graph A -> B <- C
251
+ # B -> D -> E;
252
+ # B -> F;
253
+ # G -> E;
254
+ assert not nx.is_d_separator(large_collider_graph, {"B"}, {"E"}, set())
255
+
256
+ # minimal set of the corresponding graph
257
+ # for B and E should be (D,)
258
+ Zmin = nx.find_minimal_d_separator(large_collider_graph, "B", "E")
259
+ # check that the minimal d-separator is a d-separating set
260
+ assert nx.is_d_separator(large_collider_graph, "B", "E", Zmin)
261
+ # the minimal separating set should also pass the test for minimality
262
+ assert nx.is_minimal_d_separator(large_collider_graph, "B", "E", Zmin)
263
+ # function should also work with set arguments
264
+ assert nx.is_minimal_d_separator(large_collider_graph, {"A", "B"}, {"G", "E"}, Zmin)
265
+ assert Zmin == {"D"}
266
+
267
+ # Case 2:
268
+ # create a graph A -> B -> C
269
+ # B -> D -> C;
270
+ assert not nx.is_d_separator(chain_and_fork_graph, {"A"}, {"C"}, set())
271
+ Zmin = nx.find_minimal_d_separator(chain_and_fork_graph, "A", "C")
272
+
273
+ # the minimal separating set should pass the test for minimality
274
+ assert nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Zmin)
275
+ assert Zmin == {"B"}
276
+ Znotmin = Zmin.union({"D"})
277
+ assert not nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Znotmin)
278
+
279
+ # Case 3:
280
+ # create a graph A -> B
281
+
282
+ # there is no m-separating set between A and B at all, so
283
+ # no minimal m-separating set can exist
284
+ assert not nx.is_d_separator(no_separating_set_graph, {"A"}, {"B"}, set())
285
+ assert nx.find_minimal_d_separator(no_separating_set_graph, "A", "B") is None
286
+
287
+ # Case 4:
288
+ # create a graph A -> B with A <- C -> B
289
+
290
+ # there is no m-separating set between A and B at all, so
291
+ # no minimal m-separating set can exist
292
+ # however, the algorithm will initially propose C as a
293
+ # minimal (but invalid) separating set
294
+ assert not nx.is_d_separator(large_no_separating_set_graph, {"A"}, {"B"}, {"C"})
295
+ assert nx.find_minimal_d_separator(large_no_separating_set_graph, "A", "B") is None
296
+
297
+ # Test `included` and `excluded` args
298
+ # create graph A -> B <- C -> D
299
+ assert nx.find_minimal_d_separator(collider_trek_graph, "A", "D", included="B") == {
300
+ "B",
301
+ "C",
302
+ }
303
+ assert (
304
+ nx.find_minimal_d_separator(
305
+ collider_trek_graph, "A", "D", included="B", restricted="B"
306
+ )
307
+ is None
308
+ )
309
+
310
+
311
+ def test_is_minimal_d_separator_checks_dsep():
312
+ """Test that is_minimal_d_separator checks for d-separation as well."""
313
+ g = nx.DiGraph()
314
+ g.add_edges_from(
315
+ [
316
+ ("A", "B"),
317
+ ("A", "E"),
318
+ ("B", "C"),
319
+ ("B", "D"),
320
+ ("D", "C"),
321
+ ("D", "F"),
322
+ ("E", "D"),
323
+ ("E", "F"),
324
+ ]
325
+ )
326
+
327
+ assert not nx.is_d_separator(g, {"C"}, {"F"}, {"D"})
328
+
329
+ # since {'D'} and {} are not d-separators, we return false
330
+ assert not nx.is_minimal_d_separator(g, "C", "F", {"D"})
331
+ assert not nx.is_minimal_d_separator(g, "C", "F", set())
332
+
333
+
334
+ def test__reachable(large_collider_graph):
335
+ reachable = nx.algorithms.d_separation._reachable
336
+ g = large_collider_graph
337
+ x = {"F", "D"}
338
+ ancestors = {"A", "B", "C", "D", "F"}
339
+ assert reachable(g, x, ancestors, {"B"}) == {"B", "F", "D"}
340
+ assert reachable(g, x, ancestors, set()) == ancestors
341
+
342
+
343
+ def test_deprecations():
344
+ G = nx.DiGraph([(0, 1), (1, 2)])
345
+ with pytest.deprecated_call():
346
+ nx.d_separated(G, 0, 2, {1})
347
+ with pytest.deprecated_call():
348
+ z = nx.minimal_d_separator(G, 0, 2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_dag.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from itertools import combinations, permutations
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.utils import edges_equal, pairwise
8
+
9
+
10
+ # Recipe from the itertools documentation.
11
+ def _consume(iterator):
12
+ "Consume the iterator entirely."
13
+ # Feed the entire iterator into a zero-length deque.
14
+ deque(iterator, maxlen=0)
15
+
16
+
17
+ class TestDagLongestPath:
18
+ """Unit tests computing the longest path in a directed acyclic graph."""
19
+
20
+ def test_empty(self):
21
+ G = nx.DiGraph()
22
+ assert nx.dag_longest_path(G) == []
23
+
24
+ def test_unweighted1(self):
25
+ edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (3, 7)]
26
+ G = nx.DiGraph(edges)
27
+ assert nx.dag_longest_path(G) == [1, 2, 3, 5, 6]
28
+
29
+ def test_unweighted2(self):
30
+ edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
31
+ G = nx.DiGraph(edges)
32
+ assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
33
+
34
+ def test_weighted(self):
35
+ G = nx.DiGraph()
36
+ edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4), (1, 6, 2)]
37
+ G.add_weighted_edges_from(edges)
38
+ assert nx.dag_longest_path(G) == [2, 3, 5]
39
+
40
+ def test_undirected_not_implemented(self):
41
+ G = nx.Graph()
42
+ pytest.raises(nx.NetworkXNotImplemented, nx.dag_longest_path, G)
43
+
44
+ def test_unorderable_nodes(self):
45
+ """Tests that computing the longest path does not depend on
46
+ nodes being orderable.
47
+
48
+ For more information, see issue #1989.
49
+
50
+ """
51
+ # Create the directed path graph on four nodes in a diamond shape,
52
+ # with nodes represented as (unorderable) Python objects.
53
+ nodes = [object() for n in range(4)]
54
+ G = nx.DiGraph()
55
+ G.add_edge(nodes[0], nodes[1])
56
+ G.add_edge(nodes[0], nodes[2])
57
+ G.add_edge(nodes[2], nodes[3])
58
+ G.add_edge(nodes[1], nodes[3])
59
+
60
+ # this will raise NotImplementedError when nodes need to be ordered
61
+ nx.dag_longest_path(G)
62
+
63
+ def test_multigraph_unweighted(self):
64
+ edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
65
+ G = nx.MultiDiGraph(edges)
66
+ assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
67
+
68
+ def test_multigraph_weighted(self):
69
+ G = nx.MultiDiGraph()
70
+ edges = [
71
+ (1, 2, 2),
72
+ (2, 3, 2),
73
+ (1, 3, 1),
74
+ (1, 3, 5),
75
+ (1, 3, 2),
76
+ ]
77
+ G.add_weighted_edges_from(edges)
78
+ assert nx.dag_longest_path(G) == [1, 3]
79
+
80
+ def test_multigraph_weighted_default_weight(self):
81
+ G = nx.MultiDiGraph([(1, 2), (2, 3)]) # Unweighted edges
82
+ G.add_weighted_edges_from([(1, 3, 1), (1, 3, 5), (1, 3, 2)])
83
+
84
+ # Default value for default weight is 1
85
+ assert nx.dag_longest_path(G) == [1, 3]
86
+ assert nx.dag_longest_path(G, default_weight=3) == [1, 2, 3]
87
+
88
+
89
+ class TestDagLongestPathLength:
90
+ """Unit tests for computing the length of a longest path in a
91
+ directed acyclic graph.
92
+
93
+ """
94
+
95
+ def test_unweighted(self):
96
+ edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
97
+ G = nx.DiGraph(edges)
98
+ assert nx.dag_longest_path_length(G) == 4
99
+
100
+ edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
101
+ G = nx.DiGraph(edges)
102
+ assert nx.dag_longest_path_length(G) == 4
103
+
104
+ # test degenerate graphs
105
+ G = nx.DiGraph()
106
+ G.add_node(1)
107
+ assert nx.dag_longest_path_length(G) == 0
108
+
109
+ def test_undirected_not_implemented(self):
110
+ G = nx.Graph()
111
+ pytest.raises(nx.NetworkXNotImplemented, nx.dag_longest_path_length, G)
112
+
113
+ def test_weighted(self):
114
+ edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4), (1, 6, 2)]
115
+ G = nx.DiGraph()
116
+ G.add_weighted_edges_from(edges)
117
+ assert nx.dag_longest_path_length(G) == 5
118
+
119
+ def test_multigraph_unweighted(self):
120
+ edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
121
+ G = nx.MultiDiGraph(edges)
122
+ assert nx.dag_longest_path_length(G) == 4
123
+
124
+ def test_multigraph_weighted(self):
125
+ G = nx.MultiDiGraph()
126
+ edges = [
127
+ (1, 2, 2),
128
+ (2, 3, 2),
129
+ (1, 3, 1),
130
+ (1, 3, 5),
131
+ (1, 3, 2),
132
+ ]
133
+ G.add_weighted_edges_from(edges)
134
+ assert nx.dag_longest_path_length(G) == 5
135
+
136
+
137
+ class TestDAG:
138
+ @classmethod
139
+ def setup_class(cls):
140
+ pass
141
+
142
+ def test_topological_sort1(self):
143
+ DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
144
+
145
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
146
+ assert tuple(algorithm(DG)) == (1, 2, 3)
147
+
148
+ DG.add_edge(3, 2)
149
+
150
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
151
+ pytest.raises(nx.NetworkXUnfeasible, _consume, algorithm(DG))
152
+
153
+ DG.remove_edge(2, 3)
154
+
155
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
156
+ assert tuple(algorithm(DG)) == (1, 3, 2)
157
+
158
+ DG.remove_edge(3, 2)
159
+
160
+ assert tuple(nx.topological_sort(DG)) in {(1, 2, 3), (1, 3, 2)}
161
+ assert tuple(nx.lexicographical_topological_sort(DG)) == (1, 2, 3)
162
+
163
+ def test_is_directed_acyclic_graph(self):
164
+ G = nx.generators.complete_graph(2)
165
+ assert not nx.is_directed_acyclic_graph(G)
166
+ assert not nx.is_directed_acyclic_graph(G.to_directed())
167
+ assert not nx.is_directed_acyclic_graph(nx.Graph([(3, 4), (4, 5)]))
168
+ assert nx.is_directed_acyclic_graph(nx.DiGraph([(3, 4), (4, 5)]))
169
+
170
+ def test_topological_sort2(self):
171
+ DG = nx.DiGraph(
172
+ {
173
+ 1: [2],
174
+ 2: [3],
175
+ 3: [4],
176
+ 4: [5],
177
+ 5: [1],
178
+ 11: [12],
179
+ 12: [13],
180
+ 13: [14],
181
+ 14: [15],
182
+ }
183
+ )
184
+ pytest.raises(nx.NetworkXUnfeasible, _consume, nx.topological_sort(DG))
185
+
186
+ assert not nx.is_directed_acyclic_graph(DG)
187
+
188
+ DG.remove_edge(1, 2)
189
+ _consume(nx.topological_sort(DG))
190
+ assert nx.is_directed_acyclic_graph(DG)
191
+
192
+ def test_topological_sort3(self):
193
+ DG = nx.DiGraph()
194
+ DG.add_edges_from([(1, i) for i in range(2, 5)])
195
+ DG.add_edges_from([(2, i) for i in range(5, 9)])
196
+ DG.add_edges_from([(6, i) for i in range(9, 12)])
197
+ DG.add_edges_from([(4, i) for i in range(12, 15)])
198
+
199
+ def validate(order):
200
+ assert isinstance(order, list)
201
+ assert set(order) == set(DG)
202
+ for u, v in combinations(order, 2):
203
+ assert not nx.has_path(DG, v, u)
204
+
205
+ validate(list(nx.topological_sort(DG)))
206
+
207
+ DG.add_edge(14, 1)
208
+ pytest.raises(nx.NetworkXUnfeasible, _consume, nx.topological_sort(DG))
209
+
210
+ def test_topological_sort4(self):
211
+ G = nx.Graph()
212
+ G.add_edge(1, 2)
213
+ # Only directed graphs can be topologically sorted.
214
+ pytest.raises(nx.NetworkXError, _consume, nx.topological_sort(G))
215
+
216
+ def test_topological_sort5(self):
217
+ G = nx.DiGraph()
218
+ G.add_edge(0, 1)
219
+ assert list(nx.topological_sort(G)) == [0, 1]
220
+
221
+ def test_topological_sort6(self):
222
+ for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
223
+
224
+ def runtime_error():
225
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
226
+ first = True
227
+ for x in algorithm(DG):
228
+ if first:
229
+ first = False
230
+ DG.add_edge(5 - x, 5)
231
+
232
+ def unfeasible_error():
233
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
234
+ first = True
235
+ for x in algorithm(DG):
236
+ if first:
237
+ first = False
238
+ DG.remove_node(4)
239
+
240
+ def runtime_error2():
241
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
242
+ first = True
243
+ for x in algorithm(DG):
244
+ if first:
245
+ first = False
246
+ DG.remove_node(2)
247
+
248
+ pytest.raises(RuntimeError, runtime_error)
249
+ pytest.raises(RuntimeError, runtime_error2)
250
+ pytest.raises(nx.NetworkXUnfeasible, unfeasible_error)
251
+
252
+ def test_all_topological_sorts_1(self):
253
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5)])
254
+ assert list(nx.all_topological_sorts(DG)) == [[1, 2, 3, 4, 5]]
255
+
256
+ def test_all_topological_sorts_2(self):
257
+ DG = nx.DiGraph([(1, 3), (2, 1), (2, 4), (4, 3), (4, 5)])
258
+ assert sorted(nx.all_topological_sorts(DG)) == [
259
+ [2, 1, 4, 3, 5],
260
+ [2, 1, 4, 5, 3],
261
+ [2, 4, 1, 3, 5],
262
+ [2, 4, 1, 5, 3],
263
+ [2, 4, 5, 1, 3],
264
+ ]
265
+
266
+ def test_all_topological_sorts_3(self):
267
+ def unfeasible():
268
+ DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 2), (4, 5)])
269
+ # convert to list to execute generator
270
+ list(nx.all_topological_sorts(DG))
271
+
272
+ def not_implemented():
273
+ G = nx.Graph([(1, 2), (2, 3)])
274
+ # convert to list to execute generator
275
+ list(nx.all_topological_sorts(G))
276
+
277
+ def not_implemented_2():
278
+ G = nx.MultiGraph([(1, 2), (1, 2), (2, 3)])
279
+ list(nx.all_topological_sorts(G))
280
+
281
+ pytest.raises(nx.NetworkXUnfeasible, unfeasible)
282
+ pytest.raises(nx.NetworkXNotImplemented, not_implemented)
283
+ pytest.raises(nx.NetworkXNotImplemented, not_implemented_2)
284
+
285
+ def test_all_topological_sorts_4(self):
286
+ DG = nx.DiGraph()
287
+ for i in range(7):
288
+ DG.add_node(i)
289
+ assert sorted(map(list, permutations(DG.nodes))) == sorted(
290
+ nx.all_topological_sorts(DG)
291
+ )
292
+
293
+ def test_all_topological_sorts_multigraph_1(self):
294
+ DG = nx.MultiDiGraph([(1, 2), (1, 2), (2, 3), (3, 4), (3, 5), (3, 5), (3, 5)])
295
+ assert sorted(nx.all_topological_sorts(DG)) == sorted(
296
+ [[1, 2, 3, 4, 5], [1, 2, 3, 5, 4]]
297
+ )
298
+
299
+ def test_all_topological_sorts_multigraph_2(self):
300
+ N = 9
301
+ edges = []
302
+ for i in range(1, N):
303
+ edges.extend([(i, i + 1)] * i)
304
+ DG = nx.MultiDiGraph(edges)
305
+ assert list(nx.all_topological_sorts(DG)) == [list(range(1, N + 1))]
306
+
307
+ def test_ancestors(self):
308
+ G = nx.DiGraph()
309
+ ancestors = nx.algorithms.dag.ancestors
310
+ G.add_edges_from([(1, 2), (1, 3), (4, 2), (4, 3), (4, 5), (2, 6), (5, 6)])
311
+ assert ancestors(G, 6) == {1, 2, 4, 5}
312
+ assert ancestors(G, 3) == {1, 4}
313
+ assert ancestors(G, 1) == set()
314
+ pytest.raises(nx.NetworkXError, ancestors, G, 8)
315
+
316
+ def test_descendants(self):
317
+ G = nx.DiGraph()
318
+ descendants = nx.algorithms.dag.descendants
319
+ G.add_edges_from([(1, 2), (1, 3), (4, 2), (4, 3), (4, 5), (2, 6), (5, 6)])
320
+ assert descendants(G, 1) == {2, 3, 6}
321
+ assert descendants(G, 4) == {2, 3, 5, 6}
322
+ assert descendants(G, 3) == set()
323
+ pytest.raises(nx.NetworkXError, descendants, G, 8)
324
+
325
+ def test_transitive_closure(self):
326
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
327
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
328
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
329
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
330
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
331
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
332
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
333
+ solution = [(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)]
334
+ soln = sorted(solution + [(n, n) for n in G])
335
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), soln)
336
+
337
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
338
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
339
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
340
+
341
+ G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
342
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
343
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
344
+
345
+ G = nx.MultiDiGraph([(1, 2), (2, 3), (3, 4)])
346
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
347
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
348
+
349
+ # test if edge data is copied
350
+ G = nx.DiGraph([(1, 2, {"a": 3}), (2, 3, {"b": 0}), (3, 4)])
351
+ H = nx.transitive_closure(G)
352
+ for u, v in G.edges():
353
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
354
+
355
+ k = 10
356
+ G = nx.DiGraph((i, i + 1, {"f": "b", "weight": i}) for i in range(k))
357
+ H = nx.transitive_closure(G)
358
+ for u, v in G.edges():
359
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
360
+
361
+ G = nx.Graph()
362
+ with pytest.raises(nx.NetworkXError):
363
+ nx.transitive_closure(G, reflexive="wrong input")
364
+
365
+ def test_reflexive_transitive_closure(self):
366
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
367
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
368
+ soln = sorted(solution + [(n, n) for n in G])
369
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
370
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
371
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
372
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
373
+
374
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
375
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
376
+ soln = sorted(solution + [(n, n) for n in G])
377
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
378
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
379
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
380
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
381
+
382
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
383
+ solution = sorted([(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)])
384
+ soln = sorted(solution + [(n, n) for n in G])
385
+ assert edges_equal(sorted(nx.transitive_closure(G).edges()), soln)
386
+ assert edges_equal(sorted(nx.transitive_closure(G, False).edges()), soln)
387
+ assert edges_equal(sorted(nx.transitive_closure(G, None).edges()), solution)
388
+ assert edges_equal(sorted(nx.transitive_closure(G, True).edges()), soln)
389
+
390
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
391
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
392
+ soln = sorted(solution + [(n, n) for n in G])
393
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
394
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
395
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
396
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
397
+
398
+ G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
399
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
400
+ soln = sorted(solution + [(n, n) for n in G])
401
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
402
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
403
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
404
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
405
+
406
+ G = nx.MultiDiGraph([(1, 2), (2, 3), (3, 4)])
407
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
408
+ soln = sorted(solution + [(n, n) for n in G])
409
+ assert edges_equal(nx.transitive_closure(G).edges(), solution)
410
+ assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
411
+ assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
412
+ assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
413
+
414
+ def test_transitive_closure_dag(self):
415
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
416
+ transitive_closure = nx.algorithms.dag.transitive_closure_dag
417
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
418
+ assert edges_equal(transitive_closure(G).edges(), solution)
419
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
420
+ solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
421
+ assert edges_equal(transitive_closure(G).edges(), solution)
422
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
423
+ pytest.raises(nx.NetworkXNotImplemented, transitive_closure, G)
424
+
425
+ # test if edge data is copied
426
+ G = nx.DiGraph([(1, 2, {"a": 3}), (2, 3, {"b": 0}), (3, 4)])
427
+ H = transitive_closure(G)
428
+ for u, v in G.edges():
429
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
430
+
431
+ k = 10
432
+ G = nx.DiGraph((i, i + 1, {"foo": "bar", "weight": i}) for i in range(k))
433
+ H = transitive_closure(G)
434
+ for u, v in G.edges():
435
+ assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
436
+
437
+ def test_transitive_reduction(self):
438
+ G = nx.DiGraph([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)])
439
+ transitive_reduction = nx.algorithms.dag.transitive_reduction
440
+ solution = [(1, 2), (2, 3), (3, 4)]
441
+ assert edges_equal(transitive_reduction(G).edges(), solution)
442
+ G = nx.DiGraph([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)])
443
+ transitive_reduction = nx.algorithms.dag.transitive_reduction
444
+ solution = [(1, 2), (2, 3), (2, 4)]
445
+ assert edges_equal(transitive_reduction(G).edges(), solution)
446
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
447
+ pytest.raises(nx.NetworkXNotImplemented, transitive_reduction, G)
448
+
449
+ def _check_antichains(self, solution, result):
450
+ sol = [frozenset(a) for a in solution]
451
+ res = [frozenset(a) for a in result]
452
+ assert set(sol) == set(res)
453
+
454
+ def test_antichains(self):
455
+ antichains = nx.algorithms.dag.antichains
456
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
457
+ solution = [[], [4], [3], [2], [1]]
458
+ self._check_antichains(list(antichains(G)), solution)
459
+ G = nx.DiGraph([(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)])
460
+ solution = [
461
+ [],
462
+ [4],
463
+ [7],
464
+ [7, 4],
465
+ [6],
466
+ [6, 4],
467
+ [6, 7],
468
+ [6, 7, 4],
469
+ [5],
470
+ [5, 4],
471
+ [3],
472
+ [3, 4],
473
+ [2],
474
+ [1],
475
+ ]
476
+ self._check_antichains(list(antichains(G)), solution)
477
+ G = nx.DiGraph([(1, 2), (1, 3), (3, 4), (3, 5), (5, 6)])
478
+ solution = [
479
+ [],
480
+ [6],
481
+ [5],
482
+ [4],
483
+ [4, 6],
484
+ [4, 5],
485
+ [3],
486
+ [2],
487
+ [2, 6],
488
+ [2, 5],
489
+ [2, 4],
490
+ [2, 4, 6],
491
+ [2, 4, 5],
492
+ [2, 3],
493
+ [1],
494
+ ]
495
+ self._check_antichains(list(antichains(G)), solution)
496
+ G = nx.DiGraph({0: [1, 2], 1: [4], 2: [3], 3: [4]})
497
+ solution = [[], [4], [3], [2], [1], [1, 3], [1, 2], [0]]
498
+ self._check_antichains(list(antichains(G)), solution)
499
+ G = nx.DiGraph()
500
+ self._check_antichains(list(antichains(G)), [[]])
501
+ G = nx.DiGraph()
502
+ G.add_nodes_from([0, 1, 2])
503
+ solution = [[], [0], [1], [1, 0], [2], [2, 0], [2, 1], [2, 1, 0]]
504
+ self._check_antichains(list(antichains(G)), solution)
505
+
506
+ def f(x):
507
+ return list(antichains(x))
508
+
509
+ G = nx.Graph([(1, 2), (2, 3), (3, 4)])
510
+ pytest.raises(nx.NetworkXNotImplemented, f, G)
511
+ G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
512
+ pytest.raises(nx.NetworkXUnfeasible, f, G)
513
+
514
+ def test_lexicographical_topological_sort(self):
515
+ G = nx.DiGraph([(1, 2), (2, 3), (1, 4), (1, 5), (2, 6)])
516
+ assert list(nx.lexicographical_topological_sort(G)) == [1, 2, 3, 4, 5, 6]
517
+ assert list(nx.lexicographical_topological_sort(G, key=lambda x: x)) == [
518
+ 1,
519
+ 2,
520
+ 3,
521
+ 4,
522
+ 5,
523
+ 6,
524
+ ]
525
+ assert list(nx.lexicographical_topological_sort(G, key=lambda x: -x)) == [
526
+ 1,
527
+ 5,
528
+ 4,
529
+ 2,
530
+ 6,
531
+ 3,
532
+ ]
533
+
534
+ def test_lexicographical_topological_sort2(self):
535
+ """
536
+ Check the case of two or more nodes with same key value.
537
+ Want to avoid exception raised due to comparing nodes directly.
538
+ See Issue #3493
539
+ """
540
+
541
+ class Test_Node:
542
+ def __init__(self, n):
543
+ self.label = n
544
+ self.priority = 1
545
+
546
+ def __repr__(self):
547
+ return f"Node({self.label})"
548
+
549
+ def sorting_key(node):
550
+ return node.priority
551
+
552
+ test_nodes = [Test_Node(n) for n in range(4)]
553
+ G = nx.DiGraph()
554
+ edges = [(0, 1), (0, 2), (0, 3), (2, 3)]
555
+ G.add_edges_from((test_nodes[a], test_nodes[b]) for a, b in edges)
556
+
557
+ sorting = list(nx.lexicographical_topological_sort(G, key=sorting_key))
558
+ assert sorting == test_nodes
559
+
560
+
561
+ def test_topological_generations():
562
+ G = nx.DiGraph(
563
+ {1: [2, 3], 2: [4, 5], 3: [7], 4: [], 5: [6, 7], 6: [], 7: []}
564
+ ).reverse()
565
+ # order within each generation is inconsequential
566
+ generations = [sorted(gen) for gen in nx.topological_generations(G)]
567
+ expected = [[4, 6, 7], [3, 5], [2], [1]]
568
+ assert generations == expected
569
+
570
+ MG = nx.MultiDiGraph(G.edges)
571
+ MG.add_edge(2, 1)
572
+ generations = [sorted(gen) for gen in nx.topological_generations(MG)]
573
+ assert generations == expected
574
+
575
+
576
+ def test_topological_generations_empty():
577
+ G = nx.DiGraph()
578
+ assert list(nx.topological_generations(G)) == []
579
+
580
+
581
+ def test_topological_generations_cycle():
582
+ G = nx.DiGraph([[2, 1], [3, 1], [1, 2]])
583
+ with pytest.raises(nx.NetworkXUnfeasible):
584
+ list(nx.topological_generations(G))
585
+
586
+
587
+ def test_is_aperiodic_cycle():
588
+ G = nx.DiGraph()
589
+ nx.add_cycle(G, [1, 2, 3, 4])
590
+ assert not nx.is_aperiodic(G)
591
+
592
+
593
+ def test_is_aperiodic_cycle2():
594
+ G = nx.DiGraph()
595
+ nx.add_cycle(G, [1, 2, 3, 4])
596
+ nx.add_cycle(G, [3, 4, 5, 6, 7])
597
+ assert nx.is_aperiodic(G)
598
+
599
+
600
+ def test_is_aperiodic_cycle3():
601
+ G = nx.DiGraph()
602
+ nx.add_cycle(G, [1, 2, 3, 4])
603
+ nx.add_cycle(G, [3, 4, 5, 6])
604
+ assert not nx.is_aperiodic(G)
605
+
606
+
607
+ def test_is_aperiodic_cycle4():
608
+ G = nx.DiGraph()
609
+ nx.add_cycle(G, [1, 2, 3, 4])
610
+ G.add_edge(1, 3)
611
+ assert nx.is_aperiodic(G)
612
+
613
+
614
+ def test_is_aperiodic_selfloop():
615
+ G = nx.DiGraph()
616
+ nx.add_cycle(G, [1, 2, 3, 4])
617
+ G.add_edge(1, 1)
618
+ assert nx.is_aperiodic(G)
619
+
620
+
621
+ def test_is_aperiodic_undirected_raises():
622
+ G = nx.Graph()
623
+ pytest.raises(nx.NetworkXError, nx.is_aperiodic, G)
624
+
625
+
626
+ def test_is_aperiodic_empty_graph():
627
+ G = nx.empty_graph(create_using=nx.DiGraph)
628
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes."):
629
+ nx.is_aperiodic(G)
630
+
631
+
632
+ def test_is_aperiodic_bipartite():
633
+ # Bipartite graph
634
+ G = nx.DiGraph(nx.davis_southern_women_graph())
635
+ assert not nx.is_aperiodic(G)
636
+
637
+
638
+ def test_is_aperiodic_rary_tree():
639
+ G = nx.full_rary_tree(3, 27, create_using=nx.DiGraph())
640
+ assert not nx.is_aperiodic(G)
641
+
642
+
643
+ def test_is_aperiodic_disconnected():
644
+ # disconnected graph
645
+ G = nx.DiGraph()
646
+ nx.add_cycle(G, [1, 2, 3, 4])
647
+ nx.add_cycle(G, [5, 6, 7, 8])
648
+ assert not nx.is_aperiodic(G)
649
+ G.add_edge(1, 3)
650
+ G.add_edge(5, 7)
651
+ assert nx.is_aperiodic(G)
652
+
653
+
654
+ def test_is_aperiodic_disconnected2():
655
+ G = nx.DiGraph()
656
+ nx.add_cycle(G, [0, 1, 2])
657
+ G.add_edge(3, 3)
658
+ assert not nx.is_aperiodic(G)
659
+
660
+
661
+ class TestDagToBranching:
662
+ """Unit tests for the :func:`networkx.dag_to_branching` function."""
663
+
664
+ def test_single_root(self):
665
+ """Tests that a directed acyclic graph with a single degree
666
+ zero node produces an arborescence.
667
+
668
+ """
669
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)])
670
+ B = nx.dag_to_branching(G)
671
+ expected = nx.DiGraph([(0, 1), (1, 3), (0, 2), (2, 4)])
672
+ assert nx.is_arborescence(B)
673
+ assert nx.is_isomorphic(B, expected)
674
+
675
+ def test_multiple_roots(self):
676
+ """Tests that a directed acyclic graph with multiple degree zero
677
+ nodes creates an arborescence with multiple (weakly) connected
678
+ components.
679
+
680
+ """
681
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3), (5, 2)])
682
+ B = nx.dag_to_branching(G)
683
+ expected = nx.DiGraph([(0, 1), (1, 3), (0, 2), (2, 4), (5, 6), (6, 7)])
684
+ assert nx.is_branching(B)
685
+ assert not nx.is_arborescence(B)
686
+ assert nx.is_isomorphic(B, expected)
687
+
688
+ # # Attributes are not copied by this function. If they were, this would
689
+ # # be a good test to uncomment.
690
+ # def test_copy_attributes(self):
691
+ # """Tests that node attributes are copied in the branching."""
692
+ # G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)])
693
+ # for v in G:
694
+ # G.node[v]['label'] = str(v)
695
+ # B = nx.dag_to_branching(G)
696
+ # # Determine the root node of the branching.
697
+ # root = next(v for v, d in B.in_degree() if d == 0)
698
+ # assert_equal(B.node[root]['label'], '0')
699
+ # children = B[root]
700
+ # # Get the left and right children, nodes 1 and 2, respectively.
701
+ # left, right = sorted(children, key=lambda v: B.node[v]['label'])
702
+ # assert_equal(B.node[left]['label'], '1')
703
+ # assert_equal(B.node[right]['label'], '2')
704
+ # # Get the left grandchild.
705
+ # children = B[left]
706
+ # assert_equal(len(children), 1)
707
+ # left_grandchild = arbitrary_element(children)
708
+ # assert_equal(B.node[left_grandchild]['label'], '3')
709
+ # # Get the right grandchild.
710
+ # children = B[right]
711
+ # assert_equal(len(children), 1)
712
+ # right_grandchild = arbitrary_element(children)
713
+ # assert_equal(B.node[right_grandchild]['label'], '3')
714
+
715
+ def test_already_arborescence(self):
716
+ """Tests that a directed acyclic graph that is already an
717
+ arborescence produces an isomorphic arborescence as output.
718
+
719
+ """
720
+ A = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
721
+ B = nx.dag_to_branching(A)
722
+ assert nx.is_isomorphic(A, B)
723
+
724
+ def test_already_branching(self):
725
+ """Tests that a directed acyclic graph that is already a
726
+ branching produces an isomorphic branching as output.
727
+
728
+ """
729
+ T1 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
730
+ T2 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
731
+ G = nx.disjoint_union(T1, T2)
732
+ B = nx.dag_to_branching(G)
733
+ assert nx.is_isomorphic(G, B)
734
+
735
+ def test_not_acyclic(self):
736
+ """Tests that a non-acyclic graph causes an exception."""
737
+ with pytest.raises(nx.HasACycle):
738
+ G = nx.DiGraph(pairwise("abc", cyclic=True))
739
+ nx.dag_to_branching(G)
740
+
741
+ def test_undirected(self):
742
+ with pytest.raises(nx.NetworkXNotImplemented):
743
+ nx.dag_to_branching(nx.Graph())
744
+
745
+ def test_multigraph(self):
746
+ with pytest.raises(nx.NetworkXNotImplemented):
747
+ nx.dag_to_branching(nx.MultiGraph())
748
+
749
+ def test_multidigraph(self):
750
+ with pytest.raises(nx.NetworkXNotImplemented):
751
+ nx.dag_to_branching(nx.MultiDiGraph())
752
+
753
+
754
+ def test_ancestors_descendants_undirected():
755
+ """Regression test to ensure ancestors and descendants work as expected on
756
+ undirected graphs."""
757
+ G = nx.path_graph(5)
758
+ nx.ancestors(G, 2) == nx.descendants(G, 2) == {0, 1, 3, 4}
759
+
760
+
761
+ def test_compute_v_structures_raise():
762
+ G = nx.Graph()
763
+ with pytest.raises(nx.NetworkXNotImplemented, match="for undirected type"):
764
+ nx.compute_v_structures(G)
765
+
766
+
767
+ def test_compute_v_structures():
768
+ edges = [(0, 1), (0, 2), (3, 2)]
769
+ G = nx.DiGraph(edges)
770
+
771
+ v_structs = set(nx.compute_v_structures(G))
772
+ assert len(v_structs) == 1
773
+ assert (0, 2, 3) in v_structs
774
+
775
+ edges = [("A", "B"), ("C", "B"), ("B", "D"), ("D", "E"), ("G", "E")]
776
+ G = nx.DiGraph(edges)
777
+ v_structs = set(nx.compute_v_structures(G))
778
+ assert len(v_structs) == 2
779
+
780
+
781
+ def test_compute_v_structures_deprecated():
782
+ G = nx.DiGraph()
783
+ with pytest.deprecated_call():
784
+ nx.compute_v_structures(G)
785
+
786
+
787
+ def test_v_structures_raise():
788
+ G = nx.Graph()
789
+ with pytest.raises(nx.NetworkXNotImplemented, match="for undirected type"):
790
+ nx.dag.v_structures(G)
791
+
792
+
793
+ @pytest.mark.parametrize(
794
+ ("edgelist", "expected"),
795
+ (
796
+ (
797
+ [(0, 1), (0, 2), (3, 2)],
798
+ {(0, 2, 3)},
799
+ ),
800
+ (
801
+ [("A", "B"), ("C", "B"), ("D", "G"), ("D", "E"), ("G", "E")],
802
+ {("A", "B", "C")},
803
+ ),
804
+ ([(0, 1), (2, 1), (0, 2)], set()), # adjacent parents case: see gh-7385
805
+ ),
806
+ )
807
+ def test_v_structures(edgelist, expected):
808
+ G = nx.DiGraph(edgelist)
809
+ v_structs = set(nx.dag.v_structures(G))
810
+ assert v_structs == expected
811
+
812
+
813
+ def test_colliders_raise():
814
+ G = nx.Graph()
815
+ with pytest.raises(nx.NetworkXNotImplemented, match="for undirected type"):
816
+ nx.dag.colliders(G)
817
+
818
+
819
+ @pytest.mark.parametrize(
820
+ ("edgelist", "expected"),
821
+ (
822
+ (
823
+ [(0, 1), (0, 2), (3, 2)],
824
+ {(0, 2, 3)},
825
+ ),
826
+ (
827
+ [("A", "B"), ("C", "B"), ("D", "G"), ("D", "E"), ("G", "E")],
828
+ {("A", "B", "C"), ("D", "E", "G")},
829
+ ),
830
+ ),
831
+ )
832
+ def test_colliders(edgelist, expected):
833
+ G = nx.DiGraph(edgelist)
834
+ colliders = set(nx.dag.colliders(G))
835
+ assert colliders == expected
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_distance_measures.py ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from random import Random
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx import convert_node_labels_to_integers as cnlti
8
+ from networkx.algorithms.distance_measures import _extrema_bounding
9
+
10
+
11
+ def test__extrema_bounding_invalid_compute_kwarg():
12
+ G = nx.path_graph(3)
13
+ with pytest.raises(ValueError, match="compute must be one of"):
14
+ _extrema_bounding(G, compute="spam")
15
+
16
+
17
+ class TestDistance:
18
+ def setup_method(self):
19
+ G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
20
+ self.G = G
21
+
22
+ def test_eccentricity(self):
23
+ assert nx.eccentricity(self.G, 1) == 6
24
+ e = nx.eccentricity(self.G)
25
+ assert e[1] == 6
26
+
27
+ sp = dict(nx.shortest_path_length(self.G))
28
+ e = nx.eccentricity(self.G, sp=sp)
29
+ assert e[1] == 6
30
+
31
+ e = nx.eccentricity(self.G, v=1)
32
+ assert e == 6
33
+
34
+ # This behavior changed in version 1.8 (ticket #739)
35
+ e = nx.eccentricity(self.G, v=[1, 1])
36
+ assert e[1] == 6
37
+ e = nx.eccentricity(self.G, v=[1, 2])
38
+ assert e[1] == 6
39
+
40
+ # test against graph with one node
41
+ G = nx.path_graph(1)
42
+ e = nx.eccentricity(G)
43
+ assert e[0] == 0
44
+ e = nx.eccentricity(G, v=0)
45
+ assert e == 0
46
+ pytest.raises(nx.NetworkXError, nx.eccentricity, G, 1)
47
+
48
+ # test against empty graph
49
+ G = nx.empty_graph()
50
+ e = nx.eccentricity(G)
51
+ assert e == {}
52
+
53
+ def test_diameter(self):
54
+ assert nx.diameter(self.G) == 6
55
+
56
+ def test_harmonic_diameter(self):
57
+ assert abs(nx.harmonic_diameter(self.G) - 2.0477815699658715) < 1e-12
58
+
59
+ def test_harmonic_diameter_empty(self):
60
+ assert math.isnan(nx.harmonic_diameter(nx.empty_graph()))
61
+
62
+ def test_harmonic_diameter_single_node(self):
63
+ assert math.isnan(nx.harmonic_diameter(nx.empty_graph(1)))
64
+
65
+ def test_harmonic_diameter_discrete(self):
66
+ assert math.isinf(nx.harmonic_diameter(nx.empty_graph(3)))
67
+
68
+ def test_harmonic_diameter_not_strongly_connected(self):
69
+ DG = nx.DiGraph()
70
+ DG.add_edge(0, 1)
71
+ assert nx.harmonic_diameter(DG) == 2
72
+
73
+ def test_radius(self):
74
+ assert nx.radius(self.G) == 4
75
+
76
+ def test_periphery(self):
77
+ assert set(nx.periphery(self.G)) == {1, 4, 13, 16}
78
+
79
+ def test_center(self):
80
+ assert set(nx.center(self.G)) == {6, 7, 10, 11}
81
+
82
+ def test_bound_diameter(self):
83
+ assert nx.diameter(self.G, usebounds=True) == 6
84
+
85
+ def test_bound_radius(self):
86
+ assert nx.radius(self.G, usebounds=True) == 4
87
+
88
+ def test_bound_periphery(self):
89
+ result = {1, 4, 13, 16}
90
+ assert set(nx.periphery(self.G, usebounds=True)) == result
91
+
92
+ def test_bound_center(self):
93
+ result = {6, 7, 10, 11}
94
+ assert set(nx.center(self.G, usebounds=True)) == result
95
+
96
+ def test_radius_exception(self):
97
+ G = nx.Graph()
98
+ G.add_edge(1, 2)
99
+ G.add_edge(3, 4)
100
+ pytest.raises(nx.NetworkXError, nx.diameter, G)
101
+
102
+ def test_eccentricity_infinite(self):
103
+ with pytest.raises(nx.NetworkXError):
104
+ G = nx.Graph([(1, 2), (3, 4)])
105
+ e = nx.eccentricity(G)
106
+
107
+ def test_eccentricity_undirected_not_connected(self):
108
+ with pytest.raises(nx.NetworkXError):
109
+ G = nx.Graph([(1, 2), (3, 4)])
110
+ e = nx.eccentricity(G, sp=1)
111
+
112
+ def test_eccentricity_directed_weakly_connected(self):
113
+ with pytest.raises(nx.NetworkXError):
114
+ DG = nx.DiGraph([(1, 2), (1, 3)])
115
+ nx.eccentricity(DG)
116
+
117
+
118
+ class TestWeightedDistance:
119
+ def setup_method(self):
120
+ G = nx.Graph()
121
+ G.add_edge(0, 1, weight=0.6, cost=0.6, high_cost=6)
122
+ G.add_edge(0, 2, weight=0.2, cost=0.2, high_cost=2)
123
+ G.add_edge(2, 3, weight=0.1, cost=0.1, high_cost=1)
124
+ G.add_edge(2, 4, weight=0.7, cost=0.7, high_cost=7)
125
+ G.add_edge(2, 5, weight=0.9, cost=0.9, high_cost=9)
126
+ G.add_edge(1, 5, weight=0.3, cost=0.3, high_cost=3)
127
+ self.G = G
128
+ self.weight_fn = lambda v, u, e: 2
129
+
130
+ def test_eccentricity_weight_None(self):
131
+ assert nx.eccentricity(self.G, 1, weight=None) == 3
132
+ e = nx.eccentricity(self.G, weight=None)
133
+ assert e[1] == 3
134
+
135
+ e = nx.eccentricity(self.G, v=1, weight=None)
136
+ assert e == 3
137
+
138
+ # This behavior changed in version 1.8 (ticket #739)
139
+ e = nx.eccentricity(self.G, v=[1, 1], weight=None)
140
+ assert e[1] == 3
141
+ e = nx.eccentricity(self.G, v=[1, 2], weight=None)
142
+ assert e[1] == 3
143
+
144
+ def test_eccentricity_weight_attr(self):
145
+ assert nx.eccentricity(self.G, 1, weight="weight") == 1.5
146
+ e = nx.eccentricity(self.G, weight="weight")
147
+ assert (
148
+ e
149
+ == nx.eccentricity(self.G, weight="cost")
150
+ != nx.eccentricity(self.G, weight="high_cost")
151
+ )
152
+ assert e[1] == 1.5
153
+
154
+ e = nx.eccentricity(self.G, v=1, weight="weight")
155
+ assert e == 1.5
156
+
157
+ # This behavior changed in version 1.8 (ticket #739)
158
+ e = nx.eccentricity(self.G, v=[1, 1], weight="weight")
159
+ assert e[1] == 1.5
160
+ e = nx.eccentricity(self.G, v=[1, 2], weight="weight")
161
+ assert e[1] == 1.5
162
+
163
+ def test_eccentricity_weight_fn(self):
164
+ assert nx.eccentricity(self.G, 1, weight=self.weight_fn) == 6
165
+ e = nx.eccentricity(self.G, weight=self.weight_fn)
166
+ assert e[1] == 6
167
+
168
+ e = nx.eccentricity(self.G, v=1, weight=self.weight_fn)
169
+ assert e == 6
170
+
171
+ # This behavior changed in version 1.8 (ticket #739)
172
+ e = nx.eccentricity(self.G, v=[1, 1], weight=self.weight_fn)
173
+ assert e[1] == 6
174
+ e = nx.eccentricity(self.G, v=[1, 2], weight=self.weight_fn)
175
+ assert e[1] == 6
176
+
177
+ def test_diameter_weight_None(self):
178
+ assert nx.diameter(self.G, weight=None) == 3
179
+
180
+ def test_diameter_weight_attr(self):
181
+ assert (
182
+ nx.diameter(self.G, weight="weight")
183
+ == nx.diameter(self.G, weight="cost")
184
+ == 1.6
185
+ != nx.diameter(self.G, weight="high_cost")
186
+ )
187
+
188
+ def test_diameter_weight_fn(self):
189
+ assert nx.diameter(self.G, weight=self.weight_fn) == 6
190
+
191
+ def test_radius_weight_None(self):
192
+ assert pytest.approx(nx.radius(self.G, weight=None)) == 2
193
+
194
+ def test_radius_weight_attr(self):
195
+ assert (
196
+ pytest.approx(nx.radius(self.G, weight="weight"))
197
+ == pytest.approx(nx.radius(self.G, weight="cost"))
198
+ == 0.9
199
+ != nx.radius(self.G, weight="high_cost")
200
+ )
201
+
202
+ def test_radius_weight_fn(self):
203
+ assert nx.radius(self.G, weight=self.weight_fn) == 4
204
+
205
+ def test_periphery_weight_None(self):
206
+ for v in set(nx.periphery(self.G, weight=None)):
207
+ assert nx.eccentricity(self.G, v, weight=None) == nx.diameter(
208
+ self.G, weight=None
209
+ )
210
+
211
+ def test_periphery_weight_attr(self):
212
+ periphery = set(nx.periphery(self.G, weight="weight"))
213
+ assert (
214
+ periphery
215
+ == set(nx.periphery(self.G, weight="cost"))
216
+ == set(nx.periphery(self.G, weight="high_cost"))
217
+ )
218
+ for v in periphery:
219
+ assert (
220
+ nx.eccentricity(self.G, v, weight="high_cost")
221
+ != nx.eccentricity(self.G, v, weight="weight")
222
+ == nx.eccentricity(self.G, v, weight="cost")
223
+ == nx.diameter(self.G, weight="weight")
224
+ == nx.diameter(self.G, weight="cost")
225
+ != nx.diameter(self.G, weight="high_cost")
226
+ )
227
+ assert nx.eccentricity(self.G, v, weight="high_cost") == nx.diameter(
228
+ self.G, weight="high_cost"
229
+ )
230
+
231
+ def test_periphery_weight_fn(self):
232
+ for v in set(nx.periphery(self.G, weight=self.weight_fn)):
233
+ assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.diameter(
234
+ self.G, weight=self.weight_fn
235
+ )
236
+
237
+ def test_center_weight_None(self):
238
+ for v in set(nx.center(self.G, weight=None)):
239
+ assert pytest.approx(nx.eccentricity(self.G, v, weight=None)) == nx.radius(
240
+ self.G, weight=None
241
+ )
242
+
243
+ def test_center_weight_attr(self):
244
+ center = set(nx.center(self.G, weight="weight"))
245
+ assert (
246
+ center
247
+ == set(nx.center(self.G, weight="cost"))
248
+ != set(nx.center(self.G, weight="high_cost"))
249
+ )
250
+ for v in center:
251
+ assert (
252
+ nx.eccentricity(self.G, v, weight="high_cost")
253
+ != pytest.approx(nx.eccentricity(self.G, v, weight="weight"))
254
+ == pytest.approx(nx.eccentricity(self.G, v, weight="cost"))
255
+ == nx.radius(self.G, weight="weight")
256
+ == nx.radius(self.G, weight="cost")
257
+ != nx.radius(self.G, weight="high_cost")
258
+ )
259
+ assert nx.eccentricity(self.G, v, weight="high_cost") == nx.radius(
260
+ self.G, weight="high_cost"
261
+ )
262
+
263
+ def test_center_weight_fn(self):
264
+ for v in set(nx.center(self.G, weight=self.weight_fn)):
265
+ assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.radius(
266
+ self.G, weight=self.weight_fn
267
+ )
268
+
269
+ def test_bound_diameter_weight_None(self):
270
+ assert nx.diameter(self.G, usebounds=True, weight=None) == 3
271
+
272
+ def test_bound_diameter_weight_attr(self):
273
+ assert (
274
+ nx.diameter(self.G, usebounds=True, weight="high_cost")
275
+ != nx.diameter(self.G, usebounds=True, weight="weight")
276
+ == nx.diameter(self.G, usebounds=True, weight="cost")
277
+ == 1.6
278
+ != nx.diameter(self.G, usebounds=True, weight="high_cost")
279
+ )
280
+ assert nx.diameter(self.G, usebounds=True, weight="high_cost") == nx.diameter(
281
+ self.G, usebounds=True, weight="high_cost"
282
+ )
283
+
284
+ def test_bound_diameter_weight_fn(self):
285
+ assert nx.diameter(self.G, usebounds=True, weight=self.weight_fn) == 6
286
+
287
+ def test_bound_radius_weight_None(self):
288
+ assert pytest.approx(nx.radius(self.G, usebounds=True, weight=None)) == 2
289
+
290
+ def test_bound_radius_weight_attr(self):
291
+ assert (
292
+ nx.radius(self.G, usebounds=True, weight="high_cost")
293
+ != pytest.approx(nx.radius(self.G, usebounds=True, weight="weight"))
294
+ == pytest.approx(nx.radius(self.G, usebounds=True, weight="cost"))
295
+ == 0.9
296
+ != nx.radius(self.G, usebounds=True, weight="high_cost")
297
+ )
298
+ assert nx.radius(self.G, usebounds=True, weight="high_cost") == nx.radius(
299
+ self.G, usebounds=True, weight="high_cost"
300
+ )
301
+
302
+ def test_bound_radius_weight_fn(self):
303
+ assert nx.radius(self.G, usebounds=True, weight=self.weight_fn) == 4
304
+
305
+ def test_bound_periphery_weight_None(self):
306
+ result = {1, 3, 4}
307
+ assert set(nx.periphery(self.G, usebounds=True, weight=None)) == result
308
+
309
+ def test_bound_periphery_weight_attr(self):
310
+ result = {4, 5}
311
+ assert (
312
+ set(nx.periphery(self.G, usebounds=True, weight="weight"))
313
+ == set(nx.periphery(self.G, usebounds=True, weight="cost"))
314
+ == result
315
+ )
316
+
317
+ def test_bound_periphery_weight_fn(self):
318
+ result = {1, 3, 4}
319
+ assert (
320
+ set(nx.periphery(self.G, usebounds=True, weight=self.weight_fn)) == result
321
+ )
322
+
323
+ def test_bound_center_weight_None(self):
324
+ result = {0, 2, 5}
325
+ assert set(nx.center(self.G, usebounds=True, weight=None)) == result
326
+
327
+ def test_bound_center_weight_attr(self):
328
+ result = {0}
329
+ assert (
330
+ set(nx.center(self.G, usebounds=True, weight="weight"))
331
+ == set(nx.center(self.G, usebounds=True, weight="cost"))
332
+ == result
333
+ )
334
+
335
+ def test_bound_center_weight_fn(self):
336
+ result = {0, 2, 5}
337
+ assert set(nx.center(self.G, usebounds=True, weight=self.weight_fn)) == result
338
+
339
+
340
+ class TestResistanceDistance:
341
+ @classmethod
342
+ def setup_class(cls):
343
+ global np
344
+ np = pytest.importorskip("numpy")
345
+ sp = pytest.importorskip("scipy")
346
+
347
+ def setup_method(self):
348
+ G = nx.Graph()
349
+ G.add_edge(1, 2, weight=2)
350
+ G.add_edge(2, 3, weight=4)
351
+ G.add_edge(3, 4, weight=1)
352
+ G.add_edge(1, 4, weight=3)
353
+ self.G = G
354
+
355
+ def test_resistance_distance_directed_graph(self):
356
+ G = nx.DiGraph()
357
+ with pytest.raises(nx.NetworkXNotImplemented):
358
+ nx.resistance_distance(G)
359
+
360
+ def test_resistance_distance_empty(self):
361
+ G = nx.Graph()
362
+ with pytest.raises(nx.NetworkXError):
363
+ nx.resistance_distance(G)
364
+
365
+ def test_resistance_distance_not_connected(self):
366
+ with pytest.raises(nx.NetworkXError):
367
+ self.G.add_node(5)
368
+ nx.resistance_distance(self.G, 1, 5)
369
+
370
+ def test_resistance_distance_nodeA_not_in_graph(self):
371
+ with pytest.raises(nx.NetworkXError):
372
+ nx.resistance_distance(self.G, 9, 1)
373
+
374
+ def test_resistance_distance_nodeB_not_in_graph(self):
375
+ with pytest.raises(nx.NetworkXError):
376
+ nx.resistance_distance(self.G, 1, 9)
377
+
378
+ def test_resistance_distance(self):
379
+ rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
380
+ test_data = 1 / (1 / (2 + 4) + 1 / (1 + 3))
381
+ assert round(rd, 5) == round(test_data, 5)
382
+
383
+ def test_resistance_distance_noinv(self):
384
+ rd = nx.resistance_distance(self.G, 1, 3, "weight", False)
385
+ test_data = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1 + 1 / 3))
386
+ assert round(rd, 5) == round(test_data, 5)
387
+
388
+ def test_resistance_distance_no_weight(self):
389
+ rd = nx.resistance_distance(self.G, 1, 3)
390
+ assert round(rd, 5) == 1
391
+
392
+ def test_resistance_distance_neg_weight(self):
393
+ self.G[2][3]["weight"] = -4
394
+ rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
395
+ test_data = 1 / (1 / (2 + -4) + 1 / (1 + 3))
396
+ assert round(rd, 5) == round(test_data, 5)
397
+
398
+ def test_multigraph(self):
399
+ G = nx.MultiGraph()
400
+ G.add_edge(1, 2, weight=2)
401
+ G.add_edge(2, 3, weight=4)
402
+ G.add_edge(3, 4, weight=1)
403
+ G.add_edge(1, 4, weight=3)
404
+ rd = nx.resistance_distance(G, 1, 3, "weight", True)
405
+ assert np.isclose(rd, 1 / (1 / (2 + 4) + 1 / (1 + 3)))
406
+
407
+ def test_resistance_distance_div0(self):
408
+ with pytest.raises(ZeroDivisionError):
409
+ self.G[1][2]["weight"] = 0
410
+ nx.resistance_distance(self.G, 1, 3, "weight")
411
+
412
+ def test_resistance_distance_same_node(self):
413
+ assert nx.resistance_distance(self.G, 1, 1) == 0
414
+
415
+ def test_resistance_distance_only_nodeA(self):
416
+ rd = nx.resistance_distance(self.G, nodeA=1)
417
+ test_data = {}
418
+ test_data[1] = 0
419
+ test_data[2] = 0.75
420
+ test_data[3] = 1
421
+ test_data[4] = 0.75
422
+ assert type(rd) == dict
423
+ assert sorted(rd.keys()) == sorted(test_data.keys())
424
+ for key in rd:
425
+ assert np.isclose(rd[key], test_data[key])
426
+
427
+ def test_resistance_distance_only_nodeB(self):
428
+ rd = nx.resistance_distance(self.G, nodeB=1)
429
+ test_data = {}
430
+ test_data[1] = 0
431
+ test_data[2] = 0.75
432
+ test_data[3] = 1
433
+ test_data[4] = 0.75
434
+ assert type(rd) == dict
435
+ assert sorted(rd.keys()) == sorted(test_data.keys())
436
+ for key in rd:
437
+ assert np.isclose(rd[key], test_data[key])
438
+
439
+ def test_resistance_distance_all(self):
440
+ rd = nx.resistance_distance(self.G)
441
+ assert type(rd) == dict
442
+ assert round(rd[1][3], 5) == 1
443
+
444
+
445
+ class TestEffectiveGraphResistance:
446
+ @classmethod
447
+ def setup_class(cls):
448
+ global np
449
+ np = pytest.importorskip("numpy")
450
+ sp = pytest.importorskip("scipy")
451
+
452
+ def setup_method(self):
453
+ G = nx.Graph()
454
+ G.add_edge(1, 2, weight=2)
455
+ G.add_edge(1, 3, weight=1)
456
+ G.add_edge(2, 3, weight=4)
457
+ self.G = G
458
+
459
+ def test_effective_graph_resistance_directed_graph(self):
460
+ G = nx.DiGraph()
461
+ with pytest.raises(nx.NetworkXNotImplemented):
462
+ nx.effective_graph_resistance(G)
463
+
464
+ def test_effective_graph_resistance_empty(self):
465
+ G = nx.Graph()
466
+ with pytest.raises(nx.NetworkXError):
467
+ nx.effective_graph_resistance(G)
468
+
469
+ def test_effective_graph_resistance_not_connected(self):
470
+ G = nx.Graph([(1, 2), (3, 4)])
471
+ RG = nx.effective_graph_resistance(G)
472
+ assert np.isinf(RG)
473
+
474
+ def test_effective_graph_resistance(self):
475
+ RG = nx.effective_graph_resistance(self.G, "weight", True)
476
+ rd12 = 1 / (1 / (1 + 4) + 1 / 2)
477
+ rd13 = 1 / (1 / (1 + 2) + 1 / 4)
478
+ rd23 = 1 / (1 / (2 + 4) + 1 / 1)
479
+ assert np.isclose(RG, rd12 + rd13 + rd23)
480
+
481
+ def test_effective_graph_resistance_noinv(self):
482
+ RG = nx.effective_graph_resistance(self.G, "weight", False)
483
+ rd12 = 1 / (1 / (1 / 1 + 1 / 4) + 1 / (1 / 2))
484
+ rd13 = 1 / (1 / (1 / 1 + 1 / 2) + 1 / (1 / 4))
485
+ rd23 = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1))
486
+ assert np.isclose(RG, rd12 + rd13 + rd23)
487
+
488
+ def test_effective_graph_resistance_no_weight(self):
489
+ RG = nx.effective_graph_resistance(self.G)
490
+ assert np.isclose(RG, 2)
491
+
492
+ def test_effective_graph_resistance_neg_weight(self):
493
+ self.G[2][3]["weight"] = -4
494
+ RG = nx.effective_graph_resistance(self.G, "weight", True)
495
+ rd12 = 1 / (1 / (1 + -4) + 1 / 2)
496
+ rd13 = 1 / (1 / (1 + 2) + 1 / (-4))
497
+ rd23 = 1 / (1 / (2 + -4) + 1 / 1)
498
+ assert np.isclose(RG, rd12 + rd13 + rd23)
499
+
500
+ def test_effective_graph_resistance_multigraph(self):
501
+ G = nx.MultiGraph()
502
+ G.add_edge(1, 2, weight=2)
503
+ G.add_edge(1, 3, weight=1)
504
+ G.add_edge(2, 3, weight=1)
505
+ G.add_edge(2, 3, weight=3)
506
+ RG = nx.effective_graph_resistance(G, "weight", True)
507
+ edge23 = 1 / (1 / 1 + 1 / 3)
508
+ rd12 = 1 / (1 / (1 + edge23) + 1 / 2)
509
+ rd13 = 1 / (1 / (1 + 2) + 1 / edge23)
510
+ rd23 = 1 / (1 / (2 + edge23) + 1 / 1)
511
+ assert np.isclose(RG, rd12 + rd13 + rd23)
512
+
513
+ def test_effective_graph_resistance_div0(self):
514
+ with pytest.raises(ZeroDivisionError):
515
+ self.G[1][2]["weight"] = 0
516
+ nx.effective_graph_resistance(self.G, "weight")
517
+
518
+ def test_effective_graph_resistance_complete_graph(self):
519
+ N = 10
520
+ G = nx.complete_graph(N)
521
+ RG = nx.effective_graph_resistance(G)
522
+ assert np.isclose(RG, N - 1)
523
+
524
+ def test_effective_graph_resistance_path_graph(self):
525
+ N = 10
526
+ G = nx.path_graph(N)
527
+ RG = nx.effective_graph_resistance(G)
528
+ assert np.isclose(RG, (N - 1) * N * (N + 1) // 6)
529
+
530
+
531
+ class TestBarycenter:
532
+ """Test :func:`networkx.algorithms.distance_measures.barycenter`."""
533
+
534
+ def barycenter_as_subgraph(self, g, **kwargs):
535
+ """Return the subgraph induced on the barycenter of g"""
536
+ b = nx.barycenter(g, **kwargs)
537
+ assert isinstance(b, list)
538
+ assert set(b) <= set(g)
539
+ return g.subgraph(b)
540
+
541
+ def test_must_be_connected(self):
542
+ pytest.raises(nx.NetworkXNoPath, nx.barycenter, nx.empty_graph(5))
543
+
544
+ def test_sp_kwarg(self):
545
+ # Complete graph K_5. Normally it works...
546
+ K_5 = nx.complete_graph(5)
547
+ sp = dict(nx.shortest_path_length(K_5))
548
+ assert nx.barycenter(K_5, sp=sp) == list(K_5)
549
+
550
+ # ...but not with the weight argument
551
+ for u, v, data in K_5.edges.data():
552
+ data["weight"] = 1
553
+ pytest.raises(ValueError, nx.barycenter, K_5, sp=sp, weight="weight")
554
+
555
+ # ...and a corrupted sp can make it seem like K_5 is disconnected
556
+ del sp[0][1]
557
+ pytest.raises(nx.NetworkXNoPath, nx.barycenter, K_5, sp=sp)
558
+
559
+ def test_trees(self):
560
+ """The barycenter of a tree is a single vertex or an edge.
561
+
562
+ See [West01]_, p. 78.
563
+ """
564
+ prng = Random(0xDEADBEEF)
565
+ for i in range(50):
566
+ RT = nx.random_labeled_tree(prng.randint(1, 75), seed=prng)
567
+ b = self.barycenter_as_subgraph(RT)
568
+ if len(b) == 2:
569
+ assert b.size() == 1
570
+ else:
571
+ assert len(b) == 1
572
+ assert b.size() == 0
573
+
574
+ def test_this_one_specific_tree(self):
575
+ """Test the tree pictured at the bottom of [West01]_, p. 78."""
576
+ g = nx.Graph(
577
+ {
578
+ "a": ["b"],
579
+ "b": ["a", "x"],
580
+ "x": ["b", "y"],
581
+ "y": ["x", "z"],
582
+ "z": ["y", 0, 1, 2, 3, 4],
583
+ 0: ["z"],
584
+ 1: ["z"],
585
+ 2: ["z"],
586
+ 3: ["z"],
587
+ 4: ["z"],
588
+ }
589
+ )
590
+ b = self.barycenter_as_subgraph(g, attr="barycentricity")
591
+ assert list(b) == ["z"]
592
+ assert not b.edges
593
+ expected_barycentricity = {
594
+ 0: 23,
595
+ 1: 23,
596
+ 2: 23,
597
+ 3: 23,
598
+ 4: 23,
599
+ "a": 35,
600
+ "b": 27,
601
+ "x": 21,
602
+ "y": 17,
603
+ "z": 15,
604
+ }
605
+ for node, barycentricity in expected_barycentricity.items():
606
+ assert g.nodes[node]["barycentricity"] == barycentricity
607
+
608
+ # Doubling weights should do nothing but double the barycentricities
609
+ for edge in g.edges:
610
+ g.edges[edge]["weight"] = 2
611
+ b = self.barycenter_as_subgraph(g, weight="weight", attr="barycentricity2")
612
+ assert list(b) == ["z"]
613
+ assert not b.edges
614
+ for node, barycentricity in expected_barycentricity.items():
615
+ assert g.nodes[node]["barycentricity2"] == barycentricity * 2
616
+
617
+
618
+ class TestKemenyConstant:
619
+ @classmethod
620
+ def setup_class(cls):
621
+ global np
622
+ np = pytest.importorskip("numpy")
623
+ sp = pytest.importorskip("scipy")
624
+
625
+ def setup_method(self):
626
+ G = nx.Graph()
627
+ w12 = 2
628
+ w13 = 3
629
+ w23 = 4
630
+ G.add_edge(1, 2, weight=w12)
631
+ G.add_edge(1, 3, weight=w13)
632
+ G.add_edge(2, 3, weight=w23)
633
+ self.G = G
634
+
635
+ def test_kemeny_constant_directed(self):
636
+ G = nx.DiGraph()
637
+ G.add_edge(1, 2)
638
+ G.add_edge(1, 3)
639
+ G.add_edge(2, 3)
640
+ with pytest.raises(nx.NetworkXNotImplemented):
641
+ nx.kemeny_constant(G)
642
+
643
+ def test_kemeny_constant_not_connected(self):
644
+ self.G.add_node(5)
645
+ with pytest.raises(nx.NetworkXError):
646
+ nx.kemeny_constant(self.G)
647
+
648
+ def test_kemeny_constant_no_nodes(self):
649
+ G = nx.Graph()
650
+ with pytest.raises(nx.NetworkXError):
651
+ nx.kemeny_constant(G)
652
+
653
+ def test_kemeny_constant_negative_weight(self):
654
+ G = nx.Graph()
655
+ w12 = 2
656
+ w13 = 3
657
+ w23 = -10
658
+ G.add_edge(1, 2, weight=w12)
659
+ G.add_edge(1, 3, weight=w13)
660
+ G.add_edge(2, 3, weight=w23)
661
+ with pytest.raises(nx.NetworkXError):
662
+ nx.kemeny_constant(G, weight="weight")
663
+
664
+ def test_kemeny_constant(self):
665
+ K = nx.kemeny_constant(self.G, weight="weight")
666
+ w12 = 2
667
+ w13 = 3
668
+ w23 = 4
669
+ test_data = (
670
+ 3
671
+ / 2
672
+ * (w12 + w13)
673
+ * (w12 + w23)
674
+ * (w13 + w23)
675
+ / (
676
+ w12**2 * (w13 + w23)
677
+ + w13**2 * (w12 + w23)
678
+ + w23**2 * (w12 + w13)
679
+ + 3 * w12 * w13 * w23
680
+ )
681
+ )
682
+ assert np.isclose(K, test_data)
683
+
684
+ def test_kemeny_constant_no_weight(self):
685
+ K = nx.kemeny_constant(self.G)
686
+ assert np.isclose(K, 4 / 3)
687
+
688
+ def test_kemeny_constant_multigraph(self):
689
+ G = nx.MultiGraph()
690
+ w12_1 = 2
691
+ w12_2 = 1
692
+ w13 = 3
693
+ w23 = 4
694
+ G.add_edge(1, 2, weight=w12_1)
695
+ G.add_edge(1, 2, weight=w12_2)
696
+ G.add_edge(1, 3, weight=w13)
697
+ G.add_edge(2, 3, weight=w23)
698
+ K = nx.kemeny_constant(G, weight="weight")
699
+ w12 = w12_1 + w12_2
700
+ test_data = (
701
+ 3
702
+ / 2
703
+ * (w12 + w13)
704
+ * (w12 + w23)
705
+ * (w13 + w23)
706
+ / (
707
+ w12**2 * (w13 + w23)
708
+ + w13**2 * (w12 + w23)
709
+ + w23**2 * (w12 + w13)
710
+ + 3 * w12 * w13 * w23
711
+ )
712
+ )
713
+ assert np.isclose(K, test_data)
714
+
715
+ def test_kemeny_constant_weight0(self):
716
+ G = nx.Graph()
717
+ w12 = 0
718
+ w13 = 3
719
+ w23 = 4
720
+ G.add_edge(1, 2, weight=w12)
721
+ G.add_edge(1, 3, weight=w13)
722
+ G.add_edge(2, 3, weight=w23)
723
+ K = nx.kemeny_constant(G, weight="weight")
724
+ test_data = (
725
+ 3
726
+ / 2
727
+ * (w12 + w13)
728
+ * (w12 + w23)
729
+ * (w13 + w23)
730
+ / (
731
+ w12**2 * (w13 + w23)
732
+ + w13**2 * (w12 + w23)
733
+ + w23**2 * (w12 + w13)
734
+ + 3 * w12 * w13 * w23
735
+ )
736
+ )
737
+ assert np.isclose(K, test_data)
738
+
739
+ def test_kemeny_constant_selfloop(self):
740
+ G = nx.Graph()
741
+ w11 = 1
742
+ w12 = 2
743
+ w13 = 3
744
+ w23 = 4
745
+ G.add_edge(1, 1, weight=w11)
746
+ G.add_edge(1, 2, weight=w12)
747
+ G.add_edge(1, 3, weight=w13)
748
+ G.add_edge(2, 3, weight=w23)
749
+ K = nx.kemeny_constant(G, weight="weight")
750
+ test_data = (
751
+ (2 * w11 + 3 * w12 + 3 * w13)
752
+ * (w12 + w23)
753
+ * (w13 + w23)
754
+ / (
755
+ (w12 * w13 + w12 * w23 + w13 * w23)
756
+ * (w11 + 2 * w12 + 2 * w13 + 2 * w23)
757
+ )
758
+ )
759
+ assert np.isclose(K, test_data)
760
+
761
+ def test_kemeny_constant_complete_bipartite_graph(self):
762
+ # Theorem 1 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
763
+ n1 = 5
764
+ n2 = 4
765
+ G = nx.complete_bipartite_graph(n1, n2)
766
+ K = nx.kemeny_constant(G)
767
+ assert np.isclose(K, n1 + n2 - 3 / 2)
768
+
769
+ def test_kemeny_constant_path_graph(self):
770
+ # Theorem 2 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
771
+ n = 10
772
+ G = nx.path_graph(n)
773
+ K = nx.kemeny_constant(G)
774
+ assert np.isclose(K, n**2 / 3 - 2 * n / 3 + 1 / 2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_distance_regular.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import is_strongly_regular
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ "f", (nx.is_distance_regular, nx.intersection_array, nx.is_strongly_regular)
9
+ )
10
+ @pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
11
+ def test_raises_on_directed_and_multigraphs(f, graph_constructor):
12
+ G = graph_constructor([(0, 1), (1, 2)])
13
+ with pytest.raises(nx.NetworkXNotImplemented):
14
+ f(G)
15
+
16
+
17
+ class TestDistanceRegular:
18
+ def test_is_distance_regular(self):
19
+ assert nx.is_distance_regular(nx.icosahedral_graph())
20
+ assert nx.is_distance_regular(nx.petersen_graph())
21
+ assert nx.is_distance_regular(nx.cubical_graph())
22
+ assert nx.is_distance_regular(nx.complete_bipartite_graph(3, 3))
23
+ assert nx.is_distance_regular(nx.tetrahedral_graph())
24
+ assert nx.is_distance_regular(nx.dodecahedral_graph())
25
+ assert nx.is_distance_regular(nx.pappus_graph())
26
+ assert nx.is_distance_regular(nx.heawood_graph())
27
+ assert nx.is_distance_regular(nx.cycle_graph(3))
28
+ # no distance regular
29
+ assert not nx.is_distance_regular(nx.path_graph(4))
30
+
31
+ def test_not_connected(self):
32
+ G = nx.cycle_graph(4)
33
+ nx.add_cycle(G, [5, 6, 7])
34
+ assert not nx.is_distance_regular(G)
35
+
36
+ def test_global_parameters(self):
37
+ b, c = nx.intersection_array(nx.cycle_graph(5))
38
+ g = nx.global_parameters(b, c)
39
+ assert list(g) == [(0, 0, 2), (1, 0, 1), (1, 1, 0)]
40
+ b, c = nx.intersection_array(nx.cycle_graph(3))
41
+ g = nx.global_parameters(b, c)
42
+ assert list(g) == [(0, 0, 2), (1, 1, 0)]
43
+
44
+ def test_intersection_array(self):
45
+ b, c = nx.intersection_array(nx.cycle_graph(5))
46
+ assert b == [2, 1]
47
+ assert c == [1, 1]
48
+ b, c = nx.intersection_array(nx.dodecahedral_graph())
49
+ assert b == [3, 2, 1, 1, 1]
50
+ assert c == [1, 1, 1, 2, 3]
51
+ b, c = nx.intersection_array(nx.icosahedral_graph())
52
+ assert b == [5, 2, 1]
53
+ assert c == [1, 2, 5]
54
+
55
+
56
+ @pytest.mark.parametrize("f", (nx.is_distance_regular, nx.is_strongly_regular))
57
+ def test_empty_graph_raises(f):
58
+ G = nx.Graph()
59
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes"):
60
+ f(G)
61
+
62
+
63
+ class TestStronglyRegular:
64
+ """Unit tests for the :func:`~networkx.is_strongly_regular`
65
+ function.
66
+
67
+ """
68
+
69
+ def test_cycle_graph(self):
70
+ """Tests that the cycle graph on five vertices is strongly
71
+ regular.
72
+
73
+ """
74
+ G = nx.cycle_graph(5)
75
+ assert is_strongly_regular(G)
76
+
77
+ def test_petersen_graph(self):
78
+ """Tests that the Petersen graph is strongly regular."""
79
+ G = nx.petersen_graph()
80
+ assert is_strongly_regular(G)
81
+
82
+ def test_path_graph(self):
83
+ """Tests that the path graph is not strongly regular."""
84
+ G = nx.path_graph(4)
85
+ assert not is_strongly_regular(G)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_dominance.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestImmediateDominators:
7
+ def test_exceptions(self):
8
+ G = nx.Graph()
9
+ G.add_node(0)
10
+ pytest.raises(nx.NetworkXNotImplemented, nx.immediate_dominators, G, 0)
11
+ G = nx.MultiGraph(G)
12
+ pytest.raises(nx.NetworkXNotImplemented, nx.immediate_dominators, G, 0)
13
+ G = nx.DiGraph([[0, 0]])
14
+ pytest.raises(nx.NetworkXError, nx.immediate_dominators, G, 1)
15
+
16
+ def test_singleton(self):
17
+ G = nx.DiGraph()
18
+ G.add_node(0)
19
+ assert nx.immediate_dominators(G, 0) == {0: 0}
20
+ G.add_edge(0, 0)
21
+ assert nx.immediate_dominators(G, 0) == {0: 0}
22
+
23
+ def test_path(self):
24
+ n = 5
25
+ G = nx.path_graph(n, create_using=nx.DiGraph())
26
+ assert nx.immediate_dominators(G, 0) == {i: max(i - 1, 0) for i in range(n)}
27
+
28
+ def test_cycle(self):
29
+ n = 5
30
+ G = nx.cycle_graph(n, create_using=nx.DiGraph())
31
+ assert nx.immediate_dominators(G, 0) == {i: max(i - 1, 0) for i in range(n)}
32
+
33
+ def test_unreachable(self):
34
+ n = 5
35
+ assert n > 1
36
+ G = nx.path_graph(n, create_using=nx.DiGraph())
37
+ assert nx.immediate_dominators(G, n // 2) == {
38
+ i: max(i - 1, n // 2) for i in range(n // 2, n)
39
+ }
40
+
41
+ def test_irreducible1(self):
42
+ """
43
+ Graph taken from figure 2 of "A simple, fast dominance algorithm." (2006).
44
+ https://hdl.handle.net/1911/96345
45
+ """
46
+ edges = [(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)]
47
+ G = nx.DiGraph(edges)
48
+ assert nx.immediate_dominators(G, 5) == {i: 5 for i in range(1, 6)}
49
+
50
+ def test_irreducible2(self):
51
+ """
52
+ Graph taken from figure 4 of "A simple, fast dominance algorithm." (2006).
53
+ https://hdl.handle.net/1911/96345
54
+ """
55
+
56
+ edges = [(1, 2), (2, 1), (2, 3), (3, 2), (4, 2), (4, 3), (5, 1), (6, 4), (6, 5)]
57
+ G = nx.DiGraph(edges)
58
+ result = nx.immediate_dominators(G, 6)
59
+ assert result == {i: 6 for i in range(1, 7)}
60
+
61
+ def test_domrel_png(self):
62
+ # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
63
+ edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
64
+ G = nx.DiGraph(edges)
65
+ result = nx.immediate_dominators(G, 1)
66
+ assert result == {1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 2}
67
+ # Test postdominance.
68
+ result = nx.immediate_dominators(G.reverse(copy=False), 6)
69
+ assert result == {1: 2, 2: 6, 3: 5, 4: 5, 5: 2, 6: 6}
70
+
71
+ def test_boost_example(self):
72
+ # Graph taken from Figure 1 of
73
+ # http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
74
+ edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
75
+ G = nx.DiGraph(edges)
76
+ result = nx.immediate_dominators(G, 0)
77
+ assert result == {0: 0, 1: 0, 2: 1, 3: 1, 4: 3, 5: 4, 6: 4, 7: 1}
78
+ # Test postdominance.
79
+ result = nx.immediate_dominators(G.reverse(copy=False), 7)
80
+ assert result == {0: 1, 1: 7, 2: 7, 3: 4, 4: 5, 5: 7, 6: 4, 7: 7}
81
+
82
+
83
+ class TestDominanceFrontiers:
84
+ def test_exceptions(self):
85
+ G = nx.Graph()
86
+ G.add_node(0)
87
+ pytest.raises(nx.NetworkXNotImplemented, nx.dominance_frontiers, G, 0)
88
+ G = nx.MultiGraph(G)
89
+ pytest.raises(nx.NetworkXNotImplemented, nx.dominance_frontiers, G, 0)
90
+ G = nx.DiGraph([[0, 0]])
91
+ pytest.raises(nx.NetworkXError, nx.dominance_frontiers, G, 1)
92
+
93
+ def test_singleton(self):
94
+ G = nx.DiGraph()
95
+ G.add_node(0)
96
+ assert nx.dominance_frontiers(G, 0) == {0: set()}
97
+ G.add_edge(0, 0)
98
+ assert nx.dominance_frontiers(G, 0) == {0: set()}
99
+
100
+ def test_path(self):
101
+ n = 5
102
+ G = nx.path_graph(n, create_using=nx.DiGraph())
103
+ assert nx.dominance_frontiers(G, 0) == {i: set() for i in range(n)}
104
+
105
+ def test_cycle(self):
106
+ n = 5
107
+ G = nx.cycle_graph(n, create_using=nx.DiGraph())
108
+ assert nx.dominance_frontiers(G, 0) == {i: set() for i in range(n)}
109
+
110
+ def test_unreachable(self):
111
+ n = 5
112
+ assert n > 1
113
+ G = nx.path_graph(n, create_using=nx.DiGraph())
114
+ assert nx.dominance_frontiers(G, n // 2) == {i: set() for i in range(n // 2, n)}
115
+
116
+ def test_irreducible1(self):
117
+ """
118
+ Graph taken from figure 2 of "A simple, fast dominance algorithm." (2006).
119
+ https://hdl.handle.net/1911/96345
120
+ """
121
+ edges = [(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)]
122
+ G = nx.DiGraph(edges)
123
+ assert dict(nx.dominance_frontiers(G, 5).items()) == {
124
+ 1: {2},
125
+ 2: {1},
126
+ 3: {2},
127
+ 4: {1},
128
+ 5: set(),
129
+ }
130
+
131
+ def test_irreducible2(self):
132
+ """
133
+ Graph taken from figure 4 of "A simple, fast dominance algorithm." (2006).
134
+ https://hdl.handle.net/1911/96345
135
+ """
136
+ edges = [(1, 2), (2, 1), (2, 3), (3, 2), (4, 2), (4, 3), (5, 1), (6, 4), (6, 5)]
137
+ G = nx.DiGraph(edges)
138
+ assert nx.dominance_frontiers(G, 6) == {
139
+ 1: {2},
140
+ 2: {1, 3},
141
+ 3: {2},
142
+ 4: {2, 3},
143
+ 5: {1},
144
+ 6: set(),
145
+ }
146
+
147
+ def test_domrel_png(self):
148
+ # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
149
+ edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
150
+ G = nx.DiGraph(edges)
151
+ assert nx.dominance_frontiers(G, 1) == {
152
+ 1: set(),
153
+ 2: {2},
154
+ 3: {5},
155
+ 4: {5},
156
+ 5: {2},
157
+ 6: set(),
158
+ }
159
+ # Test postdominance.
160
+ result = nx.dominance_frontiers(G.reverse(copy=False), 6)
161
+ assert result == {1: set(), 2: {2}, 3: {2}, 4: {2}, 5: {2}, 6: set()}
162
+
163
+ def test_boost_example(self):
164
+ # Graph taken from Figure 1 of
165
+ # http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
166
+ edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
167
+ G = nx.DiGraph(edges)
168
+ assert nx.dominance_frontiers(G, 0) == {
169
+ 0: set(),
170
+ 1: set(),
171
+ 2: {7},
172
+ 3: {7},
173
+ 4: {4, 7},
174
+ 5: {7},
175
+ 6: {4},
176
+ 7: set(),
177
+ }
178
+ # Test postdominance.
179
+ result = nx.dominance_frontiers(G.reverse(copy=False), 7)
180
+ expected = {
181
+ 0: set(),
182
+ 1: set(),
183
+ 2: {1},
184
+ 3: {1},
185
+ 4: {1, 4},
186
+ 5: {1},
187
+ 6: {4},
188
+ 7: set(),
189
+ }
190
+ assert result == expected
191
+
192
+ def test_discard_issue(self):
193
+ # https://github.com/networkx/networkx/issues/2071
194
+ g = nx.DiGraph()
195
+ g.add_edges_from(
196
+ [
197
+ ("b0", "b1"),
198
+ ("b1", "b2"),
199
+ ("b2", "b3"),
200
+ ("b3", "b1"),
201
+ ("b1", "b5"),
202
+ ("b5", "b6"),
203
+ ("b5", "b8"),
204
+ ("b6", "b7"),
205
+ ("b8", "b7"),
206
+ ("b7", "b3"),
207
+ ("b3", "b4"),
208
+ ]
209
+ )
210
+ df = nx.dominance_frontiers(g, "b0")
211
+ assert df == {
212
+ "b4": set(),
213
+ "b5": {"b3"},
214
+ "b6": {"b7"},
215
+ "b7": {"b3"},
216
+ "b0": set(),
217
+ "b1": {"b1"},
218
+ "b2": {"b3"},
219
+ "b3": {"b1"},
220
+ "b8": {"b7"},
221
+ }
222
+
223
+ def test_loop(self):
224
+ g = nx.DiGraph()
225
+ g.add_edges_from([("a", "b"), ("b", "c"), ("b", "a")])
226
+ df = nx.dominance_frontiers(g, "a")
227
+ assert df == {"a": set(), "b": set(), "c": set()}
228
+
229
+ def test_missing_immediate_doms(self):
230
+ # see https://github.com/networkx/networkx/issues/2070
231
+ g = nx.DiGraph()
232
+ edges = [
233
+ ("entry_1", "b1"),
234
+ ("b1", "b2"),
235
+ ("b2", "b3"),
236
+ ("b3", "exit"),
237
+ ("entry_2", "b3"),
238
+ ]
239
+
240
+ # entry_1
241
+ # |
242
+ # b1
243
+ # |
244
+ # b2 entry_2
245
+ # | /
246
+ # b3
247
+ # |
248
+ # exit
249
+
250
+ g.add_edges_from(edges)
251
+ # formerly raised KeyError on entry_2 when parsing b3
252
+ # because entry_2 does not have immediate doms (no path)
253
+ nx.dominance_frontiers(g, "entry_1")
254
+
255
+ def test_loops_larger(self):
256
+ # from
257
+ # http://ecee.colorado.edu/~waite/Darmstadt/motion.html
258
+ g = nx.DiGraph()
259
+ edges = [
260
+ ("entry", "exit"),
261
+ ("entry", "1"),
262
+ ("1", "2"),
263
+ ("2", "3"),
264
+ ("3", "4"),
265
+ ("4", "5"),
266
+ ("5", "6"),
267
+ ("6", "exit"),
268
+ ("6", "2"),
269
+ ("5", "3"),
270
+ ("4", "4"),
271
+ ]
272
+
273
+ g.add_edges_from(edges)
274
+ df = nx.dominance_frontiers(g, "entry")
275
+ answer = {
276
+ "entry": set(),
277
+ "1": {"exit"},
278
+ "2": {"exit", "2"},
279
+ "3": {"exit", "3", "2"},
280
+ "4": {"exit", "4", "3", "2"},
281
+ "5": {"exit", "3", "2"},
282
+ "6": {"exit", "2"},
283
+ "exit": set(),
284
+ }
285
+ for n in df:
286
+ assert set(df[n]) == set(answer[n])
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_dominating_set():
7
+ G = nx.gnp_random_graph(100, 0.1)
8
+ D = nx.dominating_set(G)
9
+ assert nx.is_dominating_set(G, D)
10
+ D = nx.dominating_set(G, start_with=0)
11
+ assert nx.is_dominating_set(G, D)
12
+
13
+
14
+ def test_complete():
15
+ """In complete graphs each node is a dominating set.
16
+ Thus the dominating set has to be of cardinality 1.
17
+ """
18
+ K4 = nx.complete_graph(4)
19
+ assert len(nx.dominating_set(K4)) == 1
20
+ K5 = nx.complete_graph(5)
21
+ assert len(nx.dominating_set(K5)) == 1
22
+
23
+
24
+ def test_raise_dominating_set():
25
+ with pytest.raises(nx.NetworkXError):
26
+ G = nx.path_graph(4)
27
+ D = nx.dominating_set(G, start_with=10)
28
+
29
+
30
+ def test_is_dominating_set():
31
+ G = nx.path_graph(4)
32
+ d = {1, 3}
33
+ assert nx.is_dominating_set(G, d)
34
+ d = {0, 2}
35
+ assert nx.is_dominating_set(G, d)
36
+ d = {1}
37
+ assert not nx.is_dominating_set(G, d)
38
+
39
+
40
+ def test_wikipedia_is_dominating_set():
41
+ """Example from https://en.wikipedia.org/wiki/Dominating_set"""
42
+ G = nx.cycle_graph(4)
43
+ G.add_edges_from([(0, 4), (1, 4), (2, 5)])
44
+ assert nx.is_dominating_set(G, {4, 3, 5})
45
+ assert nx.is_dominating_set(G, {0, 2})
46
+ assert nx.is_dominating_set(G, {1, 2})
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_efficiency.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.efficiency` module."""
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestEfficiency:
7
+ def setup_method(self):
8
+ # G1 is a disconnected graph
9
+ self.G1 = nx.Graph()
10
+ self.G1.add_nodes_from([1, 2, 3])
11
+ # G2 is a cycle graph
12
+ self.G2 = nx.cycle_graph(4)
13
+ # G3 is the triangle graph with one additional edge
14
+ self.G3 = nx.lollipop_graph(3, 1)
15
+
16
+ def test_efficiency_disconnected_nodes(self):
17
+ """
18
+ When nodes are disconnected, efficiency is 0
19
+ """
20
+ assert nx.efficiency(self.G1, 1, 2) == 0
21
+
22
+ def test_local_efficiency_disconnected_graph(self):
23
+ """
24
+ In a disconnected graph the efficiency is 0
25
+ """
26
+ assert nx.local_efficiency(self.G1) == 0
27
+
28
+ def test_efficiency(self):
29
+ assert nx.efficiency(self.G2, 0, 1) == 1
30
+ assert nx.efficiency(self.G2, 0, 2) == 1 / 2
31
+
32
+ def test_global_efficiency(self):
33
+ assert nx.global_efficiency(self.G2) == 5 / 6
34
+
35
+ def test_global_efficiency_complete_graph(self):
36
+ """
37
+ Tests that the average global efficiency of the complete graph is one.
38
+ """
39
+ for n in range(2, 10):
40
+ G = nx.complete_graph(n)
41
+ assert nx.global_efficiency(G) == 1
42
+
43
+ def test_local_efficiency_complete_graph(self):
44
+ """
45
+ Test that the local efficiency for a complete graph with at least 3
46
+ nodes should be one. For a graph with only 2 nodes, the induced
47
+ subgraph has no edges.
48
+ """
49
+ for n in range(3, 10):
50
+ G = nx.complete_graph(n)
51
+ assert nx.local_efficiency(G) == 1
52
+
53
+ def test_using_ego_graph(self):
54
+ """
55
+ Test that the ego graph is used when computing local efficiency.
56
+ For more information, see GitHub issue #2710.
57
+ """
58
+ assert nx.local_efficiency(self.G3) == 7 / 12
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_euler.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ @pytest.mark.parametrize("f", (nx.is_eulerian, nx.is_semieulerian))
9
+ def test_empty_graph_raises(f):
10
+ G = nx.Graph()
11
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
12
+ f(G)
13
+
14
+
15
+ class TestIsEulerian:
16
+ def test_is_eulerian(self):
17
+ assert nx.is_eulerian(nx.complete_graph(5))
18
+ assert nx.is_eulerian(nx.complete_graph(7))
19
+ assert nx.is_eulerian(nx.hypercube_graph(4))
20
+ assert nx.is_eulerian(nx.hypercube_graph(6))
21
+
22
+ assert not nx.is_eulerian(nx.complete_graph(4))
23
+ assert not nx.is_eulerian(nx.complete_graph(6))
24
+ assert not nx.is_eulerian(nx.hypercube_graph(3))
25
+ assert not nx.is_eulerian(nx.hypercube_graph(5))
26
+
27
+ assert not nx.is_eulerian(nx.petersen_graph())
28
+ assert not nx.is_eulerian(nx.path_graph(4))
29
+
30
+ def test_is_eulerian2(self):
31
+ # not connected
32
+ G = nx.Graph()
33
+ G.add_nodes_from([1, 2, 3])
34
+ assert not nx.is_eulerian(G)
35
+ # not strongly connected
36
+ G = nx.DiGraph()
37
+ G.add_nodes_from([1, 2, 3])
38
+ assert not nx.is_eulerian(G)
39
+ G = nx.MultiDiGraph()
40
+ G.add_edge(1, 2)
41
+ G.add_edge(2, 3)
42
+ G.add_edge(2, 3)
43
+ G.add_edge(3, 1)
44
+ assert not nx.is_eulerian(G)
45
+
46
+
47
+ class TestEulerianCircuit:
48
+ def test_eulerian_circuit_cycle(self):
49
+ G = nx.cycle_graph(4)
50
+
51
+ edges = list(nx.eulerian_circuit(G, source=0))
52
+ nodes = [u for u, v in edges]
53
+ assert nodes == [0, 3, 2, 1]
54
+ assert edges == [(0, 3), (3, 2), (2, 1), (1, 0)]
55
+
56
+ edges = list(nx.eulerian_circuit(G, source=1))
57
+ nodes = [u for u, v in edges]
58
+ assert nodes == [1, 2, 3, 0]
59
+ assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
60
+
61
+ G = nx.complete_graph(3)
62
+
63
+ edges = list(nx.eulerian_circuit(G, source=0))
64
+ nodes = [u for u, v in edges]
65
+ assert nodes == [0, 2, 1]
66
+ assert edges == [(0, 2), (2, 1), (1, 0)]
67
+
68
+ edges = list(nx.eulerian_circuit(G, source=1))
69
+ nodes = [u for u, v in edges]
70
+ assert nodes == [1, 2, 0]
71
+ assert edges == [(1, 2), (2, 0), (0, 1)]
72
+
73
+ def test_eulerian_circuit_digraph(self):
74
+ G = nx.DiGraph()
75
+ nx.add_cycle(G, [0, 1, 2, 3])
76
+
77
+ edges = list(nx.eulerian_circuit(G, source=0))
78
+ nodes = [u for u, v in edges]
79
+ assert nodes == [0, 1, 2, 3]
80
+ assert edges == [(0, 1), (1, 2), (2, 3), (3, 0)]
81
+
82
+ edges = list(nx.eulerian_circuit(G, source=1))
83
+ nodes = [u for u, v in edges]
84
+ assert nodes == [1, 2, 3, 0]
85
+ assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
86
+
87
+ def test_multigraph(self):
88
+ G = nx.MultiGraph()
89
+ nx.add_cycle(G, [0, 1, 2, 3])
90
+ G.add_edge(1, 2)
91
+ G.add_edge(1, 2)
92
+ edges = list(nx.eulerian_circuit(G, source=0))
93
+ nodes = [u for u, v in edges]
94
+ assert nodes == [0, 3, 2, 1, 2, 1]
95
+ assert edges == [(0, 3), (3, 2), (2, 1), (1, 2), (2, 1), (1, 0)]
96
+
97
+ def test_multigraph_with_keys(self):
98
+ G = nx.MultiGraph()
99
+ nx.add_cycle(G, [0, 1, 2, 3])
100
+ G.add_edge(1, 2)
101
+ G.add_edge(1, 2)
102
+ edges = list(nx.eulerian_circuit(G, source=0, keys=True))
103
+ nodes = [u for u, v, k in edges]
104
+ assert nodes == [0, 3, 2, 1, 2, 1]
105
+ assert edges[:2] == [(0, 3, 0), (3, 2, 0)]
106
+ assert collections.Counter(edges[2:5]) == collections.Counter(
107
+ [(2, 1, 0), (1, 2, 1), (2, 1, 2)]
108
+ )
109
+ assert edges[5:] == [(1, 0, 0)]
110
+
111
+ def test_not_eulerian(self):
112
+ with pytest.raises(nx.NetworkXError):
113
+ f = list(nx.eulerian_circuit(nx.complete_graph(4)))
114
+
115
+
116
+ class TestIsSemiEulerian:
117
+ def test_is_semieulerian(self):
118
+ # Test graphs with Eulerian paths but no cycles return True.
119
+ assert nx.is_semieulerian(nx.path_graph(4))
120
+ G = nx.path_graph(6, create_using=nx.DiGraph)
121
+ assert nx.is_semieulerian(G)
122
+
123
+ # Test graphs with Eulerian cycles return False.
124
+ assert not nx.is_semieulerian(nx.complete_graph(5))
125
+ assert not nx.is_semieulerian(nx.complete_graph(7))
126
+ assert not nx.is_semieulerian(nx.hypercube_graph(4))
127
+ assert not nx.is_semieulerian(nx.hypercube_graph(6))
128
+
129
+
130
+ class TestHasEulerianPath:
131
+ def test_has_eulerian_path_cyclic(self):
132
+ # Test graphs with Eulerian cycles return True.
133
+ assert nx.has_eulerian_path(nx.complete_graph(5))
134
+ assert nx.has_eulerian_path(nx.complete_graph(7))
135
+ assert nx.has_eulerian_path(nx.hypercube_graph(4))
136
+ assert nx.has_eulerian_path(nx.hypercube_graph(6))
137
+
138
+ def test_has_eulerian_path_non_cyclic(self):
139
+ # Test graphs with Eulerian paths but no cycles return True.
140
+ assert nx.has_eulerian_path(nx.path_graph(4))
141
+ G = nx.path_graph(6, create_using=nx.DiGraph)
142
+ assert nx.has_eulerian_path(G)
143
+
144
+ def test_has_eulerian_path_directed_graph(self):
145
+ # Test directed graphs and returns False
146
+ G = nx.DiGraph()
147
+ G.add_edges_from([(0, 1), (1, 2), (0, 2)])
148
+ assert not nx.has_eulerian_path(G)
149
+
150
+ # Test directed graphs without isolated node returns True
151
+ G = nx.DiGraph()
152
+ G.add_edges_from([(0, 1), (1, 2), (2, 0)])
153
+ assert nx.has_eulerian_path(G)
154
+
155
+ # Test directed graphs with isolated node returns False
156
+ G.add_node(3)
157
+ assert not nx.has_eulerian_path(G)
158
+
159
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
160
+ def test_has_eulerian_path_not_weakly_connected(self, G):
161
+ G.add_edges_from([(0, 1), (2, 3), (3, 2)])
162
+ assert not nx.has_eulerian_path(G)
163
+
164
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
165
+ def test_has_eulerian_path_unbalancedins_more_than_one(self, G):
166
+ G.add_edges_from([(0, 1), (2, 3)])
167
+ assert not nx.has_eulerian_path(G)
168
+
169
+
170
+ class TestFindPathStart:
171
+ def testfind_path_start(self):
172
+ find_path_start = nx.algorithms.euler._find_path_start
173
+ # Test digraphs return correct starting node.
174
+ G = nx.path_graph(6, create_using=nx.DiGraph)
175
+ assert find_path_start(G) == 0
176
+ edges = [(0, 1), (1, 2), (2, 0), (4, 0)]
177
+ assert find_path_start(nx.DiGraph(edges)) == 4
178
+
179
+ # Test graph with no Eulerian path return None.
180
+ edges = [(0, 1), (1, 2), (2, 3), (2, 4)]
181
+ assert find_path_start(nx.DiGraph(edges)) is None
182
+
183
+
184
+ class TestEulerianPath:
185
+ def test_eulerian_path(self):
186
+ x = [(4, 0), (0, 1), (1, 2), (2, 0)]
187
+ for e1, e2 in zip(x, nx.eulerian_path(nx.DiGraph(x))):
188
+ assert e1 == e2
189
+
190
+ def test_eulerian_path_straight_link(self):
191
+ G = nx.DiGraph()
192
+ result = [(1, 2), (2, 3), (3, 4), (4, 5)]
193
+ G.add_edges_from(result)
194
+ assert result == list(nx.eulerian_path(G))
195
+ assert result == list(nx.eulerian_path(G, source=1))
196
+ with pytest.raises(nx.NetworkXError):
197
+ list(nx.eulerian_path(G, source=3))
198
+ with pytest.raises(nx.NetworkXError):
199
+ list(nx.eulerian_path(G, source=4))
200
+ with pytest.raises(nx.NetworkXError):
201
+ list(nx.eulerian_path(G, source=5))
202
+
203
+ def test_eulerian_path_multigraph(self):
204
+ G = nx.MultiDiGraph()
205
+ result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4), (4, 3)]
206
+ G.add_edges_from(result)
207
+ assert result == list(nx.eulerian_path(G))
208
+ assert result == list(nx.eulerian_path(G, source=2))
209
+ with pytest.raises(nx.NetworkXError):
210
+ list(nx.eulerian_path(G, source=3))
211
+ with pytest.raises(nx.NetworkXError):
212
+ list(nx.eulerian_path(G, source=4))
213
+
214
+ def test_eulerian_path_eulerian_circuit(self):
215
+ G = nx.DiGraph()
216
+ result = [(1, 2), (2, 3), (3, 4), (4, 1)]
217
+ result2 = [(2, 3), (3, 4), (4, 1), (1, 2)]
218
+ result3 = [(3, 4), (4, 1), (1, 2), (2, 3)]
219
+ G.add_edges_from(result)
220
+ assert result == list(nx.eulerian_path(G))
221
+ assert result == list(nx.eulerian_path(G, source=1))
222
+ assert result2 == list(nx.eulerian_path(G, source=2))
223
+ assert result3 == list(nx.eulerian_path(G, source=3))
224
+
225
+ def test_eulerian_path_undirected(self):
226
+ G = nx.Graph()
227
+ result = [(1, 2), (2, 3), (3, 4), (4, 5)]
228
+ result2 = [(5, 4), (4, 3), (3, 2), (2, 1)]
229
+ G.add_edges_from(result)
230
+ assert list(nx.eulerian_path(G)) in (result, result2)
231
+ assert result == list(nx.eulerian_path(G, source=1))
232
+ assert result2 == list(nx.eulerian_path(G, source=5))
233
+ with pytest.raises(nx.NetworkXError):
234
+ list(nx.eulerian_path(G, source=3))
235
+ with pytest.raises(nx.NetworkXError):
236
+ list(nx.eulerian_path(G, source=2))
237
+
238
+ def test_eulerian_path_multigraph_undirected(self):
239
+ G = nx.MultiGraph()
240
+ result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4)]
241
+ G.add_edges_from(result)
242
+ assert result == list(nx.eulerian_path(G))
243
+ assert result == list(nx.eulerian_path(G, source=2))
244
+ with pytest.raises(nx.NetworkXError):
245
+ list(nx.eulerian_path(G, source=3))
246
+ with pytest.raises(nx.NetworkXError):
247
+ list(nx.eulerian_path(G, source=1))
248
+
249
+ @pytest.mark.parametrize(
250
+ ("graph_type", "result"),
251
+ (
252
+ (nx.MultiGraph, [(0, 1, 0), (1, 0, 1)]),
253
+ (nx.MultiDiGraph, [(0, 1, 0), (1, 0, 0)]),
254
+ ),
255
+ )
256
+ def test_eulerian_with_keys(self, graph_type, result):
257
+ G = graph_type([(0, 1), (1, 0)])
258
+ answer = nx.eulerian_path(G, keys=True)
259
+ assert list(answer) == result
260
+
261
+
262
+ class TestEulerize:
263
+ def test_disconnected(self):
264
+ with pytest.raises(nx.NetworkXError):
265
+ G = nx.from_edgelist([(0, 1), (2, 3)])
266
+ nx.eulerize(G)
267
+
268
+ def test_null_graph(self):
269
+ with pytest.raises(nx.NetworkXPointlessConcept):
270
+ nx.eulerize(nx.Graph())
271
+
272
+ def test_null_multigraph(self):
273
+ with pytest.raises(nx.NetworkXPointlessConcept):
274
+ nx.eulerize(nx.MultiGraph())
275
+
276
+ def test_on_empty_graph(self):
277
+ with pytest.raises(nx.NetworkXError):
278
+ nx.eulerize(nx.empty_graph(3))
279
+
280
+ def test_on_eulerian(self):
281
+ G = nx.cycle_graph(3)
282
+ H = nx.eulerize(G)
283
+ assert nx.is_isomorphic(G, H)
284
+
285
+ def test_on_eulerian_multigraph(self):
286
+ G = nx.MultiGraph(nx.cycle_graph(3))
287
+ G.add_edge(0, 1)
288
+ H = nx.eulerize(G)
289
+ assert nx.is_eulerian(H)
290
+
291
+ def test_on_complete_graph(self):
292
+ G = nx.complete_graph(4)
293
+ assert nx.is_eulerian(nx.eulerize(G))
294
+ assert nx.is_eulerian(nx.eulerize(nx.MultiGraph(G)))
295
+
296
+ def test_on_non_eulerian_graph(self):
297
+ G = nx.cycle_graph(18)
298
+ G.add_edge(0, 18)
299
+ G.add_edge(18, 19)
300
+ G.add_edge(17, 19)
301
+ G.add_edge(4, 20)
302
+ G.add_edge(20, 21)
303
+ G.add_edge(21, 22)
304
+ G.add_edge(22, 23)
305
+ G.add_edge(23, 24)
306
+ G.add_edge(24, 25)
307
+ G.add_edge(25, 26)
308
+ G.add_edge(26, 27)
309
+ G.add_edge(27, 28)
310
+ G.add_edge(28, 13)
311
+ assert not nx.is_eulerian(G)
312
+ G = nx.eulerize(G)
313
+ assert nx.is_eulerian(G)
314
+ assert nx.number_of_edges(G) == 39
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/networkx/algorithms/tests/test_graph_hashing.py ADDED
@@ -0,0 +1,686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.generators import directed
5
+
6
+ # Unit tests for the :func:`~networkx.weisfeiler_lehman_graph_hash` function
7
+
8
+
9
+ def test_empty_graph_hash():
10
+ """
11
+ empty graphs should give hashes regardless of other params
12
+ """
13
+ G1 = nx.empty_graph()
14
+ G2 = nx.empty_graph()
15
+
16
+ h1 = nx.weisfeiler_lehman_graph_hash(G1)
17
+ h2 = nx.weisfeiler_lehman_graph_hash(G2)
18
+ h3 = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="edge_attr1")
19
+ h4 = nx.weisfeiler_lehman_graph_hash(G2, node_attr="node_attr1")
20
+ h5 = nx.weisfeiler_lehman_graph_hash(
21
+ G2, edge_attr="edge_attr1", node_attr="node_attr1"
22
+ )
23
+ h6 = nx.weisfeiler_lehman_graph_hash(G2, iterations=10)
24
+
25
+ assert h1 == h2
26
+ assert h1 == h3
27
+ assert h1 == h4
28
+ assert h1 == h5
29
+ assert h1 == h6
30
+
31
+
32
+ def test_directed():
33
+ """
34
+ A directed graph with no bi-directional edges should yield different a graph hash
35
+ to the same graph taken as undirected if there are no hash collisions.
36
+ """
37
+ r = 10
38
+ for i in range(r):
39
+ G_directed = nx.gn_graph(10 + r, seed=100 + i)
40
+ G_undirected = nx.to_undirected(G_directed)
41
+
42
+ h_directed = nx.weisfeiler_lehman_graph_hash(G_directed)
43
+ h_undirected = nx.weisfeiler_lehman_graph_hash(G_undirected)
44
+
45
+ assert h_directed != h_undirected
46
+
47
+
48
+ def test_reversed():
49
+ """
50
+ A directed graph with no bi-directional edges should yield different a graph hash
51
+ to the same graph taken with edge directions reversed if there are no hash collisions.
52
+ Here we test a cycle graph which is the minimal counterexample
53
+ """
54
+ G = nx.cycle_graph(5, create_using=nx.DiGraph)
55
+ nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
56
+
57
+ G_reversed = G.reverse()
58
+
59
+ h = nx.weisfeiler_lehman_graph_hash(G, node_attr="label")
60
+ h_reversed = nx.weisfeiler_lehman_graph_hash(G_reversed, node_attr="label")
61
+
62
+ assert h != h_reversed
63
+
64
+
65
+ def test_isomorphic():
66
+ """
67
+ graph hashes should be invariant to node-relabeling (when the output is reindexed
68
+ by the same mapping)
69
+ """
70
+ n, r = 100, 10
71
+ p = 1.0 / r
72
+ for i in range(1, r + 1):
73
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
74
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
75
+
76
+ g1_hash = nx.weisfeiler_lehman_graph_hash(G1)
77
+ g2_hash = nx.weisfeiler_lehman_graph_hash(G2)
78
+
79
+ assert g1_hash == g2_hash
80
+
81
+
82
+ def test_isomorphic_edge_attr():
83
+ """
84
+ Isomorphic graphs with differing edge attributes should yield different graph
85
+ hashes if the 'edge_attr' argument is supplied and populated in the graph,
86
+ and there are no hash collisions.
87
+ The output should still be invariant to node-relabeling
88
+ """
89
+ n, r = 100, 10
90
+ p = 1.0 / r
91
+ for i in range(1, r + 1):
92
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
93
+
94
+ for a, b in G1.edges:
95
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
96
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
97
+
98
+ g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
99
+ G1, edge_attr="edge_attr1"
100
+ )
101
+ g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
102
+ G1, edge_attr="edge_attr2"
103
+ )
104
+ g1_hash_no_edge_attr = nx.weisfeiler_lehman_graph_hash(G1, edge_attr=None)
105
+
106
+ assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
107
+ assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
108
+ assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
109
+
110
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
111
+
112
+ g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
113
+ G2, edge_attr="edge_attr1"
114
+ )
115
+ g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
116
+ G2, edge_attr="edge_attr2"
117
+ )
118
+
119
+ assert g1_hash_with_edge_attr1 == g2_hash_with_edge_attr1
120
+ assert g1_hash_with_edge_attr2 == g2_hash_with_edge_attr2
121
+
122
+
123
+ def test_missing_edge_attr():
124
+ """
125
+ If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
126
+ we should raise a KeyError
127
+ """
128
+ G = nx.Graph()
129
+ G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
130
+ pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, edge_attr="edge_attr1")
131
+
132
+
133
+ def test_isomorphic_node_attr():
134
+ """
135
+ Isomorphic graphs with differing node attributes should yield different graph
136
+ hashes if the 'node_attr' argument is supplied and populated in the graph, and
137
+ there are no hash collisions.
138
+ The output should still be invariant to node-relabeling
139
+ """
140
+ n, r = 100, 10
141
+ p = 1.0 / r
142
+ for i in range(1, r + 1):
143
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
144
+
145
+ for u in G1.nodes():
146
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
147
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
148
+
149
+ g1_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
150
+ G1, node_attr="node_attr1"
151
+ )
152
+ g1_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
153
+ G1, node_attr="node_attr2"
154
+ )
155
+ g1_hash_no_node_attr = nx.weisfeiler_lehman_graph_hash(G1, node_attr=None)
156
+
157
+ assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
158
+ assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
159
+ assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
160
+
161
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
162
+
163
+ g2_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
164
+ G2, node_attr="node_attr1"
165
+ )
166
+ g2_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
167
+ G2, node_attr="node_attr2"
168
+ )
169
+
170
+ assert g1_hash_with_node_attr1 == g2_hash_with_node_attr1
171
+ assert g1_hash_with_node_attr2 == g2_hash_with_node_attr2
172
+
173
+
174
+ def test_missing_node_attr():
175
+ """
176
+ If the 'node_attr' argument is supplied but is missing from a node in the graph,
177
+ we should raise a KeyError
178
+ """
179
+ G = nx.Graph()
180
+ G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
181
+ G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
182
+ pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, node_attr="node_attr1")
183
+
184
+
185
+ def test_isomorphic_edge_attr_and_node_attr():
186
+ """
187
+ Isomorphic graphs with differing node attributes should yield different graph
188
+ hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
189
+ the graph, and there are no hash collisions.
190
+ The output should still be invariant to node-relabeling
191
+ """
192
+ n, r = 100, 10
193
+ p = 1.0 / r
194
+ for i in range(1, r + 1):
195
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
196
+
197
+ for u in G1.nodes():
198
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
199
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
200
+
201
+ for a, b in G1.edges:
202
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
203
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
204
+
205
+ g1_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
206
+ G1, edge_attr="edge_attr1", node_attr="node_attr1"
207
+ )
208
+ g1_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
209
+ G1, edge_attr="edge_attr2", node_attr="node_attr2"
210
+ )
211
+ g1_hash_edge1_node2 = nx.weisfeiler_lehman_graph_hash(
212
+ G1, edge_attr="edge_attr1", node_attr="node_attr2"
213
+ )
214
+ g1_hash_no_attr = nx.weisfeiler_lehman_graph_hash(G1)
215
+
216
+ assert g1_hash_edge1_node1 != g1_hash_no_attr
217
+ assert g1_hash_edge2_node2 != g1_hash_no_attr
218
+ assert g1_hash_edge1_node1 != g1_hash_edge2_node2
219
+ assert g1_hash_edge1_node2 != g1_hash_edge2_node2
220
+ assert g1_hash_edge1_node2 != g1_hash_edge1_node1
221
+
222
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
223
+
224
+ g2_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
225
+ G2, edge_attr="edge_attr1", node_attr="node_attr1"
226
+ )
227
+ g2_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
228
+ G2, edge_attr="edge_attr2", node_attr="node_attr2"
229
+ )
230
+
231
+ assert g1_hash_edge1_node1 == g2_hash_edge1_node1
232
+ assert g1_hash_edge2_node2 == g2_hash_edge2_node2
233
+
234
+
235
+ def test_digest_size():
236
+ """
237
+ The hash string lengths should be as expected for a variety of graphs and
238
+ digest sizes
239
+ """
240
+ n, r = 100, 10
241
+ p = 1.0 / r
242
+ for i in range(1, r + 1):
243
+ G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
244
+
245
+ h16 = nx.weisfeiler_lehman_graph_hash(G)
246
+ h32 = nx.weisfeiler_lehman_graph_hash(G, digest_size=32)
247
+
248
+ assert h16 != h32
249
+ assert len(h16) == 16 * 2
250
+ assert len(h32) == 32 * 2
251
+
252
+
253
+ # Unit tests for the :func:`~networkx.weisfeiler_lehman_hash_subgraphs` function
254
+
255
+
256
+ def is_subiteration(a, b):
257
+ """
258
+ returns True if that each hash sequence in 'a' is a prefix for
259
+ the corresponding sequence indexed by the same node in 'b'.
260
+ """
261
+ return all(b[node][: len(hashes)] == hashes for node, hashes in a.items())
262
+
263
+
264
+ def hexdigest_sizes_correct(a, digest_size):
265
+ """
266
+ returns True if all hex digest sizes are the expected length in a node:subgraph-hashes
267
+ dictionary. Hex digest string length == 2 * bytes digest length since each pair of hex
268
+ digits encodes 1 byte (https://docs.python.org/3/library/hashlib.html)
269
+ """
270
+ hexdigest_size = digest_size * 2
271
+ list_digest_sizes_correct = lambda l: all(len(x) == hexdigest_size for x in l)
272
+ return all(list_digest_sizes_correct(hashes) for hashes in a.values())
273
+
274
+
275
+ def test_empty_graph_subgraph_hash():
276
+ """ "
277
+ empty graphs should give empty dict subgraph hashes regardless of other params
278
+ """
279
+ G = nx.empty_graph()
280
+
281
+ subgraph_hashes1 = nx.weisfeiler_lehman_subgraph_hashes(G)
282
+ subgraph_hashes2 = nx.weisfeiler_lehman_subgraph_hashes(G, edge_attr="edge_attr")
283
+ subgraph_hashes3 = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="edge_attr")
284
+ subgraph_hashes4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=2)
285
+ subgraph_hashes5 = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=64)
286
+
287
+ assert subgraph_hashes1 == {}
288
+ assert subgraph_hashes2 == {}
289
+ assert subgraph_hashes3 == {}
290
+ assert subgraph_hashes4 == {}
291
+ assert subgraph_hashes5 == {}
292
+
293
+
294
+ def test_directed_subgraph_hash():
295
+ """
296
+ A directed graph with no bi-directional edges should yield different subgraph hashes
297
+ to the same graph taken as undirected, if all hashes don't collide.
298
+ """
299
+ r = 10
300
+ for i in range(r):
301
+ G_directed = nx.gn_graph(10 + r, seed=100 + i)
302
+ G_undirected = nx.to_undirected(G_directed)
303
+
304
+ directed_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_directed)
305
+ undirected_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_undirected)
306
+
307
+ assert directed_subgraph_hashes != undirected_subgraph_hashes
308
+
309
+
310
+ def test_reversed_subgraph_hash():
311
+ """
312
+ A directed graph with no bi-directional edges should yield different subgraph hashes
313
+ to the same graph taken with edge directions reversed if there are no hash collisions.
314
+ Here we test a cycle graph which is the minimal counterexample
315
+ """
316
+ G = nx.cycle_graph(5, create_using=nx.DiGraph)
317
+ nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
318
+
319
+ G_reversed = G.reverse()
320
+
321
+ h = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
322
+ h_reversed = nx.weisfeiler_lehman_subgraph_hashes(G_reversed, node_attr="label")
323
+
324
+ assert h != h_reversed
325
+
326
+
327
+ def test_isomorphic_subgraph_hash():
328
+ """
329
+ the subgraph hashes should be invariant to node-relabeling when the output is reindexed
330
+ by the same mapping and all hashes don't collide.
331
+ """
332
+ n, r = 100, 10
333
+ p = 1.0 / r
334
+ for i in range(1, r + 1):
335
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
336
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
337
+
338
+ g1_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G1)
339
+ g2_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G2)
340
+
341
+ assert g1_subgraph_hashes == {-1 * k: v for k, v in g2_subgraph_hashes.items()}
342
+
343
+
344
+ def test_isomorphic_edge_attr_subgraph_hash():
345
+ """
346
+ Isomorphic graphs with differing edge attributes should yield different subgraph
347
+ hashes if the 'edge_attr' argument is supplied and populated in the graph, and
348
+ all hashes don't collide.
349
+ The output should still be invariant to node-relabeling
350
+ """
351
+ n, r = 100, 10
352
+ p = 1.0 / r
353
+ for i in range(1, r + 1):
354
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
355
+
356
+ for a, b in G1.edges:
357
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
358
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
359
+
360
+ g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
361
+ G1, edge_attr="edge_attr1"
362
+ )
363
+ g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
364
+ G1, edge_attr="edge_attr2"
365
+ )
366
+ g1_hash_no_edge_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, edge_attr=None)
367
+
368
+ assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
369
+ assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
370
+ assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
371
+
372
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
373
+
374
+ g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
375
+ G2, edge_attr="edge_attr1"
376
+ )
377
+ g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
378
+ G2, edge_attr="edge_attr2"
379
+ )
380
+
381
+ assert g1_hash_with_edge_attr1 == {
382
+ -1 * k: v for k, v in g2_hash_with_edge_attr1.items()
383
+ }
384
+ assert g1_hash_with_edge_attr2 == {
385
+ -1 * k: v for k, v in g2_hash_with_edge_attr2.items()
386
+ }
387
+
388
+
389
+ def test_missing_edge_attr_subgraph_hash():
390
+ """
391
+ If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
392
+ we should raise a KeyError
393
+ """
394
+ G = nx.Graph()
395
+ G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
396
+ pytest.raises(
397
+ KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, edge_attr="edge_attr1"
398
+ )
399
+
400
+
401
+ def test_isomorphic_node_attr_subgraph_hash():
402
+ """
403
+ Isomorphic graphs with differing node attributes should yield different subgraph
404
+ hashes if the 'node_attr' argument is supplied and populated in the graph, and
405
+ all hashes don't collide.
406
+ The output should still be invariant to node-relabeling
407
+ """
408
+ n, r = 100, 10
409
+ p = 1.0 / r
410
+ for i in range(1, r + 1):
411
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
412
+
413
+ for u in G1.nodes():
414
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
415
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
416
+
417
+ g1_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
418
+ G1, node_attr="node_attr1"
419
+ )
420
+ g1_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
421
+ G1, node_attr="node_attr2"
422
+ )
423
+ g1_hash_no_node_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, node_attr=None)
424
+
425
+ assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
426
+ assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
427
+ assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
428
+
429
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
430
+
431
+ g2_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
432
+ G2, node_attr="node_attr1"
433
+ )
434
+ g2_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
435
+ G2, node_attr="node_attr2"
436
+ )
437
+
438
+ assert g1_hash_with_node_attr1 == {
439
+ -1 * k: v for k, v in g2_hash_with_node_attr1.items()
440
+ }
441
+ assert g1_hash_with_node_attr2 == {
442
+ -1 * k: v for k, v in g2_hash_with_node_attr2.items()
443
+ }
444
+
445
+
446
+ def test_missing_node_attr_subgraph_hash():
447
+ """
448
+ If the 'node_attr' argument is supplied but is missing from a node in the graph,
449
+ we should raise a KeyError
450
+ """
451
+ G = nx.Graph()
452
+ G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
453
+ G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
454
+ pytest.raises(
455
+ KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, node_attr="node_attr1"
456
+ )
457
+
458
+
459
+ def test_isomorphic_edge_attr_and_node_attr_subgraph_hash():
460
+ """
461
+ Isomorphic graphs with differing node attributes should yield different subgraph
462
+ hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
463
+ the graph, and all hashes don't collide
464
+ The output should still be invariant to node-relabeling
465
+ """
466
+ n, r = 100, 10
467
+ p = 1.0 / r
468
+ for i in range(1, r + 1):
469
+ G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
470
+
471
+ for u in G1.nodes():
472
+ G1.nodes[u]["node_attr1"] = f"{u}-1"
473
+ G1.nodes[u]["node_attr2"] = f"{u}-2"
474
+
475
+ for a, b in G1.edges:
476
+ G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
477
+ G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
478
+
479
+ g1_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
480
+ G1, edge_attr="edge_attr1", node_attr="node_attr1"
481
+ )
482
+ g1_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
483
+ G1, edge_attr="edge_attr2", node_attr="node_attr2"
484
+ )
485
+ g1_hash_edge1_node2 = nx.weisfeiler_lehman_subgraph_hashes(
486
+ G1, edge_attr="edge_attr1", node_attr="node_attr2"
487
+ )
488
+ g1_hash_no_attr = nx.weisfeiler_lehman_subgraph_hashes(G1)
489
+
490
+ assert g1_hash_edge1_node1 != g1_hash_no_attr
491
+ assert g1_hash_edge2_node2 != g1_hash_no_attr
492
+ assert g1_hash_edge1_node1 != g1_hash_edge2_node2
493
+ assert g1_hash_edge1_node2 != g1_hash_edge2_node2
494
+ assert g1_hash_edge1_node2 != g1_hash_edge1_node1
495
+
496
+ G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
497
+
498
+ g2_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
499
+ G2, edge_attr="edge_attr1", node_attr="node_attr1"
500
+ )
501
+ g2_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
502
+ G2, edge_attr="edge_attr2", node_attr="node_attr2"
503
+ )
504
+
505
+ assert g1_hash_edge1_node1 == {
506
+ -1 * k: v for k, v in g2_hash_edge1_node1.items()
507
+ }
508
+ assert g1_hash_edge2_node2 == {
509
+ -1 * k: v for k, v in g2_hash_edge2_node2.items()
510
+ }
511
+
512
+
513
+ def test_iteration_depth():
514
+ """
515
+ All nodes should have the correct number of subgraph hashes in the output when
516
+ using degree as initial node labels
517
+ Subsequent iteration depths for the same graph should be additive for each node
518
+ """
519
+ n, r = 100, 10
520
+ p = 1.0 / r
521
+ for i in range(1, r + 1):
522
+ G = nx.erdos_renyi_graph(n, p * i, seed=600 + i)
523
+
524
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=3)
525
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=4)
526
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=5)
527
+
528
+ assert all(len(hashes) == 3 for hashes in depth3.values())
529
+ assert all(len(hashes) == 4 for hashes in depth4.values())
530
+ assert all(len(hashes) == 5 for hashes in depth5.values())
531
+
532
+ assert is_subiteration(depth3, depth4)
533
+ assert is_subiteration(depth4, depth5)
534
+ assert is_subiteration(depth3, depth5)
535
+
536
+
537
+ def test_iteration_depth_edge_attr():
538
+ """
539
+ All nodes should have the correct number of subgraph hashes in the output when
540
+ setting initial node labels empty and using an edge attribute when aggregating
541
+ neighborhoods.
542
+ Subsequent iteration depths for the same graph should be additive for each node
543
+ """
544
+ n, r = 100, 10
545
+ p = 1.0 / r
546
+ for i in range(1, r + 1):
547
+ G = nx.erdos_renyi_graph(n, p * i, seed=700 + i)
548
+
549
+ for a, b in G.edges:
550
+ G[a][b]["edge_attr1"] = f"{a}-{b}-1"
551
+
552
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(
553
+ G, edge_attr="edge_attr1", iterations=3
554
+ )
555
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(
556
+ G, edge_attr="edge_attr1", iterations=4
557
+ )
558
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(
559
+ G, edge_attr="edge_attr1", iterations=5
560
+ )
561
+
562
+ assert all(len(hashes) == 3 for hashes in depth3.values())
563
+ assert all(len(hashes) == 4 for hashes in depth4.values())
564
+ assert all(len(hashes) == 5 for hashes in depth5.values())
565
+
566
+ assert is_subiteration(depth3, depth4)
567
+ assert is_subiteration(depth4, depth5)
568
+ assert is_subiteration(depth3, depth5)
569
+
570
+
571
+ def test_iteration_depth_node_attr():
572
+ """
573
+ All nodes should have the correct number of subgraph hashes in the output when
574
+ setting initial node labels to an attribute.
575
+ Subsequent iteration depths for the same graph should be additive for each node
576
+ """
577
+ n, r = 100, 10
578
+ p = 1.0 / r
579
+ for i in range(1, r + 1):
580
+ G = nx.erdos_renyi_graph(n, p * i, seed=800 + i)
581
+
582
+ for u in G.nodes():
583
+ G.nodes[u]["node_attr1"] = f"{u}-1"
584
+
585
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(
586
+ G, node_attr="node_attr1", iterations=3
587
+ )
588
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(
589
+ G, node_attr="node_attr1", iterations=4
590
+ )
591
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(
592
+ G, node_attr="node_attr1", iterations=5
593
+ )
594
+
595
+ assert all(len(hashes) == 3 for hashes in depth3.values())
596
+ assert all(len(hashes) == 4 for hashes in depth4.values())
597
+ assert all(len(hashes) == 5 for hashes in depth5.values())
598
+
599
+ assert is_subiteration(depth3, depth4)
600
+ assert is_subiteration(depth4, depth5)
601
+ assert is_subiteration(depth3, depth5)
602
+
603
+
604
+ def test_iteration_depth_node_edge_attr():
605
+ """
606
+ All nodes should have the correct number of subgraph hashes in the output when
607
+ setting initial node labels to an attribute and also using an edge attribute when
608
+ aggregating neighborhoods.
609
+ Subsequent iteration depths for the same graph should be additive for each node
610
+ """
611
+ n, r = 100, 10
612
+ p = 1.0 / r
613
+ for i in range(1, r + 1):
614
+ G = nx.erdos_renyi_graph(n, p * i, seed=900 + i)
615
+
616
+ for u in G.nodes():
617
+ G.nodes[u]["node_attr1"] = f"{u}-1"
618
+
619
+ for a, b in G.edges:
620
+ G[a][b]["edge_attr1"] = f"{a}-{b}-1"
621
+
622
+ depth3 = nx.weisfeiler_lehman_subgraph_hashes(
623
+ G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=3
624
+ )
625
+ depth4 = nx.weisfeiler_lehman_subgraph_hashes(
626
+ G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=4
627
+ )
628
+ depth5 = nx.weisfeiler_lehman_subgraph_hashes(
629
+ G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=5
630
+ )
631
+
632
+ assert all(len(hashes) == 3 for hashes in depth3.values())
633
+ assert all(len(hashes) == 4 for hashes in depth4.values())
634
+ assert all(len(hashes) == 5 for hashes in depth5.values())
635
+
636
+ assert is_subiteration(depth3, depth4)
637
+ assert is_subiteration(depth4, depth5)
638
+ assert is_subiteration(depth3, depth5)
639
+
640
+
641
+ def test_digest_size_subgraph_hash():
642
+ """
643
+ The hash string lengths should be as expected for a variety of graphs and
644
+ digest sizes
645
+ """
646
+ n, r = 100, 10
647
+ p = 1.0 / r
648
+ for i in range(1, r + 1):
649
+ G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
650
+
651
+ digest_size16_hashes = nx.weisfeiler_lehman_subgraph_hashes(G)
652
+ digest_size32_hashes = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=32)
653
+
654
+ assert digest_size16_hashes != digest_size32_hashes
655
+
656
+ assert hexdigest_sizes_correct(digest_size16_hashes, 16)
657
+ assert hexdigest_sizes_correct(digest_size32_hashes, 32)
658
+
659
+
660
+ def test_initial_node_labels_subgraph_hash():
661
+ """
662
+ Including the hashed initial label prepends an extra hash to the lists
663
+ """
664
+ G = nx.path_graph(5)
665
+ nx.set_node_attributes(G, {i: int(0 < i < 4) for i in G}, "label")
666
+ # initial node labels:
667
+ # 0--1--1--1--0
668
+
669
+ without_initial_label = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
670
+ assert all(len(v) == 3 for v in without_initial_label.values())
671
+ # 3 different 1 hop nhds
672
+ assert len({v[0] for v in without_initial_label.values()}) == 3
673
+
674
+ with_initial_label = nx.weisfeiler_lehman_subgraph_hashes(
675
+ G, node_attr="label", include_initial_labels=True
676
+ )
677
+ assert all(len(v) == 4 for v in with_initial_label.values())
678
+ # 2 different initial labels
679
+ assert len({v[0] for v in with_initial_label.values()}) == 2
680
+
681
+ # check hashes match otherwise
682
+ for u in G:
683
+ for a, b in zip(
684
+ with_initial_label[u][1:], without_initial_label[u], strict=True
685
+ ):
686
+ assert a == b