TheHassanSaud commited on
Commit
33e8f48
·
1 Parent(s): 9c8e0e8

Upload folder using huggingface_hub (part 8)

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 +6 -0
  2. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/METADATA +177 -0
  3. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/RECORD +601 -0
  4. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/WHEEL +5 -0
  5. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/entry_points.txt +2 -0
  6. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt +37 -0
  7. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/top_level.txt +1 -0
  8. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/line.cpython-311.pyc +0 -0
  9. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/mycielski.cpython-311.pyc +0 -0
  10. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-311.pyc +0 -0
  11. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/random_clustered.cpython-311.pyc +0 -0
  12. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/random_graphs.cpython-311.pyc +0 -0
  13. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/small.cpython-311.pyc +0 -0
  14. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/social.cpython-311.pyc +0 -0
  15. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-311.pyc +0 -0
  16. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/stochastic.cpython-311.pyc +0 -0
  17. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/sudoku.cpython-311.pyc +0 -0
  18. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/time_series.cpython-311.pyc +0 -0
  19. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/trees.cpython-311.pyc +0 -0
  20. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/triads.cpython-311.pyc +0 -0
  21. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/atlas.dat.gz +3 -0
  22. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/atlas.py +227 -0
  23. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/classic.py +1091 -0
  24. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/cographs.py +68 -0
  25. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/community.py +1070 -0
  26. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/degree_seq.py +886 -0
  27. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/directed.py +572 -0
  28. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/duplication.py +174 -0
  29. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/ego.py +66 -0
  30. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/expanders.py +499 -0
  31. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/geometric.py +1037 -0
  32. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/harary_graph.py +163 -0
  33. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/internet_as_graphs.py +443 -0
  34. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/intersection.py +125 -0
  35. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/interval_graph.py +70 -0
  36. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/joint_degree_seq.py +664 -0
  37. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/lattice.py +405 -0
  38. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/line.py +501 -0
  39. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/mycielski.py +110 -0
  40. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/nonisomorphic_trees.py +259 -0
  41. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/random_clustered.py +117 -0
  42. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/random_graphs.py +1416 -0
  43. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/small.py +1070 -0
  44. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/social.py +554 -0
  45. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/spectral_graph_forge.py +120 -0
  46. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/stochastic.py +54 -0
  47. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/sudoku.py +131 -0
  48. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/tests/__init__.py +0 -0
  49. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/tests/test_atlas.py +75 -0
  50. pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/tests/test_classic.py +642 -0
.gitattributes CHANGED
@@ -983,3 +983,9 @@ pace_revision_2/.venv-pace/lib/python3.11/site-packages/matplotlib/mpl-data/font
983
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/mpl_toolkits/mplot3d/__pycache__/axes3d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
984
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/mpmath/__pycache__/function_docs.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
985
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
983
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/mpl_toolkits/mplot3d/__pycache__/axes3d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
984
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/mpmath/__pycache__/function_docs.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
985
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
986
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
987
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
988
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/numpy/_core/_multiarray_tests.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
989
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/numpy/_core/_multiarray_umath.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
990
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/numpy/_core/_simd.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
991
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/numpy/_core/lib/libnpymath.a filter=lfs diff=lfs merge=lfs -text
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/METADATA ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: networkx
3
+ Version: 3.6.1
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.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
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.11
33
+ Description-Content-Type: text/x-rst
34
+ License-File: LICENSE.txt
35
+ Provides-Extra: benchmarking
36
+ Requires-Dist: asv; extra == "benchmarking"
37
+ Requires-Dist: virtualenv; extra == "benchmarking"
38
+ Provides-Extra: default
39
+ Requires-Dist: numpy>=1.25; extra == "default"
40
+ Requires-Dist: scipy>=1.11.2; extra == "default"
41
+ Requires-Dist: matplotlib>=3.8; extra == "default"
42
+ Requires-Dist: pandas>=2.0; extra == "default"
43
+ Provides-Extra: developer
44
+ Requires-Dist: pre-commit>=4.1; extra == "developer"
45
+ Requires-Dist: mypy>=1.15; extra == "developer"
46
+ Provides-Extra: doc
47
+ Requires-Dist: sphinx>=8.0; extra == "doc"
48
+ Requires-Dist: pydata-sphinx-theme>=0.16; extra == "doc"
49
+ Requires-Dist: sphinx-gallery>=0.18; extra == "doc"
50
+ Requires-Dist: numpydoc>=1.8.0; extra == "doc"
51
+ Requires-Dist: pillow>=10; extra == "doc"
52
+ Requires-Dist: texext>=0.6.7; extra == "doc"
53
+ Requires-Dist: myst-nb>=1.1; extra == "doc"
54
+ Requires-Dist: intersphinx-registry; extra == "doc"
55
+ Provides-Extra: example
56
+ Requires-Dist: osmnx>=2.0.0; extra == "example"
57
+ Requires-Dist: momepy>=0.7.2; extra == "example"
58
+ Requires-Dist: contextily>=1.6; extra == "example"
59
+ Requires-Dist: seaborn>=0.13; extra == "example"
60
+ Requires-Dist: cairocffi>=1.7; extra == "example"
61
+ Requires-Dist: igraph>=0.11; extra == "example"
62
+ Requires-Dist: scikit-learn>=1.5; extra == "example"
63
+ Requires-Dist: iplotx>=0.9.0; extra == "example"
64
+ Provides-Extra: extra
65
+ Requires-Dist: lxml>=4.6; extra == "extra"
66
+ Requires-Dist: pygraphviz>=1.14; extra == "extra"
67
+ Requires-Dist: pydot>=3.0.1; extra == "extra"
68
+ Requires-Dist: sympy>=1.10; extra == "extra"
69
+ Provides-Extra: release
70
+ Requires-Dist: build>=0.10; extra == "release"
71
+ Requires-Dist: twine>=4.0; extra == "release"
72
+ Requires-Dist: wheel>=0.40; extra == "release"
73
+ Requires-Dist: changelist==0.5; extra == "release"
74
+ Provides-Extra: test
75
+ Requires-Dist: pytest>=7.2; extra == "test"
76
+ Requires-Dist: pytest-cov>=4.0; extra == "test"
77
+ Requires-Dist: pytest-xdist>=3.0; extra == "test"
78
+ Provides-Extra: test-extras
79
+ Requires-Dist: pytest-mpl; extra == "test-extras"
80
+ Requires-Dist: pytest-randomly; extra == "test-extras"
81
+ Dynamic: license-file
82
+
83
+ NetworkX
84
+ ========
85
+
86
+
87
+ .. image::
88
+ https://github.com/networkx/networkx/actions/workflows/test.yml/badge.svg?branch=main
89
+ :target: https://github.com/networkx/networkx/actions/workflows/test.yml
90
+
91
+ .. image::
92
+ https://img.shields.io/pypi/v/networkx.svg?
93
+ :target: https://pypi.python.org/pypi/networkx
94
+
95
+ .. image::
96
+ https://img.shields.io/pypi/l/networkx.svg?
97
+ :target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
98
+
99
+ .. image::
100
+ https://img.shields.io/pypi/pyversions/networkx.svg?
101
+ :target: https://pypi.python.org/pypi/networkx
102
+
103
+ .. image::
104
+ https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute
105
+ :target: https://github.com/networkx/networkx/contribute
106
+
107
+ .. image::
108
+ https://insights.linuxfoundation.org/api/badge/health-score?project=networkx
109
+ :target: https://insights.linuxfoundation.org/project/networkx
110
+
111
+
112
+ NetworkX is a Python package for the creation, manipulation,
113
+ and study of the structure, dynamics, and functions
114
+ of complex networks.
115
+
116
+ - **Website (including documentation):** https://networkx.org
117
+ - **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
118
+ - **Source:** https://github.com/networkx/networkx
119
+ - **Bug reports:** https://github.com/networkx/networkx/issues
120
+ - **Report a security vulnerability:** https://tidelift.com/security
121
+ - **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
122
+ - **GitHub Discussions:** https://github.com/networkx/networkx/discussions
123
+ - **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz
124
+ - **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
125
+
126
+ Simple example
127
+ --------------
128
+
129
+ Find the shortest path between two nodes in an undirected graph:
130
+
131
+ .. code:: pycon
132
+
133
+ >>> import networkx as nx
134
+ >>> G = nx.Graph()
135
+ >>> G.add_edge("A", "B", weight=4)
136
+ >>> G.add_edge("B", "D", weight=2)
137
+ >>> G.add_edge("A", "C", weight=3)
138
+ >>> G.add_edge("C", "D", weight=4)
139
+ >>> nx.shortest_path(G, "A", "D", weight="weight")
140
+ ['A', 'B', 'D']
141
+
142
+ Install
143
+ -------
144
+
145
+ Install the latest released version of NetworkX:
146
+
147
+ .. code:: shell
148
+
149
+ $ pip install networkx
150
+
151
+ Install with all optional dependencies:
152
+
153
+ .. code:: shell
154
+
155
+ $ pip install networkx[default]
156
+
157
+ For additional details,
158
+ please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
159
+
160
+ Bugs
161
+ ----
162
+
163
+ Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
164
+ Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
165
+ and create a pull request (PR). We welcome all changes, big or small, and we
166
+ will help you make the PR if you are new to `git` (just ask on the issue and/or
167
+ see the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
168
+
169
+ License
170
+ -------
171
+
172
+ Released under the `3-clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
173
+
174
+ Copyright (c) 2004-2025, NetworkX Developers
175
+ Aric Hagberg <hagberg@lanl.gov>
176
+ Dan Schult <dschult@colgate.edu>
177
+ Pieter Swart <swart@lanl.gov>
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/RECORD ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ networkx-3.6.1.dist-info/METADATA,sha256=rKXZSpfR9w8wHQM63bY19uZr6Jc6AKukEnY37tLvMWo,6783
2
+ networkx-3.6.1.dist-info/RECORD,,
3
+ networkx-3.6.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
4
+ networkx-3.6.1.dist-info/entry_points.txt,sha256=H2jZaDsDJ_i9H2SwWpwuFel8BrZ9xHKuvh-DQAWW9lQ,94
5
+ networkx-3.6.1.dist-info/licenses/LICENSE.txt,sha256=PPfDoXnYF7I7i4VoIRdp_v35N5fSB9mEuLL6JNAiCzM,1763
6
+ networkx-3.6.1.dist-info/top_level.txt,sha256=s3Mk-7KOlu-kD39w8Xg_KXoP5Z_MVvgB-upkyuOE4Hk,9
7
+ networkx/__init__.py,sha256=OVN8C-x44LgeJWKcb77v-WwfMV7EYqieafkoQdlAl5E,1625
8
+ networkx/algorithms/__init__.py,sha256=sXdgBEDG0qlsOAymWl9zyT-c_luwOQOhWuus6quro0A,6607
9
+ networkx/algorithms/approximation/__init__.py,sha256=1W0c3YlSfVQtNI4-WiQdzMfPqmcrCar5hJQmrwcsVoI,1234
10
+ networkx/algorithms/approximation/clique.py,sha256=b4cnWMJXmmgCyjMI8A_doHZeKS_RQbGqm2L01OpT_Jg,7691
11
+ networkx/algorithms/approximation/clustering_coefficient.py,sha256=SWpSLEhW3DJc1n2fHlSbJSGg3wdoJkN5Y4_tnntn0Ws,2164
12
+ networkx/algorithms/approximation/connectivity.py,sha256=aVXSfUiWEG4gUL0R1u6WZ-h-wheuLP1_suO_pRFB8M4,13118
13
+ networkx/algorithms/approximation/density.py,sha256=_JU9nIH4wneHG6PtEAF_q1oLwy5UUKk--FkTVkkMAMg,15258
14
+ networkx/algorithms/approximation/distance_measures.py,sha256=UEkmKagNw9sj8kiUDdbAeYuzvZ31pgLMXqzliqMkG84,5805
15
+ networkx/algorithms/approximation/dominating_set.py,sha256=5fC90w1CgYR4Xkpqact8iukKY0i57bMmyJW-A9CToUQ,4710
16
+ networkx/algorithms/approximation/kcomponents.py,sha256=MDkoyQbk0gSAm3ZZK35VOsiLJDv7wiDsxfzH5O-ObFs,13285
17
+ networkx/algorithms/approximation/matching.py,sha256=PFof5m9AIq9Xr5Kaa_-mYxI1IBBP7HEkjf-R9wVE3bo,1175
18
+ networkx/algorithms/approximation/maxcut.py,sha256=eTQZqsDQAAUaufni-aDJAY2UzIcajDhRMdj-AcqVkPs,4333
19
+ networkx/algorithms/approximation/ramsey.py,sha256=W5tX7BOQJIM_qNsBeUhCXVWMD8DFdeTycYyk08k4Sqk,1358
20
+ networkx/algorithms/approximation/steinertree.py,sha256=2t58cQQt9OAMRWP1q0RV9QrdNzgasZtPNp6PbA0LFDU,9363
21
+ networkx/algorithms/approximation/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
+ networkx/algorithms/approximation/tests/test_approx_clust_coeff.py,sha256=PGOVEKf2BcJu1vvjZrgTlBBpwM8V6t7yCANjyS9nWF0,1171
23
+ networkx/algorithms/approximation/tests/test_clique.py,sha256=s6HQB-lK3RAu_ftpe2NvIiMu0Ol8tpAdbGvWzucNL6k,3021
24
+ networkx/algorithms/approximation/tests/test_connectivity.py,sha256=gDG6tsgP3ux7Dgu0x7r0nso7_yknIxicV42Gq0It5pc,5952
25
+ networkx/algorithms/approximation/tests/test_density.py,sha256=EgJsX9z2lxWJCpF5NPbYEbE0GIATazCmgj7wFYeObDM,5298
26
+ networkx/algorithms/approximation/tests/test_distance_measures.py,sha256=axgOojplJIgXdopgkjxjAgvzGTQ1FV1oJ5NG-7ICalo,2023
27
+ networkx/algorithms/approximation/tests/test_dominating_set.py,sha256=l4pBDY7pK7Fxw-S4tOlNcxf-j2j5GpHPJ9f4TrMs1sI,2686
28
+ networkx/algorithms/approximation/tests/test_kcomponents.py,sha256=tTljP1FHzXrUwi-oBz5AQcibRw1NgR4N5UE0a2OrOUA,9346
29
+ networkx/algorithms/approximation/tests/test_matching.py,sha256=nitZncaM0605kaIu1NO6_5TFV2--nohUCO46XTD_lnM,186
30
+ networkx/algorithms/approximation/tests/test_maxcut.py,sha256=U6CDZFSLfYDII-1nX9XB7avSz10kTx88vNazJFoLQ1k,2804
31
+ networkx/algorithms/approximation/tests/test_ramsey.py,sha256=h36Ol39csHbIoTDBxbxMgn4371iVUGZ3a2N6l7d56lI,1143
32
+ networkx/algorithms/approximation/tests/test_steinertree.py,sha256=ifBKzrKjRzfMg2g9BKSXVYLvuEbygQPp9rXR4cK99Q8,10727
33
+ networkx/algorithms/approximation/tests/test_traveling_salesman.py,sha256=odnyk7CgLbMGI2QuHxj3BPRX4cCfWHK5N65rj0jMLW8,32048
34
+ networkx/algorithms/approximation/tests/test_treewidth.py,sha256=b_79ZKiW0XX24-GYaeQJ9Zaq7ZFYQT0DcDTkACII3EY,8868
35
+ networkx/algorithms/approximation/tests/test_vertex_cover.py,sha256=FobHNhG9CAMeB_AOEprUs-7XQdPoc1YvfmXhozDZ8pM,1942
36
+ networkx/algorithms/approximation/traveling_salesman.py,sha256=HZU6dbPo3Hiz2-Z3QHLFm5kdGBQwkXPefkVUuW-IC2A,56210
37
+ networkx/algorithms/approximation/treewidth.py,sha256=hfLiPlheQMN7MG6CGR5w7AscKbLu3pTLNYRS13SO0Xo,8389
38
+ networkx/algorithms/approximation/vertex_cover.py,sha256=oIi_yg5O-IisnfmrSof1P4HD-fsZpW69RpvkR_SM5Og,2803
39
+ networkx/algorithms/assortativity/__init__.py,sha256=ov3HRRbeYB_6Qezvxp1OTl77GBpw-EWkWGUzgfT8G9c,294
40
+ networkx/algorithms/assortativity/connectivity.py,sha256=-V0C5MTqtErl86N-gyrZ487MUyiG5x1QFEZKurOpIJA,4220
41
+ networkx/algorithms/assortativity/correlation.py,sha256=0rc4FDi-e8eQRia7gpFrTqjIy-J7V2GtSwOb4QN6WZk,8689
42
+ networkx/algorithms/assortativity/mixing.py,sha256=RRqqkuVwo71LosJLDbeVCVBikqC7I_XZORdsonQsf9Y,7586
43
+ networkx/algorithms/assortativity/neighbor_degree.py,sha256=UMaQWKBkOZ0ZgC8xGt5fXEz8OL1rgwYjt2zKbKEqofI,5282
44
+ networkx/algorithms/assortativity/pairs.py,sha256=w7xnaWxDDteluHoCsqunLlcM6nlcBenO_5Nz87oOEnE,3841
45
+ networkx/algorithms/assortativity/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
46
+ networkx/algorithms/assortativity/tests/base_test.py,sha256=MNeQMLA3oBUCM8TSyNbBQ_uW0nDc1GEZYdNdUwePAm4,2651
47
+ networkx/algorithms/assortativity/tests/test_connectivity.py,sha256=Js841GQLYTLWvc6xZhnyqj-JtyrnS0ska1TFYntxyXA,4978
48
+ networkx/algorithms/assortativity/tests/test_correlation.py,sha256=ddx-yqnVcOfx1dKVNUF695hS3Q-zCmFmCGzK64B7YSE,5068
49
+ networkx/algorithms/assortativity/tests/test_mixing.py,sha256=1kkiMoQXslY-VnT1j00mFbRdj75A4d1b6OPTUOJVgaY,6802
50
+ networkx/algorithms/assortativity/tests/test_neighbor_degree.py,sha256=wphbir1e-h-BAq5rjvWBi4WlgWdseyQbh_KLGQvy5Pc,3934
51
+ networkx/algorithms/assortativity/tests/test_pairs.py,sha256=t05qP_-gfkbiR6aTLtE1owYl9otBSsuJcRkuZsa63UQ,3008
52
+ networkx/algorithms/asteroidal.py,sha256=hIGg9zI4vylRXkrY5wHverTSOeK6dt1Gn2T_JYvGNnU,5500
53
+ networkx/algorithms/bipartite/__init__.py,sha256=FZug-pg0FUDgAdysnKXxDpi1ly8ezxf4UxBPRklqjys,3883
54
+ networkx/algorithms/bipartite/basic.py,sha256=JPC2gGuPvFA6q2CuI5mqLX_9QUGxrsQ8cIwcS0e9P4U,8375
55
+ networkx/algorithms/bipartite/centrality.py,sha256=G280bAqeyXyCmes5NpRqUv2Tc-EHWrMshJ3_f4uqV9U,9156
56
+ networkx/algorithms/bipartite/cluster.py,sha256=8aZRmlQ3g0XtzHyF1kUBBwnzMSjtduquHDH8MxKNSEI,7346
57
+ networkx/algorithms/bipartite/covering.py,sha256=B3ITc016Kk70NBv-1lb30emXnfjlMIQJ7M-FIPCZip0,2163
58
+ networkx/algorithms/bipartite/edgelist.py,sha256=mmiM2Bvh9CxRKCsspbs-90GZedpt7Gj5AGzvJ-aYDSM,11409
59
+ networkx/algorithms/bipartite/extendability.py,sha256=OrYHlS4ruQST-dlQOuleiqHFKpVVNOvrG5aDNFgfckg,3989
60
+ networkx/algorithms/bipartite/generators.py,sha256=p0xgyuJ5hp52NYPu2ryPEKZ0MEktP5VSW2HMK2VdBCo,20408
61
+ networkx/algorithms/bipartite/link_analysis.py,sha256=eVRRQgwzMcUPPu6ccskPk72yc_lmnF5EGqNIdXe-MxA,12772
62
+ networkx/algorithms/bipartite/matching.py,sha256=xsT048Ok_uM0Zhpdc34qswV1zaCGOlJQnsbGTDsm5oo,21637
63
+ networkx/algorithms/bipartite/matrix.py,sha256=rxmjBNHts4hQ-EIlHLE3vIAeGHaMz8Kg_FJ8je5zFyQ,8320
64
+ networkx/algorithms/bipartite/projection.py,sha256=YIUlreqQQ6IPE37OXF32zNIdzEGeyR8aY-7iUENZYVA,17252
65
+ networkx/algorithms/bipartite/redundancy.py,sha256=eGNVo0qW-3unhGhY5VTs2vbc8QmOGve70UDY3ykjhNo,3340
66
+ networkx/algorithms/bipartite/spectral.py,sha256=fu2grV1the_e_G-e_lUdhk8Y9XFe6_p2tPmx3RKntFw,1902
67
+ networkx/algorithms/bipartite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
68
+ networkx/algorithms/bipartite/tests/test_basic.py,sha256=gzbtsQqPi85BznX5REdGBBJVyr9aH4nO06c3eEI4634,4291
69
+ networkx/algorithms/bipartite/tests/test_centrality.py,sha256=PABPbrIyoAziEEQKXsZLl2jT36N8DZpNRzEO-jeu89Y,6362
70
+ networkx/algorithms/bipartite/tests/test_cluster.py,sha256=O0VsPVt8vcY_E1FjjLJX2xaUbhVViI5MP6_gLTbEpos,2801
71
+ networkx/algorithms/bipartite/tests/test_covering.py,sha256=EGVxYQsyLXE5yY5N5u6D4wZq2NcZe9OwlYpEuY6DF3o,1221
72
+ networkx/algorithms/bipartite/tests/test_edgelist.py,sha256=fK35tSekG_-9Ewr5Bhl1bRdwAy247Z9zZ4dQFFDQ9xw,8471
73
+ networkx/algorithms/bipartite/tests/test_extendability.py,sha256=XgPmg6bWiHAF1iQ75_r2NqUxExOQNZRUeYUPzlCa5-E,7043
74
+ networkx/algorithms/bipartite/tests/test_generators.py,sha256=BehRU6SQnWzKsAFoshrN2vpxcPByLAViofGeq38v23E,13203
75
+ networkx/algorithms/bipartite/tests/test_link_analysis.py,sha256=vJMOtYG0vxYQCif_ztnYTUm_13gApfzFiNxChRefONg,6914
76
+ networkx/algorithms/bipartite/tests/test_matching.py,sha256=3-2DMl3tF-g4_xNHvEuY4fZW7S5cqMTO_GUpcz1gkeQ,11973
77
+ networkx/algorithms/bipartite/tests/test_matrix.py,sha256=TlZRVHCTKO2sqhycKFsefvdqP-Se47b_8iZwjtPpQYs,5063
78
+ networkx/algorithms/bipartite/tests/test_project.py,sha256=WhX_yteTrXOdTZLMXpkW2A5ZFIBkw0WsnJRsNITyYtQ,15294
79
+ networkx/algorithms/bipartite/tests/test_redundancy.py,sha256=utxcrQaTrkcEN3kqtObgKNpLZai8B5sMAqLyXatOuUo,917
80
+ networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py,sha256=1jGDgrIx3-TWOCNMSC4zxmZa7LHyMU69DXh3h12Bjag,2358
81
+ networkx/algorithms/boundary.py,sha256=q3JtWssmn9yCB2mBdkjKZjkaxmBhkG9_dJOzmuJiQos,5339
82
+ networkx/algorithms/bridges.py,sha256=CsxueHDOB9aFM5D8GP83u1ZKGzxF193XBpvmMReAcQk,6066
83
+ networkx/algorithms/broadcasting.py,sha256=Amw1oRpr8pdS67aC_9wjJOQomP1IqPvqtE7c0Mf9L70,4974
84
+ networkx/algorithms/centrality/__init__.py,sha256=Er3YoYoj76UfY4P6I0L-0fCQkO7mMU0b3NLsTT2RGWI,558
85
+ networkx/algorithms/centrality/betweenness.py,sha256=8829b5ep0pilM2Muqk5U0rPVQ02kwwedXaVGuQ_hY_U,22814
86
+ networkx/algorithms/centrality/betweenness_subset.py,sha256=CUX0c96gYIORsdjOxVtif2796gOAcMitYoqEnbXDi5c,8114
87
+ networkx/algorithms/centrality/closeness.py,sha256=ehkntG-gApT9uhWJjGaEZQ-tEQ-hdxDT7luf-uVPNAE,10281
88
+ networkx/algorithms/centrality/current_flow_betweenness.py,sha256=kbq9XsZQvrCOdCAYvF67hRni1aqA1sT93WU2i0WfKKI,12717
89
+ networkx/algorithms/centrality/current_flow_betweenness_subset.py,sha256=2qtLgf_3ft5qdDvHFrfYUt6zeQi42Nw7XBpSZRboJIA,8107
90
+ networkx/algorithms/centrality/current_flow_closeness.py,sha256=IvecI8BZE4SgKayEXhKowIJw7S2fD_dN__N-f9TW-ME,3327
91
+ networkx/algorithms/centrality/degree_alg.py,sha256=EFTA1b_GWUbmBy5R9beRQp7yh1X_NwZtk5L6is-mFGk,3894
92
+ networkx/algorithms/centrality/dispersion.py,sha256=M12L2KiVPrC2-SyCXMF0kvxLelgcmvXJkLT_cBHoCTw,3631
93
+ networkx/algorithms/centrality/eigenvector.py,sha256=LAxVqaT3LmuQw20__t1KrgLKPF1Cz-PkTaiSrgPC1FU,13623
94
+ networkx/algorithms/centrality/flow_matrix.py,sha256=Y65m6VbWyYjNK0CInE_lufyEkKy9-TyPmBeXb-Gkz70,3834
95
+ networkx/algorithms/centrality/group.py,sha256=TLlK2eWlcMX7Lvbe2wAcZrmZ9LLTvbRCz-3RbXF0Zug,27960
96
+ networkx/algorithms/centrality/harmonic.py,sha256=OfrDikASbb0Xejjbd1kJ-lQuGT3Gv-rg3pmTtncAbho,2832
97
+ networkx/algorithms/centrality/katz.py,sha256=uVGHAyjqndSd4y4idHjkv0mUhmKmHU5vaEfNWfiKlzc,11042
98
+ networkx/algorithms/centrality/laplacian.py,sha256=qjyW2WnxMFo_mZqiQ4d8PVHLpXi3xNEX148Yikvk_ls,5554
99
+ networkx/algorithms/centrality/load.py,sha256=M2EdPX4gJEYGjMBIJMFKRWGI9uYHbFOWYxsILeaJuOE,6859
100
+ networkx/algorithms/centrality/percolation.py,sha256=YJB8iYgbpjJ3EYK8pl26iSnjgfFsK31ufytRHnUTYYE,4419
101
+ networkx/algorithms/centrality/reaching.py,sha256=Q9rda_dqXBfVaHOi8FgZSYNHKpJ0SHfCbX_myMsIe2I,7255
102
+ networkx/algorithms/centrality/second_order.py,sha256=4CTboP95B6gUtAtSKLfeeE4s9oq0_3hXsXczxL6c_g8,5012
103
+ networkx/algorithms/centrality/subgraph_alg.py,sha256=YXkuyhhhZHmobNFpKDUpfeqSPyBvk97MlcJy5ESWh1s,10520
104
+ networkx/algorithms/centrality/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
105
+ networkx/algorithms/centrality/tests/test_betweenness_centrality.py,sha256=LmHNSaqExAT8kE-eOb_67Z6ckSGD_XqO56OHXhNkbFc,33669
106
+ networkx/algorithms/centrality/tests/test_betweenness_centrality_subset.py,sha256=Y7qigLxQwFJqClJiCrKWGkcOHD467W0b6C5gBb0rFUg,13085
107
+ networkx/algorithms/centrality/tests/test_closeness_centrality.py,sha256=-LtG4ex192Xjgy4JCTfdjdJ3Cd9Op-3XnVvG2GA3FWQ,8728
108
+ networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py,sha256=1sipOadh8bsuzHZ0_7haapKU6Vrn0rbZL5HXvbsto5w,10072
109
+ networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py,sha256=JfRGgPuiF-vJu5fc2_pcJYREEboxcK_dmy-np39c4Aw,5839
110
+ networkx/algorithms/centrality/tests/test_current_flow_closeness.py,sha256=vflQeoNKngrGUiRb3XNlm2X9wR4vKgMSW_sCyMUCQi8,1379
111
+ networkx/algorithms/centrality/tests/test_degree_centrality.py,sha256=Jn_p5lThA3__ZBTDAORwo_EchjXKKkK1NwU_73HHI6M,4101
112
+ networkx/algorithms/centrality/tests/test_dispersion.py,sha256=ROgl_5bGhcNXonNW3ylsvUcA0NCwynsQu_scic371Gw,1959
113
+ networkx/algorithms/centrality/tests/test_eigenvector_centrality.py,sha256=AfUa7GTve0UX6QOdBF6YMipmo-gKhyCu6aT8OCSf8wc,5254
114
+ networkx/algorithms/centrality/tests/test_group.py,sha256=833ME4tGlOGQZz8YANw4MSyeVPpjbyCdYh5X88GOprw,8685
115
+ networkx/algorithms/centrality/tests/test_harmonic_centrality.py,sha256=wI7nStX_kIFJoZQY_i8DXXlZBOJzVnQfOP8yidX0PAU,3867
116
+ networkx/algorithms/centrality/tests/test_katz_centrality.py,sha256=JL0bZZsJe2MQFL6urXgY82wCAwucUvhjaShYZPxpL6U,11240
117
+ networkx/algorithms/centrality/tests/test_laplacian_centrality.py,sha256=9Nd9CfiCn2908BgRZ-cQiMQjpOFDu4Bftod1didWyCE,5898
118
+ networkx/algorithms/centrality/tests/test_load_centrality.py,sha256=Vv3zSW89iELN-8KNbUclmkhOe1LzKdF7U_w34nYovIo,11343
119
+ networkx/algorithms/centrality/tests/test_percolation_centrality.py,sha256=ycQ1fvEZZcWAfqL11urT7yHiEP77usJDSG25OQiDM2s,2591
120
+ networkx/algorithms/centrality/tests/test_reaching.py,sha256=_JVeO1Ri-KybdnGCJ_yNPtJQmT_g77z0DAkU0JYFVGQ,5090
121
+ networkx/algorithms/centrality/tests/test_second_order_centrality.py,sha256=ce0wQ4T33lu23wskzGUnBS7X4BSODlvAX1S5KxlLzOA,1999
122
+ networkx/algorithms/centrality/tests/test_subgraph.py,sha256=vhE9Uh-_Hlk49k-ny6ORHCgqk7LWH8OHIYOEYM96uz0,3729
123
+ networkx/algorithms/centrality/tests/test_trophic.py,sha256=mt--0AUc_8qez2SjauEHVnetC3DMwMAlLME6kgb8Lc0,8796
124
+ networkx/algorithms/centrality/tests/test_voterank.py,sha256=tN5u7pKAnJ_4AiwhPW6EuJZz7FLIG2jYqLKcXFi2urk,1687
125
+ networkx/algorithms/centrality/trophic.py,sha256=7mpFrpgQhwP3Ad1plpJu1WzTGR1YWrIp_SUhM0D8Zww,5328
126
+ networkx/algorithms/centrality/voterank_alg.py,sha256=z_1eq8rSDadEO5W5BbAg1zuOJj2di4FUCkmOwiuK12I,3231
127
+ networkx/algorithms/chains.py,sha256=PPiSq5-GsT1Lsf8fwtGwGDVf1hhv5ZLariWtfzkBbAw,6968
128
+ networkx/algorithms/chordal.py,sha256=L-ILWdVLWE44OkWmEO_4bSo4z6Ro-_zLglfLfTrwdqQ,13411
129
+ networkx/algorithms/clique.py,sha256=SAvORAbZrZ-IpTVuEcarETQihNes-glpNiqoZ7hEgnM,27522
130
+ networkx/algorithms/cluster.py,sha256=sKexvbvRnjuHSAkoJ9_dzCuOWDUDQkT_KjzmkKSoAhE,24851
131
+ networkx/algorithms/coloring/__init__.py,sha256=P1cmqrAjcaCdObkNZ1e6Hp__ZpxBAhQx0iIipOVW8jg,182
132
+ networkx/algorithms/coloring/equitable_coloring.py,sha256=uDcza6PD9qbvwVPUX1MBZbopQdrAEKNk6DpCFkc02tU,16315
133
+ networkx/algorithms/coloring/greedy_coloring.py,sha256=GLXbwSvitsQgmxtOsbgUt4DTkURnb2k0X-7-SNsDW9I,20043
134
+ networkx/algorithms/coloring/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
135
+ networkx/algorithms/coloring/tests/test_coloring.py,sha256=7v_d1xanjYMZCa3dq2hE2hCcyexwWBTEFV5SoLgQDv4,23697
136
+ networkx/algorithms/communicability_alg.py,sha256=0tZvZKY-_GUUB7GsRILxabS2jEpI51Udg5ADI9ADGZw,4545
137
+ networkx/algorithms/community/__init__.py,sha256=vfw5aY7eoL7UDk42e0JPoVzRViCzk5cQf83zbls5p90,1279
138
+ networkx/algorithms/community/asyn_fluid.py,sha256=bsY14UgR5FKLFqhFhHKmPP4-RJsVzH6K8ogsImLnCE8,6010
139
+ networkx/algorithms/community/bipartitions.py,sha256=jqgJyMKOCs8TwI8YM9DO8qzuVZFe4XCnYRGeVAx5P4c,12238
140
+ networkx/algorithms/community/centrality.py,sha256=Yyv5kyf1hf_L7iQ_ZbG8_FAkP638Sc_3N4tCSoB6J1w,6635
141
+ networkx/algorithms/community/community_utils.py,sha256=sUi-AcPYyGrYhnjI9ztt-vrSHLl28lKXxTJPfi5N0c8,908
142
+ networkx/algorithms/community/divisive.py,sha256=yFcKfKkiI6FqEVlBVxLa1fbqI1Yeiqe_A5fpPnYvlAE,6655
143
+ networkx/algorithms/community/kclique.py,sha256=DTr9iUT_XWv0S3Y79KQl6OXefjztNMc9SAHWhdFOxcU,2460
144
+ networkx/algorithms/community/label_propagation.py,sha256=LhzAXSHFCPQ2kG_rPgXb06YKdppO7buApksCC4GI4w8,11878
145
+ networkx/algorithms/community/leiden.py,sha256=dx1N_KEsy30mfJ4729rJ28qaLsnkxoqDnv3UOXV2hWQ,6964
146
+ networkx/algorithms/community/local.py,sha256=w-LK7qlMsQ2YHbZRQP95JvqM2gHGSe4yYZi7CXNkj_M,7316
147
+ networkx/algorithms/community/louvain.py,sha256=jscGGTF6uUnC7yGEZTcE9UFmKsLDFwlZa4ecQyVQrOU,15424
148
+ networkx/algorithms/community/lukes.py,sha256=gzqnup95RR2UzUiPpIt8qkepzZ9dCWqHGQSVPIJDMx8,8115
149
+ networkx/algorithms/community/modularity_max.py,sha256=Qzidmvk2QOIb-S2o4erJvLSeQWcPbLq5TVMrxw15Wc4,18093
150
+ networkx/algorithms/community/quality.py,sha256=oEw-RZBe62janFTTs-ak62APBiF2FpQoBiHv11_4YQY,11943
151
+ networkx/algorithms/community/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
152
+ networkx/algorithms/community/tests/test_asyn_fluid.py,sha256=XziMTOiEhzX6cvJdLeODUC1zjOLWchhHf9Z_9Eb3TME,3738
153
+ networkx/algorithms/community/tests/test_bipartitions.py,sha256=w7kxfw5WjKzIosCdq3eHsvuYhUoElaO9Q3lK0kVyNg4,4639
154
+ networkx/algorithms/community/tests/test_centrality.py,sha256=s8q4k5aThR0OgO9CDQk_PXMxfllmf5uC1GlvyUc_8EY,2932
155
+ networkx/algorithms/community/tests/test_divisive.py,sha256=-Ee40OR-mPDReTngTEhbpx4_uLtNI7cqFkt8cZT9t5Y,3441
156
+ networkx/algorithms/community/tests/test_kclique.py,sha256=iA0SBqwbDfaD2u7KM6ccs6LfgAQY_xxrnW05UIT_tFA,2413
157
+ networkx/algorithms/community/tests/test_label_propagation.py,sha256=IHidFEv7MI781zsdk7XT848rLvLwDk2wBK1FjL-CRv4,7985
158
+ networkx/algorithms/community/tests/test_leiden.py,sha256=bl4jr-Z0m59AISIAl-OLsnATz1lDacNssc-ICKn72Nw,4803
159
+ networkx/algorithms/community/tests/test_local.py,sha256=c-dy1rs1L0ahhDTQwNZP1zNbffjzRgw5IBFTCBV-fas,1809
160
+ networkx/algorithms/community/tests/test_louvain.py,sha256=TwW1nlSKWGJeIKr9QOJ8xGehSY6R0Nz01xsnFqzt0Oo,8071
161
+ networkx/algorithms/community/tests/test_lukes.py,sha256=f_JU-EzY6PwXEkPN8kk5_3NVg6phlX0nrj1f57M49lk,3961
162
+ networkx/algorithms/community/tests/test_modularity_max.py,sha256=XYyPuDkxL4CYFwnpTdU_qD4GydpqgiRAIJO3CHQN_m4,10617
163
+ networkx/algorithms/community/tests/test_quality.py,sha256=sZEy10hh3zlelUmww5r2pk5LxpZAht06PC5zCHxV1bs,5275
164
+ networkx/algorithms/community/tests/test_utils.py,sha256=gomD6rFgAaywxT1Yjdi4ozY-1rC0ina4jgfvWeCvwGE,704
165
+ networkx/algorithms/components/__init__.py,sha256=Dt74KZWp_cJ_j0lL5hd_S50_hia5DKcC2SjuRnubr6M,173
166
+ networkx/algorithms/components/attracting.py,sha256=6az3lgqWhHTXaWUUuOPZfW9t7okliAhooFRotQY5JoM,2712
167
+ networkx/algorithms/components/biconnected.py,sha256=_9GJdPZgqusGKZLzqT9tUSj1XZr2DgohiT6hcHVyil4,12782
168
+ networkx/algorithms/components/connected.py,sha256=s-uvEdHkY8dNxNPS5G8jnk-qTCum-bet_yKAx8_qTXc,7904
169
+ networkx/algorithms/components/semiconnected.py,sha256=BaBMFlQ208vuHOo5y1xeV0PDEI3yDUfH6zFb_jkcVhQ,2030
170
+ networkx/algorithms/components/strongly_connected.py,sha256=oZGBBDzhsrCBQjIfqYlkzvXkE3sF-WTRtYEa5UYy6-k,9911
171
+ networkx/algorithms/components/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
172
+ networkx/algorithms/components/tests/test_attracting.py,sha256=b3N3ZR9E5gLSQWGgaqhcRfRs4KBW6GnnkVYeAjdxC_o,2243
173
+ networkx/algorithms/components/tests/test_biconnected.py,sha256=N-J-dgBgI77ytYUUrXjduLxtDydH7jS-af98fyPBkYc,6036
174
+ networkx/algorithms/components/tests/test_connected.py,sha256=KMYm55BpbFdGXk_B2WozS9rIagQROd7_k0LT3HFQmr4,4815
175
+ networkx/algorithms/components/tests/test_semiconnected.py,sha256=q860lIxZF5M2JmDwwdzy-SGSXnrillOefMx23GcJpw0,1792
176
+ networkx/algorithms/components/tests/test_strongly_connected.py,sha256=Zm7MgUIZbuPPJu66xZH1zfMZQ_3X1YBl2fLCOjph7NQ,6021
177
+ networkx/algorithms/components/tests/test_weakly_connected.py,sha256=_eUx7226dxme_K2WNmvSIwZXQlKNoCuglWOOC3kFUW4,3083
178
+ networkx/algorithms/components/weakly_connected.py,sha256=q5siwSHQYtbKDcVc4dUDzfKh-DClETmuy3jLQN2_K4o,4413
179
+ networkx/algorithms/connectivity/__init__.py,sha256=EvYKw8LJn7wyZECHAsuEkIaSl-cV-LhymR6tqcn90p8,281
180
+ networkx/algorithms/connectivity/connectivity.py,sha256=xck9yth1asWFAM9Hp7UP6vdUh-Kr0IOmq046plOAXPQ,29367
181
+ networkx/algorithms/connectivity/cuts.py,sha256=o-5GRQotOVXsNq7Kx_w7yBBVuGLa57whS2YF5DVb1KQ,23199
182
+ networkx/algorithms/connectivity/disjoint_paths.py,sha256=57ZerbGqn30B8cwomcsS0GScectvP-mgCMb0GH-RYb8,14649
183
+ networkx/algorithms/connectivity/edge_augmentation.py,sha256=cK9S6pRnsKLyb_57guKfrAbLiXL6sMALHCf7pR4tzFM,44063
184
+ networkx/algorithms/connectivity/edge_kcomponents.py,sha256=hqABcfCqZ-rb45I0qYE-X4NtstsKJbxl37FZzzmoXA4,20894
185
+ networkx/algorithms/connectivity/kcomponents.py,sha256=qDDeMqPb5rWbi6EKZwetBft5Qmv6PSUngQTVunJxyy0,8086
186
+ networkx/algorithms/connectivity/kcutsets.py,sha256=zYohzgkR2FODi_Ew2M9uMLb_a9ZP5fNqcXJwMYy6P7o,9371
187
+ networkx/algorithms/connectivity/stoerwagner.py,sha256=WodsJEqKgsmTTcyUBk2u3wV_CXeon-cAzveWgIGgFmA,5431
188
+ networkx/algorithms/connectivity/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
189
+ networkx/algorithms/connectivity/tests/test_connectivity.py,sha256=eSmsi8uQk6MI591JgtSu2elIusb08bmSZS0h9gxb76I,15027
190
+ networkx/algorithms/connectivity/tests/test_cuts.py,sha256=q8dxYBAnsGtIBBPZCjIvMszZvXOYST2cVVsCJvXbIhw,10356
191
+ networkx/algorithms/connectivity/tests/test_disjoint_paths.py,sha256=NLHReLoXSKoA6KPBNRbjF84ktg5PEaaktIj2AII3SDY,8392
192
+ networkx/algorithms/connectivity/tests/test_edge_augmentation.py,sha256=gIu58oxk_uSexawlr3H1ds2HGqkTHHGhhVYUCNmfrb4,15737
193
+ networkx/algorithms/connectivity/tests/test_edge_kcomponents.py,sha256=Bzo77zG79Lv_-OzdI1ZZKO_c13wrnFmfv60FrkDyXI0,16453
194
+ networkx/algorithms/connectivity/tests/test_kcomponents.py,sha256=vLwQOLRevXeeid3e7SSKVpd_OyAJE8PxiAU8GYX0Tf0,9276
195
+ networkx/algorithms/connectivity/tests/test_kcutsets.py,sha256=w5DyrjndNqyT3qxQH6WTBCuBR0ljYXatZCtcT1WeiYM,8974
196
+ networkx/algorithms/connectivity/tests/test_stoer_wagner.py,sha256=A291C30_t2CI1erPCqN1W0DoAj3zqNA8fThPIj4Rku0,3011
197
+ networkx/algorithms/connectivity/utils.py,sha256=gL8LmZnK4GKAZQcIPEhVNYmVi18Mqsqwg4O4j_et56s,3217
198
+ networkx/algorithms/core.py,sha256=6SO5Wz-LSkx6t2DSq0GPmOvFALGe0gVsXdsvno9Fljs,17479
199
+ networkx/algorithms/covering.py,sha256=I_on4DUgmwbtbo-qlBq4YWhOsNjuSHCfVGZNAL-Sefs,5278
200
+ networkx/algorithms/cuts.py,sha256=eqwi5bhCMchItKlRAUw4wGVRtHUK0JzTkaXJFUyxXEw,10419
201
+ networkx/algorithms/cycles.py,sha256=AGpANFoLZ2td8YkGn0cHypASJuRllAwj_-g2Vve7QW8,43302
202
+ networkx/algorithms/d_separation.py,sha256=DpOl1YaI-72_fgUJ2NI3Piuj7EQRQ8xmyAQCRdLgjTw,26089
203
+ networkx/algorithms/dag.py,sha256=OPgrOtnKJVMwxu2AxBGWPZyO7ti6qXa6pn57SsO8FAQ,44673
204
+ networkx/algorithms/distance_measures.py,sha256=cQIRYjP4FtpbA3SP_dOPM6hvwpM1z77oMfmuZ4w8suI,37618
205
+ networkx/algorithms/distance_regular.py,sha256=M9m6qitAtCXYbv2k9hDjF0CpxdeEXPu2_KOI8CCGc_I,8391
206
+ networkx/algorithms/dominance.py,sha256=00Ng1SMzAvxodLTfAeLnXexpPb13IlB_S_mDEuT8JhY,3897
207
+ networkx/algorithms/dominating.py,sha256=yoRB4WCe0wMvJpkbKtNo2fpd0jTVq6b09JsCYcaeR_Y,8145
208
+ networkx/algorithms/efficiency_measures.py,sha256=VKbLKJgdIbno-YnJaLaCZt7TNXXnQPdz8N99uJCo748,4741
209
+ networkx/algorithms/euler.py,sha256=yCqKaGchFSRPTRDXq7u1fH2IXZF94wWf9S10K9-Cd6U,14205
210
+ networkx/algorithms/flow/__init__.py,sha256=rVtMUy6dViPLewjDRntmn15QF0bQwiDdQbZZx9j7Drc,341
211
+ networkx/algorithms/flow/boykovkolmogorov.py,sha256=qFcppmiXz4VKKFd4RbDsiWOqJODtDTHbNr9_UFTjQaU,13334
212
+ networkx/algorithms/flow/capacityscaling.py,sha256=8rng2qO5kawNSxq2S8BNlUMmdvNSoC6R8ekiBGU8LxU,14469
213
+ networkx/algorithms/flow/dinitz_alg.py,sha256=I5nnZVsj0aU8-9Cje0umey407epFzpd7BDJpkI6ESK4,8341
214
+ networkx/algorithms/flow/edmondskarp.py,sha256=PEIwLftevS2VYHaTzzZMSOLPy7QSBPsWPedjx1lR6Cs,8056
215
+ networkx/algorithms/flow/gomory_hu.py,sha256=EuibaxPl65shGM9Jxvaa9WMwMmoczDvXXc2b0E81cqM,6345
216
+ networkx/algorithms/flow/maxflow.py,sha256=GuVA4MlPwdOeCdPRXW2QVW1OdJqgzSpPhEyASr302u4,22975
217
+ networkx/algorithms/flow/mincost.py,sha256=GzMYInS4QcNe0yImGrVXJ0bRd7t5TSSMa9jSeenIoOk,12853
218
+ networkx/algorithms/flow/networksimplex.py,sha256=6F1JNT1pMEMt-C27H3PsdZYF-53SrJMrHaakQ8pD7Ng,25098
219
+ networkx/algorithms/flow/preflowpush.py,sha256=CUKZ0-7X9l7P7qH_2n2Immbf8mFm8vocH2SY0tIwjGo,15721
220
+ networkx/algorithms/flow/shortestaugmentingpath.py,sha256=gXXdkY3nH4d0hXVn0P2-kzfC3DHcuCdrudFdxetflKI,10372
221
+ networkx/algorithms/flow/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
222
+ networkx/algorithms/flow/tests/gl1.gpickle.bz2,sha256=z4-BzrXqruFiGqYLiS2D5ZamFz9vZRc1m2ef89qhsPg,44623
223
+ networkx/algorithms/flow/tests/gw1.gpickle.bz2,sha256=b3nw6Q-kxR7HkWXxWWPh7YlHdXbga8qmeuYiwmBBGTE,42248
224
+ networkx/algorithms/flow/tests/netgen-2.gpickle.bz2,sha256=OxfmbN7ajtuNHexyYmx38fZd1GdeP3bcL8T9hKoDjjA,18972
225
+ networkx/algorithms/flow/tests/test_gomory_hu.py,sha256=aWtbI3AHofIK6LDJnmj9UH1QOfulXsi5NyB7bNyV2Vw,4471
226
+ networkx/algorithms/flow/tests/test_maxflow.py,sha256=4CtGOqeyloAxFSajaxPfGuyVhE0R3IdJf2SuIg4kHKQ,18940
227
+ networkx/algorithms/flow/tests/test_maxflow_large_graph.py,sha256=P2e7G8TKN17zrMeOEbSIkLwK08MjfOtNhPva3nLM-B0,4612
228
+ networkx/algorithms/flow/tests/test_mincost.py,sha256=vI61ZCLoWAzwYU4hU0AJS8Ori8vAWEPzFDCUoiloVRk,17806
229
+ networkx/algorithms/flow/tests/test_networksimplex.py,sha256=tCw5C1hLEwbUbt_ySWgkvRyLKj-1T2wfXV9HT4Fx77Q,14162
230
+ networkx/algorithms/flow/tests/wlm3.gpickle.bz2,sha256=zKy6Hg-_swvsNh8OSOyIyZnTR0_Npd35O9RErOF8-g4,88132
231
+ networkx/algorithms/flow/utils.py,sha256=jexiKM-_BQfSAy15f4iZ_Km7DvRrcdOKqi6hxu9X0MM,6246
232
+ networkx/algorithms/graph_hashing.py,sha256=kS881g6vUvMZms856A_tblq3ljB6BanUbt5az37fSlo,16918
233
+ networkx/algorithms/graphical.py,sha256=1NdlhXuGEgUkHPo47EoNTWUMfdeTpiv7BBVM9ty2ivw,15831
234
+ networkx/algorithms/hierarchy.py,sha256=_KFhCF1Afr2TrkPhqx-1PXUXEtfYLhbRShC58ZKbDGE,1786
235
+ networkx/algorithms/hybrid.py,sha256=z3sIFMOpja1wlj-lI8YI6OIbSLZWHr66uSqyVESZWXY,6209
236
+ networkx/algorithms/isolate.py,sha256=8F4GCBHZIW21CZresBlHuZhvq85ruPH_pnlxYetbHuQ,2251
237
+ networkx/algorithms/isomorphism/__init__.py,sha256=gPRQ-_X6xN2lJZPQNw86IVj4NemGmbQYTejf5yJ32N4,406
238
+ networkx/algorithms/isomorphism/ismags.py,sha256=AwJKq94d5e_RU0PZs5Gm7D73v-eOBBP8QDkpPxUocd0,60177
239
+ networkx/algorithms/isomorphism/isomorph.py,sha256=O2TZtUPe89CsZxoNchv6FyYsGU79kWrwywGFBeonksE,10561
240
+ networkx/algorithms/isomorphism/isomorphvf2.py,sha256=NTc9uCm2RnR9RxuKsAS_70RWD1zJYCJNPhefcJZUi5U,47637
241
+ networkx/algorithms/isomorphism/matchhelpers.py,sha256=PaZ7PjmNNsJO9KoeRrf9JgcDHIcFr1tZckQc_ol4e9I,10884
242
+ networkx/algorithms/isomorphism/temporalisomorphvf2.py,sha256=-1NW81l8kM9orQ2ni9tcNizQzEhOUE9BaBJXjUWqhiI,10948
243
+ networkx/algorithms/isomorphism/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
244
+ networkx/algorithms/isomorphism/tests/iso_r01_s80.A99,sha256=hKzMtYLUR8Oqp9pmJR6RwG7qo31aNPZcnXy4KHDGhqU,1442
245
+ networkx/algorithms/isomorphism/tests/iso_r01_s80.B99,sha256=AHx_W2xG4JEcz1xKoN5TwCHVE6-UO2PiMByynkd4TPE,1442
246
+ networkx/algorithms/isomorphism/tests/si2_b06_m200.A99,sha256=NVnPFA52amNl3qM55G1V9eL9ZlP9NwugBlPf-zekTFU,310
247
+ networkx/algorithms/isomorphism/tests/si2_b06_m200.B99,sha256=-clIDp05LFNRHA2BghhGTeyuXDqBBqA9XpEzpB7Ku7M,1602
248
+ networkx/algorithms/isomorphism/tests/test_ismags.py,sha256=YIrF8xSbnY8zsxiqjSZkzMFXF9TKwZ91m9araTfxJwE,24323
249
+ networkx/algorithms/isomorphism/tests/test_isomorphism.py,sha256=e92l9AcYLKISmXB3hOdKanrvgKlUKuQ0TuXz7xuCD1Q,4576
250
+ networkx/algorithms/isomorphism/tests/test_isomorphvf2.py,sha256=fVZZQgTU_L_kgp6KsiVwy5iLBewVFzXGDl72VQ0CgS0,15303
251
+ networkx/algorithms/isomorphism/tests/test_match_helpers.py,sha256=uuTcvjgf2LPqSQzzECPIh0dezw8-a1IN0u42u8TxwAw,2483
252
+ networkx/algorithms/isomorphism/tests/test_temporalisomorphvf2.py,sha256=k8032J4ItZ4aFHeOraOpiF8y4aPm2O1g44UvUfrQJgg,7343
253
+ networkx/algorithms/isomorphism/tests/test_tree_isomorphism.py,sha256=mZPWRv2sSVJ9PbpGi5MEj5GaFbrp_ha2bL1wre1-Jqo,5681
254
+ networkx/algorithms/isomorphism/tests/test_vf2pp.py,sha256=u_baOdKDdp34CQWwPob8henY90k8_hdK82SQDGesaO0,51386
255
+ networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py,sha256=A8Y-FcGsLPWvmci5oHHDowSeh-Fhl_y88TrvboPZwdw,90251
256
+ networkx/algorithms/isomorphism/tests/test_vf2userfunc.py,sha256=TrXs7E3Ynva18dBmaJDO4QGsySteCwK32cUKw-WkZ0I,6309
257
+ networkx/algorithms/isomorphism/tree_isomorphism.py,sha256=J4RfMpO5LfL5z_wI3xP2wcbK2vMFEsxAQqBddPdw3YA,9033
258
+ networkx/algorithms/isomorphism/vf2pp.py,sha256=jM3mzJNC0EutWHDmDkKIh1JfsB9XbpTkzEC6qXD0Lpo,36681
259
+ networkx/algorithms/isomorphism/vf2userfunc.py,sha256=HiPwyr7nJF1QS9w69MzKf6wGvO8cgjvdS5vW59iwCew,7371
260
+ networkx/algorithms/link_analysis/__init__.py,sha256=UkcgTDdzsIu-jsJ4jBwP8sF2CsRPC1YcZZT-q5Wlj3I,118
261
+ networkx/algorithms/link_analysis/hits_alg.py,sha256=ot5sEhIvQ-JruYgcqCoi_EvNk89UWx_skG4KayIuO9I,10439
262
+ networkx/algorithms/link_analysis/pagerank_alg.py,sha256=e7HuXXXVCG79YG0iuIOr1wqA_zC60hKoXGlMfvh9k1o,17202
263
+ networkx/algorithms/link_analysis/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
264
+ networkx/algorithms/link_analysis/tests/test_hits.py,sha256=BQ7QHXvJDkXtK-_VDFagtdp_-VXxVerwPymjGjzFWA0,2546
265
+ networkx/algorithms/link_analysis/tests/test_pagerank.py,sha256=rUJNa_2nKDSk75Fg1yygMPAqg_Bdk0gGWMDRKY8g1lk,7282
266
+ networkx/algorithms/link_prediction.py,sha256=UYo_LJgoVXcM1iLMXswM2g4jvUJmvxln3e5bVfXxQ10,22253
267
+ networkx/algorithms/lowest_common_ancestors.py,sha256=D1LgoX_ibv2hR-viKEx6l_qp3mWVCkW6YAlGGdoWgXQ,9286
268
+ networkx/algorithms/matching.py,sha256=Xgi-zy9C2pNvGwTixTFV7ut7W-l8s7zUgJha9v8D0s8,44325
269
+ networkx/algorithms/minors/__init__.py,sha256=ceeKdsZ6U1H40ED-KmtVGkbADxeWMTVG07Ja8P7N_Pg,587
270
+ networkx/algorithms/minors/contraction.py,sha256=o5i1UfWpI1KhD4-pVx4yuFJvwi00yJx58Te6GYpys7Y,27606
271
+ networkx/algorithms/minors/tests/test_contraction.py,sha256=31FgiENkElrScHzJrQ3DcKG8W2ieow6zI7PZ9wgVJKE,17674
272
+ networkx/algorithms/mis.py,sha256=BEMv_dW8R6CjMMXJQGIhS4HpS8A8AkLJJWnz3GstuS4,2344
273
+ networkx/algorithms/moral.py,sha256=z5lp42k4kqYk7t_FfszVj5KAC7BxXe6Adik3T2qvA6o,1535
274
+ networkx/algorithms/node_classification.py,sha256=s2yjsHk4mj_6llCuawgGvJ59HyswbcW6ufGQC4UBmG0,6465
275
+ networkx/algorithms/non_randomness.py,sha256=rjIoT7-aqKwGSBNoYxgKniDFgqSDwV8Hh21lkWRYGVE,5787
276
+ networkx/algorithms/operators/__init__.py,sha256=dJ3xOXvHxSzzM3-YcfvjGTJ_ndxULF1TybkIRzUS87Y,201
277
+ networkx/algorithms/operators/all.py,sha256=v_W9ZT3u4STNvT4YI9zYn1Z2PDMhqfh4vfhtO4glaIA,9718
278
+ networkx/algorithms/operators/binary.py,sha256=hziSCLDIVIoTWPV56fED5gI1pErOdyLOQ3Z_E_Nz9As,13150
279
+ networkx/algorithms/operators/product.py,sha256=FQkSIduOv-z1ktVzid2T40759S-BmAfTlya88VytuZc,19632
280
+ networkx/algorithms/operators/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
281
+ networkx/algorithms/operators/tests/test_all.py,sha256=Jn8IfNZ1P4Aa51C0gU58S2A-DPksQUFersWco0kG0Yw,8280
282
+ networkx/algorithms/operators/tests/test_binary.py,sha256=BdZQS-qsWbEbRXuWANvH2eXEv7myAKyuldtQzHj6n4Y,12190
283
+ networkx/algorithms/operators/tests/test_product.py,sha256=i4pBb5A4NmaCsllR1XizyhUToaQFMuLZ-JrywkQFdbU,15155
284
+ networkx/algorithms/operators/tests/test_unary.py,sha256=UZdzbt5GI9hnflEizUWXihGqBWmSFJDkzjwVv6wziQE,1415
285
+ networkx/algorithms/operators/unary.py,sha256=Eo2yeTg-F5uODGWSWR_im5VaKZQ97LyATIuKZcAFQR8,1795
286
+ networkx/algorithms/perfect_graph.py,sha256=aMdQkfcXEySVutIOwngHkvDEy1qinO_92uZFJx6Ydnk,2597
287
+ networkx/algorithms/planar_drawing.py,sha256=AXuoT3aFgEtCeMnAaUsRqjxCABdNYZ8Oo9sGOKBQto0,16254
288
+ networkx/algorithms/planarity.py,sha256=nN6QCMz9PJYRqnAa06qEDANdd9bxsbO64PQdbVEGwk4,49887
289
+ networkx/algorithms/polynomials.py,sha256=iP30_mcOlj81Vrzt4iB_ZZxYiRokubs-O1i9RW4pgTw,11278
290
+ networkx/algorithms/reciprocity.py,sha256=1WMhLbSMkVPxRPlfUvbgO5FgVvJHn1doXQF4WuqSLQk,2855
291
+ networkx/algorithms/regular.py,sha256=fEHD4VBREbJwSlR48okVZBuwgvD76GXdT28NitJI8qQ,4877
292
+ networkx/algorithms/richclub.py,sha256=kARzso3M6wnUcAJo2g8ga_ZtigL2czDNzeUDzBtRfqo,4892
293
+ networkx/algorithms/shortest_paths/__init__.py,sha256=Rmxtsje-mPdQyeYhE8TP2NId-iZEOu4eAsWhVRm2Xqk,285
294
+ networkx/algorithms/shortest_paths/astar.py,sha256=0pEnYNzG7Z86zWqyFe0OL8HTlQO9PwjDABy_ypC30_A,8937
295
+ networkx/algorithms/shortest_paths/dense.py,sha256=5Y8ziU-RsWZRTzxEEzg5gB7f4j9yxbNhplTbLaMliG8,8261
296
+ networkx/algorithms/shortest_paths/generic.py,sha256=-7wIqqDWeScy8brYFkdt68nuxkSgXVs1iXcwGWoBZAU,25337
297
+ networkx/algorithms/shortest_paths/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
298
+ networkx/algorithms/shortest_paths/tests/test_astar.py,sha256=F0zXZ7R0eXP8Et4F3mrCtdtfE1-tQTGB2ATcFveDUHI,8989
299
+ networkx/algorithms/shortest_paths/tests/test_dense.py,sha256=ievl4gu3Exl_31hp4OKcsAGPb3g3_xFUM4t3NnvrG_A,6747
300
+ networkx/algorithms/shortest_paths/tests/test_dense_numpy.py,sha256=IEwhjPNTlc2H1on-B3WhFoyLkDkJVdAFBjn675XALHA,2299
301
+ networkx/algorithms/shortest_paths/tests/test_generic.py,sha256=CQJxa5by1xE1a2E8iZm8GAtiPy_DILcrB4dIyWVM_qM,20609
302
+ networkx/algorithms/shortest_paths/tests/test_unweighted.py,sha256=r1F5qVEDZnzPn5yJ71Rp-Z7pq33CzJFfZmDhVBekR9Y,5879
303
+ networkx/algorithms/shortest_paths/tests/test_weighted.py,sha256=dzMts7Y1mMUuz4zEz4adEqYUNoXi9BMf-oyzQ0BMG3s,35502
304
+ networkx/algorithms/shortest_paths/unweighted.py,sha256=iuJAO3WzB1p-fwpDyGM4snuFB5k57KIsVGcAJUhCpi0,17825
305
+ networkx/algorithms/shortest_paths/weighted.py,sha256=PphAp7PmN9qpWzkLudePIVgvySh_SGDi5GhdQN5iufk,84155
306
+ networkx/algorithms/similarity.py,sha256=E8P8vWqCR-r2SFVSqW9Y-Bb4I4R7BzUc_jzhiCYx7tU,72679
307
+ networkx/algorithms/simple_paths.py,sha256=8oG_bRDVRrBKVCDEjZLHW3Qyzrv5KVynp-Hl0m5SNmA,31091
308
+ networkx/algorithms/smallworld.py,sha256=3xT-z2_CVdp5-Ap8vF6fsd3DiavDYtspFNZrcwcpXG0,13565
309
+ networkx/algorithms/smetric.py,sha256=_Aj4BIMnafiXbJtLkvAfAnIEMdI9OcVvMy6kk9KKTns,770
310
+ networkx/algorithms/sparsifiers.py,sha256=4T8pMlh-usEHA2-rZFh-CmZbBY9dcXIHjoqR-oJ2hSw,10048
311
+ networkx/algorithms/structuralholes.py,sha256=rYaVkndSJ3kFxbjkhfQd6uMBpYO7NNlcsOPR0Xbiy7Y,12626
312
+ networkx/algorithms/summarization.py,sha256=CygTsSthyCKHs0ZTZsCgWnyaT8annQbLpUtahmfY9Sw,23251
313
+ networkx/algorithms/swap.py,sha256=NVZMmlnkdxgwwNw5GDrc8waNERcdCu52ydHcBdOA_hw,14744
314
+ networkx/algorithms/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
315
+ networkx/algorithms/tests/test_asteroidal.py,sha256=DnWI5_jnaaZMxtG44XD0K690HZs8ez7HU_9dSR-p6eA,502
316
+ networkx/algorithms/tests/test_boundary.py,sha256=1OSJh32FYFhAVYB5zqxhZGEXZLS0HPp9kvfHZvWmD3o,6227
317
+ networkx/algorithms/tests/test_bridges.py,sha256=jSCguECho0GNHnu0vpRh1twyfGP6tWFcaYL1rgvc8mU,4026
318
+ networkx/algorithms/tests/test_broadcasting.py,sha256=GqjkpHC5Z7ogZZdf1qsz5B1lmX-Pd5pFMD5e3QRPAkI,3034
319
+ networkx/algorithms/tests/test_chains.py,sha256=4fR5Uh2NMrTZGT1yR6sAsQEP3uy1U3UnwjcXLFk9d1Y,4196
320
+ networkx/algorithms/tests/test_chordal.py,sha256=DPdNPY7KtqCsCwYVb4xQfnIm-z35dUJIWxNHtAiQLAQ,4438
321
+ networkx/algorithms/tests/test_clique.py,sha256=RX1Q38DRDmclLLJ04pfE5RIFAy86EuTZ2QAERrtkjS4,9772
322
+ networkx/algorithms/tests/test_cluster.py,sha256=b0OXtKvUYGzDxBrnIbPh8A3vo3jmRYOFzW02MVSWYgo,19320
323
+ networkx/algorithms/tests/test_communicability.py,sha256=4KK9wU9gAUqHAAAyHwAKpq2dV9g415s_X0qd7Tt83gU,2938
324
+ networkx/algorithms/tests/test_core.py,sha256=Q3bi_c0LpxZ-0VopHU6Lyzkb_JKseVT16H45qDuax9A,9619
325
+ networkx/algorithms/tests/test_covering.py,sha256=EeBjQ5mxcVctgavqXZ255T8ryFocuxjxdVpIxVUNFvw,2718
326
+ networkx/algorithms/tests/test_cuts.py,sha256=gKm9VDtnmwFli6kgwV1ktEFI_rw84p2Sg02Em6SoW5Q,5376
327
+ networkx/algorithms/tests/test_cycles.py,sha256=CBEQ_kNlHg5PHb9vKMS9ot-lqUuvs_cAgaPtnEQn76g,34851
328
+ networkx/algorithms/tests/test_d_separation.py,sha256=cxoAOA_EahXQHFsFaRopz6cp3h5sMnD7D_isq4_EuWI,10714
329
+ networkx/algorithms/tests/test_dag.py,sha256=sd6OlsrK57rY7x6vMfWSf11tEiKH5BakNp7747KvCnA,29407
330
+ networkx/algorithms/tests/test_distance_measures.py,sha256=kF-pR5WbVBs1d_IO-U6Dr-sf8MaRHfxc_D286sBN62E,28793
331
+ networkx/algorithms/tests/test_distance_regular.py,sha256=w27OTUtAI0VQv7cikkOdJg4bo4q7xTNIVE8nbU_x7b8,2915
332
+ networkx/algorithms/tests/test_dominance.py,sha256=rD-m7LVQpqrOTCUJrli43lYpezYxajfkcNd3xvGhTj8,9811
333
+ networkx/algorithms/tests/test_dominating.py,sha256=5WwPlrQ6_pFaVx_-K4D5cHNbCZL23qp-PytgsXDuS4Q,3112
334
+ networkx/algorithms/tests/test_efficiency.py,sha256=QKWMvyjCG1Byt-oNp7Rz_qxnVeT77Zk27lrzI1qH0mA,1894
335
+ networkx/algorithms/tests/test_euler.py,sha256=L4L1ljHVxQxjQQludO2r6k3UZU7WAY_N6WYUjFx1fEk,11209
336
+ networkx/algorithms/tests/test_graph_hashing.py,sha256=ribxC8ZkNxkkBDyjSZ8P2f8J6y5y4g-Ik-k5hBgZcx4,31567
337
+ networkx/algorithms/tests/test_graphical.py,sha256=uhFjvs04odxABToY4IRig_CaUTpAC3SfZRu1p1T7FwY,5366
338
+ networkx/algorithms/tests/test_hierarchy.py,sha256=uW8DqCdXiAeypkNPKcAYX7aW86CawYH84Q0bW4cDTXo,1184
339
+ networkx/algorithms/tests/test_hybrid.py,sha256=kQLzaMoqZcKFaJ3D7PKbY2O-FX59XDZ1pN5un8My-tk,720
340
+ networkx/algorithms/tests/test_isolate.py,sha256=LyR0YYHJDH5vppQzGzGiJK-aaIV17_Jmla8dMf93olg,555
341
+ networkx/algorithms/tests/test_link_prediction.py,sha256=lP6slSHwXdzdJzNSeMTUsP88ypSqe6EeVy-bUP2d-48,20451
342
+ networkx/algorithms/tests/test_lowest_common_ancestors.py,sha256=5ZT_17q-5ipw7NNgNisaVcxIxrY6XeQQaUlBXHx9k9g,14160
343
+ networkx/algorithms/tests/test_matching.py,sha256=1IKeUi49HR8aAOm2V4cmBL2NGXvF9cb8mqW9jnkNGuY,18319
344
+ networkx/algorithms/tests/test_max_weight_clique.py,sha256=M1eoy8OtuQVZkEvNMauV9vqR6hHtOCrtq6INv2qzMyA,6739
345
+ networkx/algorithms/tests/test_mis.py,sha256=Z2tKoqbs-AFPzEBDYO7S8U-F7usLfZJ2l6j2DpZUts4,1865
346
+ networkx/algorithms/tests/test_moral.py,sha256=15PZgkx7O9aXQB1npQ2JNqBBkEqPPP2RfeZzKqY-GNU,452
347
+ networkx/algorithms/tests/test_node_classification.py,sha256=NgJJKUHH1GoD1GE3F4QRYBLM3fUo_En3RNtZvhqCjlg,4663
348
+ networkx/algorithms/tests/test_non_randomness.py,sha256=iDHCFzFvxGXCi_vWnv-DkXHcmO9uU6KVpYGMCpHKQG8,1678
349
+ networkx/algorithms/tests/test_perfect_graph.py,sha256=Y2mpreh5TNCkqn4PDO57MFkgYozt-tlZFScKH3TZJRg,609
350
+ networkx/algorithms/tests/test_planar_drawing.py,sha256=fBTd9JzDkTqNQz7GBQCS9lShU1P3lWRQ7L-E5WhSdlA,8765
351
+ networkx/algorithms/tests/test_planarity.py,sha256=2iy22H4APB2K0DiPcoWmiQV9BTQlJ9JSOexubN14sU0,17312
352
+ networkx/algorithms/tests/test_polynomials.py,sha256=baI0Kua1pRngRC6Scm5gRRwi1bl0iET5_Xxo3AZTP3A,1983
353
+ networkx/algorithms/tests/test_reciprocity.py,sha256=X_PXWFOTzuEcyMWpRdwEJfm8lJOfNE_1rb9AAybf4is,1296
354
+ networkx/algorithms/tests/test_regular.py,sha256=ppXES6zvpsppoZmzXPFim-S4ZMWPG2Zhhmlgc67y_GA,2951
355
+ networkx/algorithms/tests/test_richclub.py,sha256=Wl8aE0CSswaXJiHCQ42IkyRvjWaJQZ2OQcbC7LpIgfo,3962
356
+ networkx/algorithms/tests/test_similarity.py,sha256=l02q6PMnweng8EfUm6Z0yor-Uy-zd6WN0Tm28lh3pBU,41248
357
+ networkx/algorithms/tests/test_simple_paths.py,sha256=7U9wCXz4SHK0XeYrs1k2KjYgrYVQDnts2ggQLzU18p0,25181
358
+ networkx/algorithms/tests/test_smallworld.py,sha256=bmoNDxIuhV0bBKWh2hgFw0XYTPCc2rgg1y77uMg6rE8,2390
359
+ networkx/algorithms/tests/test_smetric.py,sha256=VM14L4X1AABvINDL9qKXzlech_Q2g4Aee-ozWM2Qrr4,144
360
+ networkx/algorithms/tests/test_sparsifiers.py,sha256=1GRbQy1vfmwv6eUhP4Io0aykH2VyTJfFWmncrXmTqi4,4044
361
+ networkx/algorithms/tests/test_structuralholes.py,sha256=F0xZ1nlKJLGmQDebDiExju4fMffu79qThnyF7ZGA53A,7592
362
+ networkx/algorithms/tests/test_summarization.py,sha256=uNyaUstobIEu6M_Hexik-3YiYTRSy_XO6LUqoE4wazw,21312
363
+ networkx/algorithms/tests/test_swap.py,sha256=WJtGMkSbAd1Cv06VaUeDVHosNOtdigsqEspyux0ExCs,6144
364
+ networkx/algorithms/tests/test_threshold.py,sha256=x0hqqbH65nbDNEUV0vYz0J2TSmmBbJ0daEgLIR7CRm0,9733
365
+ networkx/algorithms/tests/test_time_dependent.py,sha256=NmuV2kDo4nh2MeN0hwcJf0QSDtqMD0dfSeeKSsYBtQ8,13342
366
+ networkx/algorithms/tests/test_tournament.py,sha256=tfOPwN7YHnw0oxl9d7-ErPBFKz6KBfSc5S3tbGrGHs8,4107
367
+ networkx/algorithms/tests/test_triads.py,sha256=CbnFABCMDU0X1mzu3tzW4-WL2qn5ptaDTOShNaTjIwk,8219
368
+ networkx/algorithms/tests/test_vitality.py,sha256=p5lPWCtVMtbvxDw6TJUaf8vpb0zKPoz5pND722xiypQ,1380
369
+ networkx/algorithms/tests/test_voronoi.py,sha256=M4B6JtkJUw56ULEWRs1kyVEUsroNrnb5FBq9OioAyHM,3477
370
+ networkx/algorithms/tests/test_walks.py,sha256=X8cb-YvGHiiqbMEXuKMSdTAb9WtVtbHjIESNSqpJTmU,1499
371
+ networkx/algorithms/tests/test_wiener.py,sha256=uT6Es_OFbJqxnVY7lImzlJSRTQS4eJnMaKotKbObMd8,4186
372
+ networkx/algorithms/threshold.py,sha256=maOMixTxDibvBL2BkVcaYz1Co_09jg8d7DpAW2blNnY,30776
373
+ networkx/algorithms/time_dependent.py,sha256=PAeJ7Yt8kUqbDgvBaz_ZfUFZg-w-vf1gPC0HO6go_TI,5762
374
+ networkx/algorithms/tournament.py,sha256=TyWD0P-8JYXsckulbyr-bkKOoc0gLUHK59R1RQm2We4,11613
375
+ networkx/algorithms/traversal/__init__.py,sha256=YtFrfNjciqTOI6jGePQaJ01tRSEQXTHqTGGNhDEDb_8,142
376
+ networkx/algorithms/traversal/beamsearch.py,sha256=Vn0U4Wck8ICShIAGggv3tVtQWVW0ABEz_hcBsGrql6o,3473
377
+ networkx/algorithms/traversal/breadth_first_search.py,sha256=KGpFnXuCQrDwcQg27Irtrqu7hcIWlFSlVWGpA26XbHA,18259
378
+ networkx/algorithms/traversal/depth_first_search.py,sha256=2V4T3tGujcAtV3W6WcTQUjGAAe3b1rqinONowUhLsa8,16795
379
+ networkx/algorithms/traversal/edgebfs.py,sha256=JJ1mQCmv8WydqQtIVQC1HqkqEFDMeKVzJ_hexwU8sXA,6333
380
+ networkx/algorithms/traversal/edgedfs.py,sha256=T1xHGr8p_eC1pEUyCP-kpaYlIY_la_ms-J0-50c4EDk,6041
381
+ networkx/algorithms/traversal/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
382
+ networkx/algorithms/traversal/tests/test_beamsearch.py,sha256=bzUcswZ1qo0ecDZYSER_4enbsW6SjTpb_3Nb3fqmkAo,900
383
+ networkx/algorithms/traversal/tests/test_bfs.py,sha256=tGQSiYhc6BxaZEuw-G3ZxVfYLN7q0zrP_BeKl6EfxkU,6447
384
+ networkx/algorithms/traversal/tests/test_dfs.py,sha256=rQMq7GToM6CVU3WwIZfmqa-HrqlmvIT1DryRU7NbU_U,10580
385
+ networkx/algorithms/traversal/tests/test_edgebfs.py,sha256=8oplCu0fct3QipT0JB0-292EA2aOm8zWlMkPedfe6iY,4702
386
+ networkx/algorithms/traversal/tests/test_edgedfs.py,sha256=HGmC3GUYSn9XLMHQpdefdE6g-Uh3KqbmgEEXBcckdYc,4775
387
+ networkx/algorithms/tree/__init__.py,sha256=wOh_v70XEdFHL2qUMje7qkJI5RcjFNrDremJYl4zzkg,182
388
+ networkx/algorithms/tree/branchings.py,sha256=B0c_uKpcnV2SwJMZJRK0BMEz8LkvIcOhv1y0AI0gTnY,34339
389
+ networkx/algorithms/tree/coding.py,sha256=l9P4jhmhg_9uYBVMNSmLYW8btHJH07-Sl2SIKJtO1LA,13466
390
+ networkx/algorithms/tree/decomposition.py,sha256=lY_rqx9JxnLEkp1wiAv0mX62PGPwGQ6SW4Jp48o8aiw,3071
391
+ networkx/algorithms/tree/distance_measures.py,sha256=Dwtk2BRTXmEGjFFtpiAbk02HrX2Hb5kjXusfwn6nm9M,6981
392
+ networkx/algorithms/tree/mst.py,sha256=UMeSnnpKrPeq7a_w_tR415w9TOLltmzuXyIy_HfqbAU,46145
393
+ networkx/algorithms/tree/operations.py,sha256=TjfLQpxwlaLgdOnhLkdzHfZ68yFCYz6BMzzh_d_2mJc,4048
394
+ networkx/algorithms/tree/recognition.py,sha256=bYnaDN0ZaIWTgq0tbPEHAcdxQBWZpDvWypZarBbA334,7569
395
+ networkx/algorithms/tree/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
396
+ networkx/algorithms/tree/tests/test_branchings.py,sha256=euky-3tFOV5CVV5v_yFawuVGCaqTuTrKtBIkCygwhiA,17731
397
+ networkx/algorithms/tree/tests/test_coding.py,sha256=XC6SbfA2zVGH4FyJJyv6o8eOnBu7FNzNot3SKs7QmEo,3955
398
+ networkx/algorithms/tree/tests/test_decomposition.py,sha256=vnl_xoQzi1LnlZL25vXOZWwvaWmon3-x222OKt4eDqE,1871
399
+ networkx/algorithms/tree/tests/test_distance_measures.py,sha256=WNzqjgDuFLUt_NgjD4R8gGhbYhQ3F5a4HZfBBipunv0,3389
400
+ networkx/algorithms/tree/tests/test_mst.py,sha256=D3o217cjuUtf0TxZ9ks1wqQ4cpwVySoOBYfg0Jmr1AU,32376
401
+ networkx/algorithms/tree/tests/test_operations.py,sha256=ybU96kROTVJRTyjLG7JSJjYlPxaWmYjUVJqbXV5VGGI,1961
402
+ networkx/algorithms/tree/tests/test_recognition.py,sha256=qeMEIvg-j2MqaU-TNIQhCcXxao8vTBy0wjpU7jr2iw8,4521
403
+ networkx/algorithms/triads.py,sha256=FqOtB5fi40k4EoA_-bV1TBwimsRihAqrVdFyNnq0hns,14233
404
+ networkx/algorithms/vitality.py,sha256=8M1cubIydO49El2kwVCURHZ2UwCtfGVFeGS8-JYt1ko,2289
405
+ networkx/algorithms/voronoi.py,sha256=07SnSpxLDz4k6K59Jo-VTNA-Qy5knaHfBC-y_5vAOLQ,3183
406
+ networkx/algorithms/walks.py,sha256=5A611YwX9D8IZYbFcQ4aT3cuKZWHq1QOzCpy4mAM6XE,2312
407
+ networkx/algorithms/wiener.py,sha256=88sTSCXt6gakAmxP4BD_ir1R-_0NOUxXlyZKeElzzvs,9221
408
+ networkx/classes/__init__.py,sha256=Q9oONJrnTFs874SGpwcbV_kyJTDcrLI69GFt99MiE6I,364
409
+ networkx/classes/coreviews.py,sha256=5Dgi8PjMZJz_Uun2SXL5a6mxtAfdbm3kPIdbgzSTXgM,13251
410
+ networkx/classes/digraph.py,sha256=ys8hmrqUjto00TDwBNCwiaNAahFbizNvKkkx84BxS30,48781
411
+ networkx/classes/filters.py,sha256=PCy7BsoIby8VcamqDjZQiNAe_5egI0WKUq-y5nc9unQ,2817
412
+ networkx/classes/function.py,sha256=pPpy-TgC33yNX3nPMZoSjfVmaiiSTbfwYJJMFGa35hQ,43794
413
+ networkx/classes/graph.py,sha256=bY5x7WQHoQxSZow95OUAmU8UZaYV0ZWQvhrEFjSAt0Y,72337
414
+ networkx/classes/graphviews.py,sha256=ulUTLozEK_hj_4TGHdgvxveR2-rb92Q14jjxH4oH4Go,8520
415
+ networkx/classes/multidigraph.py,sha256=qBhb2eoiMejz5fkv-ihLsqwQKKYnUjUANHnrWZKYQfI,37036
416
+ networkx/classes/multigraph.py,sha256=7SD8_ZT7yE1EfIotDzIgITSj4HkKLxZfj6ZnWjQ7hIA,47931
417
+ networkx/classes/reportviews.py,sha256=u0hNZqaWXCfLMP_lq835XCIVStkZQJ9HaQPeDPPoo88,46132
418
+ networkx/classes/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
419
+ networkx/classes/tests/dispatch_interface.py,sha256=gffiIwS4OZWKIgRkfvghixQds5hY0tPBi86p0lpV7eY,6823
420
+ networkx/classes/tests/historical_tests.py,sha256=oUJSS-QhvInhad9AJCXCCk0x7OzAclIF9RjBSZ6gB58,16291
421
+ networkx/classes/tests/test_coreviews.py,sha256=qzdozzWK8vLag-CAUqrXAM2CZZwMFN5vMu6Tdrwdf-E,12128
422
+ networkx/classes/tests/test_digraph.py,sha256=uw0FuEu3y_YI-PSGuQCRytFpXLF7Eye2fqLJaKbXkBc,12283
423
+ networkx/classes/tests/test_digraph_historical.py,sha256=8TbDcvmLgfllfGomTRStSpT5WIQiTHLt-rS3GyJEItU,3668
424
+ networkx/classes/tests/test_filters.py,sha256=fBLig8z548gsBBlQw6VJdGZb4IcqJj7_0mi2Fd2ncEM,5851
425
+ networkx/classes/tests/test_function.py,sha256=PDtKrB31Ix1-abPc8NzuP-h7HOOIRtkL5bvcOE8mshU,35481
426
+ networkx/classes/tests/test_graph.py,sha256=ST12bvoj72uzUDpnyVz-Zx0mlXV2CegcEg3txT5qS6k,31798
427
+ networkx/classes/tests/test_graph_historical.py,sha256=EVAndjelyyZ9laQCTrj6KR6lhdmG8Y1raP2IrxkZxdA,258
428
+ networkx/classes/tests/test_graphviews.py,sha256=JoTS_ZY7u4dBHEttD55WT1pD47FcvELBEzw-uJQiqv4,11496
429
+ networkx/classes/tests/test_multidigraph.py,sha256=ryTKegCoYixXbAqOn3mIt9vSMb5666Dv-pfMkXEjoUE,16342
430
+ networkx/classes/tests/test_multigraph.py,sha256=0vFQO3RCJaBpzXvnQzdWa_qYLHNo_I9DICYhPZJNUMk,18777
431
+ networkx/classes/tests/test_reportviews.py,sha256=MgP9_cKlw4aTU5m1XbsNTM3ZjmO7roOOf-7x-Hn9xKs,41332
432
+ networkx/classes/tests/test_special.py,sha256=wl-Idzdc55eOQ4Tn5SNqOG21AjwLb2TTp9x102Qx3Ms,4053
433
+ networkx/classes/tests/test_subgraphviews.py,sha256=iIMkbHdtJsgDlcdphhE_uUTJ0VGTGFzKIVvMd7oamoU,13669
434
+ networkx/conftest.py,sha256=5-BwqVMgfaZyRZICFpG1plLMJ2G1IchSQVEuRjoBtyc,8041
435
+ networkx/convert.py,sha256=Xmkhacuyw9CDviBTZPlH6nmD-JabSk0aPcVmGgp4LeY,16143
436
+ networkx/convert_matrix.py,sha256=9BXSEXzCEIte1nx8f35cWhXo-EVYjOkuW4H3Jutq-oE,45342
437
+ networkx/drawing/__init__.py,sha256=rnTFNzLc4fis1hTAEpnWTC80neAR88-llVQ-LObN-i4,160
438
+ networkx/drawing/layout.py,sha256=5MUr2NTp4L3IbOShTb_m7fD4SH1HPZKJPJ4G1mJC3Js,66346
439
+ networkx/drawing/nx_agraph.py,sha256=4Vd8JQH4BQ7BaRO8TmYlqBKmFPm8e2XcDDJiqFkNMxM,14248
440
+ networkx/drawing/nx_latex.py,sha256=PySHixo2YhGV0xbKLroaX-_XcI1L5u8IF8nP6xdV2NU,24846
441
+ networkx/drawing/nx_pydot.py,sha256=9KbNVrVcU5gFmo1GPpB_UMBXcD1tnBYDBzxHvgg6mOs,9992
442
+ networkx/drawing/nx_pylab.py,sha256=MHoDvYE4FO9kJRogqeB1FfqrStyLcjQTq3fr67vAjOE,103488
443
+ networkx/drawing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
444
+ networkx/drawing/tests/baseline/test_display_complex.png,sha256=3YPN6JEuyq1KEpRgSnH-2yECI81frU_5fw0VxHlwo9A,142315
445
+ networkx/drawing/tests/baseline/test_display_empty_graph.png,sha256=XsOkBCZlt-55c40ElwEapBENVfmdc4TZKIF1ufs5Dzk,3257
446
+ networkx/drawing/tests/baseline/test_display_house_with_colors.png,sha256=uiEx6_2RddHG-516OsRVM0AG7M5CGiAo4tpDgbgPKIU,26002
447
+ networkx/drawing/tests/baseline/test_display_labels_and_colors.png,sha256=RfA1OtWYKttP5_LDScIcx8MFbC-_5wljXeDsZAqAqDU,62571
448
+ networkx/drawing/tests/baseline/test_display_shortest_path.png,sha256=6W7EMitF8jojJ8epmaYEWpjhYRlzBlL7QV98MStxvvQ,35264
449
+ networkx/drawing/tests/baseline/test_house_with_colors.png,sha256=FQi9pIRFwjq4gvgB8cDdBHL5euQUJFw6sQlABf2kRVo,21918
450
+ networkx/drawing/tests/test_agraph.py,sha256=5cbqLGEgJmAocWOMSikv_9ykRWfBymjGfalvKbR1_KE,8725
451
+ networkx/drawing/tests/test_image_comparison_pylab_mpl.py,sha256=2UtGMJFpcWiG0sQtXIYT0j03Q2LhGqWM2G-pfKY3Sw0,6340
452
+ networkx/drawing/tests/test_latex.py,sha256=YQjLxsZnx7_CX2sJ3nN0cUiJzC7p6UhyFN6ufbox5G0,8621
453
+ networkx/drawing/tests/test_layout.py,sha256=2_wJfBcCcHwBm1JRrQiLMcnNWoaURX6F4LFcn5OPul4,23709
454
+ networkx/drawing/tests/test_pydot.py,sha256=X9b66gWqMgdTEyRJ7Zmy5kL9cr22waI688K9BJUf4Bk,4973
455
+ networkx/drawing/tests/test_pylab.py,sha256=TMGpM6IKm5vTSu9Dbfm8mvyhMqz2aAu1gafGbLiOU1k,54825
456
+ networkx/exception.py,sha256=hC8efPfIzOFo0jiWiQbTPaNKuNTuUwhp9RPw--pdv4U,3787
457
+ networkx/generators/__init__.py,sha256=EoYB5c5ZE4rsNKZvl1TRQy2Vo2D3T2H-YunyD2i6sa0,1366
458
+ networkx/generators/atlas.dat.gz,sha256=c_xBbfAWSSNgd1HLdZ9K6B3rX2VQvyW-Wcht47dH5B0,8887
459
+ networkx/generators/atlas.py,sha256=cbki_oYDi_7vniSesqJZ-PCEM3BvnzEdjSc3TA3s1xc,6955
460
+ networkx/generators/classic.py,sha256=Wzey-Pl6Rm-ELYyg2lIb0lFZAxywRr5iQxv7zo3d9Bk,32658
461
+ networkx/generators/cographs.py,sha256=-WR4_yrNk_X5nj7egb7A22eKPVymOdIYM-IftSRH4WA,1891
462
+ networkx/generators/community.py,sha256=_p_4OfItbg8nS0b3EvojCXZ8cESdC-0Gj67V5w2veuM,34911
463
+ networkx/generators/degree_seq.py,sha256=Hxv1rjY2NS8qmnvSWh4rcvublDZzor3D3IiB2OAFXoE,30493
464
+ networkx/generators/directed.py,sha256=rtgf2Imf34SogrWA0BNgDltlA5kUv_l2NkxKPcJgGtQ,18149
465
+ networkx/generators/duplication.py,sha256=hmYAHJBez7WlfdVGGa288JFUBHoIUdVqEGCodApKOr4,5831
466
+ networkx/generators/ego.py,sha256=ylW-UMvg9C8cqygw9vrBNLGAVZJT4U5EWbU4gaT_H1g,1894
467
+ networkx/generators/expanders.py,sha256=gJioNdyhBOnNcjh0qC-kfbFs1SEMU5_o9GHy85pdJXk,15184
468
+ networkx/generators/geometric.py,sha256=6slgS0vraxql67AOP9lWzBrpNbx_OBZCoBwYuSkQQXg,39461
469
+ networkx/generators/harary_graph.py,sha256=N2_b49xrET0bjZ4C7sgcG2xLv64ia9xjvJ2NB75CAz8,4950
470
+ networkx/generators/internet_as_graphs.py,sha256=RuhEW9rQ8f5VzeIyZe6GqSWgxKtMVuwqnzv0llW3FeY,14226
471
+ networkx/generators/intersection.py,sha256=EFm0AOjnqyp8KcT7kGWqANq-_vq9kQ0d_0DzVyQyP-o,4101
472
+ networkx/generators/interval_graph.py,sha256=ZTmdgQbBx3M6sysGWXbGyngYYOC1TAXD3Ozkw4deQFw,2204
473
+ networkx/generators/joint_degree_seq.py,sha256=nyp86NC_4XvzvwpwwzKrrCSz1i_4bESSDtVjWvpkWFg,24773
474
+ networkx/generators/lattice.py,sha256=5iujIY5pF_VhbWEE2osM5i7uuYqs5Hv1wS33WGPMn_o,14740
475
+ networkx/generators/line.py,sha256=DDQZvD2Y2c-4kc_xTuUWpmmViLftTSGKFukgqSiyI_c,17540
476
+ networkx/generators/mycielski.py,sha256=xBX2m77sCzumoH5cAGitksvEEW-ocbCnbdaN7fKUtVk,3314
477
+ networkx/generators/nonisomorphic_trees.py,sha256=62FIt4Qx-giwDflNKP5BrDoCv1HbQmlp6oVGjqGeRlE,6993
478
+ networkx/generators/random_clustered.py,sha256=i_NdvvchHvsvbwgQtoWSY_pLwvhO9Lh02MSZXzgGb7c,4183
479
+ networkx/generators/random_graphs.py,sha256=WIJ4v8PSNpHePclSCQ3IcLWwcipZJ2Cn9pNx6XenBEo,51669
480
+ networkx/generators/small.py,sha256=duBVJgz4f2TByU4SdyRGHw7YyLHrlrr0UFw6spVTCbo,30967
481
+ networkx/generators/social.py,sha256=brzAScpAxWGRExE9J7FuiJ29QZxBm8bXpRgCc0IoHP0,23416
482
+ networkx/generators/spectral_graph_forge.py,sha256=9r6d9f5Y03KPX138sQTKWG3_RjeiYQVUJJWwCHqG4MA,4282
483
+ networkx/generators/stochastic.py,sha256=Qg9vWm9EOug2OQVIHL_dZ5HrXc16lxnWyzX52KWNEPI,1981
484
+ networkx/generators/sudoku.py,sha256=kLM2AP0H4966uYiNO1oAFEmv5qBftU_bOfYucRxexM0,4288
485
+ networkx/generators/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
486
+ networkx/generators/tests/test_atlas.py,sha256=nwXJL4O5jUqhTwqhkPxHY8s3KXHQTDEdsfbg4MsSzVQ,2530
487
+ networkx/generators/tests/test_classic.py,sha256=eRtftt3fcr5kYJI8PffuY3tWOnn4u0yJZwKav1bZACU,24400
488
+ networkx/generators/tests/test_cographs.py,sha256=v2fYoolmfwfCpJZRKRtH9YKyWcuJkaPOQUpDK9DMsn0,553
489
+ networkx/generators/tests/test_community.py,sha256=FGcDo3Ajb-yYc5kUkFbVfOJVMG-YppbAtjgBPcVzjLc,11311
490
+ networkx/generators/tests/test_degree_seq.py,sha256=V_X-Mc0H2sqEy7OTJb4yY9khsi-9HD-DIA_fvngW-VE,7284
491
+ networkx/generators/tests/test_directed.py,sha256=e8C7AF2whjaqdxga7WSvCrtIx7ByBG_JyJ9gYqJ6HBA,6020
492
+ networkx/generators/tests/test_duplication.py,sha256=UdIGDF_fishanWid1xO_aH4NDfie8xpIqd26qndhOqI,3155
493
+ networkx/generators/tests/test_ego.py,sha256=8v1Qjmkli9wIhhUuqzgqCzysr0C1Z2C3oJMCUoNvgY4,1327
494
+ networkx/generators/tests/test_expanders.py,sha256=Cf0cCJOplngPlN23OVqDcrny2QZlrYMrrWHeIi0APaA,6363
495
+ networkx/generators/tests/test_geometric.py,sha256=gnVm4dam_Er88YwaNpNZC6mjJjfgwMYhyLOtU9oPn1o,18087
496
+ networkx/generators/tests/test_harary_graph.py,sha256=GiX5LXXJaNxzjvd-Nyw_QuARzbFGkA6zE1R1eX8mclw,4936
497
+ networkx/generators/tests/test_internet_as_graphs.py,sha256=3et6aawAPZ9bPNWqADJ3bQN_2KhyqPf8VFgrBAkgABQ,8514
498
+ networkx/generators/tests/test_intersection.py,sha256=hcIit5fKfOn3VjMhz9KqovZK9tzxZfmC6ezvA7gZAvM,819
499
+ networkx/generators/tests/test_interval_graph.py,sha256=JYMi-QMkJQdBU9uOdfm0Xr6MEYqIbhU5oSDa6D3tSb0,4277
500
+ networkx/generators/tests/test_joint_degree_seq.py,sha256=8TXTZI3Um2gBXtP-4yhGKf9vCi78-NVmWZw9r9WG3F8,4270
501
+ networkx/generators/tests/test_lattice.py,sha256=iYB2F7j1Qt3QAHkhGnGKcgiRNB1Gq9MxtE3152XdS_A,10102
502
+ networkx/generators/tests/test_line.py,sha256=Dt1R1Hnm47aq_8FX9gRFdby0sV3Oxyap1R5Z4eK0A5o,10516
503
+ networkx/generators/tests/test_mycielski.py,sha256=fwZLO1ybcltRy6TzCel8tPBil1oZWv9QSXs779H6Xt0,946
504
+ networkx/generators/tests/test_nonisomorphic_trees.py,sha256=KFRwMfx-x_a9oGvPlhtMlWGk__rKgm77Gk4LtbxFrZE,2945
505
+ networkx/generators/tests/test_random_clustered.py,sha256=SalHqWvpnXA3QrDRMjLx15dk2c4Us8Ck52clUERoUI8,1297
506
+ networkx/generators/tests/test_random_graphs.py,sha256=R5dHYuzAbcIBduoP7PUdoV-6CFauqk5r1Ak1Slwlsho,19565
507
+ networkx/generators/tests/test_small.py,sha256=y9rZHpwQG4Bjp-sHJp18rM3A0uEGOUkbklqlJec11ao,8074
508
+ networkx/generators/tests/test_spectral_graph_forge.py,sha256=x4jyTiQiydaUPWYaGsNFsIB47PAzSSwQYCNXGa2B4SU,1594
509
+ networkx/generators/tests/test_stochastic.py,sha256=f-5KD3RpoQf369gXHH7KGebE19g5lCkXR_alcwmFm_s,2179
510
+ networkx/generators/tests/test_sudoku.py,sha256=dgOmk-B7MxCVkbHdZzsLZppQ61FAArVy4McSVL8Afzo,1968
511
+ networkx/generators/tests/test_time_series.py,sha256=rgmFcitlKa_kF6TzJ2ze91lSmNJlqjhvgrYet0AUZx8,2230
512
+ networkx/generators/tests/test_trees.py,sha256=Pvh0MvTKaRuZuwWL-wpJIC0zlBAcnTirpSLJi-9c7qc,7006
513
+ networkx/generators/tests/test_triads.py,sha256=K8anVEP8R90Y172IrKIOrYRWRJBGeqxNqU9isX7Ybxs,333
514
+ networkx/generators/time_series.py,sha256=_DMiY9X95O_9sK2BSeeTb2yMWfStBwKFWwn6FUOXN4Q,2439
515
+ networkx/generators/trees.py,sha256=KvKYhZwwSl1KKMyKBe_6G_UTpLwLLeqdWwRkWJ2Xxz4,36517
516
+ networkx/generators/triads.py,sha256=7kScTf3ITDi3qsSa-IvGMpa9diEaFwQnRuIf3Tv4UBI,2452
517
+ networkx/lazy_imports.py,sha256=pZWn3f6NCY-lGtViKQh11NJ5Cn-cXBKhvacMycg3844,5764
518
+ networkx/linalg/__init__.py,sha256=7iyNZ_YYBnlsW8zSfhUgvEkywOrUWfpIuyS86ZOKlG8,568
519
+ networkx/linalg/algebraicconnectivity.py,sha256=qAjHk8Ew2av9HM-Sevf99alKHWkeo4R76U-1SFn2so8,20790
520
+ networkx/linalg/attrmatrix.py,sha256=gG2cZZm4N7PQhXuq5nxZq1S_OmW61641rdRnrDiX_ws,15900
521
+ networkx/linalg/bethehessianmatrix.py,sha256=Q5dJZOMopwWnvpSdebfo9QSQABEmLy-z1_hGCWsopDo,2513
522
+ networkx/linalg/graphmatrix.py,sha256=NIs2uWGS_8lJJ5IQ8Og9aIWHawghtlCDWifqOIKV2-c,5623
523
+ networkx/linalg/laplacianmatrix.py,sha256=YrzwLTLoGIisJVS2NLaD9g4fA3VDKzlYo1u3yOCVrF4,16722
524
+ networkx/linalg/modularitymatrix.py,sha256=R_VITtgIkGenxlsCLN4u6CYxj3_HiPXfeU29yarntRo,4706
525
+ networkx/linalg/spectrum.py,sha256=aRY7ApYv5HxrO_4O8brxpZRw3SJU3fYzlgMwhEIXcrc,4215
526
+ networkx/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
527
+ networkx/linalg/tests/test_algebraic_connectivity.py,sha256=uXq7h1fCmvcUyJhh3DujyZvJH2SGlgo-JRdLbff3bKI,13735
528
+ networkx/linalg/tests/test_attrmatrix.py,sha256=I8p_ME5Cq__SZJoxla1y5ynGaa_b4UruZRcuzPOh_wE,2833
529
+ networkx/linalg/tests/test_bethehessian.py,sha256=WQM3H_y1GWrtM2B659HYQ2vvYGs-4H9V1qeo3Bx75B4,1268
530
+ networkx/linalg/tests/test_graphmatrix.py,sha256=6y-DSezX5slSms8LtEJcoggI4wP_duBqodNYWKKvM4w,8655
531
+ networkx/linalg/tests/test_laplacian.py,sha256=sIJ64KVVCUcK3b4ohF-443222vR64myIlV6addwwfWs,13953
532
+ networkx/linalg/tests/test_modularity.py,sha256=Xs7iaUr_QqcxG0t0xHx54iYbM2VyQNmFeANovTMJomE,3056
533
+ networkx/linalg/tests/test_spectrum.py,sha256=Hrl3FE0Z0u4urwY5eNMx0VcH4IRTYgudT04EmfhkosA,2769
534
+ networkx/readwrite/__init__.py,sha256=TvSbnGEHQ5F9CY2tkpjWYOyrUj6BeW3sc6P4_IczbKA,561
535
+ networkx/readwrite/adjlist.py,sha256=XkmtOO-aP-BGLoIjMoSXEOhCIEQz1TJcSrhMHGPCJTc,9050
536
+ networkx/readwrite/edgelist.py,sha256=XwemCOs-xNet3mVIGpxol3RgFVJVa1iXsgBonAHDmug,14292
537
+ networkx/readwrite/gexf.py,sha256=B5rj7Ra1XHSZR4qO5DRJMAEgWwQfiL0IKlE85fzQZ5Q,40438
538
+ networkx/readwrite/gml.py,sha256=JcP0hsDKwpZOPzZeXdoEiKBBNd94Ox8y7_cjT5AVBT4,31193
539
+ networkx/readwrite/graph6.py,sha256=dED6yWelHARFvyKniX8xSTtqj1-asDs1vUBWuZOG9cA,11684
540
+ networkx/readwrite/graphml.py,sha256=sb-D5I5gmqyNj_TSNUvLn-96NBXtOAPFMEKvT3mkdTw,39326
541
+ networkx/readwrite/json_graph/__init__.py,sha256=37XJPMmilcwwo8KqouLWUly7Yv5tZ7IKraMHbBRx3fI,677
542
+ networkx/readwrite/json_graph/adjacency.py,sha256=WM6fdncV87WDLPOfF-IbOlOOBMX0utUjJ09UsxtwRAo,4716
543
+ networkx/readwrite/json_graph/cytoscape.py,sha256=NaHGbwLuQCx_GB5R7Uag2ACKSmrpCFQKsRk3y9hE6Io,5841
544
+ networkx/readwrite/json_graph/node_link.py,sha256=9hr4sk2fIHYDPuwSyyGNLNKDhahf6aFAEsIRhd5V890,7850
545
+ networkx/readwrite/json_graph/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
546
+ networkx/readwrite/json_graph/tests/test_adjacency.py,sha256=jueQE3Z_W5BZuCjr0hEsOWSfoQ2fP51p0o0m7IcXUuE,2456
547
+ networkx/readwrite/json_graph/tests/test_cytoscape.py,sha256=vFoDzcSRI9THlmp4Fu2HHhIF9AUmECWs5mftVWjaWWs,2044
548
+ networkx/readwrite/json_graph/tests/test_node_link.py,sha256=3RbMNRlLBLN86EG4YyCvNmA3ISzmECqr17EqTcov3kI,3364
549
+ networkx/readwrite/json_graph/tests/test_tree.py,sha256=zBXv3_db2XGxFs3XQ35btNf_ku52aLXXiHZmmX4ixAs,1352
550
+ networkx/readwrite/json_graph/tree.py,sha256=K4rF4Kds4g0JhgcPTrrR_I3Pswpze8yCVH4M-WF9nn0,3851
551
+ networkx/readwrite/leda.py,sha256=mtuIRKecfykiInePt-oIw91JB1vIgNXuUEbuBInO7Hs,2852
552
+ networkx/readwrite/multiline_adjlist.py,sha256=TyvVZih3DIYaCQ6MC7XF8GuGBfcYIX-q-ccYu2Qs05M,11384
553
+ networkx/readwrite/p2g.py,sha256=wDPg_3u42rlsv8pFtVLbZIjo-BN6dd95jCxFAoEC_6E,3253
554
+ networkx/readwrite/pajek.py,sha256=0Xli27YbjyW5Ny6-qqVOtBmhZkPj4i3cJPvwjU3mMjM,8746
555
+ networkx/readwrite/sparse6.py,sha256=kGEbDmnK1qcR5I6LZnPKYXLe7Qp6esT6gftkwSt1xcs,10442
556
+ networkx/readwrite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
557
+ networkx/readwrite/tests/test_adjlist.py,sha256=aCDyLpv8cekWwEZgv5rB4gtwUvor7_YDArTYvL2ngPs,12756
558
+ networkx/readwrite/tests/test_edgelist.py,sha256=5_rZ5rI_o8VDJr-R4besR-XcPwKY8-dHn4VmrrlBorc,10190
559
+ networkx/readwrite/tests/test_gexf.py,sha256=TJLCj0ULSewUt5PlqEuoD8yhZoc6jFPqElIyQYhoKz0,21327
560
+ networkx/readwrite/tests/test_gml.py,sha256=SIuCCSoH9psZdjKkrJfdGHbMROhUsfms70B71rnozUU,21399
561
+ networkx/readwrite/tests/test_graph6.py,sha256=WMQmTgrI_VDcli1Gl5cjM17EFKc8_AkwoR14FLS1sXQ,6559
562
+ networkx/readwrite/tests/test_graphml.py,sha256=RHZqs_-0Vw_NboMK1Sq65Nmk_XPAjfvnsgiPCptnpnI,67633
563
+ networkx/readwrite/tests/test_leda.py,sha256=_5F4nLLQ1oAZQMZtTQoFncZL0Oc-IsztFBglEdQeH3k,1392
564
+ networkx/readwrite/tests/test_p2g.py,sha256=0kvtohQuM2zjw88ogoDMhVbFcm85R3Sk2_yFdQ7TcWg,1319
565
+ networkx/readwrite/tests/test_pajek.py,sha256=VxMk_TXQE1R-2t2B2OTSkwvPepKNYwExDbdlTDb0SOM,4696
566
+ networkx/readwrite/tests/test_sparse6.py,sha256=zpd0hUPtOqwAJiuke4FXWFaQVa6Fa47dgIdHpCWXQ6U,5288
567
+ networkx/readwrite/tests/test_text.py,sha256=x1N97hD31HPkj9Wn2PYti5-gcwaFNnStkaN_38HKnIg,55319
568
+ networkx/readwrite/text.py,sha256=u62a-zG_7NpJD4Bh6kBZbUntORVM4XZId9zGX9wJBGQ,29140
569
+ networkx/relabel.py,sha256=0HptAQOBToKhLZzxscd6FQpzVCNMlYmiHjHul69ct8o,10300
570
+ networkx/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
571
+ networkx/tests/test_all_random_functions.py,sha256=T6bYvfqCmBfqOHAAJAqCv95VceTqdT32cN740HZTWH0,8549
572
+ networkx/tests/test_convert.py,sha256=SoIVrqJFF9Gu9Jff_apfbpqg8QhkfC6QW4qzoSM-ukM,12731
573
+ networkx/tests/test_convert_numpy.py,sha256=wivMBF5pmDd2FdrHX72J4Xt26IxTIfb12G-t-TWch40,19032
574
+ networkx/tests/test_convert_pandas.py,sha256=VXumRYNIV2jdr4dfDsRidqpUDXHlgbhAFhaiqWlcx6s,13361
575
+ networkx/tests/test_convert_scipy.py,sha256=IO9Xfke5Vk0SC4c7UR4YbQMjVZBuADQBt_wlMaOxTSQ,10381
576
+ networkx/tests/test_exceptions.py,sha256=XYkpPzqMepSw3MPRUJN5LcFsUsy3YT_fiRDhm0OeAeQ,927
577
+ networkx/tests/test_import.py,sha256=Gm4ujfH9JkQtDrSjOlwXXXUuubI057wskKLCkF6Z92k,220
578
+ networkx/tests/test_lazy_imports.py,sha256=PylxEvRtD8ekwH-1M1sjnV_4uyhCYQl4WvlyF6ah0wo,2675
579
+ networkx/tests/test_relabel.py,sha256=2qua3Z45m9mXkBQYmD82h17-pK6fYHJLpntn6ILj9cg,14554
580
+ networkx/tests/test_removed_functions_exception_messages.py,sha256=V6AyU-RHQmilakEMJ1kpK4HSgzKbmimIxu0pBQ1DVaY,177
581
+ networkx/utils/__init__.py,sha256=7pxleRNpBWuL3FEQz3CzKLn17b6_eSwkM7dqnL1okDk,302
582
+ networkx/utils/backends.py,sha256=IDXNJjBWOfcqPm3Any5-kfwU9hZTH33R16gr3vZ6wnE,96862
583
+ networkx/utils/configs.py,sha256=1LFNHgkR6CdXxTpNT8j4QdQ5vn5r7BTzPlxFYrEm7_E,15440
584
+ networkx/utils/decorators.py,sha256=rRgAZw6glxOBYN6n5kkbQ7RS43EH3eVbJ5F91-uk0IM,44713
585
+ networkx/utils/heaps.py,sha256=98tdylWKqrLQKdNlpjT2NvIpuOF2mT2Lhh5OzVg3Hu8,10355
586
+ networkx/utils/mapped_queue.py,sha256=WdIRk27D_ArmPs9tdpvQLQCV4Tmus212BQhxsFIMYgk,10184
587
+ networkx/utils/misc.py,sha256=zifBxwKM3msQsmMVg5vAMDo84ZPByU_yEig0VPS0iek,22844
588
+ networkx/utils/random_sequence.py,sha256=kk3F8_5cazolIeSL_eDdZzQ15aB3b5lHazef9kM1NNw,5303
589
+ networkx/utils/rcm.py,sha256=t2LJq6BG39JnPl_353nM8eDfGWy3LVL8BdrBZCcAy2g,4618
590
+ networkx/utils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
591
+ networkx/utils/tests/test__init.py,sha256=QE0i-lNE4pG2eYjB2mZ0uw7jPD-7TdL7Y9p73JoWQmo,363
592
+ networkx/utils/tests/test_backends.py,sha256=VzzgmdT_ymvQ7EKB4BbdntkBYaO5w6OgXzvr7pbgQsY,7784
593
+ networkx/utils/tests/test_config.py,sha256=eBAiwADWJgCAIyJjgF3-zn89VPIGftiWMWyccpFnyMU,8717
594
+ networkx/utils/tests/test_decorators.py,sha256=dm3b5yiQPlnlT_4pSm0FwK-xBGV9dcnhv14Vh9Jiz1o,14050
595
+ networkx/utils/tests/test_heaps.py,sha256=qCuWMzpcMH1Gwu014CAams78o151QD5YL0mB1fz16Yw,3711
596
+ networkx/utils/tests/test_mapped_queue.py,sha256=l1Nguzz68Fv91FnAT7y7B0GXSoje9uoWiObHo7TliGM,7354
597
+ networkx/utils/tests/test_misc.py,sha256=3rKc5wy3qAwk1JdVZYD8FaTF4_4Y1_Tq1nbza6eR_jc,13965
598
+ networkx/utils/tests/test_random_sequence.py,sha256=yvfWhJQJJqM1W-_etHo7BsLXA18YiHcLaF-IdhSwcYA,1502
599
+ networkx/utils/tests/test_rcm.py,sha256=UvUAkgmQMGk_Nn94TJyQsle4A5SLQFqMQWld1tiQ2lk,1421
600
+ networkx/utils/tests/test_unionfind.py,sha256=j-DF5XyeJzq1hoeAgN5Nye2Au7EPD040t8oS4Aw2IwU,1579
601
+ networkx/utils/union_find.py,sha256=NxKlBlyS71A1Wlnt28L-wyZoI9ExZvJth_0e2XSVris,3338
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [networkx.backends]
2
+ nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.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-2025, 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.
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx-3.6.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ networkx
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/line.cpython-311.pyc ADDED
Binary file (21.8 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/mycielski.cpython-311.pyc ADDED
Binary file (5.26 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-311.pyc ADDED
Binary file (9.82 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/random_clustered.cpython-311.pyc ADDED
Binary file (5.41 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/random_graphs.cpython-311.pyc ADDED
Binary file (59.3 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/small.cpython-311.pyc ADDED
Binary file (36.4 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/social.cpython-311.pyc ADDED
Binary file (29.5 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-311.pyc ADDED
Binary file (5.74 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/stochastic.cpython-311.pyc ADDED
Binary file (2.66 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/sudoku.cpython-311.pyc ADDED
Binary file (5.08 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/time_series.cpython-311.pyc ADDED
Binary file (3.38 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/trees.cpython-311.pyc ADDED
Binary file (44.4 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/__pycache__/triads.cpython-311.pyc ADDED
Binary file (2.89 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/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
pace_revision_2/.venv-pace/lib/python3.11/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 1213 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())
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/classic.py ADDED
@@ -0,0 +1,1091 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.exception import NetworkXError
19
+ from networkx.utils import nodes_or_number, pairwise
20
+
21
+ __all__ = [
22
+ "balanced_tree",
23
+ "barbell_graph",
24
+ "binomial_tree",
25
+ "complete_graph",
26
+ "complete_multipartite_graph",
27
+ "circular_ladder_graph",
28
+ "circulant_graph",
29
+ "cycle_graph",
30
+ "dorogovtsev_goltsev_mendes_graph",
31
+ "empty_graph",
32
+ "full_rary_tree",
33
+ "kneser_graph",
34
+ "ladder_graph",
35
+ "lollipop_graph",
36
+ "null_graph",
37
+ "path_graph",
38
+ "star_graph",
39
+ "tadpole_graph",
40
+ "trivial_graph",
41
+ "turan_graph",
42
+ "wheel_graph",
43
+ ]
44
+
45
+
46
+ # -------------------------------------------------------------------
47
+ # Some Classic Graphs
48
+ # -------------------------------------------------------------------
49
+
50
+
51
+ def _tree_edges(n, r):
52
+ if n == 0:
53
+ return
54
+ # helper function for trees
55
+ # yields edges in rooted tree at 0 with n nodes and branching ratio r
56
+ nodes = iter(range(n))
57
+ parents = [next(nodes)] # stack of max length r
58
+ while parents:
59
+ source = parents.pop(0)
60
+ for i in range(r):
61
+ try:
62
+ target = next(nodes)
63
+ parents.append(target)
64
+ yield source, target
65
+ except StopIteration:
66
+ break
67
+
68
+
69
+ @nx._dispatchable(graphs=None, returns_graph=True)
70
+ def full_rary_tree(r, n, create_using=None):
71
+ """Creates a full r-ary tree of `n` nodes.
72
+
73
+ Sometimes called a k-ary, n-ary, or m-ary tree.
74
+ "... all non-leaf nodes have exactly r children and all levels
75
+ are full except for some rightmost position of the bottom level
76
+ (if a leaf at the bottom level is missing, then so are all of the
77
+ leaves to its right." [1]_
78
+
79
+ .. plot::
80
+
81
+ >>> nx.draw(nx.full_rary_tree(2, 10))
82
+
83
+ Parameters
84
+ ----------
85
+ r : int
86
+ branching factor of the tree
87
+ n : int
88
+ Number of nodes in the tree
89
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
90
+ Graph type to create. If graph instance, then cleared before populated.
91
+
92
+ Returns
93
+ -------
94
+ G : networkx Graph
95
+ An r-ary tree with n nodes
96
+
97
+ References
98
+ ----------
99
+ .. [1] An introduction to data structures and algorithms,
100
+ James Andrew Storer, Birkhauser Boston 2001, (page 225).
101
+ """
102
+ G = empty_graph(n, create_using)
103
+ G.add_edges_from(_tree_edges(n, r))
104
+ return G
105
+
106
+
107
+ @nx._dispatchable(graphs=None, returns_graph=True)
108
+ def kneser_graph(n, k):
109
+ """Returns the Kneser Graph with parameters `n` and `k`.
110
+
111
+ The Kneser Graph has nodes that are k-tuples (subsets) of the integers
112
+ between 0 and ``n-1``. Nodes are adjacent if their corresponding sets are disjoint.
113
+
114
+ Parameters
115
+ ----------
116
+ n: int
117
+ Number of integers from which to make node subsets.
118
+ Subsets are drawn from ``set(range(n))``.
119
+ k: int
120
+ Size of the subsets.
121
+
122
+ Returns
123
+ -------
124
+ G : NetworkX Graph
125
+
126
+ Examples
127
+ --------
128
+ >>> G = nx.kneser_graph(5, 2)
129
+ >>> G.number_of_nodes()
130
+ 10
131
+ >>> G.number_of_edges()
132
+ 15
133
+ >>> nx.is_isomorphic(G, nx.petersen_graph())
134
+ True
135
+ """
136
+ if n <= 0:
137
+ raise NetworkXError("n should be greater than zero")
138
+ if k <= 0 or k > n:
139
+ raise NetworkXError("k should be greater than zero and smaller than n")
140
+
141
+ G = nx.Graph()
142
+ # Create all k-subsets of [0, 1, ..., n-1]
143
+ subsets = list(itertools.combinations(range(n), k))
144
+
145
+ if 2 * k > n:
146
+ G.add_nodes_from(subsets)
147
+
148
+ universe = set(range(n))
149
+ comb = itertools.combinations # only to make it all fit on one line
150
+ G.add_edges_from((s, t) for s in subsets for t in comb(universe - set(s), k))
151
+ return G
152
+
153
+
154
+ @nx._dispatchable(graphs=None, returns_graph=True)
155
+ def balanced_tree(r, h, create_using=None):
156
+ """Returns the perfectly balanced `r`-ary tree of height `h`.
157
+
158
+ .. plot::
159
+
160
+ >>> nx.draw(nx.balanced_tree(2, 3))
161
+
162
+ Parameters
163
+ ----------
164
+ r : int
165
+ Branching factor of the tree; each node will have `r`
166
+ children.
167
+
168
+ h : int
169
+ Height of the tree.
170
+
171
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
172
+ Graph type to create. If graph instance, then cleared before populated.
173
+
174
+ Returns
175
+ -------
176
+ G : NetworkX graph
177
+ A balanced `r`-ary tree of height `h`.
178
+
179
+ Notes
180
+ -----
181
+ This is the rooted tree where all leaves are at distance `h` from
182
+ the root. The root has degree `r` and all other internal nodes
183
+ have degree `r + 1`.
184
+
185
+ Node labels are integers, starting from zero.
186
+
187
+ A balanced tree is also known as a *complete r-ary tree*.
188
+
189
+ """
190
+ # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
191
+ # which is computed by using the closed-form formula for a geometric
192
+ # sum with ratio `r`. In the special case that `r` is 1, the number
193
+ # of nodes is simply `h + 1` (since the tree is actually a path
194
+ # graph).
195
+ if r == 1:
196
+ n = h + 1
197
+ else:
198
+ # This must be an integer if both `r` and `h` are integers. If
199
+ # they are not, we force integer division anyway.
200
+ n = (1 - r ** (h + 1)) // (1 - r)
201
+ return full_rary_tree(r, n, create_using=create_using)
202
+
203
+
204
+ @nx._dispatchable(graphs=None, returns_graph=True)
205
+ def barbell_graph(m1, m2, create_using=None):
206
+ """Returns the Barbell Graph: two complete graphs connected by a path.
207
+
208
+ .. plot::
209
+
210
+ >>> nx.draw(nx.barbell_graph(4, 2))
211
+
212
+ Parameters
213
+ ----------
214
+ m1 : int
215
+ Size of the left and right barbells, must be greater than 2.
216
+
217
+ m2 : int
218
+ Length of the path connecting the barbells.
219
+
220
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
221
+ Graph type to create. If graph instance, then cleared before populated.
222
+ Only undirected Graphs are supported.
223
+
224
+ Returns
225
+ -------
226
+ G : NetworkX graph
227
+ A barbell graph.
228
+
229
+ Notes
230
+ -----
231
+
232
+
233
+ Two identical complete graphs $K_{m1}$ form the left and right bells,
234
+ and are connected by a path $P_{m2}$.
235
+
236
+ The `2*m1+m2` nodes are numbered
237
+ `0, ..., m1-1` for the left barbell,
238
+ `m1, ..., m1+m2-1` for the path,
239
+ and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
240
+
241
+ The 3 subgraphs are joined via the edges `(m1-1, m1)` and
242
+ `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
243
+ graphs joined together.
244
+
245
+ This graph is an extremal example in David Aldous
246
+ and Jim Fill's e-text on Random Walks on Graphs.
247
+
248
+ """
249
+ if m1 < 2:
250
+ raise NetworkXError("Invalid graph description, m1 should be >=2")
251
+ if m2 < 0:
252
+ raise NetworkXError("Invalid graph description, m2 should be >=0")
253
+
254
+ # left barbell
255
+ G = complete_graph(m1, create_using)
256
+ if G.is_directed():
257
+ raise NetworkXError("Directed Graph not supported")
258
+
259
+ # connecting path
260
+ G.add_nodes_from(range(m1, m1 + m2 - 1))
261
+ if m2 > 1:
262
+ G.add_edges_from(pairwise(range(m1, m1 + m2)))
263
+
264
+ # right barbell
265
+ G.add_edges_from(
266
+ (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
267
+ )
268
+
269
+ # connect it up
270
+ G.add_edge(m1 - 1, m1)
271
+ if m2 > 0:
272
+ G.add_edge(m1 + m2 - 1, m1 + m2)
273
+
274
+ return G
275
+
276
+
277
+ @nx._dispatchable(graphs=None, returns_graph=True)
278
+ def binomial_tree(n, create_using=None):
279
+ """Returns the Binomial Tree of order n.
280
+
281
+ The binomial tree of order 0 consists of a single node. A binomial tree of order k
282
+ is defined recursively by linking two binomial trees of order k-1: the root of one is
283
+ the leftmost child of the root of the other.
284
+
285
+ .. plot::
286
+
287
+ >>> nx.draw(nx.binomial_tree(3))
288
+
289
+ Parameters
290
+ ----------
291
+ n : int
292
+ Order of the binomial tree.
293
+
294
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
295
+ Graph type to create. If graph instance, then cleared before populated.
296
+
297
+ Returns
298
+ -------
299
+ G : NetworkX graph
300
+ A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
301
+
302
+ """
303
+ G = nx.empty_graph(1, create_using)
304
+
305
+ N = 1
306
+ for i in range(n):
307
+ # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
308
+ edges = [(u + N, v + N) for (u, v) in G.edges()]
309
+ G.add_edges_from(edges)
310
+ G.add_edge(0, N)
311
+ N *= 2
312
+ return G
313
+
314
+
315
+ @nx._dispatchable(graphs=None, returns_graph=True)
316
+ @nodes_or_number(0)
317
+ def complete_graph(n, create_using=None):
318
+ """Return the complete graph `K_n` with n nodes.
319
+
320
+ A complete graph on `n` nodes means that all pairs
321
+ of distinct nodes have an edge connecting them.
322
+
323
+ .. plot::
324
+
325
+ >>> nx.draw(nx.complete_graph(5))
326
+
327
+ Parameters
328
+ ----------
329
+ n : int or iterable container of nodes
330
+ If n is an integer, nodes are from range(n).
331
+ If n is a container of nodes, those nodes appear in the graph.
332
+ Warning: n is not checked for duplicates and if present the
333
+ resulting graph may not be as desired. Make sure you have no duplicates.
334
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
335
+ Graph type to create. If graph instance, then cleared before populated.
336
+
337
+ Examples
338
+ --------
339
+ >>> G = nx.complete_graph(9)
340
+ >>> len(G)
341
+ 9
342
+ >>> G.size()
343
+ 36
344
+ >>> G = nx.complete_graph(range(11, 14))
345
+ >>> list(G.nodes())
346
+ [11, 12, 13]
347
+ >>> G = nx.complete_graph(4, nx.DiGraph())
348
+ >>> G.is_directed()
349
+ True
350
+
351
+ """
352
+ _, nodes = n
353
+ G = empty_graph(nodes, create_using)
354
+ if len(nodes) > 1:
355
+ if G.is_directed():
356
+ edges = itertools.permutations(nodes, 2)
357
+ else:
358
+ edges = itertools.combinations(nodes, 2)
359
+ G.add_edges_from(edges)
360
+ return G
361
+
362
+
363
+ @nx._dispatchable(graphs=None, returns_graph=True)
364
+ def circular_ladder_graph(n, create_using=None):
365
+ """Returns the circular ladder graph $CL_n$ of length n.
366
+
367
+ $CL_n$ consists of two concentric n-cycles in which
368
+ each of the n pairs of concentric nodes are joined by an edge.
369
+
370
+ Node labels are the integers 0 to n-1
371
+
372
+ .. plot::
373
+
374
+ >>> nx.draw(nx.circular_ladder_graph(5))
375
+
376
+ """
377
+ G = ladder_graph(n, create_using)
378
+ G.add_edge(0, n - 1)
379
+ G.add_edge(n, 2 * n - 1)
380
+ return G
381
+
382
+
383
+ @nx._dispatchable(graphs=None, returns_graph=True)
384
+ def circulant_graph(n, offsets, create_using=None):
385
+ r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
386
+
387
+ The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
388
+ such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
389
+ for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
390
+
391
+ .. plot::
392
+
393
+ >>> nx.draw(nx.circulant_graph(10, [1]))
394
+
395
+ Parameters
396
+ ----------
397
+ n : integer
398
+ The number of nodes in the graph.
399
+ offsets : list of integers
400
+ A list of node offsets, $x_1$ up to $x_m$, as described above.
401
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
402
+ Graph type to create. If graph instance, then cleared before populated.
403
+
404
+ Returns
405
+ -------
406
+ NetworkX Graph of type create_using
407
+
408
+ Examples
409
+ --------
410
+ Many well-known graph families are subfamilies of the circulant graphs;
411
+ for example, to create the cycle graph on n points, we connect every
412
+ node to nodes on either side (with offset plus or minus one). For n = 10,
413
+
414
+ >>> G = nx.circulant_graph(10, [1])
415
+ >>> edges = [
416
+ ... (0, 9),
417
+ ... (0, 1),
418
+ ... (1, 2),
419
+ ... (2, 3),
420
+ ... (3, 4),
421
+ ... (4, 5),
422
+ ... (5, 6),
423
+ ... (6, 7),
424
+ ... (7, 8),
425
+ ... (8, 9),
426
+ ... ]
427
+ >>> sorted(edges) == sorted(G.edges())
428
+ True
429
+
430
+ Similarly, we can create the complete graph
431
+ on 5 points with the set of offsets [1, 2]:
432
+
433
+ >>> G = nx.circulant_graph(5, [1, 2])
434
+ >>> edges = [
435
+ ... (0, 1),
436
+ ... (0, 2),
437
+ ... (0, 3),
438
+ ... (0, 4),
439
+ ... (1, 2),
440
+ ... (1, 3),
441
+ ... (1, 4),
442
+ ... (2, 3),
443
+ ... (2, 4),
444
+ ... (3, 4),
445
+ ... ]
446
+ >>> sorted(edges) == sorted(G.edges())
447
+ True
448
+
449
+ """
450
+ G = empty_graph(n, create_using)
451
+ G.add_edges_from((i, (i - j) % n) for i in range(n) for j in offsets)
452
+ G.add_edges_from((i, (i + j) % n) for i in range(n) for j in offsets)
453
+ return G
454
+
455
+
456
+ @nx._dispatchable(graphs=None, returns_graph=True)
457
+ @nodes_or_number(0)
458
+ def cycle_graph(n, create_using=None):
459
+ """Returns the cycle graph $C_n$ of cyclically connected nodes.
460
+
461
+ $C_n$ is a path with its two end-nodes connected.
462
+
463
+ .. plot::
464
+
465
+ >>> nx.draw(nx.cycle_graph(5))
466
+
467
+ Parameters
468
+ ----------
469
+ n : int or iterable container of nodes
470
+ If n is an integer, nodes are from `range(n)`.
471
+ If n is a container of nodes, those nodes appear in the graph.
472
+ Warning: n is not checked for duplicates and if present the
473
+ resulting graph may not be as desired. Make sure you have no duplicates.
474
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
475
+ Graph type to create. If graph instance, then cleared before populated.
476
+
477
+ Notes
478
+ -----
479
+ If create_using is directed, the direction is in increasing order.
480
+
481
+ """
482
+ _, nodes = n
483
+ G = empty_graph(nodes, create_using)
484
+ G.add_edges_from(pairwise(nodes, cyclic=True))
485
+ return G
486
+
487
+
488
+ @nx._dispatchable(graphs=None, returns_graph=True)
489
+ def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
490
+ """Returns the hierarchically constructed Dorogovtsev--Goltsev--Mendes graph.
491
+
492
+ The Dorogovtsev--Goltsev--Mendes [1]_ procedure deterministically produces a
493
+ scale-free graph with ``3/2 * (3**(n-1) + 1)`` nodes
494
+ and ``3**n`` edges for a given `n`.
495
+
496
+ Note that `n` denotes the number of times the state transition is applied,
497
+ starting from the base graph with ``n = 0`` (no transitions), as in [2]_.
498
+ This is different from the parameter ``t = n - 1`` in [1]_.
499
+
500
+ .. plot::
501
+
502
+ >>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
503
+
504
+ Parameters
505
+ ----------
506
+ n : integer
507
+ The generation number.
508
+
509
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
510
+ Graph type to create. Directed graphs and multigraphs are not supported.
511
+
512
+ Returns
513
+ -------
514
+ G : NetworkX `Graph`
515
+
516
+ Raises
517
+ ------
518
+ NetworkXError
519
+ If `n` is less than zero.
520
+
521
+ If `create_using` is a directed graph or multigraph.
522
+
523
+ Examples
524
+ --------
525
+ >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
526
+ >>> G.number_of_nodes()
527
+ 15
528
+ >>> G.number_of_edges()
529
+ 27
530
+ >>> nx.is_planar(G)
531
+ True
532
+
533
+ References
534
+ ----------
535
+ .. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
536
+ "Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
537
+ https://arxiv.org/pdf/cond-mat/0112143.pdf
538
+ .. [2] Weisstein, Eric W. "Dorogovtsev--Goltsev--Mendes Graph".
539
+ From MathWorld--A Wolfram Web Resource.
540
+ https://mathworld.wolfram.com/Dorogovtsev-Goltsev-MendesGraph.html
541
+ """
542
+ if n < 0:
543
+ raise NetworkXError("n must be greater than or equal to 0")
544
+
545
+ G = empty_graph(0, create_using)
546
+ if G.is_directed():
547
+ raise NetworkXError("directed graph not supported")
548
+ if G.is_multigraph():
549
+ raise NetworkXError("multigraph not supported")
550
+
551
+ G.add_edge(0, 1)
552
+ new_node = 2 # next node to be added
553
+ for _ in range(n): # iterate over number of generations.
554
+ new_edges = []
555
+ for u, v in G.edges():
556
+ new_edges.append((u, new_node))
557
+ new_edges.append((v, new_node))
558
+ new_node += 1
559
+
560
+ G.add_edges_from(new_edges)
561
+ return G
562
+
563
+
564
+ @nx._dispatchable(graphs=None, returns_graph=True)
565
+ @nodes_or_number(0)
566
+ def empty_graph(n=0, create_using=None, default=Graph):
567
+ """Returns the empty graph with n nodes and zero edges.
568
+
569
+ .. plot::
570
+
571
+ >>> nx.draw(nx.empty_graph(5))
572
+
573
+ Parameters
574
+ ----------
575
+ n : int or iterable container of nodes (default = 0)
576
+ If n is an integer, nodes are from `range(n)`.
577
+ If n is a container of nodes, those nodes appear in the graph.
578
+ create_using : Graph Instance, Constructor or None
579
+ Indicator of type of graph to return.
580
+ If a Graph-type instance, then clear and use it.
581
+ If None, use the `default` constructor.
582
+ If a constructor, call it to create an empty graph.
583
+ default : Graph constructor (optional, default = nx.Graph)
584
+ The constructor to use if create_using is None.
585
+ If None, then nx.Graph is used.
586
+ This is used when passing an unknown `create_using` value
587
+ through your home-grown function to `empty_graph` and
588
+ you want a default constructor other than nx.Graph.
589
+
590
+ Examples
591
+ --------
592
+ >>> G = nx.empty_graph(10)
593
+ >>> G.number_of_nodes()
594
+ 10
595
+ >>> G.number_of_edges()
596
+ 0
597
+ >>> G = nx.empty_graph("ABC")
598
+ >>> G.number_of_nodes()
599
+ 3
600
+ >>> sorted(G)
601
+ ['A', 'B', 'C']
602
+
603
+ Notes
604
+ -----
605
+ The variable create_using should be a Graph Constructor or a
606
+ "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
607
+ will be used to create the returned graph. "graph"-like objects
608
+ will be cleared (nodes and edges will be removed) and refitted as
609
+ an empty "graph" with nodes specified in n. This capability
610
+ is useful for specifying the class-nature of the resulting empty
611
+ "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
612
+
613
+ The variable create_using has three main uses:
614
+ Firstly, the variable create_using can be used to create an
615
+ empty digraph, multigraph, etc. For example,
616
+
617
+ >>> n = 10
618
+ >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
619
+
620
+ will create an empty digraph on n nodes.
621
+
622
+ Secondly, one can pass an existing graph (digraph, multigraph,
623
+ etc.) via create_using. For example, if G is an existing graph
624
+ (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
625
+ will empty G (i.e. delete all nodes and edges using G.clear())
626
+ and then add n nodes and zero edges, and return the modified graph.
627
+
628
+ Thirdly, when constructing your home-grown graph creation function
629
+ you can use empty_graph to construct the graph by passing a user
630
+ defined create_using to empty_graph. In this case, if you want the
631
+ default constructor to be other than nx.Graph, specify `default`.
632
+
633
+ >>> def mygraph(n, create_using=None):
634
+ ... G = nx.empty_graph(n, create_using, nx.MultiGraph)
635
+ ... G.add_edges_from([(0, 1), (0, 1)])
636
+ ... return G
637
+ >>> G = mygraph(3)
638
+ >>> G.is_multigraph()
639
+ True
640
+ >>> G = mygraph(3, nx.Graph)
641
+ >>> G.is_multigraph()
642
+ False
643
+
644
+ See also create_empty_copy(G).
645
+
646
+ """
647
+ if create_using is None:
648
+ G = default()
649
+ elif isinstance(create_using, type):
650
+ G = create_using()
651
+ elif not hasattr(create_using, "adj"):
652
+ raise TypeError("create_using is not a valid NetworkX graph type or instance")
653
+ else:
654
+ # create_using is a NetworkX style Graph
655
+ create_using.clear()
656
+ G = create_using
657
+
658
+ _, nodes = n
659
+ G.add_nodes_from(nodes)
660
+ return G
661
+
662
+
663
+ @nx._dispatchable(graphs=None, returns_graph=True)
664
+ def ladder_graph(n, create_using=None):
665
+ """Returns the Ladder graph of length n.
666
+
667
+ This is two paths of n nodes, with
668
+ each pair connected by a single edge.
669
+
670
+ Node labels are the integers 0 to 2*n - 1.
671
+
672
+ .. plot::
673
+
674
+ >>> nx.draw(nx.ladder_graph(5))
675
+
676
+ """
677
+ G = empty_graph(2 * n, create_using)
678
+ if G.is_directed():
679
+ raise NetworkXError("Directed Graph not supported")
680
+ G.add_edges_from(pairwise(range(n)))
681
+ G.add_edges_from(pairwise(range(n, 2 * n)))
682
+ G.add_edges_from((v, v + n) for v in range(n))
683
+ return G
684
+
685
+
686
+ @nx._dispatchable(graphs=None, returns_graph=True)
687
+ @nodes_or_number([0, 1])
688
+ def lollipop_graph(m, n, create_using=None):
689
+ """Returns the Lollipop Graph; ``K_m`` connected to ``P_n``.
690
+
691
+ This is the Barbell Graph without the right barbell.
692
+
693
+ .. plot::
694
+
695
+ >>> nx.draw(nx.lollipop_graph(3, 4))
696
+
697
+ Parameters
698
+ ----------
699
+ m, n : int or iterable container of nodes
700
+ If an integer, nodes are from ``range(m)`` and ``range(m, m+n)``.
701
+ If a container of nodes, those nodes appear in the graph.
702
+ Warning: `m` and `n` are not checked for duplicates and if present the
703
+ resulting graph may not be as desired. Make sure you have no duplicates.
704
+
705
+ The nodes for `m` appear in the complete graph $K_m$ and the nodes
706
+ for `n` appear in the path $P_n$
707
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
708
+ Graph type to create. If graph instance, then cleared before populated.
709
+
710
+ Returns
711
+ -------
712
+ Networkx graph
713
+ A complete graph with `m` nodes connected to a path of length `n`.
714
+
715
+ Notes
716
+ -----
717
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
718
+ If ``n=0``, this is merely a complete graph.
719
+
720
+ (This graph is an extremal example in David Aldous and Jim
721
+ Fill's etext on Random Walks on Graphs.)
722
+
723
+ """
724
+ m, m_nodes = m
725
+ M = len(m_nodes)
726
+ if M < 2:
727
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
728
+
729
+ n, n_nodes = n
730
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
731
+ n_nodes = list(range(M, M + n))
732
+ N = len(n_nodes)
733
+
734
+ # the ball
735
+ G = complete_graph(m_nodes, create_using)
736
+ if G.is_directed():
737
+ raise NetworkXError("Directed Graph not supported")
738
+
739
+ # the stick
740
+ G.add_nodes_from(n_nodes)
741
+ if N > 1:
742
+ G.add_edges_from(pairwise(n_nodes))
743
+
744
+ if len(G) != M + N:
745
+ raise NetworkXError("Nodes must be distinct in containers m and n")
746
+
747
+ # connect ball to stick
748
+ if M > 0 and N > 0:
749
+ G.add_edge(m_nodes[-1], n_nodes[0])
750
+ return G
751
+
752
+
753
+ @nx._dispatchable(graphs=None, returns_graph=True)
754
+ def null_graph(create_using=None):
755
+ """Returns the Null graph with no nodes or edges.
756
+
757
+ See empty_graph for the use of create_using.
758
+
759
+ """
760
+ G = empty_graph(0, create_using)
761
+ return G
762
+
763
+
764
+ @nx._dispatchable(graphs=None, returns_graph=True)
765
+ @nodes_or_number(0)
766
+ def path_graph(n, create_using=None):
767
+ """Returns the Path graph `P_n` of linearly connected nodes.
768
+
769
+ .. plot::
770
+
771
+ >>> nx.draw(nx.path_graph(5))
772
+
773
+ Parameters
774
+ ----------
775
+ n : int or iterable
776
+ If an integer, nodes are 0 to n - 1.
777
+ If an iterable of nodes, in the order they appear in the path.
778
+ Warning: n is not checked for duplicates and if present the
779
+ resulting graph may not be as desired. Make sure you have no duplicates.
780
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
781
+ Graph type to create. If graph instance, then cleared before populated.
782
+
783
+ """
784
+ _, nodes = n
785
+ G = empty_graph(nodes, create_using)
786
+ G.add_edges_from(pairwise(nodes))
787
+ return G
788
+
789
+
790
+ @nx._dispatchable(graphs=None, returns_graph=True)
791
+ @nodes_or_number(0)
792
+ def star_graph(n, create_using=None):
793
+ """Return a star graph.
794
+
795
+ The star graph consists of one center node connected to `n` outer nodes.
796
+
797
+ .. plot::
798
+
799
+ >>> nx.draw(nx.star_graph(6))
800
+
801
+ Parameters
802
+ ----------
803
+ n : int or iterable
804
+ If an integer, node labels are ``0`` to `n`, with center ``0``.
805
+ If an iterable of nodes, the center is the first.
806
+ Warning: `n` is not checked for duplicates and if present, the
807
+ resulting graph may not be as desired. Make sure you have no duplicates.
808
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
809
+ Graph type to create. If graph instance, then cleared before populated.
810
+
811
+ Examples
812
+ --------
813
+ A star graph with 3 spokes can be generated with
814
+
815
+ >>> G = nx.star_graph(3)
816
+ >>> sorted(G.edges)
817
+ [(0, 1), (0, 2), (0, 3)]
818
+
819
+ For directed graphs, the convention is to have edges pointing from the hub
820
+ to the spokes:
821
+
822
+ >>> DG1 = nx.star_graph(3, create_using=nx.DiGraph)
823
+ >>> sorted(DG1.edges)
824
+ [(0, 1), (0, 2), (0, 3)]
825
+
826
+ Other possible definitions have edges pointing from the spokes to the hub:
827
+
828
+ >>> DG2 = nx.star_graph(3, create_using=nx.DiGraph).reverse()
829
+ >>> sorted(DG2.edges)
830
+ [(1, 0), (2, 0), (3, 0)]
831
+
832
+ or have bidirectional edges:
833
+
834
+ >>> DG3 = nx.star_graph(3).to_directed()
835
+ >>> sorted(DG3.edges)
836
+ [(0, 1), (0, 2), (0, 3), (1, 0), (2, 0), (3, 0)]
837
+
838
+ Notes
839
+ -----
840
+ The graph has ``n + 1`` nodes for integer `n`.
841
+ So ``star_graph(3)`` is the same as ``star_graph(range(4))``.
842
+ """
843
+ n, nodes = n
844
+ if isinstance(n, numbers.Integral):
845
+ nodes.append(int(n)) # There should be n + 1 nodes.
846
+ G = empty_graph(nodes, create_using)
847
+
848
+ if len(nodes) > 1:
849
+ hub, *spokes = nodes
850
+ G.add_edges_from((hub, node) for node in spokes)
851
+ return G
852
+
853
+
854
+ @nx._dispatchable(graphs=None, returns_graph=True)
855
+ @nodes_or_number([0, 1])
856
+ def tadpole_graph(m, n, create_using=None):
857
+ """Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``.
858
+
859
+ This graph on m+n nodes connects a cycle of size `m` to a path of length `n`.
860
+ It looks like a tadpole. It is also called a kite graph or a dragon graph.
861
+
862
+ .. plot::
863
+
864
+ >>> nx.draw(nx.tadpole_graph(3, 5))
865
+
866
+ Parameters
867
+ ----------
868
+ m, n : int or iterable container of nodes
869
+ If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``.
870
+ If a container of nodes, those nodes appear in the graph.
871
+ Warning: `m` and `n` are not checked for duplicates and if present the
872
+ resulting graph may not be as desired.
873
+
874
+ The nodes for `m` appear in the cycle graph $C_m$ and the nodes
875
+ for `n` appear in the path $P_n$.
876
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
877
+ Graph type to create. If graph instance, then cleared before populated.
878
+
879
+ Returns
880
+ -------
881
+ Networkx graph
882
+ A cycle of size `m` connected to a path of length `n`.
883
+
884
+ Raises
885
+ ------
886
+ NetworkXError
887
+ If ``m < 2``. The tadpole graph is undefined for ``m<2``.
888
+
889
+ Notes
890
+ -----
891
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
892
+ If ``n=0``, this is a cycle graph.
893
+ `m` and/or `n` can be a container of nodes instead of an integer.
894
+
895
+ """
896
+ m, m_nodes = m
897
+ M = len(m_nodes)
898
+ if M < 2:
899
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
900
+
901
+ n, n_nodes = n
902
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
903
+ n_nodes = list(range(M, M + n))
904
+
905
+ # the circle
906
+ G = cycle_graph(m_nodes, create_using)
907
+ if G.is_directed():
908
+ raise NetworkXError("Directed Graph not supported")
909
+
910
+ # the stick
911
+ nx.add_path(G, [m_nodes[-1]] + list(n_nodes))
912
+
913
+ return G
914
+
915
+
916
+ @nx._dispatchable(graphs=None, returns_graph=True)
917
+ def trivial_graph(create_using=None):
918
+ """Return the Trivial graph with one node (with label 0) and no edges.
919
+
920
+ .. plot::
921
+
922
+ >>> nx.draw(nx.trivial_graph(), with_labels=True)
923
+
924
+ """
925
+ G = empty_graph(1, create_using)
926
+ return G
927
+
928
+
929
+ @nx._dispatchable(graphs=None, returns_graph=True)
930
+ def turan_graph(n, r):
931
+ r"""Return the Turan Graph
932
+
933
+ The Turan Graph is a complete multipartite graph on $n$ nodes
934
+ with $r$ disjoint subsets. That is, edges connect each node to
935
+ every node not in its subset.
936
+
937
+ Given $n$ and $r$, we create a complete multipartite graph with
938
+ $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
939
+ $n \mod r$ partitions of size $n/r+1$, rounded down.
940
+
941
+ .. plot::
942
+
943
+ >>> nx.draw(nx.turan_graph(6, 2))
944
+
945
+ Parameters
946
+ ----------
947
+ n : int
948
+ The number of nodes.
949
+ r : int
950
+ The number of partitions.
951
+ Must be less than or equal to n.
952
+
953
+ Notes
954
+ -----
955
+ Must satisfy $1 <= r <= n$.
956
+ The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
957
+ """
958
+
959
+ if not 1 <= r <= n:
960
+ raise NetworkXError("Must satisfy 1 <= r <= n")
961
+
962
+ partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
963
+ G = complete_multipartite_graph(*partitions)
964
+ return G
965
+
966
+
967
+ @nx._dispatchable(graphs=None, returns_graph=True)
968
+ @nodes_or_number(0)
969
+ def wheel_graph(n, create_using=None):
970
+ """Return the wheel graph
971
+
972
+ The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
973
+
974
+ .. plot::
975
+
976
+ >>> nx.draw(nx.wheel_graph(5))
977
+
978
+ Parameters
979
+ ----------
980
+ n : int or iterable
981
+ If an integer, node labels are 0 to n with center 0.
982
+ If an iterable of nodes, the center is the first.
983
+ Warning: n is not checked for duplicates and if present the
984
+ resulting graph may not be as desired. Make sure you have no duplicates.
985
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
986
+ Graph type to create. If graph instance, then cleared before populated.
987
+
988
+ Node labels are the integers 0 to n - 1.
989
+ """
990
+ _, nodes = n
991
+ G = empty_graph(nodes, create_using)
992
+ if G.is_directed():
993
+ raise NetworkXError("Directed Graph not supported")
994
+
995
+ if len(nodes) > 1:
996
+ hub, *rim = nodes
997
+ G.add_edges_from((hub, node) for node in rim)
998
+ if len(rim) > 1:
999
+ G.add_edges_from(pairwise(rim, cyclic=True))
1000
+ return G
1001
+
1002
+
1003
+ @nx._dispatchable(graphs=None, returns_graph=True)
1004
+ def complete_multipartite_graph(*subset_sizes):
1005
+ """Returns the complete multipartite graph with the specified subset sizes.
1006
+
1007
+ .. plot::
1008
+
1009
+ >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3))
1010
+
1011
+ Parameters
1012
+ ----------
1013
+ subset_sizes : tuple of integers or tuple of node iterables
1014
+ The arguments can either all be integer number of nodes or they
1015
+ can all be iterables of nodes. If integers, they represent the
1016
+ number of nodes in each subset of the multipartite graph.
1017
+ If iterables, each is used to create the nodes for that subset.
1018
+ The length of subset_sizes is the number of subsets.
1019
+
1020
+ Returns
1021
+ -------
1022
+ G : NetworkX Graph
1023
+ Returns the complete multipartite graph with the specified subsets.
1024
+
1025
+ For each node, the node attribute 'subset' is an integer
1026
+ indicating which subset contains the node.
1027
+
1028
+ Examples
1029
+ --------
1030
+ Creating a complete tripartite graph, with subsets of one, two, and three
1031
+ nodes, respectively.
1032
+
1033
+ >>> G = nx.complete_multipartite_graph(1, 2, 3)
1034
+ >>> [G.nodes[u]["subset"] for u in G]
1035
+ [0, 1, 1, 2, 2, 2]
1036
+ >>> list(G.edges(0))
1037
+ [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
1038
+ >>> list(G.edges(2))
1039
+ [(2, 0), (2, 3), (2, 4), (2, 5)]
1040
+ >>> list(G.edges(4))
1041
+ [(4, 0), (4, 1), (4, 2)]
1042
+
1043
+ >>> G = nx.complete_multipartite_graph("a", "bc", "def")
1044
+ >>> [G.nodes[u]["subset"] for u in sorted(G)]
1045
+ [0, 1, 1, 2, 2, 2]
1046
+
1047
+ Notes
1048
+ -----
1049
+ This function generalizes several other graph builder functions.
1050
+
1051
+ - If no subset sizes are given, this returns the null graph.
1052
+ - If a single subset size `n` is given, this returns the empty graph on
1053
+ `n` nodes.
1054
+ - If two subset sizes `m` and `n` are given, this returns the complete
1055
+ bipartite graph on `m + n` nodes.
1056
+ - If subset sizes `1` and `n` are given, this returns the star graph on
1057
+ `n + 1` nodes.
1058
+
1059
+ See also
1060
+ --------
1061
+ complete_bipartite_graph
1062
+ """
1063
+ # The complete multipartite graph is an undirected simple graph.
1064
+ G = Graph()
1065
+
1066
+ if len(subset_sizes) == 0:
1067
+ return G
1068
+
1069
+ # set up subsets of nodes
1070
+ try:
1071
+ extents = pairwise(itertools.accumulate((0,) + subset_sizes))
1072
+ subsets = [range(start, end) for start, end in extents]
1073
+ except TypeError:
1074
+ subsets = subset_sizes
1075
+ else:
1076
+ if any(size < 0 for size in subset_sizes):
1077
+ raise NetworkXError(f"Negative number of nodes not valid: {subset_sizes}")
1078
+
1079
+ # add nodes with subset attribute
1080
+ # while checking that ints are not mixed with iterables
1081
+ try:
1082
+ for i, subset in enumerate(subsets):
1083
+ G.add_nodes_from(subset, subset=i)
1084
+ except TypeError as err:
1085
+ raise NetworkXError("Arguments must be all ints or all iterables") from err
1086
+
1087
+ # Across subsets, all nodes should be adjacent.
1088
+ # We can use itertools.combinations() because undirected.
1089
+ for subset1, subset2 in itertools.combinations(subsets, 2):
1090
+ G.add_edges_from(itertools.product(subset1, subset2))
1091
+ return G
pace_revision_2/.venv-pace/lib/python3.11/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
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/community.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.245
556
+ 0.348
557
+ 0.405
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.051
561
+ 0.022
562
+ 0.07
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
+ for e in edges:
639
+ if seed.random() < p[i][j]:
640
+ g.add_edge(*e)
641
+ else:
642
+ edges = itertools.product(parts[i], parts[j])
643
+ if sparse:
644
+ if p[i][j] == 1: # Test edges cases p_ij = 0 or 1
645
+ for e in edges:
646
+ g.add_edge(*e)
647
+ elif p[i][j] > 0:
648
+ while True:
649
+ try:
650
+ logrand = math.log(seed.random())
651
+ skip = math.floor(logrand / math.log(1 - p[i][j]))
652
+ # consume "skip" edges
653
+ next(itertools.islice(edges, skip, skip), None)
654
+ e = next(edges)
655
+ g.add_edge(*e) # __safe
656
+ except StopIteration:
657
+ break
658
+ else:
659
+ for e in edges:
660
+ if seed.random() < p[i][j]:
661
+ g.add_edge(*e) # __safe
662
+ return g
663
+
664
+
665
+ def _zipf_rv_below(gamma, xmin, threshold, seed):
666
+ """Returns a random value chosen from the bounded Zipf distribution.
667
+
668
+ Repeatedly draws values from the Zipf distribution until the
669
+ threshold is met, then returns that value.
670
+ """
671
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
672
+ while result > threshold:
673
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
674
+ return result
675
+
676
+
677
+ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters, seed):
678
+ """Returns a list of numbers obeying a constrained power law distribution.
679
+
680
+ ``gamma`` and ``low`` are the parameters for the Zipf distribution.
681
+
682
+ ``high`` is the maximum allowed value for values draw from the Zipf
683
+ distribution. For more information, see :func:`_zipf_rv_below`.
684
+
685
+ ``condition`` and ``length`` are Boolean-valued functions on
686
+ lists. While generating the list, random values are drawn and
687
+ appended to the list until ``length`` is satisfied by the created
688
+ list. Once ``condition`` is satisfied, the sequence generated in
689
+ this way is returned.
690
+
691
+ ``max_iters`` indicates the number of times to generate a list
692
+ satisfying ``length``. If the number of iterations exceeds this
693
+ value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.
694
+
695
+ seed : integer, random_state, or None (default)
696
+ Indicator of random number generation state.
697
+ See :ref:`Randomness<randomness>`.
698
+ """
699
+ for i in range(max_iters):
700
+ seq = []
701
+ while not length(seq):
702
+ seq.append(_zipf_rv_below(gamma, low, high, seed))
703
+ if condition(seq):
704
+ return seq
705
+ raise nx.ExceededMaxIterations("Could not create power law sequence")
706
+
707
+
708
+ def _hurwitz_zeta(x, q, tolerance):
709
+ """The Hurwitz zeta function, or the Riemann zeta function of two arguments.
710
+
711
+ ``x`` must be greater than one and ``q`` must be positive.
712
+
713
+ This function repeatedly computes subsequent partial sums until
714
+ convergence, as decided by ``tolerance``.
715
+ """
716
+ z = 0
717
+ z_prev = -float("inf")
718
+ k = 0
719
+ while abs(z - z_prev) > tolerance:
720
+ z_prev = z
721
+ z += 1 / ((k + q) ** x)
722
+ k += 1
723
+ return z
724
+
725
+
726
+ def _generate_min_degree(gamma, average_degree, max_degree, tolerance, max_iters):
727
+ """Returns a minimum degree from the given average degree."""
728
+ # Defines zeta function whether or not Scipy is available
729
+ try:
730
+ from scipy.special import zeta
731
+ except ImportError:
732
+
733
+ def zeta(x, q):
734
+ return _hurwitz_zeta(x, q, tolerance)
735
+
736
+ min_deg_top = max_degree
737
+ min_deg_bot = 1
738
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
739
+ itrs = 0
740
+ mid_avg_deg = 0
741
+ while abs(mid_avg_deg - average_degree) > tolerance:
742
+ if itrs > max_iters:
743
+ raise nx.ExceededMaxIterations("Could not match average_degree")
744
+ mid_avg_deg = 0
745
+ for x in range(int(min_deg_mid), max_degree + 1):
746
+ mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid)
747
+ if mid_avg_deg > average_degree:
748
+ min_deg_top = min_deg_mid
749
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
750
+ else:
751
+ min_deg_bot = min_deg_mid
752
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
753
+ itrs += 1
754
+ # return int(min_deg_mid + 0.5)
755
+ return round(min_deg_mid)
756
+
757
+
758
+ def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed):
759
+ """Returns a list of sets, each of which represents a community.
760
+
761
+ ``degree_seq`` is the degree sequence that must be met by the
762
+ graph.
763
+
764
+ ``community_sizes`` is the community size distribution that must be
765
+ met by the generated list of sets.
766
+
767
+ ``mu`` is a float in the interval [0, 1] indicating the fraction of
768
+ intra-community edges incident to each node.
769
+
770
+ ``max_iters`` is the number of times to try to add a node to a
771
+ community. This must be greater than the length of
772
+ ``degree_seq``, otherwise this function will always fail. If
773
+ the number of iterations exceeds this value,
774
+ :exc:`~networkx.exception.ExceededMaxIterations` is raised.
775
+
776
+ seed : integer, random_state, or None (default)
777
+ Indicator of random number generation state.
778
+ See :ref:`Randomness<randomness>`.
779
+
780
+ The communities returned by this are sets of integers in the set {0,
781
+ ..., *n* - 1}, where *n* is the length of ``degree_seq``.
782
+
783
+ """
784
+ # This assumes the nodes in the graph will be natural numbers.
785
+ result = [set() for _ in community_sizes]
786
+ n = len(degree_seq)
787
+ free = list(range(n))
788
+ for i in range(max_iters):
789
+ v = free.pop()
790
+ c = seed.choice(range(len(community_sizes)))
791
+ # s = int(degree_seq[v] * (1 - mu) + 0.5)
792
+ s = round(degree_seq[v] * (1 - mu))
793
+ # If the community is large enough, add the node to the chosen
794
+ # community. Otherwise, return it to the list of unaffiliated
795
+ # nodes.
796
+ if s < community_sizes[c]:
797
+ result[c].add(v)
798
+ else:
799
+ free.append(v)
800
+ # If the community is too big, remove a node from it.
801
+ if len(result[c]) > community_sizes[c]:
802
+ free.append(result[c].pop())
803
+ if not free:
804
+ return result
805
+ msg = "Could not assign communities; try increasing min_community"
806
+ raise nx.ExceededMaxIterations(msg)
807
+
808
+
809
+ @py_random_state(11)
810
+ @nx._dispatchable(graphs=None, returns_graph=True)
811
+ def LFR_benchmark_graph(
812
+ n,
813
+ tau1,
814
+ tau2,
815
+ mu,
816
+ average_degree=None,
817
+ min_degree=None,
818
+ max_degree=None,
819
+ min_community=None,
820
+ max_community=None,
821
+ tol=1.0e-7,
822
+ max_iters=500,
823
+ seed=None,
824
+ ):
825
+ r"""Returns the LFR benchmark graph.
826
+
827
+ This algorithm proceeds as follows:
828
+
829
+ 1) Find a degree sequence with a power law distribution, and minimum
830
+ value ``min_degree``, which has approximate average degree
831
+ ``average_degree``. This is accomplished by either
832
+
833
+ a) specifying ``min_degree`` and not ``average_degree``,
834
+ b) specifying ``average_degree`` and not ``min_degree``, in which
835
+ case a suitable minimum degree will be found.
836
+
837
+ ``max_degree`` can also be specified, otherwise it will be set to
838
+ ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
839
+ joining it to nodes in communities other than its own and $(1 -
840
+ \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
841
+ community.
842
+ 2) Generate community sizes according to a power law distribution
843
+ with exponent ``tau2``. If ``min_community`` and
844
+ ``max_community`` are not specified they will be selected to be
845
+ ``min_degree`` and ``max_degree``, respectively. Community sizes
846
+ are generated until the sum of their sizes equals ``n``.
847
+ 3) Each node will be randomly assigned a community with the
848
+ condition that the community is large enough for the node's
849
+ intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
850
+ described in step 2. If a community grows too large, a random node
851
+ will be selected for reassignment to a new community, until all
852
+ nodes have been assigned a community.
853
+ 4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
854
+ intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
855
+ edges.
856
+
857
+ Parameters
858
+ ----------
859
+ n : int
860
+ Number of nodes in the created graph.
861
+
862
+ tau1 : float
863
+ Power law exponent for the degree distribution of the created
864
+ graph. This value must be strictly greater than one.
865
+
866
+ tau2 : float
867
+ Power law exponent for the community size distribution in the
868
+ created graph. This value must be strictly greater than one.
869
+
870
+ mu : float
871
+ Fraction of inter-community edges incident to each node. This
872
+ value must be in the interval [0, 1].
873
+
874
+ average_degree : float
875
+ Desired average degree of nodes in the created graph. This value
876
+ must be in the interval [0, *n*]. Exactly one of this and
877
+ ``min_degree`` must be specified, otherwise a
878
+ :exc:`NetworkXError` is raised.
879
+
880
+ min_degree : int
881
+ Minimum degree of nodes in the created graph. This value must be
882
+ in the interval [0, *n*]. Exactly one of this and
883
+ ``average_degree`` must be specified, otherwise a
884
+ :exc:`NetworkXError` is raised.
885
+
886
+ max_degree : int
887
+ Maximum degree of nodes in the created graph. If not specified,
888
+ this is set to ``n``, the total number of nodes in the graph.
889
+
890
+ min_community : int
891
+ Minimum size of communities in the graph. If not specified, this
892
+ is set to ``min_degree``.
893
+
894
+ max_community : int
895
+ Maximum size of communities in the graph. If not specified, this
896
+ is set to ``n``, the total number of nodes in the graph.
897
+
898
+ tol : float
899
+ Tolerance when comparing floats, specifically when comparing
900
+ average degree values.
901
+
902
+ max_iters : int
903
+ Maximum number of iterations to try to create the community sizes,
904
+ degree distribution, and community affiliations.
905
+
906
+ seed : integer, random_state, or None (default)
907
+ Indicator of random number generation state.
908
+ See :ref:`Randomness<randomness>`.
909
+
910
+ Returns
911
+ -------
912
+ G : NetworkX graph
913
+ The LFR benchmark graph generated according to the specified
914
+ parameters.
915
+
916
+ Each node in the graph has a node attribute ``'community'`` that
917
+ stores the community (that is, the set of nodes) that includes
918
+ it.
919
+
920
+ Raises
921
+ ------
922
+ NetworkXError
923
+ If any of the parameters do not meet their upper and lower bounds:
924
+
925
+ - ``tau1`` and ``tau2`` must be strictly greater than 1.
926
+ - ``mu`` must be in [0, 1].
927
+ - ``max_degree`` must be in {1, ..., *n*}.
928
+ - ``min_community`` and ``max_community`` must be in {0, ...,
929
+ *n*}.
930
+
931
+ If not exactly one of ``average_degree`` and ``min_degree`` is
932
+ specified.
933
+
934
+ If ``min_degree`` is not specified and a suitable ``min_degree``
935
+ cannot be found.
936
+
937
+ ExceededMaxIterations
938
+ If a valid degree sequence cannot be created within
939
+ ``max_iters`` number of iterations.
940
+
941
+ If a valid set of community sizes cannot be created within
942
+ ``max_iters`` number of iterations.
943
+
944
+ If a valid community assignment cannot be created within ``10 *
945
+ n * max_iters`` number of iterations.
946
+
947
+ Examples
948
+ --------
949
+ Basic usage::
950
+
951
+ >>> from networkx.generators.community import LFR_benchmark_graph
952
+ >>> n = 250
953
+ >>> tau1 = 3
954
+ >>> tau2 = 1.5
955
+ >>> mu = 0.1
956
+ >>> G = LFR_benchmark_graph(
957
+ ... n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
958
+ ... )
959
+
960
+ Continuing the example above, you can get the communities from the
961
+ node attributes of the graph::
962
+
963
+ >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}
964
+
965
+ Notes
966
+ -----
967
+ This algorithm differs slightly from the original way it was
968
+ presented in [1].
969
+
970
+ 1) Rather than connecting the graph via a configuration model then
971
+ rewiring to match the intra-community and inter-community
972
+ degrees, we do this wiring explicitly at the end, which should be
973
+ equivalent.
974
+ 2) The code posted on the author's website [2] calculates the random
975
+ power law distributed variables and their average using
976
+ continuous approximations, whereas we use the discrete
977
+ distributions here as both degree and community size are
978
+ discrete.
979
+
980
+ Though the authors describe the algorithm as quite robust, testing
981
+ during development indicates that a somewhat narrower parameter set
982
+ is likely to successfully produce a graph. Some suggestions have
983
+ been provided in the event of exceptions.
984
+
985
+ References
986
+ ----------
987
+ .. [1] "Benchmark graphs for testing community detection algorithms",
988
+ Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
989
+ Phys. Rev. E 78, 046110 2008
990
+ .. [2] https://www.santofortunato.net/resources
991
+
992
+ """
993
+ # Perform some basic parameter validation.
994
+ if not tau1 > 1:
995
+ raise nx.NetworkXError("tau1 must be greater than one")
996
+ if not tau2 > 1:
997
+ raise nx.NetworkXError("tau2 must be greater than one")
998
+ if not 0 <= mu <= 1:
999
+ raise nx.NetworkXError("mu must be in the interval [0, 1]")
1000
+
1001
+ # Validate parameters for generating the degree sequence.
1002
+ if max_degree is None:
1003
+ max_degree = n
1004
+ elif not 0 < max_degree <= n:
1005
+ raise nx.NetworkXError("max_degree must be in the interval (0, n]")
1006
+ if not ((min_degree is None) ^ (average_degree is None)):
1007
+ raise nx.NetworkXError(
1008
+ "Must assign exactly one of min_degree and average_degree"
1009
+ )
1010
+ if min_degree is None:
1011
+ min_degree = _generate_min_degree(
1012
+ tau1, average_degree, max_degree, tol, max_iters
1013
+ )
1014
+
1015
+ # Generate a degree sequence with a power law distribution.
1016
+ low, high = min_degree, max_degree
1017
+
1018
+ def condition(seq):
1019
+ return sum(seq) % 2 == 0
1020
+
1021
+ def length(seq):
1022
+ return len(seq) >= n
1023
+
1024
+ deg_seq = _powerlaw_sequence(tau1, low, high, condition, length, max_iters, seed)
1025
+
1026
+ # Validate parameters for generating the community size sequence.
1027
+ if min_community is None:
1028
+ min_community = min(deg_seq)
1029
+ if max_community is None:
1030
+ max_community = max(deg_seq)
1031
+
1032
+ # Generate a community size sequence with a power law distribution.
1033
+ #
1034
+ # TODO The original code incremented the number of iterations each
1035
+ # time a new Zipf random value was drawn from the distribution. This
1036
+ # differed from the way the number of iterations was incremented in
1037
+ # `_powerlaw_degree_sequence`, so this code was changed to match
1038
+ # that one. As a result, this code is allowed many more chances to
1039
+ # generate a valid community size sequence.
1040
+ low, high = min_community, max_community
1041
+
1042
+ def condition(seq):
1043
+ return sum(seq) == n
1044
+
1045
+ def length(seq):
1046
+ return sum(seq) >= n
1047
+
1048
+ comms = _powerlaw_sequence(tau2, low, high, condition, length, max_iters, seed)
1049
+
1050
+ # Generate the communities based on the given degree sequence and
1051
+ # community sizes.
1052
+ max_iters *= 10 * n
1053
+ communities = _generate_communities(deg_seq, comms, mu, max_iters, seed)
1054
+
1055
+ # Finally, generate the benchmark graph based on the given
1056
+ # communities, joining nodes according to the intra- and
1057
+ # inter-community degrees.
1058
+ G = nx.Graph()
1059
+ G.add_nodes_from(range(n))
1060
+ for c in communities:
1061
+ for u in c:
1062
+ while G.degree(u) < round(deg_seq[u] * (1 - mu)):
1063
+ v = seed.choice(list(c))
1064
+ G.add_edge(u, v)
1065
+ while G.degree(u) < deg_seq[u]:
1066
+ v = seed.choice(range(n))
1067
+ if v not in c:
1068
+ G.add_edge(u, v)
1069
+ G.nodes[u]["community"] = c
1070
+ return G
pace_revision_2/.venv-pace/lib/python3.11/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, dsum, n = 0, 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, dsum, n = max(dmax, d), dsum + 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
+ degree_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)
pace_revision_2/.venv-pace/lib/python3.11/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
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/duplication.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.exception import NetworkXError
11
+ from networkx.utils import py_random_state
12
+ from networkx.utils.misc import check_create_using
13
+
14
+ __all__ = ["partial_duplication_graph", "duplication_divergence_graph"]
15
+
16
+
17
+ @py_random_state(4)
18
+ @nx._dispatchable(graphs=None, returns_graph=True)
19
+ def partial_duplication_graph(N, n, p, q, seed=None, *, create_using=None):
20
+ """Returns a random graph using the partial duplication model.
21
+
22
+ Parameters
23
+ ----------
24
+ N : int
25
+ The total number of nodes in the final graph.
26
+
27
+ n : int
28
+ The number of nodes in the initial clique.
29
+
30
+ p : float
31
+ The probability of joining each neighbor of a node to the
32
+ duplicate node. Must be a number in the between zero and one,
33
+ inclusive.
34
+
35
+ q : float
36
+ The probability of joining the source node to the duplicate
37
+ node. Must be a number in the between zero and one, inclusive.
38
+
39
+ seed : integer, random_state, or None (default)
40
+ Indicator of random number generation state.
41
+ See :ref:`Randomness<randomness>`.
42
+
43
+ create_using : Graph constructor, optional (default=nx.Graph)
44
+ Graph type to create. If graph instance, then cleared before populated.
45
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
46
+
47
+ Notes
48
+ -----
49
+ A graph of nodes is grown by creating a fully connected graph
50
+ of size `n`. The following procedure is then repeated until
51
+ a total of `N` nodes have been reached.
52
+
53
+ 1. A random node, *u*, is picked and a new node, *v*, is created.
54
+ 2. For each neighbor of *u* an edge from the neighbor to *v* is created
55
+ with probability `p`.
56
+ 3. An edge from *u* to *v* is created with probability `q`.
57
+
58
+ This algorithm appears in [1].
59
+
60
+ This implementation allows the possibility of generating
61
+ disconnected graphs.
62
+
63
+ References
64
+ ----------
65
+ .. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
66
+ randomly grown graphs." Journal of Applied Mathematics 2008.
67
+ <https://doi.org/10.1155/2008/190836>
68
+
69
+ """
70
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
71
+ if p < 0 or p > 1 or q < 0 or q > 1:
72
+ msg = "partial duplication graph must have 0 <= p, q <= 1."
73
+ raise NetworkXError(msg)
74
+ if n > N:
75
+ raise NetworkXError("partial duplication graph must have n <= N.")
76
+
77
+ G = nx.complete_graph(n, create_using)
78
+ for new_node in range(n, N):
79
+ # Pick a random vertex, u, already in the graph.
80
+ src_node = seed.randint(0, new_node - 1)
81
+
82
+ # Add a new vertex, v, to the graph.
83
+ G.add_node(new_node)
84
+
85
+ # For each neighbor of u...
86
+ for nbr_node in list(nx.all_neighbors(G, src_node)):
87
+ # Add the neighbor to v with probability p.
88
+ if seed.random() < p:
89
+ G.add_edge(new_node, nbr_node)
90
+
91
+ # Join v and u with probability q.
92
+ if seed.random() < q:
93
+ G.add_edge(new_node, src_node)
94
+ return G
95
+
96
+
97
+ @py_random_state(2)
98
+ @nx._dispatchable(graphs=None, returns_graph=True)
99
+ def duplication_divergence_graph(n, p, seed=None, *, create_using=None):
100
+ """Returns an undirected graph using the duplication-divergence model.
101
+
102
+ A graph of `n` nodes is created by duplicating the initial nodes
103
+ and retaining edges incident to the original nodes with a retention
104
+ probability `p`.
105
+
106
+ Parameters
107
+ ----------
108
+ n : int
109
+ The desired number of nodes in the graph.
110
+ p : float
111
+ The probability for retaining the edge of the replicated node.
112
+ seed : integer, random_state, or None (default)
113
+ Indicator of random number generation state.
114
+ See :ref:`Randomness<randomness>`.
115
+ create_using : Graph constructor, optional (default=nx.Graph)
116
+ Graph type to create. If graph instance, then cleared before populated.
117
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
118
+
119
+ Returns
120
+ -------
121
+ G : Graph
122
+
123
+ Raises
124
+ ------
125
+ NetworkXError
126
+ If `p` is not a valid probability.
127
+ If `n` is less than 2.
128
+
129
+ Notes
130
+ -----
131
+ This algorithm appears in [1].
132
+
133
+ This implementation disallows the possibility of generating
134
+ disconnected graphs.
135
+
136
+ References
137
+ ----------
138
+ .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
139
+ "Duplication-divergence model of protein interaction network",
140
+ Phys. Rev. E, 71, 061911, 2005.
141
+
142
+ """
143
+ if p > 1 or p < 0:
144
+ msg = f"NetworkXError p={p} is not in [0,1]."
145
+ raise nx.NetworkXError(msg)
146
+ if n < 2:
147
+ msg = "n must be greater than or equal to 2"
148
+ raise nx.NetworkXError(msg)
149
+
150
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
151
+ G = nx.empty_graph(create_using=create_using)
152
+
153
+ # Initialize the graph with two connected nodes.
154
+ G.add_edge(0, 1)
155
+ i = 2
156
+ while i < n:
157
+ # Choose a random node from current graph to duplicate.
158
+ random_node = seed.choice(list(G))
159
+ # Make the replica.
160
+ G.add_node(i)
161
+ # flag indicates whether at least one edge is connected on the replica.
162
+ flag = False
163
+ for nbr in G.neighbors(random_node):
164
+ if seed.random() < p:
165
+ # Link retention step.
166
+ G.add_edge(i, nbr)
167
+ flag = True
168
+ if not flag:
169
+ # Delete replica if no edges retained.
170
+ G.remove_node(i)
171
+ else:
172
+ # Successful duplication.
173
+ i += 1
174
+ return G
pace_revision_2/.venv-pace/lib/python3.11/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
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/expanders.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]_.
100
+
101
+ `p` *must* be a prime number.
102
+
103
+ Parameters
104
+ ----------
105
+ p : a prime number
106
+
107
+ The number of vertices in the graph. This also indicates where the
108
+ chordal edges in the cycle will be created.
109
+
110
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
111
+ Graph type to create. If graph instance, then cleared before populated.
112
+
113
+ Returns
114
+ -------
115
+ G : graph
116
+ The constructed undirected multigraph.
117
+
118
+ Raises
119
+ ------
120
+ NetworkXError
121
+
122
+ If `create_using` indicates directed or not a multigraph.
123
+
124
+ References
125
+ ----------
126
+
127
+ .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and
128
+ invariant measures", volume 125 of Progress in Mathematics.
129
+ Birkhäuser Verlag, Basel, 1994.
130
+
131
+ """
132
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
133
+ if G.is_directed() or not G.is_multigraph():
134
+ msg = "`create_using` must be an undirected multigraph."
135
+ raise nx.NetworkXError(msg)
136
+
137
+ for x in range(p):
138
+ left = (x - 1) % p
139
+ right = (x + 1) % p
140
+ # Here we apply Fermat's Little Theorem to compute the multiplicative
141
+ # inverse of x in Z/pZ. By Fermat's Little Theorem,
142
+ #
143
+ # x^p = x (mod p)
144
+ #
145
+ # Therefore,
146
+ #
147
+ # x * x^(p - 2) = 1 (mod p)
148
+ #
149
+ # The number 0 is a special case: we just let its inverse be itself.
150
+ chord = pow(x, p - 2, p) if x > 0 else 0
151
+ for y in (left, right, chord):
152
+ G.add_edge(x, y)
153
+ G.graph["name"] = f"chordal_cycle_graph({p})"
154
+ return G
155
+
156
+
157
+ @nx._dispatchable(graphs=None, returns_graph=True)
158
+ def paley_graph(p, create_using=None):
159
+ r"""Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
160
+
161
+ The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
162
+ if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
163
+
164
+ If $p \equiv 1 \pmod 4$, $-1$ is a square in
165
+ $\mathbb{Z}/p\mathbb{Z}$ and therefore $x-y$ is a square if and
166
+ only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
167
+
168
+ If $p \equiv 3 \pmod 4$, $-1$ is not a square in $\mathbb{Z}/p\mathbb{Z}$
169
+ and therefore either $x-y$ or $y-x$ is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
170
+
171
+ Note that a more general definition of Paley graphs extends this construction
172
+ to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of
173
+ $\mathbb{Z}/p\mathbb{Z}$.
174
+ This construction requires to compute squares in general finite fields and is
175
+ not what is implemented here (i.e `paley_graph(25)` does not return the true
176
+ Paley graph associated with $5^2$).
177
+
178
+ Parameters
179
+ ----------
180
+ p : int, an odd prime number.
181
+
182
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
183
+ Graph type to create. If graph instance, then cleared before populated.
184
+
185
+ Returns
186
+ -------
187
+ G : graph
188
+ The constructed directed graph.
189
+
190
+ Raises
191
+ ------
192
+ NetworkXError
193
+ If the graph is a multigraph.
194
+
195
+ References
196
+ ----------
197
+ Chapter 13 in B. Bollobas, Random Graphs. Second edition.
198
+ Cambridge Studies in Advanced Mathematics, 73.
199
+ Cambridge University Press, Cambridge (2001).
200
+ """
201
+ G = nx.empty_graph(0, create_using, default=nx.DiGraph)
202
+ if G.is_multigraph():
203
+ msg = "`create_using` cannot be a multigraph."
204
+ raise nx.NetworkXError(msg)
205
+
206
+ # Compute the squares in Z/pZ.
207
+ # Make it a set to uniquify (there are exactly (p-1)/2 squares in Z/pZ
208
+ # when is prime).
209
+ square_set = {(x**2) % p for x in range(1, p) if (x**2) % p != 0}
210
+
211
+ for x in range(p):
212
+ for x2 in square_set:
213
+ G.add_edge(x, (x + x2) % p)
214
+ G.graph["name"] = f"paley({p})"
215
+ return G
216
+
217
+
218
+ @nx.utils.decorators.np_random_state("seed")
219
+ @nx._dispatchable(graphs=None, returns_graph=True)
220
+ def maybe_regular_expander_graph(n, d, *, create_using=None, max_tries=100, seed=None):
221
+ r"""Utility for creating a random regular expander.
222
+
223
+ Returns a random $d$-regular graph on $n$ nodes which is an expander
224
+ graph with very good probability.
225
+
226
+ Parameters
227
+ ----------
228
+ n : int
229
+ The number of nodes.
230
+ d : int
231
+ The degree of each node.
232
+ create_using : Graph Instance or Constructor
233
+ Indicator of type of graph to return.
234
+ If a Graph-type instance, then clear and use it.
235
+ If a constructor, call it to create an empty graph.
236
+ Use the Graph constructor by default.
237
+ max_tries : int. (default: 100)
238
+ The number of allowed loops when generating each independent cycle
239
+ seed : (default: None)
240
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
241
+
242
+ Notes
243
+ -----
244
+ The nodes are numbered from $0$ to $n - 1$.
245
+
246
+ The graph is generated by taking $d / 2$ random independent cycles.
247
+
248
+ Joel Friedman proved that in this model the resulting
249
+ graph is an expander with probability
250
+ $1 - O(n^{-\tau})$ where $\tau = \lceil (\sqrt{d - 1}) / 2 \rceil - 1$. [1]_
251
+
252
+ Examples
253
+ --------
254
+ >>> G = nx.maybe_regular_expander_graph(n=200, d=6, seed=8020)
255
+
256
+ Returns
257
+ -------
258
+ G : graph
259
+ The constructed undirected graph.
260
+
261
+ Raises
262
+ ------
263
+ NetworkXError
264
+ If $d % 2 != 0$ as the degree must be even.
265
+ If $n - 1$ is less than $ 2d $ as the graph is complete at most.
266
+ If max_tries is reached
267
+
268
+ See Also
269
+ --------
270
+ is_regular_expander
271
+ random_regular_expander_graph
272
+
273
+ References
274
+ ----------
275
+ .. [1] Joel Friedman,
276
+ A Proof of Alon's Second Eigenvalue Conjecture and Related Problems, 2004
277
+ https://arxiv.org/abs/cs/0405020
278
+
279
+ """
280
+
281
+ import numpy as np
282
+
283
+ if n < 1:
284
+ raise nx.NetworkXError("n must be a positive integer")
285
+
286
+ if not (d >= 2):
287
+ raise nx.NetworkXError("d must be greater than or equal to 2")
288
+
289
+ if not (d % 2 == 0):
290
+ raise nx.NetworkXError("d must be even")
291
+
292
+ if not (n - 1 >= d):
293
+ raise nx.NetworkXError(
294
+ f"Need n-1>= d to have room for {d // 2} independent cycles with {n} nodes"
295
+ )
296
+
297
+ G = nx.empty_graph(n, create_using)
298
+
299
+ if n < 2:
300
+ return G
301
+
302
+ cycles = []
303
+ edges = set()
304
+
305
+ # Create d / 2 cycles
306
+ for i in range(d // 2):
307
+ iterations = max_tries
308
+ # Make sure the cycles are independent to have a regular graph
309
+ while len(edges) != (i + 1) * n:
310
+ iterations -= 1
311
+ # Faster than random.permutation(n) since there are only
312
+ # (n-1)! distinct cycles against n! permutations of size n
313
+ cycle = seed.permutation(n - 1).tolist()
314
+ cycle.append(n - 1)
315
+
316
+ new_edges = {
317
+ (u, v)
318
+ for u, v in nx.utils.pairwise(cycle, cyclic=True)
319
+ if (u, v) not in edges and (v, u) not in edges
320
+ }
321
+ # If the new cycle has no edges in common with previous cycles
322
+ # then add it to the list otherwise try again
323
+ if len(new_edges) == n:
324
+ cycles.append(cycle)
325
+ edges.update(new_edges)
326
+
327
+ if iterations == 0:
328
+ msg = "Too many iterations in maybe_regular_expander_graph"
329
+ raise nx.NetworkXError(msg)
330
+
331
+ G.add_edges_from(edges)
332
+
333
+ return G
334
+
335
+
336
+ def maybe_regular_expander(n, d, *, create_using=None, max_tries=100, seed=None):
337
+ """
338
+ .. deprecated:: 3.6
339
+ `maybe_regular_expander` is a deprecated alias
340
+ for `maybe_regular_expander_graph`.
341
+ Use `maybe_regular_expander_graph` instead.
342
+ """
343
+ import warnings
344
+
345
+ warnings.warn(
346
+ "maybe_regular_expander is deprecated, "
347
+ "use `maybe_regular_expander_graph` instead.",
348
+ category=DeprecationWarning,
349
+ stacklevel=2,
350
+ )
351
+ return maybe_regular_expander_graph(
352
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
353
+ )
354
+
355
+
356
+ @nx.utils.not_implemented_for("directed")
357
+ @nx.utils.not_implemented_for("multigraph")
358
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
359
+ def is_regular_expander(G, *, epsilon=0):
360
+ r"""Determines whether the graph G is a regular expander. [1]_
361
+
362
+ An expander graph is a sparse graph with strong connectivity properties.
363
+
364
+ More precisely, this helper checks whether the graph is a
365
+ regular $(n, d, \lambda)$-expander with $\lambda$ close to
366
+ the Alon-Boppana bound and given by
367
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$. [2]_
368
+
369
+ In the case where $\epsilon = 0$ then if the graph successfully passes the test
370
+ it is a Ramanujan graph. [3]_
371
+
372
+ A Ramanujan graph has spectral gap almost as large as possible, which makes them
373
+ excellent expanders.
374
+
375
+ Parameters
376
+ ----------
377
+ G : NetworkX graph
378
+ epsilon : int, float, default=0
379
+
380
+ Returns
381
+ -------
382
+ bool
383
+ Whether the given graph is a regular $(n, d, \lambda)$-expander
384
+ where $\lambda = 2 \sqrt{d - 1} + \epsilon$.
385
+
386
+ Examples
387
+ --------
388
+ >>> G = nx.random_regular_expander_graph(20, 4)
389
+ >>> nx.is_regular_expander(G)
390
+ True
391
+
392
+ See Also
393
+ --------
394
+ maybe_regular_expander_graph
395
+ random_regular_expander_graph
396
+
397
+ References
398
+ ----------
399
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
400
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
401
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
402
+
403
+ """
404
+
405
+ import numpy as np
406
+ import scipy as sp
407
+
408
+ if epsilon < 0:
409
+ raise nx.NetworkXError("epsilon must be non negative")
410
+
411
+ if not nx.is_regular(G):
412
+ return False
413
+
414
+ _, d = nx.utils.arbitrary_element(G.degree)
415
+
416
+ A = nx.adjacency_matrix(G, dtype=float)
417
+ lams = sp.sparse.linalg.eigsh(A, which="LM", k=2, return_eigenvectors=False)
418
+
419
+ # lambda2 is the second biggest eigenvalue
420
+ lambda2 = min(lams)
421
+
422
+ # Use bool() to convert numpy scalar to Python Boolean
423
+ return bool(abs(lambda2) < 2 * np.sqrt(d - 1) + epsilon)
424
+
425
+
426
+ @nx.utils.decorators.np_random_state("seed")
427
+ @nx._dispatchable(graphs=None, returns_graph=True)
428
+ def random_regular_expander_graph(
429
+ n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None
430
+ ):
431
+ r"""Returns a random regular expander graph on $n$ nodes with degree $d$.
432
+
433
+ An expander graph is a sparse graph with strong connectivity properties. [1]_
434
+
435
+ More precisely the returned graph is a $(n, d, \lambda)$-expander with
436
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
437
+
438
+ In the case where $\epsilon = 0$ it returns a Ramanujan graph.
439
+ A Ramanujan graph has spectral gap almost as large as possible,
440
+ which makes them excellent expanders. [3]_
441
+
442
+ Parameters
443
+ ----------
444
+ n : int
445
+ The number of nodes.
446
+ d : int
447
+ The degree of each node.
448
+ epsilon : int, float, default=0
449
+ max_tries : int, (default: 100)
450
+ The number of allowed loops,
451
+ also used in the `maybe_regular_expander_graph` utility
452
+ seed : (default: None)
453
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
454
+
455
+ Raises
456
+ ------
457
+ NetworkXError
458
+ If max_tries is reached
459
+
460
+ Examples
461
+ --------
462
+ >>> G = nx.random_regular_expander_graph(20, 4)
463
+ >>> nx.is_regular_expander(G)
464
+ True
465
+
466
+ Notes
467
+ -----
468
+ This loops over `maybe_regular_expander_graph` and can be slow when
469
+ $n$ is too big or $\epsilon$ too small.
470
+
471
+ See Also
472
+ --------
473
+ maybe_regular_expander_graph
474
+ is_regular_expander
475
+
476
+ References
477
+ ----------
478
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
479
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
480
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
481
+
482
+ """
483
+ G = maybe_regular_expander_graph(
484
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
485
+ )
486
+ iterations = max_tries
487
+
488
+ while not is_regular_expander(G, epsilon=epsilon):
489
+ iterations -= 1
490
+ G = maybe_regular_expander_graph(
491
+ n=n, d=d, create_using=create_using, max_tries=max_tries, seed=seed
492
+ )
493
+
494
+ if iterations == 0:
495
+ raise nx.NetworkXError(
496
+ "Too many iterations in random_regular_expander_graph"
497
+ )
498
+
499
+ return G
pace_revision_2/.venv-pace/lib/python3.11/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) / 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
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/harary_graph.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from networkx.exception import NetworkXError
20
+
21
+ __all__ = ["hnm_harary_graph", "hkn_harary_graph"]
22
+
23
+
24
+ @nx._dispatchable(graphs=None, returns_graph=True)
25
+ def hnm_harary_graph(n, m, create_using=None):
26
+ r"""Return the Harary graph with given numbers of nodes and edges.
27
+
28
+ The Harary graph $H_{n, m}$ is the graph that maximizes node connectivity
29
+ with $n$ nodes and $m$ edges.
30
+
31
+ This maximum node connectivity is known to be $\lfloor 2m/n \rfloor$. [1]_
32
+
33
+ Parameters
34
+ ----------
35
+ n: integer
36
+ The number of nodes the generated graph is to contain.
37
+
38
+ m: integer
39
+ The number of edges the generated graph is to contain.
40
+
41
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
42
+ Graph type to create. If graph instance, then cleared before populated.
43
+
44
+ Returns
45
+ -------
46
+ NetworkX graph
47
+ The Harary graph $H_{n, m}$.
48
+
49
+ See Also
50
+ --------
51
+ hkn_harary_graph
52
+
53
+ Notes
54
+ -----
55
+ This algorithm runs in $O(m)$ time.
56
+ The implementation follows [2]_.
57
+
58
+ References
59
+ ----------
60
+ .. [1] F. T. Boesch, A. Satyanarayana, and C. L. Suffel,
61
+ "A Survey of Some Network Reliability Analysis and Synthesis Results,"
62
+ Networks, pp. 99-107, 2009.
63
+
64
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
65
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
66
+ """
67
+
68
+ if n < 1:
69
+ raise NetworkXError("The number of nodes must be >= 1!")
70
+ if m < n - 1:
71
+ raise NetworkXError("The number of edges must be >= n - 1 !")
72
+ if m > n * (n - 1) // 2:
73
+ raise NetworkXError("The number of edges must be <= n(n-1)/2")
74
+
75
+ # Get the floor of average node degree.
76
+ d = 2 * m // n
77
+
78
+ offset = d // 2
79
+ H = nx.circulant_graph(n, range(1, offset + 1), create_using=create_using)
80
+
81
+ half = n // 2
82
+ if (n % 2 == 0) or (d % 2 == 0):
83
+ # If d is odd; n must be even.
84
+ if d % 2 == 1:
85
+ # Add edges diagonally.
86
+ H.add_edges_from((i, i + half) for i in range(half))
87
+
88
+ r = 2 * m % n
89
+ # Add remaining edges at offset + 1.
90
+ H.add_edges_from((i, i + offset + 1) for i in range(r // 2))
91
+ else:
92
+ # Add the remaining m - n * offset edges between i and i + half.
93
+ H.add_edges_from((i, (i + half) % n) for i in range(m - n * offset))
94
+
95
+ return H
96
+
97
+
98
+ @nx._dispatchable(graphs=None, returns_graph=True)
99
+ def hkn_harary_graph(k, n, create_using=None):
100
+ r"""Return the Harary graph with given node connectivity and node number.
101
+
102
+ The Harary graph $H_{k, n}$ is the graph that minimizes the number of
103
+ edges needed with given node connectivity $k$ and node number $n$.
104
+
105
+ This smallest number of edges is known to be $\lceil kn/2 \rceil$ [1]_.
106
+
107
+ Parameters
108
+ ----------
109
+ k: integer
110
+ The node connectivity of the generated graph.
111
+
112
+ n: integer
113
+ The number of nodes the generated graph is to contain.
114
+
115
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
116
+ Graph type to create. If graph instance, then cleared before populated.
117
+
118
+ Returns
119
+ -------
120
+ NetworkX graph
121
+ The Harary graph $H_{k, n}$.
122
+
123
+ See Also
124
+ --------
125
+ hnm_harary_graph
126
+
127
+ Notes
128
+ -----
129
+ This algorithm runs in $O(kn)$ time.
130
+ The implementation follows [2]_.
131
+
132
+ References
133
+ ----------
134
+ .. [1] Weisstein, Eric W. "Harary Graph." From MathWorld--A Wolfram Web
135
+ Resource. http://mathworld.wolfram.com/HararyGraph.html.
136
+
137
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
138
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
139
+ """
140
+
141
+ if k < 1:
142
+ raise NetworkXError("The node connectivity must be >= 1!")
143
+ if n < k + 1:
144
+ raise NetworkXError("The number of nodes must be >= k+1 !")
145
+
146
+ # In case of connectivity 1, simply return the path graph.
147
+ if k == 1:
148
+ return nx.path_graph(n, create_using)
149
+
150
+ offset = k // 2
151
+ H = nx.circulant_graph(n, range(1, offset + 1), create_using=create_using)
152
+
153
+ half = n // 2
154
+ if (k % 2 == 0) or (n % 2 == 0):
155
+ # If k is odd; n must be even.
156
+ if k % 2 == 1:
157
+ # Add edges diagonally.
158
+ H.add_edges_from((i, i + half) for i in range(half))
159
+ else:
160
+ # Add half + 1 edges between i and i + half.
161
+ H.add_edges_from((i, (i + half) % n) for i in range(half + 1))
162
+
163
+ return H
pace_revision_2/.venv-pace/lib/python3.11/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
pace_revision_2/.venv-pace/lib/python3.11/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))
pace_revision_2/.venv-pace/lib/python3.11/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
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/joint_degree_seq.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given joint degree and directed joint degree"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = [
7
+ "is_valid_joint_degree",
8
+ "is_valid_directed_joint_degree",
9
+ "joint_degree_graph",
10
+ "directed_joint_degree_graph",
11
+ ]
12
+
13
+
14
+ @nx._dispatchable(graphs=None)
15
+ def is_valid_joint_degree(joint_degrees):
16
+ """Checks whether the given joint degree dictionary is realizable.
17
+
18
+ A *joint degree dictionary* is a dictionary of dictionaries, in
19
+ which entry ``joint_degrees[k][l]`` is an integer representing the
20
+ number of edges joining nodes of degree *k* with nodes of degree
21
+ *l*. Such a dictionary is realizable as a simple graph if and only
22
+ if the following conditions are satisfied.
23
+
24
+ - each entry must be an integer,
25
+ - the total number of nodes of degree *k*, computed by
26
+ ``sum(joint_degrees[k].values()) / k``, must be an integer,
27
+ - the total number of edges joining nodes of degree *k* with
28
+ nodes of degree *l* cannot exceed the total number of possible edges,
29
+ - each diagonal entry ``joint_degrees[k][k]`` must be even (this is
30
+ a convention assumed by the :func:`joint_degree_graph` function).
31
+
32
+
33
+ Parameters
34
+ ----------
35
+ joint_degrees : dictionary of dictionary of integers
36
+ A joint degree dictionary in which entry ``joint_degrees[k][l]``
37
+ is the number of edges joining nodes of degree *k* with nodes of
38
+ degree *l*.
39
+
40
+ Returns
41
+ -------
42
+ bool
43
+ Whether the given joint degree dictionary is realizable as a
44
+ simple graph.
45
+
46
+ References
47
+ ----------
48
+ .. [1] M. Gjoka, M. Kurant, A. Markopoulou, "2.5K Graphs: from Sampling
49
+ to Generation", IEEE Infocom, 2013.
50
+ .. [2] I. Stanton, A. Pinar, "Constructing and sampling graphs with a
51
+ prescribed joint degree distribution", Journal of Experimental
52
+ Algorithmics, 2012.
53
+ """
54
+
55
+ degree_count = {}
56
+ for k in joint_degrees:
57
+ if k > 0:
58
+ k_size = sum(joint_degrees[k].values()) / k
59
+ if not k_size.is_integer():
60
+ return False
61
+ degree_count[k] = k_size
62
+
63
+ for k in joint_degrees:
64
+ for l in joint_degrees[k]:
65
+ if not float(joint_degrees[k][l]).is_integer():
66
+ return False
67
+
68
+ if (k != l) and (joint_degrees[k][l] > degree_count[k] * degree_count[l]):
69
+ return False
70
+ elif k == l:
71
+ if joint_degrees[k][k] > degree_count[k] * (degree_count[k] - 1):
72
+ return False
73
+ if joint_degrees[k][k] % 2 != 0:
74
+ return False
75
+
76
+ # if all above conditions have been satisfied then the input
77
+ # joint degree is realizable as a simple graph.
78
+ return True
79
+
80
+
81
+ def _neighbor_switch(G, w, unsat, h_node_residual, avoid_node_id=None):
82
+ """Releases one free stub for ``w``, while preserving joint degree in G.
83
+
84
+ Parameters
85
+ ----------
86
+ G : NetworkX graph
87
+ Graph in which the neighbor switch will take place.
88
+ w : integer
89
+ Node id for which we will execute this neighbor switch.
90
+ unsat : set of integers
91
+ Set of unsaturated node ids that have the same degree as w.
92
+ h_node_residual: dictionary of integers
93
+ Keeps track of the remaining stubs for a given node.
94
+ avoid_node_id: integer
95
+ Node id to avoid when selecting w_prime.
96
+
97
+ Notes
98
+ -----
99
+ First, it selects *w_prime*, an unsaturated node that has the same degree
100
+ as ``w``. Second, it selects *switch_node*, a neighbor node of ``w`` that
101
+ is not connected to *w_prime*. Then it executes an edge swap i.e. removes
102
+ (``w``,*switch_node*) and adds (*w_prime*,*switch_node*). Gjoka et. al. [1]
103
+ prove that such an edge swap is always possible.
104
+
105
+ References
106
+ ----------
107
+ .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
108
+ Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
109
+ """
110
+
111
+ if (avoid_node_id is None) or (h_node_residual[avoid_node_id] > 1):
112
+ # select unsaturated node w_prime that has the same degree as w
113
+ w_prime = next(iter(unsat))
114
+ else:
115
+ # assume that the node pair (v,w) has been selected for connection. if
116
+ # - neighbor_switch is called for node w,
117
+ # - nodes v and w have the same degree,
118
+ # - node v=avoid_node_id has only one stub left,
119
+ # then prevent v=avoid_node_id from being selected as w_prime.
120
+
121
+ iter_var = iter(unsat)
122
+ while True:
123
+ w_prime = next(iter_var)
124
+ if w_prime != avoid_node_id:
125
+ break
126
+
127
+ # select switch_node, a neighbor of w, that is not connected to w_prime
128
+ w_prime_neighbs = G[w_prime] # slightly faster declaring this variable
129
+ for v in G[w]:
130
+ if (v not in w_prime_neighbs) and (v != w_prime):
131
+ switch_node = v
132
+ break
133
+
134
+ # remove edge (w,switch_node), add edge (w_prime,switch_node) and update
135
+ # data structures
136
+ G.remove_edge(w, switch_node)
137
+ G.add_edge(w_prime, switch_node)
138
+ h_node_residual[w] += 1
139
+ h_node_residual[w_prime] -= 1
140
+ if h_node_residual[w_prime] == 0:
141
+ unsat.remove(w_prime)
142
+
143
+
144
+ @py_random_state(1)
145
+ @nx._dispatchable(graphs=None, returns_graph=True)
146
+ def joint_degree_graph(joint_degrees, seed=None):
147
+ """Generates a random simple graph with the given joint degree dictionary.
148
+
149
+ Parameters
150
+ ----------
151
+ joint_degrees : dictionary of dictionary of integers
152
+ A joint degree dictionary in which entry ``joint_degrees[k][l]`` is the
153
+ number of edges joining nodes of degree *k* with nodes of degree *l*.
154
+ seed : integer, random_state, or None (default)
155
+ Indicator of random number generation state.
156
+ See :ref:`Randomness<randomness>`.
157
+
158
+ Returns
159
+ -------
160
+ G : Graph
161
+ A graph with the specified joint degree dictionary.
162
+
163
+ Raises
164
+ ------
165
+ NetworkXError
166
+ If *joint_degrees* dictionary is not realizable.
167
+
168
+ Notes
169
+ -----
170
+ In each iteration of the "while loop" the algorithm picks two disconnected
171
+ nodes *v* and *w*, of degree *k* and *l* correspondingly, for which
172
+ ``joint_degrees[k][l]`` has not reached its target yet. It then adds
173
+ edge (*v*, *w*) and increases the number of edges in graph G by one.
174
+
175
+ The intelligence of the algorithm lies in the fact that it is always
176
+ possible to add an edge between such disconnected nodes *v* and *w*,
177
+ even if one or both nodes do not have free stubs. That is made possible by
178
+ executing a "neighbor switch", an edge rewiring move that releases
179
+ a free stub while keeping the joint degree of G the same.
180
+
181
+ The algorithm continues for E (number of edges) iterations of
182
+ the "while loop", at the which point all entries of the given
183
+ ``joint_degrees[k][l]`` have reached their target values and the
184
+ construction is complete.
185
+
186
+ References
187
+ ----------
188
+ .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
189
+ Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
190
+
191
+ Examples
192
+ --------
193
+ >>> joint_degrees = {
194
+ ... 1: {4: 1},
195
+ ... 2: {2: 2, 3: 2, 4: 2},
196
+ ... 3: {2: 2, 4: 1},
197
+ ... 4: {1: 1, 2: 2, 3: 1},
198
+ ... }
199
+ >>> G = nx.joint_degree_graph(joint_degrees)
200
+ >>>
201
+ """
202
+
203
+ if not is_valid_joint_degree(joint_degrees):
204
+ msg = "Input joint degree dict not realizable as a simple graph"
205
+ raise nx.NetworkXError(msg)
206
+
207
+ # compute degree count from joint_degrees
208
+ degree_count = {k: sum(l.values()) // k for k, l in joint_degrees.items() if k > 0}
209
+
210
+ # start with empty N-node graph
211
+ N = sum(degree_count.values())
212
+ G = nx.empty_graph(N)
213
+
214
+ # for a given degree group, keep the list of all node ids
215
+ h_degree_nodelist = {}
216
+
217
+ # for a given node, keep track of the remaining stubs
218
+ h_node_residual = {}
219
+
220
+ # populate h_degree_nodelist and h_node_residual
221
+ nodeid = 0
222
+ for degree, num_nodes in degree_count.items():
223
+ h_degree_nodelist[degree] = range(nodeid, nodeid + num_nodes)
224
+ for v in h_degree_nodelist[degree]:
225
+ h_node_residual[v] = degree
226
+ nodeid += int(num_nodes)
227
+
228
+ # iterate over every degree pair (k,l) and add the number of edges given
229
+ # for each pair
230
+ for k in joint_degrees:
231
+ for l in joint_degrees[k]:
232
+ # n_edges_add is the number of edges to add for the
233
+ # degree pair (k,l)
234
+ n_edges_add = joint_degrees[k][l]
235
+
236
+ if (n_edges_add > 0) and (k >= l):
237
+ # number of nodes with degree k and l
238
+ k_size = degree_count[k]
239
+ l_size = degree_count[l]
240
+
241
+ # k_nodes and l_nodes consist of all nodes of degree k and l
242
+ k_nodes = h_degree_nodelist[k]
243
+ l_nodes = h_degree_nodelist[l]
244
+
245
+ # k_unsat and l_unsat consist of nodes of degree k and l that
246
+ # are unsaturated (nodes that have at least 1 available stub)
247
+ k_unsat = {v for v in k_nodes if h_node_residual[v] > 0}
248
+
249
+ if k != l:
250
+ l_unsat = {w for w in l_nodes if h_node_residual[w] > 0}
251
+ else:
252
+ l_unsat = k_unsat
253
+ n_edges_add = joint_degrees[k][l] // 2
254
+
255
+ while n_edges_add > 0:
256
+ # randomly pick nodes v and w that have degrees k and l
257
+ v = k_nodes[seed.randrange(k_size)]
258
+ w = l_nodes[seed.randrange(l_size)]
259
+
260
+ # if nodes v and w are disconnected then attempt to connect
261
+ if not G.has_edge(v, w) and (v != w):
262
+ # if node v has no free stubs then do neighbor switch
263
+ if h_node_residual[v] == 0:
264
+ _neighbor_switch(G, v, k_unsat, h_node_residual)
265
+
266
+ # if node w has no free stubs then do neighbor switch
267
+ if h_node_residual[w] == 0:
268
+ if k != l:
269
+ _neighbor_switch(G, w, l_unsat, h_node_residual)
270
+ else:
271
+ _neighbor_switch(
272
+ G, w, l_unsat, h_node_residual, avoid_node_id=v
273
+ )
274
+
275
+ # add edge (v, w) and update data structures
276
+ G.add_edge(v, w)
277
+ h_node_residual[v] -= 1
278
+ h_node_residual[w] -= 1
279
+ n_edges_add -= 1
280
+
281
+ if h_node_residual[v] == 0:
282
+ k_unsat.discard(v)
283
+ if h_node_residual[w] == 0:
284
+ l_unsat.discard(w)
285
+ return G
286
+
287
+
288
+ @nx._dispatchable(graphs=None)
289
+ def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
290
+ """Checks whether the given directed joint degree input is realizable
291
+
292
+ Parameters
293
+ ----------
294
+ in_degrees : list of integers
295
+ in degree sequence contains the in degrees of nodes.
296
+ out_degrees : list of integers
297
+ out degree sequence contains the out degrees of nodes.
298
+ nkk : dictionary of dictionary of integers
299
+ directed joint degree dictionary. for nodes of out degree k (first
300
+ level of dict) and nodes of in degree l (second level of dict)
301
+ describes the number of edges.
302
+
303
+ Returns
304
+ -------
305
+ boolean
306
+ returns true if given input is realizable, else returns false.
307
+
308
+ Notes
309
+ -----
310
+ Here is the list of conditions that the inputs (in/out degree sequences,
311
+ nkk) need to satisfy for simple directed graph realizability:
312
+
313
+ - Condition 0: in_degrees and out_degrees have the same length
314
+ - Condition 1: nkk[k][l] is integer for all k,l
315
+ - Condition 2: sum(nkk[k])/k = number of nodes with partition id k, is an
316
+ integer and matching degree sequence
317
+ - Condition 3: number of edges and non-chords between k and l cannot exceed
318
+ maximum possible number of edges
319
+
320
+
321
+ References
322
+ ----------
323
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
324
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
325
+ """
326
+ V = {} # number of nodes with in/out degree.
327
+ forbidden = {}
328
+ if len(in_degrees) != len(out_degrees):
329
+ return False
330
+
331
+ for idx in range(len(in_degrees)):
332
+ i = in_degrees[idx]
333
+ o = out_degrees[idx]
334
+ V[(i, 0)] = V.get((i, 0), 0) + 1
335
+ V[(o, 1)] = V.get((o, 1), 0) + 1
336
+
337
+ forbidden[(o, i)] = forbidden.get((o, i), 0) + 1
338
+
339
+ S = {} # number of edges going from in/out degree nodes.
340
+ for k in nkk:
341
+ for l in nkk[k]:
342
+ val = nkk[k][l]
343
+ if not float(val).is_integer(): # condition 1
344
+ return False
345
+
346
+ if val > 0:
347
+ S[(k, 1)] = S.get((k, 1), 0) + val
348
+ S[(l, 0)] = S.get((l, 0), 0) + val
349
+ # condition 3
350
+ if val + forbidden.get((k, l), 0) > V[(k, 1)] * V[(l, 0)]:
351
+ return False
352
+
353
+ return all(S[s] / s[0] == V[s] for s in S)
354
+
355
+
356
+ def _directed_neighbor_switch(
357
+ G, w, unsat, h_node_residual_out, chords, h_partition_in, partition
358
+ ):
359
+ """Releases one free stub for node w, while preserving joint degree in G.
360
+
361
+ Parameters
362
+ ----------
363
+ G : networkx directed graph
364
+ graph within which the edge swap will take place.
365
+ w : integer
366
+ node id for which we need to perform a neighbor switch.
367
+ unsat: set of integers
368
+ set of node ids that have the same degree as w and are unsaturated.
369
+ h_node_residual_out: dict of integers
370
+ for a given node, keeps track of the remaining stubs to be added.
371
+ chords: set of tuples
372
+ keeps track of available positions to add edges.
373
+ h_partition_in: dict of integers
374
+ for a given node, keeps track of its partition id (in degree).
375
+ partition: integer
376
+ partition id to check if chords have to be updated.
377
+
378
+ Notes
379
+ -----
380
+ First, it selects node w_prime that (1) has the same degree as w and
381
+ (2) is unsaturated. Then, it selects node v, a neighbor of w, that is
382
+ not connected to w_prime and does an edge swap i.e. removes (w,v) and
383
+ adds (w_prime,v). If neighbor switch is not possible for w using
384
+ w_prime and v, then return w_prime; in [1] it's proven that
385
+ such unsaturated nodes can be used.
386
+
387
+ References
388
+ ----------
389
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
390
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
391
+ """
392
+ w_prime = unsat.pop()
393
+ unsat.add(w_prime)
394
+ # select node t, a neighbor of w, that is not connected to w_prime
395
+ w_neighbs = list(G.successors(w))
396
+ # slightly faster declaring this variable
397
+ w_prime_neighbs = list(G.successors(w_prime))
398
+
399
+ for v in w_neighbs:
400
+ if (v not in w_prime_neighbs) and w_prime != v:
401
+ # removes (w,v), add (w_prime,v) and update data structures
402
+ G.remove_edge(w, v)
403
+ G.add_edge(w_prime, v)
404
+
405
+ if h_partition_in[v] == partition:
406
+ chords.add((w, v))
407
+ chords.discard((w_prime, v))
408
+
409
+ h_node_residual_out[w] += 1
410
+ h_node_residual_out[w_prime] -= 1
411
+ if h_node_residual_out[w_prime] == 0:
412
+ unsat.remove(w_prime)
413
+ return None
414
+
415
+ # If neighbor switch didn't work, use unsaturated node
416
+ return w_prime
417
+
418
+
419
+ def _directed_neighbor_switch_rev(
420
+ G, w, unsat, h_node_residual_in, chords, h_partition_out, partition
421
+ ):
422
+ """The reverse of directed_neighbor_switch.
423
+
424
+ Parameters
425
+ ----------
426
+ G : networkx directed graph
427
+ graph within which the edge swap will take place.
428
+ w : integer
429
+ node id for which we need to perform a neighbor switch.
430
+ unsat: set of integers
431
+ set of node ids that have the same degree as w and are unsaturated.
432
+ h_node_residual_in: dict of integers
433
+ for a given node, keeps track of the remaining stubs to be added.
434
+ chords: set of tuples
435
+ keeps track of available positions to add edges.
436
+ h_partition_out: dict of integers
437
+ for a given node, keeps track of its partition id (out degree).
438
+ partition: integer
439
+ partition id to check if chords have to be updated.
440
+
441
+ Notes
442
+ -----
443
+ Same operation as directed_neighbor_switch except it handles this operation
444
+ for incoming edges instead of outgoing.
445
+ """
446
+ w_prime = unsat.pop()
447
+ unsat.add(w_prime)
448
+ # slightly faster declaring these as variables.
449
+ w_neighbs = list(G.predecessors(w))
450
+ w_prime_neighbs = list(G.predecessors(w_prime))
451
+ # select node v, a neighbor of w, that is not connected to w_prime.
452
+ for v in w_neighbs:
453
+ if (v not in w_prime_neighbs) and w_prime != v:
454
+ # removes (v,w), add (v,w_prime) and update data structures.
455
+ G.remove_edge(v, w)
456
+ G.add_edge(v, w_prime)
457
+ if h_partition_out[v] == partition:
458
+ chords.add((v, w))
459
+ chords.discard((v, w_prime))
460
+
461
+ h_node_residual_in[w] += 1
462
+ h_node_residual_in[w_prime] -= 1
463
+ if h_node_residual_in[w_prime] == 0:
464
+ unsat.remove(w_prime)
465
+ return None
466
+
467
+ # If neighbor switch didn't work, use the unsaturated node.
468
+ return w_prime
469
+
470
+
471
+ @py_random_state(3)
472
+ @nx._dispatchable(graphs=None, returns_graph=True)
473
+ def directed_joint_degree_graph(in_degrees, out_degrees, nkk, seed=None):
474
+ """Generates a random simple directed graph with the joint degree.
475
+
476
+ Parameters
477
+ ----------
478
+ degree_seq : list of tuples (of size 3)
479
+ degree sequence contains tuples of nodes with node id, in degree and
480
+ out degree.
481
+ nkk : dictionary of dictionary of integers
482
+ directed joint degree dictionary, for nodes of out degree k (first
483
+ level of dict) and nodes of in degree l (second level of dict)
484
+ describes the number of edges.
485
+ seed : hashable object, optional
486
+ Seed for random number generator.
487
+
488
+ Returns
489
+ -------
490
+ G : Graph
491
+ A directed graph with the specified inputs.
492
+
493
+ Raises
494
+ ------
495
+ NetworkXError
496
+ If degree_seq and nkk are not realizable as a simple directed graph.
497
+
498
+
499
+ Notes
500
+ -----
501
+ Similarly to the undirected version:
502
+ In each iteration of the "while loop" the algorithm picks two disconnected
503
+ nodes v and w, of degree k and l correspondingly, for which nkk[k][l] has
504
+ not reached its target yet i.e. (for given k,l): n_edges_add < nkk[k][l].
505
+ It then adds edge (v,w) and always increases the number of edges in graph G
506
+ by one.
507
+
508
+ The intelligence of the algorithm lies in the fact that it is always
509
+ possible to add an edge between disconnected nodes v and w, for which
510
+ nkk[degree(v)][degree(w)] has not reached its target, even if one or both
511
+ nodes do not have free stubs. If either node v or w does not have a free
512
+ stub, we perform a "neighbor switch", an edge rewiring move that releases a
513
+ free stub while keeping nkk the same.
514
+
515
+ The difference for the directed version lies in the fact that neighbor
516
+ switches might not be able to rewire, but in these cases unsaturated nodes
517
+ can be reassigned to use instead, see [1] for detailed description and
518
+ proofs.
519
+
520
+ The algorithm continues for E (number of edges in the graph) iterations of
521
+ the "while loop", at which point all entries of the given nkk[k][l] have
522
+ reached their target values and the construction is complete.
523
+
524
+ References
525
+ ----------
526
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
527
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
528
+
529
+ Examples
530
+ --------
531
+ >>> in_degrees = [0, 1, 1, 2]
532
+ >>> out_degrees = [1, 1, 1, 1]
533
+ >>> nkk = {1: {1: 2, 2: 2}}
534
+ >>> G = nx.directed_joint_degree_graph(in_degrees, out_degrees, nkk)
535
+ >>>
536
+ """
537
+ if not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
538
+ msg = "Input is not realizable as a simple graph"
539
+ raise nx.NetworkXError(msg)
540
+
541
+ # start with an empty directed graph.
542
+ G = nx.DiGraph()
543
+
544
+ # for a given group, keep the list of all node ids.
545
+ h_degree_nodelist_in = {}
546
+ h_degree_nodelist_out = {}
547
+ # for a given group, keep the list of all unsaturated node ids.
548
+ h_degree_nodelist_in_unsat = {}
549
+ h_degree_nodelist_out_unsat = {}
550
+ # for a given node, keep track of the remaining stubs to be added.
551
+ h_node_residual_out = {}
552
+ h_node_residual_in = {}
553
+ # for a given node, keep track of the partition id.
554
+ h_partition_out = {}
555
+ h_partition_in = {}
556
+ # keep track of non-chords between pairs of partition ids.
557
+ non_chords = {}
558
+
559
+ # populate data structures
560
+ for idx, i in enumerate(in_degrees):
561
+ idx = int(idx)
562
+ if i > 0:
563
+ h_degree_nodelist_in.setdefault(i, [])
564
+ h_degree_nodelist_in_unsat.setdefault(i, set())
565
+ h_degree_nodelist_in[i].append(idx)
566
+ h_degree_nodelist_in_unsat[i].add(idx)
567
+ h_node_residual_in[idx] = i
568
+ h_partition_in[idx] = i
569
+
570
+ for idx, o in enumerate(out_degrees):
571
+ o = out_degrees[idx]
572
+ non_chords[(o, in_degrees[idx])] = non_chords.get((o, in_degrees[idx]), 0) + 1
573
+ idx = int(idx)
574
+ if o > 0:
575
+ h_degree_nodelist_out.setdefault(o, [])
576
+ h_degree_nodelist_out_unsat.setdefault(o, set())
577
+ h_degree_nodelist_out[o].append(idx)
578
+ h_degree_nodelist_out_unsat[o].add(idx)
579
+ h_node_residual_out[idx] = o
580
+ h_partition_out[idx] = o
581
+
582
+ G.add_node(idx)
583
+
584
+ nk_in = {}
585
+ nk_out = {}
586
+ for p in h_degree_nodelist_in:
587
+ nk_in[p] = len(h_degree_nodelist_in[p])
588
+ for p in h_degree_nodelist_out:
589
+ nk_out[p] = len(h_degree_nodelist_out[p])
590
+
591
+ # iterate over every degree pair (k,l) and add the number of edges given
592
+ # for each pair.
593
+ for k in nkk:
594
+ for l in nkk[k]:
595
+ n_edges_add = nkk[k][l]
596
+
597
+ if n_edges_add > 0:
598
+ # chords contains a random set of potential edges.
599
+ chords = set()
600
+
601
+ k_len = nk_out[k]
602
+ l_len = nk_in[l]
603
+ chords_sample = seed.sample(
604
+ range(k_len * l_len), n_edges_add + non_chords.get((k, l), 0)
605
+ )
606
+
607
+ num = 0
608
+ while len(chords) < n_edges_add:
609
+ i = h_degree_nodelist_out[k][chords_sample[num] % k_len]
610
+ j = h_degree_nodelist_in[l][chords_sample[num] // k_len]
611
+ num += 1
612
+ if i != j:
613
+ chords.add((i, j))
614
+
615
+ # k_unsat and l_unsat consist of nodes of in/out degree k and l
616
+ # that are unsaturated i.e. those nodes that have at least one
617
+ # available stub
618
+ k_unsat = h_degree_nodelist_out_unsat[k]
619
+ l_unsat = h_degree_nodelist_in_unsat[l]
620
+
621
+ while n_edges_add > 0:
622
+ v, w = chords.pop()
623
+ chords.add((v, w))
624
+
625
+ # if node v has no free stubs then do neighbor switch.
626
+ if h_node_residual_out[v] == 0:
627
+ _v = _directed_neighbor_switch(
628
+ G,
629
+ v,
630
+ k_unsat,
631
+ h_node_residual_out,
632
+ chords,
633
+ h_partition_in,
634
+ l,
635
+ )
636
+ if _v is not None:
637
+ v = _v
638
+
639
+ # if node w has no free stubs then do neighbor switch.
640
+ if h_node_residual_in[w] == 0:
641
+ _w = _directed_neighbor_switch_rev(
642
+ G,
643
+ w,
644
+ l_unsat,
645
+ h_node_residual_in,
646
+ chords,
647
+ h_partition_out,
648
+ k,
649
+ )
650
+ if _w is not None:
651
+ w = _w
652
+
653
+ # add edge (v,w) and update data structures.
654
+ G.add_edge(v, w)
655
+ h_node_residual_out[v] -= 1
656
+ h_node_residual_in[w] -= 1
657
+ n_edges_add -= 1
658
+ chords.discard((v, w))
659
+
660
+ if h_node_residual_out[v] == 0:
661
+ k_unsat.discard(v)
662
+ if h_node_residual_in[w] == 0:
663
+ l_unsat.discard(w)
664
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/lattice.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating grid graphs and lattices
2
+
3
+ The :func:`grid_2d_graph`, :func:`triangular_lattice_graph`, and
4
+ :func:`hexagonal_lattice_graph` functions correspond to the three
5
+ `regular tilings of the plane`_, the square, triangular, and hexagonal
6
+ tilings, respectively. :func:`grid_graph` and :func:`hypercube_graph`
7
+ are similar for arbitrary dimensions. Useful relevant discussion can
8
+ be found about `Triangular Tiling`_, and `Square, Hex and Triangle Grids`_
9
+
10
+ .. _regular tilings of the plane: https://en.wikipedia.org/wiki/List_of_regular_polytopes_and_compounds#Euclidean_tilings
11
+ .. _Square, Hex and Triangle Grids: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
12
+ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
13
+
14
+ """
15
+
16
+ from itertools import repeat
17
+ from math import sqrt
18
+
19
+ import networkx as nx
20
+ from networkx.classes import set_node_attributes
21
+ from networkx.exception import NetworkXError
22
+ from networkx.generators.classic import cycle_graph, empty_graph, path_graph
23
+ from networkx.relabel import relabel_nodes
24
+ from networkx.utils import flatten, nodes_or_number, pairwise
25
+
26
+ __all__ = [
27
+ "grid_2d_graph",
28
+ "grid_graph",
29
+ "hypercube_graph",
30
+ "triangular_lattice_graph",
31
+ "hexagonal_lattice_graph",
32
+ ]
33
+
34
+
35
+ @nx._dispatchable(graphs=None, returns_graph=True)
36
+ @nodes_or_number([0, 1])
37
+ def grid_2d_graph(m, n, periodic=False, create_using=None):
38
+ """Returns the two-dimensional grid graph.
39
+
40
+ The grid graph has each node connected to its four nearest neighbors.
41
+
42
+ Parameters
43
+ ----------
44
+ m, n : int or iterable container of nodes
45
+ If an integer, nodes are from `range(n)`.
46
+ If a container, elements become the coordinate of the nodes.
47
+
48
+ periodic : bool or iterable
49
+ If `periodic` is True, both dimensions are periodic. If False, none
50
+ are periodic. If `periodic` is iterable, it should yield 2 bool
51
+ values indicating whether the 1st and 2nd axes, respectively, are
52
+ periodic.
53
+
54
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
55
+ Graph type to create. If graph instance, then cleared before populated.
56
+
57
+ Returns
58
+ -------
59
+ NetworkX graph
60
+ The (possibly periodic) grid graph of the specified dimensions.
61
+
62
+ See Also
63
+ --------
64
+ triangular_lattice_graph, hexagonal_lattice_graph :
65
+ Other 2D lattice graphs
66
+ grid_graph, hypercube_graph :
67
+ N-dimensional lattice graphs
68
+ """
69
+ G = empty_graph(0, create_using)
70
+ row_name, rows = m
71
+ col_name, cols = n
72
+ G.add_nodes_from((i, j) for i in rows for j in cols)
73
+ G.add_edges_from(((i, j), (pi, j)) for pi, i in pairwise(rows) for j in cols)
74
+ G.add_edges_from(((i, j), (i, pj)) for i in rows for pj, j in pairwise(cols))
75
+
76
+ try:
77
+ periodic_r, periodic_c = periodic
78
+ except TypeError:
79
+ periodic_r = periodic_c = periodic
80
+
81
+ if periodic_r and len(rows) > 2:
82
+ first = rows[0]
83
+ last = rows[-1]
84
+ G.add_edges_from(((first, j), (last, j)) for j in cols)
85
+ if periodic_c and len(cols) > 2:
86
+ first = cols[0]
87
+ last = cols[-1]
88
+ G.add_edges_from(((i, first), (i, last)) for i in rows)
89
+ # both directions for directed
90
+ if G.is_directed():
91
+ G.add_edges_from((v, u) for u, v in G.edges())
92
+ return G
93
+
94
+
95
+ @nx._dispatchable(graphs=None, returns_graph=True)
96
+ def grid_graph(dim, periodic=False):
97
+ """Returns the *n*-dimensional grid graph.
98
+
99
+ The dimension *n* is the length of the list `dim` and the size in
100
+ each dimension is the value of the corresponding list element.
101
+
102
+ Parameters
103
+ ----------
104
+ dim : list or tuple of numbers or iterables of nodes
105
+ 'dim' is a tuple or list with, for each dimension, either a number
106
+ that is the size of that dimension or an iterable of nodes for
107
+ that dimension. The dimension of the grid_graph is the length
108
+ of `dim`.
109
+
110
+ periodic : bool or iterable
111
+ If `periodic` is True, all dimensions are periodic. If False all
112
+ dimensions are not periodic. If `periodic` is iterable, it should
113
+ yield `dim` bool values each of which indicates whether the
114
+ corresponding axis is periodic.
115
+
116
+ Returns
117
+ -------
118
+ NetworkX graph
119
+ The (possibly periodic) grid graph of the specified dimensions.
120
+
121
+ See Also
122
+ --------
123
+ grid_2d_graph, triangular_lattice_graph, hexagonal_lattice_graph :
124
+ 2D lattice graphs
125
+ hypercube_graph :
126
+ A special case of `grid_graph` where all elements of `dim` are identical
127
+
128
+ Examples
129
+ --------
130
+ To produce a 2 by 3 by 4 grid graph, a graph on 24 nodes:
131
+
132
+ >>> from networkx import grid_graph
133
+ >>> G = grid_graph(dim=(2, 3, 4))
134
+ >>> len(G)
135
+ 24
136
+ >>> G = grid_graph(dim=(range(7, 9), range(3, 6)))
137
+ >>> len(G)
138
+ 6
139
+ """
140
+ from collections.abc import Iterable
141
+
142
+ from networkx.algorithms.operators.product import cartesian_product
143
+
144
+ if not dim:
145
+ return empty_graph(0)
146
+
147
+ periodic = repeat(periodic) if not isinstance(periodic, Iterable) else periodic
148
+ func = (cycle_graph if p else path_graph for p in periodic)
149
+
150
+ G = next(func)(dim[0])
151
+ for current_dim in dim[1:]:
152
+ Gnew = next(func)(current_dim)
153
+ G = cartesian_product(Gnew, G)
154
+ # graph G is done but has labels of the form (1, (2, (3, 1))) so relabel
155
+ H = relabel_nodes(G, flatten)
156
+ return H
157
+
158
+
159
+ @nx._dispatchable(graphs=None, returns_graph=True)
160
+ def hypercube_graph(n):
161
+ """Returns the *n*-dimensional hypercube graph.
162
+
163
+ The *n*-dimensional hypercube graph [1]_ has ``2**n`` nodes, each represented as
164
+ a binary integer in the form of a tuple of 0's and 1's. Edges exist between
165
+ nodes that differ in exactly one bit.
166
+
167
+ Parameters
168
+ ----------
169
+ n : int
170
+ Dimension of the hypercube, must be a positive integer.
171
+
172
+ Returns
173
+ -------
174
+ networkx.Graph
175
+ The n-dimensional hypercube graph as an undirected graph.
176
+
177
+ See Also
178
+ --------
179
+ grid_2d_graph, triangular_lattice_graph, hexagonal_lattice_graph :
180
+ 2D lattice graphs
181
+ grid_graph :
182
+ A more general N-dimensional grid
183
+
184
+ Examples
185
+ --------
186
+ >>> G = nx.hypercube_graph(3)
187
+ >>> list(G.neighbors((0, 0, 0)))
188
+ [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
189
+
190
+ References
191
+ ----------
192
+ .. [1] https://en.wikipedia.org/wiki/Hypercube_graph
193
+ """
194
+ dim = n * [2]
195
+ G = grid_graph(dim)
196
+ return G
197
+
198
+
199
+ @nx._dispatchable(graphs=None, returns_graph=True)
200
+ def triangular_lattice_graph(
201
+ m, n, periodic=False, with_positions=True, create_using=None
202
+ ):
203
+ r"""Returns the $m$ by $n$ triangular lattice graph.
204
+
205
+ The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in
206
+ which each square unit has a diagonal edge (each grid unit has a chord).
207
+
208
+ The returned graph has $m$ rows and $n$ columns of triangles. Rows and
209
+ columns include both triangles pointing up and down. Rows form a strip
210
+ of constant height. Columns form a series of diamond shapes, staggered
211
+ with the columns on either side. Another way to state the size is that
212
+ the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns.
213
+ The odd row nodes are shifted horizontally relative to the even rows.
214
+
215
+ Directed graph types have edges pointed up or right.
216
+
217
+ Positions of nodes are computed by default or `with_positions is True`.
218
+ The position of each node (embedded in a euclidean plane) is stored in
219
+ the graph using equilateral triangles with sidelength 1.
220
+ The height between rows of nodes is thus $\sqrt(3)/2$.
221
+ Nodes lie in the first quadrant with the node $(0, 0)$ at the origin.
222
+
223
+ .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html
224
+ .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
225
+ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
226
+
227
+ Parameters
228
+ ----------
229
+ m : int
230
+ The number of rows in the lattice.
231
+
232
+ n : int
233
+ The number of columns in the lattice.
234
+
235
+ periodic : bool (default: False)
236
+ If True, join the boundary vertices of the grid using periodic
237
+ boundary conditions. The join between boundaries is the final row
238
+ and column of triangles. This means there is one row and one column
239
+ fewer nodes for the periodic lattice. Periodic lattices require
240
+ `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd
241
+
242
+ with_positions : bool (default: True)
243
+ Store the coordinates of each node in the graph node attribute 'pos'.
244
+ The coordinates provide a lattice with equilateral triangles.
245
+ Periodic positions shift the nodes vertically in a nonlinear way so
246
+ the edges don't overlap so much.
247
+
248
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
249
+ Graph type to create. If graph instance, then cleared before populated.
250
+
251
+ Returns
252
+ -------
253
+ NetworkX graph
254
+ The *m* by *n* triangular lattice graph.
255
+
256
+ See Also
257
+ --------
258
+ grid_2d_graph, hexagonal_lattice_graph :
259
+ Other 2D lattice graphs
260
+ grid_graph, hypercube_graph :
261
+ N-dimensional lattice graphs
262
+ """
263
+ H = empty_graph(0, create_using)
264
+ if n == 0 or m == 0:
265
+ return H
266
+ if periodic:
267
+ if n < 5 or m < 3:
268
+ msg = f"m > 2 and n > 4 required for periodic. m={m}, n={n}"
269
+ raise NetworkXError(msg)
270
+
271
+ N = (n + 1) // 2 # number of nodes in row
272
+ rows = range(m + 1)
273
+ cols = range(N + 1)
274
+ # Make grid
275
+ H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N])
276
+ H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols)
277
+ # add diagonals
278
+ H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N])
279
+ H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N])
280
+
281
+ # identify boundary nodes if periodic
282
+ if periodic is True:
283
+ for i in cols:
284
+ H = nx.contracted_nodes(H, (i, 0), (i, m), store_contraction_as=None)
285
+ for j in rows[:m]:
286
+ H = nx.contracted_nodes(H, (0, j), (N, j), store_contraction_as=None)
287
+ elif n % 2:
288
+ # remove extra nodes
289
+ H.remove_nodes_from((N, j) for j in rows[1::2])
290
+
291
+ # Add position node attributes
292
+ if with_positions:
293
+ ii = (i for i in cols for j in rows)
294
+ jj = (j for i in cols for j in rows)
295
+ xx = (0.5 * (j % 2) + i for i in cols for j in rows)
296
+ h = sqrt(3) / 2
297
+ if periodic:
298
+ yy = (h * j + 0.01 * i * i for i in cols for j in rows)
299
+ else:
300
+ yy = (h * j for i in cols for j in rows)
301
+ pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H}
302
+ set_node_attributes(H, pos, "pos")
303
+ return H
304
+
305
+
306
+ @nx._dispatchable(graphs=None, returns_graph=True)
307
+ def hexagonal_lattice_graph(
308
+ m, n, periodic=False, with_positions=True, create_using=None
309
+ ):
310
+ """Returns an `m` by `n` hexagonal lattice graph.
311
+
312
+ The *hexagonal lattice graph* is a graph whose nodes and edges are
313
+ the `hexagonal tiling`_ of the plane.
314
+
315
+ The returned graph will have `m` rows and `n` columns of hexagons.
316
+ `Odd numbered columns`_ are shifted up relative to even numbered columns.
317
+
318
+ Positions of nodes are computed by default or `with_positions is True`.
319
+ Node positions creating the standard embedding in the plane
320
+ with sidelength 1 and are stored in the node attribute 'pos'.
321
+ `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing.
322
+
323
+ .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling
324
+ .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
325
+
326
+ Parameters
327
+ ----------
328
+ m : int
329
+ The number of rows of hexagons in the lattice.
330
+
331
+ n : int
332
+ The number of columns of hexagons in the lattice.
333
+
334
+ periodic : bool
335
+ Whether to make a periodic grid by joining the boundary vertices.
336
+ For this to work `n` must be even and both `n > 1` and `m > 1`.
337
+ The periodic connections create another row and column of hexagons
338
+ so these graphs have fewer nodes as boundary nodes are identified.
339
+
340
+ with_positions : bool (default: True)
341
+ Store the coordinates of each node in the graph node attribute 'pos'.
342
+ The coordinates provide a lattice with vertical columns of hexagons
343
+ offset to interleave and cover the plane.
344
+ Periodic positions shift the nodes vertically in a nonlinear way so
345
+ the edges don't overlap so much.
346
+
347
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
348
+ Graph type to create. If graph instance, then cleared before populated.
349
+ If graph is directed, edges will point up or right.
350
+
351
+ Returns
352
+ -------
353
+ NetworkX graph
354
+ The *m* by *n* hexagonal lattice graph.
355
+
356
+ See Also
357
+ --------
358
+ grid_2d_graph, triangular_lattice_graph :
359
+ Other 2D lattice graphs
360
+ grid_graph, hypercube_graph :
361
+ N-dimensional lattice graphs
362
+ """
363
+ G = empty_graph(0, create_using)
364
+ if m == 0 or n == 0:
365
+ return G
366
+ if periodic and (n % 2 == 1 or m < 2 or n < 2):
367
+ msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n"
368
+ raise NetworkXError(msg)
369
+
370
+ M = 2 * m # twice as many nodes as hexagons vertically
371
+ rows = range(M + 2)
372
+ cols = range(n + 1)
373
+ # make lattice
374
+ col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[: M + 1])
375
+ row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows if i % 2 == j % 2)
376
+ G.add_edges_from(col_edges)
377
+ G.add_edges_from(row_edges)
378
+ # Remove corner nodes with one edge
379
+ G.remove_node((0, M + 1))
380
+ G.remove_node((n, (M + 1) * (n % 2)))
381
+
382
+ # identify boundary nodes if periodic
383
+ if periodic:
384
+ for i in cols[:n]:
385
+ G = nx.contracted_nodes(G, (i, 0), (i, M), store_contraction_as=None)
386
+ for i in cols[1:]:
387
+ G = nx.contracted_nodes(G, (i, 1), (i, M + 1), store_contraction_as=None)
388
+ for j in rows[1:M]:
389
+ G = nx.contracted_nodes(G, (0, j), (n, j), store_contraction_as=None)
390
+ G.remove_node((n, M))
391
+
392
+ # calc position in embedded space
393
+ if with_positions:
394
+ ii = (i for i in cols for j in rows)
395
+ jj = (j for i in cols for j in rows)
396
+ xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - 0.5) for i in cols for j in rows)
397
+ h = sqrt(3) / 2
398
+ if periodic:
399
+ yy = (h * j + 0.01 * i * i for i in cols for j in rows)
400
+ else:
401
+ yy = (h * j for i in cols for j in rows)
402
+ # exclude nodes not in G
403
+ pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G}
404
+ set_node_attributes(G, pos, "pos")
405
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/line.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating line graphs."""
2
+
3
+ from collections import defaultdict
4
+ from functools import partial
5
+ from itertools import combinations
6
+
7
+ import networkx as nx
8
+ from networkx.utils import arbitrary_element
9
+ from networkx.utils.decorators import not_implemented_for
10
+
11
+ __all__ = ["line_graph", "inverse_line_graph"]
12
+
13
+
14
+ @nx._dispatchable(returns_graph=True)
15
+ def line_graph(G, create_using=None):
16
+ r"""Returns the line graph of the graph or digraph `G`.
17
+
18
+ The line graph of a graph `G` has a node for each edge in `G` and an
19
+ edge joining those nodes if the two edges in `G` share a common node. For
20
+ directed graphs, nodes are adjacent exactly when the edges they represent
21
+ form a directed path of length two.
22
+
23
+ The nodes of the line graph are 2-tuples of nodes in the original graph (or
24
+ 3-tuples for multigraphs, with the key of the edge as the third element).
25
+
26
+ For information about self-loops and more discussion, see the **Notes**
27
+ section below.
28
+
29
+ Parameters
30
+ ----------
31
+ G : graph
32
+ A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
33
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
34
+ Graph type to create. If graph instance, then cleared before populated.
35
+
36
+ Returns
37
+ -------
38
+ L : graph
39
+ The line graph of G.
40
+
41
+ Examples
42
+ --------
43
+ >>> G = nx.star_graph(3)
44
+ >>> L = nx.line_graph(G)
45
+ >>> print(sorted(map(sorted, L.edges()))) # makes a 3-clique, K3
46
+ [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
47
+
48
+ Edge attributes from `G` are not copied over as node attributes in `L`, but
49
+ attributes can be copied manually:
50
+
51
+ >>> G = nx.path_graph(4)
52
+ >>> G.add_edges_from((u, v, {"tot": u + v}) for u, v in G.edges)
53
+ >>> G.edges(data=True)
54
+ EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
55
+ >>> H = nx.line_graph(G)
56
+ >>> H.add_nodes_from((node, G.edges[node]) for node in H)
57
+ >>> H.nodes(data=True)
58
+ NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
59
+
60
+ Notes
61
+ -----
62
+ Graph, node, and edge data are not propagated to the new graph. For
63
+ undirected graphs, the nodes in G must be sortable, otherwise the
64
+ constructed line graph may not be correct.
65
+
66
+ *Self-loops in undirected graphs*
67
+
68
+ For an undirected graph `G` without multiple edges, each edge can be
69
+ written as a set `\{u, v\}`. Its line graph `L` has the edges of `G` as
70
+ its nodes. If `x` and `y` are two nodes in `L`, then `\{x, y\}` is an edge
71
+ in `L` if and only if the intersection of `x` and `y` is nonempty. Thus,
72
+ the set of all edges is determined by the set of all pairwise intersections
73
+ of edges in `G`.
74
+
75
+ Trivially, every edge in G would have a nonzero intersection with itself,
76
+ and so every node in `L` should have a self-loop. This is not so
77
+ interesting, and the original context of line graphs was with simple
78
+ graphs, which had no self-loops or multiple edges. The line graph was also
79
+ meant to be a simple graph and thus, self-loops in `L` are not part of the
80
+ standard definition of a line graph. In a pairwise intersection matrix,
81
+ this is analogous to excluding the diagonal entries from the line graph
82
+ definition.
83
+
84
+ Self-loops and multiple edges in `G` add nodes to `L` in a natural way, and
85
+ do not require any fundamental changes to the definition. It might be
86
+ argued that the self-loops we excluded before should now be included.
87
+ However, the self-loops are still "trivial" in some sense and thus, are
88
+ usually excluded.
89
+
90
+ *Self-loops in directed graphs*
91
+
92
+ For a directed graph `G` without multiple edges, each edge can be written
93
+ as a tuple `(u, v)`. Its line graph `L` has the edges of `G` as its
94
+ nodes. If `x` and `y` are two nodes in `L`, then `(x, y)` is an edge in `L`
95
+ if and only if the tail of `x` matches the head of `y`, for example, if `x
96
+ = (a, b)` and `y = (b, c)` for some vertices `a`, `b`, and `c` in `G`.
97
+
98
+ Due to the directed nature of the edges, it is no longer the case that
99
+ every edge in `G` should have a self-loop in `L`. Now, the only time
100
+ self-loops arise is if a node in `G` itself has a self-loop. So such
101
+ self-loops are no longer "trivial" but instead, represent essential
102
+ features of the topology of `G`. For this reason, the historical
103
+ development of line digraphs is such that self-loops are included. When the
104
+ graph `G` has multiple edges, once again only superficial changes are
105
+ required to the definition.
106
+
107
+ References
108
+ ----------
109
+ * Harary, Frank, and Norman, Robert Z., "Some properties of line digraphs",
110
+ Rend. Circ. Mat. Palermo, II. Ser. 9 (1960), 161--168.
111
+ * Hemminger, R. L.; Beineke, L. W. (1978), "Line graphs and line digraphs",
112
+ in Beineke, L. W.; Wilson, R. J., Selected Topics in Graph Theory,
113
+ Academic Press Inc., pp. 271--305.
114
+
115
+ """
116
+ if G.is_directed():
117
+ L = _lg_directed(G, create_using=create_using)
118
+ else:
119
+ L = _lg_undirected(G, selfloops=False, create_using=create_using)
120
+ return L
121
+
122
+
123
+ def _lg_directed(G, create_using=None):
124
+ """Returns the line graph L of the (multi)digraph G.
125
+
126
+ Edges in G appear as nodes in L, represented as tuples of the form (u,v)
127
+ or (u,v,key) if G is a multidigraph. A node in L corresponding to the edge
128
+ (u,v) is connected to every node corresponding to an edge (v,w).
129
+
130
+ Parameters
131
+ ----------
132
+ G : digraph
133
+ A directed graph or directed multigraph.
134
+ create_using : NetworkX graph constructor, optional
135
+ Graph type to create. If graph instance, then cleared before populated.
136
+ Default is to use the same graph class as `G`.
137
+
138
+ """
139
+ L = nx.empty_graph(0, create_using, default=G.__class__)
140
+
141
+ # Create a graph specific edge function.
142
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
143
+
144
+ for from_node in get_edges():
145
+ # from_node is: (u,v) or (u,v,key)
146
+ L.add_node(from_node)
147
+ for to_node in get_edges(from_node[1]):
148
+ L.add_edge(from_node, to_node)
149
+
150
+ return L
151
+
152
+
153
+ def _lg_undirected(G, selfloops=False, create_using=None):
154
+ """Returns the line graph L of the (multi)graph G.
155
+
156
+ Edges in G appear as nodes in L, represented as sorted tuples of the form
157
+ (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
158
+ the edge {u,v} is connected to every node corresponding to an edge that
159
+ involves u or v.
160
+
161
+ Parameters
162
+ ----------
163
+ G : graph
164
+ An undirected graph or multigraph.
165
+ selfloops : bool
166
+ If `True`, then self-loops are included in the line graph. If `False`,
167
+ they are excluded.
168
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
169
+ Graph type to create. If graph instance, then cleared before populated.
170
+
171
+ Notes
172
+ -----
173
+ The standard algorithm for line graphs of undirected graphs does not
174
+ produce self-loops.
175
+
176
+ """
177
+ L = nx.empty_graph(0, create_using, default=G.__class__)
178
+
179
+ # Graph specific functions for edges.
180
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
181
+
182
+ # Determine if we include self-loops or not.
183
+ shift = 0 if selfloops else 1
184
+
185
+ # Introduce numbering of nodes
186
+ node_index = {n: i for i, n in enumerate(G)}
187
+
188
+ # Lift canonical representation of nodes to edges in line graph
189
+ def edge_key_function(edge):
190
+ return node_index[edge[0]], node_index[edge[1]]
191
+
192
+ edges = set()
193
+ for u in G:
194
+ # Label nodes as a sorted tuple of nodes in original graph.
195
+ # Decide on representation of {u, v} as (u, v) or (v, u) depending on node_index.
196
+ # -> This ensures a canonical representation and avoids comparing values of different types.
197
+ nodes = [tuple(sorted(x[:2], key=node_index.get)) + x[2:] for x in get_edges(u)]
198
+
199
+ if len(nodes) == 1:
200
+ # Then the edge will be an isolated node in L.
201
+ L.add_node(nodes[0])
202
+
203
+ # Add a clique of `nodes` to graph. To prevent double adding edges,
204
+ # especially important for multigraphs, we store the edges in
205
+ # canonical form in a set.
206
+ for i, a in enumerate(nodes):
207
+ edges.update(
208
+ [
209
+ tuple(sorted((a, b), key=edge_key_function))
210
+ for b in nodes[i + shift :]
211
+ ]
212
+ )
213
+
214
+ L.add_edges_from(edges)
215
+ return L
216
+
217
+
218
+ @not_implemented_for("directed")
219
+ @not_implemented_for("multigraph")
220
+ @nx._dispatchable(returns_graph=True)
221
+ def inverse_line_graph(G):
222
+ """Returns the inverse line graph of graph G.
223
+
224
+ If H is a graph, and G is the line graph of H, such that G = L(H).
225
+ Then H is the inverse line graph of G.
226
+
227
+ Not all graphs are line graphs and these do not have an inverse line graph.
228
+ In these cases this function raises a NetworkXError.
229
+
230
+ Parameters
231
+ ----------
232
+ G : graph
233
+ A NetworkX Graph
234
+
235
+ Returns
236
+ -------
237
+ H : graph
238
+ The inverse line graph of G.
239
+
240
+ Raises
241
+ ------
242
+ NetworkXNotImplemented
243
+ If G is directed or a multigraph
244
+
245
+ NetworkXError
246
+ If G is not a line graph
247
+
248
+ Notes
249
+ -----
250
+ This is an implementation of the Roussopoulos algorithm[1]_.
251
+
252
+ If G consists of multiple components, then the algorithm doesn't work.
253
+ You should invert every component separately:
254
+
255
+ >>> K5 = nx.complete_graph(5)
256
+ >>> P4 = nx.Graph([("a", "b"), ("b", "c"), ("c", "d")])
257
+ >>> G = nx.union(K5, P4)
258
+ >>> root_graphs = []
259
+ >>> for comp in nx.connected_components(G):
260
+ ... root_graphs.append(nx.inverse_line_graph(G.subgraph(comp)))
261
+ >>> len(root_graphs)
262
+ 2
263
+
264
+ References
265
+ ----------
266
+ .. [1] Roussopoulos, N.D. , "A max {m, n} algorithm for determining the graph H from
267
+ its line graph G", Information Processing Letters 2, (1973), 108--112, ISSN 0020-0190,
268
+ `DOI link <https://doi.org/10.1016/0020-0190(73)90029-X>`_
269
+
270
+ """
271
+ if G.number_of_nodes() == 0:
272
+ return nx.empty_graph(1)
273
+ elif G.number_of_nodes() == 1:
274
+ v = arbitrary_element(G)
275
+ a = (v, 0)
276
+ b = (v, 1)
277
+ H = nx.Graph([(a, b)])
278
+ return H
279
+ elif G.number_of_nodes() > 1 and G.number_of_edges() == 0:
280
+ msg = (
281
+ "inverse_line_graph() doesn't work on an edgeless graph. "
282
+ "Please use this function on each component separately."
283
+ )
284
+ raise nx.NetworkXError(msg)
285
+
286
+ if nx.number_of_selfloops(G) != 0:
287
+ msg = (
288
+ "A line graph as generated by NetworkX has no selfloops, so G has no "
289
+ "inverse line graph. Please remove the selfloops from G and try again."
290
+ )
291
+ raise nx.NetworkXError(msg)
292
+
293
+ starting_cell = _select_starting_cell(G)
294
+ P = _find_partition(G, starting_cell)
295
+ # count how many times each vertex appears in the partition set
296
+ P_count = {u: 0 for u in G.nodes}
297
+ for p in P:
298
+ for u in p:
299
+ P_count[u] += 1
300
+
301
+ if max(P_count.values()) > 2:
302
+ msg = "G is not a line graph (vertex found in more than two partition cells)"
303
+ raise nx.NetworkXError(msg)
304
+ W = tuple((u,) for u in P_count if P_count[u] == 1)
305
+ H = nx.Graph()
306
+ H.add_nodes_from(P)
307
+ H.add_nodes_from(W)
308
+ for a, b in combinations(H.nodes, 2):
309
+ if any(a_bit in b for a_bit in a):
310
+ H.add_edge(a, b)
311
+ return H
312
+
313
+
314
+ def _triangles(G, e):
315
+ """Return list of all triangles containing edge e"""
316
+ u, v = e
317
+ if u not in G:
318
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
319
+ if v not in G[u]:
320
+ raise nx.NetworkXError(f"Edge ({u}, {v}) not in graph")
321
+ triangle_list = []
322
+ for x in G[u]:
323
+ if x in G[v]:
324
+ triangle_list.append((u, v, x))
325
+ return triangle_list
326
+
327
+
328
+ def _odd_triangle(G, T):
329
+ """Test whether T is an odd triangle in G
330
+
331
+ Parameters
332
+ ----------
333
+ G : NetworkX Graph
334
+ T : 3-tuple of vertices forming triangle in G
335
+
336
+ Returns
337
+ -------
338
+ True is T is an odd triangle
339
+ False otherwise
340
+
341
+ Raises
342
+ ------
343
+ NetworkXError
344
+ T is not a triangle in G
345
+
346
+ Notes
347
+ -----
348
+ An odd triangle is one in which there exists another vertex in G which is
349
+ adjacent to either exactly one or exactly all three of the vertices in the
350
+ triangle.
351
+
352
+ """
353
+ for u in T:
354
+ if u not in G.nodes():
355
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
356
+ for e in list(combinations(T, 2)):
357
+ if e[0] not in G[e[1]]:
358
+ raise nx.NetworkXError(f"Edge ({e[0]}, {e[1]}) not in graph")
359
+
360
+ T_nbrs = defaultdict(int)
361
+ for t in T:
362
+ for v in G[t]:
363
+ if v not in T:
364
+ T_nbrs[v] += 1
365
+ return any(T_nbrs[v] in [1, 3] for v in T_nbrs)
366
+
367
+
368
+ def _find_partition(G, starting_cell):
369
+ """Find a partition of the vertices of G into cells of complete graphs
370
+
371
+ Parameters
372
+ ----------
373
+ G : NetworkX Graph
374
+ starting_cell : tuple of vertices in G which form a cell
375
+
376
+ Returns
377
+ -------
378
+ List of tuples of vertices of G
379
+
380
+ Raises
381
+ ------
382
+ NetworkXError
383
+ If a cell is not a complete subgraph then G is not a line graph
384
+ """
385
+ G_partition = G.copy()
386
+ P = [starting_cell] # partition set
387
+ G_partition.remove_edges_from(list(combinations(starting_cell, 2)))
388
+ # keep list of partitioned nodes which might have an edge in G_partition
389
+ partitioned_vertices = list(starting_cell)
390
+ while G_partition.number_of_edges() > 0:
391
+ # there are still edges left and so more cells to be made
392
+ u = partitioned_vertices.pop()
393
+ deg_u = len(G_partition[u])
394
+ if deg_u != 0:
395
+ # if u still has edges then we need to find its other cell
396
+ # this other cell must be a complete subgraph or else G is
397
+ # not a line graph
398
+ new_cell = [u] + list(G_partition[u])
399
+ for u in new_cell:
400
+ for v in new_cell:
401
+ if (u != v) and (v not in G_partition[u]):
402
+ msg = (
403
+ "G is not a line graph "
404
+ "(partition cell not a complete subgraph)"
405
+ )
406
+ raise nx.NetworkXError(msg)
407
+ P.append(tuple(new_cell))
408
+ G_partition.remove_edges_from(list(combinations(new_cell, 2)))
409
+ partitioned_vertices += new_cell
410
+ return P
411
+
412
+
413
+ def _select_starting_cell(G, starting_edge=None):
414
+ """Select a cell to initiate _find_partition
415
+
416
+ Parameters
417
+ ----------
418
+ G : NetworkX Graph
419
+ starting_edge: an edge to build the starting cell from
420
+
421
+ Returns
422
+ -------
423
+ Tuple of vertices in G
424
+
425
+ Raises
426
+ ------
427
+ NetworkXError
428
+ If it is determined that G is not a line graph
429
+
430
+ Notes
431
+ -----
432
+ If starting edge not specified then pick an arbitrary edge - doesn't
433
+ matter which. However, this function may call itself requiring a
434
+ specific starting edge. Note that the r, s notation for counting
435
+ triangles is the same as in the Roussopoulos paper cited above.
436
+ """
437
+ if starting_edge is None:
438
+ e = arbitrary_element(G.edges())
439
+ else:
440
+ e = starting_edge
441
+ if e[0] not in G.nodes():
442
+ raise nx.NetworkXError(f"Vertex {e[0]} not in graph")
443
+ if e[1] not in G[e[0]]:
444
+ msg = f"starting_edge ({e[0]}, {e[1]}) is not in the Graph"
445
+ raise nx.NetworkXError(msg)
446
+ e_triangles = _triangles(G, e)
447
+ r = len(e_triangles)
448
+ if r == 0:
449
+ # there are no triangles containing e, so the starting cell is just e
450
+ starting_cell = e
451
+ elif r == 1:
452
+ # there is exactly one triangle, T, containing e. If other 2 edges
453
+ # of T belong only to this triangle then T is starting cell
454
+ T = e_triangles[0]
455
+ a, b, c = T
456
+ # ab was original edge so check the other 2 edges
457
+ ac_edges = len(_triangles(G, (a, c)))
458
+ bc_edges = len(_triangles(G, (b, c)))
459
+ if ac_edges == 1:
460
+ if bc_edges == 1:
461
+ starting_cell = T
462
+ else:
463
+ return _select_starting_cell(G, starting_edge=(b, c))
464
+ else:
465
+ return _select_starting_cell(G, starting_edge=(a, c))
466
+ else:
467
+ # r >= 2 so we need to count the number of odd triangles, s
468
+ s = 0
469
+ odd_triangles = []
470
+ for T in e_triangles:
471
+ if _odd_triangle(G, T):
472
+ s += 1
473
+ odd_triangles.append(T)
474
+ if r == 2 and s == 0:
475
+ # in this case either triangle works, so just use T
476
+ starting_cell = T
477
+ elif r - 1 <= s <= r:
478
+ # check if odd triangles containing e form complete subgraph
479
+ triangle_nodes = set()
480
+ for T in odd_triangles:
481
+ for x in T:
482
+ triangle_nodes.add(x)
483
+
484
+ for u in triangle_nodes:
485
+ for v in triangle_nodes:
486
+ if u != v and (v not in G[u]):
487
+ msg = (
488
+ "G is not a line graph (odd triangles "
489
+ "do not form complete subgraph)"
490
+ )
491
+ raise nx.NetworkXError(msg)
492
+ # otherwise then we can use this as the starting cell
493
+ starting_cell = tuple(triangle_nodes)
494
+
495
+ else:
496
+ msg = (
497
+ "G is not a line graph (incorrect number of "
498
+ "odd triangles around starting edge)"
499
+ )
500
+ raise nx.NetworkXError(msg)
501
+ return starting_cell
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/mycielski.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to the Mycielski Operation and the Mycielskian family
2
+ of graphs.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for
8
+
9
+ __all__ = ["mycielskian", "mycielski_graph"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ @nx._dispatchable(returns_graph=True)
15
+ def mycielskian(G, iterations=1):
16
+ r"""Returns the Mycielskian of a simple, undirected graph G
17
+
18
+ The Mycielskian of graph preserves a graph's triangle free
19
+ property while increasing the chromatic number by 1.
20
+
21
+ The Mycielski Operation on a graph, :math:`G=(V, E)`, constructs a new
22
+ graph with :math:`2|V| + 1` nodes and :math:`3|E| + |V|` edges.
23
+
24
+ The construction is as follows:
25
+
26
+ Let :math:`V = {0, ..., n-1}`. Construct another vertex set
27
+ :math:`U = {n, ..., 2n}` and a vertex, `w`.
28
+ Construct a new graph, `M`, with vertices :math:`U \bigcup V \bigcup w`.
29
+ For edges, :math:`(u, v) \in E` add edges :math:`(u, v), (u, v + n)`, and
30
+ :math:`(u + n, v)` to M. Finally, for all vertices :math:`u \in U`, add
31
+ edge :math:`(u, w)` to M.
32
+
33
+ The Mycielski Operation can be done multiple times by repeating the above
34
+ process iteratively.
35
+
36
+ More information can be found at https://en.wikipedia.org/wiki/Mycielskian
37
+
38
+ Parameters
39
+ ----------
40
+ G : graph
41
+ A simple, undirected NetworkX graph
42
+ iterations : int
43
+ The number of iterations of the Mycielski operation to
44
+ perform on G. Defaults to 1. Must be a non-negative integer.
45
+
46
+ Returns
47
+ -------
48
+ M : graph
49
+ The Mycielskian of G after the specified number of iterations.
50
+
51
+ Notes
52
+ -----
53
+ Graph, node, and edge data are not necessarily propagated to the new graph.
54
+
55
+ """
56
+
57
+ M = nx.convert_node_labels_to_integers(G)
58
+
59
+ for i in range(iterations):
60
+ n = M.number_of_nodes()
61
+ M.add_nodes_from(range(n, 2 * n))
62
+ old_edges = list(M.edges())
63
+ M.add_edges_from((u, v + n) for u, v in old_edges)
64
+ M.add_edges_from((u + n, v) for u, v in old_edges)
65
+ M.add_node(2 * n)
66
+ M.add_edges_from((u + n, 2 * n) for u in range(n))
67
+
68
+ return M
69
+
70
+
71
+ @nx._dispatchable(graphs=None, returns_graph=True)
72
+ def mycielski_graph(n):
73
+ """Generator for the n_th Mycielski Graph.
74
+
75
+ The Mycielski family of graphs is an infinite set of graphs.
76
+ :math:`M_1` is the singleton graph, :math:`M_2` is two vertices with an
77
+ edge, and, for :math:`i > 2`, :math:`M_i` is the Mycielskian of
78
+ :math:`M_{i-1}`.
79
+
80
+ More information can be found at
81
+ http://mathworld.wolfram.com/MycielskiGraph.html
82
+
83
+ Parameters
84
+ ----------
85
+ n : int
86
+ The desired Mycielski Graph.
87
+
88
+ Returns
89
+ -------
90
+ M : graph
91
+ The n_th Mycielski Graph
92
+
93
+ Notes
94
+ -----
95
+ The first graph in the Mycielski sequence is the singleton graph.
96
+ The Mycielskian of this graph is not the :math:`P_2` graph, but rather the
97
+ :math:`P_2` graph with an extra, isolated vertex. The second Mycielski
98
+ graph is the :math:`P_2` graph, so the first two are hard coded.
99
+ The remaining graphs are generated using the Mycielski operation.
100
+
101
+ """
102
+
103
+ if n < 1:
104
+ raise nx.NetworkXError("must satisfy n >= 1")
105
+
106
+ if n == 1:
107
+ return nx.empty_graph(1)
108
+
109
+ else:
110
+ return mycielskian(nx.path_graph(2), n - 2)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/nonisomorphic_trees.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of the Wright, Richmond, Odlyzko and McKay (WROM)
3
+ algorithm for the enumeration of all non-isomorphic free trees of a
4
+ given order. Rooted trees are represented by level sequences, i.e.,
5
+ lists in which the i-th element specifies the distance of vertex i to
6
+ the root.
7
+
8
+ """
9
+
10
+ __all__ = ["nonisomorphic_trees", "number_of_nonisomorphic_trees"]
11
+
12
+ from functools import lru_cache
13
+
14
+ import networkx as nx
15
+
16
+
17
+ @nx._dispatchable(graphs=None, returns_graph=True)
18
+ def nonisomorphic_trees(order):
19
+ """Generate nonisomorphic trees of specified `order`.
20
+
21
+ Parameters
22
+ ----------
23
+ order : int
24
+ order of the desired tree(s)
25
+
26
+ Yields
27
+ ------
28
+ `networkx.Graph` instances
29
+ A tree with `order` number of nodes that is not isomorphic to any other
30
+ yielded tree.
31
+
32
+ Raises
33
+ ------
34
+ ValueError
35
+ If `order` is negative.
36
+
37
+ Examples
38
+ --------
39
+ There are 11 unique (non-isomorphic) trees with 7 nodes.
40
+
41
+ >>> n = 7
42
+ >>> nit_list = list(nx.nonisomorphic_trees(n))
43
+ >>> len(nit_list) == nx.number_of_nonisomorphic_trees(n) == 11
44
+ True
45
+
46
+ All trees yielded by the generator have the specified order.
47
+
48
+ >>> all(len(G) == n for G in nx.nonisomorphic_trees(n))
49
+ True
50
+
51
+ Each tree is nonisomorphic to every other tree yielded by the generator.
52
+ >>> seen = []
53
+ >>> for G in nx.nonisomorphic_trees(n):
54
+ ... assert not any(nx.is_isomorphic(G, H) for H in seen)
55
+ ... seen.append(G)
56
+
57
+ See Also
58
+ --------
59
+ number_of_nonisomorphic_trees
60
+ """
61
+ if order < 0:
62
+ raise ValueError("order must be non-negative")
63
+ if order == 0:
64
+ # Idiom for empty generator, i.e. list(nonisomorphic_trees(0)) == []
65
+ return
66
+ yield
67
+ if order == 1:
68
+ yield nx.empty_graph(1)
69
+ return
70
+ # start at the path graph rooted at its center
71
+ layout = list(range(order // 2 + 1)) + list(range(1, (order + 1) // 2))
72
+
73
+ while layout is not None:
74
+ layout = _next_tree(layout)
75
+ if layout is not None:
76
+ yield _layout_to_graph(layout)
77
+ layout = _next_rooted_tree(layout)
78
+
79
+
80
+ @nx._dispatchable(graphs=None)
81
+ def number_of_nonisomorphic_trees(order):
82
+ """Returns the number of nonisomorphic trees of the specified `order`.
83
+
84
+ Based on an algorithm by Alois P. Heinz in
85
+ `OEIS entry A000055 <https://oeis.org/A000055>`_. Complexity is ``O(n ** 3)``.
86
+
87
+ Parameters
88
+ ----------
89
+ order : int
90
+ Order of the desired tree(s).
91
+
92
+ Returns
93
+ -------
94
+ int
95
+ Number of nonisomorphic trees with `order` number of nodes.
96
+
97
+ Raises
98
+ ------
99
+ ValueError
100
+ If `order` is negative.
101
+
102
+ Examples
103
+ --------
104
+ >>> nx.number_of_nonisomorphic_trees(10)
105
+ 106
106
+
107
+ See Also
108
+ --------
109
+ nonisomorphic_trees
110
+ """
111
+ if order < 0:
112
+ raise ValueError("order must be non-negative")
113
+ return _unlabeled_trees(order)
114
+
115
+
116
+ @lru_cache(None)
117
+ def _unlabeled_trees(n):
118
+ """Implements OEIS A000055 (number of unlabeled trees)."""
119
+
120
+ value = 0
121
+ for k in range(n + 1):
122
+ value += _rooted_trees(k) * _rooted_trees(n - k)
123
+ if n % 2 == 0:
124
+ value -= _rooted_trees(n // 2)
125
+ return _rooted_trees(n) - value // 2
126
+
127
+
128
+ @lru_cache(None)
129
+ def _rooted_trees(n):
130
+ """Implements OEIS A000081 (number of unlabeled rooted trees)."""
131
+
132
+ if n < 2:
133
+ return n
134
+ value = 0
135
+ for j in range(1, n):
136
+ for d in range(1, n):
137
+ if j % d == 0:
138
+ value += d * _rooted_trees(d) * _rooted_trees(n - j)
139
+ return value // (n - 1)
140
+
141
+
142
+ def _next_rooted_tree(predecessor, p=None):
143
+ """One iteration of the Beyer-Hedetniemi algorithm."""
144
+
145
+ if p is None:
146
+ p = len(predecessor) - 1
147
+ while predecessor[p] == 1:
148
+ p -= 1
149
+ if p == 0:
150
+ return None
151
+
152
+ q = p - 1
153
+ while predecessor[q] != predecessor[p] - 1:
154
+ q -= 1
155
+ result = list(predecessor)
156
+ for i in range(p, len(result)):
157
+ result[i] = result[i - p + q]
158
+ return result
159
+
160
+
161
+ def _next_tree(candidate):
162
+ """One iteration of the Wright, Richmond, Odlyzko and McKay
163
+ algorithm."""
164
+
165
+ # valid representation of a free tree if:
166
+ # there are at least two vertices at layer 1
167
+ # (this is always the case because we start at the path graph)
168
+ left, rest = _split_tree(candidate)
169
+
170
+ # and the left subtree of the root
171
+ # is less high than the tree with the left subtree removed
172
+ left_height = max(left)
173
+ rest_height = max(rest)
174
+ valid = rest_height >= left_height
175
+
176
+ if valid and rest_height == left_height:
177
+ # and, if left and rest are of the same height,
178
+ # if left does not encompass more vertices
179
+ if len(left) > len(rest):
180
+ valid = False
181
+ # and, if they have the same number or vertices,
182
+ # if left does not come after rest lexicographically
183
+ elif len(left) == len(rest) and left > rest:
184
+ valid = False
185
+
186
+ if valid:
187
+ return candidate
188
+ else:
189
+ # jump to the next valid free tree
190
+ p = len(left)
191
+ new_candidate = _next_rooted_tree(candidate, p)
192
+ if candidate[p] > 2:
193
+ new_left, new_rest = _split_tree(new_candidate)
194
+ new_left_height = max(new_left)
195
+ suffix = range(1, new_left_height + 2)
196
+ new_candidate[-len(suffix) :] = suffix
197
+ return new_candidate
198
+
199
+
200
+ def _split_tree(layout):
201
+ """Returns a tuple of two layouts, one containing the left
202
+ subtree of the root vertex, and one containing the original tree
203
+ with the left subtree removed."""
204
+
205
+ one_found = False
206
+ m = None
207
+ for i in range(len(layout)):
208
+ if layout[i] == 1:
209
+ if one_found:
210
+ m = i
211
+ break
212
+ else:
213
+ one_found = True
214
+
215
+ if m is None:
216
+ m = len(layout)
217
+
218
+ left = [layout[i] - 1 for i in range(1, m)]
219
+ rest = [0] + [layout[i] for i in range(m, len(layout))]
220
+ return (left, rest)
221
+
222
+
223
+ def _layout_to_matrix(layout):
224
+ """Create the adjacency matrix for the tree specified by the
225
+ given layout (level sequence)."""
226
+
227
+ result = [[0] * len(layout) for i in range(len(layout))]
228
+ stack = []
229
+ for i in range(len(layout)):
230
+ i_level = layout[i]
231
+ if stack:
232
+ j = stack[-1]
233
+ j_level = layout[j]
234
+ while j_level >= i_level:
235
+ stack.pop()
236
+ j = stack[-1]
237
+ j_level = layout[j]
238
+ result[i][j] = result[j][i] = 1
239
+ stack.append(i)
240
+ return result
241
+
242
+
243
+ def _layout_to_graph(layout):
244
+ """Create a NetworkX Graph for the tree specified by the
245
+ given layout(level sequence)"""
246
+ G = nx.Graph()
247
+ stack = []
248
+ for i in range(len(layout)):
249
+ i_level = layout[i]
250
+ if stack:
251
+ j = stack[-1]
252
+ j_level = layout[j]
253
+ while j_level >= i_level:
254
+ stack.pop()
255
+ j = stack[-1]
256
+ j_level = layout[j]
257
+ G.add_edge(i, j)
258
+ stack.append(i)
259
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/random_clustered.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with given degree and triangle sequence."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = ["random_clustered_graph"]
7
+
8
+
9
+ @py_random_state(2)
10
+ @nx._dispatchable(graphs=None, returns_graph=True)
11
+ def random_clustered_graph(joint_degree_sequence, create_using=None, seed=None):
12
+ r"""Generate a random graph with the given joint independent edge degree and
13
+ triangle degree sequence.
14
+
15
+ This uses a configuration model-like approach to generate a random graph
16
+ (with parallel edges and self-loops) by randomly assigning edges to match
17
+ the given joint degree sequence.
18
+
19
+ The joint degree sequence is a list of pairs of integers of the form
20
+ $[(d_{1,i}, d_{1,t}), \dotsc, (d_{n,i}, d_{n,t})]$. According to this list,
21
+ vertex $u$ is a member of $d_{u,t}$ triangles and has $d_{u, i}$ other
22
+ edges. The number $d_{u,t}$ is the *triangle degree* of $u$ and the number
23
+ $d_{u,i}$ is the *independent edge degree*.
24
+
25
+ Parameters
26
+ ----------
27
+ joint_degree_sequence : list of integer pairs
28
+ Each list entry corresponds to the independent edge degree and
29
+ triangle degree of a node.
30
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
31
+ Graph type to create. If graph instance, then cleared before populated.
32
+ seed : integer, random_state, or None (default)
33
+ Indicator of random number generation state.
34
+ See :ref:`Randomness<randomness>`.
35
+
36
+ Returns
37
+ -------
38
+ G : MultiGraph
39
+ A graph with the specified degree sequence. Nodes are labeled
40
+ starting at 0 with an index corresponding to the position in
41
+ deg_sequence.
42
+
43
+ Raises
44
+ ------
45
+ NetworkXError
46
+ If the independent edge degree sequence sum is not even
47
+ or the triangle degree sequence sum is not divisible by 3.
48
+
49
+ Notes
50
+ -----
51
+ As described by Miller [1]_ (see also Newman [2]_ for an equivalent
52
+ description).
53
+
54
+ A non-graphical degree sequence (not realizable by some simple
55
+ graph) is allowed since this function returns graphs with self
56
+ loops and parallel edges. An exception is raised if the
57
+ independent degree sequence does not have an even sum or the
58
+ triangle degree sequence sum is not divisible by 3.
59
+
60
+ This configuration model-like construction process can lead to
61
+ duplicate edges and loops. You can remove the self-loops and
62
+ parallel edges (see below) which will likely result in a graph
63
+ that doesn't have the exact degree sequence specified. This
64
+ "finite-size effect" decreases as the size of the graph increases.
65
+
66
+ References
67
+ ----------
68
+ .. [1] Joel C. Miller. "Percolation and epidemics in random clustered
69
+ networks". In: Physical review. E, Statistical, nonlinear, and soft
70
+ matter physics 80 (2 Part 1 August 2009).
71
+ .. [2] M. E. J. Newman. "Random Graphs with Clustering".
72
+ In: Physical Review Letters 103 (5 July 2009)
73
+
74
+ Examples
75
+ --------
76
+ >>> deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)]
77
+ >>> G = nx.random_clustered_graph(deg)
78
+
79
+ To remove parallel edges:
80
+
81
+ >>> G = nx.Graph(G)
82
+
83
+ To remove self loops:
84
+
85
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
86
+
87
+ """
88
+ # In Python 3, zip() returns an iterator. Make this into a list.
89
+ joint_degree_sequence = list(joint_degree_sequence)
90
+
91
+ N = len(joint_degree_sequence)
92
+ G = nx.empty_graph(N, create_using, default=nx.MultiGraph)
93
+ if G.is_directed():
94
+ raise nx.NetworkXError("Directed Graph not supported")
95
+
96
+ ilist = []
97
+ tlist = []
98
+ for n in G:
99
+ degrees = joint_degree_sequence[n]
100
+ for icount in range(degrees[0]):
101
+ ilist.append(n)
102
+ for tcount in range(degrees[1]):
103
+ tlist.append(n)
104
+
105
+ if len(ilist) % 2 != 0 or len(tlist) % 3 != 0:
106
+ raise nx.NetworkXError("Invalid degree sequence")
107
+
108
+ seed.shuffle(ilist)
109
+ seed.shuffle(tlist)
110
+ while ilist:
111
+ G.add_edge(ilist.pop(), ilist.pop())
112
+ while tlist:
113
+ n1 = tlist.pop()
114
+ n2 = tlist.pop()
115
+ n3 = tlist.pop()
116
+ G.add_edges_from([(n1, n2), (n1, n3), (n2, n3)])
117
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/random_graphs.py ADDED
@@ -0,0 +1,1416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random graphs.
3
+
4
+ """
5
+
6
+ import itertools
7
+ import math
8
+ from collections import defaultdict
9
+
10
+ import networkx as nx
11
+ from networkx.utils import py_random_state
12
+
13
+ from ..utils.misc import check_create_using
14
+ from .classic import complete_graph, empty_graph, path_graph, star_graph
15
+ from .degree_seq import degree_sequence_tree
16
+
17
+ __all__ = [
18
+ "fast_gnp_random_graph",
19
+ "gnp_random_graph",
20
+ "dense_gnm_random_graph",
21
+ "gnm_random_graph",
22
+ "erdos_renyi_graph",
23
+ "binomial_graph",
24
+ "newman_watts_strogatz_graph",
25
+ "watts_strogatz_graph",
26
+ "connected_watts_strogatz_graph",
27
+ "random_regular_graph",
28
+ "barabasi_albert_graph",
29
+ "dual_barabasi_albert_graph",
30
+ "extended_barabasi_albert_graph",
31
+ "powerlaw_cluster_graph",
32
+ "random_lobster",
33
+ "random_lobster_graph",
34
+ "random_shell_graph",
35
+ "random_powerlaw_tree",
36
+ "random_powerlaw_tree_sequence",
37
+ "random_kernel_graph",
38
+ ]
39
+
40
+
41
+ @py_random_state(2)
42
+ @nx._dispatchable(graphs=None, returns_graph=True)
43
+ def fast_gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
44
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
45
+ a binomial graph.
46
+
47
+ Parameters
48
+ ----------
49
+ n : int
50
+ The number of nodes.
51
+ p : float
52
+ Probability for edge creation.
53
+ seed : integer, random_state, or None (default)
54
+ Indicator of random number generation state.
55
+ See :ref:`Randomness<randomness>`.
56
+ directed : bool, optional (default=False)
57
+ If True, this function returns a directed graph.
58
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
59
+ Graph type to create. If graph instance, then cleared before populated.
60
+ Multigraph types are not supported and raise a ``NetworkXError``.
61
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
62
+
63
+ Notes
64
+ -----
65
+ The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
66
+ (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
67
+
68
+ This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
69
+ edges, which equals $p n (n - 1) / 2$. This should be faster than
70
+ :func:`gnp_random_graph` when $p$ is small and the expected number of edges
71
+ is small (that is, the graph is sparse).
72
+
73
+ See Also
74
+ --------
75
+ gnp_random_graph
76
+
77
+ References
78
+ ----------
79
+ .. [1] Vladimir Batagelj and Ulrik Brandes,
80
+ "Efficient generation of large random networks",
81
+ Phys. Rev. E, 71, 036113, 2005.
82
+ """
83
+ default = nx.DiGraph if directed else nx.Graph
84
+ create_using = check_create_using(
85
+ create_using, directed=directed, multigraph=False, default=default
86
+ )
87
+ if p <= 0 or p >= 1:
88
+ return nx.gnp_random_graph(
89
+ n, p, seed=seed, directed=directed, create_using=create_using
90
+ )
91
+
92
+ G = empty_graph(n, create_using=create_using)
93
+
94
+ lp = math.log(1.0 - p)
95
+
96
+ if directed:
97
+ v = 1
98
+ w = -1
99
+ while v < n:
100
+ lr = math.log(1.0 - seed.random())
101
+ w = w + 1 + int(lr / lp)
102
+ while w >= v and v < n:
103
+ w = w - v
104
+ v = v + 1
105
+ if v < n:
106
+ G.add_edge(w, v)
107
+
108
+ # Nodes in graph are from 0,n-1 (start with v as the second node index).
109
+ v = 1
110
+ w = -1
111
+ while v < n:
112
+ lr = math.log(1.0 - seed.random())
113
+ w = w + 1 + int(lr / lp)
114
+ while w >= v and v < n:
115
+ w = w - v
116
+ v = v + 1
117
+ if v < n:
118
+ G.add_edge(v, w)
119
+ return G
120
+
121
+
122
+ @py_random_state(2)
123
+ @nx._dispatchable(graphs=None, returns_graph=True)
124
+ def gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
125
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
126
+ or a binomial graph.
127
+
128
+ The $G_{n,p}$ model chooses each of the possible edges with probability $p$.
129
+
130
+ Parameters
131
+ ----------
132
+ n : int
133
+ The number of nodes.
134
+ p : float
135
+ Probability for edge creation.
136
+ seed : integer, random_state, or None (default)
137
+ Indicator of random number generation state.
138
+ See :ref:`Randomness<randomness>`.
139
+ directed : bool, optional (default=False)
140
+ If True, this function returns a directed graph.
141
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
142
+ Graph type to create. If graph instance, then cleared before populated.
143
+ Multigraph types are not supported and raise a ``NetworkXError``.
144
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
145
+
146
+ See Also
147
+ --------
148
+ fast_gnp_random_graph
149
+
150
+ Notes
151
+ -----
152
+ This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for
153
+ small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm.
154
+
155
+ :func:`binomial_graph` and :func:`erdos_renyi_graph` are
156
+ aliases for :func:`gnp_random_graph`.
157
+
158
+ >>> nx.binomial_graph is nx.gnp_random_graph
159
+ True
160
+ >>> nx.erdos_renyi_graph is nx.gnp_random_graph
161
+ True
162
+
163
+ References
164
+ ----------
165
+ .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
166
+ .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
167
+ """
168
+ default = nx.DiGraph if directed else nx.Graph
169
+ create_using = check_create_using(
170
+ create_using, directed=directed, multigraph=False, default=default
171
+ )
172
+ if p >= 1:
173
+ return complete_graph(n, create_using=create_using)
174
+
175
+ G = nx.empty_graph(n, create_using=create_using)
176
+ if p <= 0:
177
+ return G
178
+
179
+ edgetool = itertools.permutations if directed else itertools.combinations
180
+ for e in edgetool(range(n), 2):
181
+ if seed.random() < p:
182
+ G.add_edge(*e)
183
+ return G
184
+
185
+
186
+ # add some aliases to common names
187
+ binomial_graph = gnp_random_graph
188
+ erdos_renyi_graph = gnp_random_graph
189
+
190
+
191
+ @py_random_state(2)
192
+ @nx._dispatchable(graphs=None, returns_graph=True)
193
+ def dense_gnm_random_graph(n, m, seed=None, *, create_using=None):
194
+ """Returns a $G_{n,m}$ random graph.
195
+
196
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
197
+ of all graphs with $n$ nodes and $m$ edges.
198
+
199
+ This algorithm should be faster than :func:`gnm_random_graph` for dense
200
+ graphs.
201
+
202
+ Parameters
203
+ ----------
204
+ n : int
205
+ The number of nodes.
206
+ m : int
207
+ The number of edges.
208
+ seed : integer, random_state, or None (default)
209
+ Indicator of random number generation state.
210
+ See :ref:`Randomness<randomness>`.
211
+ create_using : Graph constructor, optional (default=nx.Graph)
212
+ Graph type to create. If graph instance, then cleared before populated.
213
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
214
+
215
+ See Also
216
+ --------
217
+ gnm_random_graph
218
+
219
+ Notes
220
+ -----
221
+ Algorithm by Keith M. Briggs Mar 31, 2006.
222
+ Inspired by Knuth's Algorithm S (Selection sampling technique),
223
+ in section 3.4.2 of [1]_.
224
+
225
+ References
226
+ ----------
227
+ .. [1] Donald E. Knuth, The Art of Computer Programming,
228
+ Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
229
+ """
230
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
231
+ mmax = n * (n - 1) // 2
232
+ if m >= mmax:
233
+ return complete_graph(n, create_using)
234
+ G = empty_graph(n, create_using)
235
+
236
+ if n == 1:
237
+ return G
238
+
239
+ u = 0
240
+ v = 1
241
+ t = 0
242
+ k = 0
243
+ while True:
244
+ if seed.randrange(mmax - t) < m - k:
245
+ G.add_edge(u, v)
246
+ k += 1
247
+ if k == m:
248
+ return G
249
+ t += 1
250
+ v += 1
251
+ if v == n: # go to next row of adjacency matrix
252
+ u += 1
253
+ v = u + 1
254
+
255
+
256
+ @py_random_state(2)
257
+ @nx._dispatchable(graphs=None, returns_graph=True)
258
+ def gnm_random_graph(n, m, seed=None, directed=False, *, create_using=None):
259
+ """Returns a $G_{n,m}$ random graph.
260
+
261
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
262
+ of all graphs with $n$ nodes and $m$ edges.
263
+
264
+ This algorithm should be faster than :func:`dense_gnm_random_graph` for
265
+ sparse graphs.
266
+
267
+ Parameters
268
+ ----------
269
+ n : int
270
+ The number of nodes.
271
+ m : int
272
+ The number of edges.
273
+ seed : integer, random_state, or None (default)
274
+ Indicator of random number generation state.
275
+ See :ref:`Randomness<randomness>`.
276
+ directed : bool, optional (default=False)
277
+ If True return a directed graph
278
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
279
+ Graph type to create. If graph instance, then cleared before populated.
280
+ Multigraph types are not supported and raise a ``NetworkXError``.
281
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
282
+
283
+ See also
284
+ --------
285
+ dense_gnm_random_graph
286
+
287
+ """
288
+ default = nx.DiGraph if directed else nx.Graph
289
+ create_using = check_create_using(
290
+ create_using, directed=directed, multigraph=False, default=default
291
+ )
292
+ if n == 1:
293
+ return nx.empty_graph(n, create_using=create_using)
294
+ max_edges = n * (n - 1) if directed else n * (n - 1) / 2.0
295
+ if m >= max_edges:
296
+ return complete_graph(n, create_using=create_using)
297
+
298
+ G = nx.empty_graph(n, create_using=create_using)
299
+ nlist = list(G)
300
+ edge_count = 0
301
+ while edge_count < m:
302
+ # generate random edge,u,v
303
+ u = seed.choice(nlist)
304
+ v = seed.choice(nlist)
305
+ if u == v or G.has_edge(u, v):
306
+ continue
307
+ else:
308
+ G.add_edge(u, v)
309
+ edge_count = edge_count + 1
310
+ return G
311
+
312
+
313
+ @py_random_state(3)
314
+ @nx._dispatchable(graphs=None, returns_graph=True)
315
+ def newman_watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
316
+ """Returns a Newman–Watts–Strogatz small-world graph.
317
+
318
+ Parameters
319
+ ----------
320
+ n : int
321
+ The number of nodes.
322
+ k : int
323
+ Each node is joined with its `k` nearest neighbors in a ring
324
+ topology.
325
+ p : float
326
+ The probability of adding a new edge for each edge.
327
+ seed : integer, random_state, or None (default)
328
+ Indicator of random number generation state.
329
+ See :ref:`Randomness<randomness>`.
330
+ create_using : Graph constructor, optional (default=nx.Graph)
331
+ Graph type to create. If graph instance, then cleared before populated.
332
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
333
+
334
+ Notes
335
+ -----
336
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is
337
+ connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
338
+ is odd). Then shortcuts are created by adding new edges as follows: for
339
+ each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
340
+ neighbors" with probability $p$ add a new edge $(u, w)$ with
341
+ randomly-chosen existing node $w$. In contrast with
342
+ :func:`watts_strogatz_graph`, no edges are removed.
343
+
344
+ See Also
345
+ --------
346
+ watts_strogatz_graph
347
+
348
+ References
349
+ ----------
350
+ .. [1] M. E. J. Newman and D. J. Watts,
351
+ Renormalization group analysis of the small-world network model,
352
+ Physics Letters A, 263, 341, 1999.
353
+ https://doi.org/10.1016/S0375-9601(99)00757-4
354
+ """
355
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
356
+ if k > n:
357
+ raise nx.NetworkXError("k>=n, choose smaller k or larger n")
358
+
359
+ # If k == n the graph return is a complete graph
360
+ if k == n:
361
+ return nx.complete_graph(n, create_using)
362
+
363
+ G = empty_graph(n, create_using)
364
+ nlist = list(G.nodes())
365
+ fromv = nlist
366
+ # connect the k/2 neighbors
367
+ for j in range(1, k // 2 + 1):
368
+ tov = fromv[j:] + fromv[0:j] # the first j are now last
369
+ for i in range(len(fromv)):
370
+ G.add_edge(fromv[i], tov[i])
371
+ # for each edge u-v, with probability p, randomly select existing
372
+ # node w and add new edge u-w
373
+ e = list(G.edges())
374
+ for u, v in e:
375
+ if seed.random() < p:
376
+ w = seed.choice(nlist)
377
+ # no self-loops and reject if edge u-w exists
378
+ # is that the correct NWS model?
379
+ while w == u or G.has_edge(u, w):
380
+ w = seed.choice(nlist)
381
+ if G.degree(u) >= n - 1:
382
+ break # skip this rewiring
383
+ else:
384
+ G.add_edge(u, w)
385
+ return G
386
+
387
+
388
+ @py_random_state(3)
389
+ @nx._dispatchable(graphs=None, returns_graph=True)
390
+ def watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
391
+ """Returns a Watts–Strogatz small-world graph.
392
+
393
+ Parameters
394
+ ----------
395
+ n : int
396
+ The number of nodes
397
+ k : int
398
+ Each node is joined with its `k` nearest neighbors in a ring
399
+ topology.
400
+ p : float
401
+ The probability of rewiring each edge
402
+ seed : integer, random_state, or None (default)
403
+ Indicator of random number generation state.
404
+ See :ref:`Randomness<randomness>`.
405
+ create_using : Graph constructor, optional (default=nx.Graph)
406
+ Graph type to create. If graph instance, then cleared before populated.
407
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
408
+
409
+ See Also
410
+ --------
411
+ newman_watts_strogatz_graph
412
+ connected_watts_strogatz_graph
413
+
414
+ Notes
415
+ -----
416
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
417
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
418
+ Then shortcuts are created by replacing some edges as follows: for each
419
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
420
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
421
+ random choice of existing node $w$.
422
+
423
+ In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring
424
+ does not increase the number of edges. The rewired graph is not guaranteed
425
+ to be connected as in :func:`connected_watts_strogatz_graph`.
426
+
427
+ References
428
+ ----------
429
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
430
+ Collective dynamics of small-world networks,
431
+ Nature, 393, pp. 440--442, 1998.
432
+ """
433
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
434
+ if k > n:
435
+ raise nx.NetworkXError("k>n, choose smaller k or larger n")
436
+
437
+ # If k == n, the graph is complete not Watts-Strogatz
438
+ if k == n:
439
+ G = nx.complete_graph(n, create_using)
440
+ return G
441
+
442
+ G = nx.empty_graph(n, create_using=create_using)
443
+ nodes = list(range(n)) # nodes are labeled 0 to n-1
444
+ # connect each node to k/2 neighbors
445
+ for j in range(1, k // 2 + 1):
446
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
447
+ G.add_edges_from(zip(nodes, targets))
448
+ # rewire edges from each node
449
+ # loop over all nodes in order (label) and neighbors in order (distance)
450
+ # no self loops or multiple edges allowed
451
+ for j in range(1, k // 2 + 1): # outer loop is neighbors
452
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
453
+ # inner loop in node order
454
+ for u, v in zip(nodes, targets):
455
+ if seed.random() < p:
456
+ w = seed.choice(nodes)
457
+ # Enforce no self-loops or multiple edges
458
+ while w == u or G.has_edge(u, w):
459
+ w = seed.choice(nodes)
460
+ if G.degree(u) >= n - 1:
461
+ break # skip this rewiring
462
+ else:
463
+ G.remove_edge(u, v)
464
+ G.add_edge(u, w)
465
+ return G
466
+
467
+
468
+ @py_random_state(4)
469
+ @nx._dispatchable(graphs=None, returns_graph=True)
470
+ def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None, *, create_using=None):
471
+ """Returns a connected Watts–Strogatz small-world graph.
472
+
473
+ Attempts to generate a connected graph by repeated generation of
474
+ Watts–Strogatz small-world graphs. An exception is raised if the maximum
475
+ number of tries is exceeded.
476
+
477
+ Parameters
478
+ ----------
479
+ n : int
480
+ The number of nodes
481
+ k : int
482
+ Each node is joined with its `k` nearest neighbors in a ring
483
+ topology.
484
+ p : float
485
+ The probability of rewiring each edge
486
+ tries : int
487
+ Number of attempts to generate a connected graph.
488
+ seed : integer, random_state, or None (default)
489
+ Indicator of random number generation state.
490
+ See :ref:`Randomness<randomness>`.
491
+ create_using : Graph constructor, optional (default=nx.Graph)
492
+ Graph type to create. If graph instance, then cleared before populated.
493
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
494
+
495
+ Notes
496
+ -----
497
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
498
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
499
+ Then shortcuts are created by replacing some edges as follows: for each
500
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
501
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
502
+ random choice of existing node $w$.
503
+ The entire process is repeated until a connected graph results.
504
+
505
+ See Also
506
+ --------
507
+ newman_watts_strogatz_graph
508
+ watts_strogatz_graph
509
+
510
+ References
511
+ ----------
512
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
513
+ Collective dynamics of small-world networks,
514
+ Nature, 393, pp. 440--442, 1998.
515
+ """
516
+ for i in range(tries):
517
+ # seed is an RNG so should change sequence each call
518
+ G = watts_strogatz_graph(n, k, p, seed, create_using=create_using)
519
+ if nx.is_connected(G):
520
+ return G
521
+ raise nx.NetworkXError("Maximum number of tries exceeded")
522
+
523
+
524
+ @py_random_state(2)
525
+ @nx._dispatchable(graphs=None, returns_graph=True)
526
+ def random_regular_graph(d, n, seed=None, *, create_using=None):
527
+ r"""Returns a random $d$-regular graph on $n$ nodes.
528
+
529
+ A regular graph is a graph where each node has the same number of neighbors.
530
+
531
+ The resulting graph has no self-loops or parallel edges.
532
+
533
+ Parameters
534
+ ----------
535
+ d : int
536
+ The degree of each node.
537
+ n : integer
538
+ The number of nodes. The value of $n \times d$ must be even.
539
+ seed : integer, random_state, or None (default)
540
+ Indicator of random number generation state.
541
+ See :ref:`Randomness<randomness>`.
542
+ create_using : Graph constructor, optional (default=nx.Graph)
543
+ Graph type to create. If graph instance, then cleared before populated.
544
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
545
+
546
+ Notes
547
+ -----
548
+ The nodes are numbered from $0$ to $n - 1$.
549
+
550
+ Kim and Vu's paper [2]_ shows that this algorithm samples in an
551
+ asymptotically uniform way from the space of random graphs when
552
+ $d = O(n^{1 / 3 - \epsilon})$.
553
+
554
+ Raises
555
+ ------
556
+
557
+ NetworkXError
558
+ If $n \times d$ is odd or $d$ is greater than or equal to $n$.
559
+
560
+ References
561
+ ----------
562
+ .. [1] A. Steger and N. Wormald,
563
+ Generating random regular graphs quickly,
564
+ Probability and Computing 8 (1999), 377-396, 1999.
565
+ https://doi.org/10.1017/S0963548399003867
566
+
567
+ .. [2] Jeong Han Kim and Van H. Vu,
568
+ Generating random regular graphs,
569
+ Proceedings of the thirty-fifth ACM symposium on Theory of computing,
570
+ San Diego, CA, USA, pp 213--222, 2003.
571
+ http://portal.acm.org/citation.cfm?id=780542.780576
572
+ """
573
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
574
+ if (n * d) % 2 != 0:
575
+ raise nx.NetworkXError("n * d must be even")
576
+
577
+ if not 0 <= d < n:
578
+ raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
579
+
580
+ G = nx.empty_graph(n, create_using=create_using)
581
+
582
+ if d == 0:
583
+ return G
584
+
585
+ def _suitable(edges, potential_edges):
586
+ # Helper subroutine to check if there are suitable edges remaining
587
+ # If False, the generation of the graph has failed
588
+ if not potential_edges:
589
+ return True
590
+ for s1 in potential_edges:
591
+ for s2 in potential_edges:
592
+ # Two iterators on the same dictionary are guaranteed
593
+ # to visit it in the same order if there are no
594
+ # intervening modifications.
595
+ if s1 == s2:
596
+ # Only need to consider s1-s2 pair one time
597
+ break
598
+ if s1 > s2:
599
+ s1, s2 = s2, s1
600
+ if (s1, s2) not in edges:
601
+ return True
602
+ return False
603
+
604
+ def _try_creation():
605
+ # Attempt to create an edge set
606
+
607
+ edges = set()
608
+ stubs = list(range(n)) * d
609
+
610
+ while stubs:
611
+ potential_edges = defaultdict(lambda: 0)
612
+ seed.shuffle(stubs)
613
+ stubiter = iter(stubs)
614
+ for s1, s2 in zip(stubiter, stubiter):
615
+ if s1 > s2:
616
+ s1, s2 = s2, s1
617
+ if s1 != s2 and ((s1, s2) not in edges):
618
+ edges.add((s1, s2))
619
+ else:
620
+ potential_edges[s1] += 1
621
+ potential_edges[s2] += 1
622
+
623
+ if not _suitable(edges, potential_edges):
624
+ return None # failed to find suitable edge set
625
+
626
+ stubs = [
627
+ node
628
+ for node, potential in potential_edges.items()
629
+ for _ in range(potential)
630
+ ]
631
+ return edges
632
+
633
+ # Even though a suitable edge set exists,
634
+ # the generation of such a set is not guaranteed.
635
+ # Try repeatedly to find one.
636
+ edges = _try_creation()
637
+ while edges is None:
638
+ edges = _try_creation()
639
+ G.add_edges_from(edges)
640
+
641
+ return G
642
+
643
+
644
+ def _random_subset(seq, m, rng):
645
+ """Return m unique elements from seq.
646
+
647
+ This differs from random.sample which can return repeated
648
+ elements if seq holds repeated elements.
649
+
650
+ Note: rng is a random.Random or numpy.random.RandomState instance.
651
+ """
652
+ targets = set()
653
+ while len(targets) < m:
654
+ x = rng.choice(seq)
655
+ targets.add(x)
656
+ return targets
657
+
658
+
659
+ @py_random_state(2)
660
+ @nx._dispatchable(graphs=None, returns_graph=True)
661
+ def barabasi_albert_graph(n, m, seed=None, initial_graph=None, *, create_using=None):
662
+ """Returns a random graph using Barabási–Albert preferential attachment
663
+
664
+ A graph of $n$ nodes is grown by attaching new nodes each with $m$
665
+ edges that are preferentially attached to existing nodes with high degree.
666
+
667
+ Parameters
668
+ ----------
669
+ n : int
670
+ Number of nodes
671
+ m : int
672
+ Number of edges to attach from a new node to existing nodes
673
+ seed : integer, random_state, or None (default)
674
+ Indicator of random number generation state.
675
+ See :ref:`Randomness<randomness>`.
676
+ initial_graph : Graph or None (default)
677
+ Initial network for Barabási–Albert algorithm.
678
+ It should be a connected graph for most use cases.
679
+ A copy of `initial_graph` is used.
680
+ If None, starts from a star graph on (m+1) nodes.
681
+ create_using : Graph constructor, optional (default=nx.Graph)
682
+ Graph type to create. If graph instance, then cleared before populated.
683
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
684
+
685
+ Returns
686
+ -------
687
+ G : Graph
688
+
689
+ Raises
690
+ ------
691
+ NetworkXError
692
+ If `m` does not satisfy ``1 <= m < n``, or
693
+ the initial graph number of nodes m0 does not satisfy ``m <= m0 <= n``.
694
+
695
+ References
696
+ ----------
697
+ .. [1] A. L. Barabási and R. Albert "Emergence of scaling in
698
+ random networks", Science 286, pp 509-512, 1999.
699
+ """
700
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
701
+ if m < 1 or m >= n:
702
+ raise nx.NetworkXError(
703
+ f"Barabási–Albert network must have m >= 1 and m < n, m = {m}, n = {n}"
704
+ )
705
+
706
+ if initial_graph is None:
707
+ # Default initial graph : star graph on (m + 1) nodes
708
+ G = star_graph(m, create_using)
709
+ else:
710
+ if len(initial_graph) < m or len(initial_graph) > n:
711
+ raise nx.NetworkXError(
712
+ f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
713
+ )
714
+ G = initial_graph.copy()
715
+
716
+ # List of existing nodes, with nodes repeated once for each adjacent edge
717
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
718
+ # Start adding the other n - m0 nodes.
719
+ source = len(G)
720
+ while source < n:
721
+ # Now choose m unique nodes from the existing nodes
722
+ # Pick uniformly from repeated_nodes (preferential attachment)
723
+ targets = _random_subset(repeated_nodes, m, seed)
724
+ # Add edges to m nodes from the source.
725
+ G.add_edges_from(zip([source] * m, targets))
726
+ # Add one node to the list for each new edge just created.
727
+ repeated_nodes.extend(targets)
728
+ # And the new node "source" has m edges to add to the list.
729
+ repeated_nodes.extend([source] * m)
730
+
731
+ source += 1
732
+ return G
733
+
734
+
735
+ @py_random_state(4)
736
+ @nx._dispatchable(graphs=None, returns_graph=True)
737
+ def dual_barabasi_albert_graph(
738
+ n, m1, m2, p, seed=None, initial_graph=None, *, create_using=None
739
+ ):
740
+ """Returns a random graph using dual Barabási–Albert preferential attachment
741
+
742
+ A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
743
+ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
744
+ are preferentially attached to existing nodes with high degree.
745
+
746
+ Parameters
747
+ ----------
748
+ n : int
749
+ Number of nodes
750
+ m1 : int
751
+ Number of edges to link each new node to existing nodes with probability $p$
752
+ m2 : int
753
+ Number of edges to link each new node to existing nodes with probability $1-p$
754
+ p : float
755
+ The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
756
+ seed : integer, random_state, or None (default)
757
+ Indicator of random number generation state.
758
+ See :ref:`Randomness<randomness>`.
759
+ initial_graph : Graph or None (default)
760
+ Initial network for Barabási–Albert algorithm.
761
+ A copy of `initial_graph` is used.
762
+ It should be connected for most use cases.
763
+ If None, starts from an star graph on max(m1, m2) + 1 nodes.
764
+ create_using : Graph constructor, optional (default=nx.Graph)
765
+ Graph type to create. If graph instance, then cleared before populated.
766
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
767
+
768
+ Returns
769
+ -------
770
+ G : Graph
771
+
772
+ Raises
773
+ ------
774
+ NetworkXError
775
+ If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
776
+ `p` does not satisfy ``0 <= p <= 1``, or
777
+ the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
778
+
779
+ References
780
+ ----------
781
+ .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
782
+ """
783
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
784
+ if m1 < 1 or m1 >= n:
785
+ raise nx.NetworkXError(
786
+ f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
787
+ )
788
+ if m2 < 1 or m2 >= n:
789
+ raise nx.NetworkXError(
790
+ f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
791
+ )
792
+ if p < 0 or p > 1:
793
+ raise nx.NetworkXError(
794
+ f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
795
+ )
796
+
797
+ # For simplicity, if p == 0 or 1, just return BA
798
+ if p == 1:
799
+ return barabasi_albert_graph(n, m1, seed, create_using=create_using)
800
+ elif p == 0:
801
+ return barabasi_albert_graph(n, m2, seed, create_using=create_using)
802
+
803
+ if initial_graph is None:
804
+ # Default initial graph : star graph on max(m1, m2) nodes
805
+ G = star_graph(max(m1, m2), create_using)
806
+ else:
807
+ if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
808
+ raise nx.NetworkXError(
809
+ f"Barabási–Albert initial graph must have between "
810
+ f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
811
+ )
812
+ G = initial_graph.copy()
813
+
814
+ # Target nodes for new edges
815
+ targets = list(G)
816
+ # List of existing nodes, with nodes repeated once for each adjacent edge
817
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
818
+ # Start adding the remaining nodes.
819
+ source = len(G)
820
+ while source < n:
821
+ # Pick which m to use (m1 or m2)
822
+ if seed.random() < p:
823
+ m = m1
824
+ else:
825
+ m = m2
826
+ # Now choose m unique nodes from the existing nodes
827
+ # Pick uniformly from repeated_nodes (preferential attachment)
828
+ targets = _random_subset(repeated_nodes, m, seed)
829
+ # Add edges to m nodes from the source.
830
+ G.add_edges_from(zip([source] * m, targets))
831
+ # Add one node to the list for each new edge just created.
832
+ repeated_nodes.extend(targets)
833
+ # And the new node "source" has m edges to add to the list.
834
+ repeated_nodes.extend([source] * m)
835
+
836
+ source += 1
837
+ return G
838
+
839
+
840
+ @py_random_state(4)
841
+ @nx._dispatchable(graphs=None, returns_graph=True)
842
+ def extended_barabasi_albert_graph(n, m, p, q, seed=None, *, create_using=None):
843
+ """Returns an extended Barabási–Albert model graph.
844
+
845
+ An extended Barabási–Albert model graph is a random graph constructed
846
+ using preferential attachment. The extended model allows new edges,
847
+ rewired edges or new nodes. Based on the probabilities $p$ and $q$
848
+ with $p + q < 1$, the growing behavior of the graph is determined as:
849
+
850
+ 1) With $p$ probability, $m$ new edges are added to the graph,
851
+ starting from randomly chosen existing nodes and attached preferentially at the
852
+ other end.
853
+
854
+ 2) With $q$ probability, $m$ existing edges are rewired
855
+ by randomly choosing an edge and rewiring one end to a preferentially chosen node.
856
+
857
+ 3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
858
+ with edges attached preferentially.
859
+
860
+ When $p = q = 0$, the model behaves just like the Barabási–Alber model.
861
+
862
+ Parameters
863
+ ----------
864
+ n : int
865
+ Number of nodes
866
+ m : int
867
+ Number of edges with which a new node attaches to existing nodes
868
+ p : float
869
+ Probability value for adding an edge between existing nodes. p + q < 1
870
+ q : float
871
+ Probability value of rewiring of existing edges. p + q < 1
872
+ seed : integer, random_state, or None (default)
873
+ Indicator of random number generation state.
874
+ See :ref:`Randomness<randomness>`.
875
+ create_using : Graph constructor, optional (default=nx.Graph)
876
+ Graph type to create. If graph instance, then cleared before populated.
877
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
878
+
879
+ Returns
880
+ -------
881
+ G : Graph
882
+
883
+ Raises
884
+ ------
885
+ NetworkXError
886
+ If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
887
+
888
+ References
889
+ ----------
890
+ .. [1] Albert, R., & Barabási, A. L. (2000)
891
+ Topology of evolving networks: local events and universality
892
+ Physical review letters, 85(24), 5234.
893
+ """
894
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
895
+ if m < 1 or m >= n:
896
+ msg = f"Extended Barabasi-Albert network needs m>=1 and m<n, m={m}, n={n}"
897
+ raise nx.NetworkXError(msg)
898
+ if p + q >= 1:
899
+ msg = f"Extended Barabasi-Albert network needs p + q <= 1, p={p}, q={q}"
900
+ raise nx.NetworkXError(msg)
901
+
902
+ # Add m initial nodes (m0 in barabasi-speak)
903
+ G = empty_graph(m, create_using)
904
+
905
+ # List of nodes to represent the preferential attachment random selection.
906
+ # At the creation of the graph, all nodes are added to the list
907
+ # so that even nodes that are not connected have a chance to get selected,
908
+ # for rewiring and adding of edges.
909
+ # With each new edge, nodes at the ends of the edge are added to the list.
910
+ attachment_preference = []
911
+ attachment_preference.extend(range(m))
912
+
913
+ # Start adding the other n-m nodes. The first node is m.
914
+ new_node = m
915
+ while new_node < n:
916
+ a_probability = seed.random()
917
+
918
+ # Total number of edges of a Clique of all the nodes
919
+ clique_degree = len(G) - 1
920
+ clique_size = (len(G) * clique_degree) / 2
921
+
922
+ # Adding m new edges, if there is room to add them
923
+ if a_probability < p and G.size() <= clique_size - m:
924
+ # Select the nodes where an edge can be added
925
+ eligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
926
+ for i in range(m):
927
+ # Choosing a random source node from eligible_nodes
928
+ src_node = seed.choice(eligible_nodes)
929
+
930
+ # Picking a possible node that is not 'src_node' or
931
+ # neighbor with 'src_node', with preferential attachment
932
+ prohibited_nodes = list(G[src_node])
933
+ prohibited_nodes.append(src_node)
934
+ # This will raise an exception if the sequence is empty
935
+ dest_node = seed.choice(
936
+ [nd for nd in attachment_preference if nd not in prohibited_nodes]
937
+ )
938
+ # Adding the new edge
939
+ G.add_edge(src_node, dest_node)
940
+
941
+ # Appending both nodes to add to their preferential attachment
942
+ attachment_preference.append(src_node)
943
+ attachment_preference.append(dest_node)
944
+
945
+ # Adjusting the eligible nodes. Degree may be saturated.
946
+ if G.degree(src_node) == clique_degree:
947
+ eligible_nodes.remove(src_node)
948
+ if G.degree(dest_node) == clique_degree and dest_node in eligible_nodes:
949
+ eligible_nodes.remove(dest_node)
950
+
951
+ # Rewiring m edges, if there are enough edges
952
+ elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
953
+ # Selecting nodes that have at least 1 edge but that are not
954
+ # fully connected to ALL other nodes (center of star).
955
+ # These nodes are the pivot nodes of the edges to rewire
956
+ eligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
957
+ for i in range(m):
958
+ # Choosing a random source node
959
+ node = seed.choice(eligible_nodes)
960
+
961
+ # The available nodes do have a neighbor at least.
962
+ nbr_nodes = list(G[node])
963
+
964
+ # Choosing the other end that will get detached
965
+ src_node = seed.choice(nbr_nodes)
966
+
967
+ # Picking a target node that is not 'node' or
968
+ # neighbor with 'node', with preferential attachment
969
+ nbr_nodes.append(node)
970
+ dest_node = seed.choice(
971
+ [nd for nd in attachment_preference if nd not in nbr_nodes]
972
+ )
973
+ # Rewire
974
+ G.remove_edge(node, src_node)
975
+ G.add_edge(node, dest_node)
976
+
977
+ # Adjusting the preferential attachment list
978
+ attachment_preference.remove(src_node)
979
+ attachment_preference.append(dest_node)
980
+
981
+ # Adjusting the eligible nodes.
982
+ # nodes may be saturated or isolated.
983
+ if G.degree(src_node) == 0 and src_node in eligible_nodes:
984
+ eligible_nodes.remove(src_node)
985
+ if dest_node in eligible_nodes:
986
+ if G.degree(dest_node) == clique_degree:
987
+ eligible_nodes.remove(dest_node)
988
+ else:
989
+ if G.degree(dest_node) == 1:
990
+ eligible_nodes.append(dest_node)
991
+
992
+ # Adding new node with m edges
993
+ else:
994
+ # Select the edges' nodes by preferential attachment
995
+ targets = _random_subset(attachment_preference, m, seed)
996
+ G.add_edges_from(zip([new_node] * m, targets))
997
+
998
+ # Add one node to the list for each new edge just created.
999
+ attachment_preference.extend(targets)
1000
+ # The new node has m edges to it, plus itself: m + 1
1001
+ attachment_preference.extend([new_node] * (m + 1))
1002
+ new_node += 1
1003
+ return G
1004
+
1005
+
1006
+ @py_random_state(3)
1007
+ @nx._dispatchable(graphs=None, returns_graph=True)
1008
+ def powerlaw_cluster_graph(n, m, p, seed=None, *, create_using=None):
1009
+ """Holme and Kim algorithm for growing graphs with powerlaw
1010
+ degree distribution and approximate average clustering.
1011
+
1012
+ Parameters
1013
+ ----------
1014
+ n : int
1015
+ the number of nodes
1016
+ m : int
1017
+ the number of random edges to add for each new node
1018
+ p : float,
1019
+ Probability of adding a triangle after adding a random edge
1020
+ seed : integer, random_state, or None (default)
1021
+ Indicator of random number generation state.
1022
+ See :ref:`Randomness<randomness>`.
1023
+ create_using : Graph constructor, optional (default=nx.Graph)
1024
+ Graph type to create. If graph instance, then cleared before populated.
1025
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1026
+
1027
+ Notes
1028
+ -----
1029
+ The average clustering has a hard time getting above a certain
1030
+ cutoff that depends on `m`. This cutoff is often quite low. The
1031
+ transitivity (fraction of triangles to possible triangles) seems to
1032
+ decrease with network size.
1033
+
1034
+ It is essentially the Barabási–Albert (BA) growth model with an
1035
+ extra step that each random edge is followed by a chance of
1036
+ making an edge to one of its neighbors too (and thus a triangle).
1037
+
1038
+ This algorithm improves on BA in the sense that it enables a
1039
+ higher average clustering to be attained if desired.
1040
+
1041
+ It seems possible to have a disconnected graph with this algorithm
1042
+ since the initial `m` nodes may not be all linked to a new node
1043
+ on the first iteration like the BA model.
1044
+
1045
+ Raises
1046
+ ------
1047
+ NetworkXError
1048
+ If `m` does not satisfy ``1 <= m <= n`` or `p` does not
1049
+ satisfy ``0 <= p <= 1``.
1050
+
1051
+ References
1052
+ ----------
1053
+ .. [1] P. Holme and B. J. Kim,
1054
+ "Growing scale-free networks with tunable clustering",
1055
+ Phys. Rev. E, 65, 026107, 2002.
1056
+ """
1057
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1058
+ if m < 1 or n < m:
1059
+ raise nx.NetworkXError(f"NetworkXError must have m>1 and m<n, m={m},n={n}")
1060
+
1061
+ if p > 1 or p < 0:
1062
+ raise nx.NetworkXError(f"NetworkXError p must be in [0,1], p={p}")
1063
+
1064
+ G = empty_graph(m, create_using) # add m initial nodes (m0 in barabasi-speak)
1065
+ repeated_nodes = list(G) # list of existing nodes to sample from
1066
+ # with nodes repeated once for each adjacent edge
1067
+ source = m # next node is m
1068
+ while source < n: # Now add the other n-1 nodes
1069
+ possible_targets = _random_subset(repeated_nodes, m, seed)
1070
+ # do one preferential attachment for new node
1071
+ target = possible_targets.pop()
1072
+ G.add_edge(source, target)
1073
+ repeated_nodes.append(target) # add one node to list for each new link
1074
+ count = 1
1075
+ while count < m: # add m-1 more new links
1076
+ if seed.random() < p: # clustering step: add triangle
1077
+ neighborhood = [
1078
+ nbr
1079
+ for nbr in G.neighbors(target)
1080
+ if not G.has_edge(source, nbr) and nbr != source
1081
+ ]
1082
+ if neighborhood: # if there is a neighbor without a link
1083
+ nbr = seed.choice(neighborhood)
1084
+ G.add_edge(source, nbr) # add triangle
1085
+ repeated_nodes.append(nbr)
1086
+ count = count + 1
1087
+ continue # go to top of while loop
1088
+ # else do preferential attachment step if above fails
1089
+ target = possible_targets.pop()
1090
+ G.add_edge(source, target)
1091
+ repeated_nodes.append(target)
1092
+ count = count + 1
1093
+
1094
+ repeated_nodes.extend([source] * m) # add source node to list m times
1095
+ source += 1
1096
+ return G
1097
+
1098
+
1099
+ @py_random_state(3)
1100
+ @nx._dispatchable(graphs=None, returns_graph=True)
1101
+ def random_lobster_graph(n, p1, p2, seed=None, *, create_using=None):
1102
+ """Returns a random lobster graph.
1103
+
1104
+ A lobster is a tree that reduces to a caterpillar when pruning all
1105
+ leaf nodes. A caterpillar is a tree that reduces to a path graph
1106
+ when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
1107
+
1108
+ This implementation iterates on the probabilities `p1` and `p2` to add
1109
+ edges at levels 1 and 2, respectively. Graphs are therefore constructed
1110
+ iteratively with uniform randomness at each level rather than being selected
1111
+ uniformly at random from the set of all possible lobsters.
1112
+
1113
+ Parameters
1114
+ ----------
1115
+ n : int
1116
+ The expected number of nodes in the backbone
1117
+ p1 : float
1118
+ Probability of adding an edge to the backbone
1119
+ p2 : float
1120
+ Probability of adding an edge one level beyond backbone
1121
+ seed : integer, random_state, or None (default)
1122
+ Indicator of random number generation state.
1123
+ See :ref:`Randomness<randomness>`.
1124
+ create_using : Graph constructor, optional (default=nx.Graph)
1125
+ Graph type to create. If graph instance, then cleared before populated.
1126
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1127
+
1128
+ Raises
1129
+ ------
1130
+ NetworkXError
1131
+ If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
1132
+ """
1133
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1134
+ p1, p2 = abs(p1), abs(p2)
1135
+ if any(p >= 1 for p in [p1, p2]):
1136
+ raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
1137
+
1138
+ # a necessary ingredient in any self-respecting graph library
1139
+ llen = int(2 * seed.random() * n + 0.5)
1140
+ L = path_graph(llen, create_using)
1141
+ # build caterpillar: add edges to path graph with probability p1
1142
+ current_node = llen - 1
1143
+ for n in range(llen):
1144
+ while seed.random() < p1: # add fuzzy caterpillar parts
1145
+ current_node += 1
1146
+ L.add_edge(n, current_node)
1147
+ cat_node = current_node
1148
+ while seed.random() < p2: # add crunchy lobster bits
1149
+ current_node += 1
1150
+ L.add_edge(cat_node, current_node)
1151
+ return L # voila, un lobster!
1152
+
1153
+
1154
+ @py_random_state(3)
1155
+ @nx._dispatchable(graphs=None, returns_graph=True)
1156
+ def random_lobster(n, p1, p2, seed=None, *, create_using=None):
1157
+ """
1158
+ .. deprecated:: 3.5
1159
+ `random_lobster` is a deprecated alias
1160
+ for `random_lobster_graph`.
1161
+ Use `random_lobster_graph` instead.
1162
+ """
1163
+ import warnings
1164
+
1165
+ warnings.warn(
1166
+ "`random_lobster` is deprecated, use `random_lobster_graph` instead.",
1167
+ category=DeprecationWarning,
1168
+ stacklevel=2,
1169
+ )
1170
+ return random_lobster_graph(n, p1, p2, seed=seed, create_using=create_using)
1171
+
1172
+
1173
+ @py_random_state(1)
1174
+ @nx._dispatchable(graphs=None, returns_graph=True)
1175
+ def random_shell_graph(constructor, seed=None, *, create_using=None):
1176
+ """Returns a random shell graph for the constructor given.
1177
+
1178
+ Parameters
1179
+ ----------
1180
+ constructor : list of three-tuples
1181
+ Represents the parameters for a shell, starting at the center
1182
+ shell. Each element of the list must be of the form `(n, m,
1183
+ d)`, where `n` is the number of nodes in the shell, `m` is
1184
+ the number of edges in the shell, and `d` is the ratio of
1185
+ inter-shell (next) edges to intra-shell edges. If `d` is zero,
1186
+ there will be no intra-shell edges, and if `d` is one there
1187
+ will be all possible intra-shell edges.
1188
+ seed : integer, random_state, or None (default)
1189
+ Indicator of random number generation state.
1190
+ See :ref:`Randomness<randomness>`.
1191
+ create_using : Graph constructor, optional (default=nx.Graph)
1192
+ Graph type to create. Graph instances are not supported.
1193
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1194
+
1195
+ Examples
1196
+ --------
1197
+ >>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
1198
+ >>> G = nx.random_shell_graph(constructor)
1199
+
1200
+ """
1201
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1202
+ G = empty_graph(0, create_using)
1203
+
1204
+ glist = []
1205
+ intra_edges = []
1206
+ nnodes = 0
1207
+ # create gnm graphs for each shell
1208
+ for n, m, d in constructor:
1209
+ inter_edges = int(m * d)
1210
+ intra_edges.append(m - inter_edges)
1211
+ g = nx.convert_node_labels_to_integers(
1212
+ gnm_random_graph(n, inter_edges, seed=seed, create_using=G.__class__),
1213
+ first_label=nnodes,
1214
+ )
1215
+ glist.append(g)
1216
+ nnodes += n
1217
+ G = nx.operators.union(G, g)
1218
+
1219
+ # connect the shells randomly
1220
+ for gi in range(len(glist) - 1):
1221
+ nlist1 = list(glist[gi])
1222
+ nlist2 = list(glist[gi + 1])
1223
+ total_edges = intra_edges[gi]
1224
+ edge_count = 0
1225
+ while edge_count < total_edges:
1226
+ u = seed.choice(nlist1)
1227
+ v = seed.choice(nlist2)
1228
+ if u == v or G.has_edge(u, v):
1229
+ continue
1230
+ else:
1231
+ G.add_edge(u, v)
1232
+ edge_count = edge_count + 1
1233
+ return G
1234
+
1235
+
1236
+ @py_random_state(2)
1237
+ @nx._dispatchable(graphs=None, returns_graph=True)
1238
+ def random_powerlaw_tree(n, gamma=3, seed=None, tries=100, *, create_using=None):
1239
+ """Returns a tree with a power law degree distribution.
1240
+
1241
+ Parameters
1242
+ ----------
1243
+ n : int
1244
+ The number of nodes.
1245
+ gamma : float
1246
+ Exponent of the power law.
1247
+ seed : integer, random_state, or None (default)
1248
+ Indicator of random number generation state.
1249
+ See :ref:`Randomness<randomness>`.
1250
+ tries : int
1251
+ Number of attempts to adjust the sequence to make it a tree.
1252
+ create_using : Graph constructor, optional (default=nx.Graph)
1253
+ Graph type to create. If graph instance, then cleared before populated.
1254
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1255
+
1256
+ Raises
1257
+ ------
1258
+ NetworkXError
1259
+ If no valid sequence is found within the maximum number of
1260
+ attempts.
1261
+
1262
+ Notes
1263
+ -----
1264
+ A trial power law degree sequence is chosen and then elements are
1265
+ swapped with new elements from a powerlaw distribution until the
1266
+ sequence makes a tree (by checking, for example, that the number of
1267
+ edges is one smaller than the number of nodes).
1268
+
1269
+ """
1270
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1271
+ # This call may raise a NetworkXError if the number of tries is succeeded.
1272
+ seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
1273
+ G = degree_sequence_tree(seq, create_using)
1274
+ return G
1275
+
1276
+
1277
+ @py_random_state(2)
1278
+ @nx._dispatchable(graphs=None)
1279
+ def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
1280
+ """Returns a degree sequence for a tree with a power law distribution.
1281
+
1282
+ Parameters
1283
+ ----------
1284
+ n : int,
1285
+ The number of nodes.
1286
+ gamma : float
1287
+ Exponent of the power law.
1288
+ seed : integer, random_state, or None (default)
1289
+ Indicator of random number generation state.
1290
+ See :ref:`Randomness<randomness>`.
1291
+ tries : int
1292
+ Number of attempts to adjust the sequence to make it a tree.
1293
+
1294
+ Raises
1295
+ ------
1296
+ NetworkXError
1297
+ If no valid sequence is found within the maximum number of
1298
+ attempts.
1299
+
1300
+ Notes
1301
+ -----
1302
+ A trial power law degree sequence is chosen and then elements are
1303
+ swapped with new elements from a power law distribution until
1304
+ the sequence makes a tree (by checking, for example, that the number of
1305
+ edges is one smaller than the number of nodes).
1306
+
1307
+ """
1308
+ # get trial sequence
1309
+ z = nx.utils.powerlaw_sequence(n, exponent=gamma, seed=seed)
1310
+ # round to integer values in the range [0,n]
1311
+ zseq = [min(n, max(round(s), 0)) for s in z]
1312
+
1313
+ # another sequence to swap values from
1314
+ z = nx.utils.powerlaw_sequence(tries, exponent=gamma, seed=seed)
1315
+ # round to integer values in the range [0,n]
1316
+ swap = [min(n, max(round(s), 0)) for s in z]
1317
+
1318
+ for _ in swap:
1319
+ valid, _ = nx.utils.is_valid_tree_degree_sequence(zseq)
1320
+ if valid:
1321
+ return zseq
1322
+ index = seed.randint(0, n - 1)
1323
+ zseq[index] = swap.pop()
1324
+
1325
+ raise nx.NetworkXError(
1326
+ f"Exceeded max ({tries}) attempts for a valid tree sequence."
1327
+ )
1328
+
1329
+
1330
+ @py_random_state(3)
1331
+ @nx._dispatchable(graphs=None, returns_graph=True)
1332
+ def random_kernel_graph(
1333
+ n, kernel_integral, kernel_root=None, seed=None, *, create_using=None
1334
+ ):
1335
+ r"""Returns an random graph based on the specified kernel.
1336
+
1337
+ The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
1338
+ probability specified by a kernel $\kappa(x,y)$ [1]_. The kernel
1339
+ $\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
1340
+ bounded function.
1341
+
1342
+ Parameters
1343
+ ----------
1344
+ n : int
1345
+ The number of nodes
1346
+ kernel_integral : function
1347
+ Function that returns the definite integral of the kernel $\kappa(x,y)$,
1348
+ $F(y,a,b) := \int_a^b \kappa(x,y)dx$
1349
+ kernel_root: function (optional)
1350
+ Function that returns the root $b$ of the equation $F(y,a,b) = r$.
1351
+ If None, the root is found using :func:`scipy.optimize.brentq`
1352
+ (this requires SciPy).
1353
+ seed : integer, random_state, or None (default)
1354
+ Indicator of random number generation state.
1355
+ See :ref:`Randomness<randomness>`.
1356
+ create_using : Graph constructor, optional (default=nx.Graph)
1357
+ Graph type to create. If graph instance, then cleared before populated.
1358
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1359
+
1360
+ Notes
1361
+ -----
1362
+ The kernel is specified through its definite integral which must be
1363
+ provided as one of the arguments. If the integral and root of the
1364
+ kernel integral can be found in $O(1)$ time then this algorithm runs in
1365
+ time $O(n+m)$ where m is the expected number of edges [2]_.
1366
+
1367
+ The nodes are set to integers from $0$ to $n-1$.
1368
+
1369
+ Examples
1370
+ --------
1371
+ Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
1372
+ $\kappa(x,y)=c$ where $c$ is the mean expected degree.
1373
+
1374
+ >>> def integral(u, w, z):
1375
+ ... return c * (z - w)
1376
+ >>> def root(u, w, r):
1377
+ ... return r / c + w
1378
+ >>> c = 1
1379
+ >>> graph = nx.random_kernel_graph(1000, integral, root)
1380
+
1381
+ See Also
1382
+ --------
1383
+ gnp_random_graph
1384
+ expected_degree_graph
1385
+
1386
+ References
1387
+ ----------
1388
+ .. [1] Bollobás, Béla, Janson, S. and Riordan, O.
1389
+ "The phase transition in inhomogeneous random graphs",
1390
+ *Random Structures Algorithms*, 31, 3--122, 2007.
1391
+
1392
+ .. [2] Hagberg A, Lemons N (2015),
1393
+ "Fast Generation of Sparse Random Kernel Graphs".
1394
+ PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
1395
+ """
1396
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1397
+ if kernel_root is None:
1398
+ import scipy as sp
1399
+
1400
+ def kernel_root(y, a, r):
1401
+ def my_function(b):
1402
+ return kernel_integral(y, a, b) - r
1403
+
1404
+ return sp.optimize.brentq(my_function, a, 1)
1405
+
1406
+ graph = nx.empty_graph(create_using=create_using)
1407
+ graph.add_nodes_from(range(n))
1408
+ (i, j) = (1, 1)
1409
+ while i < n:
1410
+ r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
1411
+ if kernel_integral(i / n, j / n, 1) <= r:
1412
+ i, j = i + 1, i + 1
1413
+ else:
1414
+ j = math.ceil(n * kernel_root(i / n, j / n, r))
1415
+ graph.add_edge(i - 1, j - 1)
1416
+ return graph
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/small.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various small and named graphs, together with some compact generators.
3
+
4
+ """
5
+
6
+ __all__ = [
7
+ "LCF_graph",
8
+ "bull_graph",
9
+ "chvatal_graph",
10
+ "cubical_graph",
11
+ "desargues_graph",
12
+ "diamond_graph",
13
+ "dodecahedral_graph",
14
+ "frucht_graph",
15
+ "generalized_petersen_graph",
16
+ "heawood_graph",
17
+ "hoffman_singleton_graph",
18
+ "house_graph",
19
+ "house_x_graph",
20
+ "icosahedral_graph",
21
+ "krackhardt_kite_graph",
22
+ "moebius_kantor_graph",
23
+ "octahedral_graph",
24
+ "pappus_graph",
25
+ "petersen_graph",
26
+ "sedgewick_maze_graph",
27
+ "tetrahedral_graph",
28
+ "truncated_cube_graph",
29
+ "truncated_tetrahedron_graph",
30
+ "tutte_graph",
31
+ ]
32
+
33
+ from functools import wraps
34
+
35
+ import networkx as nx
36
+ from networkx.exception import NetworkXError
37
+ from networkx.generators.classic import (
38
+ complete_graph,
39
+ cycle_graph,
40
+ empty_graph,
41
+ path_graph,
42
+ )
43
+
44
+
45
+ def _raise_on_directed(func):
46
+ """
47
+ A decorator which inspects the `create_using` argument and raises a
48
+ NetworkX exception when `create_using` is a DiGraph (class or instance) for
49
+ graph generators that do not support directed outputs.
50
+
51
+ `create_using` may be a keyword argument or the first positional argument.
52
+ """
53
+
54
+ @wraps(func)
55
+ def wrapper(*args, **kwargs):
56
+ create_using = args[0] if args else kwargs.get("create_using")
57
+ if create_using is not None:
58
+ G = nx.empty_graph(create_using=create_using)
59
+ if G.is_directed():
60
+ raise NetworkXError("Directed Graph not supported in create_using")
61
+ return func(*args, **kwargs)
62
+
63
+ return wrapper
64
+
65
+
66
+ @nx._dispatchable(graphs=None, returns_graph=True)
67
+ def LCF_graph(n, shift_list, repeats, create_using=None):
68
+ """
69
+ Return the cubic graph specified in LCF notation.
70
+
71
+ LCF (Lederberg-Coxeter-Fruchte) notation[1]_ is a compressed
72
+ notation used in the generation of various cubic Hamiltonian
73
+ graphs of high symmetry. See, for example, `dodecahedral_graph`,
74
+ `desargues_graph`, `heawood_graph` and `pappus_graph`.
75
+
76
+ Nodes are drawn from ``range(n)``. Each node ``n_i`` is connected with
77
+ node ``n_i + shift % n`` where ``shift`` is given by cycling through
78
+ the input `shift_list` `repeat` s times.
79
+
80
+ Parameters
81
+ ----------
82
+ n : int
83
+ The starting graph is the `n`-cycle with nodes ``0, ..., n-1``.
84
+ The null graph is returned if `n` < 1.
85
+
86
+ shift_list : list
87
+ A list of integer shifts mod `n`, ``[s1, s2, .., sk]``
88
+
89
+ repeats : int
90
+ Integer specifying the number of times that shifts in `shift_list`
91
+ are successively applied to each current node in the n-cycle
92
+ to generate an edge between ``n_current`` and ``n_current + shift mod n``.
93
+
94
+ Returns
95
+ -------
96
+ G : Graph
97
+ A graph instance created from the specified LCF notation.
98
+
99
+ Examples
100
+ --------
101
+ The utility graph $K_{3,3}$
102
+
103
+ >>> G = nx.LCF_graph(6, [3, -3], 3)
104
+ >>> G.edges()
105
+ EdgeView([(0, 1), (0, 5), (0, 3), (1, 2), (1, 4), (2, 3), (2, 5), (3, 4), (4, 5)])
106
+
107
+ The Heawood graph:
108
+
109
+ >>> G = nx.LCF_graph(14, [5, -5], 7)
110
+ >>> nx.is_isomorphic(G, nx.heawood_graph())
111
+ True
112
+
113
+ References
114
+ ----------
115
+ .. [1] https://en.wikipedia.org/wiki/LCF_notation
116
+
117
+ """
118
+ if n <= 0:
119
+ return empty_graph(0, create_using)
120
+
121
+ # start with the n-cycle
122
+ G = cycle_graph(n, create_using)
123
+ if G.is_directed():
124
+ raise NetworkXError("Directed Graph not supported")
125
+ G.name = "LCF_graph"
126
+ nodes = sorted(G)
127
+
128
+ n_extra_edges = repeats * len(shift_list)
129
+ # edges are added n_extra_edges times
130
+ # (not all of these need be new)
131
+ if n_extra_edges < 1:
132
+ return G
133
+
134
+ for i in range(n_extra_edges):
135
+ shift = shift_list[i % len(shift_list)] # cycle through shift_list
136
+ v1 = nodes[i % n] # cycle repeatedly through nodes
137
+ v2 = nodes[(i + shift) % n]
138
+ G.add_edge(v1, v2)
139
+ return G
140
+
141
+
142
+ # -------------------------------------------------------------------------------
143
+ # Various small and named graphs
144
+ # -------------------------------------------------------------------------------
145
+
146
+
147
+ @_raise_on_directed
148
+ @nx._dispatchable(graphs=None, returns_graph=True)
149
+ def bull_graph(create_using=None):
150
+ """
151
+ Returns the Bull Graph
152
+
153
+ The Bull Graph has 5 nodes and 5 edges. It is a planar undirected
154
+ graph in the form of a triangle with two disjoint pendant edges [1]_
155
+ The name comes from the triangle and pendant edges representing
156
+ respectively the body and legs of a bull.
157
+
158
+ Parameters
159
+ ----------
160
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
161
+ Graph type to create. If graph instance, then cleared before populated.
162
+
163
+ Returns
164
+ -------
165
+ G : networkx Graph
166
+ A bull graph with 5 nodes
167
+
168
+ References
169
+ ----------
170
+ .. [1] https://en.wikipedia.org/wiki/Bull_graph.
171
+
172
+ """
173
+ G = nx.from_dict_of_lists(
174
+ {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 4], 3: [1], 4: [2]},
175
+ create_using=create_using,
176
+ )
177
+ G.name = "Bull Graph"
178
+ return G
179
+
180
+
181
+ @_raise_on_directed
182
+ @nx._dispatchable(graphs=None, returns_graph=True)
183
+ def chvatal_graph(create_using=None):
184
+ """
185
+ Returns the Chvátal Graph
186
+
187
+ The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_.
188
+ It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized
189
+ LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_.
190
+
191
+ Parameters
192
+ ----------
193
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
194
+ Graph type to create. If graph instance, then cleared before populated.
195
+
196
+ Returns
197
+ -------
198
+ G : networkx Graph
199
+ The Chvátal graph with 12 nodes and 24 edges
200
+
201
+ References
202
+ ----------
203
+ .. [1] https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph
204
+ .. [2] https://mathworld.wolfram.com/ChvatalGraph.html
205
+
206
+ """
207
+ G = nx.from_dict_of_lists(
208
+ {
209
+ 0: [1, 4, 6, 9],
210
+ 1: [2, 5, 7],
211
+ 2: [3, 6, 8],
212
+ 3: [4, 7, 9],
213
+ 4: [5, 8],
214
+ 5: [10, 11],
215
+ 6: [10, 11],
216
+ 7: [8, 11],
217
+ 8: [10],
218
+ 9: [10, 11],
219
+ },
220
+ create_using=create_using,
221
+ )
222
+ G.name = "Chvatal Graph"
223
+ return G
224
+
225
+
226
+ @_raise_on_directed
227
+ @nx._dispatchable(graphs=None, returns_graph=True)
228
+ def cubical_graph(create_using=None):
229
+ """
230
+ Returns the 3-regular Platonic Cubical Graph
231
+
232
+ The skeleton of the cube (the nodes and edges) form a graph, with 8
233
+ nodes, and 12 edges. It is a special case of the hypercube graph.
234
+ It is one of 5 Platonic graphs, each a skeleton of its
235
+ Platonic solid [1]_.
236
+ Such graphs arise in parallel processing in computers.
237
+
238
+ Parameters
239
+ ----------
240
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
241
+ Graph type to create. If graph instance, then cleared before populated.
242
+
243
+ Returns
244
+ -------
245
+ G : networkx Graph
246
+ A cubical graph with 8 nodes and 12 edges
247
+
248
+ See Also
249
+ --------
250
+ tetrahedral_graph, octahedral_graph, dodecahedral_graph, icosahedral_graph
251
+
252
+ References
253
+ ----------
254
+ .. [1] https://en.wikipedia.org/wiki/Cube#Cubical_graph
255
+
256
+ """
257
+ G = nx.from_dict_of_lists(
258
+ {
259
+ 0: [1, 3, 4],
260
+ 1: [0, 2, 7],
261
+ 2: [1, 3, 6],
262
+ 3: [0, 2, 5],
263
+ 4: [0, 5, 7],
264
+ 5: [3, 4, 6],
265
+ 6: [2, 5, 7],
266
+ 7: [1, 4, 6],
267
+ },
268
+ create_using=create_using,
269
+ )
270
+ G.name = "Platonic Cubical Graph"
271
+ return G
272
+
273
+
274
+ @nx._dispatchable(graphs=None, returns_graph=True)
275
+ def desargues_graph(create_using=None):
276
+ """
277
+ Returns the Desargues Graph
278
+
279
+ The Desargues Graph is a non-planar, distance-transitive cubic graph
280
+ with 20 nodes and 30 edges [1]_. It is isomorphic to the Generalized
281
+ Petersen Graph GP(10, 3). It is a symmetric graph. It can be represented
282
+ in LCF notation as [5,-5,9,-9]^5 [2]_.
283
+
284
+ Parameters
285
+ ----------
286
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
287
+ Graph type to create. If graph instance, then cleared before populated.
288
+
289
+ Returns
290
+ -------
291
+ G : networkx Graph
292
+ Desargues Graph with 20 nodes and 30 edges
293
+
294
+ References
295
+ ----------
296
+ .. [1] https://en.wikipedia.org/wiki/Desargues_graph
297
+ .. [2] https://mathworld.wolfram.com/DesarguesGraph.html
298
+ """
299
+ G = LCF_graph(20, [5, -5, 9, -9], 5, create_using)
300
+ G.name = "Desargues Graph"
301
+ return G
302
+
303
+
304
+ @_raise_on_directed
305
+ @nx._dispatchable(graphs=None, returns_graph=True)
306
+ def diamond_graph(create_using=None):
307
+ """
308
+ Returns the Diamond graph
309
+
310
+ The Diamond Graph is planar undirected graph with 4 nodes and 5 edges.
311
+ It is also sometimes known as the double triangle graph or kite graph [1]_.
312
+
313
+ Parameters
314
+ ----------
315
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
316
+ Graph type to create. If graph instance, then cleared before populated.
317
+
318
+ Returns
319
+ -------
320
+ G : networkx Graph
321
+ Diamond Graph with 4 nodes and 5 edges
322
+
323
+ References
324
+ ----------
325
+ .. [1] https://mathworld.wolfram.com/DiamondGraph.html
326
+ """
327
+ G = nx.from_dict_of_lists(
328
+ {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 3], 3: [1, 2]}, create_using=create_using
329
+ )
330
+ G.name = "Diamond Graph"
331
+ return G
332
+
333
+
334
+ @nx._dispatchable(graphs=None, returns_graph=True)
335
+ def dodecahedral_graph(create_using=None):
336
+ """
337
+ Returns the Platonic Dodecahedral graph.
338
+
339
+ The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the
340
+ dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_.
341
+ It can be described in LCF notation as:
342
+ ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_.
343
+
344
+ Parameters
345
+ ----------
346
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
347
+ Graph type to create. If graph instance, then cleared before populated.
348
+
349
+ Returns
350
+ -------
351
+ G : networkx Graph
352
+ Dodecahedral Graph with 20 nodes and 30 edges
353
+
354
+ See Also
355
+ --------
356
+ tetrahedral_graph, cubical_graph, octahedral_graph, icosahedral_graph
357
+
358
+ References
359
+ ----------
360
+ .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph
361
+ .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html
362
+
363
+ """
364
+ G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using)
365
+ G.name = "Dodecahedral Graph"
366
+ return G
367
+
368
+
369
+ @nx._dispatchable(graphs=None, returns_graph=True)
370
+ def frucht_graph(create_using=None):
371
+ """
372
+ Returns the Frucht Graph.
373
+
374
+ The Frucht Graph is the smallest cubical graph whose
375
+ automorphism group consists only of the identity element [1]_.
376
+ It has 12 nodes and 18 edges and no nontrivial symmetries.
377
+ It is planar and Hamiltonian [2]_.
378
+
379
+ Parameters
380
+ ----------
381
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
382
+ Graph type to create. If graph instance, then cleared before populated.
383
+
384
+ Returns
385
+ -------
386
+ G : networkx Graph
387
+ Frucht Graph with 12 nodes and 18 edges
388
+
389
+ References
390
+ ----------
391
+ .. [1] https://en.wikipedia.org/wiki/Frucht_graph
392
+ .. [2] https://mathworld.wolfram.com/FruchtGraph.html
393
+
394
+ """
395
+ G = cycle_graph(7, create_using)
396
+ G.add_edges_from(
397
+ [
398
+ [0, 7],
399
+ [1, 7],
400
+ [2, 8],
401
+ [3, 9],
402
+ [4, 9],
403
+ [5, 10],
404
+ [6, 10],
405
+ [7, 11],
406
+ [8, 11],
407
+ [8, 9],
408
+ [10, 11],
409
+ ]
410
+ )
411
+
412
+ G.name = "Frucht Graph"
413
+ return G
414
+
415
+
416
+ @nx._dispatchable(graphs=None, returns_graph=True)
417
+ def heawood_graph(create_using=None):
418
+ """
419
+ Returns the Heawood Graph, a (3,6) cage.
420
+
421
+ The Heawood Graph is an undirected graph with 14 nodes and 21 edges,
422
+ named after Percy John Heawood [1]_.
423
+ It is cubic symmetric, nonplanar, Hamiltonian, and can be represented
424
+ in LCF notation as ``[5,-5]^7`` [2]_.
425
+ It is the unique (3,6)-cage: the regular cubic graph of girth 6 with
426
+ minimal number of vertices [3]_.
427
+
428
+ Parameters
429
+ ----------
430
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
431
+ Graph type to create. If graph instance, then cleared before populated.
432
+
433
+ Returns
434
+ -------
435
+ G : networkx Graph
436
+ Heawood Graph with 14 nodes and 21 edges
437
+
438
+ References
439
+ ----------
440
+ .. [1] https://en.wikipedia.org/wiki/Heawood_graph
441
+ .. [2] https://mathworld.wolfram.com/HeawoodGraph.html
442
+ .. [3] https://www.win.tue.nl/~aeb/graphs/Heawood.html
443
+
444
+ """
445
+ G = LCF_graph(14, [5, -5], 7, create_using)
446
+ G.name = "Heawood Graph"
447
+ return G
448
+
449
+
450
+ @nx._dispatchable(graphs=None, returns_graph=True)
451
+ def hoffman_singleton_graph():
452
+ """
453
+ Returns the Hoffman-Singleton Graph.
454
+
455
+ The Hoffman–Singleton graph is a symmetrical undirected graph
456
+ with 50 nodes and 175 edges.
457
+ All indices lie in ``Z % 5``: that is, the integers mod 5 [1]_.
458
+ It is the only regular graph of vertex degree 7, diameter 2, and girth 5.
459
+ It is the unique (7,5)-cage graph and Moore graph, and contains many
460
+ copies of the Petersen Graph [2]_.
461
+
462
+ Returns
463
+ -------
464
+ G : networkx Graph
465
+ Hoffman–Singleton Graph with 50 nodes and 175 edges
466
+
467
+ Notes
468
+ -----
469
+ Constructed from pentagon and pentagram as follows: Take five pentagons $P_h$
470
+ and five pentagrams $Q_i$ . Join vertex $j$ of $P_h$ to vertex $h·i+j$ of $Q_i$ [3]_.
471
+
472
+ References
473
+ ----------
474
+ .. [1] https://blogs.ams.org/visualinsight/2016/02/01/hoffman-singleton-graph/
475
+ .. [2] https://mathworld.wolfram.com/Hoffman-SingletonGraph.html
476
+ .. [3] https://en.wikipedia.org/wiki/Hoffman%E2%80%93Singleton_graph
477
+
478
+ """
479
+ G = nx.Graph()
480
+ for i in range(5):
481
+ for j in range(5):
482
+ G.add_edge(("pentagon", i, j), ("pentagon", i, (j - 1) % 5))
483
+ G.add_edge(("pentagon", i, j), ("pentagon", i, (j + 1) % 5))
484
+ G.add_edge(("pentagram", i, j), ("pentagram", i, (j - 2) % 5))
485
+ G.add_edge(("pentagram", i, j), ("pentagram", i, (j + 2) % 5))
486
+ for k in range(5):
487
+ G.add_edge(("pentagon", i, j), ("pentagram", k, (i * k + j) % 5))
488
+ G = nx.convert_node_labels_to_integers(G)
489
+ G.name = "Hoffman-Singleton Graph"
490
+ return G
491
+
492
+
493
+ @_raise_on_directed
494
+ @nx._dispatchable(graphs=None, returns_graph=True)
495
+ def house_graph(create_using=None):
496
+ """
497
+ Returns the House graph (square with triangle on top)
498
+
499
+ The house graph is a simple undirected graph with
500
+ 5 nodes and 6 edges [1]_.
501
+
502
+ Parameters
503
+ ----------
504
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
505
+ Graph type to create. If graph instance, then cleared before populated.
506
+
507
+ Returns
508
+ -------
509
+ G : networkx Graph
510
+ House graph in the form of a square with a triangle on top
511
+
512
+ References
513
+ ----------
514
+ .. [1] https://mathworld.wolfram.com/HouseGraph.html
515
+ """
516
+ G = nx.from_dict_of_lists(
517
+ {0: [1, 2], 1: [0, 3], 2: [0, 3, 4], 3: [1, 2, 4], 4: [2, 3]},
518
+ create_using=create_using,
519
+ )
520
+ G.name = "House Graph"
521
+ return G
522
+
523
+
524
+ @_raise_on_directed
525
+ @nx._dispatchable(graphs=None, returns_graph=True)
526
+ def house_x_graph(create_using=None):
527
+ """
528
+ Returns the House graph with a cross inside the house square.
529
+
530
+ The House X-graph is the House graph plus the two edges connecting diagonally
531
+ opposite vertices of the square base. It is also one of the two graphs
532
+ obtained by removing two edges from the pentatope graph [1]_.
533
+
534
+ Parameters
535
+ ----------
536
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
537
+ Graph type to create. If graph instance, then cleared before populated.
538
+
539
+ Returns
540
+ -------
541
+ G : networkx Graph
542
+ House graph with diagonal vertices connected
543
+
544
+ References
545
+ ----------
546
+ .. [1] https://mathworld.wolfram.com/HouseGraph.html
547
+ """
548
+ G = house_graph(create_using)
549
+ G.add_edges_from([(0, 3), (1, 2)])
550
+ G.name = "House-with-X-inside Graph"
551
+ return G
552
+
553
+
554
+ @_raise_on_directed
555
+ @nx._dispatchable(graphs=None, returns_graph=True)
556
+ def icosahedral_graph(create_using=None):
557
+ """
558
+ Returns the Platonic Icosahedral graph.
559
+
560
+ The icosahedral graph has 12 nodes and 30 edges. It is a Platonic graph
561
+ whose nodes have the connectivity of the icosahedron. It is undirected,
562
+ regular and Hamiltonian [1]_.
563
+
564
+ Parameters
565
+ ----------
566
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
567
+ Graph type to create. If graph instance, then cleared before populated.
568
+
569
+ Returns
570
+ -------
571
+ G : networkx Graph
572
+ Icosahedral graph with 12 nodes and 30 edges.
573
+
574
+ See Also
575
+ --------
576
+ tetrahedral_graph, cubical_graph, octahedral_graph, dodecahedral_graph
577
+
578
+ References
579
+ ----------
580
+ .. [1] https://mathworld.wolfram.com/IcosahedralGraph.html
581
+ """
582
+ G = nx.from_dict_of_lists(
583
+ {
584
+ 0: [1, 5, 7, 8, 11],
585
+ 1: [2, 5, 6, 8],
586
+ 2: [3, 6, 8, 9],
587
+ 3: [4, 6, 9, 10],
588
+ 4: [5, 6, 10, 11],
589
+ 5: [6, 11],
590
+ 7: [8, 9, 10, 11],
591
+ 8: [9],
592
+ 9: [10],
593
+ 10: [11],
594
+ },
595
+ create_using=create_using,
596
+ )
597
+ G.name = "Platonic Icosahedral Graph"
598
+ return G
599
+
600
+
601
+ @_raise_on_directed
602
+ @nx._dispatchable(graphs=None, returns_graph=True)
603
+ def krackhardt_kite_graph(create_using=None):
604
+ """
605
+ Returns the Krackhardt Kite Social Network.
606
+
607
+ A 10 actor social network introduced by David Krackhardt
608
+ to illustrate different centrality measures [1]_.
609
+
610
+ Parameters
611
+ ----------
612
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
613
+ Graph type to create. If graph instance, then cleared before populated.
614
+
615
+ Returns
616
+ -------
617
+ G : networkx Graph
618
+ Krackhardt Kite graph with 10 nodes and 18 edges
619
+
620
+ Notes
621
+ -----
622
+ The traditional labeling is:
623
+ Andre=1, Beverley=2, Carol=3, Diane=4,
624
+ Ed=5, Fernando=6, Garth=7, Heather=8, Ike=9, Jane=10.
625
+
626
+ References
627
+ ----------
628
+ .. [1] Krackhardt, David. "Assessing the Political Landscape: Structure,
629
+ Cognition, and Power in Organizations". Administrative Science Quarterly.
630
+ 35 (2): 342–369. doi:10.2307/2393394. JSTOR 2393394. June 1990.
631
+
632
+ """
633
+ G = nx.from_dict_of_lists(
634
+ {
635
+ 0: [1, 2, 3, 5],
636
+ 1: [0, 3, 4, 6],
637
+ 2: [0, 3, 5],
638
+ 3: [0, 1, 2, 4, 5, 6],
639
+ 4: [1, 3, 6],
640
+ 5: [0, 2, 3, 6, 7],
641
+ 6: [1, 3, 4, 5, 7],
642
+ 7: [5, 6, 8],
643
+ 8: [7, 9],
644
+ 9: [8],
645
+ },
646
+ create_using=create_using,
647
+ )
648
+ G.name = "Krackhardt Kite Social Network"
649
+ return G
650
+
651
+
652
+ @nx._dispatchable(graphs=None, returns_graph=True)
653
+ def moebius_kantor_graph(create_using=None):
654
+ """
655
+ Returns the Moebius-Kantor graph.
656
+
657
+ The Möbius-Kantor graph is the cubic symmetric graph on 16 nodes.
658
+ Its LCF notation is [5,-5]^8, and it is isomorphic to the generalized
659
+ Petersen Graph GP(8, 3) [1]_.
660
+
661
+ Parameters
662
+ ----------
663
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
664
+ Graph type to create. If graph instance, then cleared before populated.
665
+
666
+ Returns
667
+ -------
668
+ G : networkx Graph
669
+ Moebius-Kantor graph
670
+
671
+ References
672
+ ----------
673
+ .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph
674
+
675
+ """
676
+ G = LCF_graph(16, [5, -5], 8, create_using)
677
+ G.name = "Moebius-Kantor Graph"
678
+ return G
679
+
680
+
681
+ @_raise_on_directed
682
+ @nx._dispatchable(graphs=None, returns_graph=True)
683
+ def octahedral_graph(create_using=None):
684
+ """
685
+ Returns the Platonic Octahedral graph.
686
+
687
+ The octahedral graph is the 6-node 12-edge Platonic graph having the
688
+ connectivity of the octahedron [1]_. If 6 couples go to a party,
689
+ and each person shakes hands with every person except his or her partner,
690
+ then this graph describes the set of handshakes that take place;
691
+ for this reason it is also called the cocktail party graph [2]_.
692
+
693
+ Parameters
694
+ ----------
695
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
696
+ Graph type to create. If graph instance, then cleared before populated.
697
+
698
+ Returns
699
+ -------
700
+ G : networkx Graph
701
+ Octahedral graph
702
+
703
+ See Also
704
+ --------
705
+ tetrahedral_graph, cubical_graph, dodecahedral_graph, icosahedral_graph
706
+
707
+ References
708
+ ----------
709
+ .. [1] https://mathworld.wolfram.com/OctahedralGraph.html
710
+ .. [2] https://en.wikipedia.org/wiki/Tur%C3%A1n_graph#Special_cases
711
+
712
+ """
713
+ G = nx.from_dict_of_lists(
714
+ {0: [1, 2, 3, 4], 1: [2, 3, 5], 2: [4, 5], 3: [4, 5], 4: [5]},
715
+ create_using=create_using,
716
+ )
717
+ G.name = "Platonic Octahedral Graph"
718
+ return G
719
+
720
+
721
+ @nx._dispatchable(graphs=None, returns_graph=True)
722
+ def pappus_graph():
723
+ """
724
+ Returns the Pappus graph.
725
+
726
+ The Pappus graph is a cubic symmetric distance-regular graph with 18 nodes
727
+ and 27 edges. It is Hamiltonian and can be represented in LCF notation as
728
+ [5,7,-7,7,-7,-5]^3 [1]_.
729
+
730
+ Returns
731
+ -------
732
+ G : networkx Graph
733
+ Pappus graph
734
+
735
+ References
736
+ ----------
737
+ .. [1] https://en.wikipedia.org/wiki/Pappus_graph
738
+ """
739
+ G = LCF_graph(18, [5, 7, -7, 7, -7, -5], 3)
740
+ G.name = "Pappus Graph"
741
+ return G
742
+
743
+
744
+ @_raise_on_directed
745
+ @nx._dispatchable(graphs=None, returns_graph=True)
746
+ def petersen_graph(create_using=None):
747
+ """
748
+ Returns the Petersen Graph.
749
+
750
+ The Peterson Graph is a cubic, undirected graph with 10 nodes and 15 edges [1]_.
751
+ Julius Petersen constructed the graph as the smallest counterexample
752
+ against the claim that a connected bridgeless cubic graph
753
+ has an edge colouring with three colours [2]_.
754
+
755
+ Parameters
756
+ ----------
757
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
758
+ Graph type to create. If graph instance, then cleared before populated.
759
+
760
+ Returns
761
+ -------
762
+ G : networkx Graph
763
+ Petersen Graph
764
+
765
+ References
766
+ ----------
767
+ .. [1] https://en.wikipedia.org/wiki/Petersen_graph
768
+ .. [2] https://www.win.tue.nl/~aeb/drg/graphs/Petersen.html
769
+ """
770
+ G = nx.from_dict_of_lists(
771
+ {
772
+ 0: [1, 4, 5],
773
+ 1: [0, 2, 6],
774
+ 2: [1, 3, 7],
775
+ 3: [2, 4, 8],
776
+ 4: [3, 0, 9],
777
+ 5: [0, 7, 8],
778
+ 6: [1, 8, 9],
779
+ 7: [2, 5, 9],
780
+ 8: [3, 5, 6],
781
+ 9: [4, 6, 7],
782
+ },
783
+ create_using=create_using,
784
+ )
785
+ G.name = "Petersen Graph"
786
+ return G
787
+
788
+
789
+ @nx._dispatchable(graphs=None, returns_graph=True)
790
+ def generalized_petersen_graph(n, k, *, create_using=None):
791
+ """
792
+ Returns the Generalized Petersen Graph GP(n,k).
793
+
794
+ The Generalized Peterson Graph consists of an outer cycle of n nodes
795
+ connected to an inner circulant graph of n nodes, where nodes in the
796
+ inner circulant are connected to their kth nearest neighbor [1]_ [2]_.
797
+ A Generalized Petersen Graph is cubic with 2n nodes and 3n edges.
798
+
799
+ Some well known graphs are examples of Generalized Petersen Graphs such
800
+ as the Petersen Graph GP(5, 2), the Desargues graph GP(10, 3), the
801
+ Moebius-Kantor graph GP(8, 3), and the dodecahedron graph GP(10, 2).
802
+
803
+ Parameters
804
+ ----------
805
+ n : int
806
+ Number of nodes in the outer cycle and inner circulant. ``n >= 3`` is required.
807
+
808
+ k : int
809
+ Neighbor to connect in the inner circulant. ``1 <= k <= n/2``.
810
+ Note that some people require ``k < n/2`` but we and others allow equality.
811
+ Also, ``k < n/2`` is equivalent to ``k <= floor((n-1)/2)``
812
+
813
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
814
+ Graph type to create. If graph instance, then cleared before populated.
815
+
816
+ Returns
817
+ -------
818
+ G : networkx Graph
819
+ Generalized Petersen Graph n k
820
+
821
+ References
822
+ ----------
823
+ .. [1] https://mathworld.wolfram.com/GeneralizedPetersenGraph.html
824
+ .. [2] https://en.wikipedia.org/wiki/Generalized_Petersen_graph
825
+ """
826
+ if n <= 2:
827
+ raise NetworkXError(f"n >= 3 required. Got {n=}")
828
+ if k < 1 or k > n / 2:
829
+ raise NetworkXError(f" Got {n=} {k=}. Need 1 <= k <= n/2")
830
+
831
+ G = nx.cycle_graph(range(n), create_using=create_using) # u-nodes
832
+ if G.is_directed():
833
+ raise NetworkXError("Directed Graph not supported in create_using")
834
+ for i in range(n):
835
+ G.add_edge(i, n + i) # add v-nodes and u to v edges
836
+ G.add_edge(n + i, n + (i + k) % n) # edge from v_i to v_(i+k)%n
837
+
838
+ G.name = f"Generalized Petersen Graph GP({n}, {k})"
839
+ return G
840
+
841
+
842
+ @nx._dispatchable(graphs=None, returns_graph=True)
843
+ def sedgewick_maze_graph(create_using=None):
844
+ """
845
+ Return a small maze with a cycle.
846
+
847
+ This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph
848
+ Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_.
849
+ Nodes are numbered 0,..,7
850
+
851
+ Parameters
852
+ ----------
853
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
854
+ Graph type to create. If graph instance, then cleared before populated.
855
+
856
+ Returns
857
+ -------
858
+ G : networkx Graph
859
+ Small maze with a cycle
860
+
861
+ References
862
+ ----------
863
+ .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick
864
+ """
865
+ G = empty_graph(0, create_using)
866
+ G.add_nodes_from(range(8))
867
+ G.add_edges_from([[0, 2], [0, 7], [0, 5]])
868
+ G.add_edges_from([[1, 7], [2, 6]])
869
+ G.add_edges_from([[3, 4], [3, 5]])
870
+ G.add_edges_from([[4, 5], [4, 7], [4, 6]])
871
+ G.name = "Sedgewick Maze"
872
+ return G
873
+
874
+
875
+ @nx._dispatchable(graphs=None, returns_graph=True)
876
+ def tetrahedral_graph(create_using=None):
877
+ """
878
+ Returns the 3-regular Platonic Tetrahedral graph.
879
+
880
+ Tetrahedral graph has 4 nodes and 6 edges. It is a
881
+ special case of the complete graph, K4, and wheel graph, W4.
882
+ It is one of the 5 platonic graphs [1]_.
883
+
884
+ Parameters
885
+ ----------
886
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
887
+ Graph type to create. If graph instance, then cleared before populated.
888
+
889
+ Returns
890
+ -------
891
+ G : networkx Graph
892
+ Tetrahedral Graph
893
+
894
+ See Also
895
+ --------
896
+ cubical_graph, octahedral_graph, dodecahedral_graph, icosahedral_graph
897
+
898
+ References
899
+ ----------
900
+ .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph
901
+
902
+ """
903
+ G = complete_graph(4, create_using)
904
+ G.name = "Platonic Tetrahedral Graph"
905
+ return G
906
+
907
+
908
+ @_raise_on_directed
909
+ @nx._dispatchable(graphs=None, returns_graph=True)
910
+ def truncated_cube_graph(create_using=None):
911
+ """
912
+ Returns the skeleton of the truncated cube.
913
+
914
+ The truncated cube is an Archimedean solid with 14 regular
915
+ faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_.
916
+ The truncated cube is created by truncating (cutting off) the tips
917
+ of the cube one third of the way into each edge [2]_.
918
+
919
+ Parameters
920
+ ----------
921
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
922
+ Graph type to create. If graph instance, then cleared before populated.
923
+
924
+ Returns
925
+ -------
926
+ G : networkx Graph
927
+ Skeleton of the truncated cube
928
+
929
+ References
930
+ ----------
931
+ .. [1] https://en.wikipedia.org/wiki/Truncated_cube
932
+ .. [2] https://www.coolmath.com/reference/polyhedra-truncated-cube
933
+
934
+ """
935
+ G = nx.from_dict_of_lists(
936
+ {
937
+ 0: [1, 2, 4],
938
+ 1: [11, 14],
939
+ 2: [3, 4],
940
+ 3: [6, 8],
941
+ 4: [5],
942
+ 5: [16, 18],
943
+ 6: [7, 8],
944
+ 7: [10, 12],
945
+ 8: [9],
946
+ 9: [17, 20],
947
+ 10: [11, 12],
948
+ 11: [14],
949
+ 12: [13],
950
+ 13: [21, 22],
951
+ 14: [15],
952
+ 15: [19, 23],
953
+ 16: [17, 18],
954
+ 17: [20],
955
+ 18: [19],
956
+ 19: [23],
957
+ 20: [21],
958
+ 21: [22],
959
+ 22: [23],
960
+ },
961
+ create_using=create_using,
962
+ )
963
+ G.name = "Truncated Cube Graph"
964
+ return G
965
+
966
+
967
+ @nx._dispatchable(graphs=None, returns_graph=True)
968
+ def truncated_tetrahedron_graph(create_using=None):
969
+ """
970
+ Returns the skeleton of the truncated Platonic tetrahedron.
971
+
972
+ The truncated tetrahedron is an Archimedean solid with 4 regular hexagonal faces,
973
+ 4 equilateral triangle faces, 12 nodes and 18 edges. It can be constructed by truncating
974
+ all 4 vertices of a regular tetrahedron at one third of the original edge length [1]_.
975
+
976
+ Parameters
977
+ ----------
978
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
979
+ Graph type to create. If graph instance, then cleared before populated.
980
+
981
+ Returns
982
+ -------
983
+ G : networkx Graph
984
+ Skeleton of the truncated tetrahedron
985
+
986
+ References
987
+ ----------
988
+ .. [1] https://en.wikipedia.org/wiki/Truncated_tetrahedron
989
+
990
+ """
991
+ G = path_graph(12, create_using)
992
+ G.add_edges_from([(0, 2), (0, 9), (1, 6), (3, 11), (4, 11), (5, 7), (8, 10)])
993
+ G.name = "Truncated Tetrahedron Graph"
994
+ return G
995
+
996
+
997
+ @_raise_on_directed
998
+ @nx._dispatchable(graphs=None, returns_graph=True)
999
+ def tutte_graph(create_using=None):
1000
+ """
1001
+ Returns the Tutte graph.
1002
+
1003
+ The Tutte graph is a cubic polyhedral, non-Hamiltonian graph. It has
1004
+ 46 nodes and 69 edges.
1005
+ It is a counterexample to Tait's conjecture that every 3-regular polyhedron
1006
+ has a Hamiltonian cycle.
1007
+ It can be realized geometrically from a tetrahedron by multiply truncating
1008
+ three of its vertices [1]_.
1009
+
1010
+ Parameters
1011
+ ----------
1012
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
1013
+ Graph type to create. If graph instance, then cleared before populated.
1014
+
1015
+ Returns
1016
+ -------
1017
+ G : networkx Graph
1018
+ Tutte graph
1019
+
1020
+ References
1021
+ ----------
1022
+ .. [1] https://en.wikipedia.org/wiki/Tutte_graph
1023
+ """
1024
+ G = nx.from_dict_of_lists(
1025
+ {
1026
+ 0: [1, 2, 3],
1027
+ 1: [4, 26],
1028
+ 2: [10, 11],
1029
+ 3: [18, 19],
1030
+ 4: [5, 33],
1031
+ 5: [6, 29],
1032
+ 6: [7, 27],
1033
+ 7: [8, 14],
1034
+ 8: [9, 38],
1035
+ 9: [10, 37],
1036
+ 10: [39],
1037
+ 11: [12, 39],
1038
+ 12: [13, 35],
1039
+ 13: [14, 15],
1040
+ 14: [34],
1041
+ 15: [16, 22],
1042
+ 16: [17, 44],
1043
+ 17: [18, 43],
1044
+ 18: [45],
1045
+ 19: [20, 45],
1046
+ 20: [21, 41],
1047
+ 21: [22, 23],
1048
+ 22: [40],
1049
+ 23: [24, 27],
1050
+ 24: [25, 32],
1051
+ 25: [26, 31],
1052
+ 26: [33],
1053
+ 27: [28],
1054
+ 28: [29, 32],
1055
+ 29: [30],
1056
+ 30: [31, 33],
1057
+ 31: [32],
1058
+ 34: [35, 38],
1059
+ 35: [36],
1060
+ 36: [37, 39],
1061
+ 37: [38],
1062
+ 40: [41, 44],
1063
+ 41: [42],
1064
+ 42: [43, 45],
1065
+ 43: [44],
1066
+ },
1067
+ create_using=create_using,
1068
+ )
1069
+ G.name = "Tutte's Graph"
1070
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/social.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Famous social networks.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "karate_club_graph",
9
+ "davis_southern_women_graph",
10
+ "florentine_families_graph",
11
+ "les_miserables_graph",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(graphs=None, returns_graph=True)
16
+ def karate_club_graph():
17
+ """Returns Zachary's Karate Club graph.
18
+
19
+ Each node in the returned graph has a node attribute 'club' that
20
+ indicates the name of the club to which the member represented by that node
21
+ belongs, either 'Mr. Hi' or 'Officer'. Each edge has a weight based on the
22
+ number of contexts in which that edge's incident node members interacted.
23
+
24
+ The dataset is derived from the 'Club After Split From Data' column of Table 3 in [1]_.
25
+ This was in turn derived from the 'Club After Fission' column of Table 1 in the
26
+ same paper. Note that the nodes are 0-indexed in NetworkX, but 1-indexed in the
27
+ paper (the 'Individual Number in Matrix C' column of Table 3 starts at 1). This
28
+ means, for example, that ``G.nodes[9]["club"]`` returns 'Officer', which
29
+ corresponds to row 10 of Table 3 in the paper.
30
+
31
+ Examples
32
+ --------
33
+ To get the name of the club to which a node belongs:
34
+
35
+ >>> G = nx.karate_club_graph()
36
+ >>> G.nodes[5]["club"]
37
+ 'Mr. Hi'
38
+ >>> G.nodes[9]["club"]
39
+ 'Officer'
40
+
41
+ References
42
+ ----------
43
+ .. [1] Zachary, Wayne W.
44
+ "An Information Flow Model for Conflict and Fission in Small Groups."
45
+ *Journal of Anthropological Research*, 33, 452--473, (1977).
46
+ """
47
+ # Create the set of all members, and the members of each club.
48
+ all_members = set(range(34))
49
+ club1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21}
50
+ # club2 = all_members - club1
51
+
52
+ G = nx.Graph()
53
+ G.add_nodes_from(all_members)
54
+ G.name = "Zachary's Karate Club"
55
+
56
+ zacharydat = """\
57
+ 0 4 5 3 3 3 3 2 2 0 2 3 2 3 0 0 0 2 0 2 0 2 0 0 0 0 0 0 0 0 0 2 0 0
58
+ 4 0 6 3 0 0 0 4 0 0 0 0 0 5 0 0 0 1 0 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0
59
+ 5 6 0 3 0 0 0 4 5 1 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 0 0 0 3 0
60
+ 3 3 3 0 0 0 0 3 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
61
+ 3 0 0 0 0 0 2 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
62
+ 3 0 0 0 0 0 5 0 0 0 3 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
63
+ 3 0 0 0 2 5 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
64
+ 2 4 4 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
65
+ 2 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 4 3
66
+ 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
67
+ 2 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
68
+ 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
69
+ 1 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
70
+ 3 5 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3
71
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2
72
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 4
73
+ 0 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
74
+ 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
75
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2
76
+ 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
77
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1
78
+ 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
79
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0
80
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 4 0 2 0 0 5 4
81
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 3 0 0 0 2 0 0
82
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 2 0 0 0 0 0 0 7 0 0
83
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 2
84
+ 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 3 0 0 0 0 0 0 0 0 4
85
+ 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 2
86
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 4 0 0 0 0 0 3 2
87
+ 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3
88
+ 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 7 0 0 2 0 0 0 4 4
89
+ 0 0 2 0 0 0 0 0 3 0 0 0 0 0 3 3 0 0 1 0 3 0 2 5 0 0 0 0 0 4 3 4 0 5
90
+ 0 0 0 0 0 0 0 0 4 2 0 0 0 3 2 4 0 0 2 1 1 0 3 4 0 0 2 4 2 2 3 4 5 0"""
91
+
92
+ for row, line in enumerate(zacharydat.split("\n")):
93
+ thisrow = [int(b) for b in line.split()]
94
+ for col, entry in enumerate(thisrow):
95
+ if entry >= 1:
96
+ G.add_edge(row, col, weight=entry)
97
+
98
+ # Add the name of each member's club as a node attribute.
99
+ for v in G:
100
+ G.nodes[v]["club"] = "Mr. Hi" if v in club1 else "Officer"
101
+ return G
102
+
103
+
104
+ @nx._dispatchable(graphs=None, returns_graph=True)
105
+ def davis_southern_women_graph():
106
+ """Returns Davis Southern women social network.
107
+
108
+ This is a bipartite graph.
109
+
110
+ References
111
+ ----------
112
+ .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.
113
+ University of Chicago Press, Chicago, IL.
114
+ """
115
+ G = nx.Graph()
116
+ # Top nodes
117
+ women = [
118
+ "Evelyn Jefferson",
119
+ "Laura Mandeville",
120
+ "Theresa Anderson",
121
+ "Brenda Rogers",
122
+ "Charlotte McDowd",
123
+ "Frances Anderson",
124
+ "Eleanor Nye",
125
+ "Pearl Oglethorpe",
126
+ "Ruth DeSand",
127
+ "Verne Sanderson",
128
+ "Myra Liddel",
129
+ "Katherina Rogers",
130
+ "Sylvia Avondale",
131
+ "Nora Fayette",
132
+ "Helen Lloyd",
133
+ "Dorothy Murchison",
134
+ "Olivia Carleton",
135
+ "Flora Price",
136
+ ]
137
+ G.add_nodes_from(women, bipartite=0)
138
+ # Bottom nodes
139
+ events = [
140
+ "E1",
141
+ "E2",
142
+ "E3",
143
+ "E4",
144
+ "E5",
145
+ "E6",
146
+ "E7",
147
+ "E8",
148
+ "E9",
149
+ "E10",
150
+ "E11",
151
+ "E12",
152
+ "E13",
153
+ "E14",
154
+ ]
155
+ G.add_nodes_from(events, bipartite=1)
156
+
157
+ G.add_edges_from(
158
+ [
159
+ ("Evelyn Jefferson", "E1"),
160
+ ("Evelyn Jefferson", "E2"),
161
+ ("Evelyn Jefferson", "E3"),
162
+ ("Evelyn Jefferson", "E4"),
163
+ ("Evelyn Jefferson", "E5"),
164
+ ("Evelyn Jefferson", "E6"),
165
+ ("Evelyn Jefferson", "E8"),
166
+ ("Evelyn Jefferson", "E9"),
167
+ ("Laura Mandeville", "E1"),
168
+ ("Laura Mandeville", "E2"),
169
+ ("Laura Mandeville", "E3"),
170
+ ("Laura Mandeville", "E5"),
171
+ ("Laura Mandeville", "E6"),
172
+ ("Laura Mandeville", "E7"),
173
+ ("Laura Mandeville", "E8"),
174
+ ("Theresa Anderson", "E2"),
175
+ ("Theresa Anderson", "E3"),
176
+ ("Theresa Anderson", "E4"),
177
+ ("Theresa Anderson", "E5"),
178
+ ("Theresa Anderson", "E6"),
179
+ ("Theresa Anderson", "E7"),
180
+ ("Theresa Anderson", "E8"),
181
+ ("Theresa Anderson", "E9"),
182
+ ("Brenda Rogers", "E1"),
183
+ ("Brenda Rogers", "E3"),
184
+ ("Brenda Rogers", "E4"),
185
+ ("Brenda Rogers", "E5"),
186
+ ("Brenda Rogers", "E6"),
187
+ ("Brenda Rogers", "E7"),
188
+ ("Brenda Rogers", "E8"),
189
+ ("Charlotte McDowd", "E3"),
190
+ ("Charlotte McDowd", "E4"),
191
+ ("Charlotte McDowd", "E5"),
192
+ ("Charlotte McDowd", "E7"),
193
+ ("Frances Anderson", "E3"),
194
+ ("Frances Anderson", "E5"),
195
+ ("Frances Anderson", "E6"),
196
+ ("Frances Anderson", "E8"),
197
+ ("Eleanor Nye", "E5"),
198
+ ("Eleanor Nye", "E6"),
199
+ ("Eleanor Nye", "E7"),
200
+ ("Eleanor Nye", "E8"),
201
+ ("Pearl Oglethorpe", "E6"),
202
+ ("Pearl Oglethorpe", "E8"),
203
+ ("Pearl Oglethorpe", "E9"),
204
+ ("Ruth DeSand", "E5"),
205
+ ("Ruth DeSand", "E7"),
206
+ ("Ruth DeSand", "E8"),
207
+ ("Ruth DeSand", "E9"),
208
+ ("Verne Sanderson", "E7"),
209
+ ("Verne Sanderson", "E8"),
210
+ ("Verne Sanderson", "E9"),
211
+ ("Verne Sanderson", "E12"),
212
+ ("Myra Liddel", "E8"),
213
+ ("Myra Liddel", "E9"),
214
+ ("Myra Liddel", "E10"),
215
+ ("Myra Liddel", "E12"),
216
+ ("Katherina Rogers", "E8"),
217
+ ("Katherina Rogers", "E9"),
218
+ ("Katherina Rogers", "E10"),
219
+ ("Katherina Rogers", "E12"),
220
+ ("Katherina Rogers", "E13"),
221
+ ("Katherina Rogers", "E14"),
222
+ ("Sylvia Avondale", "E7"),
223
+ ("Sylvia Avondale", "E8"),
224
+ ("Sylvia Avondale", "E9"),
225
+ ("Sylvia Avondale", "E10"),
226
+ ("Sylvia Avondale", "E12"),
227
+ ("Sylvia Avondale", "E13"),
228
+ ("Sylvia Avondale", "E14"),
229
+ ("Nora Fayette", "E6"),
230
+ ("Nora Fayette", "E7"),
231
+ ("Nora Fayette", "E9"),
232
+ ("Nora Fayette", "E10"),
233
+ ("Nora Fayette", "E11"),
234
+ ("Nora Fayette", "E12"),
235
+ ("Nora Fayette", "E13"),
236
+ ("Nora Fayette", "E14"),
237
+ ("Helen Lloyd", "E7"),
238
+ ("Helen Lloyd", "E8"),
239
+ ("Helen Lloyd", "E10"),
240
+ ("Helen Lloyd", "E11"),
241
+ ("Helen Lloyd", "E12"),
242
+ ("Dorothy Murchison", "E8"),
243
+ ("Dorothy Murchison", "E9"),
244
+ ("Olivia Carleton", "E9"),
245
+ ("Olivia Carleton", "E11"),
246
+ ("Flora Price", "E9"),
247
+ ("Flora Price", "E11"),
248
+ ]
249
+ )
250
+ G.graph["top"] = women
251
+ G.graph["bottom"] = events
252
+ return G
253
+
254
+
255
+ @nx._dispatchable(graphs=None, returns_graph=True)
256
+ def florentine_families_graph():
257
+ """Returns Florentine families graph.
258
+
259
+ References
260
+ ----------
261
+ .. [1] Ronald L. Breiger and Philippa E. Pattison
262
+ Cumulated social roles: The duality of persons and their algebras,1
263
+ Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
264
+ """
265
+ G = nx.Graph()
266
+ G.add_edge("Acciaiuoli", "Medici")
267
+ G.add_edge("Castellani", "Peruzzi")
268
+ G.add_edge("Castellani", "Strozzi")
269
+ G.add_edge("Castellani", "Barbadori")
270
+ G.add_edge("Medici", "Barbadori")
271
+ G.add_edge("Medici", "Ridolfi")
272
+ G.add_edge("Medici", "Tornabuoni")
273
+ G.add_edge("Medici", "Albizzi")
274
+ G.add_edge("Medici", "Salviati")
275
+ G.add_edge("Salviati", "Pazzi")
276
+ G.add_edge("Peruzzi", "Strozzi")
277
+ G.add_edge("Peruzzi", "Bischeri")
278
+ G.add_edge("Strozzi", "Ridolfi")
279
+ G.add_edge("Strozzi", "Bischeri")
280
+ G.add_edge("Ridolfi", "Tornabuoni")
281
+ G.add_edge("Tornabuoni", "Guadagni")
282
+ G.add_edge("Albizzi", "Ginori")
283
+ G.add_edge("Albizzi", "Guadagni")
284
+ G.add_edge("Bischeri", "Guadagni")
285
+ G.add_edge("Guadagni", "Lamberteschi")
286
+ return G
287
+
288
+
289
+ @nx._dispatchable(graphs=None, returns_graph=True)
290
+ def les_miserables_graph():
291
+ """Returns coappearance network of characters in the novel Les Miserables.
292
+
293
+ References
294
+ ----------
295
+ .. [1] D. E. Knuth, 1993.
296
+ The Stanford GraphBase: a platform for combinatorial computing,
297
+ pp. 74-87. New York: AcM Press.
298
+ """
299
+ G = nx.Graph()
300
+ G.add_edge("Napoleon", "Myriel", weight=1)
301
+ G.add_edge("MlleBaptistine", "Myriel", weight=8)
302
+ G.add_edge("MmeMagloire", "Myriel", weight=10)
303
+ G.add_edge("MmeMagloire", "MlleBaptistine", weight=6)
304
+ G.add_edge("CountessDeLo", "Myriel", weight=1)
305
+ G.add_edge("Geborand", "Myriel", weight=1)
306
+ G.add_edge("Champtercier", "Myriel", weight=1)
307
+ G.add_edge("Cravatte", "Myriel", weight=1)
308
+ G.add_edge("Count", "Myriel", weight=2)
309
+ G.add_edge("OldMan", "Myriel", weight=1)
310
+ G.add_edge("Valjean", "Labarre", weight=1)
311
+ G.add_edge("Valjean", "MmeMagloire", weight=3)
312
+ G.add_edge("Valjean", "MlleBaptistine", weight=3)
313
+ G.add_edge("Valjean", "Myriel", weight=5)
314
+ G.add_edge("Marguerite", "Valjean", weight=1)
315
+ G.add_edge("MmeDeR", "Valjean", weight=1)
316
+ G.add_edge("Isabeau", "Valjean", weight=1)
317
+ G.add_edge("Gervais", "Valjean", weight=1)
318
+ G.add_edge("Listolier", "Tholomyes", weight=4)
319
+ G.add_edge("Fameuil", "Tholomyes", weight=4)
320
+ G.add_edge("Fameuil", "Listolier", weight=4)
321
+ G.add_edge("Blacheville", "Tholomyes", weight=4)
322
+ G.add_edge("Blacheville", "Listolier", weight=4)
323
+ G.add_edge("Blacheville", "Fameuil", weight=4)
324
+ G.add_edge("Favourite", "Tholomyes", weight=3)
325
+ G.add_edge("Favourite", "Listolier", weight=3)
326
+ G.add_edge("Favourite", "Fameuil", weight=3)
327
+ G.add_edge("Favourite", "Blacheville", weight=4)
328
+ G.add_edge("Dahlia", "Tholomyes", weight=3)
329
+ G.add_edge("Dahlia", "Listolier", weight=3)
330
+ G.add_edge("Dahlia", "Fameuil", weight=3)
331
+ G.add_edge("Dahlia", "Blacheville", weight=3)
332
+ G.add_edge("Dahlia", "Favourite", weight=5)
333
+ G.add_edge("Zephine", "Tholomyes", weight=3)
334
+ G.add_edge("Zephine", "Listolier", weight=3)
335
+ G.add_edge("Zephine", "Fameuil", weight=3)
336
+ G.add_edge("Zephine", "Blacheville", weight=3)
337
+ G.add_edge("Zephine", "Favourite", weight=4)
338
+ G.add_edge("Zephine", "Dahlia", weight=4)
339
+ G.add_edge("Fantine", "Tholomyes", weight=3)
340
+ G.add_edge("Fantine", "Listolier", weight=3)
341
+ G.add_edge("Fantine", "Fameuil", weight=3)
342
+ G.add_edge("Fantine", "Blacheville", weight=3)
343
+ G.add_edge("Fantine", "Favourite", weight=4)
344
+ G.add_edge("Fantine", "Dahlia", weight=4)
345
+ G.add_edge("Fantine", "Zephine", weight=4)
346
+ G.add_edge("Fantine", "Marguerite", weight=2)
347
+ G.add_edge("Fantine", "Valjean", weight=9)
348
+ G.add_edge("MmeThenardier", "Fantine", weight=2)
349
+ G.add_edge("MmeThenardier", "Valjean", weight=7)
350
+ G.add_edge("Thenardier", "MmeThenardier", weight=13)
351
+ G.add_edge("Thenardier", "Fantine", weight=1)
352
+ G.add_edge("Thenardier", "Valjean", weight=12)
353
+ G.add_edge("Cosette", "MmeThenardier", weight=4)
354
+ G.add_edge("Cosette", "Valjean", weight=31)
355
+ G.add_edge("Cosette", "Tholomyes", weight=1)
356
+ G.add_edge("Cosette", "Thenardier", weight=1)
357
+ G.add_edge("Javert", "Valjean", weight=17)
358
+ G.add_edge("Javert", "Fantine", weight=5)
359
+ G.add_edge("Javert", "Thenardier", weight=5)
360
+ G.add_edge("Javert", "MmeThenardier", weight=1)
361
+ G.add_edge("Javert", "Cosette", weight=1)
362
+ G.add_edge("Fauchelevent", "Valjean", weight=8)
363
+ G.add_edge("Fauchelevent", "Javert", weight=1)
364
+ G.add_edge("Bamatabois", "Fantine", weight=1)
365
+ G.add_edge("Bamatabois", "Javert", weight=1)
366
+ G.add_edge("Bamatabois", "Valjean", weight=2)
367
+ G.add_edge("Perpetue", "Fantine", weight=1)
368
+ G.add_edge("Simplice", "Perpetue", weight=2)
369
+ G.add_edge("Simplice", "Valjean", weight=3)
370
+ G.add_edge("Simplice", "Fantine", weight=2)
371
+ G.add_edge("Simplice", "Javert", weight=1)
372
+ G.add_edge("Scaufflaire", "Valjean", weight=1)
373
+ G.add_edge("Woman1", "Valjean", weight=2)
374
+ G.add_edge("Woman1", "Javert", weight=1)
375
+ G.add_edge("Judge", "Valjean", weight=3)
376
+ G.add_edge("Judge", "Bamatabois", weight=2)
377
+ G.add_edge("Champmathieu", "Valjean", weight=3)
378
+ G.add_edge("Champmathieu", "Judge", weight=3)
379
+ G.add_edge("Champmathieu", "Bamatabois", weight=2)
380
+ G.add_edge("Brevet", "Judge", weight=2)
381
+ G.add_edge("Brevet", "Champmathieu", weight=2)
382
+ G.add_edge("Brevet", "Valjean", weight=2)
383
+ G.add_edge("Brevet", "Bamatabois", weight=1)
384
+ G.add_edge("Chenildieu", "Judge", weight=2)
385
+ G.add_edge("Chenildieu", "Champmathieu", weight=2)
386
+ G.add_edge("Chenildieu", "Brevet", weight=2)
387
+ G.add_edge("Chenildieu", "Valjean", weight=2)
388
+ G.add_edge("Chenildieu", "Bamatabois", weight=1)
389
+ G.add_edge("Cochepaille", "Judge", weight=2)
390
+ G.add_edge("Cochepaille", "Champmathieu", weight=2)
391
+ G.add_edge("Cochepaille", "Brevet", weight=2)
392
+ G.add_edge("Cochepaille", "Chenildieu", weight=2)
393
+ G.add_edge("Cochepaille", "Valjean", weight=2)
394
+ G.add_edge("Cochepaille", "Bamatabois", weight=1)
395
+ G.add_edge("Pontmercy", "Thenardier", weight=1)
396
+ G.add_edge("Boulatruelle", "Thenardier", weight=1)
397
+ G.add_edge("Eponine", "MmeThenardier", weight=2)
398
+ G.add_edge("Eponine", "Thenardier", weight=3)
399
+ G.add_edge("Anzelma", "Eponine", weight=2)
400
+ G.add_edge("Anzelma", "Thenardier", weight=2)
401
+ G.add_edge("Anzelma", "MmeThenardier", weight=1)
402
+ G.add_edge("Woman2", "Valjean", weight=3)
403
+ G.add_edge("Woman2", "Cosette", weight=1)
404
+ G.add_edge("Woman2", "Javert", weight=1)
405
+ G.add_edge("MotherInnocent", "Fauchelevent", weight=3)
406
+ G.add_edge("MotherInnocent", "Valjean", weight=1)
407
+ G.add_edge("Gribier", "Fauchelevent", weight=2)
408
+ G.add_edge("MmeBurgon", "Jondrette", weight=1)
409
+ G.add_edge("Gavroche", "MmeBurgon", weight=2)
410
+ G.add_edge("Gavroche", "Thenardier", weight=1)
411
+ G.add_edge("Gavroche", "Javert", weight=1)
412
+ G.add_edge("Gavroche", "Valjean", weight=1)
413
+ G.add_edge("Gillenormand", "Cosette", weight=3)
414
+ G.add_edge("Gillenormand", "Valjean", weight=2)
415
+ G.add_edge("Magnon", "Gillenormand", weight=1)
416
+ G.add_edge("Magnon", "MmeThenardier", weight=1)
417
+ G.add_edge("MlleGillenormand", "Gillenormand", weight=9)
418
+ G.add_edge("MlleGillenormand", "Cosette", weight=2)
419
+ G.add_edge("MlleGillenormand", "Valjean", weight=2)
420
+ G.add_edge("MmePontmercy", "MlleGillenormand", weight=1)
421
+ G.add_edge("MmePontmercy", "Pontmercy", weight=1)
422
+ G.add_edge("MlleVaubois", "MlleGillenormand", weight=1)
423
+ G.add_edge("LtGillenormand", "MlleGillenormand", weight=2)
424
+ G.add_edge("LtGillenormand", "Gillenormand", weight=1)
425
+ G.add_edge("LtGillenormand", "Cosette", weight=1)
426
+ G.add_edge("Marius", "MlleGillenormand", weight=6)
427
+ G.add_edge("Marius", "Gillenormand", weight=12)
428
+ G.add_edge("Marius", "Pontmercy", weight=1)
429
+ G.add_edge("Marius", "LtGillenormand", weight=1)
430
+ G.add_edge("Marius", "Cosette", weight=21)
431
+ G.add_edge("Marius", "Valjean", weight=19)
432
+ G.add_edge("Marius", "Tholomyes", weight=1)
433
+ G.add_edge("Marius", "Thenardier", weight=2)
434
+ G.add_edge("Marius", "Eponine", weight=5)
435
+ G.add_edge("Marius", "Gavroche", weight=4)
436
+ G.add_edge("BaronessT", "Gillenormand", weight=1)
437
+ G.add_edge("BaronessT", "Marius", weight=1)
438
+ G.add_edge("Mabeuf", "Marius", weight=1)
439
+ G.add_edge("Mabeuf", "Eponine", weight=1)
440
+ G.add_edge("Mabeuf", "Gavroche", weight=1)
441
+ G.add_edge("Enjolras", "Marius", weight=7)
442
+ G.add_edge("Enjolras", "Gavroche", weight=7)
443
+ G.add_edge("Enjolras", "Javert", weight=6)
444
+ G.add_edge("Enjolras", "Mabeuf", weight=1)
445
+ G.add_edge("Enjolras", "Valjean", weight=4)
446
+ G.add_edge("Combeferre", "Enjolras", weight=15)
447
+ G.add_edge("Combeferre", "Marius", weight=5)
448
+ G.add_edge("Combeferre", "Gavroche", weight=6)
449
+ G.add_edge("Combeferre", "Mabeuf", weight=2)
450
+ G.add_edge("Prouvaire", "Gavroche", weight=1)
451
+ G.add_edge("Prouvaire", "Enjolras", weight=4)
452
+ G.add_edge("Prouvaire", "Combeferre", weight=2)
453
+ G.add_edge("Feuilly", "Gavroche", weight=2)
454
+ G.add_edge("Feuilly", "Enjolras", weight=6)
455
+ G.add_edge("Feuilly", "Prouvaire", weight=2)
456
+ G.add_edge("Feuilly", "Combeferre", weight=5)
457
+ G.add_edge("Feuilly", "Mabeuf", weight=1)
458
+ G.add_edge("Feuilly", "Marius", weight=1)
459
+ G.add_edge("Courfeyrac", "Marius", weight=9)
460
+ G.add_edge("Courfeyrac", "Enjolras", weight=17)
461
+ G.add_edge("Courfeyrac", "Combeferre", weight=13)
462
+ G.add_edge("Courfeyrac", "Gavroche", weight=7)
463
+ G.add_edge("Courfeyrac", "Mabeuf", weight=2)
464
+ G.add_edge("Courfeyrac", "Eponine", weight=1)
465
+ G.add_edge("Courfeyrac", "Feuilly", weight=6)
466
+ G.add_edge("Courfeyrac", "Prouvaire", weight=3)
467
+ G.add_edge("Bahorel", "Combeferre", weight=5)
468
+ G.add_edge("Bahorel", "Gavroche", weight=5)
469
+ G.add_edge("Bahorel", "Courfeyrac", weight=6)
470
+ G.add_edge("Bahorel", "Mabeuf", weight=2)
471
+ G.add_edge("Bahorel", "Enjolras", weight=4)
472
+ G.add_edge("Bahorel", "Feuilly", weight=3)
473
+ G.add_edge("Bahorel", "Prouvaire", weight=2)
474
+ G.add_edge("Bahorel", "Marius", weight=1)
475
+ G.add_edge("Bossuet", "Marius", weight=5)
476
+ G.add_edge("Bossuet", "Courfeyrac", weight=12)
477
+ G.add_edge("Bossuet", "Gavroche", weight=5)
478
+ G.add_edge("Bossuet", "Bahorel", weight=4)
479
+ G.add_edge("Bossuet", "Enjolras", weight=10)
480
+ G.add_edge("Bossuet", "Feuilly", weight=6)
481
+ G.add_edge("Bossuet", "Prouvaire", weight=2)
482
+ G.add_edge("Bossuet", "Combeferre", weight=9)
483
+ G.add_edge("Bossuet", "Mabeuf", weight=1)
484
+ G.add_edge("Bossuet", "Valjean", weight=1)
485
+ G.add_edge("Joly", "Bahorel", weight=5)
486
+ G.add_edge("Joly", "Bossuet", weight=7)
487
+ G.add_edge("Joly", "Gavroche", weight=3)
488
+ G.add_edge("Joly", "Courfeyrac", weight=5)
489
+ G.add_edge("Joly", "Enjolras", weight=5)
490
+ G.add_edge("Joly", "Feuilly", weight=5)
491
+ G.add_edge("Joly", "Prouvaire", weight=2)
492
+ G.add_edge("Joly", "Combeferre", weight=5)
493
+ G.add_edge("Joly", "Mabeuf", weight=1)
494
+ G.add_edge("Joly", "Marius", weight=2)
495
+ G.add_edge("Grantaire", "Bossuet", weight=3)
496
+ G.add_edge("Grantaire", "Enjolras", weight=3)
497
+ G.add_edge("Grantaire", "Combeferre", weight=1)
498
+ G.add_edge("Grantaire", "Courfeyrac", weight=2)
499
+ G.add_edge("Grantaire", "Joly", weight=2)
500
+ G.add_edge("Grantaire", "Gavroche", weight=1)
501
+ G.add_edge("Grantaire", "Bahorel", weight=1)
502
+ G.add_edge("Grantaire", "Feuilly", weight=1)
503
+ G.add_edge("Grantaire", "Prouvaire", weight=1)
504
+ G.add_edge("MotherPlutarch", "Mabeuf", weight=3)
505
+ G.add_edge("Gueulemer", "Thenardier", weight=5)
506
+ G.add_edge("Gueulemer", "Valjean", weight=1)
507
+ G.add_edge("Gueulemer", "MmeThenardier", weight=1)
508
+ G.add_edge("Gueulemer", "Javert", weight=1)
509
+ G.add_edge("Gueulemer", "Gavroche", weight=1)
510
+ G.add_edge("Gueulemer", "Eponine", weight=1)
511
+ G.add_edge("Babet", "Thenardier", weight=6)
512
+ G.add_edge("Babet", "Gueulemer", weight=6)
513
+ G.add_edge("Babet", "Valjean", weight=1)
514
+ G.add_edge("Babet", "MmeThenardier", weight=1)
515
+ G.add_edge("Babet", "Javert", weight=2)
516
+ G.add_edge("Babet", "Gavroche", weight=1)
517
+ G.add_edge("Babet", "Eponine", weight=1)
518
+ G.add_edge("Claquesous", "Thenardier", weight=4)
519
+ G.add_edge("Claquesous", "Babet", weight=4)
520
+ G.add_edge("Claquesous", "Gueulemer", weight=4)
521
+ G.add_edge("Claquesous", "Valjean", weight=1)
522
+ G.add_edge("Claquesous", "MmeThenardier", weight=1)
523
+ G.add_edge("Claquesous", "Javert", weight=1)
524
+ G.add_edge("Claquesous", "Eponine", weight=1)
525
+ G.add_edge("Claquesous", "Enjolras", weight=1)
526
+ G.add_edge("Montparnasse", "Javert", weight=1)
527
+ G.add_edge("Montparnasse", "Babet", weight=2)
528
+ G.add_edge("Montparnasse", "Gueulemer", weight=2)
529
+ G.add_edge("Montparnasse", "Claquesous", weight=2)
530
+ G.add_edge("Montparnasse", "Valjean", weight=1)
531
+ G.add_edge("Montparnasse", "Gavroche", weight=1)
532
+ G.add_edge("Montparnasse", "Eponine", weight=1)
533
+ G.add_edge("Montparnasse", "Thenardier", weight=1)
534
+ G.add_edge("Toussaint", "Cosette", weight=2)
535
+ G.add_edge("Toussaint", "Javert", weight=1)
536
+ G.add_edge("Toussaint", "Valjean", weight=1)
537
+ G.add_edge("Child1", "Gavroche", weight=2)
538
+ G.add_edge("Child2", "Gavroche", weight=2)
539
+ G.add_edge("Child2", "Child1", weight=3)
540
+ G.add_edge("Brujon", "Babet", weight=3)
541
+ G.add_edge("Brujon", "Gueulemer", weight=3)
542
+ G.add_edge("Brujon", "Thenardier", weight=3)
543
+ G.add_edge("Brujon", "Gavroche", weight=1)
544
+ G.add_edge("Brujon", "Eponine", weight=1)
545
+ G.add_edge("Brujon", "Claquesous", weight=1)
546
+ G.add_edge("Brujon", "Montparnasse", weight=1)
547
+ G.add_edge("MmeHucheloup", "Bossuet", weight=1)
548
+ G.add_edge("MmeHucheloup", "Joly", weight=1)
549
+ G.add_edge("MmeHucheloup", "Grantaire", weight=1)
550
+ G.add_edge("MmeHucheloup", "Bahorel", weight=1)
551
+ G.add_edge("MmeHucheloup", "Courfeyrac", weight=1)
552
+ G.add_edge("MmeHucheloup", "Gavroche", weight=1)
553
+ G.add_edge("MmeHucheloup", "Enjolras", weight=1)
554
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/spectral_graph_forge.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates graphs with a given eigenvector structure"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import np_random_state
5
+
6
+ __all__ = ["spectral_graph_forge"]
7
+
8
+
9
+ @np_random_state(3)
10
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}}, returns_graph=True)
11
+ def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
12
+ """Returns a random simple graph with spectrum resembling that of `G`
13
+
14
+ This algorithm, called Spectral Graph Forge (SGF), computes the
15
+ eigenvectors of a given graph adjacency matrix, filters them and
16
+ builds a random graph with a similar eigenstructure.
17
+ SGF has been proved to be particularly useful for synthesizing
18
+ realistic social networks and it can also be used to anonymize
19
+ graph sensitive data.
20
+
21
+ Parameters
22
+ ----------
23
+ G : Graph
24
+ alpha : float
25
+ Ratio representing the percentage of eigenvectors of G to consider,
26
+ values in [0,1].
27
+ transformation : string, optional
28
+ Represents the intended matrix linear transformation, possible values
29
+ are 'identity' and 'modularity'
30
+ seed : integer, random_state, or None (default)
31
+ Indicator of numpy random number generation state.
32
+ See :ref:`Randomness<randomness>`.
33
+
34
+ Returns
35
+ -------
36
+ H : Graph
37
+ A graph with a similar eigenvector structure of the input one.
38
+
39
+ Raises
40
+ ------
41
+ NetworkXError
42
+ If transformation has a value different from 'identity' or 'modularity'
43
+
44
+ Notes
45
+ -----
46
+ Spectral Graph Forge (SGF) generates a random simple graph resembling the
47
+ global properties of the given one.
48
+ It leverages the low-rank approximation of the associated adjacency matrix
49
+ driven by the *alpha* precision parameter.
50
+ SGF preserves the number of nodes of the input graph and their ordering.
51
+ This way, nodes of output graphs resemble the properties of the input one
52
+ and attributes can be directly mapped.
53
+
54
+ It considers the graph adjacency matrices which can optionally be
55
+ transformed to other symmetric real matrices (currently transformation
56
+ options include *identity* and *modularity*).
57
+ The *modularity* transformation, in the sense of Newman's modularity matrix
58
+ allows the focusing on community structure related properties of the graph.
59
+
60
+ SGF applies a low-rank approximation whose fixed rank is computed from the
61
+ ratio *alpha* of the input graph adjacency matrix dimension.
62
+ This step performs a filtering on the input eigenvectors similar to the low
63
+ pass filtering common in telecommunications.
64
+
65
+ The filtered values (after truncation) are used as input to a Bernoulli
66
+ sampling for constructing a random adjacency matrix.
67
+
68
+ References
69
+ ----------
70
+ .. [1] L. Baldesi, C. T. Butts, A. Markopoulou, "Spectral Graph Forge:
71
+ Graph Generation Targeting Modularity", IEEE Infocom, '18.
72
+ https://arxiv.org/abs/1801.01715
73
+ .. [2] M. Newman, "Networks: an introduction", Oxford university press,
74
+ 2010
75
+
76
+ Examples
77
+ --------
78
+ >>> G = nx.karate_club_graph()
79
+ >>> H = nx.spectral_graph_forge(G, 0.3)
80
+ >>>
81
+ """
82
+ import numpy as np
83
+ import scipy as sp
84
+
85
+ available_transformations = ["identity", "modularity"]
86
+ alpha = np.clip(alpha, 0, 1)
87
+ A = nx.to_numpy_array(G)
88
+ n = A.shape[1]
89
+ level = round(n * alpha)
90
+
91
+ if transformation not in available_transformations:
92
+ msg = f"{transformation!r} is not a valid transformation. "
93
+ msg += f"Transformations: {available_transformations}"
94
+ raise nx.NetworkXError(msg)
95
+
96
+ K = np.ones((1, n)) @ A
97
+
98
+ B = A
99
+ if transformation == "modularity":
100
+ B -= K.T @ K / K.sum()
101
+
102
+ # Compute low-rank approximation of B
103
+ evals, evecs = np.linalg.eigh(B)
104
+ k = np.argsort(np.abs(evals))[::-1] # indices of evals in descending order
105
+ evecs[:, k[np.arange(level, n)]] = 0 # set smallest eigenvectors to 0
106
+ B = evecs @ np.diag(evals) @ evecs.T
107
+
108
+ if transformation == "modularity":
109
+ B += K.T @ K / K.sum()
110
+
111
+ B = np.clip(B, 0, 1)
112
+ np.fill_diagonal(B, 0)
113
+
114
+ for i in range(n - 1):
115
+ B[i, i + 1 :] = sp.stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed)
116
+ B[i + 1 :, i] = np.transpose(B[i, i + 1 :])
117
+
118
+ H = nx.from_numpy_array(B)
119
+
120
+ return H
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/stochastic.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating stochastic graphs from a given weighted directed
2
+ graph.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.classes import DiGraph, MultiDiGraph
8
+ from networkx.utils import not_implemented_for
9
+
10
+ __all__ = ["stochastic_graph"]
11
+
12
+
13
+ @not_implemented_for("undirected")
14
+ @nx._dispatchable(
15
+ edge_attrs="weight", mutates_input={"not copy": 1}, returns_graph=True
16
+ )
17
+ def stochastic_graph(G, copy=True, weight="weight"):
18
+ """Returns a right-stochastic representation of directed graph `G`.
19
+
20
+ A right-stochastic graph is a weighted digraph in which for each
21
+ node, the sum of the weights of all the out-edges of that node is
22
+ 1. If the graph is already weighted (for example, via a 'weight'
23
+ edge attribute), the reweighting takes that into account.
24
+
25
+ Parameters
26
+ ----------
27
+ G : directed graph
28
+ A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.
29
+
30
+ copy : boolean, optional
31
+ If this is True, then this function returns a new graph with
32
+ the stochastic reweighting. Otherwise, the original graph is
33
+ modified in-place (and also returned, for convenience).
34
+
35
+ weight : edge attribute key (optional, default='weight')
36
+ Edge attribute key used for reading the existing weight and
37
+ setting the new weight. If no attribute with this key is found
38
+ for an edge, then the edge weight is assumed to be 1. If an edge
39
+ has a weight, it must be a positive number.
40
+
41
+ """
42
+ if copy:
43
+ G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
44
+ # There is a tradeoff here: the dictionary of node degrees may
45
+ # require a lot of memory, whereas making a call to `G.out_degree`
46
+ # inside the loop may be costly in computation time.
47
+ degree = dict(G.out_degree(weight=weight))
48
+ for u, v, d in G.edges(data=True):
49
+ if degree[u] == 0:
50
+ d[weight] = 0
51
+ else:
52
+ d[weight] = d.get(weight, 1) / degree[u]
53
+ nx._clear_cache(G)
54
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/sudoku.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generator for Sudoku graphs
2
+
3
+ This module gives a generator for n-Sudoku graphs. It can be used to develop
4
+ algorithms for solving or generating Sudoku puzzles.
5
+
6
+ A completed Sudoku grid is a 9x9 array of integers between 1 and 9, with no
7
+ number appearing twice in the same row, column, or 3x3 box.
8
+
9
+ +---------+---------+---------+
10
+ | | 8 6 4 | | 3 7 1 | | 2 5 9 |
11
+ | | 3 2 5 | | 8 4 9 | | 7 6 1 |
12
+ | | 9 7 1 | | 2 6 5 | | 8 4 3 |
13
+ +---------+---------+---------+
14
+ | | 4 3 6 | | 1 9 2 | | 5 8 7 |
15
+ | | 1 9 8 | | 6 5 7 | | 4 3 2 |
16
+ | | 2 5 7 | | 4 8 3 | | 9 1 6 |
17
+ +---------+---------+---------+
18
+ | | 6 8 9 | | 7 3 4 | | 1 2 5 |
19
+ | | 7 1 3 | | 5 2 8 | | 6 9 4 |
20
+ | | 5 4 2 | | 9 1 6 | | 3 7 8 |
21
+ +---------+---------+---------+
22
+
23
+
24
+ The Sudoku graph is an undirected graph with 81 vertices, corresponding to
25
+ the cells of a Sudoku grid. It is a regular graph of degree 20. Two distinct
26
+ vertices are adjacent if and only if the corresponding cells belong to the
27
+ same row, column, or box. A completed Sudoku grid corresponds to a vertex
28
+ coloring of the Sudoku graph with nine colors.
29
+
30
+ More generally, the n-Sudoku graph is a graph with n^4 vertices, corresponding
31
+ to the cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
32
+ only if they belong to the same row, column, or n by n box.
33
+
34
+ References
35
+ ----------
36
+ .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
37
+ polynomials. Notices of the AMS, 54(6), 708-717.
38
+ .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
39
+ Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
40
+ .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
41
+ Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
42
+ """
43
+
44
+ import networkx as nx
45
+ from networkx.exception import NetworkXError
46
+
47
+ __all__ = ["sudoku_graph"]
48
+
49
+
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def sudoku_graph(n=3):
52
+ """Returns the n-Sudoku graph. The default value of n is 3.
53
+
54
+ The n-Sudoku graph is a graph with n^4 vertices, corresponding to the
55
+ cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
56
+ only if they belong to the same row, column, or n-by-n box.
57
+
58
+ Parameters
59
+ ----------
60
+ n: integer
61
+ The order of the Sudoku graph, equal to the square root of the
62
+ number of rows. The default is 3.
63
+
64
+ Returns
65
+ -------
66
+ NetworkX graph
67
+ The n-Sudoku graph Sud(n).
68
+
69
+ Examples
70
+ --------
71
+ >>> G = nx.sudoku_graph()
72
+ >>> G.number_of_nodes()
73
+ 81
74
+ >>> G.number_of_edges()
75
+ 810
76
+ >>> sorted(G.neighbors(42))
77
+ [6, 15, 24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 51, 52, 53, 60, 69, 78]
78
+ >>> G = nx.sudoku_graph(2)
79
+ >>> G.number_of_nodes()
80
+ 16
81
+ >>> G.number_of_edges()
82
+ 56
83
+
84
+ References
85
+ ----------
86
+ .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
87
+ polynomials. Notices of the AMS, 54(6), 708-717.
88
+ .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
89
+ Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
90
+ .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
91
+ Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
92
+ """
93
+
94
+ if n < 0:
95
+ raise NetworkXError("The order must be greater than or equal to zero.")
96
+
97
+ n2 = n * n
98
+ n3 = n2 * n
99
+ n4 = n3 * n
100
+
101
+ # Construct an empty graph with n^4 nodes
102
+ G = nx.empty_graph(n4)
103
+
104
+ # A Sudoku graph of order 0 or 1 has no edges
105
+ if n < 2:
106
+ return G
107
+
108
+ # Add edges for cells in the same row
109
+ for row_no in range(n2):
110
+ row_start = row_no * n2
111
+ for j in range(1, n2):
112
+ for i in range(j):
113
+ G.add_edge(row_start + i, row_start + j)
114
+
115
+ # Add edges for cells in the same column
116
+ for col_no in range(n2):
117
+ for j in range(col_no, n4, n2):
118
+ for i in range(col_no, j, n2):
119
+ G.add_edge(i, j)
120
+
121
+ # Add edges for cells in the same box
122
+ for band_no in range(n):
123
+ for stack_no in range(n):
124
+ box_start = n3 * band_no + n * stack_no
125
+ for j in range(1, n2):
126
+ for i in range(j):
127
+ u = box_start + (i % n) + n2 * (i // n)
128
+ v = box_start + (j % n) + n2 * (j // n)
129
+ G.add_edge(u, v)
130
+
131
+ return G
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/tests/__init__.py ADDED
File without changes
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/tests/test_atlas.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import groupby
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx import graph_atlas, graph_atlas_g
7
+ from networkx.generators.atlas import NUM_GRAPHS
8
+ from networkx.utils import edges_equal, nodes_equal, pairwise
9
+
10
+
11
+ class TestAtlasGraph:
12
+ """Unit tests for the :func:`~networkx.graph_atlas` function."""
13
+
14
+ def test_index_too_small(self):
15
+ with pytest.raises(ValueError):
16
+ graph_atlas(-1)
17
+
18
+ def test_index_too_large(self):
19
+ with pytest.raises(ValueError):
20
+ graph_atlas(NUM_GRAPHS)
21
+
22
+ def test_graph(self):
23
+ G = graph_atlas(6)
24
+ assert nodes_equal(G.nodes(), range(3))
25
+ assert edges_equal(G.edges(), [(0, 1), (0, 2)])
26
+
27
+
28
+ class TestAtlasGraphG:
29
+ """Unit tests for the :func:`~networkx.graph_atlas_g` function."""
30
+
31
+ @classmethod
32
+ def setup_class(cls):
33
+ cls.GAG = graph_atlas_g()
34
+
35
+ def test_sizes(self):
36
+ G = self.GAG[0]
37
+ assert G.number_of_nodes() == 0
38
+ assert G.number_of_edges() == 0
39
+
40
+ G = self.GAG[7]
41
+ assert G.number_of_nodes() == 3
42
+ assert G.number_of_edges() == 3
43
+
44
+ def test_names(self):
45
+ for i, G in enumerate(self.GAG):
46
+ assert int(G.name[1:]) == i
47
+
48
+ def test_nondecreasing_nodes(self):
49
+ # check for nondecreasing number of nodes
50
+ for n1, n2 in pairwise(map(len, self.GAG)):
51
+ assert n2 <= n1 + 1
52
+
53
+ def test_nondecreasing_edges(self):
54
+ # check for nondecreasing number of edges (for fixed number of
55
+ # nodes)
56
+ for n, group in groupby(self.GAG, key=nx.number_of_nodes):
57
+ for m1, m2 in pairwise(map(nx.number_of_edges, group)):
58
+ assert m2 <= m1 + 1
59
+
60
+ def test_nondecreasing_degree_sequence(self):
61
+ # Check for lexicographically nondecreasing degree sequences
62
+ # (for fixed number of nodes and edges).
63
+ #
64
+ # There are three exceptions to this rule in the order given in
65
+ # the "Atlas of Graphs" book, so we need to manually exclude
66
+ # those.
67
+ exceptions = [("G55", "G56"), ("G1007", "G1008"), ("G1012", "G1013")]
68
+ for n, group in groupby(self.GAG, key=nx.number_of_nodes):
69
+ for m, group in groupby(group, key=nx.number_of_edges):
70
+ for G1, G2 in pairwise(group):
71
+ if (G1.name, G2.name) in exceptions:
72
+ continue
73
+ d1 = sorted(d for v, d in G1.degree())
74
+ d2 = sorted(d for v, d in G2.degree())
75
+ assert d1 <= d2
pace_revision_2/.venv-pace/lib/python3.11/site-packages/networkx/generators/tests/test_classic.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ====================
3
+ Generators - Classic
4
+ ====================
5
+
6
+ Unit tests for various classic graph generators in generators/classic.py
7
+ """
8
+
9
+ import itertools
10
+ import typing
11
+
12
+ import pytest
13
+
14
+ import networkx as nx
15
+ from networkx.utils import edges_equal, nodes_equal
16
+
17
+
18
+ class TestGeneratorClassic:
19
+ def test_balanced_tree(self):
20
+ # balanced_tree(r,h) is a tree with (r**(h+1)-1)/(r-1) edges
21
+ for r, h in [(2, 2), (3, 3), (6, 2)]:
22
+ t = nx.balanced_tree(r, h)
23
+ order = t.order()
24
+ assert order == (r ** (h + 1) - 1) / (r - 1)
25
+ assert nx.is_connected(t)
26
+ assert t.size() == order - 1
27
+ dh = nx.degree_histogram(t)
28
+ assert dh[0] == 0 # no nodes of 0
29
+ assert dh[1] == r**h # nodes of degree 1 are leaves
30
+ assert dh[r] == 1 # root is degree r
31
+ assert dh[r + 1] == order - r**h - 1 # everyone else is degree r+1
32
+ assert len(dh) == r + 2
33
+
34
+ def test_balanced_tree_star(self):
35
+ # balanced_tree(r,1) is the r-star
36
+ t = nx.balanced_tree(r=2, h=1)
37
+ assert nx.could_be_isomorphic(t, nx.star_graph(2))
38
+ t = nx.balanced_tree(r=5, h=1)
39
+ assert nx.could_be_isomorphic(t, nx.star_graph(5))
40
+ t = nx.balanced_tree(r=10, h=1)
41
+ assert nx.could_be_isomorphic(t, nx.star_graph(10))
42
+
43
+ def test_balanced_tree_path(self):
44
+ """Tests that the balanced tree with branching factor one is the
45
+ path graph.
46
+
47
+ """
48
+ # A tree of height four has five levels.
49
+ T = nx.balanced_tree(1, 4)
50
+ P = nx.path_graph(5)
51
+ assert nx.could_be_isomorphic(T, P)
52
+
53
+ def test_full_rary_tree(self):
54
+ r = 2
55
+ n = 9
56
+ t = nx.full_rary_tree(r, n)
57
+ assert t.order() == n
58
+ assert nx.is_connected(t)
59
+ dh = nx.degree_histogram(t)
60
+ assert dh[0] == 0 # no nodes of 0
61
+ assert dh[1] == 5 # nodes of degree 1 are leaves
62
+ assert dh[r] == 1 # root is degree r
63
+ assert dh[r + 1] == 9 - 5 - 1 # everyone else is degree r+1
64
+ assert len(dh) == r + 2
65
+
66
+ def test_full_rary_tree_balanced(self):
67
+ t = nx.full_rary_tree(2, 15)
68
+ th = nx.balanced_tree(2, 3)
69
+ assert nx.could_be_isomorphic(t, th)
70
+
71
+ def test_full_rary_tree_path(self):
72
+ t = nx.full_rary_tree(1, 10)
73
+ assert nx.could_be_isomorphic(t, nx.path_graph(10))
74
+
75
+ def test_full_rary_tree_empty(self):
76
+ t = nx.full_rary_tree(0, 10)
77
+ assert nx.could_be_isomorphic(t, nx.empty_graph(10))
78
+ t = nx.full_rary_tree(3, 0)
79
+ assert nx.could_be_isomorphic(t, nx.empty_graph(0))
80
+
81
+ def test_full_rary_tree_3_20(self):
82
+ t = nx.full_rary_tree(3, 20)
83
+ assert t.order() == 20
84
+
85
+ def test_barbell_graph(self):
86
+ # number of nodes = 2*m1 + m2 (2 m1-complete graphs + m2-path + 2 edges)
87
+ # number of edges = 2*(nx.number_of_edges(m1-complete graph) + m2 + 1
88
+ m1 = 3
89
+ m2 = 5
90
+ b = nx.barbell_graph(m1, m2)
91
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
92
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
93
+
94
+ m1 = 4
95
+ m2 = 10
96
+ b = nx.barbell_graph(m1, m2)
97
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
98
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
99
+
100
+ m1 = 3
101
+ m2 = 20
102
+ b = nx.barbell_graph(m1, m2)
103
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
104
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
105
+
106
+ # Raise NetworkXError if m1<2
107
+ m1 = 1
108
+ m2 = 20
109
+ pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
110
+
111
+ # Raise NetworkXError if m2<0
112
+ m1 = 5
113
+ m2 = -2
114
+ pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
115
+
116
+ # nx.barbell_graph(2,m) = nx.path_graph(m+4)
117
+ m1 = 2
118
+ m2 = 5
119
+ b = nx.barbell_graph(m1, m2)
120
+ assert nx.could_be_isomorphic(b, nx.path_graph(m2 + 4))
121
+
122
+ m1 = 2
123
+ m2 = 10
124
+ b = nx.barbell_graph(m1, m2)
125
+ assert nx.could_be_isomorphic(b, nx.path_graph(m2 + 4))
126
+
127
+ m1 = 2
128
+ m2 = 20
129
+ b = nx.barbell_graph(m1, m2)
130
+ assert nx.could_be_isomorphic(b, nx.path_graph(m2 + 4))
131
+
132
+ pytest.raises(
133
+ nx.NetworkXError, nx.barbell_graph, m1, m2, create_using=nx.DiGraph()
134
+ )
135
+
136
+ mb = nx.barbell_graph(m1, m2, create_using=nx.MultiGraph())
137
+ assert edges_equal(mb.edges(), b.edges())
138
+
139
+ def test_binomial_tree(self):
140
+ graphs = (None, nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
141
+ for create_using in graphs:
142
+ for n in range(4):
143
+ b = nx.binomial_tree(n, create_using)
144
+ assert nx.number_of_nodes(b) == 2**n
145
+ assert nx.number_of_edges(b) == (2**n - 1)
146
+
147
+ def test_complete_graph(self):
148
+ # complete_graph(m) is a connected graph with
149
+ # m nodes and m*(m+1)/2 edges
150
+ for m in [0, 1, 3, 5]:
151
+ g = nx.complete_graph(m)
152
+ assert nx.number_of_nodes(g) == m
153
+ assert nx.number_of_edges(g) == m * (m - 1) // 2
154
+
155
+ mg = nx.complete_graph(m, create_using=nx.MultiGraph)
156
+ assert edges_equal(mg.edges(), g.edges())
157
+
158
+ g = nx.complete_graph("abc")
159
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
160
+ assert g.size() == 3
161
+
162
+ # creates a self-loop... should it? <backward compatible says yes>
163
+ g = nx.complete_graph("abcb")
164
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
165
+ assert g.size() == 4
166
+
167
+ g = nx.complete_graph("abcb", create_using=nx.MultiGraph)
168
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
169
+ assert g.size() == 6
170
+
171
+ def test_complete_digraph(self):
172
+ # complete_graph(m) is a connected graph with
173
+ # m nodes and m*(m+1)/2 edges
174
+ for m in [0, 1, 3, 5]:
175
+ g = nx.complete_graph(m, create_using=nx.DiGraph)
176
+ assert nx.number_of_nodes(g) == m
177
+ assert nx.number_of_edges(g) == m * (m - 1)
178
+
179
+ g = nx.complete_graph("abc", create_using=nx.DiGraph)
180
+ assert len(g) == 3
181
+ assert g.size() == 6
182
+ assert g.is_directed()
183
+
184
+ def test_circular_ladder_graph(self):
185
+ G = nx.circular_ladder_graph(5)
186
+ pytest.raises(
187
+ nx.NetworkXError, nx.circular_ladder_graph, 5, create_using=nx.DiGraph
188
+ )
189
+ mG = nx.circular_ladder_graph(5, create_using=nx.MultiGraph)
190
+ assert edges_equal(mG.edges(), G.edges())
191
+
192
+ def test_circulant_graph(self):
193
+ # Ci_n(1) is the cycle graph for all n
194
+ Ci6_1 = nx.circulant_graph(6, [1])
195
+ C6 = nx.cycle_graph(6)
196
+ assert edges_equal(Ci6_1.edges(), C6.edges())
197
+
198
+ # Ci_n(1, 2, ..., n div 2) is the complete graph for all n
199
+ Ci7 = nx.circulant_graph(7, [1, 2, 3])
200
+ K7 = nx.complete_graph(7)
201
+ assert edges_equal(Ci7.edges(), K7.edges())
202
+
203
+ # Ci_6(1, 3) is K_3,3 i.e. the utility graph
204
+ Ci6_1_3 = nx.circulant_graph(6, [1, 3])
205
+ K3_3 = nx.complete_bipartite_graph(3, 3)
206
+ assert nx.could_be_isomorphic(Ci6_1_3, K3_3)
207
+
208
+ def test_cycle_graph(self):
209
+ G = nx.cycle_graph(4)
210
+ assert edges_equal(G.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
211
+ mG = nx.cycle_graph(4, create_using=nx.MultiGraph)
212
+ assert edges_equal(mG.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
213
+ G = nx.cycle_graph(4, create_using=nx.DiGraph)
214
+ assert not G.has_edge(2, 1)
215
+ assert G.has_edge(1, 2)
216
+ assert G.is_directed()
217
+
218
+ G = nx.cycle_graph("abc")
219
+ assert len(G) == 3
220
+ assert G.size() == 3
221
+ G = nx.cycle_graph("abcb")
222
+ assert len(G) == 3
223
+ assert G.size() == 2
224
+ g = nx.cycle_graph("abc", nx.DiGraph)
225
+ assert len(g) == 3
226
+ assert g.size() == 3
227
+ assert g.is_directed()
228
+ g = nx.cycle_graph("abcb", nx.DiGraph)
229
+ assert len(g) == 3
230
+ assert g.size() == 4
231
+
232
+ def test_dorogovtsev_goltsev_mendes_graph(self):
233
+ G = nx.dorogovtsev_goltsev_mendes_graph(0)
234
+ assert edges_equal(G.edges(), [(0, 1)])
235
+ assert nodes_equal(list(G), [0, 1])
236
+ G = nx.dorogovtsev_goltsev_mendes_graph(1)
237
+ assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
238
+ assert nx.average_clustering(G) == 1.0
239
+ assert nx.average_shortest_path_length(G) == 1.0
240
+ assert sorted(nx.triangles(G).values()) == [1, 1, 1]
241
+ assert nx.is_planar(G)
242
+ G = nx.dorogovtsev_goltsev_mendes_graph(2)
243
+ assert nx.number_of_nodes(G) == 6
244
+ assert nx.number_of_edges(G) == 9
245
+ assert nx.average_clustering(G) == 0.75
246
+ assert nx.average_shortest_path_length(G) == 1.4
247
+ assert nx.is_planar(G)
248
+ G = nx.dorogovtsev_goltsev_mendes_graph(10)
249
+ assert nx.number_of_nodes(G) == 29526
250
+ assert nx.number_of_edges(G) == 59049
251
+ assert G.degree(0) == 1024
252
+ assert G.degree(1) == 1024
253
+ assert G.degree(2) == 1024
254
+
255
+ with pytest.raises(nx.NetworkXError, match=r"n must be greater than"):
256
+ nx.dorogovtsev_goltsev_mendes_graph(-1)
257
+ with pytest.raises(nx.NetworkXError, match=r"directed graph not supported"):
258
+ nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.DiGraph)
259
+ with pytest.raises(nx.NetworkXError, match=r"multigraph not supported"):
260
+ nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.MultiGraph)
261
+ with pytest.raises(nx.NetworkXError):
262
+ nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.MultiDiGraph)
263
+
264
+ def test_create_using(self):
265
+ G = nx.empty_graph()
266
+ assert isinstance(G, nx.Graph)
267
+ pytest.raises(TypeError, nx.empty_graph, create_using=0.0)
268
+ pytest.raises(TypeError, nx.empty_graph, create_using="Graph")
269
+
270
+ G = nx.empty_graph(create_using=nx.MultiGraph)
271
+ assert isinstance(G, nx.MultiGraph)
272
+ G = nx.empty_graph(create_using=nx.DiGraph)
273
+ assert isinstance(G, nx.DiGraph)
274
+
275
+ G = nx.empty_graph(create_using=nx.DiGraph, default=nx.MultiGraph)
276
+ assert isinstance(G, nx.DiGraph)
277
+ G = nx.empty_graph(create_using=None, default=nx.MultiGraph)
278
+ assert isinstance(G, nx.MultiGraph)
279
+ G = nx.empty_graph(default=nx.MultiGraph)
280
+ assert isinstance(G, nx.MultiGraph)
281
+
282
+ G = nx.path_graph(5)
283
+ H = nx.empty_graph(create_using=G)
284
+ assert not H.is_multigraph()
285
+ assert not H.is_directed()
286
+ assert len(H) == 0
287
+ assert G is H
288
+
289
+ H = nx.empty_graph(create_using=nx.MultiGraph())
290
+ assert H.is_multigraph()
291
+ assert not H.is_directed()
292
+ assert G is not H
293
+
294
+ # test for subclasses that also use typing.Protocol. See gh-6243
295
+ class Mixin(typing.Protocol):
296
+ pass
297
+
298
+ class MyGraph(Mixin, nx.DiGraph):
299
+ pass
300
+
301
+ G = nx.empty_graph(create_using=MyGraph)
302
+
303
+ def test_empty_graph(self):
304
+ G = nx.empty_graph()
305
+ assert nx.number_of_nodes(G) == 0
306
+ G = nx.empty_graph(42)
307
+ assert nx.number_of_nodes(G) == 42
308
+ assert nx.number_of_edges(G) == 0
309
+
310
+ G = nx.empty_graph("abc")
311
+ assert len(G) == 3
312
+ assert G.size() == 0
313
+
314
+ # create empty digraph
315
+ G = nx.empty_graph(42, create_using=nx.DiGraph(name="duh"))
316
+ assert nx.number_of_nodes(G) == 42
317
+ assert nx.number_of_edges(G) == 0
318
+ assert isinstance(G, nx.DiGraph)
319
+
320
+ # create empty multigraph
321
+ G = nx.empty_graph(42, create_using=nx.MultiGraph(name="duh"))
322
+ assert nx.number_of_nodes(G) == 42
323
+ assert nx.number_of_edges(G) == 0
324
+ assert isinstance(G, nx.MultiGraph)
325
+
326
+ # create empty graph from another
327
+ pete = nx.petersen_graph()
328
+ G = nx.empty_graph(42, create_using=pete)
329
+ assert nx.number_of_nodes(G) == 42
330
+ assert nx.number_of_edges(G) == 0
331
+ assert isinstance(G, nx.Graph)
332
+
333
+ def test_ladder_graph(self):
334
+ for i, G in [
335
+ (0, nx.empty_graph(0)),
336
+ (1, nx.path_graph(2)),
337
+ (2, nx.hypercube_graph(2)),
338
+ (10, nx.grid_graph([2, 10])),
339
+ ]:
340
+ assert nx.could_be_isomorphic(nx.ladder_graph(i), G)
341
+
342
+ pytest.raises(nx.NetworkXError, nx.ladder_graph, 2, create_using=nx.DiGraph)
343
+
344
+ g = nx.ladder_graph(2)
345
+ mg = nx.ladder_graph(2, create_using=nx.MultiGraph)
346
+ assert edges_equal(mg.edges(), g.edges())
347
+
348
+ @pytest.mark.parametrize(("m", "n"), [(3, 5), (4, 10), (3, 20)])
349
+ def test_lollipop_graph_right_sizes(self, m, n):
350
+ G = nx.lollipop_graph(m, n)
351
+ assert nx.number_of_nodes(G) == m + n
352
+ assert nx.number_of_edges(G) == m * (m - 1) / 2 + n
353
+
354
+ @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("abc", "defg")])
355
+ def test_lollipop_graph_size_node_sequence(self, m, n):
356
+ G = nx.lollipop_graph(m, n)
357
+ assert nx.number_of_nodes(G) == len(m) + len(n)
358
+ assert nx.number_of_edges(G) == len(m) * (len(m) - 1) / 2 + len(n)
359
+
360
+ def test_lollipop_graph_exceptions(self):
361
+ # Raise NetworkXError if m<2
362
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, -1, 2)
363
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, 1, 20)
364
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, "", 20)
365
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, "a", 20)
366
+
367
+ # Raise NetworkXError if n<0
368
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, 5, -2)
369
+
370
+ # raise NetworkXError if create_using is directed
371
+ with pytest.raises(nx.NetworkXError):
372
+ nx.lollipop_graph(2, 20, create_using=nx.DiGraph)
373
+ with pytest.raises(nx.NetworkXError):
374
+ nx.lollipop_graph(2, 20, create_using=nx.MultiDiGraph)
375
+
376
+ @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
377
+ def test_lollipop_graph_same_as_path_when_m1_is_2(self, m, n):
378
+ G = nx.lollipop_graph(m, n)
379
+ assert nx.could_be_isomorphic(G, nx.path_graph(n + 2))
380
+
381
+ def test_lollipop_graph_for_multigraph(self):
382
+ G = nx.lollipop_graph(5, 20)
383
+ MG = nx.lollipop_graph(5, 20, create_using=nx.MultiGraph)
384
+ assert edges_equal(MG.edges(), G.edges())
385
+
386
+ @pytest.mark.parametrize(
387
+ ("m", "n"),
388
+ [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
389
+ )
390
+ def test_lollipop_graph_mixing_input_types(self, m, n):
391
+ expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
392
+ expected.add_edge(0, 100) # Connect complete graph and path graph
393
+ assert nx.could_be_isomorphic(nx.lollipop_graph(m, n), expected)
394
+
395
+ def test_lollipop_graph_non_builtin_ints(self):
396
+ np = pytest.importorskip("numpy")
397
+ G = nx.lollipop_graph(np.int32(4), np.int64(3))
398
+ expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
399
+ expected.add_edge(0, 100) # Connect complete graph and path graph
400
+ assert nx.could_be_isomorphic(G, expected)
401
+
402
+ def test_null_graph(self):
403
+ assert nx.number_of_nodes(nx.null_graph()) == 0
404
+
405
+ def test_path_graph(self):
406
+ p = nx.path_graph(0)
407
+ assert nx.could_be_isomorphic(p, nx.null_graph())
408
+
409
+ p = nx.path_graph(1)
410
+ assert nx.could_be_isomorphic(p, nx.empty_graph(1))
411
+
412
+ p = nx.path_graph(10)
413
+ assert nx.is_connected(p)
414
+ assert sorted(d for n, d in p.degree()) == [1, 1, 2, 2, 2, 2, 2, 2, 2, 2]
415
+ assert p.order() - 1 == p.size()
416
+
417
+ dp = nx.path_graph(3, create_using=nx.DiGraph)
418
+ assert dp.has_edge(0, 1)
419
+ assert not dp.has_edge(1, 0)
420
+
421
+ mp = nx.path_graph(10, create_using=nx.MultiGraph)
422
+ assert edges_equal(mp.edges(), p.edges())
423
+
424
+ G = nx.path_graph("abc")
425
+ assert len(G) == 3
426
+ assert G.size() == 2
427
+ G = nx.path_graph("abcb")
428
+ assert len(G) == 3
429
+ assert G.size() == 2
430
+ g = nx.path_graph("abc", nx.DiGraph)
431
+ assert len(g) == 3
432
+ assert g.size() == 2
433
+ assert g.is_directed()
434
+ g = nx.path_graph("abcb", nx.DiGraph)
435
+ assert len(g) == 3
436
+ assert g.size() == 3
437
+
438
+ G = nx.path_graph((1, 2, 3, 2, 4))
439
+ assert G.has_edge(2, 4)
440
+
441
+ def test_star_graph(self):
442
+ assert nx.could_be_isomorphic(nx.star_graph(""), nx.empty_graph(0))
443
+ assert nx.could_be_isomorphic(nx.star_graph([]), nx.empty_graph(0))
444
+ assert nx.could_be_isomorphic(nx.star_graph(0), nx.empty_graph(1))
445
+ assert nx.could_be_isomorphic(nx.star_graph(1), nx.path_graph(2))
446
+ assert nx.could_be_isomorphic(nx.star_graph(2), nx.path_graph(3))
447
+ assert nx.could_be_isomorphic(
448
+ nx.star_graph(5), nx.complete_bipartite_graph(1, 5)
449
+ )
450
+
451
+ s = nx.star_graph(10)
452
+ assert sorted(d for n, d in s.degree()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10]
453
+
454
+ ms = nx.star_graph(10, create_using=nx.MultiGraph)
455
+ assert edges_equal(ms.edges(), s.edges())
456
+
457
+ G = nx.star_graph("abc")
458
+ assert len(G) == 3
459
+ assert G.size() == 2
460
+
461
+ G = nx.star_graph("abcb")
462
+ assert len(G) == 3
463
+ assert G.size() == 2
464
+ G = nx.star_graph("abcb", create_using=nx.MultiGraph)
465
+ assert len(G) == 3
466
+ assert G.size() == 3
467
+
468
+ G = nx.star_graph("abcdefg")
469
+ assert len(G) == 7
470
+ assert G.size() == 6
471
+
472
+ @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiDiGraph))
473
+ def test_star_graph_directed(self, graph_type):
474
+ dg = nx.star_graph(3, create_using=graph_type)
475
+ assert sorted([(u, v) for u, v, *d in dg.edges]) == [(0, 1), (0, 2), (0, 3)]
476
+
477
+ def test_non_int_integers_for_star_graph(self):
478
+ np = pytest.importorskip("numpy")
479
+ G = nx.star_graph(np.int32(3))
480
+ assert len(G) == 4
481
+ assert G.size() == 3
482
+
483
+ @pytest.mark.parametrize(("m", "n"), [(3, 0), (3, 5), (4, 10), (3, 20)])
484
+ def test_tadpole_graph_right_sizes(self, m, n):
485
+ G = nx.tadpole_graph(m, n)
486
+ assert nx.number_of_nodes(G) == m + n
487
+ assert nx.number_of_edges(G) == m + n - (m == 2)
488
+
489
+ @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("ab", "c"), ("abc", "defg")])
490
+ def test_tadpole_graph_size_node_sequences(self, m, n):
491
+ G = nx.tadpole_graph(m, n)
492
+ assert nx.number_of_nodes(G) == len(m) + len(n)
493
+ assert nx.number_of_edges(G) == len(m) + len(n) - (len(m) == 2)
494
+
495
+ def test_tadpole_graph_exceptions(self):
496
+ # Raise NetworkXError if m<2
497
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, -1, 3)
498
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 0, 3)
499
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 1, 3)
500
+
501
+ # Raise NetworkXError if n<0
502
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 5, -2)
503
+
504
+ # Raise NetworkXError for digraphs
505
+ with pytest.raises(nx.NetworkXError):
506
+ nx.tadpole_graph(2, 20, create_using=nx.DiGraph)
507
+ with pytest.raises(nx.NetworkXError):
508
+ nx.tadpole_graph(2, 20, create_using=nx.MultiDiGraph)
509
+
510
+ @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
511
+ def test_tadpole_graph_same_as_path_when_m_is_2(self, m, n):
512
+ G = nx.tadpole_graph(m, n)
513
+ assert nx.could_be_isomorphic(G, nx.path_graph(n + 2))
514
+
515
+ @pytest.mark.parametrize("m", [4, 7])
516
+ def test_tadpole_graph_same_as_cycle_when_m2_is_0(self, m):
517
+ G = nx.tadpole_graph(m, 0)
518
+ assert nx.could_be_isomorphic(G, nx.cycle_graph(m))
519
+
520
+ def test_tadpole_graph_for_multigraph(self):
521
+ G = nx.tadpole_graph(5, 20)
522
+ MG = nx.tadpole_graph(5, 20, create_using=nx.MultiGraph)
523
+ assert edges_equal(MG.edges(), G.edges())
524
+
525
+ @pytest.mark.parametrize(
526
+ ("m", "n"),
527
+ [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
528
+ )
529
+ def test_tadpole_graph_mixing_input_types(self, m, n):
530
+ expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
531
+ expected.add_edge(0, 100) # Connect cycle and path
532
+ assert nx.could_be_isomorphic(nx.tadpole_graph(m, n), expected)
533
+
534
+ def test_tadpole_graph_non_builtin_integers(self):
535
+ np = pytest.importorskip("numpy")
536
+ G = nx.tadpole_graph(np.int32(4), np.int64(3))
537
+ expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
538
+ expected.add_edge(0, 100) # Connect cycle and path
539
+ assert nx.could_be_isomorphic(G, expected)
540
+
541
+ def test_trivial_graph(self):
542
+ assert nx.number_of_nodes(nx.trivial_graph()) == 1
543
+
544
+ def test_turan_graph(self):
545
+ assert nx.number_of_edges(nx.turan_graph(13, 4)) == 63
546
+ assert nx.could_be_isomorphic(
547
+ nx.turan_graph(13, 4), nx.complete_multipartite_graph(3, 4, 3, 3)
548
+ )
549
+
550
+ def test_wheel_graph(self):
551
+ for n, G in [
552
+ ("", nx.null_graph()),
553
+ (0, nx.null_graph()),
554
+ (1, nx.empty_graph(1)),
555
+ (2, nx.path_graph(2)),
556
+ (3, nx.complete_graph(3)),
557
+ (4, nx.complete_graph(4)),
558
+ ]:
559
+ g = nx.wheel_graph(n)
560
+ assert nx.could_be_isomorphic(g, G)
561
+
562
+ g = nx.wheel_graph(10)
563
+ assert sorted(d for n, d in g.degree()) == [3, 3, 3, 3, 3, 3, 3, 3, 3, 9]
564
+
565
+ pytest.raises(nx.NetworkXError, nx.wheel_graph, 10, create_using=nx.DiGraph)
566
+
567
+ mg = nx.wheel_graph(10, create_using=nx.MultiGraph())
568
+ assert edges_equal(mg.edges(), g.edges())
569
+
570
+ G = nx.wheel_graph("abc")
571
+ assert len(G) == 3
572
+ assert G.size() == 3
573
+
574
+ G = nx.wheel_graph("abcb")
575
+ assert len(G) == 3
576
+ assert G.size() == 4
577
+ G = nx.wheel_graph("abcb", nx.MultiGraph)
578
+ assert len(G) == 3
579
+ assert G.size() == 6
580
+
581
+ def test_non_int_integers_for_wheel_graph(self):
582
+ np = pytest.importorskip("numpy")
583
+ G = nx.wheel_graph(np.int32(3))
584
+ assert len(G) == 3
585
+ assert G.size() == 3
586
+
587
+ def test_complete_0_partite_graph(self):
588
+ """Tests that the complete 0-partite graph is the null graph."""
589
+ G = nx.complete_multipartite_graph()
590
+ H = nx.null_graph()
591
+ assert nodes_equal(G, H)
592
+ assert edges_equal(G.edges(), H.edges())
593
+
594
+ def test_complete_1_partite_graph(self):
595
+ """Tests that the complete 1-partite graph is the empty graph."""
596
+ G = nx.complete_multipartite_graph(3)
597
+ H = nx.empty_graph(3)
598
+ assert nodes_equal(G, H)
599
+ assert edges_equal(G.edges(), H.edges())
600
+
601
+ def test_complete_2_partite_graph(self):
602
+ """Tests that the complete 2-partite graph is the complete bipartite
603
+ graph.
604
+
605
+ """
606
+ G = nx.complete_multipartite_graph(2, 3)
607
+ H = nx.complete_bipartite_graph(2, 3)
608
+ assert nodes_equal(G, H)
609
+ assert edges_equal(G.edges(), H.edges())
610
+
611
+ def test_complete_multipartite_graph(self):
612
+ """Tests for generating the complete multipartite graph."""
613
+ G = nx.complete_multipartite_graph(2, 3, 4)
614
+ blocks = [(0, 1), (2, 3, 4), (5, 6, 7, 8)]
615
+ # Within each block, no two vertices should be adjacent.
616
+ for block in blocks:
617
+ for u, v in itertools.combinations_with_replacement(block, 2):
618
+ assert v not in G[u]
619
+ assert G.nodes[u] == G.nodes[v]
620
+ # Across blocks, all vertices should be adjacent.
621
+ for block1, block2 in itertools.combinations(blocks, 2):
622
+ for u, v in itertools.product(block1, block2):
623
+ assert v in G[u]
624
+ assert G.nodes[u] != G.nodes[v]
625
+ with pytest.raises(nx.NetworkXError, match="Negative number of nodes"):
626
+ nx.complete_multipartite_graph(2, -3, 4)
627
+
628
+ def test_kneser_graph(self):
629
+ # the petersen graph is a special case of the kneser graph when n=5 and k=2
630
+ assert nx.could_be_isomorphic(nx.kneser_graph(5, 2), nx.petersen_graph())
631
+
632
+ # when k is 1, the kneser graph returns a complete graph with n vertices
633
+ for i in range(1, 7):
634
+ assert nx.could_be_isomorphic(nx.kneser_graph(i, 1), nx.complete_graph(i))
635
+
636
+ # the kneser graph of n and n-1 is the empty graph with n vertices
637
+ for j in range(3, 7):
638
+ assert nx.could_be_isomorphic(nx.kneser_graph(j, j - 1), nx.empty_graph(j))
639
+
640
+ # in general the number of edges of the kneser graph is equal to
641
+ # (n choose k) times (n-k choose k) divided by 2
642
+ assert nx.number_of_edges(nx.kneser_graph(8, 3)) == 280