godlykmathews commited on
Commit
10f13f9
·
verified ·
1 Parent(s): 6c16ba9

Upload folder using huggingface_hub (part 7)

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 +4 -0
  2. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/INSTALLER +1 -0
  3. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/METADATA +175 -0
  4. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/RECORD +0 -0
  5. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/WHEEL +5 -0
  6. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/entry_points.txt +2 -0
  7. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/licenses/LICENSE.txt +37 -0
  8. venv/lib/python3.14/site-packages/networkx-3.7.dist-info/top_level.txt +1 -0
  9. venv/lib/python3.14/site-packages/networkx/classes/tests/test_reportviews.py +1444 -0
  10. venv/lib/python3.14/site-packages/networkx/classes/tests/test_special.py +131 -0
  11. venv/lib/python3.14/site-packages/networkx/classes/tests/test_subgraphviews.py +371 -0
  12. venv/lib/python3.14/site-packages/networkx/conftest.py +285 -0
  13. venv/lib/python3.14/site-packages/networkx/convert.py +502 -0
  14. venv/lib/python3.14/site-packages/networkx/convert_matrix.py +1350 -0
  15. venv/lib/python3.14/site-packages/networkx/drawing/__init__.py +7 -0
  16. venv/lib/python3.14/site-packages/networkx/drawing/layout.py +2041 -0
  17. venv/lib/python3.14/site-packages/networkx/drawing/nx_agraph.py +473 -0
  18. venv/lib/python3.14/site-packages/networkx/drawing/nx_latex.py +699 -0
  19. venv/lib/python3.14/site-packages/networkx/drawing/nx_pydot.py +361 -0
  20. venv/lib/python3.14/site-packages/networkx/drawing/nx_pylab.py +0 -0
  21. venv/lib/python3.14/site-packages/networkx/drawing/tests/__init__.py +0 -0
  22. venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_complex.png +3 -0
  23. venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_empty_graph.png +0 -0
  24. venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_house_with_colors.png +0 -0
  25. venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_labels_and_colors.png +0 -0
  26. venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_shortest_path.png +0 -0
  27. venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png +0 -0
  28. venv/lib/python3.14/site-packages/networkx/drawing/tests/test_agraph.py +261 -0
  29. venv/lib/python3.14/site-packages/networkx/drawing/tests/test_image_comparison_pylab_mpl.py +229 -0
  30. venv/lib/python3.14/site-packages/networkx/drawing/tests/test_latex.py +285 -0
  31. venv/lib/python3.14/site-packages/networkx/drawing/tests/test_layout.py +679 -0
  32. venv/lib/python3.14/site-packages/networkx/drawing/tests/test_pydot.py +158 -0
  33. venv/lib/python3.14/site-packages/networkx/drawing/tests/test_pylab.py +1581 -0
  34. venv/lib/python3.14/site-packages/networkx/exception.py +131 -0
  35. venv/lib/python3.14/site-packages/networkx/generators/__init__.py +34 -0
  36. venv/lib/python3.14/site-packages/networkx/generators/atlas.dat.gz +3 -0
  37. venv/lib/python3.14/site-packages/networkx/generators/atlas.py +227 -0
  38. venv/lib/python3.14/site-packages/networkx/generators/classic.py +1102 -0
  39. venv/lib/python3.14/site-packages/networkx/generators/cographs.py +68 -0
  40. venv/lib/python3.14/site-packages/networkx/generators/community.py +1067 -0
  41. venv/lib/python3.14/site-packages/networkx/generators/degree_seq.py +886 -0
  42. venv/lib/python3.14/site-packages/networkx/generators/directed.py +572 -0
  43. venv/lib/python3.14/site-packages/networkx/generators/duplication.py +173 -0
  44. venv/lib/python3.14/site-packages/networkx/generators/ego.py +66 -0
  45. venv/lib/python3.14/site-packages/networkx/generators/expanders.py +502 -0
  46. venv/lib/python3.14/site-packages/networkx/generators/geometric.py +1037 -0
  47. venv/lib/python3.14/site-packages/networkx/generators/harary_graph.py +162 -0
  48. venv/lib/python3.14/site-packages/networkx/generators/internet_as_graphs.py +443 -0
  49. venv/lib/python3.14/site-packages/networkx/generators/intersection.py +125 -0
  50. venv/lib/python3.14/site-packages/networkx/generators/interval_graph.py +70 -0
.gitattributes CHANGED
@@ -61,3 +61,7 @@ venv/lib/python3.14/site-packages/google/_upb/_message.abi3.so filter=lfs diff=l
61
  venv/lib/python3.14/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
62
  venv/lib/python3.14/site-packages/httptools/parser/parser.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
63
  venv/lib/python3.14/site-packages/httptools/parser/url_parser.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
61
  venv/lib/python3.14/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
62
  venv/lib/python3.14/site-packages/httptools/parser/parser.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
63
  venv/lib/python3.14/site-packages/httptools/parser/url_parser.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
64
+ venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text
65
+ venv/lib/python3.14/site-packages/numpy/_core/_multiarray_tests.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
66
+ venv/lib/python3.14/site-packages/numpy/_core/_multiarray_umath.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
67
+ venv/lib/python3.14/site-packages/numpy/_core/_simd.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/METADATA ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: networkx
3
+ Version: 3.7
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
+ License-Expression: BSD-3-Clause
8
+ Project-URL: Homepage, https://networkx.org/
9
+ Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues
10
+ Project-URL: Documentation, https://networkx.org/documentation/stable/
11
+ Project-URL: Source Code, https://github.com/networkx/networkx
12
+ Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math
13
+ Platform: Linux
14
+ Platform: Mac OSX
15
+ Platform: Windows
16
+ Platform: Unix
17
+ Classifier: Development Status :: 5 - Production/Stable
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Intended Audience :: Science/Research
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: 3.15
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.14.1,>=3.12
33
+ Description-Content-Type: text/x-rst
34
+ License-File: LICENSE.txt
35
+ Provides-Extra: benchmarking
36
+ Requires-Dist: asv>=0.6.5; extra == "benchmarking"
37
+ Requires-Dist: py-rattler<0.22,>=0.21; extra == "benchmarking"
38
+ Requires-Dist: virtualenv; extra == "benchmarking"
39
+ Provides-Extra: default
40
+ Requires-Dist: numpy>=2.2; extra == "default"
41
+ Requires-Dist: scipy>=1.15; extra == "default"
42
+ Requires-Dist: matplotlib>=3.10; extra == "default"
43
+ Requires-Dist: pandas>=2.3; extra == "default"
44
+ Provides-Extra: developer
45
+ Requires-Dist: pre-commit>=4.1; extra == "developer"
46
+ Requires-Dist: mypy>=1.15; extra == "developer"
47
+ Provides-Extra: doc
48
+ Requires-Dist: sphinx>=8.0; extra == "doc"
49
+ Requires-Dist: pydata-sphinx-theme>=0.16; extra == "doc"
50
+ Requires-Dist: sphinx-gallery>=0.18; extra == "doc"
51
+ Requires-Dist: numpydoc>=1.8.0; extra == "doc"
52
+ Requires-Dist: pillow>=10; extra == "doc"
53
+ Requires-Dist: texext>=0.6.7; extra == "doc"
54
+ Requires-Dist: myst-nb>=1.1; extra == "doc"
55
+ Requires-Dist: intersphinx-registry; extra == "doc"
56
+ Provides-Extra: example
57
+ Requires-Dist: osmnx>=2.0.0; extra == "example"
58
+ Requires-Dist: momepy>=0.7.2; extra == "example"
59
+ Requires-Dist: contextily>=1.6; extra == "example"
60
+ Requires-Dist: seaborn>=0.13; extra == "example"
61
+ Requires-Dist: cairocffi>=1.7; extra == "example"
62
+ Requires-Dist: igraph>=0.11; extra == "example"
63
+ Requires-Dist: scikit-learn>=1.6; extra == "example"
64
+ Requires-Dist: iplotx>=0.9.0; extra == "example"
65
+ Requires-Dist: hiveplotlib>=0.28; extra == "example"
66
+ Provides-Extra: extra
67
+ Requires-Dist: lxml>=4.6; extra == "extra"
68
+ Requires-Dist: pygraphviz>=2.0; extra == "extra"
69
+ Requires-Dist: pydot>=3.0.1; extra == "extra"
70
+ Requires-Dist: sympy>=1.10; extra == "extra"
71
+ Provides-Extra: release
72
+ Requires-Dist: build>=0.10; extra == "release"
73
+ Requires-Dist: twine>=4.0; extra == "release"
74
+ Requires-Dist: wheel>=0.40; extra == "release"
75
+ Requires-Dist: changelist==0.5; extra == "release"
76
+ Provides-Extra: test
77
+ Requires-Dist: pytest>=7.2; extra == "test"
78
+ Requires-Dist: pytest-cov>=4.0; extra == "test"
79
+ Requires-Dist: pytest-xdist>=3.0; extra == "test"
80
+ Provides-Extra: test-extras
81
+ Requires-Dist: pytest-mpl; extra == "test-extras"
82
+ Requires-Dist: pytest-randomly; extra == "test-extras"
83
+ Dynamic: license-file
84
+
85
+ NetworkX
86
+ ========
87
+
88
+
89
+ .. image::
90
+ https://github.com/networkx/networkx/actions/workflows/test.yml/badge.svg?branch=main
91
+ :target: https://github.com/networkx/networkx/actions/workflows/test.yml
92
+
93
+ .. image::
94
+ https://img.shields.io/pypi/v/networkx.svg?
95
+ :target: https://pypi.python.org/pypi/networkx
96
+
97
+ .. image::
98
+ https://img.shields.io/pypi/l/networkx.svg?
99
+ :target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
100
+
101
+ .. image::
102
+ https://img.shields.io/pypi/pyversions/networkx.svg?
103
+ :target: https://pypi.python.org/pypi/networkx
104
+
105
+ .. image::
106
+ https://insights.linuxfoundation.org/api/badge/health-score?project=networkx
107
+ :target: https://insights.linuxfoundation.org/project/networkx
108
+
109
+
110
+ NetworkX is a Python package for the creation, manipulation,
111
+ and study of the structure, dynamics, and functions
112
+ of complex networks.
113
+
114
+ - **Website (including documentation):** https://networkx.org
115
+ - **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
116
+ - **Source:** https://github.com/networkx/networkx
117
+ - **Bug reports:** https://github.com/networkx/networkx/issues
118
+ - **Report a security vulnerability:** https://tidelift.com/security
119
+ - **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
120
+ - **GitHub Discussions:** https://github.com/networkx/networkx/discussions
121
+ - **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz
122
+ - **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
123
+
124
+ Simple example
125
+ --------------
126
+
127
+ Find the shortest path between two nodes in an undirected graph:
128
+
129
+ .. code:: pycon
130
+
131
+ >>> import networkx as nx
132
+ >>> G = nx.Graph()
133
+ >>> G.add_edge("A", "B", weight=4)
134
+ >>> G.add_edge("B", "D", weight=2)
135
+ >>> G.add_edge("A", "C", weight=3)
136
+ >>> G.add_edge("C", "D", weight=4)
137
+ >>> nx.shortest_path(G, "A", "D", weight="weight")
138
+ ['A', 'B', 'D']
139
+
140
+ Install
141
+ -------
142
+
143
+ Install the latest released version of NetworkX:
144
+
145
+ .. code:: shell
146
+
147
+ $ pip install networkx
148
+
149
+ Install with all optional dependencies:
150
+
151
+ .. code:: shell
152
+
153
+ $ pip install networkx[default]
154
+
155
+ For additional details,
156
+ please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
157
+
158
+ Bugs
159
+ ----
160
+
161
+ Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
162
+ Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
163
+ and create a pull request (PR). We welcome all changes, big or small, and we
164
+ will help you make the PR if you are new to `git` (just ask on the issue and/or
165
+ see the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
166
+
167
+ License
168
+ -------
169
+
170
+ Released under the `3-clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
171
+
172
+ Copyright (c) 2004-2026, NetworkX Developers
173
+ Aric Hagberg <hagberg@lanl.gov>
174
+ Dan Schult <dschult@colgate.edu>
175
+ Pieter Swart <swart@lanl.gov>
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [networkx.backends]
2
+ nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NetworkX is distributed with the 3-clause BSD license.
2
+
3
+ ::
4
+
5
+ Copyright (c) 2004-2026, 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.
venv/lib/python3.14/site-packages/networkx-3.7.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ networkx
venv/lib/python3.14/site-packages/networkx/classes/tests/test_reportviews.py ADDED
@@ -0,0 +1,1444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from copy import deepcopy
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.classes import reportviews as rv
8
+ from networkx.classes.reportviews import NodeDataView
9
+
10
+
11
+ # Nodes
12
+ class TestNodeView:
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9)
16
+ cls.nv = cls.G.nodes # NodeView(G)
17
+
18
+ def test_pickle(self):
19
+ import pickle
20
+
21
+ nv = self.nv
22
+ pnv = pickle.loads(pickle.dumps(nv, -1))
23
+ assert nv == pnv
24
+ assert nv.__slots__ == pnv.__slots__
25
+
26
+ def test_str(self):
27
+ assert str(self.nv) == "[0, 1, 2, 3, 4, 5, 6, 7, 8]"
28
+
29
+ def test_repr(self):
30
+ assert repr(self.nv) == "NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
31
+
32
+ def test_contains(self):
33
+ G = self.G.copy()
34
+ nv = G.nodes
35
+ assert 7 in nv
36
+ assert 9 not in nv
37
+ G.remove_node(7)
38
+ G.add_node(9)
39
+ assert 7 not in nv
40
+ assert 9 in nv
41
+
42
+ def test_getitem(self):
43
+ G = self.G.copy()
44
+ nv = G.nodes
45
+ G.nodes[3]["foo"] = "bar"
46
+ assert nv[7] == {}
47
+ assert nv[3] == {"foo": "bar"}
48
+ # slicing
49
+ with pytest.raises(nx.NetworkXError):
50
+ G.nodes[0:5]
51
+
52
+ def test_iter(self):
53
+ nv = self.nv
54
+ for i, n in enumerate(nv):
55
+ assert i == n
56
+ inv = iter(nv)
57
+ assert next(inv) == 0
58
+ assert iter(nv) != nv
59
+ assert iter(inv) == inv
60
+ inv2 = iter(nv)
61
+ next(inv2)
62
+ assert list(inv) == list(inv2)
63
+ # odd case where NodeView calls NodeDataView with data=False
64
+ nnv = nv(data=False)
65
+ for i, n in enumerate(nnv):
66
+ assert i == n
67
+
68
+ def test_call(self):
69
+ nodes = self.nv
70
+ assert nodes is nodes()
71
+ assert nodes is not nodes(data=True)
72
+ assert nodes is not nodes(data="weight")
73
+
74
+
75
+ class TestNodeDataView:
76
+ @classmethod
77
+ def setup_class(cls):
78
+ cls.G = nx.path_graph(9)
79
+ cls.nv = NodeDataView(cls.G)
80
+ cls.ndv = cls.G.nodes.data(True)
81
+ cls.nwv = cls.G.nodes.data("foo")
82
+
83
+ def test_viewtype(self):
84
+ nv = self.G.nodes
85
+ ndvfalse = nv.data(False)
86
+ assert nv is ndvfalse
87
+ assert nv is not self.ndv
88
+
89
+ def test_pickle(self):
90
+ import pickle
91
+
92
+ nv = self.nv
93
+ pnv = pickle.loads(pickle.dumps(nv, -1))
94
+ assert nv == pnv
95
+ assert nv.__slots__ == pnv.__slots__
96
+
97
+ def test_str(self):
98
+ msg = str([(n, {}) for n in range(9)])
99
+ assert str(self.ndv) == msg
100
+
101
+ def test_repr(self):
102
+ expected = "NodeDataView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
103
+ assert repr(self.nv) == expected
104
+ expected = (
105
+ "NodeDataView({0: {}, 1: {}, 2: {}, 3: {}, "
106
+ + "4: {}, 5: {}, 6: {}, 7: {}, 8: {}})"
107
+ )
108
+ assert repr(self.ndv) == expected
109
+ expected = (
110
+ "NodeDataView({0: None, 1: None, 2: None, 3: None, 4: None, "
111
+ + "5: None, 6: None, 7: None, 8: None}, data='foo')"
112
+ )
113
+ assert repr(self.nwv) == expected
114
+
115
+ def test_contains(self):
116
+ G = self.G.copy()
117
+ nv = G.nodes.data()
118
+ nwv = G.nodes.data("foo")
119
+ G.nodes[3]["foo"] = "bar"
120
+ assert (7, {}) in nv
121
+ assert (3, {"foo": "bar"}) in nv
122
+ assert (3, "bar") in nwv
123
+ assert (7, None) in nwv
124
+ # default
125
+ nwv_def = G.nodes(data="foo", default="biz")
126
+ assert (7, "biz") in nwv_def
127
+ assert (3, "bar") in nwv_def
128
+
129
+ def test_getitem(self):
130
+ G = self.G.copy()
131
+ nv = G.nodes
132
+ G.nodes[3]["foo"] = "bar"
133
+ assert nv[3] == {"foo": "bar"}
134
+ # default
135
+ nwv_def = G.nodes(data="foo", default="biz")
136
+ assert nwv_def[7], "biz"
137
+ assert nwv_def[3] == "bar"
138
+ # slicing
139
+ with pytest.raises(nx.NetworkXError):
140
+ G.nodes.data()[0:5]
141
+
142
+ def test_iter(self):
143
+ G = self.G.copy()
144
+ nv = G.nodes.data()
145
+ ndv = G.nodes.data(True)
146
+ nwv = G.nodes.data("foo")
147
+ for i, (n, d) in enumerate(nv):
148
+ assert i == n
149
+ assert d == {}
150
+ inv = iter(nv)
151
+ assert next(inv) == (0, {})
152
+ G.nodes[3]["foo"] = "bar"
153
+ # default
154
+ for n, d in nv:
155
+ if n == 3:
156
+ assert d == {"foo": "bar"}
157
+ else:
158
+ assert d == {}
159
+ # data=True
160
+ for n, d in ndv:
161
+ if n == 3:
162
+ assert d == {"foo": "bar"}
163
+ else:
164
+ assert d == {}
165
+ # data='foo'
166
+ for n, d in nwv:
167
+ if n == 3:
168
+ assert d == "bar"
169
+ else:
170
+ assert d is None
171
+ # data='foo', default=1
172
+ for n, d in G.nodes.data("foo", default=1):
173
+ if n == 3:
174
+ assert d == "bar"
175
+ else:
176
+ assert d == 1
177
+
178
+
179
+ def test_nodedataview_unhashable():
180
+ G = nx.path_graph(9)
181
+ G.nodes[3]["foo"] = "bar"
182
+ nvs = [G.nodes.data()]
183
+ nvs.append(G.nodes.data(True))
184
+ H = G.copy()
185
+ H.nodes[4]["foo"] = {1, 2, 3}
186
+ nvs.append(H.nodes.data(True))
187
+ # raise unhashable
188
+ for nv in nvs:
189
+ pytest.raises(TypeError, set, nv)
190
+ pytest.raises(TypeError, eval, "nv | nv", locals())
191
+ # no raise... hashable
192
+ Gn = G.nodes.data(False)
193
+ set(Gn)
194
+ Gn | Gn
195
+ Gn = G.nodes.data("foo")
196
+ set(Gn)
197
+ Gn | Gn
198
+
199
+
200
+ class TestNodeViewSetOps:
201
+ @classmethod
202
+ def setup_class(cls):
203
+ cls.G = nx.path_graph(9)
204
+ cls.G.nodes[3]["foo"] = "bar"
205
+ cls.nv = cls.G.nodes
206
+
207
+ def n_its(self, nodes):
208
+ return set(nodes)
209
+
210
+ def test_len(self):
211
+ G = self.G.copy()
212
+ nv = G.nodes
213
+ assert len(nv) == 9
214
+ G.remove_node(7)
215
+ assert len(nv) == 8
216
+ G.add_node(9)
217
+ assert len(nv) == 9
218
+
219
+ def test_and(self):
220
+ nv = self.nv
221
+ some_nodes = self.n_its(range(5, 12))
222
+ assert nv & some_nodes == self.n_its(range(5, 9))
223
+ assert some_nodes & nv == self.n_its(range(5, 9))
224
+
225
+ def test_or(self):
226
+ nv = self.nv
227
+ some_nodes = self.n_its(range(5, 12))
228
+ assert nv | some_nodes == self.n_its(range(12))
229
+ assert some_nodes | nv == self.n_its(range(12))
230
+
231
+ def test_xor(self):
232
+ nv = self.nv
233
+ some_nodes = self.n_its(range(5, 12))
234
+ nodes = {0, 1, 2, 3, 4, 9, 10, 11}
235
+ assert nv ^ some_nodes == self.n_its(nodes)
236
+ assert some_nodes ^ nv == self.n_its(nodes)
237
+
238
+ def test_sub(self):
239
+ nv = self.nv
240
+ some_nodes = self.n_its(range(5, 12))
241
+ assert nv - some_nodes == self.n_its(range(5))
242
+ assert some_nodes - nv == self.n_its(range(9, 12))
243
+
244
+
245
+ class TestNodeDataViewSetOps(TestNodeViewSetOps):
246
+ @classmethod
247
+ def setup_class(cls):
248
+ cls.G = nx.path_graph(9)
249
+ cls.G.nodes[3]["foo"] = "bar"
250
+ cls.nv = cls.G.nodes.data("foo")
251
+
252
+ def n_its(self, nodes):
253
+ return {(node, "bar" if node == 3 else None) for node in nodes}
254
+
255
+
256
+ class TestNodeDataViewDefaultSetOps(TestNodeDataViewSetOps):
257
+ @classmethod
258
+ def setup_class(cls):
259
+ cls.G = nx.path_graph(9)
260
+ cls.G.nodes[3]["foo"] = "bar"
261
+ cls.nv = cls.G.nodes.data("foo", default=1)
262
+
263
+ def n_its(self, nodes):
264
+ return {(node, "bar" if node == 3 else 1) for node in nodes}
265
+
266
+
267
+ # Edges Data View
268
+ class TestEdgeDataView:
269
+ @classmethod
270
+ def setup_class(cls):
271
+ cls.G = nx.path_graph(9)
272
+ cls.eview = nx.reportviews.EdgeView
273
+
274
+ def test_pickle(self):
275
+ import pickle
276
+
277
+ ev = self.eview(self.G)(data=True)
278
+ pev = pickle.loads(pickle.dumps(ev, -1))
279
+ assert list(ev) == list(pev)
280
+ assert ev.__slots__ == pev.__slots__
281
+
282
+ def modify_edge(self, G, e, **kwds):
283
+ G._adj[e[0]][e[1]].update(kwds)
284
+
285
+ def test_str(self):
286
+ ev = self.eview(self.G)(data=True)
287
+ rep = str([(n, n + 1, {}) for n in range(8)])
288
+ assert str(ev) == rep
289
+
290
+ def test_repr(self):
291
+ ev = self.eview(self.G)(data=True)
292
+ rep = (
293
+ "EdgeDataView([(0, 1, {}), (1, 2, {}), "
294
+ + "(2, 3, {}), (3, 4, {}), "
295
+ + "(4, 5, {}), (5, 6, {}), "
296
+ + "(6, 7, {}), (7, 8, {})])"
297
+ )
298
+ assert repr(ev) == rep
299
+
300
+ def test_iterdata(self):
301
+ G = self.G.copy()
302
+ evr = self.eview(G)
303
+ ev = evr(data=True)
304
+ ev_def = evr(data="foo", default=1)
305
+
306
+ for u, v, d in ev:
307
+ pass
308
+ assert d == {}
309
+
310
+ for u, v, wt in ev_def:
311
+ pass
312
+ assert wt == 1
313
+
314
+ self.modify_edge(G, (2, 3), foo="bar")
315
+ for e in ev:
316
+ assert len(e) == 3
317
+ if set(e[:2]) == {2, 3}:
318
+ assert e[2] == {"foo": "bar"}
319
+ checked = True
320
+ else:
321
+ assert e[2] == {}
322
+ assert checked
323
+
324
+ for e in ev_def:
325
+ assert len(e) == 3
326
+ if set(e[:2]) == {2, 3}:
327
+ assert e[2] == "bar"
328
+ checked_wt = True
329
+ else:
330
+ assert e[2] == 1
331
+ assert checked_wt
332
+
333
+ def test_iter(self):
334
+ evr = self.eview(self.G)
335
+ ev = evr()
336
+ for u, v in ev:
337
+ pass
338
+ iev = iter(ev)
339
+ assert next(iev) == (0, 1)
340
+ assert iter(ev) != ev
341
+ assert iter(iev) == iev
342
+
343
+ def test_contains(self):
344
+ evr = self.eview(self.G)
345
+ ev = evr()
346
+ if self.G.is_directed():
347
+ assert (1, 2) in ev and (2, 1) not in ev
348
+ else:
349
+ assert (1, 2) in ev and (2, 1) in ev
350
+ assert (1, 4) not in ev
351
+ assert (1, 90) not in ev
352
+ assert (90, 1) not in ev
353
+
354
+ def test_contains_with_nbunch(self):
355
+ evr = self.eview(self.G)
356
+ ev = evr(nbunch=[0, 2])
357
+ if self.G.is_directed():
358
+ assert (0, 1) in ev
359
+ assert (1, 2) not in ev
360
+ assert (2, 3) in ev
361
+ else:
362
+ assert (0, 1) in ev
363
+ assert (1, 2) in ev
364
+ assert (2, 3) in ev
365
+ assert (3, 4) not in ev
366
+ assert (4, 5) not in ev
367
+ assert (5, 6) not in ev
368
+ assert (7, 8) not in ev
369
+ assert (8, 9) not in ev
370
+
371
+ def test_len(self):
372
+ evr = self.eview(self.G)
373
+ ev = evr(data="foo")
374
+ assert len(ev) == 8
375
+ assert len(evr(1)) == 2
376
+ assert len(evr([1, 2, 3])) == 4
377
+
378
+ assert len(self.G.edges(1)) == 2
379
+ assert len(self.G.edges()) == 8
380
+ assert len(self.G.edges) == 8
381
+
382
+ H = self.G.copy()
383
+ H.add_edge(1, 1)
384
+ assert len(H.edges(1)) == 3
385
+ assert len(H.edges()) == 9
386
+ assert len(H.edges) == 9
387
+
388
+
389
+ class TestOutEdgeDataView(TestEdgeDataView):
390
+ @classmethod
391
+ def setup_class(cls):
392
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
393
+ cls.eview = nx.reportviews.OutEdgeView
394
+
395
+ def test_repr(self):
396
+ ev = self.eview(self.G)(data=True)
397
+ rep = (
398
+ "OutEdgeDataView([(0, 1, {}), (1, 2, {}), "
399
+ + "(2, 3, {}), (3, 4, {}), "
400
+ + "(4, 5, {}), (5, 6, {}), "
401
+ + "(6, 7, {}), (7, 8, {})])"
402
+ )
403
+ assert repr(ev) == rep
404
+
405
+ def test_len(self):
406
+ evr = self.eview(self.G)
407
+ ev = evr(data="foo")
408
+ assert len(ev) == 8
409
+ assert len(evr(1)) == 1
410
+ assert len(evr([1, 2, 3])) == 3
411
+
412
+ assert len(self.G.edges(1)) == 1
413
+ assert len(self.G.edges()) == 8
414
+ assert len(self.G.edges) == 8
415
+
416
+ H = self.G.copy()
417
+ H.add_edge(1, 1)
418
+ assert len(H.edges(1)) == 2
419
+ assert len(H.edges()) == 9
420
+ assert len(H.edges) == 9
421
+
422
+ def test_contains_with_nbunch(self):
423
+ evr = self.eview(self.G)
424
+ ev = evr(nbunch=[0, 2])
425
+ assert (0, 1) in ev
426
+ assert (1, 2) not in ev
427
+ assert (2, 3) in ev
428
+ assert (3, 4) not in ev
429
+ assert (4, 5) not in ev
430
+ assert (5, 6) not in ev
431
+ assert (7, 8) not in ev
432
+ assert (8, 9) not in ev
433
+
434
+
435
+ class TestInEdgeDataView(TestOutEdgeDataView):
436
+ @classmethod
437
+ def setup_class(cls):
438
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
439
+ cls.eview = nx.reportviews.InEdgeView
440
+
441
+ def test_repr(self):
442
+ ev = self.eview(self.G)(data=True)
443
+ rep = (
444
+ "InEdgeDataView([(0, 1, {}), (1, 2, {}), "
445
+ + "(2, 3, {}), (3, 4, {}), "
446
+ + "(4, 5, {}), (5, 6, {}), "
447
+ + "(6, 7, {}), (7, 8, {})])"
448
+ )
449
+ assert repr(ev) == rep
450
+
451
+ def test_contains_with_nbunch(self):
452
+ evr = self.eview(self.G)
453
+ ev = evr(nbunch=[0, 2])
454
+ assert (0, 1) not in ev
455
+ assert (1, 2) in ev
456
+ assert (2, 3) not in ev
457
+ assert (3, 4) not in ev
458
+ assert (4, 5) not in ev
459
+ assert (5, 6) not in ev
460
+ assert (7, 8) not in ev
461
+ assert (8, 9) not in ev
462
+
463
+
464
+ class TestMultiEdgeDataView(TestEdgeDataView):
465
+ @classmethod
466
+ def setup_class(cls):
467
+ cls.G = nx.path_graph(9, create_using=nx.MultiGraph())
468
+ cls.eview = nx.reportviews.MultiEdgeView
469
+
470
+ def modify_edge(self, G, e, **kwds):
471
+ G._adj[e[0]][e[1]][0].update(kwds)
472
+
473
+ def test_repr(self):
474
+ ev = self.eview(self.G)(data=True)
475
+ rep = (
476
+ "MultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
477
+ + "(2, 3, {}), (3, 4, {}), "
478
+ + "(4, 5, {}), (5, 6, {}), "
479
+ + "(6, 7, {}), (7, 8, {})])"
480
+ )
481
+ assert repr(ev) == rep
482
+
483
+ def test_contains_with_nbunch(self):
484
+ evr = self.eview(self.G)
485
+ ev = evr(nbunch=[0, 2])
486
+ assert (0, 1) in ev
487
+ assert (1, 2) in ev
488
+ assert (2, 3) in ev
489
+ assert (3, 4) not in ev
490
+ assert (4, 5) not in ev
491
+ assert (5, 6) not in ev
492
+ assert (7, 8) not in ev
493
+ assert (8, 9) not in ev
494
+
495
+
496
+ class TestOutMultiEdgeDataView(TestOutEdgeDataView):
497
+ @classmethod
498
+ def setup_class(cls):
499
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
500
+ cls.eview = nx.reportviews.OutMultiEdgeView
501
+
502
+ def modify_edge(self, G, e, **kwds):
503
+ G._adj[e[0]][e[1]][0].update(kwds)
504
+
505
+ def test_repr(self):
506
+ ev = self.eview(self.G)(data=True)
507
+ rep = (
508
+ "OutMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
509
+ + "(2, 3, {}), (3, 4, {}), "
510
+ + "(4, 5, {}), (5, 6, {}), "
511
+ + "(6, 7, {}), (7, 8, {})])"
512
+ )
513
+ assert repr(ev) == rep
514
+
515
+ def test_contains_with_nbunch(self):
516
+ evr = self.eview(self.G)
517
+ ev = evr(nbunch=[0, 2])
518
+ assert (0, 1) in ev
519
+ assert (1, 2) not in ev
520
+ assert (2, 3) in ev
521
+ assert (3, 4) not in ev
522
+ assert (4, 5) not in ev
523
+ assert (5, 6) not in ev
524
+ assert (7, 8) not in ev
525
+ assert (8, 9) not in ev
526
+
527
+
528
+ class TestInMultiEdgeDataView(TestOutMultiEdgeDataView):
529
+ @classmethod
530
+ def setup_class(cls):
531
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
532
+ cls.eview = nx.reportviews.InMultiEdgeView
533
+
534
+ def test_repr(self):
535
+ ev = self.eview(self.G)(data=True)
536
+ rep = (
537
+ "InMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
538
+ + "(2, 3, {}), (3, 4, {}), "
539
+ + "(4, 5, {}), (5, 6, {}), "
540
+ + "(6, 7, {}), (7, 8, {})])"
541
+ )
542
+ assert repr(ev) == rep
543
+
544
+ def test_contains_with_nbunch(self):
545
+ evr = self.eview(self.G)
546
+ ev = evr(nbunch=[0, 2])
547
+ assert (0, 1) not in ev
548
+ assert (1, 2) in ev
549
+ assert (2, 3) not in ev
550
+ assert (3, 4) not in ev
551
+ assert (4, 5) not in ev
552
+ assert (5, 6) not in ev
553
+ assert (7, 8) not in ev
554
+ assert (8, 9) not in ev
555
+
556
+
557
+ # Edge Views
558
+ class TestEdgeView:
559
+ @classmethod
560
+ def setup_class(cls):
561
+ cls.G = nx.path_graph(9)
562
+ cls.eview = nx.reportviews.EdgeView
563
+
564
+ def test_pickle(self):
565
+ import pickle
566
+
567
+ ev = self.eview(self.G)
568
+ pev = pickle.loads(pickle.dumps(ev, -1))
569
+ assert ev == pev
570
+ assert ev.__slots__ == pev.__slots__
571
+
572
+ def modify_edge(self, G, e, **kwds):
573
+ G._adj[e[0]][e[1]].update(kwds)
574
+
575
+ def test_str(self):
576
+ ev = self.eview(self.G)
577
+ rep = str([(n, n + 1) for n in range(8)])
578
+ assert str(ev) == rep
579
+
580
+ def test_repr(self):
581
+ ev = self.eview(self.G)
582
+ rep = (
583
+ "EdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
584
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
585
+ )
586
+ assert repr(ev) == rep
587
+
588
+ def test_getitem(self):
589
+ G = self.G.copy()
590
+ ev = G.edges
591
+ G.edges[0, 1]["foo"] = "bar"
592
+ assert ev[0, 1] == {"foo": "bar"}
593
+
594
+ # slicing
595
+ with pytest.raises(nx.NetworkXError, match=".*does not support slicing"):
596
+ G.edges[0:5]
597
+
598
+ # Missing edge
599
+ with pytest.raises(KeyError, match=r".*edge.*is not in the graph"):
600
+ G.edges[42, 42]
601
+
602
+ def test_call(self):
603
+ ev = self.eview(self.G)
604
+ assert id(ev) == id(ev())
605
+ assert id(ev) == id(ev(data=False))
606
+ assert id(ev) != id(ev(data=True))
607
+ assert id(ev) != id(ev(nbunch=1))
608
+
609
+ def test_data(self):
610
+ ev = self.eview(self.G)
611
+ assert id(ev) != id(ev.data())
612
+ assert id(ev) == id(ev.data(data=False))
613
+ assert id(ev) != id(ev.data(data=True))
614
+ assert id(ev) != id(ev.data(nbunch=1))
615
+
616
+ def test_iter(self):
617
+ ev = self.eview(self.G)
618
+ for u, v in ev:
619
+ pass
620
+ iev = iter(ev)
621
+ assert next(iev) == (0, 1)
622
+ assert iter(ev) != ev
623
+ assert iter(iev) == iev
624
+
625
+ def test_contains(self):
626
+ ev = self.eview(self.G)
627
+ edv = ev()
628
+ if self.G.is_directed():
629
+ assert (1, 2) in ev and (2, 1) not in ev
630
+ assert (1, 2) in edv and (2, 1) not in edv
631
+ else:
632
+ assert (1, 2) in ev and (2, 1) in ev
633
+ assert (1, 2) in edv and (2, 1) in edv
634
+ assert (1, 4) not in ev
635
+ assert (1, 4) not in edv
636
+ # edge not in graph
637
+ assert (1, 90) not in ev
638
+ assert (90, 1) not in ev
639
+ assert (1, 90) not in edv
640
+ assert (90, 1) not in edv
641
+
642
+ def test_contains_with_nbunch(self):
643
+ ev = self.eview(self.G)
644
+ evn = ev(nbunch=[0, 2])
645
+ assert (0, 1) in evn
646
+ assert (1, 2) in evn
647
+ assert (2, 3) in evn
648
+ assert (3, 4) not in evn
649
+ assert (4, 5) not in evn
650
+ assert (5, 6) not in evn
651
+ assert (7, 8) not in evn
652
+ assert (8, 9) not in evn
653
+
654
+ def test_len(self):
655
+ ev = self.eview(self.G)
656
+ num_ed = 9 if self.G.is_multigraph() else 8
657
+ assert len(ev) == num_ed
658
+
659
+ H = self.G.copy()
660
+ H.add_edge(1, 1)
661
+ assert len(H.edges(1)) == 3 + H.is_multigraph() - H.is_directed()
662
+ assert len(H.edges()) == num_ed + 1
663
+ assert len(H.edges) == num_ed + 1
664
+
665
+ def test_and(self):
666
+ ev = self.eview(self.G)
667
+ some_edges = {(0, 1), (1, 0), (0, 2)}
668
+ if self.G.is_directed():
669
+ assert some_edges & ev, {(0, 1)}
670
+ assert ev & some_edges, {(0, 1)}
671
+ else:
672
+ assert ev & some_edges == {(0, 1), (1, 0)}
673
+ assert some_edges & ev == {(0, 1), (1, 0)}
674
+ return
675
+
676
+ def test_or(self):
677
+ ev = self.eview(self.G)
678
+ some_edges = {(0, 1), (1, 0), (0, 2)}
679
+ result1 = {(n, n + 1) for n in range(8)}
680
+ result1.update(some_edges)
681
+ result2 = {(n + 1, n) for n in range(8)}
682
+ result2.update(some_edges)
683
+ assert (ev | some_edges) in (result1, result2)
684
+ assert (some_edges | ev) in (result1, result2)
685
+
686
+ def test_xor(self):
687
+ ev = self.eview(self.G)
688
+ some_edges = {(0, 1), (1, 0), (0, 2)}
689
+ if self.G.is_directed():
690
+ result = {(n, n + 1) for n in range(1, 8)}
691
+ result.update({(1, 0), (0, 2)})
692
+ assert ev ^ some_edges == result
693
+ else:
694
+ result = {(n, n + 1) for n in range(1, 8)}
695
+ result.update({(0, 2)})
696
+ assert ev ^ some_edges == result
697
+ return
698
+
699
+ def test_sub(self):
700
+ ev = self.eview(self.G)
701
+ some_edges = {(0, 1), (1, 0), (0, 2)}
702
+ result = {(n, n + 1) for n in range(8)}
703
+ result.remove((0, 1))
704
+ assert ev - some_edges, result
705
+
706
+
707
+ class TestOutEdgeView(TestEdgeView):
708
+ @classmethod
709
+ def setup_class(cls):
710
+ cls.G = nx.path_graph(9, nx.DiGraph())
711
+ cls.eview = nx.reportviews.OutEdgeView
712
+
713
+ def test_repr(self):
714
+ ev = self.eview(self.G)
715
+ rep = (
716
+ "OutEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
717
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
718
+ )
719
+ assert repr(ev) == rep
720
+
721
+ def test_contains_with_nbunch(self):
722
+ ev = self.eview(self.G)
723
+ evn = ev(nbunch=[0, 2])
724
+ assert (0, 1) in evn
725
+ assert (1, 2) not in evn
726
+ assert (2, 3) in evn
727
+ assert (3, 4) not in evn
728
+ assert (4, 5) not in evn
729
+ assert (5, 6) not in evn
730
+ assert (7, 8) not in evn
731
+ assert (8, 9) not in evn
732
+
733
+
734
+ class TestInEdgeView(TestEdgeView):
735
+ @classmethod
736
+ def setup_class(cls):
737
+ cls.G = nx.path_graph(9, nx.DiGraph())
738
+ cls.eview = nx.reportviews.InEdgeView
739
+
740
+ def test_repr(self):
741
+ ev = self.eview(self.G)
742
+ rep = (
743
+ "InEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
744
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
745
+ )
746
+ assert repr(ev) == rep
747
+
748
+ def test_contains_with_nbunch(self):
749
+ ev = self.eview(self.G)
750
+ evn = ev(nbunch=[0, 2])
751
+ assert (0, 1) not in evn
752
+ assert (1, 2) in evn
753
+ assert (2, 3) not in evn
754
+ assert (3, 4) not in evn
755
+ assert (4, 5) not in evn
756
+ assert (5, 6) not in evn
757
+ assert (7, 8) not in evn
758
+ assert (8, 9) not in evn
759
+
760
+
761
+ class TestMultiEdgeView(TestEdgeView):
762
+ @classmethod
763
+ def setup_class(cls):
764
+ cls.G = nx.path_graph(9, nx.MultiGraph())
765
+ cls.G.add_edge(1, 2, key=3, foo="bar")
766
+ cls.eview = nx.reportviews.MultiEdgeView
767
+
768
+ def modify_edge(self, G, e, **kwds):
769
+ if len(e) == 2:
770
+ e = e + (0,)
771
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
772
+
773
+ def test_str(self):
774
+ ev = self.eview(self.G)
775
+ replist = [(n, n + 1, 0) for n in range(8)]
776
+ replist.insert(2, (1, 2, 3))
777
+ rep = str(replist)
778
+ assert str(ev) == rep
779
+
780
+ def test_getitem(self):
781
+ G = self.G.copy()
782
+ ev = G.edges
783
+ G.edges[0, 1, 0]["foo"] = "bar"
784
+ assert ev[0, 1, 0] == {"foo": "bar"}
785
+
786
+ # slicing
787
+ with pytest.raises(nx.NetworkXError):
788
+ G.edges[0:5]
789
+
790
+ # Missing edge
791
+ with pytest.raises(KeyError, match=r".*edge.*is not in the graph"):
792
+ G.edges[42, 42, 42]
793
+
794
+ def test_repr(self):
795
+ ev = self.eview(self.G)
796
+ rep = (
797
+ "MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
798
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
799
+ )
800
+ assert repr(ev) == rep
801
+
802
+ def test_call(self):
803
+ ev = self.eview(self.G)
804
+ assert id(ev) == id(ev(keys=True))
805
+ assert id(ev) == id(ev(data=False, keys=True))
806
+ assert id(ev) != id(ev(keys=False))
807
+ assert id(ev) != id(ev(data=True))
808
+ assert id(ev) != id(ev(nbunch=1))
809
+
810
+ def test_data(self):
811
+ ev = self.eview(self.G)
812
+ assert id(ev) != id(ev.data())
813
+ assert id(ev) == id(ev.data(data=False, keys=True))
814
+ assert id(ev) != id(ev.data(keys=False))
815
+ assert id(ev) != id(ev.data(data=True))
816
+ assert id(ev) != id(ev.data(nbunch=1))
817
+
818
+ def test_iter(self):
819
+ ev = self.eview(self.G)
820
+ for u, v, k in ev:
821
+ pass
822
+ iev = iter(ev)
823
+ assert next(iev) == (0, 1, 0)
824
+ assert iter(ev) != ev
825
+ assert iter(iev) == iev
826
+
827
+ def test_iterkeys(self):
828
+ G = self.G
829
+ evr = self.eview(G)
830
+ ev = evr(keys=True)
831
+ for u, v, k in ev:
832
+ pass
833
+ assert k == 0
834
+ ev = evr(keys=True, data="foo", default=1)
835
+ for u, v, k, wt in ev:
836
+ pass
837
+ assert wt == 1
838
+
839
+ self.modify_edge(G, (2, 3, 0), foo="bar")
840
+ ev = evr(keys=True, data=True)
841
+ for e in ev:
842
+ assert len(e) == 4
843
+ if set(e[:2]) == {2, 3}:
844
+ assert e[2] == 0
845
+ assert e[3] == {"foo": "bar"}
846
+ checked = True
847
+ elif set(e[:3]) == {1, 2, 3}:
848
+ assert e[2] == 3
849
+ assert e[3] == {"foo": "bar"}
850
+ checked_multi = True
851
+ else:
852
+ assert e[2] == 0
853
+ assert e[3] == {}
854
+ assert checked
855
+ assert checked_multi
856
+ ev = evr(keys=True, data="foo", default=1)
857
+ for e in ev:
858
+ if set(e[:2]) == {1, 2} and e[2] == 3:
859
+ assert e[3] == "bar"
860
+ if set(e[:2]) == {1, 2} and e[2] == 0:
861
+ assert e[3] == 1
862
+ if set(e[:2]) == {2, 3}:
863
+ assert e[2] == 0
864
+ assert e[3] == "bar"
865
+ assert len(e) == 4
866
+ checked_wt = True
867
+ assert checked_wt
868
+ ev = evr(keys=True)
869
+ for e in ev:
870
+ assert len(e) == 3
871
+ elist = sorted([(i, i + 1, 0) for i in range(8)] + [(1, 2, 3)])
872
+ assert sorted(ev) == elist
873
+ # test that the keyword arguments are passed correctly
874
+ ev = evr((1, 2), "foo", keys=True, default=1)
875
+ with pytest.raises(TypeError):
876
+ evr((1, 2), "foo", True, 1)
877
+ with pytest.raises(TypeError):
878
+ evr((1, 2), "foo", True, default=1)
879
+ for e in ev:
880
+ if set(e[:2]) == {1, 2}:
881
+ assert e[2] in {0, 3}
882
+ if e[2] == 3:
883
+ assert e[3] == "bar"
884
+ else: # e[2] == 0
885
+ assert e[3] == 1
886
+ if G.is_directed():
887
+ assert len(list(ev)) == 3
888
+ else:
889
+ assert len(list(ev)) == 4
890
+
891
+ def test_or(self):
892
+ ev = self.eview(self.G)
893
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
894
+ result = {(n, n + 1, 0) for n in range(8)}
895
+ result.update(some_edges)
896
+ result.update({(1, 2, 3)})
897
+ assert ev | some_edges == result
898
+ assert some_edges | ev == result
899
+
900
+ def test_sub(self):
901
+ ev = self.eview(self.G)
902
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
903
+ result = {(n, n + 1, 0) for n in range(8)}
904
+ result.remove((0, 1, 0))
905
+ result.update({(1, 2, 3)})
906
+ assert ev - some_edges, result
907
+ assert some_edges - ev, result
908
+
909
+ def test_xor(self):
910
+ ev = self.eview(self.G)
911
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
912
+ if self.G.is_directed():
913
+ result = {(n, n + 1, 0) for n in range(1, 8)}
914
+ result.update({(1, 0, 0), (0, 2, 0), (1, 2, 3)})
915
+ assert ev ^ some_edges == result
916
+ assert some_edges ^ ev == result
917
+ else:
918
+ result = {(n, n + 1, 0) for n in range(1, 8)}
919
+ result.update({(0, 2, 0), (1, 2, 3)})
920
+ assert ev ^ some_edges == result
921
+ assert some_edges ^ ev == result
922
+
923
+ def test_and(self):
924
+ ev = self.eview(self.G)
925
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
926
+ if self.G.is_directed():
927
+ assert ev & some_edges == {(0, 1, 0)}
928
+ assert some_edges & ev == {(0, 1, 0)}
929
+ else:
930
+ assert ev & some_edges == {(0, 1, 0), (1, 0, 0)}
931
+ assert some_edges & ev == {(0, 1, 0), (1, 0, 0)}
932
+
933
+ def test_contains_with_nbunch(self):
934
+ ev = self.eview(self.G)
935
+ evn = ev(nbunch=[0, 2])
936
+ assert (0, 1) in evn
937
+ assert (1, 2) in evn
938
+ assert (2, 3) in evn
939
+ assert (3, 4) not in evn
940
+ assert (4, 5) not in evn
941
+ assert (5, 6) not in evn
942
+ assert (7, 8) not in evn
943
+ assert (8, 9) not in evn
944
+
945
+
946
+ class TestOutMultiEdgeView(TestMultiEdgeView):
947
+ @classmethod
948
+ def setup_class(cls):
949
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
950
+ cls.G.add_edge(1, 2, key=3, foo="bar")
951
+ cls.eview = nx.reportviews.OutMultiEdgeView
952
+
953
+ def modify_edge(self, G, e, **kwds):
954
+ if len(e) == 2:
955
+ e = e + (0,)
956
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
957
+
958
+ def test_repr(self):
959
+ ev = self.eview(self.G)
960
+ rep = (
961
+ "OutMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0),"
962
+ + " (3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
963
+ )
964
+ assert repr(ev) == rep
965
+
966
+ def test_contains_with_nbunch(self):
967
+ ev = self.eview(self.G)
968
+ evn = ev(nbunch=[0, 2])
969
+ assert (0, 1) in evn
970
+ assert (1, 2) not in evn
971
+ assert (2, 3) in evn
972
+ assert (3, 4) not in evn
973
+ assert (4, 5) not in evn
974
+ assert (5, 6) not in evn
975
+ assert (7, 8) not in evn
976
+ assert (8, 9) not in evn
977
+
978
+
979
+ class TestInMultiEdgeView(TestMultiEdgeView):
980
+ @classmethod
981
+ def setup_class(cls):
982
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
983
+ cls.G.add_edge(1, 2, key=3, foo="bar")
984
+ cls.eview = nx.reportviews.InMultiEdgeView
985
+
986
+ def modify_edge(self, G, e, **kwds):
987
+ if len(e) == 2:
988
+ e = e + (0,)
989
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
990
+
991
+ def test_repr(self):
992
+ ev = self.eview(self.G)
993
+ rep = (
994
+ "InMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
995
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
996
+ )
997
+ assert repr(ev) == rep
998
+
999
+ def test_contains_with_nbunch(self):
1000
+ ev = self.eview(self.G)
1001
+ evn = ev(nbunch=[0, 2])
1002
+ assert (0, 1) not in evn
1003
+ assert (1, 2) in evn
1004
+ assert (2, 3) not in evn
1005
+ assert (3, 4) not in evn
1006
+ assert (4, 5) not in evn
1007
+ assert (5, 6) not in evn
1008
+ assert (7, 8) not in evn
1009
+ assert (8, 9) not in evn
1010
+
1011
+
1012
+ # Degrees
1013
+ class TestDegreeView:
1014
+ GRAPH = nx.Graph
1015
+ dview = nx.reportviews.DegreeView
1016
+
1017
+ @classmethod
1018
+ def setup_class(cls):
1019
+ cls.G = nx.path_graph(6, cls.GRAPH())
1020
+ cls.G.add_edge(1, 3, foo=2)
1021
+ cls.G.add_edge(1, 3, foo=3)
1022
+
1023
+ def test_pickle(self):
1024
+ import pickle
1025
+
1026
+ deg = self.G.degree
1027
+ pdeg = pickle.loads(pickle.dumps(deg, -1))
1028
+ assert dict(deg) == dict(pdeg)
1029
+
1030
+ def test_str(self):
1031
+ dv = self.dview(self.G)
1032
+ rep = str([(0, 1), (1, 3), (2, 2), (3, 3), (4, 2), (5, 1)])
1033
+ assert str(dv) == rep
1034
+ dv = self.G.degree()
1035
+ assert str(dv) == rep
1036
+
1037
+ def test_repr(self):
1038
+ dv = self.dview(self.G)
1039
+ rep = "DegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1040
+ assert repr(dv) == rep
1041
+
1042
+ def test_iter(self):
1043
+ dv = self.dview(self.G)
1044
+ for n, d in dv:
1045
+ pass
1046
+ idv = iter(dv)
1047
+ assert iter(dv) != dv
1048
+ assert iter(idv) == idv
1049
+ assert next(idv) == (0, dv[0])
1050
+ assert next(idv) == (1, dv[1])
1051
+ # weighted
1052
+ dv = self.dview(self.G, weight="foo")
1053
+ for n, d in dv:
1054
+ pass
1055
+ idv = iter(dv)
1056
+ assert iter(dv) != dv
1057
+ assert iter(idv) == idv
1058
+ assert next(idv) == (0, dv[0])
1059
+ assert next(idv) == (1, dv[1])
1060
+
1061
+ def test_nbunch(self):
1062
+ dv = self.dview(self.G)
1063
+ dvn = dv(0)
1064
+ assert dvn == 1
1065
+ dvn = dv([2, 3])
1066
+ assert sorted(dvn) == [(2, 2), (3, 3)]
1067
+
1068
+ def test_getitem(self):
1069
+ dv = self.dview(self.G)
1070
+ assert dv[0] == 1
1071
+ assert dv[1] == 3
1072
+ assert dv[2] == 2
1073
+ assert dv[3] == 3
1074
+ dv = self.dview(self.G, weight="foo")
1075
+ assert dv[0] == 1
1076
+ assert dv[1] == 5
1077
+ assert dv[2] == 2
1078
+ assert dv[3] == 5
1079
+
1080
+ def test_weight(self):
1081
+ dv = self.dview(self.G)
1082
+ dvw = dv(0, weight="foo")
1083
+ assert dvw == 1
1084
+ dvw = dv(1, weight="foo")
1085
+ assert dvw == 5
1086
+ dvw = dv([2, 3], weight="foo")
1087
+ assert sorted(dvw) == [(2, 2), (3, 5)]
1088
+ dvd = dict(dv(weight="foo"))
1089
+ assert dvd[0] == 1
1090
+ assert dvd[1] == 5
1091
+ assert dvd[2] == 2
1092
+ assert dvd[3] == 5
1093
+
1094
+ def test_len(self):
1095
+ dv = self.dview(self.G)
1096
+ assert len(dv) == 6
1097
+
1098
+
1099
+ class TestDiDegreeView(TestDegreeView):
1100
+ GRAPH = nx.DiGraph
1101
+ dview = nx.reportviews.DiDegreeView
1102
+
1103
+ def test_repr(self):
1104
+ dv = self.G.degree()
1105
+ rep = "DiDegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1106
+ assert repr(dv) == rep
1107
+
1108
+
1109
+ class TestOutDegreeView(TestDegreeView):
1110
+ GRAPH = nx.DiGraph
1111
+ dview = nx.reportviews.OutDegreeView
1112
+
1113
+ def test_str(self):
1114
+ dv = self.dview(self.G)
1115
+ rep = str([(0, 1), (1, 2), (2, 1), (3, 1), (4, 1), (5, 0)])
1116
+ assert str(dv) == rep
1117
+ dv = self.G.out_degree()
1118
+ assert str(dv) == rep
1119
+
1120
+ def test_repr(self):
1121
+ dv = self.G.out_degree()
1122
+ rep = "OutDegreeView({0: 1, 1: 2, 2: 1, 3: 1, 4: 1, 5: 0})"
1123
+ assert repr(dv) == rep
1124
+
1125
+ def test_nbunch(self):
1126
+ dv = self.dview(self.G)
1127
+ dvn = dv(0)
1128
+ assert dvn == 1
1129
+ dvn = dv([2, 3])
1130
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1131
+
1132
+ def test_getitem(self):
1133
+ dv = self.dview(self.G)
1134
+ assert dv[0] == 1
1135
+ assert dv[1] == 2
1136
+ assert dv[2] == 1
1137
+ assert dv[3] == 1
1138
+ dv = self.dview(self.G, weight="foo")
1139
+ assert dv[0] == 1
1140
+ assert dv[1] == 4
1141
+ assert dv[2] == 1
1142
+ assert dv[3] == 1
1143
+
1144
+ def test_weight(self):
1145
+ dv = self.dview(self.G)
1146
+ dvw = dv(0, weight="foo")
1147
+ assert dvw == 1
1148
+ dvw = dv(1, weight="foo")
1149
+ assert dvw == 4
1150
+ dvw = dv([2, 3], weight="foo")
1151
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1152
+ dvd = dict(dv(weight="foo"))
1153
+ assert dvd[0] == 1
1154
+ assert dvd[1] == 4
1155
+ assert dvd[2] == 1
1156
+ assert dvd[3] == 1
1157
+
1158
+
1159
+ class TestInDegreeView(TestDegreeView):
1160
+ GRAPH = nx.DiGraph
1161
+ dview = nx.reportviews.InDegreeView
1162
+
1163
+ def test_str(self):
1164
+ dv = self.dview(self.G)
1165
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 2), (4, 1), (5, 1)])
1166
+ assert str(dv) == rep
1167
+ dv = self.G.in_degree()
1168
+ assert str(dv) == rep
1169
+
1170
+ def test_repr(self):
1171
+ dv = self.G.in_degree()
1172
+ rep = "InDegreeView({0: 0, 1: 1, 2: 1, 3: 2, 4: 1, 5: 1})"
1173
+ assert repr(dv) == rep
1174
+
1175
+ def test_nbunch(self):
1176
+ dv = self.dview(self.G)
1177
+ dvn = dv(0)
1178
+ assert dvn == 0
1179
+ dvn = dv([2, 3])
1180
+ assert sorted(dvn) == [(2, 1), (3, 2)]
1181
+
1182
+ def test_getitem(self):
1183
+ dv = self.dview(self.G)
1184
+ assert dv[0] == 0
1185
+ assert dv[1] == 1
1186
+ assert dv[2] == 1
1187
+ assert dv[3] == 2
1188
+ dv = self.dview(self.G, weight="foo")
1189
+ assert dv[0] == 0
1190
+ assert dv[1] == 1
1191
+ assert dv[2] == 1
1192
+ assert dv[3] == 4
1193
+
1194
+ def test_weight(self):
1195
+ dv = self.dview(self.G)
1196
+ dvw = dv(0, weight="foo")
1197
+ assert dvw == 0
1198
+ dvw = dv(1, weight="foo")
1199
+ assert dvw == 1
1200
+ dvw = dv([2, 3], weight="foo")
1201
+ assert sorted(dvw) == [(2, 1), (3, 4)]
1202
+ dvd = dict(dv(weight="foo"))
1203
+ assert dvd[0] == 0
1204
+ assert dvd[1] == 1
1205
+ assert dvd[2] == 1
1206
+ assert dvd[3] == 4
1207
+
1208
+
1209
+ class TestMultiDegreeView(TestDegreeView):
1210
+ GRAPH = nx.MultiGraph
1211
+ dview = nx.reportviews.MultiDegreeView
1212
+
1213
+ def test_str(self):
1214
+ dv = self.dview(self.G)
1215
+ rep = str([(0, 1), (1, 4), (2, 2), (3, 4), (4, 2), (5, 1)])
1216
+ assert str(dv) == rep
1217
+ dv = self.G.degree()
1218
+ assert str(dv) == rep
1219
+
1220
+ def test_repr(self):
1221
+ dv = self.G.degree()
1222
+ rep = "MultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1223
+ assert repr(dv) == rep
1224
+
1225
+ def test_nbunch(self):
1226
+ dv = self.dview(self.G)
1227
+ dvn = dv(0)
1228
+ assert dvn == 1
1229
+ dvn = dv([2, 3])
1230
+ assert sorted(dvn) == [(2, 2), (3, 4)]
1231
+
1232
+ def test_getitem(self):
1233
+ dv = self.dview(self.G)
1234
+ assert dv[0] == 1
1235
+ assert dv[1] == 4
1236
+ assert dv[2] == 2
1237
+ assert dv[3] == 4
1238
+ dv = self.dview(self.G, weight="foo")
1239
+ assert dv[0] == 1
1240
+ assert dv[1] == 7
1241
+ assert dv[2] == 2
1242
+ assert dv[3] == 7
1243
+
1244
+ def test_weight(self):
1245
+ dv = self.dview(self.G)
1246
+ dvw = dv(0, weight="foo")
1247
+ assert dvw == 1
1248
+ dvw = dv(1, weight="foo")
1249
+ assert dvw == 7
1250
+ dvw = dv([2, 3], weight="foo")
1251
+ assert sorted(dvw) == [(2, 2), (3, 7)]
1252
+ dvd = dict(dv(weight="foo"))
1253
+ assert dvd[0] == 1
1254
+ assert dvd[1] == 7
1255
+ assert dvd[2] == 2
1256
+ assert dvd[3] == 7
1257
+
1258
+
1259
+ class TestDiMultiDegreeView(TestMultiDegreeView):
1260
+ GRAPH = nx.MultiDiGraph
1261
+ dview = nx.reportviews.DiMultiDegreeView
1262
+
1263
+ def test_repr(self):
1264
+ dv = self.G.degree()
1265
+ rep = "DiMultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1266
+ assert repr(dv) == rep
1267
+
1268
+
1269
+ class TestOutMultiDegreeView(TestDegreeView):
1270
+ GRAPH = nx.MultiDiGraph
1271
+ dview = nx.reportviews.OutMultiDegreeView
1272
+
1273
+ def test_str(self):
1274
+ dv = self.dview(self.G)
1275
+ rep = str([(0, 1), (1, 3), (2, 1), (3, 1), (4, 1), (5, 0)])
1276
+ assert str(dv) == rep
1277
+ dv = self.G.out_degree()
1278
+ assert str(dv) == rep
1279
+
1280
+ def test_repr(self):
1281
+ dv = self.G.out_degree()
1282
+ rep = "OutMultiDegreeView({0: 1, 1: 3, 2: 1, 3: 1, 4: 1, 5: 0})"
1283
+ assert repr(dv) == rep
1284
+
1285
+ def test_nbunch(self):
1286
+ dv = self.dview(self.G)
1287
+ dvn = dv(0)
1288
+ assert dvn == 1
1289
+ dvn = dv([2, 3])
1290
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1291
+
1292
+ def test_getitem(self):
1293
+ dv = self.dview(self.G)
1294
+ assert dv[0] == 1
1295
+ assert dv[1] == 3
1296
+ assert dv[2] == 1
1297
+ assert dv[3] == 1
1298
+ dv = self.dview(self.G, weight="foo")
1299
+ assert dv[0] == 1
1300
+ assert dv[1] == 6
1301
+ assert dv[2] == 1
1302
+ assert dv[3] == 1
1303
+
1304
+ def test_weight(self):
1305
+ dv = self.dview(self.G)
1306
+ dvw = dv(0, weight="foo")
1307
+ assert dvw == 1
1308
+ dvw = dv(1, weight="foo")
1309
+ assert dvw == 6
1310
+ dvw = dv([2, 3], weight="foo")
1311
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1312
+ dvd = dict(dv(weight="foo"))
1313
+ assert dvd[0] == 1
1314
+ assert dvd[1] == 6
1315
+ assert dvd[2] == 1
1316
+ assert dvd[3] == 1
1317
+
1318
+
1319
+ class TestInMultiDegreeView(TestDegreeView):
1320
+ GRAPH = nx.MultiDiGraph
1321
+ dview = nx.reportviews.InMultiDegreeView
1322
+
1323
+ def test_str(self):
1324
+ dv = self.dview(self.G)
1325
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 3), (4, 1), (5, 1)])
1326
+ assert str(dv) == rep
1327
+ dv = self.G.in_degree()
1328
+ assert str(dv) == rep
1329
+
1330
+ def test_repr(self):
1331
+ dv = self.G.in_degree()
1332
+ rep = "InMultiDegreeView({0: 0, 1: 1, 2: 1, 3: 3, 4: 1, 5: 1})"
1333
+ assert repr(dv) == rep
1334
+
1335
+ def test_nbunch(self):
1336
+ dv = self.dview(self.G)
1337
+ dvn = dv(0)
1338
+ assert dvn == 0
1339
+ dvn = dv([2, 3])
1340
+ assert sorted(dvn) == [(2, 1), (3, 3)]
1341
+
1342
+ def test_getitem(self):
1343
+ dv = self.dview(self.G)
1344
+ assert dv[0] == 0
1345
+ assert dv[1] == 1
1346
+ assert dv[2] == 1
1347
+ assert dv[3] == 3
1348
+ dv = self.dview(self.G, weight="foo")
1349
+ assert dv[0] == 0
1350
+ assert dv[1] == 1
1351
+ assert dv[2] == 1
1352
+ assert dv[3] == 6
1353
+
1354
+ def test_weight(self):
1355
+ dv = self.dview(self.G)
1356
+ dvw = dv(0, weight="foo")
1357
+ assert dvw == 0
1358
+ dvw = dv(1, weight="foo")
1359
+ assert dvw == 1
1360
+ dvw = dv([2, 3], weight="foo")
1361
+ assert sorted(dvw) == [(2, 1), (3, 6)]
1362
+ dvd = dict(dv(weight="foo"))
1363
+ assert dvd[0] == 0
1364
+ assert dvd[1] == 1
1365
+ assert dvd[2] == 1
1366
+ assert dvd[3] == 6
1367
+
1368
+
1369
+ @pytest.mark.parametrize(
1370
+ ("reportview", "err_msg_terms"),
1371
+ (
1372
+ (rv.NodeView, "list(G.nodes"),
1373
+ (rv.NodeDataView, "list(G.nodes.data"),
1374
+ (rv.EdgeView, "list(G.edges"),
1375
+ # Directed EdgeViews
1376
+ (rv.InEdgeView, "list(G.in_edges"),
1377
+ (rv.OutEdgeView, "list(G.edges"),
1378
+ # Multi EdgeViews
1379
+ (rv.MultiEdgeView, "list(G.edges"),
1380
+ (rv.InMultiEdgeView, "list(G.in_edges"),
1381
+ (rv.OutMultiEdgeView, "list(G.edges"),
1382
+ ),
1383
+ )
1384
+ def test_slicing_reportviews(reportview, err_msg_terms):
1385
+ G = nx.complete_graph(3)
1386
+ view = reportview(G)
1387
+ with pytest.raises(nx.NetworkXError) as exc:
1388
+ view[0:2]
1389
+ errmsg = str(exc.value)
1390
+ assert type(view).__name__ in errmsg
1391
+ assert err_msg_terms in errmsg
1392
+
1393
+
1394
+ @pytest.mark.parametrize(
1395
+ "graph", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
1396
+ )
1397
+ def test_cache_dict_get_set_state(graph):
1398
+ G = nx.path_graph(5, graph())
1399
+ G.nodes, G.edges, G.adj, G.degree
1400
+ if G.is_directed():
1401
+ G.pred, G.succ, G.in_edges, G.out_edges, G.in_degree, G.out_degree
1402
+ cached_dict = G.__dict__
1403
+ assert "nodes" in cached_dict
1404
+ assert "edges" in cached_dict
1405
+ assert "adj" in cached_dict
1406
+ assert "degree" in cached_dict
1407
+ if G.is_directed():
1408
+ assert "pred" in cached_dict
1409
+ assert "succ" in cached_dict
1410
+ assert "in_edges" in cached_dict
1411
+ assert "out_edges" in cached_dict
1412
+ assert "in_degree" in cached_dict
1413
+ assert "out_degree" in cached_dict
1414
+
1415
+ # Raises error if the cached properties and views do not work
1416
+ pickle.loads(pickle.dumps(G, -1))
1417
+ deepcopy(G)
1418
+
1419
+
1420
+ @pytest.mark.parametrize(
1421
+ "graph_class", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
1422
+ )
1423
+ def test_unpickled_views_are_callable(graph_class):
1424
+ # Views hold their graph weakly. An unpickled view, or a view of a graph
1425
+ # that no longer exists, must still answer nbunch/weight calls and pickle.
1426
+ G = graph_class([(0, 1), (1, 2)])
1427
+ ev = pickle.loads(pickle.dumps(G.edges, -1))
1428
+ assert list(ev([1])) == list(G.edges([1]))
1429
+ assert list(ev.data("w", nbunch=[1])) == list(G.edges.data("w", nbunch=[1]))
1430
+ dv = pickle.loads(pickle.dumps(G.degree, -1))
1431
+ assert dict(dv(weight="w")) == dict(G.degree(weight="w"))
1432
+ assert dv(1) == G.degree(1)
1433
+ # the graph is a temporary here: gone before pickling even starts
1434
+ ev = pickle.loads(pickle.dumps(graph_class([(0, 1), (1, 2)]).edges, -1))
1435
+ assert list(ev([1])) == list(G.edges([1]))
1436
+ pickle.dumps(ev, -1)
1437
+
1438
+
1439
+ def test_edge_views_inherit_from_EdgeViewABC():
1440
+ all_edge_view_classes = (v for v in dir(nx.reportviews) if "Edge" in v)
1441
+ for eview_class in all_edge_view_classes:
1442
+ assert issubclass(
1443
+ getattr(nx.reportviews, eview_class), nx.reportviews.EdgeViewABC
1444
+ )
venv/lib/python3.14/site-packages/networkx/classes/tests/test_special.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ from .test_digraph import BaseDiGraphTester
4
+ from .test_digraph import TestDiGraph as _TestDiGraph
5
+ from .test_graph import BaseGraphTester
6
+ from .test_graph import TestGraph as _TestGraph
7
+ from .test_multidigraph import TestMultiDiGraph as _TestMultiDiGraph
8
+ from .test_multigraph import TestMultiGraph as _TestMultiGraph
9
+
10
+
11
+ def test_factories():
12
+ class mydict1(dict):
13
+ pass
14
+
15
+ class mydict2(dict):
16
+ pass
17
+
18
+ class mydict3(dict):
19
+ pass
20
+
21
+ class mydict4(dict):
22
+ pass
23
+
24
+ class mydict5(dict):
25
+ pass
26
+
27
+ for Graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):
28
+
29
+ class MyGraph(Graph):
30
+ node_dict_factory = mydict1
31
+ adjlist_outer_dict_factory = mydict2
32
+ adjlist_inner_dict_factory = mydict3
33
+ edge_key_dict_factory = mydict4
34
+ edge_attr_dict_factory = mydict5
35
+
36
+ G = MyGraph()
37
+ assert isinstance(G._node, mydict1)
38
+ assert isinstance(G._adj, mydict2)
39
+ G.add_node(1)
40
+ assert isinstance(G._adj[1], mydict3)
41
+ if G.is_directed():
42
+ assert isinstance(G._pred, mydict2)
43
+ assert isinstance(G._succ, mydict2)
44
+ assert isinstance(G._pred[1], mydict3)
45
+ G.add_edge(1, 2)
46
+ if G.is_multigraph():
47
+ assert isinstance(G._adj[1][2], mydict4)
48
+ assert isinstance(G._adj[1][2][0], mydict5)
49
+ else:
50
+ assert isinstance(G._adj[1][2], mydict5)
51
+
52
+
53
+ class TestSpecialGraph(_TestGraph):
54
+ def setup_method(self):
55
+ _TestGraph.setup_method(self)
56
+ self.Graph = nx.Graph
57
+
58
+
59
+ class TestThinGraph(BaseGraphTester):
60
+ def setup_method(self):
61
+ all_edge_dict = {"weight": 1}
62
+
63
+ class MyGraph(nx.Graph):
64
+ def edge_attr_dict_factory(self):
65
+ return all_edge_dict
66
+
67
+ self.Graph = MyGraph
68
+ # build dict-of-dict-of-dict K3
69
+ ed1, ed2, ed3 = (all_edge_dict, all_edge_dict, all_edge_dict)
70
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
71
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
72
+ self.k3nodes = [0, 1, 2]
73
+ self.K3 = self.Graph()
74
+ self.K3._adj = self.k3adj
75
+ self.K3._node = {}
76
+ self.K3._node[0] = {}
77
+ self.K3._node[1] = {}
78
+ self.K3._node[2] = {}
79
+
80
+
81
+ class TestSpecialDiGraph(_TestDiGraph):
82
+ def setup_method(self):
83
+ _TestDiGraph.setup_method(self)
84
+ self.Graph = nx.DiGraph
85
+
86
+
87
+ class TestThinDiGraph(BaseDiGraphTester):
88
+ def setup_method(self):
89
+ all_edge_dict = {"weight": 1}
90
+
91
+ class MyGraph(nx.DiGraph):
92
+ def edge_attr_dict_factory(self):
93
+ return all_edge_dict
94
+
95
+ self.Graph = MyGraph
96
+ # build dict-of-dict-of-dict K3
97
+ ed1, ed2, ed3 = (all_edge_dict, all_edge_dict, all_edge_dict)
98
+ ed4, ed5, ed6 = (all_edge_dict, all_edge_dict, all_edge_dict)
99
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
100
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
101
+ self.k3nodes = [0, 1, 2]
102
+ self.K3 = self.Graph()
103
+ self.K3._succ = self.k3adj
104
+ # K3._adj is synced with K3._succ
105
+ self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
106
+ self.K3._node = {}
107
+ self.K3._node[0] = {}
108
+ self.K3._node[1] = {}
109
+ self.K3._node[2] = {}
110
+
111
+ ed1, ed2 = (all_edge_dict, all_edge_dict)
112
+ self.P3 = self.Graph()
113
+ self.P3._succ = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
114
+ # P3._adj is synced with P3._succ
115
+ self.P3._pred = {0: {}, 1: {0: ed1}, 2: {1: ed2}}
116
+ self.P3._node = {}
117
+ self.P3._node[0] = {}
118
+ self.P3._node[1] = {}
119
+ self.P3._node[2] = {}
120
+
121
+
122
+ class TestSpecialMultiGraph(_TestMultiGraph):
123
+ def setup_method(self):
124
+ _TestMultiGraph.setup_method(self)
125
+ self.Graph = nx.MultiGraph
126
+
127
+
128
+ class TestSpecialMultiDiGraph(_TestMultiDiGraph):
129
+ def setup_method(self):
130
+ _TestMultiDiGraph.setup_method(self)
131
+ self.Graph = nx.MultiDiGraph
venv/lib/python3.14/site-packages/networkx/classes/tests/test_subgraphviews.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ class TestSubGraphView:
8
+ gview = staticmethod(nx.subgraph_view)
9
+ graph = nx.Graph
10
+ hide_edges_filter = staticmethod(nx.filters.hide_edges)
11
+ show_edges_filter = staticmethod(nx.filters.show_edges)
12
+
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9, create_using=cls.graph())
16
+ cls.hide_edges_w_hide_nodes = {(3, 4), (4, 5), (5, 6)}
17
+
18
+ def test_hidden_nodes(self):
19
+ hide_nodes = [4, 5, 111]
20
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
21
+ gview = self.gview
22
+ G = gview(self.G, filter_node=nodes_gone)
23
+ assert self.G.nodes - G.nodes == {4, 5}
24
+ assert self.G.edges - G.edges == self.hide_edges_w_hide_nodes
25
+ if G.is_directed():
26
+ assert list(G[3]) == []
27
+ assert list(G[2]) == [3]
28
+ else:
29
+ assert list(G[3]) == [2]
30
+ assert set(G[2]) == {1, 3}
31
+ pytest.raises(KeyError, G.__getitem__, 4)
32
+ pytest.raises(KeyError, G.__getitem__, 112)
33
+ pytest.raises(KeyError, G.__getitem__, 111)
34
+ assert G.degree(3) == (3 if G.is_multigraph() else 1)
35
+ assert G.size() == (7 if G.is_multigraph() else 5)
36
+
37
+ def test_hidden_edges(self):
38
+ hide_edges = [(2, 3), (8, 7), (222, 223)]
39
+ edges_gone = self.hide_edges_filter(hide_edges)
40
+ gview = self.gview
41
+ G = gview(self.G, filter_edge=edges_gone)
42
+ assert self.G.nodes == G.nodes
43
+ if G.is_directed():
44
+ assert self.G.edges - G.edges == {(2, 3)}
45
+ assert list(G[2]) == []
46
+ assert list(G.pred[3]) == []
47
+ assert list(G.pred[2]) == [1]
48
+ assert G.size() == 7
49
+ else:
50
+ assert self.G.edges - G.edges == {(2, 3), (7, 8)}
51
+ assert list(G[2]) == [1]
52
+ assert G.size() == 6
53
+ assert list(G[3]) == [4]
54
+ pytest.raises(KeyError, G.__getitem__, 221)
55
+ pytest.raises(KeyError, G.__getitem__, 222)
56
+ assert G.degree(3) == 1
57
+
58
+ def test_shown_node(self):
59
+ induced_subgraph = nx.filters.show_nodes([2, 3, 111])
60
+ gview = self.gview
61
+ G = gview(self.G, filter_node=induced_subgraph)
62
+ assert set(G.nodes) == {2, 3}
63
+ if G.is_directed():
64
+ assert list(G[3]) == []
65
+ else:
66
+ assert list(G[3]) == [2]
67
+ assert list(G[2]) == [3]
68
+ pytest.raises(KeyError, G.__getitem__, 4)
69
+ pytest.raises(KeyError, G.__getitem__, 112)
70
+ pytest.raises(KeyError, G.__getitem__, 111)
71
+ assert G.degree(3) == (3 if G.is_multigraph() else 1)
72
+ assert G.size() == (3 if G.is_multigraph() else 1)
73
+
74
+ def test_shown_edges(self):
75
+ show_edges = [(2, 3), (8, 7), (222, 223)]
76
+ edge_subgraph = self.show_edges_filter(show_edges)
77
+ G = self.gview(self.G, filter_edge=edge_subgraph)
78
+ assert self.G.nodes == G.nodes
79
+ if G.is_directed():
80
+ assert G.edges == {(2, 3)}
81
+ assert list(G[3]) == []
82
+ assert list(G[2]) == [3]
83
+ assert list(G.pred[3]) == [2]
84
+ assert list(G.pred[2]) == []
85
+ assert G.size() == 1
86
+ else:
87
+ assert G.edges == {(2, 3), (7, 8)}
88
+ assert list(G[3]) == [2]
89
+ assert list(G[2]) == [3]
90
+ assert G.size() == 2
91
+ pytest.raises(KeyError, G.__getitem__, 221)
92
+ pytest.raises(KeyError, G.__getitem__, 222)
93
+ assert G.degree(3) == 1
94
+
95
+
96
+ class TestSubDiGraphView(TestSubGraphView):
97
+ gview = staticmethod(nx.subgraph_view)
98
+ graph = nx.DiGraph
99
+ hide_edges_filter = staticmethod(nx.filters.hide_diedges)
100
+ show_edges_filter = staticmethod(nx.filters.show_diedges)
101
+ hide_edges = [(2, 3), (8, 7), (222, 223)]
102
+ excluded = {(2, 3), (3, 4), (4, 5), (5, 6)}
103
+
104
+ def test_inoutedges(self):
105
+ edges_gone = self.hide_edges_filter(self.hide_edges)
106
+ hide_nodes = [4, 5, 111]
107
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
108
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
109
+
110
+ assert self.G.in_edges - G.in_edges == self.excluded
111
+ assert self.G.out_edges - G.out_edges == self.excluded
112
+
113
+ def test_pred(self):
114
+ edges_gone = self.hide_edges_filter(self.hide_edges)
115
+ hide_nodes = [4, 5, 111]
116
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
117
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
118
+
119
+ assert list(G.pred[2]) == [1]
120
+ assert list(G.pred[6]) == []
121
+
122
+ def test_inout_degree(self):
123
+ edges_gone = self.hide_edges_filter(self.hide_edges)
124
+ hide_nodes = [4, 5, 111]
125
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
126
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
127
+
128
+ assert G.degree(2) == 1
129
+ assert G.out_degree(2) == 0
130
+ assert G.in_degree(2) == 1
131
+ assert G.size() == 4
132
+
133
+
134
+ # multigraph
135
+ class TestMultiGraphView(TestSubGraphView):
136
+ gview = staticmethod(nx.subgraph_view)
137
+ graph = nx.MultiGraph
138
+ hide_edges_filter = staticmethod(nx.filters.hide_multiedges)
139
+ show_edges_filter = staticmethod(nx.filters.show_multiedges)
140
+
141
+ @classmethod
142
+ def setup_class(cls):
143
+ cls.G = nx.path_graph(9, create_using=cls.graph())
144
+ multiedges = {(2, 3, 4), (2, 3, 5)}
145
+ cls.G.add_edges_from(multiedges)
146
+ cls.hide_edges_w_hide_nodes = {(3, 4, 0), (4, 5, 0), (5, 6, 0)}
147
+
148
+ def test_hidden_edges(self):
149
+ hide_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
150
+ edges_gone = self.hide_edges_filter(hide_edges)
151
+ G = self.gview(self.G, filter_edge=edges_gone)
152
+ assert self.G.nodes == G.nodes
153
+ if G.is_directed():
154
+ assert self.G.edges - G.edges == {(2, 3, 4)}
155
+ assert list(G[3]) == [4]
156
+ assert list(G[2]) == [3]
157
+ assert list(G.pred[3]) == [2] # only one 2 but two edges
158
+ assert list(G.pred[2]) == [1]
159
+ assert G.size() == 9
160
+ else:
161
+ assert self.G.edges - G.edges == {(2, 3, 4), (7, 8, 0)}
162
+ assert list(G[3]) == [2, 4]
163
+ assert list(G[2]) == [1, 3]
164
+ assert G.size() == 8
165
+ assert G.degree(3) == 3
166
+ pytest.raises(KeyError, G.__getitem__, 221)
167
+ pytest.raises(KeyError, G.__getitem__, 222)
168
+
169
+ def test_shown_edges(self):
170
+ show_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
171
+ edge_subgraph = self.show_edges_filter(show_edges)
172
+ G = self.gview(self.G, filter_edge=edge_subgraph)
173
+ assert self.G.nodes == G.nodes
174
+ if G.is_directed():
175
+ assert G.edges == {(2, 3, 4)}
176
+ assert list(G[3]) == []
177
+ assert list(G.pred[3]) == [2]
178
+ assert list(G.pred[2]) == []
179
+ assert G.size() == 1
180
+ else:
181
+ assert G.edges == {(2, 3, 4), (7, 8, 0)}
182
+ assert G.size() == 2
183
+ assert list(G[3]) == [2]
184
+ assert G.degree(3) == 1
185
+ assert list(G[2]) == [3]
186
+ pytest.raises(KeyError, G.__getitem__, 221)
187
+ pytest.raises(KeyError, G.__getitem__, 222)
188
+
189
+
190
+ # multidigraph
191
+ class TestMultiDiGraphView(TestMultiGraphView, TestSubDiGraphView):
192
+ gview = staticmethod(nx.subgraph_view)
193
+ graph = nx.MultiDiGraph
194
+ hide_edges_filter = staticmethod(nx.filters.hide_multidiedges)
195
+ show_edges_filter = staticmethod(nx.filters.show_multidiedges)
196
+ hide_edges = [(2, 3, 0), (8, 7, 0), (222, 223, 0)]
197
+ excluded = {(2, 3, 0), (3, 4, 0), (4, 5, 0), (5, 6, 0)}
198
+
199
+ def test_inout_degree(self):
200
+ edges_gone = self.hide_edges_filter(self.hide_edges)
201
+ hide_nodes = [4, 5, 111]
202
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
203
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
204
+
205
+ assert G.degree(2) == 3
206
+ assert G.out_degree(2) == 2
207
+ assert G.in_degree(2) == 1
208
+ assert G.size() == 6
209
+
210
+
211
+ # induced_subgraph
212
+ class TestInducedSubGraph:
213
+ @classmethod
214
+ def setup_class(cls):
215
+ cls.K3 = G = nx.complete_graph(3)
216
+ G.graph["foo"] = []
217
+ G.nodes[0]["foo"] = []
218
+ G.remove_edge(1, 2)
219
+ ll = []
220
+ G.add_edge(1, 2, foo=ll)
221
+ G.add_edge(2, 1, foo=ll)
222
+
223
+ def test_full_graph(self):
224
+ G = self.K3
225
+ H = nx.induced_subgraph(G, [0, 1, 2, 5])
226
+ assert H.name == G.name
227
+ self.graphs_equal(H, G)
228
+ self.same_attrdict(H, G)
229
+
230
+ def test_partial_subgraph(self):
231
+ G = self.K3
232
+ H = nx.induced_subgraph(G, 0)
233
+ assert dict(H.adj) == {0: {}}
234
+ assert dict(G.adj) != {0: {}}
235
+
236
+ H = nx.induced_subgraph(G, [0, 1])
237
+ assert dict(H.adj) == {0: {1: {}}, 1: {0: {}}}
238
+
239
+ def same_attrdict(self, H, G):
240
+ old_foo = H[1][2]["foo"]
241
+ H.edges[1, 2]["foo"] = "baz"
242
+ assert G.edges == H.edges
243
+ H.edges[1, 2]["foo"] = old_foo
244
+ assert G.edges == H.edges
245
+ old_foo = H.nodes[0]["foo"]
246
+ H.nodes[0]["foo"] = "baz"
247
+ assert G.nodes == H.nodes
248
+ H.nodes[0]["foo"] = old_foo
249
+ assert G.nodes == H.nodes
250
+
251
+ def graphs_equal(self, H, G):
252
+ assert G._adj == H._adj
253
+ assert G._node == H._node
254
+ assert G.graph == H.graph
255
+ assert G.name == H.name
256
+ if not G.is_directed() and not H.is_directed():
257
+ assert H._adj[1][2] is H._adj[2][1]
258
+ assert G._adj[1][2] is G._adj[2][1]
259
+ else: # at least one is directed
260
+ if not G.is_directed():
261
+ G._pred = G._adj
262
+ G._succ = G._adj
263
+ if not H.is_directed():
264
+ H._pred = H._adj
265
+ H._succ = H._adj
266
+ assert G._pred == H._pred
267
+ assert G._succ == H._succ
268
+ assert H._succ[1][2] is H._pred[2][1]
269
+ assert G._succ[1][2] is G._pred[2][1]
270
+
271
+
272
+ # edge_subgraph
273
+ class TestEdgeSubGraph:
274
+ @classmethod
275
+ def setup_class(cls):
276
+ # Create a path graph on five nodes.
277
+ cls.G = G = nx.path_graph(5)
278
+ # Add some node, edge, and graph attributes.
279
+ for i in range(5):
280
+ G.nodes[i]["name"] = f"node{i}"
281
+ G.edges[0, 1]["name"] = "edge01"
282
+ G.edges[3, 4]["name"] = "edge34"
283
+ G.graph["name"] = "graph"
284
+ # Get the subgraph induced by the first and last edges.
285
+ cls.H = nx.edge_subgraph(G, [(0, 1), (3, 4)])
286
+
287
+ def test_correct_nodes(self):
288
+ """Tests that the subgraph has the correct nodes."""
289
+ assert [(0, "node0"), (1, "node1"), (3, "node3"), (4, "node4")] == sorted(
290
+ self.H.nodes.data("name")
291
+ )
292
+
293
+ def test_correct_edges(self):
294
+ """Tests that the subgraph has the correct edges."""
295
+ assert edges_equal(
296
+ [(0, 1, "edge01"), (3, 4, "edge34")], self.H.edges.data("name")
297
+ )
298
+
299
+ def test_add_node(self):
300
+ """Tests that adding a node to the original graph does not
301
+ affect the nodes of the subgraph.
302
+
303
+ """
304
+ self.G.add_node(5)
305
+ assert [0, 1, 3, 4] == sorted(self.H.nodes)
306
+ self.G.remove_node(5)
307
+
308
+ def test_remove_node(self):
309
+ """Tests that removing a node in the original graph
310
+ removes the nodes of the subgraph.
311
+
312
+ """
313
+ self.G.remove_node(0)
314
+ assert [1, 3, 4] == sorted(self.H.nodes)
315
+ self.G.add_node(0, name="node0")
316
+ self.G.add_edge(0, 1, name="edge01")
317
+
318
+ def test_node_attr_dict(self):
319
+ """Tests that the node attribute dictionary of the two graphs is
320
+ the same object.
321
+
322
+ """
323
+ for v in self.H:
324
+ assert self.G.nodes[v] == self.H.nodes[v]
325
+ # Making a change to G should make a change in H and vice versa.
326
+ self.G.nodes[0]["name"] = "foo"
327
+ assert self.G.nodes[0] == self.H.nodes[0]
328
+ self.H.nodes[1]["name"] = "bar"
329
+ assert self.G.nodes[1] == self.H.nodes[1]
330
+ # Revert the change, so tests pass with pytest-randomly
331
+ self.G.nodes[0]["name"] = "node0"
332
+ self.H.nodes[1]["name"] = "node1"
333
+
334
+ def test_edge_attr_dict(self):
335
+ """Tests that the edge attribute dictionary of the two graphs is
336
+ the same object.
337
+
338
+ """
339
+ for u, v in self.H.edges():
340
+ assert self.G.edges[u, v] == self.H.edges[u, v]
341
+ # Making a change to G should make a change in H and vice versa.
342
+ self.G.edges[0, 1]["name"] = "foo"
343
+ assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
344
+ self.H.edges[3, 4]["name"] = "bar"
345
+ assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
346
+ # Revert the change, so tests pass with pytest-randomly
347
+ self.G.edges[0, 1]["name"] = "edge01"
348
+ self.H.edges[3, 4]["name"] = "edge34"
349
+
350
+ def test_graph_attr_dict(self):
351
+ """Tests that the graph attribute dictionary of the two graphs
352
+ is the same object.
353
+
354
+ """
355
+ assert self.G.graph is self.H.graph
356
+
357
+ def test_readonly(self):
358
+ """Tests that the subgraph cannot change the graph structure"""
359
+ pytest.raises(nx.NetworkXError, self.H.add_node, 5)
360
+ pytest.raises(nx.NetworkXError, self.H.remove_node, 0)
361
+ pytest.raises(nx.NetworkXError, self.H.add_edge, 5, 6)
362
+ pytest.raises(nx.NetworkXError, self.H.remove_edge, 0, 1)
363
+
364
+ @pytest.mark.parametrize("multigraph", (nx.MultiGraph, nx.MultiDiGraph))
365
+ def test_multigraph_filtered_edges(self, multigraph):
366
+ """Check edge visibility in FilterMultiInner on edge_subgraph's of
367
+ multigraphs. See gh-7724."""
368
+ G = multigraph([("a", "b"), ("a", "c"), ("c", "b")])
369
+ H = nx.edge_subgraph(G, [("a", "b", 0), ("c", "b", 0)])
370
+ assert "c" not in H["a"]
371
+ assert not H.has_edge("a", "c")
venv/lib/python3.14/site-packages/networkx/conftest.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing
3
+ =======
4
+
5
+ General guidelines for writing good tests:
6
+
7
+ - doctests always assume ``import networkx as nx`` so don't add that
8
+ - prefer pytest fixtures over classes with setup methods.
9
+ - use the ``@pytest.mark.parametrize`` decorator
10
+ - use ``pytest.importorskip`` for numpy, scipy, pandas, and matplotlib b/c of PyPy.
11
+ and add the module to the relevant entries below.
12
+
13
+ """
14
+
15
+ import os
16
+ import subprocess
17
+ import warnings
18
+ from importlib.metadata import entry_points
19
+
20
+ import pytest
21
+
22
+ import networkx as nx
23
+
24
+
25
+ def pytest_addoption(parser):
26
+ parser.addoption(
27
+ "--runslow", action="store_true", default=False, help="run slow tests"
28
+ )
29
+ parser.addoption(
30
+ "--backend",
31
+ action="store",
32
+ default=None,
33
+ help="Run tests with a backend by auto-converting nx graphs to backend graphs",
34
+ )
35
+ parser.addoption(
36
+ "--fallback-to-nx",
37
+ action="store_true",
38
+ default=False,
39
+ help="Run nx function if a backend doesn't implement a dispatchable function"
40
+ " (use with --backend)",
41
+ )
42
+
43
+
44
+ def pytest_configure(config):
45
+ config.addinivalue_line("markers", "slow: mark test as slow to run")
46
+ backend = config.getoption("--backend")
47
+ if backend is None:
48
+ backend = os.environ.get("NETWORKX_TEST_BACKEND")
49
+ # nx_loopback backend is only available when testing with a backend
50
+ loopback_ep = entry_points(name="nx_loopback", group="networkx.backends")
51
+ if not loopback_ep:
52
+ warnings.warn(
53
+ "\n\n WARNING: Mixed NetworkX configuration! \n\n"
54
+ " This environment has mixed configuration for networkx.\n"
55
+ " The test object nx_loopback is not configured correctly.\n"
56
+ " You should not be seeing this message.\n"
57
+ " Try `pip install -e .`, or change your PYTHONPATH\n"
58
+ " Make sure python finds the networkx repo you are testing\n\n"
59
+ )
60
+ config.backend = backend
61
+ if backend:
62
+ # We will update `networkx.config.backend_priority` below in `*_modify_items`
63
+ # to allow tests to get set up with normal networkx graphs.
64
+ nx.utils.backends.backends["nx_loopback"] = loopback_ep["nx_loopback"]
65
+ nx.utils.backends.backend_info["nx_loopback"] = {}
66
+ nx.config.backends = nx.utils.Config(
67
+ nx_loopback=nx.utils.Config(),
68
+ **nx.config.backends,
69
+ )
70
+ fallback_to_nx = config.getoption("--fallback-to-nx")
71
+ if not fallback_to_nx:
72
+ fallback_to_nx = os.environ.get("NETWORKX_FALLBACK_TO_NX")
73
+ nx.config.fallback_to_nx = bool(fallback_to_nx)
74
+ nx.utils.backends._dispatchable.__call__ = (
75
+ nx.utils.backends._dispatchable._call_if_any_backends_installed
76
+ )
77
+
78
+
79
+ def pytest_collection_modifyitems(config, items):
80
+ # Setting this to True here allows tests to be set up before dispatching
81
+ # any function call to a backend.
82
+ if config.backend:
83
+ # Allow pluggable backends to add markers to tests (such as skip or xfail)
84
+ # when running in auto-conversion test mode
85
+ backend_name = config.backend
86
+ if backend_name != "networkx":
87
+ nx.utils.backends._dispatchable._is_testing = True
88
+ nx.config.backend_priority.algos = [backend_name]
89
+ nx.config.backend_priority.generators = [backend_name]
90
+ backend = nx.utils.backends.backends[backend_name].load()
91
+ if hasattr(backend, "on_start_tests"):
92
+ getattr(backend, "on_start_tests")(items)
93
+
94
+ if config.getoption("--runslow"):
95
+ # --runslow given in cli: do not skip slow tests
96
+ return
97
+ skip_slow = pytest.mark.skip(reason="need --runslow option to run")
98
+ for item in items:
99
+ if "slow" in item.keywords:
100
+ item.add_marker(skip_slow)
101
+
102
+
103
+ # TODO: The warnings below need to be dealt with, but for now we silence them.
104
+ @pytest.fixture(autouse=True)
105
+ def set_warnings():
106
+ warnings.filterwarnings(
107
+ "ignore",
108
+ category=UserWarning,
109
+ message=r"Exited (at iteration \d+|postprocessing) with accuracies.*",
110
+ )
111
+ warnings.filterwarnings(
112
+ "ignore",
113
+ category=UserWarning,
114
+ message=r"The hashes produced for ",
115
+ )
116
+ warnings.filterwarnings(
117
+ "ignore", category=DeprecationWarning, message="\n\nThe `normalized`"
118
+ )
119
+ warnings.filterwarnings(
120
+ "ignore", category=DeprecationWarning, message="maybe_regular_expander"
121
+ )
122
+ warnings.filterwarnings(
123
+ "ignore", category=DeprecationWarning, message="metric_closure is deprecated"
124
+ )
125
+ warnings.filterwarnings(
126
+ "ignore", category=DeprecationWarning, message="\n\nbfs_predecessors"
127
+ )
128
+ warnings.filterwarnings(
129
+ "ignore", category=DeprecationWarning, message="The p2g module"
130
+ )
131
+ # NOTE: pydot is a common source of deprecation warnings from its underlying
132
+ # dependencies - notably pyparsing. Filter these warnings out.
133
+ warnings.filterwarnings("ignore", category=DeprecationWarning, module="pydot")
134
+
135
+
136
+ @pytest.fixture(autouse=True)
137
+ def add_nx(doctest_namespace):
138
+ doctest_namespace["nx"] = nx
139
+
140
+
141
+ # What dependencies are installed?
142
+
143
+ try:
144
+ import numpy as np
145
+
146
+ has_numpy = True
147
+ except ImportError:
148
+ has_numpy = False
149
+
150
+ try:
151
+ import scipy as sp
152
+
153
+ has_scipy = True
154
+ except ImportError:
155
+ has_scipy = False
156
+
157
+ try:
158
+ import matplotlib as mpl
159
+
160
+ has_matplotlib = True
161
+ except ImportError:
162
+ has_matplotlib = False
163
+
164
+ try:
165
+ import pandas as pd
166
+
167
+ has_pandas = True
168
+ except ImportError:
169
+ has_pandas = False
170
+
171
+ try:
172
+ import pygraphviz
173
+
174
+ has_pygraphviz = True
175
+ except ImportError:
176
+ has_pygraphviz = False
177
+
178
+ try:
179
+ import pydot
180
+
181
+ # Pydot also requires graphviz to be installed for layouts
182
+ subprocess.check_output("dot -V".split())
183
+
184
+ has_pydot = True
185
+ except (ImportError, FileNotFoundError):
186
+ has_pydot = False
187
+
188
+ try:
189
+ import sympy
190
+
191
+ has_sympy = True
192
+ except ImportError:
193
+ has_sympy = False
194
+
195
+ try:
196
+ import lxml
197
+
198
+ has_lxml = True
199
+ except ImportError:
200
+ has_lxml = False
201
+
202
+
203
+ # List of files that pytest should ignore
204
+
205
+ collect_ignore = ["readwrite/p2g.py"]
206
+
207
+ needs_numpy = [
208
+ "algorithms/approximation/traveling_salesman.py",
209
+ "algorithms/approximation/density.py",
210
+ "algorithms/centrality/current_flow_closeness.py",
211
+ "algorithms/centrality/laplacian.py",
212
+ "algorithms/node_classification.py",
213
+ "algorithms/non_randomness.py",
214
+ "algorithms/polynomials.py",
215
+ "algorithms/shortest_paths/dense.py",
216
+ "algorithms/tree/mst.py",
217
+ "drawing/nx_latex.py",
218
+ "generators/expanders.py",
219
+ "linalg/bethehessianmatrix.py",
220
+ "linalg/laplacianmatrix.py",
221
+ "utils/misc.py",
222
+ ]
223
+ needs_scipy = [
224
+ "algorithms/approximation/traveling_salesman.py",
225
+ "algorithms/assortativity/correlation.py",
226
+ "algorithms/assortativity/mixing.py",
227
+ "algorithms/assortativity/pairs.py",
228
+ "algorithms/bipartite/matrix.py",
229
+ "algorithms/bipartite/spectral.py",
230
+ "algorithms/bipartite/link_analysis.py",
231
+ "algorithms/centrality/current_flow_betweenness.py",
232
+ "algorithms/centrality/current_flow_betweenness_subset.py",
233
+ "algorithms/centrality/eigenvector.py",
234
+ "algorithms/centrality/katz.py",
235
+ "algorithms/centrality/laplacian.py",
236
+ "algorithms/centrality/second_order.py",
237
+ "algorithms/centrality/subgraph_alg.py",
238
+ "algorithms/communicability_alg.py",
239
+ "algorithms/community/divisive.py",
240
+ "algorithms/community/bipartitions.py",
241
+ "algorithms/distance_measures.py",
242
+ "algorithms/link_analysis/hits_alg.py",
243
+ "algorithms/link_analysis/pagerank_alg.py",
244
+ "algorithms/node_classification.py",
245
+ "algorithms/similarity.py",
246
+ "algorithms/tree/mst.py",
247
+ "algorithms/walks.py",
248
+ "convert_matrix.py",
249
+ "drawing/layout.py",
250
+ "drawing/nx_pylab.py",
251
+ "generators/spectral_graph_forge.py",
252
+ "generators/geometric.py",
253
+ "generators/expanders.py",
254
+ "linalg/algebraicconnectivity.py",
255
+ "linalg/attrmatrix.py",
256
+ "linalg/bethehessianmatrix.py",
257
+ "linalg/graphmatrix.py",
258
+ "linalg/laplacianmatrix.py",
259
+ "linalg/modularitymatrix.py",
260
+ "linalg/spectrum.py",
261
+ "utils/rcm.py",
262
+ ]
263
+ needs_matplotlib = ["drawing/nx_pylab.py", "generators/classic.py"]
264
+ needs_pandas = ["convert_matrix.py"]
265
+ needs_pygraphviz = ["drawing/nx_agraph.py"]
266
+ needs_pydot = ["drawing/nx_pydot.py"]
267
+ needs_sympy = ["algorithms/polynomials.py"]
268
+ needs_lxml = ["readwrite/graphml.py"]
269
+
270
+ if not has_numpy:
271
+ collect_ignore += needs_numpy
272
+ if not has_scipy:
273
+ collect_ignore += needs_scipy
274
+ if not has_matplotlib:
275
+ collect_ignore += needs_matplotlib
276
+ if not has_pandas:
277
+ collect_ignore += needs_pandas
278
+ if not has_pygraphviz:
279
+ collect_ignore += needs_pygraphviz
280
+ if not has_pydot:
281
+ collect_ignore += needs_pydot
282
+ if not has_sympy:
283
+ collect_ignore += needs_sympy
284
+ if not has_lxml:
285
+ collect_ignore += needs_lxml
venv/lib/python3.14/site-packages/networkx/convert.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions to convert NetworkX graphs to and from other formats.
2
+
3
+ The preferred way of converting data to a NetworkX graph is through the
4
+ graph constructor. The constructor calls the to_networkx_graph() function
5
+ which attempts to guess the input type and convert it automatically.
6
+
7
+ Examples
8
+ --------
9
+ Create a graph with a single edge from a dictionary of dictionaries
10
+
11
+ >>> d = {0: {1: 1}} # dict-of-dicts single edge (0,1)
12
+ >>> G = nx.Graph(d)
13
+
14
+ See Also
15
+ --------
16
+ nx_agraph, nx_pydot
17
+ """
18
+
19
+ from collections.abc import Collection, Generator, Iterator
20
+
21
+ import networkx as nx
22
+
23
+ __all__ = [
24
+ "to_networkx_graph",
25
+ "from_dict_of_dicts",
26
+ "to_dict_of_dicts",
27
+ "from_dict_of_lists",
28
+ "to_dict_of_lists",
29
+ "from_edgelist",
30
+ "to_edgelist",
31
+ ]
32
+
33
+
34
+ def to_networkx_graph(data, create_using=None, multigraph_input=False):
35
+ """Make a NetworkX graph from a known data structure.
36
+
37
+ The preferred way to call this is automatically
38
+ from the class constructor
39
+
40
+ >>> d = {0: {1: {"weight": 1}}} # dict-of-dicts single edge (0,1)
41
+ >>> G = nx.Graph(d)
42
+
43
+ instead of the equivalent
44
+
45
+ >>> G = nx.from_dict_of_dicts(d)
46
+
47
+ Parameters
48
+ ----------
49
+ data : object to be converted
50
+
51
+ Current known types are:
52
+ any NetworkX graph
53
+ dict-of-dicts
54
+ dict-of-lists
55
+ container (e.g. set, list, tuple) of edges
56
+ iterator (e.g. itertools.chain) that produces edges
57
+ generator of edges
58
+ Pandas DataFrame (row per edge)
59
+ 2D numpy array
60
+ scipy sparse array
61
+ pygraphviz agraph
62
+
63
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
64
+ Graph type to create. If graph instance, then cleared before populated.
65
+
66
+ multigraph_input : bool (default False)
67
+ If True and data is a dict_of_dicts,
68
+ try to create a multigraph assuming dict_of_dict_of_lists.
69
+ If data and create_using are both multigraphs then create
70
+ a multigraph from a multigraph.
71
+
72
+ """
73
+ # NX graph
74
+ if hasattr(data, "adj"):
75
+ try:
76
+ result = from_dict_of_dicts(
77
+ data.adj,
78
+ create_using=create_using,
79
+ multigraph_input=data.is_multigraph(),
80
+ )
81
+ # data.graph should be dict-like
82
+ result.graph.update(data.graph)
83
+ # data.nodes should be dict-like
84
+ # result.add_node_from(data.nodes.items()) possible but
85
+ # for custom node_attr_dict_factory which may be hashable
86
+ # will be unexpected behavior
87
+ for n, dd in data.nodes.items():
88
+ result._node[n].update(dd)
89
+ return result
90
+ except Exception as err:
91
+ raise nx.NetworkXError("Input is not a correct NetworkX graph.") from err
92
+
93
+ # dict of dicts/lists
94
+ if isinstance(data, dict):
95
+ try:
96
+ return from_dict_of_dicts(
97
+ data, create_using=create_using, multigraph_input=multigraph_input
98
+ )
99
+ except Exception as err1:
100
+ if multigraph_input is True:
101
+ raise nx.NetworkXError(
102
+ f"converting multigraph_input raised:\n{type(err1)}: {err1}"
103
+ )
104
+ try:
105
+ return from_dict_of_lists(data, create_using=create_using)
106
+ except Exception as err2:
107
+ raise TypeError("Input is not known type.") from err2
108
+
109
+ # edgelists
110
+ if isinstance(data, list | tuple | nx.reportviews.EdgeViewABC | Iterator):
111
+ try:
112
+ return from_edgelist(data, create_using=create_using)
113
+ except:
114
+ pass
115
+
116
+ # pygraphviz agraph
117
+ if hasattr(data, "is_strict"):
118
+ try:
119
+ return nx.nx_agraph.from_agraph(data, create_using=create_using)
120
+ except Exception as err:
121
+ raise nx.NetworkXError("Input is not a correct pygraphviz graph.") from err
122
+
123
+ # Pandas DataFrame
124
+ try:
125
+ import pandas as pd
126
+
127
+ if isinstance(data, pd.DataFrame):
128
+ if data.shape[0] == data.shape[1]:
129
+ try:
130
+ return nx.from_pandas_adjacency(data, create_using=create_using)
131
+ except Exception as err:
132
+ msg = "Input is not a correct Pandas DataFrame adjacency matrix."
133
+ raise nx.NetworkXError(msg) from err
134
+ else:
135
+ try:
136
+ return nx.from_pandas_edgelist(
137
+ data, edge_attr=True, create_using=create_using
138
+ )
139
+ except Exception as err:
140
+ msg = "Input is not a correct Pandas DataFrame edge-list."
141
+ raise nx.NetworkXError(msg) from err
142
+ except ImportError:
143
+ pass
144
+
145
+ # numpy array
146
+ try:
147
+ import numpy as np
148
+
149
+ if isinstance(data, np.ndarray):
150
+ try:
151
+ return nx.from_numpy_array(data, create_using=create_using)
152
+ except Exception as err:
153
+ raise nx.NetworkXError(
154
+ f"Failed to interpret array as an adjacency matrix."
155
+ ) from err
156
+ except ImportError:
157
+ pass
158
+
159
+ # scipy sparse array - any format
160
+ try:
161
+ import scipy as sp
162
+
163
+ if hasattr(data, "format"):
164
+ try:
165
+ return nx.from_scipy_sparse_array(data, create_using=create_using)
166
+ except Exception as err:
167
+ raise nx.NetworkXError(
168
+ "Input is not a correct scipy sparse array type."
169
+ ) from err
170
+ except ImportError:
171
+ pass
172
+
173
+ # Note: most general check - should remain last in order of execution
174
+ # Includes containers (e.g. list, set, dict, etc.), generators, and
175
+ # iterators (e.g. itertools.chain) of edges
176
+
177
+ if isinstance(data, Collection | Generator | Iterator):
178
+ try:
179
+ return from_edgelist(data, create_using=create_using)
180
+ except Exception as err:
181
+ raise nx.NetworkXError("Input is not a valid edge list") from err
182
+
183
+ raise nx.NetworkXError("Input is not a known data type for conversion.")
184
+
185
+
186
+ @nx._dispatchable
187
+ def to_dict_of_lists(G, nodelist=None):
188
+ """Returns adjacency representation of graph as a dictionary of lists.
189
+
190
+ Parameters
191
+ ----------
192
+ G : graph
193
+ A NetworkX graph
194
+
195
+ nodelist : list
196
+ Use only nodes specified in nodelist
197
+
198
+ Notes
199
+ -----
200
+ Completely ignores edge data for MultiGraph and MultiDiGraph.
201
+
202
+ """
203
+ if nodelist is None:
204
+ nodelist = G
205
+
206
+ d = {}
207
+ for n in nodelist:
208
+ d[n] = [nbr for nbr in G.neighbors(n) if nbr in nodelist]
209
+ return d
210
+
211
+
212
+ @nx._dispatchable(graphs=None, returns_graph=True)
213
+ def from_dict_of_lists(d, create_using=None):
214
+ """Returns a graph from a dictionary of lists.
215
+
216
+ Parameters
217
+ ----------
218
+ d : dictionary of lists
219
+ A dictionary of lists adjacency representation.
220
+
221
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
222
+ Graph type to create. If graph instance, then cleared before populated.
223
+
224
+ Examples
225
+ --------
226
+ >>> dol = {0: [1]} # single edge (0,1)
227
+ >>> G = nx.from_dict_of_lists(dol)
228
+
229
+ or
230
+
231
+ >>> G = nx.Graph(dol) # use Graph constructor
232
+
233
+ """
234
+ G = nx.empty_graph(0, create_using)
235
+ G.add_nodes_from(d)
236
+ if G.is_multigraph() and not G.is_directed():
237
+ # a dict_of_lists can't show multiedges. BUT for undirected graphs,
238
+ # each edge shows up twice in the dict_of_lists.
239
+ # So we need to treat this case separately.
240
+ seen = {}
241
+ for node, nbrlist in d.items():
242
+ for nbr in nbrlist:
243
+ if nbr not in seen:
244
+ G.add_edge(node, nbr)
245
+ seen[node] = 1 # don't allow reverse edge to show up
246
+ else:
247
+ G.add_edges_from(
248
+ ((node, nbr) for node, nbrlist in d.items() for nbr in nbrlist)
249
+ )
250
+ return G
251
+
252
+
253
+ def to_dict_of_dicts(G, nodelist=None, edge_data=None):
254
+ """Returns adjacency representation of graph as a dictionary of dictionaries.
255
+
256
+ Parameters
257
+ ----------
258
+ G : graph
259
+ A NetworkX graph
260
+
261
+ nodelist : list
262
+ Use only nodes specified in nodelist. If None, all nodes in G.
263
+
264
+ edge_data : scalar, optional (default: the G edgedatadict for each edge)
265
+ If provided, the value of the dictionary will be set to `edge_data` for
266
+ all edges. Usual values could be `1` or `True`. If `edge_data` is
267
+ `None` (the default), the edgedata in `G` is used, resulting in a
268
+ dict-of-dict-of-dicts. If `G` is a MultiGraph, the result will be a
269
+ dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize
270
+ handling edge data. `edge_data` should *not* be a container as it will
271
+ be the same container for all the edges.
272
+
273
+ Returns
274
+ -------
275
+ dod : dict
276
+ A nested dictionary representation of `G`. Note that the level of
277
+ nesting depends on the type of `G` and the value of `edge_data`
278
+ (see Examples).
279
+
280
+ See Also
281
+ --------
282
+ from_dict_of_dicts, to_dict_of_lists
283
+
284
+ Notes
285
+ -----
286
+ For a more custom approach to handling edge data, try::
287
+
288
+ dod = {
289
+ n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()}
290
+ for n, nbrdict in G.adj.items()
291
+ }
292
+
293
+ where `custom` returns the desired edge data for each edge between `n` and
294
+ `nbr`, given existing edge data `dd`.
295
+
296
+ Examples
297
+ --------
298
+ >>> G = nx.path_graph(3)
299
+ >>> nx.to_dict_of_dicts(G)
300
+ {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}}
301
+
302
+ Edge data is preserved by default (``edge_data=None``), resulting
303
+ in dict-of-dict-of-dicts where the innermost dictionary contains the
304
+ edge data:
305
+
306
+ >>> G = nx.Graph()
307
+ >>> G.add_edges_from(
308
+ ... [
309
+ ... (0, 1, {"weight": 1.0}),
310
+ ... (1, 2, {"weight": 2.0}),
311
+ ... (2, 0, {"weight": 1.0}),
312
+ ... ]
313
+ ... )
314
+ >>> d = nx.to_dict_of_dicts(G)
315
+ >>> d # doctest: +SKIP
316
+ {0: {1: {'weight': 1.0}, 2: {'weight': 1.0}},
317
+ 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}},
318
+ 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}}
319
+ >>> d[1][2]["weight"]
320
+ 2.0
321
+
322
+ If `edge_data` is not `None`, edge data in the original graph (if any) is
323
+ replaced:
324
+
325
+ >>> d = nx.to_dict_of_dicts(G, edge_data=1)
326
+ >>> d
327
+ {0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}}
328
+ >>> d[1][2]
329
+ 1
330
+
331
+ This also applies to MultiGraphs: edge data is preserved by default:
332
+
333
+ >>> G = nx.MultiGraph()
334
+ >>> G.add_edge(0, 1, key="a", weight=1.0)
335
+ 'a'
336
+ >>> G.add_edge(0, 1, key="b", weight=5.0)
337
+ 'b'
338
+ >>> d = nx.to_dict_of_dicts(G)
339
+ >>> d # doctest: +SKIP
340
+ {0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}},
341
+ 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}}
342
+ >>> d[0][1]["b"]["weight"]
343
+ 5.0
344
+
345
+ But multi edge data is lost if `edge_data` is not `None`:
346
+
347
+ >>> d = nx.to_dict_of_dicts(G, edge_data=10)
348
+ >>> d
349
+ {0: {1: 10}, 1: {0: 10}}
350
+ """
351
+ dod = {}
352
+ if nodelist is None:
353
+ if edge_data is None:
354
+ for u, nbrdict in G.adjacency():
355
+ dod[u] = nbrdict.copy()
356
+ else: # edge_data is not None
357
+ for u, nbrdict in G.adjacency():
358
+ dod[u] = dod.fromkeys(nbrdict, edge_data)
359
+ else: # nodelist is not None
360
+ if edge_data is None:
361
+ for u in nodelist:
362
+ dod[u] = {}
363
+ for v, data in ((v, data) for v, data in G[u].items() if v in nodelist):
364
+ dod[u][v] = data
365
+ else: # nodelist and edge_data are not None
366
+ for u in nodelist:
367
+ dod[u] = {}
368
+ for v in (v for v in G[u] if v in nodelist):
369
+ dod[u][v] = edge_data
370
+ return dod
371
+
372
+
373
+ @nx._dispatchable(graphs=None, returns_graph=True)
374
+ def from_dict_of_dicts(d, create_using=None, multigraph_input=False):
375
+ """Returns a graph from a dictionary of dictionaries.
376
+
377
+ Parameters
378
+ ----------
379
+ d : dictionary of dictionaries
380
+ A dictionary of dictionaries adjacency representation.
381
+
382
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
383
+ Graph type to create. If graph instance, then cleared before populated.
384
+
385
+ multigraph_input : bool (default False)
386
+ When True, the dict `d` is assumed
387
+ to be a dict-of-dict-of-dict-of-dict structure keyed by
388
+ node to neighbor to edge keys to edge data for multi-edges.
389
+ Otherwise this routine assumes dict-of-dict-of-dict keyed by
390
+ node to neighbor to edge data.
391
+
392
+ Examples
393
+ --------
394
+ >>> dod = {0: {1: {"weight": 1}}} # single edge (0,1)
395
+ >>> G = nx.from_dict_of_dicts(dod)
396
+
397
+ or
398
+
399
+ >>> G = nx.Graph(dod) # use Graph constructor
400
+
401
+ """
402
+ G = nx.empty_graph(0, create_using)
403
+ G.add_nodes_from(d)
404
+ # does dict d represent a MultiGraph or MultiDiGraph?
405
+ if multigraph_input:
406
+ if G.is_directed():
407
+ if G.is_multigraph():
408
+ G.add_edges_from(
409
+ (u, v, key, data)
410
+ for u, nbrs in d.items()
411
+ for v, datadict in nbrs.items()
412
+ for key, data in datadict.items()
413
+ )
414
+ else:
415
+ G.add_edges_from(
416
+ (u, v, data)
417
+ for u, nbrs in d.items()
418
+ for v, datadict in nbrs.items()
419
+ for key, data in datadict.items()
420
+ )
421
+ else: # Undirected
422
+ if G.is_multigraph():
423
+ seen = set() # don't add both directions of undirected graph
424
+ for u, nbrs in d.items():
425
+ for v, datadict in nbrs.items():
426
+ if (u, v) not in seen:
427
+ G.add_edges_from(
428
+ (u, v, key, data) for key, data in datadict.items()
429
+ )
430
+ seen.add((v, u))
431
+ else:
432
+ seen = set() # don't add both directions of undirected graph
433
+ for u, nbrs in d.items():
434
+ for v, datadict in nbrs.items():
435
+ if (u, v) not in seen:
436
+ G.add_edges_from(
437
+ (u, v, data) for key, data in datadict.items()
438
+ )
439
+ seen.add((v, u))
440
+
441
+ else: # not a multigraph to multigraph transfer
442
+ if G.is_multigraph() and not G.is_directed():
443
+ # d can have both representations u-v, v-u in dict. Only add one.
444
+ # We don't need this check for digraphs since we add both directions,
445
+ # or for Graph() since it is done implicitly (parallel edges not allowed)
446
+ seen = set()
447
+ for u, nbrs in d.items():
448
+ for v, data in nbrs.items():
449
+ if (u, v) not in seen:
450
+ G.add_edge(u, v, key=0)
451
+ G[u][v][0].update(data)
452
+ seen.add((v, u))
453
+ else:
454
+ G.add_edges_from(
455
+ ((u, v, data) for u, nbrs in d.items() for v, data in nbrs.items())
456
+ )
457
+ return G
458
+
459
+
460
+ @nx._dispatchable(preserve_edge_attrs=True)
461
+ def to_edgelist(G, nodelist=None):
462
+ """Returns a list of edges in the graph.
463
+
464
+ Parameters
465
+ ----------
466
+ G : graph
467
+ A NetworkX graph
468
+
469
+ nodelist : list
470
+ Use only nodes specified in nodelist
471
+
472
+ """
473
+ if nodelist is None:
474
+ return G.edges(data=True)
475
+ return G.edges(nodelist, data=True)
476
+
477
+
478
+ @nx._dispatchable(graphs=None, returns_graph=True)
479
+ def from_edgelist(edgelist, create_using=None):
480
+ """Returns a graph from a list of edges.
481
+
482
+ Parameters
483
+ ----------
484
+ edgelist : list or iterator
485
+ Edge tuples
486
+
487
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
488
+ Graph type to create. If graph instance, then cleared before populated.
489
+
490
+ Examples
491
+ --------
492
+ >>> edgelist = [(0, 1)] # single edge (0,1)
493
+ >>> G = nx.from_edgelist(edgelist)
494
+
495
+ or
496
+
497
+ >>> G = nx.Graph(edgelist) # use Graph constructor
498
+
499
+ """
500
+ G = nx.empty_graph(0, create_using)
501
+ G.add_edges_from(edgelist)
502
+ return G
venv/lib/python3.14/site-packages/networkx/convert_matrix.py ADDED
@@ -0,0 +1,1350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions to convert NetworkX graphs to and from common data containers
2
+ like numpy arrays, scipy sparse arrays, and pandas DataFrames.
3
+
4
+ The preferred way of converting data to a NetworkX graph is through the
5
+ graph constructor. The constructor calls the `~networkx.convert.to_networkx_graph`
6
+ function which attempts to guess the input type and convert it automatically.
7
+
8
+ Examples
9
+ --------
10
+ Create a 10 node random graph from a numpy array
11
+
12
+ >>> import numpy as np
13
+ >>> rng = np.random.default_rng()
14
+ >>> a = rng.integers(low=0, high=2, size=(10, 10))
15
+ >>> DG = nx.from_numpy_array(a, create_using=nx.DiGraph)
16
+
17
+ or equivalently:
18
+
19
+ >>> DG = nx.DiGraph(a)
20
+
21
+ which calls `from_numpy_array` internally based on the type of ``a``.
22
+
23
+ See Also
24
+ --------
25
+ nx_agraph, nx_pydot
26
+ """
27
+
28
+ import itertools
29
+ from collections import defaultdict
30
+
31
+ import networkx as nx
32
+
33
+ __all__ = [
34
+ "from_pandas_adjacency",
35
+ "to_pandas_adjacency",
36
+ "from_pandas_edgelist",
37
+ "to_pandas_edgelist",
38
+ "from_scipy_sparse_array",
39
+ "to_scipy_sparse_array",
40
+ "from_numpy_array",
41
+ "to_numpy_array",
42
+ ]
43
+
44
+
45
+ @nx._dispatchable(edge_attrs="weight")
46
+ def to_pandas_adjacency(
47
+ G,
48
+ nodelist=None,
49
+ dtype=None,
50
+ order=None,
51
+ multigraph_weight=sum,
52
+ weight="weight",
53
+ nonedge=0.0,
54
+ ):
55
+ """Returns the graph adjacency matrix as a Pandas DataFrame.
56
+
57
+ Parameters
58
+ ----------
59
+ G : graph
60
+ The NetworkX graph used to construct the Pandas DataFrame.
61
+
62
+ nodelist : list, optional
63
+ The rows and columns are ordered according to the nodes in `nodelist`.
64
+ If `nodelist` is None, then the ordering is produced by G.nodes().
65
+
66
+ multigraph_weight : {sum, min, max}, optional
67
+ An operator that determines how weights in multigraphs are handled.
68
+ The default is to sum the weights of the multiple edges.
69
+
70
+ weight : string or None, optional
71
+ The edge attribute that holds the numerical value used for
72
+ the edge weight. If an edge does not have that attribute, then the
73
+ value 1 is used instead.
74
+
75
+ nonedge : float, optional
76
+ The matrix values corresponding to nonedges are typically set to zero.
77
+ However, this could be undesirable if there are matrix values
78
+ corresponding to actual edges that also have the value zero. If so,
79
+ one might prefer nonedges to have some other value, such as nan.
80
+
81
+ Returns
82
+ -------
83
+ df : Pandas DataFrame
84
+ Graph adjacency matrix
85
+
86
+ Notes
87
+ -----
88
+ For directed graphs, entry i,j corresponds to an edge from i to j.
89
+
90
+ The DataFrame entries are assigned to the weight edge attribute. When
91
+ an edge does not have a weight attribute, the value of the entry is set to
92
+ the number 1. For multiple (parallel) edges, the values of the entries
93
+ are determined by the 'multigraph_weight' parameter. The default is to
94
+ sum the weight attributes for each of the parallel edges.
95
+
96
+ When `nodelist` does not contain every node in `G`, the matrix is built
97
+ from the subgraph of `G` that is induced by the nodes in `nodelist`.
98
+
99
+ The convention used for self-loop edges in graphs is to assign the
100
+ diagonal matrix entry value to the weight attribute of the edge
101
+ (or the number 1 if the edge has no weight attribute). If the
102
+ alternate convention of doubling the edge weight is desired the
103
+ resulting Pandas DataFrame can be modified as follows::
104
+
105
+ >>> import pandas as pd
106
+ >>> G = nx.Graph([(1, 1), (2, 2)])
107
+ >>> df = nx.to_pandas_adjacency(G)
108
+ >>> df
109
+ 1 2
110
+ 1 1.0 0.0
111
+ 2 0.0 1.0
112
+ >>> diag_idx = list(range(len(df)))
113
+ >>> df.iloc[diag_idx, diag_idx] *= 2
114
+ >>> df
115
+ 1 2
116
+ 1 2.0 0.0
117
+ 2 0.0 2.0
118
+
119
+ Examples
120
+ --------
121
+ >>> G = nx.MultiDiGraph()
122
+ >>> G.add_edge(0, 1, weight=2)
123
+ 0
124
+ >>> G.add_edge(1, 0)
125
+ 0
126
+ >>> G.add_edge(2, 2, weight=3)
127
+ 0
128
+ >>> G.add_edge(2, 2)
129
+ 1
130
+ >>> nx.to_pandas_adjacency(G, nodelist=[0, 1, 2], dtype=int)
131
+ 0 1 2
132
+ 0 0 2 0
133
+ 1 1 0 0
134
+ 2 0 0 4
135
+
136
+ """
137
+ import pandas as pd
138
+
139
+ M = to_numpy_array(
140
+ G,
141
+ nodelist=nodelist,
142
+ dtype=dtype,
143
+ order=order,
144
+ multigraph_weight=multigraph_weight,
145
+ weight=weight,
146
+ nonedge=nonedge,
147
+ )
148
+ if nodelist is None:
149
+ nodelist = list(G)
150
+ return pd.DataFrame(data=M, index=nodelist, columns=nodelist)
151
+
152
+
153
+ @nx._dispatchable(graphs=None, returns_graph=True)
154
+ def from_pandas_adjacency(df, create_using=None, *, nonedge=0):
155
+ r"""Returns a graph from Pandas DataFrame.
156
+
157
+ The Pandas DataFrame is interpreted as an adjacency matrix for the graph.
158
+
159
+ Parameters
160
+ ----------
161
+ df : Pandas DataFrame
162
+ An adjacency matrix representation of a graph
163
+
164
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
165
+ Graph type to create. If graph instance, then cleared before populated.
166
+
167
+ nonedge : array_like (default = 0)
168
+ The value used to represent non-edges in the adjacency matrix.
169
+ See :func:`from_numpy_array` for details.
170
+
171
+ Notes
172
+ -----
173
+ For directed graphs, explicitly mention create_using=nx.DiGraph,
174
+ and entry i,j of df corresponds to an edge from i to j.
175
+
176
+ If `df` has a single data type for each entry it will be converted to an
177
+ appropriate Python data type.
178
+
179
+ If you have node attributes stored in a separate dataframe `df_nodes`,
180
+ you can load those attributes to the graph `G` using the following code::
181
+
182
+ df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]})
183
+ G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows())
184
+
185
+ If `df` has a user-specified compound data type the names
186
+ of the data fields will be used as attribute keys in the resulting
187
+ NetworkX graph.
188
+
189
+ See Also
190
+ --------
191
+ to_pandas_adjacency
192
+
193
+ Examples
194
+ --------
195
+ Simple integer weights on edges:
196
+
197
+ >>> import pandas as pd
198
+ >>> pd.options.display.max_columns = 20
199
+ >>> df = pd.DataFrame([[1, 1], [2, 1]])
200
+ >>> df
201
+ 0 1
202
+ 0 1 1
203
+ 1 2 1
204
+ >>> G = nx.from_pandas_adjacency(df)
205
+ >>> G.name = "Graph from pandas adjacency matrix"
206
+ >>> print(G)
207
+ Graph named 'Graph from pandas adjacency matrix' with 2 nodes and 3 edges
208
+ """
209
+
210
+ try:
211
+ df = df[df.index]
212
+ except Exception as err:
213
+ missing = list(set(df.index).difference(set(df.columns)))
214
+ msg = f"{missing} not in columns"
215
+ raise nx.NetworkXError("Columns must match Indices.", msg) from err
216
+
217
+ A = df.values
218
+ G = from_numpy_array(
219
+ A, create_using=create_using, nodelist=df.columns, nonedge=nonedge
220
+ )
221
+
222
+ return G
223
+
224
+
225
+ @nx._dispatchable(preserve_edge_attrs=True)
226
+ def to_pandas_edgelist(
227
+ G,
228
+ source="source",
229
+ target="target",
230
+ nodelist=None,
231
+ dtype=None,
232
+ edge_key=None,
233
+ ):
234
+ """Returns the graph edge list as a Pandas DataFrame.
235
+
236
+ Parameters
237
+ ----------
238
+ G : graph
239
+ The NetworkX graph used to construct the Pandas DataFrame.
240
+
241
+ source : str or int, optional
242
+ A valid column name (string or integer) for the source nodes (for the
243
+ directed case).
244
+
245
+ target : str or int, optional
246
+ A valid column name (string or integer) for the target nodes (for the
247
+ directed case).
248
+
249
+ nodelist : list, optional
250
+ Use only nodes specified in nodelist
251
+
252
+ dtype : dtype, default None
253
+ Use to create the DataFrame. Data type to force.
254
+ Only a single dtype is allowed. If None, infer.
255
+
256
+ edge_key : str or int or None, optional (default=None)
257
+ A valid column name (string or integer) for the edge keys (for the
258
+ multigraph case). If None, edge keys are not stored in the DataFrame.
259
+
260
+ Returns
261
+ -------
262
+ df : Pandas DataFrame
263
+ Graph edge list
264
+
265
+ Examples
266
+ --------
267
+ >>> G = nx.Graph(
268
+ ... [
269
+ ... ("A", "B", {"cost": 1, "weight": 7}),
270
+ ... ("C", "E", {"cost": 9, "weight": 10}),
271
+ ... ]
272
+ ... )
273
+ >>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"])
274
+ >>> df[["source", "target", "cost", "weight"]]
275
+ source target cost weight
276
+ 0 A B 1 7
277
+ 1 C E 9 10
278
+
279
+ >>> G = nx.MultiGraph([("A", "B", {"cost": 1}), ("A", "B", {"cost": 9})])
280
+ >>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"], edge_key="ekey")
281
+ >>> df[["source", "target", "cost", "ekey"]]
282
+ source target cost ekey
283
+ 0 A B 1 0
284
+ 1 A B 9 1
285
+
286
+ """
287
+ import pandas as pd
288
+
289
+ if nodelist is None:
290
+ edgelist = G.edges(data=True)
291
+ else:
292
+ edgelist = G.edges(nodelist, data=True)
293
+ source_nodes = [s for s, _, _ in edgelist]
294
+ target_nodes = [t for _, t, _ in edgelist]
295
+
296
+ all_attrs = set().union(*(d.keys() for _, _, d in edgelist))
297
+ if source in all_attrs:
298
+ raise nx.NetworkXError(f"Source name {source!r} is an edge attr name")
299
+ if target in all_attrs:
300
+ raise nx.NetworkXError(f"Target name {target!r} is an edge attr name")
301
+
302
+ nan = float("nan")
303
+ edge_attr = {k: [d.get(k, nan) for _, _, d in edgelist] for k in all_attrs}
304
+
305
+ if G.is_multigraph() and edge_key is not None:
306
+ if edge_key in all_attrs:
307
+ raise nx.NetworkXError(f"Edge key name {edge_key!r} is an edge attr name")
308
+ edge_keys = [k for _, _, k in G.edges(keys=True)]
309
+ edgelistdict = {source: source_nodes, target: target_nodes, edge_key: edge_keys}
310
+ else:
311
+ edgelistdict = {source: source_nodes, target: target_nodes}
312
+
313
+ edgelistdict.update(edge_attr)
314
+ return pd.DataFrame(edgelistdict, dtype=dtype)
315
+
316
+
317
+ @nx._dispatchable(graphs=None, returns_graph=True)
318
+ def from_pandas_edgelist(
319
+ df,
320
+ source="source",
321
+ target="target",
322
+ edge_attr=None,
323
+ create_using=None,
324
+ edge_key=None,
325
+ ):
326
+ """Returns a graph from Pandas DataFrame containing an edge list.
327
+
328
+ The Pandas DataFrame should contain at least two columns of node names and
329
+ zero or more columns of edge attributes. Each row will be processed as one
330
+ edge instance.
331
+
332
+ Note: This function iterates over DataFrame.values, which is not
333
+ guaranteed to retain the data type across columns in the row. This is only
334
+ a problem if your row is entirely numeric and a mix of ints and floats. In
335
+ that case, all values will be returned as floats. See the
336
+ DataFrame.iterrows documentation for an example.
337
+
338
+ Parameters
339
+ ----------
340
+ df : Pandas DataFrame
341
+ An edge list representation of a graph
342
+
343
+ source : str or int
344
+ A valid column name (string or integer) for the source nodes (for the
345
+ directed case).
346
+
347
+ target : str or int
348
+ A valid column name (string or integer) for the target nodes (for the
349
+ directed case).
350
+
351
+ edge_attr : str or int, iterable, True, or None
352
+ A valid column name (str or int) or iterable of column names that are
353
+ used to retrieve items and add them to the graph as edge attributes.
354
+ If `True`, all columns will be added except `source`, `target` and `edge_key`.
355
+ If `None`, no edge attributes are added to the graph.
356
+
357
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
358
+ Graph type to create. If graph instance, then cleared before populated.
359
+
360
+ edge_key : str or None, optional (default=None)
361
+ A valid column name for the edge keys (for a MultiGraph). The values in
362
+ this column are used for the edge keys when adding edges if create_using
363
+ is a multigraph.
364
+
365
+ Notes
366
+ -----
367
+ If you have node attributes stored in a separate dataframe `df_nodes`,
368
+ you can load those attributes to the graph `G` using the following code::
369
+
370
+ df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]})
371
+ G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows())
372
+
373
+ See Also
374
+ --------
375
+ to_pandas_edgelist
376
+
377
+ Examples
378
+ --------
379
+ Simple integer weights on edges:
380
+
381
+ >>> import pandas as pd
382
+ >>> pd.options.display.max_columns = 20
383
+ >>> import numpy as np
384
+ >>> rng = np.random.RandomState(seed=5)
385
+ >>> ints = rng.randint(1, 11, size=(3, 2))
386
+ >>> a = ["A", "B", "C"]
387
+ >>> b = ["D", "A", "E"]
388
+ >>> df = pd.DataFrame(ints, columns=["weight", "cost"])
389
+ >>> df[0] = a
390
+ >>> df["b"] = b
391
+ >>> df[["weight", "cost", 0, "b"]]
392
+ weight cost 0 b
393
+ 0 4 7 A D
394
+ 1 7 1 B A
395
+ 2 10 9 C E
396
+ >>> G = nx.from_pandas_edgelist(df, 0, "b", ["weight", "cost"])
397
+ >>> G["E"]["C"]["weight"]
398
+ 10
399
+ >>> G["E"]["C"]["cost"]
400
+ 9
401
+ >>> edges = pd.DataFrame(
402
+ ... {
403
+ ... "source": [0, 1, 2],
404
+ ... "target": [2, 2, 3],
405
+ ... "weight": [3, 4, 5],
406
+ ... "color": ["red", "blue", "blue"],
407
+ ... }
408
+ ... )
409
+ >>> G = nx.from_pandas_edgelist(edges, edge_attr=True)
410
+ >>> G[0][2]["color"]
411
+ 'red'
412
+
413
+ Build multigraph with custom keys:
414
+
415
+ >>> edges = pd.DataFrame(
416
+ ... {
417
+ ... "source": [0, 1, 2, 0],
418
+ ... "target": [2, 2, 3, 2],
419
+ ... "my_edge_key": ["A", "B", "C", "D"],
420
+ ... "weight": [3, 4, 5, 6],
421
+ ... "color": ["red", "blue", "blue", "blue"],
422
+ ... }
423
+ ... )
424
+ >>> G = nx.from_pandas_edgelist(
425
+ ... edges,
426
+ ... edge_key="my_edge_key",
427
+ ... edge_attr=["weight", "color"],
428
+ ... create_using=nx.MultiGraph(),
429
+ ... )
430
+ >>> G[0][2]
431
+ AtlasView({'A': {'weight': 3, 'color': 'red'}, 'D': {'weight': 6, 'color': 'blue'}})
432
+
433
+
434
+ """
435
+ g = nx.empty_graph(0, create_using)
436
+
437
+ if edge_attr is None:
438
+ if g.is_multigraph() and edge_key is not None:
439
+ for u, v, k in zip(df[source], df[target], df[edge_key]):
440
+ g.add_edge(u, v, k)
441
+ else:
442
+ g.add_edges_from(zip(df[source], df[target]))
443
+ return g
444
+
445
+ reserved_columns = [source, target]
446
+ if g.is_multigraph() and edge_key is not None:
447
+ reserved_columns.append(edge_key)
448
+
449
+ # Additional columns requested
450
+ attr_col_headings = []
451
+ attribute_data = []
452
+ if edge_attr is True:
453
+ attr_col_headings = [c for c in df.columns if c not in reserved_columns]
454
+ elif isinstance(edge_attr, list | tuple):
455
+ attr_col_headings = edge_attr
456
+ else:
457
+ attr_col_headings = [edge_attr]
458
+ if len(attr_col_headings) == 0:
459
+ raise nx.NetworkXError(
460
+ f"Invalid edge_attr argument: No columns found with name: {attr_col_headings}"
461
+ )
462
+
463
+ try:
464
+ attribute_data = zip(*[df[col] for col in attr_col_headings])
465
+ except (KeyError, TypeError) as err:
466
+ msg = f"Invalid edge_attr argument: {edge_attr}"
467
+ raise nx.NetworkXError(msg) from err
468
+
469
+ if g.is_multigraph():
470
+ # => append the edge keys from the df to the bundled data
471
+ if edge_key is not None:
472
+ try:
473
+ multigraph_edge_keys = df[edge_key]
474
+ attribute_data = zip(attribute_data, multigraph_edge_keys)
475
+ except (KeyError, TypeError) as err:
476
+ msg = f"Invalid edge_key argument: {edge_key}"
477
+ raise nx.NetworkXError(msg) from err
478
+
479
+ for s, t, attrs in zip(df[source], df[target], attribute_data):
480
+ if edge_key is not None:
481
+ attrs, multigraph_edge_key = attrs
482
+ key = g.add_edge(s, t, key=multigraph_edge_key)
483
+ else:
484
+ key = g.add_edge(s, t)
485
+
486
+ g[s][t][key].update(zip(attr_col_headings, attrs))
487
+ else:
488
+ for s, t, attrs in zip(df[source], df[target], attribute_data):
489
+ g.add_edge(s, t)
490
+ g[s][t].update(zip(attr_col_headings, attrs))
491
+
492
+ return g
493
+
494
+
495
+ @nx._dispatchable(edge_attrs="weight")
496
+ def to_scipy_sparse_array(G, nodelist=None, dtype=None, weight="weight", format="csr"):
497
+ """Returns the graph adjacency matrix as a SciPy sparse array.
498
+
499
+ Parameters
500
+ ----------
501
+ G : graph
502
+ The NetworkX graph used to construct the sparse array.
503
+
504
+ nodelist : list, optional
505
+ The rows and columns are ordered according to the nodes in `nodelist`.
506
+ If `nodelist` is None, then the ordering is produced by ``G.nodes()``.
507
+
508
+ dtype : NumPy data-type, optional
509
+ A valid NumPy dtype used to initialize the array. If None, then the
510
+ NumPy default is used.
511
+
512
+ weight : string or None, optional (default='weight')
513
+ The edge attribute that holds the numerical value used for
514
+ the edge weight. If None then all edge weights are 1.
515
+
516
+ format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
517
+ The format of the sparse array to be returned (default 'csr'). For
518
+ some algorithms different implementations of sparse arrays
519
+ can perform better. See [1]_ for details.
520
+
521
+ Returns
522
+ -------
523
+ A : SciPy sparse array
524
+ Graph adjacency matrix.
525
+
526
+ Notes
527
+ -----
528
+ For directed graphs, matrix entry ``i, j`` corresponds to an edge from
529
+ ``i`` to ``j``.
530
+
531
+ The values of the adjacency matrix are populated using the edge attribute held in
532
+ parameter `weight`. When an edge does not have that attribute, the
533
+ value of the entry is 1.
534
+
535
+ For multiple edges the matrix values are the sums of the edge weights.
536
+
537
+ When `nodelist` does not contain every node in `G`, the adjacency matrix
538
+ is built from the subgraph of `G` that is induced by the nodes in
539
+ `nodelist`.
540
+
541
+ The convention used for self-loop edges in graphs is to assign the
542
+ diagonal matrix entry value to the weight attribute of the edge
543
+ (or the number 1 if the edge has no weight attribute). If the
544
+ alternate convention of doubling the edge weight is desired the
545
+ resulting array can be modified as follows::
546
+
547
+ >>> G = nx.Graph([(1, 1)])
548
+ >>> A = nx.to_scipy_sparse_array(G)
549
+ >>> A.toarray()
550
+ array([[1]])
551
+ >>> A.setdiag(A.diagonal() * 2)
552
+ >>> A.toarray()
553
+ array([[2]])
554
+
555
+ Examples
556
+ --------
557
+
558
+ Basic usage:
559
+
560
+ >>> G = nx.path_graph(4)
561
+ >>> A = nx.to_scipy_sparse_array(G)
562
+ >>> A # doctest: +SKIP
563
+ <Compressed Sparse Row sparse array of dtype 'int64'
564
+ with 6 stored elements and shape (4, 4)>
565
+
566
+ >>> A.toarray()
567
+ array([[0, 1, 0, 0],
568
+ [1, 0, 1, 0],
569
+ [0, 1, 0, 1],
570
+ [0, 0, 1, 0]])
571
+
572
+ .. note:: The `toarray` method is used in these examples to better visualize
573
+ the adjacency matrix. For a dense representation of the adjaceny matrix,
574
+ use `to_numpy_array` instead.
575
+
576
+ Directed graphs:
577
+
578
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
579
+ >>> nx.to_scipy_sparse_array(G).toarray()
580
+ array([[0, 1, 0, 0],
581
+ [0, 0, 1, 0],
582
+ [0, 0, 0, 1],
583
+ [0, 0, 0, 0]])
584
+
585
+ >>> H = G.reverse()
586
+ >>> H.edges
587
+ OutEdgeView([(1, 0), (2, 1), (3, 2)])
588
+ >>> nx.to_scipy_sparse_array(H).toarray()
589
+ array([[0, 0, 0, 0],
590
+ [1, 0, 0, 0],
591
+ [0, 1, 0, 0],
592
+ [0, 0, 1, 0]])
593
+
594
+ By default, the order of the rows/columns of the adjacency matrix is determined
595
+ by the ordering of the nodes in `G`:
596
+
597
+ >>> G = nx.Graph()
598
+ >>> G.add_nodes_from([3, 5, 0, 1])
599
+ >>> G.add_edges_from([(1, 3), (1, 5)])
600
+ >>> nx.to_scipy_sparse_array(G).toarray()
601
+ array([[0, 0, 0, 1],
602
+ [0, 0, 0, 1],
603
+ [0, 0, 0, 0],
604
+ [1, 1, 0, 0]])
605
+
606
+ The ordering of the rows can be changed with `nodelist`:
607
+
608
+ >>> ordered = [0, 1, 3, 5]
609
+ >>> nx.to_scipy_sparse_array(G, nodelist=ordered).toarray()
610
+ array([[0, 0, 0, 0],
611
+ [0, 0, 1, 1],
612
+ [0, 1, 0, 0],
613
+ [0, 1, 0, 0]])
614
+
615
+ If `nodelist` contains a subset of the nodes in `G`, the adjacency matrix
616
+ for the node-induced subgraph is produced:
617
+
618
+ >>> nx.to_scipy_sparse_array(G, nodelist=[1, 3, 5]).toarray()
619
+ array([[0, 1, 1],
620
+ [1, 0, 0],
621
+ [1, 0, 0]])
622
+
623
+ The values of the adjacency matrix are drawn from the edge attribute
624
+ specified by the `weight` parameter:
625
+
626
+ >>> G = nx.path_graph(4)
627
+ >>> nx.set_edge_attributes(
628
+ ... G, values={(0, 1): 1, (1, 2): 10, (2, 3): 2}, name="weight"
629
+ ... )
630
+ >>> nx.set_edge_attributes(
631
+ ... G, values={(0, 1): 50, (1, 2): 35, (2, 3): 10}, name="capacity"
632
+ ... )
633
+ >>> nx.to_scipy_sparse_array(G).toarray() # Default weight="weight"
634
+ array([[ 0, 1, 0, 0],
635
+ [ 1, 0, 10, 0],
636
+ [ 0, 10, 0, 2],
637
+ [ 0, 0, 2, 0]])
638
+ >>> nx.to_scipy_sparse_array(G, weight="capacity").toarray()
639
+ array([[ 0, 50, 0, 0],
640
+ [50, 0, 35, 0],
641
+ [ 0, 35, 0, 10],
642
+ [ 0, 0, 10, 0]])
643
+
644
+ Any edges that don't have a `weight` attribute default to 1:
645
+
646
+ >>> G[1][2].pop("capacity")
647
+ 35
648
+ >>> nx.to_scipy_sparse_array(G, weight="capacity").toarray()
649
+ array([[ 0, 50, 0, 0],
650
+ [50, 0, 1, 0],
651
+ [ 0, 1, 0, 10],
652
+ [ 0, 0, 10, 0]])
653
+
654
+ When `G` is a multigraph, the values in the adjacency matrix are given by
655
+ the sum of the `weight` edge attribute over each edge key:
656
+
657
+ >>> G = nx.MultiDiGraph([(0, 1), (0, 1), (0, 1), (2, 0)])
658
+ >>> nx.to_scipy_sparse_array(G).toarray()
659
+ array([[0, 3, 0],
660
+ [0, 0, 0],
661
+ [1, 0, 0]])
662
+
663
+ References
664
+ ----------
665
+ .. [1] Scipy Dev. References, "Sparse Arrays",
666
+ https://docs.scipy.org/doc/scipy/reference/sparse.html
667
+ """
668
+ import scipy as sp
669
+
670
+ if len(G) == 0:
671
+ raise nx.NetworkXError("Graph has no nodes or edges")
672
+
673
+ if nodelist is None:
674
+ nodelist = list(G)
675
+ nlen = len(G)
676
+ else:
677
+ nlen = len(nodelist)
678
+ if nlen == 0:
679
+ raise nx.NetworkXError("nodelist has no nodes")
680
+ nodeset = set(G.nbunch_iter(nodelist))
681
+ if nlen != len(nodeset):
682
+ for n in nodelist:
683
+ if n not in G:
684
+ raise nx.NetworkXError(f"Node {n} in nodelist is not in G")
685
+ raise nx.NetworkXError("nodelist contains duplicates.")
686
+ if nlen < len(G):
687
+ G = G.subgraph(nodelist)
688
+
689
+ index = dict(zip(nodelist, range(nlen)))
690
+ coefficients = zip(
691
+ *((index[u], index[v], wt) for u, v, wt in G.edges(data=weight, default=1))
692
+ )
693
+ try:
694
+ row, col, data = coefficients
695
+ except ValueError:
696
+ # there is no edge in the subgraph
697
+ row, col, data = [], [], []
698
+
699
+ if G.is_directed():
700
+ A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, nlen), dtype=dtype)
701
+ else:
702
+ # symmetrize matrix
703
+ d = data + data
704
+ r = row + col
705
+ c = col + row
706
+ # selfloop entries get double counted when symmetrizing
707
+ # so we subtract the data on the diagonal
708
+ selfloops = list(nx.selfloop_edges(G, data=weight, default=1))
709
+ if selfloops:
710
+ diag_index, diag_data = zip(*((index[u], -wt) for u, v, wt in selfloops))
711
+ d += diag_data
712
+ r += diag_index
713
+ c += diag_index
714
+ A = sp.sparse.coo_array((d, (r, c)), shape=(nlen, nlen), dtype=dtype)
715
+ try:
716
+ return A.asformat(format)
717
+ except ValueError as err:
718
+ raise nx.NetworkXError(f"Unknown sparse matrix format: {format}") from err
719
+
720
+
721
+ def _csr_gen_triples(A):
722
+ """Converts a SciPy sparse array in **Compressed Sparse Row** format to
723
+ an iterable of weighted edge triples.
724
+
725
+ """
726
+ nrows = A.shape[0]
727
+ indptr, dst_indices, data = A.indptr, A.indices, A.data
728
+ import numpy as np
729
+
730
+ src_indices = np.repeat(np.arange(nrows), np.diff(indptr))
731
+ return zip(src_indices.tolist(), dst_indices.tolist(), A.data.tolist())
732
+
733
+
734
+ def _csc_gen_triples(A):
735
+ """Converts a SciPy sparse array in **Compressed Sparse Column** format to
736
+ an iterable of weighted edge triples.
737
+
738
+ """
739
+ ncols = A.shape[1]
740
+ indptr, src_indices, data = A.indptr, A.indices, A.data
741
+ import numpy as np
742
+
743
+ dst_indices = np.repeat(np.arange(ncols), np.diff(indptr))
744
+ return zip(src_indices.tolist(), dst_indices.tolist(), A.data.tolist())
745
+
746
+
747
+ def _coo_gen_triples(A):
748
+ """Converts a SciPy sparse array in **Coordinate** format to an iterable
749
+ of weighted edge triples.
750
+
751
+ """
752
+ return zip(A.row.tolist(), A.col.tolist(), A.data.tolist())
753
+
754
+
755
+ def _dok_gen_triples(A):
756
+ """Converts a SciPy sparse array in **Dictionary of Keys** format to an
757
+ iterable of weighted edge triples.
758
+
759
+ """
760
+ for (r, c), v in A.items():
761
+ # Use `v.item()` to convert a NumPy scalar to the appropriate Python scalar
762
+ yield int(r), int(c), v.item()
763
+
764
+
765
+ def _generate_weighted_edges(A):
766
+ """Returns an iterable over (u, v, w) triples, where u and v are adjacent
767
+ vertices and w is the weight of the edge joining u and v.
768
+
769
+ `A` is a SciPy sparse array (in any format).
770
+
771
+ """
772
+ if A.format == "csr":
773
+ return _csr_gen_triples(A)
774
+ if A.format == "csc":
775
+ return _csc_gen_triples(A)
776
+ if A.format == "dok":
777
+ return _dok_gen_triples(A)
778
+ # If A is in any other format (including COO), convert it to COO format.
779
+ return _coo_gen_triples(A.tocoo())
780
+
781
+
782
+ @nx._dispatchable(graphs=None, returns_graph=True)
783
+ def from_scipy_sparse_array(
784
+ A, parallel_edges=False, create_using=None, edge_attribute="weight"
785
+ ):
786
+ """Creates a new graph from an adjacency matrix given as a SciPy sparse
787
+ array.
788
+
789
+ Parameters
790
+ ----------
791
+ A: scipy.sparse array
792
+ An adjacency matrix representation of a graph
793
+
794
+ parallel_edges : Boolean
795
+ If this is True, `create_using` is a multigraph, and `A` is an
796
+ integer matrix, then entry *(i, j)* in the matrix is interpreted as the
797
+ number of parallel edges joining vertices *i* and *j* in the graph.
798
+ If it is False, then the entries in the matrix are interpreted as
799
+ the weight of a single edge joining the vertices.
800
+
801
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
802
+ Graph type to create. If graph instance, then cleared before populated.
803
+
804
+ edge_attribute: string
805
+ Name of edge attribute to store matrix numeric value. The data will
806
+ have the same type as the matrix entry (int, float, (real,imag)).
807
+
808
+ Notes
809
+ -----
810
+ The edges are generated from the explicitly stored entries of the sparse
811
+ array, including explicitly stored zero entries. If the sparse array
812
+ contains explicit zeros that should not be treated as edges, call
813
+ ``A.eliminate_zeros()`` before passing the array to this function.
814
+
815
+ For directed graphs, explicitly mention create_using=nx.DiGraph,
816
+ and entry i,j of A corresponds to an edge from i to j.
817
+
818
+ If `create_using` is :class:`networkx.MultiGraph` or
819
+ :class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the
820
+ entries of `A` are of type :class:`int`, then this function returns a
821
+ multigraph (constructed from `create_using`) with parallel edges.
822
+ In this case, `edge_attribute` will be ignored.
823
+
824
+ If `create_using` indicates an undirected multigraph, then only the edges
825
+ indicated by the upper triangle of the matrix `A` will be added to the
826
+ graph.
827
+
828
+ Examples
829
+ --------
830
+ >>> import scipy as sp
831
+ >>> A = sp.sparse.eye_array(2, 2, k=1)
832
+ >>> G = nx.from_scipy_sparse_array(A)
833
+
834
+ If `create_using` indicates a multigraph and the matrix has only integer
835
+ entries and `parallel_edges` is False, then the entries will be treated
836
+ as weights for edges joining the nodes (without creating parallel edges):
837
+
838
+ >>> A = sp.sparse.csr_array([[1, 1], [1, 2]])
839
+ >>> G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph)
840
+ >>> G[1][1]
841
+ AtlasView({0: {'weight': 2}})
842
+
843
+ If `create_using` indicates a multigraph and the matrix has only integer
844
+ entries and `parallel_edges` is True, then the entries will be treated
845
+ as the number of parallel edges joining those two vertices:
846
+
847
+ >>> A = sp.sparse.csr_array([[1, 1], [1, 2]])
848
+ >>> G = nx.from_scipy_sparse_array(
849
+ ... A, parallel_edges=True, create_using=nx.MultiGraph
850
+ ... )
851
+ >>> G[1][1]
852
+ AtlasView({0: {'weight': 1}, 1: {'weight': 1}})
853
+
854
+ """
855
+ G = nx.empty_graph(0, create_using)
856
+ n, m = A.shape
857
+ if n != m:
858
+ raise nx.NetworkXError(f"Adjacency matrix not square: nx,ny={A.shape}")
859
+ # Make sure we get even the isolated nodes of the graph.
860
+ G.add_nodes_from(range(n))
861
+ # Create an iterable over (u, v, w) triples and for each triple, add an
862
+ # edge from u to v with weight w.
863
+ triples = _generate_weighted_edges(A)
864
+ # If the entries in the adjacency matrix are integers, the graph is a
865
+ # multigraph, and parallel_edges is True, then create parallel edges, each
866
+ # with weight 1, for each entry in the adjacency matrix. Otherwise, create
867
+ # one edge for each positive entry in the adjacency matrix and set the
868
+ # weight of that edge to be the entry in the matrix.
869
+ if A.dtype.kind in ("i", "u") and G.is_multigraph() and parallel_edges:
870
+ chain = itertools.chain.from_iterable
871
+ # The following line is equivalent to:
872
+ #
873
+ # for (u, v) in edges:
874
+ # for d in range(A[u, v]):
875
+ # G.add_edge(u, v, weight=1)
876
+ #
877
+ triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
878
+ # If we are creating an undirected multigraph, only add the edges from the
879
+ # upper triangle of the matrix. Otherwise, add all the edges. This relies
880
+ # on the fact that the vertices created in the
881
+ # `_generated_weighted_edges()` function are actually the row/column
882
+ # indices for the matrix `A`.
883
+ #
884
+ # Without this check, we run into a problem where each edge is added twice
885
+ # when `G.add_weighted_edges_from()` is invoked below.
886
+ if G.is_multigraph() and not G.is_directed():
887
+ triples = ((u, v, d) for u, v, d in triples if u <= v)
888
+ G.add_weighted_edges_from(triples, weight=edge_attribute)
889
+ return G
890
+
891
+
892
+ @nx._dispatchable(edge_attrs="weight") # edge attrs may also be obtained from `dtype`
893
+ def to_numpy_array(
894
+ G,
895
+ nodelist=None,
896
+ dtype=None,
897
+ order=None,
898
+ multigraph_weight=sum,
899
+ weight="weight",
900
+ nonedge=0.0,
901
+ ):
902
+ """Returns the graph adjacency matrix as a NumPy array.
903
+
904
+ Parameters
905
+ ----------
906
+ G : graph
907
+ The NetworkX graph used to construct the NumPy array.
908
+
909
+ nodelist : list, optional
910
+ The rows and columns are ordered according to the nodes in `nodelist`.
911
+ If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``.
912
+
913
+ dtype : NumPy data type, optional
914
+ A NumPy data type used to initialize the array. If None, then the NumPy
915
+ default is used. The dtype can be structured if `weight=None`, in which
916
+ case the dtype field names are used to look up edge attributes. The
917
+ result is a structured array where each named field in the dtype
918
+ corresponds to the adjacency for that edge attribute. See examples for
919
+ details.
920
+
921
+ order : {'C', 'F'}, optional
922
+ Whether to store multidimensional data in C- or Fortran-contiguous
923
+ (row- or column-wise) order in memory. If None, then the NumPy default
924
+ is used.
925
+
926
+ multigraph_weight : callable, optional
927
+ An function that determines how weights in multigraphs are handled.
928
+ The function should accept a sequence of weights and return a single
929
+ value. The default is to sum the weights of the multiple edges.
930
+
931
+ weight : string or None optional (default = 'weight')
932
+ The edge attribute that holds the numerical value used for
933
+ the edge weight. If an edge does not have that attribute, then the
934
+ value 1 is used instead. `weight` must be ``None`` if a structured
935
+ dtype is used.
936
+
937
+ nonedge : array_like (default = 0.0)
938
+ The value used to represent non-edges in the adjacency matrix.
939
+ The array values corresponding to nonedges are typically set to zero.
940
+ However, this could be undesirable if there are array values
941
+ corresponding to actual edges that also have the value zero. If so,
942
+ one might prefer nonedges to have some other value, such as ``nan``.
943
+
944
+ Returns
945
+ -------
946
+ A : NumPy ndarray
947
+ Graph adjacency matrix
948
+
949
+ Raises
950
+ ------
951
+ NetworkXError
952
+ If `dtype` is a structured dtype and `G` is a multigraph
953
+ ValueError
954
+ If `dtype` is a structured dtype and `weight` is not `None`
955
+
956
+ See Also
957
+ --------
958
+ from_numpy_array
959
+
960
+ Notes
961
+ -----
962
+ For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
963
+
964
+ Entries in the adjacency matrix are given by the `weight` edge attribute.
965
+ When an edge does not have a weight attribute, the value of the entry is
966
+ set to the number 1. For multiple (parallel) edges, the values of the
967
+ entries are determined by the `multigraph_weight` parameter. The default is
968
+ to sum the weight attributes for each of the parallel edges.
969
+
970
+ When `nodelist` does not contain every node in `G`, the adjacency matrix is
971
+ built from the subgraph of `G` that is induced by the nodes in `nodelist`.
972
+
973
+ The convention used for self-loop edges in graphs is to assign the
974
+ diagonal array entry value to the weight attribute of the edge
975
+ (or the number 1 if the edge has no weight attribute). If the
976
+ alternate convention of doubling the edge weight is desired the
977
+ resulting NumPy array can be modified as follows:
978
+
979
+ >>> import numpy as np
980
+ >>> G = nx.Graph([(1, 1)])
981
+ >>> A = nx.to_numpy_array(G)
982
+ >>> A
983
+ array([[1.]])
984
+ >>> A[np.diag_indices_from(A)] *= 2
985
+ >>> A
986
+ array([[2.]])
987
+
988
+ Examples
989
+ --------
990
+ >>> G = nx.MultiDiGraph()
991
+ >>> G.add_edge(0, 1, weight=2)
992
+ 0
993
+ >>> G.add_edge(1, 0)
994
+ 0
995
+ >>> G.add_edge(2, 2, weight=3)
996
+ 0
997
+ >>> G.add_edge(2, 2)
998
+ 1
999
+ >>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
1000
+ array([[0., 2., 0.],
1001
+ [1., 0., 0.],
1002
+ [0., 0., 4.]])
1003
+
1004
+ When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist`
1005
+ and their edges are not included in the adjacency matrix. Here is an example:
1006
+
1007
+ >>> G = nx.Graph()
1008
+ >>> G.add_edge(3, 1)
1009
+ >>> G.add_edge(2, 0)
1010
+ >>> G.add_edge(2, 1)
1011
+ >>> G.add_edge(3, 0)
1012
+ >>> nx.to_numpy_array(G, nodelist=[1, 2, 3])
1013
+ array([[0., 1., 1.],
1014
+ [1., 0., 0.],
1015
+ [1., 0., 0.]])
1016
+
1017
+ This function can also be used to create adjacency matrices for multiple
1018
+ edge attributes with structured dtypes:
1019
+
1020
+ >>> G = nx.Graph()
1021
+ >>> G.add_edge(0, 1, weight=10)
1022
+ >>> G.add_edge(1, 2, cost=5)
1023
+ >>> G.add_edge(2, 3, weight=3, cost=-4.0)
1024
+ >>> dtype = np.dtype([("weight", int), ("cost", float)])
1025
+ >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None)
1026
+ >>> A["weight"]
1027
+ array([[ 0, 10, 0, 0],
1028
+ [10, 0, 1, 0],
1029
+ [ 0, 1, 0, 3],
1030
+ [ 0, 0, 3, 0]])
1031
+ >>> A["cost"]
1032
+ array([[ 0., 1., 0., 0.],
1033
+ [ 1., 0., 5., 0.],
1034
+ [ 0., 5., 0., -4.],
1035
+ [ 0., 0., -4., 0.]])
1036
+
1037
+ As stated above, the argument "nonedge" is useful especially when there are
1038
+ actually edges with weight 0 in the graph. Setting a nonedge value different than 0,
1039
+ makes it much clearer to differentiate such 0-weighted edges and actual nonedge values.
1040
+
1041
+ >>> G = nx.Graph()
1042
+ >>> G.add_edge(3, 1, weight=2)
1043
+ >>> G.add_edge(2, 0, weight=0)
1044
+ >>> G.add_edge(2, 1, weight=0)
1045
+ >>> G.add_edge(3, 0, weight=1)
1046
+ >>> nx.to_numpy_array(G, nonedge=-1.0)
1047
+ array([[-1., 2., -1., 1.],
1048
+ [ 2., -1., 0., -1.],
1049
+ [-1., 0., -1., 0.],
1050
+ [ 1., -1., 0., -1.]])
1051
+ """
1052
+ import numpy as np
1053
+
1054
+ if nodelist is None:
1055
+ nodelist = list(G)
1056
+ nlen = len(nodelist)
1057
+
1058
+ # Input validation
1059
+ nodeset = set(nodelist)
1060
+ if nodeset - set(G):
1061
+ raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G")
1062
+ if len(nodeset) < nlen:
1063
+ raise nx.NetworkXError("nodelist contains duplicates.")
1064
+
1065
+ A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order)
1066
+
1067
+ # Corner cases: empty nodelist or graph without any edges
1068
+ if nlen == 0 or G.number_of_edges() == 0:
1069
+ return A
1070
+
1071
+ # If dtype is structured and weight is None, use dtype field names as
1072
+ # edge attributes
1073
+ edge_attrs = None # Only single edge attribute by default
1074
+ if A.dtype.names:
1075
+ if weight is None:
1076
+ edge_attrs = dtype.names
1077
+ else:
1078
+ raise ValueError(
1079
+ "Specifying `weight` not supported for structured dtypes\n."
1080
+ "To create adjacency matrices from structured dtypes, use `weight=None`."
1081
+ )
1082
+
1083
+ # Map nodes to row/col in matrix
1084
+ idx = dict(zip(nodelist, range(nlen)))
1085
+ if len(nodelist) < len(G):
1086
+ G = G.subgraph(nodelist).copy()
1087
+
1088
+ # Collect all edge weights and reduce with `multigraph_weights`
1089
+ if G.is_multigraph():
1090
+ if edge_attrs:
1091
+ raise nx.NetworkXError(
1092
+ "Structured arrays are not supported for MultiGraphs"
1093
+ )
1094
+ d = defaultdict(list)
1095
+ for u, v, wt in G.edges(data=weight, default=1.0):
1096
+ d[(idx[u], idx[v])].append(wt)
1097
+ i, j = np.array(list(d.keys())).T # indices
1098
+ wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights
1099
+ else:
1100
+ i, j, wts = [], [], []
1101
+
1102
+ # Special branch: multi-attr adjacency from structured dtypes
1103
+ if edge_attrs:
1104
+ # Extract edges with all data
1105
+ for u, v, data in G.edges(data=True):
1106
+ i.append(idx[u])
1107
+ j.append(idx[v])
1108
+ wts.append(data)
1109
+ # Map each attribute to the appropriate named field in the
1110
+ # structured dtype
1111
+ for attr in edge_attrs:
1112
+ attr_data = [wt.get(attr, 1.0) for wt in wts]
1113
+ A[attr][i, j] = attr_data
1114
+ if not G.is_directed():
1115
+ A[attr][j, i] = attr_data
1116
+ return A
1117
+
1118
+ for u, v, wt in G.edges(data=weight, default=1.0):
1119
+ i.append(idx[u])
1120
+ j.append(idx[v])
1121
+ wts.append(wt)
1122
+
1123
+ # Set array values with advanced indexing
1124
+ A[i, j] = wts
1125
+ if not G.is_directed():
1126
+ A[j, i] = wts
1127
+
1128
+ return A
1129
+
1130
+
1131
+ @nx._dispatchable(graphs=None, returns_graph=True)
1132
+ def from_numpy_array(
1133
+ A,
1134
+ parallel_edges=False,
1135
+ create_using=None,
1136
+ edge_attr="weight",
1137
+ *,
1138
+ nodelist=None,
1139
+ nonedge=0,
1140
+ ):
1141
+ """Returns a graph from a 2D NumPy array.
1142
+
1143
+ The 2D NumPy array is interpreted as an adjacency matrix for the graph.
1144
+
1145
+ Parameters
1146
+ ----------
1147
+ A : a 2D numpy.ndarray
1148
+ An adjacency matrix representation of a graph
1149
+
1150
+ parallel_edges : Boolean
1151
+ If this is True, `create_using` is a multigraph, and `A` is an
1152
+ integer array, then entry *(i, j)* in the array is interpreted as the
1153
+ number of parallel edges joining vertices *i* and *j* in the graph.
1154
+ If it is False, then the entries in the array are interpreted as
1155
+ the weight of a single edge joining the vertices.
1156
+
1157
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
1158
+ Graph type to create. If graph instance, then cleared before populated.
1159
+
1160
+ edge_attr : String, optional (default="weight")
1161
+ The attribute to which the array values are assigned on each edge. If
1162
+ it is None, edge attributes will not be assigned.
1163
+
1164
+ nodelist : sequence of nodes, optional
1165
+ A sequence of objects to use as the nodes in the graph. If provided, the
1166
+ list of nodes must be the same length as the dimensions of `A`. The
1167
+ default is `None`, in which case the nodes are drawn from ``range(n)``.
1168
+
1169
+ nonedge : array_like (default = 0)
1170
+ The value used to represent non-edges in the adjacency matrix. Entries
1171
+ in `A` equal to this value will not be added as edges. If the array has
1172
+ a numeric dtype, the default non-edge value is ``0``, which means
1173
+ entries with value ``0`` are not treated as edges. To create edges with
1174
+ weight ``0``, use a different sentinel (e.g. ``nan``).
1175
+
1176
+ Notes
1177
+ -----
1178
+ For directed graphs, explicitly mention create_using=nx.DiGraph,
1179
+ and entry i,j of A corresponds to an edge from i to j.
1180
+
1181
+ If `create_using` is :class:`networkx.MultiGraph` or
1182
+ :class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the
1183
+ entries of `A` are of type :class:`int`, then this function returns a
1184
+ multigraph (of the same type as `create_using`) with parallel edges.
1185
+
1186
+ If `create_using` indicates an undirected multigraph, then only the edges
1187
+ indicated by the upper triangle of the array `A` will be added to the
1188
+ graph.
1189
+
1190
+ If `edge_attr` is Falsy (False or None), edge attributes will not be
1191
+ assigned, and the array data will be treated like a binary mask of
1192
+ edge presence or absence. Otherwise, the attributes will be assigned
1193
+ as follows:
1194
+
1195
+ If the NumPy array has a single data type for each array entry it
1196
+ will be converted to an appropriate Python data type.
1197
+
1198
+ If the NumPy array has a user-specified compound data type the names
1199
+ of the data fields will be used as attribute keys in the resulting
1200
+ NetworkX graph.
1201
+
1202
+ See Also
1203
+ --------
1204
+ to_numpy_array
1205
+
1206
+ Examples
1207
+ --------
1208
+ Simple integer weights on edges:
1209
+
1210
+ >>> import numpy as np
1211
+ >>> A = np.array([[1, 1], [2, 1]])
1212
+ >>> G = nx.from_numpy_array(A)
1213
+ >>> G.edges(data=True)
1214
+ EdgeDataView([(0, 0, {'weight': 1}), (0, 1, {'weight': 2}), (1, 1, {'weight': 1})])
1215
+
1216
+ If `create_using` indicates a multigraph and the array has only integer
1217
+ entries and `parallel_edges` is False, then the entries will be treated
1218
+ as weights for edges joining the nodes (without creating parallel edges):
1219
+
1220
+ >>> A = np.array([[1, 1], [1, 2]])
1221
+ >>> G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
1222
+ >>> G[1][1]
1223
+ AtlasView({0: {'weight': 2}})
1224
+
1225
+ If `create_using` indicates a multigraph and the array has only integer
1226
+ entries and `parallel_edges` is True, then the entries will be treated
1227
+ as the number of parallel edges joining those two vertices:
1228
+
1229
+ >>> A = np.array([[1, 1], [1, 2]])
1230
+ >>> temp = nx.MultiGraph()
1231
+ >>> G = nx.from_numpy_array(A, parallel_edges=True, create_using=temp)
1232
+ >>> G[1][1]
1233
+ AtlasView({0: {'weight': 1}, 1: {'weight': 1}})
1234
+
1235
+ Using ``nan`` as the nonedge sentinel allows zero-weight edges:
1236
+
1237
+ >>> A = np.array([[np.nan, 0.0], [0.0, np.nan]])
1238
+ >>> G = nx.from_numpy_array(A, nonedge=np.nan)
1239
+ >>> sorted(G.edges(data=True))
1240
+ [(0, 1, {'weight': 0.0})]
1241
+
1242
+ User defined compound data type on edges:
1243
+
1244
+ >>> dt = [("weight", float), ("cost", int)]
1245
+ >>> A = np.array([[(1.0, 2)]], dtype=dt)
1246
+ >>> G = nx.from_numpy_array(A)
1247
+ >>> G.edges()
1248
+ EdgeView([(0, 0)])
1249
+ >>> G[0][0]["cost"]
1250
+ 2
1251
+ >>> G[0][0]["weight"]
1252
+ 1.0
1253
+
1254
+ """
1255
+ kind_to_python_type = {
1256
+ "f": float,
1257
+ "i": int,
1258
+ "u": int,
1259
+ "b": bool,
1260
+ "c": complex,
1261
+ "S": str,
1262
+ "U": str,
1263
+ "V": "void",
1264
+ }
1265
+ G = nx.empty_graph(0, create_using)
1266
+ if A.ndim != 2:
1267
+ raise nx.NetworkXError(f"Input array must be 2D, not {A.ndim}")
1268
+ n, m = A.shape
1269
+ if n != m:
1270
+ raise nx.NetworkXError(f"Adjacency matrix not square: nx,ny={A.shape}")
1271
+ dt = A.dtype
1272
+ try:
1273
+ python_type = kind_to_python_type[dt.kind]
1274
+ except Exception as err:
1275
+ raise TypeError(f"Unknown numpy data type: {dt}") from err
1276
+ if _default_nodes := (nodelist is None):
1277
+ nodelist = range(n)
1278
+ else:
1279
+ if len(nodelist) != n:
1280
+ raise ValueError("nodelist must have the same length as A.shape[0]")
1281
+
1282
+ # Make sure we get even the isolated nodes of the graph.
1283
+ G.add_nodes_from(nodelist)
1284
+ # Get a list of all the entries in the array with nonzero entries which are not equal
1285
+ # to the nonedge sentinel. These coordinates become edges in the graph. (convert to int from np.int64)
1286
+ if python_type == "void":
1287
+ edges = ((int(e[0]), int(e[1])) for e in zip(*A.nonzero()))
1288
+ elif nonedge != nonedge: # to check if nonedge is nan
1289
+ edges = ((int(e[0]), int(e[1])) for e in zip(*(A == A).nonzero()))
1290
+ else:
1291
+ edges = ((int(e[0]), int(e[1])) for e in zip(*(A != nonedge).nonzero()))
1292
+ # Handle numpy constructed data type
1293
+ if python_type == "void":
1294
+ # Sort the fields by their offset, then by dtype, then by name.
1295
+ fields = sorted(
1296
+ (offset, dtype, name) for name, (dtype, offset) in A.dtype.fields.items()
1297
+ )
1298
+ triples = (
1299
+ (
1300
+ u,
1301
+ v,
1302
+ {}
1303
+ if edge_attr in [False, None]
1304
+ else {
1305
+ name: kind_to_python_type[dtype.kind](val)
1306
+ for (_, dtype, name), val in zip(fields, A[u, v])
1307
+ },
1308
+ )
1309
+ for u, v in edges
1310
+ )
1311
+ # If the entries in the adjacency matrix are integers, the graph is a
1312
+ # multigraph, and parallel_edges is True, then create parallel edges, each
1313
+ # with weight 1, for each entry in the adjacency matrix. Otherwise, create
1314
+ # one edge for each positive entry in the adjacency matrix and set the
1315
+ # weight of that edge to be the entry in the matrix.
1316
+ elif python_type is int and G.is_multigraph() and parallel_edges:
1317
+ chain = itertools.chain.from_iterable
1318
+ # The following line is equivalent to:
1319
+ #
1320
+ # for (u, v) in edges:
1321
+ # for d in range(A[u, v]):
1322
+ # G.add_edge(u, v, weight=1)
1323
+ #
1324
+ if edge_attr in [False, None]:
1325
+ triples = chain(((u, v, {}) for d in range(A[u, v])) for (u, v) in edges)
1326
+ else:
1327
+ triples = chain(
1328
+ ((u, v, {edge_attr: 1}) for d in range(A[u, v])) for (u, v) in edges
1329
+ )
1330
+ else: # basic data type
1331
+ if edge_attr in [False, None]:
1332
+ triples = ((u, v, {}) for u, v in edges)
1333
+ else:
1334
+ triples = ((u, v, {edge_attr: python_type(A[u, v])}) for u, v in edges)
1335
+ # If we are creating an undirected multigraph, only add the edges from the
1336
+ # upper triangle of the matrix. Otherwise, add all the edges. This relies
1337
+ # on the fact that the vertices created in the
1338
+ # `_generated_weighted_edges()` function are actually the row/column
1339
+ # indices for the matrix `A`.
1340
+ #
1341
+ # Without this check, we run into a problem where each edge is added twice
1342
+ # when `G.add_edges_from()` is invoked below.
1343
+ if G.is_multigraph() and not G.is_directed():
1344
+ triples = ((u, v, d) for u, v, d in triples if u <= v)
1345
+ # Remap nodes if user provided custom `nodelist`
1346
+ if not _default_nodes:
1347
+ idx_to_node = dict(enumerate(nodelist))
1348
+ triples = ((idx_to_node[u], idx_to_node[v], d) for u, v, d in triples)
1349
+ G.add_edges_from(triples)
1350
+ return G
venv/lib/python3.14/site-packages/networkx/drawing/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # graph drawing and interface to graphviz
2
+
3
+ from .layout import *
4
+ from .nx_latex import *
5
+ from .nx_pylab import *
6
+ from . import nx_agraph
7
+ from . import nx_pydot
venv/lib/python3.14/site-packages/networkx/drawing/layout.py ADDED
@@ -0,0 +1,2041 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ******
3
+ Layout
4
+ ******
5
+
6
+ Node positioning algorithms for graph drawing.
7
+
8
+ For `random_layout()` the possible resulting shape
9
+ is a square of side [0, scale] (default: [0, 1])
10
+ Changing `center` shifts the layout by that amount.
11
+
12
+ For the other layout routines, the extent is
13
+ [center - scale, center + scale] (default: [-1, 1]).
14
+
15
+ Warning: Most layout routines have only been tested in 2-dimensions.
16
+
17
+ """
18
+
19
+ import networkx as nx
20
+ from networkx.utils import np_random_state
21
+
22
+ __all__ = [
23
+ "bipartite_layout",
24
+ "circular_layout",
25
+ "forceatlas2_layout",
26
+ "kamada_kawai_layout",
27
+ "random_layout",
28
+ "rescale_layout",
29
+ "rescale_layout_dict",
30
+ "shell_layout",
31
+ "spring_layout",
32
+ "spectral_layout",
33
+ "planar_layout",
34
+ "fruchterman_reingold_layout",
35
+ "spiral_layout",
36
+ "multipartite_layout",
37
+ "bfs_layout",
38
+ "arf_layout",
39
+ ]
40
+
41
+
42
+ def _process_params(G, center, dim):
43
+ # Some boilerplate code.
44
+ import numpy as np
45
+
46
+ if not isinstance(G, nx.Graph):
47
+ empty_graph = nx.Graph()
48
+ empty_graph.add_nodes_from(G)
49
+ G = empty_graph
50
+
51
+ if center is None:
52
+ center = np.zeros(dim)
53
+ else:
54
+ center = np.asarray(center)
55
+
56
+ if len(center) != dim:
57
+ msg = "length of center coordinates must match dimension of layout"
58
+ raise ValueError(msg)
59
+
60
+ return G, center
61
+
62
+
63
+ @np_random_state(3)
64
+ def random_layout(G, center=None, dim=2, seed=None, store_pos_as=None):
65
+ """Position nodes uniformly at random in the unit square.
66
+
67
+ For every node, a position is generated by choosing each of dim
68
+ coordinates uniformly at random on the interval [0.0, 1.0).
69
+
70
+ NumPy (http://scipy.org) is required for this function.
71
+
72
+ Parameters
73
+ ----------
74
+ G : NetworkX graph or list of nodes
75
+ A position will be assigned to every node in G.
76
+
77
+ center : array-like or None
78
+ Coordinate pair around which to center the layout.
79
+
80
+ dim : int
81
+ Dimension of layout.
82
+
83
+ seed : int, RandomState instance or None optional (default=None)
84
+ Set the random state for deterministic node layouts.
85
+ If int, `seed` is the seed used by the random number generator,
86
+ if numpy.random.RandomState instance, `seed` is the random
87
+ number generator,
88
+ if None, the random number generator is the RandomState instance used
89
+ by numpy.random.
90
+
91
+ store_pos_as : str, default None
92
+ If non-None, the position of each node will be stored on the graph as
93
+ an attribute with this string as its name, which can be accessed with
94
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
95
+
96
+ Returns
97
+ -------
98
+ pos : dict
99
+ A dictionary of positions keyed by node
100
+
101
+ Examples
102
+ --------
103
+ >>> from pprint import pprint
104
+ >>> G = nx.lollipop_graph(4, 3)
105
+ >>> pos = nx.random_layout(G)
106
+ >>> # suppress the returned dict and store on the graph directly
107
+ >>> _ = nx.random_layout(G, seed=42, store_pos_as="pos")
108
+ >>> pprint(nx.get_node_attributes(G, "pos"))
109
+ {0: array([0.37454012, 0.9507143 ], dtype=float32),
110
+ 1: array([0.7319939, 0.5986585], dtype=float32),
111
+ 2: array([0.15601864, 0.15599452], dtype=float32),
112
+ 3: array([0.05808361, 0.8661761 ], dtype=float32),
113
+ 4: array([0.601115 , 0.7080726], dtype=float32),
114
+ 5: array([0.02058449, 0.96990985], dtype=float32),
115
+ 6: array([0.83244264, 0.21233912], dtype=float32)}
116
+ """
117
+ import numpy as np
118
+
119
+ G, center = _process_params(G, center, dim)
120
+ pos = seed.rand(len(G), dim) + center
121
+ pos = pos.astype(np.float32)
122
+ pos = dict(zip(G, pos))
123
+
124
+ if store_pos_as is not None:
125
+ nx.set_node_attributes(G, pos, store_pos_as)
126
+ return pos
127
+
128
+
129
+ def circular_layout(G, scale=1, center=None, dim=2, store_pos_as=None):
130
+ # dim=2 only
131
+ """Position nodes on a circle.
132
+
133
+ Parameters
134
+ ----------
135
+ G : NetworkX graph or list of nodes
136
+ A position will be assigned to every node in G.
137
+
138
+ scale : number (default: 1)
139
+ Scale factor for positions.
140
+
141
+ center : array-like or None
142
+ Coordinate pair around which to center the layout.
143
+
144
+ dim : int
145
+ Dimension of layout.
146
+ If dim>2, the remaining dimensions are set to zero
147
+ in the returned positions.
148
+ If dim<2, a ValueError is raised.
149
+
150
+ store_pos_as : str, default None
151
+ If non-None, the position of each node will be stored on the graph as
152
+ an attribute with this string as its name, which can be accessed with
153
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
154
+
155
+ Returns
156
+ -------
157
+ pos : dict
158
+ A dictionary of positions keyed by node
159
+
160
+ Raises
161
+ ------
162
+ ValueError
163
+ If dim < 2
164
+
165
+ Examples
166
+ --------
167
+ >>> from pprint import pprint
168
+ >>> G = nx.path_graph(4)
169
+ >>> pos = nx.circular_layout(G)
170
+ >>> # suppress the returned dict and store on the graph directly
171
+ >>> _ = nx.circular_layout(G, store_pos_as="pos")
172
+ >>> pprint(nx.get_node_attributes(G, "pos"))
173
+ {0: array([9.99999986e-01, 2.18556937e-08]),
174
+ 1: array([-3.57647606e-08, 1.00000000e+00]),
175
+ 2: array([-9.9999997e-01, -6.5567081e-08]),
176
+ 3: array([ 1.98715071e-08, -9.99999956e-01])}
177
+
178
+
179
+ Notes
180
+ -----
181
+ This algorithm currently only works in two dimensions and does not
182
+ try to minimize edge crossings.
183
+
184
+ """
185
+ import numpy as np
186
+
187
+ if dim < 2:
188
+ raise ValueError("cannot handle dimensions < 2")
189
+
190
+ G, center = _process_params(G, center, dim)
191
+
192
+ paddims = max(0, (dim - 2))
193
+
194
+ if len(G) == 0:
195
+ pos = {}
196
+ elif len(G) == 1:
197
+ pos = {nx.utils.arbitrary_element(G): center}
198
+ else:
199
+ # Discard the extra angle since it matches 0 radians.
200
+ theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
201
+ theta = theta.astype(np.float32)
202
+ pos = np.column_stack(
203
+ [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
204
+ )
205
+ pos = rescale_layout(pos, scale=scale) + center
206
+ pos = dict(zip(G, pos))
207
+
208
+ if store_pos_as is not None:
209
+ nx.set_node_attributes(G, pos, store_pos_as)
210
+
211
+ return pos
212
+
213
+
214
+ def shell_layout(
215
+ G, nlist=None, rotate=None, scale=1, center=None, dim=2, store_pos_as=None
216
+ ):
217
+ """Position nodes in concentric circles.
218
+
219
+ Parameters
220
+ ----------
221
+ G : NetworkX graph or list of nodes
222
+ A position will be assigned to every node in G.
223
+
224
+ nlist : list of lists
225
+ List of node lists for each shell.
226
+
227
+ rotate : angle in radians (default=pi/len(nlist))
228
+ Angle by which to rotate the starting position of each shell
229
+ relative to the starting position of the previous shell.
230
+ To recreate behavior before v2.5 use rotate=0.
231
+
232
+ scale : number (default: 1)
233
+ Scale factor for positions.
234
+
235
+ center : array-like or None
236
+ Coordinate pair around which to center the layout.
237
+
238
+ dim : int
239
+ Dimension of layout, currently only dim=2 is supported.
240
+ Other dimension values result in a ValueError.
241
+
242
+ store_pos_as : str, default None
243
+ If non-None, the position of each node will be stored on the graph as
244
+ an attribute with this string as its name, which can be accessed with
245
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
246
+
247
+ Returns
248
+ -------
249
+ pos : dict
250
+ A dictionary of positions keyed by node
251
+
252
+ Raises
253
+ ------
254
+ ValueError
255
+ If dim != 2
256
+
257
+ Examples
258
+ --------
259
+ >>> from pprint import pprint
260
+ >>> G = nx.path_graph(4)
261
+ >>> shells = [[0], [1, 2, 3]]
262
+ >>> pos = nx.shell_layout(G, shells)
263
+ >>> # suppress the returned dict and store on the graph directly
264
+ >>> _ = nx.shell_layout(G, shells, store_pos_as="pos")
265
+ >>> pprint(nx.get_node_attributes(G, "pos"))
266
+ {0: array([0., 0.]),
267
+ 1: array([-5.00000000e-01, -4.37113883e-08]),
268
+ 2: array([ 0.24999996, -0.43301272]),
269
+ 3: array([0.24999981, 0.43301281])}
270
+
271
+ Notes
272
+ -----
273
+ This algorithm currently only works in two dimensions and does not
274
+ try to minimize edge crossings.
275
+
276
+ """
277
+ import numpy as np
278
+
279
+ if dim != 2:
280
+ raise ValueError("can only handle 2 dimensions")
281
+
282
+ G, center = _process_params(G, center, dim)
283
+
284
+ if len(G) == 0:
285
+ return {}
286
+ if len(G) == 1:
287
+ return {nx.utils.arbitrary_element(G): center}
288
+
289
+ if nlist is None:
290
+ # draw the whole graph in one shell
291
+ nlist = [list(G)]
292
+
293
+ radius_bump = scale / len(nlist)
294
+
295
+ if len(nlist[0]) == 1:
296
+ # single node at center
297
+ radius = 0.0
298
+ else:
299
+ # else start at r=1
300
+ radius = radius_bump
301
+
302
+ if rotate is None:
303
+ rotate = np.pi / len(nlist)
304
+ first_theta = rotate
305
+ npos = {}
306
+ for nodes in nlist:
307
+ # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
308
+ theta = (
309
+ np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
310
+ + first_theta
311
+ )
312
+ pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
313
+ npos.update(zip(nodes, pos))
314
+ radius += radius_bump
315
+ first_theta += rotate
316
+
317
+ if store_pos_as is not None:
318
+ nx.set_node_attributes(G, npos, store_pos_as)
319
+ return npos
320
+
321
+
322
+ def bipartite_layout(
323
+ G,
324
+ nodes=None,
325
+ align="vertical",
326
+ scale=1,
327
+ center=None,
328
+ aspect_ratio=4 / 3,
329
+ store_pos_as=None,
330
+ ):
331
+ """Position nodes in two straight lines.
332
+
333
+ Parameters
334
+ ----------
335
+ G : NetworkX graph or list of nodes
336
+ A position will be assigned to every node in G.
337
+
338
+ nodes : collection of nodes
339
+ Nodes in one node set of the graph. This set will be placed on
340
+ left or top. If `None` (the default), a node set is chosen arbitrarily
341
+ if the graph if bipartite.
342
+
343
+ align : string (default='vertical')
344
+ The alignment of nodes. Vertical or horizontal.
345
+
346
+ scale : number (default: 1)
347
+ Scale factor for positions.
348
+
349
+ center : array-like or None
350
+ Coordinate pair around which to center the layout.
351
+
352
+ aspect_ratio : number (default=4/3):
353
+ The ratio of the width to the height of the layout.
354
+
355
+ store_pos_as : str, default None
356
+ If non-None, the position of each node will be stored on the graph as
357
+ an attribute with this string as its name, which can be accessed with
358
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
359
+
360
+ Returns
361
+ -------
362
+ pos : dict
363
+ A dictionary of positions keyed by node.
364
+
365
+ Raises
366
+ ------
367
+ NetworkXError
368
+ If ``nodes=None`` and `G` is not bipartite.
369
+
370
+ Examples
371
+ --------
372
+ >>> G = nx.complete_bipartite_graph(3, 3)
373
+ >>> pos = nx.bipartite_layout(G)
374
+
375
+ The ordering of the layout (i.e. which nodes appear on the left/top) can
376
+ be specified with the `nodes` parameter:
377
+
378
+ >>> top, bottom = nx.bipartite.sets(G)
379
+ >>> pos = nx.bipartite_layout(G, nodes=bottom) # "bottom" set appears on the left
380
+
381
+ `store_pos_as` can be used to store the node positions for the computed layout
382
+ directly on the nodes:
383
+
384
+ >>> _ = nx.bipartite_layout(G, nodes=bottom, store_pos_as="pos")
385
+ >>> from pprint import pprint
386
+ >>> pprint(nx.get_node_attributes(G, "pos"))
387
+ {0: array([ 1. , -0.75]),
388
+ 1: array([1., 0.]),
389
+ 2: array([1. , 0.75]),
390
+ 3: array([-1. , -0.75]),
391
+ 4: array([-1., 0.]),
392
+ 5: array([-1. , 0.75])}
393
+
394
+
395
+ The ``bipartite_layout`` function can be used with non-bipartite graphs
396
+ by explicitly specifying how the layout should be partitioned with `nodes`:
397
+
398
+ >>> G = nx.complete_graph(5) # Non-bipartite
399
+ >>> pos = nx.bipartite_layout(G, nodes={0, 1, 2})
400
+
401
+ Notes
402
+ -----
403
+ This algorithm currently only works in two dimensions and does not
404
+ try to minimize edge crossings.
405
+
406
+ """
407
+
408
+ import numpy as np
409
+
410
+ if align not in ("vertical", "horizontal"):
411
+ msg = "align must be either vertical or horizontal."
412
+ raise ValueError(msg)
413
+
414
+ G, center = _process_params(G, center=center, dim=2)
415
+ if len(G) == 0:
416
+ return {}
417
+
418
+ height = 1
419
+ width = aspect_ratio * height
420
+ offset = (width / 2, height / 2)
421
+
422
+ if nodes is None:
423
+ top, bottom = nx.bipartite.sets(G)
424
+ nodes = list(G)
425
+ else:
426
+ top = set(nodes)
427
+ bottom = set(G) - top
428
+ # Preserves backward-compatible node ordering in returned pos dict
429
+ nodes = list(top) + list(bottom)
430
+
431
+ left_xs = np.repeat(0, len(top))
432
+ right_xs = np.repeat(width, len(bottom))
433
+ left_ys = np.linspace(0, height, len(top))
434
+ right_ys = np.linspace(0, height, len(bottom))
435
+
436
+ top_pos = np.column_stack([left_xs, left_ys]) - offset
437
+ bottom_pos = np.column_stack([right_xs, right_ys]) - offset
438
+
439
+ pos = np.concatenate([top_pos, bottom_pos])
440
+ pos = rescale_layout(pos, scale=scale) + center
441
+ if align == "horizontal":
442
+ pos = pos[:, ::-1] # swap x and y coords
443
+ pos = dict(zip(nodes, pos))
444
+
445
+ if store_pos_as is not None:
446
+ nx.set_node_attributes(G, pos, store_pos_as)
447
+
448
+ return pos
449
+
450
+
451
+ @np_random_state("seed")
452
+ def spring_layout(
453
+ G,
454
+ k=None,
455
+ pos=None,
456
+ fixed=None,
457
+ iterations=50,
458
+ threshold=1e-4,
459
+ weight="weight",
460
+ scale=1,
461
+ center=None,
462
+ dim=2,
463
+ seed=None,
464
+ store_pos_as=None,
465
+ *,
466
+ method="auto",
467
+ gravity=1.0,
468
+ ):
469
+ """Position nodes using Fruchterman-Reingold force-directed algorithm.
470
+
471
+ The algorithm simulates a force-directed representation of the network
472
+ treating edges as springs holding nodes close, while treating nodes
473
+ as repelling objects, sometimes called an anti-gravity force.
474
+ Simulation continues until the positions are close to an equilibrium.
475
+
476
+ There are some hard-coded values: minimal distance between
477
+ nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
478
+ During the simulation, `k` helps determine the distance between nodes,
479
+ though `scale` and `center` determine the size and place after
480
+ rescaling occurs at the end of the simulation.
481
+
482
+ Fixing some nodes doesn't allow them to move in the simulation.
483
+ It also turns off the rescaling feature at the simulation's end.
484
+ In addition, setting `scale` to `None` turns off rescaling.
485
+
486
+ Parameters
487
+ ----------
488
+ G : NetworkX graph or list of nodes
489
+ A position will be assigned to every node in G.
490
+
491
+ k : float (default=None)
492
+ Optimal distance between nodes. If None the distance is set to
493
+ 1/sqrt(n) where n is the number of nodes. Increase this value
494
+ to move nodes farther apart.
495
+
496
+ pos : dict or None optional (default=None)
497
+ Initial positions for nodes as a dictionary with node as keys
498
+ and values as a coordinate list or tuple. If None, then use
499
+ random initial positions.
500
+
501
+ fixed : list or None optional (default=None)
502
+ Nodes to keep fixed at initial position.
503
+ Nodes not in ``G.nodes`` are ignored.
504
+ ValueError raised if `fixed` specified and `pos` not.
505
+
506
+ iterations : int optional (default=50)
507
+ Maximum number of iterations taken
508
+
509
+ threshold: float optional (default = 1e-4)
510
+ Threshold for relative error in node position changes.
511
+ The iteration stops if the error is below this threshold.
512
+
513
+ weight : string or None optional (default='weight')
514
+ The edge attribute that holds the numerical value used for
515
+ the edge weight. Larger means a stronger attractive force.
516
+ If None, then all edge weights are 1.
517
+
518
+ scale : number or None (default: 1)
519
+ Scale factor for positions. Not used unless `fixed is None`.
520
+ If scale is None, no rescaling is performed.
521
+
522
+ center : array-like or None
523
+ Coordinate pair around which to center the layout.
524
+ Not used unless `fixed is None`.
525
+
526
+ dim : int
527
+ Dimension of layout.
528
+
529
+ seed : int, RandomState instance or None optional (default=None)
530
+ Used only for the initial positions in the algorithm.
531
+ Set the random state for deterministic node layouts.
532
+ If int, `seed` is the seed used by the random number generator,
533
+ if numpy.random.RandomState instance, `seed` is the random
534
+ number generator,
535
+ if None, the random number generator is the RandomState instance used
536
+ by numpy.random.
537
+
538
+ store_pos_as : str, default None
539
+ If non-None, the position of each node will be stored on the graph as
540
+ an attribute with this string as its name, which can be accessed with
541
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
542
+
543
+ method : str optional (default='auto')
544
+ The method to compute the layout.
545
+ If 'force', the force-directed Fruchterman-Reingold algorithm [1]_ is used.
546
+ If 'energy', the energy-based optimization algorithm [2]_ is used with absolute
547
+ values of edge weights and gravitational forces acting on each connected component.
548
+ If 'auto', we use 'force' if ``len(G) < 500`` and 'energy' otherwise.
549
+
550
+ gravity: float optional (default=1.0)
551
+ Used only for the method='energy'.
552
+ The positive coefficient of gravitational forces per connected component.
553
+
554
+ Returns
555
+ -------
556
+ pos : dict
557
+ A dictionary of positions keyed by node
558
+
559
+ Examples
560
+ --------
561
+ >>> from pprint import pprint
562
+ >>> G = nx.path_graph(4)
563
+ >>> pos = nx.spring_layout(G)
564
+ >>> # suppress the returned dict and store on the graph directly
565
+ >>> _ = nx.spring_layout(G, seed=123, store_pos_as="pos")
566
+ >>> pprint(nx.get_node_attributes(G, "pos"))
567
+ {0: array([-0.61495802, -1. ]),
568
+ 1: array([-0.21789544, -0.35432583]),
569
+ 2: array([0.21847843, 0.35527369]),
570
+ 3: array([0.61437502, 0.99905215])}
571
+
572
+
573
+ # The same using longer but equivalent function name
574
+ >>> pos = nx.fruchterman_reingold_layout(G)
575
+
576
+ References
577
+ ----------
578
+ .. [1] Fruchterman, Thomas MJ, and Edward M. Reingold.
579
+ "Graph drawing by force-directed placement."
580
+ Software: Practice and experience 21, no. 11 (1991): 1129-1164.
581
+ http://dx.doi.org/10.1002/spe.4380211102
582
+ .. [2] Hamaguchi, Hiroki, Naoki Marumo, and Akiko Takeda.
583
+ "Initial Placement for Fruchterman--Reingold Force Model With Coordinate Newton Direction."
584
+ arXiv preprint arXiv:2412.20317 (2024).
585
+ https://arxiv.org/abs/2412.20317
586
+ """
587
+ import numpy as np
588
+
589
+ if method not in ("auto", "force", "energy"):
590
+ raise ValueError("the method must be either auto, force, or energy.")
591
+ if method == "auto":
592
+ method = "force" if len(G) < 500 else "energy"
593
+
594
+ G, center = _process_params(G, center, dim)
595
+
596
+ if fixed is not None:
597
+ if pos is None:
598
+ raise ValueError("nodes are fixed without positions given")
599
+ for node in fixed:
600
+ if node not in pos:
601
+ raise ValueError("nodes are fixed without positions given")
602
+ nfixed = {node: i for i, node in enumerate(G)}
603
+ fixed = np.asarray(
604
+ [nfixed[node] for node in fixed if node in nfixed], dtype=int
605
+ )
606
+
607
+ if pos is not None:
608
+ # Determine size of existing domain to adjust initial positions
609
+ dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
610
+ if dom_size == 0:
611
+ dom_size = 1
612
+ pos_arr = seed.rand(len(G), dim) * dom_size + center
613
+
614
+ for i, n in enumerate(G):
615
+ if n in pos:
616
+ pos_arr[i] = np.asarray(pos[n])
617
+ else:
618
+ pos_arr = None
619
+ dom_size = 1
620
+
621
+ if len(G) == 0:
622
+ return {}
623
+ if len(G) == 1:
624
+ pos = {nx.utils.arbitrary_element(G.nodes()): center}
625
+ if store_pos_as is not None:
626
+ nx.set_node_attributes(G, pos, store_pos_as)
627
+ return pos
628
+
629
+ # Sparse matrix
630
+ if len(G) >= 500 or method == "energy":
631
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
632
+ if k is None and fixed is not None:
633
+ # We must adjust k by domain size for layouts not near 1x1
634
+ nnodes, _ = A.shape
635
+ k = dom_size / np.sqrt(nnodes)
636
+ pos = _sparse_fruchterman_reingold(
637
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed, method, gravity
638
+ )
639
+ else:
640
+ A = nx.to_numpy_array(G, weight=weight)
641
+ if k is None and fixed is not None:
642
+ # We must adjust k by domain size for layouts not near 1x1
643
+ nnodes, _ = A.shape
644
+ k = dom_size / np.sqrt(nnodes)
645
+ pos = _fruchterman_reingold(
646
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
647
+ )
648
+ if fixed is None and scale is not None:
649
+ pos = rescale_layout(pos, scale=scale) + center
650
+ pos = dict(zip(G, pos))
651
+
652
+ if store_pos_as is not None:
653
+ nx.set_node_attributes(G, pos, store_pos_as)
654
+
655
+ return pos
656
+
657
+
658
+ fruchterman_reingold_layout = spring_layout
659
+
660
+
661
+ @np_random_state(7)
662
+ def _fruchterman_reingold(
663
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
664
+ ):
665
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
666
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
667
+ import numpy as np
668
+
669
+ try:
670
+ nnodes, _ = A.shape
671
+ except AttributeError as err:
672
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
673
+ raise nx.NetworkXError(msg) from err
674
+
675
+ if pos is None:
676
+ # random initial positions
677
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
678
+ else:
679
+ # make sure positions are of same type as matrix
680
+ pos = pos.astype(A.dtype)
681
+
682
+ # optimal distance between nodes
683
+ if k is None:
684
+ k = np.sqrt(1.0 / nnodes)
685
+ # the initial "temperature" is about .1 of domain area (=1x1)
686
+ # this is the largest step allowed in the dynamics.
687
+ # We need to calculate this in case our fixed positions force our domain
688
+ # to be much bigger than 1x1
689
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
690
+ # simple cooling scheme.
691
+ # linearly step down by dt on each iteration so last iteration is size dt.
692
+ dt = t / (iterations + 1)
693
+ delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
694
+ # the inscrutable (but fast) version
695
+ # this is still O(V^2)
696
+ # could use multilevel methods to speed this up significantly
697
+ for iteration in range(iterations):
698
+ # matrix of difference between points
699
+ delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
700
+ # distance between points
701
+ distance = np.linalg.norm(delta, axis=-1)
702
+ # enforce minimum distance of 0.01
703
+ np.clip(distance, 0.01, None, out=distance)
704
+ # displacement "force"
705
+ displacement = np.einsum(
706
+ "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
707
+ )
708
+ # update positions
709
+ length = np.linalg.norm(displacement, axis=-1)
710
+ # Threshold the minimum length prior to position scaling
711
+ # See gh-8113 for detailed discussion of the threshold
712
+ length = np.clip(length, a_min=0.01, a_max=None)
713
+ delta_pos = np.einsum("ij,i->ij", displacement, t / length)
714
+ if fixed is not None:
715
+ # don't change positions of fixed nodes
716
+ delta_pos[fixed] = 0.0
717
+ pos += delta_pos
718
+ # cool temperature
719
+ t -= dt
720
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
721
+ break
722
+ return pos
723
+
724
+
725
+ @np_random_state(7)
726
+ def _sparse_fruchterman_reingold(
727
+ A,
728
+ k=None,
729
+ pos=None,
730
+ fixed=None,
731
+ iterations=50,
732
+ threshold=1e-4,
733
+ dim=2,
734
+ seed=None,
735
+ method="energy",
736
+ gravity=1.0,
737
+ ):
738
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
739
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
740
+ # Sparse version
741
+ import numpy as np
742
+ import scipy as sp
743
+
744
+ try:
745
+ nnodes, _ = A.shape
746
+ except AttributeError as err:
747
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
748
+ raise nx.NetworkXError(msg) from err
749
+
750
+ if pos is None:
751
+ # random initial positions
752
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
753
+ else:
754
+ # make sure positions are of same type as matrix
755
+ pos = pos.astype(A.dtype)
756
+
757
+ # no fixed nodes
758
+ if fixed is None:
759
+ fixed = []
760
+
761
+ # optimal distance between nodes
762
+ if k is None:
763
+ k = np.sqrt(1.0 / nnodes)
764
+
765
+ if method == "energy":
766
+ return _energy_fruchterman_reingold(
767
+ A, nnodes, k, pos, fixed, iterations, threshold, dim, gravity
768
+ )
769
+
770
+ # make sure we have a LIst of Lists representation
771
+ try:
772
+ A = A.tolil()
773
+ except AttributeError:
774
+ A = (sp.sparse.coo_array(A)).tolil()
775
+
776
+ # the initial "temperature" is about .1 of domain area (=1x1)
777
+ # this is the largest step allowed in the dynamics.
778
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
779
+ # simple cooling scheme.
780
+ # linearly step down by dt on each iteration so last iteration is size dt.
781
+ dt = t / (iterations + 1)
782
+
783
+ displacement = np.zeros((dim, nnodes))
784
+ for iteration in range(iterations):
785
+ displacement *= 0
786
+ # loop over rows
787
+ for i in range(A.shape[0]):
788
+ if i in fixed:
789
+ continue
790
+ # difference between this row's node position and all others
791
+ delta = (pos[i] - pos).T
792
+ # distance between points
793
+ distance = np.sqrt((delta**2).sum(axis=0))
794
+ # enforce minimum distance of 0.01
795
+ distance = np.clip(distance, a_min=0.01, a_max=None)
796
+ # the adjacency matrix row
797
+ Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
798
+ # displacement "force"
799
+ displacement[:, i] += (
800
+ delta * (k * k / distance**2 - Ai * distance / k)
801
+ ).sum(axis=1)
802
+ # update positions
803
+ length = np.sqrt((displacement**2).sum(axis=0))
804
+ # Threshold the minimum length prior to position scaling
805
+ # See gh-8113 for detailed discussion of the threshold
806
+ length = np.clip(length, a_min=0.01, a_max=None)
807
+ delta_pos = (displacement * t / length).T
808
+ pos += delta_pos
809
+ # cool temperature
810
+ t -= dt
811
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
812
+ break
813
+ return pos
814
+
815
+
816
+ def _energy_fruchterman_reingold(
817
+ A, nnodes, k, pos, fixed, iterations, threshold, dim, gravity
818
+ ):
819
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
820
+ # energy-based version
821
+ import numpy as np
822
+ import scipy as sp
823
+
824
+ if gravity <= 0:
825
+ raise ValueError(f"the gravity must be positive.")
826
+
827
+ # Zero iterations, return initial positions
828
+ if iterations == 0:
829
+ return pos.copy()
830
+
831
+ # make sure we have a Compressed Sparse Row format
832
+ try:
833
+ A = A.tocsr()
834
+ except AttributeError:
835
+ A = sp.sparse.csr_array(A)
836
+
837
+ # Take absolute values of edge weights and symmetrize it
838
+ A = np.abs(A)
839
+ A = (A + A.T) / 2
840
+
841
+ n_components, labels = sp.sparse.csgraph.connected_components(A, directed=False)
842
+ bincount = np.bincount(labels)
843
+ batchsize = 500
844
+
845
+ def _cost_FR(x):
846
+ pos = x.reshape((nnodes, dim))
847
+ grad = np.zeros((nnodes, dim))
848
+ cost = 0.0
849
+ for l in range(0, nnodes, batchsize):
850
+ r = min(l + batchsize, nnodes)
851
+ # difference between selected node positions and all others
852
+ delta = pos[l:r, np.newaxis, :] - pos[np.newaxis, :, :]
853
+ # distance between points with a minimum distance of 1e-5
854
+ distance2 = np.sum(delta * delta, axis=2)
855
+ distance2 = np.maximum(distance2, 1e-10)
856
+ distance = np.sqrt(distance2)
857
+ # temporary variable for calculation
858
+ Ad = A[l:r] * distance
859
+ # attractive forces and repulsive forces
860
+ grad[l:r] = 2 * np.einsum("ij,ijk->ik", Ad / k - k**2 / distance2, delta)
861
+ # integrated attractive forces
862
+ cost += np.sum(Ad * distance2) / (3 * k)
863
+ # integrated repulsive forces
864
+ cost -= k**2 * np.sum(np.log(distance))
865
+ # gravitational force from the centroids of connected components to (0.5, ..., 0.5)^T
866
+ centers = np.zeros((n_components, dim))
867
+ np.add.at(centers, labels, pos)
868
+ delta0 = centers / bincount[:, np.newaxis] - 0.5
869
+ grad += gravity * delta0[labels]
870
+ cost += gravity * 0.5 * np.sum(bincount * np.linalg.norm(delta0, axis=1) ** 2)
871
+ # fix positions of fixed nodes
872
+ grad[fixed] = 0.0
873
+ return cost, grad.ravel()
874
+
875
+ # Optimization of the energy function by L-BFGS algorithm
876
+ options = {"maxiter": iterations, "gtol": threshold}
877
+ return sp.optimize.minimize(
878
+ _cost_FR, pos.ravel(), method="L-BFGS-B", jac=True, options=options
879
+ ).x.reshape((nnodes, dim))
880
+
881
+
882
+ def kamada_kawai_layout(
883
+ G,
884
+ dist=None,
885
+ pos=None,
886
+ weight="weight",
887
+ scale=1,
888
+ center=None,
889
+ dim=2,
890
+ store_pos_as=None,
891
+ ):
892
+ """Position nodes using Kamada-Kawai path-length cost-function.
893
+
894
+ Parameters
895
+ ----------
896
+ G : NetworkX graph or list of nodes
897
+ A position will be assigned to every node in G.
898
+
899
+ dist : dict (default=None)
900
+ A two-level dictionary of optimal distances between nodes,
901
+ indexed by source and destination node.
902
+ If None, the distance is computed using shortest_path_length().
903
+
904
+ pos : dict or None optional (default=None)
905
+ Initial positions for nodes as a dictionary with node as keys
906
+ and values as a coordinate list or tuple. If None, then use
907
+ circular_layout() for dim >= 2 and a linear layout for dim == 1.
908
+
909
+ weight : string or None optional (default='weight')
910
+ The edge attribute that holds the numerical value used for
911
+ the edge weight. If None, then all edge weights are 1.
912
+
913
+ scale : number (default: 1)
914
+ Scale factor for positions.
915
+
916
+ center : array-like or None
917
+ Coordinate pair around which to center the layout.
918
+
919
+ dim : int
920
+ Dimension of layout.
921
+
922
+ store_pos_as : str, default None
923
+ If non-None, the position of each node will be stored on the graph as
924
+ an attribute with this string as its name, which can be accessed with
925
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
926
+
927
+ Returns
928
+ -------
929
+ pos : dict
930
+ A dictionary of positions keyed by node
931
+
932
+ Examples
933
+ --------
934
+ >>> from pprint import pprint
935
+ >>> G = nx.path_graph(4)
936
+ >>> pos = nx.kamada_kawai_layout(G)
937
+ >>> # suppress the returned dict and store on the graph directly
938
+ >>> _ = nx.kamada_kawai_layout(G, store_pos_as="pos")
939
+ >>> pprint(nx.get_node_attributes(G, "pos"))
940
+ {0: array([0.99996577, 0.99366857]),
941
+ 1: array([0.32913544, 0.33543827]),
942
+ 2: array([-0.33544334, -0.32910684]),
943
+ 3: array([-0.99365787, -1. ])}
944
+ """
945
+ import numpy as np
946
+
947
+ G, center = _process_params(G, center, dim)
948
+ nNodes = len(G)
949
+ if nNodes == 0:
950
+ return {}
951
+
952
+ if dist is None:
953
+ dist = dict(nx.shortest_path_length(G, weight=weight))
954
+ dist_mtx = 1e6 * np.ones((nNodes, nNodes))
955
+ for row, nr in enumerate(G):
956
+ if nr not in dist:
957
+ continue
958
+ rdist = dist[nr]
959
+ for col, nc in enumerate(G):
960
+ if nc not in rdist:
961
+ continue
962
+ dist_mtx[row][col] = rdist[nc]
963
+
964
+ if pos is None:
965
+ if dim >= 3:
966
+ pos = random_layout(G, dim=dim)
967
+ elif dim == 2:
968
+ pos = circular_layout(G, dim=dim)
969
+ else:
970
+ pos = dict(zip(G, np.linspace(0, 1, len(G))))
971
+ pos_arr = np.array([pos[n] for n in G])
972
+
973
+ pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
974
+
975
+ pos = rescale_layout(pos, scale=scale) + center
976
+ pos = dict(zip(G, pos))
977
+
978
+ if store_pos_as is not None:
979
+ nx.set_node_attributes(G, pos, store_pos_as)
980
+
981
+ return pos
982
+
983
+
984
+ def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
985
+ # Anneal node locations based on the Kamada-Kawai cost-function,
986
+ # using the supplied matrix of preferred inter-node distances,
987
+ # and starting locations.
988
+
989
+ import numpy as np
990
+ import scipy as sp
991
+
992
+ meanwt = 1e-3
993
+ costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
994
+
995
+ optresult = sp.optimize.minimize(
996
+ _kamada_kawai_costfn,
997
+ pos_arr.ravel(),
998
+ method="L-BFGS-B",
999
+ args=costargs,
1000
+ jac=True,
1001
+ )
1002
+
1003
+ return optresult.x.reshape((-1, dim))
1004
+
1005
+
1006
+ def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
1007
+ # Cost-function and gradient for Kamada-Kawai layout algorithm
1008
+ nNodes = invdist.shape[0]
1009
+ pos_arr = pos_vec.reshape((nNodes, dim))
1010
+
1011
+ delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
1012
+ nodesep = np.linalg.norm(delta, axis=-1)
1013
+ direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
1014
+
1015
+ offset = nodesep * invdist - 1.0
1016
+ offset[np.diag_indices(nNodes)] = 0
1017
+
1018
+ cost = 0.5 * np.sum(offset**2)
1019
+ grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
1020
+ "ij,ij,ijk->jk", invdist, offset, direction
1021
+ )
1022
+
1023
+ # Additional parabolic term to encourage mean position to be near origin:
1024
+ sumpos = np.sum(pos_arr, axis=0)
1025
+ cost += 0.5 * meanweight * np.sum(sumpos**2)
1026
+ grad += meanweight * sumpos
1027
+
1028
+ return (cost, grad.ravel())
1029
+
1030
+
1031
+ def spectral_layout(G, weight="weight", scale=1, center=None, dim=2, store_pos_as=None):
1032
+ """Position nodes using the eigenvectors of the graph Laplacian.
1033
+
1034
+ Using the unnormalized Laplacian, the layout shows possible clusters of
1035
+ nodes which are an approximation of the ratio cut. If dim is the number of
1036
+ dimensions then the positions are the entries of the dim eigenvectors
1037
+ corresponding to the ascending eigenvalues starting from the second one.
1038
+
1039
+ Parameters
1040
+ ----------
1041
+ G : NetworkX graph or list of nodes
1042
+ A position will be assigned to every node in G.
1043
+
1044
+ weight : string or None optional (default='weight')
1045
+ The edge attribute that holds the numerical value used for
1046
+ the edge weight. If None, then all edge weights are 1.
1047
+
1048
+ scale : number (default: 1)
1049
+ Scale factor for positions.
1050
+
1051
+ center : array-like or None
1052
+ Coordinate pair around which to center the layout.
1053
+
1054
+ dim : int
1055
+ Dimension of layout.
1056
+
1057
+ store_pos_as : str, default None
1058
+ If non-None, the position of each node will be stored on the graph as
1059
+ an attribute with this string as its name, which can be accessed with
1060
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1061
+
1062
+ Returns
1063
+ -------
1064
+ pos : dict
1065
+ A dictionary of positions keyed by node
1066
+
1067
+ Examples
1068
+ --------
1069
+ >>> from pprint import pprint
1070
+ >>> G = nx.path_graph(4)
1071
+ >>> pos = nx.spectral_layout(G)
1072
+ >>> # suppress the returned dict and store on the graph directly
1073
+ >>> _ = nx.spectral_layout(G, store_pos_as="pos")
1074
+ >>> pprint(nx.get_node_attributes(G, "pos"))
1075
+ {0: array([-1. , 0.76536686]),
1076
+ 1: array([-0.41421356, -0.76536686]),
1077
+ 2: array([ 0.41421356, -0.76536686]),
1078
+ 3: array([1. , 0.76536686])}
1079
+
1080
+
1081
+ Notes
1082
+ -----
1083
+ Directed graphs will be considered as undirected graphs when
1084
+ positioning the nodes.
1085
+
1086
+ For larger graphs (>500 nodes) this will use the SciPy sparse
1087
+ eigenvalue solver (ARPACK).
1088
+ """
1089
+ # handle some special cases that break the eigensolvers
1090
+ import numpy as np
1091
+
1092
+ G, center = _process_params(G, center, dim)
1093
+
1094
+ if len(G) <= 2:
1095
+ if len(G) == 0:
1096
+ pos = np.array([])
1097
+ elif len(G) == 1:
1098
+ pos = np.array([center])
1099
+ else:
1100
+ pos = np.array([np.zeros(dim), np.array(center) * 2.0])
1101
+ return dict(zip(G, pos))
1102
+ try:
1103
+ # Sparse matrix
1104
+ if len(G) < 500: # dense solver is faster for small graphs
1105
+ raise ValueError
1106
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
1107
+ # Symmetrize directed graphs
1108
+ if G.is_directed():
1109
+ A = A + np.transpose(A)
1110
+ pos = _sparse_spectral(A, dim)
1111
+ except (ImportError, ValueError):
1112
+ # Dense matrix
1113
+ A = nx.to_numpy_array(G, weight=weight)
1114
+ # Symmetrize directed graphs
1115
+ if G.is_directed():
1116
+ A += A.T
1117
+ pos = _spectral(A, dim)
1118
+
1119
+ if pos.shape[1] < dim:
1120
+ pos = np.pad(pos, ((0, 0), (0, dim - pos.shape[1])), constant_values=0)
1121
+
1122
+ pos = rescale_layout(pos, scale=scale) + center
1123
+ pos = dict(zip(G, pos))
1124
+
1125
+ if store_pos_as is not None:
1126
+ nx.set_node_attributes(G, pos, store_pos_as)
1127
+
1128
+ return pos
1129
+
1130
+
1131
+ def _spectral(A, dim=2):
1132
+ # Input adjacency matrix A
1133
+ # Uses dense eigenvalue solver from numpy
1134
+ import numpy as np
1135
+
1136
+ try:
1137
+ nnodes, _ = A.shape
1138
+ except AttributeError as err:
1139
+ msg = "spectral() takes an adjacency matrix as input"
1140
+ raise nx.NetworkXError(msg) from err
1141
+
1142
+ # form Laplacian matrix where D is diagonal of degrees
1143
+ D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
1144
+ L = D - A
1145
+
1146
+ eigenvalues, eigenvectors = np.linalg.eig(L)
1147
+ # sort and keep smallest nonzero
1148
+ index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
1149
+ return np.real(eigenvectors[:, index])
1150
+
1151
+
1152
+ def _sparse_spectral(A, dim=2):
1153
+ # Input adjacency matrix A
1154
+ # Uses sparse eigenvalue solver from scipy
1155
+ # Could use multilevel methods here, see Koren "On spectral graph drawing"
1156
+ import numpy as np
1157
+ import scipy as sp
1158
+
1159
+ try:
1160
+ nnodes, _ = A.shape
1161
+ except AttributeError as err:
1162
+ msg = "sparse_spectral() takes an adjacency matrix as input"
1163
+ raise nx.NetworkXError(msg) from err
1164
+
1165
+ # form Laplacian matrix
1166
+ D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(nnodes, nnodes)).tocsr()
1167
+ L = D - A
1168
+
1169
+ k = dim + 1
1170
+ # number of Lanczos vectors for ARPACK solver.What is the right scaling?
1171
+ ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
1172
+ # return smallest k eigenvalues and eigenvectors
1173
+ eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
1174
+ index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
1175
+ return np.real(eigenvectors[:, index])
1176
+
1177
+
1178
+ def planar_layout(G, scale=1, center=None, dim=2, store_pos_as=None):
1179
+ """Position nodes without edge intersections.
1180
+
1181
+ Parameters
1182
+ ----------
1183
+ G : NetworkX graph or list of nodes
1184
+ A position will be assigned to every node in G. If G is of type
1185
+ nx.PlanarEmbedding, the positions are selected accordingly.
1186
+
1187
+ scale : number (default: 1)
1188
+ Scale factor for positions.
1189
+
1190
+ center : array-like or None
1191
+ Coordinate pair around which to center the layout.
1192
+
1193
+ dim : int
1194
+ Dimension of layout.
1195
+
1196
+ store_pos_as : str, default None
1197
+ If non-None, the position of each node will be stored on the graph as
1198
+ an attribute with this string as its name, which can be accessed with
1199
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1200
+
1201
+ Returns
1202
+ -------
1203
+ pos : dict
1204
+ A dictionary of positions keyed by node
1205
+
1206
+ Raises
1207
+ ------
1208
+ NetworkXException
1209
+ If G is not planar
1210
+
1211
+ Examples
1212
+ --------
1213
+ >>> from pprint import pprint
1214
+ >>> G = nx.path_graph(4)
1215
+ >>> pos = nx.planar_layout(G)
1216
+ >>> # suppress the returned dict and store on the graph directly
1217
+ >>> _ = nx.planar_layout(G, store_pos_as="pos")
1218
+ >>> pprint(nx.get_node_attributes(G, "pos"))
1219
+ {0: array([-0.77777778, -0.33333333]),
1220
+ 1: array([ 1. , -0.33333333]),
1221
+ 2: array([0.11111111, 0.55555556]),
1222
+ 3: array([-0.33333333, 0.11111111])}
1223
+ """
1224
+ import numpy as np
1225
+
1226
+ if dim != 2:
1227
+ raise ValueError("can only handle 2 dimensions")
1228
+
1229
+ G, center = _process_params(G, center, dim)
1230
+
1231
+ if len(G) == 0:
1232
+ return {}
1233
+
1234
+ if isinstance(G, nx.PlanarEmbedding):
1235
+ embedding = G
1236
+ else:
1237
+ is_planar, embedding = nx.check_planarity(G)
1238
+ if not is_planar:
1239
+ raise nx.NetworkXException("G is not planar.")
1240
+ pos = nx.combinatorial_embedding_to_pos(embedding)
1241
+ node_list = list(embedding)
1242
+ pos = np.vstack([pos[x] for x in node_list])
1243
+ pos = pos.astype(np.float64)
1244
+ pos = rescale_layout(pos, scale=scale) + center
1245
+ pos = dict(zip(node_list, pos))
1246
+ if store_pos_as is not None:
1247
+ nx.set_node_attributes(G, pos, store_pos_as)
1248
+ return pos
1249
+
1250
+
1251
+ def spiral_layout(
1252
+ G,
1253
+ scale=1,
1254
+ center=None,
1255
+ dim=2,
1256
+ resolution=0.35,
1257
+ equidistant=False,
1258
+ store_pos_as=None,
1259
+ ):
1260
+ """Position nodes in a spiral layout.
1261
+
1262
+ Parameters
1263
+ ----------
1264
+ G : NetworkX graph or list of nodes
1265
+ A position will be assigned to every node in G.
1266
+
1267
+ scale : number (default: 1)
1268
+ Scale factor for positions.
1269
+
1270
+ center : array-like or None
1271
+ Coordinate pair around which to center the layout.
1272
+
1273
+ dim : int, default=2
1274
+ Dimension of layout, currently only dim=2 is supported.
1275
+ Other dimension values result in a ValueError.
1276
+
1277
+ resolution : float, default=0.35
1278
+ The compactness of the spiral layout returned.
1279
+ Lower values result in more compressed spiral layouts.
1280
+
1281
+ equidistant : bool, default=False
1282
+ If True, nodes will be positioned equidistant from each other
1283
+ by decreasing angle further from center.
1284
+ If False, nodes will be positioned at equal angles
1285
+ from each other by increasing separation further from center.
1286
+
1287
+ store_pos_as : str, default None
1288
+ If non-None, the position of each node will be stored on the graph as
1289
+ an attribute with this string as its name, which can be accessed with
1290
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1291
+
1292
+ Returns
1293
+ -------
1294
+ pos : dict
1295
+ A dictionary of positions keyed by node
1296
+
1297
+ Raises
1298
+ ------
1299
+ ValueError
1300
+ If dim != 2
1301
+
1302
+ Examples
1303
+ --------
1304
+ >>> from pprint import pprint
1305
+ >>> G = nx.path_graph(4)
1306
+ >>> pos = nx.spiral_layout(G)
1307
+ >>> nx.draw(G, pos=pos)
1308
+ >>> # suppress the returned dict and store on the graph directly
1309
+ >>> _ = nx.spiral_layout(G, store_pos_as="pos")
1310
+ >>> pprint(nx.get_node_attributes(G, "pos"))
1311
+ {0: array([-0.64153279, -0.68555087]),
1312
+ 1: array([-0.03307913, -0.46344795]),
1313
+ 2: array([0.34927952, 0.14899882]),
1314
+ 3: array([0.32533239, 1. ])}
1315
+
1316
+ Notes
1317
+ -----
1318
+ This algorithm currently only works in two dimensions.
1319
+
1320
+ """
1321
+ import numpy as np
1322
+
1323
+ if dim != 2:
1324
+ raise ValueError("can only handle 2 dimensions")
1325
+
1326
+ G, center = _process_params(G, center, dim)
1327
+
1328
+ if len(G) == 0:
1329
+ return {}
1330
+ if len(G) == 1:
1331
+ pos = {nx.utils.arbitrary_element(G): center}
1332
+ if store_pos_as is not None:
1333
+ nx.set_node_attributes(G, pos, store_pos_as)
1334
+ return pos
1335
+
1336
+ pos = []
1337
+ if equidistant:
1338
+ chord = 1
1339
+ step = 0.5
1340
+ theta = resolution
1341
+ theta += chord / (step * theta)
1342
+ for _ in range(len(G)):
1343
+ r = step * theta
1344
+ theta += chord / r
1345
+ pos.append([np.cos(theta) * r, np.sin(theta) * r])
1346
+
1347
+ else:
1348
+ dist = np.arange(len(G), dtype=float)
1349
+ angle = resolution * dist
1350
+ pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
1351
+
1352
+ pos = rescale_layout(np.array(pos), scale=scale) + center
1353
+
1354
+ pos = dict(zip(G, pos))
1355
+
1356
+ if store_pos_as is not None:
1357
+ nx.set_node_attributes(G, pos, store_pos_as)
1358
+
1359
+ return pos
1360
+
1361
+
1362
+ def multipartite_layout(
1363
+ G, subset_key="subset", align="vertical", scale=1, center=None, store_pos_as=None
1364
+ ):
1365
+ """Position nodes in layers of straight lines.
1366
+
1367
+ Parameters
1368
+ ----------
1369
+ G : NetworkX graph or list of nodes
1370
+ A position will be assigned to every node in G.
1371
+
1372
+ subset_key : string or dict (default='subset')
1373
+ If a string, the key of node data in G that holds the node subset.
1374
+ If a dict, keyed by layer number to the nodes in that layer/subset.
1375
+
1376
+ align : string (default='vertical')
1377
+ The alignment of nodes. Vertical or horizontal.
1378
+
1379
+ scale : number (default: 1)
1380
+ Scale factor for positions.
1381
+
1382
+ center : array-like or None
1383
+ Coordinate pair around which to center the layout.
1384
+
1385
+ store_pos_as : str, default None
1386
+ If non-None, the position of each node will be stored on the graph as
1387
+ an attribute with this string as its name, which can be accessed with
1388
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1389
+
1390
+ Returns
1391
+ -------
1392
+ pos : dict
1393
+ A dictionary of positions keyed by node.
1394
+
1395
+ Examples
1396
+ --------
1397
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1398
+ >>> pos = nx.multipartite_layout(G)
1399
+ >>> # suppress the returned dict and store on the graph directly
1400
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1401
+ >>> _ = nx.multipartite_layout(G, store_pos_as="pos")
1402
+
1403
+ or use a dict to provide the layers of the layout
1404
+
1405
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
1406
+ >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
1407
+ >>> pos = nx.multipartite_layout(G, subset_key=layers)
1408
+
1409
+ Notes
1410
+ -----
1411
+ This algorithm currently only works in two dimensions and does not
1412
+ try to minimize edge crossings.
1413
+
1414
+ Network does not need to be a complete multipartite graph. As long as nodes
1415
+ have subset_key data, they will be placed in the corresponding layers.
1416
+
1417
+ """
1418
+ import numpy as np
1419
+
1420
+ if align not in ("vertical", "horizontal"):
1421
+ msg = "align must be either vertical or horizontal."
1422
+ raise ValueError(msg)
1423
+
1424
+ G, center = _process_params(G, center=center, dim=2)
1425
+ if len(G) == 0:
1426
+ return {}
1427
+
1428
+ try:
1429
+ # check if subset_key is dict-like
1430
+ if len(G) != sum(len(nodes) for nodes in subset_key.values()):
1431
+ raise nx.NetworkXError(
1432
+ "all nodes must be in one subset of `subset_key` dict"
1433
+ )
1434
+ except AttributeError:
1435
+ # subset_key is not a dict, hence a string
1436
+ node_to_subset = nx.get_node_attributes(G, subset_key)
1437
+ if len(node_to_subset) != len(G):
1438
+ raise nx.NetworkXError(
1439
+ f"all nodes need a subset_key attribute: {subset_key}"
1440
+ )
1441
+ subset_key = nx.utils.groups(node_to_subset)
1442
+
1443
+ # Sort by layer, if possible
1444
+ try:
1445
+ layers = dict(sorted(subset_key.items()))
1446
+ except TypeError:
1447
+ layers = subset_key
1448
+
1449
+ pos = None
1450
+ nodes = []
1451
+ width = len(layers)
1452
+ for i, layer in enumerate(layers.values()):
1453
+ height = len(layer)
1454
+ xs = np.repeat(i, height)
1455
+ ys = np.arange(0, height, dtype=float)
1456
+ offset = ((width - 1) / 2, (height - 1) / 2)
1457
+ layer_pos = np.column_stack([xs, ys]) - offset
1458
+ if pos is None:
1459
+ pos = layer_pos
1460
+ else:
1461
+ pos = np.concatenate([pos, layer_pos])
1462
+ nodes.extend(layer)
1463
+ pos = rescale_layout(pos, scale=scale) + center
1464
+ if align == "horizontal":
1465
+ pos = pos[:, ::-1] # swap x and y coords
1466
+ pos = dict(zip(nodes, pos))
1467
+
1468
+ if store_pos_as is not None:
1469
+ nx.set_node_attributes(G, pos, store_pos_as)
1470
+
1471
+ return pos
1472
+
1473
+
1474
+ @np_random_state("seed")
1475
+ def arf_layout(
1476
+ G,
1477
+ pos=None,
1478
+ scaling=1,
1479
+ a=1.1,
1480
+ etol=1e-6,
1481
+ dt=1e-3,
1482
+ max_iter=1000,
1483
+ *,
1484
+ seed=None,
1485
+ store_pos_as=None,
1486
+ ):
1487
+ """Arf layout for networkx
1488
+
1489
+ The attractive and repulsive forces (arf) layout [1] improves the spring
1490
+ layout in three ways. First, it prevents congestion of highly connected nodes
1491
+ due to strong forcing between nodes. Second, it utilizes the layout space
1492
+ more effectively by preventing large gaps that spring layout tends to create.
1493
+ Lastly, the arf layout represents symmetries in the layout better than the
1494
+ default spring layout.
1495
+
1496
+ Parameters
1497
+ ----------
1498
+ G : nx.Graph or nx.DiGraph
1499
+ Networkx graph.
1500
+ pos : dict
1501
+ Initial position of the nodes. If set to None a
1502
+ random layout will be used.
1503
+ scaling : float
1504
+ Scales the radius of the circular layout space.
1505
+ a : float
1506
+ Strength of springs between connected nodes. Should be larger than 1.
1507
+ The greater a, the clearer the separation of unconnected sub clusters.
1508
+ etol : float
1509
+ Gradient sum of spring forces must be larger than `etol` before successful
1510
+ termination.
1511
+ dt : float
1512
+ Time step for force differential equation simulations.
1513
+ max_iter : int
1514
+ Max iterations before termination of the algorithm.
1515
+ seed : int, RandomState instance or None optional (default=None)
1516
+ Set the random state for deterministic node layouts.
1517
+ If int, `seed` is the seed used by the random number generator,
1518
+ if numpy.random.RandomState instance, `seed` is the random
1519
+ number generator,
1520
+ if None, the random number generator is the RandomState instance used
1521
+ by numpy.random.
1522
+ store_pos_as : str, default None
1523
+ If non-None, the position of each node will be stored on the graph as
1524
+ an attribute with this string as its name, which can be accessed with
1525
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1526
+
1527
+ Returns
1528
+ -------
1529
+ pos : dict
1530
+ A dictionary of positions keyed by node.
1531
+
1532
+ Examples
1533
+ --------
1534
+ >>> G = nx.grid_graph((5, 5))
1535
+ >>> pos = nx.arf_layout(G)
1536
+ >>> # suppress the returned dict and store on the graph directly
1537
+ >>> G = nx.grid_graph((5, 5))
1538
+ >>> _ = nx.arf_layout(G, store_pos_as="pos")
1539
+
1540
+ References
1541
+ ----------
1542
+ .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
1543
+ International Journal of Modern Physics C, 2007, Vol 18, No 10,
1544
+ pp. 1537-1549.
1545
+ https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
1546
+ """
1547
+ import warnings
1548
+
1549
+ import numpy as np
1550
+
1551
+ if a <= 1:
1552
+ msg = "The parameter a should be larger than 1"
1553
+ raise ValueError(msg)
1554
+
1555
+ pos_tmp = nx.random_layout(G, seed=seed)
1556
+ if pos is None:
1557
+ pos = pos_tmp
1558
+ else:
1559
+ for node in G.nodes():
1560
+ if node not in pos:
1561
+ pos[node] = pos_tmp[node].copy()
1562
+
1563
+ # Initialize spring constant matrix
1564
+ N = len(G)
1565
+ # No nodes no computation
1566
+ if N == 0:
1567
+ return pos
1568
+
1569
+ # init force of springs
1570
+ K = np.ones((N, N)) - np.eye(N)
1571
+ node_order = {node: i for i, node in enumerate(G)}
1572
+ for x, y in G.edges():
1573
+ if x != y:
1574
+ idx, jdx = (node_order[i] for i in (x, y))
1575
+ K[idx, jdx] = a
1576
+
1577
+ # vectorize values
1578
+ p = np.asarray(list(pos.values()))
1579
+
1580
+ # equation 10 in [1]
1581
+ rho = scaling * np.sqrt(N)
1582
+
1583
+ # looping variables
1584
+ error = etol + 1
1585
+ n_iter = 0
1586
+ while error > etol and n_iter < max_iter:
1587
+ diff = p[:, np.newaxis] - p[np.newaxis]
1588
+ A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
1589
+ # attraction_force - repulsions force
1590
+ # suppress nans due to division; caused by diagonal set to zero.
1591
+ # Does not affect the computation due to nansum
1592
+ with warnings.catch_warnings():
1593
+ warnings.simplefilter("ignore")
1594
+ change = K[..., np.newaxis] * diff - rho / A * diff
1595
+ change = np.nansum(change, axis=0)
1596
+ p += change * dt
1597
+
1598
+ error = np.linalg.norm(change, axis=-1).sum()
1599
+ n_iter += 1
1600
+
1601
+ pos = dict(zip(G.nodes(), p))
1602
+
1603
+ if store_pos_as is not None:
1604
+ nx.set_node_attributes(G, pos, store_pos_as)
1605
+
1606
+ return pos
1607
+
1608
+
1609
+ @np_random_state("seed")
1610
+ @nx._dispatchable(edge_attrs="weight", mutates_input={"store_pos_as": 15})
1611
+ def forceatlas2_layout(
1612
+ G,
1613
+ pos=None,
1614
+ *,
1615
+ max_iter=100,
1616
+ jitter_tolerance=1.0,
1617
+ scaling_ratio=2.0,
1618
+ gravity=1.0,
1619
+ distributed_action=False,
1620
+ strong_gravity=False,
1621
+ node_mass=None,
1622
+ node_size=None,
1623
+ weight=None,
1624
+ linlog=False,
1625
+ seed=None,
1626
+ dim=2,
1627
+ store_pos_as=None,
1628
+ ):
1629
+ """Position nodes using the ForceAtlas2 force-directed layout algorithm.
1630
+
1631
+ This function applies the ForceAtlas2 layout algorithm [1]_ to a NetworkX graph,
1632
+ positioning the nodes in a way that visually represents the structure of the graph.
1633
+ The algorithm uses physical simulation to minimize the energy of the system,
1634
+ resulting in a more readable layout.
1635
+
1636
+ Parameters
1637
+ ----------
1638
+ G : nx.Graph
1639
+ A NetworkX graph to be laid out.
1640
+ pos : dict or None, optional
1641
+ Initial positions of the nodes. If None, random initial positions are used.
1642
+ max_iter : int (default: 100)
1643
+ Number of iterations for the layout optimization.
1644
+ jitter_tolerance : float (default: 1.0)
1645
+ Controls the tolerance for adjusting the speed of layout generation.
1646
+ scaling_ratio : float (default: 2.0)
1647
+ Determines the scaling of attraction and repulsion forces.
1648
+ gravity : float (default: 1.0)
1649
+ Determines the amount of attraction on nodes to the center. Prevents islands
1650
+ (i.e. weakly connected or disconnected parts of the graph)
1651
+ from drifting away.
1652
+ distributed_action : bool (default: False)
1653
+ Distributes the attraction force evenly among nodes.
1654
+ strong_gravity : bool (default: False)
1655
+ Applies a strong gravitational pull towards the center.
1656
+ node_mass : dict or None, optional
1657
+ Maps nodes to their masses, influencing the attraction to other nodes.
1658
+ node_size : dict or None, optional
1659
+ Maps nodes to their sizes, preventing crowding by creating a halo effect.
1660
+ weight : string or None, optional (default: None)
1661
+ The edge attribute that holds the numerical value used for
1662
+ the edge weight. If None, then all edge weights are 1.
1663
+ linlog : bool (default: False)
1664
+ Uses logarithmic attraction instead of linear.
1665
+ seed : int, RandomState instance or None optional (default=None)
1666
+ Used only for the initial positions in the algorithm.
1667
+ Set the random state for deterministic node layouts.
1668
+ If int, `seed` is the seed used by the random number generator,
1669
+ if numpy.random.RandomState instance, `seed` is the random
1670
+ number generator,
1671
+ if None, the random number generator is the RandomState instance used
1672
+ by numpy.random.
1673
+ dim : int (default: 2)
1674
+ Sets the dimensions for the layout. Ignored if `pos` is provided.
1675
+ store_pos_as : str, default None
1676
+ If non-None, the position of each node will be stored on the graph as
1677
+ an attribute with this string as its name, which can be accessed with
1678
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1679
+
1680
+ Examples
1681
+ --------
1682
+ >>> import networkx as nx
1683
+ >>> G = nx.florentine_families_graph()
1684
+ >>> pos = nx.forceatlas2_layout(G)
1685
+ >>> nx.draw(G, pos=pos)
1686
+ >>> # suppress the returned dict and store on the graph directly
1687
+ >>> pos = nx.forceatlas2_layout(G, store_pos_as="pos")
1688
+ >>> _ = nx.forceatlas2_layout(G, store_pos_as="pos")
1689
+
1690
+ References
1691
+ ----------
1692
+ .. [1] Jacomy, M., Venturini, T., Heymann, S., & Bastian, M. (2014).
1693
+ ForceAtlas2, a continuous graph layout algorithm for handy network
1694
+ visualization designed for the Gephi software. PloS one, 9(6), e98679.
1695
+ https://doi.org/10.1371/journal.pone.0098679
1696
+ """
1697
+ import numpy as np
1698
+
1699
+ if len(G) == 0:
1700
+ return {}
1701
+ # parse optional pos positions
1702
+ if pos is None:
1703
+ pos = nx.random_layout(G, dim=dim, seed=seed)
1704
+ pos_arr = np.array(list(pos.values()))
1705
+ elif len(pos) == len(G):
1706
+ pos_arr = np.array([pos[node] for node in G])
1707
+ else:
1708
+ # set random node pos within the initial pos values
1709
+ pos_init = np.array(list(pos.values()))
1710
+ max_pos = pos_init.max(axis=0)
1711
+ min_pos = pos_init.min(axis=0)
1712
+ dim = max_pos.size
1713
+ pos_arr = min_pos + seed.rand(len(G), dim) * (max_pos - min_pos)
1714
+ for idx, node in enumerate(G):
1715
+ if node in pos:
1716
+ pos_arr[idx] = pos[node].copy()
1717
+
1718
+ mass = np.zeros(len(G))
1719
+ size = np.zeros(len(G))
1720
+
1721
+ # Only adjust for size when the users specifies size other than default (1)
1722
+ adjust_sizes = False
1723
+ if node_size is None:
1724
+ node_size = {}
1725
+ else:
1726
+ adjust_sizes = True
1727
+
1728
+ if node_mass is None:
1729
+ node_mass = {}
1730
+
1731
+ for idx, node in enumerate(G):
1732
+ mass[idx] = node_mass.get(node, G.degree(node) + 1)
1733
+ size[idx] = node_size.get(node, 1)
1734
+
1735
+ n = len(G)
1736
+ gravities = np.zeros((n, dim))
1737
+ attraction = np.zeros((n, dim))
1738
+ repulsion = np.zeros((n, dim))
1739
+ A = nx.to_numpy_array(G, weight=weight)
1740
+
1741
+ def estimate_factor(n, swing, traction, speed, speed_efficiency, jitter_tolerance):
1742
+ """Computes the scaling factor for the force in the ForceAtlas2 layout algorithm.
1743
+
1744
+ This helper function adjusts the speed and
1745
+ efficiency of the layout generation based on the
1746
+ current state of the system, such as the number of
1747
+ nodes, current swing, and traction forces.
1748
+
1749
+ Parameters
1750
+ ----------
1751
+ n : int
1752
+ Number of nodes in the graph.
1753
+ swing : float
1754
+ The current swing, representing the oscillation of the nodes.
1755
+ traction : float
1756
+ The current traction force, representing the attraction between nodes.
1757
+ speed : float
1758
+ The current speed of the layout generation.
1759
+ speed_efficiency : float
1760
+ The efficiency of the current speed, influencing how fast the layout converges.
1761
+ jitter_tolerance : float
1762
+ The tolerance for jitter, affecting how much speed adjustment is allowed.
1763
+
1764
+ Returns
1765
+ -------
1766
+ tuple
1767
+ A tuple containing the updated speed and speed efficiency.
1768
+
1769
+ Notes
1770
+ -----
1771
+ This function is a part of the ForceAtlas2 layout algorithm and is used to dynamically adjust the
1772
+ layout parameters to achieve an optimal and stable visualization.
1773
+
1774
+ """
1775
+ import numpy as np
1776
+
1777
+ # estimate jitter
1778
+ opt_jitter = 0.05 * np.sqrt(n)
1779
+ min_jitter = np.sqrt(opt_jitter)
1780
+ max_jitter = 10
1781
+ min_speed_efficiency = 0.05
1782
+
1783
+ other = min(max_jitter, opt_jitter * traction / n**2)
1784
+ jitter = jitter_tolerance * max(min_jitter, other)
1785
+
1786
+ if swing / traction > 2.0:
1787
+ if speed_efficiency > min_speed_efficiency:
1788
+ speed_efficiency *= 0.5
1789
+ jitter = max(jitter, jitter_tolerance)
1790
+ if swing == 0:
1791
+ target_speed = np.inf
1792
+ else:
1793
+ target_speed = jitter * speed_efficiency * traction / swing
1794
+
1795
+ if swing > jitter * traction:
1796
+ if speed_efficiency > min_speed_efficiency:
1797
+ speed_efficiency *= 0.7
1798
+ elif speed < 1000:
1799
+ speed_efficiency *= 1.3
1800
+
1801
+ max_rise = 0.5
1802
+ speed = speed + min(target_speed - speed, max_rise * speed)
1803
+ return speed, speed_efficiency
1804
+
1805
+ speed = 1
1806
+ speed_efficiency = 1
1807
+ swing = 1
1808
+ traction = 1
1809
+ for _ in range(max_iter):
1810
+ # compute pairwise difference
1811
+ diff = pos_arr[:, None] - pos_arr[None]
1812
+ # compute pairwise distance
1813
+ distance = np.linalg.norm(diff, axis=-1)
1814
+
1815
+ # linear attraction
1816
+ if linlog:
1817
+ attraction = -np.log(1 + distance) / distance
1818
+ np.fill_diagonal(attraction, 0)
1819
+ attraction = np.einsum("ij, ij -> ij", attraction, A)
1820
+ attraction = np.einsum("ijk, ij -> ik", diff, attraction)
1821
+
1822
+ else:
1823
+ attraction = -np.einsum("ijk, ij -> ik", diff, A)
1824
+
1825
+ if distributed_action:
1826
+ attraction /= mass[:, None]
1827
+
1828
+ # repulsion
1829
+ tmp = mass[:, None] @ mass[None]
1830
+ if adjust_sizes:
1831
+ distance += -size[:, None] - size[None]
1832
+
1833
+ d2 = distance**2
1834
+ # remove self-interaction
1835
+ np.fill_diagonal(tmp, 0)
1836
+ np.fill_diagonal(d2, 1)
1837
+ factor = (tmp / d2) * scaling_ratio
1838
+ repulsion = np.einsum("ijk, ij -> ik", diff, factor)
1839
+
1840
+ # gravity
1841
+ pos_centered = pos_arr - np.mean(pos_arr, axis=0)
1842
+ if strong_gravity:
1843
+ gravities = -gravity * mass[:, None] * pos_centered
1844
+ else:
1845
+ # hide warnings for divide by zero. Then change nan to 0
1846
+ with np.errstate(divide="ignore", invalid="ignore"):
1847
+ unit_vec = pos_centered / np.linalg.norm(pos_centered, axis=-1)[:, None]
1848
+ unit_vec = np.nan_to_num(unit_vec, nan=0)
1849
+ gravities = -gravity * mass[:, None] * unit_vec
1850
+
1851
+ # total forces
1852
+ update = attraction + repulsion + gravities
1853
+
1854
+ # compute total swing and traction
1855
+ swing += (mass * np.linalg.norm(pos_arr - update, axis=-1)).sum()
1856
+ traction += (0.5 * mass * np.linalg.norm(pos_arr + update, axis=-1)).sum()
1857
+
1858
+ speed, speed_efficiency = estimate_factor(
1859
+ n,
1860
+ swing,
1861
+ traction,
1862
+ speed,
1863
+ speed_efficiency,
1864
+ jitter_tolerance,
1865
+ )
1866
+
1867
+ # update pos
1868
+ if adjust_sizes:
1869
+ df = np.linalg.norm(update, axis=-1)
1870
+ swinging = mass * df
1871
+ factor = 0.1 * speed / (1 + np.sqrt(speed * swinging))
1872
+ factor = np.minimum(factor * df, 10.0 * np.ones(df.shape)) / df
1873
+ else:
1874
+ swinging = mass * np.linalg.norm(update, axis=-1)
1875
+ factor = speed / (1 + np.sqrt(speed * swinging))
1876
+
1877
+ factored_update = update * factor[:, None]
1878
+ pos_arr += factored_update
1879
+ if abs(factored_update).sum() < 1e-10:
1880
+ break
1881
+
1882
+ pos = dict(zip(G, pos_arr))
1883
+ if store_pos_as is not None:
1884
+ nx.set_node_attributes(G, pos, store_pos_as)
1885
+
1886
+ return pos
1887
+
1888
+
1889
+ def rescale_layout(pos, scale=1):
1890
+ """Returns scaled position array to (-scale, scale) in all axes.
1891
+
1892
+ The function acts on NumPy arrays which hold position information.
1893
+ Each position is one row of the array. The dimension of the space
1894
+ equals the number of columns. Each coordinate in one column.
1895
+
1896
+ To rescale, the mean (center) is subtracted from each axis separately.
1897
+ Then all values are scaled so that the largest magnitude value
1898
+ from all axes equals `scale` (thus, the aspect ratio is preserved).
1899
+ The resulting NumPy Array is returned (order of rows unchanged).
1900
+
1901
+ Parameters
1902
+ ----------
1903
+ pos : numpy array
1904
+ positions to be scaled. Each row is a position.
1905
+
1906
+ scale : number (default: 1)
1907
+ The size of the resulting extent in all directions.
1908
+
1909
+ Returns
1910
+ -------
1911
+ pos : numpy array
1912
+ scaled positions. Each row is a position.
1913
+
1914
+ See Also
1915
+ --------
1916
+ rescale_layout_dict
1917
+ """
1918
+ import numpy as np
1919
+
1920
+ # Find max length over all dimensions
1921
+ pos -= pos.mean(axis=0)
1922
+ lim = np.abs(pos).max() # max coordinate for all axes
1923
+ # rescale to (-scale, scale) in all directions, preserves aspect
1924
+ if lim > 0:
1925
+ pos *= scale / lim
1926
+ return pos
1927
+
1928
+
1929
+ def rescale_layout_dict(pos, scale=1):
1930
+ """Return a dictionary of scaled positions keyed by node
1931
+
1932
+ Parameters
1933
+ ----------
1934
+ pos : A dictionary of positions keyed by node
1935
+
1936
+ scale : number (default: 1)
1937
+ The size of the resulting extent in all directions.
1938
+
1939
+ Returns
1940
+ -------
1941
+ pos : A dictionary of positions keyed by node
1942
+
1943
+ Examples
1944
+ --------
1945
+ >>> import numpy as np
1946
+ >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
1947
+ >>> nx.rescale_layout_dict(pos)
1948
+ {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
1949
+
1950
+ >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
1951
+ >>> nx.rescale_layout_dict(pos, scale=2)
1952
+ {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
1953
+
1954
+ See Also
1955
+ --------
1956
+ rescale_layout
1957
+ """
1958
+ import numpy as np
1959
+
1960
+ if not pos: # empty_graph
1961
+ return {}
1962
+ pos_v = np.array(list(pos.values()))
1963
+ pos_v = rescale_layout(pos_v, scale=scale)
1964
+ return dict(zip(pos, pos_v))
1965
+
1966
+
1967
+ def bfs_layout(G, start, *, align="vertical", scale=1, center=None, store_pos_as=None):
1968
+ """Position nodes according to breadth-first search algorithm.
1969
+
1970
+ Parameters
1971
+ ----------
1972
+ G : NetworkX graph
1973
+ A position will be assigned to every node in `G`.
1974
+
1975
+ start : node in `G`
1976
+ Starting node for bfs
1977
+
1978
+ align : string (default='vertical')
1979
+ The alignment of nodes within a layer, either ``"vertical"`` or
1980
+ ``"horizontal"``.
1981
+
1982
+ scale : number (default: 1)
1983
+ Scale factor for positions.
1984
+
1985
+ center : array-like or None
1986
+ Coordinate pair around which to center the layout.
1987
+
1988
+ store_pos_as : str, default None
1989
+ If non-None, the position of each node will be stored on the graph as
1990
+ an attribute with this string as its name, which can be accessed with
1991
+ ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
1992
+
1993
+ Returns
1994
+ -------
1995
+ pos : dict
1996
+ A dictionary of positions keyed by node.
1997
+
1998
+ Raises
1999
+ ------
2000
+ NetworkXError
2001
+ If any nodes are unreachable from `start`, e.g. `G` is not connected,
2002
+ or `G` is directed and `start` has 0 out degree.
2003
+
2004
+ Examples
2005
+ --------
2006
+ >>> from pprint import pprint
2007
+ >>> G = nx.path_graph(4)
2008
+ >>> pos = nx.bfs_layout(G, 0)
2009
+ >>> # suppress the returned dict and store on the graph directly
2010
+ >>> _ = nx.bfs_layout(G, 0, store_pos_as="pos")
2011
+ >>> pprint(nx.get_node_attributes(G, "pos"))
2012
+ {0: array([-1., 0.]),
2013
+ 1: array([-0.33333333, 0. ]),
2014
+ 2: array([0.33333333, 0. ]),
2015
+ 3: array([1., 0.])}
2016
+
2017
+ Notes
2018
+ -----
2019
+ This algorithm currently only works in two dimensions and does not
2020
+ try to minimize edge crossings.
2021
+ """
2022
+ G, center = _process_params(G, center, 2)
2023
+
2024
+ # Compute layers with BFS
2025
+ layers = dict(enumerate(nx.bfs_layers(G, start)))
2026
+
2027
+ if len(G) != sum(len(nodes) for nodes in layers.values()):
2028
+ raise nx.NetworkXError(
2029
+ "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
2030
+ " G.subgraph(nx.node_connected_component(G, start))"
2031
+ )
2032
+
2033
+ # Compute node positions with multipartite_layout
2034
+ pos = multipartite_layout(
2035
+ G, subset_key=layers, align=align, scale=scale, center=center
2036
+ )
2037
+
2038
+ if store_pos_as is not None:
2039
+ nx.set_node_attributes(G, pos, store_pos_as)
2040
+
2041
+ return pos
venv/lib/python3.14/site-packages/networkx/drawing/nx_agraph.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ***************
3
+ Graphviz AGraph
4
+ ***************
5
+
6
+ Interface to pygraphviz AGraph class.
7
+
8
+ Examples
9
+ --------
10
+ >>> G = nx.complete_graph(5)
11
+ >>> A = nx.nx_agraph.to_agraph(G)
12
+ >>> H = nx.nx_agraph.from_agraph(A)
13
+
14
+ See Also
15
+ --------
16
+ - Pygraphviz: http://pygraphviz.github.io/
17
+ - Graphviz: https://www.graphviz.org
18
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
19
+ """
20
+
21
+ import tempfile
22
+
23
+ import networkx as nx
24
+
25
+ __all__ = [
26
+ "from_agraph",
27
+ "to_agraph",
28
+ "write_dot",
29
+ "read_dot",
30
+ "graphviz_layout",
31
+ "pygraphviz_layout",
32
+ "view_pygraphviz",
33
+ ]
34
+
35
+
36
+ @nx._dispatchable(graphs=None, returns_graph=True)
37
+ def from_agraph(A, create_using=None):
38
+ """Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
39
+
40
+ Parameters
41
+ ----------
42
+ A : PyGraphviz AGraph
43
+ A graph created with PyGraphviz
44
+
45
+ create_using : NetworkX graph constructor, optional (default=None)
46
+ Graph type to create. If graph instance, then cleared before populated.
47
+ If `None`, then the appropriate Graph type is inferred from `A`.
48
+
49
+ Examples
50
+ --------
51
+ >>> K5 = nx.complete_graph(5)
52
+ >>> A = nx.nx_agraph.to_agraph(K5)
53
+ >>> G = nx.nx_agraph.from_agraph(A)
54
+
55
+ Notes
56
+ -----
57
+ The Graph G will have a dictionary G.graph_attr containing
58
+ the default graphviz attributes for graphs, nodes and edges.
59
+
60
+ Default node attributes will be in the dictionary G.node_attr
61
+ which is keyed by node.
62
+
63
+ Edge attributes will be returned as edge data in G. With
64
+ edge_attr=False the edge data will be the Graphviz edge weight
65
+ attribute or the value 1 if no edge weight attribute is found.
66
+
67
+ """
68
+ if create_using is None:
69
+ if A.is_directed():
70
+ if A.is_strict():
71
+ create_using = nx.DiGraph
72
+ else:
73
+ create_using = nx.MultiDiGraph
74
+ else:
75
+ if A.is_strict():
76
+ create_using = nx.Graph
77
+ else:
78
+ create_using = nx.MultiGraph
79
+
80
+ # assign defaults
81
+ N = nx.empty_graph(0, create_using)
82
+ if A.name is not None:
83
+ N.name = A.name
84
+
85
+ # add graph attributes
86
+ N.graph.update(A.graph_attr)
87
+
88
+ # add nodes, attributes to N.node_attr
89
+ for n in A.nodes():
90
+ str_attr = {str(k): v for k, v in n.attr.items()}
91
+ N.add_node(str(n), **str_attr)
92
+
93
+ # add edges, assign edge data as dictionary of attributes
94
+ for e in A.edges():
95
+ u, v = str(e[0]), str(e[1])
96
+ attr = dict(e.attr)
97
+ str_attr = {str(k): v for k, v in attr.items()}
98
+ if not N.is_multigraph():
99
+ if e.name is not None:
100
+ str_attr["key"] = e.name
101
+ N.add_edge(u, v, **str_attr)
102
+ else:
103
+ N.add_edge(u, v, key=e.name, **str_attr)
104
+
105
+ # add default attributes for graph, nodes, and edges
106
+ # hang them on N.graph_attr
107
+ graph_default_dict = dict(A.graph_attr)
108
+ if graph_default_dict:
109
+ N.graph["graph"] = graph_default_dict
110
+ node_default_dict = dict(A.node_attr)
111
+ if node_default_dict and node_default_dict != {"label": "\\N"}:
112
+ N.graph["node"] = node_default_dict
113
+ edge_default_dict = dict(A.edge_attr)
114
+ if edge_default_dict:
115
+ N.graph["edge"] = edge_default_dict
116
+ return N
117
+
118
+
119
+ def to_agraph(N):
120
+ """Returns a pygraphviz graph from a NetworkX graph N.
121
+
122
+ Parameters
123
+ ----------
124
+ N : NetworkX graph
125
+ A graph created with NetworkX
126
+
127
+ Examples
128
+ --------
129
+ >>> K5 = nx.complete_graph(5)
130
+ >>> A = nx.nx_agraph.to_agraph(K5)
131
+
132
+ Notes
133
+ -----
134
+ If N has an dict N.graph_attr an attempt will be made first
135
+ to copy properties attached to the graph (see from_agraph)
136
+ and then updated with the calling arguments if any.
137
+
138
+ """
139
+ try:
140
+ import pygraphviz
141
+ except ImportError as err:
142
+ raise ImportError("requires pygraphviz https://pygraphviz.github.io/") from err
143
+ directed = N.is_directed()
144
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
145
+
146
+ A = pygraphviz.AGraph(name=N.name, strict=strict, directed=directed)
147
+
148
+ # default graph attributes
149
+ A.graph_attr.update(N.graph.get("graph", {}))
150
+ A.node_attr.update(N.graph.get("node", {}))
151
+ A.edge_attr.update(N.graph.get("edge", {}))
152
+
153
+ A.graph_attr.update(
154
+ (k, v) for k, v in N.graph.items() if k not in ("graph", "node", "edge")
155
+ )
156
+
157
+ # add nodes
158
+ for n, nodedata in N.nodes(data=True):
159
+ A.add_node(n)
160
+ # Add node data
161
+ a = A.get_node(n)
162
+ for key, val in nodedata.items():
163
+ if key == "pos":
164
+ if isinstance(val, str):
165
+ a.attr["pos"] = val
166
+ else:
167
+ a.attr["pos"] = f"{val[0]},{val[1]}!"
168
+ else:
169
+ a.attr[key] = str(val)
170
+
171
+ # loop over edges
172
+ if N.is_multigraph():
173
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
174
+ str_edgedata = {k: str(v) for k, v in edgedata.items() if k != "key"}
175
+ A.add_edge(u, v, key=str(key))
176
+ # Add edge data
177
+ a = A.get_edge(u, v)
178
+ a.attr.update(str_edgedata)
179
+
180
+ else:
181
+ for u, v, edgedata in N.edges(data=True):
182
+ str_edgedata = {k: str(v) for k, v in edgedata.items()}
183
+ A.add_edge(u, v)
184
+ # Add edge data
185
+ a = A.get_edge(u, v)
186
+ a.attr.update(str_edgedata)
187
+
188
+ return A
189
+
190
+
191
+ def write_dot(G, path):
192
+ """Write NetworkX graph G to Graphviz dot format on path.
193
+
194
+ Parameters
195
+ ----------
196
+ G : graph
197
+ A networkx graph
198
+ path : filename
199
+ Filename or file handle to write
200
+
201
+ Notes
202
+ -----
203
+ To use a specific graph layout, call ``A.layout`` prior to `write_dot`.
204
+ Note that some graphviz layouts are not guaranteed to be deterministic,
205
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
206
+ """
207
+ A = to_agraph(G)
208
+ A.write(path)
209
+ A.clear()
210
+ return
211
+
212
+
213
+ @nx._dispatchable(name="agraph_read_dot", graphs=None, returns_graph=True)
214
+ def read_dot(path):
215
+ """Returns a NetworkX graph from a dot file on path.
216
+
217
+ Parameters
218
+ ----------
219
+ path : file or string
220
+ File name or file handle to read.
221
+ """
222
+ try:
223
+ import pygraphviz
224
+ except ImportError as err:
225
+ raise ImportError(
226
+ "read_dot() requires pygraphviz https://pygraphviz.github.io/"
227
+ ) from err
228
+ A = pygraphviz.AGraph(file=path)
229
+ gr = from_agraph(A)
230
+ A.clear()
231
+ return gr
232
+
233
+
234
+ def graphviz_layout(G, prog="neato", root=None, args=""):
235
+ """Create node positions for G using Graphviz.
236
+
237
+ Parameters
238
+ ----------
239
+ G : NetworkX graph
240
+ A graph created with NetworkX
241
+ prog : string
242
+ Name of Graphviz layout program
243
+ root : string, optional
244
+ Root node for twopi layout
245
+ args : string, optional
246
+ Extra arguments to Graphviz layout program
247
+
248
+ Returns
249
+ -------
250
+ Dictionary of x, y, positions keyed by node.
251
+
252
+ Examples
253
+ --------
254
+ >>> G = nx.petersen_graph()
255
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
256
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
257
+
258
+ Notes
259
+ -----
260
+ This is a wrapper for pygraphviz_layout.
261
+
262
+ Note that some graphviz layouts are not guaranteed to be deterministic,
263
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
264
+ """
265
+ return pygraphviz_layout(G, prog=prog, root=root, args=args)
266
+
267
+
268
+ def pygraphviz_layout(G, prog="neato", root=None, args=""):
269
+ """Create node positions for G using Graphviz.
270
+
271
+ Parameters
272
+ ----------
273
+ G : NetworkX graph
274
+ A graph created with NetworkX
275
+ prog : string
276
+ Name of Graphviz layout program
277
+ root : string, optional
278
+ Root node for twopi layout
279
+ args : string, optional
280
+ Extra arguments to Graphviz layout program
281
+
282
+ Returns
283
+ -------
284
+ node_pos : dict
285
+ Dictionary of x, y, positions keyed by node.
286
+
287
+ Examples
288
+ --------
289
+ >>> G = nx.petersen_graph()
290
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
291
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
292
+
293
+ Notes
294
+ -----
295
+ If you use complex node objects, they may have the same string
296
+ representation and GraphViz could treat them as the same node.
297
+ The layout may assign both nodes a single location. See Issue #1568
298
+ If this occurs in your case, consider relabeling the nodes just
299
+ for the layout computation using something similar to::
300
+
301
+ >>> H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
302
+ >>> H_layout = nx.nx_agraph.pygraphviz_layout(H, prog="dot")
303
+ >>> G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
304
+
305
+ Note that some graphviz layouts are not guaranteed to be deterministic,
306
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
307
+ """
308
+ try:
309
+ import pygraphviz
310
+ except ImportError as err:
311
+ raise ImportError("requires pygraphviz https://pygraphviz.github.io/") from err
312
+ if root is not None:
313
+ args += f"-Groot={root}"
314
+ A = to_agraph(G)
315
+ A.layout(prog=prog, args=args)
316
+ node_pos = {}
317
+ for n in G:
318
+ node = pygraphviz.Node(A, n)
319
+ try:
320
+ xs = node.attr["pos"].split(",")
321
+ node_pos[n] = tuple(float(x) for x in xs)
322
+ except:
323
+ print("no position for node", n)
324
+ node_pos[n] = (0.0, 0.0)
325
+ return node_pos
326
+
327
+
328
+ @nx.utils.open_file(5, "w+b")
329
+ def view_pygraphviz(
330
+ G, edgelabel=None, prog="dot", args="", suffix="", path=None, show=True
331
+ ):
332
+ """Views the graph G using the specified layout algorithm.
333
+
334
+ Parameters
335
+ ----------
336
+ G : NetworkX graph
337
+ The machine to draw.
338
+ edgelabel : str, callable, None
339
+ If a string, then it specifies the edge attribute to be displayed
340
+ on the edge labels. If a callable, then it is called for each
341
+ edge and it should return the string to be displayed on the edges.
342
+ The function signature of `edgelabel` should be edgelabel(data),
343
+ where `data` is the edge attribute dictionary.
344
+ prog : string
345
+ Name of Graphviz layout program.
346
+ args : str
347
+ Additional arguments to pass to the Graphviz layout program.
348
+ suffix : str
349
+ If `filename` is None, we save to a temporary file. The value of
350
+ `suffix` will appear at the tail end of the temporary filename.
351
+ path : str, None
352
+ The filename used to save the image. If None, save to a temporary
353
+ file. File formats are the same as those from pygraphviz.agraph.draw.
354
+ Filenames ending in .gz or .bz2 will be compressed.
355
+ show : bool, default = True
356
+ Whether to display the graph with :mod:`PIL.Image.show`,
357
+ default is `True`. If `False`, the rendered graph is still available
358
+ at `path`.
359
+
360
+ Returns
361
+ -------
362
+ path : str
363
+ The filename of the generated image.
364
+ A : PyGraphviz graph
365
+ The PyGraphviz graph instance used to generate the image.
366
+
367
+ Notes
368
+ -----
369
+ If this function is called in succession too quickly, sometimes the
370
+ image is not displayed. So you might consider time.sleep(.5) between
371
+ calls if you experience problems.
372
+
373
+ Note that some graphviz layouts are not guaranteed to be deterministic,
374
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
375
+
376
+ """
377
+ if not len(G):
378
+ raise nx.NetworkXException("An empty graph cannot be drawn.")
379
+
380
+ # If we are providing default values for graphviz, these must be set
381
+ # before any nodes or edges are added to the PyGraphviz graph object.
382
+ # The reason for this is that default values only affect incoming objects.
383
+ # If you change the default values after the objects have been added,
384
+ # then they inherit no value and are set only if explicitly set.
385
+
386
+ # to_agraph() uses these values.
387
+ attrs = ["edge", "node", "graph"]
388
+ for attr in attrs:
389
+ if attr not in G.graph:
390
+ G.graph[attr] = {}
391
+
392
+ # These are the default values.
393
+ edge_attrs = {"fontsize": "10"}
394
+ node_attrs = {
395
+ "style": "filled",
396
+ "fillcolor": "#0000FF40",
397
+ "height": "0.75",
398
+ "width": "0.75",
399
+ "shape": "circle",
400
+ }
401
+ graph_attrs = {}
402
+
403
+ def update_attrs(which, attrs):
404
+ # Update graph attributes. Return list of those which were added.
405
+ added = []
406
+ for k, v in attrs.items():
407
+ if k not in G.graph[which]:
408
+ G.graph[which][k] = v
409
+ added.append(k)
410
+
411
+ def clean_attrs(which, added):
412
+ # Remove added attributes
413
+ for attr in added:
414
+ del G.graph[which][attr]
415
+ if not G.graph[which]:
416
+ del G.graph[which]
417
+
418
+ # Update all default values
419
+ update_attrs("edge", edge_attrs)
420
+ update_attrs("node", node_attrs)
421
+ update_attrs("graph", graph_attrs)
422
+
423
+ # Convert to agraph, so we inherit default values
424
+ A = to_agraph(G)
425
+
426
+ # Remove the default values we added to the original graph.
427
+ clean_attrs("edge", edge_attrs)
428
+ clean_attrs("node", node_attrs)
429
+ clean_attrs("graph", graph_attrs)
430
+
431
+ # If the user passed in an edgelabel, we update the labels for all edges.
432
+ if edgelabel is not None:
433
+ if not callable(edgelabel):
434
+
435
+ def func(data):
436
+ return "".join([" ", str(data[edgelabel]), " "])
437
+
438
+ else:
439
+ func = edgelabel
440
+
441
+ # update all the edge labels
442
+ if G.is_multigraph():
443
+ for u, v, key, data in G.edges(keys=True, data=True):
444
+ # PyGraphviz doesn't convert the key to a string. See #339
445
+ edge = A.get_edge(u, v, str(key))
446
+ edge.attr["label"] = str(func(data))
447
+ else:
448
+ for u, v, data in G.edges(data=True):
449
+ edge = A.get_edge(u, v)
450
+ edge.attr["label"] = str(func(data))
451
+
452
+ if path is None:
453
+ ext = "png"
454
+ if suffix:
455
+ suffix = f"_{suffix}.{ext}"
456
+ else:
457
+ suffix = f".{ext}"
458
+ path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
459
+ else:
460
+ # Assume the decorator worked and it is a file-object.
461
+ pass
462
+
463
+ # Write graph to file
464
+ A.draw(path=path, format=None, prog=prog, args=args)
465
+ path.close()
466
+
467
+ # Show graph in a new window (depends on platform configuration)
468
+ if show:
469
+ from PIL import Image
470
+
471
+ Image.open(path.name).show()
472
+
473
+ return path.name, A
venv/lib/python3.14/site-packages/networkx/drawing/nx_latex.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ *****
3
+ LaTeX
4
+ *****
5
+
6
+ Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
7
+ Usually, you will want the drawing to appear in a figure environment so
8
+ you use ``to_latex(G, caption="A caption")``. If you want the raw
9
+ drawing commands without a figure environment use :func:`to_latex_raw`.
10
+ And if you want to write to a file instead of just returning the latex
11
+ code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
12
+
13
+ To construct a figure with subfigures for each graph to be shown, provide
14
+ ``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
15
+ and a number of rows of subfigures inside the figure.
16
+
17
+ To be able to refer to the figures or subfigures in latex using ``\\ref``,
18
+ the keyword ``latex_label`` is available for figures and `sub_labels` for
19
+ a list of labels, one for each subfigure.
20
+
21
+ We intend to eventually provide an interface to the TikZ Graph
22
+ features which include e.g. layout algorithms.
23
+
24
+ Let us know via github what you'd like to see available, or better yet
25
+ give us some code to do it, or even better make a github pull request
26
+ to add the feature.
27
+
28
+ The TikZ approach
29
+ =================
30
+ Drawing options can be stored on the graph as node/edge attributes, or
31
+ can be provided as dicts keyed by node/edge to a string of the options
32
+ for that node/edge. Similarly a label can be shown for each node/edge
33
+ by specifying the labels as graph node/edge attributes or by providing
34
+ a dict keyed by node/edge to the text to be written for that node/edge.
35
+
36
+ Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
37
+ via a keyword argument. Similarly default node and edge options can be
38
+ provided through keywords arguments. The default node options are applied
39
+ to the single TikZ "path" that draws all nodes (and no edges). The default edge
40
+ options are applied to a TikZ "scope" which contains a path for each edge.
41
+
42
+ Examples
43
+ ========
44
+ >>> from pathlib import Path
45
+ >>> import tempfile
46
+ >>> tmp_path = Path(tempfile.gettempdir())
47
+
48
+ >>> G = nx.path_graph(3)
49
+
50
+ The TeX-formatted graph can be written to a file as a standalone document:
51
+
52
+ >>> fpath = tmp_path / "just_my_figure.tex"
53
+ >>> nx.write_latex(G, fpath, as_document=True)
54
+
55
+ >>> with open(fpath) as fh:
56
+ ... print(fh.read())
57
+ \documentclass{report}
58
+ \usepackage{tikz}
59
+ \usepackage{subcaption}
60
+ <BLANKLINE>
61
+ \begin{document}
62
+ \begin{figure}
63
+ \begin{tikzpicture}
64
+ \draw
65
+ (0.0:2) node (0){0}
66
+ (120.0:2) node (1){1}
67
+ (240.0:2) node (2){2};
68
+ \begin{scope}[-]
69
+ \draw (0) to (1);
70
+ \draw (1) to (2);
71
+ \end{scope}
72
+ \end{tikzpicture}
73
+ \end{figure}
74
+ \end{document}
75
+
76
+ Or as a figure to be incorporated in another TeX document:
77
+
78
+ >>> fpath = tmp_path / "my_figure.tex"
79
+ >>> nx.write_latex(G, fpath, as_document=False, caption="P3", latex_label="fig1")
80
+
81
+ >>> with open(fpath) as fh:
82
+ ... print(fh.read())
83
+ \begin{figure}
84
+ \begin{tikzpicture}
85
+ \draw
86
+ (0.0:2) node (0){0}
87
+ (120.0:2) node (1){1}
88
+ (240.0:2) node (2){2};
89
+ \begin{scope}[-]
90
+ \draw (0) to (1);
91
+ \draw (1) to (2);
92
+ \end{scope}
93
+ \end{tikzpicture}
94
+ \caption{P3}\label{fig1}
95
+ \end{figure}
96
+
97
+ The TeX code can be generated programmatically without writing to disk with `to_latex`:
98
+
99
+ >>> latex_code = nx.to_latex(G, as_document=False)
100
+ >>> print(latex_code)
101
+ \begin{figure}
102
+ \begin{tikzpicture}
103
+ \draw
104
+ (0.0:2) node (0){0}
105
+ (120.0:2) node (1){1}
106
+ (240.0:2) node (2){2};
107
+ \begin{scope}[-]
108
+ \draw (0) to (1);
109
+ \draw (1) to (2);
110
+ \end{scope}
111
+ \end{tikzpicture}
112
+ \end{figure}
113
+
114
+ Visualization properties such as colors, line widths, etc. can be changed either
115
+ by looking up values stored as node/edge attributes by name:
116
+
117
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph)
118
+ >>> pos = {n: (n, n) for n in G} # nodes set on a line
119
+
120
+ >>> G.nodes[0]["style"] = "blue"
121
+ >>> G.nodes[2]["style"] = "line width=3,draw"
122
+ >>> G.nodes[3]["label"] = "Stop"
123
+ >>> G.edges[(0, 1)]["label"] = "1st Step"
124
+ >>> G.edges[(0, 1)]["label_opts"] = "near start"
125
+ >>> G.edges[(1, 2)]["style"] = "line width=3"
126
+ >>> G.edges[(1, 2)]["label"] = "2nd Step"
127
+ >>> G.edges[(2, 3)]["style"] = "green"
128
+ >>> G.edges[(2, 3)]["label"] = "3rd Step"
129
+ >>> G.edges[(2, 3)]["label_opts"] = "near end"
130
+
131
+ >>> fpath = tmp_path / "latex_graph.tex"
132
+ >>> opts = { # Name of node/edge attributes that hold visualization options
133
+ ... "node_label": "label",
134
+ ... "edge_label": "label",
135
+ ... "node_options": "style",
136
+ ... "edge_options": "style",
137
+ ... "edge_label_options": "label_opts",
138
+ ... }
139
+ >>> nx.write_latex(G, fpath, pos=pos, as_document=False, **opts)
140
+
141
+ >>> with open(fpath) as fh:
142
+ ... print(fh.read())
143
+ \begin{figure}
144
+ \begin{tikzpicture}
145
+ \draw
146
+ (0, 0) node[blue] (0){0}
147
+ (1, 1) node (1){1}
148
+ (2, 2) node[line width=3,draw] (2){2}
149
+ (3, 3) node (3){Stop};
150
+ \begin{scope}[->]
151
+ \draw (0) to node[near start] {1st Step} (1);
152
+ \draw[line width=3] (1) to node[] {2nd Step} (2);
153
+ \draw[green] (2) to node[near end] {3rd Step} (3);
154
+ \end{scope}
155
+ \end{tikzpicture}
156
+ \end{figure}
157
+
158
+ Or by specifying them manually:
159
+
160
+ >>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
161
+ >>> edge_width = {e: "line width=1.5" for e in G.edges}
162
+ >>> pos = nx.circular_layout(G)
163
+ >>> nx.write_latex(G, fpath, pos=pos, node_options=node_color, edge_options=edge_width)
164
+ >>> with open(fpath) as fh:
165
+ ... print(fh.read())
166
+ \documentclass{report}
167
+ \usepackage{tikz}
168
+ \usepackage{subcaption}
169
+ <BLANKLINE>
170
+ \begin{document}
171
+ \begin{figure}
172
+ \begin{tikzpicture}
173
+ \draw
174
+ (1.0, 0.0) node[red] (0){0}
175
+ (-0.0, 1.0) node[orange] (1){1}
176
+ (-1.0, -0.0) node[blue] (2){2}
177
+ (0.0, -1.0) node[gray!90] (3){3};
178
+ \begin{scope}[->]
179
+ \draw[line width=1.5] (0) to (1);
180
+ \draw[line width=1.5] (1) to (2);
181
+ \draw[line width=1.5] (2) to (3);
182
+ \end{scope}
183
+ \end{tikzpicture}
184
+ \end{figure}
185
+ \end{document}
186
+
187
+ Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
188
+ and view the pdf file created: ``latex_graph.pdf``.
189
+
190
+ If you want **subfigures** each containing one graph, you can input a list of graphs.
191
+
192
+ >>> H1 = nx.path_graph(4)
193
+ >>> H2 = nx.complete_graph(4)
194
+ >>> H3 = nx.path_graph(8)
195
+ >>> H4 = nx.complete_graph(8)
196
+ >>> graphs = [H1, H2, H3, H4]
197
+ >>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
198
+ >>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
199
+
200
+ >>> fpath = tmp_path / "subfigs.tex"
201
+ >>> nx.write_latex(
202
+ ... graphs, fpath, n_rows=2, sub_captions=caps, sub_labels=lbls, as_document=False
203
+ ... )
204
+
205
+ The lines in the output file corresponding to the first two sub figures:
206
+
207
+ >>> with open(fpath) as fh:
208
+ ... lines_from_file = fh.readlines()
209
+ >>> print("".join(lines_from_file[1:34]))
210
+ \begin{subfigure}{0.5\textwidth}
211
+ \begin{tikzpicture}
212
+ \draw
213
+ (0.0:2) node (0){0}
214
+ (90.0:2) node (1){1}
215
+ (180.0:2) node (2){2}
216
+ (270.0:2) node (3){3};
217
+ \begin{scope}[-]
218
+ \draw (0) to (1);
219
+ \draw (1) to (2);
220
+ \draw (2) to (3);
221
+ \end{scope}
222
+ \end{tikzpicture}
223
+ \caption{Path 4}\label{fig2a}
224
+ \end{subfigure}
225
+ \begin{subfigure}{0.5\textwidth}
226
+ \begin{tikzpicture}
227
+ \draw
228
+ (0.0:2) node (0){0}
229
+ (90.0:2) node (1){1}
230
+ (180.0:2) node (2){2}
231
+ (270.0:2) node (3){3};
232
+ \begin{scope}[-]
233
+ \draw (0) to (1);
234
+ \draw (0) to (2);
235
+ \draw (0) to (3);
236
+ \draw (1) to (2);
237
+ \draw (1) to (3);
238
+ \draw (2) to (3);
239
+ \end{scope}
240
+ \end{tikzpicture}
241
+ \caption{Complete graph 4}\label{fig2b}
242
+ \end{subfigure}
243
+ <BLANKLINE>
244
+
245
+ Notes
246
+ -----
247
+ If you want to change the preamble/postamble of the figure/document/subfigure
248
+ environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
249
+ `subfigure_wrapper`. The default values are stored in private variables
250
+ e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
251
+
252
+ References
253
+ ----------
254
+ TikZ: https://tikz.dev/
255
+
256
+ TikZ options details: https://tikz.dev/tikz-actions
257
+ """
258
+
259
+ import networkx as nx
260
+
261
+ __all__ = [
262
+ "to_latex_raw",
263
+ "to_latex",
264
+ "write_latex",
265
+ ]
266
+
267
+
268
+ @nx.utils.not_implemented_for("multigraph")
269
+ def to_latex_raw(
270
+ G,
271
+ pos="pos",
272
+ tikz_options="",
273
+ default_node_options="",
274
+ node_options="node_options",
275
+ node_label="label",
276
+ default_edge_options="",
277
+ edge_options="edge_options",
278
+ edge_label="label",
279
+ edge_label_options="edge_label_options",
280
+ ):
281
+ """Return a string of the LaTeX/TikZ code to draw `G`
282
+
283
+ This function produces just the code for the tikzpicture
284
+ without any enclosing environment.
285
+
286
+ Parameters
287
+ ==========
288
+ G : NetworkX graph
289
+ The NetworkX graph to be drawn
290
+ pos : string or dict (default "pos")
291
+ The name of the node attribute on `G` that holds the position of each node.
292
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
293
+ They can also be strings to denote positions in TikZ style, such as (x, y)
294
+ or (angle:radius).
295
+ If a dict, it should be keyed by node to a position.
296
+ If an empty dict, a circular layout is computed by TikZ.
297
+ tikz_options : string
298
+ The tikzpicture options description defining the options for the picture.
299
+ Often large scale options like `[scale=2]`.
300
+ default_node_options : string
301
+ The draw options for a path of nodes. Individual node options override these.
302
+ node_options : string or dict
303
+ The name of the node attribute on `G` that holds the options for each node.
304
+ Or a dict keyed by node to a string holding the options for that node.
305
+ node_label : string or dict
306
+ The name of the node attribute on `G` that holds the node label (text)
307
+ displayed for each node. If the attribute is "" or not present, the node
308
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
309
+ Or a dict keyed by node to a string holding the label for that node.
310
+ default_edge_options : string
311
+ The options for the scope drawing all edges. The default is "[-]" for
312
+ undirected graphs and "[->]" for directed graphs.
313
+ edge_options : string or dict
314
+ The name of the edge attribute on `G` that holds the options for each edge.
315
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
316
+ "loop," is added to the options for the self-loop edge. Hence you can
317
+ use "[loop above]" explicitly, but the default is "[loop]".
318
+ Or a dict keyed by edge to a string holding the options for that edge.
319
+ edge_label : string or dict
320
+ The name of the edge attribute on `G` that holds the edge label (text)
321
+ displayed for each edge. If the attribute is "" or not present, no edge
322
+ label is drawn.
323
+ Or a dict keyed by edge to a string holding the label for that edge.
324
+ edge_label_options : string or dict
325
+ The name of the edge attribute on `G` that holds the label options for
326
+ each edge. For example, "[sloped,above,blue]". The default is no options.
327
+ Or a dict keyed by edge to a string holding the label options for that edge.
328
+
329
+ Returns
330
+ =======
331
+ latex_code : string
332
+ The text string which draws the desired graph(s) when compiled by LaTeX.
333
+
334
+ See Also
335
+ ========
336
+ to_latex
337
+ write_latex
338
+ """
339
+ i4 = "\n "
340
+ i8 = "\n "
341
+
342
+ # set up position dict
343
+ # TODO allow pos to be None and use a nice TikZ default
344
+ if not isinstance(pos, dict):
345
+ pos = nx.get_node_attributes(G, pos)
346
+ if not pos:
347
+ # circular layout with radius 2
348
+ pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
349
+ for node in G:
350
+ if node not in pos:
351
+ raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
352
+ posnode = pos[node]
353
+ if not isinstance(posnode, str):
354
+ try:
355
+ posx, posy = posnode
356
+ pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
357
+ except (TypeError, ValueError):
358
+ msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
359
+ raise nx.NetworkXError(msg)
360
+
361
+ # set up all the dicts
362
+ if not isinstance(node_options, dict):
363
+ node_options = nx.get_node_attributes(G, node_options)
364
+ if not isinstance(node_label, dict):
365
+ node_label = nx.get_node_attributes(G, node_label)
366
+ if not isinstance(edge_options, dict):
367
+ edge_options = nx.get_edge_attributes(G, edge_options)
368
+ if not isinstance(edge_label, dict):
369
+ edge_label = nx.get_edge_attributes(G, edge_label)
370
+ if not isinstance(edge_label_options, dict):
371
+ edge_label_options = nx.get_edge_attributes(G, edge_label_options)
372
+
373
+ # process default options (add brackets or not)
374
+ topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
375
+ defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
376
+ linestyle = f"{'->' if G.is_directed() else '-'}"
377
+ if default_edge_options == "":
378
+ defe = "[" + linestyle + "]"
379
+ elif "-" in default_edge_options:
380
+ defe = default_edge_options
381
+ else:
382
+ defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
383
+
384
+ # Construct the string line by line
385
+ result = " \\begin{tikzpicture}" + topts
386
+ result += i4 + " \\draw" + defn
387
+ # load the nodes
388
+ for n in G:
389
+ # node options goes inside square brackets
390
+ nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
391
+ # node text goes inside curly brackets {}
392
+ ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
393
+
394
+ result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
395
+ result += ";\n"
396
+
397
+ # load the edges
398
+ result += " \\begin{scope}" + defe
399
+ for edge in G.edges:
400
+ u, v = edge[:2]
401
+ e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
402
+ # add loop options for selfloops if not present
403
+ if u == v and "loop" not in e_opts:
404
+ e_opts = "loop," + e_opts
405
+ e_opts = f"[{e_opts}]" if e_opts != "" else ""
406
+ # TODO -- handle bending of multiedges
407
+
408
+ els = edge_label_options[edge] if edge in edge_label_options else ""
409
+ # edge label options goes inside square brackets []
410
+ els = f"[{els.strip('[]')}]"
411
+ # edge text is drawn using the TikZ node command inside curly brackets {}
412
+ e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
413
+
414
+ result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
415
+
416
+ result += "\n \\end{scope}\n \\end{tikzpicture}\n"
417
+ return result
418
+
419
+
420
+ _DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
421
+ \usepackage{{tikz}}
422
+ \usepackage{{subcaption}}
423
+
424
+ \begin{{document}}
425
+ {content}
426
+ \end{{document}}"""
427
+
428
+
429
+ _FIG_WRAPPER = r"""\begin{{figure}}
430
+ {content}{caption}{label}
431
+ \end{{figure}}"""
432
+
433
+
434
+ _SUBFIG_WRAPPER = r""" \begin{{subfigure}}{{{size}\textwidth}}
435
+ {content}{caption}{label}
436
+ \end{{subfigure}}"""
437
+
438
+
439
+ def to_latex(
440
+ Gbunch,
441
+ pos="pos",
442
+ tikz_options="",
443
+ default_node_options="",
444
+ node_options="node_options",
445
+ node_label="node_label",
446
+ default_edge_options="",
447
+ edge_options="edge_options",
448
+ edge_label="edge_label",
449
+ edge_label_options="edge_label_options",
450
+ caption="",
451
+ latex_label="",
452
+ sub_captions=None,
453
+ sub_labels=None,
454
+ n_rows=1,
455
+ as_document=True,
456
+ document_wrapper=_DOC_WRAPPER_TIKZ,
457
+ figure_wrapper=_FIG_WRAPPER,
458
+ subfigure_wrapper=_SUBFIG_WRAPPER,
459
+ ):
460
+ """Return latex code to draw the graph(s) in `Gbunch`
461
+
462
+ The TikZ drawing utility in LaTeX is used to draw the graph(s).
463
+ If `Gbunch` is a graph, it is drawn in a figure environment.
464
+ If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
465
+ within a single figure environment.
466
+
467
+ If `as_document` is True, the figure is wrapped inside a document environment
468
+ so that the resulting string is ready to be compiled by LaTeX. Otherwise,
469
+ the string is ready for inclusion in a larger tex document using ``\\include``
470
+ or ``\\input`` statements.
471
+
472
+ Parameters
473
+ ==========
474
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
475
+ The NetworkX graph to be drawn or an iterable of graphs
476
+ to be drawn inside subfigures of a single figure.
477
+ pos : string or list of strings
478
+ The name of the node attribute on `G` that holds the position of each node.
479
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
480
+ They can also be strings to denote positions in TikZ style, such as (x, y)
481
+ or (angle:radius).
482
+ If a dict, it should be keyed by node to a position.
483
+ If an empty dict, a circular layout is computed by TikZ.
484
+ If you are drawing many graphs in subfigures, use a list of position dicts.
485
+ tikz_options : string
486
+ The tikzpicture options description defining the options for the picture.
487
+ Often large scale options like `[scale=2]`.
488
+ default_node_options : string
489
+ The draw options for a path of nodes. Individual node options override these.
490
+ node_options : string or dict
491
+ The name of the node attribute on `G` that holds the options for each node.
492
+ Or a dict keyed by node to a string holding the options for that node.
493
+ node_label : string or dict
494
+ The name of the node attribute on `G` that holds the node label (text)
495
+ displayed for each node. If the attribute is "" or not present, the node
496
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
497
+ Or a dict keyed by node to a string holding the label for that node.
498
+ default_edge_options : string
499
+ The options for the scope drawing all edges. The default is "[-]" for
500
+ undirected graphs and "[->]" for directed graphs.
501
+ edge_options : string or dict
502
+ The name of the edge attribute on `G` that holds the options for each edge.
503
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
504
+ "loop," is added to the options for the self-loop edge. Hence you can
505
+ use "[loop above]" explicitly, but the default is "[loop]".
506
+ Or a dict keyed by edge to a string holding the options for that edge.
507
+ edge_label : string or dict
508
+ The name of the edge attribute on `G` that holds the edge label (text)
509
+ displayed for each edge. If the attribute is "" or not present, no edge
510
+ label is drawn.
511
+ Or a dict keyed by edge to a string holding the label for that edge.
512
+ edge_label_options : string or dict
513
+ The name of the edge attribute on `G` that holds the label options for
514
+ each edge. For example, "[sloped,above,blue]". The default is no options.
515
+ Or a dict keyed by edge to a string holding the label options for that edge.
516
+ caption : string
517
+ The caption string for the figure environment
518
+ latex_label : string
519
+ The latex label used for the figure for easy referral from the main text
520
+ sub_captions : list of strings
521
+ The sub_caption string for each subfigure in the figure
522
+ sub_labels : list of strings
523
+ The latex label for each subfigure in the figure
524
+ n_rows : int
525
+ The number of rows of subfigures to arrange for multiple graphs
526
+ as_document : bool
527
+ Whether to wrap the latex code in a document environment for compiling
528
+ document_wrapper : formatted text string with variable ``content``.
529
+ This text is called to evaluate the content embedded in a document
530
+ environment with a preamble setting up TikZ.
531
+ figure_wrapper : formatted text string
532
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
533
+ It wraps the content and if a caption is provided, adds the latex code for
534
+ that caption, and if a label is provided, adds the latex code for a label.
535
+ subfigure_wrapper : formatted text string
536
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
537
+ It wraps the content and if a caption is provided, adds the latex code for
538
+ that caption, and if a label is provided, adds the latex code for a label.
539
+ The size is the vertical size of each row of subfigures as a fraction.
540
+
541
+ Returns
542
+ =======
543
+ latex_code : string
544
+ The text string which draws the desired graph(s) when compiled by LaTeX.
545
+
546
+ See Also
547
+ ========
548
+ write_latex
549
+ to_latex_raw
550
+ """
551
+ if hasattr(Gbunch, "adj"):
552
+ raw = to_latex_raw(
553
+ Gbunch,
554
+ pos,
555
+ tikz_options,
556
+ default_node_options,
557
+ node_options,
558
+ node_label,
559
+ default_edge_options,
560
+ edge_options,
561
+ edge_label,
562
+ edge_label_options,
563
+ )
564
+ else: # iterator of graphs
565
+ sbf = subfigure_wrapper
566
+ size = 1 / n_rows
567
+
568
+ N = len(Gbunch)
569
+ if isinstance(pos, str | dict):
570
+ pos = [pos] * N
571
+ if sub_captions is None:
572
+ sub_captions = [""] * N
573
+ if sub_labels is None:
574
+ sub_labels = [""] * N
575
+ if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
576
+ raise nx.NetworkXError(
577
+ "length of Gbunch, sub_captions and sub_figures must agree"
578
+ )
579
+
580
+ raw = ""
581
+ for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
582
+ subraw = to_latex_raw(
583
+ G,
584
+ pos,
585
+ tikz_options,
586
+ default_node_options,
587
+ node_options,
588
+ node_label,
589
+ default_edge_options,
590
+ edge_options,
591
+ edge_label,
592
+ edge_label_options,
593
+ )
594
+ cap = f" \\caption{{{subcap}}}" if subcap else ""
595
+ lbl = f"\\label{{{sublbl}}}" if sublbl else ""
596
+ raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
597
+ raw += "\n"
598
+
599
+ # put raw latex code into a figure environment and optionally into a document
600
+ raw = raw[:-1]
601
+ cap = f"\n \\caption{{{caption}}}" if caption else ""
602
+ lbl = f"\\label{{{latex_label}}}" if latex_label else ""
603
+ fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
604
+ if as_document:
605
+ return document_wrapper.format(content=fig)
606
+ return fig
607
+
608
+
609
+ @nx.utils.open_file(1, mode="w")
610
+ def write_latex(Gbunch, path, **options):
611
+ """Write the latex code to draw the graph(s) onto `path`.
612
+
613
+ This convenience function creates the latex drawing code as a string
614
+ and writes that to a file ready to be compiled when `as_document` is True
615
+ or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
616
+
617
+ The `path` argument can be a string filename or a file handle to write to.
618
+
619
+ Parameters
620
+ ----------
621
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
622
+ If Gbunch is a graph, it is drawn in a figure environment.
623
+ If Gbunch is an iterable of graphs, each is drawn in a subfigure
624
+ environment within a single figure environment.
625
+ path : string or file
626
+ Filename or file handle to write to.
627
+ Filenames ending in .gz or .bz2 will be compressed.
628
+ options : dict
629
+ By default, TikZ is used with options: (others are ignored)::
630
+
631
+ pos : string or dict or list
632
+ The name of the node attribute on `G` that holds the position of each node.
633
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
634
+ They can also be strings to denote positions in TikZ style, such as (x, y)
635
+ or (angle:radius).
636
+ If a dict, it should be keyed by node to a position.
637
+ If an empty dict, a circular layout is computed by TikZ.
638
+ If you are drawing many graphs in subfigures, use a list of position dicts.
639
+ tikz_options : string
640
+ The tikzpicture options description defining the options for the picture.
641
+ Often large scale options like `[scale=2]`.
642
+ default_node_options : string
643
+ The draw options for a path of nodes. Individual node options override these.
644
+ node_options : string or dict
645
+ The name of the node attribute on `G` that holds the options for each node.
646
+ Or a dict keyed by node to a string holding the options for that node.
647
+ node_label : string or dict
648
+ The name of the node attribute on `G` that holds the node label (text)
649
+ displayed for each node. If the attribute is "" or not present, the node
650
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
651
+ Or a dict keyed by node to a string holding the label for that node.
652
+ default_edge_options : string
653
+ The options for the scope drawing all edges. The default is "[-]" for
654
+ undirected graphs and "[->]" for directed graphs.
655
+ edge_options : string or dict
656
+ The name of the edge attribute on `G` that holds the options for each edge.
657
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
658
+ "loop," is added to the options for the self-loop edge. Hence you can
659
+ use "[loop above]" explicitly, but the default is "[loop]".
660
+ Or a dict keyed by edge to a string holding the options for that edge.
661
+ edge_label : string or dict
662
+ The name of the edge attribute on `G` that holds the edge label (text)
663
+ displayed for each edge. If the attribute is "" or not present, no edge
664
+ label is drawn.
665
+ Or a dict keyed by edge to a string holding the label for that edge.
666
+ edge_label_options : string or dict
667
+ The name of the edge attribute on `G` that holds the label options for
668
+ each edge. For example, "[sloped,above,blue]". The default is no options.
669
+ Or a dict keyed by edge to a string holding the label options for that edge.
670
+ caption : string
671
+ The caption string for the figure environment
672
+ latex_label : string
673
+ The latex label used for the figure for easy referral from the main text
674
+ sub_captions : list of strings
675
+ The sub_caption string for each subfigure in the figure
676
+ sub_latex_labels : list of strings
677
+ The latex label for each subfigure in the figure
678
+ n_rows : int
679
+ The number of rows of subfigures to arrange for multiple graphs
680
+ as_document : bool
681
+ Whether to wrap the latex code in a document environment for compiling
682
+ document_wrapper : formatted text string with variable ``content``.
683
+ This text is called to evaluate the content embedded in a document
684
+ environment with a preamble setting up the TikZ syntax.
685
+ figure_wrapper : formatted text string
686
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
687
+ It wraps the content and if a caption is provided, adds the latex code for
688
+ that caption, and if a label is provided, adds the latex code for a label.
689
+ subfigure_wrapper : formatted text string
690
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
691
+ It wraps the content and if a caption is provided, adds the latex code for
692
+ that caption, and if a label is provided, adds the latex code for a label.
693
+ The size is the vertical size of each row of subfigures as a fraction.
694
+
695
+ See Also
696
+ ========
697
+ to_latex
698
+ """
699
+ path.write(to_latex(Gbunch, **options))
venv/lib/python3.14/site-packages/networkx/drawing/nx_pydot.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ *****
3
+ Pydot
4
+ *****
5
+
6
+ Import and export NetworkX graphs in Graphviz dot format using pydot.
7
+
8
+ Either this module or nx_agraph can be used to interface with graphviz.
9
+
10
+ Examples
11
+ --------
12
+ >>> G = nx.complete_graph(5)
13
+ >>> PG = nx.nx_pydot.to_pydot(G)
14
+ >>> H = nx.nx_pydot.from_pydot(PG)
15
+
16
+ See Also
17
+ --------
18
+ - pydot: https://github.com/erocarrera/pydot
19
+ - Graphviz: https://www.graphviz.org
20
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
21
+ """
22
+
23
+ from locale import getpreferredencoding
24
+
25
+ import networkx as nx
26
+ from networkx.utils import open_file
27
+
28
+ __all__ = [
29
+ "write_dot",
30
+ "read_dot",
31
+ "graphviz_layout",
32
+ "pydot_layout",
33
+ "to_pydot",
34
+ "from_pydot",
35
+ ]
36
+
37
+
38
+ @open_file(1, mode="w")
39
+ def write_dot(G, path):
40
+ """Write NetworkX graph G to Graphviz dot format on path.
41
+
42
+ Parameters
43
+ ----------
44
+ G : NetworkX graph
45
+
46
+ path : string or file
47
+ Filename or file handle for data output.
48
+ Filenames ending in .gz or .bz2 will be compressed.
49
+ """
50
+ P = to_pydot(G)
51
+ path.write(P.to_string())
52
+ return
53
+
54
+
55
+ @open_file(0, mode="r")
56
+ @nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
57
+ def read_dot(path):
58
+ """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
59
+ dot file with the passed path.
60
+
61
+ If this file contains multiple graphs, only the first such graph is
62
+ returned. All graphs _except_ the first are silently ignored.
63
+
64
+ Parameters
65
+ ----------
66
+ path : str or file
67
+ Filename or file handle to read.
68
+ Filenames ending in .gz or .bz2 will be decompressed.
69
+
70
+ Returns
71
+ -------
72
+ G : MultiGraph or MultiDiGraph
73
+ A :class:`MultiGraph` or :class:`MultiDiGraph`.
74
+
75
+ Notes
76
+ -----
77
+ Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
78
+ :class:`MultiGraph`.
79
+ """
80
+ import pydot
81
+
82
+ data = path.read()
83
+
84
+ # List of one or more "pydot.Dot" instances deserialized from this file.
85
+ P_list = pydot.graph_from_dot_data(data)
86
+
87
+ # Convert only the first such instance into a NetworkX graph.
88
+ return from_pydot(P_list[0])
89
+
90
+
91
+ @nx._dispatchable(graphs=None, returns_graph=True)
92
+ def from_pydot(P):
93
+ """Returns a NetworkX graph from a Pydot graph.
94
+
95
+ Parameters
96
+ ----------
97
+ P : Pydot graph
98
+ A graph created with Pydot
99
+
100
+ Returns
101
+ -------
102
+ G : NetworkX multigraph
103
+ A MultiGraph or MultiDiGraph.
104
+
105
+ Examples
106
+ --------
107
+ >>> K5 = nx.complete_graph(5)
108
+ >>> A = nx.nx_pydot.to_pydot(K5)
109
+ >>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
110
+
111
+ # make a Graph instead of MultiGraph
112
+ >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
113
+
114
+ """
115
+ # NOTE: Pydot v3 expects a dummy argument whereas Pydot v4 doesn't
116
+ # Remove the try-except when Pydot v4 becomes the minimum supported version
117
+ try:
118
+ strict = P.get_strict()
119
+ except TypeError:
120
+ strict = P.get_strict(None) # pydot bug: get_strict() shouldn't take argument
121
+ multiedges = not strict
122
+
123
+ if P.get_type() == "graph": # undirected
124
+ if multiedges:
125
+ N = nx.MultiGraph()
126
+ else:
127
+ N = nx.Graph()
128
+ else:
129
+ if multiedges:
130
+ N = nx.MultiDiGraph()
131
+ else:
132
+ N = nx.DiGraph()
133
+
134
+ # assign defaults
135
+ name = P.get_name().strip('"')
136
+ if name != "":
137
+ N.name = name
138
+
139
+ # add nodes, attributes to N.node_attr
140
+ for p in P.get_node_list():
141
+ n = p.get_name().strip('"')
142
+ if n in ("node", "graph", "edge"):
143
+ continue
144
+ N.add_node(n, **p.get_attributes())
145
+
146
+ # add edges
147
+ for e in P.get_edge_list():
148
+ u = e.get_source()
149
+ v = e.get_destination()
150
+ attr = e.get_attributes()
151
+ s = []
152
+ d = []
153
+
154
+ if isinstance(u, str):
155
+ s.append(u.strip('"'))
156
+ else:
157
+ for unodes in u["nodes"]:
158
+ s.append(unodes.strip('"'))
159
+
160
+ if isinstance(v, str):
161
+ d.append(v.strip('"'))
162
+ else:
163
+ for vnodes in v["nodes"]:
164
+ d.append(vnodes.strip('"'))
165
+
166
+ for source_node in s:
167
+ for destination_node in d:
168
+ N.add_edge(source_node, destination_node, **attr)
169
+
170
+ # add default attributes for graph, nodes, edges
171
+ pattr = P.get_attributes()
172
+ if pattr:
173
+ N.graph["graph"] = pattr
174
+ try:
175
+ N.graph["node"] = P.get_node_defaults()[0]
176
+ except (IndexError, TypeError):
177
+ pass # N.graph['node']={}
178
+ try:
179
+ N.graph["edge"] = P.get_edge_defaults()[0]
180
+ except (IndexError, TypeError):
181
+ pass # N.graph['edge']={}
182
+ return N
183
+
184
+
185
+ def to_pydot(N):
186
+ """Returns a pydot graph from a NetworkX graph N.
187
+
188
+ Parameters
189
+ ----------
190
+ N : NetworkX graph
191
+ A graph created with NetworkX
192
+
193
+ Examples
194
+ --------
195
+ >>> K5 = nx.complete_graph(5)
196
+ >>> P = nx.nx_pydot.to_pydot(K5)
197
+
198
+ Notes
199
+ -----
200
+
201
+ """
202
+ import pydot
203
+
204
+ # set Graphviz graph type
205
+ if N.is_directed():
206
+ graph_type = "digraph"
207
+ else:
208
+ graph_type = "graph"
209
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
210
+
211
+ name = N.name
212
+ graph_defaults = N.graph.get("graph", {})
213
+ if name == "":
214
+ P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
215
+ else:
216
+ P = pydot.Dot(
217
+ f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
218
+ )
219
+ try:
220
+ P.set_node_defaults(**N.graph["node"])
221
+ except KeyError:
222
+ pass
223
+ try:
224
+ P.set_edge_defaults(**N.graph["edge"])
225
+ except KeyError:
226
+ pass
227
+
228
+ for n, nodedata in N.nodes(data=True):
229
+ str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
230
+ n = str(n)
231
+ p = pydot.Node(n, **str_nodedata)
232
+ P.add_node(p)
233
+
234
+ if N.is_multigraph():
235
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
236
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
237
+ u, v = str(u), str(v)
238
+ edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
239
+ P.add_edge(edge)
240
+
241
+ else:
242
+ for u, v, edgedata in N.edges(data=True):
243
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
244
+ u, v = str(u), str(v)
245
+ edge = pydot.Edge(u, v, **str_edgedata)
246
+ P.add_edge(edge)
247
+ return P
248
+
249
+
250
+ def graphviz_layout(G, prog="neato", root=None):
251
+ """Create node positions using Pydot and Graphviz.
252
+
253
+ Returns a dictionary of positions keyed by node.
254
+
255
+ Parameters
256
+ ----------
257
+ G : NetworkX Graph
258
+ The graph for which the layout is computed.
259
+ prog : string (default: 'neato')
260
+ The name of the GraphViz program to use for layout.
261
+ Options depend on GraphViz version but may include:
262
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
263
+ root : Node from G or None (default: None)
264
+ The node of G from which to start some layout algorithms.
265
+
266
+ Returns
267
+ -------
268
+ Dictionary of (x, y) positions keyed by node.
269
+
270
+ Examples
271
+ --------
272
+ >>> G = nx.complete_graph(4)
273
+ >>> pos = nx.nx_pydot.graphviz_layout(G)
274
+ >>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
275
+
276
+ Notes
277
+ -----
278
+ This is a wrapper for pydot_layout.
279
+ """
280
+ return pydot_layout(G=G, prog=prog, root=root)
281
+
282
+
283
+ def pydot_layout(G, prog="neato", root=None):
284
+ """Create node positions using :mod:`pydot` and Graphviz.
285
+
286
+ Parameters
287
+ ----------
288
+ G : Graph
289
+ NetworkX graph to be laid out.
290
+ prog : string (default: 'neato')
291
+ Name of the GraphViz command to use for layout.
292
+ Options depend on GraphViz version but may include:
293
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
294
+ root : Node from G or None (default: None)
295
+ The node of G from which to start some layout algorithms.
296
+
297
+ Returns
298
+ -------
299
+ dict
300
+ Dictionary of positions keyed by node.
301
+
302
+ Examples
303
+ --------
304
+ >>> G = nx.complete_graph(4)
305
+ >>> pos = nx.nx_pydot.pydot_layout(G)
306
+ >>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
307
+
308
+ Notes
309
+ -----
310
+ If you use complex node objects, they may have the same string
311
+ representation and GraphViz could treat them as the same node.
312
+ The layout may assign both nodes a single location. See Issue #1568
313
+ If this occurs in your case, consider relabeling the nodes just
314
+ for the layout computation using something similar to::
315
+
316
+ H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
317
+ H_layout = nx.nx_pydot.pydot_layout(H, prog="dot")
318
+ G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
319
+
320
+ """
321
+ import pydot
322
+
323
+ P = to_pydot(G)
324
+ if root is not None:
325
+ P.set("root", str(root))
326
+
327
+ # List of low-level bytes comprising a string in the dot language converted
328
+ # from the passed graph with the passed external GraphViz command.
329
+ D_bytes = P.create_dot(prog=prog)
330
+
331
+ # Unique string decoded from these bytes with the preferred locale encoding
332
+ D = str(D_bytes, encoding=getpreferredencoding())
333
+
334
+ if D == "": # no data returned
335
+ print(f"Graphviz layout with {prog} failed")
336
+ print()
337
+ print("To debug what happened try:")
338
+ print("P = nx.nx_pydot.to_pydot(G)")
339
+ print('P.write_dot("file.dot")')
340
+ print(f"And then run {prog} on file.dot")
341
+ return
342
+
343
+ # List of one or more "pydot.Dot" instances deserialized from this string.
344
+ Q_list = pydot.graph_from_dot_data(D)
345
+ assert len(Q_list) == 1
346
+
347
+ # The first and only such instance, as guaranteed by the above assertion.
348
+ Q = Q_list[0]
349
+
350
+ node_pos = {}
351
+ for n in G.nodes():
352
+ str_n = str(n)
353
+ node = Q.get_node(pydot.quote_id_if_necessary(str_n))
354
+
355
+ if isinstance(node, list):
356
+ node = node[0]
357
+ pos = node.get_pos()[1:-1] # strip leading and trailing double quotes
358
+ if pos is not None:
359
+ xx, yy = pos.split(",")
360
+ node_pos[n] = (float(xx), float(yy))
361
+ return node_pos
venv/lib/python3.14/site-packages/networkx/drawing/nx_pylab.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.14/site-packages/networkx/drawing/tests/__init__.py ADDED
File without changes
venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_complex.png ADDED

Git LFS Details

  • SHA256: 466b378fe0e91e310023be3322c0674b8c90428de5c22885fd14f9020873c520
  • Pointer size: 131 Bytes
  • Size of remote file: 140 kB
venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_empty_graph.png ADDED
venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_house_with_colors.png ADDED
venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_labels_and_colors.png ADDED
venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_display_shortest_path.png ADDED
venv/lib/python3.14/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png ADDED
venv/lib/python3.14/site-packages/networkx/drawing/tests/test_agraph.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for PyGraphviz interface."""
2
+
3
+ import warnings
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
9
+
10
+ pygraphviz = pytest.importorskip("pygraphviz")
11
+
12
+
13
+ class TestAGraph:
14
+ def build_graph(self, G):
15
+ edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")]
16
+ G.add_edges_from(edges)
17
+ G.add_node("E")
18
+ G.graph["metal"] = "bronze"
19
+ return G
20
+
21
+ def assert_equal(self, G1, G2):
22
+ assert nodes_equal(G1.nodes(), G2.nodes())
23
+ assert edges_equal(G1.edges(), G2.edges(), directed=G1.is_directed())
24
+ assert G1.graph["metal"] == G2.graph["metal"]
25
+
26
+ @pytest.mark.parametrize(
27
+ "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
28
+ )
29
+ def test_agraph_roundtripping(self, G, tmp_path):
30
+ G = self.build_graph(G)
31
+ A = nx.nx_agraph.to_agraph(G)
32
+ H = nx.nx_agraph.from_agraph(A)
33
+ self.assert_equal(G, H)
34
+
35
+ fname = tmp_path / "test.dot"
36
+ nx.drawing.nx_agraph.write_dot(H, fname)
37
+ Hin = nx.nx_agraph.read_dot(fname)
38
+ self.assert_equal(H, Hin)
39
+
40
+ fname = tmp_path / "fh_test.dot"
41
+ with open(fname, "w") as fh:
42
+ nx.drawing.nx_agraph.write_dot(H, fh)
43
+
44
+ with open(fname) as fh:
45
+ Hin = nx.nx_agraph.read_dot(fh)
46
+ self.assert_equal(H, Hin)
47
+
48
+ def test_from_agraph_name(self):
49
+ G = nx.Graph(name="test")
50
+ A = nx.nx_agraph.to_agraph(G)
51
+ H = nx.nx_agraph.from_agraph(A)
52
+ assert G.name == "test"
53
+
54
+ @pytest.mark.parametrize(
55
+ "graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
56
+ )
57
+ def test_from_agraph_create_using(self, graph_class):
58
+ G = nx.path_graph(3)
59
+ A = nx.nx_agraph.to_agraph(G)
60
+ H = nx.nx_agraph.from_agraph(A, create_using=graph_class)
61
+ assert isinstance(H, graph_class)
62
+
63
+ def test_from_agraph_named_edges(self):
64
+ # Create an AGraph from an existing (non-multi) Graph
65
+ G = nx.Graph()
66
+ G.add_nodes_from([0, 1])
67
+ A = nx.nx_agraph.to_agraph(G)
68
+ # Add edge (+ name, given by key) to the AGraph
69
+ A.add_edge(0, 1, key="foo")
70
+ # Verify a.name roundtrips out to 'key' in from_agraph
71
+ H = nx.nx_agraph.from_agraph(A)
72
+ assert isinstance(H, nx.Graph)
73
+ assert ("0", "1", {"key": "foo"}) in H.edges(data=True)
74
+
75
+ def test_to_agraph_with_nodedata(self):
76
+ G = nx.Graph()
77
+ G.add_node(1, color="red")
78
+ A = nx.nx_agraph.to_agraph(G)
79
+ assert dict(A.nodes()[0].attr) == {"color": "red"}
80
+
81
+ @pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph))
82
+ def test_to_agraph_with_edgedata(self, graph_class):
83
+ G = graph_class()
84
+ G.add_nodes_from([0, 1])
85
+ G.add_edge(0, 1, color="yellow")
86
+ A = nx.nx_agraph.to_agraph(G)
87
+ assert dict(A.edges()[0].attr) == {"color": "yellow"}
88
+
89
+ def test_view_pygraphviz_path(self, tmp_path):
90
+ G = nx.complete_graph(3)
91
+ input_path = str(tmp_path / "graph.png")
92
+ out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False)
93
+ assert out_path == input_path
94
+ # Ensure file is not empty
95
+ with open(input_path, "rb") as fh:
96
+ data = fh.read()
97
+ assert len(data) > 0
98
+
99
+ def test_view_pygraphviz_file_suffix(self, tmp_path):
100
+ G = nx.complete_graph(3)
101
+ path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False)
102
+ assert path[-6:] == "_1.png"
103
+
104
+ def test_view_pygraphviz(self):
105
+ G = nx.Graph() # "An empty graph cannot be drawn."
106
+ pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
107
+ G = nx.barbell_graph(4, 6)
108
+ nx.nx_agraph.view_pygraphviz(G, show=False)
109
+
110
+ def test_view_pygraphviz_edgelabel(self):
111
+ G = nx.Graph()
112
+ G.add_edge(1, 2, weight=7)
113
+ G.add_edge(2, 3, weight=8)
114
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False)
115
+ for edge in A.edges():
116
+ assert edge.attr["weight"] in ("7", "8")
117
+
118
+ def test_view_pygraphviz_callable_edgelabel(self):
119
+ G = nx.complete_graph(3)
120
+
121
+ def foo_label(data):
122
+ return "foo"
123
+
124
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False)
125
+ for edge in A.edges():
126
+ assert edge.attr["label"] == "foo"
127
+
128
+ def test_view_pygraphviz_multigraph_edgelabels(self):
129
+ G = nx.MultiGraph()
130
+ G.add_edge(0, 1, key=0, name="left_fork")
131
+ G.add_edge(0, 1, key=1, name="right_fork")
132
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False)
133
+ edges = A.edges()
134
+ assert len(edges) == 2
135
+ for edge in edges:
136
+ assert edge.attr["label"].strip() in ("left_fork", "right_fork")
137
+
138
+ def test_graph_with_reserved_keywords(self):
139
+ # test attribute/keyword clash case for #1582
140
+ # node: n
141
+ # edges: u,v
142
+ G = nx.Graph()
143
+ G = self.build_graph(G)
144
+ G.nodes["E"]["n"] = "keyword"
145
+ G.edges[("A", "B")]["u"] = "keyword"
146
+ G.edges[("A", "B")]["v"] = "keyword"
147
+ A = nx.nx_agraph.to_agraph(G)
148
+
149
+ def test_view_pygraphviz_no_added_attrs_to_input(self):
150
+ G = nx.complete_graph(2)
151
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
152
+ assert G.graph == {}
153
+
154
+ @pytest.mark.xfail(reason="known bug in clean_attrs")
155
+ def test_view_pygraphviz_leaves_input_graph_unmodified(self):
156
+ G = nx.complete_graph(2)
157
+ # Add entries to graph dict that to_agraph handles specially
158
+ G.graph["node"] = {"width": "0.80"}
159
+ G.graph["edge"] = {"fontsize": "14"}
160
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
161
+ assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}}
162
+
163
+ def test_graph_with_AGraph_attrs(self):
164
+ G = nx.complete_graph(2)
165
+ # Add entries to graph dict that to_agraph handles specially
166
+ G.graph["node"] = {"width": "0.80"}
167
+ G.graph["edge"] = {"fontsize": "14"}
168
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
169
+ # Ensure user-specified values are not lost
170
+ assert dict(A.node_attr)["width"] == "0.80"
171
+ assert dict(A.edge_attr)["fontsize"] == "14"
172
+
173
+ def test_round_trip_empty_graph(self):
174
+ G = nx.Graph()
175
+ A = nx.nx_agraph.to_agraph(G)
176
+ H = nx.nx_agraph.from_agraph(A)
177
+ assert graphs_equal(G, H)
178
+ AA = nx.nx_agraph.to_agraph(H)
179
+ HH = nx.nx_agraph.from_agraph(AA)
180
+ assert graphs_equal(H, HH)
181
+ assert graphs_equal(G, HH)
182
+
183
+ @pytest.mark.xfail(reason="integer->string node conversion in round trip")
184
+ def test_round_trip_integer_nodes(self):
185
+ G = nx.complete_graph(3)
186
+ A = nx.nx_agraph.to_agraph(G)
187
+ H = nx.nx_agraph.from_agraph(A)
188
+ assert graphs_equal(G, H)
189
+
190
+ def test_graphviz_alias(self):
191
+ G = self.build_graph(nx.Graph())
192
+ pos_graphviz = nx.nx_agraph.graphviz_layout(G)
193
+ pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G)
194
+ assert pos_graphviz == pos_pygraphviz
195
+
196
+ @pytest.mark.parametrize("root", range(5))
197
+ def test_pygraphviz_layout_root(self, root):
198
+ # NOTE: test depends on layout prog being deterministic
199
+ G = nx.complete_graph(5)
200
+ A = nx.nx_agraph.to_agraph(G)
201
+ # Get layout with root arg is not None
202
+ pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root)
203
+ # Equivalent layout directly on AGraph
204
+ A.layout(args=f"-Groot={root}", prog="circo")
205
+ # Parse AGraph layout
206
+ a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(","))
207
+ assert pygv_layout[1] == a1_pos
208
+
209
+ def test_2d_layout(self):
210
+ G = nx.Graph()
211
+ G = self.build_graph(G)
212
+ G.graph["dimen"] = 2
213
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
214
+ pos = list(pos.values())
215
+ assert len(pos) == 5
216
+ assert len(pos[0]) == 2
217
+
218
+ def test_3d_layout(self):
219
+ G = nx.Graph()
220
+ G = self.build_graph(G)
221
+ G.graph["dimen"] = 3
222
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
223
+ pos = list(pos.values())
224
+ assert len(pos) == 5
225
+ assert len(pos[0]) == 3
226
+
227
+ def test_no_warnings_raised(self):
228
+ # Test that no warnings are raised when Networkx graph
229
+ # is converted to Pygraphviz graph and 'pos'
230
+ # attribute is given
231
+ G = nx.Graph()
232
+ G.add_node(0, pos=(0, 0))
233
+ G.add_node(1, pos=(1, 1))
234
+ A = nx.nx_agraph.to_agraph(G)
235
+ with warnings.catch_warnings(record=True) as record:
236
+ A.layout()
237
+ assert len(record) == 0
238
+
239
+ def test_to_agraph_preserves_string_positions(self):
240
+ # see gh-8203
241
+ AG = pygraphviz.AGraph(directed=True)
242
+ AG.add_node("1", label="1", pos="0.0,0.0!")
243
+ AG.add_node("2", label="2", pos="100.0,0.0!")
244
+ AG.add_edge("1", "2")
245
+
246
+ G = nx.nx_agraph.from_agraph(AG)
247
+ A = nx.nx_agraph.to_agraph(G)
248
+
249
+ assert A.get_node("1").attr["pos"] == "0.0,0.0!"
250
+ assert A.get_node("2").attr["pos"] == "100.0,0.0!"
251
+
252
+ def test_to_agraph_converts_tuple_positions(self):
253
+ G = nx.DiGraph()
254
+ G.add_node("1", pos=(0.0, 0.0))
255
+ G.add_node("2", pos=(100.0, 50.0))
256
+ G.add_edge("1", "2")
257
+
258
+ A = nx.nx_agraph.to_agraph(G)
259
+
260
+ assert A.get_node("1").attr["pos"] == "0.0,0.0!"
261
+ assert A.get_node("2").attr["pos"] == "100.0,50.0!"
venv/lib/python3.14/site-packages/networkx/drawing/tests/test_image_comparison_pylab_mpl.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for explicit image comparison with pytest-mpl."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+ pytest.importorskip("pytest_mpl")
8
+
9
+ mpl = pytest.importorskip("matplotlib")
10
+ mpl.use("PS")
11
+ plt = pytest.importorskip("matplotlib.pyplot")
12
+ plt.rcParams["text.usetex"] = False
13
+ np = pytest.importorskip("numpy")
14
+
15
+
16
+ @pytest.mark.mpl_image_compare
17
+ def test_display_house_with_colors():
18
+ """
19
+ Originally, I wanted to use the exact samge image as test_house_with_colors.
20
+ But I can't seem to find the correct value for the margins to get the figures
21
+ to line up perfectly. To the human eye, these visualizations are basically the
22
+ same.
23
+ """
24
+ G = nx.house_graph()
25
+ fig, ax = plt.subplots()
26
+ nx.set_node_attributes(
27
+ G, {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}, "pos"
28
+ )
29
+ nx.set_node_attributes(
30
+ G,
31
+ {
32
+ n: {
33
+ "size": 3000 if n != 4 else 2000,
34
+ "color": "tab:blue" if n != 4 else "tab:orange",
35
+ }
36
+ for n in G.nodes()
37
+ },
38
+ )
39
+ nx.display(
40
+ G,
41
+ node_pos="pos",
42
+ edge_alpha=0.5,
43
+ edge_width=6,
44
+ node_label=None,
45
+ node_border_color="k",
46
+ )
47
+ ax.margins(0.17)
48
+ plt.tight_layout()
49
+ plt.axis("off")
50
+ return fig
51
+
52
+
53
+ @pytest.mark.mpl_image_compare
54
+ def test_display_labels_and_colors():
55
+ """See 'Labels and Colors' gallery example"""
56
+ fig, ax = plt.subplots()
57
+ G = nx.cubical_graph()
58
+ pos = nx.spring_layout(G, seed=3113794652) # positions for all nodes
59
+ nx.set_node_attributes(G, pos, "pos") # Will not be needed after PR 7571
60
+ labels = iter(
61
+ [
62
+ r"$a$",
63
+ r"$b$",
64
+ r"$c$",
65
+ r"$d$",
66
+ r"$\alpha$",
67
+ r"$\beta$",
68
+ r"$\gamma$",
69
+ r"$\delta$",
70
+ ]
71
+ )
72
+ nx.set_node_attributes(
73
+ G,
74
+ {
75
+ n: {
76
+ "size": 800,
77
+ "alpha": 0.9,
78
+ "color": "tab:red" if n < 4 else "tab:blue",
79
+ "label": {"label": next(labels), "size": 22, "color": "whitesmoke"},
80
+ }
81
+ for n in G.nodes()
82
+ },
83
+ )
84
+
85
+ nx.display(G, node_pos="pos", edge_color="tab:grey")
86
+
87
+ # The tricky bit is the highlighted colors for the edges
88
+ edgelist = [(0, 1), (1, 2), (2, 3), (0, 3)]
89
+ nx.set_edge_attributes(
90
+ G,
91
+ {
92
+ (u, v): {
93
+ "width": 8,
94
+ "alpha": 0.5,
95
+ "color": "tab:red",
96
+ "visible": (u, v) in edgelist,
97
+ }
98
+ for u, v in G.edges()
99
+ },
100
+ )
101
+ nx.display(G, node_pos="pos", node_visible=False)
102
+ edgelist = [(4, 5), (5, 6), (6, 7), (4, 7)]
103
+ nx.set_edge_attributes(
104
+ G,
105
+ {
106
+ (u, v): {
107
+ "color": "tab:blue",
108
+ "visible": (u, v) in edgelist,
109
+ }
110
+ for u, v in G.edges()
111
+ },
112
+ )
113
+ nx.display(G, node_pos="pos", node_visible=False)
114
+
115
+ plt.tight_layout()
116
+ plt.axis("off")
117
+ return fig
118
+
119
+
120
+ @pytest.mark.mpl_image_compare
121
+ def test_display_complex():
122
+ import itertools as it
123
+
124
+ fig, ax = plt.subplots()
125
+ G = nx.MultiDiGraph()
126
+ nodes = "ABC"
127
+ prod = list(it.product(nodes, repeat=2)) * 4
128
+ G = nx.MultiDiGraph()
129
+ for i, (u, v) in enumerate(prod):
130
+ G.add_edge(u, v, w=round(i / 3, 2))
131
+ nx.set_node_attributes(G, nx.spring_layout(G, seed=3113794652), "pos")
132
+ csi = it.cycle([f"arc3,rad={r}" for r in it.accumulate([0.15] * 4)])
133
+ nx.set_edge_attributes(G, {e: next(csi) for e in G.edges(keys=True)}, "curvature")
134
+ nx.set_edge_attributes(
135
+ G,
136
+ {
137
+ tuple(e): {"label": w, "bbox": {"alpha": 0}}
138
+ for *e, w in G.edges(keys=True, data="w")
139
+ },
140
+ "label",
141
+ )
142
+ nx.apply_matplotlib_colors(G, "w", "color", mpl.colormaps["inferno"], nodes=False)
143
+ nx.display(G, canvas=ax, node_pos="pos")
144
+
145
+ plt.tight_layout()
146
+ plt.axis("off")
147
+ return fig
148
+
149
+
150
+ @pytest.mark.mpl_image_compare
151
+ def test_display_shortest_path():
152
+ fig, ax = plt.subplots()
153
+ G = nx.Graph()
154
+ G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
155
+ G.add_edge("A", "B", weight=4)
156
+ G.add_edge("A", "H", weight=8)
157
+ G.add_edge("B", "C", weight=8)
158
+ G.add_edge("B", "H", weight=11)
159
+ G.add_edge("C", "D", weight=7)
160
+ G.add_edge("C", "F", weight=4)
161
+ G.add_edge("C", "I", weight=2)
162
+ G.add_edge("D", "E", weight=9)
163
+ G.add_edge("D", "F", weight=14)
164
+ G.add_edge("E", "F", weight=10)
165
+ G.add_edge("F", "G", weight=2)
166
+ G.add_edge("G", "H", weight=1)
167
+ G.add_edge("G", "I", weight=6)
168
+ G.add_edge("H", "I", weight=7)
169
+
170
+ # Find the shortest path from node A to node E
171
+ path = nx.shortest_path(G, "A", "E", weight="weight")
172
+
173
+ # Create a list of edges in the shortest path
174
+ path_edges = list(zip(path, path[1:]))
175
+ nx.set_node_attributes(G, nx.spring_layout(G, seed=37), "pos")
176
+ nx.set_edge_attributes(
177
+ G,
178
+ {
179
+ (u, v): {
180
+ "color": (
181
+ "red"
182
+ if (u, v) in path_edges or tuple(reversed((u, v))) in path_edges
183
+ else "black"
184
+ ),
185
+ "label": {"label": d["weight"], "rotate": False},
186
+ }
187
+ for u, v, d in G.edges(data=True)
188
+ },
189
+ )
190
+ nx.display(G, canvas=ax)
191
+ plt.tight_layout()
192
+ plt.axis("off")
193
+ return fig
194
+
195
+
196
+ @pytest.mark.mpl_image_compare
197
+ def test_display_empty_graph():
198
+ G = nx.empty_graph()
199
+ fig, ax = plt.subplots()
200
+ nx.display(G, canvas=ax)
201
+ plt.tight_layout()
202
+ plt.axis("off")
203
+ return fig
204
+
205
+
206
+ @pytest.mark.mpl_image_compare
207
+ def test_house_with_colors():
208
+ G = nx.house_graph()
209
+ # explicitly set positions
210
+ fig, ax = plt.subplots()
211
+ pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
212
+
213
+ # Plot nodes with different properties for the "wall" and "roof" nodes
214
+ nx.draw_networkx_nodes(
215
+ G,
216
+ pos,
217
+ node_size=3000,
218
+ nodelist=[0, 1, 2, 3],
219
+ node_color="tab:blue",
220
+ )
221
+ nx.draw_networkx_nodes(
222
+ G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
223
+ )
224
+ nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
225
+ # Customize axes
226
+ ax.margins(0.11)
227
+ plt.tight_layout()
228
+ plt.axis("off")
229
+ return fig
venv/lib/python3.14/site-packages/networkx/drawing/tests/test_latex.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_tikz_attributes():
7
+ G = nx.path_graph(4, create_using=nx.DiGraph)
8
+ pos = {n: (n, n) for n in G}
9
+
10
+ G.add_edge(0, 0)
11
+ G.edges[(0, 0)]["label"] = "Loop"
12
+ G.edges[(0, 0)]["label_options"] = "midway"
13
+
14
+ G.nodes[0]["style"] = "blue"
15
+ G.nodes[1]["style"] = "line width=3,draw"
16
+ G.nodes[2]["style"] = "circle,draw,blue!50"
17
+ G.nodes[3]["label"] = "Stop"
18
+ G.edges[(0, 1)]["label"] = "1st Step"
19
+ G.edges[(0, 1)]["label_options"] = "near end"
20
+ G.edges[(2, 3)]["label"] = "3rd Step"
21
+ G.edges[(2, 3)]["label_options"] = "near start"
22
+ G.edges[(2, 3)]["style"] = "bend left,green"
23
+ G.edges[(1, 2)]["label"] = "2nd"
24
+ G.edges[(1, 2)]["label_options"] = "pos=0.5"
25
+ G.edges[(1, 2)]["style"] = ">->,bend right,line width=3,green!90"
26
+
27
+ output_tex = nx.to_latex(
28
+ G,
29
+ pos=pos,
30
+ as_document=False,
31
+ tikz_options="[scale=3]",
32
+ node_options="style",
33
+ edge_options="style",
34
+ node_label="label",
35
+ edge_label="label",
36
+ edge_label_options="label_options",
37
+ )
38
+ expected_tex = r"""\begin{figure}
39
+ \begin{tikzpicture}[scale=3]
40
+ \draw
41
+ (0, 0) node[blue] (0){0}
42
+ (1, 1) node[line width=3,draw] (1){1}
43
+ (2, 2) node[circle,draw,blue!50] (2){2}
44
+ (3, 3) node (3){Stop};
45
+ \begin{scope}[->]
46
+ \draw (0) to node[near end] {1st Step} (1);
47
+ \draw[loop,] (0) to node[midway] {Loop} (0);
48
+ \draw[>->,bend right,line width=3,green!90] (1) to node[pos=0.5] {2nd} (2);
49
+ \draw[bend left,green] (2) to node[near start] {3rd Step} (3);
50
+ \end{scope}
51
+ \end{tikzpicture}
52
+ \end{figure}"""
53
+
54
+ # First, check for consistency line-by-line - if this fails, the mismatched
55
+ # line will be shown explicitly in the failure summary
56
+ for expected, actual in zip(expected_tex.split("\n"), output_tex.split("\n")):
57
+ assert expected == actual
58
+
59
+ assert output_tex == expected_tex
60
+
61
+
62
+ def test_basic_multiple_graphs():
63
+ H1 = nx.path_graph(4)
64
+ H2 = nx.complete_graph(4)
65
+ H3 = nx.path_graph(8)
66
+ H4 = nx.complete_graph(8)
67
+ captions = [
68
+ "Path on 4 nodes",
69
+ "Complete graph on 4 nodes",
70
+ "Path on 8 nodes",
71
+ "Complete graph on 8 nodes",
72
+ ]
73
+ labels = ["fig2a", "fig2b", "fig2c", "fig2d"]
74
+ latex_code = nx.to_latex(
75
+ [H1, H2, H3, H4],
76
+ n_rows=2,
77
+ sub_captions=captions,
78
+ sub_labels=labels,
79
+ )
80
+ assert "begin{document}" in latex_code
81
+ assert "begin{figure}" in latex_code
82
+ assert latex_code.count("begin{subfigure}") == 4
83
+ assert latex_code.count("tikzpicture") == 8
84
+ assert latex_code.count("[-]") == 4
85
+
86
+
87
+ def test_basic_tikz():
88
+ expected_tex = r"""\documentclass{report}
89
+ \usepackage{tikz}
90
+ \usepackage{subcaption}
91
+
92
+ \begin{document}
93
+ \begin{figure}
94
+ \begin{subfigure}{0.5\textwidth}
95
+ \begin{tikzpicture}[scale=2]
96
+ \draw[gray!90]
97
+ (0.749, 0.702) node[red!90] (0){0}
98
+ (1.0, -0.014) node[red!90] (1){1}
99
+ (-0.777, -0.705) node (2){2}
100
+ (-0.984, 0.042) node (3){3}
101
+ (-0.028, 0.375) node[cyan!90] (4){4}
102
+ (-0.412, 0.888) node (5){5}
103
+ (0.448, -0.856) node (6){6}
104
+ (0.003, -0.431) node[cyan!90] (7){7};
105
+ \begin{scope}[->,gray!90]
106
+ \draw (0) to (4);
107
+ \draw (0) to (5);
108
+ \draw (0) to (6);
109
+ \draw (0) to (7);
110
+ \draw (1) to (4);
111
+ \draw (1) to (5);
112
+ \draw (1) to (6);
113
+ \draw (1) to (7);
114
+ \draw (2) to (4);
115
+ \draw (2) to (5);
116
+ \draw (2) to (6);
117
+ \draw (2) to (7);
118
+ \draw (3) to (4);
119
+ \draw (3) to (5);
120
+ \draw (3) to (6);
121
+ \draw (3) to (7);
122
+ \end{scope}
123
+ \end{tikzpicture}
124
+ \caption{My tikz number 1 of 2}\label{tikz_1_2}
125
+ \end{subfigure}
126
+ \begin{subfigure}{0.5\textwidth}
127
+ \begin{tikzpicture}[scale=2]
128
+ \draw[gray!90]
129
+ (0.749, 0.702) node[green!90] (0){0}
130
+ (1.0, -0.014) node[green!90] (1){1}
131
+ (-0.777, -0.705) node (2){2}
132
+ (-0.984, 0.042) node (3){3}
133
+ (-0.028, 0.375) node[purple!90] (4){4}
134
+ (-0.412, 0.888) node (5){5}
135
+ (0.448, -0.856) node (6){6}
136
+ (0.003, -0.431) node[purple!90] (7){7};
137
+ \begin{scope}[->,gray!90]
138
+ \draw (0) to (4);
139
+ \draw (0) to (5);
140
+ \draw (0) to (6);
141
+ \draw (0) to (7);
142
+ \draw (1) to (4);
143
+ \draw (1) to (5);
144
+ \draw (1) to (6);
145
+ \draw (1) to (7);
146
+ \draw (2) to (4);
147
+ \draw (2) to (5);
148
+ \draw (2) to (6);
149
+ \draw (2) to (7);
150
+ \draw (3) to (4);
151
+ \draw (3) to (5);
152
+ \draw (3) to (6);
153
+ \draw (3) to (7);
154
+ \end{scope}
155
+ \end{tikzpicture}
156
+ \caption{My tikz number 2 of 2}\label{tikz_2_2}
157
+ \end{subfigure}
158
+ \caption{A graph generated with python and latex.}
159
+ \end{figure}
160
+ \end{document}"""
161
+
162
+ edges = [
163
+ (0, 4),
164
+ (0, 5),
165
+ (0, 6),
166
+ (0, 7),
167
+ (1, 4),
168
+ (1, 5),
169
+ (1, 6),
170
+ (1, 7),
171
+ (2, 4),
172
+ (2, 5),
173
+ (2, 6),
174
+ (2, 7),
175
+ (3, 4),
176
+ (3, 5),
177
+ (3, 6),
178
+ (3, 7),
179
+ ]
180
+ G = nx.DiGraph()
181
+ G.add_nodes_from(range(8))
182
+ G.add_edges_from(edges)
183
+ pos = {
184
+ 0: (0.7490296171687696, 0.702353520257394),
185
+ 1: (1.0, -0.014221357723796535),
186
+ 2: (-0.7765783344161441, -0.7054170966808919),
187
+ 3: (-0.9842690223417624, 0.04177547602465483),
188
+ 4: (-0.02768523817180917, 0.3745724439551441),
189
+ 5: (-0.41154855146767433, 0.8880106515525136),
190
+ 6: (0.44780153389148264, -0.8561492709269164),
191
+ 7: (0.0032499953371383505, -0.43092436645809945),
192
+ }
193
+
194
+ rc_node_color = {0: "red!90", 1: "red!90", 4: "cyan!90", 7: "cyan!90"}
195
+ gp_node_color = {0: "green!90", 1: "green!90", 4: "purple!90", 7: "purple!90"}
196
+
197
+ H = G.copy()
198
+ nx.set_node_attributes(G, rc_node_color, "color")
199
+ nx.set_node_attributes(H, gp_node_color, "color")
200
+
201
+ sub_captions = ["My tikz number 1 of 2", "My tikz number 2 of 2"]
202
+ sub_labels = ["tikz_1_2", "tikz_2_2"]
203
+
204
+ output_tex = nx.to_latex(
205
+ [G, H],
206
+ [pos, pos],
207
+ tikz_options="[scale=2]",
208
+ default_node_options="gray!90",
209
+ default_edge_options="gray!90",
210
+ node_options="color",
211
+ sub_captions=sub_captions,
212
+ sub_labels=sub_labels,
213
+ caption="A graph generated with python and latex.",
214
+ n_rows=2,
215
+ as_document=True,
216
+ )
217
+
218
+ # First, check for consistency line-by-line - if this fails, the mismatched
219
+ # line will be shown explicitly in the failure summary
220
+ for expected, actual in zip(expected_tex.split("\n"), output_tex.split("\n")):
221
+ assert expected == actual
222
+ # Double-check for document-level consistency
223
+ assert output_tex == expected_tex
224
+
225
+
226
+ def test_exception_pos_single_graph(to_latex=nx.to_latex):
227
+ # smoke test that pos can be a string
228
+ G = nx.path_graph(4)
229
+ to_latex(G, pos="pos")
230
+
231
+ # must include all nodes
232
+ pos = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
233
+ with pytest.raises(nx.NetworkXError):
234
+ to_latex(G, pos)
235
+
236
+ # must have 2 values
237
+ pos[3] = (1, 2, 3)
238
+ with pytest.raises(nx.NetworkXError):
239
+ to_latex(G, pos)
240
+ pos[3] = 2
241
+ with pytest.raises(nx.NetworkXError):
242
+ to_latex(G, pos)
243
+
244
+ # check that passes with 2 values
245
+ pos[3] = (3, 2)
246
+ to_latex(G, pos)
247
+
248
+
249
+ def test_exception_multiple_graphs(to_latex=nx.to_latex):
250
+ G = nx.path_graph(3)
251
+ pos_bad = {0: (1, 2), 1: (0, 1)}
252
+ pos_OK = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
253
+ fourG = [G, G, G, G]
254
+ fourpos = [pos_OK, pos_OK, pos_OK, pos_OK]
255
+
256
+ # input single dict to use for all graphs
257
+ to_latex(fourG, pos_OK)
258
+ with pytest.raises(nx.NetworkXError):
259
+ to_latex(fourG, pos_bad)
260
+
261
+ # input list of dicts to use for all graphs
262
+ to_latex(fourG, fourpos)
263
+ with pytest.raises(nx.NetworkXError):
264
+ to_latex(fourG, [pos_bad, pos_bad, pos_bad, pos_bad])
265
+
266
+ # every pos dict must include all nodes
267
+ with pytest.raises(nx.NetworkXError):
268
+ to_latex(fourG, [pos_OK, pos_OK, pos_bad, pos_OK])
269
+
270
+ # test sub_captions and sub_labels (len must match Gbunch)
271
+ with pytest.raises(nx.NetworkXError):
272
+ to_latex(fourG, fourpos, sub_captions=["hi", "hi"])
273
+
274
+ with pytest.raises(nx.NetworkXError):
275
+ to_latex(fourG, fourpos, sub_labels=["hi", "hi"])
276
+
277
+ # all pass
278
+ to_latex(fourG, fourpos, sub_captions=["hi"] * 4, sub_labels=["lbl"] * 4)
279
+
280
+
281
+ def test_exception_multigraph():
282
+ G = nx.path_graph(4, create_using=nx.MultiGraph)
283
+ G.add_edge(1, 2)
284
+ with pytest.raises(nx.NetworkXNotImplemented):
285
+ nx.to_latex(G)
venv/lib/python3.14/site-packages/networkx/drawing/tests/test_layout.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for layout functions."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+ np = pytest.importorskip("numpy")
8
+ pytest.importorskip("scipy")
9
+
10
+
11
+ class TestLayout:
12
+ @classmethod
13
+ def setup_class(cls):
14
+ cls.Gi = nx.grid_2d_graph(5, 5)
15
+ cls.Gs = nx.Graph()
16
+ nx.add_path(cls.Gs, "abcdef")
17
+ cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse
18
+
19
+ def test_spring_fixed_without_pos(self):
20
+ G = nx.path_graph(4)
21
+ # No pos dict at all
22
+ with pytest.raises(ValueError, match="nodes are fixed without positions"):
23
+ nx.spring_layout(G, fixed=[0])
24
+
25
+ pos = {0: (1, 1), 2: (0, 0)}
26
+ # Node 1 not in pos dict
27
+ with pytest.raises(ValueError, match="nodes are fixed without positions"):
28
+ nx.spring_layout(G, fixed=[0, 1], pos=pos)
29
+
30
+ # All fixed nodes in pos dict
31
+ out = nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError
32
+ assert all(np.array_equal(out[n], pos[n]) for n in (0, 2))
33
+
34
+ def test_spring_init_pos(self):
35
+ # Tests GH #2448
36
+ import math
37
+
38
+ G = nx.Graph()
39
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)])
40
+
41
+ init_pos = {0: (0.0, 0.0)}
42
+ fixed_pos = [0]
43
+ pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos)
44
+ has_nan = any(math.isnan(c) for coords in pos.values() for c in coords)
45
+ assert not has_nan, "values should not be nan"
46
+
47
+ def test_smoke_empty_graph(self):
48
+ G = []
49
+ nx.random_layout(G)
50
+ nx.circular_layout(G)
51
+ nx.planar_layout(G)
52
+ nx.spring_layout(G)
53
+ nx.fruchterman_reingold_layout(G)
54
+ nx.spectral_layout(G)
55
+ nx.shell_layout(G)
56
+ nx.bipartite_layout(G, G)
57
+ nx.spiral_layout(G)
58
+ nx.multipartite_layout(G)
59
+ nx.kamada_kawai_layout(G)
60
+
61
+ def test_smoke_int(self):
62
+ G = self.Gi
63
+ nx.random_layout(G)
64
+ nx.circular_layout(G)
65
+ nx.planar_layout(G)
66
+ nx.spring_layout(G)
67
+ nx.forceatlas2_layout(G)
68
+ nx.fruchterman_reingold_layout(G)
69
+ nx.fruchterman_reingold_layout(self.bigG)
70
+ nx.spectral_layout(G)
71
+ nx.spectral_layout(G.to_directed())
72
+ nx.spectral_layout(self.bigG)
73
+ nx.spectral_layout(self.bigG.to_directed())
74
+ nx.shell_layout(G)
75
+ nx.spiral_layout(G)
76
+ nx.kamada_kawai_layout(G)
77
+ nx.kamada_kawai_layout(G, dim=1)
78
+ nx.kamada_kawai_layout(G, dim=3)
79
+ nx.arf_layout(G)
80
+
81
+ def test_smoke_string(self):
82
+ G = self.Gs
83
+ nx.random_layout(G)
84
+ nx.circular_layout(G)
85
+ nx.planar_layout(G)
86
+ nx.spring_layout(G)
87
+ nx.forceatlas2_layout(G)
88
+ nx.fruchterman_reingold_layout(G)
89
+ nx.spectral_layout(G)
90
+ nx.shell_layout(G)
91
+ nx.spiral_layout(G)
92
+ nx.kamada_kawai_layout(G)
93
+ nx.kamada_kawai_layout(G, dim=1)
94
+ nx.kamada_kawai_layout(G, dim=3)
95
+ nx.arf_layout(G)
96
+
97
+ def check_scale_and_center(self, pos, scale, center):
98
+ center = np.array(center)
99
+ low = center - scale
100
+ hi = center + scale
101
+ vpos = np.array(list(pos.values()))
102
+ length = vpos.max(0) - vpos.min(0)
103
+ assert (length <= 2 * scale).all()
104
+ assert (vpos >= low).all()
105
+ assert (vpos <= hi).all()
106
+
107
+ def test_scale_and_center_arg(self):
108
+ sc = self.check_scale_and_center
109
+ c = (4, 5)
110
+ G = nx.complete_graph(9)
111
+ G.add_node(9)
112
+ sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
113
+ # rest can have 2*scale length: [-scale, scale]
114
+ sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
115
+ sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
116
+ sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
117
+ sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
118
+ sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
119
+ sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
120
+
121
+ c = (2, 3, 5)
122
+ sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c)
123
+
124
+ def test_planar_layout_non_planar_input(self):
125
+ G = nx.complete_graph(9)
126
+ pytest.raises(nx.NetworkXException, nx.planar_layout, G)
127
+
128
+ def test_smoke_planar_layout_embedding_input(self):
129
+ embedding = nx.PlanarEmbedding()
130
+ embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]})
131
+ nx.planar_layout(embedding)
132
+
133
+ def test_default_scale_and_center(self):
134
+ sc = self.check_scale_and_center
135
+ c = (0, 0)
136
+ G = nx.complete_graph(9)
137
+ G.add_node(9)
138
+ sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
139
+ sc(nx.spring_layout(G), scale=1, center=c)
140
+ sc(nx.spectral_layout(G), scale=1, center=c)
141
+ sc(nx.circular_layout(G), scale=1, center=c)
142
+ sc(nx.shell_layout(G), scale=1, center=c)
143
+ sc(nx.spiral_layout(G), scale=1, center=c)
144
+ sc(nx.kamada_kawai_layout(G), scale=1, center=c)
145
+
146
+ c = (0, 0, 0)
147
+ sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c)
148
+
149
+ def test_circular_planar_and_shell_dim_error(self):
150
+ G = nx.path_graph(4)
151
+ pytest.raises(ValueError, nx.circular_layout, G, dim=1)
152
+ pytest.raises(ValueError, nx.shell_layout, G, dim=1)
153
+ pytest.raises(ValueError, nx.shell_layout, G, dim=3)
154
+ pytest.raises(ValueError, nx.planar_layout, G, dim=1)
155
+ pytest.raises(ValueError, nx.planar_layout, G, dim=3)
156
+
157
+ def test_adjacency_interface_numpy(self):
158
+ A = nx.to_numpy_array(self.Gs)
159
+ pos = nx.drawing.layout._fruchterman_reingold(A)
160
+ assert pos.shape == (6, 2)
161
+ pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
162
+ assert pos.shape == (6, 3)
163
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
164
+ assert pos.shape == (6, 2)
165
+
166
+ def test_adjacency_interface_scipy(self):
167
+ A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
168
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
169
+ assert pos.shape == (6, 2)
170
+ pos = nx.drawing.layout._sparse_spectral(A)
171
+ assert pos.shape == (6, 2)
172
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
173
+ assert pos.shape == (6, 3)
174
+
175
+ def test_single_nodes(self):
176
+ G = nx.path_graph(1)
177
+ vpos = nx.shell_layout(G)
178
+ assert not vpos[0].any()
179
+ G = nx.path_graph(4)
180
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]])
181
+ assert not vpos[0].any()
182
+ assert vpos[3].any() # ensure node 3 not at origin (#3188)
183
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
184
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0)
185
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
186
+
187
+ def test_smoke_initial_pos_forceatlas2(self):
188
+ pos = nx.circular_layout(self.Gi)
189
+ npos = nx.forceatlas2_layout(self.Gi, pos=pos)
190
+
191
+ def test_smoke_initial_pos_nonarray_forceatlas2(self):
192
+ # See gh-8451
193
+ pos = nx.circular_layout(self.Gi)
194
+ pos = {key: tuple(value) for key, value in pos.items()}
195
+ npos = nx.forceatlas2_layout(self.Gi, pos=pos)
196
+
197
+ def test_smoke_initial_pos_fruchterman_reingold(self):
198
+ pos = nx.circular_layout(self.Gi)
199
+ npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
200
+
201
+ def test_smoke_initial_pos_arf(self):
202
+ pos = nx.circular_layout(self.Gi)
203
+ npos = nx.arf_layout(self.Gi, pos=pos)
204
+
205
+ @pytest.mark.parametrize("method", ("force", "energy"))
206
+ @pytest.mark.parametrize(
207
+ "layout_fn", (nx.spring_layout, nx.fruchterman_reingold_layout)
208
+ )
209
+ def test_zero_iterations_fruchterman_reingold(self, method, layout_fn):
210
+ pos = nx.circular_layout(self.Gi)
211
+ npos = layout_fn(self.Gi, pos=pos, method=method, iterations=0, scale=None)
212
+ assert pos.keys() == npos.keys()
213
+ for node, p in npos.items():
214
+ assert np.allclose(pos[node], p)
215
+
216
+ def test_zero_iterations_arf(self):
217
+ pos = nx.circular_layout(self.Gi)
218
+ npos = nx.arf_layout(self.Gi, pos=pos, max_iter=0)
219
+ assert pos.keys() == npos.keys()
220
+ for node, p in npos.items():
221
+ assert np.allclose(pos[node], p)
222
+
223
+ def test_fixed_node_fruchterman_reingold(self):
224
+ # Dense version (numpy based)
225
+ pos = nx.circular_layout(self.Gi)
226
+ npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)])
227
+ assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)])
228
+ # Sparse version (scipy based)
229
+ pos = nx.circular_layout(self.bigG)
230
+ npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)])
231
+ for axis in range(2):
232
+ assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7)
233
+ # Empty fixed list - see gh-8446
234
+ pos = nx.circular_layout(self.Gi)
235
+ npos = nx.spring_layout(self.Gi, pos=pos, fixed=[])
236
+ assert len(npos) == len(pos)
237
+
238
+ def test_center_parameter(self):
239
+ G = nx.path_graph(1)
240
+ nx.random_layout(G, center=(1, 1))
241
+ vpos = nx.circular_layout(G, center=(1, 1))
242
+ assert tuple(vpos[0]) == (1, 1)
243
+ vpos = nx.planar_layout(G, center=(1, 1))
244
+ assert tuple(vpos[0]) == (1, 1)
245
+ vpos = nx.spring_layout(G, center=(1, 1))
246
+ assert tuple(vpos[0]) == (1, 1)
247
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
248
+ assert tuple(vpos[0]) == (1, 1)
249
+ vpos = nx.spectral_layout(G, center=(1, 1))
250
+ assert tuple(vpos[0]) == (1, 1)
251
+ vpos = nx.shell_layout(G, center=(1, 1))
252
+ assert tuple(vpos[0]) == (1, 1)
253
+ vpos = nx.spiral_layout(G, center=(1, 1))
254
+ assert tuple(vpos[0]) == (1, 1)
255
+
256
+ def test_center_wrong_dimensions(self):
257
+ G = nx.path_graph(1)
258
+ assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout)
259
+ pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1))
260
+ pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1))
261
+ pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1))
262
+ pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1))
263
+ pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1))
264
+ pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1))
265
+ pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1))
266
+ pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
267
+ pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1))
268
+ pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1))
269
+
270
+ def test_empty_graph(self):
271
+ G = nx.empty_graph()
272
+ vpos = nx.random_layout(G, center=(1, 1))
273
+ assert vpos == {}
274
+ vpos = nx.circular_layout(G, center=(1, 1))
275
+ assert vpos == {}
276
+ vpos = nx.planar_layout(G, center=(1, 1))
277
+ assert vpos == {}
278
+ vpos = nx.bipartite_layout(G, G)
279
+ assert vpos == {}
280
+ vpos = nx.spring_layout(G, center=(1, 1))
281
+ assert vpos == {}
282
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
283
+ assert vpos == {}
284
+ vpos = nx.spectral_layout(G, center=(1, 1))
285
+ assert vpos == {}
286
+ vpos = nx.shell_layout(G, center=(1, 1))
287
+ assert vpos == {}
288
+ vpos = nx.spiral_layout(G, center=(1, 1))
289
+ assert vpos == {}
290
+ vpos = nx.multipartite_layout(G, center=(1, 1))
291
+ assert vpos == {}
292
+ vpos = nx.kamada_kawai_layout(G, center=(1, 1))
293
+ assert vpos == {}
294
+ vpos = nx.forceatlas2_layout(G)
295
+ assert vpos == {}
296
+ vpos = nx.arf_layout(G)
297
+ assert vpos == {}
298
+
299
+ def test_bipartite_layout(self):
300
+ G = nx.complete_bipartite_graph(3, 5)
301
+ top, bottom = nx.bipartite.sets(G)
302
+
303
+ vpos = nx.bipartite_layout(G, top)
304
+ assert len(vpos) == len(G)
305
+
306
+ top_x = vpos[list(top)[0]][0]
307
+ bottom_x = vpos[list(bottom)[0]][0]
308
+ for node in top:
309
+ assert vpos[node][0] == top_x
310
+ for node in bottom:
311
+ assert vpos[node][0] == bottom_x
312
+
313
+ vpos = nx.bipartite_layout(
314
+ G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1
315
+ )
316
+ assert len(vpos) == len(G)
317
+
318
+ top_y = vpos[list(top)[0]][1]
319
+ bottom_y = vpos[list(bottom)[0]][1]
320
+ for node in top:
321
+ assert vpos[node][1] == top_y
322
+ for node in bottom:
323
+ assert vpos[node][1] == bottom_y
324
+
325
+ pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo")
326
+
327
+ def test_multipartite_layout(self):
328
+ sizes = (0, 5, 7, 2, 8)
329
+ G = nx.complete_multipartite_graph(*sizes)
330
+
331
+ vpos = nx.multipartite_layout(G)
332
+ assert len(vpos) == len(G)
333
+
334
+ start = 0
335
+ for n in sizes:
336
+ end = start + n
337
+ assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end))
338
+ start += n
339
+
340
+ vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2))
341
+ assert len(vpos) == len(G)
342
+
343
+ start = 0
344
+ for n in sizes:
345
+ end = start + n
346
+ assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end))
347
+ start += n
348
+
349
+ pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
350
+
351
+ def test_kamada_kawai_costfn_1d(self):
352
+ costfn = nx.drawing.layout._kamada_kawai_costfn
353
+
354
+ pos = np.array([4.0, 7.0])
355
+ invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]])
356
+
357
+ cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1)
358
+
359
+ assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7)
360
+ assert grad[0] == pytest.approx((-0.5), abs=1e-7)
361
+ assert grad[1] == pytest.approx(0.5, abs=1e-7)
362
+
363
+ def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim):
364
+ costfn = nx.drawing.layout._kamada_kawai_costfn
365
+
366
+ cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim)
367
+
368
+ expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2)
369
+ for i in range(pos.shape[0]):
370
+ for j in range(i + 1, pos.shape[0]):
371
+ diff = np.linalg.norm(pos[i] - pos[j])
372
+ expected_cost += (diff * invdist[i][j] - 1.0) ** 2
373
+
374
+ assert cost == pytest.approx(expected_cost, abs=1e-7)
375
+
376
+ dx = 1e-4
377
+ for nd in range(pos.shape[0]):
378
+ for dm in range(pos.shape[1]):
379
+ idx = nd * pos.shape[1] + dm
380
+ ps = pos.flatten()
381
+
382
+ ps[idx] += dx
383
+ cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
384
+
385
+ ps[idx] -= 2 * dx
386
+ cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
387
+
388
+ assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5)
389
+
390
+ def test_kamada_kawai_costfn(self):
391
+ invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]])
392
+ meanwt = 0.3
393
+
394
+ # 2d
395
+ pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]])
396
+
397
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2)
398
+
399
+ # 3d
400
+ pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]])
401
+
402
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3)
403
+
404
+ def test_spiral_layout(self):
405
+ G = self.Gs
406
+
407
+ # a lower value of resolution should result in a more compact layout
408
+ # intuitively, the total distance from the start and end nodes
409
+ # via each node in between (transiting through each) will be less,
410
+ # assuming rescaling does not occur on the computed node positions
411
+ pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values()))
412
+ pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values()))
413
+ distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1)
414
+ distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1)
415
+ assert sum(distances) > sum(distances_tighter)
416
+
417
+ # return near-equidistant points after the first value if set to true
418
+ pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values()))
419
+ distances_equidistant = np.linalg.norm(
420
+ pos_equidistant[:-1] - pos_equidistant[1:], axis=1
421
+ )
422
+ assert np.allclose(
423
+ distances_equidistant[1:], distances_equidistant[-1], atol=0.01
424
+ )
425
+
426
+ def test_spiral_layout_equidistant(self):
427
+ G = nx.path_graph(10)
428
+ nx.spiral_layout(G, equidistant=True, store_pos_as="pos")
429
+ pos = nx.get_node_attributes(G, "pos")
430
+ # Extract individual node positions as an array
431
+ p = np.array(list(pos.values()))
432
+ # Elementwise-distance between node positions
433
+ dist = np.linalg.norm(p[1:] - p[:-1], axis=1)
434
+ assert np.allclose(np.diff(dist), 0, atol=1e-3)
435
+
436
+ def test_forceatlas2_layout_partial_input_test(self):
437
+ # check whether partial pos input still returns a full proper position
438
+ G = self.Gs
439
+ node = nx.utils.arbitrary_element(G)
440
+ pos = nx.circular_layout(G)
441
+ del pos[node]
442
+ pos = nx.forceatlas2_layout(G, pos=pos)
443
+ assert len(pos) == len(G)
444
+
445
+ def test_rescale_layout_dict(self):
446
+ G = nx.empty_graph()
447
+ vpos = nx.random_layout(G, center=(1, 1))
448
+ assert nx.rescale_layout_dict(vpos) == {}
449
+
450
+ G = nx.empty_graph(2)
451
+ vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)}
452
+ s_vpos = nx.rescale_layout_dict(vpos)
453
+ assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6
454
+
455
+ G = nx.empty_graph(3)
456
+ vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)}
457
+ s_vpos = nx.rescale_layout_dict(vpos)
458
+
459
+ expectation = {
460
+ 0: np.array((-1, -1)),
461
+ 1: np.array((1, 1)),
462
+ 2: np.array((0, 0)),
463
+ }
464
+ for k, v in expectation.items():
465
+ assert (s_vpos[k] == v).all()
466
+ s_vpos = nx.rescale_layout_dict(vpos, scale=2)
467
+ expectation = {
468
+ 0: np.array((-2, -2)),
469
+ 1: np.array((2, 2)),
470
+ 2: np.array((0, 0)),
471
+ }
472
+ for k, v in expectation.items():
473
+ assert (s_vpos[k] == v).all()
474
+
475
+ def test_arf_layout_partial_input_test(self):
476
+ # Checks whether partial pos input still returns a proper position.
477
+ G = self.Gs
478
+ node = nx.utils.arbitrary_element(G)
479
+ pos = nx.circular_layout(G)
480
+ del pos[node]
481
+ pos = nx.arf_layout(G, pos=pos)
482
+ assert len(pos) == len(G)
483
+
484
+ def test_arf_layout_negative_a_check(self):
485
+ """
486
+ Checks input parameters correctly raises errors. For example, `a` should be larger than 1
487
+ """
488
+ G = self.Gs
489
+ pytest.raises(ValueError, nx.arf_layout, G=G, a=-1)
490
+
491
+ def test_smoke_seed_input(self):
492
+ G = self.Gs
493
+ nx.random_layout(G, seed=42)
494
+ nx.spring_layout(G, seed=42)
495
+ nx.arf_layout(G, seed=42)
496
+ nx.forceatlas2_layout(G, seed=42)
497
+
498
+ def test_node_at_center(self):
499
+ # see gh-7791 avoid divide by zero
500
+ G = nx.path_graph(3)
501
+ orig_pos = {i: [i - 1, 0.0] for i in range(3)}
502
+ new_pos = nx.forceatlas2_layout(G, pos=orig_pos)
503
+
504
+ def test_initial_only_some_pos(self):
505
+ G = nx.path_graph(3)
506
+ orig_pos = {i: [i - 1, 0.0] for i in range(2)}
507
+ new_pos = nx.forceatlas2_layout(G, pos=orig_pos, seed=42)
508
+
509
+
510
+ def test_multipartite_layout_nonnumeric_partition_labels():
511
+ """See gh-5123."""
512
+ G = nx.Graph()
513
+ G.add_node(0, subset="s0")
514
+ G.add_node(1, subset="s0")
515
+ G.add_node(2, subset="s1")
516
+ G.add_node(3, subset="s1")
517
+ G.add_edges_from([(0, 2), (0, 3), (1, 2)])
518
+ pos = nx.multipartite_layout(G)
519
+ assert len(pos) == len(G)
520
+
521
+
522
+ def test_multipartite_layout_layer_order():
523
+ """Return the layers in sorted order if the layers of the multipartite
524
+ graph are sortable. See gh-5691"""
525
+ G = nx.Graph()
526
+ node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4)))
527
+ for node, layer in node_group.items():
528
+ G.add_node(node, subset=layer)
529
+
530
+ # Horizontal alignment, therefore y-coord determines layers
531
+ pos = nx.multipartite_layout(G, align="horizontal")
532
+
533
+ layers = nx.utils.groups(node_group)
534
+ pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers)
535
+ for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()):
536
+ assert n1 == n2 and (p1 == p2).all()
537
+
538
+ # Nodes "a" and "d" are in the same layer
539
+ assert pos["a"][-1] == pos["d"][-1]
540
+ # positions should be sorted according to layer
541
+ assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1]
542
+
543
+ # Make sure that multipartite_layout still works when layers are not sortable
544
+ G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints
545
+ pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise
546
+ assert pos_nosort.keys() == pos.keys()
547
+
548
+
549
+ def _num_nodes_per_bfs_layer(pos):
550
+ """Helper function to extract the number of nodes in each layer of bfs_layout"""
551
+ x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension
552
+ _, layer_count = np.unique(x, return_counts=True)
553
+ return layer_count
554
+
555
+
556
+ @pytest.mark.parametrize("n", range(2, 7))
557
+ def test_bfs_layout_complete_graph(n):
558
+ """The complete graph should result in two layers: the starting node and
559
+ a second layer containing all neighbors."""
560
+ G = nx.complete_graph(n)
561
+ nx.bfs_layout(G, start=0, store_pos_as="pos")
562
+ pos = nx.get_node_attributes(G, "pos")
563
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1])
564
+
565
+
566
+ def test_bfs_layout_barbell():
567
+ G = nx.barbell_graph(5, 3)
568
+ # Start in one of the "bells"
569
+ pos = nx.bfs_layout(G, start=0)
570
+ # start, bell-1, [1] * len(bar)+1, bell-1
571
+ expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4]
572
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
573
+ # Start in the other "bell" - expect same layer pattern
574
+ pos = nx.bfs_layout(G, start=12)
575
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
576
+ # Starting in the center of the bar, expect layers to be symmetric
577
+ pos = nx.bfs_layout(G, start=6)
578
+ # Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells}
579
+ expected_nodes_per_layer = [1, 2, 2, 8]
580
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
581
+
582
+
583
+ def test_bfs_layout_disconnected():
584
+ G = nx.complete_graph(5)
585
+ G.add_edges_from([(10, 11), (11, 12)])
586
+ with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"):
587
+ nx.bfs_layout(G, start=0)
588
+
589
+
590
+ def test_bipartite_layout_default_nodes_raises_non_bipartite_input():
591
+ G = nx.complete_graph(5)
592
+ with pytest.raises(nx.NetworkXError, match="Graph is not bipartite"):
593
+ nx.bipartite_layout(G)
594
+ # No exception if nodes are explicitly specified
595
+ pos = nx.bipartite_layout(G, nodes=[2, 3])
596
+
597
+
598
+ def test_bipartite_layout_default_nodes():
599
+ G = nx.complete_bipartite_graph(3, 3)
600
+ pos = nx.bipartite_layout(G) # no nodes specified
601
+ # X coords of nodes should be the same within the bipartite sets
602
+ for nodeset in nx.bipartite.sets(G):
603
+ xs = [pos[k][0] for k in nodeset]
604
+ assert all(x == pytest.approx(xs[0]) for x in xs)
605
+
606
+
607
+ @pytest.mark.parametrize(
608
+ "layout",
609
+ [
610
+ nx.random_layout,
611
+ nx.circular_layout,
612
+ nx.shell_layout,
613
+ nx.spring_layout,
614
+ nx.kamada_kawai_layout,
615
+ nx.spectral_layout,
616
+ nx.planar_layout,
617
+ nx.spiral_layout,
618
+ nx.forceatlas2_layout,
619
+ ],
620
+ )
621
+ def test_layouts_negative_dim(layout):
622
+ """Test all layouts that support dim kwarg handle invalid inputs."""
623
+ G = nx.path_graph(4)
624
+ valid_err_msgs = "|".join(
625
+ [
626
+ "negative dimensions.*not allowed",
627
+ "can only handle 2",
628
+ "cannot handle.*2",
629
+ ]
630
+ )
631
+ with pytest.raises(ValueError, match=valid_err_msgs):
632
+ layout(G, dim=-1)
633
+
634
+
635
+ @pytest.mark.parametrize(
636
+ "layout",
637
+ [
638
+ nx.random_layout,
639
+ nx.circular_layout,
640
+ nx.kamada_kawai_layout,
641
+ nx.spring_layout,
642
+ nx.spectral_layout,
643
+ ],
644
+ )
645
+ @pytest.mark.parametrize("dim", [3, 4, 5])
646
+ def test_dim_parameter(layout, dim):
647
+ """Test layouts that support unrestricted dim kwarg."""
648
+ G = nx.path_graph(4)
649
+ pos = layout(G, dim=dim)
650
+ assert len(pos) == len(G)
651
+ for coords in pos.values():
652
+ assert len(coords) == dim
653
+
654
+
655
+ @pytest.mark.parametrize(
656
+ ("num_nodes", "expected_method"), [(100, "force"), (501, "energy")]
657
+ )
658
+ @pytest.mark.parametrize(
659
+ "extra_layout_kwargs",
660
+ [
661
+ {}, # No extra kwargs
662
+ {"pos": {0: (0, 0)}, "fixed": [0]}, # Fixed node position
663
+ {"dim": 3}, # 3D layout
664
+ ],
665
+ )
666
+ def test_spring_layout_graph_size_heuristic(
667
+ num_nodes, expected_method, extra_layout_kwargs
668
+ ):
669
+ """Expect 'force' layout for n < 500 and 'energy' for n >= 500"""
670
+ G = nx.cycle_graph(num_nodes)
671
+ # Seeded layout to compare explicit method to one determined by "auto"
672
+ seed = 163674319
673
+
674
+ # Compare explicit method to auto method
675
+ expected = nx.spring_layout(
676
+ G, method=expected_method, seed=seed, **extra_layout_kwargs
677
+ )
678
+ actual = nx.spring_layout(G, method="auto", seed=seed, **extra_layout_kwargs)
679
+ assert np.allclose(list(expected.values()), list(actual.values()), atol=1e-5)
venv/lib/python3.14/site-packages/networkx/drawing/tests/test_pydot.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for pydot drawing functions."""
2
+
3
+ import subprocess
4
+ from io import StringIO
5
+
6
+ import pytest
7
+
8
+ import networkx as nx
9
+ from networkx.utils import graphs_equal
10
+
11
+ pydot = pytest.importorskip("pydot")
12
+
13
+ # NOTE: pydot layouts and drawing require graphviz to be installed. Skip these
14
+ # tests if they are not found
15
+ try:
16
+ subprocess.check_output("dot -V".split())
17
+ has_graphviz = True
18
+ except FileNotFoundError:
19
+ has_graphviz = False
20
+
21
+
22
+ class TestPydot:
23
+ @pytest.mark.skipif(not has_graphviz, reason="graphviz required for layout")
24
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
25
+ @pytest.mark.parametrize("prog", ("neato", "dot"))
26
+ def test_pydot(self, G, prog, tmp_path):
27
+ """
28
+ Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
29
+ passed basename of an external GraphViz command (e.g., `dot`, `neato`).
30
+ """
31
+
32
+ # Set the name of this graph to... "G". Failing to do so will
33
+ # subsequently trip an assertion expecting this name.
34
+ G.graph["name"] = "G"
35
+
36
+ # Add arbitrary nodes and edges to the passed empty graph.
37
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
38
+ G.add_node("E")
39
+
40
+ # Validate layout of this graph with the passed GraphViz command.
41
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
42
+ assert isinstance(graph_layout, dict)
43
+
44
+ # Convert this graph into a "pydot.Dot" instance.
45
+ P = nx.nx_pydot.to_pydot(G)
46
+
47
+ # Convert this "pydot.Dot" instance back into a graph of the same type.
48
+ G2 = G.__class__(nx.nx_pydot.from_pydot(P))
49
+
50
+ # Validate the original and resulting graphs to be the same.
51
+ assert graphs_equal(G, G2)
52
+
53
+ fname = tmp_path / "out.dot"
54
+
55
+ # Serialize this "pydot.Dot" instance to a temporary file in dot format
56
+ P.write_raw(fname)
57
+
58
+ # Deserialize a list of new "pydot.Dot" instances back from this file.
59
+ Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")
60
+
61
+ # Validate this file to contain only one graph.
62
+ assert len(Pin_list) == 1
63
+
64
+ # The single "pydot.Dot" instance deserialized from this file.
65
+ Pin = Pin_list[0]
66
+
67
+ # Sorted list of all nodes in the original "pydot.Dot" instance.
68
+ n1 = sorted(p.get_name() for p in P.get_node_list())
69
+
70
+ # Sorted list of all nodes in the deserialized "pydot.Dot" instance.
71
+ n2 = sorted(p.get_name() for p in Pin.get_node_list())
72
+
73
+ # Validate these instances to contain the same nodes.
74
+ assert n1 == n2
75
+
76
+ # Sorted list of all edges in the original "pydot.Dot" instance.
77
+ e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list())
78
+
79
+ # Sorted list of all edges in the original "pydot.Dot" instance.
80
+ e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list())
81
+
82
+ # Validate these instances to contain the same edges.
83
+ assert e1 == e2
84
+
85
+ # Deserialize a new graph of the same type back from this file.
86
+ Hin = nx.nx_pydot.read_dot(fname)
87
+ Hin = G.__class__(Hin)
88
+
89
+ # Validate the original and resulting graphs to be the same.
90
+ assert graphs_equal(G, Hin)
91
+
92
+ def test_read_write(self):
93
+ G = nx.MultiGraph()
94
+ G.graph["name"] = "G"
95
+ G.add_edge("1", "2", key="0") # read assumes strings
96
+ fh = StringIO()
97
+ nx.nx_pydot.write_dot(G, fh)
98
+ fh.seek(0)
99
+ H = nx.nx_pydot.read_dot(fh)
100
+ assert graphs_equal(G, H)
101
+
102
+
103
+ @pytest.mark.skipif(not has_graphviz, reason="graphviz required for layout")
104
+ def test_pydot_issue_7581(tmp_path):
105
+ """Validate that `nx_pydot.pydot_layout` handles nodes
106
+ with characters like "\n", " ".
107
+
108
+ Those characters cause `pydot` to escape and quote them on output,
109
+ which caused #7581.
110
+ """
111
+ G = nx.Graph()
112
+ G.add_edges_from([("A\nbig test", "B"), ("A\nbig test", "C"), ("B", "C")])
113
+
114
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
115
+ assert isinstance(graph_layout, dict)
116
+
117
+ # Convert the graph to pydot and back into a graph. There should be no difference.
118
+ P = nx.nx_pydot.to_pydot(G)
119
+ G2 = nx.Graph(nx.nx_pydot.from_pydot(P))
120
+ assert graphs_equal(G, G2)
121
+
122
+
123
+ @pytest.mark.parametrize(
124
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
125
+ )
126
+ def test_hashable_pydot(graph_type):
127
+ # gh-5790
128
+ G = graph_type()
129
+ G.add_edge("5", frozenset([1]), t='"Example:A"', l=False)
130
+ G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"]))
131
+ G.add_edge("node", (3, 3), w="string")
132
+
133
+ assert [
134
+ {"t": '"Example:A"', "l": "False"},
135
+ {"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"},
136
+ {"w": "string"},
137
+ ] == [
138
+ attr
139
+ for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
140
+ ]
141
+
142
+ assert {str(i) for i in G.nodes()} == set(
143
+ nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes
144
+ )
145
+
146
+
147
+ @pytest.mark.skipif(not has_graphviz, reason="graphviz required for layout")
148
+ def test_pydot_numerical_name():
149
+ G = nx.Graph()
150
+ G.add_edges_from([("A", "B"), (0, 1)])
151
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
152
+ assert isinstance(graph_layout, dict)
153
+ assert "0" not in graph_layout
154
+ assert 0 in graph_layout
155
+ assert "1" not in graph_layout
156
+ assert 1 in graph_layout
157
+ assert "A" in graph_layout
158
+ assert "B" in graph_layout
venv/lib/python3.14/site-packages/networkx/drawing/tests/test_pylab.py ADDED
@@ -0,0 +1,1581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for matplotlib drawing functions."""
2
+
3
+ import itertools
4
+ import warnings
5
+
6
+ import pytest
7
+
8
+ import networkx as nx
9
+
10
+ mpl = pytest.importorskip("matplotlib")
11
+ np = pytest.importorskip("numpy")
12
+ mpl.use("PS")
13
+ plt = pytest.importorskip("matplotlib.pyplot")
14
+ plt.rcParams["text.usetex"] = False
15
+
16
+
17
+ barbell = nx.barbell_graph(4, 6)
18
+
19
+ defaults = {
20
+ "node_pos": None,
21
+ "node_visible": True,
22
+ "node_color": "#1f78b4",
23
+ "node_size": 300,
24
+ "node_label": {
25
+ "size": 12,
26
+ "color": "#000000",
27
+ "family": "sans-serif",
28
+ "weight": "normal",
29
+ "alpha": 1.0,
30
+ "background_color": None,
31
+ "background_alpha": None,
32
+ "h_align": "center",
33
+ "v_align": "center",
34
+ "bbox": None,
35
+ },
36
+ "node_shape": "o",
37
+ "node_alpha": 1.0,
38
+ "node_border_width": 1.0,
39
+ "node_border_color": "face",
40
+ "edge_visible": True,
41
+ "edge_width": 1.0,
42
+ "edge_color": "#000000",
43
+ "edge_label": {
44
+ "size": 12,
45
+ "color": "#000000",
46
+ "family": "sans-serif",
47
+ "weight": "normal",
48
+ "alpha": 1.0,
49
+ "bbox": {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)},
50
+ "h_align": "center",
51
+ "v_align": "center",
52
+ "pos": 0.5,
53
+ "rotate": True,
54
+ },
55
+ "edge_style": "-",
56
+ "edge_alpha": 1.0,
57
+ # These are for undirected-graphs. Directed graphs should use "-|>" and 10, respectively
58
+ "edge_arrowstyle": "-",
59
+ "edge_arrowsize": 0,
60
+ "edge_curvature": "arc3",
61
+ "edge_source_margin": 0,
62
+ "edge_target_margin": 0,
63
+ }
64
+
65
+
66
+ @pytest.mark.parametrize(
67
+ ("param_name", "param_value", "expected"),
68
+ (
69
+ ("node_color", None, defaults["node_color"]),
70
+ ("node_color", "#FF0000", "red"),
71
+ ("node_color", "color", "lime"),
72
+ ),
73
+ )
74
+ def test_display_arg_handling_node_color(param_name, param_value, expected):
75
+ G = nx.path_graph(4)
76
+ nx.set_node_attributes(G, "#00FF00", "color")
77
+ canvas = plt.figure().add_subplot(111)
78
+ nx.display(G, canvas=canvas, **{param_name: param_value})
79
+ assert mpl.colors.same_color(canvas.get_children()[0].get_edgecolors()[0], expected)
80
+ plt.close()
81
+
82
+
83
+ @pytest.mark.parametrize(
84
+ ("param_value", "expected"),
85
+ (
86
+ (None, (1, 1, 1, 1)), # default value
87
+ (0.5, (0.5, 0.5, 0.5, 0.5)),
88
+ ("n_alpha", (1.0, 1 / 2, 1 / 3, 0.25)),
89
+ ),
90
+ )
91
+ def test_display_arg_handling_node_alpha(param_value, expected):
92
+ G = nx.path_graph(4)
93
+ nx.set_node_attributes(G, {n: 1 / (n + 1) for n in G.nodes()}, "n_alpha")
94
+ canvas = plt.figure().add_subplot(111)
95
+ nx.display(G, canvas=canvas, node_alpha=param_value)
96
+ assert all(
97
+ canvas.get_children()[0].get_fc()[:, 3] == expected
98
+ ) # Extract just the alpha from the node colors
99
+ plt.close()
100
+
101
+
102
+ def test_display_node_position():
103
+ G = nx.path_graph(4)
104
+ nx.set_node_attributes(G, {n: (n, n) for n in G.nodes()}, "pos")
105
+ canvas = plt.figure().add_subplot(111)
106
+ nx.display(G, canvas=canvas, node_pos="pos")
107
+ assert np.all(
108
+ canvas.get_children()[0].get_offsets().data == [[0, 0], [1, 1], [2, 2], [3, 3]]
109
+ )
110
+ plt.close()
111
+
112
+
113
+ def test_display_line_collection():
114
+ G = nx.karate_club_graph()
115
+ nx.set_edge_attributes(
116
+ G, {(u, v): "-|>" if (u + v) % 2 else "-" for u, v in G.edges()}, "arrowstyle"
117
+ )
118
+ canvas = plt.figure().add_subplot(111)
119
+ nx.display(G, canvas=canvas, edge_arrowsize=10)
120
+ # There should only be one line collection in any given visualization
121
+ lc = [
122
+ l
123
+ for l in canvas.get_children()
124
+ if isinstance(l, mpl.collections.LineCollection)
125
+ ][0]
126
+ assert len(lc.get_paths()) == sum([1 for u, v in G.edges() if (u + v) % 2])
127
+ plt.close()
128
+
129
+
130
+ @pytest.mark.parametrize(
131
+ ("edge_color", "expected"),
132
+ (
133
+ (None, "black"),
134
+ ("r", "red"),
135
+ ((1.0, 1.0, 0.0), "yellow"),
136
+ ((0, 1, 0, 1), "lime"),
137
+ ("color", "blue"),
138
+ ("#0000FF", "blue"),
139
+ ),
140
+ )
141
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
142
+ def test_display_edge_single_color(edge_color, expected, graph_type):
143
+ G = nx.path_graph(3, create_using=graph_type)
144
+ nx.set_edge_attributes(G, "#0000FF", "color")
145
+ canvas = plt.figure().add_subplot(111)
146
+ nx.display(G, edge_color=edge_color, canvas=canvas)
147
+ if G.is_directed():
148
+ colors = [
149
+ f.get_fc()
150
+ for f in canvas.get_children()
151
+ if isinstance(f, mpl.patches.FancyArrowPatch)
152
+ ]
153
+ else:
154
+ colors = [
155
+ l
156
+ for l in canvas.collections
157
+ if isinstance(l, mpl.collections.LineCollection)
158
+ ][0].get_colors()
159
+ assert all(mpl.colors.same_color(c, expected) for c in colors)
160
+ plt.close()
161
+
162
+
163
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
164
+ def test_display_edge_multiple_colors(graph_type):
165
+ G = nx.path_graph(3, create_using=graph_type)
166
+ nx.set_edge_attributes(G, {(0, 1): "#FF0000", (1, 2): (0, 0, 1)}, "color")
167
+ ax = plt.figure().add_subplot(111)
168
+ nx.display(G, canvas=ax)
169
+ expected = ["red", "blue"]
170
+ if G.is_directed():
171
+ colors = [
172
+ f.get_fc()
173
+ for f in ax.get_children()
174
+ if isinstance(f, mpl.patches.FancyArrowPatch)
175
+ ]
176
+ else:
177
+ colors = [
178
+ l for l in ax.collections if isinstance(l, mpl.collections.LineCollection)
179
+ ][0].get_colors()
180
+ assert mpl.colors.same_color(colors, expected)
181
+ plt.close()
182
+
183
+
184
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
185
+ def test_display_edge_position(graph_type):
186
+ G = nx.path_graph(3, create_using=graph_type)
187
+ nx.set_node_attributes(G, {n: (n, n) for n in G.nodes()}, "pos")
188
+ ax = plt.figure().add_subplot(111)
189
+ nx.display(G, canvas=ax)
190
+ if G.is_directed():
191
+ end_points = [
192
+ (f.get_path().vertices[0, :], f.get_path().vertices[-2, :])
193
+ for f in ax.get_children()
194
+ if isinstance(f, mpl.patches.FancyArrowPatch)
195
+ ]
196
+ else:
197
+ line_collection = [
198
+ l for l in ax.collections if isinstance(l, mpl.collections.LineCollection)
199
+ ][0]
200
+ end_points = [
201
+ (p.vertices[0, :], p.vertices[-1, :]) for p in line_collection.get_paths()
202
+ ]
203
+ expected = [((0, 0), (1, 1)), ((1, 1), (2, 2))]
204
+ # Use the threshold to account for slight shifts in FancyArrowPatch margins to
205
+ # avoid covering the arrow head with the node.
206
+ threshold = 0.05
207
+ for a, e in zip(end_points, expected):
208
+ act_start, act_end = a
209
+ exp_start, exp_end = e
210
+ assert all(abs(act_start - exp_start) < (threshold, threshold)) and all(
211
+ abs(act_end - exp_end) < (threshold, threshold)
212
+ )
213
+ plt.close()
214
+
215
+
216
+ def test_display_position_function():
217
+ G = nx.karate_club_graph()
218
+
219
+ def fixed_layout(G):
220
+ return nx.spring_layout(G, seed=314159)
221
+
222
+ pos = fixed_layout(G)
223
+ ax = plt.figure().add_subplot(111)
224
+ nx.display(G, node_pos=fixed_layout, canvas=ax)
225
+ # rebuild the position dictionary from the canvas
226
+ act_pos = {
227
+ n: tuple(p) for n, p in zip(G.nodes(), ax.get_children()[0].get_offsets().data)
228
+ }
229
+ for n in G.nodes():
230
+ assert all(pos[n] == act_pos[n])
231
+ plt.close()
232
+
233
+
234
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
235
+ def test_display_edge_colormaps(graph_type):
236
+ G = nx.path_graph(3, create_using=graph_type)
237
+ nx.set_edge_attributes(G, {(0, 1): 0, (1, 2): 1}, "weight")
238
+ cmap = mpl.colormaps["plasma"]
239
+ nx.apply_matplotlib_colors(G, "weight", "color", cmap, nodes=False)
240
+ canvas = plt.figure().add_subplot(111)
241
+ nx.display(G, canvas=canvas)
242
+ mapper = mpl.cm.ScalarMappable(cmap=cmap)
243
+ mapper.set_clim(0, 1)
244
+ expected = [mapper.to_rgba(0), mapper.to_rgba(1)]
245
+ if G.is_directed():
246
+ colors = [
247
+ f.get_facecolor()
248
+ for f in canvas.get_children()
249
+ if isinstance(f, mpl.patches.FancyArrowPatch)
250
+ ]
251
+ else:
252
+ colors = [
253
+ l
254
+ for l in canvas.collections
255
+ if isinstance(l, mpl.collections.LineCollection)
256
+ ][0].get_colors()
257
+ assert mpl.colors.same_color(expected[0], G.edges[0, 1]["color"])
258
+ assert mpl.colors.same_color(expected[1], G.edges[1, 2]["color"])
259
+ assert mpl.colors.same_color(expected, colors)
260
+ plt.close()
261
+
262
+
263
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
264
+ def test_display_node_colormaps(graph_type):
265
+ G = nx.path_graph(3, create_using=graph_type)
266
+ nx.set_node_attributes(G, {0: 0, 1: 0.5, 2: 1}, "weight")
267
+ cmap = mpl.colormaps["plasma"]
268
+ nx.apply_matplotlib_colors(G, "weight", "color", cmap)
269
+ canvas = plt.figure().add_subplot(111)
270
+ nx.display(G, canvas=canvas)
271
+ mapper = mpl.cm.ScalarMappable(cmap=cmap)
272
+ mapper.set_clim(0, 1)
273
+ expected = [mapper.to_rgba(0), mapper.to_rgba(0.5), mapper.to_rgba(1)]
274
+ colors = [
275
+ s for s in canvas.collections if isinstance(s, mpl.collections.PathCollection)
276
+ ][0].get_edgecolors()
277
+ assert mpl.colors.same_color(expected[0], G.nodes[0]["color"])
278
+ assert mpl.colors.same_color(expected[1], G.nodes[1]["color"])
279
+ assert mpl.colors.same_color(expected[2], G.nodes[2]["color"])
280
+ assert mpl.colors.same_color(expected, colors)
281
+ plt.close()
282
+
283
+
284
+ @pytest.mark.parametrize(
285
+ ("param_value", "expected"),
286
+ (
287
+ (None, [defaults["edge_width"], defaults["edge_width"]]),
288
+ (5, [5, 5]),
289
+ ("width", [5, 10]),
290
+ ),
291
+ )
292
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
293
+ def test_display_edge_width(param_value, expected, graph_type):
294
+ G = nx.path_graph(3, create_using=graph_type)
295
+ nx.set_edge_attributes(G, {(0, 1): 5, (1, 2): 10}, "width")
296
+ canvas = plt.figure().add_subplot(111)
297
+ nx.display(G, edge_width=param_value, canvas=canvas)
298
+ if G.is_directed():
299
+ widths = [
300
+ f.get_linewidth()
301
+ for f in canvas.get_children()
302
+ if isinstance(f, mpl.patches.FancyArrowPatch)
303
+ ]
304
+ else:
305
+ widths = list(
306
+ [
307
+ l
308
+ for l in canvas.collections
309
+ if isinstance(l, mpl.collections.LineCollection)
310
+ ][0].get_linewidths()
311
+ )
312
+ assert widths == expected
313
+
314
+
315
+ @pytest.mark.parametrize(
316
+ ("param_value", "expected"),
317
+ (
318
+ (None, [defaults["edge_style"], defaults["edge_style"]]),
319
+ (":", [":", ":"]),
320
+ ("style", ["-", ":"]),
321
+ ),
322
+ )
323
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
324
+ def test_display_edge_style(param_value, expected, graph_type):
325
+ G = nx.path_graph(3, create_using=graph_type)
326
+ nx.set_edge_attributes(G, {(0, 1): "-", (1, 2): ":"}, "style")
327
+ canvas = plt.figure().add_subplot(111)
328
+ nx.display(G, edge_style=param_value, canvas=canvas)
329
+ if G.is_directed():
330
+ styles = [
331
+ f.get_linestyle()
332
+ for f in canvas.get_children()
333
+ if isinstance(f, mpl.patches.FancyArrowPatch)
334
+ ]
335
+ else:
336
+ # Convert back from tuple description to character form
337
+ linestyles = {(0, None): "-", (0, (1, 1.65)): ":"}
338
+ styles = [
339
+ linestyles[(s[0], tuple(s[1]) if s[1] is not None else None)]
340
+ for s in [
341
+ l
342
+ for l in canvas.collections
343
+ if isinstance(l, mpl.collections.LineCollection)
344
+ ][0].get_linestyles()
345
+ ]
346
+ assert styles == expected
347
+ plt.close()
348
+
349
+
350
+ def test_display_node_labels():
351
+ G = nx.path_graph(4)
352
+ canvas = plt.figure().add_subplot(111)
353
+ nx.display(G, canvas=canvas, node_label={"size": 20})
354
+ labels = [t for t in canvas.get_children() if isinstance(t, mpl.text.Text)]
355
+ for n, l in zip(G.nodes(), labels):
356
+ assert l.get_text() == str(n)
357
+ assert l.get_size() == 20.0
358
+ plt.close()
359
+
360
+
361
+ def test_display_edge_labels():
362
+ G = nx.path_graph(4)
363
+ canvas = plt.figure().add_subplot(111)
364
+ # While we can pass in dicts for edge label defaults without errors,
365
+ # this isn't helpful unless we want one label for all edges.
366
+ nx.set_edge_attributes(G, {(u, v): {"label": u + v} for u, v in G.edges()})
367
+ nx.display(G, canvas=canvas, edge_label={"color": "r"}, node_label=None)
368
+ labels = [t for t in canvas.get_children() if isinstance(t, mpl.text.Text)]
369
+ print(labels)
370
+ for e, l in zip(G.edges(), labels):
371
+ assert l.get_text() == str(e[0] + e[1])
372
+ assert l.get_color() == "r"
373
+ plt.close()
374
+
375
+
376
+ def test_display_multigraph_non_integer_keys():
377
+ G = nx.MultiGraph()
378
+ G.add_nodes_from(["A", "B", "C", "D"])
379
+ G.add_edges_from(
380
+ [
381
+ ("A", "B", "0"),
382
+ ("A", "B", "1"),
383
+ ("B", "C", "-1"),
384
+ ("B", "C", "1"),
385
+ ("C", "D", "-1"),
386
+ ("C", "D", "0"),
387
+ ]
388
+ )
389
+ nx.set_edge_attributes(
390
+ G, {e: f"arc3,rad={0.2 * int(e[2])}" for e in G.edges(keys=True)}, "curvature"
391
+ )
392
+ canvas = plt.figure().add_subplot(111)
393
+ nx.display(G, canvas=canvas)
394
+ rads = [
395
+ f.get_connectionstyle().rad
396
+ for f in canvas.get_children()
397
+ if isinstance(f, mpl.patches.FancyArrowPatch)
398
+ ]
399
+ assert rads == [0.0, 0.2, -0.2, 0.2, -0.2, 0.0]
400
+ plt.close()
401
+
402
+
403
+ def test_display_raises_for_bad_arg():
404
+ G = nx.karate_club_graph()
405
+ with pytest.raises(nx.NetworkXError):
406
+ nx.display(G, bad_arg="bad_arg")
407
+ plt.close()
408
+
409
+
410
+ def test_display_arrow_size():
411
+ G = nx.path_graph(4, create_using=nx.DiGraph)
412
+ nx.set_edge_attributes(
413
+ G, {(u, v): (u + v + 2) ** 2 for u, v in G.edges()}, "arrowsize"
414
+ )
415
+ ax = plt.axes()
416
+ nx.display(G, canvas=ax)
417
+ assert [9, 25, 49] == [
418
+ f.get_mutation_scale()
419
+ for f in ax.get_children()
420
+ if isinstance(f, mpl.patches.FancyArrowPatch)
421
+ ]
422
+ plt.close()
423
+
424
+
425
+ def test_display_mismatched_edge_position():
426
+ """
427
+ This test ensures that a error is raised for incomplete position data.
428
+ """
429
+ G = nx.path_graph(5)
430
+ # Notice that there is no position for node 3
431
+ nx.set_node_attributes(G, {0: (0, 0), 1: (1, 1), 2: (2, 2), 4: (4, 4)}, "pos")
432
+ # But that's not a problem since we don't want to show node 4, right?
433
+ nx.set_node_attributes(G, {n: n < 4 for n in G.nodes()}, "visible")
434
+ # However, if we try to visualize every edge (including 3 -> 4)...
435
+ # That's a problem since node 4 doesn't have a position
436
+ with pytest.raises(nx.NetworkXError):
437
+ nx.display(G)
438
+
439
+
440
+ # NOTE: parametrizing on marker to test both branches of internal
441
+ # to_marker_edge function
442
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
443
+ def test_display_edge_margins(node_shape):
444
+ """
445
+ Test that there is a wider gap between the node and the start of an
446
+ incident edge when min_source_margin is specified.
447
+
448
+ This test checks that the use os min_{source/target}_margin edge
449
+ attributes result is shorter (more padding) between the edges and
450
+ source and target nodes.
451
+
452
+
453
+ As a crude visual example, let 's' and 't' represent source and target
454
+ nodes, respectively:
455
+
456
+ Default:
457
+ s-----------------------------t
458
+
459
+ With margins:
460
+ s ----------------------- t
461
+
462
+ """
463
+ ax = plt.figure().add_subplot(111)
464
+ G = nx.DiGraph([(0, 1)])
465
+ nx.set_node_attributes(G, {0: (0, 0), 1: (1, 1)}, "pos")
466
+ # Get the default patches from the regular visualization
467
+ nx.display(G, canvas=ax, node_shape=node_shape)
468
+ default_arrow = [
469
+ f for f in ax.get_children() if isinstance(f, mpl.patches.FancyArrowPatch)
470
+ ][0]
471
+ default_extent = default_arrow.get_extents().corners()[::2, 0]
472
+ # Now plot again with margins
473
+ ax = plt.figure().add_subplot(111)
474
+ nx.display(
475
+ G,
476
+ canvas=ax,
477
+ edge_source_margin=100,
478
+ edge_target_margin=100,
479
+ node_shape=node_shape,
480
+ )
481
+ padded_arrow = [
482
+ f for f in ax.get_children() if isinstance(f, mpl.patches.FancyArrowPatch)
483
+ ][0]
484
+ padded_extent = padded_arrow.get_extents().corners()[::2, 0]
485
+
486
+ # With padding, the left-most extent of the edge should be further to the right
487
+ assert padded_extent[0] > default_extent[0]
488
+ # And the rightmost extent of the edge, further to the left
489
+ assert padded_extent[1] < default_extent[1]
490
+ plt.close()
491
+
492
+
493
+ @pytest.mark.parametrize("ticks", [False, True])
494
+ def test_display_hide_ticks(ticks):
495
+ G = nx.path_graph(3)
496
+ nx.set_node_attributes(G, {n: (n, n) for n in G.nodes()}, "pos")
497
+ ax = plt.axes()
498
+ nx.display(G, hide_ticks=ticks)
499
+ for axis in [ax.xaxis, ax.yaxis]:
500
+ assert bool(axis.get_ticklabels()) != ticks
501
+
502
+ plt.close()
503
+
504
+
505
+ def test_display_self_loop():
506
+ ax = plt.axes()
507
+ G = nx.DiGraph()
508
+ G.add_node(0)
509
+ G.add_edge(0, 0)
510
+ nx.set_node_attributes(G, {0: (0, 0)}, "pos")
511
+ nx.display(G, canvas=ax)
512
+ arrow = [
513
+ f for f in ax.get_children() if isinstance(f, mpl.patches.FancyArrowPatch)
514
+ ][0]
515
+ bbox = arrow.get_extents()
516
+ print(bbox.width)
517
+ print(bbox.height)
518
+ assert bbox.width > 0 and bbox.height > 0
519
+
520
+ plt.delaxes(ax)
521
+ plt.close()
522
+
523
+
524
+ def test_display_remove_pos_attr():
525
+ """
526
+ If the pos attribute isn't provided or is a function, display computes the layout
527
+ and adds it to the graph. We need to ensure that this new attribute is removed from
528
+ the returned graph.
529
+ """
530
+ G = nx.karate_club_graph()
531
+ nx.display(G)
532
+ assert nx.get_node_attributes(G, "display's position attribute name") == {}
533
+
534
+
535
+ @pytest.fixture
536
+ def subplots():
537
+ fig, ax = plt.subplots()
538
+ yield fig, ax
539
+ plt.delaxes(ax)
540
+ plt.close()
541
+
542
+
543
+ @pytest.mark.parametrize(
544
+ "function",
545
+ [
546
+ nx.draw_circular,
547
+ nx.draw_kamada_kawai,
548
+ nx.draw_planar,
549
+ nx.draw_random,
550
+ nx.draw_spectral,
551
+ nx.draw_spring,
552
+ nx.draw_shell,
553
+ nx.draw_forceatlas2,
554
+ ],
555
+ )
556
+ def test_draw(function, subplots, tmp_path):
557
+ if function == nx.draw_kamada_kawai:
558
+ pytest.importorskip("scipy", reason="draw_kamada_kawai requires scipy")
559
+ fig, _ = subplots
560
+ options = {"node_color": "black", "node_size": 100, "width": 3}
561
+ function(barbell, **options)
562
+ fig.savefig(tmp_path / "test.ps")
563
+
564
+
565
+ def test_draw_shell_nlist(subplots, tmp_path):
566
+ fig, _ = subplots
567
+ nlist = [list(range(4)), list(range(4, 10)), list(range(10, 14))]
568
+ nx.draw_shell(barbell, nlist=nlist)
569
+ fig.savefig(tmp_path / "test.ps")
570
+
571
+
572
+ def test_draw_bipartite(subplots, tmp_path):
573
+ fig, _ = subplots
574
+ G = nx.complete_bipartite_graph(2, 5)
575
+ nx.draw_bipartite(G)
576
+ fig.savefig(tmp_path / "test.ps")
577
+
578
+
579
+ def test_edge_colormap():
580
+ colors = range(barbell.number_of_edges())
581
+ nx.draw_spring(
582
+ barbell, edge_color=colors, width=4, edge_cmap=plt.cm.Blues, with_labels=True
583
+ )
584
+ # plt.show()
585
+
586
+
587
+ def test_draw_networkx_edge_labels(subplots, tmp_path):
588
+ fig, _ = subplots
589
+ edge = (0, 1)
590
+ G = nx.DiGraph([edge])
591
+ pos = {n: (n, n) for n in G}
592
+ nx.draw(G, pos=pos)
593
+ nx.draw_networkx_edge_labels(G, pos, edge_labels={edge: "edge"})
594
+ fig.savefig(tmp_path / "test.ps")
595
+
596
+
597
+ def test_arrows():
598
+ nx.draw_spring(barbell.to_directed())
599
+ # plt.show()
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ ("edge_color", "expected"),
604
+ (
605
+ (None, "black"), # Default
606
+ ("r", "red"), # Non-default color string
607
+ (["r"], "red"), # Single non-default color in a list
608
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
609
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
610
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
611
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
612
+ ("#0000ff", "blue"), # single color hex code
613
+ (["#0000ff"], "blue"), # hex code in list
614
+ ),
615
+ )
616
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
617
+ def test_single_edge_color_undirected(edge_color, expected, edgelist):
618
+ """Tests ways of specifying all edges have a single color for edges
619
+ drawn with a LineCollection"""
620
+
621
+ G = nx.path_graph(3)
622
+ drawn_edges = nx.draw_networkx_edges(
623
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
624
+ )
625
+ assert mpl.colors.same_color(drawn_edges.get_color(), expected)
626
+
627
+
628
+ @pytest.mark.parametrize(
629
+ ("edge_color", "expected"),
630
+ (
631
+ (None, "black"), # Default
632
+ ("r", "red"), # Non-default color string
633
+ (["r"], "red"), # Single non-default color in a list
634
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
635
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
636
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
637
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
638
+ ("#0000ff", "blue"), # single color hex code
639
+ (["#0000ff"], "blue"), # hex code in list
640
+ ),
641
+ )
642
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
643
+ def test_single_edge_color_directed(edge_color, expected, edgelist):
644
+ """Tests ways of specifying all edges have a single color for edges drawn
645
+ with FancyArrowPatches"""
646
+
647
+ G = nx.path_graph(3, create_using=nx.DiGraph)
648
+ drawn_edges = nx.draw_networkx_edges(
649
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
650
+ )
651
+ for fap in drawn_edges:
652
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
653
+
654
+
655
+ def test_edge_color_tuple_interpretation():
656
+ """If edge_color is a sequence with the same length as edgelist, then each
657
+ value in edge_color is mapped onto each edge via colormap."""
658
+ G = nx.path_graph(6, create_using=nx.DiGraph)
659
+ pos = {n: (n, n) for n in range(len(G))}
660
+
661
+ # num edges != 3 or 4 --> edge_color interpreted as rgb(a)
662
+ for ec in ((0, 0, 1), (0, 0, 1, 1)):
663
+ # More than 4 edges
664
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=ec)
665
+ for fap in drawn_edges:
666
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
667
+ # Fewer than 3 edges
668
+ drawn_edges = nx.draw_networkx_edges(
669
+ G, pos, edgelist=[(0, 1), (1, 2)], edge_color=ec
670
+ )
671
+ for fap in drawn_edges:
672
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
673
+
674
+ # num edges == 3, len(edge_color) == 4: interpreted as rgba
675
+ drawn_edges = nx.draw_networkx_edges(
676
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1, 1)
677
+ )
678
+ for fap in drawn_edges:
679
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
680
+
681
+ # num edges == 4, len(edge_color) == 3: interpreted as rgb
682
+ drawn_edges = nx.draw_networkx_edges(
683
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1)
684
+ )
685
+ for fap in drawn_edges:
686
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
687
+
688
+ # num edges == len(edge_color) == 3: interpreted with cmap, *not* as rgb
689
+ drawn_edges = nx.draw_networkx_edges(
690
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1)
691
+ )
692
+ assert mpl.colors.same_color(
693
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
694
+ )
695
+ for fap in drawn_edges:
696
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
697
+
698
+ # num edges == len(edge_color) == 4: interpreted with cmap, *not* as rgba
699
+ drawn_edges = nx.draw_networkx_edges(
700
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1, 1)
701
+ )
702
+ assert mpl.colors.same_color(
703
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
704
+ )
705
+ assert mpl.colors.same_color(
706
+ drawn_edges[2].get_edgecolor(), drawn_edges[3].get_edgecolor()
707
+ )
708
+ for fap in drawn_edges:
709
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
710
+
711
+
712
+ def test_fewer_edge_colors_than_num_edges_directed():
713
+ """Test that the edge colors are cycled when there are fewer specified
714
+ colors than edges."""
715
+ G = barbell.to_directed()
716
+ pos = nx.random_layout(barbell)
717
+ edgecolors = ("r", "g", "b")
718
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
719
+ for fap, expected in zip(drawn_edges, itertools.cycle(edgecolors)):
720
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
721
+
722
+
723
+ def test_more_edge_colors_than_num_edges_directed():
724
+ """Test that extra edge colors are ignored when there are more specified
725
+ colors than edges."""
726
+ G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges
727
+ pos = nx.random_layout(barbell)
728
+ edgecolors = ("r", "g", "b", "c") # 4 edge colors
729
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
730
+ for fap, expected in zip(drawn_edges, edgecolors[:-1]):
731
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
732
+
733
+
734
+ def test_edge_color_string_with_global_alpha_undirected():
735
+ edge_collection = nx.draw_networkx_edges(
736
+ barbell,
737
+ pos=nx.random_layout(barbell),
738
+ edgelist=[(0, 1), (1, 2)],
739
+ edge_color="purple",
740
+ alpha=0.2,
741
+ )
742
+ ec = edge_collection.get_color().squeeze() # as rgba tuple
743
+ assert len(edge_collection.get_paths()) == 2
744
+ assert mpl.colors.same_color(ec[:-1], "purple")
745
+ assert ec[-1] == 0.2
746
+
747
+
748
+ def test_edge_color_string_with_global_alpha_directed():
749
+ drawn_edges = nx.draw_networkx_edges(
750
+ barbell.to_directed(),
751
+ pos=nx.random_layout(barbell),
752
+ edgelist=[(0, 1), (1, 2)],
753
+ edge_color="purple",
754
+ alpha=0.2,
755
+ )
756
+ assert len(drawn_edges) == 2
757
+ for fap in drawn_edges:
758
+ ec = fap.get_edgecolor() # As rgba tuple
759
+ assert mpl.colors.same_color(ec[:-1], "purple")
760
+ assert ec[-1] == 0.2
761
+
762
+
763
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
764
+ def test_edge_width_default_value(graph_type):
765
+ """Test the default linewidth for edges drawn either via LineCollection or
766
+ FancyArrowPatches."""
767
+ G = nx.path_graph(2, create_using=graph_type)
768
+ pos = {n: (n, n) for n in range(len(G))}
769
+ drawn_edges = nx.draw_networkx_edges(G, pos)
770
+ if isinstance(drawn_edges, list): # directed case: list of FancyArrowPatch
771
+ drawn_edges = drawn_edges[0]
772
+ assert drawn_edges.get_linewidth() == 1
773
+
774
+
775
+ @pytest.mark.parametrize(
776
+ ("edgewidth", "expected"),
777
+ (
778
+ (3, 3), # single-value, non-default
779
+ ([3], 3), # Single value as a list
780
+ ),
781
+ )
782
+ def test_edge_width_single_value_undirected(edgewidth, expected):
783
+ G = nx.path_graph(4)
784
+ pos = {n: (n, n) for n in range(len(G))}
785
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
786
+ assert len(drawn_edges.get_paths()) == 3
787
+ assert drawn_edges.get_linewidth() == expected
788
+
789
+
790
+ @pytest.mark.parametrize(
791
+ ("edgewidth", "expected"),
792
+ (
793
+ (3, 3), # single-value, non-default
794
+ ([3], 3), # Single value as a list
795
+ ),
796
+ )
797
+ def test_edge_width_single_value_directed(edgewidth, expected):
798
+ G = nx.path_graph(4, create_using=nx.DiGraph)
799
+ pos = {n: (n, n) for n in range(len(G))}
800
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
801
+ assert len(drawn_edges) == 3
802
+ for fap in drawn_edges:
803
+ assert fap.get_linewidth() == expected
804
+
805
+
806
+ @pytest.mark.parametrize(
807
+ "edgelist",
808
+ (
809
+ [(0, 1), (1, 2), (2, 3)], # one width specification per edge
810
+ None, # fewer widths than edges - widths cycle
811
+ [(0, 1), (1, 2)], # More widths than edges - unused widths ignored
812
+ ),
813
+ )
814
+ def test_edge_width_sequence(edgelist):
815
+ G = barbell.to_directed()
816
+ pos = nx.random_layout(G)
817
+ widths = (0.5, 2.0, 12.0)
818
+ drawn_edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, width=widths)
819
+ for fap, expected_width in zip(drawn_edges, itertools.cycle(widths)):
820
+ assert fap.get_linewidth() == expected_width
821
+
822
+
823
+ def test_edge_color_with_edge_vmin_vmax():
824
+ """Test that edge_vmin and edge_vmax properly set the dynamic range of the
825
+ color map when num edges == len(edge_colors)."""
826
+ G = nx.path_graph(3, create_using=nx.DiGraph)
827
+ pos = nx.random_layout(G)
828
+ # Extract colors from the original (unscaled) colormap
829
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=[0, 1.0])
830
+ orig_colors = [e.get_edgecolor() for e in drawn_edges]
831
+ # Colors from scaled colormap
832
+ drawn_edges = nx.draw_networkx_edges(
833
+ G, pos, edge_color=[0.2, 0.8], edge_vmin=0.2, edge_vmax=0.8
834
+ )
835
+ scaled_colors = [e.get_edgecolor() for e in drawn_edges]
836
+ assert mpl.colors.same_color(orig_colors, scaled_colors)
837
+
838
+
839
+ def test_directed_edges_linestyle_default():
840
+ """Test default linestyle for edges drawn with FancyArrowPatches."""
841
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
842
+ pos = {n: (n, n) for n in range(len(G))}
843
+
844
+ # edge with default style
845
+ drawn_edges = nx.draw_networkx_edges(G, pos)
846
+ assert len(drawn_edges) == 3
847
+ for fap in drawn_edges:
848
+ assert fap.get_linestyle() == "solid"
849
+
850
+
851
+ @pytest.mark.parametrize(
852
+ "style",
853
+ (
854
+ "dashed", # edge with string style
855
+ "--", # edge with simplified string style
856
+ (1, (1, 1)), # edge with (offset, onoffseq) style
857
+ ),
858
+ )
859
+ def test_directed_edges_linestyle_single_value(style):
860
+ """Tests support for specifying linestyles with a single value to be applied to
861
+ all edges in ``draw_networkx_edges`` for FancyArrowPatch outputs
862
+ (e.g. directed edges)."""
863
+
864
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
865
+ pos = {n: (n, n) for n in range(len(G))}
866
+
867
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style)
868
+ assert len(drawn_edges) == 3
869
+ for fap in drawn_edges:
870
+ assert fap.get_linestyle() == style
871
+
872
+
873
+ @pytest.mark.parametrize(
874
+ "style_seq",
875
+ (
876
+ ["dashed"], # edge with string style in list
877
+ ["--"], # edge with simplified string style in list
878
+ [(1, (1, 1))], # edge with (offset, onoffseq) style in list
879
+ ["--", "-", ":"], # edges with styles for each edge
880
+ ["--", "-"], # edges with fewer styles than edges (styles cycle)
881
+ ["--", "-", ":", "-."], # edges with more styles than edges (extra unused)
882
+ ),
883
+ )
884
+ def test_directed_edges_linestyle_sequence(style_seq):
885
+ """Tests support for specifying linestyles with sequences in
886
+ ``draw_networkx_edges`` for FancyArrowPatch outputs (e.g. directed edges)."""
887
+
888
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
889
+ pos = {n: (n, n) for n in range(len(G))}
890
+
891
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style_seq)
892
+ assert len(drawn_edges) == 3
893
+ for fap, style in zip(drawn_edges, itertools.cycle(style_seq)):
894
+ assert fap.get_linestyle() == style
895
+
896
+
897
+ def test_return_types():
898
+ from matplotlib.collections import LineCollection, PathCollection
899
+ from matplotlib.patches import FancyArrowPatch
900
+
901
+ G = nx.frucht_graph(create_using=nx.Graph)
902
+ dG = nx.frucht_graph(create_using=nx.DiGraph)
903
+ pos = nx.spring_layout(G, seed=42)
904
+ dpos = nx.spring_layout(dG, seed=42)
905
+ # nodes
906
+ nodes = nx.draw_networkx_nodes(G, pos)
907
+ assert isinstance(nodes, PathCollection)
908
+ # edges
909
+ edges = nx.draw_networkx_edges(dG, dpos, arrows=True)
910
+ assert isinstance(edges, list)
911
+ if len(edges) > 0:
912
+ assert isinstance(edges[0], FancyArrowPatch)
913
+ edges = nx.draw_networkx_edges(dG, dpos, arrows=False)
914
+ assert isinstance(edges, LineCollection)
915
+ edges = nx.draw_networkx_edges(G, dpos, arrows=None)
916
+ assert isinstance(edges, LineCollection)
917
+ edges = nx.draw_networkx_edges(dG, pos, arrows=None)
918
+ assert isinstance(edges, list)
919
+ if len(edges) > 0:
920
+ assert isinstance(edges[0], FancyArrowPatch)
921
+
922
+
923
+ def test_labels_and_colors():
924
+ G = nx.cubical_graph()
925
+ pos = nx.spring_layout(G, seed=42) # positions for all nodes
926
+ # nodes
927
+ nx.draw_networkx_nodes(
928
+ G, pos, nodelist=[0, 1, 2, 3], node_color="r", node_size=500, alpha=0.75
929
+ )
930
+ nx.draw_networkx_nodes(
931
+ G,
932
+ pos,
933
+ nodelist=[4, 5, 6, 7],
934
+ node_color="b",
935
+ node_size=500,
936
+ alpha=[0.25, 0.5, 0.75, 1.0],
937
+ )
938
+ # edges
939
+ nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
940
+ nx.draw_networkx_edges(
941
+ G,
942
+ pos,
943
+ edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
944
+ width=8,
945
+ alpha=0.5,
946
+ edge_color="r",
947
+ )
948
+ nx.draw_networkx_edges(
949
+ G,
950
+ pos,
951
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
952
+ width=8,
953
+ alpha=0.5,
954
+ edge_color="b",
955
+ )
956
+ nx.draw_networkx_edges(
957
+ G,
958
+ pos,
959
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
960
+ arrows=True,
961
+ min_source_margin=0.5,
962
+ min_target_margin=0.75,
963
+ width=8,
964
+ edge_color="b",
965
+ )
966
+ # some math labels
967
+ labels = {}
968
+ labels[0] = r"$a$"
969
+ labels[1] = r"$b$"
970
+ labels[2] = r"$c$"
971
+ labels[3] = r"$d$"
972
+ labels[4] = r"$\alpha$"
973
+ labels[5] = r"$\beta$"
974
+ labels[6] = r"$\gamma$"
975
+ labels[7] = r"$\delta$"
976
+ colors = {n: "k" if n % 2 == 0 else "r" for n in range(8)}
977
+ nx.draw_networkx_labels(G, pos, labels, font_size=16)
978
+ nx.draw_networkx_labels(G, pos, labels, font_size=16, font_color=colors)
979
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=None, rotate=False)
980
+ nx.draw_networkx_edge_labels(G, pos, edge_labels={(4, 5): "4-5"})
981
+ # plt.show()
982
+
983
+
984
+ def test_axes(subplots):
985
+ fig, ax = subplots
986
+ nx.draw(barbell, ax=ax)
987
+ nx.draw_networkx_edge_labels(barbell, nx.circular_layout(barbell), ax=ax)
988
+
989
+
990
+ def test_empty_graph():
991
+ G = nx.Graph()
992
+ nx.draw(G)
993
+
994
+
995
+ def test_draw_empty_nodes_return_values():
996
+ # See Issue #3833
997
+ import matplotlib.collections # call as mpl.collections
998
+
999
+ G = nx.Graph([(1, 2), (2, 3)])
1000
+ DG = nx.DiGraph([(1, 2), (2, 3)])
1001
+ pos = nx.circular_layout(G)
1002
+ assert isinstance(
1003
+ nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection
1004
+ )
1005
+ assert isinstance(
1006
+ nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection
1007
+ )
1008
+
1009
+ # drawing empty edges used to return an empty LineCollection or empty list.
1010
+ # Now it is always an empty list (because edges are now lists of FancyArrows)
1011
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=True) == []
1012
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=False) == []
1013
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=False) == []
1014
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=True) == []
1015
+
1016
+
1017
+ def test_multigraph_edgelist_tuples():
1018
+ # See Issue #3295
1019
+ G = nx.path_graph(3, create_using=nx.MultiDiGraph)
1020
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)])
1021
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20, 0])
1022
+
1023
+
1024
+ def test_alpha_iter():
1025
+ pos = nx.random_layout(barbell)
1026
+ fig = plt.figure()
1027
+ # with fewer alpha elements than nodes
1028
+ fig.add_subplot(131) # Each test in a new axis object
1029
+ nx.draw_networkx_nodes(barbell, pos, alpha=[0.1, 0.2])
1030
+ # with equal alpha elements and nodes
1031
+ num_nodes = len(barbell.nodes)
1032
+ alpha = [x / num_nodes for x in range(num_nodes)]
1033
+ colors = range(num_nodes)
1034
+ fig.add_subplot(132)
1035
+ nx.draw_networkx_nodes(barbell, pos, node_color=colors, alpha=alpha)
1036
+ # with more alpha elements than nodes
1037
+ alpha.append(1)
1038
+ fig.add_subplot(133)
1039
+ nx.draw_networkx_nodes(barbell, pos, alpha=alpha)
1040
+
1041
+
1042
+ def test_multiple_node_shapes(subplots):
1043
+ fig, ax = subplots
1044
+ G = nx.path_graph(4)
1045
+ nx.draw(G, node_shape=["o", "h", "s", "^"], ax=ax)
1046
+ scatters = [
1047
+ s for s in ax.get_children() if isinstance(s, mpl.collections.PathCollection)
1048
+ ]
1049
+ assert len(scatters) == 4
1050
+
1051
+
1052
+ def test_individualized_font_attributes(subplots):
1053
+ G = nx.karate_club_graph()
1054
+ fig, ax = subplots
1055
+ nx.draw(
1056
+ G,
1057
+ ax=ax,
1058
+ font_color={n: "k" if n % 2 else "r" for n in G.nodes()},
1059
+ font_size={n: int(n / (34 / 15) + 5) for n in G.nodes()},
1060
+ )
1061
+ for n, t in zip(
1062
+ G.nodes(),
1063
+ [
1064
+ t
1065
+ for t in ax.get_children()
1066
+ if isinstance(t, mpl.text.Text) and len(t.get_text()) > 0
1067
+ ],
1068
+ ):
1069
+ expected = "black" if n % 2 else "red"
1070
+
1071
+ assert mpl.colors.same_color(t.get_color(), expected)
1072
+ assert int(n / (34 / 15) + 5) == t.get_size()
1073
+
1074
+
1075
+ def test_individualized_edge_attributes(subplots):
1076
+ G = nx.karate_club_graph()
1077
+ fig, ax = subplots
1078
+ arrowstyles = ["-|>" if (u + v) % 2 == 0 else "-[" for u, v in G.edges()]
1079
+ arrowsizes = [10 * (u % 2 + v % 2) + 10 for u, v in G.edges()]
1080
+ nx.draw(G, ax=ax, arrows=True, arrowstyle=arrowstyles, arrowsize=arrowsizes)
1081
+ arrows = [
1082
+ f for f in ax.get_children() if isinstance(f, mpl.patches.FancyArrowPatch)
1083
+ ]
1084
+ for e, a in zip(G.edges(), arrows):
1085
+ assert a.get_mutation_scale() == 10 * (e[0] % 2 + e[1] % 2) + 10
1086
+ expected = (
1087
+ mpl.patches.ArrowStyle.BracketB
1088
+ if sum(e) % 2
1089
+ else mpl.patches.ArrowStyle.CurveFilledB
1090
+ )
1091
+ assert isinstance(a.get_arrowstyle(), expected)
1092
+
1093
+
1094
+ def test_error_invalid_kwds():
1095
+ with pytest.raises(ValueError, match="Received invalid argument"):
1096
+ nx.draw(barbell, foo="bar")
1097
+
1098
+
1099
+ def test_draw_networkx_arrowsize_incorrect_size():
1100
+ G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 3)])
1101
+ arrowsize = [1, 2, 3]
1102
+ with pytest.raises(
1103
+ ValueError, match="arrowsize should have the same length as edgelist"
1104
+ ):
1105
+ nx.draw(G, arrowsize=arrowsize)
1106
+
1107
+
1108
+ @pytest.mark.parametrize("arrowsize", (30, [10, 20, 30]))
1109
+ def test_draw_edges_arrowsize(arrowsize):
1110
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
1111
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
1112
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowsize=arrowsize)
1113
+
1114
+ arrowsize = itertools.repeat(arrowsize) if isinstance(arrowsize, int) else arrowsize
1115
+
1116
+ for fap, expected in zip(edges, arrowsize):
1117
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
1118
+ assert fap.get_mutation_scale() == expected
1119
+
1120
+
1121
+ @pytest.mark.parametrize("arrowstyle", ("-|>", ["-|>", "-[", "<|-|>"]))
1122
+ def test_draw_edges_arrowstyle(arrowstyle):
1123
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
1124
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
1125
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowstyle=arrowstyle)
1126
+
1127
+ arrowstyle = (
1128
+ itertools.repeat(arrowstyle) if isinstance(arrowstyle, str) else arrowstyle
1129
+ )
1130
+
1131
+ arrow_objects = {
1132
+ "-|>": mpl.patches.ArrowStyle.CurveFilledB,
1133
+ "-[": mpl.patches.ArrowStyle.BracketB,
1134
+ "<|-|>": mpl.patches.ArrowStyle.CurveFilledAB,
1135
+ }
1136
+
1137
+ for fap, expected in zip(edges, arrowstyle):
1138
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
1139
+ assert isinstance(fap.get_arrowstyle(), arrow_objects[expected])
1140
+
1141
+
1142
+ def test_np_edgelist():
1143
+ # see issue #4129
1144
+ nx.draw_networkx(barbell, edgelist=np.array([(0, 2), (0, 3)]))
1145
+
1146
+
1147
+ def test_draw_nodes_missing_node_from_position():
1148
+ G = nx.path_graph(3)
1149
+ pos = {0: (0, 0), 1: (1, 1)} # No position for node 2
1150
+ with pytest.raises(nx.NetworkXError, match="has no position"):
1151
+ nx.draw_networkx_nodes(G, pos)
1152
+
1153
+
1154
+ def test_draw_networkx_nodes_node_shape_list_with_scalar_color(subplots):
1155
+ """Ensure draw_networkx_nodes works when node_shape is a Python list.
1156
+
1157
+ This covers the case where node_shape is a sequence (list) and node_color
1158
+ is a single scalar color, which should be supported.
1159
+ """
1160
+ fig, ax = subplots
1161
+
1162
+ G = nx.empty_graph(5)
1163
+ pos = {i: (i, i) for i in G}
1164
+
1165
+ shapes = ["o", "^", "o", "^", "o"]
1166
+
1167
+ nodes = nx.draw_networkx_nodes(
1168
+ G,
1169
+ pos,
1170
+ node_color="red", # scalar color (supported)
1171
+ node_shape=shapes, # list of shapes – this used to be buggy
1172
+ ax=ax,
1173
+ )
1174
+ # Should get a PathCollection with an element in it (same as with numpy arrays)
1175
+ assert len(nodes.get_offsets()) > 0
1176
+ # NOTE: When node_shape is a sequence, draw_networkx_nodes internally calls
1177
+ # ax.scatter multiple times and returns only the last PathCollection.
1178
+ # Therefore, we do NOT assert a value for len(nodes.get_offsets()) here.
1179
+
1180
+
1181
+ # NOTE: parametrizing on marker to test both branches of internal
1182
+ # nx.draw_networkx_edges.to_marker_edge function
1183
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
1184
+ def test_draw_edges_min_source_target_margins(node_shape, subplots):
1185
+ """Test that there is a wider gap between the node and the start of an
1186
+ incident edge when min_source_margin is specified.
1187
+
1188
+ This test checks that the use of min_{source/target}_margin kwargs result
1189
+ in shorter (more padding) between the edges and source and target nodes.
1190
+ As a crude visual example, let 's' and 't' represent source and target
1191
+ nodes, respectively:
1192
+
1193
+ Default:
1194
+ s-----------------------------t
1195
+
1196
+ With margins:
1197
+ s ----------------------- t
1198
+
1199
+ """
1200
+ # Create a single axis object to get consistent pixel coords across
1201
+ # multiple draws
1202
+ fig, ax = subplots
1203
+ G = nx.DiGraph([(0, 1)])
1204
+ pos = {0: (0, 0), 1: (1, 0)} # horizontal layout
1205
+ # Get leftmost and rightmost points of the FancyArrowPatch object
1206
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
1207
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)[0]
1208
+ default_extent = default_patch.get_extents().corners()[::2, 0]
1209
+ # Now, do the same but with "padding" for the source and target via the
1210
+ # min_{source/target}_margin kwargs
1211
+ padded_patch = nx.draw_networkx_edges(
1212
+ G,
1213
+ pos,
1214
+ ax=ax,
1215
+ node_shape=node_shape,
1216
+ min_source_margin=100,
1217
+ min_target_margin=100,
1218
+ )[0]
1219
+ padded_extent = padded_patch.get_extents().corners()[::2, 0]
1220
+
1221
+ # With padding, the left-most extent of the edge should be further to the
1222
+ # right
1223
+ assert padded_extent[0] > default_extent[0]
1224
+ # And the rightmost extent of the edge, further to the left
1225
+ assert padded_extent[1] < default_extent[1]
1226
+
1227
+
1228
+ # NOTE: parametrizing on marker to test both branches of internal
1229
+ # nx.draw_networkx_edges.to_marker_edge function
1230
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
1231
+ def test_draw_edges_min_source_target_margins_individual(node_shape, subplots):
1232
+ """Test that there is a wider gap between the node and the start of an
1233
+ incident edge when min_source_margin is specified.
1234
+
1235
+ This test checks that the use of min_{source/target}_margin kwargs result
1236
+ in shorter (more padding) between the edges and source and target nodes.
1237
+ As a crude visual example, let 's' and 't' represent source and target
1238
+ nodes, respectively:
1239
+
1240
+ Default:
1241
+ s-----------------------------t
1242
+
1243
+ With margins:
1244
+ s ----------------------- t
1245
+
1246
+ """
1247
+ # Create a single axis object to get consistent pixel coords across
1248
+ # multiple draws
1249
+ fig, ax = subplots
1250
+ G = nx.DiGraph([(0, 1), (1, 2)])
1251
+ pos = {0: (0, 0), 1: (1, 0), 2: (2, 0)} # horizontal layout
1252
+ # Get leftmost and rightmost points of the FancyArrowPatch object
1253
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
1254
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)
1255
+ default_extent = [d.get_extents().corners()[::2, 0] for d in default_patch]
1256
+ # Now, do the same but with "padding" for the source and target via the
1257
+ # min_{source/target}_margin kwargs
1258
+ padded_patch = nx.draw_networkx_edges(
1259
+ G,
1260
+ pos,
1261
+ ax=ax,
1262
+ node_shape=node_shape,
1263
+ min_source_margin=[98, 102],
1264
+ min_target_margin=[98, 102],
1265
+ )
1266
+ padded_extent = [p.get_extents().corners()[::2, 0] for p in padded_patch]
1267
+ for d, p in zip(default_extent, padded_extent):
1268
+ # With padding, the left-most extent of the edge should be further to the
1269
+ # right
1270
+ assert p[0] > d[0]
1271
+ # And the rightmost extent of the edge, further to the left
1272
+ assert p[1] < d[1]
1273
+
1274
+
1275
+ def test_nonzero_selfloop_with_single_node(subplots):
1276
+ """Ensure that selfloop extent is non-zero when there is only one node."""
1277
+ # Create explicit axis object for test
1278
+ fig, ax = subplots
1279
+ # Graph with single node + self loop
1280
+ G = nx.DiGraph()
1281
+ G.add_node(0)
1282
+ G.add_edge(0, 0)
1283
+ # Draw
1284
+ patch = nx.draw_networkx_edges(G, {0: (0, 0)})[0]
1285
+ # The resulting patch must have non-zero extent
1286
+ bbox = patch.get_extents()
1287
+ assert bbox.width > 0 and bbox.height > 0
1288
+
1289
+
1290
+ def test_nonzero_selfloop_with_single_edge_in_edgelist(subplots):
1291
+ """Ensure that selfloop extent is non-zero when only a single edge is
1292
+ specified in the edgelist.
1293
+ """
1294
+ # Create explicit axis object for test
1295
+ fig, ax = subplots
1296
+ # Graph with selfloop
1297
+ G = nx.path_graph(2, create_using=nx.DiGraph)
1298
+ G.add_edge(1, 1)
1299
+ pos = {n: (n, n) for n in G.nodes}
1300
+ # Draw only the selfloop edge via the `edgelist` kwarg
1301
+ patch = nx.draw_networkx_edges(G, pos, edgelist=[(1, 1)])[0]
1302
+ # The resulting patch must have non-zero extent
1303
+ bbox = patch.get_extents()
1304
+ assert bbox.width > 0 and bbox.height > 0
1305
+
1306
+
1307
+ def test_apply_alpha():
1308
+ """Test apply_alpha when there is a mismatch between the number of
1309
+ supplied colors and elements.
1310
+ """
1311
+ nodelist = [0, 1, 2]
1312
+ colorlist = ["r", "g", "b"]
1313
+ alpha = 0.5
1314
+ rgba_colors = nx.drawing.nx_pylab.apply_alpha(colorlist, alpha, nodelist)
1315
+ assert all(rgba_colors[:, -1] == alpha)
1316
+
1317
+
1318
+ def test_draw_edges_toggling_with_arrows_kwarg():
1319
+ """
1320
+ The `arrows` keyword argument is used as a 3-way switch to select which
1321
+ type of object to use for drawing edges:
1322
+ - ``arrows=None`` -> default (FancyArrowPatches for directed, else LineCollection)
1323
+ - ``arrows=True`` -> FancyArrowPatches
1324
+ - ``arrows=False`` -> LineCollection
1325
+ """
1326
+ import matplotlib.collections
1327
+ import matplotlib.patches
1328
+
1329
+ UG = nx.path_graph(3)
1330
+ DG = nx.path_graph(3, create_using=nx.DiGraph)
1331
+ pos = {n: (n, n) for n in UG}
1332
+
1333
+ # Use FancyArrowPatches when arrows=True, regardless of graph type
1334
+ for G in (UG, DG):
1335
+ edges = nx.draw_networkx_edges(G, pos, arrows=True)
1336
+ assert len(edges) == len(G.edges)
1337
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
1338
+
1339
+ # Use LineCollection when arrows=False, regardless of graph type
1340
+ for G in (UG, DG):
1341
+ edges = nx.draw_networkx_edges(G, pos, arrows=False)
1342
+ assert isinstance(edges, mpl.collections.LineCollection)
1343
+
1344
+ # Default behavior when arrows=None: FAPs for directed, LC's for undirected
1345
+ edges = nx.draw_networkx_edges(UG, pos)
1346
+ assert isinstance(edges, mpl.collections.LineCollection)
1347
+ edges = nx.draw_networkx_edges(DG, pos)
1348
+ assert len(edges) == len(G.edges)
1349
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
1350
+
1351
+
1352
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
1353
+ def test_draw_networkx_arrows_default_undirected(drawing_func, subplots):
1354
+ import matplotlib.collections
1355
+
1356
+ G = nx.path_graph(3)
1357
+ fig, ax = subplots
1358
+ drawing_func(G, ax=ax)
1359
+ assert any(isinstance(c, mpl.collections.LineCollection) for c in ax.collections)
1360
+ assert not ax.patches
1361
+
1362
+
1363
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
1364
+ def test_draw_networkx_arrows_default_directed(drawing_func, subplots):
1365
+ import matplotlib.collections
1366
+
1367
+ G = nx.path_graph(3, create_using=nx.DiGraph)
1368
+ fig, ax = subplots
1369
+ drawing_func(G, ax=ax)
1370
+ assert not any(
1371
+ isinstance(c, mpl.collections.LineCollection) for c in ax.collections
1372
+ )
1373
+ assert ax.patches
1374
+
1375
+
1376
+ def test_edgelist_kwarg_not_ignored(subplots):
1377
+ # See gh-4994
1378
+ G = nx.path_graph(3)
1379
+ G.add_edge(0, 0)
1380
+ fig, ax = subplots
1381
+ nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax) # Exclude self-loop from edgelist
1382
+ assert not ax.patches
1383
+
1384
+
1385
+ @pytest.mark.parametrize(
1386
+ ("G", "expected_n_edges"),
1387
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
1388
+ )
1389
+ def test_draw_networkx_edges_multiedge_connectionstyle(G, expected_n_edges):
1390
+ """Draws edges correctly for 3 types of graphs and checks for valid length"""
1391
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
1392
+ G.add_edge(u, v, weight=round(i / 3, 2))
1393
+ pos = {n: (n, n) for n in G}
1394
+ # Raises on insufficient connectionstyle length
1395
+ for conn_style in [
1396
+ "arc3,rad=0.1",
1397
+ ["arc3,rad=0.1", "arc3,rad=0.1"],
1398
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.2"],
1399
+ ]:
1400
+ nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
1401
+ arrows = nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
1402
+ assert len(arrows) == expected_n_edges
1403
+
1404
+
1405
+ @pytest.mark.parametrize(
1406
+ ("G", "expected_n_edges"),
1407
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
1408
+ )
1409
+ def test_draw_networkx_edge_labels_multiedge_connectionstyle(G, expected_n_edges):
1410
+ """Draws labels correctly for 3 types of graphs and checks for valid length and class names"""
1411
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
1412
+ G.add_edge(u, v, weight=round(i / 3, 2))
1413
+ pos = {n: (n, n) for n in G}
1414
+ # Raises on insufficient connectionstyle length
1415
+ arrows = nx.draw_networkx_edges(
1416
+ G, pos, connectionstyle=["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"]
1417
+ )
1418
+ for conn_style in [
1419
+ "arc3,rad=0.1",
1420
+ ["arc3,rad=0.1", "arc3,rad=0.2"],
1421
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"],
1422
+ ]:
1423
+ text_items = nx.draw_networkx_edge_labels(G, pos, connectionstyle=conn_style)
1424
+ assert len(text_items) == expected_n_edges
1425
+ for ti in text_items.values():
1426
+ assert ti.__class__.__name__ == "CurvedArrowText"
1427
+
1428
+
1429
+ def test_draw_networkx_edge_label_multiedge():
1430
+ G = nx.MultiGraph()
1431
+ G.add_edge(0, 1, weight=10)
1432
+ G.add_edge(0, 1, weight=20)
1433
+ edge_labels = nx.get_edge_attributes(G, "weight") # Includes edge keys
1434
+ pos = {n: (n, n) for n in G}
1435
+ text_items = nx.draw_networkx_edge_labels(
1436
+ G,
1437
+ pos,
1438
+ edge_labels=edge_labels,
1439
+ connectionstyle=["arc3,rad=0.1", "arc3,rad=0.2"],
1440
+ )
1441
+ assert len(text_items) == 2
1442
+
1443
+
1444
+ def test_draw_networkx_edge_label_empty_dict():
1445
+ """Regression test for draw_networkx_edge_labels with empty dict. See
1446
+ gh-5372."""
1447
+ G = nx.path_graph(3)
1448
+ pos = {n: (n, n) for n in G.nodes}
1449
+ assert nx.draw_networkx_edge_labels(G, pos, edge_labels={}) == {}
1450
+
1451
+
1452
+ def test_draw_networkx_edges_undirected_selfloop_colors(subplots):
1453
+ """When an edgelist is supplied along with a sequence of colors, check that
1454
+ the self-loops have the correct colors."""
1455
+ fig, ax = subplots
1456
+ # Edge list and corresponding colors
1457
+ edgelist = [(1, 3), (1, 2), (2, 3), (1, 1), (3, 3), (2, 2)]
1458
+ edge_colors = ["pink", "cyan", "black", "red", "blue", "green"]
1459
+
1460
+ G = nx.Graph(edgelist)
1461
+ pos = {n: (n, n) for n in G.nodes}
1462
+ nx.draw_networkx_edges(G, pos, ax=ax, edgelist=edgelist, edge_color=edge_colors)
1463
+
1464
+ # Verify that there are three fancy arrow patches (1 per self loop)
1465
+ assert len(ax.patches) == 3
1466
+
1467
+ # These are points that should be contained in the self loops. For example,
1468
+ # sl_points[0] will be (1, 1.1), which is inside the "path" of the first
1469
+ # self-loop but outside the others
1470
+ sl_points = np.array(edgelist[-3:]) + np.array([0, 0.1])
1471
+
1472
+ # Check that the mapping between self-loop locations and their colors is
1473
+ # correct
1474
+ for fap, clr, slp in zip(ax.patches, edge_colors[-3:], sl_points):
1475
+ assert fap.get_path().contains_point(slp)
1476
+ assert mpl.colors.same_color(fap.get_edgecolor(), clr)
1477
+
1478
+
1479
+ @pytest.mark.parametrize(
1480
+ "fap_only_kwarg", # Non-default values for kwargs that only apply to FAPs
1481
+ (
1482
+ {"arrowstyle": "-"},
1483
+ {"arrowsize": 20},
1484
+ {"connectionstyle": "arc3,rad=0.2"},
1485
+ {"min_source_margin": 10},
1486
+ {"min_target_margin": 10},
1487
+ ),
1488
+ )
1489
+ def test_user_warnings_for_unused_edge_drawing_kwargs(fap_only_kwarg, subplots):
1490
+ """Users should get a warning when they specify a non-default value for
1491
+ one of the kwargs that applies only to edges drawn with FancyArrowPatches,
1492
+ but FancyArrowPatches aren't being used under the hood."""
1493
+ G = nx.path_graph(3)
1494
+ pos = {n: (n, n) for n in G}
1495
+ fig, ax = subplots
1496
+ # By default, an undirected graph will use LineCollection to represent
1497
+ # the edges
1498
+ kwarg_name = list(fap_only_kwarg.keys())[0]
1499
+ with pytest.warns(
1500
+ UserWarning, match=f"\n\nThe {kwarg_name} keyword argument is not applicable"
1501
+ ):
1502
+ nx.draw_networkx_edges(G, pos, ax=ax, **fap_only_kwarg)
1503
+ # FancyArrowPatches are always used when `arrows=True` is specified.
1504
+ # Check that warnings are *not* raised in this case
1505
+ with warnings.catch_warnings():
1506
+ # Escalate warnings -> errors so tests fail if warnings are raised
1507
+ warnings.simplefilter("error")
1508
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
1509
+ nx.draw_networkx_edges(G, pos, ax=ax, arrows=True, **fap_only_kwarg)
1510
+
1511
+
1512
+ @pytest.mark.parametrize("draw_fn", (nx.draw, nx.draw_circular))
1513
+ def test_no_warning_on_default_draw_arrowstyle(draw_fn, subplots):
1514
+ # See gh-7284
1515
+ fig, ax = subplots
1516
+ G = nx.cycle_graph(5)
1517
+ with warnings.catch_warnings(record=True) as w:
1518
+ draw_fn(G, ax=ax)
1519
+ assert len(w) == 0
1520
+
1521
+
1522
+ @pytest.mark.parametrize("hide_ticks", [False, True])
1523
+ @pytest.mark.parametrize(
1524
+ "method",
1525
+ [
1526
+ nx.draw_networkx,
1527
+ nx.draw_networkx_edge_labels,
1528
+ nx.draw_networkx_edges,
1529
+ nx.draw_networkx_labels,
1530
+ nx.draw_networkx_nodes,
1531
+ ],
1532
+ )
1533
+ def test_hide_ticks(method, hide_ticks, subplots):
1534
+ G = nx.path_graph(3)
1535
+ pos = {n: (n, n) for n in G.nodes}
1536
+ _, ax = subplots
1537
+ method(G, pos=pos, ax=ax, hide_ticks=hide_ticks)
1538
+ for axis in [ax.xaxis, ax.yaxis]:
1539
+ assert bool(axis.get_ticklabels()) != hide_ticks
1540
+
1541
+
1542
+ @pytest.mark.parametrize(
1543
+ "style", ["angle", "angle3", "arc", "arc3,rad=0.0", "bar,fraction=0.1"]
1544
+ )
1545
+ def test_edge_label_all_connectionstyles(subplots, style):
1546
+ """
1547
+ Check that FancyArrowPatches with all `connectionstyle`s are supported
1548
+ in edge label rendering. See gh-7735 and gh-8106.
1549
+ """
1550
+ fig, ax = subplots
1551
+ edge = (0, 1)
1552
+ G = nx.DiGraph([edge])
1553
+ pos = {n: (n, 0) for n in G}
1554
+
1555
+ name = style.split(",")[0]
1556
+ labels = nx.draw_networkx_edge_labels(
1557
+ G, pos, edge_labels={edge: "edge"}, connectionstyle=style
1558
+ )
1559
+
1560
+ hmid = (pos[0][0] + pos[1][0]) / 2
1561
+ vmid = (pos[0][1] + pos[1][1]) / 2
1562
+ if name in {"arc", "arc3"}: # The label should be at roughly the midpoint.
1563
+ assert labels[edge].x, labels[edge].y == pytest.approx((hmid, vmid))
1564
+ elif name == "bar": # The label should be below the vertical midpoint.
1565
+ assert labels[edge].y < vmid
1566
+
1567
+
1568
+ @pytest.mark.parametrize("label_pos", [-0.1, 1.1])
1569
+ def test_edge_label_label_pos(subplots, label_pos):
1570
+ """
1571
+ Check that label positions can be extrapolated outside [0, 1].
1572
+ """
1573
+ fig, ax = subplots
1574
+ edge = (0, 1)
1575
+ G = nx.DiGraph([edge])
1576
+ pos = {n: (n, n) for n in G}
1577
+ lbl = nx.draw_networkx_edge_labels(
1578
+ G, pos, edge_labels={edge: "edge"}, label_pos=label_pos, connectionstyle="angle"
1579
+ )
1580
+
1581
+ assert lbl[edge].x, lbl[edge].y == pytest.approx((label_pos, label_pos))
venv/lib/python3.14/site-packages/networkx/exception.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **********
3
+ Exceptions
4
+ **********
5
+
6
+ Base exceptions and errors for NetworkX.
7
+ """
8
+
9
+ __all__ = [
10
+ "HasACycle",
11
+ "NodeNotFound",
12
+ "PowerIterationFailedConvergence",
13
+ "ExceededMaxIterations",
14
+ "AmbiguousSolution",
15
+ "NetworkXAlgorithmError",
16
+ "NetworkXException",
17
+ "NetworkXError",
18
+ "NetworkXNoCycle",
19
+ "NetworkXNoPath",
20
+ "NetworkXNotImplemented",
21
+ "NetworkXPointlessConcept",
22
+ "NetworkXUnbounded",
23
+ "NetworkXUnfeasible",
24
+ ]
25
+
26
+
27
+ class NetworkXException(Exception):
28
+ """Base class for exceptions in NetworkX."""
29
+
30
+
31
+ class NetworkXError(NetworkXException):
32
+ """Exception for a serious error in NetworkX"""
33
+
34
+
35
+ class NetworkXPointlessConcept(NetworkXException):
36
+ """Raised when a null graph is provided as input to an algorithm
37
+ that cannot use it.
38
+
39
+ The null graph is sometimes considered a pointless concept [1]_,
40
+ thus the name of the exception.
41
+
42
+ Notes
43
+ -----
44
+ Null graphs and empty graphs are often used interchangeably but they
45
+ are well defined in NetworkX. An ``empty_graph`` is a graph with ``n`` nodes
46
+ and 0 edges, and a ``null_graph`` is a graph with 0 nodes and 0 edges.
47
+
48
+ References
49
+ ----------
50
+ .. [1] Harary, F. and Read, R. "Is the Null Graph a Pointless
51
+ Concept?" In Graphs and Combinatorics Conference, George
52
+ Washington University. New York: Springer-Verlag, 1973.
53
+
54
+ """
55
+
56
+
57
+ class NetworkXAlgorithmError(NetworkXException):
58
+ """Exception for unexpected termination of algorithms."""
59
+
60
+
61
+ class NetworkXUnfeasible(NetworkXAlgorithmError):
62
+ """Exception raised by algorithms trying to solve a problem
63
+ instance that has no feasible solution."""
64
+
65
+
66
+ class NetworkXNoPath(NetworkXUnfeasible):
67
+ """Exception for algorithms that should return a path when running
68
+ on graphs where such a path does not exist."""
69
+
70
+
71
+ class NetworkXNoCycle(NetworkXUnfeasible):
72
+ """Exception for algorithms that should return a cycle when running
73
+ on graphs where such a cycle does not exist."""
74
+
75
+
76
+ class HasACycle(NetworkXException):
77
+ """Raised if a graph has a cycle when an algorithm expects that it
78
+ will have no cycles.
79
+
80
+ """
81
+
82
+
83
+ class NetworkXUnbounded(NetworkXAlgorithmError):
84
+ """Exception raised by algorithms trying to solve a maximization
85
+ or a minimization problem instance that is unbounded."""
86
+
87
+
88
+ class NetworkXNotImplemented(NetworkXException):
89
+ """Exception raised by algorithms not implemented for a type of graph."""
90
+
91
+
92
+ class NodeNotFound(NetworkXException):
93
+ """Exception raised if requested node is not present in the graph"""
94
+
95
+
96
+ class AmbiguousSolution(NetworkXException):
97
+ """Raised if more than one valid solution exists for an intermediary step
98
+ of an algorithm.
99
+
100
+ In the face of ambiguity, refuse the temptation to guess.
101
+ This may occur, for example, when trying to determine the
102
+ bipartite node sets in a disconnected bipartite graph when
103
+ computing bipartite matchings.
104
+
105
+ """
106
+
107
+
108
+ class ExceededMaxIterations(NetworkXException):
109
+ """Raised if a loop iterates too many times without breaking.
110
+
111
+ This may occur, for example, in an algorithm that computes
112
+ progressively better approximations to a value but exceeds an
113
+ iteration bound specified by the user.
114
+
115
+ """
116
+
117
+
118
+ class PowerIterationFailedConvergence(ExceededMaxIterations):
119
+ """Raised when the power iteration method fails to converge within a
120
+ specified iteration limit.
121
+
122
+ `num_iterations` is the number of iterations that have been
123
+ completed when this exception was raised.
124
+
125
+ """
126
+
127
+ def __init__(self, num_iterations, *args, **kw):
128
+ msg = f"power iteration failed to converge within {num_iterations} iterations"
129
+ exception_message = msg
130
+ superinit = super().__init__
131
+ superinit(self, exception_message, *args, **kw)
venv/lib/python3.14/site-packages/networkx/generators/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A package for generating various graphs in networkx.
3
+
4
+ """
5
+
6
+ from networkx.generators.atlas import *
7
+ from networkx.generators.classic import *
8
+ from networkx.generators.cographs import *
9
+ from networkx.generators.community import *
10
+ from networkx.generators.degree_seq import *
11
+ from networkx.generators.directed import *
12
+ from networkx.generators.duplication import *
13
+ from networkx.generators.ego import *
14
+ from networkx.generators.expanders import *
15
+ from networkx.generators.geometric import *
16
+ from networkx.generators.harary_graph import *
17
+ from networkx.generators.internet_as_graphs import *
18
+ from networkx.generators.intersection import *
19
+ from networkx.generators.interval_graph import *
20
+ from networkx.generators.joint_degree_seq import *
21
+ from networkx.generators.lattice import *
22
+ from networkx.generators.line import *
23
+ from networkx.generators.mycielski import *
24
+ from networkx.generators.nonisomorphic_trees import *
25
+ from networkx.generators.random_clustered import *
26
+ from networkx.generators.random_graphs import *
27
+ from networkx.generators.small import *
28
+ from networkx.generators.social import *
29
+ from networkx.generators.spectral_graph_forge import *
30
+ from networkx.generators.stochastic import *
31
+ from networkx.generators.sudoku import *
32
+ from networkx.generators.time_series import *
33
+ from networkx.generators.trees import *
34
+ from networkx.generators.triads import *
venv/lib/python3.14/site-packages/networkx/generators/atlas.dat.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73fc416df0164923607751cb759f4ae81deb5f6550bf25be59c86de3b747e41d
3
+ size 8887
venv/lib/python3.14/site-packages/networkx/generators/atlas.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for the small graph atlas.
3
+ """
4
+
5
+ import gzip
6
+ import importlib.resources
7
+ from itertools import islice
8
+
9
+ import networkx as nx
10
+
11
+ __all__ = ["graph_atlas", "graph_atlas_g"]
12
+
13
+ #: The total number of graphs in the atlas.
14
+ #:
15
+ #: The graphs are labeled starting from 0 and extending to (but not
16
+ #: including) this number.
17
+ NUM_GRAPHS = 1253
18
+
19
+ #: The path to the data file containing the graph edge lists.
20
+ #:
21
+ #: This is the absolute path of the gzipped text file containing the
22
+ #: edge list for each graph in the atlas. The file contains one entry
23
+ #: per graph in the atlas, in sequential order, starting from graph
24
+ #: number 0 and extending through graph number 1252 (see
25
+ #: :data:`NUM_GRAPHS`). Each entry looks like
26
+ #:
27
+ #: .. sourcecode:: text
28
+ #:
29
+ #: GRAPH 6
30
+ #: NODES 3
31
+ #: 0 1
32
+ #: 0 2
33
+ #:
34
+ #: where the first two lines are the graph's index in the atlas and the
35
+ #: number of nodes in the graph, and the remaining lines are the edge
36
+ #: list.
37
+ #:
38
+ #: This file was generated from a Python list of graphs via code like
39
+ #: the following::
40
+ #:
41
+ #: import gzip
42
+ #: from networkx.generators.atlas import graph_atlas_g
43
+ #: from networkx.readwrite.edgelist import write_edgelist
44
+ #:
45
+ #: with gzip.open('atlas.dat.gz', 'wb') as f:
46
+ #: for i, G in enumerate(graph_atlas_g()):
47
+ #: f.write(bytes(f'GRAPH {i}\n', encoding='utf-8'))
48
+ #: f.write(bytes(f'NODES {len(G)}\n', encoding='utf-8'))
49
+ #: write_edgelist(G, f, data=False)
50
+ #:
51
+
52
+ # Path to the atlas file
53
+ ATLAS_FILE = importlib.resources.files("networkx.generators") / "atlas.dat.gz"
54
+
55
+
56
+ def _generate_graphs():
57
+ """Sequentially read the file containing the edge list data for the
58
+ graphs in the atlas and generate the graphs one at a time.
59
+
60
+ This function reads the file given in :data:`.ATLAS_FILE`.
61
+
62
+ """
63
+ with gzip.open(ATLAS_FILE, "rb") as f:
64
+ line = f.readline()
65
+ while line and line.startswith(b"GRAPH"):
66
+ # The first two lines of each entry tell us the index of the
67
+ # graph in the list and the number of nodes in the graph.
68
+ # They look like this:
69
+ #
70
+ # GRAPH 3
71
+ # NODES 2
72
+ #
73
+ graph_index = int(line[6:].rstrip())
74
+ line = f.readline()
75
+ num_nodes = int(line[6:].rstrip())
76
+ # The remaining lines contain the edge list, until the next
77
+ # GRAPH line (or until the end of the file).
78
+ edgelist = []
79
+ line = f.readline()
80
+ while line and not line.startswith(b"GRAPH"):
81
+ edgelist.append(line.rstrip())
82
+ line = f.readline()
83
+ G = nx.Graph()
84
+ G.name = f"G{graph_index}"
85
+ G.add_nodes_from(range(num_nodes))
86
+ G.add_edges_from(tuple(map(int, e.split())) for e in edgelist)
87
+ yield G
88
+
89
+
90
+ @nx._dispatchable(graphs=None, returns_graph=True)
91
+ def graph_atlas(i):
92
+ """Returns graph number `i` from the Graph Atlas.
93
+
94
+ For more information, see :func:`.graph_atlas_g`.
95
+
96
+ Parameters
97
+ ----------
98
+ i : int
99
+ The index of the graph from the atlas to get. The graph at index
100
+ 0 is assumed to be the null graph.
101
+
102
+ Returns
103
+ -------
104
+ list
105
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
106
+ corresponding to the graph *i* in the Graph Atlas.
107
+
108
+ See also
109
+ --------
110
+ graph_atlas_g
111
+
112
+ Notes
113
+ -----
114
+ The time required by this function increases linearly with the
115
+ argument `i`, since it reads a large file sequentially in order to
116
+ generate the graph [1]_.
117
+
118
+ References
119
+ ----------
120
+ .. [1] Ronald C. Read and Robin J. Wilson, *An Atlas of Graphs*.
121
+ Oxford University Press, 1998.
122
+
123
+ """
124
+ if not (0 <= i < NUM_GRAPHS):
125
+ raise ValueError(f"index must be between 0 and {NUM_GRAPHS}")
126
+ return next(islice(_generate_graphs(), i, None))
127
+
128
+
129
+ @nx._dispatchable(graphs=None, returns_graph=True)
130
+ def graph_atlas_g():
131
+ """Returns the list of all graphs with up to seven nodes named in the
132
+ Graph Atlas.
133
+
134
+ The graphs are listed in increasing order by
135
+
136
+ 1. number of nodes,
137
+ 2. number of edges,
138
+ 3. degree sequence (for example 111223 < 112222),
139
+ 4. number of automorphisms,
140
+
141
+ in that order, with three exceptions as described in the *Notes*
142
+ section below. This causes the list to correspond with the index of
143
+ the graphs in the Graph Atlas [atlas]_, with the first graph,
144
+ ``G[0]``, being the null graph.
145
+
146
+ Returns
147
+ -------
148
+ list
149
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
150
+ corresponding to the graph *i* in the Graph Atlas.
151
+
152
+ Examples
153
+ --------
154
+ >>> from pprint import pprint
155
+ >>> atlas = nx.graph_atlas_g()
156
+
157
+ There are 1253 graphs in the atlas
158
+
159
+ >>> len(atlas)
160
+ 1253
161
+
162
+ The number of graphs with *n* nodes, where *n* ranges from 0 to 7:
163
+
164
+ >>> from collections import Counter
165
+ >>> num_nodes_per_graph = [len(G) for G in atlas]
166
+ >>> Counter(num_nodes_per_graph)
167
+ Counter({7: 1044, 6: 156, 5: 34, 4: 11, 3: 4, 2: 2, 0: 1, 1: 1})
168
+
169
+ Since the atlas is ordered by the number of nodes in the graph, all graphs
170
+ with *n* nodes can be obtained by slicing the atlas. For example, all
171
+ graphs with 5 nodes:
172
+
173
+ >>> G5_list = atlas[19:53]
174
+ >>> all(len(G) == 5 for G in G5_list)
175
+ True
176
+
177
+ Or all graphs with at least 3 nodes but fewer than 7 nodes:
178
+
179
+ >>> G3_6_list = atlas[4:209]
180
+
181
+ More generally, the indices that partition the atlas by the number of nodes
182
+ per graph:
183
+
184
+ >>> import itertools
185
+ >>> partition_indices = [0] + list(
186
+ ... itertools.accumulate(Counter(num_nodes_per_graph).values()) # cumsum
187
+ ... )
188
+ >>> partition_indices
189
+ [0, 1, 2, 4, 8, 19, 53, 209, 1253]
190
+ >>> partition_mapping = dict(enumerate(itertools.pairwise(partition_indices)))
191
+ >>> pprint(partition_mapping)
192
+ {0: (0, 1),
193
+ 1: (1, 2),
194
+ 2: (2, 4),
195
+ 3: (4, 8),
196
+ 4: (8, 19),
197
+ 5: (19, 53),
198
+ 6: (53, 209),
199
+ 7: (209, 1253)}
200
+
201
+ See also
202
+ --------
203
+ graph_atlas
204
+
205
+ Notes
206
+ -----
207
+ This function may be expensive in both time and space, since it
208
+ reads a large file sequentially in order to populate the list.
209
+
210
+ Although the NetworkX atlas functions match the order of graphs
211
+ given in the "Atlas of Graphs" book, there are (at least) three
212
+ errors in the ordering described in the book. The following three
213
+ pairs of nodes violate the lexicographically nondecreasing sorted
214
+ degree sequence rule:
215
+
216
+ - graphs 55 and 56 with degree sequences 001111 and 000112,
217
+ - graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
218
+ - graphs 1012 and 1013 with degree sequences 1244555 and 1244456.
219
+
220
+ References
221
+ ----------
222
+ .. [atlas] Ronald C. Read and Robin J. Wilson,
223
+ *An Atlas of Graphs*.
224
+ Oxford University Press, 1998.
225
+
226
+ """
227
+ return list(_generate_graphs())
venv/lib/python3.14/site-packages/networkx/generators/classic.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for some classic graphs.
2
+
3
+ The typical graph builder function is called as follows:
4
+
5
+ >>> G = nx.complete_graph(100)
6
+
7
+ returning the complete graph on n nodes labeled 0, .., 99
8
+ as a simple graph. Except for `empty_graph`, all the functions
9
+ in this module return a Graph class (i.e. a simple, undirected graph).
10
+
11
+ """
12
+
13
+ import itertools
14
+ import numbers
15
+
16
+ import networkx as nx
17
+ from networkx.classes import Graph
18
+ from networkx.utils import nodes_or_number, pairwise
19
+
20
+ __all__ = [
21
+ "balanced_tree",
22
+ "barbell_graph",
23
+ "binomial_tree",
24
+ "complete_graph",
25
+ "complete_multipartite_graph",
26
+ "circular_ladder_graph",
27
+ "circulant_graph",
28
+ "cycle_graph",
29
+ "dorogovtsev_goltsev_mendes_graph",
30
+ "empty_graph",
31
+ "full_rary_tree",
32
+ "kneser_graph",
33
+ "ladder_graph",
34
+ "lollipop_graph",
35
+ "null_graph",
36
+ "path_graph",
37
+ "star_graph",
38
+ "tadpole_graph",
39
+ "trivial_graph",
40
+ "turan_graph",
41
+ "wheel_graph",
42
+ ]
43
+
44
+
45
+ # -------------------------------------------------------------------
46
+ # Some Classic Graphs
47
+ # -------------------------------------------------------------------
48
+
49
+
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def full_rary_tree(r, n, create_using=None):
52
+ """Creates a full r-ary tree of `n` nodes.
53
+
54
+ Sometimes called a k-ary, n-ary, or m-ary tree.
55
+ "... all non-leaf nodes have exactly r children and all levels
56
+ are full except for some rightmost position of the bottom level
57
+ (if a leaf at the bottom level is missing, then so are all of the
58
+ leaves to its right." [1]_
59
+
60
+ .. plot::
61
+
62
+ >>> nx.draw(nx.full_rary_tree(2, 10))
63
+
64
+ Parameters
65
+ ----------
66
+ r : int
67
+ branching factor of the tree
68
+ n : int
69
+ Number of nodes in the tree
70
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
71
+ Graph type to create. If graph instance, then cleared before populated.
72
+
73
+ Returns
74
+ -------
75
+ G : networkx Graph
76
+ An r-ary tree with n nodes
77
+
78
+ References
79
+ ----------
80
+ .. [1] An introduction to data structures and algorithms,
81
+ James Andrew Storer, Birkhauser Boston 2001, (page 225).
82
+ """
83
+ G = empty_graph(n, create_using)
84
+ if r > 0:
85
+ # Nodes are labeled in breadth-first order from the root, so the parent
86
+ # of node `child` is simply ``(child - 1) // r``.
87
+ G.add_edges_from(((child - 1) // r, child) for child in range(1, n))
88
+ return G
89
+
90
+
91
+ @nx._dispatchable(graphs=None, returns_graph=True)
92
+ def kneser_graph(n, k):
93
+ """Returns the Kneser Graph with parameters `n` and `k`.
94
+
95
+ The Kneser Graph has nodes that are k-tuples (subsets) of the integers
96
+ between 0 and ``n-1``. Nodes are adjacent if their corresponding sets are disjoint.
97
+
98
+ Parameters
99
+ ----------
100
+ n: int
101
+ Number of integers from which to make node subsets.
102
+ Subsets are drawn from ``set(range(n))``.
103
+ k: int
104
+ Size of the subsets.
105
+
106
+ Returns
107
+ -------
108
+ G : NetworkX Graph
109
+
110
+ Examples
111
+ --------
112
+ >>> G = nx.kneser_graph(5, 2)
113
+ >>> G.number_of_nodes()
114
+ 10
115
+ >>> G.number_of_edges()
116
+ 15
117
+ >>> nx.is_isomorphic(G, nx.petersen_graph())
118
+ True
119
+ """
120
+ if n <= 0:
121
+ raise nx.NetworkXError("n should be greater than zero")
122
+ if k <= 0 or k > n:
123
+ raise nx.NetworkXError("k should be greater than zero and smaller than n")
124
+
125
+ G = nx.Graph()
126
+ # Create all k-subsets of [0, 1, ..., n-1]
127
+ subsets = list(itertools.combinations(range(n), k))
128
+
129
+ if 2 * k > n:
130
+ G.add_nodes_from(subsets)
131
+
132
+ universe = set(range(n))
133
+ comb = itertools.combinations # only to make it all fit on one line
134
+ G.add_edges_from((s, t) for s in subsets for t in comb(universe - set(s), k))
135
+ return G
136
+
137
+
138
+ @nx._dispatchable(graphs=None, returns_graph=True)
139
+ def balanced_tree(r, h, create_using=None):
140
+ """Returns the perfectly balanced `r`-ary tree of height `h`.
141
+
142
+ .. plot::
143
+
144
+ >>> nx.draw(nx.balanced_tree(2, 3))
145
+
146
+ Parameters
147
+ ----------
148
+ r : int
149
+ Branching factor of the tree; each node will have `r`
150
+ children.
151
+
152
+ h : int
153
+ Height of the tree.
154
+
155
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
156
+ Graph type to create. If graph instance, then cleared before populated.
157
+
158
+ Returns
159
+ -------
160
+ G : NetworkX graph
161
+ A balanced `r`-ary tree of height `h`.
162
+
163
+ Notes
164
+ -----
165
+ This is the rooted tree where all leaves are at distance `h` from
166
+ the root. The root has degree `r` and all other internal nodes
167
+ have degree `r + 1`.
168
+
169
+ Node labels are integers, starting from zero.
170
+
171
+ A balanced tree is also known as a *complete r-ary tree*.
172
+
173
+ """
174
+ # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
175
+ # which is computed by using the closed-form formula for a geometric
176
+ # sum with ratio `r`. In the special case that `r` is 1, the number
177
+ # of nodes is simply `h + 1` (since the tree is actually a path
178
+ # graph).
179
+ if r == 1:
180
+ n = h + 1
181
+ else:
182
+ # This must be an integer if both `r` and `h` are integers. If
183
+ # they are not, we force integer division anyway.
184
+ n = (1 - r ** (h + 1)) // (1 - r)
185
+ return full_rary_tree(r, n, create_using=create_using)
186
+
187
+
188
+ @nx._dispatchable(graphs=None, returns_graph=True)
189
+ def barbell_graph(m1, m2, create_using=None):
190
+ """Returns the Barbell Graph: two complete graphs connected by a path.
191
+
192
+ .. plot::
193
+
194
+ >>> nx.draw(nx.barbell_graph(4, 2))
195
+
196
+ Parameters
197
+ ----------
198
+ m1 : int
199
+ Size of the left and right barbells, must be greater than 2.
200
+
201
+ m2 : int
202
+ Length of the path connecting the barbells.
203
+
204
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
205
+ Graph type to create. If graph instance, then cleared before populated.
206
+ Only undirected Graphs are supported.
207
+
208
+ Returns
209
+ -------
210
+ G : NetworkX graph
211
+ A barbell graph.
212
+
213
+ Notes
214
+ -----
215
+
216
+
217
+ Two identical complete graphs $K_{m1}$ form the left and right bells,
218
+ and are connected by a path $P_{m2}$.
219
+
220
+ The `2*m1+m2` nodes are numbered
221
+ `0, ..., m1-1` for the left barbell,
222
+ `m1, ..., m1+m2-1` for the path,
223
+ and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
224
+
225
+ The 3 subgraphs are joined via the edges `(m1-1, m1)` and
226
+ `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
227
+ graphs joined together.
228
+
229
+ This graph is an extremal example in David Aldous
230
+ and Jim Fill's e-text on Random Walks on Graphs.
231
+
232
+ """
233
+ if m1 < 2:
234
+ raise nx.NetworkXError("Invalid graph description, m1 should be >=2")
235
+ if m2 < 0:
236
+ raise nx.NetworkXError("Invalid graph description, m2 should be >=0")
237
+
238
+ # left barbell
239
+ G = complete_graph(m1, create_using)
240
+ if G.is_directed():
241
+ raise nx.NetworkXError("Directed Graph not supported")
242
+
243
+ # connecting path
244
+ G.add_nodes_from(range(m1, m1 + m2 - 1))
245
+ if m2 > 1:
246
+ G.add_edges_from(pairwise(range(m1, m1 + m2)))
247
+
248
+ # right barbell
249
+ G.add_edges_from(
250
+ (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
251
+ )
252
+
253
+ # connect it up
254
+ G.add_edge(m1 - 1, m1)
255
+ if m2 > 0:
256
+ G.add_edge(m1 + m2 - 1, m1 + m2)
257
+
258
+ return G
259
+
260
+
261
+ @nx._dispatchable(graphs=None, returns_graph=True)
262
+ def binomial_tree(n, create_using=None):
263
+ """Returns the Binomial Tree of order n.
264
+
265
+ The binomial tree of order 0 consists of a single node. A binomial tree of order k
266
+ is defined recursively by linking two binomial trees of order k-1: the root of one is
267
+ the leftmost child of the root of the other.
268
+
269
+ .. plot::
270
+
271
+ >>> nx.draw(nx.binomial_tree(3))
272
+
273
+ Parameters
274
+ ----------
275
+ n : int
276
+ Order of the binomial tree.
277
+
278
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
279
+ Graph type to create. If graph instance, then cleared before populated.
280
+
281
+ Returns
282
+ -------
283
+ G : NetworkX graph
284
+ A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
285
+
286
+ """
287
+ G = nx.empty_graph(1, create_using)
288
+
289
+ N = 1
290
+ for i in range(n):
291
+ # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
292
+ edges = [(u + N, v + N) for (u, v) in G.edges()]
293
+ G.add_edges_from(edges)
294
+ G.add_edge(0, N)
295
+ N *= 2
296
+ return G
297
+
298
+
299
+ @nx._dispatchable(graphs=None, returns_graph=True)
300
+ @nodes_or_number(0)
301
+ def complete_graph(n, create_using=None):
302
+ """Return the complete graph `K_n` with n nodes.
303
+
304
+ A complete graph on `n` nodes means that all pairs
305
+ of distinct nodes have an edge connecting them.
306
+
307
+ .. plot::
308
+
309
+ >>> nx.draw(nx.complete_graph(5))
310
+
311
+ Parameters
312
+ ----------
313
+ n : int or iterable container of nodes
314
+ If n is an integer, nodes are from range(n).
315
+ If n is a container of nodes, those nodes appear in the graph.
316
+ Warning: n is not checked for duplicates and if present the
317
+ resulting graph may not be as desired. Make sure you have no duplicates.
318
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
319
+ Graph type to create. If graph instance, then cleared before populated.
320
+
321
+ Examples
322
+ --------
323
+ >>> G = nx.complete_graph(9)
324
+ >>> len(G)
325
+ 9
326
+ >>> G.size()
327
+ 36
328
+ >>> G = nx.complete_graph(range(11, 14))
329
+ >>> list(G.nodes())
330
+ [11, 12, 13]
331
+ >>> G = nx.complete_graph(4, nx.DiGraph())
332
+ >>> G.is_directed()
333
+ True
334
+
335
+ """
336
+ _, nodes = n
337
+ G = empty_graph(nodes, create_using)
338
+ if len(nodes) > 1:
339
+ if G.is_directed():
340
+ edges = itertools.permutations(nodes, 2)
341
+ else:
342
+ edges = itertools.combinations(nodes, 2)
343
+ G.add_edges_from(edges)
344
+ return G
345
+
346
+
347
+ @nx._dispatchable(graphs=None, returns_graph=True)
348
+ def circular_ladder_graph(n, create_using=None):
349
+ """Returns the circular ladder graph $CL_n$ of length n.
350
+
351
+ $CL_n$ consists of two concentric n-cycles in which
352
+ each of the n pairs of concentric nodes are joined by an edge.
353
+
354
+ Node labels are the integers 0 to n-1
355
+
356
+ .. plot::
357
+
358
+ >>> nx.draw(nx.circular_ladder_graph(5))
359
+
360
+ Parameters
361
+ ----------
362
+ n : int
363
+ The length of the ladder. Must be at least 2.
364
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
365
+ Graph type to create. If graph instance, then cleared before populated.
366
+
367
+ Returns
368
+ -------
369
+ G : Graph
370
+ A circular ladder graph.
371
+
372
+ Raises
373
+ ------
374
+ ValueError
375
+ If `n` is less than 2.
376
+ NetworkXError
377
+ If `create_using` is a directed graph.
378
+
379
+ """
380
+ if n < 2:
381
+ raise ValueError("n must be at least 2 for circular_ladder_graph")
382
+ G = ladder_graph(n, create_using)
383
+ G.add_edge(0, n - 1)
384
+ G.add_edge(n, 2 * n - 1)
385
+ return G
386
+
387
+
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def circulant_graph(n, offsets, create_using=None):
390
+ r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
391
+
392
+ The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
393
+ such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
394
+ for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
395
+
396
+ .. plot::
397
+
398
+ >>> nx.draw(nx.circulant_graph(10, [1]))
399
+
400
+ Parameters
401
+ ----------
402
+ n : integer
403
+ The number of nodes in the graph.
404
+ offsets : list of integers
405
+ A list of node offsets, $x_1$ up to $x_m$, as described above.
406
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
407
+ Graph type to create. If graph instance, then cleared before populated.
408
+
409
+ Returns
410
+ -------
411
+ NetworkX Graph of type create_using
412
+
413
+ Examples
414
+ --------
415
+ Many well-known graph families are subfamilies of the circulant graphs;
416
+ for example, to create the cycle graph on n points, we connect every
417
+ node to nodes on either side (with offset plus or minus one). For n = 10,
418
+
419
+ >>> G = nx.circulant_graph(10, [1])
420
+ >>> edges = [
421
+ ... (0, 9),
422
+ ... (0, 1),
423
+ ... (1, 2),
424
+ ... (2, 3),
425
+ ... (3, 4),
426
+ ... (4, 5),
427
+ ... (5, 6),
428
+ ... (6, 7),
429
+ ... (7, 8),
430
+ ... (8, 9),
431
+ ... ]
432
+ >>> sorted(edges) == sorted(G.edges())
433
+ True
434
+
435
+ Similarly, we can create the complete graph
436
+ on 5 points with the set of offsets [1, 2]:
437
+
438
+ >>> G = nx.circulant_graph(5, [1, 2])
439
+ >>> edges = [
440
+ ... (0, 1),
441
+ ... (0, 2),
442
+ ... (0, 3),
443
+ ... (0, 4),
444
+ ... (1, 2),
445
+ ... (1, 3),
446
+ ... (1, 4),
447
+ ... (2, 3),
448
+ ... (2, 4),
449
+ ... (3, 4),
450
+ ... ]
451
+ >>> sorted(edges) == sorted(G.edges())
452
+ True
453
+
454
+ """
455
+ G = empty_graph(n, create_using)
456
+ G.add_edges_from((i, (i - j) % n) for i in range(n) for j in offsets)
457
+ G.add_edges_from((i, (i + j) % n) for i in range(n) for j in offsets)
458
+ return G
459
+
460
+
461
+ @nx._dispatchable(graphs=None, returns_graph=True)
462
+ @nodes_or_number(0)
463
+ def cycle_graph(n, create_using=None):
464
+ """Returns the cycle graph $C_n$ of cyclically connected nodes.
465
+
466
+ $C_n$ is a path with its two end-nodes connected.
467
+
468
+ .. plot::
469
+
470
+ >>> nx.draw(nx.cycle_graph(5))
471
+
472
+ Parameters
473
+ ----------
474
+ n : int or iterable container of nodes
475
+ If n is an integer, nodes are from `range(n)`.
476
+ If n is a container of nodes, those nodes appear in the graph.
477
+ Warning: n is not checked for duplicates and if present the
478
+ resulting graph may not be as desired. Make sure you have no duplicates.
479
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
480
+ Graph type to create. If graph instance, then cleared before populated.
481
+
482
+ Notes
483
+ -----
484
+ If create_using is directed, the direction is in increasing order.
485
+
486
+ """
487
+ _, nodes = n
488
+ G = empty_graph(nodes, create_using)
489
+ G.add_edges_from(pairwise(nodes, cyclic=True))
490
+ return G
491
+
492
+
493
+ @nx._dispatchable(graphs=None, returns_graph=True)
494
+ def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
495
+ """Returns the hierarchically constructed Dorogovtsev--Goltsev--Mendes graph.
496
+
497
+ The Dorogovtsev--Goltsev--Mendes [1]_ procedure deterministically produces a
498
+ scale-free graph with ``3/2 * (3**(n-1) + 1)`` nodes
499
+ and ``3**n`` edges for a given `n`.
500
+
501
+ Note that `n` denotes the number of times the state transition is applied,
502
+ starting from the base graph with ``n = 0`` (no transitions), as in [2]_.
503
+ This is different from the parameter ``t = n - 1`` in [1]_.
504
+
505
+ .. plot::
506
+
507
+ >>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
508
+
509
+ Parameters
510
+ ----------
511
+ n : integer
512
+ The generation number.
513
+
514
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
515
+ Graph type to create. Directed graphs and multigraphs are not supported.
516
+
517
+ Returns
518
+ -------
519
+ G : NetworkX `Graph`
520
+
521
+ Raises
522
+ ------
523
+ NetworkXError
524
+ If `n` is less than zero.
525
+
526
+ If `create_using` is a directed graph or multigraph.
527
+
528
+ Examples
529
+ --------
530
+ >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
531
+ >>> G.number_of_nodes()
532
+ 15
533
+ >>> G.number_of_edges()
534
+ 27
535
+ >>> nx.is_planar(G)
536
+ True
537
+
538
+ References
539
+ ----------
540
+ .. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
541
+ "Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
542
+ https://arxiv.org/pdf/cond-mat/0112143.pdf
543
+ .. [2] Weisstein, Eric W. "Dorogovtsev--Goltsev--Mendes Graph".
544
+ From MathWorld--A Wolfram Web Resource.
545
+ https://mathworld.wolfram.com/Dorogovtsev-Goltsev-MendesGraph.html
546
+ """
547
+ if n < 0:
548
+ raise nx.NetworkXError("n must be greater than or equal to 0")
549
+
550
+ G = empty_graph(0, create_using)
551
+ if G.is_directed():
552
+ raise nx.NetworkXError("directed graph not supported")
553
+ if G.is_multigraph():
554
+ raise nx.NetworkXError("multigraph not supported")
555
+
556
+ G.add_edge(0, 1)
557
+ new_node = 2 # next node to be added
558
+ for _ in range(n): # iterate over number of generations.
559
+ new_edges = []
560
+ for u, v in G.edges():
561
+ new_edges.append((u, new_node))
562
+ new_edges.append((v, new_node))
563
+ new_node += 1
564
+
565
+ G.add_edges_from(new_edges)
566
+ return G
567
+
568
+
569
+ @nx._dispatchable(graphs=None, returns_graph=True)
570
+ @nodes_or_number(0)
571
+ def empty_graph(n=0, create_using=None, default=Graph):
572
+ """Returns the empty graph with n nodes and zero edges.
573
+
574
+ .. plot::
575
+
576
+ >>> nx.draw(nx.empty_graph(5))
577
+
578
+ Parameters
579
+ ----------
580
+ n : int or iterable container of nodes (default = 0)
581
+ If n is an integer, nodes are from `range(n)`.
582
+ If n is a container of nodes, those nodes appear in the graph.
583
+ create_using : Graph Instance, Constructor or None
584
+ Indicator of type of graph to return.
585
+ If a Graph-type instance, then clear and use it.
586
+ If None, use the `default` constructor.
587
+ If a constructor, call it to create an empty graph.
588
+ default : Graph constructor (optional, default = nx.Graph)
589
+ The constructor to use if create_using is None.
590
+ If None, then nx.Graph is used.
591
+ This is used when passing an unknown `create_using` value
592
+ through your home-grown function to `empty_graph` and
593
+ you want a default constructor other than nx.Graph.
594
+
595
+ Examples
596
+ --------
597
+ >>> G = nx.empty_graph(10)
598
+ >>> G.number_of_nodes()
599
+ 10
600
+ >>> G.number_of_edges()
601
+ 0
602
+ >>> G = nx.empty_graph("ABC")
603
+ >>> G.number_of_nodes()
604
+ 3
605
+ >>> sorted(G)
606
+ ['A', 'B', 'C']
607
+
608
+ Notes
609
+ -----
610
+ The variable create_using should be a Graph Constructor or a
611
+ "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
612
+ will be used to create the returned graph. "graph"-like objects
613
+ will be cleared (nodes and edges will be removed) and refitted as
614
+ an empty "graph" with nodes specified in n. This capability
615
+ is useful for specifying the class-nature of the resulting empty
616
+ "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
617
+
618
+ The variable create_using has three main uses:
619
+ Firstly, the variable create_using can be used to create an
620
+ empty digraph, multigraph, etc. For example,
621
+
622
+ >>> n = 10
623
+ >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
624
+
625
+ will create an empty digraph on n nodes.
626
+
627
+ Secondly, one can pass an existing graph (digraph, multigraph,
628
+ etc.) via create_using. For example, if G is an existing graph
629
+ (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
630
+ will empty G (i.e. delete all nodes and edges using G.clear())
631
+ and then add n nodes and zero edges, and return the modified graph.
632
+
633
+ Thirdly, when constructing your home-grown graph creation function
634
+ you can use empty_graph to construct the graph by passing a user
635
+ defined create_using to empty_graph. In this case, if you want the
636
+ default constructor to be other than nx.Graph, specify `default`.
637
+
638
+ >>> def mygraph(n, create_using=None):
639
+ ... G = nx.empty_graph(n, create_using, nx.MultiGraph)
640
+ ... G.add_edges_from([(0, 1), (0, 1)])
641
+ ... return G
642
+ >>> G = mygraph(3)
643
+ >>> G.is_multigraph()
644
+ True
645
+ >>> G = mygraph(3, nx.Graph)
646
+ >>> G.is_multigraph()
647
+ False
648
+
649
+ See also create_empty_copy(G).
650
+
651
+ """
652
+ if create_using is None:
653
+ G = default()
654
+ elif isinstance(create_using, type):
655
+ G = create_using()
656
+ elif not hasattr(create_using, "adj"):
657
+ raise TypeError("create_using is not a valid NetworkX graph type or instance")
658
+ else:
659
+ # create_using is a NetworkX style Graph
660
+ create_using.clear()
661
+ G = create_using
662
+
663
+ _, nodes = n
664
+ G.add_nodes_from(nodes)
665
+ return G
666
+
667
+
668
+ @nx._dispatchable(graphs=None, returns_graph=True)
669
+ def ladder_graph(n, create_using=None):
670
+ """Returns the Ladder graph of length n.
671
+
672
+ This is two paths of n nodes, with
673
+ each pair connected by a single edge.
674
+
675
+ Node labels are the integers 0 to 2*n - 1.
676
+
677
+ .. plot::
678
+
679
+ >>> nx.draw(nx.ladder_graph(5))
680
+
681
+ """
682
+ G = empty_graph(2 * n, create_using)
683
+ if G.is_directed():
684
+ raise nx.NetworkXError("Directed Graph not supported")
685
+ G.add_edges_from(pairwise(range(n)))
686
+ G.add_edges_from(pairwise(range(n, 2 * n)))
687
+ G.add_edges_from((v, v + n) for v in range(n))
688
+ return G
689
+
690
+
691
+ @nx._dispatchable(graphs=None, returns_graph=True)
692
+ @nodes_or_number([0, 1])
693
+ def lollipop_graph(m, n, create_using=None):
694
+ """Returns the Lollipop Graph; ``K_m`` connected to ``P_n``.
695
+
696
+ This is the Barbell Graph without the right barbell.
697
+
698
+ .. plot::
699
+
700
+ >>> nx.draw(nx.lollipop_graph(3, 4))
701
+
702
+ Parameters
703
+ ----------
704
+ m, n : int or iterable container of nodes
705
+ If an integer, nodes are from ``range(m)`` and ``range(m, m+n)``.
706
+ If a container of nodes, those nodes appear in the graph.
707
+ Warning: `m` and `n` are not checked for duplicates and if present the
708
+ resulting graph may not be as desired. Make sure you have no duplicates.
709
+
710
+ The nodes for `m` appear in the complete graph $K_m$ and the nodes
711
+ for `n` appear in the path $P_n$
712
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
713
+ Graph type to create. If graph instance, then cleared before populated.
714
+
715
+ Returns
716
+ -------
717
+ Networkx graph
718
+ A complete graph with `m` nodes connected to a path of length `n`.
719
+
720
+ Notes
721
+ -----
722
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
723
+ If ``n=0``, this is merely a complete graph.
724
+
725
+ (This graph is an extremal example in David Aldous and Jim
726
+ Fill's etext on Random Walks on Graphs.)
727
+
728
+ """
729
+ m, m_nodes = m
730
+ M = len(m_nodes)
731
+ if M < 2:
732
+ raise nx.NetworkXError(
733
+ "Invalid description: m should indicate at least 2 nodes"
734
+ )
735
+
736
+ n, n_nodes = n
737
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
738
+ n_nodes = list(range(M, M + n))
739
+ N = len(n_nodes)
740
+
741
+ # the ball
742
+ G = complete_graph(m_nodes, create_using)
743
+ if G.is_directed():
744
+ raise nx.NetworkXError("Directed Graph not supported")
745
+
746
+ # the stick
747
+ G.add_nodes_from(n_nodes)
748
+ if N > 1:
749
+ G.add_edges_from(pairwise(n_nodes))
750
+
751
+ if len(G) != M + N:
752
+ raise nx.NetworkXError("Nodes must be distinct in containers m and n")
753
+
754
+ # connect ball to stick
755
+ if M > 0 and N > 0:
756
+ G.add_edge(m_nodes[-1], n_nodes[0])
757
+ return G
758
+
759
+
760
+ @nx._dispatchable(graphs=None, returns_graph=True)
761
+ def null_graph(create_using=None):
762
+ """Returns the Null graph with no nodes or edges.
763
+
764
+ See empty_graph for the use of create_using.
765
+
766
+ """
767
+ G = empty_graph(0, create_using)
768
+ return G
769
+
770
+
771
+ @nx._dispatchable(graphs=None, returns_graph=True)
772
+ @nodes_or_number(0)
773
+ def path_graph(n, create_using=None):
774
+ """Returns the Path graph `P_n` of linearly connected nodes.
775
+
776
+ .. plot::
777
+
778
+ >>> nx.draw(nx.path_graph(5))
779
+
780
+ Parameters
781
+ ----------
782
+ n : int or iterable
783
+ If an integer, nodes are 0 to n - 1.
784
+ If an iterable of nodes, in the order they appear in the path.
785
+ Warning: n is not checked for duplicates and if present the
786
+ resulting graph may not be as desired. Make sure you have no duplicates.
787
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
788
+ Graph type to create. If graph instance, then cleared before populated.
789
+
790
+ """
791
+ _, nodes = n
792
+ G = empty_graph(nodes, create_using)
793
+ G.add_edges_from(pairwise(nodes))
794
+ return G
795
+
796
+
797
+ @nx._dispatchable(graphs=None, returns_graph=True)
798
+ @nodes_or_number(0)
799
+ def star_graph(n, create_using=None):
800
+ """Return a star graph.
801
+
802
+ The star graph consists of one center node connected to `n` outer nodes.
803
+
804
+ .. plot::
805
+
806
+ >>> nx.draw(nx.star_graph(6))
807
+
808
+ Parameters
809
+ ----------
810
+ n : int or iterable
811
+ If an integer, node labels are ``0`` to `n`, with center ``0``.
812
+ If an iterable of nodes, the center is the first.
813
+ Warning: `n` is not checked for duplicates and if present, the
814
+ resulting graph may not be as desired. Make sure you have no duplicates.
815
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
816
+ Graph type to create. If graph instance, then cleared before populated.
817
+
818
+ Examples
819
+ --------
820
+ A star graph with 3 spokes can be generated with
821
+
822
+ >>> G = nx.star_graph(3)
823
+ >>> sorted(G.edges)
824
+ [(0, 1), (0, 2), (0, 3)]
825
+
826
+ For directed graphs, the convention is to have edges pointing from the hub
827
+ to the spokes:
828
+
829
+ >>> DG1 = nx.star_graph(3, create_using=nx.DiGraph)
830
+ >>> sorted(DG1.edges)
831
+ [(0, 1), (0, 2), (0, 3)]
832
+
833
+ Other possible definitions have edges pointing from the spokes to the hub:
834
+
835
+ >>> DG2 = nx.star_graph(3, create_using=nx.DiGraph).reverse()
836
+ >>> sorted(DG2.edges)
837
+ [(1, 0), (2, 0), (3, 0)]
838
+
839
+ or have bidirectional edges:
840
+
841
+ >>> DG3 = nx.star_graph(3).to_directed()
842
+ >>> sorted(DG3.edges)
843
+ [(0, 1), (0, 2), (0, 3), (1, 0), (2, 0), (3, 0)]
844
+
845
+ Notes
846
+ -----
847
+ The graph has ``n + 1`` nodes for integer `n`.
848
+ So ``star_graph(3)`` is the same as ``star_graph(range(4))``.
849
+ """
850
+ n, nodes = n
851
+ if isinstance(n, numbers.Integral):
852
+ nodes.append(int(n)) # There should be n + 1 nodes.
853
+ G = empty_graph(nodes, create_using)
854
+
855
+ if len(nodes) > 1:
856
+ hub, *spokes = nodes
857
+ G.add_edges_from((hub, node) for node in spokes)
858
+ return G
859
+
860
+
861
+ @nx._dispatchable(graphs=None, returns_graph=True)
862
+ @nodes_or_number([0, 1])
863
+ def tadpole_graph(m, n, create_using=None):
864
+ """Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``.
865
+
866
+ This graph on m+n nodes connects a cycle of size `m` to a path of length `n`.
867
+ It looks like a tadpole. It is also called a kite graph or a dragon graph.
868
+
869
+ .. plot::
870
+
871
+ >>> nx.draw(nx.tadpole_graph(3, 5))
872
+
873
+ Parameters
874
+ ----------
875
+ m, n : int or iterable container of nodes
876
+ If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``.
877
+ If a container of nodes, those nodes appear in the graph.
878
+ Warning: `m` and `n` are not checked for duplicates and if present the
879
+ resulting graph may not be as desired.
880
+
881
+ The nodes for `m` appear in the cycle graph $C_m$ and the nodes
882
+ for `n` appear in the path $P_n$.
883
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
884
+ Graph type to create. If graph instance, then cleared before populated.
885
+
886
+ Returns
887
+ -------
888
+ Networkx graph
889
+ A cycle of size `m` connected to a path of length `n`.
890
+
891
+ Raises
892
+ ------
893
+ NetworkXError
894
+ If ``m < 2``. The tadpole graph is undefined for ``m<2``.
895
+
896
+ Notes
897
+ -----
898
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
899
+ If ``n=0``, this is a cycle graph.
900
+ `m` and/or `n` can be a container of nodes instead of an integer.
901
+
902
+ """
903
+ m, m_nodes = m
904
+ M = len(m_nodes)
905
+ if M < 2:
906
+ raise nx.NetworkXError(
907
+ "Invalid description: m should indicate at least 2 nodes"
908
+ )
909
+
910
+ n, n_nodes = n
911
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
912
+ n_nodes = list(range(M, M + n))
913
+
914
+ # the circle
915
+ G = cycle_graph(m_nodes, create_using)
916
+ if G.is_directed():
917
+ raise nx.NetworkXError("Directed Graph not supported")
918
+
919
+ # the stick
920
+ nx.add_path(G, [m_nodes[-1]] + list(n_nodes))
921
+
922
+ return G
923
+
924
+
925
+ @nx._dispatchable(graphs=None, returns_graph=True)
926
+ def trivial_graph(create_using=None):
927
+ """Return the Trivial graph with one node (with label 0) and no edges.
928
+
929
+ .. plot::
930
+
931
+ >>> nx.draw(nx.trivial_graph(), with_labels=True)
932
+
933
+ """
934
+ G = empty_graph(1, create_using)
935
+ return G
936
+
937
+
938
+ @nx._dispatchable(graphs=None, returns_graph=True)
939
+ def turan_graph(n, r):
940
+ r"""Return the Turan Graph
941
+
942
+ The Turan Graph is a complete multipartite graph on $n$ nodes
943
+ with $r$ disjoint subsets. That is, edges connect each node to
944
+ every node not in its subset.
945
+
946
+ Given $n$ and $r$, we create a complete multipartite graph with
947
+ $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
948
+ $n \mod r$ partitions of size $n/r+1$, rounded down.
949
+
950
+ .. plot::
951
+
952
+ >>> nx.draw(nx.turan_graph(6, 2))
953
+
954
+ Parameters
955
+ ----------
956
+ n : int
957
+ The number of nodes.
958
+ r : int
959
+ The number of partitions.
960
+ Must be less than or equal to n.
961
+
962
+ Notes
963
+ -----
964
+ Must satisfy $1 <= r <= n$.
965
+ The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
966
+ """
967
+
968
+ if not 1 <= r <= n:
969
+ raise nx.NetworkXError("Must satisfy 1 <= r <= n")
970
+
971
+ partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
972
+ G = complete_multipartite_graph(*partitions)
973
+ return G
974
+
975
+
976
+ @nx._dispatchable(graphs=None, returns_graph=True)
977
+ @nodes_or_number(0)
978
+ def wheel_graph(n, create_using=None):
979
+ """Return the wheel graph
980
+
981
+ The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
982
+
983
+ .. plot::
984
+
985
+ >>> nx.draw(nx.wheel_graph(5))
986
+
987
+ Parameters
988
+ ----------
989
+ n : int or iterable
990
+ If an integer, node labels are 0 to n with center 0.
991
+ If an iterable of nodes, the center is the first.
992
+ Warning: n is not checked for duplicates and if present the
993
+ resulting graph may not be as desired. Make sure you have no duplicates.
994
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
995
+ Graph type to create. If graph instance, then cleared before populated.
996
+
997
+ Node labels are the integers 0 to n - 1.
998
+ """
999
+ _, nodes = n
1000
+ G = empty_graph(nodes, create_using)
1001
+ if G.is_directed():
1002
+ raise nx.NetworkXError("Directed Graph not supported")
1003
+
1004
+ if len(nodes) > 1:
1005
+ hub, *rim = nodes
1006
+ G.add_edges_from((hub, node) for node in rim)
1007
+ if len(rim) > 1:
1008
+ G.add_edges_from(pairwise(rim, cyclic=True))
1009
+ return G
1010
+
1011
+
1012
+ @nx._dispatchable(graphs=None, returns_graph=True)
1013
+ def complete_multipartite_graph(*subset_sizes):
1014
+ """Returns the complete multipartite graph with the specified subset sizes.
1015
+
1016
+ .. plot::
1017
+
1018
+ >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3))
1019
+
1020
+ Parameters
1021
+ ----------
1022
+ subset_sizes : tuple of integers or tuple of node iterables
1023
+ The arguments can either all be integer number of nodes or they
1024
+ can all be iterables of nodes. If integers, they represent the
1025
+ number of nodes in each subset of the multipartite graph.
1026
+ If iterables, each is used to create the nodes for that subset.
1027
+ The length of subset_sizes is the number of subsets.
1028
+
1029
+ Returns
1030
+ -------
1031
+ G : NetworkX Graph
1032
+ Returns the complete multipartite graph with the specified subsets.
1033
+
1034
+ For each node, the node attribute 'subset' is an integer
1035
+ indicating which subset contains the node.
1036
+
1037
+ Examples
1038
+ --------
1039
+ Creating a complete tripartite graph, with subsets of one, two, and three
1040
+ nodes, respectively.
1041
+
1042
+ >>> G = nx.complete_multipartite_graph(1, 2, 3)
1043
+ >>> [G.nodes[u]["subset"] for u in G]
1044
+ [0, 1, 1, 2, 2, 2]
1045
+ >>> list(G.edges(0))
1046
+ [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
1047
+ >>> list(G.edges(2))
1048
+ [(2, 0), (2, 3), (2, 4), (2, 5)]
1049
+ >>> list(G.edges(4))
1050
+ [(4, 0), (4, 1), (4, 2)]
1051
+
1052
+ >>> G = nx.complete_multipartite_graph("a", "bc", "def")
1053
+ >>> [G.nodes[u]["subset"] for u in sorted(G)]
1054
+ [0, 1, 1, 2, 2, 2]
1055
+
1056
+ Notes
1057
+ -----
1058
+ This function generalizes several other graph builder functions.
1059
+
1060
+ - If no subset sizes are given, this returns the null graph.
1061
+ - If a single subset size `n` is given, this returns the empty graph on
1062
+ `n` nodes.
1063
+ - If two subset sizes `m` and `n` are given, this returns the complete
1064
+ bipartite graph on `m + n` nodes.
1065
+ - If subset sizes `1` and `n` are given, this returns the star graph on
1066
+ `n + 1` nodes.
1067
+
1068
+ See also
1069
+ --------
1070
+ complete_bipartite_graph
1071
+ """
1072
+ # The complete multipartite graph is an undirected simple graph.
1073
+ G = Graph()
1074
+
1075
+ if len(subset_sizes) == 0:
1076
+ return G
1077
+
1078
+ # set up subsets of nodes
1079
+ try:
1080
+ extents = pairwise(itertools.accumulate((0,) + subset_sizes))
1081
+ subsets = [range(start, end) for start, end in extents]
1082
+ except TypeError:
1083
+ subsets = subset_sizes
1084
+ else:
1085
+ if any(size < 0 for size in subset_sizes):
1086
+ raise nx.NetworkXError(
1087
+ f"Negative number of nodes not valid: {subset_sizes}"
1088
+ )
1089
+
1090
+ # add nodes with subset attribute
1091
+ # while checking that ints are not mixed with iterables
1092
+ try:
1093
+ for i, subset in enumerate(subsets):
1094
+ G.add_nodes_from(subset, subset=i)
1095
+ except TypeError as err:
1096
+ raise nx.NetworkXError("Arguments must be all ints or all iterables") from err
1097
+
1098
+ # Across subsets, all nodes should be adjacent.
1099
+ # We can use itertools.combinations() because undirected.
1100
+ for subset1, subset2 in itertools.combinations(subsets, 2):
1101
+ G.add_edges_from(itertools.product(subset1, subset2))
1102
+ return G
venv/lib/python3.14/site-packages/networkx/generators/cographs.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Generators for cographs
2
+
3
+ A cograph is a graph containing no path on four vertices.
4
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
5
+ by disjoint union and complementation operations.
6
+
7
+ References
8
+ ----------
9
+ .. [0] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
10
+ "Complement reducible graphs",
11
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
12
+ ISSN 0166-218X.
13
+ """
14
+
15
+ import networkx as nx
16
+ from networkx.utils import py_random_state
17
+
18
+ __all__ = ["random_cograph"]
19
+
20
+
21
+ @py_random_state(1)
22
+ @nx._dispatchable(graphs=None, returns_graph=True)
23
+ def random_cograph(n, seed=None):
24
+ r"""Returns a random cograph with $2 ^ n$ nodes.
25
+
26
+ A cograph is a graph containing no path on four vertices.
27
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
28
+ by disjoint union and complementation operations.
29
+
30
+ This generator starts off from a single vertex and performs disjoint
31
+ union and full join operations on itself.
32
+ The decision on which operation will take place is random.
33
+
34
+ Parameters
35
+ ----------
36
+ n : int
37
+ The order of the cograph.
38
+ seed : integer, random_state, or None (default)
39
+ Indicator of random number generation state.
40
+ See :ref:`Randomness<randomness>`.
41
+
42
+ Returns
43
+ -------
44
+ G : A random graph containing no path on four vertices.
45
+
46
+ See Also
47
+ --------
48
+ full_join
49
+ union
50
+
51
+ References
52
+ ----------
53
+ .. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
54
+ "Complement reducible graphs",
55
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
56
+ ISSN 0166-218X.
57
+ """
58
+ R = nx.empty_graph(1)
59
+
60
+ for i in range(n):
61
+ RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
62
+
63
+ if seed.randint(0, 1) == 0:
64
+ R = nx.full_join(R, RR)
65
+ else:
66
+ R = nx.disjoint_union(R, RR)
67
+
68
+ return R
venv/lib/python3.14/site-packages/networkx/generators/community.py ADDED
@@ -0,0 +1,1067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for classes of graphs used in studying social networks."""
2
+
3
+ import itertools
4
+ import math
5
+
6
+ import networkx as nx
7
+ from networkx.utils import py_random_state
8
+
9
+ __all__ = [
10
+ "caveman_graph",
11
+ "connected_caveman_graph",
12
+ "relaxed_caveman_graph",
13
+ "random_partition_graph",
14
+ "planted_partition_graph",
15
+ "gaussian_random_partition_graph",
16
+ "ring_of_cliques",
17
+ "windmill_graph",
18
+ "stochastic_block_model",
19
+ "LFR_benchmark_graph",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(graphs=None, returns_graph=True)
24
+ def caveman_graph(l, k):
25
+ """Returns a caveman graph of `l` cliques of size `k`.
26
+
27
+ Parameters
28
+ ----------
29
+ l : int
30
+ Number of cliques
31
+ k : int
32
+ Size of cliques
33
+
34
+ Returns
35
+ -------
36
+ G : NetworkX Graph
37
+ caveman graph
38
+
39
+ Notes
40
+ -----
41
+ This returns an undirected graph, it can be converted to a directed
42
+ graph using :func:`nx.to_directed`, or a multigraph using
43
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
44
+ described in [1]_ and it is unclear which of the directed
45
+ generalizations is most useful.
46
+
47
+ Examples
48
+ --------
49
+ >>> G = nx.caveman_graph(3, 3)
50
+
51
+ See also
52
+ --------
53
+
54
+ connected_caveman_graph
55
+
56
+ References
57
+ ----------
58
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
59
+ Amer. J. Soc. 105, 493-527, 1999.
60
+ """
61
+ # l disjoint cliques of size k
62
+ G = nx.empty_graph(l * k)
63
+ if k > 1:
64
+ for start in range(0, l * k, k):
65
+ edges = itertools.combinations(range(start, start + k), 2)
66
+ G.add_edges_from(edges)
67
+ return G
68
+
69
+
70
+ @nx._dispatchable(graphs=None, returns_graph=True)
71
+ def connected_caveman_graph(l, k):
72
+ """Returns a connected caveman graph of `l` cliques of size `k`.
73
+
74
+ The connected caveman graph is formed by creating `n` cliques of size
75
+ `k`, then a single edge in each clique is rewired to a node in an
76
+ adjacent clique.
77
+
78
+ Parameters
79
+ ----------
80
+ l : int
81
+ number of cliques
82
+ k : int
83
+ size of cliques (k at least 2 or NetworkXError is raised)
84
+
85
+ Returns
86
+ -------
87
+ G : NetworkX Graph
88
+ connected caveman graph
89
+
90
+ Raises
91
+ ------
92
+ NetworkXError
93
+ If the size of cliques `k` is smaller than 2.
94
+
95
+ Notes
96
+ -----
97
+ This returns an undirected graph, it can be converted to a directed
98
+ graph using :func:`nx.to_directed`, or a multigraph using
99
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
100
+ described in [1]_ and it is unclear which of the directed
101
+ generalizations is most useful.
102
+
103
+ Examples
104
+ --------
105
+ >>> G = nx.connected_caveman_graph(3, 3)
106
+
107
+ References
108
+ ----------
109
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
110
+ Amer. J. Soc. 105, 493-527, 1999.
111
+ """
112
+ if k < 2:
113
+ raise nx.NetworkXError(
114
+ "The size of cliques in a connected caveman graph must be at least 2."
115
+ )
116
+
117
+ G = nx.caveman_graph(l, k)
118
+ for start in range(0, l * k, k):
119
+ G.remove_edge(start, start + 1)
120
+ G.add_edge(start, (start - 1) % (l * k))
121
+ return G
122
+
123
+
124
+ @py_random_state(3)
125
+ @nx._dispatchable(graphs=None, returns_graph=True)
126
+ def relaxed_caveman_graph(l, k, p, seed=None):
127
+ """Returns a relaxed caveman graph.
128
+
129
+ A relaxed caveman graph starts with `l` cliques of size `k`. Edges are
130
+ then randomly rewired with probability `p` to link different cliques.
131
+
132
+ Parameters
133
+ ----------
134
+ l : int
135
+ Number of groups
136
+ k : int
137
+ Size of cliques
138
+ p : float
139
+ Probability of rewiring each edge.
140
+ seed : integer, random_state, or None (default)
141
+ Indicator of random number generation state.
142
+ See :ref:`Randomness<randomness>`.
143
+
144
+ Returns
145
+ -------
146
+ G : NetworkX Graph
147
+ Relaxed Caveman Graph
148
+
149
+ Raises
150
+ ------
151
+ NetworkXError
152
+ If p is not in [0,1]
153
+
154
+ Examples
155
+ --------
156
+ >>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42)
157
+
158
+ References
159
+ ----------
160
+ .. [1] Santo Fortunato, Community Detection in Graphs,
161
+ Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174.
162
+ https://arxiv.org/abs/0906.0612
163
+ """
164
+ G = nx.caveman_graph(l, k)
165
+ nodes = list(G)
166
+ for u, v in G.edges():
167
+ if seed.random() < p: # rewire the edge
168
+ x = seed.choice(nodes)
169
+ if G.has_edge(u, x):
170
+ continue
171
+ G.remove_edge(u, v)
172
+ G.add_edge(u, x)
173
+ return G
174
+
175
+
176
+ @py_random_state(3)
177
+ @nx._dispatchable(graphs=None, returns_graph=True)
178
+ def random_partition_graph(sizes, p_in, p_out, seed=None, directed=False):
179
+ """Returns the random partition graph with a partition of sizes.
180
+
181
+ A partition graph is a graph of communities with sizes defined by
182
+ s in sizes. Nodes in the same group are connected with probability
183
+ p_in and nodes of different groups are connected with probability
184
+ p_out.
185
+
186
+ Parameters
187
+ ----------
188
+ sizes : list of ints
189
+ Sizes of groups
190
+ p_in : float
191
+ probability of edges with in groups
192
+ p_out : float
193
+ probability of edges between groups
194
+ directed : boolean optional, default=False
195
+ Whether to create a directed graph
196
+ seed : integer, random_state, or None (default)
197
+ Indicator of random number generation state.
198
+ See :ref:`Randomness<randomness>`.
199
+
200
+ Returns
201
+ -------
202
+ G : NetworkX Graph or DiGraph
203
+ random partition graph of size sum(gs)
204
+
205
+ Raises
206
+ ------
207
+ NetworkXError
208
+ If p_in or p_out is not in [0,1]
209
+
210
+ Examples
211
+ --------
212
+ >>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
213
+ >>> len(G)
214
+ 30
215
+ >>> partition = G.graph["partition"]
216
+ >>> len(partition)
217
+ 3
218
+
219
+ Notes
220
+ -----
221
+ This is a generalization of the planted-l-partition described in
222
+ [1]_. It allows for the creation of groups of any size.
223
+
224
+ The partition is store as a graph attribute 'partition'.
225
+
226
+ References
227
+ ----------
228
+ .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
229
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
230
+ """
231
+ # Use geometric method for O(n+m) complexity algorithm
232
+ # partition = nx.community_sets(nx.get_node_attributes(G, 'affiliation'))
233
+ if not 0.0 <= p_in <= 1.0:
234
+ raise nx.NetworkXError("p_in must be in [0,1]")
235
+ if not 0.0 <= p_out <= 1.0:
236
+ raise nx.NetworkXError("p_out must be in [0,1]")
237
+
238
+ # create connection matrix
239
+ num_blocks = len(sizes)
240
+ p = [[p_out for s in range(num_blocks)] for r in range(num_blocks)]
241
+ for r in range(num_blocks):
242
+ p[r][r] = p_in
243
+
244
+ return stochastic_block_model(
245
+ sizes,
246
+ p,
247
+ nodelist=None,
248
+ seed=seed,
249
+ directed=directed,
250
+ selfloops=False,
251
+ sparse=True,
252
+ )
253
+
254
+
255
+ @py_random_state(4)
256
+ @nx._dispatchable(graphs=None, returns_graph=True)
257
+ def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
258
+ """Returns the planted l-partition graph.
259
+
260
+ This model partitions a graph with n=l*k vertices in
261
+ l groups with k vertices each. Vertices of the same
262
+ group are linked with a probability p_in, and vertices
263
+ of different groups are linked with probability p_out.
264
+
265
+ Parameters
266
+ ----------
267
+ l : int
268
+ Number of groups
269
+ k : int
270
+ Number of vertices in each group
271
+ p_in : float
272
+ probability of connecting vertices within a group
273
+ p_out : float
274
+ probability of connected vertices between groups
275
+ seed : integer, random_state, or None (default)
276
+ Indicator of random number generation state.
277
+ See :ref:`Randomness<randomness>`.
278
+ directed : bool,optional (default=False)
279
+ If True return a directed graph
280
+
281
+ Returns
282
+ -------
283
+ G : NetworkX Graph or DiGraph
284
+ planted l-partition graph
285
+
286
+ Raises
287
+ ------
288
+ NetworkXError
289
+ If `p_in`, `p_out` are not in `[0, 1]`
290
+
291
+ Examples
292
+ --------
293
+ >>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)
294
+
295
+ See Also
296
+ --------
297
+ random_partition_model
298
+
299
+ References
300
+ ----------
301
+ .. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
302
+ on the planted partition model,
303
+ Random Struct. Algor. 18 (2001) 116-140.
304
+
305
+ .. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
306
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
307
+ """
308
+ return random_partition_graph([k] * l, p_in, p_out, seed=seed, directed=directed)
309
+
310
+
311
+ @py_random_state(6)
312
+ @nx._dispatchable(graphs=None, returns_graph=True)
313
+ def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
314
+ """Generate a Gaussian random partition graph.
315
+
316
+ A Gaussian random partition graph is created by creating k partitions
317
+ each with a size drawn from a normal distribution with mean s and variance
318
+ s/v. Nodes are connected within clusters with probability p_in and
319
+ between clusters with probability p_out[1]
320
+
321
+ Parameters
322
+ ----------
323
+ n : int
324
+ Number of nodes in the graph
325
+ s : float
326
+ Mean cluster size
327
+ v : float
328
+ Shape parameter. The variance of cluster size distribution is s/v.
329
+ p_in : float
330
+ Probability of intra cluster connection.
331
+ p_out : float
332
+ Probability of inter cluster connection.
333
+ directed : boolean, optional default=False
334
+ Whether to create a directed graph or not
335
+ seed : integer, random_state, or None (default)
336
+ Indicator of random number generation state.
337
+ See :ref:`Randomness<randomness>`.
338
+
339
+ Returns
340
+ -------
341
+ G : NetworkX Graph or DiGraph
342
+ gaussian random partition graph
343
+
344
+ Raises
345
+ ------
346
+ NetworkXError
347
+ If s is > n
348
+ If p_in or p_out is not in [0,1]
349
+
350
+ Notes
351
+ -----
352
+ Note the number of partitions is dependent on s,v and n, and that the
353
+ last partition may be considerably smaller, as it is sized to simply
354
+ fill out the nodes [1]
355
+
356
+ See Also
357
+ --------
358
+ random_partition_graph
359
+
360
+ Examples
361
+ --------
362
+ >>> G = nx.gaussian_random_partition_graph(100, 10, 10, 0.25, 0.1)
363
+ >>> len(G)
364
+ 100
365
+
366
+ References
367
+ ----------
368
+ .. [1] Ulrik Brandes, Marco Gaertler, Dorothea Wagner,
369
+ Experiments on Graph Clustering Algorithms,
370
+ In the proceedings of the 11th Europ. Symp. Algorithms, 2003.
371
+ """
372
+ if s > n:
373
+ raise nx.NetworkXError("s must be <= n")
374
+ assigned = 0
375
+ sizes = []
376
+ while True:
377
+ size = int(seed.gauss(s, s / v + 0.5))
378
+ if size < 1: # how to handle 0 or negative sizes?
379
+ continue
380
+ if assigned + size >= n:
381
+ sizes.append(n - assigned)
382
+ break
383
+ assigned += size
384
+ sizes.append(size)
385
+ return random_partition_graph(sizes, p_in, p_out, seed=seed, directed=directed)
386
+
387
+
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def ring_of_cliques(num_cliques, clique_size):
390
+ """Defines a "ring of cliques" graph.
391
+
392
+ A ring of cliques graph is consisting of cliques, connected through single
393
+ links. Each clique is a complete graph.
394
+
395
+ Parameters
396
+ ----------
397
+ num_cliques : int
398
+ Number of cliques
399
+ clique_size : int
400
+ Size of cliques
401
+
402
+ Returns
403
+ -------
404
+ G : NetworkX Graph
405
+ ring of cliques graph
406
+
407
+ Raises
408
+ ------
409
+ NetworkXError
410
+ If the number of cliques is lower than 2 or
411
+ if the size of cliques is smaller than 2.
412
+
413
+ Examples
414
+ --------
415
+ >>> G = nx.ring_of_cliques(8, 4)
416
+
417
+ See Also
418
+ --------
419
+ connected_caveman_graph
420
+
421
+ Notes
422
+ -----
423
+ The `connected_caveman_graph` graph removes a link from each clique to
424
+ connect it with the next clique. Instead, the `ring_of_cliques` graph
425
+ simply adds the link without removing any link from the cliques.
426
+ """
427
+ if num_cliques < 2:
428
+ raise nx.NetworkXError("A ring of cliques must have at least two cliques")
429
+ if clique_size < 2:
430
+ raise nx.NetworkXError("The cliques must have at least two nodes")
431
+
432
+ G = nx.Graph()
433
+ for i in range(num_cliques):
434
+ edges = itertools.combinations(
435
+ range(i * clique_size, i * clique_size + clique_size), 2
436
+ )
437
+ G.add_edges_from(edges)
438
+ G.add_edge(
439
+ i * clique_size + 1, (i + 1) * clique_size % (num_cliques * clique_size)
440
+ )
441
+ return G
442
+
443
+
444
+ @nx._dispatchable(graphs=None, returns_graph=True)
445
+ def windmill_graph(n, k):
446
+ """Generate a windmill graph.
447
+ A windmill graph is a graph of `n` cliques each of size `k` that are all
448
+ joined at one node.
449
+ It can be thought of as taking a disjoint union of `n` cliques of size `k`,
450
+ selecting one point from each, and contracting all of the selected points.
451
+ Alternatively, one could generate `n` cliques of size `k-1` and one node
452
+ that is connected to all other nodes in the graph.
453
+
454
+ Parameters
455
+ ----------
456
+ n : int
457
+ Number of cliques
458
+ k : int
459
+ Size of cliques
460
+
461
+ Returns
462
+ -------
463
+ G : NetworkX Graph
464
+ windmill graph with n cliques of size k
465
+
466
+ Raises
467
+ ------
468
+ NetworkXError
469
+ If the number of cliques is less than two
470
+ If the size of the cliques are less than two
471
+
472
+ Examples
473
+ --------
474
+ >>> G = nx.windmill_graph(4, 5)
475
+
476
+ Notes
477
+ -----
478
+ The node labeled `0` will be the node connected to all other nodes.
479
+ Note that windmill graphs are usually denoted `Wd(k,n)`, so the parameters
480
+ are in the opposite order as the parameters of this method.
481
+ """
482
+ if n < 2:
483
+ msg = "A windmill graph must have at least two cliques"
484
+ raise nx.NetworkXError(msg)
485
+ if k < 2:
486
+ raise nx.NetworkXError("The cliques must have at least two nodes")
487
+
488
+ G = nx.disjoint_union_all(
489
+ itertools.chain(
490
+ [nx.complete_graph(k)], (nx.complete_graph(k - 1) for _ in range(n - 1))
491
+ )
492
+ )
493
+ G.add_edges_from((0, i) for i in range(k, G.number_of_nodes()))
494
+ return G
495
+
496
+
497
+ @py_random_state(3)
498
+ @nx._dispatchable(graphs=None, returns_graph=True)
499
+ def stochastic_block_model(
500
+ sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True
501
+ ):
502
+ """Returns a stochastic block model graph.
503
+
504
+ This model partitions the nodes in blocks of arbitrary sizes, and places
505
+ edges between pairs of nodes independently, with a probability that depends
506
+ on the blocks.
507
+
508
+ Parameters
509
+ ----------
510
+ sizes : list of ints
511
+ Sizes of blocks
512
+ p : list of list of floats
513
+ Element (r,s) gives the density of edges going from the nodes
514
+ of group r to nodes of group s.
515
+ p must match the number of groups (len(sizes) == len(p)),
516
+ and it must be symmetric if the graph is undirected.
517
+ nodelist : list, optional
518
+ The block tags are assigned according to the node identifiers
519
+ in nodelist. If nodelist is None, then the ordering is the
520
+ range [0,sum(sizes)-1].
521
+ seed : integer, random_state, or None (default)
522
+ Indicator of random number generation state.
523
+ See :ref:`Randomness<randomness>`.
524
+ directed : boolean optional, default=False
525
+ Whether to create a directed graph or not.
526
+ selfloops : boolean optional, default=False
527
+ Whether to include self-loops or not.
528
+ sparse: boolean optional, default=True
529
+ Use the sparse heuristic to speed up the generator.
530
+
531
+ Returns
532
+ -------
533
+ g : NetworkX Graph or DiGraph
534
+ Stochastic block model graph of size sum(sizes)
535
+
536
+ Raises
537
+ ------
538
+ NetworkXError
539
+ If probabilities are not in [0,1].
540
+ If the probability matrix is not square (directed case).
541
+ If the probability matrix is not symmetric (undirected case).
542
+ If the sizes list does not match nodelist or the probability matrix.
543
+ If nodelist contains duplicate.
544
+
545
+ Examples
546
+ --------
547
+ >>> sizes = [75, 75, 300]
548
+ >>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
549
+ >>> g = nx.stochastic_block_model(sizes, probs, seed=0)
550
+ >>> len(g)
551
+ 450
552
+ >>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True)
553
+ >>> for v in H.nodes(data=True):
554
+ ... print(round(v[1]["density"], 3))
555
+ 0.244
556
+ 0.354
557
+ 0.398
558
+ >>> for v in H.edges(data=True):
559
+ ... print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3))
560
+ 0.047
561
+ 0.02
562
+ 0.071
563
+
564
+ See Also
565
+ --------
566
+ random_partition_graph
567
+ planted_partition_graph
568
+ gaussian_random_partition_graph
569
+ gnp_random_graph
570
+
571
+ References
572
+ ----------
573
+ .. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S.,
574
+ "Stochastic blockmodels: First steps",
575
+ Social networks, 5(2), 109-137, 1983.
576
+ """
577
+ # Check if dimensions match
578
+ if len(sizes) != len(p):
579
+ raise nx.NetworkXException("'sizes' and 'p' do not match.")
580
+ # Check for probability symmetry (undirected) and shape (directed)
581
+ for row in p:
582
+ if len(p) != len(row):
583
+ raise nx.NetworkXException("'p' must be a square matrix.")
584
+ if not directed:
585
+ p_transpose = [list(i) for i in zip(*p)]
586
+ for i in zip(p, p_transpose):
587
+ for j in zip(i[0], i[1]):
588
+ if abs(j[0] - j[1]) > 1e-08:
589
+ raise nx.NetworkXException("'p' must be symmetric.")
590
+ # Check for probability range
591
+ for row in p:
592
+ for prob in row:
593
+ if prob < 0 or prob > 1:
594
+ raise nx.NetworkXException("Entries of 'p' not in [0,1].")
595
+ # Check for nodelist consistency
596
+ if nodelist is not None:
597
+ if len(nodelist) != sum(sizes):
598
+ raise nx.NetworkXException("'nodelist' and 'sizes' do not match.")
599
+ if len(nodelist) != len(set(nodelist)):
600
+ raise nx.NetworkXException("nodelist contains duplicate.")
601
+ else:
602
+ nodelist = range(sum(sizes))
603
+
604
+ # Setup the graph conditionally to the directed switch.
605
+ block_range = range(len(sizes))
606
+ if directed:
607
+ g = nx.DiGraph()
608
+ block_iter = itertools.product(block_range, block_range)
609
+ else:
610
+ g = nx.Graph()
611
+ block_iter = itertools.combinations_with_replacement(block_range, 2)
612
+ # Split nodelist in a partition (list of sets).
613
+ size_cumsum = [sum(sizes[0:x]) for x in range(len(sizes) + 1)]
614
+ g.graph["partition"] = [
615
+ set(nodelist[size_cumsum[x] : size_cumsum[x + 1]])
616
+ for x in range(len(size_cumsum) - 1)
617
+ ]
618
+ # Setup nodes and graph name
619
+ for block_id, nodes in enumerate(g.graph["partition"]):
620
+ for node in nodes:
621
+ g.add_node(node, block=block_id)
622
+
623
+ g.name = "stochastic_block_model"
624
+
625
+ # Test for edge existence
626
+ parts = g.graph["partition"]
627
+ for i, j in block_iter:
628
+ if i == j:
629
+ if directed:
630
+ if selfloops:
631
+ edges = itertools.product(parts[i], parts[i])
632
+ else:
633
+ edges = itertools.permutations(parts[i], 2)
634
+ else:
635
+ edges = itertools.combinations(parts[i], 2)
636
+ if selfloops:
637
+ edges = itertools.chain(edges, zip(parts[i], parts[i]))
638
+ else:
639
+ edges = itertools.product(parts[i], parts[j])
640
+ if sparse:
641
+ if p[i][j] == 1: # Test edges cases p_ij = 0 or 1
642
+ for e in edges:
643
+ g.add_edge(*e)
644
+ elif p[i][j] > 0:
645
+ while True:
646
+ try:
647
+ logrand = math.log(seed.random())
648
+ skip = math.floor(logrand / math.log(1 - p[i][j]))
649
+ # consume "skip" edges
650
+ next(itertools.islice(edges, skip, skip), None)
651
+ e = next(edges)
652
+ g.add_edge(*e) # __safe
653
+ except StopIteration:
654
+ break
655
+ else:
656
+ for e in edges:
657
+ if seed.random() < p[i][j]:
658
+ g.add_edge(*e) # __safe
659
+ return g
660
+
661
+
662
+ def _zipf_rv_below(gamma, xmin, threshold, seed):
663
+ """Returns a random value chosen from the bounded Zipf distribution.
664
+
665
+ Repeatedly draws values from the Zipf distribution until the
666
+ threshold is met, then returns that value.
667
+ """
668
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
669
+ while result > threshold:
670
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
671
+ return result
672
+
673
+
674
+ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters, seed):
675
+ """Returns a list of numbers obeying a constrained power law distribution.
676
+
677
+ ``gamma`` and ``low`` are the parameters for the Zipf distribution.
678
+
679
+ ``high`` is the maximum allowed value for values draw from the Zipf
680
+ distribution. For more information, see :func:`_zipf_rv_below`.
681
+
682
+ ``condition`` and ``length`` are Boolean-valued functions on
683
+ lists. While generating the list, random values are drawn and
684
+ appended to the list until ``length`` is satisfied by the created
685
+ list. Once ``condition`` is satisfied, the sequence generated in
686
+ this way is returned.
687
+
688
+ ``max_iters`` indicates the number of times to generate a list
689
+ satisfying ``length``. If the number of iterations exceeds this
690
+ value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.
691
+
692
+ seed : integer, random_state, or None (default)
693
+ Indicator of random number generation state.
694
+ See :ref:`Randomness<randomness>`.
695
+ """
696
+ for i in range(max_iters):
697
+ seq = []
698
+ while not length(seq):
699
+ seq.append(_zipf_rv_below(gamma, low, high, seed))
700
+ if condition(seq):
701
+ return seq
702
+ raise nx.ExceededMaxIterations("Could not create power law sequence")
703
+
704
+
705
+ def _hurwitz_zeta(x, q, tolerance):
706
+ """The Hurwitz zeta function, or the Riemann zeta function of two arguments.
707
+
708
+ ``x`` must be greater than one and ``q`` must be positive.
709
+
710
+ This function repeatedly computes subsequent partial sums until
711
+ convergence, as decided by ``tolerance``.
712
+ """
713
+ z = 0
714
+ z_prev = -float("inf")
715
+ k = 0
716
+ while abs(z - z_prev) > tolerance:
717
+ z_prev = z
718
+ z += 1 / ((k + q) ** x)
719
+ k += 1
720
+ return z
721
+
722
+
723
+ def _generate_min_degree(gamma, average_degree, max_degree, tolerance, max_iters):
724
+ """Returns a minimum degree from the given average degree."""
725
+ # Defines zeta function whether or not Scipy is available
726
+ try:
727
+ from scipy.special import zeta
728
+ except ImportError:
729
+
730
+ def zeta(x, q):
731
+ return _hurwitz_zeta(x, q, tolerance)
732
+
733
+ min_deg_top = max_degree
734
+ min_deg_bot = 1
735
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
736
+ itrs = 0
737
+ mid_avg_deg = 0
738
+ while abs(mid_avg_deg - average_degree) > tolerance:
739
+ if itrs > max_iters:
740
+ raise nx.ExceededMaxIterations("Could not match average_degree")
741
+ mid_avg_deg = 0
742
+ for x in range(int(min_deg_mid), max_degree + 1):
743
+ mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid)
744
+ if mid_avg_deg > average_degree:
745
+ min_deg_top = min_deg_mid
746
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
747
+ else:
748
+ min_deg_bot = min_deg_mid
749
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
750
+ itrs += 1
751
+ # return int(min_deg_mid + 0.5)
752
+ return round(min_deg_mid)
753
+
754
+
755
+ def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed):
756
+ """Returns a list of sets, each of which represents a community.
757
+
758
+ ``degree_seq`` is the degree sequence that must be met by the
759
+ graph.
760
+
761
+ ``community_sizes`` is the community size distribution that must be
762
+ met by the generated list of sets.
763
+
764
+ ``mu`` is a float in the interval [0, 1] indicating the fraction of
765
+ intra-community edges incident to each node.
766
+
767
+ ``max_iters`` is the number of times to try to add a node to a
768
+ community. This must be greater than the length of
769
+ ``degree_seq``, otherwise this function will always fail. If
770
+ the number of iterations exceeds this value,
771
+ :exc:`~networkx.exception.ExceededMaxIterations` is raised.
772
+
773
+ seed : integer, random_state, or None (default)
774
+ Indicator of random number generation state.
775
+ See :ref:`Randomness<randomness>`.
776
+
777
+ The communities returned by this are sets of integers in the set {0,
778
+ ..., *n* - 1}, where *n* is the length of ``degree_seq``.
779
+
780
+ """
781
+ # This assumes the nodes in the graph will be natural numbers.
782
+ result = [set() for _ in community_sizes]
783
+ n = len(degree_seq)
784
+ free = list(range(n))
785
+ for i in range(max_iters):
786
+ v = free.pop()
787
+ c = seed.choice(range(len(community_sizes)))
788
+ # s = int(degree_seq[v] * (1 - mu) + 0.5)
789
+ s = round(degree_seq[v] * (1 - mu))
790
+ # If the community is large enough, add the node to the chosen
791
+ # community. Otherwise, return it to the list of unaffiliated
792
+ # nodes.
793
+ if s < community_sizes[c]:
794
+ result[c].add(v)
795
+ else:
796
+ free.append(v)
797
+ # If the community is too big, remove a node from it.
798
+ if len(result[c]) > community_sizes[c]:
799
+ free.append(result[c].pop())
800
+ if not free:
801
+ return result
802
+ msg = "Could not assign communities; try increasing min_community"
803
+ raise nx.ExceededMaxIterations(msg)
804
+
805
+
806
+ @py_random_state(11)
807
+ @nx._dispatchable(graphs=None, returns_graph=True)
808
+ def LFR_benchmark_graph(
809
+ n,
810
+ tau1,
811
+ tau2,
812
+ mu,
813
+ average_degree=None,
814
+ min_degree=None,
815
+ max_degree=None,
816
+ min_community=None,
817
+ max_community=None,
818
+ tol=1.0e-7,
819
+ max_iters=500,
820
+ seed=None,
821
+ ):
822
+ r"""Returns the LFR benchmark graph.
823
+
824
+ This algorithm proceeds as follows:
825
+
826
+ 1) Find a degree sequence with a power law distribution, and minimum
827
+ value ``min_degree``, which has approximate average degree
828
+ ``average_degree``. This is accomplished by either
829
+
830
+ a) specifying ``min_degree`` and not ``average_degree``,
831
+ b) specifying ``average_degree`` and not ``min_degree``, in which
832
+ case a suitable minimum degree will be found.
833
+
834
+ ``max_degree`` can also be specified, otherwise it will be set to
835
+ ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
836
+ joining it to nodes in communities other than its own and $(1 -
837
+ \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
838
+ community.
839
+ 2) Generate community sizes according to a power law distribution
840
+ with exponent ``tau2``. If ``min_community`` and
841
+ ``max_community`` are not specified they will be selected to be
842
+ ``min_degree`` and ``max_degree``, respectively. Community sizes
843
+ are generated until the sum of their sizes equals ``n``.
844
+ 3) Each node will be randomly assigned a community with the
845
+ condition that the community is large enough for the node's
846
+ intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
847
+ described in step 2. If a community grows too large, a random node
848
+ will be selected for reassignment to a new community, until all
849
+ nodes have been assigned a community.
850
+ 4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
851
+ intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
852
+ edges.
853
+
854
+ Parameters
855
+ ----------
856
+ n : int
857
+ Number of nodes in the created graph.
858
+
859
+ tau1 : float
860
+ Power law exponent for the degree distribution of the created
861
+ graph. This value must be strictly greater than one.
862
+
863
+ tau2 : float
864
+ Power law exponent for the community size distribution in the
865
+ created graph. This value must be strictly greater than one.
866
+
867
+ mu : float
868
+ Fraction of inter-community edges incident to each node. This
869
+ value must be in the interval [0, 1].
870
+
871
+ average_degree : float
872
+ Desired average degree of nodes in the created graph. This value
873
+ must be in the interval [0, *n*]. Exactly one of this and
874
+ ``min_degree`` must be specified, otherwise a
875
+ :exc:`NetworkXError` is raised.
876
+
877
+ min_degree : int
878
+ Minimum degree of nodes in the created graph. This value must be
879
+ in the interval [0, *n*]. Exactly one of this and
880
+ ``average_degree`` must be specified, otherwise a
881
+ :exc:`NetworkXError` is raised.
882
+
883
+ max_degree : int
884
+ Maximum degree of nodes in the created graph. If not specified,
885
+ this is set to ``n``, the total number of nodes in the graph.
886
+
887
+ min_community : int
888
+ Minimum size of communities in the graph. If not specified, this
889
+ is set to ``min_degree``.
890
+
891
+ max_community : int
892
+ Maximum size of communities in the graph. If not specified, this
893
+ is set to ``n``, the total number of nodes in the graph.
894
+
895
+ tol : float
896
+ Tolerance when comparing floats, specifically when comparing
897
+ average degree values.
898
+
899
+ max_iters : int
900
+ Maximum number of iterations to try to create the community sizes,
901
+ degree distribution, and community affiliations.
902
+
903
+ seed : integer, random_state, or None (default)
904
+ Indicator of random number generation state.
905
+ See :ref:`Randomness<randomness>`.
906
+
907
+ Returns
908
+ -------
909
+ G : NetworkX graph
910
+ The LFR benchmark graph generated according to the specified
911
+ parameters.
912
+
913
+ Each node in the graph has a node attribute ``'community'`` that
914
+ stores the community (that is, the set of nodes) that includes
915
+ it.
916
+
917
+ Raises
918
+ ------
919
+ NetworkXError
920
+ If any of the parameters do not meet their upper and lower bounds:
921
+
922
+ - ``tau1`` and ``tau2`` must be strictly greater than 1.
923
+ - ``mu`` must be in [0, 1].
924
+ - ``max_degree`` must be in {1, ..., *n*}.
925
+ - ``min_community`` and ``max_community`` must be in {0, ...,
926
+ *n*}.
927
+
928
+ If not exactly one of ``average_degree`` and ``min_degree`` is
929
+ specified.
930
+
931
+ If ``min_degree`` is not specified and a suitable ``min_degree``
932
+ cannot be found.
933
+
934
+ ExceededMaxIterations
935
+ If a valid degree sequence cannot be created within
936
+ ``max_iters`` number of iterations.
937
+
938
+ If a valid set of community sizes cannot be created within
939
+ ``max_iters`` number of iterations.
940
+
941
+ If a valid community assignment cannot be created within ``10 *
942
+ n * max_iters`` number of iterations.
943
+
944
+ Examples
945
+ --------
946
+ Basic usage::
947
+
948
+ >>> from networkx.generators.community import LFR_benchmark_graph
949
+ >>> n = 250
950
+ >>> tau1 = 3
951
+ >>> tau2 = 1.5
952
+ >>> mu = 0.1
953
+ >>> G = LFR_benchmark_graph(
954
+ ... n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
955
+ ... )
956
+
957
+ Continuing the example above, you can get the communities from the
958
+ node attributes of the graph::
959
+
960
+ >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}
961
+
962
+ Notes
963
+ -----
964
+ This algorithm differs slightly from the original way it was
965
+ presented in [1].
966
+
967
+ 1) Rather than connecting the graph via a configuration model then
968
+ rewiring to match the intra-community and inter-community
969
+ degrees, we do this wiring explicitly at the end, which should be
970
+ equivalent.
971
+ 2) The code posted on the author's website [2] calculates the random
972
+ power law distributed variables and their average using
973
+ continuous approximations, whereas we use the discrete
974
+ distributions here as both degree and community size are
975
+ discrete.
976
+
977
+ Though the authors describe the algorithm as quite robust, testing
978
+ during development indicates that a somewhat narrower parameter set
979
+ is likely to successfully produce a graph. Some suggestions have
980
+ been provided in the event of exceptions.
981
+
982
+ References
983
+ ----------
984
+ .. [1] "Benchmark graphs for testing community detection algorithms",
985
+ Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
986
+ Phys. Rev. E 78, 046110 2008
987
+ .. [2] https://www.santofortunato.net/resources
988
+
989
+ """
990
+ # Perform some basic parameter validation.
991
+ if not tau1 > 1:
992
+ raise nx.NetworkXError("tau1 must be greater than one")
993
+ if not tau2 > 1:
994
+ raise nx.NetworkXError("tau2 must be greater than one")
995
+ if not 0 <= mu <= 1:
996
+ raise nx.NetworkXError("mu must be in the interval [0, 1]")
997
+
998
+ # Validate parameters for generating the degree sequence.
999
+ if max_degree is None:
1000
+ max_degree = n
1001
+ elif not 0 < max_degree <= n:
1002
+ raise nx.NetworkXError("max_degree must be in the interval (0, n]")
1003
+ if not ((min_degree is None) ^ (average_degree is None)):
1004
+ raise nx.NetworkXError(
1005
+ "Must assign exactly one of min_degree and average_degree"
1006
+ )
1007
+ if min_degree is None:
1008
+ min_degree = _generate_min_degree(
1009
+ tau1, average_degree, max_degree, tol, max_iters
1010
+ )
1011
+
1012
+ # Generate a degree sequence with a power law distribution.
1013
+ low, high = min_degree, max_degree
1014
+
1015
+ def condition(seq):
1016
+ return sum(seq) % 2 == 0
1017
+
1018
+ def length(seq):
1019
+ return len(seq) >= n
1020
+
1021
+ deg_seq = _powerlaw_sequence(tau1, low, high, condition, length, max_iters, seed)
1022
+
1023
+ # Validate parameters for generating the community size sequence.
1024
+ if min_community is None:
1025
+ min_community = min(deg_seq)
1026
+ if max_community is None:
1027
+ max_community = max(deg_seq)
1028
+
1029
+ # Generate a community size sequence with a power law distribution.
1030
+ #
1031
+ # TODO The original code incremented the number of iterations each
1032
+ # time a new Zipf random value was drawn from the distribution. This
1033
+ # differed from the way the number of iterations was incremented in
1034
+ # `_powerlaw_degree_sequence`, so this code was changed to match
1035
+ # that one. As a result, this code is allowed many more chances to
1036
+ # generate a valid community size sequence.
1037
+ low, high = min_community, max_community
1038
+
1039
+ def condition(seq):
1040
+ return sum(seq) == n
1041
+
1042
+ def length(seq):
1043
+ return sum(seq) >= n
1044
+
1045
+ comms = _powerlaw_sequence(tau2, low, high, condition, length, max_iters, seed)
1046
+
1047
+ # Generate the communities based on the given degree sequence and
1048
+ # community sizes.
1049
+ max_iters *= 10 * n
1050
+ communities = _generate_communities(deg_seq, comms, mu, max_iters, seed)
1051
+
1052
+ # Finally, generate the benchmark graph based on the given
1053
+ # communities, joining nodes according to the intra- and
1054
+ # inter-community degrees.
1055
+ G = nx.Graph()
1056
+ G.add_nodes_from(range(n))
1057
+ for c in communities:
1058
+ for u in c:
1059
+ while G.degree(u) < round(deg_seq[u] * (1 - mu)):
1060
+ v = seed.choice(list(c))
1061
+ G.add_edge(u, v)
1062
+ while G.degree(u) < deg_seq[u]:
1063
+ v = seed.choice(range(n))
1064
+ if v not in c:
1065
+ G.add_edge(u, v)
1066
+ G.nodes[u]["community"] = c
1067
+ return G
venv/lib/python3.14/site-packages/networkx/generators/degree_seq.py ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given degree sequence or expected degree sequence."""
2
+
3
+ import heapq
4
+ import math
5
+ from itertools import chain, combinations, zip_longest
6
+ from operator import itemgetter
7
+
8
+ import networkx as nx
9
+ from networkx.utils import py_random_state, random_weighted_sample
10
+
11
+ __all__ = [
12
+ "configuration_model",
13
+ "directed_configuration_model",
14
+ "expected_degree_graph",
15
+ "havel_hakimi_graph",
16
+ "directed_havel_hakimi_graph",
17
+ "degree_sequence_tree",
18
+ "random_degree_sequence_graph",
19
+ ]
20
+
21
+ chaini = chain.from_iterable
22
+
23
+
24
+ def _to_stublist(degree_sequence):
25
+ """Returns a list of degree-repeated node numbers.
26
+
27
+ ``degree_sequence`` is a list of nonnegative integers representing
28
+ the degrees of nodes in a graph.
29
+
30
+ This function returns a list of node numbers with multiplicities
31
+ according to the given degree sequence. For example, if the first
32
+ element of ``degree_sequence`` is ``3``, then the first node number,
33
+ ``0``, will appear at the head of the returned list three times. The
34
+ node numbers are assumed to be the numbers zero through
35
+ ``len(degree_sequence) - 1``.
36
+
37
+ Examples
38
+ --------
39
+
40
+ >>> degree_sequence = [1, 2, 3]
41
+ >>> _to_stublist(degree_sequence)
42
+ [0, 1, 1, 2, 2, 2]
43
+
44
+ If a zero appears in the sequence, that means the node exists but
45
+ has degree zero, so that number will be skipped in the returned
46
+ list::
47
+
48
+ >>> degree_sequence = [2, 0, 1]
49
+ >>> _to_stublist(degree_sequence)
50
+ [0, 0, 2]
51
+
52
+ """
53
+ return list(chaini([n] * d for n, d in enumerate(degree_sequence)))
54
+
55
+
56
+ def _configuration_model(
57
+ deg_sequence, create_using, directed=False, in_deg_sequence=None, seed=None
58
+ ):
59
+ """Helper function for generating either undirected or directed
60
+ configuration model graphs.
61
+
62
+ ``deg_sequence`` is a list of nonnegative integers representing the
63
+ degree of the node whose label is the index of the list element.
64
+
65
+ ``create_using`` see :func:`~networkx.empty_graph`.
66
+
67
+ ``directed`` and ``in_deg_sequence`` are required if you want the
68
+ returned graph to be generated using the directed configuration
69
+ model algorithm. If ``directed`` is ``False``, then ``deg_sequence``
70
+ is interpreted as the degree sequence of an undirected graph and
71
+ ``in_deg_sequence`` is ignored. Otherwise, if ``directed`` is
72
+ ``True``, then ``deg_sequence`` is interpreted as the out-degree
73
+ sequence and ``in_deg_sequence`` as the in-degree sequence of a
74
+ directed graph.
75
+
76
+ .. note::
77
+
78
+ ``deg_sequence`` and ``in_deg_sequence`` need not be the same
79
+ length.
80
+
81
+ ``seed`` is a random.Random or numpy.random.RandomState instance
82
+
83
+ This function returns a graph, directed if and only if ``directed``
84
+ is ``True``, generated according to the configuration model
85
+ algorithm. For more information on the algorithm, see the
86
+ :func:`configuration_model` or :func:`directed_configuration_model`
87
+ functions.
88
+
89
+ """
90
+ n = len(deg_sequence)
91
+ G = nx.empty_graph(n, create_using)
92
+ # If empty, return the null graph immediately.
93
+ if n == 0:
94
+ return G
95
+ # Build a list of available degree-repeated nodes. For example,
96
+ # for degree sequence [3, 2, 1, 1, 1], the "stub list" is
97
+ # initially [0, 0, 0, 1, 1, 2, 3, 4], that is, node 0 has degree
98
+ # 3 and thus is repeated 3 times, etc.
99
+ #
100
+ # Also, shuffle the stub list in order to get a random sequence of
101
+ # node pairs.
102
+ if directed:
103
+ pairs = zip_longest(deg_sequence, in_deg_sequence, fillvalue=0)
104
+ # Unzip the list of pairs into a pair of lists.
105
+ out_deg, in_deg = zip(*pairs)
106
+
107
+ out_stublist = _to_stublist(out_deg)
108
+ in_stublist = _to_stublist(in_deg)
109
+
110
+ seed.shuffle(out_stublist)
111
+ seed.shuffle(in_stublist)
112
+ else:
113
+ stublist = _to_stublist(deg_sequence)
114
+ # Choose a random balanced bipartition of the stublist, which
115
+ # gives a random pairing of nodes. In this implementation, we
116
+ # shuffle the list and then split it in half.
117
+ n = len(stublist)
118
+ half = n // 2
119
+ seed.shuffle(stublist)
120
+ out_stublist, in_stublist = stublist[:half], stublist[half:]
121
+ G.add_edges_from(zip(out_stublist, in_stublist))
122
+ return G
123
+
124
+
125
+ @py_random_state(2)
126
+ @nx._dispatchable(graphs=None, returns_graph=True)
127
+ def configuration_model(deg_sequence, create_using=None, seed=None):
128
+ """Returns a random graph with the given degree sequence.
129
+
130
+ The configuration model generates a random pseudograph (graph with
131
+ parallel edges and self loops) by randomly assigning edges to
132
+ match the given degree sequence.
133
+
134
+ Parameters
135
+ ----------
136
+ deg_sequence : list of nonnegative integers
137
+ Each list entry corresponds to the degree of a node.
138
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
139
+ Graph type to create. If graph instance, then cleared before populated.
140
+ seed : integer, random_state, or None (default)
141
+ Indicator of random number generation state.
142
+ See :ref:`Randomness<randomness>`.
143
+
144
+ Returns
145
+ -------
146
+ G : MultiGraph
147
+ A graph with the specified degree sequence.
148
+ Nodes are labeled starting at 0 with an index
149
+ corresponding to the position in deg_sequence.
150
+
151
+ Raises
152
+ ------
153
+ NetworkXError
154
+ If the degree sequence does not have an even sum.
155
+
156
+ See Also
157
+ --------
158
+ is_graphical
159
+
160
+ Notes
161
+ -----
162
+ As described by Newman [1]_.
163
+
164
+ A non-graphical degree sequence (not realizable by some simple
165
+ graph) is allowed since this function returns graphs with self
166
+ loops and parallel edges. An exception is raised if the degree
167
+ sequence does not have an even sum.
168
+
169
+ This configuration model construction process can lead to
170
+ duplicate edges and loops. You can remove the self-loops and
171
+ parallel edges (see below) which will likely result in a graph
172
+ that doesn't have the exact degree sequence specified.
173
+
174
+ The density of self-loops and parallel edges tends to decrease as
175
+ the number of nodes increases. However, typically the number of
176
+ self-loops will approach a Poisson distribution with a nonzero mean,
177
+ and similarly for the number of parallel edges. Consider a node
178
+ with *k* stubs. The probability of being joined to another stub of
179
+ the same node is basically (*k* - *1*) / *N*, where *k* is the
180
+ degree and *N* is the number of nodes. So the probability of a
181
+ self-loop scales like *c* / *N* for some constant *c*. As *N* grows,
182
+ this means we expect *c* self-loops. Similarly for parallel edges.
183
+
184
+ References
185
+ ----------
186
+ .. [1] M.E.J. Newman, "The structure and function of complex networks",
187
+ SIAM REVIEW 45-2, pp 167-256, 2003.
188
+
189
+ Examples
190
+ --------
191
+ You can create a degree sequence following a particular distribution
192
+ by using the one of the distribution functions in
193
+ :mod:`~networkx.utils.random_sequence` (or one of your own). For
194
+ example, to create an undirected multigraph on one hundred nodes
195
+ with degree sequence chosen from the power law distribution:
196
+
197
+ >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000)
198
+ >>> G = nx.configuration_model(sequence)
199
+ >>> len(G)
200
+ 100
201
+ >>> actual_degrees = [d for v, d in G.degree()]
202
+ >>> actual_degrees == sequence
203
+ True
204
+
205
+ The returned graph is a multigraph, which may have parallel
206
+ edges. To remove any parallel edges from the returned graph:
207
+
208
+ >>> G = nx.Graph(G)
209
+
210
+ Similarly, to remove self-loops:
211
+
212
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
213
+
214
+ """
215
+ if sum(deg_sequence) % 2 != 0:
216
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
217
+ raise nx.NetworkXError(msg)
218
+
219
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
220
+ if G.is_directed():
221
+ raise nx.NetworkXNotImplemented("not implemented for directed graphs")
222
+
223
+ G = _configuration_model(deg_sequence, G, seed=seed)
224
+
225
+ return G
226
+
227
+
228
+ @py_random_state(3)
229
+ @nx._dispatchable(graphs=None, returns_graph=True)
230
+ def directed_configuration_model(
231
+ in_degree_sequence, out_degree_sequence, create_using=None, seed=None
232
+ ):
233
+ """Returns a directed_random graph with the given degree sequences.
234
+
235
+ The configuration model generates a random directed pseudograph
236
+ (graph with parallel edges and self loops) by randomly assigning
237
+ edges to match the given degree sequences.
238
+
239
+ Parameters
240
+ ----------
241
+ in_degree_sequence : list of nonnegative integers
242
+ Each list entry corresponds to the in-degree of a node.
243
+ out_degree_sequence : list of nonnegative integers
244
+ Each list entry corresponds to the out-degree of a node.
245
+ create_using : NetworkX graph constructor, optional (default MultiDiGraph)
246
+ Graph type to create. If graph instance, then cleared before populated.
247
+ seed : integer, random_state, or None (default)
248
+ Indicator of random number generation state.
249
+ See :ref:`Randomness<randomness>`.
250
+
251
+ Returns
252
+ -------
253
+ G : MultiDiGraph
254
+ A graph with the specified degree sequences.
255
+ Nodes are labeled starting at 0 with an index
256
+ corresponding to the position in deg_sequence.
257
+
258
+ Raises
259
+ ------
260
+ NetworkXError
261
+ If the degree sequences do not have the same sum.
262
+
263
+ See Also
264
+ --------
265
+ configuration_model
266
+
267
+ Notes
268
+ -----
269
+ Algorithm as described by Newman [1]_.
270
+
271
+ A non-graphical degree sequence (not realizable by some simple
272
+ graph) is allowed since this function returns graphs with self
273
+ loops and parallel edges. An exception is raised if the degree
274
+ sequences does not have the same sum.
275
+
276
+ This configuration model construction process can lead to
277
+ duplicate edges and loops. You can remove the self-loops and
278
+ parallel edges (see below) which will likely result in a graph
279
+ that doesn't have the exact degree sequence specified. This
280
+ "finite-size effect" decreases as the size of the graph increases.
281
+
282
+ References
283
+ ----------
284
+ .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
285
+ Random graphs with arbitrary degree distributions and their applications
286
+ Phys. Rev. E, 64, 026118 (2001)
287
+
288
+ Examples
289
+ --------
290
+ One can modify the in- and out-degree sequences from an existing
291
+ directed graph in order to create a new directed graph. For example,
292
+ here we modify the directed path graph:
293
+
294
+ >>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
295
+ >>> din = list(d for n, d in D.in_degree())
296
+ >>> dout = list(d for n, d in D.out_degree())
297
+ >>> din.append(1)
298
+ >>> dout[0] = 2
299
+ >>> # We now expect an edge from node 0 to a new node, node 3.
300
+ ... D = nx.directed_configuration_model(din, dout)
301
+
302
+ The returned graph is a directed multigraph, which may have parallel
303
+ edges. To remove any parallel edges from the returned graph:
304
+
305
+ >>> D = nx.DiGraph(D)
306
+
307
+ Similarly, to remove self-loops:
308
+
309
+ >>> D.remove_edges_from(nx.selfloop_edges(D))
310
+
311
+ """
312
+ if sum(in_degree_sequence) != sum(out_degree_sequence):
313
+ msg = "Invalid degree sequences: sequences must have equal sums"
314
+ raise nx.NetworkXError(msg)
315
+
316
+ if create_using is None:
317
+ create_using = nx.MultiDiGraph
318
+
319
+ G = _configuration_model(
320
+ out_degree_sequence,
321
+ create_using,
322
+ directed=True,
323
+ in_deg_sequence=in_degree_sequence,
324
+ seed=seed,
325
+ )
326
+
327
+ name = "directed configuration_model {} nodes {} edges"
328
+ return G
329
+
330
+
331
+ @py_random_state(1)
332
+ @nx._dispatchable(graphs=None, returns_graph=True)
333
+ def expected_degree_graph(w, seed=None, selfloops=True):
334
+ r"""Returns a random graph with given expected degrees.
335
+
336
+ Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$
337
+ of length $n$ this algorithm assigns an edge between node $u$ and
338
+ node $v$ with probability
339
+
340
+ .. math::
341
+
342
+ p_{uv} = \frac{w_u w_v}{\sum_k w_k} .
343
+
344
+ Parameters
345
+ ----------
346
+ w : list
347
+ The list of expected degrees.
348
+ selfloops: bool (default=True)
349
+ Set to False to remove the possibility of self-loop edges.
350
+ seed : integer, random_state, or None (default)
351
+ Indicator of random number generation state.
352
+ See :ref:`Randomness<randomness>`.
353
+
354
+ Returns
355
+ -------
356
+ Graph
357
+
358
+ Examples
359
+ --------
360
+ >>> z = [10 for i in range(100)]
361
+ >>> G = nx.expected_degree_graph(z)
362
+
363
+ Notes
364
+ -----
365
+ The nodes have integer labels corresponding to index of expected degrees
366
+ input sequence.
367
+
368
+ The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the
369
+ number of nodes and $m$ is the expected number of edges.
370
+
371
+ The model in [1]_ includes the possibility of self-loop edges.
372
+ Set selfloops=False to produce a graph without self loops.
373
+
374
+ For finite graphs this model doesn't produce exactly the given
375
+ expected degree sequence. Instead the expected degrees are as
376
+ follows.
377
+
378
+ For the case without self loops (selfloops=False),
379
+
380
+ .. math::
381
+
382
+ E[deg(u)] = \sum_{v \ne u} p_{uv}
383
+ = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .
384
+
385
+
386
+ NetworkX uses the standard convention that a self-loop edge counts 2
387
+ in the degree of a node, so with self loops (selfloops=True),
388
+
389
+ .. math::
390
+
391
+ E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}
392
+ = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .
393
+
394
+ References
395
+ ----------
396
+ .. [1] Fan Chung and L. Lu, Connected components in random graphs with
397
+ given expected degree sequences, Ann. Combinatorics, 6,
398
+ pp. 125-145, 2002.
399
+ .. [2] Joel Miller and Aric Hagberg,
400
+ Efficient generation of networks with given expected degrees,
401
+ in Algorithms and Models for the Web-Graph (WAW 2011),
402
+ Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
403
+ pp. 115-126, 2011.
404
+ """
405
+ n = len(w)
406
+ G = nx.empty_graph(n)
407
+
408
+ # If there are no nodes are no edges in the graph, return the empty graph.
409
+ if n == 0 or max(w) == 0:
410
+ return G
411
+
412
+ rho = 1 / sum(w)
413
+ # Sort the weights in decreasing order. The original order of the
414
+ # weights dictates the order of the (integer) node labels, so we
415
+ # need to remember the permutation applied in the sorting.
416
+ order = sorted(enumerate(w), key=itemgetter(1), reverse=True)
417
+ mapping = {c: u for c, (u, v) in enumerate(order)}
418
+ seq = [v for u, v in order]
419
+ last = n
420
+ if not selfloops:
421
+ last -= 1
422
+ for u in range(last):
423
+ v = u
424
+ if not selfloops:
425
+ v += 1
426
+ factor = seq[u] * rho
427
+ p = min(seq[v] * factor, 1)
428
+ while v < n and p > 0:
429
+ if p != 1:
430
+ r = seed.random()
431
+ v += math.floor(math.log(r, 1 - p))
432
+ if v < n:
433
+ q = min(seq[v] * factor, 1)
434
+ if seed.random() < q / p:
435
+ G.add_edge(mapping[u], mapping[v])
436
+ v += 1
437
+ p = q
438
+ return G
439
+
440
+
441
+ @nx._dispatchable(graphs=None, returns_graph=True)
442
+ def havel_hakimi_graph(deg_sequence, create_using=None):
443
+ """Returns a simple graph with given degree sequence constructed
444
+ using the Havel-Hakimi algorithm.
445
+
446
+ Parameters
447
+ ----------
448
+ deg_sequence: list of integers
449
+ Each integer corresponds to the degree of a node (need not be sorted).
450
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
451
+ Graph type to create. If graph instance, then cleared before populated.
452
+ Directed graphs are not allowed.
453
+
454
+ Raises
455
+ ------
456
+ NetworkXException
457
+ For a non-graphical degree sequence (i.e. one
458
+ not realizable by some simple graph).
459
+
460
+ Notes
461
+ -----
462
+ The Havel-Hakimi algorithm constructs a simple graph by
463
+ successively connecting the node of highest degree to other nodes
464
+ of highest degree, resorting remaining nodes by degree, and
465
+ repeating the process. The resulting graph has a high
466
+ degree-associativity. Nodes are labeled 1,.., len(deg_sequence),
467
+ corresponding to their position in deg_sequence.
468
+
469
+ The basic algorithm is from Hakimi [1]_ and was generalized by
470
+ Kleitman and Wang [2]_.
471
+
472
+ References
473
+ ----------
474
+ .. [1] Hakimi S., On Realizability of a Set of Integers as
475
+ Degrees of the Vertices of a Linear Graph. I,
476
+ Journal of SIAM, 10(3), pp. 496-506 (1962)
477
+ .. [2] Kleitman D.J. and Wang D.L.
478
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
479
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
480
+ """
481
+ if not nx.is_graphical(deg_sequence):
482
+ raise nx.NetworkXError("Invalid degree sequence")
483
+
484
+ p = len(deg_sequence)
485
+ G = nx.empty_graph(p, create_using)
486
+ if G.is_directed():
487
+ raise nx.NetworkXError("Directed graphs are not supported")
488
+ num_degs = [[] for i in range(p)]
489
+ dmax, n = 0, 0
490
+ for d in deg_sequence:
491
+ # Process only the non-zero integers
492
+ if d > 0:
493
+ num_degs[d].append(n)
494
+ dmax, n = max(dmax, d), n + 1
495
+ # Return graph if no edges
496
+ if n == 0:
497
+ return G
498
+
499
+ modstubs = [(0, 0)] * (dmax + 1)
500
+ # Successively reduce degree sequence by removing the maximum degree
501
+ while n > 0:
502
+ # Retrieve the maximum degree in the sequence
503
+ while len(num_degs[dmax]) == 0:
504
+ dmax -= 1
505
+ # If there are not enough stubs to connect to, then the sequence is
506
+ # not graphical
507
+ if dmax > n - 1:
508
+ raise nx.NetworkXError("Non-graphical integer sequence")
509
+
510
+ # Remove largest stub in list
511
+ source = num_degs[dmax].pop()
512
+ n -= 1
513
+ # Reduce the next dmax largest stubs
514
+ mslen = 0
515
+ k = dmax
516
+ for i in range(dmax):
517
+ while len(num_degs[k]) == 0:
518
+ k -= 1
519
+ target = num_degs[k].pop()
520
+ G.add_edge(source, target)
521
+ n -= 1
522
+ if k > 1:
523
+ modstubs[mslen] = (k - 1, target)
524
+ mslen += 1
525
+ # Add back to the list any nonzero stubs that were removed
526
+ for i in range(mslen):
527
+ (stubval, stubtarget) = modstubs[i]
528
+ num_degs[stubval].append(stubtarget)
529
+ n += 1
530
+
531
+ return G
532
+
533
+
534
+ @nx._dispatchable(graphs=None, returns_graph=True)
535
+ def directed_havel_hakimi_graph(in_deg_sequence, out_deg_sequence, create_using=None):
536
+ """Returns a directed graph with the given degree sequences.
537
+
538
+ Parameters
539
+ ----------
540
+ in_deg_sequence : list of integers
541
+ Each list entry corresponds to the in-degree of a node.
542
+ out_deg_sequence : list of integers
543
+ Each list entry corresponds to the out-degree of a node.
544
+ create_using : NetworkX graph constructor, optional (default DiGraph)
545
+ Graph type to create. If graph instance, then cleared before populated.
546
+
547
+ Returns
548
+ -------
549
+ G : DiGraph
550
+ A graph with the specified degree sequences.
551
+ Nodes are labeled starting at 0 with an index
552
+ corresponding to the position in deg_sequence
553
+
554
+ Raises
555
+ ------
556
+ NetworkXError
557
+ If the degree sequences are not digraphical.
558
+
559
+ See Also
560
+ --------
561
+ configuration_model
562
+
563
+ Notes
564
+ -----
565
+ Algorithm as described by Kleitman and Wang [1]_.
566
+
567
+ References
568
+ ----------
569
+ .. [1] D.J. Kleitman and D.L. Wang
570
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
571
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
572
+ """
573
+ in_deg_sequence = nx.utils.make_list_of_ints(in_deg_sequence)
574
+ out_deg_sequence = nx.utils.make_list_of_ints(out_deg_sequence)
575
+
576
+ # Process the sequences and form two heaps to store degree pairs with
577
+ # either zero or nonzero out degrees
578
+ sumin, sumout = 0, 0
579
+ nin, nout = len(in_deg_sequence), len(out_deg_sequence)
580
+ maxn = max(nin, nout)
581
+ G = nx.empty_graph(maxn, create_using, default=nx.DiGraph)
582
+ if maxn == 0:
583
+ return G
584
+ maxin = 0
585
+ stubheap, zeroheap = [], []
586
+ for n in range(maxn):
587
+ in_deg, out_deg = 0, 0
588
+ if n < nout:
589
+ out_deg = out_deg_sequence[n]
590
+ if n < nin:
591
+ in_deg = in_deg_sequence[n]
592
+ if in_deg < 0 or out_deg < 0:
593
+ raise nx.NetworkXError(
594
+ "Invalid degree sequences. Sequence values must be positive."
595
+ )
596
+ sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
597
+ if in_deg > 0:
598
+ stubheap.append((-1 * out_deg, -1 * in_deg, n))
599
+ elif out_deg > 0:
600
+ zeroheap.append((-1 * out_deg, n))
601
+ if sumin != sumout:
602
+ raise nx.NetworkXError(
603
+ "Invalid degree sequences. Sequences must have equal sums."
604
+ )
605
+ heapq.heapify(stubheap)
606
+ heapq.heapify(zeroheap)
607
+
608
+ modstubs = [(0, 0, 0)] * (maxin + 1)
609
+ # Successively reduce degree sequence by removing the maximum
610
+ while stubheap:
611
+ # Remove first value in the sequence with a non-zero in degree
612
+ (freeout, freein, target) = heapq.heappop(stubheap)
613
+ freein *= -1
614
+ if freein > len(stubheap) + len(zeroheap):
615
+ raise nx.NetworkXError("Non-digraphical integer sequence")
616
+
617
+ # Attach arcs from the nodes with the most stubs
618
+ mslen = 0
619
+ for i in range(freein):
620
+ if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]):
621
+ (stubout, stubsource) = heapq.heappop(zeroheap)
622
+ stubin = 0
623
+ else:
624
+ (stubout, stubin, stubsource) = heapq.heappop(stubheap)
625
+ if stubout == 0:
626
+ raise nx.NetworkXError("Non-digraphical integer sequence")
627
+ G.add_edge(stubsource, target)
628
+ # Check if source is now totally connected
629
+ if stubout + 1 < 0 or stubin < 0:
630
+ modstubs[mslen] = (stubout + 1, stubin, stubsource)
631
+ mslen += 1
632
+
633
+ # Add the nodes back to the heaps that still have available stubs
634
+ for i in range(mslen):
635
+ stub = modstubs[i]
636
+ if stub[1] < 0:
637
+ heapq.heappush(stubheap, stub)
638
+ else:
639
+ heapq.heappush(zeroheap, (stub[0], stub[2]))
640
+ if freeout < 0:
641
+ heapq.heappush(zeroheap, (freeout, target))
642
+
643
+ return G
644
+
645
+
646
+ @nx._dispatchable(graphs=None, returns_graph=True)
647
+ def degree_sequence_tree(deg_sequence, create_using=None):
648
+ """Return a tree with the given degree sequence.
649
+
650
+ Two conditions must be met for a degree sequence to be valid for a tree:
651
+
652
+ 1. The number of nodes must be one more than the number of edges.
653
+ 2. The degree sequence must be trivial or have only strictly positive
654
+ node degrees.
655
+
656
+ Parameters
657
+ ----------
658
+ deg_sequence : iterable
659
+ Iterable of node degrees.
660
+
661
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
662
+ Graph type to create. If graph instance, then cleared before populated.
663
+
664
+ Returns
665
+ -------
666
+ networkx.Graph
667
+ A tree with the given degree sequence.
668
+
669
+ Raises
670
+ ------
671
+ NetworkXError
672
+ If the degree sequence is not valid for a tree.
673
+
674
+ If `create_using` is directed.
675
+
676
+ See Also
677
+ --------
678
+ random_degree_sequence_graph
679
+ """
680
+ deg_sequence = list(deg_sequence)
681
+ valid, reason = nx.utils.is_valid_tree_degree_sequence(deg_sequence)
682
+ if not valid:
683
+ raise nx.NetworkXError(reason)
684
+
685
+ G = nx.empty_graph(0, create_using)
686
+ if G.is_directed():
687
+ raise nx.NetworkXError("Directed Graph not supported")
688
+
689
+ if deg_sequence == [0]:
690
+ G.add_node(0)
691
+ return G
692
+
693
+ # Sort all degrees greater than 1 in decreasing order.
694
+ #
695
+ # TODO Does this need to be sorted in reverse order?
696
+ deg = sorted((s for s in deg_sequence if s > 1), reverse=True)
697
+
698
+ # make path graph as backbone
699
+ n = len(deg) + 2
700
+ nx.add_path(G, range(n))
701
+ last = n
702
+
703
+ # add the leaves
704
+ for source in range(1, n - 1):
705
+ nedges = deg.pop() - 2
706
+ G.add_edges_from((source, target) for target in range(last, last + nedges))
707
+ last += nedges
708
+ return G
709
+
710
+
711
+ @py_random_state(1)
712
+ @nx._dispatchable(graphs=None, returns_graph=True)
713
+ def random_degree_sequence_graph(sequence, seed=None, tries=10):
714
+ r"""Returns a simple random graph with the given degree sequence.
715
+
716
+ If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the
717
+ algorithm produces almost uniform random graphs in $O(m d_m)$ time
718
+ where $m$ is the number of edges.
719
+
720
+ Parameters
721
+ ----------
722
+ sequence : list of integers
723
+ Sequence of degrees
724
+ seed : integer, random_state, or None (default)
725
+ Indicator of random number generation state.
726
+ See :ref:`Randomness<randomness>`.
727
+ tries : int, optional
728
+ Maximum number of tries to create a graph
729
+
730
+ Returns
731
+ -------
732
+ G : Graph
733
+ A graph with the specified degree sequence.
734
+ Nodes are labeled starting at 0 with an index
735
+ corresponding to the position in the sequence.
736
+
737
+ Raises
738
+ ------
739
+ NetworkXUnfeasible
740
+ If the degree sequence is not graphical.
741
+ NetworkXError
742
+ If a graph is not produced in specified number of tries
743
+
744
+ See Also
745
+ --------
746
+ is_graphical, configuration_model
747
+
748
+ Notes
749
+ -----
750
+ The generator algorithm [1]_ is not guaranteed to produce a graph.
751
+
752
+ References
753
+ ----------
754
+ .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
755
+ A sequential algorithm for generating random graphs.
756
+ Algorithmica, Volume 58, Number 4, 860-910,
757
+ DOI: 10.1007/s00453-009-9340-1
758
+
759
+ Examples
760
+ --------
761
+ >>> sequence = [1, 2, 2, 3]
762
+ >>> G = nx.random_degree_sequence_graph(sequence, seed=42)
763
+ >>> sorted(d for n, d in G.degree())
764
+ [1, 2, 2, 3]
765
+ """
766
+ DSRG = DegreeSequenceRandomGraph(sequence, seed)
767
+ for try_n in range(tries):
768
+ try:
769
+ return DSRG.generate()
770
+ except nx.NetworkXUnfeasible:
771
+ pass
772
+ raise nx.NetworkXError(f"failed to generate graph in {tries} tries")
773
+
774
+
775
+ class DegreeSequenceRandomGraph:
776
+ # class to generate random graphs with a given degree sequence
777
+ # use random_degree_sequence_graph()
778
+ def __init__(self, degree, rng):
779
+ self.rng = rng
780
+ self.degree = list(degree)
781
+ if not nx.is_graphical(self.degree):
782
+ raise nx.NetworkXUnfeasible("degree sequence is not graphical")
783
+ # node labels are integers 0,...,n-1
784
+ self.m = sum(self.degree) / 2.0 # number of edges
785
+ try:
786
+ self.dmax = max(self.degree) # maximum degree
787
+ except ValueError:
788
+ self.dmax = 0
789
+
790
+ def generate(self):
791
+ # remaining_degree is mapping from int->remaining degree
792
+ self.remaining_degree = dict(enumerate(self.degree))
793
+ # add all nodes to make sure we get isolated nodes
794
+ self.graph = nx.Graph()
795
+ self.graph.add_nodes_from(self.remaining_degree)
796
+ # remove zero degree nodes
797
+ for n, d in list(self.remaining_degree.items()):
798
+ if d == 0:
799
+ del self.remaining_degree[n]
800
+ if len(self.remaining_degree) > 0:
801
+ # build graph in three phases according to how many unmatched edges
802
+ self.phase1()
803
+ self.phase2()
804
+ self.phase3()
805
+ return self.graph
806
+
807
+ def update_remaining(self, u, v, aux_graph=None):
808
+ # decrement remaining nodes, modify auxiliary graph if in phase3
809
+ if aux_graph is not None:
810
+ # remove edges from auxiliary graph
811
+ aux_graph.remove_edge(u, v)
812
+ if self.remaining_degree[u] == 1:
813
+ del self.remaining_degree[u]
814
+ if aux_graph is not None:
815
+ aux_graph.remove_node(u)
816
+ else:
817
+ self.remaining_degree[u] -= 1
818
+ if self.remaining_degree[v] == 1:
819
+ del self.remaining_degree[v]
820
+ if aux_graph is not None:
821
+ aux_graph.remove_node(v)
822
+ else:
823
+ self.remaining_degree[v] -= 1
824
+
825
+ def p(self, u, v):
826
+ # degree probability
827
+ return 1 - self.degree[u] * self.degree[v] / (4.0 * self.m)
828
+
829
+ def q(self, u, v):
830
+ # remaining degree probability
831
+ norm = max(self.remaining_degree.values()) ** 2
832
+ return self.remaining_degree[u] * self.remaining_degree[v] / norm
833
+
834
+ def suitable_edge(self):
835
+ """Returns True if and only if an arbitrary remaining node can
836
+ potentially be joined with some other remaining node.
837
+
838
+ """
839
+ nodes = iter(self.remaining_degree)
840
+ u = next(nodes)
841
+ return any(v not in self.graph[u] for v in nodes)
842
+
843
+ def phase1(self):
844
+ # choose node pairs from (degree) weighted distribution
845
+ rem_deg = self.remaining_degree
846
+ while sum(rem_deg.values()) >= 2 * self.dmax**2:
847
+ u, v = sorted(random_weighted_sample(rem_deg, 2, self.rng))
848
+ if self.graph.has_edge(u, v):
849
+ continue
850
+ if self.rng.random() < self.p(u, v): # accept edge
851
+ self.graph.add_edge(u, v)
852
+ self.update_remaining(u, v)
853
+
854
+ def phase2(self):
855
+ # choose remaining nodes uniformly at random and use rejection sampling
856
+ remaining_deg = self.remaining_degree
857
+ rng = self.rng
858
+ while len(remaining_deg) >= 2 * self.dmax:
859
+ while True:
860
+ u, v = sorted(rng.sample(list(remaining_deg.keys()), 2))
861
+ if self.graph.has_edge(u, v):
862
+ continue
863
+ if rng.random() < self.q(u, v):
864
+ break
865
+ if rng.random() < self.p(u, v): # accept edge
866
+ self.graph.add_edge(u, v)
867
+ self.update_remaining(u, v)
868
+
869
+ def phase3(self):
870
+ # build potential remaining edges and choose with rejection sampling
871
+ potential_edges = combinations(self.remaining_degree, 2)
872
+ # build auxiliary graph of potential edges not already in graph
873
+ H = nx.Graph(
874
+ [(u, v) for (u, v) in potential_edges if not self.graph.has_edge(u, v)]
875
+ )
876
+ rng = self.rng
877
+ while self.remaining_degree:
878
+ if not self.suitable_edge():
879
+ raise nx.NetworkXUnfeasible("no suitable edges left")
880
+ while True:
881
+ u, v = sorted(rng.choice(list(H.edges())))
882
+ if rng.random() < self.q(u, v):
883
+ break
884
+ if rng.random() < self.p(u, v): # accept edge
885
+ self.graph.add_edge(u, v)
886
+ self.update_remaining(u, v, aux_graph=H)
venv/lib/python3.14/site-packages/networkx/generators/directed.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for some directed graphs, including growing network (GN) graphs and
3
+ scale-free graphs.
4
+
5
+ """
6
+
7
+ import numbers
8
+ from collections import Counter
9
+
10
+ import networkx as nx
11
+ from networkx.generators.classic import empty_graph
12
+ from networkx.utils import (
13
+ discrete_sequence,
14
+ np_random_state,
15
+ py_random_state,
16
+ weighted_choice,
17
+ )
18
+
19
+ __all__ = [
20
+ "gn_graph",
21
+ "gnc_graph",
22
+ "gnr_graph",
23
+ "random_k_out_graph",
24
+ "scale_free_graph",
25
+ ]
26
+
27
+
28
+ @py_random_state(3)
29
+ @nx._dispatchable(graphs=None, returns_graph=True)
30
+ def gn_graph(n, kernel=None, create_using=None, seed=None):
31
+ """Returns the growing network (GN) digraph with `n` nodes.
32
+
33
+ The GN graph is built by adding nodes one at a time with a link to one
34
+ previously added node. The target node for the link is chosen with
35
+ probability based on degree. The default attachment kernel is a linear
36
+ function of the degree of a node.
37
+
38
+ The graph is always a (directed) tree.
39
+
40
+ Parameters
41
+ ----------
42
+ n : int
43
+ The number of nodes for the generated graph.
44
+ kernel : function
45
+ The attachment kernel.
46
+ create_using : NetworkX graph constructor, optional (default DiGraph)
47
+ Graph type to create. If graph instance, then cleared before populated.
48
+ seed : integer, random_state, or None (default)
49
+ Indicator of random number generation state.
50
+ See :ref:`Randomness<randomness>`.
51
+
52
+ Examples
53
+ --------
54
+ To create the undirected GN graph, use the :meth:`~DiGraph.to_directed`
55
+ method::
56
+
57
+ >>> D = nx.gn_graph(10) # the GN graph
58
+ >>> G = D.to_undirected() # the undirected version
59
+
60
+ To specify an attachment kernel, use the `kernel` keyword argument::
61
+
62
+ >>> D = nx.gn_graph(10, kernel=lambda x: x**1.5) # A_k = k^1.5
63
+
64
+ References
65
+ ----------
66
+ .. [1] P. L. Krapivsky and S. Redner,
67
+ Organization of Growing Random Networks,
68
+ Phys. Rev. E, 63, 066123, 2001.
69
+ """
70
+ G = empty_graph(1, create_using, default=nx.DiGraph)
71
+ if not G.is_directed():
72
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
73
+
74
+ if kernel is None:
75
+
76
+ def kernel(x):
77
+ return x
78
+
79
+ if n == 1:
80
+ return G
81
+
82
+ G.add_edge(1, 0) # get started
83
+ ds = [1, 1] # degree sequence
84
+
85
+ for source in range(2, n):
86
+ # compute distribution from kernel and degree
87
+ dist = [kernel(d) for d in ds]
88
+ # choose target from discrete distribution
89
+ target = discrete_sequence(1, distribution=dist, seed=seed)[0]
90
+ G.add_edge(source, target)
91
+ ds.append(1) # the source has only one link (degree one)
92
+ ds[target] += 1 # add one to the target link degree
93
+ return G
94
+
95
+
96
+ @py_random_state(3)
97
+ @nx._dispatchable(graphs=None, returns_graph=True)
98
+ def gnr_graph(n, p, create_using=None, seed=None):
99
+ """Returns the growing network with redirection (GNR) digraph with `n`
100
+ nodes and redirection probability `p`.
101
+
102
+ The GNR graph is built by adding nodes one at a time with a link to one
103
+ previously added node. The previous target node is chosen uniformly at
104
+ random. With probability `p` the link is instead "redirected" to the
105
+ successor node of the target.
106
+
107
+ The graph is always a (directed) tree.
108
+
109
+ Parameters
110
+ ----------
111
+ n : int
112
+ The number of nodes for the generated graph.
113
+ p : float
114
+ The redirection probability.
115
+ create_using : NetworkX graph constructor, optional (default DiGraph)
116
+ Graph type to create. If graph instance, then cleared before populated.
117
+ seed : integer, random_state, or None (default)
118
+ Indicator of random number generation state.
119
+ See :ref:`Randomness<randomness>`.
120
+
121
+ Examples
122
+ --------
123
+ To create the undirected GNR graph, use the :meth:`~DiGraph.to_directed`
124
+ method::
125
+
126
+ >>> D = nx.gnr_graph(10, 0.5) # the GNR graph
127
+ >>> G = D.to_undirected() # the undirected version
128
+
129
+ References
130
+ ----------
131
+ .. [1] P. L. Krapivsky and S. Redner,
132
+ Organization of Growing Random Networks,
133
+ Phys. Rev. E, 63, 066123, 2001.
134
+ """
135
+ G = empty_graph(1, create_using, default=nx.DiGraph)
136
+ if not G.is_directed():
137
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
138
+
139
+ if n == 1:
140
+ return G
141
+
142
+ for source in range(1, n):
143
+ target = seed.randrange(0, source)
144
+ if seed.random() < p and target != 0:
145
+ target = next(G.successors(target))
146
+ G.add_edge(source, target)
147
+ return G
148
+
149
+
150
+ @py_random_state(2)
151
+ @nx._dispatchable(graphs=None, returns_graph=True)
152
+ def gnc_graph(n, create_using=None, seed=None):
153
+ """Returns the growing network with copying (GNC) digraph with `n` nodes.
154
+
155
+ The GNC graph is built by adding nodes one at a time with a link to one
156
+ previously added node (chosen uniformly at random) and to all of that
157
+ node's successors.
158
+
159
+ Parameters
160
+ ----------
161
+ n : int
162
+ The number of nodes for the generated graph.
163
+ create_using : NetworkX graph constructor, optional (default DiGraph)
164
+ Graph type to create. If graph instance, then cleared before populated.
165
+ seed : integer, random_state, or None (default)
166
+ Indicator of random number generation state.
167
+ See :ref:`Randomness<randomness>`.
168
+
169
+ References
170
+ ----------
171
+ .. [1] P. L. Krapivsky and S. Redner,
172
+ Network Growth by Copying,
173
+ Phys. Rev. E, 71, 036118, 2005k.},
174
+ """
175
+ G = empty_graph(1, create_using, default=nx.DiGraph)
176
+ if not G.is_directed():
177
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
178
+
179
+ if n == 1:
180
+ return G
181
+
182
+ for source in range(1, n):
183
+ target = seed.randrange(0, source)
184
+ for succ in G.successors(target):
185
+ G.add_edge(source, succ)
186
+ G.add_edge(source, target)
187
+ return G
188
+
189
+
190
+ @py_random_state(6)
191
+ @nx._dispatchable(graphs=None, returns_graph=True)
192
+ def scale_free_graph(
193
+ n,
194
+ alpha=0.41,
195
+ beta=0.54,
196
+ gamma=0.05,
197
+ delta_in=0.2,
198
+ delta_out=0,
199
+ seed=None,
200
+ initial_graph=None,
201
+ ):
202
+ """Returns a scale-free directed graph.
203
+
204
+ Parameters
205
+ ----------
206
+ n : integer
207
+ Number of nodes in graph
208
+ alpha : float
209
+ Probability for adding a new node connected to an existing node
210
+ chosen randomly according to the in-degree distribution.
211
+ beta : float
212
+ Probability for adding an edge between two existing nodes.
213
+ One existing node is chosen randomly according the in-degree
214
+ distribution and the other chosen randomly according to the out-degree
215
+ distribution.
216
+ gamma : float
217
+ Probability for adding a new node connected to an existing node
218
+ chosen randomly according to the out-degree distribution.
219
+ delta_in : float
220
+ Bias for choosing nodes from in-degree distribution.
221
+ delta_out : float
222
+ Bias for choosing nodes from out-degree distribution.
223
+ seed : integer, random_state, or None (default)
224
+ Indicator of random number generation state.
225
+ See :ref:`Randomness<randomness>`.
226
+ initial_graph : MultiDiGraph instance, optional
227
+ Build the scale-free graph starting from this initial MultiDiGraph,
228
+ if provided.
229
+
230
+ Returns
231
+ -------
232
+ MultiDiGraph
233
+
234
+ Examples
235
+ --------
236
+ Create a scale-free graph on one hundred nodes::
237
+
238
+ >>> G = nx.scale_free_graph(100)
239
+
240
+ Notes
241
+ -----
242
+ The sum of `alpha`, `beta`, and `gamma` must be 1.
243
+
244
+ References
245
+ ----------
246
+ .. [1] B. Bollobás, C. Borgs, J. Chayes, and O. Riordan,
247
+ Directed scale-free graphs,
248
+ Proceedings of the fourteenth annual ACM-SIAM Symposium on
249
+ Discrete Algorithms, 132--139, 2003.
250
+ """
251
+
252
+ def _choose_node(candidates, node_list, delta):
253
+ if delta > 0:
254
+ bias_sum = len(node_list) * delta
255
+ p_delta = bias_sum / (bias_sum + len(candidates))
256
+ if seed.random() < p_delta:
257
+ return seed.choice(node_list)
258
+ return seed.choice(candidates)
259
+
260
+ if initial_graph is not None and hasattr(initial_graph, "_adj"):
261
+ if not isinstance(initial_graph, nx.MultiDiGraph):
262
+ raise nx.NetworkXError("initial_graph must be a MultiDiGraph.")
263
+ G = initial_graph
264
+ else:
265
+ # Start with 3-cycle
266
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 0)])
267
+
268
+ if alpha <= 0:
269
+ raise ValueError("alpha must be > 0.")
270
+ if beta <= 0:
271
+ raise ValueError("beta must be > 0.")
272
+ if gamma <= 0:
273
+ raise ValueError("gamma must be > 0.")
274
+
275
+ if abs(alpha + beta + gamma - 1.0) >= 1e-9:
276
+ raise ValueError("alpha+beta+gamma must equal 1.")
277
+
278
+ if delta_in < 0:
279
+ raise ValueError("delta_in must be >= 0.")
280
+
281
+ if delta_out < 0:
282
+ raise ValueError("delta_out must be >= 0.")
283
+
284
+ # pre-populate degree states
285
+ vs = sum((count * [idx] for idx, count in G.out_degree()), [])
286
+ ws = sum((count * [idx] for idx, count in G.in_degree()), [])
287
+
288
+ # pre-populate node state
289
+ node_list = list(G.nodes())
290
+
291
+ # see if there already are number-based nodes
292
+ numeric_nodes = [n for n in node_list if isinstance(n, numbers.Number)]
293
+ if len(numeric_nodes) > 0:
294
+ # set cursor for new nodes appropriately
295
+ cursor = max(int(n.real) for n in numeric_nodes) + 1
296
+ else:
297
+ # or start at zero
298
+ cursor = 0
299
+
300
+ while len(G) < n:
301
+ r = seed.random()
302
+
303
+ # random choice in alpha,beta,gamma ranges
304
+ if r < alpha:
305
+ # alpha
306
+ # add new node v
307
+ v = cursor
308
+ cursor += 1
309
+ # also add to node state
310
+ node_list.append(v)
311
+ # choose w according to in-degree and delta_in
312
+ w = _choose_node(ws, node_list, delta_in)
313
+
314
+ elif r < alpha + beta:
315
+ # beta
316
+ # choose v according to out-degree and delta_out
317
+ v = _choose_node(vs, node_list, delta_out)
318
+ # choose w according to in-degree and delta_in
319
+ w = _choose_node(ws, node_list, delta_in)
320
+
321
+ else:
322
+ # gamma
323
+ # choose v according to out-degree and delta_out
324
+ v = _choose_node(vs, node_list, delta_out)
325
+ # add new node w
326
+ w = cursor
327
+ cursor += 1
328
+ # also add to node state
329
+ node_list.append(w)
330
+
331
+ # add edge to graph
332
+ G.add_edge(v, w)
333
+
334
+ # update degree states
335
+ vs.append(v)
336
+ ws.append(w)
337
+
338
+ return G
339
+
340
+
341
+ @py_random_state(4)
342
+ @nx._dispatchable(graphs=None, returns_graph=True)
343
+ def random_uniform_k_out_graph(n, k, self_loops=True, with_replacement=True, seed=None):
344
+ """Returns a random `k`-out graph with uniform attachment.
345
+
346
+ A random `k`-out graph with uniform attachment is a multidigraph
347
+ generated by the following algorithm. For each node *u*, choose
348
+ `k` nodes *v* uniformly at random (with replacement). Add a
349
+ directed edge joining *u* to *v*.
350
+
351
+ Parameters
352
+ ----------
353
+ n : int
354
+ The number of nodes in the returned graph.
355
+
356
+ k : int
357
+ The out-degree of each node in the returned graph.
358
+
359
+ self_loops : bool
360
+ If True, self-loops are allowed when generating the graph.
361
+
362
+ with_replacement : bool
363
+ If True, neighbors are chosen with replacement and the
364
+ returned graph will be a directed multigraph. Otherwise,
365
+ neighbors are chosen without replacement and the returned graph
366
+ will be a directed graph.
367
+
368
+ seed : integer, random_state, or None (default)
369
+ Indicator of random number generation state.
370
+ See :ref:`Randomness<randomness>`.
371
+
372
+ Returns
373
+ -------
374
+ NetworkX graph
375
+ A `k`-out-regular directed graph generated according to the
376
+ above algorithm. It will be a multigraph if and only if
377
+ `with_replacement` is True.
378
+
379
+ Raises
380
+ ------
381
+ ValueError
382
+ If `with_replacement` is False and `k` is greater than
383
+ `n`.
384
+
385
+ See also
386
+ --------
387
+ random_k_out_graph
388
+
389
+ Notes
390
+ -----
391
+ The return digraph or multidigraph may not be strongly connected, or
392
+ even weakly connected.
393
+
394
+ If `with_replacement` is True, this function is similar to
395
+ :func:`random_k_out_graph`, if that function had parameter `alpha`
396
+ set to positive infinity.
397
+
398
+ """
399
+ if with_replacement:
400
+ create_using = nx.MultiDiGraph()
401
+
402
+ def sample(v, nodes):
403
+ if not self_loops:
404
+ nodes = nodes - {v}
405
+ return (seed.choice(list(nodes)) for i in range(k))
406
+
407
+ else:
408
+ create_using = nx.DiGraph()
409
+
410
+ def sample(v, nodes):
411
+ if not self_loops:
412
+ nodes = nodes - {v}
413
+ return seed.sample(list(nodes), k)
414
+
415
+ G = nx.empty_graph(n, create_using)
416
+ nodes = set(G)
417
+ for u in G:
418
+ G.add_edges_from((u, v) for v in sample(u, nodes))
419
+ return G
420
+
421
+
422
+ @nx._dispatchable(graphs=None, returns_graph=True)
423
+ def random_k_out_graph(n, k, alpha, self_loops=True, seed=None):
424
+ """Returns a random `k`-out graph with preferential attachment.
425
+
426
+ .. versionchanged:: 3.5
427
+ Different implementations will be used based on whether NumPy is
428
+ available. See Notes for details.
429
+
430
+ A random `k`-out graph with preferential attachment is a
431
+ multidigraph generated by the following algorithm.
432
+
433
+ 1. Begin with an empty digraph, and initially set each node to have
434
+ weight `alpha`.
435
+ 2. Choose a node `u` with out-degree less than `k` uniformly at
436
+ random.
437
+ 3. Choose a node `v` from with probability proportional to its
438
+ weight.
439
+ 4. Add a directed edge from `u` to `v`, and increase the weight
440
+ of `v` by one.
441
+ 5. If each node has out-degree `k`, halt, otherwise repeat from
442
+ step 2.
443
+
444
+ For more information on this model of random graph, see [1]_.
445
+
446
+ Parameters
447
+ ----------
448
+ n : int
449
+ The number of nodes in the returned graph.
450
+
451
+ k : int
452
+ The out-degree of each node in the returned graph.
453
+
454
+ alpha : float
455
+ A positive :class:`float` representing the initial weight of
456
+ each vertex. A higher number means that in step 3 above, nodes
457
+ will be chosen more like a true uniformly random sample, and a
458
+ lower number means that nodes are more likely to be chosen as
459
+ their in-degree increases. If this parameter is not positive, a
460
+ :exc:`ValueError` is raised.
461
+
462
+ self_loops : bool
463
+ If True, self-loops are allowed when generating the graph.
464
+
465
+ seed : integer, random_state, or None (default)
466
+ Indicator of random number generation state.
467
+ See :ref:`Randomness<randomness>`.
468
+
469
+ Returns
470
+ -------
471
+ :class:`~networkx.classes.MultiDiGraph`
472
+ A `k`-out-regular multidigraph generated according to the above
473
+ algorithm.
474
+
475
+ Raises
476
+ ------
477
+ ValueError
478
+ If `alpha` is not positive.
479
+
480
+ Notes
481
+ -----
482
+ The returned multidigraph may not be strongly connected, or even
483
+ weakly connected.
484
+
485
+ `random_k_out_graph` has two implementations: an array-based formulation that
486
+ uses `numpy` (``_random_k_out_graph_numpy``), and a pure-Python
487
+ implementation (``_random_k_out_graph_python``).
488
+ The NumPy implementation is more performant, especially for large `n`, and is
489
+ therefore used by default. If NumPy is not installed in the environment,
490
+ then the pure Python implementation is executed.
491
+ However, you can explicitly control which implementation is executed by directly
492
+ calling the corresponding function::
493
+
494
+ # Use numpy if available, else Python
495
+ nx.random_k_out_graph(1000, 5, alpha=1)
496
+
497
+ # Use the numpy-based implementation (raises ImportError if numpy not installed)
498
+ nx.generators.directed._random_k_out_graph_numpy(1000, 5, alpha=1)
499
+
500
+ # Use the Python-based implementation
501
+ nx.generators.directed._random_k_out_graph_python(1000, 5, alpha=1)
502
+
503
+ References
504
+ ----------
505
+ .. [1] Peterson, Nicholas R., and Boris Pittel.
506
+ "Distance between two random `k`-out digraphs, with and without preferential attachment."
507
+ arXiv preprint arXiv:1311.5961 (2013) <https://arxiv.org/abs/1311.5961>.
508
+
509
+ """
510
+ if alpha < 0:
511
+ raise ValueError("alpha must be positive")
512
+ try: # Use numpy if available, otherwise fall back to pure Python implementation
513
+ return _random_k_out_graph_numpy(n, k, alpha, self_loops, seed)
514
+ except ImportError:
515
+ return _random_k_out_graph_python(n, k, alpha, self_loops, seed)
516
+
517
+
518
+ @np_random_state(4)
519
+ def _random_k_out_graph_numpy(n, k, alpha, self_loops=True, seed=None):
520
+ import numpy as np
521
+
522
+ G = nx.empty_graph(n, create_using=nx.MultiDiGraph)
523
+ nodes = np.arange(n)
524
+ remaining_mask = np.full(n, True)
525
+ weights = np.full(n, alpha)
526
+ total_weight = n * alpha
527
+ out_strengths = np.zeros(n)
528
+
529
+ for i in range(k * n):
530
+ u = seed.choice(nodes[remaining_mask])
531
+
532
+ if self_loops:
533
+ v = seed.choice(nodes, p=weights / total_weight)
534
+ else: # Ignore weight of u when selecting v
535
+ u_weight = weights[u]
536
+ weights[u] = 0
537
+ v = seed.choice(nodes, p=weights / (total_weight - u_weight))
538
+ weights[u] = u_weight
539
+
540
+ G.add_edge(u.item(), v.item())
541
+ weights[v] += 1
542
+ total_weight += 1
543
+ out_strengths[u] += 1
544
+ if out_strengths[u] == k:
545
+ remaining_mask[u] = False
546
+ return G
547
+
548
+
549
+ @py_random_state(4)
550
+ def _random_k_out_graph_python(n, k, alpha, self_loops=True, seed=None):
551
+ G = nx.empty_graph(n, create_using=nx.MultiDiGraph)
552
+ weights = Counter({v: alpha for v in G})
553
+ out_strengths = Counter({v: 0 for v in G})
554
+
555
+ for i in range(k * n):
556
+ u = seed.choice(list(out_strengths.keys()))
557
+ # If self-loops are not allowed, make the source node `u` have
558
+ # weight zero.
559
+ if not self_loops:
560
+ uweight = weights.pop(u)
561
+
562
+ v = weighted_choice(weights, seed=seed)
563
+
564
+ if not self_loops:
565
+ weights[u] = uweight
566
+
567
+ G.add_edge(u, v)
568
+ weights[v] += 1
569
+ out_strengths[u] += 1
570
+ if out_strengths[u] == k:
571
+ out_strengths.pop(u)
572
+ return G
venv/lib/python3.14/site-packages/networkx/generators/duplication.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating graphs based on the "duplication" method.
2
+
3
+ These graph generators start with a small initial graph then duplicate
4
+ nodes and (partially) duplicate their edges. These functions are
5
+ generally inspired by biological networks.
6
+
7
+ """
8
+
9
+ import networkx as nx
10
+ from networkx.utils import py_random_state
11
+ from networkx.utils.misc import check_create_using
12
+
13
+ __all__ = ["partial_duplication_graph", "duplication_divergence_graph"]
14
+
15
+
16
+ @py_random_state(4)
17
+ @nx._dispatchable(graphs=None, returns_graph=True)
18
+ def partial_duplication_graph(N, n, p, q, seed=None, *, create_using=None):
19
+ """Returns a random graph using the partial duplication model.
20
+
21
+ Parameters
22
+ ----------
23
+ N : int
24
+ The total number of nodes in the final graph.
25
+
26
+ n : int
27
+ The number of nodes in the initial clique.
28
+
29
+ p : float
30
+ The probability of joining each neighbor of a node to the
31
+ duplicate node. Must be a number in the between zero and one,
32
+ inclusive.
33
+
34
+ q : float
35
+ The probability of joining the source node to the duplicate
36
+ node. Must be a number in the between zero and one, inclusive.
37
+
38
+ seed : integer, random_state, or None (default)
39
+ Indicator of random number generation state.
40
+ See :ref:`Randomness<randomness>`.
41
+
42
+ create_using : Graph constructor, optional (default=nx.Graph)
43
+ Graph type to create. If graph instance, then cleared before populated.
44
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
45
+
46
+ Notes
47
+ -----
48
+ A graph of nodes is grown by creating a fully connected graph
49
+ of size `n`. The following procedure is then repeated until
50
+ a total of `N` nodes have been reached.
51
+
52
+ 1. A random node, *u*, is picked and a new node, *v*, is created.
53
+ 2. For each neighbor of *u* an edge from the neighbor to *v* is created
54
+ with probability `p`.
55
+ 3. An edge from *u* to *v* is created with probability `q`.
56
+
57
+ This algorithm appears in [1].
58
+
59
+ This implementation allows the possibility of generating
60
+ disconnected graphs.
61
+
62
+ References
63
+ ----------
64
+ .. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
65
+ randomly grown graphs." Journal of Applied Mathematics 2008.
66
+ <https://doi.org/10.1155/2008/190836>
67
+
68
+ """
69
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
70
+ if p < 0 or p > 1 or q < 0 or q > 1:
71
+ msg = "partial duplication graph must have 0 <= p, q <= 1."
72
+ raise nx.NetworkXError(msg)
73
+ if n > N:
74
+ raise nx.NetworkXError("partial duplication graph must have n <= N.")
75
+
76
+ G = nx.complete_graph(n, create_using)
77
+ for new_node in range(n, N):
78
+ # Pick a random vertex, u, already in the graph.
79
+ src_node = seed.randint(0, new_node - 1)
80
+
81
+ # Add a new vertex, v, to the graph.
82
+ G.add_node(new_node)
83
+
84
+ # For each neighbor of u...
85
+ for nbr_node in list(nx.all_neighbors(G, src_node)):
86
+ # Add the neighbor to v with probability p.
87
+ if seed.random() < p:
88
+ G.add_edge(new_node, nbr_node)
89
+
90
+ # Join v and u with probability q.
91
+ if seed.random() < q:
92
+ G.add_edge(new_node, src_node)
93
+ return G
94
+
95
+
96
+ @py_random_state(2)
97
+ @nx._dispatchable(graphs=None, returns_graph=True)
98
+ def duplication_divergence_graph(n, p, seed=None, *, create_using=None):
99
+ """Returns an undirected graph using the duplication-divergence model.
100
+
101
+ A graph of `n` nodes is created by duplicating the initial nodes
102
+ and retaining edges incident to the original nodes with a retention
103
+ probability `p`.
104
+
105
+ Parameters
106
+ ----------
107
+ n : int
108
+ The desired number of nodes in the graph.
109
+ p : float
110
+ The probability for retaining the edge of the replicated node.
111
+ seed : integer, random_state, or None (default)
112
+ Indicator of random number generation state.
113
+ See :ref:`Randomness<randomness>`.
114
+ create_using : Graph constructor, optional (default=nx.Graph)
115
+ Graph type to create. If graph instance, then cleared before populated.
116
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
117
+
118
+ Returns
119
+ -------
120
+ G : Graph
121
+
122
+ Raises
123
+ ------
124
+ NetworkXError
125
+ If `p` is not a valid probability.
126
+ If `n` is less than 2.
127
+
128
+ Notes
129
+ -----
130
+ This algorithm appears in [1].
131
+
132
+ This implementation disallows the possibility of generating
133
+ disconnected graphs.
134
+
135
+ References
136
+ ----------
137
+ .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
138
+ "Duplication-divergence model of protein interaction network",
139
+ Phys. Rev. E, 71, 061911, 2005.
140
+
141
+ """
142
+ if p > 1 or p < 0:
143
+ msg = f"NetworkXError p={p} is not in [0,1]."
144
+ raise nx.NetworkXError(msg)
145
+ if n < 2:
146
+ msg = "n must be greater than or equal to 2"
147
+ raise nx.NetworkXError(msg)
148
+
149
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
150
+ G = nx.empty_graph(create_using=create_using)
151
+
152
+ # Initialize the graph with two connected nodes.
153
+ G.add_edge(0, 1)
154
+ i = 2
155
+ while i < n:
156
+ # Choose a random node from current graph to duplicate.
157
+ random_node = seed.choice(list(G))
158
+ # Make the replica.
159
+ G.add_node(i)
160
+ # flag indicates whether at least one edge is connected on the replica.
161
+ flag = False
162
+ for nbr in G.neighbors(random_node):
163
+ if seed.random() < p:
164
+ # Link retention step.
165
+ G.add_edge(i, nbr)
166
+ flag = True
167
+ if not flag:
168
+ # Delete replica if no edges retained.
169
+ G.remove_node(i)
170
+ else:
171
+ # Successful duplication.
172
+ i += 1
173
+ return G
venv/lib/python3.14/site-packages/networkx/generators/ego.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ego graph.
3
+ """
4
+
5
+ __all__ = ["ego_graph"]
6
+
7
+ import networkx as nx
8
+
9
+
10
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
11
+ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
12
+ """Returns induced subgraph of neighbors centered at node n within
13
+ a given radius.
14
+
15
+ Parameters
16
+ ----------
17
+ G : graph
18
+ A NetworkX Graph or DiGraph
19
+
20
+ n : node
21
+ A single node
22
+
23
+ radius : number, optional
24
+ Include all neighbors of distance<=radius from n.
25
+
26
+ center : bool, optional
27
+ If False, do not include center node in graph
28
+
29
+ undirected : bool, optional
30
+ If True use both in- and out-neighbors of directed graphs.
31
+
32
+ distance : key, optional
33
+ Use specified edge data key as distance. For example, setting
34
+ distance='weight' will use the edge weight to measure the
35
+ distance from the node n.
36
+
37
+ Notes
38
+ -----
39
+ For directed graphs D this produces the "out" neighborhood
40
+ or successors. If you want the neighborhood of predecessors
41
+ first reverse the graph with D.reverse(). If you want both
42
+ directions use the keyword argument undirected=True.
43
+
44
+ Node, edge, and graph attributes are copied to the returned subgraph.
45
+ """
46
+ if undirected:
47
+ if distance is not None:
48
+ sp, _ = nx.single_source_dijkstra(
49
+ G.to_undirected(), n, cutoff=radius, weight=distance
50
+ )
51
+ else:
52
+ sp = dict(
53
+ nx.single_source_shortest_path_length(
54
+ G.to_undirected(), n, cutoff=radius
55
+ )
56
+ )
57
+ else:
58
+ if distance is not None:
59
+ sp, _ = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
60
+ else:
61
+ sp = nx.single_source_shortest_path_length(G, n, cutoff=radius)
62
+
63
+ H = G.subgraph(sp).copy()
64
+ if not center:
65
+ H.remove_node(n)
66
+ return H
venv/lib/python3.14/site-packages/networkx/generators/expanders.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides explicit constructions of expander graphs."""
2
+
3
+ import itertools
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "margulis_gabber_galil_graph",
9
+ "chordal_cycle_graph",
10
+ "paley_graph",
11
+ "maybe_regular_expander",
12
+ "maybe_regular_expander_graph",
13
+ "is_regular_expander",
14
+ "random_regular_expander_graph",
15
+ ]
16
+
17
+
18
+ # Other discrete torus expanders can be constructed by using the following edge
19
+ # sets. For more information, see Chapter 4, "Expander Graphs", in
20
+ # "Pseudorandomness", by Salil Vadhan.
21
+ #
22
+ # For a directed expander, add edges from (x, y) to:
23
+ #
24
+ # (x, y),
25
+ # ((x + 1) % n, y),
26
+ # (x, (y + 1) % n),
27
+ # (x, (x + y) % n),
28
+ # (-y % n, x)
29
+ #
30
+ # For an undirected expander, add the reverse edges.
31
+ #
32
+ # Also appearing in the paper of Gabber and Galil:
33
+ #
34
+ # (x, y),
35
+ # (x, (x + y) % n),
36
+ # (x, (x + y + 1) % n),
37
+ # ((x + y) % n, y),
38
+ # ((x + y + 1) % n, y)
39
+ #
40
+ # and:
41
+ #
42
+ # (x, y),
43
+ # ((x + 2*y) % n, y),
44
+ # ((x + (2*y + 1)) % n, y),
45
+ # ((x + (2*y + 2)) % n, y),
46
+ # (x, (y + 2*x) % n),
47
+ # (x, (y + (2*x + 1)) % n),
48
+ # (x, (y + (2*x + 2)) % n),
49
+ #
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def margulis_gabber_galil_graph(n, create_using=None):
52
+ r"""Returns the Margulis-Gabber-Galil undirected MultiGraph on `n^2` nodes.
53
+
54
+ The undirected MultiGraph is regular with degree `8`. Nodes are integer
55
+ pairs. The second-largest eigenvalue of the adjacency matrix of the graph
56
+ is at most `5 \sqrt{2}`, regardless of `n`.
57
+
58
+ Parameters
59
+ ----------
60
+ n : int
61
+ Determines the number of nodes in the graph: `n^2`.
62
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
63
+ Graph type to create. If graph instance, then cleared before populated.
64
+
65
+ Returns
66
+ -------
67
+ G : graph
68
+ The constructed undirected multigraph.
69
+
70
+ Raises
71
+ ------
72
+ NetworkXError
73
+ If the graph is directed or not a multigraph.
74
+
75
+ """
76
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
77
+ if G.is_directed() or not G.is_multigraph():
78
+ msg = "`create_using` must be an undirected multigraph."
79
+ raise nx.NetworkXError(msg)
80
+
81
+ for x, y in itertools.product(range(n), repeat=2):
82
+ for u, v in (
83
+ ((x + 2 * y) % n, y),
84
+ ((x + (2 * y + 1)) % n, y),
85
+ (x, (y + 2 * x) % n),
86
+ (x, (y + (2 * x + 1)) % n),
87
+ ):
88
+ G.add_edge((x, y), (u, v))
89
+ G.graph["name"] = f"margulis_gabber_galil_graph({n})"
90
+ return G
91
+
92
+
93
+ @nx._dispatchable(graphs=None, returns_graph=True)
94
+ def chordal_cycle_graph(p, create_using=None):
95
+ """Returns the chordal cycle graph on `p` nodes.
96
+
97
+ The returned graph is a cycle graph on `p` nodes with chords joining each
98
+ vertex `x` to its inverse modulo `p`. This graph is a (mildly explicit)
99
+ 3-regular expander [1]_ when viewed as a simple graph. The default return
100
+ type is a MultiGraph, which has 6-regular nodes due to the symmetric nature
101
+ of the edge additions. Use ``nx.Graph(nx.chordal_cycle_graph(p))`` to obtain
102
+ the 3-regular simple graph.
103
+
104
+ `p` *must* be a prime number.
105
+
106
+ Parameters
107
+ ----------
108
+ p : a prime number
109
+
110
+ The number of vertices in the graph. This also indicates where the
111
+ chordal edges in the cycle will be created.
112
+
113
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
114
+ Graph type to create. If graph instance, then cleared before populated.
115
+
116
+ Returns
117
+ -------
118
+ G : graph
119
+ The constructed undirected multigraph.
120
+
121
+ Raises
122
+ ------
123
+ NetworkXError
124
+
125
+ If `create_using` indicates directed or not a multigraph.
126
+
127
+ References
128
+ ----------
129
+
130
+ .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and
131
+ invariant measures", volume 125 of Progress in Mathematics.
132
+ Birkhäuser Verlag, Basel, 1994.
133
+
134
+ """
135
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
136
+ if G.is_directed() or not G.is_multigraph():
137
+ msg = "`create_using` must be an undirected multigraph."
138
+ raise nx.NetworkXError(msg)
139
+
140
+ for x in range(p):
141
+ left = (x - 1) % p
142
+ right = (x + 1) % p
143
+ # Here we apply Fermat's Little Theorem to compute the multiplicative
144
+ # inverse of x in Z/pZ. By Fermat's Little Theorem,
145
+ #
146
+ # x^p = x (mod p)
147
+ #
148
+ # Therefore,
149
+ #
150
+ # x * x^(p - 2) = 1 (mod p)
151
+ #
152
+ # The number 0 is a special case: we just let its inverse be itself.
153
+ chord = pow(x, p - 2, p) if x > 0 else 0
154
+ for y in (left, right, chord):
155
+ G.add_edge(x, y)
156
+ G.graph["name"] = f"chordal_cycle_graph({p})"
157
+ return G
158
+
159
+
160
+ @nx._dispatchable(graphs=None, returns_graph=True)
161
+ def paley_graph(p, create_using=None):
162
+ r"""Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
163
+
164
+ The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
165
+ if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
166
+
167
+ If $p \equiv 1 \pmod 4$, $-1$ is a square in
168
+ $\mathbb{Z}/p\mathbb{Z}$ and therefore $x-y$ is a square if and
169
+ only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
170
+
171
+ If $p \equiv 3 \pmod 4$, $-1$ is not a square in $\mathbb{Z}/p\mathbb{Z}$
172
+ and therefore either $x-y$ or $y-x$ is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
173
+
174
+ Note that a more general definition of Paley graphs extends this construction
175
+ to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of
176
+ $\mathbb{Z}/p\mathbb{Z}$.
177
+ This construction requires to compute squares in general finite fields and is
178
+ not what is implemented here (i.e `paley_graph(25)` does not return the true
179
+ Paley graph associated with $5^2$).
180
+
181
+ Parameters
182
+ ----------
183
+ p : int, an odd prime number.
184
+
185
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
186
+ Graph type to create. If graph instance, then cleared before populated.
187
+
188
+ Returns
189
+ -------
190
+ G : graph
191
+ The constructed directed graph.
192
+
193
+ Raises
194
+ ------
195
+ NetworkXError
196
+ If the graph is a multigraph.
197
+
198
+ References
199
+ ----------
200
+ Chapter 13 in B. Bollobas, Random Graphs. Second edition.
201
+ Cambridge Studies in Advanced Mathematics, 73.
202
+ Cambridge University Press, Cambridge (2001).
203
+ """
204
+ G = nx.empty_graph(0, create_using, default=nx.DiGraph)
205
+ if G.is_multigraph():
206
+ msg = "`create_using` cannot be a multigraph."
207
+ raise nx.NetworkXError(msg)
208
+
209
+ # Compute the squares in Z/pZ.
210
+ # Make it a set to uniquify (there are exactly (p-1)/2 squares in Z/pZ
211
+ # when is prime).
212
+ square_set = {(x**2) % p for x in range(1, p) if (x**2) % p != 0}
213
+
214
+ for x in range(p):
215
+ for x2 in square_set:
216
+ G.add_edge(x, (x + x2) % p)
217
+ G.graph["name"] = f"paley({p})"
218
+ return G
219
+
220
+
221
+ @nx.utils.decorators.np_random_state("seed")
222
+ @nx._dispatchable(graphs=None, returns_graph=True)
223
+ def maybe_regular_expander_graph(n, d, *, create_using=None, max_tries=100, seed=None):
224
+ r"""Utility for creating a random regular expander.
225
+
226
+ Returns a random $d$-regular graph on $n$ nodes which is an expander
227
+ graph with very good probability.
228
+
229
+ Parameters
230
+ ----------
231
+ n : int
232
+ The number of nodes.
233
+ d : int
234
+ The degree of each node.
235
+ create_using : Graph Instance or Constructor
236
+ Indicator of type of graph to return.
237
+ If a Graph-type instance, then clear and use it.
238
+ If a constructor, call it to create an empty graph.
239
+ Use the Graph constructor by default.
240
+ max_tries : int. (default: 100)
241
+ The number of allowed loops when generating each independent cycle
242
+ seed : (default: None)
243
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
244
+
245
+ Notes
246
+ -----
247
+ The nodes are numbered from $0$ to $n - 1$.
248
+
249
+ The graph is generated by taking $d / 2$ random independent cycles.
250
+
251
+ Joel Friedman proved that in this model the resulting
252
+ graph is an expander with probability
253
+ $1 - O(n^{-\tau})$ where $\tau = \lceil (\sqrt{d - 1}) / 2 \rceil - 1$. [1]_
254
+
255
+ Examples
256
+ --------
257
+ >>> G = nx.maybe_regular_expander_graph(n=200, d=6, seed=8020)
258
+
259
+ Returns
260
+ -------
261
+ G : graph
262
+ The constructed undirected graph.
263
+
264
+ Raises
265
+ ------
266
+ NetworkXError
267
+ If $d % 2 != 0$ as the degree must be even.
268
+ If $n - 1$ is less than $ 2d $ as the graph is complete at most.
269
+ If max_tries is reached
270
+
271
+ See Also
272
+ --------
273
+ is_regular_expander
274
+ random_regular_expander_graph
275
+
276
+ References
277
+ ----------
278
+ .. [1] Joel Friedman,
279
+ A Proof of Alon's Second Eigenvalue Conjecture and Related Problems, 2004
280
+ https://arxiv.org/abs/cs/0405020
281
+
282
+ """
283
+
284
+ import numpy as np
285
+
286
+ if n < 1:
287
+ raise nx.NetworkXError("n must be a positive integer")
288
+
289
+ if not (d >= 2):
290
+ raise nx.NetworkXError("d must be greater than or equal to 2")
291
+
292
+ if not (d % 2 == 0):
293
+ raise nx.NetworkXError("d must be even")
294
+
295
+ if not (n - 1 >= d):
296
+ raise nx.NetworkXError(
297
+ f"Need n-1>= d to have room for {d // 2} independent cycles with {n} nodes"
298
+ )
299
+
300
+ G = nx.empty_graph(n, create_using)
301
+
302
+ if n < 2:
303
+ return G
304
+
305
+ cycles = []
306
+ edges = set()
307
+
308
+ # Create d / 2 cycles
309
+ for i in range(d // 2):
310
+ iterations = max_tries
311
+ # Make sure the cycles are independent to have a regular graph
312
+ while len(edges) != (i + 1) * n:
313
+ iterations -= 1
314
+ # Faster than random.permutation(n) since there are only
315
+ # (n-1)! distinct cycles against n! permutations of size n
316
+ cycle = seed.permutation(n - 1).tolist()
317
+ cycle.append(n - 1)
318
+
319
+ new_edges = {
320
+ (u, v)
321
+ for u, v in nx.utils.pairwise(cycle, cyclic=True)
322
+ if (u, v) not in edges and (v, u) not in edges
323
+ }
324
+ # If the new cycle has no edges in common with previous cycles
325
+ # then add it to the list otherwise try again
326
+ if len(new_edges) == n:
327
+ cycles.append(cycle)
328
+ edges.update(new_edges)
329
+
330
+ if iterations == 0:
331
+ msg = "Too many iterations in maybe_regular_expander_graph"
332
+ raise nx.NetworkXError(msg)
333
+
334
+ G.add_edges_from(edges)
335
+
336
+ return G
337
+
338
+
339
+ def maybe_regular_expander(n, d, *, create_using=None, max_tries=100, seed=None):
340
+ """
341
+ .. deprecated:: 3.6
342
+ `maybe_regular_expander` is a deprecated alias
343
+ for `maybe_regular_expander_graph`.
344
+ Use `maybe_regular_expander_graph` instead.
345
+ """
346
+ import warnings
347
+
348
+ warnings.warn(
349
+ "maybe_regular_expander is deprecated, "
350
+ "use `maybe_regular_expander_graph` instead.",
351
+ category=DeprecationWarning,
352
+ stacklevel=2,
353
+ )
354
+ return maybe_regular_expander_graph(
355
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
356
+ )
357
+
358
+
359
+ @nx.utils.not_implemented_for("directed")
360
+ @nx.utils.not_implemented_for("multigraph")
361
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
362
+ def is_regular_expander(G, *, epsilon=0):
363
+ r"""Determines whether the graph G is a regular expander. [1]_
364
+
365
+ An expander graph is a sparse graph with strong connectivity properties.
366
+
367
+ More precisely, this helper checks whether the graph is a
368
+ regular $(n, d, \lambda)$-expander with $\lambda$ close to
369
+ the Alon-Boppana bound and given by
370
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$. [2]_
371
+
372
+ In the case where $\epsilon = 0$ then if the graph successfully passes the test
373
+ it is a Ramanujan graph. [3]_
374
+
375
+ A Ramanujan graph has spectral gap almost as large as possible, which makes them
376
+ excellent expanders.
377
+
378
+ Parameters
379
+ ----------
380
+ G : NetworkX graph
381
+ epsilon : int, float, default=0
382
+
383
+ Returns
384
+ -------
385
+ bool
386
+ Whether the given graph is a regular $(n, d, \lambda)$-expander
387
+ where $\lambda = 2 \sqrt{d - 1} + \epsilon$.
388
+
389
+ Examples
390
+ --------
391
+ >>> G = nx.random_regular_expander_graph(20, 4)
392
+ >>> nx.is_regular_expander(G)
393
+ True
394
+
395
+ See Also
396
+ --------
397
+ maybe_regular_expander_graph
398
+ random_regular_expander_graph
399
+
400
+ References
401
+ ----------
402
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
403
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
404
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
405
+
406
+ """
407
+
408
+ import numpy as np
409
+ import scipy as sp
410
+
411
+ if epsilon < 0:
412
+ raise nx.NetworkXError("epsilon must be non negative")
413
+
414
+ if not nx.is_regular(G):
415
+ return False
416
+
417
+ _, d = nx.utils.arbitrary_element(G.degree)
418
+
419
+ A = nx.adjacency_matrix(G, dtype=float)
420
+ lams = sp.sparse.linalg.eigsh(A, which="LM", k=2, return_eigenvectors=False)
421
+
422
+ # lambda2 is the second biggest eigenvalue
423
+ lambda2 = min(lams)
424
+
425
+ # Use bool() to convert numpy scalar to Python Boolean
426
+ return bool(abs(lambda2) < 2 * np.sqrt(d - 1) + epsilon)
427
+
428
+
429
+ @nx.utils.decorators.np_random_state("seed")
430
+ @nx._dispatchable(graphs=None, returns_graph=True)
431
+ def random_regular_expander_graph(
432
+ n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None
433
+ ):
434
+ r"""Returns a random regular expander graph on $n$ nodes with degree $d$.
435
+
436
+ An expander graph is a sparse graph with strong connectivity properties. [1]_
437
+
438
+ More precisely the returned graph is a $(n, d, \lambda)$-expander with
439
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
440
+
441
+ In the case where $\epsilon = 0$ it returns a Ramanujan graph.
442
+ A Ramanujan graph has spectral gap almost as large as possible,
443
+ which makes them excellent expanders. [3]_
444
+
445
+ Parameters
446
+ ----------
447
+ n : int
448
+ The number of nodes.
449
+ d : int
450
+ The degree of each node.
451
+ epsilon : int, float, default=0
452
+ max_tries : int, (default: 100)
453
+ The number of allowed loops,
454
+ also used in the `maybe_regular_expander_graph` utility
455
+ seed : (default: None)
456
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
457
+
458
+ Raises
459
+ ------
460
+ NetworkXError
461
+ If max_tries is reached
462
+
463
+ Examples
464
+ --------
465
+ >>> G = nx.random_regular_expander_graph(20, 4)
466
+ >>> nx.is_regular_expander(G)
467
+ True
468
+
469
+ Notes
470
+ -----
471
+ This loops over `maybe_regular_expander_graph` and can be slow when
472
+ $n$ is too big or $\epsilon$ too small.
473
+
474
+ See Also
475
+ --------
476
+ maybe_regular_expander_graph
477
+ is_regular_expander
478
+
479
+ References
480
+ ----------
481
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
482
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
483
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
484
+
485
+ """
486
+ G = maybe_regular_expander_graph(
487
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
488
+ )
489
+ iterations = max_tries
490
+
491
+ while not is_regular_expander(G, epsilon=epsilon):
492
+ iterations -= 1
493
+ G = maybe_regular_expander_graph(
494
+ n=n, d=d, create_using=create_using, max_tries=max_tries, seed=seed
495
+ )
496
+
497
+ if iterations == 0:
498
+ raise nx.NetworkXError(
499
+ "Too many iterations in random_regular_expander_graph"
500
+ )
501
+
502
+ return G
venv/lib/python3.14/site-packages/networkx/generators/geometric.py ADDED
@@ -0,0 +1,1037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for geometric graphs."""
2
+
3
+ import math
4
+ from bisect import bisect_left
5
+ from itertools import accumulate, combinations, product
6
+
7
+ import networkx as nx
8
+ from networkx.utils import py_random_state
9
+
10
+ __all__ = [
11
+ "geometric_edges",
12
+ "geographical_threshold_graph",
13
+ "navigable_small_world_graph",
14
+ "random_geometric_graph",
15
+ "soft_random_geometric_graph",
16
+ "thresholded_random_geometric_graph",
17
+ "waxman_graph",
18
+ "geometric_soft_configuration_graph",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable(node_attrs="pos_name")
23
+ def geometric_edges(G, radius, p=2, *, pos_name="pos"):
24
+ """Returns edge list of node pairs within `radius` of each other.
25
+
26
+ Parameters
27
+ ----------
28
+ G : networkx graph
29
+ The graph from which to generate the edge list. The nodes in `G` should
30
+ have an attribute ``pos`` corresponding to the node position, which is
31
+ used to compute the distance to other nodes.
32
+ radius : scalar
33
+ The distance threshold. Edges are included in the edge list if the
34
+ distance between the two nodes is less than `radius`.
35
+ pos_name : string, default="pos"
36
+ The name of the node attribute which represents the position of each
37
+ node in 2D coordinates. Every node in the Graph must have this attribute.
38
+ p : scalar, default=2
39
+ The `Minkowski distance metric
40
+ <https://en.wikipedia.org/wiki/Minkowski_distance>`_ used to compute
41
+ distances. The default value is 2, i.e. Euclidean distance.
42
+
43
+ Returns
44
+ -------
45
+ edges : list
46
+ List of edges whose distances are less than `radius`
47
+
48
+ Notes
49
+ -----
50
+ Radius uses Minkowski distance metric `p`.
51
+ If scipy is available, `scipy.spatial.cKDTree` is used to speed computation.
52
+
53
+ Examples
54
+ --------
55
+ Create a graph with nodes that have a "pos" attribute representing 2D
56
+ coordinates.
57
+
58
+ >>> G = nx.Graph()
59
+ >>> G.add_nodes_from(
60
+ ... [
61
+ ... (0, {"pos": (0, 0)}),
62
+ ... (1, {"pos": (3, 0)}),
63
+ ... (2, {"pos": (8, 0)}),
64
+ ... ]
65
+ ... )
66
+ >>> nx.geometric_edges(G, radius=1)
67
+ []
68
+ >>> nx.geometric_edges(G, radius=4)
69
+ [(0, 1)]
70
+ >>> nx.geometric_edges(G, radius=6)
71
+ [(0, 1), (1, 2)]
72
+ >>> nx.geometric_edges(G, radius=9)
73
+ [(0, 1), (0, 2), (1, 2)]
74
+ """
75
+ # Input validation - every node must have a "pos" attribute
76
+ for n, pos in G.nodes(data=pos_name):
77
+ if pos is None:
78
+ raise nx.NetworkXError(
79
+ f"Node {n} (and all nodes) must have a '{pos_name}' attribute."
80
+ )
81
+
82
+ # NOTE: See _geometric_edges for the actual implementation. The reason this
83
+ # is split into two functions is to avoid the overhead of input validation
84
+ # every time the function is called internally in one of the other
85
+ # geometric generators
86
+ return _geometric_edges(G, radius, p, pos_name)
87
+
88
+
89
+ def _geometric_edges(G, radius, p, pos_name):
90
+ """
91
+ Implements `geometric_edges` without input validation. See `geometric_edges`
92
+ for complete docstring.
93
+ """
94
+ nodes_pos = G.nodes(data=pos_name)
95
+ try:
96
+ import scipy as sp
97
+ except ImportError:
98
+ # no scipy KDTree so compute by for-loop
99
+ radius_p = radius**p
100
+ edges = [
101
+ (u, v)
102
+ for (u, pu), (v, pv) in combinations(nodes_pos, 2)
103
+ if sum(abs(a - b) ** p for a, b in zip(pu, pv)) <= radius_p
104
+ ]
105
+ return edges
106
+ # scipy KDTree is available
107
+ nodes, coords = list(zip(*nodes_pos))
108
+ kdtree = sp.spatial.cKDTree(coords) # Cannot provide generator.
109
+ edge_indexes = kdtree.query_pairs(radius, p)
110
+ edges = [(nodes[u], nodes[v]) for u, v in sorted(edge_indexes)]
111
+ return edges
112
+
113
+
114
+ @py_random_state(5)
115
+ @nx._dispatchable(graphs=None, returns_graph=True)
116
+ def random_geometric_graph(
117
+ n, radius, dim=2, pos=None, p=2, seed=None, *, pos_name="pos"
118
+ ):
119
+ """Returns a random geometric graph in the unit cube of dimensions `dim`.
120
+
121
+ The random geometric graph model places `n` nodes uniformly at
122
+ random in the unit cube. Two nodes are joined by an edge if the
123
+ distance between the nodes is at most `radius`.
124
+
125
+ Edges are determined using a KDTree when SciPy is available.
126
+ This reduces the time complexity from $O(n^2)$ to $O(n)$.
127
+
128
+ Parameters
129
+ ----------
130
+ n : int or iterable
131
+ Number of nodes or iterable of nodes
132
+ radius: float
133
+ Distance threshold value
134
+ dim : int, optional
135
+ Dimension of graph
136
+ pos : dict, optional
137
+ A dictionary keyed by node with node positions as values.
138
+ p : float, optional
139
+ Which Minkowski distance metric to use. `p` has to meet the condition
140
+ ``1 <= p <= infinity``.
141
+
142
+ If this argument is not specified, the :math:`L^2` metric
143
+ (the Euclidean distance metric), p = 2 is used.
144
+ This should not be confused with the `p` of an Erdős-Rényi random
145
+ graph, which represents probability.
146
+ seed : integer, random_state, or None (default)
147
+ Indicator of random number generation state.
148
+ See :ref:`Randomness<randomness>`.
149
+ pos_name : string, default="pos"
150
+ The name of the node attribute which represents the position
151
+ in 2D coordinates of the node in the returned graph.
152
+
153
+ Returns
154
+ -------
155
+ Graph
156
+ A random geometric graph, undirected and without self-loops.
157
+ Each node has a node attribute ``'pos'`` that stores the
158
+ position of that node in Euclidean space as provided by the
159
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
160
+ generated by this function.
161
+
162
+ Examples
163
+ --------
164
+ Create a random geometric graph on twenty nodes where nodes are joined by
165
+ an edge if their distance is at most 0.1::
166
+
167
+ >>> G = nx.random_geometric_graph(20, 0.1)
168
+
169
+ Notes
170
+ -----
171
+ This uses a *k*-d tree to build the graph.
172
+
173
+ The `pos` keyword argument can be used to specify node positions so you
174
+ can create an arbitrary distribution and domain for positions.
175
+
176
+ For example, to use a 2D Gaussian distribution of node positions with mean
177
+ (0, 0) and standard deviation 2::
178
+
179
+ >>> import random
180
+ >>> n = 20
181
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
182
+ >>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
183
+
184
+ References
185
+ ----------
186
+ .. [1] Penrose, Mathew, *Random Geometric Graphs*,
187
+ Oxford Studies in Probability, 5, 2003.
188
+
189
+ """
190
+ # TODO Is this function just a special case of the geographical
191
+ # threshold graph?
192
+ #
193
+ # half_radius = {v: radius / 2 for v in n}
194
+ # return geographical_threshold_graph(nodes, theta=1, alpha=1,
195
+ # weight=half_radius)
196
+ #
197
+ G = nx.empty_graph(n)
198
+ # If no positions are provided, choose uniformly random vectors in
199
+ # Euclidean space of the specified dimension.
200
+ if pos is None:
201
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
202
+ nx.set_node_attributes(G, pos, pos_name)
203
+
204
+ G.add_edges_from(_geometric_edges(G, radius, p, pos_name))
205
+ return G
206
+
207
+
208
+ @py_random_state(6)
209
+ @nx._dispatchable(graphs=None, returns_graph=True)
210
+ def soft_random_geometric_graph(
211
+ n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name="pos"
212
+ ):
213
+ r"""Returns a soft random geometric graph in the unit cube.
214
+
215
+ The soft random geometric graph [1] model places `n` nodes uniformly at
216
+ random in the unit cube in dimension `dim`. Two nodes of distance, `dist`,
217
+ computed by the `p`-Minkowski distance metric are joined by an edge with
218
+ probability `p_dist` if the computed distance metric value of the nodes
219
+ is at most `radius`, otherwise they are not joined.
220
+
221
+ Edges within `radius` of each other are determined using a KDTree when
222
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
223
+ to :math:`O(n)`.
224
+
225
+ Parameters
226
+ ----------
227
+ n : int or iterable
228
+ Number of nodes or iterable of nodes
229
+ radius: float
230
+ Distance threshold value
231
+ dim : int, optional
232
+ Dimension of graph
233
+ pos : dict, optional
234
+ A dictionary keyed by node with node positions as values.
235
+ p : float, optional
236
+ Which Minkowski distance metric to use.
237
+ `p` has to meet the condition ``1 <= p <= infinity``.
238
+
239
+ If this argument is not specified, the :math:`L^2` metric
240
+ (the Euclidean distance metric), p = 2 is used.
241
+
242
+ This should not be confused with the `p` of an Erdős-Rényi random
243
+ graph, which represents probability.
244
+ p_dist : function, optional
245
+ A probability density function computing the probability of
246
+ connecting two nodes that are of distance, dist, computed by the
247
+ Minkowski distance metric. The probability density function, `p_dist`,
248
+ must be any function that takes the metric value as input
249
+ and outputs a single probability value between 0-1. The `scipy.stats`
250
+ package has many probability distribution functions implemented and
251
+ tools for custom probability distribution definitions [2], and passing
252
+ the .pdf method of `scipy.stats` distributions can be used here. If the
253
+ probability function, `p_dist`, is not supplied, the default function
254
+ is an exponential distribution with rate parameter :math:`\lambda=1`.
255
+ seed : integer, random_state, or None (default)
256
+ Indicator of random number generation state.
257
+ See :ref:`Randomness<randomness>`.
258
+ pos_name : string, default="pos"
259
+ The name of the node attribute which represents the position
260
+ in 2D coordinates of the node in the returned graph.
261
+
262
+ Returns
263
+ -------
264
+ Graph
265
+ A soft random geometric graph, undirected and without self-loops.
266
+ Each node has a node attribute ``'pos'`` that stores the
267
+ position of that node in Euclidean space as provided by the
268
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
269
+ generated by this function.
270
+
271
+ Notes
272
+ -----
273
+ This uses a *k*-d tree to build the graph.
274
+
275
+ References
276
+ ----------
277
+ .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs."
278
+ The Annals of Applied Probability 26.2 (2016): 986-1028.
279
+
280
+ Examples
281
+ --------
282
+ Default Graph:
283
+
284
+ >>> G = nx.soft_random_geometric_graph(50, 0.2)
285
+
286
+ Custom Graph:
287
+
288
+ The `pos` keyword argument can be used to specify node positions so you
289
+ can create an arbitrary distribution and domain for positions.
290
+
291
+ The `scipy.stats` package can be used to define the probability distribution
292
+ with the ``.pdf`` method used as `p_dist`.
293
+
294
+ For example, create a soft random geometric graph on 100 nodes using a 2D
295
+ Gaussian distribution of node positions with mean (0, 0) and standard deviation 2,
296
+ where nodes are joined by an edge with probability computed from an
297
+ exponential distribution with rate parameter :math:`\lambda=1` if their
298
+ Euclidean distance is at most 0.2.
299
+
300
+ >>> import random
301
+ >>> from scipy.stats import expon
302
+ >>> n = 100
303
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
304
+ >>> p_dist = lambda x: expon.pdf(x, scale=1)
305
+ >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist)
306
+
307
+ """
308
+ G = nx.empty_graph(n)
309
+ G.name = f"soft_random_geometric_graph({n}, {radius}, {dim})"
310
+ # If no positions are provided, choose uniformly random vectors in
311
+ # Euclidean space of the specified dimension.
312
+ if pos is None:
313
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
314
+ nx.set_node_attributes(G, pos, pos_name)
315
+
316
+ # if p_dist function not supplied the default function is an exponential
317
+ # distribution with rate parameter :math:`\lambda=1`.
318
+ if p_dist is None:
319
+
320
+ def p_dist(dist):
321
+ return math.exp(-dist)
322
+
323
+ def should_join(edge):
324
+ u, v = edge
325
+ dist = (sum(abs(a - b) ** p for a, b in zip(pos[u], pos[v]))) ** (1 / p)
326
+ return seed.random() < p_dist(dist)
327
+
328
+ G.add_edges_from(filter(should_join, _geometric_edges(G, radius, p, pos_name)))
329
+ return G
330
+
331
+
332
+ @py_random_state(7)
333
+ @nx._dispatchable(graphs=None, returns_graph=True)
334
+ def geographical_threshold_graph(
335
+ n,
336
+ theta,
337
+ dim=2,
338
+ pos=None,
339
+ weight=None,
340
+ metric=None,
341
+ p_dist=None,
342
+ seed=None,
343
+ *,
344
+ pos_name="pos",
345
+ weight_name="weight",
346
+ ):
347
+ r"""Returns a geographical threshold graph.
348
+
349
+ The geographical threshold graph model places $n$ nodes uniformly at
350
+ random in a rectangular domain. Each node $u$ is assigned a weight
351
+ $w_u$. Two nodes $u$ and $v$ are joined by an edge if
352
+
353
+ .. math::
354
+
355
+ (w_u + w_v)p_{dist}(r) \ge \theta
356
+
357
+ where `r` is the distance between `u` and `v`, `p_dist` is any function of
358
+ `r`, and :math:`\theta` as the threshold parameter. `p_dist` is used to
359
+ give weight to the distance between nodes when deciding whether or not
360
+ they should be connected. The larger `p_dist` is, the more prone nodes
361
+ separated by `r` are to be connected, and vice versa.
362
+
363
+ Parameters
364
+ ----------
365
+ n : int or iterable
366
+ Number of nodes or iterable of nodes
367
+ theta: float
368
+ Threshold value
369
+ dim : int, optional
370
+ Dimension of graph
371
+ pos : dict
372
+ Node positions as a dictionary of tuples keyed by node.
373
+ weight : dict
374
+ Node weights as a dictionary of numbers keyed by node.
375
+ metric : function
376
+ A metric on vectors of numbers (represented as lists or
377
+ tuples). This must be a function that accepts two lists (or
378
+ tuples) as input and yields a number as output. The function
379
+ must also satisfy the four requirements of a `metric`_.
380
+ Specifically, if $d$ is the function and $x$, $y$,
381
+ and $z$ are vectors in the graph, then $d$ must satisfy
382
+
383
+ 1. $d(x, y) \ge 0$,
384
+ 2. $d(x, y) = 0$ if and only if $x = y$,
385
+ 3. $d(x, y) = d(y, x)$,
386
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
387
+
388
+ If this argument is not specified, the Euclidean distance metric is
389
+ used.
390
+
391
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
392
+ p_dist : function, optional
393
+ Any function used to give weight to the distance between nodes when
394
+ deciding whether or not they should be connected. `p_dist` was
395
+ originally conceived as a probability density function giving the
396
+ probability of connecting two nodes that are of metric distance `r`
397
+ apart. The implementation here allows for more arbitrary definitions
398
+ of `p_dist` that do not need to correspond to valid probability
399
+ density functions. The :mod:`scipy.stats` package has many
400
+ probability density functions implemented and tools for custom
401
+ probability density definitions, and passing the ``.pdf`` method of
402
+ `scipy.stats` distributions can be used here. If ``p_dist=None``
403
+ (the default), the exponential function :math:`r^{-2}` is used.
404
+ seed : integer, random_state, or None (default)
405
+ Indicator of random number generation state.
406
+ See :ref:`Randomness<randomness>`.
407
+ pos_name : string, default="pos"
408
+ The name of the node attribute which represents the position
409
+ in 2D coordinates of the node in the returned graph.
410
+ weight_name : string, default="weight"
411
+ The name of the node attribute which represents the weight
412
+ of the node in the returned graph.
413
+
414
+ Returns
415
+ -------
416
+ Graph
417
+ A random geographic threshold graph, undirected and without
418
+ self-loops.
419
+
420
+ Each node has a node attribute ``pos`` that stores the
421
+ position of that node in Euclidean space as provided by the
422
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
423
+ generated by this function. Similarly, each node has a node
424
+ attribute ``weight`` that stores the weight of that node as
425
+ provided or as generated.
426
+
427
+ Examples
428
+ --------
429
+ Specify an alternate distance metric using the ``metric`` keyword
430
+ argument. For example, to use the `taxicab metric`_ instead of the
431
+ default `Euclidean metric`_::
432
+
433
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
434
+ >>> G = nx.geographical_threshold_graph(10, 0.1, metric=dist)
435
+
436
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
437
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
438
+
439
+ Notes
440
+ -----
441
+ If weights are not specified they are assigned to nodes by drawing randomly
442
+ from the exponential distribution with rate parameter $\lambda=1$.
443
+ To specify weights from a different distribution, use the `weight` keyword
444
+ argument::
445
+
446
+ >>> import random
447
+ >>> n = 20
448
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
449
+ >>> G = nx.geographical_threshold_graph(20, 50, weight=w)
450
+
451
+ If node positions are not specified they are randomly assigned from the
452
+ uniform distribution.
453
+
454
+ References
455
+ ----------
456
+ .. [1] Masuda, N., Miwa, H., Konno, N.:
457
+ Geographical threshold graphs with small-world and scale-free
458
+ properties.
459
+ Physical Review E 71, 036108 (2005)
460
+ .. [2] Milan Bradonjić, Aric Hagberg and Allon G. Percus,
461
+ Giant component and connectivity in geographical threshold graphs,
462
+ in Algorithms and Models for the Web-Graph (WAW 2007),
463
+ Antony Bonato and Fan Chung (Eds), pp. 209--216, 2007
464
+ """
465
+ G = nx.empty_graph(n)
466
+ # If no weights are provided, choose them from an exponential
467
+ # distribution.
468
+ if weight is None:
469
+ weight = {v: seed.expovariate(1) for v in G}
470
+ # If no positions are provided, choose uniformly random vectors in
471
+ # Euclidean space of the specified dimension.
472
+ if pos is None:
473
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
474
+ # If no distance metric is provided, use Euclidean distance.
475
+ if metric is None:
476
+ metric = math.dist
477
+ nx.set_node_attributes(G, weight, weight_name)
478
+ nx.set_node_attributes(G, pos, pos_name)
479
+
480
+ # if p_dist is not supplied, use default r^-2
481
+ if p_dist is None:
482
+
483
+ def p_dist(r):
484
+ return r**-2
485
+
486
+ # Returns ``True`` if and only if the nodes whose attributes are
487
+ # ``du`` and ``dv`` should be joined, according to the threshold
488
+ # condition.
489
+ def should_join(pair):
490
+ u, v = pair
491
+ u_pos, v_pos = pos[u], pos[v]
492
+ u_weight, v_weight = weight[u], weight[v]
493
+ return (u_weight + v_weight) * p_dist(metric(u_pos, v_pos)) >= theta
494
+
495
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
496
+ return G
497
+
498
+
499
+ @py_random_state(6)
500
+ @nx._dispatchable(graphs=None, returns_graph=True)
501
+ def waxman_graph(
502
+ n,
503
+ beta=0.4,
504
+ alpha=0.1,
505
+ L=None,
506
+ domain=(0, 0, 1, 1),
507
+ metric=None,
508
+ seed=None,
509
+ *,
510
+ pos_name="pos",
511
+ ):
512
+ r"""Returns a Waxman random graph.
513
+
514
+ The Waxman random graph model places `n` nodes uniformly at random
515
+ in a rectangular domain. Each pair of nodes at distance `d` is
516
+ joined by an edge with probability
517
+
518
+ .. math::
519
+ p = \beta \exp(-d / \alpha L).
520
+
521
+ This function implements both Waxman models, using the `L` keyword
522
+ argument.
523
+
524
+ * Waxman-1: if `L` is not specified, it is set to be the maximum distance
525
+ between any pair of nodes.
526
+ * Waxman-2: if `L` is specified, the distance between a pair of nodes is
527
+ chosen uniformly at random from the interval `[0, L]`.
528
+
529
+ Parameters
530
+ ----------
531
+ n : int or iterable
532
+ Number of nodes or iterable of nodes
533
+ beta: float
534
+ Model parameter
535
+ alpha: float
536
+ Model parameter
537
+ L : float, optional
538
+ Maximum distance between nodes. If not specified, the actual distance
539
+ is calculated.
540
+ domain : four-tuple of numbers, optional
541
+ Domain size, given as a tuple of the form `(x_min, y_min, x_max,
542
+ y_max)`.
543
+ metric : function
544
+ A metric on vectors of numbers (represented as lists or
545
+ tuples). This must be a function that accepts two lists (or
546
+ tuples) as input and yields a number as output. The function
547
+ must also satisfy the four requirements of a `metric`_.
548
+ Specifically, if $d$ is the function and $x$, $y$,
549
+ and $z$ are vectors in the graph, then $d$ must satisfy
550
+
551
+ 1. $d(x, y) \ge 0$,
552
+ 2. $d(x, y) = 0$ if and only if $x = y$,
553
+ 3. $d(x, y) = d(y, x)$,
554
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
555
+
556
+ If this argument is not specified, the Euclidean distance metric is
557
+ used.
558
+
559
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
560
+
561
+ seed : integer, random_state, or None (default)
562
+ Indicator of random number generation state.
563
+ See :ref:`Randomness<randomness>`.
564
+ pos_name : string, default="pos"
565
+ The name of the node attribute which represents the position
566
+ in 2D coordinates of the node in the returned graph.
567
+
568
+ Returns
569
+ -------
570
+ Graph
571
+ A random Waxman graph, undirected and without self-loops. Each
572
+ node has a node attribute ``'pos'`` that stores the position of
573
+ that node in Euclidean space as generated by this function.
574
+
575
+ Examples
576
+ --------
577
+ Specify an alternate distance metric using the ``metric`` keyword
578
+ argument. For example, to use the "`taxicab metric`_" instead of the
579
+ default `Euclidean metric`_::
580
+
581
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
582
+ >>> G = nx.waxman_graph(10, 0.5, 0.1, metric=dist)
583
+
584
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
585
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
586
+
587
+ Notes
588
+ -----
589
+ Starting in NetworkX 2.0 the parameters alpha and beta align with their
590
+ usual roles in the probability distribution. In earlier versions their
591
+ positions in the expression were reversed. Their position in the calling
592
+ sequence reversed as well to minimize backward incompatibility.
593
+
594
+ References
595
+ ----------
596
+ .. [1] B. M. Waxman, *Routing of multipoint connections*.
597
+ IEEE J. Select. Areas Commun. 6(9),(1988) 1617--1622.
598
+ """
599
+ G = nx.empty_graph(n)
600
+ (xmin, ymin, xmax, ymax) = domain
601
+ # Each node gets a uniformly random position in the given rectangle.
602
+ pos = {v: (seed.uniform(xmin, xmax), seed.uniform(ymin, ymax)) for v in G}
603
+ nx.set_node_attributes(G, pos, pos_name)
604
+ # If no distance metric is provided, use Euclidean distance.
605
+ if metric is None:
606
+ metric = math.dist
607
+ # If the maximum distance L is not specified (that is, we are in the
608
+ # Waxman-1 model), then find the maximum distance between any pair
609
+ # of nodes.
610
+ #
611
+ # In the Waxman-1 model, join nodes randomly based on distance. In
612
+ # the Waxman-2 model, join randomly based on random l.
613
+ if L is None:
614
+ L = max(metric(x, y) for x, y in combinations(pos.values(), 2))
615
+
616
+ def dist(u, v):
617
+ return metric(pos[u], pos[v])
618
+
619
+ else:
620
+
621
+ def dist(u, v):
622
+ return seed.random() * L
623
+
624
+ # `pair` is the pair of nodes to decide whether to join.
625
+ def should_join(pair):
626
+ return seed.random() < beta * math.exp(-dist(*pair) / (alpha * L))
627
+
628
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
629
+ return G
630
+
631
+
632
+ @py_random_state(5)
633
+ @nx._dispatchable(graphs=None, returns_graph=True)
634
+ def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None):
635
+ r"""Returns a navigable small-world graph.
636
+
637
+ A navigable small-world graph is a directed grid with additional long-range
638
+ connections that are chosen randomly.
639
+
640
+ [...] we begin with a set of nodes [...] that are identified with the set
641
+ of lattice points in an $n \times n$ square,
642
+ $\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
643
+ and we define the *lattice distance* between two nodes $(i, j)$ and
644
+ $(k, l)$ to be the number of "lattice steps" separating them:
645
+ $d((i, j), (k, l)) = |k - i| + |l - j|$.
646
+
647
+ For a universal constant $p >= 1$, the node $u$ has a directed edge to
648
+ every other node within lattice distance $p$---these are its *local
649
+ contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
650
+ construct directed edges from $u$ to $q$ other nodes (the *long-range
651
+ contacts*) using independent random trials; the $i$th directed edge from
652
+ $u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
653
+
654
+ -- [1]_
655
+
656
+ Parameters
657
+ ----------
658
+ n : int
659
+ The length of one side of the lattice; the number of nodes in
660
+ the graph is therefore $n^2$.
661
+ p : int
662
+ The diameter of short range connections. Each node is joined with every
663
+ other node within this lattice distance.
664
+ q : int
665
+ The number of long-range connections for each node.
666
+ r : float
667
+ Exponent for decaying probability of connections. The probability of
668
+ connecting to a node at lattice distance $d$ is $1/d^r$.
669
+ dim : int
670
+ Dimension of grid
671
+ seed : integer, random_state, or None (default)
672
+ Indicator of random number generation state.
673
+ See :ref:`Randomness<randomness>`.
674
+
675
+ References
676
+ ----------
677
+ .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
678
+ perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
679
+ """
680
+ if p < 1:
681
+ raise nx.NetworkXException("p must be >= 1")
682
+ if q < 0:
683
+ raise nx.NetworkXException("q must be >= 0")
684
+ if r < 0:
685
+ raise nx.NetworkXException("r must be >= 0")
686
+
687
+ G = nx.DiGraph()
688
+ nodes = list(product(range(n), repeat=dim))
689
+ for p1 in nodes:
690
+ probs = [0]
691
+ for p2 in nodes:
692
+ if p1 == p2:
693
+ continue
694
+ d = sum((abs(b - a) for a, b in zip(p1, p2)))
695
+ if d <= p:
696
+ G.add_edge(p1, p2)
697
+ probs.append(d**-r)
698
+ cdf = list(accumulate(probs))
699
+ for _ in range(q):
700
+ target = nodes[bisect_left(cdf, seed.uniform(0, cdf[-1]))]
701
+ G.add_edge(p1, target)
702
+ return G
703
+
704
+
705
+ @py_random_state(7)
706
+ @nx._dispatchable(graphs=None, returns_graph=True)
707
+ def thresholded_random_geometric_graph(
708
+ n,
709
+ radius,
710
+ theta,
711
+ dim=2,
712
+ pos=None,
713
+ weight=None,
714
+ p=2,
715
+ seed=None,
716
+ *,
717
+ pos_name="pos",
718
+ weight_name="weight",
719
+ ):
720
+ r"""Returns a thresholded random geometric graph in the unit cube.
721
+
722
+ The thresholded random geometric graph [1] model places `n` nodes
723
+ uniformly at random in the unit cube of dimensions `dim`. Each node
724
+ `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are
725
+ joined by an edge if they are within the maximum connection distance,
726
+ `radius` computed by the `p`-Minkowski distance and the summation of
727
+ weights :math:`w_u` + :math:`w_v` is greater than or equal
728
+ to the threshold parameter `theta`.
729
+
730
+ Edges within `radius` of each other are determined using a KDTree when
731
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
732
+ to :math:`O(n)`.
733
+
734
+ Parameters
735
+ ----------
736
+ n : int or iterable
737
+ Number of nodes or iterable of nodes
738
+ radius: float
739
+ Distance threshold value
740
+ theta: float
741
+ Threshold value
742
+ dim : int, optional
743
+ Dimension of graph
744
+ pos : dict, optional
745
+ A dictionary keyed by node with node positions as values.
746
+ weight : dict, optional
747
+ Node weights as a dictionary of numbers keyed by node.
748
+ p : float, optional (default 2)
749
+ Which Minkowski distance metric to use. `p` has to meet the condition
750
+ ``1 <= p <= infinity``.
751
+
752
+ If this argument is not specified, the :math:`L^2` metric
753
+ (the Euclidean distance metric), p = 2 is used.
754
+
755
+ This should not be confused with the `p` of an Erdős-Rényi random
756
+ graph, which represents probability.
757
+ seed : integer, random_state, or None (default)
758
+ Indicator of random number generation state.
759
+ See :ref:`Randomness<randomness>`.
760
+ pos_name : string, default="pos"
761
+ The name of the node attribute which represents the position
762
+ in 2D coordinates of the node in the returned graph.
763
+ weight_name : string, default="weight"
764
+ The name of the node attribute which represents the weight
765
+ of the node in the returned graph.
766
+
767
+ Returns
768
+ -------
769
+ Graph
770
+ A thresholded random geographic graph, undirected and without
771
+ self-loops.
772
+
773
+ Each node has a node attribute ``'pos'`` that stores the
774
+ position of that node in Euclidean space as provided by the
775
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
776
+ generated by this function. Similarly, each node has a nodethre
777
+ attribute ``'weight'`` that stores the weight of that node as
778
+ provided or as generated.
779
+
780
+ Notes
781
+ -----
782
+ This uses a *k*-d tree to build the graph.
783
+
784
+ References
785
+ ----------
786
+ .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
787
+
788
+ Examples
789
+ --------
790
+ Default Graph:
791
+
792
+ >>> G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
793
+
794
+ Custom Graph:
795
+
796
+ The `pos` keyword argument can be used to specify node positions so you
797
+ can create an arbitrary distribution and domain for positions.
798
+
799
+ If weights are not specified they are assigned to nodes by drawing randomly
800
+ from the exponential distribution with rate parameter :math:`\lambda=1`.
801
+ To specify weights from a different distribution, use the `weight` keyword
802
+ argument.
803
+
804
+ For example, create a thresholded random geometric graph on 50 nodes using a 2D
805
+ Gaussian distribution of node positions with mean (0, 0) and standard deviation 2,
806
+ where nodes are joined by an edge if their sum weights drawn from
807
+ a exponential distribution with rate = 5 are >= theta = 0.1 and their
808
+ Euclidean distance is at most 0.2.
809
+
810
+ >>> import random
811
+ >>> n = 50
812
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
813
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
814
+ >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w)
815
+
816
+ """
817
+ G = nx.empty_graph(n)
818
+ G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})"
819
+ # If no weights are provided, choose them from an exponential
820
+ # distribution.
821
+ if weight is None:
822
+ weight = {v: seed.expovariate(1) for v in G}
823
+ # If no positions are provided, choose uniformly random vectors in
824
+ # Euclidean space of the specified dimension.
825
+ if pos is None:
826
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
827
+ # If no distance metric is provided, use Euclidean distance.
828
+ nx.set_node_attributes(G, weight, weight_name)
829
+ nx.set_node_attributes(G, pos, pos_name)
830
+
831
+ edges = (
832
+ (u, v)
833
+ for u, v in _geometric_edges(G, radius, p, pos_name)
834
+ if weight[u] + weight[v] >= theta
835
+ )
836
+ G.add_edges_from(edges)
837
+ return G
838
+
839
+
840
+ @py_random_state(5)
841
+ @nx._dispatchable(graphs=None, returns_graph=True)
842
+ def geometric_soft_configuration_graph(
843
+ *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None
844
+ ):
845
+ r"""Returns a random graph from the geometric soft configuration model.
846
+
847
+ The $\mathbb{S}^1$ model [1]_ is the geometric soft configuration model
848
+ which is able to explain many fundamental features of real networks such as
849
+ small-world property, heteregenous degree distributions, high level of
850
+ clustering, and self-similarity.
851
+
852
+ In the geometric soft configuration model, a node $i$ is assigned two hidden
853
+ variables: a hidden degree $\kappa_i$, quantifying its popularity, influence,
854
+ or importance, and an angular position $\theta_i$ in a circle abstracting the
855
+ similarity space, where angular distances between nodes are a proxy for their
856
+ similarity. Focusing on the angular position, this model is often called
857
+ the $\mathbb{S}^1$ model (a one-dimensional sphere). The circle's radius is
858
+ adjusted to $R = N/2\pi$, where $N$ is the number of nodes, so that the density
859
+ is set to 1 without loss of generality.
860
+
861
+ The connection probability between any pair of nodes increases with
862
+ the product of their hidden degrees (i.e., their combined popularities),
863
+ and decreases with the angular distance between the two nodes.
864
+ Specifically, nodes $i$ and $j$ are connected with the probability
865
+
866
+ $p_{ij} = \frac{1}{1 + \frac{d_{ij}^\beta}{\left(\mu \kappa_i \kappa_j\right)^{\max(1, \beta)}}}$
867
+
868
+ where $d_{ij} = R\Delta\theta_{ij}$ is the arc length of the circle between
869
+ nodes $i$ and $j$ separated by an angular distance $\Delta\theta_{ij}$.
870
+ Parameters $\mu$ and $\beta$ (also called inverse temperature) control the
871
+ average degree and the clustering coefficient, respectively.
872
+
873
+ It can be shown [2]_ that the model undergoes a structural phase transition
874
+ at $\beta=1$ so that for $\beta<1$ networks are unclustered in the thermodynamic
875
+ limit (when $N\to \infty$) whereas for $\beta>1$ the ensemble generates
876
+ networks with finite clustering coefficient.
877
+
878
+ The $\mathbb{S}^1$ model can be expressed as a purely geometric model
879
+ $\mathbb{H}^2$ in the hyperbolic plane [3]_ by mapping the hidden degree of
880
+ each node into a radial coordinate as
881
+
882
+ $r_i = \hat{R} - \frac{2 \max(1, \beta)}{\beta \zeta} \ln \left(\frac{\kappa_i}{\kappa_0}\right)$
883
+
884
+ where $\hat{R}$ is the radius of the hyperbolic disk and $\zeta$ is the curvature,
885
+
886
+ $\hat{R} = \frac{2}{\zeta} \ln \left(\frac{N}{\pi}\right)
887
+ - \frac{2\max(1, \beta)}{\beta \zeta} \ln (\mu \kappa_0^2)$
888
+
889
+ The connection probability then reads
890
+
891
+ $p_{ij} = \frac{1}{1 + \exp\left({\frac{\beta\zeta}{2} (x_{ij} - \hat{R})}\right)}$
892
+
893
+ where
894
+
895
+ $x_{ij} = r_i + r_j + \frac{2}{\zeta} \ln \frac{\Delta\theta_{ij}}{2}$
896
+
897
+ is a good approximation of the hyperbolic distance between two nodes separated
898
+ by an angular distance $\Delta\theta_{ij}$ with radial coordinates $r_i$ and $r_j$.
899
+ For $\beta > 1$, the curvature $\zeta = 1$, for $\beta < 1$, $\zeta = \beta^{-1}$.
900
+
901
+
902
+ Parameters
903
+ ----------
904
+ Either `n`, `gamma`, `mean_degree` are provided or `kappas`. The values of
905
+ `n`, `gamma`, `mean_degree` (if provided) are used to construct a random
906
+ kappa-dict keyed by node with values sampled from a power-law distribution.
907
+
908
+ beta : positive number
909
+ Inverse temperature, controlling the clustering coefficient.
910
+ n : int (default: None)
911
+ Size of the network (number of nodes).
912
+ If not provided, `kappas` must be provided and holds the nodes.
913
+ gamma : float (default: None)
914
+ Exponent of the power-law distribution for hidden degrees `kappas`.
915
+ If not provided, `kappas` must be provided directly.
916
+ mean_degree : float (default: None)
917
+ The mean degree in the network.
918
+ If not provided, `kappas` must be provided directly.
919
+ kappas : dict (default: None)
920
+ A dict keyed by node to its hidden degree value.
921
+ If not provided, random values are computed based on a power-law
922
+ distribution using `n`, `gamma` and `mean_degree`.
923
+ seed : int, random_state, or None (default)
924
+ Indicator of random number generation state.
925
+ See :ref:`Randomness<randomness>`.
926
+
927
+ Returns
928
+ -------
929
+ Graph
930
+ A random geometric soft configuration graph (undirected with no self-loops).
931
+ Each node has three node-attributes:
932
+
933
+ - ``kappa`` that represents the hidden degree.
934
+
935
+ - ``theta`` the position in the similarity space ($\mathbb{S}^1$) which is
936
+ also the angular position in the hyperbolic plane.
937
+
938
+ - ``radius`` the radial position in the hyperbolic plane
939
+ (based on the hidden degree).
940
+
941
+
942
+ Examples
943
+ --------
944
+ Generate a network with specified parameters:
945
+
946
+ >>> G = nx.geometric_soft_configuration_graph(
947
+ ... beta=1.5, n=100, gamma=2.7, mean_degree=5
948
+ ... )
949
+
950
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
951
+ is set to 1.5 and the exponent of the powerlaw distribution of the hidden
952
+ degrees is 2.7 with mean value of 5.
953
+
954
+ Generate a network with predefined hidden degrees:
955
+
956
+ >>> kappas = {i: 10 for i in range(100)}
957
+ >>> G = nx.geometric_soft_configuration_graph(beta=2.5, kappas=kappas)
958
+
959
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
960
+ is set to 2.5 and all nodes with hidden degree $\kappa=10$.
961
+
962
+
963
+ References
964
+ ----------
965
+ .. [1] Serrano, M. Á., Krioukov, D., & Boguñá, M. (2008). Self-similarity
966
+ of complex networks and hidden metric spaces. Physical review letters, 100(7), 078701.
967
+
968
+ .. [2] van der Kolk, J., Serrano, M. Á., & Boguñá, M. (2022). An anomalous
969
+ topological phase transition in spatial random graphs. Communications Physics, 5(1), 245.
970
+
971
+ .. [3] Krioukov, D., Papadopoulos, F., Kitsak, M., Vahdat, A., & Boguná, M. (2010).
972
+ Hyperbolic geometry of complex networks. Physical Review E, 82(3), 036106.
973
+
974
+ """
975
+ if beta <= 0:
976
+ raise nx.NetworkXError("The parameter beta cannot be smaller or equal to 0.")
977
+
978
+ if kappas is not None:
979
+ if not all((n is None, gamma is None, mean_degree is None)):
980
+ raise nx.NetworkXError(
981
+ "When kappas is input, n, gamma and mean_degree must not be."
982
+ )
983
+
984
+ n = len(kappas)
985
+ mean_degree = sum(kappas.values()) / len(kappas)
986
+ else:
987
+ if any((n is None, gamma is None, mean_degree is None)):
988
+ raise nx.NetworkXError(
989
+ "Please provide either kappas, or all 3 of: n, gamma and mean_degree."
990
+ )
991
+
992
+ # Generate `n` hidden degrees from a powerlaw distribution
993
+ # with given exponent `gamma` and mean value `mean_degree`
994
+ gam_ratio = (gamma - 2) / (gamma - 1)
995
+ kappa_0 = mean_degree * gam_ratio * (1 - 1 / n) / (1 - 1 / n**gam_ratio)
996
+ base = 1 - 1 / n
997
+ power = 1 / (1 - gamma)
998
+ kappas = {i: kappa_0 * (1 - seed.random() * base) ** power for i in range(n)}
999
+
1000
+ G = nx.Graph()
1001
+ R = n / (2 * math.pi)
1002
+
1003
+ # Approximate values for mu in the thermodynamic limit (when n -> infinity)
1004
+ if beta > 1:
1005
+ mu = beta * math.sin(math.pi / beta) / (2 * math.pi * mean_degree)
1006
+ elif beta == 1:
1007
+ mu = 1 / (2 * mean_degree * math.log(n))
1008
+ else:
1009
+ mu = (1 - beta) / (2**beta * mean_degree * n ** (1 - beta))
1010
+
1011
+ # Generate random positions on a circle
1012
+ thetas = {k: seed.uniform(0, 2 * math.pi) for k in kappas}
1013
+
1014
+ for u in kappas:
1015
+ for v in list(G):
1016
+ angle = math.pi - math.fabs(math.pi - math.fabs(thetas[u] - thetas[v]))
1017
+ dij = math.pow(R * angle, beta)
1018
+ mu_kappas = math.pow(mu * kappas[u] * kappas[v], max(1, beta))
1019
+ p_ij = 1 / (1 + dij / mu_kappas)
1020
+
1021
+ # Create an edge with a certain connection probability
1022
+ if seed.random() < p_ij:
1023
+ G.add_edge(u, v)
1024
+ G.add_node(u)
1025
+
1026
+ nx.set_node_attributes(G, thetas, "theta")
1027
+ nx.set_node_attributes(G, kappas, "kappa")
1028
+
1029
+ # Map hidden degrees into the radial coordinates
1030
+ zeta = 1 if beta > 1 else 1 / beta
1031
+ kappa_min = min(kappas.values())
1032
+ R_c = 2 * max(1, beta) / (beta * zeta)
1033
+ R_hat = (2 / zeta) * math.log(n / math.pi) - R_c * math.log(mu * kappa_min)
1034
+ radii = {node: R_hat - R_c * math.log(kappa) for node, kappa in kappas.items()}
1035
+ nx.set_node_attributes(G, radii, "radius")
1036
+
1037
+ return G
venv/lib/python3.14/site-packages/networkx/generators/harary_graph.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for Harary graphs
2
+
3
+ This module gives two generators for the Harary graph, which was
4
+ introduced by the famous mathematician Frank Harary in his 1962 work [H]_.
5
+ The first generator gives the Harary graph that maximizes the node
6
+ connectivity with given number of nodes and given number of edges.
7
+ The second generator gives the Harary graph that minimizes
8
+ the number of edges in the graph with given node connectivity and
9
+ number of nodes.
10
+
11
+ References
12
+ ----------
13
+ .. [H] Harary, F. "The Maximum Connectivity of a Graph."
14
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
15
+
16
+ """
17
+
18
+ import networkx as nx
19
+
20
+ __all__ = ["hnm_harary_graph", "hkn_harary_graph"]
21
+
22
+
23
+ @nx._dispatchable(graphs=None, returns_graph=True)
24
+ def hnm_harary_graph(n, m, create_using=None):
25
+ r"""Return the Harary graph with given numbers of nodes and edges.
26
+
27
+ The Harary graph $H_{n, m}$ is the graph that maximizes node connectivity
28
+ with $n$ nodes and $m$ edges.
29
+
30
+ This maximum node connectivity is known to be $\lfloor 2m/n \rfloor$. [1]_
31
+
32
+ Parameters
33
+ ----------
34
+ n: integer
35
+ The number of nodes the generated graph is to contain.
36
+
37
+ m: integer
38
+ The number of edges the generated graph is to contain.
39
+
40
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
41
+ Graph type to create. If graph instance, then cleared before populated.
42
+
43
+ Returns
44
+ -------
45
+ NetworkX graph
46
+ The Harary graph $H_{n, m}$.
47
+
48
+ See Also
49
+ --------
50
+ hkn_harary_graph
51
+
52
+ Notes
53
+ -----
54
+ This algorithm runs in $O(m)$ time.
55
+ The implementation follows [2]_.
56
+
57
+ References
58
+ ----------
59
+ .. [1] F. T. Boesch, A. Satyanarayana, and C. L. Suffel,
60
+ "A Survey of Some Network Reliability Analysis and Synthesis Results,"
61
+ Networks, pp. 99-107, 2009.
62
+
63
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
64
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
65
+ """
66
+
67
+ if n < 1:
68
+ raise nx.NetworkXError("The number of nodes must be >= 1!")
69
+ if m < n - 1:
70
+ raise nx.NetworkXError("The number of edges must be >= n - 1 !")
71
+ if m > n * (n - 1) // 2:
72
+ raise nx.NetworkXError("The number of edges must be <= n(n-1)/2")
73
+
74
+ # Get the floor of average node degree.
75
+ d = 2 * m // n
76
+
77
+ offset = d // 2
78
+ H = nx.circulant_graph(n, range(1, offset + 1), create_using=create_using)
79
+
80
+ half = n // 2
81
+ if (n % 2 == 0) or (d % 2 == 0):
82
+ # If d is odd; n must be even.
83
+ if d % 2 == 1:
84
+ # Add edges diagonally.
85
+ H.add_edges_from((i, i + half) for i in range(half))
86
+
87
+ r = 2 * m % n
88
+ # Add remaining edges at offset + 1.
89
+ H.add_edges_from((i, i + offset + 1) for i in range(r // 2))
90
+ else:
91
+ # Add the remaining m - n * offset edges between i and i + half.
92
+ H.add_edges_from((i, (i + half) % n) for i in range(m - n * offset))
93
+
94
+ return H
95
+
96
+
97
+ @nx._dispatchable(graphs=None, returns_graph=True)
98
+ def hkn_harary_graph(k, n, create_using=None):
99
+ r"""Return the Harary graph with given node connectivity and node number.
100
+
101
+ The Harary graph $H_{k, n}$ is the graph that minimizes the number of
102
+ edges needed with given node connectivity $k$ and node number $n$.
103
+
104
+ This smallest number of edges is known to be $\lceil kn/2 \rceil$ [1]_.
105
+
106
+ Parameters
107
+ ----------
108
+ k: integer
109
+ The node connectivity of the generated graph.
110
+
111
+ n: integer
112
+ The number of nodes the generated graph is to contain.
113
+
114
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
115
+ Graph type to create. If graph instance, then cleared before populated.
116
+
117
+ Returns
118
+ -------
119
+ NetworkX graph
120
+ The Harary graph $H_{k, n}$.
121
+
122
+ See Also
123
+ --------
124
+ hnm_harary_graph
125
+
126
+ Notes
127
+ -----
128
+ This algorithm runs in $O(kn)$ time.
129
+ The implementation follows [2]_.
130
+
131
+ References
132
+ ----------
133
+ .. [1] Weisstein, Eric W. "Harary Graph." From MathWorld--A Wolfram Web
134
+ Resource. http://mathworld.wolfram.com/HararyGraph.html.
135
+
136
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
137
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
138
+ """
139
+
140
+ if k < 1:
141
+ raise nx.NetworkXError("The node connectivity must be >= 1!")
142
+ if n < k + 1:
143
+ raise nx.NetworkXError("The number of nodes must be >= k+1 !")
144
+
145
+ # In case of connectivity 1, simply return the path graph.
146
+ if k == 1:
147
+ return nx.path_graph(n, create_using)
148
+
149
+ offset = k // 2
150
+ H = nx.circulant_graph(n, range(1, offset + 1), create_using=create_using)
151
+
152
+ half = n // 2
153
+ if (k % 2 == 0) or (n % 2 == 0):
154
+ # If k is odd; n must be even.
155
+ if k % 2 == 1:
156
+ # Add edges diagonally.
157
+ H.add_edges_from((i, i + half) for i in range(half))
158
+ else:
159
+ # Add half + 1 edges between i and i + half.
160
+ H.add_edges_from((i, (i + half) % n) for i in range(half + 1))
161
+
162
+ return H
venv/lib/python3.14/site-packages/networkx/generators/internet_as_graphs.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates graphs resembling the Internet Autonomous System network"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = ["random_internet_as_graph"]
7
+
8
+
9
+ def uniform_int_from_avg(a, m, seed):
10
+ """Pick a random integer with uniform probability.
11
+
12
+ Returns a random integer uniformly taken from a distribution with
13
+ minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where
14
+ b = 2*m - a.
15
+
16
+ Notes
17
+ -----
18
+ p = (b-floor(b))/2
19
+ X = X1 + X2; X1~U(a,floor(b)), X2~B(p)
20
+ E[X] = E[X1] + E[X2] = (floor(b)+a)/2 + (b-floor(b))/2 = (b+a)/2 = m
21
+ """
22
+
23
+ from math import floor
24
+
25
+ assert m >= a
26
+ b = 2 * m - a
27
+ p = (b - floor(b)) / 2
28
+ X1 = round(seed.random() * (floor(b) - a) + a)
29
+ if seed.random() < p:
30
+ X2 = 1
31
+ else:
32
+ X2 = 0
33
+ return X1 + X2
34
+
35
+
36
+ @py_random_state("seed")
37
+ def choose_pref_attach(degs, seed):
38
+ """Pick a random value, with a probability given by its weight.
39
+
40
+ Returns a random choice among degs keys, each of which has a
41
+ probability proportional to the corresponding dictionary value.
42
+
43
+ Parameters
44
+ ----------
45
+ degs: dictionary
46
+ It contains the possible values (keys) and the corresponding
47
+ probabilities (values)
48
+ seed: random state
49
+
50
+ Returns
51
+ -------
52
+ v: object
53
+ A key of degs or None if degs is empty
54
+ """
55
+
56
+ if len(degs) == 0:
57
+ return None
58
+ s = sum(degs.values())
59
+ if s == 0:
60
+ return seed.choice(list(degs.keys()))
61
+ v = seed.random() * s
62
+
63
+ nodes = list(degs.keys())
64
+ i = 0
65
+ acc = degs[nodes[i]]
66
+ while v > acc:
67
+ i += 1
68
+ acc += degs[nodes[i]]
69
+ return nodes[i]
70
+
71
+
72
+ class AS_graph_generator:
73
+ """Generates random internet AS graphs."""
74
+
75
+ @py_random_state("seed")
76
+ def __init__(self, n, seed):
77
+ """Initializes variables. Immediate numbers are taken from [1].
78
+
79
+ Parameters
80
+ ----------
81
+ n: integer
82
+ Number of graph nodes
83
+ seed: random state
84
+ Indicator of random number generation state.
85
+ See :ref:`Randomness<randomness>`.
86
+
87
+ Returns
88
+ -------
89
+ GG: AS_graph_generator object
90
+
91
+ References
92
+ ----------
93
+ [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
94
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
95
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
96
+ """
97
+
98
+ self.seed = seed
99
+ self.n_t = min(n, round(self.seed.random() * 2 + 4)) # num of T nodes
100
+ self.n_m = round(0.15 * n) # number of M nodes
101
+ self.n_cp = round(0.05 * n) # number of CP nodes
102
+ self.n_c = max(0, n - self.n_t - self.n_m - self.n_cp) # number of C nodes
103
+
104
+ self.d_m = 2 + (2.5 * n) / 10000 # average multihoming degree for M nodes
105
+ self.d_cp = 2 + (1.5 * n) / 10000 # avg multihoming degree for CP nodes
106
+ self.d_c = 1 + (5 * n) / 100000 # average multihoming degree for C nodes
107
+
108
+ self.p_m_m = 1 + (2 * n) / 10000 # avg num of peer edges between M and M
109
+ self.p_cp_m = 0.2 + (2 * n) / 10000 # avg num of peer edges between CP, M
110
+ self.p_cp_cp = 0.05 + (2 * n) / 100000 # avg num of peer edges btwn CP, CP
111
+
112
+ self.t_m = 0.375 # probability M's provider is T
113
+ self.t_cp = 0.375 # probability CP's provider is T
114
+ self.t_c = 0.125 # probability C's provider is T
115
+
116
+ def t_graph(self):
117
+ """Generates the core mesh network of tier one nodes of a AS graph.
118
+
119
+ Returns
120
+ -------
121
+ G: Networkx Graph
122
+ Core network
123
+ """
124
+
125
+ self.G = nx.Graph()
126
+ for i in range(self.n_t):
127
+ self.G.add_node(i, type="T")
128
+ for r in self.regions:
129
+ self.regions[r].add(i)
130
+ for j in self.G.nodes():
131
+ if i != j:
132
+ self.add_edge(i, j, "peer")
133
+ self.customers[i] = set()
134
+ self.providers[i] = set()
135
+ return self.G
136
+
137
+ def add_edge(self, i, j, kind):
138
+ if kind == "transit":
139
+ customer = str(i)
140
+ else:
141
+ customer = "none"
142
+ self.G.add_edge(i, j, type=kind, customer=customer)
143
+
144
+ def choose_peer_pref_attach(self, node_list):
145
+ """Pick a node with a probability weighted by its peer degree.
146
+
147
+ Pick a node from node_list with preferential attachment
148
+ computed only on their peer degree
149
+ """
150
+
151
+ d = {}
152
+ for n in node_list:
153
+ d[n] = self.G.nodes[n]["peers"]
154
+ return choose_pref_attach(d, self.seed)
155
+
156
+ def choose_node_pref_attach(self, node_list):
157
+ """Pick a node with a probability weighted by its degree.
158
+
159
+ Pick a node from node_list with preferential attachment
160
+ computed on their degree
161
+ """
162
+
163
+ degs = dict(self.G.degree(node_list))
164
+ return choose_pref_attach(degs, self.seed)
165
+
166
+ def add_customer(self, i, j):
167
+ """Keep the dictionaries 'customers' and 'providers' consistent."""
168
+
169
+ self.customers[j].add(i)
170
+ self.providers[i].add(j)
171
+ for z in self.providers[j]:
172
+ self.customers[z].add(i)
173
+ self.providers[i].add(z)
174
+
175
+ def add_node(self, i, kind, reg2prob, avg_deg, t_edge_prob):
176
+ """Add a node and its customer transit edges to the graph.
177
+
178
+ Parameters
179
+ ----------
180
+ i: object
181
+ Identifier of the new node
182
+ kind: string
183
+ Type of the new node. Options are: 'M' for middle node, 'CP' for
184
+ content provider and 'C' for customer.
185
+ reg2prob: float
186
+ Probability the new node can be in two different regions.
187
+ avg_deg: float
188
+ Average number of transit nodes of which node i is customer.
189
+ t_edge_prob: float
190
+ Probability node i establish a customer transit edge with a tier
191
+ one (T) node
192
+
193
+ Returns
194
+ -------
195
+ i: object
196
+ Identifier of the new node
197
+ """
198
+
199
+ regs = 1 # regions in which node resides
200
+ if self.seed.random() < reg2prob: # node is in two regions
201
+ regs = 2
202
+ node_options = set()
203
+
204
+ self.G.add_node(i, type=kind, peers=0)
205
+ self.customers[i] = set()
206
+ self.providers[i] = set()
207
+ self.nodes[kind].add(i)
208
+ for r in self.seed.sample(list(self.regions), regs):
209
+ node_options = node_options.union(self.regions[r])
210
+ self.regions[r].add(i)
211
+
212
+ edge_num = uniform_int_from_avg(1, avg_deg, self.seed)
213
+
214
+ t_options = node_options.intersection(self.nodes["T"])
215
+ m_options = node_options.intersection(self.nodes["M"])
216
+ if i in m_options:
217
+ m_options.remove(i)
218
+ d = 0
219
+ while d < edge_num and (len(t_options) > 0 or len(m_options) > 0):
220
+ if len(m_options) == 0 or (
221
+ len(t_options) > 0 and self.seed.random() < t_edge_prob
222
+ ): # add edge to a T node
223
+ j = self.choose_node_pref_attach(t_options)
224
+ t_options.remove(j)
225
+ else:
226
+ j = self.choose_node_pref_attach(m_options)
227
+ m_options.remove(j)
228
+ self.add_edge(i, j, "transit")
229
+ self.add_customer(i, j)
230
+ d += 1
231
+
232
+ return i
233
+
234
+ def add_m_peering_link(self, m, to_kind):
235
+ """Add a peering link between two middle tier (M) nodes.
236
+
237
+ Target node j is drawn considering a preferential attachment based on
238
+ other M node peering degree.
239
+
240
+ Parameters
241
+ ----------
242
+ m: object
243
+ Node identifier
244
+ to_kind: string
245
+ type for target node j (must be always M)
246
+
247
+ Returns
248
+ -------
249
+ success: boolean
250
+ """
251
+
252
+ # candidates are of type 'M' and are not customers of m
253
+ node_options = self.nodes["M"].difference(self.customers[m])
254
+ # candidates are not providers of m
255
+ node_options = node_options.difference(self.providers[m])
256
+ # remove self
257
+ if m in node_options:
258
+ node_options.remove(m)
259
+
260
+ # remove candidates we are already connected to
261
+ for j in self.G.neighbors(m):
262
+ if j in node_options:
263
+ node_options.remove(j)
264
+
265
+ if len(node_options) > 0:
266
+ j = self.choose_peer_pref_attach(node_options)
267
+ self.add_edge(m, j, "peer")
268
+ self.G.nodes[m]["peers"] += 1
269
+ self.G.nodes[j]["peers"] += 1
270
+ return True
271
+ else:
272
+ return False
273
+
274
+ def add_cp_peering_link(self, cp, to_kind):
275
+ """Add a peering link to a content provider (CP) node.
276
+
277
+ Target node j can be CP or M and it is drawn uniformly among the nodes
278
+ belonging to the same region as cp.
279
+
280
+ Parameters
281
+ ----------
282
+ cp: object
283
+ Node identifier
284
+ to_kind: string
285
+ type for target node j (must be M or CP)
286
+
287
+ Returns
288
+ -------
289
+ success: boolean
290
+ """
291
+
292
+ node_options = set()
293
+ for r in self.regions: # options include nodes in the same region(s)
294
+ if cp in self.regions[r]:
295
+ node_options = node_options.union(self.regions[r])
296
+
297
+ # options are restricted to the indicated kind ('M' or 'CP')
298
+ node_options = self.nodes[to_kind].intersection(node_options)
299
+
300
+ # remove self
301
+ if cp in node_options:
302
+ node_options.remove(cp)
303
+
304
+ # remove nodes that are cp's providers
305
+ node_options = node_options.difference(self.providers[cp])
306
+
307
+ # remove nodes we are already connected to
308
+ for j in self.G.neighbors(cp):
309
+ if j in node_options:
310
+ node_options.remove(j)
311
+
312
+ if len(node_options) > 0:
313
+ j = self.seed.sample(list(node_options), 1)[0]
314
+ self.add_edge(cp, j, "peer")
315
+ self.G.nodes[cp]["peers"] += 1
316
+ self.G.nodes[j]["peers"] += 1
317
+ return True
318
+ else:
319
+ return False
320
+
321
+ def graph_regions(self, rn):
322
+ """Initializes AS network regions.
323
+
324
+ Parameters
325
+ ----------
326
+ rn: integer
327
+ Number of regions
328
+ """
329
+
330
+ self.regions = {}
331
+ for i in range(rn):
332
+ self.regions["REG" + str(i)] = set()
333
+
334
+ def add_peering_links(self, from_kind, to_kind):
335
+ """Utility function to add peering links among node groups."""
336
+ peer_link_method = None
337
+ if from_kind == "M":
338
+ peer_link_method = self.add_m_peering_link
339
+ m = self.p_m_m
340
+ if from_kind == "CP":
341
+ peer_link_method = self.add_cp_peering_link
342
+ if to_kind == "M":
343
+ m = self.p_cp_m
344
+ else:
345
+ m = self.p_cp_cp
346
+
347
+ for i in self.nodes[from_kind]:
348
+ num = uniform_int_from_avg(0, m, self.seed)
349
+ for _ in range(num):
350
+ peer_link_method(i, to_kind)
351
+
352
+ def generate(self):
353
+ """Generates a random AS network graph as described in [1].
354
+
355
+ Returns
356
+ -------
357
+ G: Graph object
358
+
359
+ Notes
360
+ -----
361
+ The process steps are the following: first we create the core network
362
+ of tier one nodes, then we add the middle tier (M), the content
363
+ provider (CP) and the customer (C) nodes along with their transit edges
364
+ (link i,j means i is customer of j). Finally we add peering links
365
+ between M nodes, between M and CP nodes and between CP node couples.
366
+ For a detailed description of the algorithm, please refer to [1].
367
+
368
+ References
369
+ ----------
370
+ [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
371
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
372
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
373
+ """
374
+
375
+ self.graph_regions(5)
376
+ self.customers = {}
377
+ self.providers = {}
378
+ self.nodes = {"T": set(), "M": set(), "CP": set(), "C": set()}
379
+
380
+ self.t_graph()
381
+ self.nodes["T"] = set(self.G.nodes())
382
+
383
+ i = len(self.nodes["T"])
384
+ for _ in range(self.n_m):
385
+ self.nodes["M"].add(self.add_node(i, "M", 0.2, self.d_m, self.t_m))
386
+ i += 1
387
+ for _ in range(self.n_cp):
388
+ self.nodes["CP"].add(self.add_node(i, "CP", 0.05, self.d_cp, self.t_cp))
389
+ i += 1
390
+ for _ in range(self.n_c):
391
+ self.nodes["C"].add(self.add_node(i, "C", 0, self.d_c, self.t_c))
392
+ i += 1
393
+
394
+ self.add_peering_links("M", "M")
395
+ self.add_peering_links("CP", "M")
396
+ self.add_peering_links("CP", "CP")
397
+
398
+ return self.G
399
+
400
+
401
+ @py_random_state(1)
402
+ @nx._dispatchable(graphs=None, returns_graph=True)
403
+ def random_internet_as_graph(n, seed=None):
404
+ """Generates a random undirected graph resembling the Internet AS network
405
+
406
+ Parameters
407
+ ----------
408
+ n: integer in [1000, 10000]
409
+ Number of graph nodes
410
+ seed : integer, random_state, or None (default)
411
+ Indicator of random number generation state.
412
+ See :ref:`Randomness<randomness>`.
413
+
414
+ Returns
415
+ -------
416
+ G: Networkx Graph object
417
+ A randomly generated undirected graph
418
+
419
+ Notes
420
+ -----
421
+ This algorithm returns an undirected graph resembling the Internet
422
+ Autonomous System (AS) network, it uses the approach by Elmokashfi et al.
423
+ [1]_ and it grants the properties described in the related paper [1]_.
424
+
425
+ Each node models an autonomous system, with an attribute 'type' specifying
426
+ its kind; tier-1 (T), mid-level (M), customer (C) or content-provider (CP).
427
+ Each edge models an ADV communication link (hence, bidirectional) with
428
+ attributes:
429
+
430
+ - type: transit|peer, the kind of commercial agreement between nodes;
431
+ - customer: <node id>, the identifier of the node acting as customer
432
+ ('none' if type is peer).
433
+
434
+ References
435
+ ----------
436
+ .. [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
437
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
438
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
439
+ """
440
+
441
+ GG = AS_graph_generator(n, seed)
442
+ G = GG.generate()
443
+ return G
venv/lib/python3.14/site-packages/networkx/generators/intersection.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random intersection graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.utils import py_random_state
7
+
8
+ __all__ = [
9
+ "uniform_random_intersection_graph",
10
+ "k_random_intersection_graph",
11
+ "general_random_intersection_graph",
12
+ ]
13
+
14
+
15
+ @py_random_state(3)
16
+ @nx._dispatchable(graphs=None, returns_graph=True)
17
+ def uniform_random_intersection_graph(n, m, p, seed=None):
18
+ """Returns a uniform random intersection graph.
19
+
20
+ Parameters
21
+ ----------
22
+ n : int
23
+ The number of nodes in the first bipartite set (nodes)
24
+ m : int
25
+ The number of nodes in the second bipartite set (attributes)
26
+ p : float
27
+ Probability of connecting nodes between bipartite sets
28
+ seed : integer, random_state, or None (default)
29
+ Indicator of random number generation state.
30
+ See :ref:`Randomness<randomness>`.
31
+
32
+ See Also
33
+ --------
34
+ gnp_random_graph
35
+
36
+ References
37
+ ----------
38
+ .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995,
39
+ PhD thesis, Johns Hopkins University
40
+ .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B.,
41
+ Random intersection graphs when m = !(n):
42
+ An equivalence theorem relating the evolution of the g(n, m, p)
43
+ and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176.
44
+ """
45
+ from networkx.algorithms import bipartite
46
+
47
+ G = bipartite.random_graph(n, m, p, seed)
48
+ return nx.projected_graph(G, range(n))
49
+
50
+
51
+ @py_random_state(3)
52
+ @nx._dispatchable(graphs=None, returns_graph=True)
53
+ def k_random_intersection_graph(n, m, k, seed=None):
54
+ """Returns a intersection graph with randomly chosen attribute sets for
55
+ each node that are of equal size (k).
56
+
57
+ Parameters
58
+ ----------
59
+ n : int
60
+ The number of nodes in the first bipartite set (nodes)
61
+ m : int
62
+ The number of nodes in the second bipartite set (attributes)
63
+ k : float
64
+ Size of attribute set to assign to each node.
65
+ seed : integer, random_state, or None (default)
66
+ Indicator of random number generation state.
67
+ See :ref:`Randomness<randomness>`.
68
+
69
+ See Also
70
+ --------
71
+ gnp_random_graph, uniform_random_intersection_graph
72
+
73
+ References
74
+ ----------
75
+ .. [1] Godehardt, E., and Jaworski, J.
76
+ Two models of random intersection graphs and their applications.
77
+ Electronic Notes in Discrete Mathematics 10 (2001), 129--132.
78
+ """
79
+ G = nx.empty_graph(n + m)
80
+ mset = range(n, n + m)
81
+ for v in range(n):
82
+ targets = seed.sample(mset, k)
83
+ G.add_edges_from(zip([v] * len(targets), targets))
84
+ return nx.projected_graph(G, range(n))
85
+
86
+
87
+ @py_random_state(3)
88
+ @nx._dispatchable(graphs=None, returns_graph=True)
89
+ def general_random_intersection_graph(n, m, p, seed=None):
90
+ """Returns a random intersection graph with independent probabilities
91
+ for connections between node and attribute sets.
92
+
93
+ Parameters
94
+ ----------
95
+ n : int
96
+ The number of nodes in the first bipartite set (nodes)
97
+ m : int
98
+ The number of nodes in the second bipartite set (attributes)
99
+ p : list of floats of length m
100
+ Probabilities for connecting nodes to each attribute
101
+ seed : integer, random_state, or None (default)
102
+ Indicator of random number generation state.
103
+ See :ref:`Randomness<randomness>`.
104
+
105
+ See Also
106
+ --------
107
+ gnp_random_graph, uniform_random_intersection_graph
108
+
109
+ References
110
+ ----------
111
+ .. [1] Nikoletseas, S. E., Raptopoulos, C., and Spirakis, P. G.
112
+ The existence and efficient construction of large independent sets
113
+ in general random intersection graphs. In ICALP (2004), J. D´ıaz,
114
+ J. Karhum¨aki, A. Lepist¨o, and D. Sannella, Eds., vol. 3142
115
+ of Lecture Notes in Computer Science, Springer, pp. 1029–1040.
116
+ """
117
+ if len(p) != m:
118
+ raise ValueError("Probability list p must have m elements.")
119
+ G = nx.empty_graph(n + m)
120
+ mset = range(n, n + m)
121
+ for u in range(n):
122
+ for v, q in zip(mset, p):
123
+ if seed.random() < q:
124
+ G.add_edge(u, v)
125
+ return nx.projected_graph(G, range(n))
venv/lib/python3.14/site-packages/networkx/generators/interval_graph.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for interval graph.
3
+ """
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = ["interval_graph"]
10
+
11
+
12
+ @nx._dispatchable(graphs=None, returns_graph=True)
13
+ def interval_graph(intervals):
14
+ """Generates an interval graph for a list of intervals given.
15
+
16
+ In graph theory, an interval graph is an undirected graph formed from a set
17
+ of closed intervals on the real line, with a vertex for each interval
18
+ and an edge between vertices whose intervals intersect.
19
+ It is the intersection graph of the intervals.
20
+
21
+ More information can be found at:
22
+ https://en.wikipedia.org/wiki/Interval_graph
23
+
24
+ Parameters
25
+ ----------
26
+ intervals : a sequence of intervals, say (l, r) where l is the left end,
27
+ and r is the right end of the closed interval.
28
+
29
+ Returns
30
+ -------
31
+ G : networkx graph
32
+
33
+ Examples
34
+ --------
35
+ >>> intervals = [(-2, 3), [1, 4], (2, 3), (4, 6)]
36
+ >>> G = nx.interval_graph(intervals)
37
+ >>> sorted(G.edges)
38
+ [((-2, 3), (1, 4)), ((-2, 3), (2, 3)), ((1, 4), (2, 3)), ((1, 4), (4, 6))]
39
+
40
+ Raises
41
+ ------
42
+ :exc:`TypeError`
43
+ if `intervals` contains None or an element which is not
44
+ collections.abc.Sequence or not a length of 2.
45
+ :exc:`ValueError`
46
+ if `intervals` contains an interval such that min1 > max1
47
+ where min1,max1 = interval
48
+ """
49
+ intervals = list(intervals)
50
+ for interval in intervals:
51
+ if not (isinstance(interval, Sequence) and len(interval) == 2):
52
+ raise TypeError(
53
+ "Each interval must have length 2, and be a "
54
+ "collections.abc.Sequence such as tuple or list."
55
+ )
56
+ if interval[0] > interval[1]:
57
+ raise ValueError(f"Interval must have lower value first. Got {interval}")
58
+
59
+ graph = nx.Graph()
60
+
61
+ tupled_intervals = [tuple(interval) for interval in intervals]
62
+ graph.add_nodes_from(tupled_intervals)
63
+
64
+ while tupled_intervals:
65
+ min1, max1 = interval1 = tupled_intervals.pop()
66
+ for interval2 in tupled_intervals:
67
+ min2, max2 = interval2
68
+ if max1 >= min2 and max2 >= min1:
69
+ graph.add_edge(interval1, interval2)
70
+ return graph