jam134 commited on
Commit
7d8f39b
·
verified ·
1 Parent(s): 019ae1d

Upload 2588 files

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 +3 -0
  2. runtime/Lib/site-packages/networkx-2.8.8.dist-info/INSTALLER +1 -0
  3. runtime/Lib/site-packages/networkx-2.8.8.dist-info/LICENSE.txt +37 -0
  4. runtime/Lib/site-packages/networkx-2.8.8.dist-info/METADATA +133 -0
  5. runtime/Lib/site-packages/networkx-2.8.8.dist-info/RECORD +0 -0
  6. runtime/Lib/site-packages/networkx-2.8.8.dist-info/WHEEL +5 -0
  7. runtime/Lib/site-packages/networkx-2.8.8.dist-info/top_level.txt +1 -0
  8. runtime/Lib/site-packages/networkx/__init__.py +90 -0
  9. runtime/Lib/site-packages/networkx/algorithms/__init__.py +129 -0
  10. runtime/Lib/site-packages/networkx/algorithms/approximation/__init__.py +24 -0
  11. runtime/Lib/site-packages/networkx/algorithms/approximation/clique.py +233 -0
  12. runtime/Lib/site-packages/networkx/algorithms/approximation/clustering_coefficient.py +64 -0
  13. runtime/Lib/site-packages/networkx/algorithms/approximation/connectivity.py +415 -0
  14. runtime/Lib/site-packages/networkx/algorithms/approximation/distance_measures.py +140 -0
  15. runtime/Lib/site-packages/networkx/algorithms/approximation/dominating_set.py +123 -0
  16. runtime/Lib/site-packages/networkx/algorithms/approximation/kcomponents.py +368 -0
  17. runtime/Lib/site-packages/networkx/algorithms/approximation/matching.py +42 -0
  18. runtime/Lib/site-packages/networkx/algorithms/approximation/maxcut.py +111 -0
  19. runtime/Lib/site-packages/networkx/algorithms/approximation/ramsey.py +51 -0
  20. runtime/Lib/site-packages/networkx/algorithms/approximation/steinertree.py +104 -0
  21. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/__init__.py +0 -0
  22. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py +41 -0
  23. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_clique.py +113 -0
  24. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py +199 -0
  25. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py +60 -0
  26. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py +78 -0
  27. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py +301 -0
  28. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_matching.py +8 -0
  29. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py +82 -0
  30. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py +31 -0
  31. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py +83 -0
  32. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py +963 -0
  33. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py +280 -0
  34. runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py +68 -0
  35. runtime/Lib/site-packages/networkx/algorithms/approximation/traveling_salesman.py +1434 -0
  36. runtime/Lib/site-packages/networkx/algorithms/approximation/treewidth.py +249 -0
  37. runtime/Lib/site-packages/networkx/algorithms/approximation/vertex_cover.py +80 -0
  38. runtime/Lib/site-packages/networkx/algorithms/assortativity/__init__.py +5 -0
  39. runtime/Lib/site-packages/networkx/algorithms/assortativity/connectivity.py +139 -0
  40. runtime/Lib/site-packages/networkx/algorithms/assortativity/correlation.py +298 -0
  41. runtime/Lib/site-packages/networkx/algorithms/assortativity/mixing.py +298 -0
  42. runtime/Lib/site-packages/networkx/algorithms/assortativity/neighbor_degree.py +159 -0
  43. runtime/Lib/site-packages/networkx/algorithms/assortativity/pairs.py +114 -0
  44. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/__init__.py +0 -0
  45. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/base_test.py +85 -0
  46. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.py +145 -0
  47. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_correlation.py +114 -0
  48. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py +182 -0
  49. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py +104 -0
  50. runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_pairs.py +87 -0
.gitattributes CHANGED
@@ -63,3 +63,6 @@ runtime/Lib/site-packages/jieba/lac_small/model_baseline/word_emb filter=lfs dif
63
  runtime/Lib/site-packages/llvmlite/binding/llvmlite.dll filter=lfs diff=lfs merge=lfs -text
64
  runtime/Lib/site-packages/lxml/etree.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
65
  runtime/Lib/site-packages/lxml/objectify.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
 
 
 
 
63
  runtime/Lib/site-packages/llvmlite/binding/llvmlite.dll filter=lfs diff=lfs merge=lfs -text
64
  runtime/Lib/site-packages/lxml/etree.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
65
  runtime/Lib/site-packages/lxml/objectify.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
66
+ runtime/Lib/site-packages/numpy/.libs/libopenblas.FB5AE2TYXYH2IJRDKGDGQ3XBKLKTF43H.gfortran-win_amd64.dll filter=lfs diff=lfs merge=lfs -text
67
+ runtime/Lib/site-packages/numpy/core/_multiarray_umath.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
68
+ runtime/Lib/site-packages/numpy/core/_simd.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
runtime/Lib/site-packages/networkx-2.8.8.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
runtime/Lib/site-packages/networkx-2.8.8.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NetworkX is distributed with the 3-clause BSD license.
2
+
3
+ ::
4
+
5
+ Copyright (C) 2004-2022, 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.
runtime/Lib/site-packages/networkx-2.8.8.dist-info/METADATA ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: networkx
3
+ Version: 2.8.8
4
+ Summary: Python package for creating and manipulating graphs and networks
5
+ Home-page: https://networkx.org/
6
+ Author: Aric Hagberg
7
+ Author-email: hagberg@lanl.gov
8
+ Maintainer: NetworkX Developers
9
+ Maintainer-email: networkx-discuss@googlegroups.com
10
+ Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues
11
+ Project-URL: Documentation, https://networkx.org/documentation/stable/
12
+ Project-URL: Source Code, https://github.com/networkx/networkx
13
+ Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math
14
+ Platform: Linux
15
+ Platform: Mac OSX
16
+ Platform: Windows
17
+ Platform: Unix
18
+ Classifier: Development Status :: 5 - Production/Stable
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Intended Audience :: Science/Research
21
+ Classifier: License :: OSI Approved :: BSD License
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3.8
25
+ Classifier: Programming Language :: Python :: 3.9
26
+ Classifier: Programming Language :: Python :: 3.10
27
+ Classifier: Programming Language :: Python :: 3.11
28
+ Classifier: Programming Language :: Python :: 3 :: Only
29
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
30
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
31
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
32
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
33
+ Classifier: Topic :: Scientific/Engineering :: Physics
34
+ Requires-Python: >=3.8
35
+ License-File: LICENSE.txt
36
+ Provides-Extra: default
37
+ Requires-Dist: numpy (>=1.19) ; extra == 'default'
38
+ Requires-Dist: scipy (>=1.8) ; extra == 'default'
39
+ Requires-Dist: matplotlib (>=3.4) ; extra == 'default'
40
+ Requires-Dist: pandas (>=1.3) ; extra == 'default'
41
+ Provides-Extra: developer
42
+ Requires-Dist: pre-commit (>=2.20) ; extra == 'developer'
43
+ Requires-Dist: mypy (>=0.982) ; extra == 'developer'
44
+ Provides-Extra: doc
45
+ Requires-Dist: sphinx (>=5.2) ; extra == 'doc'
46
+ Requires-Dist: pydata-sphinx-theme (>=0.11) ; extra == 'doc'
47
+ Requires-Dist: sphinx-gallery (>=0.11) ; extra == 'doc'
48
+ Requires-Dist: numpydoc (>=1.5) ; extra == 'doc'
49
+ Requires-Dist: pillow (>=9.2) ; extra == 'doc'
50
+ Requires-Dist: nb2plots (>=0.6) ; extra == 'doc'
51
+ Requires-Dist: texext (>=0.6.6) ; extra == 'doc'
52
+ Provides-Extra: extra
53
+ Requires-Dist: lxml (>=4.6) ; extra == 'extra'
54
+ Requires-Dist: pygraphviz (>=1.9) ; extra == 'extra'
55
+ Requires-Dist: pydot (>=1.4.2) ; extra == 'extra'
56
+ Requires-Dist: sympy (>=1.10) ; extra == 'extra'
57
+ Provides-Extra: test
58
+ Requires-Dist: pytest (>=7.2) ; extra == 'test'
59
+ Requires-Dist: pytest-cov (>=4.0) ; extra == 'test'
60
+ Requires-Dist: codecov (>=2.1) ; extra == 'test'
61
+
62
+ NetworkX
63
+ ========
64
+
65
+ .. image:: https://github.com/networkx/networkx/workflows/test/badge.svg?tag=networkx-2.8.8
66
+ :target: https://github.com/networkx/networkx/actions?query=branch%3Anetworkx-2.8.8
67
+
68
+ .. image:: https://codecov.io/gh/networkx/networkx/branch/main/graph/badge.svg
69
+ :target: https://app.codecov.io/gh/networkx/networkx/branch/main
70
+
71
+ .. image:: https://img.shields.io/github/labels/networkx/networkx/Good%20First%20Issue?color=green&label=Contribute%20&style=flat-square
72
+ :target: https://github.com/networkx/networkx/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+First+Issue%22
73
+
74
+
75
+ NetworkX is a Python package for the creation, manipulation,
76
+ and study of the structure, dynamics, and functions
77
+ of complex networks.
78
+
79
+ - **Website (including documentation):** https://networkx.org
80
+ - **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
81
+ - **Source:** https://github.com/networkx/networkx
82
+ - **Bug reports:** https://github.com/networkx/networkx/issues
83
+ - **Report a security vulnerability:** https://tidelift.com/security
84
+ - **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
85
+ - **GitHub Discussions:** https://github.com/networkx/networkx/discussions
86
+
87
+ Simple example
88
+ --------------
89
+
90
+ Find the shortest path between two nodes in an undirected graph:
91
+
92
+ .. code:: pycon
93
+
94
+ >>> import networkx as nx
95
+ >>> G = nx.Graph()
96
+ >>> G.add_edge("A", "B", weight=4)
97
+ >>> G.add_edge("B", "D", weight=2)
98
+ >>> G.add_edge("A", "C", weight=3)
99
+ >>> G.add_edge("C", "D", weight=4)
100
+ >>> nx.shortest_path(G, "A", "D", weight="weight")
101
+ ['A', 'B', 'D']
102
+
103
+ Install
104
+ -------
105
+
106
+ Install the latest version of NetworkX::
107
+
108
+ $ pip install networkx
109
+
110
+ Install with all optional dependencies::
111
+
112
+ $ pip install networkx[all]
113
+
114
+ For additional details, please see `INSTALL.rst`.
115
+
116
+ Bugs
117
+ ----
118
+
119
+ Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
120
+ Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
121
+ and create a pull request (PR). We welcome all changes, big or small, and we
122
+ will help you make the PR if you are new to `git` (just ask on the issue and/or
123
+ see `CONTRIBUTING.rst`).
124
+
125
+ License
126
+ -------
127
+
128
+ Released under the 3-Clause BSD license (see `LICENSE.txt`)::
129
+
130
+ Copyright (C) 2004-2022 NetworkX Developers
131
+ Aric Hagberg <hagberg@lanl.gov>
132
+ Dan Schult <dschult@colgate.edu>
133
+ Pieter Swart <swart@lanl.gov>
runtime/Lib/site-packages/networkx-2.8.8.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
runtime/Lib/site-packages/networkx-2.8.8.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
runtime/Lib/site-packages/networkx-2.8.8.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ networkx
runtime/Lib/site-packages/networkx/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NetworkX
3
+ ========
4
+
5
+ NetworkX is a Python package for the creation, manipulation, and study of the
6
+ structure, dynamics, and functions of complex networks.
7
+
8
+ See https://networkx.org for complete documentation.
9
+ """
10
+
11
+ __version__ = "2.8.8"
12
+
13
+
14
+ def __getattr__(name):
15
+ """Remove functions and provide informative error messages."""
16
+ if name == "nx_yaml":
17
+ raise ImportError(
18
+ "\nThe nx_yaml module has been removed from NetworkX.\n"
19
+ "Please use the `yaml` package directly for working with yaml data.\n"
20
+ "For example, a networkx.Graph `G` can be written to and loaded\n"
21
+ "from a yaml file with:\n\n"
22
+ " import yaml\n\n"
23
+ " with open('path_to_yaml_file', 'w') as fh:\n"
24
+ " yaml.dump(G, fh)\n"
25
+ " with open('path_to_yaml_file', 'r') as fh:\n"
26
+ " G = yaml.load(fh, Loader=yaml.Loader)\n\n"
27
+ "Note that yaml.Loader is considered insecure - see the pyyaml\n"
28
+ "documentation for further details.\n\n"
29
+ "This message will be removed in NetworkX 3.0."
30
+ )
31
+ if name == "read_yaml":
32
+ raise ImportError(
33
+ "\nread_yaml has been removed from NetworkX, please use `yaml`\n"
34
+ "directly:\n\n"
35
+ " import yaml\n\n"
36
+ " with open('path', 'r') as fh:\n"
37
+ " yaml.load(fh, Loader=yaml.Loader)\n\n"
38
+ "Note that yaml.Loader is considered insecure - see the pyyaml\n"
39
+ "documentation for further details.\n\n"
40
+ "This message will be removed in NetworkX 3.0."
41
+ )
42
+ if name == "write_yaml":
43
+ raise ImportError(
44
+ "\nwrite_yaml has been removed from NetworkX, please use `yaml`\n"
45
+ "directly:\n\n"
46
+ " import yaml\n\n"
47
+ " with open('path_for_yaml_output', 'w') as fh:\n"
48
+ " yaml.dump(G_to_be_yaml, fh)\n\n"
49
+ "This message will be removed in NetworkX 3.0."
50
+ )
51
+ raise AttributeError(f"module {__name__} has no attribute {name}")
52
+
53
+
54
+ # These are imported in order as listed
55
+ from networkx.lazy_imports import _lazy_import
56
+
57
+ from networkx.exception import *
58
+
59
+ from networkx import utils
60
+
61
+ from networkx import classes
62
+ from networkx.classes import filters
63
+ from networkx.classes import *
64
+
65
+ from networkx import convert
66
+ from networkx.convert import *
67
+
68
+ from networkx import convert_matrix
69
+ from networkx.convert_matrix import *
70
+
71
+ from networkx import relabel
72
+ from networkx.relabel import *
73
+
74
+ from networkx import generators
75
+ from networkx.generators import *
76
+
77
+ from networkx import readwrite
78
+ from networkx.readwrite import *
79
+
80
+ # Need to test with SciPy, when available
81
+ from networkx import algorithms
82
+ from networkx.algorithms import *
83
+
84
+ from networkx import linalg
85
+ from networkx.linalg import *
86
+
87
+ from networkx.testing.test import run as test
88
+
89
+ from networkx import drawing
90
+ from networkx.drawing import *
runtime/Lib/site-packages/networkx/algorithms/__init__.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networkx.algorithms.assortativity import *
2
+ from networkx.algorithms.asteroidal import *
3
+ from networkx.algorithms.boundary import *
4
+ from networkx.algorithms.bridges import *
5
+ from networkx.algorithms.chains import *
6
+ from networkx.algorithms.centrality import *
7
+ from networkx.algorithms.chordal import *
8
+ from networkx.algorithms.cluster import *
9
+ from networkx.algorithms.clique import *
10
+ from networkx.algorithms.communicability_alg import *
11
+ from networkx.algorithms.components import *
12
+ from networkx.algorithms.coloring import *
13
+ from networkx.algorithms.core import *
14
+ from networkx.algorithms.covering import *
15
+ from networkx.algorithms.cycles import *
16
+ from networkx.algorithms.cuts import *
17
+ from networkx.algorithms.d_separation import *
18
+ from networkx.algorithms.dag import *
19
+ from networkx.algorithms.distance_measures import *
20
+ from networkx.algorithms.distance_regular import *
21
+ from networkx.algorithms.dominance import *
22
+ from networkx.algorithms.dominating import *
23
+ from networkx.algorithms.efficiency_measures import *
24
+ from networkx.algorithms.euler import *
25
+ from networkx.algorithms.graphical import *
26
+ from networkx.algorithms.hierarchy import *
27
+ from networkx.algorithms.hybrid import *
28
+ from networkx.algorithms.link_analysis import *
29
+ from networkx.algorithms.link_prediction import *
30
+ from networkx.algorithms.lowest_common_ancestors import *
31
+ from networkx.algorithms.isolate import *
32
+ from networkx.algorithms.matching import *
33
+ from networkx.algorithms.minors import *
34
+ from networkx.algorithms.mis import *
35
+ from networkx.algorithms.moral import *
36
+ from networkx.algorithms.non_randomness import *
37
+ from networkx.algorithms.operators import *
38
+ from networkx.algorithms.planarity import *
39
+ from networkx.algorithms.planar_drawing import *
40
+ from networkx.algorithms.reciprocity import *
41
+ from networkx.algorithms.regular import *
42
+ from networkx.algorithms.richclub import *
43
+ from networkx.algorithms.shortest_paths import *
44
+ from networkx.algorithms.similarity import *
45
+ from networkx.algorithms.graph_hashing import *
46
+ from networkx.algorithms.simple_paths import *
47
+ from networkx.algorithms.smallworld import *
48
+ from networkx.algorithms.smetric import *
49
+ from networkx.algorithms.structuralholes import *
50
+ from networkx.algorithms.sparsifiers import *
51
+ from networkx.algorithms.summarization import *
52
+ from networkx.algorithms.swap import *
53
+ from networkx.algorithms.traversal import *
54
+ from networkx.algorithms.triads import *
55
+ from networkx.algorithms.vitality import *
56
+ from networkx.algorithms.voronoi import *
57
+ from networkx.algorithms.wiener import *
58
+ from networkx.algorithms.polynomials import *
59
+
60
+ # Make certain subpackages available to the user as direct imports from
61
+ # the `networkx` namespace.
62
+ from networkx.algorithms import approximation
63
+ from networkx.algorithms import assortativity
64
+ from networkx.algorithms import bipartite
65
+ from networkx.algorithms import node_classification
66
+ from networkx.algorithms import centrality
67
+ from networkx.algorithms import chordal
68
+ from networkx.algorithms import cluster
69
+ from networkx.algorithms import clique
70
+ from networkx.algorithms import components
71
+ from networkx.algorithms import connectivity
72
+ from networkx.algorithms import community
73
+ from networkx.algorithms import coloring
74
+ from networkx.algorithms import flow
75
+ from networkx.algorithms import isomorphism
76
+ from networkx.algorithms import link_analysis
77
+ from networkx.algorithms import lowest_common_ancestors
78
+ from networkx.algorithms import operators
79
+ from networkx.algorithms import shortest_paths
80
+ from networkx.algorithms import tournament
81
+ from networkx.algorithms import traversal
82
+ from networkx.algorithms import tree
83
+
84
+ # Make certain functions from some of the previous subpackages available
85
+ # to the user as direct imports from the `networkx` namespace.
86
+ from networkx.algorithms.bipartite import complete_bipartite_graph
87
+ from networkx.algorithms.bipartite import is_bipartite
88
+ from networkx.algorithms.bipartite import project
89
+ from networkx.algorithms.bipartite import projected_graph
90
+ from networkx.algorithms.connectivity import all_pairs_node_connectivity
91
+ from networkx.algorithms.connectivity import all_node_cuts
92
+ from networkx.algorithms.connectivity import average_node_connectivity
93
+ from networkx.algorithms.connectivity import edge_connectivity
94
+ from networkx.algorithms.connectivity import edge_disjoint_paths
95
+ from networkx.algorithms.connectivity import k_components
96
+ from networkx.algorithms.connectivity import k_edge_components
97
+ from networkx.algorithms.connectivity import k_edge_subgraphs
98
+ from networkx.algorithms.connectivity import k_edge_augmentation
99
+ from networkx.algorithms.connectivity import is_k_edge_connected
100
+ from networkx.algorithms.connectivity import minimum_edge_cut
101
+ from networkx.algorithms.connectivity import minimum_node_cut
102
+ from networkx.algorithms.connectivity import node_connectivity
103
+ from networkx.algorithms.connectivity import node_disjoint_paths
104
+ from networkx.algorithms.connectivity import stoer_wagner
105
+ from networkx.algorithms.flow import capacity_scaling
106
+ from networkx.algorithms.flow import cost_of_flow
107
+ from networkx.algorithms.flow import gomory_hu_tree
108
+ from networkx.algorithms.flow import max_flow_min_cost
109
+ from networkx.algorithms.flow import maximum_flow
110
+ from networkx.algorithms.flow import maximum_flow_value
111
+ from networkx.algorithms.flow import min_cost_flow
112
+ from networkx.algorithms.flow import min_cost_flow_cost
113
+ from networkx.algorithms.flow import minimum_cut
114
+ from networkx.algorithms.flow import minimum_cut_value
115
+ from networkx.algorithms.flow import network_simplex
116
+ from networkx.algorithms.isomorphism import could_be_isomorphic
117
+ from networkx.algorithms.isomorphism import fast_could_be_isomorphic
118
+ from networkx.algorithms.isomorphism import faster_could_be_isomorphic
119
+ from networkx.algorithms.isomorphism import is_isomorphic
120
+ from networkx.algorithms.tree.branchings import maximum_branching
121
+ from networkx.algorithms.tree.branchings import maximum_spanning_arborescence
122
+ from networkx.algorithms.tree.branchings import minimum_branching
123
+ from networkx.algorithms.tree.branchings import minimum_spanning_arborescence
124
+ from networkx.algorithms.tree.branchings import ArborescenceIterator
125
+ from networkx.algorithms.tree.coding import *
126
+ from networkx.algorithms.tree.decomposition import *
127
+ from networkx.algorithms.tree.mst import *
128
+ from networkx.algorithms.tree.operations import *
129
+ from networkx.algorithms.tree.recognition import *
runtime/Lib/site-packages/networkx/algorithms/approximation/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Approximations of graph properties and Heuristic methods for optimization.
2
+
3
+ .. warning:: These functions are not imported in the top-level of ``networkx``
4
+
5
+ These functions can be accessed using
6
+ ``networkx.approximation.function_name``
7
+
8
+ They can be imported using ``from networkx.algorithms import approximation``
9
+ or ``from networkx.algorithms.approximation import function_name``
10
+
11
+ """
12
+ from networkx.algorithms.approximation.clustering_coefficient import *
13
+ from networkx.algorithms.approximation.clique import *
14
+ from networkx.algorithms.approximation.connectivity import *
15
+ from networkx.algorithms.approximation.distance_measures import *
16
+ from networkx.algorithms.approximation.dominating_set import *
17
+ from networkx.algorithms.approximation.kcomponents import *
18
+ from networkx.algorithms.approximation.matching import *
19
+ from networkx.algorithms.approximation.ramsey import *
20
+ from networkx.algorithms.approximation.steinertree import *
21
+ from networkx.algorithms.approximation.traveling_salesman import *
22
+ from networkx.algorithms.approximation.treewidth import *
23
+ from networkx.algorithms.approximation.vertex_cover import *
24
+ from networkx.algorithms.approximation.maxcut import *
runtime/Lib/site-packages/networkx/algorithms/approximation/clique.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing large cliques and maximum independent sets."""
2
+ import networkx as nx
3
+ from networkx.algorithms.approximation import ramsey
4
+ from networkx.utils import not_implemented_for
5
+
6
+ __all__ = [
7
+ "clique_removal",
8
+ "max_clique",
9
+ "large_clique_size",
10
+ "maximum_independent_set",
11
+ ]
12
+
13
+
14
+ @not_implemented_for("directed")
15
+ @not_implemented_for("multigraph")
16
+ def maximum_independent_set(G):
17
+ """Returns an approximate maximum independent set.
18
+
19
+ Independent set or stable set is a set of vertices in a graph, no two of
20
+ which are adjacent. That is, it is a set I of vertices such that for every
21
+ two vertices in I, there is no edge connecting the two. Equivalently, each
22
+ edge in the graph has at most one endpoint in I. The size of an independent
23
+ set is the number of vertices it contains [1]_.
24
+
25
+ A maximum independent set is a largest independent set for a given graph G
26
+ and its size is denoted $\\alpha(G)$. The problem of finding such a set is called
27
+ the maximum independent set problem and is an NP-hard optimization problem.
28
+ As such, it is unlikely that there exists an efficient algorithm for finding
29
+ a maximum independent set of a graph.
30
+
31
+ The Independent Set algorithm is based on [2]_.
32
+
33
+ Parameters
34
+ ----------
35
+ G : NetworkX graph
36
+ Undirected graph
37
+
38
+ Returns
39
+ -------
40
+ iset : Set
41
+ The apx-maximum independent set
42
+
43
+ Raises
44
+ ------
45
+ NetworkXNotImplemented
46
+ If the graph is directed or is a multigraph.
47
+
48
+ Notes
49
+ -----
50
+ Finds the $O(|V|/(log|V|)^2)$ apx of independent set in the worst case.
51
+
52
+ References
53
+ ----------
54
+ .. [1] `Wikipedia: Independent set
55
+ <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
56
+ .. [2] Boppana, R., & Halldórsson, M. M. (1992).
57
+ Approximating maximum independent sets by excluding subgraphs.
58
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
59
+ """
60
+ iset, _ = clique_removal(G)
61
+ return iset
62
+
63
+
64
+ @not_implemented_for("directed")
65
+ @not_implemented_for("multigraph")
66
+ def max_clique(G):
67
+ r"""Find the Maximum Clique
68
+
69
+ Finds the $O(|V|/(log|V|)^2)$ apx of maximum clique/independent set
70
+ in the worst case.
71
+
72
+ Parameters
73
+ ----------
74
+ G : NetworkX graph
75
+ Undirected graph
76
+
77
+ Returns
78
+ -------
79
+ clique : set
80
+ The apx-maximum clique of the graph
81
+
82
+ Raises
83
+ ------
84
+ NetworkXNotImplemented
85
+ If the graph is directed or is a multigraph.
86
+
87
+ Notes
88
+ -----
89
+ A clique in an undirected graph G = (V, E) is a subset of the vertex set
90
+ `C \subseteq V` such that for every two vertices in C there exists an edge
91
+ connecting the two. This is equivalent to saying that the subgraph
92
+ induced by C is complete (in some cases, the term clique may also refer
93
+ to the subgraph).
94
+
95
+ A maximum clique is a clique of the largest possible size in a given graph.
96
+ The clique number `\omega(G)` of a graph G is the number of
97
+ vertices in a maximum clique in G. The intersection number of
98
+ G is the smallest number of cliques that together cover all edges of G.
99
+
100
+ https://en.wikipedia.org/wiki/Maximum_clique
101
+
102
+ References
103
+ ----------
104
+ .. [1] Boppana, R., & Halldórsson, M. M. (1992).
105
+ Approximating maximum independent sets by excluding subgraphs.
106
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
107
+ doi:10.1007/BF01994876
108
+ """
109
+ if G is None:
110
+ raise ValueError("Expected NetworkX graph!")
111
+
112
+ # finding the maximum clique in a graph is equivalent to finding
113
+ # the independent set in the complementary graph
114
+ cgraph = nx.complement(G)
115
+ iset, _ = clique_removal(cgraph)
116
+ return iset
117
+
118
+
119
+ @not_implemented_for("directed")
120
+ @not_implemented_for("multigraph")
121
+ def clique_removal(G):
122
+ r"""Repeatedly remove cliques from the graph.
123
+
124
+ Results in a $O(|V|/(\log |V|)^2)$ approximation of maximum clique
125
+ and independent set. Returns the largest independent set found, along
126
+ with found maximal cliques.
127
+
128
+ Parameters
129
+ ----------
130
+ G : NetworkX graph
131
+ Undirected graph
132
+
133
+ Returns
134
+ -------
135
+ max_ind_cliques : (set, list) tuple
136
+ 2-tuple of Maximal Independent Set and list of maximal cliques (sets).
137
+
138
+ Raises
139
+ ------
140
+ NetworkXNotImplemented
141
+ If the graph is directed or is a multigraph.
142
+
143
+ References
144
+ ----------
145
+ .. [1] Boppana, R., & Halldórsson, M. M. (1992).
146
+ Approximating maximum independent sets by excluding subgraphs.
147
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
148
+ """
149
+ graph = G.copy()
150
+ c_i, i_i = ramsey.ramsey_R2(graph)
151
+ cliques = [c_i]
152
+ isets = [i_i]
153
+ while graph:
154
+ graph.remove_nodes_from(c_i)
155
+ c_i, i_i = ramsey.ramsey_R2(graph)
156
+ if c_i:
157
+ cliques.append(c_i)
158
+ if i_i:
159
+ isets.append(i_i)
160
+ # Determine the largest independent set as measured by cardinality.
161
+ maxiset = max(isets, key=len)
162
+ return maxiset, cliques
163
+
164
+
165
+ @not_implemented_for("directed")
166
+ @not_implemented_for("multigraph")
167
+ def large_clique_size(G):
168
+ """Find the size of a large clique in a graph.
169
+
170
+ A *clique* is a subset of nodes in which each pair of nodes is
171
+ adjacent. This function is a heuristic for finding the size of a
172
+ large clique in the graph.
173
+
174
+ Parameters
175
+ ----------
176
+ G : NetworkX graph
177
+
178
+ Returns
179
+ -------
180
+ k: integer
181
+ The size of a large clique in the graph.
182
+
183
+ Raises
184
+ ------
185
+ NetworkXNotImplemented
186
+ If the graph is directed or is a multigraph.
187
+
188
+ Notes
189
+ -----
190
+ This implementation is from [1]_. Its worst case time complexity is
191
+ :math:`O(n d^2)`, where *n* is the number of nodes in the graph and
192
+ *d* is the maximum degree.
193
+
194
+ This function is a heuristic, which means it may work well in
195
+ practice, but there is no rigorous mathematical guarantee on the
196
+ ratio between the returned number and the actual largest clique size
197
+ in the graph.
198
+
199
+ References
200
+ ----------
201
+ .. [1] Pattabiraman, Bharath, et al.
202
+ "Fast Algorithms for the Maximum Clique Problem on Massive Graphs
203
+ with Applications to Overlapping Community Detection."
204
+ *Internet Mathematics* 11.4-5 (2015): 421--448.
205
+ <https://doi.org/10.1080/15427951.2014.986778>
206
+
207
+ See also
208
+ --------
209
+
210
+ :func:`networkx.algorithms.approximation.clique.max_clique`
211
+ A function that returns an approximate maximum clique with a
212
+ guarantee on the approximation ratio.
213
+
214
+ :mod:`networkx.algorithms.clique`
215
+ Functions for finding the exact maximum clique in a graph.
216
+
217
+ """
218
+ degrees = G.degree
219
+
220
+ def _clique_heuristic(G, U, size, best_size):
221
+ if not U:
222
+ return max(best_size, size)
223
+ u = max(U, key=degrees)
224
+ U.remove(u)
225
+ N_prime = {v for v in G[u] if degrees[v] >= best_size}
226
+ return _clique_heuristic(G, U & N_prime, size + 1, best_size)
227
+
228
+ best_size = 0
229
+ nodes = (u for u in G if degrees[u] >= best_size)
230
+ for u in nodes:
231
+ neighbors = {v for v in G[u] if degrees[v] >= best_size}
232
+ best_size = _clique_heuristic(G, neighbors, 1, best_size)
233
+ return best_size
runtime/Lib/site-packages/networkx/algorithms/approximation/clustering_coefficient.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networkx.utils import not_implemented_for, py_random_state
2
+
3
+ __all__ = ["average_clustering"]
4
+
5
+
6
+ @py_random_state(2)
7
+ @not_implemented_for("directed")
8
+ def average_clustering(G, trials=1000, seed=None):
9
+ r"""Estimates the average clustering coefficient of G.
10
+
11
+ The local clustering of each node in `G` is the fraction of triangles
12
+ that actually exist over all possible triangles in its neighborhood.
13
+ The average clustering coefficient of a graph `G` is the mean of
14
+ local clusterings.
15
+
16
+ This function finds an approximate average clustering coefficient
17
+ for G by repeating `n` times (defined in `trials`) the following
18
+ experiment: choose a node at random, choose two of its neighbors
19
+ at random, and check if they are connected. The approximate
20
+ coefficient is the fraction of triangles found over the number
21
+ of trials [1]_.
22
+
23
+ Parameters
24
+ ----------
25
+ G : NetworkX graph
26
+
27
+ trials : integer
28
+ Number of trials to perform (default 1000).
29
+
30
+ seed : integer, random_state, or None (default)
31
+ Indicator of random number generation state.
32
+ See :ref:`Randomness<randomness>`.
33
+
34
+ Returns
35
+ -------
36
+ c : float
37
+ Approximated average clustering coefficient.
38
+
39
+ Examples
40
+ --------
41
+ >>> from networkx.algorithms import approximation
42
+ >>> G = nx.erdos_renyi_graph(10, 0.2, seed=10)
43
+ >>> approximation.average_clustering(G, trials=1000, seed=10)
44
+ 0.214
45
+
46
+ References
47
+ ----------
48
+ .. [1] Schank, Thomas, and Dorothea Wagner. Approximating clustering
49
+ coefficient and transitivity. Universität Karlsruhe, Fakultät für
50
+ Informatik, 2004.
51
+ https://doi.org/10.5445/IR/1000001239
52
+
53
+ """
54
+ n = len(G)
55
+ triangles = 0
56
+ nodes = list(G)
57
+ for i in [int(seed.random() * n) for i in range(trials)]:
58
+ nbrs = list(G[nodes[i]])
59
+ if len(nbrs) < 2:
60
+ continue
61
+ u, v = seed.sample(nbrs, 2)
62
+ if u in G[v]:
63
+ triangles += 1
64
+ return triangles / trials
runtime/Lib/site-packages/networkx/algorithms/approximation/connectivity.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Fast approximation for node connectivity
2
+ """
3
+ import itertools
4
+ from operator import itemgetter
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = [
9
+ "local_node_connectivity",
10
+ "node_connectivity",
11
+ "all_pairs_node_connectivity",
12
+ ]
13
+
14
+
15
+ def local_node_connectivity(G, source, target, cutoff=None):
16
+ """Compute node connectivity between source and target.
17
+
18
+ Pairwise or local node connectivity between two distinct and nonadjacent
19
+ nodes is the minimum number of nodes that must be removed (minimum
20
+ separating cutset) to disconnect them. By Menger's theorem, this is equal
21
+ to the number of node independent paths (paths that share no nodes other
22
+ than source and target). Which is what we compute in this function.
23
+
24
+ This algorithm is a fast approximation that gives an strict lower
25
+ bound on the actual number of node independent paths between two nodes [1]_.
26
+ It works for both directed and undirected graphs.
27
+
28
+ Parameters
29
+ ----------
30
+
31
+ G : NetworkX graph
32
+
33
+ source : node
34
+ Starting node for node connectivity
35
+
36
+ target : node
37
+ Ending node for node connectivity
38
+
39
+ cutoff : integer
40
+ Maximum node connectivity to consider. If None, the minimum degree
41
+ of source or target is used as a cutoff. Default value None.
42
+
43
+ Returns
44
+ -------
45
+ k: integer
46
+ pairwise node connectivity
47
+
48
+ Examples
49
+ --------
50
+ >>> # Platonic octahedral graph has node connectivity 4
51
+ >>> # for each non adjacent node pair
52
+ >>> from networkx.algorithms import approximation as approx
53
+ >>> G = nx.octahedral_graph()
54
+ >>> approx.local_node_connectivity(G, 0, 5)
55
+ 4
56
+
57
+ Notes
58
+ -----
59
+ This algorithm [1]_ finds node independents paths between two nodes by
60
+ computing their shortest path using BFS, marking the nodes of the path
61
+ found as 'used' and then searching other shortest paths excluding the
62
+ nodes marked as used until no more paths exist. It is not exact because
63
+ a shortest path could use nodes that, if the path were longer, may belong
64
+ to two different node independent paths. Thus it only guarantees an
65
+ strict lower bound on node connectivity.
66
+
67
+ Note that the authors propose a further refinement, losing accuracy and
68
+ gaining speed, which is not implemented yet.
69
+
70
+ See also
71
+ --------
72
+ all_pairs_node_connectivity
73
+ node_connectivity
74
+
75
+ References
76
+ ----------
77
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
78
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
79
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
80
+
81
+ """
82
+ if target == source:
83
+ raise nx.NetworkXError("source and target have to be different nodes.")
84
+
85
+ # Maximum possible node independent paths
86
+ if G.is_directed():
87
+ possible = min(G.out_degree(source), G.in_degree(target))
88
+ else:
89
+ possible = min(G.degree(source), G.degree(target))
90
+
91
+ K = 0
92
+ if not possible:
93
+ return K
94
+
95
+ if cutoff is None:
96
+ cutoff = float("inf")
97
+
98
+ exclude = set()
99
+ for i in range(min(possible, cutoff)):
100
+ try:
101
+ path = _bidirectional_shortest_path(G, source, target, exclude)
102
+ exclude.update(set(path))
103
+ K += 1
104
+ except nx.NetworkXNoPath:
105
+ break
106
+
107
+ return K
108
+
109
+
110
+ def node_connectivity(G, s=None, t=None):
111
+ r"""Returns an approximation for node connectivity for a graph or digraph G.
112
+
113
+ Node connectivity is equal to the minimum number of nodes that
114
+ must be removed to disconnect G or render it trivial. By Menger's theorem,
115
+ this is equal to the number of node independent paths (paths that
116
+ share no nodes other than source and target).
117
+
118
+ If source and target nodes are provided, this function returns the
119
+ local node connectivity: the minimum number of nodes that must be
120
+ removed to break all paths from source to target in G.
121
+
122
+ This algorithm is based on a fast approximation that gives an strict lower
123
+ bound on the actual number of node independent paths between two nodes [1]_.
124
+ It works for both directed and undirected graphs.
125
+
126
+ Parameters
127
+ ----------
128
+ G : NetworkX graph
129
+ Undirected graph
130
+
131
+ s : node
132
+ Source node. Optional. Default value: None.
133
+
134
+ t : node
135
+ Target node. Optional. Default value: None.
136
+
137
+ Returns
138
+ -------
139
+ K : integer
140
+ Node connectivity of G, or local node connectivity if source
141
+ and target are provided.
142
+
143
+ Examples
144
+ --------
145
+ >>> # Platonic octahedral graph is 4-node-connected
146
+ >>> from networkx.algorithms import approximation as approx
147
+ >>> G = nx.octahedral_graph()
148
+ >>> approx.node_connectivity(G)
149
+ 4
150
+
151
+ Notes
152
+ -----
153
+ This algorithm [1]_ finds node independents paths between two nodes by
154
+ computing their shortest path using BFS, marking the nodes of the path
155
+ found as 'used' and then searching other shortest paths excluding the
156
+ nodes marked as used until no more paths exist. It is not exact because
157
+ a shortest path could use nodes that, if the path were longer, may belong
158
+ to two different node independent paths. Thus it only guarantees an
159
+ strict lower bound on node connectivity.
160
+
161
+ See also
162
+ --------
163
+ all_pairs_node_connectivity
164
+ local_node_connectivity
165
+
166
+ References
167
+ ----------
168
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
169
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
170
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
171
+
172
+ """
173
+ if (s is not None and t is None) or (s is None and t is not None):
174
+ raise nx.NetworkXError("Both source and target must be specified.")
175
+
176
+ # Local node connectivity
177
+ if s is not None and t is not None:
178
+ if s not in G:
179
+ raise nx.NetworkXError(f"node {s} not in graph")
180
+ if t not in G:
181
+ raise nx.NetworkXError(f"node {t} not in graph")
182
+ return local_node_connectivity(G, s, t)
183
+
184
+ # Global node connectivity
185
+ if G.is_directed():
186
+ connected_func = nx.is_weakly_connected
187
+ iter_func = itertools.permutations
188
+
189
+ def neighbors(v):
190
+ return itertools.chain(G.predecessors(v), G.successors(v))
191
+
192
+ else:
193
+ connected_func = nx.is_connected
194
+ iter_func = itertools.combinations
195
+ neighbors = G.neighbors
196
+
197
+ if not connected_func(G):
198
+ return 0
199
+
200
+ # Choose a node with minimum degree
201
+ v, minimum_degree = min(G.degree(), key=itemgetter(1))
202
+ # Node connectivity is bounded by minimum degree
203
+ K = minimum_degree
204
+ # compute local node connectivity with all non-neighbors nodes
205
+ # and store the minimum
206
+ for w in set(G) - set(neighbors(v)) - {v}:
207
+ K = min(K, local_node_connectivity(G, v, w, cutoff=K))
208
+ # Same for non adjacent pairs of neighbors of v
209
+ for x, y in iter_func(neighbors(v), 2):
210
+ if y not in G[x] and x != y:
211
+ K = min(K, local_node_connectivity(G, x, y, cutoff=K))
212
+ return K
213
+
214
+
215
+ def all_pairs_node_connectivity(G, nbunch=None, cutoff=None):
216
+ """Compute node connectivity between all pairs of nodes.
217
+
218
+ Pairwise or local node connectivity between two distinct and nonadjacent
219
+ nodes is the minimum number of nodes that must be removed (minimum
220
+ separating cutset) to disconnect them. By Menger's theorem, this is equal
221
+ to the number of node independent paths (paths that share no nodes other
222
+ than source and target). Which is what we compute in this function.
223
+
224
+ This algorithm is a fast approximation that gives an strict lower
225
+ bound on the actual number of node independent paths between two nodes [1]_.
226
+ It works for both directed and undirected graphs.
227
+
228
+
229
+ Parameters
230
+ ----------
231
+ G : NetworkX graph
232
+
233
+ nbunch: container
234
+ Container of nodes. If provided node connectivity will be computed
235
+ only over pairs of nodes in nbunch.
236
+
237
+ cutoff : integer
238
+ Maximum node connectivity to consider. If None, the minimum degree
239
+ of source or target is used as a cutoff in each pair of nodes.
240
+ Default value None.
241
+
242
+ Returns
243
+ -------
244
+ K : dictionary
245
+ Dictionary, keyed by source and target, of pairwise node connectivity
246
+
247
+ Examples
248
+ --------
249
+ A 3 node cycle with one extra node attached has connectivity 2 between all
250
+ nodes in the cycle and connectivity 1 between the extra node and the rest:
251
+
252
+ >>> G = nx.cycle_graph(3)
253
+ >>> G.add_edge(2, 3)
254
+ >>> import pprint # for nice dictionary formatting
255
+ >>> pprint.pprint(nx.all_pairs_node_connectivity(G))
256
+ {0: {1: 2, 2: 2, 3: 1},
257
+ 1: {0: 2, 2: 2, 3: 1},
258
+ 2: {0: 2, 1: 2, 3: 1},
259
+ 3: {0: 1, 1: 1, 2: 1}}
260
+
261
+ See Also
262
+ --------
263
+ local_node_connectivity
264
+ node_connectivity
265
+
266
+ References
267
+ ----------
268
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
269
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
270
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
271
+ """
272
+ if nbunch is None:
273
+ nbunch = G
274
+ else:
275
+ nbunch = set(nbunch)
276
+
277
+ directed = G.is_directed()
278
+ if directed:
279
+ iter_func = itertools.permutations
280
+ else:
281
+ iter_func = itertools.combinations
282
+
283
+ all_pairs = {n: {} for n in nbunch}
284
+
285
+ for u, v in iter_func(nbunch, 2):
286
+ k = local_node_connectivity(G, u, v, cutoff=cutoff)
287
+ all_pairs[u][v] = k
288
+ if not directed:
289
+ all_pairs[v][u] = k
290
+
291
+ return all_pairs
292
+
293
+
294
+ def _bidirectional_shortest_path(G, source, target, exclude):
295
+ """Returns shortest path between source and target ignoring nodes in the
296
+ container 'exclude'.
297
+
298
+ Parameters
299
+ ----------
300
+
301
+ G : NetworkX graph
302
+
303
+ source : node
304
+ Starting node for path
305
+
306
+ target : node
307
+ Ending node for path
308
+
309
+ exclude: container
310
+ Container for nodes to exclude from the search for shortest paths
311
+
312
+ Returns
313
+ -------
314
+ path: list
315
+ Shortest path between source and target ignoring nodes in 'exclude'
316
+
317
+ Raises
318
+ ------
319
+ NetworkXNoPath
320
+ If there is no path or if nodes are adjacent and have only one path
321
+ between them
322
+
323
+ Notes
324
+ -----
325
+ This function and its helper are originally from
326
+ networkx.algorithms.shortest_paths.unweighted and are modified to
327
+ accept the extra parameter 'exclude', which is a container for nodes
328
+ already used in other paths that should be ignored.
329
+
330
+ References
331
+ ----------
332
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
333
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
334
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
335
+
336
+ """
337
+ # call helper to do the real work
338
+ results = _bidirectional_pred_succ(G, source, target, exclude)
339
+ pred, succ, w = results
340
+
341
+ # build path from pred+w+succ
342
+ path = []
343
+ # from source to w
344
+ while w is not None:
345
+ path.append(w)
346
+ w = pred[w]
347
+ path.reverse()
348
+ # from w to target
349
+ w = succ[path[-1]]
350
+ while w is not None:
351
+ path.append(w)
352
+ w = succ[w]
353
+
354
+ return path
355
+
356
+
357
+ def _bidirectional_pred_succ(G, source, target, exclude):
358
+ # does BFS from both source and target and meets in the middle
359
+ # excludes nodes in the container "exclude" from the search
360
+ if source is None or target is None:
361
+ raise nx.NetworkXException(
362
+ "Bidirectional shortest path called without source or target"
363
+ )
364
+ if target == source:
365
+ return ({target: None}, {source: None}, source)
366
+
367
+ # handle either directed or undirected
368
+ if G.is_directed():
369
+ Gpred = G.predecessors
370
+ Gsucc = G.successors
371
+ else:
372
+ Gpred = G.neighbors
373
+ Gsucc = G.neighbors
374
+
375
+ # predecesssor and successors in search
376
+ pred = {source: None}
377
+ succ = {target: None}
378
+
379
+ # initialize fringes, start with forward
380
+ forward_fringe = [source]
381
+ reverse_fringe = [target]
382
+
383
+ level = 0
384
+
385
+ while forward_fringe and reverse_fringe:
386
+ # Make sure that we iterate one step forward and one step backwards
387
+ # thus source and target will only trigger "found path" when they are
388
+ # adjacent and then they can be safely included in the container 'exclude'
389
+ level += 1
390
+ if not level % 2 == 0:
391
+ this_level = forward_fringe
392
+ forward_fringe = []
393
+ for v in this_level:
394
+ for w in Gsucc(v):
395
+ if w in exclude:
396
+ continue
397
+ if w not in pred:
398
+ forward_fringe.append(w)
399
+ pred[w] = v
400
+ if w in succ:
401
+ return pred, succ, w # found path
402
+ else:
403
+ this_level = reverse_fringe
404
+ reverse_fringe = []
405
+ for v in this_level:
406
+ for w in Gpred(v):
407
+ if w in exclude:
408
+ continue
409
+ if w not in succ:
410
+ succ[w] = v
411
+ reverse_fringe.append(w)
412
+ if w in pred:
413
+ return pred, succ, w # found path
414
+
415
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
runtime/Lib/site-packages/networkx/algorithms/approximation/distance_measures.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distance measures approximated metrics."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import py_random_state
5
+
6
+ __all__ = ["diameter"]
7
+
8
+
9
+ @py_random_state(1)
10
+ def diameter(G, seed=None):
11
+ """Returns a lower bound on the diameter of the graph G.
12
+
13
+ The function computes a lower bound on the diameter (i.e., the maximum eccentricity)
14
+ of a directed or undirected graph G. The procedure used varies depending on the graph
15
+ being directed or not.
16
+
17
+ If G is an `undirected` graph, then the function uses the `2-sweep` algorithm [1]_.
18
+ The main idea is to pick the farthest node from a random node and return its eccentricity.
19
+
20
+ Otherwise, if G is a `directed` graph, the function uses the `2-dSweep` algorithm [2]_,
21
+ The procedure starts by selecting a random source node $s$ from which it performs a
22
+ forward and a backward BFS. Let $a_1$ and $a_2$ be the farthest nodes in the forward and
23
+ backward cases, respectively. Then, it computes the backward eccentricity of $a_1$ using
24
+ a backward BFS and the forward eccentricity of $a_2$ using a forward BFS.
25
+ Finally, it returns the best lower bound between the two.
26
+
27
+ In both cases, the time complexity is linear with respect to the size of G.
28
+
29
+ Parameters
30
+ ----------
31
+ G : NetworkX graph
32
+
33
+ seed : integer, random_state, or None (default)
34
+ Indicator of random number generation state.
35
+ See :ref:`Randomness<randomness>`.
36
+
37
+ Returns
38
+ -------
39
+ d : integer
40
+ Lower Bound on the Diameter of G
41
+
42
+ Raises
43
+ ------
44
+ NetworkXError
45
+ If the graph is empty or
46
+ If the graph is undirected and not connected or
47
+ If the graph is directed and not strongly connected.
48
+
49
+ See Also
50
+ --------
51
+ networkx.algorithms.distance_measures.diameter
52
+
53
+ References
54
+ ----------
55
+ .. [1] Magnien, Clémence, Matthieu Latapy, and Michel Habib.
56
+ *Fast computation of empirically tight bounds for the diameter of massive graphs.*
57
+ Journal of Experimental Algorithmics (JEA), 2009.
58
+ https://arxiv.org/pdf/0904.2728.pdf
59
+ .. [2] Crescenzi, Pierluigi, Roberto Grossi, Leonardo Lanzi, and Andrea Marino.
60
+ *On computing the diameter of real-world directed (weighted) graphs.*
61
+ International Symposium on Experimental Algorithms. Springer, Berlin, Heidelberg, 2012.
62
+ https://courses.cs.ut.ee/MTAT.03.238/2014_fall/uploads/Main/diameter.pdf
63
+ """
64
+ # if G is empty
65
+ if not G:
66
+ raise nx.NetworkXError("Expected non-empty NetworkX graph!")
67
+ # if there's only a node
68
+ if G.number_of_nodes() == 1:
69
+ return 0
70
+ # if G is directed
71
+ if G.is_directed():
72
+ return _two_sweep_directed(G, seed)
73
+ # else if G is undirected
74
+ return _two_sweep_undirected(G, seed)
75
+
76
+
77
+ def _two_sweep_undirected(G, seed):
78
+ """Helper function for finding a lower bound on the diameter
79
+ for undirected Graphs.
80
+
81
+ The idea is to pick the farthest node from a random node
82
+ and return its eccentricity.
83
+
84
+ ``G`` is a NetworkX undirected graph.
85
+
86
+ .. note::
87
+
88
+ ``seed`` is a random.Random or numpy.random.RandomState instance
89
+ """
90
+ # select a random source node
91
+ source = seed.choice(list(G))
92
+ # get the distances to the other nodes
93
+ distances = nx.shortest_path_length(G, source)
94
+ # if some nodes have not been visited, then the graph is not connected
95
+ if len(distances) != len(G):
96
+ raise nx.NetworkXError("Graph not connected.")
97
+ # take a node that is (one of) the farthest nodes from the source
98
+ *_, node = distances
99
+ # return the eccentricity of the node
100
+ return nx.eccentricity(G, node)
101
+
102
+
103
+ def _two_sweep_directed(G, seed):
104
+ """Helper function for finding a lower bound on the diameter
105
+ for directed Graphs.
106
+
107
+ It implements 2-dSweep, the directed version of the 2-sweep algorithm.
108
+ The algorithm follows the following steps.
109
+ 1. Select a source node $s$ at random.
110
+ 2. Perform a forward BFS from $s$ to select a node $a_1$ at the maximum
111
+ distance from the source, and compute $LB_1$, the backward eccentricity of $a_1$.
112
+ 3. Perform a backward BFS from $s$ to select a node $a_2$ at the maximum
113
+ distance from the source, and compute $LB_2$, the forward eccentricity of $a_2$.
114
+ 4. Return the maximum between $LB_1$ and $LB_2$.
115
+
116
+ ``G`` is a NetworkX directed graph.
117
+
118
+ .. note::
119
+
120
+ ``seed`` is a random.Random or numpy.random.RandomState instance
121
+ """
122
+ # get a new digraph G' with the edges reversed in the opposite direction
123
+ G_reversed = G.reverse()
124
+ # select a random source node
125
+ source = seed.choice(list(G))
126
+ # compute forward distances from source
127
+ forward_distances = nx.shortest_path_length(G, source)
128
+ # compute backward distances from source
129
+ backward_distances = nx.shortest_path_length(G_reversed, source)
130
+ # if either the source can't reach every node or not every node
131
+ # can reach the source, then the graph is not strongly connected
132
+ n = len(G)
133
+ if len(forward_distances) != n or len(backward_distances) != n:
134
+ raise nx.NetworkXError("DiGraph not strongly connected.")
135
+ # take a node a_1 at the maximum distance from the source in G
136
+ *_, a_1 = forward_distances
137
+ # take a node a_2 at the maximum distance from the source in G_reversed
138
+ *_, a_2 = backward_distances
139
+ # return the max between the backward eccentricity of a_1 and the forward eccentricity of a_2
140
+ return max(nx.eccentricity(G_reversed, a_1), nx.eccentricity(G, a_2))
runtime/Lib/site-packages/networkx/algorithms/approximation/dominating_set.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for finding node and edge dominating sets.
2
+
3
+ A `dominating set`_ for an undirected graph *G* with vertex set *V*
4
+ and edge set *E* is a subset *D* of *V* such that every vertex not in
5
+ *D* is adjacent to at least one member of *D*. An `edge dominating set`_
6
+ is a subset *F* of *E* such that every edge not in *F* is
7
+ incident to an endpoint of at least one edge in *F*.
8
+
9
+ .. _dominating set: https://en.wikipedia.org/wiki/Dominating_set
10
+ .. _edge dominating set: https://en.wikipedia.org/wiki/Edge_dominating_set
11
+
12
+ """
13
+
14
+ from ...utils import not_implemented_for
15
+ from ..matching import maximal_matching
16
+
17
+ __all__ = ["min_weighted_dominating_set", "min_edge_dominating_set"]
18
+
19
+
20
+ # TODO Why doesn't this algorithm work for directed graphs?
21
+ @not_implemented_for("directed")
22
+ def min_weighted_dominating_set(G, weight=None):
23
+ r"""Returns a dominating set that approximates the minimum weight node
24
+ dominating set.
25
+
26
+ Parameters
27
+ ----------
28
+ G : NetworkX graph
29
+ Undirected graph.
30
+
31
+ weight : string
32
+ The node attribute storing the weight of an node. If provided,
33
+ the node attribute with this key must be a number for each
34
+ node. If not provided, each node is assumed to have weight one.
35
+
36
+ Returns
37
+ -------
38
+ min_weight_dominating_set : set
39
+ A set of nodes, the sum of whose weights is no more than `(\log
40
+ w(V)) w(V^*)`, where `w(V)` denotes the sum of the weights of
41
+ each node in the graph and `w(V^*)` denotes the sum of the
42
+ weights of each node in the minimum weight dominating set.
43
+
44
+ Notes
45
+ -----
46
+ This algorithm computes an approximate minimum weighted dominating
47
+ set for the graph `G`. The returned solution has weight `(\log
48
+ w(V)) w(V^*)`, where `w(V)` denotes the sum of the weights of each
49
+ node in the graph and `w(V^*)` denotes the sum of the weights of
50
+ each node in the minimum weight dominating set for the graph.
51
+
52
+ This implementation of the algorithm runs in $O(m)$ time, where $m$
53
+ is the number of edges in the graph.
54
+
55
+ References
56
+ ----------
57
+ .. [1] Vazirani, Vijay V.
58
+ *Approximation Algorithms*.
59
+ Springer Science & Business Media, 2001.
60
+
61
+ """
62
+ # The unique dominating set for the null graph is the empty set.
63
+ if len(G) == 0:
64
+ return set()
65
+
66
+ # This is the dominating set that will eventually be returned.
67
+ dom_set = set()
68
+
69
+ def _cost(node_and_neighborhood):
70
+ """Returns the cost-effectiveness of greedily choosing the given
71
+ node.
72
+
73
+ `node_and_neighborhood` is a two-tuple comprising a node and its
74
+ closed neighborhood.
75
+
76
+ """
77
+ v, neighborhood = node_and_neighborhood
78
+ return G.nodes[v].get(weight, 1) / len(neighborhood - dom_set)
79
+
80
+ # This is a set of all vertices not already covered by the
81
+ # dominating set.
82
+ vertices = set(G)
83
+ # This is a dictionary mapping each node to the closed neighborhood
84
+ # of that node.
85
+ neighborhoods = {v: {v} | set(G[v]) for v in G}
86
+
87
+ # Continue until all vertices are adjacent to some node in the
88
+ # dominating set.
89
+ while vertices:
90
+ # Find the most cost-effective node to add, along with its
91
+ # closed neighborhood.
92
+ dom_node, min_set = min(neighborhoods.items(), key=_cost)
93
+ # Add the node to the dominating set and reduce the remaining
94
+ # set of nodes to cover.
95
+ dom_set.add(dom_node)
96
+ del neighborhoods[dom_node]
97
+ vertices -= min_set
98
+
99
+ return dom_set
100
+
101
+
102
+ def min_edge_dominating_set(G):
103
+ r"""Returns minimum cardinality edge dominating set.
104
+
105
+ Parameters
106
+ ----------
107
+ G : NetworkX graph
108
+ Undirected graph
109
+
110
+ Returns
111
+ -------
112
+ min_edge_dominating_set : set
113
+ Returns a set of dominating edges whose size is no more than 2 * OPT.
114
+
115
+ Notes
116
+ -----
117
+ The algorithm computes an approximate solution to the edge dominating set
118
+ problem. The result is no more than 2 * OPT in terms of size of the set.
119
+ Runtime of the algorithm is $O(|E|)$.
120
+ """
121
+ if not G:
122
+ raise ValueError("Expected non-empty NetworkX graph!")
123
+ return maximal_matching(G)
runtime/Lib/site-packages/networkx/algorithms/approximation/kcomponents.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Fast approximation for k-component structure
2
+ """
3
+ import itertools
4
+ from collections import defaultdict
5
+ from collections.abc import Mapping
6
+ from functools import cached_property
7
+
8
+ import networkx as nx
9
+ from networkx.algorithms.approximation import local_node_connectivity
10
+ from networkx.exception import NetworkXError
11
+ from networkx.utils import not_implemented_for
12
+
13
+ __all__ = ["k_components"]
14
+
15
+
16
+ @not_implemented_for("directed")
17
+ def k_components(G, min_density=0.95):
18
+ r"""Returns the approximate k-component structure of a graph G.
19
+
20
+ A `k`-component is a maximal subgraph of a graph G that has, at least,
21
+ node connectivity `k`: we need to remove at least `k` nodes to break it
22
+ into more components. `k`-components have an inherent hierarchical
23
+ structure because they are nested in terms of connectivity: a connected
24
+ graph can contain several 2-components, each of which can contain
25
+ one or more 3-components, and so forth.
26
+
27
+ This implementation is based on the fast heuristics to approximate
28
+ the `k`-component structure of a graph [1]_. Which, in turn, it is based on
29
+ a fast approximation algorithm for finding good lower bounds of the number
30
+ of node independent paths between two nodes [2]_.
31
+
32
+ Parameters
33
+ ----------
34
+ G : NetworkX graph
35
+ Undirected graph
36
+
37
+ min_density : Float
38
+ Density relaxation threshold. Default value 0.95
39
+
40
+ Returns
41
+ -------
42
+ k_components : dict
43
+ Dictionary with connectivity level `k` as key and a list of
44
+ sets of nodes that form a k-component of level `k` as values.
45
+
46
+ Raises
47
+ ------
48
+ NetworkXNotImplemented
49
+ If G is directed.
50
+
51
+ Examples
52
+ --------
53
+ >>> # Petersen graph has 10 nodes and it is triconnected, thus all
54
+ >>> # nodes are in a single component on all three connectivity levels
55
+ >>> from networkx.algorithms import approximation as apxa
56
+ >>> G = nx.petersen_graph()
57
+ >>> k_components = apxa.k_components(G)
58
+
59
+ Notes
60
+ -----
61
+ The logic of the approximation algorithm for computing the `k`-component
62
+ structure [1]_ is based on repeatedly applying simple and fast algorithms
63
+ for `k`-cores and biconnected components in order to narrow down the
64
+ number of pairs of nodes over which we have to compute White and Newman's
65
+ approximation algorithm for finding node independent paths [2]_. More
66
+ formally, this algorithm is based on Whitney's theorem, which states
67
+ an inclusion relation among node connectivity, edge connectivity, and
68
+ minimum degree for any graph G. This theorem implies that every
69
+ `k`-component is nested inside a `k`-edge-component, which in turn,
70
+ is contained in a `k`-core. Thus, this algorithm computes node independent
71
+ paths among pairs of nodes in each biconnected part of each `k`-core,
72
+ and repeats this procedure for each `k` from 3 to the maximal core number
73
+ of a node in the input graph.
74
+
75
+ Because, in practice, many nodes of the core of level `k` inside a
76
+ bicomponent actually are part of a component of level k, the auxiliary
77
+ graph needed for the algorithm is likely to be very dense. Thus, we use
78
+ a complement graph data structure (see `AntiGraph`) to save memory.
79
+ AntiGraph only stores information of the edges that are *not* present
80
+ in the actual auxiliary graph. When applying algorithms to this
81
+ complement graph data structure, it behaves as if it were the dense
82
+ version.
83
+
84
+ See also
85
+ --------
86
+ k_components
87
+
88
+ References
89
+ ----------
90
+ .. [1] Torrents, J. and F. Ferraro (2015) Structural Cohesion:
91
+ Visualization and Heuristics for Fast Computation.
92
+ https://arxiv.org/pdf/1503.04476v1
93
+
94
+ .. [2] White, Douglas R., and Mark Newman (2001) A Fast Algorithm for
95
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
96
+ https://www.santafe.edu/research/results/working-papers/fast-approximation-algorithms-for-finding-node-ind
97
+
98
+ .. [3] Moody, J. and D. White (2003). Social cohesion and embeddedness:
99
+ A hierarchical conception of social groups.
100
+ American Sociological Review 68(1), 103--28.
101
+ https://doi.org/10.2307/3088904
102
+
103
+ """
104
+ # Dictionary with connectivity level (k) as keys and a list of
105
+ # sets of nodes that form a k-component as values
106
+ k_components = defaultdict(list)
107
+ # make a few functions local for speed
108
+ node_connectivity = local_node_connectivity
109
+ k_core = nx.k_core
110
+ core_number = nx.core_number
111
+ biconnected_components = nx.biconnected_components
112
+ combinations = itertools.combinations
113
+ # Exact solution for k = {1,2}
114
+ # There is a linear time algorithm for triconnectivity, if we had an
115
+ # implementation available we could start from k = 4.
116
+ for component in nx.connected_components(G):
117
+ # isolated nodes have connectivity 0
118
+ comp = set(component)
119
+ if len(comp) > 1:
120
+ k_components[1].append(comp)
121
+ for bicomponent in nx.biconnected_components(G):
122
+ # avoid considering dyads as bicomponents
123
+ bicomp = set(bicomponent)
124
+ if len(bicomp) > 2:
125
+ k_components[2].append(bicomp)
126
+ # There is no k-component of k > maximum core number
127
+ # \kappa(G) <= \lambda(G) <= \delta(G)
128
+ g_cnumber = core_number(G)
129
+ max_core = max(g_cnumber.values())
130
+ for k in range(3, max_core + 1):
131
+ C = k_core(G, k, core_number=g_cnumber)
132
+ for nodes in biconnected_components(C):
133
+ # Build a subgraph SG induced by the nodes that are part of
134
+ # each biconnected component of the k-core subgraph C.
135
+ if len(nodes) < k:
136
+ continue
137
+ SG = G.subgraph(nodes)
138
+ # Build auxiliary graph
139
+ H = _AntiGraph()
140
+ H.add_nodes_from(SG.nodes())
141
+ for u, v in combinations(SG, 2):
142
+ K = node_connectivity(SG, u, v, cutoff=k)
143
+ if k > K:
144
+ H.add_edge(u, v)
145
+ for h_nodes in biconnected_components(H):
146
+ if len(h_nodes) <= k:
147
+ continue
148
+ SH = H.subgraph(h_nodes)
149
+ for Gc in _cliques_heuristic(SG, SH, k, min_density):
150
+ for k_nodes in biconnected_components(Gc):
151
+ Gk = nx.k_core(SG.subgraph(k_nodes), k)
152
+ if len(Gk) <= k:
153
+ continue
154
+ k_components[k].append(set(Gk))
155
+ return k_components
156
+
157
+
158
+ def _cliques_heuristic(G, H, k, min_density):
159
+ h_cnumber = nx.core_number(H)
160
+ for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)):
161
+ cands = {n for n, c in h_cnumber.items() if c == c_value}
162
+ # Skip checking for overlap for the highest core value
163
+ if i == 0:
164
+ overlap = False
165
+ else:
166
+ overlap = set.intersection(
167
+ *[{x for x in H[n] if x not in cands} for n in cands]
168
+ )
169
+ if overlap and len(overlap) < k:
170
+ SH = H.subgraph(cands | overlap)
171
+ else:
172
+ SH = H.subgraph(cands)
173
+ sh_cnumber = nx.core_number(SH)
174
+ SG = nx.k_core(G.subgraph(SH), k)
175
+ while not (_same(sh_cnumber) and nx.density(SH) >= min_density):
176
+ # This subgraph must be writable => .copy()
177
+ SH = H.subgraph(SG).copy()
178
+ if len(SH) <= k:
179
+ break
180
+ sh_cnumber = nx.core_number(SH)
181
+ sh_deg = dict(SH.degree())
182
+ min_deg = min(sh_deg.values())
183
+ SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg)
184
+ SG = nx.k_core(G.subgraph(SH), k)
185
+ else:
186
+ yield SG
187
+
188
+
189
+ def _same(measure, tol=0):
190
+ vals = set(measure.values())
191
+ if (max(vals) - min(vals)) <= tol:
192
+ return True
193
+ return False
194
+
195
+
196
+ class _AntiGraph(nx.Graph):
197
+ """
198
+ Class for complement graphs.
199
+
200
+ The main goal is to be able to work with big and dense graphs with
201
+ a low memory footprint.
202
+
203
+ In this class you add the edges that *do not exist* in the dense graph,
204
+ the report methods of the class return the neighbors, the edges and
205
+ the degree as if it was the dense graph. Thus it's possible to use
206
+ an instance of this class with some of NetworkX functions. In this
207
+ case we only use k-core, connected_components, and biconnected_components.
208
+ """
209
+
210
+ all_edge_dict = {"weight": 1}
211
+
212
+ def single_edge_dict(self):
213
+ return self.all_edge_dict
214
+
215
+ edge_attr_dict_factory = single_edge_dict # type: ignore
216
+
217
+ def __getitem__(self, n):
218
+ """Returns a dict of neighbors of node n in the dense graph.
219
+
220
+ Parameters
221
+ ----------
222
+ n : node
223
+ A node in the graph.
224
+
225
+ Returns
226
+ -------
227
+ adj_dict : dictionary
228
+ The adjacency dictionary for nodes connected to n.
229
+
230
+ """
231
+ all_edge_dict = self.all_edge_dict
232
+ return {
233
+ node: all_edge_dict for node in set(self._adj) - set(self._adj[n]) - {n}
234
+ }
235
+
236
+ def neighbors(self, n):
237
+ """Returns an iterator over all neighbors of node n in the
238
+ dense graph.
239
+ """
240
+ try:
241
+ return iter(set(self._adj) - set(self._adj[n]) - {n})
242
+ except KeyError as err:
243
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
244
+
245
+ class AntiAtlasView(Mapping):
246
+ """An adjacency inner dict for AntiGraph"""
247
+
248
+ def __init__(self, graph, node):
249
+ self._graph = graph
250
+ self._atlas = graph._adj[node]
251
+ self._node = node
252
+
253
+ def __len__(self):
254
+ return len(self._graph) - len(self._atlas) - 1
255
+
256
+ def __iter__(self):
257
+ return (n for n in self._graph if n not in self._atlas and n != self._node)
258
+
259
+ def __getitem__(self, nbr):
260
+ nbrs = set(self._graph._adj) - set(self._atlas) - {self._node}
261
+ if nbr in nbrs:
262
+ return self._graph.all_edge_dict
263
+ raise KeyError(nbr)
264
+
265
+ class AntiAdjacencyView(AntiAtlasView):
266
+ """An adjacency outer dict for AntiGraph"""
267
+
268
+ def __init__(self, graph):
269
+ self._graph = graph
270
+ self._atlas = graph._adj
271
+
272
+ def __len__(self):
273
+ return len(self._atlas)
274
+
275
+ def __iter__(self):
276
+ return iter(self._graph)
277
+
278
+ def __getitem__(self, node):
279
+ if node not in self._graph:
280
+ raise KeyError(node)
281
+ return self._graph.AntiAtlasView(self._graph, node)
282
+
283
+ @cached_property
284
+ def adj(self):
285
+ return self.AntiAdjacencyView(self)
286
+
287
+ def subgraph(self, nodes):
288
+ """This subgraph method returns a full AntiGraph. Not a View"""
289
+ nodes = set(nodes)
290
+ G = _AntiGraph()
291
+ G.add_nodes_from(nodes)
292
+ for n in G:
293
+ Gnbrs = G.adjlist_inner_dict_factory()
294
+ G._adj[n] = Gnbrs
295
+ for nbr, d in self._adj[n].items():
296
+ if nbr in G._adj:
297
+ Gnbrs[nbr] = d
298
+ G._adj[nbr][n] = d
299
+ G.graph = self.graph
300
+ return G
301
+
302
+ class AntiDegreeView(nx.reportviews.DegreeView):
303
+ def __iter__(self):
304
+ all_nodes = set(self._succ)
305
+ for n in self._nodes:
306
+ nbrs = all_nodes - set(self._succ[n]) - {n}
307
+ yield (n, len(nbrs))
308
+
309
+ def __getitem__(self, n):
310
+ nbrs = set(self._succ) - set(self._succ[n]) - {n}
311
+ # AntiGraph is a ThinGraph so all edges have weight 1
312
+ return len(nbrs) + (n in nbrs)
313
+
314
+ @cached_property
315
+ def degree(self):
316
+ """Returns an iterator for (node, degree) and degree for single node.
317
+
318
+ The node degree is the number of edges adjacent to the node.
319
+
320
+ Parameters
321
+ ----------
322
+ nbunch : iterable container, optional (default=all nodes)
323
+ A container of nodes. The container will be iterated
324
+ through once.
325
+
326
+ weight : string or None, optional (default=None)
327
+ The edge attribute that holds the numerical value used
328
+ as a weight. If None, then each edge has weight 1.
329
+ The degree is the sum of the edge weights adjacent to the node.
330
+
331
+ Returns
332
+ -------
333
+ deg:
334
+ Degree of the node, if a single node is passed as argument.
335
+ nd_iter : an iterator
336
+ The iterator returns two-tuples of (node, degree).
337
+
338
+ See Also
339
+ --------
340
+ degree
341
+
342
+ Examples
343
+ --------
344
+ >>> G = nx.path_graph(4)
345
+ >>> G.degree(0) # node 0 with degree 1
346
+ 1
347
+ >>> list(G.degree([0, 1]))
348
+ [(0, 1), (1, 2)]
349
+
350
+ """
351
+ return self.AntiDegreeView(self)
352
+
353
+ def adjacency(self):
354
+ """Returns an iterator of (node, adjacency set) tuples for all nodes
355
+ in the dense graph.
356
+
357
+ This is the fastest way to look at every edge.
358
+ For directed graphs, only outgoing adjacencies are included.
359
+
360
+ Returns
361
+ -------
362
+ adj_iter : iterator
363
+ An iterator of (node, adjacency set) for all nodes in
364
+ the graph.
365
+
366
+ """
367
+ for n in self._adj:
368
+ yield (n, set(self._adj) - set(self._adj[n]) - {n})
runtime/Lib/site-packages/networkx/algorithms/approximation/matching.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **************
3
+ Graph Matching
4
+ **************
5
+
6
+ Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent
7
+ edges; that is, no two edges share a common vertex.
8
+
9
+ `Wikipedia: Matching <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
10
+ """
11
+ import networkx as nx
12
+
13
+ __all__ = ["min_maximal_matching"]
14
+
15
+
16
+ def min_maximal_matching(G):
17
+ r"""Returns the minimum maximal matching of G. That is, out of all maximal
18
+ matchings of the graph G, the smallest is returned.
19
+
20
+ Parameters
21
+ ----------
22
+ G : NetworkX graph
23
+ Undirected graph
24
+
25
+ Returns
26
+ -------
27
+ min_maximal_matching : set
28
+ Returns a set of edges such that no two edges share a common endpoint
29
+ and every edge not in the set shares some common endpoint in the set.
30
+ Cardinality will be 2*OPT in the worst case.
31
+
32
+ Notes
33
+ -----
34
+ The algorithm computes an approximate solution fo the minimum maximal
35
+ cardinality matching problem. The solution is no more than 2 * OPT in size.
36
+ Runtime is $O(|E|)$.
37
+
38
+ References
39
+ ----------
40
+ .. [1] Vazirani, Vijay Approximation Algorithms (2001)
41
+ """
42
+ return nx.maximal_matching(G)
runtime/Lib/site-packages/networkx/algorithms/approximation/maxcut.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.utils.decorators import not_implemented_for, py_random_state
3
+
4
+ __all__ = ["randomized_partitioning", "one_exchange"]
5
+
6
+
7
+ @not_implemented_for("directed", "multigraph")
8
+ @py_random_state(1)
9
+ def randomized_partitioning(G, seed=None, p=0.5, weight=None):
10
+ """Compute a random partitioning of the graph nodes and its cut value.
11
+
12
+ A partitioning is calculated by observing each node
13
+ and deciding to add it to the partition with probability `p`,
14
+ returning a random cut and its corresponding value (the
15
+ sum of weights of edges connecting different partitions).
16
+
17
+ Parameters
18
+ ----------
19
+ G : NetworkX graph
20
+
21
+ seed : integer, random_state, or None (default)
22
+ Indicator of random number generation state.
23
+ See :ref:`Randomness<randomness>`.
24
+
25
+ p : scalar
26
+ Probability for each node to be part of the first partition.
27
+ Should be in [0,1]
28
+
29
+ weight : object
30
+ Edge attribute key to use as weight. If not specified, edges
31
+ have weight one.
32
+
33
+ Returns
34
+ -------
35
+ cut_size : scalar
36
+ Value of the minimum cut.
37
+
38
+ partition : pair of node sets
39
+ A partitioning of the nodes that defines a minimum cut.
40
+ """
41
+ cut = {node for node in G.nodes() if seed.random() < p}
42
+ cut_size = nx.algorithms.cut_size(G, cut, weight=weight)
43
+ partition = (cut, G.nodes - cut)
44
+ return cut_size, partition
45
+
46
+
47
+ def _swap_node_partition(cut, node):
48
+ return cut - {node} if node in cut else cut.union({node})
49
+
50
+
51
+ @not_implemented_for("directed", "multigraph")
52
+ @py_random_state(2)
53
+ def one_exchange(G, initial_cut=None, seed=None, weight=None):
54
+ """Compute a partitioning of the graphs nodes and the corresponding cut value.
55
+
56
+ Use a greedy one exchange strategy to find a locally maximal cut
57
+ and its value, it works by finding the best node (one that gives
58
+ the highest gain to the cut value) to add to the current cut
59
+ and repeats this process until no improvement can be made.
60
+
61
+ Parameters
62
+ ----------
63
+ G : networkx Graph
64
+ Graph to find a maximum cut for.
65
+
66
+ initial_cut : set
67
+ Cut to use as a starting point. If not supplied the algorithm
68
+ starts with an empty cut.
69
+
70
+ seed : integer, random_state, or None (default)
71
+ Indicator of random number generation state.
72
+ See :ref:`Randomness<randomness>`.
73
+
74
+ weight : object
75
+ Edge attribute key to use as weight. If not specified, edges
76
+ have weight one.
77
+
78
+ Returns
79
+ -------
80
+ cut_value : scalar
81
+ Value of the maximum cut.
82
+
83
+ partition : pair of node sets
84
+ A partitioning of the nodes that defines a maximum cut.
85
+ """
86
+ if initial_cut is None:
87
+ initial_cut = set()
88
+ cut = set(initial_cut)
89
+ current_cut_size = nx.algorithms.cut_size(G, cut, weight=weight)
90
+ while True:
91
+ nodes = list(G.nodes())
92
+ # Shuffling the nodes ensures random tie-breaks in the following call to max
93
+ seed.shuffle(nodes)
94
+ best_node_to_swap = max(
95
+ nodes,
96
+ key=lambda v: nx.algorithms.cut_size(
97
+ G, _swap_node_partition(cut, v), weight=weight
98
+ ),
99
+ default=None,
100
+ )
101
+ potential_cut = _swap_node_partition(cut, best_node_to_swap)
102
+ potential_cut_size = nx.algorithms.cut_size(G, potential_cut, weight=weight)
103
+
104
+ if potential_cut_size > current_cut_size:
105
+ cut = potential_cut
106
+ current_cut_size = potential_cut_size
107
+ else:
108
+ break
109
+
110
+ partition = (cut, G.nodes - cut)
111
+ return current_cut_size, partition
runtime/Lib/site-packages/networkx/algorithms/approximation/ramsey.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ramsey numbers.
3
+ """
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for
6
+
7
+ from ...utils import arbitrary_element
8
+
9
+ __all__ = ["ramsey_R2"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ def ramsey_R2(G):
15
+ r"""Compute the largest clique and largest independent set in `G`.
16
+
17
+ This can be used to estimate bounds for the 2-color
18
+ Ramsey number `R(2;s,t)` for `G`.
19
+
20
+ This is a recursive implementation which could run into trouble
21
+ for large recursions. Note that self-loop edges are ignored.
22
+
23
+ Parameters
24
+ ----------
25
+ G : NetworkX graph
26
+ Undirected graph
27
+
28
+ Returns
29
+ -------
30
+ max_pair : (set, set) tuple
31
+ Maximum clique, Maximum independent set.
32
+
33
+ Raises
34
+ ------
35
+ NetworkXNotImplemented
36
+ If the graph is directed or is a multigraph.
37
+ """
38
+ if not G:
39
+ return set(), set()
40
+
41
+ node = arbitrary_element(G)
42
+ nbrs = (nbr for nbr in nx.all_neighbors(G, node) if nbr != node)
43
+ nnbrs = nx.non_neighbors(G, node)
44
+ c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
45
+ c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())
46
+
47
+ c_1.add(node)
48
+ i_2.add(node)
49
+ # Choose the larger of the two cliques and the larger of the two
50
+ # independent sets, according to cardinality.
51
+ return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
runtime/Lib/site-packages/networkx/algorithms/approximation/steinertree.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain
2
+
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for, pairwise
5
+
6
+ __all__ = ["metric_closure", "steiner_tree"]
7
+
8
+
9
+ @not_implemented_for("directed")
10
+ def metric_closure(G, weight="weight"):
11
+ """Return the metric closure of a graph.
12
+
13
+ The metric closure of a graph *G* is the complete graph in which each edge
14
+ is weighted by the shortest path distance between the nodes in *G* .
15
+
16
+ Parameters
17
+ ----------
18
+ G : NetworkX graph
19
+
20
+ Returns
21
+ -------
22
+ NetworkX graph
23
+ Metric closure of the graph `G`.
24
+
25
+ """
26
+ M = nx.Graph()
27
+
28
+ Gnodes = set(G)
29
+
30
+ # check for connected graph while processing first node
31
+ all_paths_iter = nx.all_pairs_dijkstra(G, weight=weight)
32
+ u, (distance, path) = next(all_paths_iter)
33
+ if Gnodes - set(distance):
34
+ msg = "G is not a connected graph. metric_closure is not defined."
35
+ raise nx.NetworkXError(msg)
36
+ Gnodes.remove(u)
37
+ for v in Gnodes:
38
+ M.add_edge(u, v, distance=distance[v], path=path[v])
39
+
40
+ # first node done -- now process the rest
41
+ for u, (distance, path) in all_paths_iter:
42
+ Gnodes.remove(u)
43
+ for v in Gnodes:
44
+ M.add_edge(u, v, distance=distance[v], path=path[v])
45
+
46
+ return M
47
+
48
+
49
+ @not_implemented_for("directed")
50
+ def steiner_tree(G, terminal_nodes, weight="weight"):
51
+ """Return an approximation to the minimum Steiner tree of a graph.
52
+
53
+ The minimum Steiner tree of `G` w.r.t a set of `terminal_nodes`
54
+ is a tree within `G` that spans those nodes and has minimum size
55
+ (sum of edge weights) among all such trees.
56
+
57
+ The minimum Steiner tree can be approximated by computing the minimum
58
+ spanning tree of the subgraph of the metric closure of *G* induced by the
59
+ terminal nodes, where the metric closure of *G* is the complete graph in
60
+ which each edge is weighted by the shortest path distance between the
61
+ nodes in *G* .
62
+ This algorithm produces a tree whose weight is within a (2 - (2 / t))
63
+ factor of the weight of the optimal Steiner tree where *t* is number of
64
+ terminal nodes.
65
+
66
+ Parameters
67
+ ----------
68
+ G : NetworkX graph
69
+
70
+ terminal_nodes : list
71
+ A list of terminal nodes for which minimum steiner tree is
72
+ to be found.
73
+
74
+ Returns
75
+ -------
76
+ NetworkX graph
77
+ Approximation to the minimum steiner tree of `G` induced by
78
+ `terminal_nodes` .
79
+
80
+ Notes
81
+ -----
82
+ For multigraphs, the edge between two nodes with minimum weight is the
83
+ edge put into the Steiner tree.
84
+
85
+
86
+ References
87
+ ----------
88
+ .. [1] Steiner_tree_problem on Wikipedia.
89
+ https://en.wikipedia.org/wiki/Steiner_tree_problem
90
+ """
91
+ # H is the subgraph induced by terminal_nodes in the metric closure M of G.
92
+ M = metric_closure(G, weight=weight)
93
+ H = M.subgraph(terminal_nodes)
94
+ # Use the 'distance' attribute of each edge provided by M.
95
+ mst_edges = nx.minimum_spanning_edges(H, weight="distance", data=True)
96
+ # Create an iterator over each edge in each shortest path; repeats are okay
97
+ edges = chain.from_iterable(pairwise(d["path"]) for u, v, d in mst_edges)
98
+ # For multigraph we should add the minimal weight edge keys
99
+ if G.is_multigraph():
100
+ edges = (
101
+ (u, v, min(G[u][v], key=lambda k: G[u][v][k][weight])) for u, v in edges
102
+ )
103
+ T = G.edge_subgraph(edges)
104
+ return T
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/__init__.py ADDED
File without changes
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import average_clustering
3
+
4
+ # This approximation has to be exact in regular graphs
5
+ # with no triangles or with all possible triangles.
6
+
7
+
8
+ def test_petersen():
9
+ # Actual coefficient is 0
10
+ G = nx.petersen_graph()
11
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
12
+
13
+
14
+ def test_petersen_seed():
15
+ # Actual coefficient is 0
16
+ G = nx.petersen_graph()
17
+ assert average_clustering(G, trials=len(G) // 2, seed=1) == nx.average_clustering(G)
18
+
19
+
20
+ def test_tetrahedral():
21
+ # Actual coefficient is 1
22
+ G = nx.tetrahedral_graph()
23
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
24
+
25
+
26
+ def test_dodecahedral():
27
+ # Actual coefficient is 0
28
+ G = nx.dodecahedral_graph()
29
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
30
+
31
+
32
+ def test_empty():
33
+ G = nx.empty_graph(5)
34
+ assert average_clustering(G, trials=len(G) // 2) == 0
35
+
36
+
37
+ def test_complete():
38
+ G = nx.complete_graph(5)
39
+ assert average_clustering(G, trials=len(G) // 2) == 1
40
+ G = nx.complete_graph(7)
41
+ assert average_clustering(G, trials=len(G) // 2) == 1
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_clique.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.approximation.clique` module."""
2
+
3
+
4
+ import networkx as nx
5
+ from networkx.algorithms.approximation import (
6
+ clique_removal,
7
+ large_clique_size,
8
+ max_clique,
9
+ maximum_independent_set,
10
+ )
11
+
12
+
13
+ def is_independent_set(G, nodes):
14
+ """Returns True if and only if `nodes` is a clique in `G`.
15
+
16
+ `G` is a NetworkX graph. `nodes` is an iterable of nodes in
17
+ `G`.
18
+
19
+ """
20
+ return G.subgraph(nodes).number_of_edges() == 0
21
+
22
+
23
+ def is_clique(G, nodes):
24
+ """Returns True if and only if `nodes` is an independent set
25
+ in `G`.
26
+
27
+ `G` is an undirected simple graph. `nodes` is an iterable of
28
+ nodes in `G`.
29
+
30
+ """
31
+ H = G.subgraph(nodes)
32
+ n = len(H)
33
+ return H.number_of_edges() == n * (n - 1) // 2
34
+
35
+
36
+ class TestCliqueRemoval:
37
+ """Unit tests for the
38
+ :func:`~networkx.algorithms.approximation.clique_removal` function.
39
+
40
+ """
41
+
42
+ def test_trivial_graph(self):
43
+ G = nx.trivial_graph()
44
+ independent_set, cliques = clique_removal(G)
45
+ assert is_independent_set(G, independent_set)
46
+ assert all(is_clique(G, clique) for clique in cliques)
47
+ # In fact, we should only have 1-cliques, that is, singleton nodes.
48
+ assert all(len(clique) == 1 for clique in cliques)
49
+
50
+ def test_complete_graph(self):
51
+ G = nx.complete_graph(10)
52
+ independent_set, cliques = clique_removal(G)
53
+ assert is_independent_set(G, independent_set)
54
+ assert all(is_clique(G, clique) for clique in cliques)
55
+
56
+ def test_barbell_graph(self):
57
+ G = nx.barbell_graph(10, 5)
58
+ independent_set, cliques = clique_removal(G)
59
+ assert is_independent_set(G, independent_set)
60
+ assert all(is_clique(G, clique) for clique in cliques)
61
+
62
+
63
+ class TestMaxClique:
64
+ """Unit tests for the :func:`networkx.algorithms.approximation.max_clique`
65
+ function.
66
+
67
+ """
68
+
69
+ def test_null_graph(self):
70
+ G = nx.null_graph()
71
+ assert len(max_clique(G)) == 0
72
+
73
+ def test_complete_graph(self):
74
+ graph = nx.complete_graph(30)
75
+ # this should return the entire graph
76
+ mc = max_clique(graph)
77
+ assert 30 == len(mc)
78
+
79
+ def test_maximal_by_cardinality(self):
80
+ """Tests that the maximal clique is computed according to maximum
81
+ cardinality of the sets.
82
+
83
+ For more information, see pull request #1531.
84
+
85
+ """
86
+ G = nx.complete_graph(5)
87
+ G.add_edge(4, 5)
88
+ clique = max_clique(G)
89
+ assert len(clique) > 1
90
+
91
+ G = nx.lollipop_graph(30, 2)
92
+ clique = max_clique(G)
93
+ assert len(clique) > 2
94
+
95
+
96
+ def test_large_clique_size():
97
+ G = nx.complete_graph(9)
98
+ nx.add_cycle(G, [9, 10, 11])
99
+ G.add_edge(8, 9)
100
+ G.add_edge(1, 12)
101
+ G.add_node(13)
102
+
103
+ assert large_clique_size(G) == 9
104
+ G.remove_node(5)
105
+ assert large_clique_size(G) == 8
106
+ G.remove_edge(2, 3)
107
+ assert large_clique_size(G) == 7
108
+
109
+
110
+ def test_independent_set():
111
+ # smoke test
112
+ G = nx.Graph()
113
+ assert len(maximum_independent_set(G)) == 0
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms import approximation as approx
5
+
6
+
7
+ def test_global_node_connectivity():
8
+ # Figure 1 chapter on Connectivity
9
+ G = nx.Graph()
10
+ G.add_edges_from(
11
+ [
12
+ (1, 2),
13
+ (1, 3),
14
+ (1, 4),
15
+ (1, 5),
16
+ (2, 3),
17
+ (2, 6),
18
+ (3, 4),
19
+ (3, 6),
20
+ (4, 6),
21
+ (4, 7),
22
+ (5, 7),
23
+ (6, 8),
24
+ (6, 9),
25
+ (7, 8),
26
+ (7, 10),
27
+ (8, 11),
28
+ (9, 10),
29
+ (9, 11),
30
+ (10, 11),
31
+ ]
32
+ )
33
+ assert 2 == approx.local_node_connectivity(G, 1, 11)
34
+ assert 2 == approx.node_connectivity(G)
35
+ assert 2 == approx.node_connectivity(G, 1, 11)
36
+
37
+
38
+ def test_white_harary1():
39
+ # Figure 1b white and harary (2001)
40
+ # A graph with high adhesion (edge connectivity) and low cohesion
41
+ # (node connectivity)
42
+ G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
43
+ G.remove_node(7)
44
+ for i in range(4, 7):
45
+ G.add_edge(0, i)
46
+ G = nx.disjoint_union(G, nx.complete_graph(4))
47
+ G.remove_node(G.order() - 1)
48
+ for i in range(7, 10):
49
+ G.add_edge(0, i)
50
+ assert 1 == approx.node_connectivity(G)
51
+
52
+
53
+ def test_complete_graphs():
54
+ for n in range(5, 25, 5):
55
+ G = nx.complete_graph(n)
56
+ assert n - 1 == approx.node_connectivity(G)
57
+ assert n - 1 == approx.node_connectivity(G, 0, 3)
58
+
59
+
60
+ def test_empty_graphs():
61
+ for k in range(5, 25, 5):
62
+ G = nx.empty_graph(k)
63
+ assert 0 == approx.node_connectivity(G)
64
+ assert 0 == approx.node_connectivity(G, 0, 3)
65
+
66
+
67
+ def test_petersen():
68
+ G = nx.petersen_graph()
69
+ assert 3 == approx.node_connectivity(G)
70
+ assert 3 == approx.node_connectivity(G, 0, 5)
71
+
72
+
73
+ # Approximation fails with tutte graph
74
+ # def test_tutte():
75
+ # G = nx.tutte_graph()
76
+ # assert_equal(3, approx.node_connectivity(G))
77
+
78
+
79
+ def test_dodecahedral():
80
+ G = nx.dodecahedral_graph()
81
+ assert 3 == approx.node_connectivity(G)
82
+ assert 3 == approx.node_connectivity(G, 0, 5)
83
+
84
+
85
+ def test_octahedral():
86
+ G = nx.octahedral_graph()
87
+ assert 4 == approx.node_connectivity(G)
88
+ assert 4 == approx.node_connectivity(G, 0, 5)
89
+
90
+
91
+ # Approximation can fail with icosahedral graph depending
92
+ # on iteration order.
93
+ # def test_icosahedral():
94
+ # G=nx.icosahedral_graph()
95
+ # assert_equal(5, approx.node_connectivity(G))
96
+ # assert_equal(5, approx.node_connectivity(G, 0, 5))
97
+
98
+
99
+ def test_only_source():
100
+ G = nx.complete_graph(5)
101
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, s=0)
102
+
103
+
104
+ def test_only_target():
105
+ G = nx.complete_graph(5)
106
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, t=0)
107
+
108
+
109
+ def test_missing_source():
110
+ G = nx.path_graph(4)
111
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 10, 1)
112
+
113
+
114
+ def test_missing_target():
115
+ G = nx.path_graph(4)
116
+ pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 1, 10)
117
+
118
+
119
+ def test_source_equals_target():
120
+ G = nx.complete_graph(5)
121
+ pytest.raises(nx.NetworkXError, approx.local_node_connectivity, G, 0, 0)
122
+
123
+
124
+ def test_directed_node_connectivity():
125
+ G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
126
+ D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
127
+ assert 1 == approx.node_connectivity(G)
128
+ assert 1 == approx.node_connectivity(G, 1, 4)
129
+ assert 2 == approx.node_connectivity(D)
130
+ assert 2 == approx.node_connectivity(D, 1, 4)
131
+
132
+
133
+ class TestAllPairsNodeConnectivityApprox:
134
+ @classmethod
135
+ def setup_class(cls):
136
+ cls.path = nx.path_graph(7)
137
+ cls.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
138
+ cls.cycle = nx.cycle_graph(7)
139
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
140
+ cls.gnp = nx.gnp_random_graph(30, 0.1)
141
+ cls.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
142
+ cls.K20 = nx.complete_graph(20)
143
+ cls.K10 = nx.complete_graph(10)
144
+ cls.K5 = nx.complete_graph(5)
145
+ cls.G_list = [
146
+ cls.path,
147
+ cls.directed_path,
148
+ cls.cycle,
149
+ cls.directed_cycle,
150
+ cls.gnp,
151
+ cls.directed_gnp,
152
+ cls.K10,
153
+ cls.K5,
154
+ cls.K20,
155
+ ]
156
+
157
+ def test_cycles(self):
158
+ K_undir = approx.all_pairs_node_connectivity(self.cycle)
159
+ for source in K_undir:
160
+ for target, k in K_undir[source].items():
161
+ assert k == 2
162
+ K_dir = approx.all_pairs_node_connectivity(self.directed_cycle)
163
+ for source in K_dir:
164
+ for target, k in K_dir[source].items():
165
+ assert k == 1
166
+
167
+ def test_complete(self):
168
+ for G in [self.K10, self.K5, self.K20]:
169
+ K = approx.all_pairs_node_connectivity(G)
170
+ for source in K:
171
+ for target, k in K[source].items():
172
+ assert k == len(G) - 1
173
+
174
+ def test_paths(self):
175
+ K_undir = approx.all_pairs_node_connectivity(self.path)
176
+ for source in K_undir:
177
+ for target, k in K_undir[source].items():
178
+ assert k == 1
179
+ K_dir = approx.all_pairs_node_connectivity(self.directed_path)
180
+ for source in K_dir:
181
+ for target, k in K_dir[source].items():
182
+ if source < target:
183
+ assert k == 1
184
+ else:
185
+ assert k == 0
186
+
187
+ def test_cutoff(self):
188
+ for G in [self.K10, self.K5, self.K20]:
189
+ for mp in [2, 3, 4]:
190
+ paths = approx.all_pairs_node_connectivity(G, cutoff=mp)
191
+ for source in paths:
192
+ for target, K in paths[source].items():
193
+ assert K == mp
194
+
195
+ def test_all_pairs_connectivity_nbunch(self):
196
+ G = nx.complete_graph(5)
197
+ nbunch = [0, 2, 3]
198
+ C = approx.all_pairs_node_connectivity(G, nbunch=nbunch)
199
+ assert len(C) == len(nbunch)
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.approximation.distance_measures` module.
2
+ """
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.algorithms.approximation import diameter
8
+
9
+
10
+ class TestDiameter:
11
+ """Unit tests for the approximate diameter function
12
+ :func:`~networkx.algorithms.approximation.distance_measures.diameter`.
13
+ """
14
+
15
+ def test_null_graph(self):
16
+ """Test empty graph."""
17
+ G = nx.null_graph()
18
+ with pytest.raises(
19
+ nx.NetworkXError, match="Expected non-empty NetworkX graph!"
20
+ ):
21
+ diameter(G)
22
+
23
+ def test_undirected_non_connected(self):
24
+ """Test an undirected disconnected graph."""
25
+ graph = nx.path_graph(10)
26
+ graph.remove_edge(3, 4)
27
+ with pytest.raises(nx.NetworkXError, match="Graph not connected."):
28
+ diameter(graph)
29
+
30
+ def test_directed_non_strongly_connected(self):
31
+ """Test a directed non strongly connected graph."""
32
+ graph = nx.path_graph(10, create_using=nx.DiGraph())
33
+ with pytest.raises(nx.NetworkXError, match="DiGraph not strongly connected."):
34
+ diameter(graph)
35
+
36
+ def test_complete_undirected_graph(self):
37
+ """Test a complete undirected graph."""
38
+ graph = nx.complete_graph(10)
39
+ assert diameter(graph) == 1
40
+
41
+ def test_complete_directed_graph(self):
42
+ """Test a complete directed graph."""
43
+ graph = nx.complete_graph(10, create_using=nx.DiGraph())
44
+ assert diameter(graph) == 1
45
+
46
+ def test_undirected_path_graph(self):
47
+ """Test an undirected path graph with 10 nodes."""
48
+ graph = nx.path_graph(10)
49
+ assert diameter(graph) == 9
50
+
51
+ def test_directed_path_graph(self):
52
+ """Test a directed path graph with 10 nodes."""
53
+ graph = nx.path_graph(10).to_directed()
54
+ assert diameter(graph) == 9
55
+
56
+ def test_single_node(self):
57
+ """Test a graph which contains just a node."""
58
+ graph = nx.Graph()
59
+ graph.add_node(1)
60
+ assert diameter(graph) == 0
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ min_edge_dominating_set,
6
+ min_weighted_dominating_set,
7
+ )
8
+
9
+
10
+ class TestMinWeightDominatingSet:
11
+ def test_min_weighted_dominating_set(self):
12
+ graph = nx.Graph()
13
+ graph.add_edge(1, 2)
14
+ graph.add_edge(1, 5)
15
+ graph.add_edge(2, 3)
16
+ graph.add_edge(2, 5)
17
+ graph.add_edge(3, 4)
18
+ graph.add_edge(3, 6)
19
+ graph.add_edge(5, 6)
20
+
21
+ vertices = {1, 2, 3, 4, 5, 6}
22
+ # due to ties, this might be hard to test tight bounds
23
+ dom_set = min_weighted_dominating_set(graph)
24
+ for vertex in vertices - dom_set:
25
+ neighbors = set(graph.neighbors(vertex))
26
+ assert len(neighbors & dom_set) > 0, "Non dominating set found!"
27
+
28
+ def test_star_graph(self):
29
+ """Tests that an approximate dominating set for the star graph,
30
+ even when the center node does not have the smallest integer
31
+ label, gives just the center node.
32
+
33
+ For more information, see #1527.
34
+
35
+ """
36
+ # Create a star graph in which the center node has the highest
37
+ # label instead of the lowest.
38
+ G = nx.star_graph(10)
39
+ G = nx.relabel_nodes(G, {0: 9, 9: 0})
40
+ assert min_weighted_dominating_set(G) == {9}
41
+
42
+ def test_null_graph(self):
43
+ """Tests that the unique dominating set for the null graph is an empty set"""
44
+ G = nx.Graph()
45
+ assert min_weighted_dominating_set(G) == set()
46
+
47
+ def test_min_edge_dominating_set(self):
48
+ graph = nx.path_graph(5)
49
+ dom_set = min_edge_dominating_set(graph)
50
+
51
+ # this is a crappy way to test, but good enough for now.
52
+ for edge in graph.edges():
53
+ if edge in dom_set:
54
+ continue
55
+ else:
56
+ u, v = edge
57
+ found = False
58
+ for dom_edge in dom_set:
59
+ found |= u == dom_edge[0] or u == dom_edge[1]
60
+ assert found, "Non adjacent edge found!"
61
+
62
+ graph = nx.complete_graph(10)
63
+ dom_set = min_edge_dominating_set(graph)
64
+
65
+ # this is a crappy way to test, but good enough for now.
66
+ for edge in graph.edges():
67
+ if edge in dom_set:
68
+ continue
69
+ else:
70
+ u, v = edge
71
+ found = False
72
+ for dom_edge in dom_set:
73
+ found |= u == dom_edge[0] or u == dom_edge[1]
74
+ assert found, "Non adjacent edge found!"
75
+
76
+ graph = nx.Graph() # empty Networkx graph
77
+ with pytest.raises(ValueError, match="Expected non-empty NetworkX graph!"):
78
+ min_edge_dominating_set(graph)
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Test for approximation to k-components algorithm
2
+ import pytest
3
+
4
+ import networkx as nx
5
+ from networkx.algorithms.approximation import k_components
6
+ from networkx.algorithms.approximation.kcomponents import _AntiGraph, _same
7
+
8
+
9
+ def build_k_number_dict(k_components):
10
+ k_num = {}
11
+ for k, comps in sorted(k_components.items()):
12
+ for comp in comps:
13
+ for node in comp:
14
+ k_num[node] = k
15
+ return k_num
16
+
17
+
18
+ ##
19
+ # Some nice synthetic graphs
20
+ ##
21
+
22
+
23
+ def graph_example_1():
24
+ G = nx.convert_node_labels_to_integers(
25
+ nx.grid_graph([5, 5]), label_attribute="labels"
26
+ )
27
+ rlabels = nx.get_node_attributes(G, "labels")
28
+ labels = {v: k for k, v in rlabels.items()}
29
+
30
+ for nodes in [
31
+ (labels[(0, 0)], labels[(1, 0)]),
32
+ (labels[(0, 4)], labels[(1, 4)]),
33
+ (labels[(3, 0)], labels[(4, 0)]),
34
+ (labels[(3, 4)], labels[(4, 4)]),
35
+ ]:
36
+ new_node = G.order() + 1
37
+ # Petersen graph is triconnected
38
+ P = nx.petersen_graph()
39
+ G = nx.disjoint_union(G, P)
40
+ # Add two edges between the grid and P
41
+ G.add_edge(new_node + 1, nodes[0])
42
+ G.add_edge(new_node, nodes[1])
43
+ # K5 is 4-connected
44
+ K = nx.complete_graph(5)
45
+ G = nx.disjoint_union(G, K)
46
+ # Add three edges between P and K5
47
+ G.add_edge(new_node + 2, new_node + 11)
48
+ G.add_edge(new_node + 3, new_node + 12)
49
+ G.add_edge(new_node + 4, new_node + 13)
50
+ # Add another K5 sharing a node
51
+ G = nx.disjoint_union(G, K)
52
+ nbrs = G[new_node + 10]
53
+ G.remove_node(new_node + 10)
54
+ for nbr in nbrs:
55
+ G.add_edge(new_node + 17, nbr)
56
+ G.add_edge(new_node + 16, new_node + 5)
57
+ return G
58
+
59
+
60
+ def torrents_and_ferraro_graph():
61
+ G = nx.convert_node_labels_to_integers(
62
+ nx.grid_graph([5, 5]), label_attribute="labels"
63
+ )
64
+ rlabels = nx.get_node_attributes(G, "labels")
65
+ labels = {v: k for k, v in rlabels.items()}
66
+
67
+ for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]:
68
+ new_node = G.order() + 1
69
+ # Petersen graph is triconnected
70
+ P = nx.petersen_graph()
71
+ G = nx.disjoint_union(G, P)
72
+ # Add two edges between the grid and P
73
+ G.add_edge(new_node + 1, nodes[0])
74
+ G.add_edge(new_node, nodes[1])
75
+ # K5 is 4-connected
76
+ K = nx.complete_graph(5)
77
+ G = nx.disjoint_union(G, K)
78
+ # Add three edges between P and K5
79
+ G.add_edge(new_node + 2, new_node + 11)
80
+ G.add_edge(new_node + 3, new_node + 12)
81
+ G.add_edge(new_node + 4, new_node + 13)
82
+ # Add another K5 sharing a node
83
+ G = nx.disjoint_union(G, K)
84
+ nbrs = G[new_node + 10]
85
+ G.remove_node(new_node + 10)
86
+ for nbr in nbrs:
87
+ G.add_edge(new_node + 17, nbr)
88
+ # Commenting this makes the graph not biconnected !!
89
+ # This stupid mistake make one reviewer very angry :P
90
+ G.add_edge(new_node + 16, new_node + 8)
91
+
92
+ for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]:
93
+ new_node = G.order() + 1
94
+ # Petersen graph is triconnected
95
+ P = nx.petersen_graph()
96
+ G = nx.disjoint_union(G, P)
97
+ # Add two edges between the grid and P
98
+ G.add_edge(new_node + 1, nodes[0])
99
+ G.add_edge(new_node, nodes[1])
100
+ # K5 is 4-connected
101
+ K = nx.complete_graph(5)
102
+ G = nx.disjoint_union(G, K)
103
+ # Add three edges between P and K5
104
+ G.add_edge(new_node + 2, new_node + 11)
105
+ G.add_edge(new_node + 3, new_node + 12)
106
+ G.add_edge(new_node + 4, new_node + 13)
107
+ # Add another K5 sharing two nodes
108
+ G = nx.disjoint_union(G, K)
109
+ nbrs = G[new_node + 10]
110
+ G.remove_node(new_node + 10)
111
+ for nbr in nbrs:
112
+ G.add_edge(new_node + 17, nbr)
113
+ nbrs2 = G[new_node + 9]
114
+ G.remove_node(new_node + 9)
115
+ for nbr in nbrs2:
116
+ G.add_edge(new_node + 18, nbr)
117
+ return G
118
+
119
+
120
+ # Helper function
121
+
122
+
123
+ def _check_connectivity(G):
124
+ result = k_components(G)
125
+ for k, components in result.items():
126
+ if k < 3:
127
+ continue
128
+ for component in components:
129
+ C = G.subgraph(component)
130
+ K = nx.node_connectivity(C)
131
+ assert K >= k
132
+
133
+
134
+ def test_torrents_and_ferraro_graph():
135
+ G = torrents_and_ferraro_graph()
136
+ _check_connectivity(G)
137
+
138
+
139
+ def test_example_1():
140
+ G = graph_example_1()
141
+ _check_connectivity(G)
142
+
143
+
144
+ def test_karate_0():
145
+ G = nx.karate_club_graph()
146
+ _check_connectivity(G)
147
+
148
+
149
+ def test_karate_1():
150
+ karate_k_num = {
151
+ 0: 4,
152
+ 1: 4,
153
+ 2: 4,
154
+ 3: 4,
155
+ 4: 3,
156
+ 5: 3,
157
+ 6: 3,
158
+ 7: 4,
159
+ 8: 4,
160
+ 9: 2,
161
+ 10: 3,
162
+ 11: 1,
163
+ 12: 2,
164
+ 13: 4,
165
+ 14: 2,
166
+ 15: 2,
167
+ 16: 2,
168
+ 17: 2,
169
+ 18: 2,
170
+ 19: 3,
171
+ 20: 2,
172
+ 21: 2,
173
+ 22: 2,
174
+ 23: 3,
175
+ 24: 3,
176
+ 25: 3,
177
+ 26: 2,
178
+ 27: 3,
179
+ 28: 3,
180
+ 29: 3,
181
+ 30: 4,
182
+ 31: 3,
183
+ 32: 4,
184
+ 33: 4,
185
+ }
186
+ approx_karate_k_num = karate_k_num.copy()
187
+ approx_karate_k_num[24] = 2
188
+ approx_karate_k_num[25] = 2
189
+ G = nx.karate_club_graph()
190
+ k_comps = k_components(G)
191
+ k_num = build_k_number_dict(k_comps)
192
+ assert k_num in (karate_k_num, approx_karate_k_num)
193
+
194
+
195
+ def test_example_1_detail_3_and_4():
196
+ G = graph_example_1()
197
+ result = k_components(G)
198
+ # In this example graph there are 8 3-components, 4 with 15 nodes
199
+ # and 4 with 5 nodes.
200
+ assert len(result[3]) == 8
201
+ assert len([c for c in result[3] if len(c) == 15]) == 4
202
+ assert len([c for c in result[3] if len(c) == 5]) == 4
203
+ # There are also 8 4-components all with 5 nodes.
204
+ assert len(result[4]) == 8
205
+ assert all(len(c) == 5 for c in result[4])
206
+ # Finally check that the k-components detected have actually node
207
+ # connectivity >= k.
208
+ for k, components in result.items():
209
+ if k < 3:
210
+ continue
211
+ for component in components:
212
+ K = nx.node_connectivity(G.subgraph(component))
213
+ assert K >= k
214
+
215
+
216
+ def test_directed():
217
+ with pytest.raises(nx.NetworkXNotImplemented):
218
+ G = nx.gnp_random_graph(10, 0.4, directed=True)
219
+ kc = k_components(G)
220
+
221
+
222
+ def test_same():
223
+ equal = {"A": 2, "B": 2, "C": 2}
224
+ slightly_different = {"A": 2, "B": 1, "C": 2}
225
+ different = {"A": 2, "B": 8, "C": 18}
226
+ assert _same(equal)
227
+ assert not _same(slightly_different)
228
+ assert _same(slightly_different, tol=1)
229
+ assert not _same(different)
230
+ assert not _same(different, tol=4)
231
+
232
+
233
+ class TestAntiGraph:
234
+ @classmethod
235
+ def setup_class(cls):
236
+ cls.Gnp = nx.gnp_random_graph(20, 0.8)
237
+ cls.Anp = _AntiGraph(nx.complement(cls.Gnp))
238
+ cls.Gd = nx.davis_southern_women_graph()
239
+ cls.Ad = _AntiGraph(nx.complement(cls.Gd))
240
+ cls.Gk = nx.karate_club_graph()
241
+ cls.Ak = _AntiGraph(nx.complement(cls.Gk))
242
+ cls.GA = [(cls.Gnp, cls.Anp), (cls.Gd, cls.Ad), (cls.Gk, cls.Ak)]
243
+
244
+ def test_size(self):
245
+ for G, A in self.GA:
246
+ n = G.order()
247
+ s = len(list(G.edges())) + len(list(A.edges()))
248
+ assert s == (n * (n - 1)) / 2
249
+
250
+ def test_degree(self):
251
+ for G, A in self.GA:
252
+ assert sorted(G.degree()) == sorted(A.degree())
253
+
254
+ def test_core_number(self):
255
+ for G, A in self.GA:
256
+ assert nx.core_number(G) == nx.core_number(A)
257
+
258
+ def test_connected_components(self):
259
+ for G, A in self.GA:
260
+ gc = [set(c) for c in nx.connected_components(G)]
261
+ ac = [set(c) for c in nx.connected_components(A)]
262
+ for comp in ac:
263
+ assert comp in gc
264
+
265
+ def test_adj(self):
266
+ for G, A in self.GA:
267
+ for n, nbrs in G.adj.items():
268
+ a_adj = sorted((n, sorted(ad)) for n, ad in A.adj.items())
269
+ g_adj = sorted((n, sorted(ad)) for n, ad in G.adj.items())
270
+ assert a_adj == g_adj
271
+
272
+ def test_adjacency(self):
273
+ for G, A in self.GA:
274
+ a_adj = list(A.adjacency())
275
+ for n, nbrs in G.adjacency():
276
+ assert (n, set(nbrs)) in a_adj
277
+
278
+ def test_neighbors(self):
279
+ for G, A in self.GA:
280
+ node = list(G.nodes())[0]
281
+ assert set(G.neighbors(node)) == set(A.neighbors(node))
282
+
283
+ def test_node_not_in_graph(self):
284
+ for G, A in self.GA:
285
+ node = "non_existent_node"
286
+ pytest.raises(nx.NetworkXError, A.neighbors, node)
287
+ pytest.raises(nx.NetworkXError, G.neighbors, node)
288
+
289
+ def test_degree_thingraph(self):
290
+ for G, A in self.GA:
291
+ node = list(G.nodes())[0]
292
+ nodes = list(G.nodes())[1:4]
293
+ assert G.degree(node) == A.degree(node)
294
+ assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
295
+ # AntiGraph is a ThinGraph, so all the weights are 1
296
+ assert sum(d for n, d in A.degree()) == sum(
297
+ d for n, d in A.degree(weight="weight")
298
+ )
299
+ assert sum(d for n, d in G.degree(nodes)) == sum(
300
+ d for n, d in A.degree(nodes)
301
+ )
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_matching.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import networkx.algorithms.approximation as a
3
+
4
+
5
+ def test_min_maximal_matching():
6
+ # smoke test
7
+ G = nx.Graph()
8
+ assert len(a.min_maximal_matching(G)) == 0
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import maxcut
5
+
6
+
7
+ def _is_valid_cut(G, set1, set2):
8
+ union = set1.union(set2)
9
+ assert union == set(G.nodes)
10
+ assert len(set1) + len(set2) == G.number_of_nodes()
11
+
12
+
13
+ def _cut_is_locally_optimal(G, cut_size, set1):
14
+ # test if cut can be locally improved
15
+ for i, node in enumerate(set1):
16
+ cut_size_without_node = nx.algorithms.cut_size(
17
+ G, set1 - {node}, weight="weight"
18
+ )
19
+ assert cut_size_without_node <= cut_size
20
+
21
+
22
+ def test_random_partitioning():
23
+ G = nx.complete_graph(5)
24
+ _, (set1, set2) = maxcut.randomized_partitioning(G, seed=5)
25
+ _is_valid_cut(G, set1, set2)
26
+
27
+
28
+ def test_random_partitioning_all_to_one():
29
+ G = nx.complete_graph(5)
30
+ _, (set1, set2) = maxcut.randomized_partitioning(G, p=1)
31
+ _is_valid_cut(G, set1, set2)
32
+ assert len(set1) == G.number_of_nodes()
33
+ assert len(set2) == 0
34
+
35
+
36
+ def test_one_exchange_basic():
37
+ G = nx.complete_graph(5)
38
+ random.seed(5)
39
+ for (u, v, w) in G.edges(data=True):
40
+ w["weight"] = random.randrange(-100, 100, 1) / 10
41
+
42
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
43
+ cut_size, (set1, set2) = maxcut.one_exchange(
44
+ G, initial_cut, weight="weight", seed=5
45
+ )
46
+
47
+ _is_valid_cut(G, set1, set2)
48
+ _cut_is_locally_optimal(G, cut_size, set1)
49
+
50
+
51
+ def test_one_exchange_optimal():
52
+ # Greedy one exchange should find the optimal solution for this graph (14)
53
+ G = nx.Graph()
54
+ G.add_edge(1, 2, weight=3)
55
+ G.add_edge(1, 3, weight=3)
56
+ G.add_edge(1, 4, weight=3)
57
+ G.add_edge(1, 5, weight=3)
58
+ G.add_edge(2, 3, weight=5)
59
+
60
+ cut_size, (set1, set2) = maxcut.one_exchange(G, weight="weight", seed=5)
61
+
62
+ _is_valid_cut(G, set1, set2)
63
+ _cut_is_locally_optimal(G, cut_size, set1)
64
+ # check global optimality
65
+ assert cut_size == 14
66
+
67
+
68
+ def test_negative_weights():
69
+ G = nx.complete_graph(5)
70
+ random.seed(5)
71
+ for (u, v, w) in G.edges(data=True):
72
+ w["weight"] = -1 * random.random()
73
+
74
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
75
+ cut_size, (set1, set2) = maxcut.one_exchange(G, initial_cut, weight="weight")
76
+
77
+ # make sure it is a valid cut
78
+ _is_valid_cut(G, set1, set2)
79
+ # check local optimality
80
+ _cut_is_locally_optimal(G, cut_size, set1)
81
+ # test that all nodes are in the same partition
82
+ assert len(set1) == len(G.nodes) or len(set2) == len(G.nodes)
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import networkx.algorithms.approximation as apxa
3
+
4
+
5
+ def test_ramsey():
6
+ # this should only find the complete graph
7
+ graph = nx.complete_graph(10)
8
+ c, i = apxa.ramsey_R2(graph)
9
+ cdens = nx.density(graph.subgraph(c))
10
+ assert cdens == 1.0, "clique not correctly found by ramsey!"
11
+ idens = nx.density(graph.subgraph(i))
12
+ assert idens == 0.0, "i-set not correctly found by ramsey!"
13
+
14
+ # this trival graph has no cliques. should just find i-sets
15
+ graph = nx.trivial_graph()
16
+ c, i = apxa.ramsey_R2(graph)
17
+ assert c == {0}, "clique not correctly found by ramsey!"
18
+ assert i == {0}, "i-set not correctly found by ramsey!"
19
+
20
+ graph = nx.barbell_graph(10, 5, nx.Graph())
21
+ c, i = apxa.ramsey_R2(graph)
22
+ cdens = nx.density(graph.subgraph(c))
23
+ assert cdens == 1.0, "clique not correctly found by ramsey!"
24
+ idens = nx.density(graph.subgraph(i))
25
+ assert idens == 0.0, "i-set not correctly found by ramsey!"
26
+
27
+ # add self-loops and test again
28
+ graph.add_edges_from([(n, n) for n in range(0, len(graph), 2)])
29
+ cc, ii = apxa.ramsey_R2(graph)
30
+ assert cc == c
31
+ assert ii == i
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation.steinertree import metric_closure, steiner_tree
5
+ from networkx.utils import edges_equal
6
+
7
+
8
+ class TestSteinerTree:
9
+ @classmethod
10
+ def setup_class(cls):
11
+ G = nx.Graph()
12
+ G.add_edge(1, 2, weight=10)
13
+ G.add_edge(2, 3, weight=10)
14
+ G.add_edge(3, 4, weight=10)
15
+ G.add_edge(4, 5, weight=10)
16
+ G.add_edge(5, 6, weight=10)
17
+ G.add_edge(2, 7, weight=1)
18
+ G.add_edge(7, 5, weight=1)
19
+ cls.G = G
20
+ cls.term_nodes = [1, 2, 3, 4, 5]
21
+
22
+ def test_connected_metric_closure(self):
23
+ G = self.G.copy()
24
+ G.add_node(100)
25
+ pytest.raises(nx.NetworkXError, metric_closure, G)
26
+
27
+ def test_metric_closure(self):
28
+ M = metric_closure(self.G)
29
+ mc = [
30
+ (1, 2, {"distance": 10, "path": [1, 2]}),
31
+ (1, 3, {"distance": 20, "path": [1, 2, 3]}),
32
+ (1, 4, {"distance": 22, "path": [1, 2, 7, 5, 4]}),
33
+ (1, 5, {"distance": 12, "path": [1, 2, 7, 5]}),
34
+ (1, 6, {"distance": 22, "path": [1, 2, 7, 5, 6]}),
35
+ (1, 7, {"distance": 11, "path": [1, 2, 7]}),
36
+ (2, 3, {"distance": 10, "path": [2, 3]}),
37
+ (2, 4, {"distance": 12, "path": [2, 7, 5, 4]}),
38
+ (2, 5, {"distance": 2, "path": [2, 7, 5]}),
39
+ (2, 6, {"distance": 12, "path": [2, 7, 5, 6]}),
40
+ (2, 7, {"distance": 1, "path": [2, 7]}),
41
+ (3, 4, {"distance": 10, "path": [3, 4]}),
42
+ (3, 5, {"distance": 12, "path": [3, 2, 7, 5]}),
43
+ (3, 6, {"distance": 22, "path": [3, 2, 7, 5, 6]}),
44
+ (3, 7, {"distance": 11, "path": [3, 2, 7]}),
45
+ (4, 5, {"distance": 10, "path": [4, 5]}),
46
+ (4, 6, {"distance": 20, "path": [4, 5, 6]}),
47
+ (4, 7, {"distance": 11, "path": [4, 5, 7]}),
48
+ (5, 6, {"distance": 10, "path": [5, 6]}),
49
+ (5, 7, {"distance": 1, "path": [5, 7]}),
50
+ (6, 7, {"distance": 11, "path": [6, 5, 7]}),
51
+ ]
52
+ assert edges_equal(list(M.edges(data=True)), mc)
53
+
54
+ def test_steiner_tree(self):
55
+ S = steiner_tree(self.G, self.term_nodes)
56
+ expected_steiner_tree = [
57
+ (1, 2, {"weight": 10}),
58
+ (2, 3, {"weight": 10}),
59
+ (2, 7, {"weight": 1}),
60
+ (3, 4, {"weight": 10}),
61
+ (5, 7, {"weight": 1}),
62
+ ]
63
+ assert edges_equal(list(S.edges(data=True)), expected_steiner_tree)
64
+
65
+ def test_multigraph_steiner_tree(self):
66
+ G = nx.MultiGraph()
67
+ G.add_edges_from(
68
+ [
69
+ (1, 2, 0, {"weight": 1}),
70
+ (2, 3, 0, {"weight": 999}),
71
+ (2, 3, 1, {"weight": 1}),
72
+ (3, 4, 0, {"weight": 1}),
73
+ (3, 5, 0, {"weight": 1}),
74
+ ]
75
+ )
76
+ terminal_nodes = [2, 4, 5]
77
+ expected_edges = [
78
+ (2, 3, 1, {"weight": 1}), # edge with key 1 has lower weight
79
+ (3, 4, 0, {"weight": 1}),
80
+ (3, 5, 0, {"weight": 1}),
81
+ ]
82
+ T = steiner_tree(G, terminal_nodes)
83
+ assert edges_equal(T.edges(data=True, keys=True), expected_edges)
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the traveling_salesman module."""
2
+ import random
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ import networkx.algorithms.approximation as nx_app
8
+
9
+ pairwise = nx.utils.pairwise
10
+
11
+
12
+ def test_christofides_hamiltonian():
13
+ random.seed(42)
14
+ G = nx.complete_graph(20)
15
+ for (u, v) in G.edges():
16
+ G[u][v]["weight"] = random.randint(0, 10)
17
+
18
+ H = nx.Graph()
19
+ H.add_edges_from(pairwise(nx_app.christofides(G)))
20
+ H.remove_edges_from(nx.find_cycle(H))
21
+ assert len(H.edges) == 0
22
+
23
+ tree = nx.minimum_spanning_tree(G, weight="weight")
24
+ H = nx.Graph()
25
+ H.add_edges_from(pairwise(nx_app.christofides(G, tree)))
26
+ H.remove_edges_from(nx.find_cycle(H))
27
+ assert len(H.edges) == 0
28
+
29
+
30
+ def test_christofides_incomplete_graph():
31
+ G = nx.complete_graph(10)
32
+ G.remove_edge(0, 1)
33
+ pytest.raises(nx.NetworkXError, nx_app.christofides, G)
34
+
35
+
36
+ def test_christofides_ignore_selfloops():
37
+ G = nx.complete_graph(5)
38
+ G.add_edge(3, 3)
39
+ cycle = nx_app.christofides(G)
40
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
41
+
42
+
43
+ # set up graphs for other tests
44
+ class TestBase:
45
+ @classmethod
46
+ def setup_class(cls):
47
+ cls.DG = nx.DiGraph()
48
+ cls.DG.add_weighted_edges_from(
49
+ {
50
+ ("A", "B", 3),
51
+ ("A", "C", 17),
52
+ ("A", "D", 14),
53
+ ("B", "A", 3),
54
+ ("B", "C", 12),
55
+ ("B", "D", 16),
56
+ ("C", "A", 13),
57
+ ("C", "B", 12),
58
+ ("C", "D", 4),
59
+ ("D", "A", 14),
60
+ ("D", "B", 15),
61
+ ("D", "C", 2),
62
+ }
63
+ )
64
+ cls.DG_cycle = ["D", "C", "B", "A", "D"]
65
+ cls.DG_cost = 31.0
66
+
67
+ cls.DG2 = nx.DiGraph()
68
+ cls.DG2.add_weighted_edges_from(
69
+ {
70
+ ("A", "B", 3),
71
+ ("A", "C", 17),
72
+ ("A", "D", 14),
73
+ ("B", "A", 30),
74
+ ("B", "C", 2),
75
+ ("B", "D", 16),
76
+ ("C", "A", 33),
77
+ ("C", "B", 32),
78
+ ("C", "D", 34),
79
+ ("D", "A", 14),
80
+ ("D", "B", 15),
81
+ ("D", "C", 2),
82
+ }
83
+ )
84
+ cls.DG2_cycle = ["D", "A", "B", "C", "D"]
85
+ cls.DG2_cost = 53.0
86
+
87
+ cls.unweightedUG = nx.complete_graph(5, nx.Graph())
88
+ cls.unweightedDG = nx.complete_graph(5, nx.DiGraph())
89
+
90
+ cls.incompleteUG = nx.Graph()
91
+ cls.incompleteUG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
92
+ cls.incompleteDG = nx.DiGraph()
93
+ cls.incompleteDG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
94
+
95
+ cls.UG = nx.Graph()
96
+ cls.UG.add_weighted_edges_from(
97
+ {
98
+ ("A", "B", 3),
99
+ ("A", "C", 17),
100
+ ("A", "D", 14),
101
+ ("B", "C", 12),
102
+ ("B", "D", 16),
103
+ ("C", "D", 4),
104
+ }
105
+ )
106
+ cls.UG_cycle = ["D", "C", "B", "A", "D"]
107
+ cls.UG_cost = 33.0
108
+
109
+ cls.UG2 = nx.Graph()
110
+ cls.UG2.add_weighted_edges_from(
111
+ {
112
+ ("A", "B", 1),
113
+ ("A", "C", 15),
114
+ ("A", "D", 5),
115
+ ("B", "C", 16),
116
+ ("B", "D", 8),
117
+ ("C", "D", 3),
118
+ }
119
+ )
120
+ cls.UG2_cycle = ["D", "C", "B", "A", "D"]
121
+ cls.UG2_cost = 25.0
122
+
123
+
124
+ def validate_solution(soln, cost, exp_soln, exp_cost):
125
+ assert soln == exp_soln
126
+ assert cost == exp_cost
127
+
128
+
129
+ def validate_symmetric_solution(soln, cost, exp_soln, exp_cost):
130
+ assert soln == exp_soln or soln == exp_soln[::-1]
131
+ assert cost == exp_cost
132
+
133
+
134
+ class TestGreedyTSP(TestBase):
135
+ def test_greedy(self):
136
+ cycle = nx_app.greedy_tsp(self.DG, source="D")
137
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
138
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 31.0)
139
+
140
+ cycle = nx_app.greedy_tsp(self.DG2, source="D")
141
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
142
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 78.0)
143
+
144
+ cycle = nx_app.greedy_tsp(self.UG, source="D")
145
+ cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
146
+ validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 33.0)
147
+
148
+ cycle = nx_app.greedy_tsp(self.UG2, source="D")
149
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
150
+ validate_solution(cycle, cost, ["D", "C", "A", "B", "D"], 27.0)
151
+
152
+ def test_not_complete_graph(self):
153
+ pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteUG)
154
+ pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteDG)
155
+
156
+ def test_not_weighted_graph(self):
157
+ nx_app.greedy_tsp(self.unweightedUG)
158
+ nx_app.greedy_tsp(self.unweightedDG)
159
+
160
+ def test_two_nodes(self):
161
+ G = nx.Graph()
162
+ G.add_weighted_edges_from({(1, 2, 1)})
163
+ cycle = nx_app.greedy_tsp(G)
164
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
165
+ validate_solution(cycle, cost, [1, 2, 1], 2)
166
+
167
+ def test_ignore_selfloops(self):
168
+ G = nx.complete_graph(5)
169
+ G.add_edge(3, 3)
170
+ cycle = nx_app.greedy_tsp(G)
171
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
172
+
173
+
174
+ class TestSimulatedAnnealingTSP(TestBase):
175
+ tsp = staticmethod(nx_app.simulated_annealing_tsp)
176
+
177
+ def test_simulated_annealing_directed(self):
178
+ cycle = self.tsp(self.DG, "greedy", source="D", seed=42)
179
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
180
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
181
+
182
+ initial_sol = ["D", "B", "A", "C", "D"]
183
+ cycle = self.tsp(self.DG, initial_sol, source="D", seed=42)
184
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
185
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
186
+
187
+ initial_sol = ["D", "A", "C", "B", "D"]
188
+ cycle = self.tsp(self.DG, initial_sol, move="1-0", source="D", seed=42)
189
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
190
+ validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
191
+
192
+ cycle = self.tsp(self.DG2, "greedy", source="D", seed=42)
193
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
194
+ validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
195
+
196
+ cycle = self.tsp(self.DG2, "greedy", move="1-0", source="D", seed=42)
197
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
198
+ validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
199
+
200
+ def test_simulated_annealing_undirected(self):
201
+ cycle = self.tsp(self.UG, "greedy", source="D", seed=42)
202
+ cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
203
+ validate_solution(cycle, cost, self.UG_cycle, self.UG_cost)
204
+
205
+ cycle = self.tsp(self.UG2, "greedy", source="D", seed=42)
206
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
207
+ validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
208
+
209
+ cycle = self.tsp(self.UG2, "greedy", move="1-0", source="D", seed=42)
210
+ cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
211
+ validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
212
+
213
+ def test_error_on_input_order_mistake(self):
214
+ # see issue #4846 https://github.com/networkx/networkx/issues/4846
215
+ pytest.raises(TypeError, self.tsp, self.UG, weight="weight")
216
+ pytest.raises(nx.NetworkXError, self.tsp, self.UG, "weight")
217
+
218
+ def test_not_complete_graph(self):
219
+ pytest.raises(nx.NetworkXError, self.tsp, self.incompleteUG, "greedy", source=0)
220
+ pytest.raises(nx.NetworkXError, self.tsp, self.incompleteDG, "greedy", source=0)
221
+
222
+ def test_ignore_selfloops(self):
223
+ G = nx.complete_graph(5)
224
+ G.add_edge(3, 3)
225
+ cycle = self.tsp(G, "greedy")
226
+ assert len(cycle) - 1 == len(G) == len(set(cycle))
227
+
228
+ def test_not_weighted_graph(self):
229
+ self.tsp(self.unweightedUG, "greedy")
230
+ self.tsp(self.unweightedDG, "greedy")
231
+
232
+ def test_two_nodes(self):
233
+ G = nx.Graph()
234
+ G.add_weighted_edges_from({(1, 2, 1)})
235
+
236
+ cycle = self.tsp(G, "greedy", source=1, seed=42)
237
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
238
+ validate_solution(cycle, cost, [1, 2, 1], 2)
239
+
240
+ cycle = self.tsp(G, [1, 2, 1], source=1, seed=42)
241
+ cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
242
+ validate_solution(cycle, cost, [1, 2, 1], 2)
243
+
244
+ def test_failure_of_costs_too_high_when_iterations_low(self):
245
+ # Simulated Annealing Version:
246
+ # set number of moves low and alpha high
247
+ cycle = self.tsp(
248
+ self.DG2, "greedy", source="D", move="1-0", alpha=1, N_inner=1, seed=42
249
+ )
250
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
251
+ print(cycle, cost)
252
+ assert cost > self.DG2_cost
253
+
254
+ # Try with an incorrect initial guess
255
+ initial_sol = ["D", "A", "B", "C", "D"]
256
+ cycle = self.tsp(
257
+ self.DG,
258
+ initial_sol,
259
+ source="D",
260
+ move="1-0",
261
+ alpha=0.1,
262
+ N_inner=1,
263
+ max_iterations=1,
264
+ seed=42,
265
+ )
266
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
267
+ print(cycle, cost)
268
+ assert cost > self.DG_cost
269
+
270
+
271
+ class TestThresholdAcceptingTSP(TestSimulatedAnnealingTSP):
272
+ tsp = staticmethod(nx_app.threshold_accepting_tsp)
273
+
274
+ def test_failure_of_costs_too_high_when_iterations_low(self):
275
+ # Threshold Version:
276
+ # set number of moves low and number of iterations low
277
+ cycle = self.tsp(
278
+ self.DG2,
279
+ "greedy",
280
+ source="D",
281
+ move="1-0",
282
+ N_inner=1,
283
+ max_iterations=1,
284
+ seed=4,
285
+ )
286
+ cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
287
+ assert cost > self.DG2_cost
288
+
289
+ # set threshold too low
290
+ initial_sol = ["D", "A", "B", "C", "D"]
291
+ cycle = self.tsp(
292
+ self.DG, initial_sol, source="D", move="1-0", threshold=-3, seed=42
293
+ )
294
+ cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
295
+ assert cost > self.DG_cost
296
+
297
+
298
+ # Tests for function traveling_salesman_problem
299
+ def test_TSP_method():
300
+ G = nx.cycle_graph(9)
301
+ G[4][5]["weight"] = 10
302
+
303
+ def my_tsp_method(G, weight):
304
+ return nx_app.simulated_annealing_tsp(G, "greedy", weight, source=4, seed=1)
305
+
306
+ path = nx_app.traveling_salesman_problem(G, method=my_tsp_method, cycle=False)
307
+ print(path)
308
+ assert path == [4, 3, 2, 1, 0, 8, 7, 6, 5]
309
+
310
+
311
+ def test_TSP_unweighted():
312
+ G = nx.cycle_graph(9)
313
+ path = nx_app.traveling_salesman_problem(G, nodes=[3, 6], cycle=False)
314
+ assert path in ([3, 4, 5, 6], [6, 5, 4, 3])
315
+
316
+ cycle = nx_app.traveling_salesman_problem(G, nodes=[3, 6])
317
+ assert cycle in ([3, 4, 5, 6, 5, 4, 3], [6, 5, 4, 3, 4, 5, 6])
318
+
319
+
320
+ def test_TSP_weighted():
321
+ G = nx.cycle_graph(9)
322
+ G[0][1]["weight"] = 2
323
+ G[1][2]["weight"] = 2
324
+ G[2][3]["weight"] = 2
325
+ G[3][4]["weight"] = 4
326
+ G[4][5]["weight"] = 5
327
+ G[5][6]["weight"] = 4
328
+ G[6][7]["weight"] = 2
329
+ G[7][8]["weight"] = 2
330
+ G[8][0]["weight"] = 2
331
+ tsp = nx_app.traveling_salesman_problem
332
+
333
+ # path between 3 and 6
334
+ expected_paths = ([3, 2, 1, 0, 8, 7, 6], [6, 7, 8, 0, 1, 2, 3])
335
+ # cycle between 3 and 6
336
+ expected_cycles = (
337
+ [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3],
338
+ [6, 7, 8, 0, 1, 2, 3, 2, 1, 0, 8, 7, 6],
339
+ )
340
+ # path through all nodes
341
+ expected_tourpaths = ([5, 6, 7, 8, 0, 1, 2, 3, 4], [4, 3, 2, 1, 0, 8, 7, 6, 5])
342
+
343
+ # Check default method
344
+ cycle = tsp(G, nodes=[3, 6], weight="weight")
345
+ assert cycle in expected_cycles
346
+
347
+ path = tsp(G, nodes=[3, 6], weight="weight", cycle=False)
348
+ assert path in expected_paths
349
+
350
+ tourpath = tsp(G, weight="weight", cycle=False)
351
+ assert tourpath in expected_tourpaths
352
+
353
+ # Check all methods
354
+ methods = [
355
+ nx_app.christofides,
356
+ nx_app.greedy_tsp,
357
+ lambda G, wt: nx_app.simulated_annealing_tsp(G, "greedy", weight=wt),
358
+ lambda G, wt: nx_app.threshold_accepting_tsp(G, "greedy", weight=wt),
359
+ ]
360
+ for method in methods:
361
+ cycle = tsp(G, nodes=[3, 6], weight="weight", method=method)
362
+ assert cycle in expected_cycles
363
+
364
+ path = tsp(G, nodes=[3, 6], weight="weight", method=method, cycle=False)
365
+ assert path in expected_paths
366
+
367
+ tourpath = tsp(G, weight="weight", method=method, cycle=False)
368
+ assert tourpath in expected_tourpaths
369
+
370
+
371
+ def test_TSP_incomplete_graph_short_path():
372
+ G = nx.cycle_graph(9)
373
+ G.add_edges_from([(4, 9), (9, 10), (10, 11), (11, 0)])
374
+ G[4][5]["weight"] = 5
375
+
376
+ cycle = nx_app.traveling_salesman_problem(G)
377
+ print(cycle)
378
+ assert len(cycle) == 17 and len(set(cycle)) == 12
379
+
380
+ # make sure that cutting one edge out of complete graph formulation
381
+ # cuts out many edges out of the path of the TSP
382
+ path = nx_app.traveling_salesman_problem(G, cycle=False)
383
+ print(path)
384
+ assert len(path) == 13 and len(set(path)) == 12
385
+
386
+
387
+ def test_held_karp_ascent():
388
+ """
389
+ Test the Held-Karp relaxation with the ascent method
390
+ """
391
+ import networkx.algorithms.approximation.traveling_salesman as tsp
392
+
393
+ np = pytest.importorskip("numpy")
394
+ pytest.importorskip("scipy")
395
+
396
+ # Adjacency matrix from page 1153 of the 1970 Held and Karp paper
397
+ # which have been edited to be directional, but also symmetric
398
+ G_array = np.array(
399
+ [
400
+ [0, 97, 60, 73, 17, 52],
401
+ [97, 0, 41, 52, 90, 30],
402
+ [60, 41, 0, 21, 35, 41],
403
+ [73, 52, 21, 0, 95, 46],
404
+ [17, 90, 35, 95, 0, 81],
405
+ [52, 30, 41, 46, 81, 0],
406
+ ]
407
+ )
408
+
409
+ solution_edges = [(1, 3), (2, 4), (3, 2), (4, 0), (5, 1), (0, 5)]
410
+
411
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
412
+ opt_hk, z_star = tsp.held_karp_ascent(G)
413
+
414
+ # Check that the optimal weights are the same
415
+ assert round(opt_hk, 2) == 207.00
416
+ # Check that the z_stars are the same
417
+ solution = nx.DiGraph()
418
+ solution.add_edges_from(solution_edges)
419
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
420
+
421
+
422
+ def test_ascent_fractional_solution():
423
+ """
424
+ Test the ascent method using a modified version of Figure 2 on page 1140
425
+ in 'The Traveling Salesman Problem and Minimum Spanning Trees' by Held and
426
+ Karp
427
+ """
428
+ import networkx.algorithms.approximation.traveling_salesman as tsp
429
+
430
+ np = pytest.importorskip("numpy")
431
+ pytest.importorskip("scipy")
432
+
433
+ # This version of Figure 2 has all of the edge weights multiplied by 100
434
+ # and is a complete directed graph with infinite edge weights for the
435
+ # edges not listed in the original graph
436
+ G_array = np.array(
437
+ [
438
+ [0, 100, 100, 100000, 100000, 1],
439
+ [100, 0, 100, 100000, 1, 100000],
440
+ [100, 100, 0, 1, 100000, 100000],
441
+ [100000, 100000, 1, 0, 100, 100],
442
+ [100000, 1, 100000, 100, 0, 100],
443
+ [1, 100000, 100000, 100, 100, 0],
444
+ ]
445
+ )
446
+
447
+ solution_z_star = {
448
+ (0, 1): 5 / 12,
449
+ (0, 2): 5 / 12,
450
+ (0, 5): 5 / 6,
451
+ (1, 0): 5 / 12,
452
+ (1, 2): 1 / 3,
453
+ (1, 4): 5 / 6,
454
+ (2, 0): 5 / 12,
455
+ (2, 1): 1 / 3,
456
+ (2, 3): 5 / 6,
457
+ (3, 2): 5 / 6,
458
+ (3, 4): 1 / 3,
459
+ (3, 5): 1 / 2,
460
+ (4, 1): 5 / 6,
461
+ (4, 3): 1 / 3,
462
+ (4, 5): 1 / 2,
463
+ (5, 0): 5 / 6,
464
+ (5, 3): 1 / 2,
465
+ (5, 4): 1 / 2,
466
+ }
467
+
468
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
469
+ opt_hk, z_star = tsp.held_karp_ascent(G)
470
+
471
+ # Check that the optimal weights are the same
472
+ assert round(opt_hk, 2) == 303.00
473
+ # Check that the z_stars are the same
474
+ assert {key: round(z_star[key], 4) for key in z_star} == {
475
+ key: round(solution_z_star[key], 4) for key in solution_z_star
476
+ }
477
+
478
+
479
+ def test_ascent_method_asymmetric():
480
+ """
481
+ Tests the ascent method using a truly asymmetric graph for which the
482
+ solution has been brute forced
483
+ """
484
+ import networkx.algorithms.approximation.traveling_salesman as tsp
485
+
486
+ np = pytest.importorskip("numpy")
487
+ pytest.importorskip("scipy")
488
+
489
+ G_array = np.array(
490
+ [
491
+ [0, 26, 63, 59, 69, 31, 41],
492
+ [62, 0, 91, 53, 75, 87, 47],
493
+ [47, 82, 0, 90, 15, 9, 18],
494
+ [68, 19, 5, 0, 58, 34, 93],
495
+ [11, 58, 53, 55, 0, 61, 79],
496
+ [88, 75, 13, 76, 98, 0, 40],
497
+ [41, 61, 55, 88, 46, 45, 0],
498
+ ]
499
+ )
500
+
501
+ solution_edges = [(0, 1), (1, 3), (3, 2), (2, 5), (5, 6), (4, 0), (6, 4)]
502
+
503
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
504
+ opt_hk, z_star = tsp.held_karp_ascent(G)
505
+
506
+ # Check that the optimal weights are the same
507
+ assert round(opt_hk, 2) == 190.00
508
+ # Check that the z_stars match.
509
+ solution = nx.DiGraph()
510
+ solution.add_edges_from(solution_edges)
511
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
512
+
513
+
514
+ def test_ascent_method_asymmetric_2():
515
+ """
516
+ Tests the ascent method using a truly asymmetric graph for which the
517
+ solution has been brute forced
518
+ """
519
+ import networkx.algorithms.approximation.traveling_salesman as tsp
520
+
521
+ np = pytest.importorskip("numpy")
522
+ pytest.importorskip("scipy")
523
+
524
+ G_array = np.array(
525
+ [
526
+ [0, 45, 39, 92, 29, 31],
527
+ [72, 0, 4, 12, 21, 60],
528
+ [81, 6, 0, 98, 70, 53],
529
+ [49, 71, 59, 0, 98, 94],
530
+ [74, 95, 24, 43, 0, 47],
531
+ [56, 43, 3, 65, 22, 0],
532
+ ]
533
+ )
534
+
535
+ solution_edges = [(0, 5), (5, 4), (1, 3), (3, 0), (2, 1), (4, 2)]
536
+
537
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
538
+ opt_hk, z_star = tsp.held_karp_ascent(G)
539
+
540
+ # Check that the optimal weights are the same
541
+ assert round(opt_hk, 2) == 144.00
542
+ # Check that the z_stars match.
543
+ solution = nx.DiGraph()
544
+ solution.add_edges_from(solution_edges)
545
+ assert nx.utils.edges_equal(z_star.edges, solution.edges)
546
+
547
+
548
+ def test_held_karp_ascent_asymmetric_3():
549
+ """
550
+ Tests the ascent method using a truly asymmetric graph with a fractional
551
+ solution for which the solution has been brute forced.
552
+
553
+ In this graph their are two different optimal, integral solutions (which
554
+ are also the overall atsp solutions) to the Held Karp relaxation. However,
555
+ this particular graph has two different tours of optimal value and the
556
+ possible solutions in the held_karp_ascent function are not stored in an
557
+ ordered data structure.
558
+ """
559
+ import networkx.algorithms.approximation.traveling_salesman as tsp
560
+
561
+ np = pytest.importorskip("numpy")
562
+ pytest.importorskip("scipy")
563
+
564
+ G_array = np.array(
565
+ [
566
+ [0, 1, 5, 2, 7, 4],
567
+ [7, 0, 7, 7, 1, 4],
568
+ [4, 7, 0, 9, 2, 1],
569
+ [7, 2, 7, 0, 4, 4],
570
+ [5, 5, 4, 4, 0, 3],
571
+ [3, 9, 1, 3, 4, 0],
572
+ ]
573
+ )
574
+
575
+ solution1_edges = [(0, 3), (1, 4), (2, 5), (3, 1), (4, 2), (5, 0)]
576
+
577
+ solution2_edges = [(0, 3), (3, 1), (1, 4), (4, 5), (2, 0), (5, 2)]
578
+
579
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
580
+ opt_hk, z_star = tsp.held_karp_ascent(G)
581
+
582
+ assert round(opt_hk, 2) == 13.00
583
+ # Check that the z_stars are the same
584
+ solution1 = nx.DiGraph()
585
+ solution1.add_edges_from(solution1_edges)
586
+ solution2 = nx.DiGraph()
587
+ solution2.add_edges_from(solution2_edges)
588
+ assert nx.utils.edges_equal(z_star.edges, solution1.edges) or nx.utils.edges_equal(
589
+ z_star.edges, solution2.edges
590
+ )
591
+
592
+
593
+ def test_held_karp_ascent_fractional_asymmetric():
594
+ """
595
+ Tests the ascent method using a truly asymmetric graph with a fractional
596
+ solution for which the solution has been brute forced
597
+ """
598
+ import networkx.algorithms.approximation.traveling_salesman as tsp
599
+
600
+ np = pytest.importorskip("numpy")
601
+ pytest.importorskip("scipy")
602
+
603
+ G_array = np.array(
604
+ [
605
+ [0, 100, 150, 100000, 100000, 1],
606
+ [150, 0, 100, 100000, 1, 100000],
607
+ [100, 150, 0, 1, 100000, 100000],
608
+ [100000, 100000, 1, 0, 150, 100],
609
+ [100000, 2, 100000, 100, 0, 150],
610
+ [2, 100000, 100000, 150, 100, 0],
611
+ ]
612
+ )
613
+
614
+ solution_z_star = {
615
+ (0, 1): 5 / 12,
616
+ (0, 2): 5 / 12,
617
+ (0, 5): 5 / 6,
618
+ (1, 0): 5 / 12,
619
+ (1, 2): 5 / 12,
620
+ (1, 4): 5 / 6,
621
+ (2, 0): 5 / 12,
622
+ (2, 1): 5 / 12,
623
+ (2, 3): 5 / 6,
624
+ (3, 2): 5 / 6,
625
+ (3, 4): 5 / 12,
626
+ (3, 5): 5 / 12,
627
+ (4, 1): 5 / 6,
628
+ (4, 3): 5 / 12,
629
+ (4, 5): 5 / 12,
630
+ (5, 0): 5 / 6,
631
+ (5, 3): 5 / 12,
632
+ (5, 4): 5 / 12,
633
+ }
634
+
635
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
636
+ opt_hk, z_star = tsp.held_karp_ascent(G)
637
+
638
+ # Check that the optimal weights are the same
639
+ assert round(opt_hk, 2) == 304.00
640
+ # Check that the z_stars are the same
641
+ assert {key: round(z_star[key], 4) for key in z_star} == {
642
+ key: round(solution_z_star[key], 4) for key in solution_z_star
643
+ }
644
+
645
+
646
+ def test_spanning_tree_distribution():
647
+ """
648
+ Test that we can create an exponential distribution of spanning trees such
649
+ that the probability of each tree is proportional to the product of edge
650
+ weights.
651
+
652
+ Results of this test have been confirmed with hypothesis testing from the
653
+ created distribution.
654
+
655
+ This test uses the symmetric, fractional Held Karp solution.
656
+ """
657
+ import networkx.algorithms.approximation.traveling_salesman as tsp
658
+
659
+ pytest.importorskip("numpy")
660
+ pytest.importorskip("scipy")
661
+
662
+ z_star = {
663
+ (0, 1): 5 / 12,
664
+ (0, 2): 5 / 12,
665
+ (0, 5): 5 / 6,
666
+ (1, 0): 5 / 12,
667
+ (1, 2): 1 / 3,
668
+ (1, 4): 5 / 6,
669
+ (2, 0): 5 / 12,
670
+ (2, 1): 1 / 3,
671
+ (2, 3): 5 / 6,
672
+ (3, 2): 5 / 6,
673
+ (3, 4): 1 / 3,
674
+ (3, 5): 1 / 2,
675
+ (4, 1): 5 / 6,
676
+ (4, 3): 1 / 3,
677
+ (4, 5): 1 / 2,
678
+ (5, 0): 5 / 6,
679
+ (5, 3): 1 / 2,
680
+ (5, 4): 1 / 2,
681
+ }
682
+
683
+ solution_gamma = {
684
+ (0, 1): -0.6383,
685
+ (0, 2): -0.6827,
686
+ (0, 5): 0,
687
+ (1, 2): -1.0781,
688
+ (1, 4): 0,
689
+ (2, 3): 0,
690
+ (5, 3): -0.2820,
691
+ (5, 4): -0.3327,
692
+ (4, 3): -0.9927,
693
+ }
694
+
695
+ # The undirected support of z_star
696
+ G = nx.MultiGraph()
697
+ for u, v in z_star:
698
+ if (u, v) in G.edges or (v, u) in G.edges:
699
+ continue
700
+ G.add_edge(u, v)
701
+
702
+ gamma = tsp.spanning_tree_distribution(G, z_star)
703
+
704
+ assert {key: round(gamma[key], 4) for key in gamma} == solution_gamma
705
+
706
+
707
+ def test_asadpour_tsp():
708
+ """
709
+ Test the complete asadpour tsp algorithm with the fractional, symmetric
710
+ Held Karp solution. This test also uses an incomplete graph as input.
711
+ """
712
+ # This version of Figure 2 has all of the edge weights multiplied by 100
713
+ # and the 0 weight edges have a weight of 1.
714
+ pytest.importorskip("numpy")
715
+ pytest.importorskip("scipy")
716
+
717
+ edge_list = [
718
+ (0, 1, 100),
719
+ (0, 2, 100),
720
+ (0, 5, 1),
721
+ (1, 2, 100),
722
+ (1, 4, 1),
723
+ (2, 3, 1),
724
+ (3, 4, 100),
725
+ (3, 5, 100),
726
+ (4, 5, 100),
727
+ (1, 0, 100),
728
+ (2, 0, 100),
729
+ (5, 0, 1),
730
+ (2, 1, 100),
731
+ (4, 1, 1),
732
+ (3, 2, 1),
733
+ (4, 3, 100),
734
+ (5, 3, 100),
735
+ (5, 4, 100),
736
+ ]
737
+
738
+ G = nx.DiGraph()
739
+ G.add_weighted_edges_from(edge_list)
740
+
741
+ def fixed_asadpour(G, weight):
742
+ return nx_app.asadpour_atsp(G, weight, 19)
743
+
744
+ tour = nx_app.traveling_salesman_problem(G, weight="weight", method=fixed_asadpour)
745
+
746
+ # Check that the returned list is a valid tour. Because this is an
747
+ # incomplete graph, the conditions are not as strict. We need the tour to
748
+ #
749
+ # Start and end at the same node
750
+ # Pass through every vertex at least once
751
+ # Have a total cost at most ln(6) / ln(ln(6)) = 3.0723 times the optimal
752
+ #
753
+ # For the second condition it is possible to have the tour pass through the
754
+ # same vertex more then. Imagine that the tour on the complete version takes
755
+ # an edge not in the original graph. In the output this is substituted with
756
+ # the shortest path between those vertices, allowing vertices to appear more
757
+ # than once.
758
+ #
759
+ # However, we are using a fixed random number generator so we know what the
760
+ # expected tour is.
761
+ expected_tours = [[1, 4, 5, 0, 2, 3, 2, 1], [3, 2, 0, 1, 4, 5, 3]]
762
+
763
+ assert tour in expected_tours
764
+
765
+
766
+ def test_asadpour_real_world():
767
+ """
768
+ This test uses airline prices between the six largest cities in the US.
769
+
770
+ * New York City -> JFK
771
+ * Los Angeles -> LAX
772
+ * Chicago -> ORD
773
+ * Houston -> IAH
774
+ * Phoenix -> PHX
775
+ * Philadelphia -> PHL
776
+
777
+ Flight prices from August 2021 using Delta or American airlines to get
778
+ nonstop flight. The brute force solution found the optimal tour to cost $872
779
+
780
+ This test also uses the `source` keyword argument to ensure that the tour
781
+ always starts at city 0.
782
+ """
783
+ np = pytest.importorskip("numpy")
784
+ pytest.importorskip("scipy")
785
+
786
+ G_array = np.array(
787
+ [
788
+ # JFK LAX ORD IAH PHX PHL
789
+ [0, 243, 199, 208, 169, 183], # JFK
790
+ [277, 0, 217, 123, 127, 252], # LAX
791
+ [297, 197, 0, 197, 123, 177], # ORD
792
+ [303, 169, 197, 0, 117, 117], # IAH
793
+ [257, 127, 160, 117, 0, 319], # PHX
794
+ [183, 332, 217, 117, 319, 0], # PHL
795
+ ]
796
+ )
797
+
798
+ node_map = {0: "JFK", 1: "LAX", 2: "ORD", 3: "IAH", 4: "PHX", 5: "PHL"}
799
+
800
+ expected_tours = [
801
+ ["JFK", "LAX", "PHX", "ORD", "IAH", "PHL", "JFK"],
802
+ ["JFK", "ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
803
+ ]
804
+
805
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
806
+ nx.relabel_nodes(G, node_map, copy=False)
807
+
808
+ def fixed_asadpour(G, weight):
809
+ return nx_app.asadpour_atsp(G, weight, 37, source="JFK")
810
+
811
+ tour = nx_app.traveling_salesman_problem(G, weight="weight", method=fixed_asadpour)
812
+
813
+ assert tour in expected_tours
814
+
815
+
816
+ def test_asadpour_real_world_path():
817
+ """
818
+ This test uses airline prices between the six largest cities in the US. This
819
+ time using a path, not a cycle.
820
+
821
+ * New York City -> JFK
822
+ * Los Angeles -> LAX
823
+ * Chicago -> ORD
824
+ * Houston -> IAH
825
+ * Phoenix -> PHX
826
+ * Philadelphia -> PHL
827
+
828
+ Flight prices from August 2021 using Delta or American airlines to get
829
+ nonstop flight. The brute force solution found the optimal tour to cost $872
830
+ """
831
+ np = pytest.importorskip("numpy")
832
+ pytest.importorskip("scipy")
833
+
834
+ G_array = np.array(
835
+ [
836
+ # JFK LAX ORD IAH PHX PHL
837
+ [0, 243, 199, 208, 169, 183], # JFK
838
+ [277, 0, 217, 123, 127, 252], # LAX
839
+ [297, 197, 0, 197, 123, 177], # ORD
840
+ [303, 169, 197, 0, 117, 117], # IAH
841
+ [257, 127, 160, 117, 0, 319], # PHX
842
+ [183, 332, 217, 117, 319, 0], # PHL
843
+ ]
844
+ )
845
+
846
+ node_map = {0: "JFK", 1: "LAX", 2: "ORD", 3: "IAH", 4: "PHX", 5: "PHL"}
847
+
848
+ expected_paths = [
849
+ ["ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
850
+ ["JFK", "PHL", "IAH", "ORD", "PHX", "LAX"],
851
+ ]
852
+
853
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
854
+ nx.relabel_nodes(G, node_map, copy=False)
855
+
856
+ def fixed_asadpour(G, weight):
857
+ return nx_app.asadpour_atsp(G, weight, 56)
858
+
859
+ path = nx_app.traveling_salesman_problem(
860
+ G, weight="weight", cycle=False, method=fixed_asadpour
861
+ )
862
+
863
+ assert path in expected_paths
864
+
865
+
866
+ def test_asadpour_disconnected_graph():
867
+ """
868
+ Test that the proper exception is raised when asadpour_atsp is given an
869
+ disconnected graph.
870
+ """
871
+
872
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
873
+ # have to set edge weights so that if the exception is not raised, the
874
+ # function will complete and we will fail the test
875
+ nx.set_edge_attributes(G, 1, "weight")
876
+ G.add_node(5)
877
+
878
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
879
+
880
+
881
+ def test_asadpour_incomplete_graph():
882
+ """
883
+ Test that the proper exception is raised when asadpour_atsp is given an
884
+ incomplete graph
885
+ """
886
+
887
+ G = nx.complete_graph(4, create_using=nx.DiGraph)
888
+ # have to set edge weights so that if the exception is not raised, the
889
+ # function will complete and we will fail the test
890
+ nx.set_edge_attributes(G, 1, "weight")
891
+ G.remove_edge(0, 1)
892
+
893
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
894
+
895
+
896
+ def test_asadpour_empty_graph():
897
+ """
898
+ Test the asadpour_atsp function with an empty graph
899
+ """
900
+ G = nx.DiGraph()
901
+
902
+ pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
903
+
904
+
905
+ @pytest.mark.slow
906
+ def test_asadpour_integral_held_karp():
907
+ """
908
+ This test uses an integral held karp solution and the held karp function
909
+ will return a graph rather than a dict, bypassing most of the asadpour
910
+ algorithm.
911
+
912
+ At first glance, this test probably doesn't look like it ensures that we
913
+ skip the rest of the asadpour algorithm, but it does. We are not fixing a
914
+ see for the random number generator, so if we sample any spanning trees
915
+ the approximation would be different basically every time this test is
916
+ executed but it is not since held karp is deterministic and we do not
917
+ reach the portion of the code with the dependence on random numbers.
918
+ """
919
+ np = pytest.importorskip("numpy")
920
+
921
+ G_array = np.array(
922
+ [
923
+ [0, 26, 63, 59, 69, 31, 41],
924
+ [62, 0, 91, 53, 75, 87, 47],
925
+ [47, 82, 0, 90, 15, 9, 18],
926
+ [68, 19, 5, 0, 58, 34, 93],
927
+ [11, 58, 53, 55, 0, 61, 79],
928
+ [88, 75, 13, 76, 98, 0, 40],
929
+ [41, 61, 55, 88, 46, 45, 0],
930
+ ]
931
+ )
932
+
933
+ G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
934
+
935
+ for _ in range(2):
936
+ tour = nx_app.traveling_salesman_problem(G, method=nx_app.asadpour_atsp)
937
+
938
+ assert [1, 3, 2, 5, 2, 6, 4, 0, 1] == tour
939
+
940
+
941
+ def test_directed_tsp_impossible():
942
+ """
943
+ Test the asadpour algorithm with a graph without a hamiltonian circuit
944
+ """
945
+ pytest.importorskip("numpy")
946
+
947
+ # In this graph, once we leave node 0 we cannot return
948
+ edges = [
949
+ (0, 1, 10),
950
+ (0, 2, 11),
951
+ (0, 3, 12),
952
+ (1, 2, 4),
953
+ (1, 3, 6),
954
+ (2, 1, 3),
955
+ (2, 3, 2),
956
+ (3, 1, 5),
957
+ (3, 2, 1),
958
+ ]
959
+
960
+ G = nx.DiGraph()
961
+ G.add_weighted_edges_from(edges)
962
+
963
+ pytest.raises(nx.NetworkXError, nx_app.traveling_salesman_problem, G)
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ treewidth_min_degree,
6
+ treewidth_min_fill_in,
7
+ )
8
+ from networkx.algorithms.approximation.treewidth import (
9
+ MinDegreeHeuristic,
10
+ min_fill_in_heuristic,
11
+ )
12
+
13
+
14
+ def is_tree_decomp(graph, decomp):
15
+ """Check if the given tree decomposition is valid."""
16
+ for x in graph.nodes():
17
+ appear_once = False
18
+ for bag in decomp.nodes():
19
+ if x in bag:
20
+ appear_once = True
21
+ break
22
+ assert appear_once
23
+
24
+ # Check if each connected pair of nodes are at least once together in a bag
25
+ for (x, y) in graph.edges():
26
+ appear_together = False
27
+ for bag in decomp.nodes():
28
+ if x in bag and y in bag:
29
+ appear_together = True
30
+ break
31
+ assert appear_together
32
+
33
+ # Check if the nodes associated with vertex v form a connected subset of T
34
+ for v in graph.nodes():
35
+ subset = []
36
+ for bag in decomp.nodes():
37
+ if v in bag:
38
+ subset.append(bag)
39
+ sub_graph = decomp.subgraph(subset)
40
+ assert nx.is_connected(sub_graph)
41
+
42
+
43
+ class TestTreewidthMinDegree:
44
+ """Unit tests for the min_degree function"""
45
+
46
+ @classmethod
47
+ def setup_class(cls):
48
+ """Setup for different kinds of trees"""
49
+ cls.complete = nx.Graph()
50
+ cls.complete.add_edge(1, 2)
51
+ cls.complete.add_edge(2, 3)
52
+ cls.complete.add_edge(1, 3)
53
+
54
+ cls.small_tree = nx.Graph()
55
+ cls.small_tree.add_edge(1, 3)
56
+ cls.small_tree.add_edge(4, 3)
57
+ cls.small_tree.add_edge(2, 3)
58
+ cls.small_tree.add_edge(3, 5)
59
+ cls.small_tree.add_edge(5, 6)
60
+ cls.small_tree.add_edge(5, 7)
61
+ cls.small_tree.add_edge(6, 7)
62
+
63
+ cls.deterministic_graph = nx.Graph()
64
+ cls.deterministic_graph.add_edge(0, 1) # deg(0) = 1
65
+
66
+ cls.deterministic_graph.add_edge(1, 2) # deg(1) = 2
67
+
68
+ cls.deterministic_graph.add_edge(2, 3)
69
+ cls.deterministic_graph.add_edge(2, 4) # deg(2) = 3
70
+
71
+ cls.deterministic_graph.add_edge(3, 4)
72
+ cls.deterministic_graph.add_edge(3, 5)
73
+ cls.deterministic_graph.add_edge(3, 6) # deg(3) = 4
74
+
75
+ cls.deterministic_graph.add_edge(4, 5)
76
+ cls.deterministic_graph.add_edge(4, 6)
77
+ cls.deterministic_graph.add_edge(4, 7) # deg(4) = 5
78
+
79
+ cls.deterministic_graph.add_edge(5, 6)
80
+ cls.deterministic_graph.add_edge(5, 7)
81
+ cls.deterministic_graph.add_edge(5, 8)
82
+ cls.deterministic_graph.add_edge(5, 9) # deg(5) = 6
83
+
84
+ cls.deterministic_graph.add_edge(6, 7)
85
+ cls.deterministic_graph.add_edge(6, 8)
86
+ cls.deterministic_graph.add_edge(6, 9) # deg(6) = 6
87
+
88
+ cls.deterministic_graph.add_edge(7, 8)
89
+ cls.deterministic_graph.add_edge(7, 9) # deg(7) = 5
90
+
91
+ cls.deterministic_graph.add_edge(8, 9) # deg(8) = 4
92
+
93
+ def test_petersen_graph(self):
94
+ """Test Petersen graph tree decomposition result"""
95
+ G = nx.petersen_graph()
96
+ _, decomp = treewidth_min_degree(G)
97
+ is_tree_decomp(G, decomp)
98
+
99
+ def test_small_tree_treewidth(self):
100
+ """Test small tree
101
+
102
+ Test if the computed treewidth of the known self.small_tree is 2.
103
+ As we know which value we can expect from our heuristic, values other
104
+ than two are regressions
105
+ """
106
+ G = self.small_tree
107
+ # the order of removal should be [1,2,4]3[5,6,7]
108
+ # (with [] denoting any order of the containing nodes)
109
+ # resulting in treewidth 2 for the heuristic
110
+ treewidth, _ = treewidth_min_fill_in(G)
111
+ assert treewidth == 2
112
+
113
+ def test_heuristic_abort(self):
114
+ """Test heuristic abort condition for fully connected graph"""
115
+ graph = {}
116
+ for u in self.complete:
117
+ graph[u] = set()
118
+ for v in self.complete[u]:
119
+ if u != v: # ignore self-loop
120
+ graph[u].add(v)
121
+
122
+ deg_heuristic = MinDegreeHeuristic(graph)
123
+ node = deg_heuristic.best_node(graph)
124
+ if node is None:
125
+ pass
126
+ else:
127
+ assert False
128
+
129
+ def test_empty_graph(self):
130
+ """Test empty graph"""
131
+ G = nx.Graph()
132
+ _, _ = treewidth_min_degree(G)
133
+
134
+ def test_two_component_graph(self):
135
+ G = nx.Graph()
136
+ G.add_node(1)
137
+ G.add_node(2)
138
+ treewidth, _ = treewidth_min_degree(G)
139
+ assert treewidth == 0
140
+
141
+ def test_not_sortable_nodes(self):
142
+ G = nx.Graph([(0, "a")])
143
+ treewidth_min_degree(G)
144
+
145
+ def test_heuristic_first_steps(self):
146
+ """Test first steps of min_degree heuristic"""
147
+ graph = {
148
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
149
+ }
150
+ deg_heuristic = MinDegreeHeuristic(graph)
151
+ elim_node = deg_heuristic.best_node(graph)
152
+ print(f"Graph {graph}:")
153
+ steps = []
154
+
155
+ while elim_node is not None:
156
+ print(f"Removing {elim_node}:")
157
+ steps.append(elim_node)
158
+ nbrs = graph[elim_node]
159
+
160
+ for u, v in itertools.permutations(nbrs, 2):
161
+ if v not in graph[u]:
162
+ graph[u].add(v)
163
+
164
+ for u in graph:
165
+ if elim_node in graph[u]:
166
+ graph[u].remove(elim_node)
167
+
168
+ del graph[elim_node]
169
+ print(f"Graph {graph}:")
170
+ elim_node = deg_heuristic.best_node(graph)
171
+
172
+ # check only the first 5 elements for equality
173
+ assert steps[:5] == [0, 1, 2, 3, 4]
174
+
175
+
176
+ class TestTreewidthMinFillIn:
177
+ """Unit tests for the treewidth_min_fill_in function."""
178
+
179
+ @classmethod
180
+ def setup_class(cls):
181
+ """Setup for different kinds of trees"""
182
+ cls.complete = nx.Graph()
183
+ cls.complete.add_edge(1, 2)
184
+ cls.complete.add_edge(2, 3)
185
+ cls.complete.add_edge(1, 3)
186
+
187
+ cls.small_tree = nx.Graph()
188
+ cls.small_tree.add_edge(1, 2)
189
+ cls.small_tree.add_edge(2, 3)
190
+ cls.small_tree.add_edge(3, 4)
191
+ cls.small_tree.add_edge(1, 4)
192
+ cls.small_tree.add_edge(2, 4)
193
+ cls.small_tree.add_edge(4, 5)
194
+ cls.small_tree.add_edge(5, 6)
195
+ cls.small_tree.add_edge(5, 7)
196
+ cls.small_tree.add_edge(6, 7)
197
+
198
+ cls.deterministic_graph = nx.Graph()
199
+ cls.deterministic_graph.add_edge(1, 2)
200
+ cls.deterministic_graph.add_edge(1, 3)
201
+ cls.deterministic_graph.add_edge(3, 4)
202
+ cls.deterministic_graph.add_edge(2, 4)
203
+ cls.deterministic_graph.add_edge(3, 5)
204
+ cls.deterministic_graph.add_edge(4, 5)
205
+ cls.deterministic_graph.add_edge(3, 6)
206
+ cls.deterministic_graph.add_edge(5, 6)
207
+
208
+ def test_petersen_graph(self):
209
+ """Test Petersen graph tree decomposition result"""
210
+ G = nx.petersen_graph()
211
+ _, decomp = treewidth_min_fill_in(G)
212
+ is_tree_decomp(G, decomp)
213
+
214
+ def test_small_tree_treewidth(self):
215
+ """Test if the computed treewidth of the known self.small_tree is 2"""
216
+ G = self.small_tree
217
+ # the order of removal should be [1,2,4]3[5,6,7]
218
+ # (with [] denoting any order of the containing nodes)
219
+ # resulting in treewidth 2 for the heuristic
220
+ treewidth, _ = treewidth_min_fill_in(G)
221
+ assert treewidth == 2
222
+
223
+ def test_heuristic_abort(self):
224
+ """Test if min_fill_in returns None for fully connected graph"""
225
+ graph = {}
226
+ for u in self.complete:
227
+ graph[u] = set()
228
+ for v in self.complete[u]:
229
+ if u != v: # ignore self-loop
230
+ graph[u].add(v)
231
+ next_node = min_fill_in_heuristic(graph)
232
+ if next_node is None:
233
+ pass
234
+ else:
235
+ assert False
236
+
237
+ def test_empty_graph(self):
238
+ """Test empty graph"""
239
+ G = nx.Graph()
240
+ _, _ = treewidth_min_fill_in(G)
241
+
242
+ def test_two_component_graph(self):
243
+ G = nx.Graph()
244
+ G.add_node(1)
245
+ G.add_node(2)
246
+ treewidth, _ = treewidth_min_fill_in(G)
247
+ assert treewidth == 0
248
+
249
+ def test_not_sortable_nodes(self):
250
+ G = nx.Graph([(0, "a")])
251
+ treewidth_min_fill_in(G)
252
+
253
+ def test_heuristic_first_steps(self):
254
+ """Test first steps of min_fill_in heuristic"""
255
+ graph = {
256
+ n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
257
+ }
258
+ print(f"Graph {graph}:")
259
+ elim_node = min_fill_in_heuristic(graph)
260
+ steps = []
261
+
262
+ while elim_node is not None:
263
+ print(f"Removing {elim_node}:")
264
+ steps.append(elim_node)
265
+ nbrs = graph[elim_node]
266
+
267
+ for u, v in itertools.permutations(nbrs, 2):
268
+ if v not in graph[u]:
269
+ graph[u].add(v)
270
+
271
+ for u in graph:
272
+ if elim_node in graph[u]:
273
+ graph[u].remove(elim_node)
274
+
275
+ del graph[elim_node]
276
+ print(f"Graph {graph}:")
277
+ elim_node = min_fill_in_heuristic(graph)
278
+
279
+ # check only the first 2 elements for equality
280
+ assert steps[:2] == [6, 5]
runtime/Lib/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import min_weighted_vertex_cover
3
+
4
+
5
+ def is_cover(G, node_cover):
6
+ return all({u, v} & node_cover for u, v in G.edges())
7
+
8
+
9
+ class TestMWVC:
10
+ """Unit tests for the approximate minimum weighted vertex cover
11
+ function,
12
+ :func:`~networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover`.
13
+
14
+ """
15
+
16
+ def test_unweighted_directed(self):
17
+ # Create a star graph in which half the nodes are directed in
18
+ # and half are directed out.
19
+ G = nx.DiGraph()
20
+ G.add_edges_from((0, v) for v in range(1, 26))
21
+ G.add_edges_from((v, 0) for v in range(26, 51))
22
+ cover = min_weighted_vertex_cover(G)
23
+ assert 1 == len(cover)
24
+ assert is_cover(G, cover)
25
+
26
+ def test_unweighted_undirected(self):
27
+ # create a simple star graph
28
+ size = 50
29
+ sg = nx.star_graph(size)
30
+ cover = min_weighted_vertex_cover(sg)
31
+ assert 1 == len(cover)
32
+ assert is_cover(sg, cover)
33
+
34
+ def test_weighted(self):
35
+ wg = nx.Graph()
36
+ wg.add_node(0, weight=10)
37
+ wg.add_node(1, weight=1)
38
+ wg.add_node(2, weight=1)
39
+ wg.add_node(3, weight=1)
40
+ wg.add_node(4, weight=1)
41
+
42
+ wg.add_edge(0, 1)
43
+ wg.add_edge(0, 2)
44
+ wg.add_edge(0, 3)
45
+ wg.add_edge(0, 4)
46
+
47
+ wg.add_edge(1, 2)
48
+ wg.add_edge(2, 3)
49
+ wg.add_edge(3, 4)
50
+ wg.add_edge(4, 1)
51
+
52
+ cover = min_weighted_vertex_cover(wg, weight="weight")
53
+ csum = sum(wg.nodes[node]["weight"] for node in cover)
54
+ assert 4 == csum
55
+ assert is_cover(wg, cover)
56
+
57
+ def test_unweighted_self_loop(self):
58
+ slg = nx.Graph()
59
+ slg.add_node(0)
60
+ slg.add_node(1)
61
+ slg.add_node(2)
62
+
63
+ slg.add_edge(0, 1)
64
+ slg.add_edge(2, 2)
65
+
66
+ cover = min_weighted_vertex_cover(slg)
67
+ assert 2 == len(cover)
68
+ assert is_cover(slg, cover)
runtime/Lib/site-packages/networkx/algorithms/approximation/traveling_salesman.py ADDED
@@ -0,0 +1,1434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =================================
3
+ Travelling Salesman Problem (TSP)
4
+ =================================
5
+
6
+ Implementation of approximate algorithms
7
+ for solving and approximating the TSP problem.
8
+
9
+ Categories of algorithms which are implemented:
10
+
11
+ - Christofides (provides a 3/2-approximation of TSP)
12
+ - Greedy
13
+ - Simulated Annealing (SA)
14
+ - Threshold Accepting (TA)
15
+ - Asadpour Asymmetric Traveling Salesman Algorithm
16
+
17
+ The Travelling Salesman Problem tries to find, given the weight
18
+ (distance) between all points where a salesman has to visit, the
19
+ route so that:
20
+
21
+ - The total distance (cost) which the salesman travels is minimized.
22
+ - The salesman returns to the starting point.
23
+ - Note that for a complete graph, the salesman visits each point once.
24
+
25
+ The function `travelling_salesman_problem` allows for incomplete
26
+ graphs by finding all-pairs shortest paths, effectively converting
27
+ the problem to a complete graph problem. It calls one of the
28
+ approximate methods on that problem and then converts the result
29
+ back to the original graph using the previously found shortest paths.
30
+
31
+ TSP is an NP-hard problem in combinatorial optimization,
32
+ important in operations research and theoretical computer science.
33
+
34
+ http://en.wikipedia.org/wiki/Travelling_salesman_problem
35
+ """
36
+ import math
37
+
38
+ import networkx as nx
39
+ from networkx.algorithms.tree.mst import random_spanning_tree
40
+ from networkx.utils import not_implemented_for, pairwise, py_random_state
41
+
42
+ __all__ = [
43
+ "traveling_salesman_problem",
44
+ "christofides",
45
+ "asadpour_atsp",
46
+ "greedy_tsp",
47
+ "simulated_annealing_tsp",
48
+ "threshold_accepting_tsp",
49
+ ]
50
+
51
+
52
+ def swap_two_nodes(soln, seed):
53
+ """Swap two nodes in `soln` to give a neighbor solution.
54
+
55
+ Parameters
56
+ ----------
57
+ soln : list of nodes
58
+ Current cycle of nodes
59
+
60
+ seed : integer, random_state, or None (default)
61
+ Indicator of random number generation state.
62
+ See :ref:`Randomness<randomness>`.
63
+
64
+ Returns
65
+ -------
66
+ list
67
+ The solution after move is applied. (A neighbor solution.)
68
+
69
+ Notes
70
+ -----
71
+ This function assumes that the incoming list `soln` is a cycle
72
+ (that the first and last element are the same) and also that
73
+ we don't want any move to change the first node in the list
74
+ (and thus not the last node either).
75
+
76
+ The input list is changed as well as returned. Make a copy if needed.
77
+
78
+ See Also
79
+ --------
80
+ move_one_node
81
+ """
82
+ a, b = seed.sample(range(1, len(soln) - 1), k=2)
83
+ soln[a], soln[b] = soln[b], soln[a]
84
+ return soln
85
+
86
+
87
+ def move_one_node(soln, seed):
88
+ """Move one node to another position to give a neighbor solution.
89
+
90
+ The node to move and the position to move to are chosen randomly.
91
+ The first and last nodes are left untouched as soln must be a cycle
92
+ starting at that node.
93
+
94
+ Parameters
95
+ ----------
96
+ soln : list of nodes
97
+ Current cycle of nodes
98
+
99
+ seed : integer, random_state, or None (default)
100
+ Indicator of random number generation state.
101
+ See :ref:`Randomness<randomness>`.
102
+
103
+ Returns
104
+ -------
105
+ list
106
+ The solution after move is applied. (A neighbor solution.)
107
+
108
+ Notes
109
+ -----
110
+ This function assumes that the incoming list `soln` is a cycle
111
+ (that the first and last element are the same) and also that
112
+ we don't want any move to change the first node in the list
113
+ (and thus not the last node either).
114
+
115
+ The input list is changed as well as returned. Make a copy if needed.
116
+
117
+ See Also
118
+ --------
119
+ swap_two_nodes
120
+ """
121
+ a, b = seed.sample(range(1, len(soln) - 1), k=2)
122
+ soln.insert(b, soln.pop(a))
123
+ return soln
124
+
125
+
126
+ @not_implemented_for("directed")
127
+ def christofides(G, weight="weight", tree=None):
128
+ """Approximate a solution of the traveling salesman problem
129
+
130
+ Compute a 3/2-approximation of the traveling salesman problem
131
+ in a complete undirected graph using Christofides [1]_ algorithm.
132
+
133
+ Parameters
134
+ ----------
135
+ G : Graph
136
+ `G` should be a complete weighted undirected graph.
137
+ The distance between all pairs of nodes should be included.
138
+
139
+ weight : string, optional (default="weight")
140
+ Edge data key corresponding to the edge weight.
141
+ If any edge does not have this attribute the weight is set to 1.
142
+
143
+ tree : NetworkX graph or None (default: None)
144
+ A minimum spanning tree of G. Or, if None, the minimum spanning
145
+ tree is computed using :func:`networkx.minimum_spanning_tree`
146
+
147
+ Returns
148
+ -------
149
+ list
150
+ List of nodes in `G` along a cycle with a 3/2-approximation of
151
+ the minimal Hamiltonian cycle.
152
+
153
+ References
154
+ ----------
155
+ .. [1] Christofides, Nicos. "Worst-case analysis of a new heuristic for
156
+ the travelling salesman problem." No. RR-388. Carnegie-Mellon Univ
157
+ Pittsburgh Pa Management Sciences Research Group, 1976.
158
+ """
159
+ # Remove selfloops if necessary
160
+ loop_nodes = nx.nodes_with_selfloops(G)
161
+ try:
162
+ node = next(loop_nodes)
163
+ except StopIteration:
164
+ pass
165
+ else:
166
+ G = G.copy()
167
+ G.remove_edge(node, node)
168
+ G.remove_edges_from((n, n) for n in loop_nodes)
169
+ # Check that G is a complete graph
170
+ N = len(G) - 1
171
+ # This check ignores selfloops which is what we want here.
172
+ if any(len(nbrdict) != N for n, nbrdict in G.adj.items()):
173
+ raise nx.NetworkXError("G must be a complete graph.")
174
+
175
+ if tree is None:
176
+ tree = nx.minimum_spanning_tree(G, weight=weight)
177
+ L = G.copy()
178
+ L.remove_nodes_from([v for v, degree in tree.degree if not (degree % 2)])
179
+ MG = nx.MultiGraph()
180
+ MG.add_edges_from(tree.edges)
181
+ edges = nx.min_weight_matching(L, maxcardinality=True, weight=weight)
182
+ MG.add_edges_from(edges)
183
+ return _shortcutting(nx.eulerian_circuit(MG))
184
+
185
+
186
+ def _shortcutting(circuit):
187
+ """Remove duplicate nodes in the path"""
188
+ nodes = []
189
+ for u, v in circuit:
190
+ if v in nodes:
191
+ continue
192
+ if not nodes:
193
+ nodes.append(u)
194
+ nodes.append(v)
195
+ nodes.append(nodes[0])
196
+ return nodes
197
+
198
+
199
+ def traveling_salesman_problem(G, weight="weight", nodes=None, cycle=True, method=None):
200
+ """Find the shortest path in `G` connecting specified nodes
201
+
202
+ This function allows approximate solution to the traveling salesman
203
+ problem on networks that are not complete graphs and/or where the
204
+ salesman does not need to visit all nodes.
205
+
206
+ This function proceeds in two steps. First, it creates a complete
207
+ graph using the all-pairs shortest_paths between nodes in `nodes`.
208
+ Edge weights in the new graph are the lengths of the paths
209
+ between each pair of nodes in the original graph.
210
+ Second, an algorithm (default: `christofides` for undirected and
211
+ `asadpour_atsp` for directed) is used to approximate the minimal Hamiltonian
212
+ cycle on this new graph. The available algorithms are:
213
+
214
+ - christofides
215
+ - greedy_tsp
216
+ - simulated_annealing_tsp
217
+ - threshold_accepting_tsp
218
+ - asadpour_atsp
219
+
220
+ Once the Hamiltonian Cycle is found, this function post-processes to
221
+ accommodate the structure of the original graph. If `cycle` is ``False``,
222
+ the biggest weight edge is removed to make a Hamiltonian path.
223
+ Then each edge on the new complete graph used for that analysis is
224
+ replaced by the shortest_path between those nodes on the original graph.
225
+
226
+ Parameters
227
+ ----------
228
+ G : NetworkX graph
229
+ A possibly weighted graph
230
+
231
+ nodes : collection of nodes (default=G.nodes)
232
+ collection (list, set, etc.) of nodes to visit
233
+
234
+ weight : string, optional (default="weight")
235
+ Edge data key corresponding to the edge weight.
236
+ If any edge does not have this attribute the weight is set to 1.
237
+
238
+ cycle : bool (default: True)
239
+ Indicates whether a cycle should be returned, or a path.
240
+ Note: the cycle is the approximate minimal cycle.
241
+ The path simply removes the biggest edge in that cycle.
242
+
243
+ method : function (default: None)
244
+ A function that returns a cycle on all nodes and approximates
245
+ the solution to the traveling salesman problem on a complete
246
+ graph. The returned cycle is then used to find a corresponding
247
+ solution on `G`. `method` should be callable; take inputs
248
+ `G`, and `weight`; and return a list of nodes along the cycle.
249
+
250
+ Provided options include :func:`christofides`, :func:`greedy_tsp`,
251
+ :func:`simulated_annealing_tsp` and :func:`threshold_accepting_tsp`.
252
+
253
+ If `method is None`: use :func:`christofides` for undirected `G` and
254
+ :func:`threshold_accepting_tsp` for directed `G`.
255
+
256
+ To specify parameters for these provided functions, construct lambda
257
+ functions that state the specific value. `method` must have 2 inputs.
258
+ (See examples).
259
+
260
+ Returns
261
+ -------
262
+ list
263
+ List of nodes in `G` along a path with an approximation of the minimal
264
+ path through `nodes`.
265
+
266
+
267
+ Raises
268
+ ------
269
+ NetworkXError
270
+ If `G` is a directed graph it has to be strongly connected or the
271
+ complete version cannot be generated.
272
+
273
+ Examples
274
+ --------
275
+ >>> tsp = nx.approximation.traveling_salesman_problem
276
+ >>> G = nx.cycle_graph(9)
277
+ >>> G[4][5]["weight"] = 5 # all other weights are 1
278
+ >>> tsp(G, nodes=[3, 6])
279
+ [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3]
280
+ >>> path = tsp(G, cycle=False)
281
+ >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
282
+ True
283
+
284
+ Build (curry) your own function to provide parameter values to the methods.
285
+
286
+ >>> SA_tsp = nx.approximation.simulated_annealing_tsp
287
+ >>> method = lambda G, wt: SA_tsp(G, "greedy", weight=wt, temp=500)
288
+ >>> path = tsp(G, cycle=False, method=method)
289
+ >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
290
+ True
291
+
292
+ """
293
+ if method is None:
294
+ if G.is_directed():
295
+ method = asadpour_atsp
296
+ else:
297
+ method = christofides
298
+ if nodes is None:
299
+ nodes = list(G.nodes)
300
+
301
+ dist = {}
302
+ path = {}
303
+ for n, (d, p) in nx.all_pairs_dijkstra(G, weight=weight):
304
+ dist[n] = d
305
+ path[n] = p
306
+
307
+ if G.is_directed():
308
+ # If the graph is not strongly connected, raise an exception
309
+ if not nx.is_strongly_connected(G):
310
+ raise nx.NetworkXError("G is not strongly connected")
311
+ GG = nx.DiGraph()
312
+ else:
313
+ GG = nx.Graph()
314
+ for u in nodes:
315
+ for v in nodes:
316
+ if u == v:
317
+ continue
318
+ GG.add_edge(u, v, weight=dist[u][v])
319
+ best_GG = method(GG, weight)
320
+
321
+ if not cycle:
322
+ # find and remove the biggest edge
323
+ (u, v) = max(pairwise(best_GG), key=lambda x: dist[x[0]][x[1]])
324
+ pos = best_GG.index(u) + 1
325
+ while best_GG[pos] != v:
326
+ pos = best_GG[pos:].index(u) + 1
327
+ best_GG = best_GG[pos:-1] + best_GG[:pos]
328
+
329
+ best_path = []
330
+ for u, v in pairwise(best_GG):
331
+ best_path.extend(path[u][v][:-1])
332
+ best_path.append(v)
333
+ return best_path
334
+
335
+
336
+ @not_implemented_for("undirected")
337
+ @py_random_state(2)
338
+ def asadpour_atsp(G, weight="weight", seed=None, source=None):
339
+ """
340
+ Returns an approximate solution to the traveling salesman problem.
341
+
342
+ This approximate solution is one of the best known approximations for the
343
+ asymmetric traveling salesman problem developed by Asadpour et al,
344
+ [1]_. The algorithm first solves the Held-Karp relaxation to find a lower
345
+ bound for the weight of the cycle. Next, it constructs an exponential
346
+ distribution of undirected spanning trees where the probability of an
347
+ edge being in the tree corresponds to the weight of that edge using a
348
+ maximum entropy rounding scheme. Next we sample that distribution
349
+ $2 \\lceil \\ln n \\rceil$ times and save the minimum sampled tree once the
350
+ direction of the arcs is added back to the edges. Finally, we augment
351
+ then short circuit that graph to find the approximate tour for the
352
+ salesman.
353
+
354
+ Parameters
355
+ ----------
356
+ G : nx.DiGraph
357
+ The graph should be a complete weighted directed graph. The
358
+ distance between all paris of nodes should be included and the triangle
359
+ inequality should hold. That is, the direct edge between any two nodes
360
+ should be the path of least cost.
361
+
362
+ weight : string, optional (default="weight")
363
+ Edge data key corresponding to the edge weight.
364
+ If any edge does not have this attribute the weight is set to 1.
365
+
366
+ seed : integer, random_state, or None (default)
367
+ Indicator of random number generation state.
368
+ See :ref:`Randomness<randomness>`.
369
+
370
+ source : node label (default=`None`)
371
+ If given, return the cycle starting and ending at the given node.
372
+
373
+ Returns
374
+ -------
375
+ cycle : list of nodes
376
+ Returns the cycle (list of nodes) that a salesman can follow to minimize
377
+ the total weight of the trip.
378
+
379
+ Raises
380
+ ------
381
+ NetworkXError
382
+ If `G` is not complete or has less than two nodes, the algorithm raises
383
+ an exception.
384
+
385
+ NetworkXError
386
+ If `source` is not `None` and is not a node in `G`, the algorithm raises
387
+ an exception.
388
+
389
+ NetworkXNotImplemented
390
+ If `G` is an undirected graph.
391
+
392
+ References
393
+ ----------
394
+ .. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
395
+ An o(log n/log log n)-approximation algorithm for the asymmetric
396
+ traveling salesman problem, Operations research, 65 (2017),
397
+ pp. 1043–1061
398
+
399
+ Examples
400
+ --------
401
+ >>> import networkx as nx
402
+ >>> import networkx.algorithms.approximation as approx
403
+ >>> G = nx.complete_graph(3, create_using=nx.DiGraph)
404
+ >>> nx.set_edge_attributes(G, {(0, 1): 2, (1, 2): 2, (2, 0): 2, (0, 2): 1, (2, 1): 1, (1, 0): 1}, "weight")
405
+ >>> tour = approx.asadpour_atsp(G,source=0)
406
+ >>> tour
407
+ [0, 2, 1, 0]
408
+ """
409
+ from math import ceil, exp
410
+ from math import log as ln
411
+
412
+ # Check that G is a complete graph
413
+ N = len(G) - 1
414
+ if N < 2:
415
+ raise nx.NetworkXError("G must have at least two nodes")
416
+ # This check ignores selfloops which is what we want here.
417
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
418
+ raise nx.NetworkXError("G is not a complete DiGraph")
419
+ # Check that the source vertex, if given, is in the graph
420
+ if source is not None and source not in G.nodes:
421
+ raise nx.NetworkXError("Given source node not in G.")
422
+
423
+ opt_hk, z_star = held_karp_ascent(G, weight)
424
+
425
+ # Test to see if the ascent method found an integer solution or a fractional
426
+ # solution. If it is integral then z_star is a nx.Graph, otherwise it is
427
+ # a dict
428
+ if not isinstance(z_star, dict):
429
+ # Here we are using the shortcutting method to go from the list of edges
430
+ # returned from eularian_circuit to a list of nodes
431
+ return _shortcutting(nx.eulerian_circuit(z_star, source=source))
432
+
433
+ # Create the undirected support of z_star
434
+ z_support = nx.MultiGraph()
435
+ for u, v in z_star:
436
+ if (u, v) not in z_support.edges:
437
+ edge_weight = min(G[u][v][weight], G[v][u][weight])
438
+ z_support.add_edge(u, v, **{weight: edge_weight})
439
+
440
+ # Create the exponential distribution of spanning trees
441
+ gamma = spanning_tree_distribution(z_support, z_star)
442
+
443
+ # Write the lambda values to the edges of z_support
444
+ z_support = nx.Graph(z_support)
445
+ lambda_dict = {(u, v): exp(gamma[(u, v)]) for u, v in z_support.edges()}
446
+ nx.set_edge_attributes(z_support, lambda_dict, "weight")
447
+ del gamma, lambda_dict
448
+
449
+ # Sample 2 * ceil( ln(n) ) spanning trees and record the minimum one
450
+ minimum_sampled_tree = None
451
+ minimum_sampled_tree_weight = math.inf
452
+ for _ in range(2 * ceil(ln(G.number_of_nodes()))):
453
+ sampled_tree = random_spanning_tree(z_support, "weight", seed=seed)
454
+ sampled_tree_weight = sampled_tree.size(weight)
455
+ if sampled_tree_weight < minimum_sampled_tree_weight:
456
+ minimum_sampled_tree = sampled_tree.copy()
457
+ minimum_sampled_tree_weight = sampled_tree_weight
458
+
459
+ # Orient the edges in that tree to keep the cost of the tree the same.
460
+ t_star = nx.MultiDiGraph()
461
+ for u, v, d in minimum_sampled_tree.edges(data=weight):
462
+ if d == G[u][v][weight]:
463
+ t_star.add_edge(u, v, **{weight: d})
464
+ else:
465
+ t_star.add_edge(v, u, **{weight: d})
466
+
467
+ # Find the node demands needed to neutralize the flow of t_star in G
468
+ node_demands = {n: t_star.out_degree(n) - t_star.in_degree(n) for n in t_star}
469
+ nx.set_node_attributes(G, node_demands, "demand")
470
+
471
+ # Find the min_cost_flow
472
+ flow_dict = nx.min_cost_flow(G, "demand")
473
+
474
+ # Build the flow into t_star
475
+ for source, values in flow_dict.items():
476
+ for target in values:
477
+ if (source, target) not in t_star.edges and values[target] > 0:
478
+ # IF values[target] > 0 we have to add that many edges
479
+ for _ in range(values[target]):
480
+ t_star.add_edge(source, target)
481
+
482
+ # Return the shortcut eulerian circuit
483
+ circuit = nx.eulerian_circuit(t_star, source=source)
484
+ return _shortcutting(circuit)
485
+
486
+
487
+ def held_karp_ascent(G, weight="weight"):
488
+ """
489
+ Minimizes the Held-Karp relaxation of the TSP for `G`
490
+
491
+ Solves the Held-Karp relaxation of the input complete digraph and scales
492
+ the output solution for use in the Asadpour [1]_ ASTP algorithm.
493
+
494
+ The Held-Karp relaxation defines the lower bound for solutions to the
495
+ ATSP, although it does return a fractional solution. This is used in the
496
+ Asadpour algorithm as an initial solution which is later rounded to a
497
+ integral tree within the spanning tree polytopes. This function solves
498
+ the relaxation with the branch and bound method in [2]_.
499
+
500
+ Parameters
501
+ ----------
502
+ G : nx.DiGraph
503
+ The graph should be a complete weighted directed graph.
504
+ The distance between all paris of nodes should be included.
505
+
506
+ weight : string, optional (default="weight")
507
+ Edge data key corresponding to the edge weight.
508
+ If any edge does not have this attribute the weight is set to 1.
509
+
510
+ Returns
511
+ -------
512
+ OPT : float
513
+ The cost for the optimal solution to the Held-Karp relaxation
514
+ z : dict or nx.Graph
515
+ A symmetrized and scaled version of the optimal solution to the
516
+ Held-Karp relaxation for use in the Asadpour algorithm.
517
+
518
+ If an integral solution is found, then that is an optimal solution for
519
+ the ATSP problem and that is returned instead.
520
+
521
+ References
522
+ ----------
523
+ .. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
524
+ An o(log n/log log n)-approximation algorithm for the asymmetric
525
+ traveling salesman problem, Operations research, 65 (2017),
526
+ pp. 1043–1061
527
+
528
+ .. [2] M. Held, R. M. Karp, The traveling-salesman problem and minimum
529
+ spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
530
+ pp.1138-1162
531
+ """
532
+ import numpy as np
533
+ import scipy.optimize as optimize
534
+
535
+ def k_pi():
536
+ """
537
+ Find the set of minimum 1-Arborescences for G at point pi.
538
+
539
+ Returns
540
+ -------
541
+ Set
542
+ The set of minimum 1-Arborescences
543
+ """
544
+ # Create a copy of G without vertex 1.
545
+ G_1 = G.copy()
546
+ minimum_1_arborescences = set()
547
+ minimum_1_arborescence_weight = math.inf
548
+
549
+ # node is node '1' in the Held and Karp paper
550
+ n = next(G.__iter__())
551
+ G_1.remove_node(n)
552
+
553
+ # Iterate over the spanning arborescences of the graph until we know
554
+ # that we have found the minimum 1-arborescences. My proposed strategy
555
+ # is to find the most extensive root to connect to from 'node 1' and
556
+ # the least expensive one. We then iterate over arborescences until
557
+ # the cost of the basic arborescence is the cost of the minimum one
558
+ # plus the difference between the most and least expensive roots,
559
+ # that way the cost of connecting 'node 1' will by definition not by
560
+ # minimum
561
+ min_root = {"node": None, weight: math.inf}
562
+ max_root = {"node": None, weight: -math.inf}
563
+ for u, v, d in G.edges(n, data=True):
564
+ if d[weight] < min_root[weight]:
565
+ min_root = {"node": v, weight: d[weight]}
566
+ if d[weight] > max_root[weight]:
567
+ max_root = {"node": v, weight: d[weight]}
568
+
569
+ min_in_edge = min(G.in_edges(n, data=True), key=lambda x: x[2][weight])
570
+ min_root[weight] = min_root[weight] + min_in_edge[2][weight]
571
+ max_root[weight] = max_root[weight] + min_in_edge[2][weight]
572
+
573
+ min_arb_weight = math.inf
574
+ for arb in nx.ArborescenceIterator(G_1):
575
+ arb_weight = arb.size(weight)
576
+ if min_arb_weight == math.inf:
577
+ min_arb_weight = arb_weight
578
+ elif arb_weight > min_arb_weight + max_root[weight] - min_root[weight]:
579
+ break
580
+ # We have to pick the root node of the arborescence for the out
581
+ # edge of the first vertex as that is the only node without an
582
+ # edge directed into it.
583
+ for N, deg in arb.in_degree:
584
+ if deg == 0:
585
+ # root found
586
+ arb.add_edge(n, N, **{weight: G[n][N][weight]})
587
+ arb_weight += G[n][N][weight]
588
+ break
589
+
590
+ # We can pick the minimum weight in-edge for the vertex with
591
+ # a cycle. If there are multiple edges with the same, minimum
592
+ # weight, We need to add all of them.
593
+ #
594
+ # Delete the edge (N, v) so that we cannot pick it.
595
+ edge_data = G[N][n]
596
+ G.remove_edge(N, n)
597
+ min_weight = min(G.in_edges(n, data=weight), key=lambda x: x[2])[2]
598
+ min_edges = [
599
+ (u, v, d) for u, v, d in G.in_edges(n, data=weight) if d == min_weight
600
+ ]
601
+ for u, v, d in min_edges:
602
+ new_arb = arb.copy()
603
+ new_arb.add_edge(u, v, **{weight: d})
604
+ new_arb_weight = arb_weight + d
605
+ # Check to see the weight of the arborescence, if it is a
606
+ # new minimum, clear all of the old potential minimum
607
+ # 1-arborescences and add this is the only one. If its
608
+ # weight is above the known minimum, do not add it.
609
+ if new_arb_weight < minimum_1_arborescence_weight:
610
+ minimum_1_arborescences.clear()
611
+ minimum_1_arborescence_weight = new_arb_weight
612
+ # We have a 1-arborescence, add it to the set
613
+ if new_arb_weight == minimum_1_arborescence_weight:
614
+ minimum_1_arborescences.add(new_arb)
615
+ G.add_edge(N, n, **edge_data)
616
+
617
+ return minimum_1_arborescences
618
+
619
+ def direction_of_ascent():
620
+ """
621
+ Find the direction of ascent at point pi.
622
+
623
+ See [1]_ for more information.
624
+
625
+ Returns
626
+ -------
627
+ dict
628
+ A mapping from the nodes of the graph which represents the direction
629
+ of ascent.
630
+
631
+ References
632
+ ----------
633
+ .. [1] M. Held, R. M. Karp, The traveling-salesman problem and minimum
634
+ spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
635
+ pp.1138-1162
636
+ """
637
+ # 1. Set d equal to the zero n-vector.
638
+ d = {}
639
+ for n in G:
640
+ d[n] = 0
641
+ del n
642
+ # 2. Find a 1-Aborescence T^k such that k is in K(pi, d).
643
+ minimum_1_arborescences = k_pi()
644
+ while True:
645
+ # Reduce K(pi) to K(pi, d)
646
+ # Find the arborescence in K(pi) which increases the lest in
647
+ # direction d
648
+ min_k_d_weight = math.inf
649
+ min_k_d = None
650
+ for arborescence in minimum_1_arborescences:
651
+ weighted_cost = 0
652
+ for n, deg in arborescence.degree:
653
+ weighted_cost += d[n] * (deg - 2)
654
+ if weighted_cost < min_k_d_weight:
655
+ min_k_d_weight = weighted_cost
656
+ min_k_d = arborescence
657
+
658
+ # 3. If sum of d_i * v_{i, k} is greater than zero, terminate
659
+ if min_k_d_weight > 0:
660
+ return d, min_k_d
661
+ # 4. d_i = d_i + v_{i, k}
662
+ for n, deg in min_k_d.degree:
663
+ d[n] += deg - 2
664
+ # Check that we do not need to terminate because the direction
665
+ # of ascent does not exist. This is done with linear
666
+ # programming.
667
+ c = np.full(len(minimum_1_arborescences), -1, dtype=int)
668
+ a_eq = np.empty((len(G) + 1, len(minimum_1_arborescences)), dtype=int)
669
+ b_eq = np.zeros(len(G) + 1, dtype=int)
670
+ b_eq[len(G)] = 1
671
+ for arb_count, arborescence in enumerate(minimum_1_arborescences):
672
+ n_count = len(G) - 1
673
+ for n, deg in arborescence.degree:
674
+ a_eq[n_count][arb_count] = deg - 2
675
+ n_count -= 1
676
+ a_eq[len(G)][arb_count] = 1
677
+ program_result = optimize.linprog(c, A_eq=a_eq, b_eq=b_eq)
678
+ # If the constants exist, then the direction of ascent doesn't
679
+ if program_result.success:
680
+ # There is no direction of ascent
681
+ return None, minimum_1_arborescences
682
+
683
+ # 5. GO TO 2
684
+
685
+ def find_epsilon(k, d):
686
+ """
687
+ Given the direction of ascent at pi, find the maximum distance we can go
688
+ in that direction.
689
+
690
+ Parameters
691
+ ----------
692
+ k_xy : set
693
+ The set of 1-arborescences which have the minimum rate of increase
694
+ in the direction of ascent
695
+
696
+ d : dict
697
+ The direction of ascent
698
+
699
+ Returns
700
+ -------
701
+ float
702
+ The distance we can travel in direction `d`
703
+ """
704
+ min_epsilon = math.inf
705
+ for e_u, e_v, e_w in G.edges(data=weight):
706
+ if (e_u, e_v) in k.edges:
707
+ continue
708
+ # Now, I have found a condition which MUST be true for the edges to
709
+ # be a valid substitute. The edge in the graph which is the
710
+ # substitute is the one with the same terminated end. This can be
711
+ # checked rather simply.
712
+ #
713
+ # Find the edge within k which is the substitute. Because k is a
714
+ # 1-arborescence, we know that they is only one such edges
715
+ # leading into every vertex.
716
+ if len(k.in_edges(e_v, data=weight)) > 1:
717
+ raise Exception
718
+ sub_u, sub_v, sub_w = next(k.in_edges(e_v, data=weight).__iter__())
719
+ k.add_edge(e_u, e_v, **{weight: e_w})
720
+ k.remove_edge(sub_u, sub_v)
721
+ if (
722
+ max(d for n, d in k.in_degree()) <= 1
723
+ and len(G) == k.number_of_edges()
724
+ and nx.is_weakly_connected(k)
725
+ ):
726
+ # Ascent method calculation
727
+ if d[sub_u] == d[e_u] or sub_w == e_w:
728
+ # Revert to the original graph
729
+ k.remove_edge(e_u, e_v)
730
+ k.add_edge(sub_u, sub_v, **{weight: sub_w})
731
+ continue
732
+ epsilon = (sub_w - e_w) / (d[e_u] - d[sub_u])
733
+ if 0 < epsilon < min_epsilon:
734
+ min_epsilon = epsilon
735
+ # Revert to the original graph
736
+ k.remove_edge(e_u, e_v)
737
+ k.add_edge(sub_u, sub_v, **{weight: sub_w})
738
+
739
+ return min_epsilon
740
+
741
+ # I have to know that the elements in pi correspond to the correct elements
742
+ # in the direction of ascent, even if the node labels are not integers.
743
+ # Thus, I will use dictionaries to made that mapping.
744
+ pi_dict = {}
745
+ for n in G:
746
+ pi_dict[n] = 0
747
+ del n
748
+ original_edge_weights = {}
749
+ for u, v, d in G.edges(data=True):
750
+ original_edge_weights[(u, v)] = d[weight]
751
+ dir_ascent, k_d = direction_of_ascent()
752
+ while dir_ascent is not None:
753
+ max_distance = find_epsilon(k_d, dir_ascent)
754
+ for n, v in dir_ascent.items():
755
+ pi_dict[n] += max_distance * v
756
+ for u, v, d in G.edges(data=True):
757
+ d[weight] = original_edge_weights[(u, v)] + pi_dict[u]
758
+ dir_ascent, k_d = direction_of_ascent()
759
+ # k_d is no longer an individual 1-arborescence but rather a set of
760
+ # minimal 1-arborescences at the maximum point of the polytope and should
761
+ # be reflected as such
762
+ k_max = k_d
763
+
764
+ # Search for a cycle within k_max. If a cycle exists, return it as the
765
+ # solution
766
+ for k in k_max:
767
+ if len([n for n in k if k.degree(n) == 2]) == G.order():
768
+ # Tour found
769
+ return k.size(weight), k
770
+
771
+ # Write the original edge weights back to G and every member of k_max at
772
+ # the maximum point. Also average the number of times that edge appears in
773
+ # the set of minimal 1-arborescences.
774
+ x_star = {}
775
+ size_k_max = len(k_max)
776
+ for u, v, d in G.edges(data=True):
777
+ edge_count = 0
778
+ d[weight] = original_edge_weights[(u, v)]
779
+ for k in k_max:
780
+ if (u, v) in k.edges():
781
+ edge_count += 1
782
+ k[u][v][weight] = original_edge_weights[(u, v)]
783
+ x_star[(u, v)] = edge_count / size_k_max
784
+ # Now symmetrize the edges in x_star and scale them according to (5) in
785
+ # reference [1]
786
+ z_star = {}
787
+ scale_factor = (G.order() - 1) / G.order()
788
+ for u, v in x_star.keys():
789
+ frequency = x_star[(u, v)] + x_star[(v, u)]
790
+ if frequency > 0:
791
+ z_star[(u, v)] = scale_factor * frequency
792
+ del x_star
793
+ # Return the optimal weight and the z dict
794
+ return next(k_max.__iter__()).size(weight), z_star
795
+
796
+
797
+ def spanning_tree_distribution(G, z):
798
+ """
799
+ Find the asadpour exponential distribution of spanning trees.
800
+
801
+ Solves the Maximum Entropy Convex Program in the Asadpour algorithm [1]_
802
+ using the approach in section 7 to build an exponential distribution of
803
+ undirected spanning trees.
804
+
805
+ This algorithm ensures that the probability of any edge in a spanning
806
+ tree is proportional to the sum of the probabilities of the tress
807
+ containing that edge over the sum of the probabilities of all spanning
808
+ trees of the graph.
809
+
810
+ Parameters
811
+ ----------
812
+ G : nx.MultiGraph
813
+ The undirected support graph for the Held Karp relaxation
814
+
815
+ z : dict
816
+ The output of `held_karp_ascent()`, a scaled version of the Held-Karp
817
+ solution.
818
+
819
+ Returns
820
+ -------
821
+ gamma : dict
822
+ The probability distribution which approximately preserves the marginal
823
+ probabilities of `z`.
824
+ """
825
+ from math import exp
826
+ from math import log as ln
827
+
828
+ def q(e):
829
+ """
830
+ The value of q(e) is described in the Asadpour paper is "the
831
+ probability that edge e will be included in a spanning tree T that is
832
+ chosen with probability proportional to exp(gamma(T))" which
833
+ basically means that it is the total probability of the edge appearing
834
+ across the whole distribution.
835
+
836
+ Parameters
837
+ ----------
838
+ e : tuple
839
+ The `(u, v)` tuple describing the edge we are interested in
840
+
841
+ Returns
842
+ -------
843
+ float
844
+ The probability that a spanning tree chosen according to the
845
+ current values of gamma will include edge `e`.
846
+ """
847
+ # Create the laplacian matrices
848
+ for u, v, d in G.edges(data=True):
849
+ d[lambda_key] = exp(gamma[(u, v)])
850
+ G_Kirchhoff = nx.total_spanning_tree_weight(G, lambda_key)
851
+ G_e = nx.contracted_edge(G, e, self_loops=False)
852
+ G_e_Kirchhoff = nx.total_spanning_tree_weight(G_e, lambda_key)
853
+
854
+ # Multiply by the weight of the contracted edge since it is not included
855
+ # in the total weight of the contracted graph.
856
+ return exp(gamma[(e[0], e[1])]) * G_e_Kirchhoff / G_Kirchhoff
857
+
858
+ # initialize gamma to the zero dict
859
+ gamma = {}
860
+ for u, v, _ in G.edges:
861
+ gamma[(u, v)] = 0
862
+
863
+ # set epsilon
864
+ EPSILON = 0.2
865
+
866
+ # pick an edge attribute name that is unlikely to be in the graph
867
+ lambda_key = "spanning_tree_distribution's secret attribute name for lambda"
868
+
869
+ while True:
870
+ # We need to know that know that no values of q_e are greater than
871
+ # (1 + epsilon) * z_e, however changing one gamma value can increase the
872
+ # value of a different q_e, so we have to complete the for loop without
873
+ # changing anything for the condition to be meet
874
+ in_range_count = 0
875
+ # Search for an edge with q_e > (1 + epsilon) * z_e
876
+ for u, v in gamma:
877
+ e = (u, v)
878
+ q_e = q(e)
879
+ z_e = z[e]
880
+ if q_e > (1 + EPSILON) * z_e:
881
+ delta = ln(
882
+ (q_e * (1 - (1 + EPSILON / 2) * z_e))
883
+ / ((1 - q_e) * (1 + EPSILON / 2) * z_e)
884
+ )
885
+ gamma[e] -= delta
886
+ # Check that delta had the desired effect
887
+ new_q_e = q(e)
888
+ desired_q_e = (1 + EPSILON / 2) * z_e
889
+ if round(new_q_e, 8) != round(desired_q_e, 8):
890
+ raise nx.NetworkXError(
891
+ f"Unable to modify probability for edge ({u}, {v})"
892
+ )
893
+ else:
894
+ in_range_count += 1
895
+ # Check if the for loop terminated without changing any gamma
896
+ if in_range_count == len(gamma):
897
+ break
898
+
899
+ # Remove the new edge attributes
900
+ for _, _, d in G.edges(data=True):
901
+ if lambda_key in d:
902
+ del d[lambda_key]
903
+
904
+ return gamma
905
+
906
+
907
+ def greedy_tsp(G, weight="weight", source=None):
908
+ """Return a low cost cycle starting at `source` and its cost.
909
+
910
+ This approximates a solution to the traveling salesman problem.
911
+ It finds a cycle of all the nodes that a salesman can visit in order
912
+ to visit many nodes while minimizing total distance.
913
+ It uses a simple greedy algorithm.
914
+ In essence, this function returns a large cycle given a source point
915
+ for which the total cost of the cycle is minimized.
916
+
917
+ Parameters
918
+ ----------
919
+ G : Graph
920
+ The Graph should be a complete weighted undirected graph.
921
+ The distance between all pairs of nodes should be included.
922
+
923
+ weight : string, optional (default="weight")
924
+ Edge data key corresponding to the edge weight.
925
+ If any edge does not have this attribute the weight is set to 1.
926
+
927
+ source : node, optional (default: first node in list(G))
928
+ Starting node. If None, defaults to ``next(iter(G))``
929
+
930
+ Returns
931
+ -------
932
+ cycle : list of nodes
933
+ Returns the cycle (list of nodes) that a salesman
934
+ can follow to minimize total weight of the trip.
935
+
936
+ Raises
937
+ ------
938
+ NetworkXError
939
+ If `G` is not complete, the algorithm raises an exception.
940
+
941
+ Examples
942
+ --------
943
+ >>> from networkx.algorithms import approximation as approx
944
+ >>> G = nx.DiGraph()
945
+ >>> G.add_weighted_edges_from({
946
+ ... ("A", "B", 3), ("A", "C", 17), ("A", "D", 14), ("B", "A", 3),
947
+ ... ("B", "C", 12), ("B", "D", 16), ("C", "A", 13),("C", "B", 12),
948
+ ... ("C", "D", 4), ("D", "A", 14), ("D", "B", 15), ("D", "C", 2)
949
+ ... })
950
+ >>> cycle = approx.greedy_tsp(G, source="D")
951
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
952
+ >>> cycle
953
+ ['D', 'C', 'B', 'A', 'D']
954
+ >>> cost
955
+ 31
956
+
957
+ Notes
958
+ -----
959
+ This implementation of a greedy algorithm is based on the following:
960
+
961
+ - The algorithm adds a node to the solution at every iteration.
962
+ - The algorithm selects a node not already in the cycle whose connection
963
+ to the previous node adds the least cost to the cycle.
964
+
965
+ A greedy algorithm does not always give the best solution.
966
+ However, it can construct a first feasible solution which can
967
+ be passed as a parameter to an iterative improvement algorithm such
968
+ as Simulated Annealing, or Threshold Accepting.
969
+
970
+ Time complexity: It has a running time $O(|V|^2)$
971
+ """
972
+ # Check that G is a complete graph
973
+ N = len(G) - 1
974
+ # This check ignores selfloops which is what we want here.
975
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
976
+ raise nx.NetworkXError("G must be a complete graph.")
977
+
978
+ if source is None:
979
+ source = nx.utils.arbitrary_element(G)
980
+
981
+ if G.number_of_nodes() == 2:
982
+ neighbor = next(G.neighbors(source))
983
+ return [source, neighbor, source]
984
+
985
+ nodeset = set(G)
986
+ nodeset.remove(source)
987
+ cycle = [source]
988
+ next_node = source
989
+ while nodeset:
990
+ nbrdict = G[next_node]
991
+ next_node = min(nodeset, key=lambda n: nbrdict[n].get(weight, 1))
992
+ cycle.append(next_node)
993
+ nodeset.remove(next_node)
994
+ cycle.append(cycle[0])
995
+ return cycle
996
+
997
+
998
+ @py_random_state(9)
999
+ def simulated_annealing_tsp(
1000
+ G,
1001
+ init_cycle,
1002
+ weight="weight",
1003
+ source=None,
1004
+ temp=100,
1005
+ move="1-1",
1006
+ max_iterations=10,
1007
+ N_inner=100,
1008
+ alpha=0.01,
1009
+ seed=None,
1010
+ ):
1011
+ """Returns an approximate solution to the traveling salesman problem.
1012
+
1013
+ This function uses simulated annealing to approximate the minimal cost
1014
+ cycle through the nodes. Starting from a suboptimal solution, simulated
1015
+ annealing perturbs that solution, occasionally accepting changes that make
1016
+ the solution worse to escape from a locally optimal solution. The chance
1017
+ of accepting such changes decreases over the iterations to encourage
1018
+ an optimal result. In summary, the function returns a cycle starting
1019
+ at `source` for which the total cost is minimized. It also returns the cost.
1020
+
1021
+ The chance of accepting a proposed change is related to a parameter called
1022
+ the temperature (annealing has a physical analogue of steel hardening
1023
+ as it cools). As the temperature is reduced, the chance of moves that
1024
+ increase cost goes down.
1025
+
1026
+ Parameters
1027
+ ----------
1028
+ G : Graph
1029
+ `G` should be a complete weighted undirected graph.
1030
+ The distance between all pairs of nodes should be included.
1031
+
1032
+ init_cycle : list of all nodes or "greedy"
1033
+ The initial solution (a cycle through all nodes returning to the start).
1034
+ This argument has no default to make you think about it.
1035
+ If "greedy", use `greedy_tsp(G, weight)`.
1036
+ Other common starting cycles are `list(G) + [next(iter(G))]` or the final
1037
+ result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.
1038
+
1039
+ weight : string, optional (default="weight")
1040
+ Edge data key corresponding to the edge weight.
1041
+ If any edge does not have this attribute the weight is set to 1.
1042
+
1043
+ source : node, optional (default: first node in list(G))
1044
+ Starting node. If None, defaults to ``next(iter(G))``
1045
+
1046
+ temp : int, optional (default=100)
1047
+ The algorithm's temperature parameter. It represents the initial
1048
+ value of temperature
1049
+
1050
+ move : "1-1" or "1-0" or function, optional (default="1-1")
1051
+ Indicator of what move to use when finding new trial solutions.
1052
+ Strings indicate two special built-in moves:
1053
+
1054
+ - "1-1": 1-1 exchange which transposes the position
1055
+ of two elements of the current solution.
1056
+ The function called is :func:`swap_two_nodes`.
1057
+ For example if we apply 1-1 exchange in the solution
1058
+ ``A = [3, 2, 1, 4, 3]``
1059
+ we can get the following by the transposition of 1 and 4 elements:
1060
+ ``A' = [3, 2, 4, 1, 3]``
1061
+ - "1-0": 1-0 exchange which moves an node in the solution
1062
+ to a new position.
1063
+ The function called is :func:`move_one_node`.
1064
+ For example if we apply 1-0 exchange in the solution
1065
+ ``A = [3, 2, 1, 4, 3]``
1066
+ we can transfer the fourth element to the second position:
1067
+ ``A' = [3, 4, 2, 1, 3]``
1068
+
1069
+ You may provide your own functions to enact a move from
1070
+ one solution to a neighbor solution. The function must take
1071
+ the solution as input along with a `seed` input to control
1072
+ random number generation (see the `seed` input here).
1073
+ Your function should maintain the solution as a cycle with
1074
+ equal first and last node and all others appearing once.
1075
+ Your function should return the new solution.
1076
+
1077
+ max_iterations : int, optional (default=10)
1078
+ Declared done when this number of consecutive iterations of
1079
+ the outer loop occurs without any change in the best cost solution.
1080
+
1081
+ N_inner : int, optional (default=100)
1082
+ The number of iterations of the inner loop.
1083
+
1084
+ alpha : float between (0, 1), optional (default=0.01)
1085
+ Percentage of temperature decrease in each iteration
1086
+ of outer loop
1087
+
1088
+ seed : integer, random_state, or None (default)
1089
+ Indicator of random number generation state.
1090
+ See :ref:`Randomness<randomness>`.
1091
+
1092
+ Returns
1093
+ -------
1094
+ cycle : list of nodes
1095
+ Returns the cycle (list of nodes) that a salesman
1096
+ can follow to minimize total weight of the trip.
1097
+
1098
+ Raises
1099
+ ------
1100
+ NetworkXError
1101
+ If `G` is not complete the algorithm raises an exception.
1102
+
1103
+ Examples
1104
+ --------
1105
+ >>> from networkx.algorithms import approximation as approx
1106
+ >>> G = nx.DiGraph()
1107
+ >>> G.add_weighted_edges_from({
1108
+ ... ("A", "B", 3), ("A", "C", 17), ("A", "D", 14), ("B", "A", 3),
1109
+ ... ("B", "C", 12), ("B", "D", 16), ("C", "A", 13),("C", "B", 12),
1110
+ ... ("C", "D", 4), ("D", "A", 14), ("D", "B", 15), ("D", "C", 2)
1111
+ ... })
1112
+ >>> cycle = approx.simulated_annealing_tsp(G, "greedy", source="D")
1113
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1114
+ >>> cycle
1115
+ ['D', 'C', 'B', 'A', 'D']
1116
+ >>> cost
1117
+ 31
1118
+ >>> incycle = ["D", "B", "A", "C", "D"]
1119
+ >>> cycle = approx.simulated_annealing_tsp(G, incycle, source="D")
1120
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1121
+ >>> cycle
1122
+ ['D', 'C', 'B', 'A', 'D']
1123
+ >>> cost
1124
+ 31
1125
+
1126
+ Notes
1127
+ -----
1128
+ Simulated Annealing is a metaheuristic local search algorithm.
1129
+ The main characteristic of this algorithm is that it accepts
1130
+ even solutions which lead to the increase of the cost in order
1131
+ to escape from low quality local optimal solutions.
1132
+
1133
+ This algorithm needs an initial solution. If not provided, it is
1134
+ constructed by a simple greedy algorithm. At every iteration, the
1135
+ algorithm selects thoughtfully a neighbor solution.
1136
+ Consider $c(x)$ cost of current solution and $c(x')$ cost of a
1137
+ neighbor solution.
1138
+ If $c(x') - c(x) <= 0$ then the neighbor solution becomes the current
1139
+ solution for the next iteration. Otherwise, the algorithm accepts
1140
+ the neighbor solution with probability $p = exp - ([c(x') - c(x)] / temp)$.
1141
+ Otherwise the current solution is retained.
1142
+
1143
+ `temp` is a parameter of the algorithm and represents temperature.
1144
+
1145
+ Time complexity:
1146
+ For $N_i$ iterations of the inner loop and $N_o$ iterations of the
1147
+ outer loop, this algorithm has running time $O(N_i * N_o * |V|)$.
1148
+
1149
+ For more information and how the algorithm is inspired see:
1150
+ http://en.wikipedia.org/wiki/Simulated_annealing
1151
+ """
1152
+ if move == "1-1":
1153
+ move = swap_two_nodes
1154
+ elif move == "1-0":
1155
+ move = move_one_node
1156
+ if init_cycle == "greedy":
1157
+ # Construct an initial solution using a greedy algorithm.
1158
+ cycle = greedy_tsp(G, weight=weight, source=source)
1159
+ if G.number_of_nodes() == 2:
1160
+ return cycle
1161
+
1162
+ else:
1163
+ cycle = list(init_cycle)
1164
+ if source is None:
1165
+ source = cycle[0]
1166
+ elif source != cycle[0]:
1167
+ raise nx.NetworkXError("source must be first node in init_cycle")
1168
+ if cycle[0] != cycle[-1]:
1169
+ raise nx.NetworkXError("init_cycle must be a cycle. (return to start)")
1170
+
1171
+ if len(cycle) - 1 != len(G) or len(set(G.nbunch_iter(cycle))) != len(G):
1172
+ raise nx.NetworkXError("init_cycle should be a cycle over all nodes in G.")
1173
+
1174
+ # Check that G is a complete graph
1175
+ N = len(G) - 1
1176
+ # This check ignores selfloops which is what we want here.
1177
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
1178
+ raise nx.NetworkXError("G must be a complete graph.")
1179
+
1180
+ if G.number_of_nodes() == 2:
1181
+ neighbor = next(G.neighbors(source))
1182
+ return [source, neighbor, source]
1183
+
1184
+ # Find the cost of initial solution
1185
+ cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(cycle))
1186
+
1187
+ count = 0
1188
+ best_cycle = cycle.copy()
1189
+ best_cost = cost
1190
+ while count <= max_iterations and temp > 0:
1191
+ count += 1
1192
+ for i in range(N_inner):
1193
+ adj_sol = move(cycle, seed)
1194
+ adj_cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(adj_sol))
1195
+ delta = adj_cost - cost
1196
+ if delta <= 0:
1197
+ # Set current solution the adjacent solution.
1198
+ cycle = adj_sol
1199
+ cost = adj_cost
1200
+
1201
+ if cost < best_cost:
1202
+ count = 0
1203
+ best_cycle = cycle.copy()
1204
+ best_cost = cost
1205
+ else:
1206
+ # Accept even a worse solution with probability p.
1207
+ p = math.exp(-delta / temp)
1208
+ if p >= seed.random():
1209
+ cycle = adj_sol
1210
+ cost = adj_cost
1211
+ temp -= temp * alpha
1212
+
1213
+ return best_cycle
1214
+
1215
+
1216
+ @py_random_state(9)
1217
+ def threshold_accepting_tsp(
1218
+ G,
1219
+ init_cycle,
1220
+ weight="weight",
1221
+ source=None,
1222
+ threshold=1,
1223
+ move="1-1",
1224
+ max_iterations=10,
1225
+ N_inner=100,
1226
+ alpha=0.1,
1227
+ seed=None,
1228
+ ):
1229
+ """Returns an approximate solution to the traveling salesman problem.
1230
+
1231
+ This function uses threshold accepting methods to approximate the minimal cost
1232
+ cycle through the nodes. Starting from a suboptimal solution, threshold
1233
+ accepting methods perturb that solution, accepting any changes that make
1234
+ the solution no worse than increasing by a threshold amount. Improvements
1235
+ in cost are accepted, but so are changes leading to small increases in cost.
1236
+ This allows the solution to leave suboptimal local minima in solution space.
1237
+ The threshold is decreased slowly as iterations proceed helping to ensure
1238
+ an optimum. In summary, the function returns a cycle starting at `source`
1239
+ for which the total cost is minimized.
1240
+
1241
+ Parameters
1242
+ ----------
1243
+ G : Graph
1244
+ `G` should be a complete weighted undirected graph.
1245
+ The distance between all pairs of nodes should be included.
1246
+
1247
+ init_cycle : list or "greedy"
1248
+ The initial solution (a cycle through all nodes returning to the start).
1249
+ This argument has no default to make you think about it.
1250
+ If "greedy", use `greedy_tsp(G, weight)`.
1251
+ Other common starting cycles are `list(G) + [next(iter(G))]` or the final
1252
+ result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.
1253
+
1254
+ weight : string, optional (default="weight")
1255
+ Edge data key corresponding to the edge weight.
1256
+ If any edge does not have this attribute the weight is set to 1.
1257
+
1258
+ source : node, optional (default: first node in list(G))
1259
+ Starting node. If None, defaults to ``next(iter(G))``
1260
+
1261
+ threshold : int, optional (default=1)
1262
+ The algorithm's threshold parameter. It represents the initial
1263
+ threshold's value
1264
+
1265
+ move : "1-1" or "1-0" or function, optional (default="1-1")
1266
+ Indicator of what move to use when finding new trial solutions.
1267
+ Strings indicate two special built-in moves:
1268
+
1269
+ - "1-1": 1-1 exchange which transposes the position
1270
+ of two elements of the current solution.
1271
+ The function called is :func:`swap_two_nodes`.
1272
+ For example if we apply 1-1 exchange in the solution
1273
+ ``A = [3, 2, 1, 4, 3]``
1274
+ we can get the following by the transposition of 1 and 4 elements:
1275
+ ``A' = [3, 2, 4, 1, 3]``
1276
+ - "1-0": 1-0 exchange which moves an node in the solution
1277
+ to a new position.
1278
+ The function called is :func:`move_one_node`.
1279
+ For example if we apply 1-0 exchange in the solution
1280
+ ``A = [3, 2, 1, 4, 3]``
1281
+ we can transfer the fourth element to the second position:
1282
+ ``A' = [3, 4, 2, 1, 3]``
1283
+
1284
+ You may provide your own functions to enact a move from
1285
+ one solution to a neighbor solution. The function must take
1286
+ the solution as input along with a `seed` input to control
1287
+ random number generation (see the `seed` input here).
1288
+ Your function should maintain the solution as a cycle with
1289
+ equal first and last node and all others appearing once.
1290
+ Your function should return the new solution.
1291
+
1292
+ max_iterations : int, optional (default=10)
1293
+ Declared done when this number of consecutive iterations of
1294
+ the outer loop occurs without any change in the best cost solution.
1295
+
1296
+ N_inner : int, optional (default=100)
1297
+ The number of iterations of the inner loop.
1298
+
1299
+ alpha : float between (0, 1), optional (default=0.1)
1300
+ Percentage of threshold decrease when there is at
1301
+ least one acceptance of a neighbor solution.
1302
+ If no inner loop moves are accepted the threshold remains unchanged.
1303
+
1304
+ seed : integer, random_state, or None (default)
1305
+ Indicator of random number generation state.
1306
+ See :ref:`Randomness<randomness>`.
1307
+
1308
+ Returns
1309
+ -------
1310
+ cycle : list of nodes
1311
+ Returns the cycle (list of nodes) that a salesman
1312
+ can follow to minimize total weight of the trip.
1313
+
1314
+ Raises
1315
+ ------
1316
+ NetworkXError
1317
+ If `G` is not complete the algorithm raises an exception.
1318
+
1319
+ Examples
1320
+ --------
1321
+ >>> from networkx.algorithms import approximation as approx
1322
+ >>> G = nx.DiGraph()
1323
+ >>> G.add_weighted_edges_from({
1324
+ ... ("A", "B", 3), ("A", "C", 17), ("A", "D", 14), ("B", "A", 3),
1325
+ ... ("B", "C", 12), ("B", "D", 16), ("C", "A", 13),("C", "B", 12),
1326
+ ... ("C", "D", 4), ("D", "A", 14), ("D", "B", 15), ("D", "C", 2)
1327
+ ... })
1328
+ >>> cycle = approx.threshold_accepting_tsp(G, "greedy", source="D")
1329
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1330
+ >>> cycle
1331
+ ['D', 'C', 'B', 'A', 'D']
1332
+ >>> cost
1333
+ 31
1334
+ >>> incycle = ["D", "B", "A", "C", "D"]
1335
+ >>> cycle = approx.threshold_accepting_tsp(G, incycle, source="D")
1336
+ >>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
1337
+ >>> cycle
1338
+ ['D', 'C', 'B', 'A', 'D']
1339
+ >>> cost
1340
+ 31
1341
+
1342
+ Notes
1343
+ -----
1344
+ Threshold Accepting is a metaheuristic local search algorithm.
1345
+ The main characteristic of this algorithm is that it accepts
1346
+ even solutions which lead to the increase of the cost in order
1347
+ to escape from low quality local optimal solutions.
1348
+
1349
+ This algorithm needs an initial solution. This solution can be
1350
+ constructed by a simple greedy algorithm. At every iteration, it
1351
+ selects thoughtfully a neighbor solution.
1352
+ Consider $c(x)$ cost of current solution and $c(x')$ cost of
1353
+ neighbor solution.
1354
+ If $c(x') - c(x) <= threshold$ then the neighbor solution becomes the current
1355
+ solution for the next iteration, where the threshold is named threshold.
1356
+
1357
+ In comparison to the Simulated Annealing algorithm, the Threshold
1358
+ Accepting algorithm does not accept very low quality solutions
1359
+ (due to the presence of the threshold value). In the case of
1360
+ Simulated Annealing, even a very low quality solution can
1361
+ be accepted with probability $p$.
1362
+
1363
+ Time complexity:
1364
+ It has a running time $O(m * n * |V|)$ where $m$ and $n$ are the number
1365
+ of times the outer and inner loop run respectively.
1366
+
1367
+ For more information and how algorithm is inspired see:
1368
+ https://doi.org/10.1016/0021-9991(90)90201-B
1369
+
1370
+ See Also
1371
+ --------
1372
+ simulated_annealing_tsp
1373
+
1374
+ """
1375
+ if move == "1-1":
1376
+ move = swap_two_nodes
1377
+ elif move == "1-0":
1378
+ move = move_one_node
1379
+ if init_cycle == "greedy":
1380
+ # Construct an initial solution using a greedy algorithm.
1381
+ cycle = greedy_tsp(G, weight=weight, source=source)
1382
+ if G.number_of_nodes() == 2:
1383
+ return cycle
1384
+
1385
+ else:
1386
+ cycle = list(init_cycle)
1387
+ if source is None:
1388
+ source = cycle[0]
1389
+ elif source != cycle[0]:
1390
+ raise nx.NetworkXError("source must be first node in init_cycle")
1391
+ if cycle[0] != cycle[-1]:
1392
+ raise nx.NetworkXError("init_cycle must be a cycle. (return to start)")
1393
+
1394
+ if len(cycle) - 1 != len(G) or len(set(G.nbunch_iter(cycle))) != len(G):
1395
+ raise nx.NetworkXError("init_cycle is not all and only nodes.")
1396
+
1397
+ # Check that G is a complete graph
1398
+ N = len(G) - 1
1399
+ # This check ignores selfloops which is what we want here.
1400
+ if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
1401
+ raise nx.NetworkXError("G must be a complete graph.")
1402
+
1403
+ if G.number_of_nodes() == 2:
1404
+ neighbor = list(G.neighbors(source))[0]
1405
+ return [source, neighbor, source]
1406
+
1407
+ # Find the cost of initial solution
1408
+ cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(cycle))
1409
+
1410
+ count = 0
1411
+ best_cycle = cycle.copy()
1412
+ best_cost = cost
1413
+ while count <= max_iterations:
1414
+ count += 1
1415
+ accepted = False
1416
+ for i in range(N_inner):
1417
+ adj_sol = move(cycle, seed)
1418
+ adj_cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(adj_sol))
1419
+ delta = adj_cost - cost
1420
+ if delta <= threshold:
1421
+ accepted = True
1422
+
1423
+ # Set current solution the adjacent solution.
1424
+ cycle = adj_sol
1425
+ cost = adj_cost
1426
+
1427
+ if cost < best_cost:
1428
+ count = 0
1429
+ best_cycle = cycle.copy()
1430
+ best_cost = cost
1431
+ if accepted:
1432
+ threshold -= threshold * alpha
1433
+
1434
+ return best_cycle
runtime/Lib/site-packages/networkx/algorithms/approximation/treewidth.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing treewidth decomposition.
2
+
3
+ Treewidth of an undirected graph is a number associated with the graph.
4
+ It can be defined as the size of the largest vertex set (bag) in a tree
5
+ decomposition of the graph minus one.
6
+
7
+ `Wikipedia: Treewidth <https://en.wikipedia.org/wiki/Treewidth>`_
8
+
9
+ The notions of treewidth and tree decomposition have gained their
10
+ attractiveness partly because many graph and network problems that are
11
+ intractable (e.g., NP-hard) on arbitrary graphs become efficiently
12
+ solvable (e.g., with a linear time algorithm) when the treewidth of the
13
+ input graphs is bounded by a constant [1]_ [2]_.
14
+
15
+ There are two different functions for computing a tree decomposition:
16
+ :func:`treewidth_min_degree` and :func:`treewidth_min_fill_in`.
17
+
18
+ .. [1] Hans L. Bodlaender and Arie M. C. A. Koster. 2010. "Treewidth
19
+ computations I.Upper bounds". Inf. Comput. 208, 3 (March 2010),259-275.
20
+ http://dx.doi.org/10.1016/j.ic.2009.03.008
21
+
22
+ .. [2] Hans L. Bodlaender. "Discovering Treewidth". Institute of Information
23
+ and Computing Sciences, Utrecht University.
24
+ Technical Report UU-CS-2005-018.
25
+ http://www.cs.uu.nl
26
+
27
+ .. [3] K. Wang, Z. Lu, and J. Hicks *Treewidth*.
28
+ https://web.archive.org/web/20210507025929/http://web.eecs.utk.edu/~cphill25/cs594_spring2015_projects/treewidth.pdf
29
+
30
+ """
31
+
32
+ import itertools
33
+ import sys
34
+ from heapq import heapify, heappop, heappush
35
+
36
+ import networkx as nx
37
+ from networkx.utils import not_implemented_for
38
+
39
+ __all__ = ["treewidth_min_degree", "treewidth_min_fill_in"]
40
+
41
+
42
+ @not_implemented_for("directed")
43
+ @not_implemented_for("multigraph")
44
+ def treewidth_min_degree(G):
45
+ """Returns a treewidth decomposition using the Minimum Degree heuristic.
46
+
47
+ The heuristic chooses the nodes according to their degree, i.e., first
48
+ the node with the lowest degree is chosen, then the graph is updated
49
+ and the corresponding node is removed. Next, a new node with the lowest
50
+ degree is chosen, and so on.
51
+
52
+ Parameters
53
+ ----------
54
+ G : NetworkX graph
55
+
56
+ Returns
57
+ -------
58
+ Treewidth decomposition : (int, Graph) tuple
59
+ 2-tuple with treewidth and the corresponding decomposed tree.
60
+ """
61
+ deg_heuristic = MinDegreeHeuristic(G)
62
+ return treewidth_decomp(G, lambda graph: deg_heuristic.best_node(graph))
63
+
64
+
65
+ @not_implemented_for("directed")
66
+ @not_implemented_for("multigraph")
67
+ def treewidth_min_fill_in(G):
68
+ """Returns a treewidth decomposition using the Minimum Fill-in heuristic.
69
+
70
+ The heuristic chooses a node from the graph, where the number of edges
71
+ added turning the neighbourhood of the chosen node into clique is as
72
+ small as possible.
73
+
74
+ Parameters
75
+ ----------
76
+ G : NetworkX graph
77
+
78
+ Returns
79
+ -------
80
+ Treewidth decomposition : (int, Graph) tuple
81
+ 2-tuple with treewidth and the corresponding decomposed tree.
82
+ """
83
+ return treewidth_decomp(G, min_fill_in_heuristic)
84
+
85
+
86
+ class MinDegreeHeuristic:
87
+ """Implements the Minimum Degree heuristic.
88
+
89
+ The heuristic chooses the nodes according to their degree
90
+ (number of neighbours), i.e., first the node with the lowest degree is
91
+ chosen, then the graph is updated and the corresponding node is
92
+ removed. Next, a new node with the lowest degree is chosen, and so on.
93
+ """
94
+
95
+ def __init__(self, graph):
96
+ self._graph = graph
97
+
98
+ # nodes that have to be updated in the heap before each iteration
99
+ self._update_nodes = []
100
+
101
+ self._degreeq = [] # a heapq with 3-tuples (degree,unique_id,node)
102
+ self.count = itertools.count()
103
+
104
+ # build heap with initial degrees
105
+ for n in graph:
106
+ self._degreeq.append((len(graph[n]), next(self.count), n))
107
+ heapify(self._degreeq)
108
+
109
+ def best_node(self, graph):
110
+ # update nodes in self._update_nodes
111
+ for n in self._update_nodes:
112
+ # insert changed degrees into degreeq
113
+ heappush(self._degreeq, (len(graph[n]), next(self.count), n))
114
+
115
+ # get the next valid (minimum degree) node
116
+ while self._degreeq:
117
+ (min_degree, _, elim_node) = heappop(self._degreeq)
118
+ if elim_node not in graph or len(graph[elim_node]) != min_degree:
119
+ # outdated entry in degreeq
120
+ continue
121
+ elif min_degree == len(graph) - 1:
122
+ # fully connected: abort condition
123
+ return None
124
+
125
+ # remember to update nodes in the heap before getting the next node
126
+ self._update_nodes = graph[elim_node]
127
+ return elim_node
128
+
129
+ # the heap is empty: abort
130
+ return None
131
+
132
+
133
+ def min_fill_in_heuristic(graph):
134
+ """Implements the Minimum Degree heuristic.
135
+
136
+ Returns the node from the graph, where the number of edges added when
137
+ turning the neighbourhood of the chosen node into clique is as small as
138
+ possible. This algorithm chooses the nodes using the Minimum Fill-In
139
+ heuristic. The running time of the algorithm is :math:`O(V^3)` and it uses
140
+ additional constant memory."""
141
+
142
+ if len(graph) == 0:
143
+ return None
144
+
145
+ min_fill_in_node = None
146
+
147
+ min_fill_in = sys.maxsize
148
+
149
+ # sort nodes by degree
150
+ nodes_by_degree = sorted(graph, key=lambda x: len(graph[x]))
151
+ min_degree = len(graph[nodes_by_degree[0]])
152
+
153
+ # abort condition (handle complete graph)
154
+ if min_degree == len(graph) - 1:
155
+ return None
156
+
157
+ for node in nodes_by_degree:
158
+ num_fill_in = 0
159
+ nbrs = graph[node]
160
+ for nbr in nbrs:
161
+ # count how many nodes in nbrs current nbr is not connected to
162
+ # subtract 1 for the node itself
163
+ num_fill_in += len(nbrs - graph[nbr]) - 1
164
+ if num_fill_in >= 2 * min_fill_in:
165
+ break
166
+
167
+ num_fill_in /= 2 # divide by 2 because of double counting
168
+
169
+ if num_fill_in < min_fill_in: # update min-fill-in node
170
+ if num_fill_in == 0:
171
+ return node
172
+ min_fill_in = num_fill_in
173
+ min_fill_in_node = node
174
+
175
+ return min_fill_in_node
176
+
177
+
178
+ def treewidth_decomp(G, heuristic=min_fill_in_heuristic):
179
+ """Returns a treewidth decomposition using the passed heuristic.
180
+
181
+ Parameters
182
+ ----------
183
+ G : NetworkX graph
184
+ heuristic : heuristic function
185
+
186
+ Returns
187
+ -------
188
+ Treewidth decomposition : (int, Graph) tuple
189
+ 2-tuple with treewidth and the corresponding decomposed tree.
190
+ """
191
+
192
+ # make dict-of-sets structure
193
+ graph = {n: set(G[n]) - {n} for n in G}
194
+
195
+ # stack containing nodes and neighbors in the order from the heuristic
196
+ node_stack = []
197
+
198
+ # get first node from heuristic
199
+ elim_node = heuristic(graph)
200
+ while elim_node is not None:
201
+ # connect all neighbours with each other
202
+ nbrs = graph[elim_node]
203
+ for u, v in itertools.permutations(nbrs, 2):
204
+ if v not in graph[u]:
205
+ graph[u].add(v)
206
+
207
+ # push node and its current neighbors on stack
208
+ node_stack.append((elim_node, nbrs))
209
+
210
+ # remove node from graph
211
+ for u in graph[elim_node]:
212
+ graph[u].remove(elim_node)
213
+
214
+ del graph[elim_node]
215
+ elim_node = heuristic(graph)
216
+
217
+ # the abort condition is met; put all remaining nodes into one bag
218
+ decomp = nx.Graph()
219
+ first_bag = frozenset(graph.keys())
220
+ decomp.add_node(first_bag)
221
+
222
+ treewidth = len(first_bag) - 1
223
+
224
+ while node_stack:
225
+ # get node and its neighbors from the stack
226
+ (curr_node, nbrs) = node_stack.pop()
227
+
228
+ # find a bag all neighbors are in
229
+ old_bag = None
230
+ for bag in decomp.nodes:
231
+ if nbrs <= bag:
232
+ old_bag = bag
233
+ break
234
+
235
+ if old_bag is None:
236
+ # no old_bag was found: just connect to the first_bag
237
+ old_bag = first_bag
238
+
239
+ # create new node for decomposition
240
+ nbrs.add(curr_node)
241
+ new_bag = frozenset(nbrs)
242
+
243
+ # update treewidth
244
+ treewidth = max(treewidth, len(new_bag) - 1)
245
+
246
+ # add edge to decomposition (implicitly also adds the new node)
247
+ decomp.add_edge(old_bag, new_bag)
248
+
249
+ return treewidth, decomp
runtime/Lib/site-packages/networkx/algorithms/approximation/vertex_cover.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing an approximate minimum weight vertex cover.
2
+
3
+ A |vertex cover|_ is a subset of nodes such that each edge in the graph
4
+ is incident to at least one node in the subset.
5
+
6
+ .. _vertex cover: https://en.wikipedia.org/wiki/Vertex_cover
7
+ .. |vertex cover| replace:: *vertex cover*
8
+
9
+ """
10
+
11
+ __all__ = ["min_weighted_vertex_cover"]
12
+
13
+
14
+ def min_weighted_vertex_cover(G, weight=None):
15
+ r"""Returns an approximate minimum weighted vertex cover.
16
+
17
+ The set of nodes returned by this function is guaranteed to be a
18
+ vertex cover, and the total weight of the set is guaranteed to be at
19
+ most twice the total weight of the minimum weight vertex cover. In
20
+ other words,
21
+
22
+ .. math::
23
+
24
+ w(S) \leq 2 * w(S^*),
25
+
26
+ where $S$ is the vertex cover returned by this function,
27
+ $S^*$ is the vertex cover of minimum weight out of all vertex
28
+ covers of the graph, and $w$ is the function that computes the
29
+ sum of the weights of each node in that given set.
30
+
31
+ Parameters
32
+ ----------
33
+ G : NetworkX graph
34
+
35
+ weight : string, optional (default = None)
36
+ If None, every node has weight 1. If a string, use this node
37
+ attribute as the node weight. A node without this attribute is
38
+ assumed to have weight 1.
39
+
40
+ Returns
41
+ -------
42
+ min_weighted_cover : set
43
+ Returns a set of nodes whose weight sum is no more than twice
44
+ the weight sum of the minimum weight vertex cover.
45
+
46
+ Notes
47
+ -----
48
+ For a directed graph, a vertex cover has the same definition: a set
49
+ of nodes such that each edge in the graph is incident to at least
50
+ one node in the set. Whether the node is the head or tail of the
51
+ directed edge is ignored.
52
+
53
+ This is the local-ratio algorithm for computing an approximate
54
+ vertex cover. The algorithm greedily reduces the costs over edges,
55
+ iteratively building a cover. The worst-case runtime of this
56
+ implementation is $O(m \log n)$, where $n$ is the number
57
+ of nodes and $m$ the number of edges in the graph.
58
+
59
+ References
60
+ ----------
61
+ .. [1] Bar-Yehuda, R., and Even, S. (1985). "A local-ratio theorem for
62
+ approximating the weighted vertex cover problem."
63
+ *Annals of Discrete Mathematics*, 25, 27–46
64
+ <http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf>
65
+
66
+ """
67
+ cost = dict(G.nodes(data=weight, default=1))
68
+ # While there are uncovered edges, choose an uncovered and update
69
+ # the cost of the remaining edges.
70
+ cover = set()
71
+ for u, v in G.edges():
72
+ if u in cover or v in cover:
73
+ continue
74
+ if cost[u] <= cost[v]:
75
+ cover.add(u)
76
+ cost[v] -= cost[u]
77
+ else:
78
+ cover.add(v)
79
+ cost[u] -= cost[v]
80
+ return cover
runtime/Lib/site-packages/networkx/algorithms/assortativity/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from networkx.algorithms.assortativity.connectivity import *
2
+ from networkx.algorithms.assortativity.correlation import *
3
+ from networkx.algorithms.assortativity.mixing import *
4
+ from networkx.algorithms.assortativity.neighbor_degree import *
5
+ from networkx.algorithms.assortativity.pairs import *
runtime/Lib/site-packages/networkx/algorithms/assortativity/connectivity.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["average_degree_connectivity", "k_nearest_neighbors"]
6
+
7
+
8
+ def average_degree_connectivity(
9
+ G, source="in+out", target="in+out", nodes=None, weight=None
10
+ ):
11
+ r"""Compute the average degree connectivity of graph.
12
+
13
+ The average degree connectivity is the average nearest neighbor degree of
14
+ nodes with degree k. For weighted graphs, an analogous measure can
15
+ be computed using the weighted average neighbors degree defined in
16
+ [1]_, for a node `i`, as
17
+
18
+ .. math::
19
+
20
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
21
+
22
+ where `s_i` is the weighted degree of node `i`,
23
+ `w_{ij}` is the weight of the edge that links `i` and `j`,
24
+ and `N(i)` are the neighbors of node `i`.
25
+
26
+ Parameters
27
+ ----------
28
+ G : NetworkX graph
29
+
30
+ source : "in"|"out"|"in+out" (default:"in+out")
31
+ Directed graphs only. Use "in"- or "out"-degree for source node.
32
+
33
+ target : "in"|"out"|"in+out" (default:"in+out"
34
+ Directed graphs only. Use "in"- or "out"-degree for target node.
35
+
36
+ nodes : list or iterable (optional)
37
+ Compute neighbor connectivity for these nodes. The default is all
38
+ nodes.
39
+
40
+ weight : string or None, optional (default=None)
41
+ The edge attribute that holds the numerical value used as a weight.
42
+ If None, then each edge has weight 1.
43
+
44
+ Returns
45
+ -------
46
+ d : dict
47
+ A dictionary keyed by degree k with the value of average connectivity.
48
+
49
+ Raises
50
+ ------
51
+ NetworkXError
52
+ If either `source` or `target` are not one of 'in',
53
+ 'out', or 'in+out'.
54
+ If either `source` or `target` is passed for an undirected graph.
55
+
56
+ Examples
57
+ --------
58
+ >>> G = nx.path_graph(4)
59
+ >>> G.edges[1, 2]["weight"] = 3
60
+ >>> nx.average_degree_connectivity(G)
61
+ {1: 2.0, 2: 1.5}
62
+ >>> nx.average_degree_connectivity(G, weight="weight")
63
+ {1: 2.0, 2: 1.75}
64
+
65
+ See Also
66
+ --------
67
+ average_neighbor_degree
68
+
69
+ References
70
+ ----------
71
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
72
+ "The architecture of complex weighted networks".
73
+ PNAS 101 (11): 3747–3752 (2004).
74
+ """
75
+ # First, determine the type of neighbors and the type of degree to use.
76
+ if G.is_directed():
77
+ if source not in ("in", "out", "in+out"):
78
+ raise nx.NetworkXError('source must be one of "in", "out", or "in+out"')
79
+ if target not in ("in", "out", "in+out"):
80
+ raise nx.NetworkXError('target must be one of "in", "out", or "in+out"')
81
+ direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree}
82
+ neighbor_funcs = {
83
+ "out": G.successors,
84
+ "in": G.predecessors,
85
+ "in+out": G.neighbors,
86
+ }
87
+ source_degree = direction[source]
88
+ target_degree = direction[target]
89
+ neighbors = neighbor_funcs[source]
90
+ # `reverse` indicates whether to look at the in-edge when
91
+ # computing the weight of an edge.
92
+ reverse = source == "in"
93
+ else:
94
+ if source != "in+out" or target != "in+out":
95
+ raise nx.NetworkXError(
96
+ f"source and target arguments are only supported for directed graphs"
97
+ )
98
+ source_degree = G.degree
99
+ target_degree = G.degree
100
+ neighbors = G.neighbors
101
+ reverse = False
102
+ dsum = defaultdict(int)
103
+ dnorm = defaultdict(int)
104
+ # Check if `source_nodes` is actually a single node in the graph.
105
+ source_nodes = source_degree(nodes)
106
+ if nodes in G:
107
+ source_nodes = [(nodes, source_degree(nodes))]
108
+ for n, k in source_nodes:
109
+ nbrdeg = target_degree(neighbors(n))
110
+ if weight is None:
111
+ s = sum(d for n, d in nbrdeg)
112
+ else: # weight nbr degree by weight of (n,nbr) edge
113
+ if reverse:
114
+ s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg)
115
+ else:
116
+ s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg)
117
+ dnorm[k] += source_degree(n, weight=weight)
118
+ dsum[k] += s
119
+
120
+ # normalize
121
+ return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}
122
+
123
+
124
+ def k_nearest_neighbors(G, source="in+out", target="in+out", nodes=None, weight=None):
125
+ """Compute the average degree connectivity of graph.
126
+
127
+ .. deprecated 2.6
128
+
129
+ k_nearest_neighbors function is deprecated and will be removed in v3.0.
130
+ Use `average_degree_connectivity` instead.
131
+ """
132
+ import warnings
133
+
134
+ msg = (
135
+ "k_nearest_neighbors function is deprecated and will be removed in v3.0.\n"
136
+ "Use `average_degree_connectivity` instead."
137
+ )
138
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
139
+ return average_degree_connectivity(G, source, target, nodes, weight)
runtime/Lib/site-packages/networkx/algorithms/assortativity/correlation.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Node assortativity coefficients and correlation measures.
2
+ """
3
+ from networkx.algorithms.assortativity.mixing import (
4
+ attribute_mixing_matrix,
5
+ degree_mixing_matrix,
6
+ )
7
+ from networkx.algorithms.assortativity.pairs import node_degree_xy
8
+
9
+ __all__ = [
10
+ "degree_pearson_correlation_coefficient",
11
+ "degree_assortativity_coefficient",
12
+ "attribute_assortativity_coefficient",
13
+ "numeric_assortativity_coefficient",
14
+ ]
15
+
16
+
17
+ def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
18
+ """Compute degree assortativity of graph.
19
+
20
+ Assortativity measures the similarity of connections
21
+ in the graph with respect to the node degree.
22
+
23
+ Parameters
24
+ ----------
25
+ G : NetworkX graph
26
+
27
+ x: string ('in','out')
28
+ The degree type for source node (directed graphs only).
29
+
30
+ y: string ('in','out')
31
+ The degree type for target node (directed graphs only).
32
+
33
+ weight: string or None, optional (default=None)
34
+ The edge attribute that holds the numerical value used
35
+ as a weight. If None, then each edge has weight 1.
36
+ The degree is the sum of the edge weights adjacent to the node.
37
+
38
+ nodes: list or iterable (optional)
39
+ Compute degree assortativity only for nodes in container.
40
+ The default is all nodes.
41
+
42
+ Returns
43
+ -------
44
+ r : float
45
+ Assortativity of graph by degree.
46
+
47
+ Examples
48
+ --------
49
+ >>> G = nx.path_graph(4)
50
+ >>> r = nx.degree_assortativity_coefficient(G)
51
+ >>> print(f"{r:3.1f}")
52
+ -0.5
53
+
54
+ See Also
55
+ --------
56
+ attribute_assortativity_coefficient
57
+ numeric_assortativity_coefficient
58
+ degree_mixing_dict
59
+ degree_mixing_matrix
60
+
61
+ Notes
62
+ -----
63
+ This computes Eq. (21) in Ref. [1]_ , where e is the joint
64
+ probability distribution (mixing matrix) of the degrees. If G is
65
+ directed than the matrix e is the joint probability of the
66
+ user-specified degree type for the source and target.
67
+
68
+ References
69
+ ----------
70
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
71
+ Physical Review E, 67 026126, 2003
72
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
73
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
74
+ """
75
+ if nodes is None:
76
+ nodes = G.nodes
77
+
78
+ degrees = None
79
+
80
+ if G.is_directed():
81
+ indeg = (
82
+ {d for _, d in G.in_degree(nodes, weight=weight)}
83
+ if "in" in (x, y)
84
+ else set()
85
+ )
86
+ outdeg = (
87
+ {d for _, d in G.out_degree(nodes, weight=weight)}
88
+ if "out" in (x, y)
89
+ else set()
90
+ )
91
+ degrees = set.union(indeg, outdeg)
92
+ else:
93
+ degrees = {d for _, d in G.degree(nodes, weight=weight)}
94
+
95
+ mapping = {d: i for i, d, in enumerate(degrees)}
96
+ M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
97
+
98
+ return _numeric_ac(M, mapping=mapping)
99
+
100
+
101
+ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
102
+ """Compute degree assortativity of graph.
103
+
104
+ Assortativity measures the similarity of connections
105
+ in the graph with respect to the node degree.
106
+
107
+ This is the same as degree_assortativity_coefficient but uses the
108
+ potentially faster scipy.stats.pearsonr function.
109
+
110
+ Parameters
111
+ ----------
112
+ G : NetworkX graph
113
+
114
+ x: string ('in','out')
115
+ The degree type for source node (directed graphs only).
116
+
117
+ y: string ('in','out')
118
+ The degree type for target node (directed graphs only).
119
+
120
+ weight: string or None, optional (default=None)
121
+ The edge attribute that holds the numerical value used
122
+ as a weight. If None, then each edge has weight 1.
123
+ The degree is the sum of the edge weights adjacent to the node.
124
+
125
+ nodes: list or iterable (optional)
126
+ Compute pearson correlation of degrees only for specified nodes.
127
+ The default is all nodes.
128
+
129
+ Returns
130
+ -------
131
+ r : float
132
+ Assortativity of graph by degree.
133
+
134
+ Examples
135
+ --------
136
+ >>> G = nx.path_graph(4)
137
+ >>> r = nx.degree_pearson_correlation_coefficient(G)
138
+ >>> print(f"{r:3.1f}")
139
+ -0.5
140
+
141
+ Notes
142
+ -----
143
+ This calls scipy.stats.pearsonr.
144
+
145
+ References
146
+ ----------
147
+ .. [1] M. E. J. Newman, Mixing patterns in networks
148
+ Physical Review E, 67 026126, 2003
149
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
150
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
151
+ """
152
+ import scipy as sp
153
+ import scipy.stats # call as sp.stats
154
+
155
+ xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
156
+ x, y = zip(*xy)
157
+ return sp.stats.pearsonr(x, y)[0]
158
+
159
+
160
+ def attribute_assortativity_coefficient(G, attribute, nodes=None):
161
+ """Compute assortativity for node attributes.
162
+
163
+ Assortativity measures the similarity of connections
164
+ in the graph with respect to the given attribute.
165
+
166
+ Parameters
167
+ ----------
168
+ G : NetworkX graph
169
+
170
+ attribute : string
171
+ Node attribute key
172
+
173
+ nodes: list or iterable (optional)
174
+ Compute attribute assortativity for nodes in container.
175
+ The default is all nodes.
176
+
177
+ Returns
178
+ -------
179
+ r: float
180
+ Assortativity of graph for given attribute
181
+
182
+ Examples
183
+ --------
184
+ >>> G = nx.Graph()
185
+ >>> G.add_nodes_from([0, 1], color="red")
186
+ >>> G.add_nodes_from([2, 3], color="blue")
187
+ >>> G.add_edges_from([(0, 1), (2, 3)])
188
+ >>> print(nx.attribute_assortativity_coefficient(G, "color"))
189
+ 1.0
190
+
191
+ Notes
192
+ -----
193
+ This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
194
+ where M is the joint probability distribution (mixing matrix)
195
+ of the specified attribute.
196
+
197
+ References
198
+ ----------
199
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
200
+ Physical Review E, 67 026126, 2003
201
+ """
202
+ M = attribute_mixing_matrix(G, attribute, nodes)
203
+ return attribute_ac(M)
204
+
205
+
206
+ def numeric_assortativity_coefficient(G, attribute, nodes=None):
207
+ """Compute assortativity for numerical node attributes.
208
+
209
+ Assortativity measures the similarity of connections
210
+ in the graph with respect to the given numeric attribute.
211
+
212
+ Parameters
213
+ ----------
214
+ G : NetworkX graph
215
+
216
+ attribute : string
217
+ Node attribute key.
218
+
219
+ nodes: list or iterable (optional)
220
+ Compute numeric assortativity only for attributes of nodes in
221
+ container. The default is all nodes.
222
+
223
+ Returns
224
+ -------
225
+ r: float
226
+ Assortativity of graph for given attribute
227
+
228
+ Examples
229
+ --------
230
+ >>> G = nx.Graph()
231
+ >>> G.add_nodes_from([0, 1], size=2)
232
+ >>> G.add_nodes_from([2, 3], size=3)
233
+ >>> G.add_edges_from([(0, 1), (2, 3)])
234
+ >>> print(nx.numeric_assortativity_coefficient(G, "size"))
235
+ 1.0
236
+
237
+ Notes
238
+ -----
239
+ This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
240
+ coefficient of the specified (scalar valued) attribute across edges.
241
+
242
+ References
243
+ ----------
244
+ .. [1] M. E. J. Newman, Mixing patterns in networks
245
+ Physical Review E, 67 026126, 2003
246
+ """
247
+ if nodes is None:
248
+ nodes = G.nodes
249
+ vals = {G.nodes[n][attribute] for n in nodes}
250
+ mapping = {d: i for i, d, in enumerate(vals)}
251
+ M = attribute_mixing_matrix(G, attribute, nodes, mapping)
252
+ return _numeric_ac(M, mapping)
253
+
254
+
255
+ def attribute_ac(M):
256
+ """Compute assortativity for attribute matrix M.
257
+
258
+ Parameters
259
+ ----------
260
+ M : numpy.ndarray
261
+ 2D ndarray representing the attribute mixing matrix.
262
+
263
+ Notes
264
+ -----
265
+ This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
266
+ where e is the joint probability distribution (mixing matrix)
267
+ of the specified attribute.
268
+
269
+ References
270
+ ----------
271
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
272
+ Physical Review E, 67 026126, 2003
273
+ """
274
+ if M.sum() != 1.0:
275
+ M = M / M.sum()
276
+ s = (M @ M).sum()
277
+ t = M.trace()
278
+ r = (t - s) / (1 - s)
279
+ return r
280
+
281
+
282
+ def _numeric_ac(M, mapping):
283
+ # M is a 2D numpy array
284
+ # numeric assortativity coefficient, pearsonr
285
+ import numpy as np
286
+
287
+ if M.sum() != 1.0:
288
+ M = M / M.sum()
289
+ x = np.array(list(mapping.keys()))
290
+ y = x # x and y have the same support
291
+ idx = list(mapping.values())
292
+ a = M.sum(axis=0)
293
+ b = M.sum(axis=1)
294
+ vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
295
+ varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
296
+ xy = np.outer(x, y)
297
+ ab = np.outer(a[idx], b[idx])
298
+ return (xy * (M - ab)).sum() / np.sqrt(vara * varb)
runtime/Lib/site-packages/networkx/algorithms/assortativity/mixing.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mixing matrices for node attributes and degree.
3
+ """
4
+ from networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xy
5
+ from networkx.utils import dict_to_numpy_array
6
+
7
+ __all__ = [
8
+ "attribute_mixing_matrix",
9
+ "attribute_mixing_dict",
10
+ "degree_mixing_matrix",
11
+ "degree_mixing_dict",
12
+ "numeric_mixing_matrix",
13
+ "mixing_dict",
14
+ ]
15
+
16
+
17
+ def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
18
+ """Returns dictionary representation of mixing matrix for attribute.
19
+
20
+ Parameters
21
+ ----------
22
+ G : graph
23
+ NetworkX graph object.
24
+
25
+ attribute : string
26
+ Node attribute key.
27
+
28
+ nodes: list or iterable (optional)
29
+ Unse nodes in container to build the dict. The default is all nodes.
30
+
31
+ normalized : bool (default=False)
32
+ Return counts if False or probabilities if True.
33
+
34
+ Examples
35
+ --------
36
+ >>> G = nx.Graph()
37
+ >>> G.add_nodes_from([0, 1], color="red")
38
+ >>> G.add_nodes_from([2, 3], color="blue")
39
+ >>> G.add_edge(1, 3)
40
+ >>> d = nx.attribute_mixing_dict(G, "color")
41
+ >>> print(d["red"]["blue"])
42
+ 1
43
+ >>> print(d["blue"]["red"]) # d symmetric for undirected graphs
44
+ 1
45
+
46
+ Returns
47
+ -------
48
+ d : dictionary
49
+ Counts or joint probability of occurrence of attribute pairs.
50
+ """
51
+ xy_iter = node_attribute_xy(G, attribute, nodes)
52
+ return mixing_dict(xy_iter, normalized=normalized)
53
+
54
+
55
+ def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True):
56
+ """Returns mixing matrix for attribute.
57
+
58
+ Parameters
59
+ ----------
60
+ G : graph
61
+ NetworkX graph object.
62
+
63
+ attribute : string
64
+ Node attribute key.
65
+
66
+ nodes: list or iterable (optional)
67
+ Use only nodes in container to build the matrix. The default is
68
+ all nodes.
69
+
70
+ mapping : dictionary, optional
71
+ Mapping from node attribute to integer index in matrix.
72
+ If not specified, an arbitrary ordering will be used.
73
+
74
+ normalized : bool (default=True)
75
+ Return counts if False or probabilities if True.
76
+
77
+ Returns
78
+ -------
79
+ m: numpy array
80
+ Counts or joint probability of occurrence of attribute pairs.
81
+
82
+ Notes
83
+ -----
84
+ If each node has a unique attribute value, the unnormalized mixing matrix
85
+ will be equal to the adjacency matrix. To get a denser mixing matrix,
86
+ the rounding can be performed to form groups of nodes with equal values.
87
+ For example, the exact height of persons in cm (180.79155222, 163.9080892,
88
+ 163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
89
+ 163, 168, 168, ...).
90
+
91
+ Definitions of attribute mixing matrix vary on whether the matrix
92
+ should include rows for attribute values that don't arise. Here we
93
+ do not include such empty-rows. But you can force them to appear
94
+ by inputting a `mapping` that includes those values.
95
+
96
+ Examples
97
+ --------
98
+ >>> G = nx.path_graph(3)
99
+ >>> gender = {0: 'male', 1: 'female', 2: 'female'}
100
+ >>> nx.set_node_attributes(G, gender, 'gender')
101
+ >>> mapping = {'male': 0, 'female': 1}
102
+ >>> mix_mat = nx.attribute_mixing_matrix(G, 'gender', mapping=mapping)
103
+ >>> # mixing from male nodes to female nodes
104
+ >>> mix_mat[mapping['male'], mapping['female']]
105
+ 0.25
106
+ """
107
+ d = attribute_mixing_dict(G, attribute, nodes)
108
+ a = dict_to_numpy_array(d, mapping=mapping)
109
+ if normalized:
110
+ a = a / a.sum()
111
+ return a
112
+
113
+
114
+ def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False):
115
+ """Returns dictionary representation of mixing matrix for degree.
116
+
117
+ Parameters
118
+ ----------
119
+ G : graph
120
+ NetworkX graph object.
121
+
122
+ x: string ('in','out')
123
+ The degree type for source node (directed graphs only).
124
+
125
+ y: string ('in','out')
126
+ The degree type for target node (directed graphs only).
127
+
128
+ weight: string or None, optional (default=None)
129
+ The edge attribute that holds the numerical value used
130
+ as a weight. If None, then each edge has weight 1.
131
+ The degree is the sum of the edge weights adjacent to the node.
132
+
133
+ normalized : bool (default=False)
134
+ Return counts if False or probabilities if True.
135
+
136
+ Returns
137
+ -------
138
+ d: dictionary
139
+ Counts or joint probability of occurrence of degree pairs.
140
+ """
141
+ xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
142
+ return mixing_dict(xy_iter, normalized=normalized)
143
+
144
+
145
+ def degree_mixing_matrix(
146
+ G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None
147
+ ):
148
+ """Returns mixing matrix for attribute.
149
+
150
+ Parameters
151
+ ----------
152
+ G : graph
153
+ NetworkX graph object.
154
+
155
+ x: string ('in','out')
156
+ The degree type for source node (directed graphs only).
157
+
158
+ y: string ('in','out')
159
+ The degree type for target node (directed graphs only).
160
+
161
+ nodes: list or iterable (optional)
162
+ Build the matrix using only nodes in container.
163
+ The default is all nodes.
164
+
165
+ weight: string or None, optional (default=None)
166
+ The edge attribute that holds the numerical value used
167
+ as a weight. If None, then each edge has weight 1.
168
+ The degree is the sum of the edge weights adjacent to the node.
169
+
170
+ normalized : bool (default=True)
171
+ Return counts if False or probabilities if True.
172
+
173
+ mapping : dictionary, optional
174
+ Mapping from node degree to integer index in matrix.
175
+ If not specified, an arbitrary ordering will be used.
176
+
177
+ Returns
178
+ -------
179
+ m: numpy array
180
+ Counts, or joint probability, of occurrence of node degree.
181
+
182
+ Notes
183
+ -----
184
+ Definitions of degree mixing matrix vary on whether the matrix
185
+ should include rows for degree values that don't arise. Here we
186
+ do not include such empty-rows. But you can force them to appear
187
+ by inputting a `mapping` that includes those values. See examples.
188
+
189
+ Examples
190
+ --------
191
+ >>> G = nx.star_graph(3)
192
+ >>> mix_mat = nx.degree_mixing_matrix(G)
193
+ >>> mix_mat[0, 1] # mixing from node degree 1 to node degree 3
194
+ 0.5
195
+
196
+ If you want every possible degree to appear as a row, even if no nodes
197
+ have that degree, use `mapping` as follows,
198
+
199
+ >>> max_degree = max(deg for n, deg in G.degree)
200
+ >>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping
201
+ >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping)
202
+ >>> mix_mat[3, 1] # mixing from node degree 3 to node degree 1
203
+ 0.5
204
+ """
205
+ d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
206
+ a = dict_to_numpy_array(d, mapping=mapping)
207
+ if normalized:
208
+ a = a / a.sum()
209
+ return a
210
+
211
+
212
+ def numeric_mixing_matrix(G, attribute, nodes=None, normalized=True, mapping=None):
213
+ """Returns numeric mixing matrix for attribute.
214
+
215
+ .. deprecated:: 2.6
216
+
217
+ numeric_mixing_matrix is deprecated and will be removed in 3.0.
218
+ Use `attribute_mixing_matrix` instead.
219
+
220
+ Parameters
221
+ ----------
222
+ G : graph
223
+ NetworkX graph object.
224
+
225
+ attribute : string
226
+ Node attribute key.
227
+
228
+ nodes: list or iterable (optional)
229
+ Build the matrix only with nodes in container. The default is all nodes.
230
+
231
+ normalized : bool (default=True)
232
+ Return counts if False or probabilities if True.
233
+
234
+ mapping : dictionary, optional
235
+ Mapping from node attribute to integer index in matrix.
236
+ If not specified, an arbitrary ordering will be used.
237
+
238
+ Notes
239
+ -----
240
+ If each node has a unique attribute value, the unnormalized mixing matrix
241
+ will be equal to the adjacency matrix. To get a denser mixing matrix,
242
+ the rounding can be performed to form groups of nodes with equal values.
243
+ For example, the exact height of persons in cm (180.79155222, 163.9080892,
244
+ 163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
245
+ 163, 168, 168, ...).
246
+
247
+ Returns
248
+ -------
249
+ m: numpy array
250
+ Counts, or joint, probability of occurrence of node attribute pairs.
251
+ """
252
+ import warnings
253
+
254
+ msg = (
255
+ "numeric_mixing_matrix is deprecated and will be removed in v3.0.\n"
256
+ "Use `attribute_mixing_matrix` instead."
257
+ )
258
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
259
+ return attribute_mixing_matrix(
260
+ G, attribute, nodes=nodes, normalized=normalized, mapping=mapping
261
+ )
262
+
263
+
264
+ def mixing_dict(xy, normalized=False):
265
+ """Returns a dictionary representation of mixing matrix.
266
+
267
+ Parameters
268
+ ----------
269
+ xy : list or container of two-tuples
270
+ Pairs of (x,y) items.
271
+
272
+ attribute : string
273
+ Node attribute key
274
+
275
+ normalized : bool (default=False)
276
+ Return counts if False or probabilities if True.
277
+
278
+ Returns
279
+ -------
280
+ d: dictionary
281
+ Counts or Joint probability of occurrence of values in xy.
282
+ """
283
+ d = {}
284
+ psum = 0.0
285
+ for x, y in xy:
286
+ if x not in d:
287
+ d[x] = {}
288
+ if y not in d:
289
+ d[y] = {}
290
+ v = d[x].get(y, 0)
291
+ d[x][y] = v + 1
292
+ psum += 1
293
+
294
+ if normalized:
295
+ for _, jdict in d.items():
296
+ for j in jdict:
297
+ jdict[j] /= psum
298
+ return d
runtime/Lib/site-packages/networkx/algorithms/assortativity/neighbor_degree.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["average_neighbor_degree"]
4
+
5
+
6
+ def average_neighbor_degree(G, source="out", target="out", nodes=None, weight=None):
7
+ r"""Returns the average degree of the neighborhood of each node.
8
+
9
+ In an undirected graph, the neighborhood `N(i)` of node `i` contains the
10
+ nodes that are connected to `i` by an edge.
11
+
12
+ For directed graphs, `N(i)` is defined according to the parameter `source`:
13
+
14
+ - if source is 'in', then `N(i)` consists of predecessors of node `i`.
15
+ - if source is 'out', then `N(i)` consists of successors of node `i`.
16
+ - if source is 'in+out', then `N(i)` is both predecessors and successors.
17
+
18
+ The average neighborhood degree of a node `i` is
19
+
20
+ .. math::
21
+
22
+ k_{nn,i} = \frac{1}{|N(i)|} \sum_{j \in N(i)} k_j
23
+
24
+ where `N(i)` are the neighbors of node `i` and `k_j` is
25
+ the degree of node `j` which belongs to `N(i)`. For weighted
26
+ graphs, an analogous measure can be defined [1]_,
27
+
28
+ .. math::
29
+
30
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
31
+
32
+ where `s_i` is the weighted degree of node `i`, `w_{ij}`
33
+ is the weight of the edge that links `i` and `j` and
34
+ `N(i)` are the neighbors of node `i`.
35
+
36
+
37
+ Parameters
38
+ ----------
39
+ G : NetworkX graph
40
+
41
+ source : string ("in"|"out"|"in+out"), optional (default="out")
42
+ Directed graphs only.
43
+ Use "in"- or "out"-neighbors of source node.
44
+
45
+ target : string ("in"|"out"|"in+out"), optional (default="out")
46
+ Directed graphs only.
47
+ Use "in"- or "out"-degree for target node.
48
+
49
+ nodes : list or iterable, optional (default=G.nodes)
50
+ Compute neighbor degree only for specified nodes.
51
+
52
+ weight : string or None, optional (default=None)
53
+ The edge attribute that holds the numerical value used as a weight.
54
+ If None, then each edge has weight 1.
55
+
56
+ Returns
57
+ -------
58
+ d: dict
59
+ A dictionary keyed by node to the average degree of its neighbors.
60
+
61
+ Raises
62
+ ------
63
+ NetworkXError
64
+ If either `source` or `target` are not one of 'in', 'out', or 'in+out'.
65
+ If either `source` or `target` is passed for an undirected graph.
66
+
67
+ Examples
68
+ --------
69
+ >>> G = nx.path_graph(4)
70
+ >>> G.edges[0, 1]["weight"] = 5
71
+ >>> G.edges[2, 3]["weight"] = 3
72
+
73
+ >>> nx.average_neighbor_degree(G)
74
+ {0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
75
+ >>> nx.average_neighbor_degree(G, weight="weight")
76
+ {0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
77
+
78
+ >>> G = nx.DiGraph()
79
+ >>> nx.add_path(G, [0, 1, 2, 3])
80
+ >>> nx.average_neighbor_degree(G, source="in", target="in")
81
+ {0: 0.0, 1: 0.0, 2: 1.0, 3: 1.0}
82
+
83
+ >>> nx.average_neighbor_degree(G, source="out", target="out")
84
+ {0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}
85
+
86
+ See Also
87
+ --------
88
+ average_degree_connectivity
89
+
90
+ References
91
+ ----------
92
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
93
+ "The architecture of complex weighted networks".
94
+ PNAS 101 (11): 3747–3752 (2004).
95
+ """
96
+ if G.is_directed():
97
+ if source == "in":
98
+ source_degree = G.in_degree
99
+ elif source == "out":
100
+ source_degree = G.out_degree
101
+ elif source == "in+out":
102
+ source_degree = G.degree
103
+ else:
104
+ raise nx.NetworkXError(
105
+ f"source argument {source} must be 'in', 'out' or 'in+out'"
106
+ )
107
+
108
+ if target == "in":
109
+ target_degree = G.in_degree
110
+ elif target == "out":
111
+ target_degree = G.out_degree
112
+ elif target == "in+out":
113
+ target_degree = G.degree
114
+ else:
115
+ raise nx.NetworkXError(
116
+ f"target argument {target} must be 'in', 'out' or 'in+out'"
117
+ )
118
+ else:
119
+ if source != "out" or target != "out":
120
+ raise nx.NetworkXError(
121
+ f"source and target arguments are only supported for directed graphs"
122
+ )
123
+ source_degree = target_degree = G.degree
124
+
125
+ # precompute target degrees -- should *not* be weighted degree
126
+ t_deg = dict(target_degree())
127
+
128
+ # Set up both predecessor and successor neighbor dicts leaving empty if not needed
129
+ G_P = G_S = {n: {} for n in G}
130
+ if G.is_directed():
131
+ # "in" or "in+out" cases: G_P contains predecessors
132
+ if "in" in source:
133
+ G_P = G.pred
134
+ # "out" or "in+out" cases: G_S contains successors
135
+ if "out" in source:
136
+ G_S = G.succ
137
+ else:
138
+ # undirected leave G_P empty but G_S is the adjacency
139
+ G_S = G.adj
140
+
141
+ # Main loop: Compute average degree of neighbors
142
+ avg = {}
143
+ for n, deg in source_degree(nodes, weight=weight):
144
+ # handle degree zero average
145
+ if deg == 0:
146
+ avg[n] = 0.0
147
+ continue
148
+
149
+ # we sum over both G_P and G_S, but one of the two is usually empty.
150
+ if weight is None:
151
+ avg[n] = (
152
+ sum(t_deg[nbr] for nbr in G_S[n]) + sum(t_deg[nbr] for nbr in G_P[n])
153
+ ) / deg
154
+ else:
155
+ avg[n] = (
156
+ sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_S[n].items())
157
+ + sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_P[n].items())
158
+ ) / deg
159
+ return avg
runtime/Lib/site-packages/networkx/algorithms/assortativity/pairs.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators of x-y pairs of node data."""
2
+ __all__ = ["node_attribute_xy", "node_degree_xy"]
3
+
4
+
5
+ def node_attribute_xy(G, attribute, nodes=None):
6
+ """Returns iterator of node-attribute pairs for all edges in G.
7
+
8
+ Parameters
9
+ ----------
10
+ G: NetworkX graph
11
+
12
+ attribute: key
13
+ The node attribute key.
14
+
15
+ nodes: list or iterable (optional)
16
+ Use only edges that are incident to specified nodes.
17
+ The default is all nodes.
18
+
19
+ Returns
20
+ -------
21
+ (x, y): 2-tuple
22
+ Generates 2-tuple of (attribute, attribute) values.
23
+
24
+ Examples
25
+ --------
26
+ >>> G = nx.DiGraph()
27
+ >>> G.add_node(1, color="red")
28
+ >>> G.add_node(2, color="blue")
29
+ >>> G.add_edge(1, 2)
30
+ >>> list(nx.node_attribute_xy(G, "color"))
31
+ [('red', 'blue')]
32
+
33
+ Notes
34
+ -----
35
+ For undirected graphs each edge is produced twice, once for each edge
36
+ representation (u, v) and (v, u), with the exception of self-loop edges
37
+ which only appear once.
38
+ """
39
+ if nodes is None:
40
+ nodes = set(G)
41
+ else:
42
+ nodes = set(nodes)
43
+ Gnodes = G.nodes
44
+ for u, nbrsdict in G.adjacency():
45
+ if u not in nodes:
46
+ continue
47
+ uattr = Gnodes[u].get(attribute, None)
48
+ if G.is_multigraph():
49
+ for v, keys in nbrsdict.items():
50
+ vattr = Gnodes[v].get(attribute, None)
51
+ for _ in keys:
52
+ yield (uattr, vattr)
53
+ else:
54
+ for v in nbrsdict:
55
+ vattr = Gnodes[v].get(attribute, None)
56
+ yield (uattr, vattr)
57
+
58
+
59
+ def node_degree_xy(G, x="out", y="in", weight=None, nodes=None):
60
+ """Generate node degree-degree pairs for edges in G.
61
+
62
+ Parameters
63
+ ----------
64
+ G: NetworkX graph
65
+
66
+ x: string ('in','out')
67
+ The degree type for source node (directed graphs only).
68
+
69
+ y: string ('in','out')
70
+ The degree type for target node (directed graphs only).
71
+
72
+ weight: string or None, optional (default=None)
73
+ The edge attribute that holds the numerical value used
74
+ as a weight. If None, then each edge has weight 1.
75
+ The degree is the sum of the edge weights adjacent to the node.
76
+
77
+ nodes: list or iterable (optional)
78
+ Use only edges that are adjacency to specified nodes.
79
+ The default is all nodes.
80
+
81
+ Returns
82
+ -------
83
+ (x, y): 2-tuple
84
+ Generates 2-tuple of (degree, degree) values.
85
+
86
+
87
+ Examples
88
+ --------
89
+ >>> G = nx.DiGraph()
90
+ >>> G.add_edge(1, 2)
91
+ >>> list(nx.node_degree_xy(G, x="out", y="in"))
92
+ [(1, 1)]
93
+ >>> list(nx.node_degree_xy(G, x="in", y="out"))
94
+ [(0, 0)]
95
+
96
+ Notes
97
+ -----
98
+ For undirected graphs each edge is produced twice, once for each edge
99
+ representation (u, v) and (v, u), with the exception of self-loop edges
100
+ which only appear once.
101
+ """
102
+ nodes = set(G) if nodes is None else set(nodes)
103
+ if G.is_directed():
104
+ direction = {"out": G.out_degree, "in": G.in_degree}
105
+ xdeg = direction[x]
106
+ ydeg = direction[y]
107
+ else:
108
+ xdeg = ydeg = G.degree
109
+
110
+ for u, degu in xdeg(nodes, weight=weight):
111
+ # use G.edges to treat multigraphs correctly
112
+ neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes)
113
+ for _, degv in ydeg(neighbors, weight=weight):
114
+ yield degu, degv
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/__init__.py ADDED
File without changes
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/base_test.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+
4
+ class BaseTestAttributeMixing:
5
+ @classmethod
6
+ def setup_class(cls):
7
+ G = nx.Graph()
8
+ G.add_nodes_from([0, 1], fish="one")
9
+ G.add_nodes_from([2, 3], fish="two")
10
+ G.add_nodes_from([4], fish="red")
11
+ G.add_nodes_from([5], fish="blue")
12
+ G.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
13
+ cls.G = G
14
+
15
+ D = nx.DiGraph()
16
+ D.add_nodes_from([0, 1], fish="one")
17
+ D.add_nodes_from([2, 3], fish="two")
18
+ D.add_nodes_from([4], fish="red")
19
+ D.add_nodes_from([5], fish="blue")
20
+ D.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
21
+ cls.D = D
22
+
23
+ M = nx.MultiGraph()
24
+ M.add_nodes_from([0, 1], fish="one")
25
+ M.add_nodes_from([2, 3], fish="two")
26
+ M.add_nodes_from([4], fish="red")
27
+ M.add_nodes_from([5], fish="blue")
28
+ M.add_edges_from([(0, 1), (0, 1), (2, 3)])
29
+ cls.M = M
30
+
31
+ S = nx.Graph()
32
+ S.add_nodes_from([0, 1], fish="one")
33
+ S.add_nodes_from([2, 3], fish="two")
34
+ S.add_nodes_from([4], fish="red")
35
+ S.add_nodes_from([5], fish="blue")
36
+ S.add_edge(0, 0)
37
+ S.add_edge(2, 2)
38
+ cls.S = S
39
+
40
+
41
+ class BaseTestDegreeMixing:
42
+ @classmethod
43
+ def setup_class(cls):
44
+ cls.P4 = nx.path_graph(4)
45
+ cls.D = nx.DiGraph()
46
+ cls.D.add_edges_from([(0, 2), (0, 3), (1, 3), (2, 3)])
47
+ cls.D2 = nx.DiGraph()
48
+ cls.D2.add_edges_from([(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)])
49
+ cls.M = nx.MultiGraph()
50
+ nx.add_path(cls.M, range(4))
51
+ cls.M.add_edge(0, 1)
52
+ cls.S = nx.Graph()
53
+ cls.S.add_edges_from([(0, 0), (1, 1)])
54
+ cls.W = nx.Graph()
55
+ cls.W.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
56
+ cls.W.add_edge(0, 2, weight=1)
57
+ S1 = nx.star_graph(4)
58
+ S2 = nx.star_graph(4)
59
+ cls.DS = nx.disjoint_union(S1, S2)
60
+ cls.DS.add_edge(4, 5)
61
+
62
+
63
+ class BaseTestNumericMixing:
64
+ @classmethod
65
+ def setup_class(cls):
66
+ N = nx.Graph()
67
+ N.add_nodes_from([0, 1], margin=-2)
68
+ N.add_nodes_from([2, 3], margin=-2)
69
+ N.add_nodes_from([4], margin=-3)
70
+ N.add_nodes_from([5], margin=-4)
71
+ N.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
72
+ cls.N = N
73
+
74
+ F = nx.Graph()
75
+ F.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
76
+ F.add_edge(0, 2, weight=1)
77
+ nx.set_node_attributes(F, dict(F.degree(weight="weight")), "margin")
78
+ cls.F = F
79
+
80
+ M = nx.Graph()
81
+ M.add_nodes_from([1, 2], margin=-1)
82
+ M.add_nodes_from([3], margin=1)
83
+ M.add_nodes_from([4], margin=2)
84
+ M.add_edges_from([(3, 4), (1, 2), (1, 3)])
85
+ cls.M = M
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import permutations
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestNeighborConnectivity:
9
+ def test_degree_p4(self):
10
+ G = nx.path_graph(4)
11
+ answer = {1: 2.0, 2: 1.5}
12
+ nd = nx.average_degree_connectivity(G)
13
+ assert nd == answer
14
+
15
+ D = G.to_directed()
16
+ answer = {2: 2.0, 4: 1.5}
17
+ nd = nx.average_degree_connectivity(D)
18
+ assert nd == answer
19
+
20
+ answer = {1: 2.0, 2: 1.5}
21
+ D = G.to_directed()
22
+ nd = nx.average_degree_connectivity(D, source="in", target="in")
23
+ assert nd == answer
24
+
25
+ D = G.to_directed()
26
+ nd = nx.average_degree_connectivity(D, source="in", target="in")
27
+ assert nd == answer
28
+
29
+ def test_degree_p4_weighted(self):
30
+ G = nx.path_graph(4)
31
+ G[1][2]["weight"] = 4
32
+ answer = {1: 2.0, 2: 1.8}
33
+ nd = nx.average_degree_connectivity(G, weight="weight")
34
+ assert nd == answer
35
+ answer = {1: 2.0, 2: 1.5}
36
+ nd = nx.average_degree_connectivity(G)
37
+ assert nd == answer
38
+
39
+ D = G.to_directed()
40
+ answer = {2: 2.0, 4: 1.8}
41
+ nd = nx.average_degree_connectivity(D, weight="weight")
42
+ assert nd == answer
43
+
44
+ answer = {1: 2.0, 2: 1.8}
45
+ D = G.to_directed()
46
+ nd = nx.average_degree_connectivity(
47
+ D, weight="weight", source="in", target="in"
48
+ )
49
+ assert nd == answer
50
+
51
+ D = G.to_directed()
52
+ nd = nx.average_degree_connectivity(
53
+ D, source="in", target="out", weight="weight"
54
+ )
55
+ assert nd == answer
56
+
57
+ def test_weight_keyword(self):
58
+ G = nx.path_graph(4)
59
+ G[1][2]["other"] = 4
60
+ answer = {1: 2.0, 2: 1.8}
61
+ nd = nx.average_degree_connectivity(G, weight="other")
62
+ assert nd == answer
63
+ answer = {1: 2.0, 2: 1.5}
64
+ nd = nx.average_degree_connectivity(G, weight=None)
65
+ assert nd == answer
66
+
67
+ D = G.to_directed()
68
+ answer = {2: 2.0, 4: 1.8}
69
+ nd = nx.average_degree_connectivity(D, weight="other")
70
+ assert nd == answer
71
+
72
+ answer = {1: 2.0, 2: 1.8}
73
+ D = G.to_directed()
74
+ nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in")
75
+ assert nd == answer
76
+
77
+ D = G.to_directed()
78
+ nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in")
79
+ assert nd == answer
80
+
81
+ def test_degree_barrat(self):
82
+ G = nx.star_graph(5)
83
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
84
+ G[0][5]["weight"] = 5
85
+ nd = nx.average_degree_connectivity(G)[5]
86
+ assert nd == 1.8
87
+ nd = nx.average_degree_connectivity(G, weight="weight")[5]
88
+ assert nd == pytest.approx(3.222222, abs=1e-5)
89
+ nd = nx.k_nearest_neighbors(G, weight="weight")[5]
90
+ assert nd == pytest.approx(3.222222, abs=1e-5)
91
+
92
+ def test_zero_deg(self):
93
+ G = nx.DiGraph()
94
+ G.add_edge(1, 2)
95
+ G.add_edge(1, 3)
96
+ G.add_edge(1, 4)
97
+ c = nx.average_degree_connectivity(G)
98
+ assert c == {1: 0, 3: 1}
99
+ c = nx.average_degree_connectivity(G, source="in", target="in")
100
+ assert c == {0: 0, 1: 0}
101
+ c = nx.average_degree_connectivity(G, source="in", target="out")
102
+ assert c == {0: 0, 1: 3}
103
+ c = nx.average_degree_connectivity(G, source="in", target="in+out")
104
+ assert c == {0: 0, 1: 3}
105
+ c = nx.average_degree_connectivity(G, source="out", target="out")
106
+ assert c == {0: 0, 3: 0}
107
+ c = nx.average_degree_connectivity(G, source="out", target="in")
108
+ assert c == {0: 0, 3: 1}
109
+ c = nx.average_degree_connectivity(G, source="out", target="in+out")
110
+ assert c == {0: 0, 3: 1}
111
+
112
+ def test_in_out_weight(self):
113
+ G = nx.DiGraph()
114
+ G.add_edge(1, 2, weight=1)
115
+ G.add_edge(1, 3, weight=1)
116
+ G.add_edge(3, 1, weight=1)
117
+ for s, t in permutations(["in", "out", "in+out"], 2):
118
+ c = nx.average_degree_connectivity(G, source=s, target=t)
119
+ cw = nx.average_degree_connectivity(G, source=s, target=t, weight="weight")
120
+ assert c == cw
121
+
122
+ def test_invalid_source(self):
123
+ with pytest.raises(nx.NetworkXError):
124
+ G = nx.DiGraph()
125
+ nx.average_degree_connectivity(G, source="bogus")
126
+
127
+ def test_invalid_target(self):
128
+ with pytest.raises(nx.NetworkXError):
129
+ G = nx.DiGraph()
130
+ nx.average_degree_connectivity(G, target="bogus")
131
+
132
+ def test_invalid_undirected_graph(self):
133
+ G = nx.Graph()
134
+ with pytest.raises(nx.NetworkXError):
135
+ nx.average_degree_connectivity(G, target="bogus")
136
+ with pytest.raises(nx.NetworkXError):
137
+ nx.average_degree_connectivity(G, source="bogus")
138
+
139
+ def test_single_node(self):
140
+ # TODO Is this really the intended behavior for providing a
141
+ # single node as the argument `nodes`? Shouldn't the function
142
+ # just return the connectivity value itself?
143
+ G = nx.trivial_graph()
144
+ conn = nx.average_degree_connectivity(G, nodes=0)
145
+ assert conn == {0: 0}
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_correlation.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+ pytest.importorskip("scipy")
5
+
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.assortativity.correlation import attribute_ac
9
+
10
+ from .base_test import (
11
+ BaseTestAttributeMixing,
12
+ BaseTestDegreeMixing,
13
+ BaseTestNumericMixing,
14
+ )
15
+
16
+
17
+ class TestDegreeMixingCorrelation(BaseTestDegreeMixing):
18
+ def test_degree_assortativity_undirected(self):
19
+ r = nx.degree_assortativity_coefficient(self.P4)
20
+ np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
21
+
22
+ def test_degree_assortativity_directed(self):
23
+ r = nx.degree_assortativity_coefficient(self.D)
24
+ np.testing.assert_almost_equal(r, -0.57735, decimal=4)
25
+
26
+ def test_degree_assortativity_directed2(self):
27
+ """Test degree assortativity for a directed graph where the set of
28
+ in/out degree does not equal the total degree."""
29
+ r = nx.degree_assortativity_coefficient(self.D2)
30
+ np.testing.assert_almost_equal(r, 0.14852, decimal=4)
31
+
32
+ def test_degree_assortativity_multigraph(self):
33
+ r = nx.degree_assortativity_coefficient(self.M)
34
+ np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
35
+
36
+ def test_degree_pearson_assortativity_undirected(self):
37
+ r = nx.degree_pearson_correlation_coefficient(self.P4)
38
+ np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
39
+
40
+ def test_degree_pearson_assortativity_directed(self):
41
+ r = nx.degree_pearson_correlation_coefficient(self.D)
42
+ np.testing.assert_almost_equal(r, -0.57735, decimal=4)
43
+
44
+ def test_degree_pearson_assortativity_directed2(self):
45
+ """Test degree assortativity with Pearson for a directed graph where
46
+ the set of in/out degree does not equal the total degree."""
47
+ r = nx.degree_pearson_correlation_coefficient(self.D2)
48
+ np.testing.assert_almost_equal(r, 0.14852, decimal=4)
49
+
50
+ def test_degree_pearson_assortativity_multigraph(self):
51
+ r = nx.degree_pearson_correlation_coefficient(self.M)
52
+ np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
53
+
54
+ def test_degree_assortativity_weighted(self):
55
+ r = nx.degree_assortativity_coefficient(self.W, weight="weight")
56
+ np.testing.assert_almost_equal(r, -0.1429, decimal=4)
57
+
58
+ def test_degree_assortativity_double_star(self):
59
+ r = nx.degree_assortativity_coefficient(self.DS)
60
+ np.testing.assert_almost_equal(r, -0.9339, decimal=4)
61
+
62
+
63
+ class TestAttributeMixingCorrelation(BaseTestAttributeMixing):
64
+ def test_attribute_assortativity_undirected(self):
65
+ r = nx.attribute_assortativity_coefficient(self.G, "fish")
66
+ assert r == 6.0 / 22.0
67
+
68
+ def test_attribute_assortativity_directed(self):
69
+ r = nx.attribute_assortativity_coefficient(self.D, "fish")
70
+ assert r == 1.0 / 3.0
71
+
72
+ def test_attribute_assortativity_multigraph(self):
73
+ r = nx.attribute_assortativity_coefficient(self.M, "fish")
74
+ assert r == 1.0
75
+
76
+ def test_attribute_assortativity_coefficient(self):
77
+ # from "Mixing patterns in networks"
78
+ # fmt: off
79
+ a = np.array([[0.258, 0.016, 0.035, 0.013],
80
+ [0.012, 0.157, 0.058, 0.019],
81
+ [0.013, 0.023, 0.306, 0.035],
82
+ [0.005, 0.007, 0.024, 0.016]])
83
+ # fmt: on
84
+ r = attribute_ac(a)
85
+ np.testing.assert_almost_equal(r, 0.623, decimal=3)
86
+
87
+ def test_attribute_assortativity_coefficient2(self):
88
+ # fmt: off
89
+ a = np.array([[0.18, 0.02, 0.01, 0.03],
90
+ [0.02, 0.20, 0.03, 0.02],
91
+ [0.01, 0.03, 0.16, 0.01],
92
+ [0.03, 0.02, 0.01, 0.22]])
93
+ # fmt: on
94
+ r = attribute_ac(a)
95
+ np.testing.assert_almost_equal(r, 0.68, decimal=2)
96
+
97
+ def test_attribute_assortativity(self):
98
+ a = np.array([[50, 50, 0], [50, 50, 0], [0, 0, 2]])
99
+ r = attribute_ac(a)
100
+ np.testing.assert_almost_equal(r, 0.029, decimal=3)
101
+
102
+
103
+ class TestNumericMixingCorrelation(BaseTestNumericMixing):
104
+ def test_numeric_assortativity_negative(self):
105
+ r = nx.numeric_assortativity_coefficient(self.N, "margin")
106
+ np.testing.assert_almost_equal(r, -0.2903, decimal=4)
107
+
108
+ def test_numeric_assortativity_float(self):
109
+ r = nx.numeric_assortativity_coefficient(self.F, "margin")
110
+ np.testing.assert_almost_equal(r, -0.1429, decimal=4)
111
+
112
+ def test_numeric_assortativity_mixed(self):
113
+ r = nx.numeric_assortativity_coefficient(self.M, "margin")
114
+ np.testing.assert_almost_equal(r, 0.4340, decimal=4)
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+
6
+ import networkx as nx
7
+
8
+ from .base_test import (
9
+ BaseTestAttributeMixing,
10
+ BaseTestDegreeMixing,
11
+ BaseTestNumericMixing,
12
+ )
13
+
14
+
15
+ class TestDegreeMixingDict(BaseTestDegreeMixing):
16
+ def test_degree_mixing_dict_undirected(self):
17
+ d = nx.degree_mixing_dict(self.P4)
18
+ d_result = {1: {2: 2}, 2: {1: 2, 2: 2}}
19
+ assert d == d_result
20
+
21
+ def test_degree_mixing_dict_undirected_normalized(self):
22
+ d = nx.degree_mixing_dict(self.P4, normalized=True)
23
+ d_result = {1: {2: 1.0 / 3}, 2: {1: 1.0 / 3, 2: 1.0 / 3}}
24
+ assert d == d_result
25
+
26
+ def test_degree_mixing_dict_directed(self):
27
+ d = nx.degree_mixing_dict(self.D)
28
+ print(d)
29
+ d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}}
30
+ assert d == d_result
31
+
32
+ def test_degree_mixing_dict_multigraph(self):
33
+ d = nx.degree_mixing_dict(self.M)
34
+ d_result = {1: {2: 1}, 2: {1: 1, 3: 3}, 3: {2: 3}}
35
+ assert d == d_result
36
+
37
+ def test_degree_mixing_dict_weighted(self):
38
+ d = nx.degree_mixing_dict(self.W, weight="weight")
39
+ d_result = {0.5: {1.5: 1}, 1.5: {1.5: 6, 0.5: 1}}
40
+ assert d == d_result
41
+
42
+
43
+ class TestDegreeMixingMatrix(BaseTestDegreeMixing):
44
+ def test_degree_mixing_matrix_undirected(self):
45
+ # fmt: off
46
+ a_result = np.array([[0, 2],
47
+ [2, 2]]
48
+ )
49
+ # fmt: on
50
+ a = nx.degree_mixing_matrix(self.P4, normalized=False)
51
+ np.testing.assert_equal(a, a_result)
52
+ a = nx.degree_mixing_matrix(self.P4)
53
+ np.testing.assert_equal(a, a_result / a_result.sum())
54
+
55
+ def test_degree_mixing_matrix_directed(self):
56
+ # fmt: off
57
+ a_result = np.array([[0, 0, 2],
58
+ [1, 0, 1],
59
+ [0, 0, 0]]
60
+ )
61
+ # fmt: on
62
+ a = nx.degree_mixing_matrix(self.D, normalized=False)
63
+ np.testing.assert_equal(a, a_result)
64
+ a = nx.degree_mixing_matrix(self.D)
65
+ np.testing.assert_equal(a, a_result / a_result.sum())
66
+
67
+ def test_degree_mixing_matrix_multigraph(self):
68
+ # fmt: off
69
+ a_result = np.array([[0, 1, 0],
70
+ [1, 0, 3],
71
+ [0, 3, 0]]
72
+ )
73
+ # fmt: on
74
+ a = nx.degree_mixing_matrix(self.M, normalized=False)
75
+ np.testing.assert_equal(a, a_result)
76
+ a = nx.degree_mixing_matrix(self.M)
77
+ np.testing.assert_equal(a, a_result / a_result.sum())
78
+
79
+ def test_degree_mixing_matrix_selfloop(self):
80
+ # fmt: off
81
+ a_result = np.array([[2]])
82
+ # fmt: on
83
+ a = nx.degree_mixing_matrix(self.S, normalized=False)
84
+ np.testing.assert_equal(a, a_result)
85
+ a = nx.degree_mixing_matrix(self.S)
86
+ np.testing.assert_equal(a, a_result / a_result.sum())
87
+
88
+ def test_degree_mixing_matrix_weighted(self):
89
+ a_result = np.array([[0.0, 1.0], [1.0, 6.0]])
90
+ a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False)
91
+ np.testing.assert_equal(a, a_result)
92
+ a = nx.degree_mixing_matrix(self.W, weight="weight")
93
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
94
+
95
+ def test_degree_mixing_matrix_mapping(self):
96
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
97
+ mapping = {0.5: 1, 1.5: 0}
98
+ a = nx.degree_mixing_matrix(
99
+ self.W, weight="weight", normalized=False, mapping=mapping
100
+ )
101
+ np.testing.assert_equal(a, a_result)
102
+
103
+
104
+ class TestAttributeMixingDict(BaseTestAttributeMixing):
105
+ def test_attribute_mixing_dict_undirected(self):
106
+ d = nx.attribute_mixing_dict(self.G, "fish")
107
+ d_result = {
108
+ "one": {"one": 2, "red": 1},
109
+ "two": {"two": 2, "blue": 1},
110
+ "red": {"one": 1},
111
+ "blue": {"two": 1},
112
+ }
113
+ assert d == d_result
114
+
115
+ def test_attribute_mixing_dict_directed(self):
116
+ d = nx.attribute_mixing_dict(self.D, "fish")
117
+ d_result = {
118
+ "one": {"one": 1, "red": 1},
119
+ "two": {"two": 1, "blue": 1},
120
+ "red": {},
121
+ "blue": {},
122
+ }
123
+ assert d == d_result
124
+
125
+ def test_attribute_mixing_dict_multigraph(self):
126
+ d = nx.attribute_mixing_dict(self.M, "fish")
127
+ d_result = {"one": {"one": 4}, "two": {"two": 2}}
128
+ assert d == d_result
129
+
130
+
131
+ class TestAttributeMixingMatrix(BaseTestAttributeMixing):
132
+ def test_attribute_mixing_matrix_undirected(self):
133
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
134
+ a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])
135
+ a = nx.attribute_mixing_matrix(
136
+ self.G, "fish", mapping=mapping, normalized=False
137
+ )
138
+ np.testing.assert_equal(a, a_result)
139
+ a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping)
140
+ np.testing.assert_equal(a, a_result / a_result.sum())
141
+
142
+ def test_attribute_mixing_matrix_directed(self):
143
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
144
+ a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
145
+ a = nx.attribute_mixing_matrix(
146
+ self.D, "fish", mapping=mapping, normalized=False
147
+ )
148
+ np.testing.assert_equal(a, a_result)
149
+ a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping)
150
+ np.testing.assert_equal(a, a_result / a_result.sum())
151
+
152
+ def test_attribute_mixing_matrix_multigraph(self):
153
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
154
+ a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
155
+ a = nx.attribute_mixing_matrix(
156
+ self.M, "fish", mapping=mapping, normalized=False
157
+ )
158
+ np.testing.assert_equal(a, a_result)
159
+ a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping)
160
+ np.testing.assert_equal(a, a_result / a_result.sum())
161
+
162
+
163
+ class TestNumericMixingMatrix(BaseTestNumericMixing):
164
+ def test_numeric_mixing_matrix_negative(self):
165
+ mapping = {-2: 0, -3: 1, -4: 2}
166
+ a_result = np.array([[4.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
167
+ a = nx.numeric_mixing_matrix(
168
+ self.N, "margin", mapping=mapping, normalized=False
169
+ )
170
+ np.testing.assert_equal(a, a_result)
171
+ a = nx.numeric_mixing_matrix(self.N, "margin", mapping=mapping)
172
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
173
+
174
+ def test_numeric_mixing_matrix_float(self):
175
+ mapping = {0.5: 1, 1.5: 0}
176
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
177
+ a = nx.numeric_mixing_matrix(
178
+ self.F, "margin", mapping=mapping, normalized=False
179
+ )
180
+ np.testing.assert_equal(a, a_result)
181
+ a = nx.numeric_mixing_matrix(self.F, "margin", mapping=mapping)
182
+ np.testing.assert_equal(a, a_result / a_result.sum())
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestAverageNeighbor:
7
+ def test_degree_p4(self):
8
+ G = nx.path_graph(4)
9
+ answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2}
10
+ nd = nx.average_neighbor_degree(G)
11
+ assert nd == answer
12
+
13
+ D = G.to_directed()
14
+ nd = nx.average_neighbor_degree(D)
15
+ assert nd == answer
16
+
17
+ D = nx.DiGraph(G.edges(data=True))
18
+ nd = nx.average_neighbor_degree(D)
19
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
20
+ nd = nx.average_neighbor_degree(D, "in", "out")
21
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
22
+ nd = nx.average_neighbor_degree(D, "out", "in")
23
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
24
+ nd = nx.average_neighbor_degree(D, "in", "in")
25
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
26
+
27
+ def test_degree_p4_weighted(self):
28
+ G = nx.path_graph(4)
29
+ G[1][2]["weight"] = 4
30
+ answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2}
31
+ nd = nx.average_neighbor_degree(G, weight="weight")
32
+ assert nd == answer
33
+
34
+ D = G.to_directed()
35
+ nd = nx.average_neighbor_degree(D, weight="weight")
36
+ assert nd == answer
37
+
38
+ D = nx.DiGraph(G.edges(data=True))
39
+ print(D.edges(data=True))
40
+ nd = nx.average_neighbor_degree(D, weight="weight")
41
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
42
+ nd = nx.average_neighbor_degree(D, "out", "out", weight="weight")
43
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
44
+ nd = nx.average_neighbor_degree(D, "in", "in", weight="weight")
45
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
46
+ nd = nx.average_neighbor_degree(D, "in", "out", weight="weight")
47
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
48
+ nd = nx.average_neighbor_degree(D, "out", "in", weight="weight")
49
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
50
+
51
+ D = G.to_directed()
52
+ nd = nx.average_neighbor_degree(D, weight="weight")
53
+ assert nd == answer
54
+ nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight")
55
+ assert nd == answer
56
+
57
+ D = G.to_directed()
58
+ nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight")
59
+ assert nd == answer
60
+
61
+ def test_degree_k4(self):
62
+ G = nx.complete_graph(4)
63
+ answer = {0: 3, 1: 3, 2: 3, 3: 3}
64
+ nd = nx.average_neighbor_degree(G)
65
+ assert nd == answer
66
+
67
+ D = G.to_directed()
68
+ nd = nx.average_neighbor_degree(D)
69
+ assert nd == answer
70
+
71
+ D = G.to_directed()
72
+ nd = nx.average_neighbor_degree(D)
73
+ assert nd == answer
74
+
75
+ D = G.to_directed()
76
+ nd = nx.average_neighbor_degree(D, source="in", target="in")
77
+ assert nd == answer
78
+
79
+ def test_degree_k4_nodes(self):
80
+ G = nx.complete_graph(4)
81
+ answer = {1: 3.0, 2: 3.0}
82
+ nd = nx.average_neighbor_degree(G, nodes=[1, 2])
83
+ assert nd == answer
84
+
85
+ def test_degree_barrat(self):
86
+ G = nx.star_graph(5)
87
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
88
+ G[0][5]["weight"] = 5
89
+ nd = nx.average_neighbor_degree(G)[5]
90
+ assert nd == 1.8
91
+ nd = nx.average_neighbor_degree(G, weight="weight")[5]
92
+ assert nd == pytest.approx(3.222222, abs=1e-5)
93
+
94
+ def test_error_invalid_source_target(self):
95
+ G = nx.path_graph(4)
96
+ with pytest.raises(nx.NetworkXError):
97
+ nx.average_neighbor_degree(G, "error")
98
+ with pytest.raises(nx.NetworkXError):
99
+ nx.average_neighbor_degree(G, "in", "error")
100
+ G = G.to_directed()
101
+ with pytest.raises(nx.NetworkXError):
102
+ nx.average_neighbor_degree(G, "error")
103
+ with pytest.raises(nx.NetworkXError):
104
+ nx.average_neighbor_degree(G, "in", "error")
runtime/Lib/site-packages/networkx/algorithms/assortativity/tests/test_pairs.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
4
+
5
+
6
+ class TestAttributeMixingXY(BaseTestAttributeMixing):
7
+ def test_node_attribute_xy_undirected(self):
8
+ attrxy = sorted(nx.node_attribute_xy(self.G, "fish"))
9
+ attrxy_result = sorted(
10
+ [
11
+ ("one", "one"),
12
+ ("one", "one"),
13
+ ("two", "two"),
14
+ ("two", "two"),
15
+ ("one", "red"),
16
+ ("red", "one"),
17
+ ("blue", "two"),
18
+ ("two", "blue"),
19
+ ]
20
+ )
21
+ assert attrxy == attrxy_result
22
+
23
+ def test_node_attribute_xy_undirected_nodes(self):
24
+ attrxy = sorted(nx.node_attribute_xy(self.G, "fish", nodes=["one", "yellow"]))
25
+ attrxy_result = sorted([])
26
+ assert attrxy == attrxy_result
27
+
28
+ def test_node_attribute_xy_directed(self):
29
+ attrxy = sorted(nx.node_attribute_xy(self.D, "fish"))
30
+ attrxy_result = sorted(
31
+ [("one", "one"), ("two", "two"), ("one", "red"), ("two", "blue")]
32
+ )
33
+ assert attrxy == attrxy_result
34
+
35
+ def test_node_attribute_xy_multigraph(self):
36
+ attrxy = sorted(nx.node_attribute_xy(self.M, "fish"))
37
+ attrxy_result = [
38
+ ("one", "one"),
39
+ ("one", "one"),
40
+ ("one", "one"),
41
+ ("one", "one"),
42
+ ("two", "two"),
43
+ ("two", "two"),
44
+ ]
45
+ assert attrxy == attrxy_result
46
+
47
+ def test_node_attribute_xy_selfloop(self):
48
+ attrxy = sorted(nx.node_attribute_xy(self.S, "fish"))
49
+ attrxy_result = [("one", "one"), ("two", "two")]
50
+ assert attrxy == attrxy_result
51
+
52
+
53
+ class TestDegreeMixingXY(BaseTestDegreeMixing):
54
+ def test_node_degree_xy_undirected(self):
55
+ xy = sorted(nx.node_degree_xy(self.P4))
56
+ xy_result = sorted([(1, 2), (2, 1), (2, 2), (2, 2), (1, 2), (2, 1)])
57
+ assert xy == xy_result
58
+
59
+ def test_node_degree_xy_undirected_nodes(self):
60
+ xy = sorted(nx.node_degree_xy(self.P4, nodes=[0, 1, -1]))
61
+ xy_result = sorted([(1, 2), (2, 1)])
62
+ assert xy == xy_result
63
+
64
+ def test_node_degree_xy_directed(self):
65
+ xy = sorted(nx.node_degree_xy(self.D))
66
+ xy_result = sorted([(2, 1), (2, 3), (1, 3), (1, 3)])
67
+ assert xy == xy_result
68
+
69
+ def test_node_degree_xy_multigraph(self):
70
+ xy = sorted(nx.node_degree_xy(self.M))
71
+ xy_result = sorted(
72
+ [(2, 3), (2, 3), (3, 2), (3, 2), (2, 3), (3, 2), (1, 2), (2, 1)]
73
+ )
74
+ assert xy == xy_result
75
+
76
+ def test_node_degree_xy_selfloop(self):
77
+ xy = sorted(nx.node_degree_xy(self.S))
78
+ xy_result = sorted([(2, 2), (2, 2)])
79
+ assert xy == xy_result
80
+
81
+ def test_node_degree_xy_weighted(self):
82
+ G = nx.Graph()
83
+ G.add_edge(1, 2, weight=7)
84
+ G.add_edge(2, 3, weight=10)
85
+ xy = sorted(nx.node_degree_xy(G, weight="weight"))
86
+ xy_result = sorted([(7, 17), (17, 10), (17, 7), (10, 17)])
87
+ assert xy == xy_result