Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/distance_measures.py +150 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/kcomponents.py +369 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/ramsey.py +52 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/steinertree.py +220 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/traveling_salesman.py +1498 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/treewidth.py +252 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/divisive.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/louvain.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/modularity_max.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/__pycache__/hits_alg.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/__pycache__/pagerank_alg.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/hits_alg.py +337 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/pagerank_alg.py +499 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__pycache__/test_hits.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__pycache__/test_pagerank.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/test_hits.py +78 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/test_pagerank.py +217 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chains.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_core.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dominance.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_isolate.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_link_prediction.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_moral.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_regular.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_simple_paths.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_vitality.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_walks.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py +23 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py +154 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py +144 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py +81 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_chains.py +140 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py +129 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_clique.py +291 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_cluster.py +549 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py +80 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_core.py +266 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_covering.py +85 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py +172 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_d_separation.py +348 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_distance_regular.py +85 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py +46 -0
- parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_euler.py +314 -0
.gitattributes
CHANGED
|
@@ -169,3 +169,5 @@ parrot/lib/libgomp.so filter=lfs diff=lfs merge=lfs -text
|
|
| 169 |
parrot/lib/python3.10/site-packages/pyarrow/_compute.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 170 |
parrot/lib/libssl.a filter=lfs diff=lfs merge=lfs -text
|
| 171 |
parrot/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-3ecfe81c.so.1 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 169 |
parrot/lib/python3.10/site-packages/pyarrow/_compute.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 170 |
parrot/lib/libssl.a filter=lfs diff=lfs merge=lfs -text
|
| 171 |
parrot/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-3ecfe81c.so.1 filter=lfs diff=lfs merge=lfs -text
|
| 172 |
+
parrot/lib/python3.10/site-packages/pillow.libs/libxcb-b8a56d01.so.1.1.0 filter=lfs diff=lfs merge=lfs -text
|
| 173 |
+
parrot/lib/python3.10/site-packages/pillow.libs/liblzma-13fa198c.so.5.4.5 filter=lfs diff=lfs merge=lfs -text
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.34 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/distance_measures.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
@nx._dispatchable(name="approximate_diameter")
|
| 11 |
+
def diameter(G, seed=None):
|
| 12 |
+
"""Returns a lower bound on the diameter of the graph G.
|
| 13 |
+
|
| 14 |
+
The function computes a lower bound on the diameter (i.e., the maximum eccentricity)
|
| 15 |
+
of a directed or undirected graph G. The procedure used varies depending on the graph
|
| 16 |
+
being directed or not.
|
| 17 |
+
|
| 18 |
+
If G is an `undirected` graph, then the function uses the `2-sweep` algorithm [1]_.
|
| 19 |
+
The main idea is to pick the farthest node from a random node and return its eccentricity.
|
| 20 |
+
|
| 21 |
+
Otherwise, if G is a `directed` graph, the function uses the `2-dSweep` algorithm [2]_,
|
| 22 |
+
The procedure starts by selecting a random source node $s$ from which it performs a
|
| 23 |
+
forward and a backward BFS. Let $a_1$ and $a_2$ be the farthest nodes in the forward and
|
| 24 |
+
backward cases, respectively. Then, it computes the backward eccentricity of $a_1$ using
|
| 25 |
+
a backward BFS and the forward eccentricity of $a_2$ using a forward BFS.
|
| 26 |
+
Finally, it returns the best lower bound between the two.
|
| 27 |
+
|
| 28 |
+
In both cases, the time complexity is linear with respect to the size of G.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
G : NetworkX graph
|
| 33 |
+
|
| 34 |
+
seed : integer, random_state, or None (default)
|
| 35 |
+
Indicator of random number generation state.
|
| 36 |
+
See :ref:`Randomness<randomness>`.
|
| 37 |
+
|
| 38 |
+
Returns
|
| 39 |
+
-------
|
| 40 |
+
d : integer
|
| 41 |
+
Lower Bound on the Diameter of G
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
--------
|
| 45 |
+
>>> G = nx.path_graph(10) # undirected graph
|
| 46 |
+
>>> nx.diameter(G)
|
| 47 |
+
9
|
| 48 |
+
>>> G = nx.cycle_graph(3, create_using=nx.DiGraph) # directed graph
|
| 49 |
+
>>> nx.diameter(G)
|
| 50 |
+
2
|
| 51 |
+
|
| 52 |
+
Raises
|
| 53 |
+
------
|
| 54 |
+
NetworkXError
|
| 55 |
+
If the graph is empty or
|
| 56 |
+
If the graph is undirected and not connected or
|
| 57 |
+
If the graph is directed and not strongly connected.
|
| 58 |
+
|
| 59 |
+
See Also
|
| 60 |
+
--------
|
| 61 |
+
networkx.algorithms.distance_measures.diameter
|
| 62 |
+
|
| 63 |
+
References
|
| 64 |
+
----------
|
| 65 |
+
.. [1] Magnien, Clémence, Matthieu Latapy, and Michel Habib.
|
| 66 |
+
*Fast computation of empirically tight bounds for the diameter of massive graphs.*
|
| 67 |
+
Journal of Experimental Algorithmics (JEA), 2009.
|
| 68 |
+
https://arxiv.org/pdf/0904.2728.pdf
|
| 69 |
+
.. [2] Crescenzi, Pierluigi, Roberto Grossi, Leonardo Lanzi, and Andrea Marino.
|
| 70 |
+
*On computing the diameter of real-world directed (weighted) graphs.*
|
| 71 |
+
International Symposium on Experimental Algorithms. Springer, Berlin, Heidelberg, 2012.
|
| 72 |
+
https://courses.cs.ut.ee/MTAT.03.238/2014_fall/uploads/Main/diameter.pdf
|
| 73 |
+
"""
|
| 74 |
+
# if G is empty
|
| 75 |
+
if not G:
|
| 76 |
+
raise nx.NetworkXError("Expected non-empty NetworkX graph!")
|
| 77 |
+
# if there's only a node
|
| 78 |
+
if G.number_of_nodes() == 1:
|
| 79 |
+
return 0
|
| 80 |
+
# if G is directed
|
| 81 |
+
if G.is_directed():
|
| 82 |
+
return _two_sweep_directed(G, seed)
|
| 83 |
+
# else if G is undirected
|
| 84 |
+
return _two_sweep_undirected(G, seed)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _two_sweep_undirected(G, seed):
|
| 88 |
+
"""Helper function for finding a lower bound on the diameter
|
| 89 |
+
for undirected Graphs.
|
| 90 |
+
|
| 91 |
+
The idea is to pick the farthest node from a random node
|
| 92 |
+
and return its eccentricity.
|
| 93 |
+
|
| 94 |
+
``G`` is a NetworkX undirected graph.
|
| 95 |
+
|
| 96 |
+
.. note::
|
| 97 |
+
|
| 98 |
+
``seed`` is a random.Random or numpy.random.RandomState instance
|
| 99 |
+
"""
|
| 100 |
+
# select a random source node
|
| 101 |
+
source = seed.choice(list(G))
|
| 102 |
+
# get the distances to the other nodes
|
| 103 |
+
distances = nx.shortest_path_length(G, source)
|
| 104 |
+
# if some nodes have not been visited, then the graph is not connected
|
| 105 |
+
if len(distances) != len(G):
|
| 106 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 107 |
+
# take a node that is (one of) the farthest nodes from the source
|
| 108 |
+
*_, node = distances
|
| 109 |
+
# return the eccentricity of the node
|
| 110 |
+
return nx.eccentricity(G, node)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _two_sweep_directed(G, seed):
|
| 114 |
+
"""Helper function for finding a lower bound on the diameter
|
| 115 |
+
for directed Graphs.
|
| 116 |
+
|
| 117 |
+
It implements 2-dSweep, the directed version of the 2-sweep algorithm.
|
| 118 |
+
The algorithm follows the following steps.
|
| 119 |
+
1. Select a source node $s$ at random.
|
| 120 |
+
2. Perform a forward BFS from $s$ to select a node $a_1$ at the maximum
|
| 121 |
+
distance from the source, and compute $LB_1$, the backward eccentricity of $a_1$.
|
| 122 |
+
3. Perform a backward BFS from $s$ to select a node $a_2$ at the maximum
|
| 123 |
+
distance from the source, and compute $LB_2$, the forward eccentricity of $a_2$.
|
| 124 |
+
4. Return the maximum between $LB_1$ and $LB_2$.
|
| 125 |
+
|
| 126 |
+
``G`` is a NetworkX directed graph.
|
| 127 |
+
|
| 128 |
+
.. note::
|
| 129 |
+
|
| 130 |
+
``seed`` is a random.Random or numpy.random.RandomState instance
|
| 131 |
+
"""
|
| 132 |
+
# get a new digraph G' with the edges reversed in the opposite direction
|
| 133 |
+
G_reversed = G.reverse()
|
| 134 |
+
# select a random source node
|
| 135 |
+
source = seed.choice(list(G))
|
| 136 |
+
# compute forward distances from source
|
| 137 |
+
forward_distances = nx.shortest_path_length(G, source)
|
| 138 |
+
# compute backward distances from source
|
| 139 |
+
backward_distances = nx.shortest_path_length(G_reversed, source)
|
| 140 |
+
# if either the source can't reach every node or not every node
|
| 141 |
+
# can reach the source, then the graph is not strongly connected
|
| 142 |
+
n = len(G)
|
| 143 |
+
if len(forward_distances) != n or len(backward_distances) != n:
|
| 144 |
+
raise nx.NetworkXError("DiGraph not strongly connected.")
|
| 145 |
+
# take a node a_1 at the maximum distance from the source in G
|
| 146 |
+
*_, a_1 = forward_distances
|
| 147 |
+
# take a node a_2 at the maximum distance from the source in G_reversed
|
| 148 |
+
*_, a_2 = backward_distances
|
| 149 |
+
# return the max between the backward eccentricity of a_1 and the forward eccentricity of a_2
|
| 150 |
+
return max(nx.eccentricity(G_reversed, a_1), nx.eccentricity(G, a_2))
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/kcomponents.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
@nx._dispatchable(name="approximate_k_components")
|
| 18 |
+
def k_components(G, min_density=0.95):
|
| 19 |
+
r"""Returns the approximate k-component structure of a graph G.
|
| 20 |
+
|
| 21 |
+
A `k`-component is a maximal subgraph of a graph G that has, at least,
|
| 22 |
+
node connectivity `k`: we need to remove at least `k` nodes to break it
|
| 23 |
+
into more components. `k`-components have an inherent hierarchical
|
| 24 |
+
structure because they are nested in terms of connectivity: a connected
|
| 25 |
+
graph can contain several 2-components, each of which can contain
|
| 26 |
+
one or more 3-components, and so forth.
|
| 27 |
+
|
| 28 |
+
This implementation is based on the fast heuristics to approximate
|
| 29 |
+
the `k`-component structure of a graph [1]_. Which, in turn, it is based on
|
| 30 |
+
a fast approximation algorithm for finding good lower bounds of the number
|
| 31 |
+
of node independent paths between two nodes [2]_.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
G : NetworkX graph
|
| 36 |
+
Undirected graph
|
| 37 |
+
|
| 38 |
+
min_density : Float
|
| 39 |
+
Density relaxation threshold. Default value 0.95
|
| 40 |
+
|
| 41 |
+
Returns
|
| 42 |
+
-------
|
| 43 |
+
k_components : dict
|
| 44 |
+
Dictionary with connectivity level `k` as key and a list of
|
| 45 |
+
sets of nodes that form a k-component of level `k` as values.
|
| 46 |
+
|
| 47 |
+
Raises
|
| 48 |
+
------
|
| 49 |
+
NetworkXNotImplemented
|
| 50 |
+
If G is directed.
|
| 51 |
+
|
| 52 |
+
Examples
|
| 53 |
+
--------
|
| 54 |
+
>>> # Petersen graph has 10 nodes and it is triconnected, thus all
|
| 55 |
+
>>> # nodes are in a single component on all three connectivity levels
|
| 56 |
+
>>> from networkx.algorithms import approximation as apxa
|
| 57 |
+
>>> G = nx.petersen_graph()
|
| 58 |
+
>>> k_components = apxa.k_components(G)
|
| 59 |
+
|
| 60 |
+
Notes
|
| 61 |
+
-----
|
| 62 |
+
The logic of the approximation algorithm for computing the `k`-component
|
| 63 |
+
structure [1]_ is based on repeatedly applying simple and fast algorithms
|
| 64 |
+
for `k`-cores and biconnected components in order to narrow down the
|
| 65 |
+
number of pairs of nodes over which we have to compute White and Newman's
|
| 66 |
+
approximation algorithm for finding node independent paths [2]_. More
|
| 67 |
+
formally, this algorithm is based on Whitney's theorem, which states
|
| 68 |
+
an inclusion relation among node connectivity, edge connectivity, and
|
| 69 |
+
minimum degree for any graph G. This theorem implies that every
|
| 70 |
+
`k`-component is nested inside a `k`-edge-component, which in turn,
|
| 71 |
+
is contained in a `k`-core. Thus, this algorithm computes node independent
|
| 72 |
+
paths among pairs of nodes in each biconnected part of each `k`-core,
|
| 73 |
+
and repeats this procedure for each `k` from 3 to the maximal core number
|
| 74 |
+
of a node in the input graph.
|
| 75 |
+
|
| 76 |
+
Because, in practice, many nodes of the core of level `k` inside a
|
| 77 |
+
bicomponent actually are part of a component of level k, the auxiliary
|
| 78 |
+
graph needed for the algorithm is likely to be very dense. Thus, we use
|
| 79 |
+
a complement graph data structure (see `AntiGraph`) to save memory.
|
| 80 |
+
AntiGraph only stores information of the edges that are *not* present
|
| 81 |
+
in the actual auxiliary graph. When applying algorithms to this
|
| 82 |
+
complement graph data structure, it behaves as if it were the dense
|
| 83 |
+
version.
|
| 84 |
+
|
| 85 |
+
See also
|
| 86 |
+
--------
|
| 87 |
+
k_components
|
| 88 |
+
|
| 89 |
+
References
|
| 90 |
+
----------
|
| 91 |
+
.. [1] Torrents, J. and F. Ferraro (2015) Structural Cohesion:
|
| 92 |
+
Visualization and Heuristics for Fast Computation.
|
| 93 |
+
https://arxiv.org/pdf/1503.04476v1
|
| 94 |
+
|
| 95 |
+
.. [2] White, Douglas R., and Mark Newman (2001) A Fast Algorithm for
|
| 96 |
+
Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
|
| 97 |
+
https://www.santafe.edu/research/results/working-papers/fast-approximation-algorithms-for-finding-node-ind
|
| 98 |
+
|
| 99 |
+
.. [3] Moody, J. and D. White (2003). Social cohesion and embeddedness:
|
| 100 |
+
A hierarchical conception of social groups.
|
| 101 |
+
American Sociological Review 68(1), 103--28.
|
| 102 |
+
https://doi.org/10.2307/3088904
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
# Dictionary with connectivity level (k) as keys and a list of
|
| 106 |
+
# sets of nodes that form a k-component as values
|
| 107 |
+
k_components = defaultdict(list)
|
| 108 |
+
# make a few functions local for speed
|
| 109 |
+
node_connectivity = local_node_connectivity
|
| 110 |
+
k_core = nx.k_core
|
| 111 |
+
core_number = nx.core_number
|
| 112 |
+
biconnected_components = nx.biconnected_components
|
| 113 |
+
combinations = itertools.combinations
|
| 114 |
+
# Exact solution for k = {1,2}
|
| 115 |
+
# There is a linear time algorithm for triconnectivity, if we had an
|
| 116 |
+
# implementation available we could start from k = 4.
|
| 117 |
+
for component in nx.connected_components(G):
|
| 118 |
+
# isolated nodes have connectivity 0
|
| 119 |
+
comp = set(component)
|
| 120 |
+
if len(comp) > 1:
|
| 121 |
+
k_components[1].append(comp)
|
| 122 |
+
for bicomponent in nx.biconnected_components(G):
|
| 123 |
+
# avoid considering dyads as bicomponents
|
| 124 |
+
bicomp = set(bicomponent)
|
| 125 |
+
if len(bicomp) > 2:
|
| 126 |
+
k_components[2].append(bicomp)
|
| 127 |
+
# There is no k-component of k > maximum core number
|
| 128 |
+
# \kappa(G) <= \lambda(G) <= \delta(G)
|
| 129 |
+
g_cnumber = core_number(G)
|
| 130 |
+
max_core = max(g_cnumber.values())
|
| 131 |
+
for k in range(3, max_core + 1):
|
| 132 |
+
C = k_core(G, k, core_number=g_cnumber)
|
| 133 |
+
for nodes in biconnected_components(C):
|
| 134 |
+
# Build a subgraph SG induced by the nodes that are part of
|
| 135 |
+
# each biconnected component of the k-core subgraph C.
|
| 136 |
+
if len(nodes) < k:
|
| 137 |
+
continue
|
| 138 |
+
SG = G.subgraph(nodes)
|
| 139 |
+
# Build auxiliary graph
|
| 140 |
+
H = _AntiGraph()
|
| 141 |
+
H.add_nodes_from(SG.nodes())
|
| 142 |
+
for u, v in combinations(SG, 2):
|
| 143 |
+
K = node_connectivity(SG, u, v, cutoff=k)
|
| 144 |
+
if k > K:
|
| 145 |
+
H.add_edge(u, v)
|
| 146 |
+
for h_nodes in biconnected_components(H):
|
| 147 |
+
if len(h_nodes) <= k:
|
| 148 |
+
continue
|
| 149 |
+
SH = H.subgraph(h_nodes)
|
| 150 |
+
for Gc in _cliques_heuristic(SG, SH, k, min_density):
|
| 151 |
+
for k_nodes in biconnected_components(Gc):
|
| 152 |
+
Gk = nx.k_core(SG.subgraph(k_nodes), k)
|
| 153 |
+
if len(Gk) <= k:
|
| 154 |
+
continue
|
| 155 |
+
k_components[k].append(set(Gk))
|
| 156 |
+
return k_components
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _cliques_heuristic(G, H, k, min_density):
|
| 160 |
+
h_cnumber = nx.core_number(H)
|
| 161 |
+
for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)):
|
| 162 |
+
cands = {n for n, c in h_cnumber.items() if c == c_value}
|
| 163 |
+
# Skip checking for overlap for the highest core value
|
| 164 |
+
if i == 0:
|
| 165 |
+
overlap = False
|
| 166 |
+
else:
|
| 167 |
+
overlap = set.intersection(
|
| 168 |
+
*[{x for x in H[n] if x not in cands} for n in cands]
|
| 169 |
+
)
|
| 170 |
+
if overlap and len(overlap) < k:
|
| 171 |
+
SH = H.subgraph(cands | overlap)
|
| 172 |
+
else:
|
| 173 |
+
SH = H.subgraph(cands)
|
| 174 |
+
sh_cnumber = nx.core_number(SH)
|
| 175 |
+
SG = nx.k_core(G.subgraph(SH), k)
|
| 176 |
+
while not (_same(sh_cnumber) and nx.density(SH) >= min_density):
|
| 177 |
+
# This subgraph must be writable => .copy()
|
| 178 |
+
SH = H.subgraph(SG).copy()
|
| 179 |
+
if len(SH) <= k:
|
| 180 |
+
break
|
| 181 |
+
sh_cnumber = nx.core_number(SH)
|
| 182 |
+
sh_deg = dict(SH.degree())
|
| 183 |
+
min_deg = min(sh_deg.values())
|
| 184 |
+
SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg)
|
| 185 |
+
SG = nx.k_core(G.subgraph(SH), k)
|
| 186 |
+
else:
|
| 187 |
+
yield SG
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _same(measure, tol=0):
|
| 191 |
+
vals = set(measure.values())
|
| 192 |
+
if (max(vals) - min(vals)) <= tol:
|
| 193 |
+
return True
|
| 194 |
+
return False
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class _AntiGraph(nx.Graph):
|
| 198 |
+
"""
|
| 199 |
+
Class for complement graphs.
|
| 200 |
+
|
| 201 |
+
The main goal is to be able to work with big and dense graphs with
|
| 202 |
+
a low memory footprint.
|
| 203 |
+
|
| 204 |
+
In this class you add the edges that *do not exist* in the dense graph,
|
| 205 |
+
the report methods of the class return the neighbors, the edges and
|
| 206 |
+
the degree as if it was the dense graph. Thus it's possible to use
|
| 207 |
+
an instance of this class with some of NetworkX functions. In this
|
| 208 |
+
case we only use k-core, connected_components, and biconnected_components.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
all_edge_dict = {"weight": 1}
|
| 212 |
+
|
| 213 |
+
def single_edge_dict(self):
|
| 214 |
+
return self.all_edge_dict
|
| 215 |
+
|
| 216 |
+
edge_attr_dict_factory = single_edge_dict # type: ignore[assignment]
|
| 217 |
+
|
| 218 |
+
def __getitem__(self, n):
|
| 219 |
+
"""Returns a dict of neighbors of node n in the dense graph.
|
| 220 |
+
|
| 221 |
+
Parameters
|
| 222 |
+
----------
|
| 223 |
+
n : node
|
| 224 |
+
A node in the graph.
|
| 225 |
+
|
| 226 |
+
Returns
|
| 227 |
+
-------
|
| 228 |
+
adj_dict : dictionary
|
| 229 |
+
The adjacency dictionary for nodes connected to n.
|
| 230 |
+
|
| 231 |
+
"""
|
| 232 |
+
all_edge_dict = self.all_edge_dict
|
| 233 |
+
return {
|
| 234 |
+
node: all_edge_dict for node in set(self._adj) - set(self._adj[n]) - {n}
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
def neighbors(self, n):
|
| 238 |
+
"""Returns an iterator over all neighbors of node n in the
|
| 239 |
+
dense graph.
|
| 240 |
+
"""
|
| 241 |
+
try:
|
| 242 |
+
return iter(set(self._adj) - set(self._adj[n]) - {n})
|
| 243 |
+
except KeyError as err:
|
| 244 |
+
raise NetworkXError(f"The node {n} is not in the graph.") from err
|
| 245 |
+
|
| 246 |
+
class AntiAtlasView(Mapping):
|
| 247 |
+
"""An adjacency inner dict for AntiGraph"""
|
| 248 |
+
|
| 249 |
+
def __init__(self, graph, node):
|
| 250 |
+
self._graph = graph
|
| 251 |
+
self._atlas = graph._adj[node]
|
| 252 |
+
self._node = node
|
| 253 |
+
|
| 254 |
+
def __len__(self):
|
| 255 |
+
return len(self._graph) - len(self._atlas) - 1
|
| 256 |
+
|
| 257 |
+
def __iter__(self):
|
| 258 |
+
return (n for n in self._graph if n not in self._atlas and n != self._node)
|
| 259 |
+
|
| 260 |
+
def __getitem__(self, nbr):
|
| 261 |
+
nbrs = set(self._graph._adj) - set(self._atlas) - {self._node}
|
| 262 |
+
if nbr in nbrs:
|
| 263 |
+
return self._graph.all_edge_dict
|
| 264 |
+
raise KeyError(nbr)
|
| 265 |
+
|
| 266 |
+
class AntiAdjacencyView(AntiAtlasView):
|
| 267 |
+
"""An adjacency outer dict for AntiGraph"""
|
| 268 |
+
|
| 269 |
+
def __init__(self, graph):
|
| 270 |
+
self._graph = graph
|
| 271 |
+
self._atlas = graph._adj
|
| 272 |
+
|
| 273 |
+
def __len__(self):
|
| 274 |
+
return len(self._atlas)
|
| 275 |
+
|
| 276 |
+
def __iter__(self):
|
| 277 |
+
return iter(self._graph)
|
| 278 |
+
|
| 279 |
+
def __getitem__(self, node):
|
| 280 |
+
if node not in self._graph:
|
| 281 |
+
raise KeyError(node)
|
| 282 |
+
return self._graph.AntiAtlasView(self._graph, node)
|
| 283 |
+
|
| 284 |
+
@cached_property
|
| 285 |
+
def adj(self):
|
| 286 |
+
return self.AntiAdjacencyView(self)
|
| 287 |
+
|
| 288 |
+
def subgraph(self, nodes):
|
| 289 |
+
"""This subgraph method returns a full AntiGraph. Not a View"""
|
| 290 |
+
nodes = set(nodes)
|
| 291 |
+
G = _AntiGraph()
|
| 292 |
+
G.add_nodes_from(nodes)
|
| 293 |
+
for n in G:
|
| 294 |
+
Gnbrs = G.adjlist_inner_dict_factory()
|
| 295 |
+
G._adj[n] = Gnbrs
|
| 296 |
+
for nbr, d in self._adj[n].items():
|
| 297 |
+
if nbr in G._adj:
|
| 298 |
+
Gnbrs[nbr] = d
|
| 299 |
+
G._adj[nbr][n] = d
|
| 300 |
+
G.graph = self.graph
|
| 301 |
+
return G
|
| 302 |
+
|
| 303 |
+
class AntiDegreeView(nx.reportviews.DegreeView):
|
| 304 |
+
def __iter__(self):
|
| 305 |
+
all_nodes = set(self._succ)
|
| 306 |
+
for n in self._nodes:
|
| 307 |
+
nbrs = all_nodes - set(self._succ[n]) - {n}
|
| 308 |
+
yield (n, len(nbrs))
|
| 309 |
+
|
| 310 |
+
def __getitem__(self, n):
|
| 311 |
+
nbrs = set(self._succ) - set(self._succ[n]) - {n}
|
| 312 |
+
# AntiGraph is a ThinGraph so all edges have weight 1
|
| 313 |
+
return len(nbrs) + (n in nbrs)
|
| 314 |
+
|
| 315 |
+
@cached_property
|
| 316 |
+
def degree(self):
|
| 317 |
+
"""Returns an iterator for (node, degree) and degree for single node.
|
| 318 |
+
|
| 319 |
+
The node degree is the number of edges adjacent to the node.
|
| 320 |
+
|
| 321 |
+
Parameters
|
| 322 |
+
----------
|
| 323 |
+
nbunch : iterable container, optional (default=all nodes)
|
| 324 |
+
A container of nodes. The container will be iterated
|
| 325 |
+
through once.
|
| 326 |
+
|
| 327 |
+
weight : string or None, optional (default=None)
|
| 328 |
+
The edge attribute that holds the numerical value used
|
| 329 |
+
as a weight. If None, then each edge has weight 1.
|
| 330 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 331 |
+
|
| 332 |
+
Returns
|
| 333 |
+
-------
|
| 334 |
+
deg:
|
| 335 |
+
Degree of the node, if a single node is passed as argument.
|
| 336 |
+
nd_iter : an iterator
|
| 337 |
+
The iterator returns two-tuples of (node, degree).
|
| 338 |
+
|
| 339 |
+
See Also
|
| 340 |
+
--------
|
| 341 |
+
degree
|
| 342 |
+
|
| 343 |
+
Examples
|
| 344 |
+
--------
|
| 345 |
+
>>> G = nx.path_graph(4)
|
| 346 |
+
>>> G.degree(0) # node 0 with degree 1
|
| 347 |
+
1
|
| 348 |
+
>>> list(G.degree([0, 1]))
|
| 349 |
+
[(0, 1), (1, 2)]
|
| 350 |
+
|
| 351 |
+
"""
|
| 352 |
+
return self.AntiDegreeView(self)
|
| 353 |
+
|
| 354 |
+
def adjacency(self):
|
| 355 |
+
"""Returns an iterator of (node, adjacency set) tuples for all nodes
|
| 356 |
+
in the dense graph.
|
| 357 |
+
|
| 358 |
+
This is the fastest way to look at every edge.
|
| 359 |
+
For directed graphs, only outgoing adjacencies are included.
|
| 360 |
+
|
| 361 |
+
Returns
|
| 362 |
+
-------
|
| 363 |
+
adj_iter : iterator
|
| 364 |
+
An iterator of (node, adjacency set) for all nodes in
|
| 365 |
+
the graph.
|
| 366 |
+
|
| 367 |
+
"""
|
| 368 |
+
for n in self._adj:
|
| 369 |
+
yield (n, set(self._adj) - set(self._adj[n]) - {n})
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/ramsey.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
@nx._dispatchable
|
| 15 |
+
def ramsey_R2(G):
|
| 16 |
+
r"""Compute the largest clique and largest independent set in `G`.
|
| 17 |
+
|
| 18 |
+
This can be used to estimate bounds for the 2-color
|
| 19 |
+
Ramsey number `R(2;s,t)` for `G`.
|
| 20 |
+
|
| 21 |
+
This is a recursive implementation which could run into trouble
|
| 22 |
+
for large recursions. Note that self-loop edges are ignored.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
----------
|
| 26 |
+
G : NetworkX graph
|
| 27 |
+
Undirected graph
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
max_pair : (set, set) tuple
|
| 32 |
+
Maximum clique, Maximum independent set.
|
| 33 |
+
|
| 34 |
+
Raises
|
| 35 |
+
------
|
| 36 |
+
NetworkXNotImplemented
|
| 37 |
+
If the graph is directed or is a multigraph.
|
| 38 |
+
"""
|
| 39 |
+
if not G:
|
| 40 |
+
return set(), set()
|
| 41 |
+
|
| 42 |
+
node = arbitrary_element(G)
|
| 43 |
+
nbrs = (nbr for nbr in nx.all_neighbors(G, node) if nbr != node)
|
| 44 |
+
nnbrs = nx.non_neighbors(G, node)
|
| 45 |
+
c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
|
| 46 |
+
c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())
|
| 47 |
+
|
| 48 |
+
c_1.add(node)
|
| 49 |
+
i_2.add(node)
|
| 50 |
+
# Choose the larger of the two cliques and the larger of the two
|
| 51 |
+
# independent sets, according to cardinality.
|
| 52 |
+
return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/steinertree.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
@nx._dispatchable(edge_attrs="weight", returns_graph=True)
|
| 11 |
+
def metric_closure(G, weight="weight"):
|
| 12 |
+
"""Return the metric closure of a graph.
|
| 13 |
+
|
| 14 |
+
The metric closure of a graph *G* is the complete graph in which each edge
|
| 15 |
+
is weighted by the shortest path distance between the nodes in *G* .
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
G : NetworkX graph
|
| 20 |
+
|
| 21 |
+
Returns
|
| 22 |
+
-------
|
| 23 |
+
NetworkX graph
|
| 24 |
+
Metric closure of the graph `G`.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
M = nx.Graph()
|
| 28 |
+
|
| 29 |
+
Gnodes = set(G)
|
| 30 |
+
|
| 31 |
+
# check for connected graph while processing first node
|
| 32 |
+
all_paths_iter = nx.all_pairs_dijkstra(G, weight=weight)
|
| 33 |
+
u, (distance, path) = next(all_paths_iter)
|
| 34 |
+
if Gnodes - set(distance):
|
| 35 |
+
msg = "G is not a connected graph. metric_closure is not defined."
|
| 36 |
+
raise nx.NetworkXError(msg)
|
| 37 |
+
Gnodes.remove(u)
|
| 38 |
+
for v in Gnodes:
|
| 39 |
+
M.add_edge(u, v, distance=distance[v], path=path[v])
|
| 40 |
+
|
| 41 |
+
# first node done -- now process the rest
|
| 42 |
+
for u, (distance, path) in all_paths_iter:
|
| 43 |
+
Gnodes.remove(u)
|
| 44 |
+
for v in Gnodes:
|
| 45 |
+
M.add_edge(u, v, distance=distance[v], path=path[v])
|
| 46 |
+
|
| 47 |
+
return M
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _mehlhorn_steiner_tree(G, terminal_nodes, weight):
|
| 51 |
+
paths = nx.multi_source_dijkstra_path(G, terminal_nodes)
|
| 52 |
+
|
| 53 |
+
d_1 = {}
|
| 54 |
+
s = {}
|
| 55 |
+
for v in G.nodes():
|
| 56 |
+
s[v] = paths[v][0]
|
| 57 |
+
d_1[(v, s[v])] = len(paths[v]) - 1
|
| 58 |
+
|
| 59 |
+
# G1-G4 names match those from the Mehlhorn 1988 paper.
|
| 60 |
+
G_1_prime = nx.Graph()
|
| 61 |
+
for u, v, data in G.edges(data=True):
|
| 62 |
+
su, sv = s[u], s[v]
|
| 63 |
+
weight_here = d_1[(u, su)] + data.get(weight, 1) + d_1[(v, sv)]
|
| 64 |
+
if not G_1_prime.has_edge(su, sv):
|
| 65 |
+
G_1_prime.add_edge(su, sv, weight=weight_here)
|
| 66 |
+
else:
|
| 67 |
+
new_weight = min(weight_here, G_1_prime[su][sv]["weight"])
|
| 68 |
+
G_1_prime.add_edge(su, sv, weight=new_weight)
|
| 69 |
+
|
| 70 |
+
G_2 = nx.minimum_spanning_edges(G_1_prime, data=True)
|
| 71 |
+
|
| 72 |
+
G_3 = nx.Graph()
|
| 73 |
+
for u, v, d in G_2:
|
| 74 |
+
path = nx.shortest_path(G, u, v, weight)
|
| 75 |
+
for n1, n2 in pairwise(path):
|
| 76 |
+
G_3.add_edge(n1, n2)
|
| 77 |
+
|
| 78 |
+
G_3_mst = list(nx.minimum_spanning_edges(G_3, data=False))
|
| 79 |
+
if G.is_multigraph():
|
| 80 |
+
G_3_mst = (
|
| 81 |
+
(u, v, min(G[u][v], key=lambda k: G[u][v][k][weight])) for u, v in G_3_mst
|
| 82 |
+
)
|
| 83 |
+
G_4 = G.edge_subgraph(G_3_mst).copy()
|
| 84 |
+
_remove_nonterminal_leaves(G_4, terminal_nodes)
|
| 85 |
+
return G_4.edges()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _kou_steiner_tree(G, terminal_nodes, weight):
|
| 89 |
+
# H is the subgraph induced by terminal_nodes in the metric closure M of G.
|
| 90 |
+
M = metric_closure(G, weight=weight)
|
| 91 |
+
H = M.subgraph(terminal_nodes)
|
| 92 |
+
|
| 93 |
+
# Use the 'distance' attribute of each edge provided by M.
|
| 94 |
+
mst_edges = nx.minimum_spanning_edges(H, weight="distance", data=True)
|
| 95 |
+
|
| 96 |
+
# Create an iterator over each edge in each shortest path; repeats are okay
|
| 97 |
+
mst_all_edges = chain.from_iterable(pairwise(d["path"]) for u, v, d in mst_edges)
|
| 98 |
+
if G.is_multigraph():
|
| 99 |
+
mst_all_edges = (
|
| 100 |
+
(u, v, min(G[u][v], key=lambda k: G[u][v][k][weight]))
|
| 101 |
+
for u, v in mst_all_edges
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Find the MST again, over this new set of edges
|
| 105 |
+
G_S = G.edge_subgraph(mst_all_edges)
|
| 106 |
+
T_S = nx.minimum_spanning_edges(G_S, weight="weight", data=False)
|
| 107 |
+
|
| 108 |
+
# Leaf nodes that are not terminal might still remain; remove them here
|
| 109 |
+
T_H = G.edge_subgraph(T_S).copy()
|
| 110 |
+
_remove_nonterminal_leaves(T_H, terminal_nodes)
|
| 111 |
+
|
| 112 |
+
return T_H.edges()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _remove_nonterminal_leaves(G, terminals):
|
| 116 |
+
terminals_set = set(terminals)
|
| 117 |
+
for n in list(G.nodes):
|
| 118 |
+
if n not in terminals_set and G.degree(n) == 1:
|
| 119 |
+
G.remove_node(n)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
ALGORITHMS = {
|
| 123 |
+
"kou": _kou_steiner_tree,
|
| 124 |
+
"mehlhorn": _mehlhorn_steiner_tree,
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@not_implemented_for("directed")
|
| 129 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 130 |
+
def steiner_tree(G, terminal_nodes, weight="weight", method=None):
|
| 131 |
+
r"""Return an approximation to the minimum Steiner tree of a graph.
|
| 132 |
+
|
| 133 |
+
The minimum Steiner tree of `G` w.r.t a set of `terminal_nodes` (also *S*)
|
| 134 |
+
is a tree within `G` that spans those nodes and has minimum size (sum of
|
| 135 |
+
edge weights) among all such trees.
|
| 136 |
+
|
| 137 |
+
The approximation algorithm is specified with the `method` keyword
|
| 138 |
+
argument. All three available algorithms produce a tree whose weight is
|
| 139 |
+
within a ``(2 - (2 / l))`` factor of the weight of the optimal Steiner tree,
|
| 140 |
+
where ``l`` is the minimum number of leaf nodes across all possible Steiner
|
| 141 |
+
trees.
|
| 142 |
+
|
| 143 |
+
* ``"kou"`` [2]_ (runtime $O(|S| |V|^2)$) computes the minimum spanning tree of
|
| 144 |
+
the subgraph of the metric closure of *G* induced by the terminal nodes,
|
| 145 |
+
where the metric closure of *G* is the complete graph in which each edge is
|
| 146 |
+
weighted by the shortest path distance between the nodes in *G*.
|
| 147 |
+
|
| 148 |
+
* ``"mehlhorn"`` [3]_ (runtime $O(|E|+|V|\log|V|)$) modifies Kou et al.'s
|
| 149 |
+
algorithm, beginning by finding the closest terminal node for each
|
| 150 |
+
non-terminal. This data is used to create a complete graph containing only
|
| 151 |
+
the terminal nodes, in which edge is weighted with the shortest path
|
| 152 |
+
distance between them. The algorithm then proceeds in the same way as Kou
|
| 153 |
+
et al..
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
G : NetworkX graph
|
| 158 |
+
|
| 159 |
+
terminal_nodes : list
|
| 160 |
+
A list of terminal nodes for which minimum steiner tree is
|
| 161 |
+
to be found.
|
| 162 |
+
|
| 163 |
+
weight : string (default = 'weight')
|
| 164 |
+
Use the edge attribute specified by this string as the edge weight.
|
| 165 |
+
Any edge attribute not present defaults to 1.
|
| 166 |
+
|
| 167 |
+
method : string, optional (default = 'mehlhorn')
|
| 168 |
+
The algorithm to use to approximate the Steiner tree.
|
| 169 |
+
Supported options: 'kou', 'mehlhorn'.
|
| 170 |
+
Other inputs produce a ValueError.
|
| 171 |
+
|
| 172 |
+
Returns
|
| 173 |
+
-------
|
| 174 |
+
NetworkX graph
|
| 175 |
+
Approximation to the minimum steiner tree of `G` induced by
|
| 176 |
+
`terminal_nodes` .
|
| 177 |
+
|
| 178 |
+
Raises
|
| 179 |
+
------
|
| 180 |
+
NetworkXNotImplemented
|
| 181 |
+
If `G` is directed.
|
| 182 |
+
|
| 183 |
+
ValueError
|
| 184 |
+
If the specified `method` is not supported.
|
| 185 |
+
|
| 186 |
+
Notes
|
| 187 |
+
-----
|
| 188 |
+
For multigraphs, the edge between two nodes with minimum weight is the
|
| 189 |
+
edge put into the Steiner tree.
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
References
|
| 193 |
+
----------
|
| 194 |
+
.. [1] Steiner_tree_problem on Wikipedia.
|
| 195 |
+
https://en.wikipedia.org/wiki/Steiner_tree_problem
|
| 196 |
+
.. [2] Kou, L., G. Markowsky, and L. Berman. 1981.
|
| 197 |
+
‘A Fast Algorithm for Steiner Trees’.
|
| 198 |
+
Acta Informatica 15 (2): 141–45.
|
| 199 |
+
https://doi.org/10.1007/BF00288961.
|
| 200 |
+
.. [3] Mehlhorn, Kurt. 1988.
|
| 201 |
+
‘A Faster Approximation Algorithm for the Steiner Problem in Graphs’.
|
| 202 |
+
Information Processing Letters 27 (3): 125–28.
|
| 203 |
+
https://doi.org/10.1016/0020-0190(88)90066-X.
|
| 204 |
+
"""
|
| 205 |
+
if method is None:
|
| 206 |
+
method = "mehlhorn"
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
algo = ALGORITHMS[method]
|
| 210 |
+
except KeyError as e:
|
| 211 |
+
raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
|
| 212 |
+
|
| 213 |
+
edges = algo(G, terminal_nodes, weight)
|
| 214 |
+
# For multigraph we should add the minimal weight edge keys
|
| 215 |
+
if G.is_multigraph():
|
| 216 |
+
edges = (
|
| 217 |
+
(u, v, min(G[u][v], key=lambda k: G[u][v][k][weight])) for u, v in edges
|
| 218 |
+
)
|
| 219 |
+
T = G.edge_subgraph(edges)
|
| 220 |
+
return T
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/traveling_salesman.py
ADDED
|
@@ -0,0 +1,1498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 128 |
+
def christofides(G, weight="weight", tree=None):
|
| 129 |
+
"""Approximate a solution of the traveling salesman problem
|
| 130 |
+
|
| 131 |
+
Compute a 3/2-approximation of the traveling salesman problem
|
| 132 |
+
in a complete undirected graph using Christofides [1]_ algorithm.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
G : Graph
|
| 137 |
+
`G` should be a complete weighted undirected graph.
|
| 138 |
+
The distance between all pairs of nodes should be included.
|
| 139 |
+
|
| 140 |
+
weight : string, optional (default="weight")
|
| 141 |
+
Edge data key corresponding to the edge weight.
|
| 142 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 143 |
+
|
| 144 |
+
tree : NetworkX graph or None (default: None)
|
| 145 |
+
A minimum spanning tree of G. Or, if None, the minimum spanning
|
| 146 |
+
tree is computed using :func:`networkx.minimum_spanning_tree`
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
list
|
| 151 |
+
List of nodes in `G` along a cycle with a 3/2-approximation of
|
| 152 |
+
the minimal Hamiltonian cycle.
|
| 153 |
+
|
| 154 |
+
References
|
| 155 |
+
----------
|
| 156 |
+
.. [1] Christofides, Nicos. "Worst-case analysis of a new heuristic for
|
| 157 |
+
the travelling salesman problem." No. RR-388. Carnegie-Mellon Univ
|
| 158 |
+
Pittsburgh Pa Management Sciences Research Group, 1976.
|
| 159 |
+
"""
|
| 160 |
+
# Remove selfloops if necessary
|
| 161 |
+
loop_nodes = nx.nodes_with_selfloops(G)
|
| 162 |
+
try:
|
| 163 |
+
node = next(loop_nodes)
|
| 164 |
+
except StopIteration:
|
| 165 |
+
pass
|
| 166 |
+
else:
|
| 167 |
+
G = G.copy()
|
| 168 |
+
G.remove_edge(node, node)
|
| 169 |
+
G.remove_edges_from((n, n) for n in loop_nodes)
|
| 170 |
+
# Check that G is a complete graph
|
| 171 |
+
N = len(G) - 1
|
| 172 |
+
# This check ignores selfloops which is what we want here.
|
| 173 |
+
if any(len(nbrdict) != N for n, nbrdict in G.adj.items()):
|
| 174 |
+
raise nx.NetworkXError("G must be a complete graph.")
|
| 175 |
+
|
| 176 |
+
if tree is None:
|
| 177 |
+
tree = nx.minimum_spanning_tree(G, weight=weight)
|
| 178 |
+
L = G.copy()
|
| 179 |
+
L.remove_nodes_from([v for v, degree in tree.degree if not (degree % 2)])
|
| 180 |
+
MG = nx.MultiGraph()
|
| 181 |
+
MG.add_edges_from(tree.edges)
|
| 182 |
+
edges = nx.min_weight_matching(L, weight=weight)
|
| 183 |
+
MG.add_edges_from(edges)
|
| 184 |
+
return _shortcutting(nx.eulerian_circuit(MG))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _shortcutting(circuit):
|
| 188 |
+
"""Remove duplicate nodes in the path"""
|
| 189 |
+
nodes = []
|
| 190 |
+
for u, v in circuit:
|
| 191 |
+
if v in nodes:
|
| 192 |
+
continue
|
| 193 |
+
if not nodes:
|
| 194 |
+
nodes.append(u)
|
| 195 |
+
nodes.append(v)
|
| 196 |
+
nodes.append(nodes[0])
|
| 197 |
+
return nodes
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 201 |
+
def traveling_salesman_problem(
|
| 202 |
+
G, weight="weight", nodes=None, cycle=True, method=None, **kwargs
|
| 203 |
+
):
|
| 204 |
+
"""Find the shortest path in `G` connecting specified nodes
|
| 205 |
+
|
| 206 |
+
This function allows approximate solution to the traveling salesman
|
| 207 |
+
problem on networks that are not complete graphs and/or where the
|
| 208 |
+
salesman does not need to visit all nodes.
|
| 209 |
+
|
| 210 |
+
This function proceeds in two steps. First, it creates a complete
|
| 211 |
+
graph using the all-pairs shortest_paths between nodes in `nodes`.
|
| 212 |
+
Edge weights in the new graph are the lengths of the paths
|
| 213 |
+
between each pair of nodes in the original graph.
|
| 214 |
+
Second, an algorithm (default: `christofides` for undirected and
|
| 215 |
+
`asadpour_atsp` for directed) is used to approximate the minimal Hamiltonian
|
| 216 |
+
cycle on this new graph. The available algorithms are:
|
| 217 |
+
|
| 218 |
+
- christofides
|
| 219 |
+
- greedy_tsp
|
| 220 |
+
- simulated_annealing_tsp
|
| 221 |
+
- threshold_accepting_tsp
|
| 222 |
+
- asadpour_atsp
|
| 223 |
+
|
| 224 |
+
Once the Hamiltonian Cycle is found, this function post-processes to
|
| 225 |
+
accommodate the structure of the original graph. If `cycle` is ``False``,
|
| 226 |
+
the biggest weight edge is removed to make a Hamiltonian path.
|
| 227 |
+
Then each edge on the new complete graph used for that analysis is
|
| 228 |
+
replaced by the shortest_path between those nodes on the original graph.
|
| 229 |
+
If the input graph `G` includes edges with weights that do not adhere to
|
| 230 |
+
the triangle inequality, such as when `G` is not a complete graph (i.e
|
| 231 |
+
length of non-existent edges is infinity), then the returned path may
|
| 232 |
+
contain some repeating nodes (other than the starting node).
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
G : NetworkX graph
|
| 237 |
+
A possibly weighted graph
|
| 238 |
+
|
| 239 |
+
nodes : collection of nodes (default=G.nodes)
|
| 240 |
+
collection (list, set, etc.) of nodes to visit
|
| 241 |
+
|
| 242 |
+
weight : string, optional (default="weight")
|
| 243 |
+
Edge data key corresponding to the edge weight.
|
| 244 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 245 |
+
|
| 246 |
+
cycle : bool (default: True)
|
| 247 |
+
Indicates whether a cycle should be returned, or a path.
|
| 248 |
+
Note: the cycle is the approximate minimal cycle.
|
| 249 |
+
The path simply removes the biggest edge in that cycle.
|
| 250 |
+
|
| 251 |
+
method : function (default: None)
|
| 252 |
+
A function that returns a cycle on all nodes and approximates
|
| 253 |
+
the solution to the traveling salesman problem on a complete
|
| 254 |
+
graph. The returned cycle is then used to find a corresponding
|
| 255 |
+
solution on `G`. `method` should be callable; take inputs
|
| 256 |
+
`G`, and `weight`; and return a list of nodes along the cycle.
|
| 257 |
+
|
| 258 |
+
Provided options include :func:`christofides`, :func:`greedy_tsp`,
|
| 259 |
+
:func:`simulated_annealing_tsp` and :func:`threshold_accepting_tsp`.
|
| 260 |
+
|
| 261 |
+
If `method is None`: use :func:`christofides` for undirected `G` and
|
| 262 |
+
:func:`asadpour_atsp` for directed `G`.
|
| 263 |
+
|
| 264 |
+
**kwargs : dict
|
| 265 |
+
Other keyword arguments to be passed to the `method` function passed in.
|
| 266 |
+
|
| 267 |
+
Returns
|
| 268 |
+
-------
|
| 269 |
+
list
|
| 270 |
+
List of nodes in `G` along a path with an approximation of the minimal
|
| 271 |
+
path through `nodes`.
|
| 272 |
+
|
| 273 |
+
Raises
|
| 274 |
+
------
|
| 275 |
+
NetworkXError
|
| 276 |
+
If `G` is a directed graph it has to be strongly connected or the
|
| 277 |
+
complete version cannot be generated.
|
| 278 |
+
|
| 279 |
+
Examples
|
| 280 |
+
--------
|
| 281 |
+
>>> tsp = nx.approximation.traveling_salesman_problem
|
| 282 |
+
>>> G = nx.cycle_graph(9)
|
| 283 |
+
>>> G[4][5]["weight"] = 5 # all other weights are 1
|
| 284 |
+
>>> tsp(G, nodes=[3, 6])
|
| 285 |
+
[3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3]
|
| 286 |
+
>>> path = tsp(G, cycle=False)
|
| 287 |
+
>>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
|
| 288 |
+
True
|
| 289 |
+
|
| 290 |
+
While no longer required, you can still build (curry) your own function
|
| 291 |
+
to provide parameter values to the methods.
|
| 292 |
+
|
| 293 |
+
>>> SA_tsp = nx.approximation.simulated_annealing_tsp
|
| 294 |
+
>>> method = lambda G, weight: SA_tsp(G, "greedy", weight=weight, temp=500)
|
| 295 |
+
>>> path = tsp(G, cycle=False, method=method)
|
| 296 |
+
>>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
|
| 297 |
+
True
|
| 298 |
+
|
| 299 |
+
Otherwise, pass other keyword arguments directly into the tsp function.
|
| 300 |
+
|
| 301 |
+
>>> path = tsp(
|
| 302 |
+
... G,
|
| 303 |
+
... cycle=False,
|
| 304 |
+
... method=nx.approximation.simulated_annealing_tsp,
|
| 305 |
+
... init_cycle="greedy",
|
| 306 |
+
... temp=500,
|
| 307 |
+
... )
|
| 308 |
+
>>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
|
| 309 |
+
True
|
| 310 |
+
"""
|
| 311 |
+
if method is None:
|
| 312 |
+
if G.is_directed():
|
| 313 |
+
method = asadpour_atsp
|
| 314 |
+
else:
|
| 315 |
+
method = christofides
|
| 316 |
+
if nodes is None:
|
| 317 |
+
nodes = list(G.nodes)
|
| 318 |
+
|
| 319 |
+
dist = {}
|
| 320 |
+
path = {}
|
| 321 |
+
for n, (d, p) in nx.all_pairs_dijkstra(G, weight=weight):
|
| 322 |
+
dist[n] = d
|
| 323 |
+
path[n] = p
|
| 324 |
+
|
| 325 |
+
if G.is_directed():
|
| 326 |
+
# If the graph is not strongly connected, raise an exception
|
| 327 |
+
if not nx.is_strongly_connected(G):
|
| 328 |
+
raise nx.NetworkXError("G is not strongly connected")
|
| 329 |
+
GG = nx.DiGraph()
|
| 330 |
+
else:
|
| 331 |
+
GG = nx.Graph()
|
| 332 |
+
for u in nodes:
|
| 333 |
+
for v in nodes:
|
| 334 |
+
if u == v:
|
| 335 |
+
continue
|
| 336 |
+
GG.add_edge(u, v, weight=dist[u][v])
|
| 337 |
+
|
| 338 |
+
best_GG = method(GG, weight=weight, **kwargs)
|
| 339 |
+
|
| 340 |
+
if not cycle:
|
| 341 |
+
# find and remove the biggest edge
|
| 342 |
+
(u, v) = max(pairwise(best_GG), key=lambda x: dist[x[0]][x[1]])
|
| 343 |
+
pos = best_GG.index(u) + 1
|
| 344 |
+
while best_GG[pos] != v:
|
| 345 |
+
pos = best_GG[pos:].index(u) + 1
|
| 346 |
+
best_GG = best_GG[pos:-1] + best_GG[:pos]
|
| 347 |
+
|
| 348 |
+
best_path = []
|
| 349 |
+
for u, v in pairwise(best_GG):
|
| 350 |
+
best_path.extend(path[u][v][:-1])
|
| 351 |
+
best_path.append(v)
|
| 352 |
+
return best_path
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@not_implemented_for("undirected")
|
| 356 |
+
@py_random_state(2)
|
| 357 |
+
@nx._dispatchable(edge_attrs="weight", mutates_input=True)
|
| 358 |
+
def asadpour_atsp(G, weight="weight", seed=None, source=None):
|
| 359 |
+
"""
|
| 360 |
+
Returns an approximate solution to the traveling salesman problem.
|
| 361 |
+
|
| 362 |
+
This approximate solution is one of the best known approximations for the
|
| 363 |
+
asymmetric traveling salesman problem developed by Asadpour et al,
|
| 364 |
+
[1]_. The algorithm first solves the Held-Karp relaxation to find a lower
|
| 365 |
+
bound for the weight of the cycle. Next, it constructs an exponential
|
| 366 |
+
distribution of undirected spanning trees where the probability of an
|
| 367 |
+
edge being in the tree corresponds to the weight of that edge using a
|
| 368 |
+
maximum entropy rounding scheme. Next we sample that distribution
|
| 369 |
+
$2 \\lceil \\ln n \\rceil$ times and save the minimum sampled tree once the
|
| 370 |
+
direction of the arcs is added back to the edges. Finally, we augment
|
| 371 |
+
then short circuit that graph to find the approximate tour for the
|
| 372 |
+
salesman.
|
| 373 |
+
|
| 374 |
+
Parameters
|
| 375 |
+
----------
|
| 376 |
+
G : nx.DiGraph
|
| 377 |
+
The graph should be a complete weighted directed graph. The
|
| 378 |
+
distance between all paris of nodes should be included and the triangle
|
| 379 |
+
inequality should hold. That is, the direct edge between any two nodes
|
| 380 |
+
should be the path of least cost.
|
| 381 |
+
|
| 382 |
+
weight : string, optional (default="weight")
|
| 383 |
+
Edge data key corresponding to the edge weight.
|
| 384 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 385 |
+
|
| 386 |
+
seed : integer, random_state, or None (default)
|
| 387 |
+
Indicator of random number generation state.
|
| 388 |
+
See :ref:`Randomness<randomness>`.
|
| 389 |
+
|
| 390 |
+
source : node label (default=`None`)
|
| 391 |
+
If given, return the cycle starting and ending at the given node.
|
| 392 |
+
|
| 393 |
+
Returns
|
| 394 |
+
-------
|
| 395 |
+
cycle : list of nodes
|
| 396 |
+
Returns the cycle (list of nodes) that a salesman can follow to minimize
|
| 397 |
+
the total weight of the trip.
|
| 398 |
+
|
| 399 |
+
Raises
|
| 400 |
+
------
|
| 401 |
+
NetworkXError
|
| 402 |
+
If `G` is not complete or has less than two nodes, the algorithm raises
|
| 403 |
+
an exception.
|
| 404 |
+
|
| 405 |
+
NetworkXError
|
| 406 |
+
If `source` is not `None` and is not a node in `G`, the algorithm raises
|
| 407 |
+
an exception.
|
| 408 |
+
|
| 409 |
+
NetworkXNotImplemented
|
| 410 |
+
If `G` is an undirected graph.
|
| 411 |
+
|
| 412 |
+
References
|
| 413 |
+
----------
|
| 414 |
+
.. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
|
| 415 |
+
An o(log n/log log n)-approximation algorithm for the asymmetric
|
| 416 |
+
traveling salesman problem, Operations research, 65 (2017),
|
| 417 |
+
pp. 1043–1061
|
| 418 |
+
|
| 419 |
+
Examples
|
| 420 |
+
--------
|
| 421 |
+
>>> import networkx as nx
|
| 422 |
+
>>> import networkx.algorithms.approximation as approx
|
| 423 |
+
>>> G = nx.complete_graph(3, create_using=nx.DiGraph)
|
| 424 |
+
>>> nx.set_edge_attributes(
|
| 425 |
+
... G, {(0, 1): 2, (1, 2): 2, (2, 0): 2, (0, 2): 1, (2, 1): 1, (1, 0): 1}, "weight"
|
| 426 |
+
... )
|
| 427 |
+
>>> tour = approx.asadpour_atsp(G, source=0)
|
| 428 |
+
>>> tour
|
| 429 |
+
[0, 2, 1, 0]
|
| 430 |
+
"""
|
| 431 |
+
from math import ceil, exp
|
| 432 |
+
from math import log as ln
|
| 433 |
+
|
| 434 |
+
# Check that G is a complete graph
|
| 435 |
+
N = len(G) - 1
|
| 436 |
+
if N < 2:
|
| 437 |
+
raise nx.NetworkXError("G must have at least two nodes")
|
| 438 |
+
# This check ignores selfloops which is what we want here.
|
| 439 |
+
if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
|
| 440 |
+
raise nx.NetworkXError("G is not a complete DiGraph")
|
| 441 |
+
# Check that the source vertex, if given, is in the graph
|
| 442 |
+
if source is not None and source not in G.nodes:
|
| 443 |
+
raise nx.NetworkXError("Given source node not in G.")
|
| 444 |
+
|
| 445 |
+
opt_hk, z_star = held_karp_ascent(G, weight)
|
| 446 |
+
|
| 447 |
+
# Test to see if the ascent method found an integer solution or a fractional
|
| 448 |
+
# solution. If it is integral then z_star is a nx.Graph, otherwise it is
|
| 449 |
+
# a dict
|
| 450 |
+
if not isinstance(z_star, dict):
|
| 451 |
+
# Here we are using the shortcutting method to go from the list of edges
|
| 452 |
+
# returned from eulerian_circuit to a list of nodes
|
| 453 |
+
return _shortcutting(nx.eulerian_circuit(z_star, source=source))
|
| 454 |
+
|
| 455 |
+
# Create the undirected support of z_star
|
| 456 |
+
z_support = nx.MultiGraph()
|
| 457 |
+
for u, v in z_star:
|
| 458 |
+
if (u, v) not in z_support.edges:
|
| 459 |
+
edge_weight = min(G[u][v][weight], G[v][u][weight])
|
| 460 |
+
z_support.add_edge(u, v, **{weight: edge_weight})
|
| 461 |
+
|
| 462 |
+
# Create the exponential distribution of spanning trees
|
| 463 |
+
gamma = spanning_tree_distribution(z_support, z_star)
|
| 464 |
+
|
| 465 |
+
# Write the lambda values to the edges of z_support
|
| 466 |
+
z_support = nx.Graph(z_support)
|
| 467 |
+
lambda_dict = {(u, v): exp(gamma[(u, v)]) for u, v in z_support.edges()}
|
| 468 |
+
nx.set_edge_attributes(z_support, lambda_dict, "weight")
|
| 469 |
+
del gamma, lambda_dict
|
| 470 |
+
|
| 471 |
+
# Sample 2 * ceil( ln(n) ) spanning trees and record the minimum one
|
| 472 |
+
minimum_sampled_tree = None
|
| 473 |
+
minimum_sampled_tree_weight = math.inf
|
| 474 |
+
for _ in range(2 * ceil(ln(G.number_of_nodes()))):
|
| 475 |
+
sampled_tree = random_spanning_tree(z_support, "weight", seed=seed)
|
| 476 |
+
sampled_tree_weight = sampled_tree.size(weight)
|
| 477 |
+
if sampled_tree_weight < minimum_sampled_tree_weight:
|
| 478 |
+
minimum_sampled_tree = sampled_tree.copy()
|
| 479 |
+
minimum_sampled_tree_weight = sampled_tree_weight
|
| 480 |
+
|
| 481 |
+
# Orient the edges in that tree to keep the cost of the tree the same.
|
| 482 |
+
t_star = nx.MultiDiGraph()
|
| 483 |
+
for u, v, d in minimum_sampled_tree.edges(data=weight):
|
| 484 |
+
if d == G[u][v][weight]:
|
| 485 |
+
t_star.add_edge(u, v, **{weight: d})
|
| 486 |
+
else:
|
| 487 |
+
t_star.add_edge(v, u, **{weight: d})
|
| 488 |
+
|
| 489 |
+
# Find the node demands needed to neutralize the flow of t_star in G
|
| 490 |
+
node_demands = {n: t_star.out_degree(n) - t_star.in_degree(n) for n in t_star}
|
| 491 |
+
nx.set_node_attributes(G, node_demands, "demand")
|
| 492 |
+
|
| 493 |
+
# Find the min_cost_flow
|
| 494 |
+
flow_dict = nx.min_cost_flow(G, "demand")
|
| 495 |
+
|
| 496 |
+
# Build the flow into t_star
|
| 497 |
+
for source, values in flow_dict.items():
|
| 498 |
+
for target in values:
|
| 499 |
+
if (source, target) not in t_star.edges and values[target] > 0:
|
| 500 |
+
# IF values[target] > 0 we have to add that many edges
|
| 501 |
+
for _ in range(values[target]):
|
| 502 |
+
t_star.add_edge(source, target)
|
| 503 |
+
|
| 504 |
+
# Return the shortcut eulerian circuit
|
| 505 |
+
circuit = nx.eulerian_circuit(t_star, source=source)
|
| 506 |
+
return _shortcutting(circuit)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
@nx._dispatchable(edge_attrs="weight", mutates_input=True, returns_graph=True)
|
| 510 |
+
def held_karp_ascent(G, weight="weight"):
|
| 511 |
+
"""
|
| 512 |
+
Minimizes the Held-Karp relaxation of the TSP for `G`
|
| 513 |
+
|
| 514 |
+
Solves the Held-Karp relaxation of the input complete digraph and scales
|
| 515 |
+
the output solution for use in the Asadpour [1]_ ASTP algorithm.
|
| 516 |
+
|
| 517 |
+
The Held-Karp relaxation defines the lower bound for solutions to the
|
| 518 |
+
ATSP, although it does return a fractional solution. This is used in the
|
| 519 |
+
Asadpour algorithm as an initial solution which is later rounded to a
|
| 520 |
+
integral tree within the spanning tree polytopes. This function solves
|
| 521 |
+
the relaxation with the branch and bound method in [2]_.
|
| 522 |
+
|
| 523 |
+
Parameters
|
| 524 |
+
----------
|
| 525 |
+
G : nx.DiGraph
|
| 526 |
+
The graph should be a complete weighted directed graph.
|
| 527 |
+
The distance between all paris of nodes should be included.
|
| 528 |
+
|
| 529 |
+
weight : string, optional (default="weight")
|
| 530 |
+
Edge data key corresponding to the edge weight.
|
| 531 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 532 |
+
|
| 533 |
+
Returns
|
| 534 |
+
-------
|
| 535 |
+
OPT : float
|
| 536 |
+
The cost for the optimal solution to the Held-Karp relaxation
|
| 537 |
+
z : dict or nx.Graph
|
| 538 |
+
A symmetrized and scaled version of the optimal solution to the
|
| 539 |
+
Held-Karp relaxation for use in the Asadpour algorithm.
|
| 540 |
+
|
| 541 |
+
If an integral solution is found, then that is an optimal solution for
|
| 542 |
+
the ATSP problem and that is returned instead.
|
| 543 |
+
|
| 544 |
+
References
|
| 545 |
+
----------
|
| 546 |
+
.. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
|
| 547 |
+
An o(log n/log log n)-approximation algorithm for the asymmetric
|
| 548 |
+
traveling salesman problem, Operations research, 65 (2017),
|
| 549 |
+
pp. 1043–1061
|
| 550 |
+
|
| 551 |
+
.. [2] M. Held, R. M. Karp, The traveling-salesman problem and minimum
|
| 552 |
+
spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
|
| 553 |
+
pp.1138-1162
|
| 554 |
+
"""
|
| 555 |
+
import numpy as np
|
| 556 |
+
from scipy import optimize
|
| 557 |
+
|
| 558 |
+
def k_pi():
|
| 559 |
+
"""
|
| 560 |
+
Find the set of minimum 1-Arborescences for G at point pi.
|
| 561 |
+
|
| 562 |
+
Returns
|
| 563 |
+
-------
|
| 564 |
+
Set
|
| 565 |
+
The set of minimum 1-Arborescences
|
| 566 |
+
"""
|
| 567 |
+
# Create a copy of G without vertex 1.
|
| 568 |
+
G_1 = G.copy()
|
| 569 |
+
minimum_1_arborescences = set()
|
| 570 |
+
minimum_1_arborescence_weight = math.inf
|
| 571 |
+
|
| 572 |
+
# node is node '1' in the Held and Karp paper
|
| 573 |
+
n = next(G.__iter__())
|
| 574 |
+
G_1.remove_node(n)
|
| 575 |
+
|
| 576 |
+
# Iterate over the spanning arborescences of the graph until we know
|
| 577 |
+
# that we have found the minimum 1-arborescences. My proposed strategy
|
| 578 |
+
# is to find the most extensive root to connect to from 'node 1' and
|
| 579 |
+
# the least expensive one. We then iterate over arborescences until
|
| 580 |
+
# the cost of the basic arborescence is the cost of the minimum one
|
| 581 |
+
# plus the difference between the most and least expensive roots,
|
| 582 |
+
# that way the cost of connecting 'node 1' will by definition not by
|
| 583 |
+
# minimum
|
| 584 |
+
min_root = {"node": None, weight: math.inf}
|
| 585 |
+
max_root = {"node": None, weight: -math.inf}
|
| 586 |
+
for u, v, d in G.edges(n, data=True):
|
| 587 |
+
if d[weight] < min_root[weight]:
|
| 588 |
+
min_root = {"node": v, weight: d[weight]}
|
| 589 |
+
if d[weight] > max_root[weight]:
|
| 590 |
+
max_root = {"node": v, weight: d[weight]}
|
| 591 |
+
|
| 592 |
+
min_in_edge = min(G.in_edges(n, data=True), key=lambda x: x[2][weight])
|
| 593 |
+
min_root[weight] = min_root[weight] + min_in_edge[2][weight]
|
| 594 |
+
max_root[weight] = max_root[weight] + min_in_edge[2][weight]
|
| 595 |
+
|
| 596 |
+
min_arb_weight = math.inf
|
| 597 |
+
for arb in nx.ArborescenceIterator(G_1):
|
| 598 |
+
arb_weight = arb.size(weight)
|
| 599 |
+
if min_arb_weight == math.inf:
|
| 600 |
+
min_arb_weight = arb_weight
|
| 601 |
+
elif arb_weight > min_arb_weight + max_root[weight] - min_root[weight]:
|
| 602 |
+
break
|
| 603 |
+
# We have to pick the root node of the arborescence for the out
|
| 604 |
+
# edge of the first vertex as that is the only node without an
|
| 605 |
+
# edge directed into it.
|
| 606 |
+
for N, deg in arb.in_degree:
|
| 607 |
+
if deg == 0:
|
| 608 |
+
# root found
|
| 609 |
+
arb.add_edge(n, N, **{weight: G[n][N][weight]})
|
| 610 |
+
arb_weight += G[n][N][weight]
|
| 611 |
+
break
|
| 612 |
+
|
| 613 |
+
# We can pick the minimum weight in-edge for the vertex with
|
| 614 |
+
# a cycle. If there are multiple edges with the same, minimum
|
| 615 |
+
# weight, We need to add all of them.
|
| 616 |
+
#
|
| 617 |
+
# Delete the edge (N, v) so that we cannot pick it.
|
| 618 |
+
edge_data = G[N][n]
|
| 619 |
+
G.remove_edge(N, n)
|
| 620 |
+
min_weight = min(G.in_edges(n, data=weight), key=lambda x: x[2])[2]
|
| 621 |
+
min_edges = [
|
| 622 |
+
(u, v, d) for u, v, d in G.in_edges(n, data=weight) if d == min_weight
|
| 623 |
+
]
|
| 624 |
+
for u, v, d in min_edges:
|
| 625 |
+
new_arb = arb.copy()
|
| 626 |
+
new_arb.add_edge(u, v, **{weight: d})
|
| 627 |
+
new_arb_weight = arb_weight + d
|
| 628 |
+
# Check to see the weight of the arborescence, if it is a
|
| 629 |
+
# new minimum, clear all of the old potential minimum
|
| 630 |
+
# 1-arborescences and add this is the only one. If its
|
| 631 |
+
# weight is above the known minimum, do not add it.
|
| 632 |
+
if new_arb_weight < minimum_1_arborescence_weight:
|
| 633 |
+
minimum_1_arborescences.clear()
|
| 634 |
+
minimum_1_arborescence_weight = new_arb_weight
|
| 635 |
+
# We have a 1-arborescence, add it to the set
|
| 636 |
+
if new_arb_weight == minimum_1_arborescence_weight:
|
| 637 |
+
minimum_1_arborescences.add(new_arb)
|
| 638 |
+
G.add_edge(N, n, **edge_data)
|
| 639 |
+
|
| 640 |
+
return minimum_1_arborescences
|
| 641 |
+
|
| 642 |
+
def direction_of_ascent():
|
| 643 |
+
"""
|
| 644 |
+
Find the direction of ascent at point pi.
|
| 645 |
+
|
| 646 |
+
See [1]_ for more information.
|
| 647 |
+
|
| 648 |
+
Returns
|
| 649 |
+
-------
|
| 650 |
+
dict
|
| 651 |
+
A mapping from the nodes of the graph which represents the direction
|
| 652 |
+
of ascent.
|
| 653 |
+
|
| 654 |
+
References
|
| 655 |
+
----------
|
| 656 |
+
.. [1] M. Held, R. M. Karp, The traveling-salesman problem and minimum
|
| 657 |
+
spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
|
| 658 |
+
pp.1138-1162
|
| 659 |
+
"""
|
| 660 |
+
# 1. Set d equal to the zero n-vector.
|
| 661 |
+
d = {}
|
| 662 |
+
for n in G:
|
| 663 |
+
d[n] = 0
|
| 664 |
+
del n
|
| 665 |
+
# 2. Find a 1-Arborescence T^k such that k is in K(pi, d).
|
| 666 |
+
minimum_1_arborescences = k_pi()
|
| 667 |
+
while True:
|
| 668 |
+
# Reduce K(pi) to K(pi, d)
|
| 669 |
+
# Find the arborescence in K(pi) which increases the lest in
|
| 670 |
+
# direction d
|
| 671 |
+
min_k_d_weight = math.inf
|
| 672 |
+
min_k_d = None
|
| 673 |
+
for arborescence in minimum_1_arborescences:
|
| 674 |
+
weighted_cost = 0
|
| 675 |
+
for n, deg in arborescence.degree:
|
| 676 |
+
weighted_cost += d[n] * (deg - 2)
|
| 677 |
+
if weighted_cost < min_k_d_weight:
|
| 678 |
+
min_k_d_weight = weighted_cost
|
| 679 |
+
min_k_d = arborescence
|
| 680 |
+
|
| 681 |
+
# 3. If sum of d_i * v_{i, k} is greater than zero, terminate
|
| 682 |
+
if min_k_d_weight > 0:
|
| 683 |
+
return d, min_k_d
|
| 684 |
+
# 4. d_i = d_i + v_{i, k}
|
| 685 |
+
for n, deg in min_k_d.degree:
|
| 686 |
+
d[n] += deg - 2
|
| 687 |
+
# Check that we do not need to terminate because the direction
|
| 688 |
+
# of ascent does not exist. This is done with linear
|
| 689 |
+
# programming.
|
| 690 |
+
c = np.full(len(minimum_1_arborescences), -1, dtype=int)
|
| 691 |
+
a_eq = np.empty((len(G) + 1, len(minimum_1_arborescences)), dtype=int)
|
| 692 |
+
b_eq = np.zeros(len(G) + 1, dtype=int)
|
| 693 |
+
b_eq[len(G)] = 1
|
| 694 |
+
for arb_count, arborescence in enumerate(minimum_1_arborescences):
|
| 695 |
+
n_count = len(G) - 1
|
| 696 |
+
for n, deg in arborescence.degree:
|
| 697 |
+
a_eq[n_count][arb_count] = deg - 2
|
| 698 |
+
n_count -= 1
|
| 699 |
+
a_eq[len(G)][arb_count] = 1
|
| 700 |
+
program_result = optimize.linprog(
|
| 701 |
+
c, A_eq=a_eq, b_eq=b_eq, method="highs-ipm"
|
| 702 |
+
)
|
| 703 |
+
# If the constants exist, then the direction of ascent doesn't
|
| 704 |
+
if program_result.success:
|
| 705 |
+
# There is no direction of ascent
|
| 706 |
+
return None, minimum_1_arborescences
|
| 707 |
+
|
| 708 |
+
# 5. GO TO 2
|
| 709 |
+
|
| 710 |
+
def find_epsilon(k, d):
|
| 711 |
+
"""
|
| 712 |
+
Given the direction of ascent at pi, find the maximum distance we can go
|
| 713 |
+
in that direction.
|
| 714 |
+
|
| 715 |
+
Parameters
|
| 716 |
+
----------
|
| 717 |
+
k_xy : set
|
| 718 |
+
The set of 1-arborescences which have the minimum rate of increase
|
| 719 |
+
in the direction of ascent
|
| 720 |
+
|
| 721 |
+
d : dict
|
| 722 |
+
The direction of ascent
|
| 723 |
+
|
| 724 |
+
Returns
|
| 725 |
+
-------
|
| 726 |
+
float
|
| 727 |
+
The distance we can travel in direction `d`
|
| 728 |
+
"""
|
| 729 |
+
min_epsilon = math.inf
|
| 730 |
+
for e_u, e_v, e_w in G.edges(data=weight):
|
| 731 |
+
if (e_u, e_v) in k.edges:
|
| 732 |
+
continue
|
| 733 |
+
# Now, I have found a condition which MUST be true for the edges to
|
| 734 |
+
# be a valid substitute. The edge in the graph which is the
|
| 735 |
+
# substitute is the one with the same terminated end. This can be
|
| 736 |
+
# checked rather simply.
|
| 737 |
+
#
|
| 738 |
+
# Find the edge within k which is the substitute. Because k is a
|
| 739 |
+
# 1-arborescence, we know that they is only one such edges
|
| 740 |
+
# leading into every vertex.
|
| 741 |
+
if len(k.in_edges(e_v, data=weight)) > 1:
|
| 742 |
+
raise Exception
|
| 743 |
+
sub_u, sub_v, sub_w = next(k.in_edges(e_v, data=weight).__iter__())
|
| 744 |
+
k.add_edge(e_u, e_v, **{weight: e_w})
|
| 745 |
+
k.remove_edge(sub_u, sub_v)
|
| 746 |
+
if (
|
| 747 |
+
max(d for n, d in k.in_degree()) <= 1
|
| 748 |
+
and len(G) == k.number_of_edges()
|
| 749 |
+
and nx.is_weakly_connected(k)
|
| 750 |
+
):
|
| 751 |
+
# Ascent method calculation
|
| 752 |
+
if d[sub_u] == d[e_u] or sub_w == e_w:
|
| 753 |
+
# Revert to the original graph
|
| 754 |
+
k.remove_edge(e_u, e_v)
|
| 755 |
+
k.add_edge(sub_u, sub_v, **{weight: sub_w})
|
| 756 |
+
continue
|
| 757 |
+
epsilon = (sub_w - e_w) / (d[e_u] - d[sub_u])
|
| 758 |
+
if 0 < epsilon < min_epsilon:
|
| 759 |
+
min_epsilon = epsilon
|
| 760 |
+
# Revert to the original graph
|
| 761 |
+
k.remove_edge(e_u, e_v)
|
| 762 |
+
k.add_edge(sub_u, sub_v, **{weight: sub_w})
|
| 763 |
+
|
| 764 |
+
return min_epsilon
|
| 765 |
+
|
| 766 |
+
# I have to know that the elements in pi correspond to the correct elements
|
| 767 |
+
# in the direction of ascent, even if the node labels are not integers.
|
| 768 |
+
# Thus, I will use dictionaries to made that mapping.
|
| 769 |
+
pi_dict = {}
|
| 770 |
+
for n in G:
|
| 771 |
+
pi_dict[n] = 0
|
| 772 |
+
del n
|
| 773 |
+
original_edge_weights = {}
|
| 774 |
+
for u, v, d in G.edges(data=True):
|
| 775 |
+
original_edge_weights[(u, v)] = d[weight]
|
| 776 |
+
dir_ascent, k_d = direction_of_ascent()
|
| 777 |
+
while dir_ascent is not None:
|
| 778 |
+
max_distance = find_epsilon(k_d, dir_ascent)
|
| 779 |
+
for n, v in dir_ascent.items():
|
| 780 |
+
pi_dict[n] += max_distance * v
|
| 781 |
+
for u, v, d in G.edges(data=True):
|
| 782 |
+
d[weight] = original_edge_weights[(u, v)] + pi_dict[u]
|
| 783 |
+
dir_ascent, k_d = direction_of_ascent()
|
| 784 |
+
nx._clear_cache(G)
|
| 785 |
+
# k_d is no longer an individual 1-arborescence but rather a set of
|
| 786 |
+
# minimal 1-arborescences at the maximum point of the polytope and should
|
| 787 |
+
# be reflected as such
|
| 788 |
+
k_max = k_d
|
| 789 |
+
|
| 790 |
+
# Search for a cycle within k_max. If a cycle exists, return it as the
|
| 791 |
+
# solution
|
| 792 |
+
for k in k_max:
|
| 793 |
+
if len([n for n in k if k.degree(n) == 2]) == G.order():
|
| 794 |
+
# Tour found
|
| 795 |
+
# TODO: this branch does not restore original_edge_weights of G!
|
| 796 |
+
return k.size(weight), k
|
| 797 |
+
|
| 798 |
+
# Write the original edge weights back to G and every member of k_max at
|
| 799 |
+
# the maximum point. Also average the number of times that edge appears in
|
| 800 |
+
# the set of minimal 1-arborescences.
|
| 801 |
+
x_star = {}
|
| 802 |
+
size_k_max = len(k_max)
|
| 803 |
+
for u, v, d in G.edges(data=True):
|
| 804 |
+
edge_count = 0
|
| 805 |
+
d[weight] = original_edge_weights[(u, v)]
|
| 806 |
+
for k in k_max:
|
| 807 |
+
if (u, v) in k.edges():
|
| 808 |
+
edge_count += 1
|
| 809 |
+
k[u][v][weight] = original_edge_weights[(u, v)]
|
| 810 |
+
x_star[(u, v)] = edge_count / size_k_max
|
| 811 |
+
# Now symmetrize the edges in x_star and scale them according to (5) in
|
| 812 |
+
# reference [1]
|
| 813 |
+
z_star = {}
|
| 814 |
+
scale_factor = (G.order() - 1) / G.order()
|
| 815 |
+
for u, v in x_star:
|
| 816 |
+
frequency = x_star[(u, v)] + x_star[(v, u)]
|
| 817 |
+
if frequency > 0:
|
| 818 |
+
z_star[(u, v)] = scale_factor * frequency
|
| 819 |
+
del x_star
|
| 820 |
+
# Return the optimal weight and the z dict
|
| 821 |
+
return next(k_max.__iter__()).size(weight), z_star
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
@nx._dispatchable
|
| 825 |
+
def spanning_tree_distribution(G, z):
|
| 826 |
+
"""
|
| 827 |
+
Find the asadpour exponential distribution of spanning trees.
|
| 828 |
+
|
| 829 |
+
Solves the Maximum Entropy Convex Program in the Asadpour algorithm [1]_
|
| 830 |
+
using the approach in section 7 to build an exponential distribution of
|
| 831 |
+
undirected spanning trees.
|
| 832 |
+
|
| 833 |
+
This algorithm ensures that the probability of any edge in a spanning
|
| 834 |
+
tree is proportional to the sum of the probabilities of the tress
|
| 835 |
+
containing that edge over the sum of the probabilities of all spanning
|
| 836 |
+
trees of the graph.
|
| 837 |
+
|
| 838 |
+
Parameters
|
| 839 |
+
----------
|
| 840 |
+
G : nx.MultiGraph
|
| 841 |
+
The undirected support graph for the Held Karp relaxation
|
| 842 |
+
|
| 843 |
+
z : dict
|
| 844 |
+
The output of `held_karp_ascent()`, a scaled version of the Held-Karp
|
| 845 |
+
solution.
|
| 846 |
+
|
| 847 |
+
Returns
|
| 848 |
+
-------
|
| 849 |
+
gamma : dict
|
| 850 |
+
The probability distribution which approximately preserves the marginal
|
| 851 |
+
probabilities of `z`.
|
| 852 |
+
"""
|
| 853 |
+
from math import exp
|
| 854 |
+
from math import log as ln
|
| 855 |
+
|
| 856 |
+
def q(e):
|
| 857 |
+
"""
|
| 858 |
+
The value of q(e) is described in the Asadpour paper is "the
|
| 859 |
+
probability that edge e will be included in a spanning tree T that is
|
| 860 |
+
chosen with probability proportional to exp(gamma(T))" which
|
| 861 |
+
basically means that it is the total probability of the edge appearing
|
| 862 |
+
across the whole distribution.
|
| 863 |
+
|
| 864 |
+
Parameters
|
| 865 |
+
----------
|
| 866 |
+
e : tuple
|
| 867 |
+
The `(u, v)` tuple describing the edge we are interested in
|
| 868 |
+
|
| 869 |
+
Returns
|
| 870 |
+
-------
|
| 871 |
+
float
|
| 872 |
+
The probability that a spanning tree chosen according to the
|
| 873 |
+
current values of gamma will include edge `e`.
|
| 874 |
+
"""
|
| 875 |
+
# Create the laplacian matrices
|
| 876 |
+
for u, v, d in G.edges(data=True):
|
| 877 |
+
d[lambda_key] = exp(gamma[(u, v)])
|
| 878 |
+
G_Kirchhoff = nx.total_spanning_tree_weight(G, lambda_key)
|
| 879 |
+
G_e = nx.contracted_edge(G, e, self_loops=False)
|
| 880 |
+
G_e_Kirchhoff = nx.total_spanning_tree_weight(G_e, lambda_key)
|
| 881 |
+
|
| 882 |
+
# Multiply by the weight of the contracted edge since it is not included
|
| 883 |
+
# in the total weight of the contracted graph.
|
| 884 |
+
return exp(gamma[(e[0], e[1])]) * G_e_Kirchhoff / G_Kirchhoff
|
| 885 |
+
|
| 886 |
+
# initialize gamma to the zero dict
|
| 887 |
+
gamma = {}
|
| 888 |
+
for u, v, _ in G.edges:
|
| 889 |
+
gamma[(u, v)] = 0
|
| 890 |
+
|
| 891 |
+
# set epsilon
|
| 892 |
+
EPSILON = 0.2
|
| 893 |
+
|
| 894 |
+
# pick an edge attribute name that is unlikely to be in the graph
|
| 895 |
+
lambda_key = "spanning_tree_distribution's secret attribute name for lambda"
|
| 896 |
+
|
| 897 |
+
while True:
|
| 898 |
+
# We need to know that know that no values of q_e are greater than
|
| 899 |
+
# (1 + epsilon) * z_e, however changing one gamma value can increase the
|
| 900 |
+
# value of a different q_e, so we have to complete the for loop without
|
| 901 |
+
# changing anything for the condition to be meet
|
| 902 |
+
in_range_count = 0
|
| 903 |
+
# Search for an edge with q_e > (1 + epsilon) * z_e
|
| 904 |
+
for u, v in gamma:
|
| 905 |
+
e = (u, v)
|
| 906 |
+
q_e = q(e)
|
| 907 |
+
z_e = z[e]
|
| 908 |
+
if q_e > (1 + EPSILON) * z_e:
|
| 909 |
+
delta = ln(
|
| 910 |
+
(q_e * (1 - (1 + EPSILON / 2) * z_e))
|
| 911 |
+
/ ((1 - q_e) * (1 + EPSILON / 2) * z_e)
|
| 912 |
+
)
|
| 913 |
+
gamma[e] -= delta
|
| 914 |
+
# Check that delta had the desired effect
|
| 915 |
+
new_q_e = q(e)
|
| 916 |
+
desired_q_e = (1 + EPSILON / 2) * z_e
|
| 917 |
+
if round(new_q_e, 8) != round(desired_q_e, 8):
|
| 918 |
+
raise nx.NetworkXError(
|
| 919 |
+
f"Unable to modify probability for edge ({u}, {v})"
|
| 920 |
+
)
|
| 921 |
+
else:
|
| 922 |
+
in_range_count += 1
|
| 923 |
+
# Check if the for loop terminated without changing any gamma
|
| 924 |
+
if in_range_count == len(gamma):
|
| 925 |
+
break
|
| 926 |
+
|
| 927 |
+
# Remove the new edge attributes
|
| 928 |
+
for _, _, d in G.edges(data=True):
|
| 929 |
+
if lambda_key in d:
|
| 930 |
+
del d[lambda_key]
|
| 931 |
+
|
| 932 |
+
return gamma
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 936 |
+
def greedy_tsp(G, weight="weight", source=None):
|
| 937 |
+
"""Return a low cost cycle starting at `source` and its cost.
|
| 938 |
+
|
| 939 |
+
This approximates a solution to the traveling salesman problem.
|
| 940 |
+
It finds a cycle of all the nodes that a salesman can visit in order
|
| 941 |
+
to visit many nodes while minimizing total distance.
|
| 942 |
+
It uses a simple greedy algorithm.
|
| 943 |
+
In essence, this function returns a large cycle given a source point
|
| 944 |
+
for which the total cost of the cycle is minimized.
|
| 945 |
+
|
| 946 |
+
Parameters
|
| 947 |
+
----------
|
| 948 |
+
G : Graph
|
| 949 |
+
The Graph should be a complete weighted undirected graph.
|
| 950 |
+
The distance between all pairs of nodes should be included.
|
| 951 |
+
|
| 952 |
+
weight : string, optional (default="weight")
|
| 953 |
+
Edge data key corresponding to the edge weight.
|
| 954 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 955 |
+
|
| 956 |
+
source : node, optional (default: first node in list(G))
|
| 957 |
+
Starting node. If None, defaults to ``next(iter(G))``
|
| 958 |
+
|
| 959 |
+
Returns
|
| 960 |
+
-------
|
| 961 |
+
cycle : list of nodes
|
| 962 |
+
Returns the cycle (list of nodes) that a salesman
|
| 963 |
+
can follow to minimize total weight of the trip.
|
| 964 |
+
|
| 965 |
+
Raises
|
| 966 |
+
------
|
| 967 |
+
NetworkXError
|
| 968 |
+
If `G` is not complete, the algorithm raises an exception.
|
| 969 |
+
|
| 970 |
+
Examples
|
| 971 |
+
--------
|
| 972 |
+
>>> from networkx.algorithms import approximation as approx
|
| 973 |
+
>>> G = nx.DiGraph()
|
| 974 |
+
>>> G.add_weighted_edges_from(
|
| 975 |
+
... {
|
| 976 |
+
... ("A", "B", 3),
|
| 977 |
+
... ("A", "C", 17),
|
| 978 |
+
... ("A", "D", 14),
|
| 979 |
+
... ("B", "A", 3),
|
| 980 |
+
... ("B", "C", 12),
|
| 981 |
+
... ("B", "D", 16),
|
| 982 |
+
... ("C", "A", 13),
|
| 983 |
+
... ("C", "B", 12),
|
| 984 |
+
... ("C", "D", 4),
|
| 985 |
+
... ("D", "A", 14),
|
| 986 |
+
... ("D", "B", 15),
|
| 987 |
+
... ("D", "C", 2),
|
| 988 |
+
... }
|
| 989 |
+
... )
|
| 990 |
+
>>> cycle = approx.greedy_tsp(G, source="D")
|
| 991 |
+
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
|
| 992 |
+
>>> cycle
|
| 993 |
+
['D', 'C', 'B', 'A', 'D']
|
| 994 |
+
>>> cost
|
| 995 |
+
31
|
| 996 |
+
|
| 997 |
+
Notes
|
| 998 |
+
-----
|
| 999 |
+
This implementation of a greedy algorithm is based on the following:
|
| 1000 |
+
|
| 1001 |
+
- The algorithm adds a node to the solution at every iteration.
|
| 1002 |
+
- The algorithm selects a node not already in the cycle whose connection
|
| 1003 |
+
to the previous node adds the least cost to the cycle.
|
| 1004 |
+
|
| 1005 |
+
A greedy algorithm does not always give the best solution.
|
| 1006 |
+
However, it can construct a first feasible solution which can
|
| 1007 |
+
be passed as a parameter to an iterative improvement algorithm such
|
| 1008 |
+
as Simulated Annealing, or Threshold Accepting.
|
| 1009 |
+
|
| 1010 |
+
Time complexity: It has a running time $O(|V|^2)$
|
| 1011 |
+
"""
|
| 1012 |
+
# Check that G is a complete graph
|
| 1013 |
+
N = len(G) - 1
|
| 1014 |
+
# This check ignores selfloops which is what we want here.
|
| 1015 |
+
if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
|
| 1016 |
+
raise nx.NetworkXError("G must be a complete graph.")
|
| 1017 |
+
|
| 1018 |
+
if source is None:
|
| 1019 |
+
source = nx.utils.arbitrary_element(G)
|
| 1020 |
+
|
| 1021 |
+
if G.number_of_nodes() == 2:
|
| 1022 |
+
neighbor = next(G.neighbors(source))
|
| 1023 |
+
return [source, neighbor, source]
|
| 1024 |
+
|
| 1025 |
+
nodeset = set(G)
|
| 1026 |
+
nodeset.remove(source)
|
| 1027 |
+
cycle = [source]
|
| 1028 |
+
next_node = source
|
| 1029 |
+
while nodeset:
|
| 1030 |
+
nbrdict = G[next_node]
|
| 1031 |
+
next_node = min(nodeset, key=lambda n: nbrdict[n].get(weight, 1))
|
| 1032 |
+
cycle.append(next_node)
|
| 1033 |
+
nodeset.remove(next_node)
|
| 1034 |
+
cycle.append(cycle[0])
|
| 1035 |
+
return cycle
|
| 1036 |
+
|
| 1037 |
+
|
| 1038 |
+
@py_random_state(9)
|
| 1039 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1040 |
+
def simulated_annealing_tsp(
|
| 1041 |
+
G,
|
| 1042 |
+
init_cycle,
|
| 1043 |
+
weight="weight",
|
| 1044 |
+
source=None,
|
| 1045 |
+
temp=100,
|
| 1046 |
+
move="1-1",
|
| 1047 |
+
max_iterations=10,
|
| 1048 |
+
N_inner=100,
|
| 1049 |
+
alpha=0.01,
|
| 1050 |
+
seed=None,
|
| 1051 |
+
):
|
| 1052 |
+
"""Returns an approximate solution to the traveling salesman problem.
|
| 1053 |
+
|
| 1054 |
+
This function uses simulated annealing to approximate the minimal cost
|
| 1055 |
+
cycle through the nodes. Starting from a suboptimal solution, simulated
|
| 1056 |
+
annealing perturbs that solution, occasionally accepting changes that make
|
| 1057 |
+
the solution worse to escape from a locally optimal solution. The chance
|
| 1058 |
+
of accepting such changes decreases over the iterations to encourage
|
| 1059 |
+
an optimal result. In summary, the function returns a cycle starting
|
| 1060 |
+
at `source` for which the total cost is minimized. It also returns the cost.
|
| 1061 |
+
|
| 1062 |
+
The chance of accepting a proposed change is related to a parameter called
|
| 1063 |
+
the temperature (annealing has a physical analogue of steel hardening
|
| 1064 |
+
as it cools). As the temperature is reduced, the chance of moves that
|
| 1065 |
+
increase cost goes down.
|
| 1066 |
+
|
| 1067 |
+
Parameters
|
| 1068 |
+
----------
|
| 1069 |
+
G : Graph
|
| 1070 |
+
`G` should be a complete weighted graph.
|
| 1071 |
+
The distance between all pairs of nodes should be included.
|
| 1072 |
+
|
| 1073 |
+
init_cycle : list of all nodes or "greedy"
|
| 1074 |
+
The initial solution (a cycle through all nodes returning to the start).
|
| 1075 |
+
This argument has no default to make you think about it.
|
| 1076 |
+
If "greedy", use `greedy_tsp(G, weight)`.
|
| 1077 |
+
Other common starting cycles are `list(G) + [next(iter(G))]` or the final
|
| 1078 |
+
result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.
|
| 1079 |
+
|
| 1080 |
+
weight : string, optional (default="weight")
|
| 1081 |
+
Edge data key corresponding to the edge weight.
|
| 1082 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 1083 |
+
|
| 1084 |
+
source : node, optional (default: first node in list(G))
|
| 1085 |
+
Starting node. If None, defaults to ``next(iter(G))``
|
| 1086 |
+
|
| 1087 |
+
temp : int, optional (default=100)
|
| 1088 |
+
The algorithm's temperature parameter. It represents the initial
|
| 1089 |
+
value of temperature
|
| 1090 |
+
|
| 1091 |
+
move : "1-1" or "1-0" or function, optional (default="1-1")
|
| 1092 |
+
Indicator of what move to use when finding new trial solutions.
|
| 1093 |
+
Strings indicate two special built-in moves:
|
| 1094 |
+
|
| 1095 |
+
- "1-1": 1-1 exchange which transposes the position
|
| 1096 |
+
of two elements of the current solution.
|
| 1097 |
+
The function called is :func:`swap_two_nodes`.
|
| 1098 |
+
For example if we apply 1-1 exchange in the solution
|
| 1099 |
+
``A = [3, 2, 1, 4, 3]``
|
| 1100 |
+
we can get the following by the transposition of 1 and 4 elements:
|
| 1101 |
+
``A' = [3, 2, 4, 1, 3]``
|
| 1102 |
+
- "1-0": 1-0 exchange which moves an node in the solution
|
| 1103 |
+
to a new position.
|
| 1104 |
+
The function called is :func:`move_one_node`.
|
| 1105 |
+
For example if we apply 1-0 exchange in the solution
|
| 1106 |
+
``A = [3, 2, 1, 4, 3]``
|
| 1107 |
+
we can transfer the fourth element to the second position:
|
| 1108 |
+
``A' = [3, 4, 2, 1, 3]``
|
| 1109 |
+
|
| 1110 |
+
You may provide your own functions to enact a move from
|
| 1111 |
+
one solution to a neighbor solution. The function must take
|
| 1112 |
+
the solution as input along with a `seed` input to control
|
| 1113 |
+
random number generation (see the `seed` input here).
|
| 1114 |
+
Your function should maintain the solution as a cycle with
|
| 1115 |
+
equal first and last node and all others appearing once.
|
| 1116 |
+
Your function should return the new solution.
|
| 1117 |
+
|
| 1118 |
+
max_iterations : int, optional (default=10)
|
| 1119 |
+
Declared done when this number of consecutive iterations of
|
| 1120 |
+
the outer loop occurs without any change in the best cost solution.
|
| 1121 |
+
|
| 1122 |
+
N_inner : int, optional (default=100)
|
| 1123 |
+
The number of iterations of the inner loop.
|
| 1124 |
+
|
| 1125 |
+
alpha : float between (0, 1), optional (default=0.01)
|
| 1126 |
+
Percentage of temperature decrease in each iteration
|
| 1127 |
+
of outer loop
|
| 1128 |
+
|
| 1129 |
+
seed : integer, random_state, or None (default)
|
| 1130 |
+
Indicator of random number generation state.
|
| 1131 |
+
See :ref:`Randomness<randomness>`.
|
| 1132 |
+
|
| 1133 |
+
Returns
|
| 1134 |
+
-------
|
| 1135 |
+
cycle : list of nodes
|
| 1136 |
+
Returns the cycle (list of nodes) that a salesman
|
| 1137 |
+
can follow to minimize total weight of the trip.
|
| 1138 |
+
|
| 1139 |
+
Raises
|
| 1140 |
+
------
|
| 1141 |
+
NetworkXError
|
| 1142 |
+
If `G` is not complete the algorithm raises an exception.
|
| 1143 |
+
|
| 1144 |
+
Examples
|
| 1145 |
+
--------
|
| 1146 |
+
>>> from networkx.algorithms import approximation as approx
|
| 1147 |
+
>>> G = nx.DiGraph()
|
| 1148 |
+
>>> G.add_weighted_edges_from(
|
| 1149 |
+
... {
|
| 1150 |
+
... ("A", "B", 3),
|
| 1151 |
+
... ("A", "C", 17),
|
| 1152 |
+
... ("A", "D", 14),
|
| 1153 |
+
... ("B", "A", 3),
|
| 1154 |
+
... ("B", "C", 12),
|
| 1155 |
+
... ("B", "D", 16),
|
| 1156 |
+
... ("C", "A", 13),
|
| 1157 |
+
... ("C", "B", 12),
|
| 1158 |
+
... ("C", "D", 4),
|
| 1159 |
+
... ("D", "A", 14),
|
| 1160 |
+
... ("D", "B", 15),
|
| 1161 |
+
... ("D", "C", 2),
|
| 1162 |
+
... }
|
| 1163 |
+
... )
|
| 1164 |
+
>>> cycle = approx.simulated_annealing_tsp(G, "greedy", source="D")
|
| 1165 |
+
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
|
| 1166 |
+
>>> cycle
|
| 1167 |
+
['D', 'C', 'B', 'A', 'D']
|
| 1168 |
+
>>> cost
|
| 1169 |
+
31
|
| 1170 |
+
>>> incycle = ["D", "B", "A", "C", "D"]
|
| 1171 |
+
>>> cycle = approx.simulated_annealing_tsp(G, incycle, source="D")
|
| 1172 |
+
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
|
| 1173 |
+
>>> cycle
|
| 1174 |
+
['D', 'C', 'B', 'A', 'D']
|
| 1175 |
+
>>> cost
|
| 1176 |
+
31
|
| 1177 |
+
|
| 1178 |
+
Notes
|
| 1179 |
+
-----
|
| 1180 |
+
Simulated Annealing is a metaheuristic local search algorithm.
|
| 1181 |
+
The main characteristic of this algorithm is that it accepts
|
| 1182 |
+
even solutions which lead to the increase of the cost in order
|
| 1183 |
+
to escape from low quality local optimal solutions.
|
| 1184 |
+
|
| 1185 |
+
This algorithm needs an initial solution. If not provided, it is
|
| 1186 |
+
constructed by a simple greedy algorithm. At every iteration, the
|
| 1187 |
+
algorithm selects thoughtfully a neighbor solution.
|
| 1188 |
+
Consider $c(x)$ cost of current solution and $c(x')$ cost of a
|
| 1189 |
+
neighbor solution.
|
| 1190 |
+
If $c(x') - c(x) <= 0$ then the neighbor solution becomes the current
|
| 1191 |
+
solution for the next iteration. Otherwise, the algorithm accepts
|
| 1192 |
+
the neighbor solution with probability $p = exp - ([c(x') - c(x)] / temp)$.
|
| 1193 |
+
Otherwise the current solution is retained.
|
| 1194 |
+
|
| 1195 |
+
`temp` is a parameter of the algorithm and represents temperature.
|
| 1196 |
+
|
| 1197 |
+
Time complexity:
|
| 1198 |
+
For $N_i$ iterations of the inner loop and $N_o$ iterations of the
|
| 1199 |
+
outer loop, this algorithm has running time $O(N_i * N_o * |V|)$.
|
| 1200 |
+
|
| 1201 |
+
For more information and how the algorithm is inspired see:
|
| 1202 |
+
http://en.wikipedia.org/wiki/Simulated_annealing
|
| 1203 |
+
"""
|
| 1204 |
+
if move == "1-1":
|
| 1205 |
+
move = swap_two_nodes
|
| 1206 |
+
elif move == "1-0":
|
| 1207 |
+
move = move_one_node
|
| 1208 |
+
if init_cycle == "greedy":
|
| 1209 |
+
# Construct an initial solution using a greedy algorithm.
|
| 1210 |
+
cycle = greedy_tsp(G, weight=weight, source=source)
|
| 1211 |
+
if G.number_of_nodes() == 2:
|
| 1212 |
+
return cycle
|
| 1213 |
+
|
| 1214 |
+
else:
|
| 1215 |
+
cycle = list(init_cycle)
|
| 1216 |
+
if source is None:
|
| 1217 |
+
source = cycle[0]
|
| 1218 |
+
elif source != cycle[0]:
|
| 1219 |
+
raise nx.NetworkXError("source must be first node in init_cycle")
|
| 1220 |
+
if cycle[0] != cycle[-1]:
|
| 1221 |
+
raise nx.NetworkXError("init_cycle must be a cycle. (return to start)")
|
| 1222 |
+
|
| 1223 |
+
if len(cycle) - 1 != len(G) or len(set(G.nbunch_iter(cycle))) != len(G):
|
| 1224 |
+
raise nx.NetworkXError("init_cycle should be a cycle over all nodes in G.")
|
| 1225 |
+
|
| 1226 |
+
# Check that G is a complete graph
|
| 1227 |
+
N = len(G) - 1
|
| 1228 |
+
# This check ignores selfloops which is what we want here.
|
| 1229 |
+
if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
|
| 1230 |
+
raise nx.NetworkXError("G must be a complete graph.")
|
| 1231 |
+
|
| 1232 |
+
if G.number_of_nodes() == 2:
|
| 1233 |
+
neighbor = next(G.neighbors(source))
|
| 1234 |
+
return [source, neighbor, source]
|
| 1235 |
+
|
| 1236 |
+
# Find the cost of initial solution
|
| 1237 |
+
cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(cycle))
|
| 1238 |
+
|
| 1239 |
+
count = 0
|
| 1240 |
+
best_cycle = cycle.copy()
|
| 1241 |
+
best_cost = cost
|
| 1242 |
+
while count <= max_iterations and temp > 0:
|
| 1243 |
+
count += 1
|
| 1244 |
+
for i in range(N_inner):
|
| 1245 |
+
adj_sol = move(cycle, seed)
|
| 1246 |
+
adj_cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(adj_sol))
|
| 1247 |
+
delta = adj_cost - cost
|
| 1248 |
+
if delta <= 0:
|
| 1249 |
+
# Set current solution the adjacent solution.
|
| 1250 |
+
cycle = adj_sol
|
| 1251 |
+
cost = adj_cost
|
| 1252 |
+
|
| 1253 |
+
if cost < best_cost:
|
| 1254 |
+
count = 0
|
| 1255 |
+
best_cycle = cycle.copy()
|
| 1256 |
+
best_cost = cost
|
| 1257 |
+
else:
|
| 1258 |
+
# Accept even a worse solution with probability p.
|
| 1259 |
+
p = math.exp(-delta / temp)
|
| 1260 |
+
if p >= seed.random():
|
| 1261 |
+
cycle = adj_sol
|
| 1262 |
+
cost = adj_cost
|
| 1263 |
+
temp -= temp * alpha
|
| 1264 |
+
|
| 1265 |
+
return best_cycle
|
| 1266 |
+
|
| 1267 |
+
|
| 1268 |
+
@py_random_state(9)
|
| 1269 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1270 |
+
def threshold_accepting_tsp(
|
| 1271 |
+
G,
|
| 1272 |
+
init_cycle,
|
| 1273 |
+
weight="weight",
|
| 1274 |
+
source=None,
|
| 1275 |
+
threshold=1,
|
| 1276 |
+
move="1-1",
|
| 1277 |
+
max_iterations=10,
|
| 1278 |
+
N_inner=100,
|
| 1279 |
+
alpha=0.1,
|
| 1280 |
+
seed=None,
|
| 1281 |
+
):
|
| 1282 |
+
"""Returns an approximate solution to the traveling salesman problem.
|
| 1283 |
+
|
| 1284 |
+
This function uses threshold accepting methods to approximate the minimal cost
|
| 1285 |
+
cycle through the nodes. Starting from a suboptimal solution, threshold
|
| 1286 |
+
accepting methods perturb that solution, accepting any changes that make
|
| 1287 |
+
the solution no worse than increasing by a threshold amount. Improvements
|
| 1288 |
+
in cost are accepted, but so are changes leading to small increases in cost.
|
| 1289 |
+
This allows the solution to leave suboptimal local minima in solution space.
|
| 1290 |
+
The threshold is decreased slowly as iterations proceed helping to ensure
|
| 1291 |
+
an optimum. In summary, the function returns a cycle starting at `source`
|
| 1292 |
+
for which the total cost is minimized.
|
| 1293 |
+
|
| 1294 |
+
Parameters
|
| 1295 |
+
----------
|
| 1296 |
+
G : Graph
|
| 1297 |
+
`G` should be a complete weighted graph.
|
| 1298 |
+
The distance between all pairs of nodes should be included.
|
| 1299 |
+
|
| 1300 |
+
init_cycle : list or "greedy"
|
| 1301 |
+
The initial solution (a cycle through all nodes returning to the start).
|
| 1302 |
+
This argument has no default to make you think about it.
|
| 1303 |
+
If "greedy", use `greedy_tsp(G, weight)`.
|
| 1304 |
+
Other common starting cycles are `list(G) + [next(iter(G))]` or the final
|
| 1305 |
+
result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.
|
| 1306 |
+
|
| 1307 |
+
weight : string, optional (default="weight")
|
| 1308 |
+
Edge data key corresponding to the edge weight.
|
| 1309 |
+
If any edge does not have this attribute the weight is set to 1.
|
| 1310 |
+
|
| 1311 |
+
source : node, optional (default: first node in list(G))
|
| 1312 |
+
Starting node. If None, defaults to ``next(iter(G))``
|
| 1313 |
+
|
| 1314 |
+
threshold : int, optional (default=1)
|
| 1315 |
+
The algorithm's threshold parameter. It represents the initial
|
| 1316 |
+
threshold's value
|
| 1317 |
+
|
| 1318 |
+
move : "1-1" or "1-0" or function, optional (default="1-1")
|
| 1319 |
+
Indicator of what move to use when finding new trial solutions.
|
| 1320 |
+
Strings indicate two special built-in moves:
|
| 1321 |
+
|
| 1322 |
+
- "1-1": 1-1 exchange which transposes the position
|
| 1323 |
+
of two elements of the current solution.
|
| 1324 |
+
The function called is :func:`swap_two_nodes`.
|
| 1325 |
+
For example if we apply 1-1 exchange in the solution
|
| 1326 |
+
``A = [3, 2, 1, 4, 3]``
|
| 1327 |
+
we can get the following by the transposition of 1 and 4 elements:
|
| 1328 |
+
``A' = [3, 2, 4, 1, 3]``
|
| 1329 |
+
- "1-0": 1-0 exchange which moves an node in the solution
|
| 1330 |
+
to a new position.
|
| 1331 |
+
The function called is :func:`move_one_node`.
|
| 1332 |
+
For example if we apply 1-0 exchange in the solution
|
| 1333 |
+
``A = [3, 2, 1, 4, 3]``
|
| 1334 |
+
we can transfer the fourth element to the second position:
|
| 1335 |
+
``A' = [3, 4, 2, 1, 3]``
|
| 1336 |
+
|
| 1337 |
+
You may provide your own functions to enact a move from
|
| 1338 |
+
one solution to a neighbor solution. The function must take
|
| 1339 |
+
the solution as input along with a `seed` input to control
|
| 1340 |
+
random number generation (see the `seed` input here).
|
| 1341 |
+
Your function should maintain the solution as a cycle with
|
| 1342 |
+
equal first and last node and all others appearing once.
|
| 1343 |
+
Your function should return the new solution.
|
| 1344 |
+
|
| 1345 |
+
max_iterations : int, optional (default=10)
|
| 1346 |
+
Declared done when this number of consecutive iterations of
|
| 1347 |
+
the outer loop occurs without any change in the best cost solution.
|
| 1348 |
+
|
| 1349 |
+
N_inner : int, optional (default=100)
|
| 1350 |
+
The number of iterations of the inner loop.
|
| 1351 |
+
|
| 1352 |
+
alpha : float between (0, 1), optional (default=0.1)
|
| 1353 |
+
Percentage of threshold decrease when there is at
|
| 1354 |
+
least one acceptance of a neighbor solution.
|
| 1355 |
+
If no inner loop moves are accepted the threshold remains unchanged.
|
| 1356 |
+
|
| 1357 |
+
seed : integer, random_state, or None (default)
|
| 1358 |
+
Indicator of random number generation state.
|
| 1359 |
+
See :ref:`Randomness<randomness>`.
|
| 1360 |
+
|
| 1361 |
+
Returns
|
| 1362 |
+
-------
|
| 1363 |
+
cycle : list of nodes
|
| 1364 |
+
Returns the cycle (list of nodes) that a salesman
|
| 1365 |
+
can follow to minimize total weight of the trip.
|
| 1366 |
+
|
| 1367 |
+
Raises
|
| 1368 |
+
------
|
| 1369 |
+
NetworkXError
|
| 1370 |
+
If `G` is not complete the algorithm raises an exception.
|
| 1371 |
+
|
| 1372 |
+
Examples
|
| 1373 |
+
--------
|
| 1374 |
+
>>> from networkx.algorithms import approximation as approx
|
| 1375 |
+
>>> G = nx.DiGraph()
|
| 1376 |
+
>>> G.add_weighted_edges_from(
|
| 1377 |
+
... {
|
| 1378 |
+
... ("A", "B", 3),
|
| 1379 |
+
... ("A", "C", 17),
|
| 1380 |
+
... ("A", "D", 14),
|
| 1381 |
+
... ("B", "A", 3),
|
| 1382 |
+
... ("B", "C", 12),
|
| 1383 |
+
... ("B", "D", 16),
|
| 1384 |
+
... ("C", "A", 13),
|
| 1385 |
+
... ("C", "B", 12),
|
| 1386 |
+
... ("C", "D", 4),
|
| 1387 |
+
... ("D", "A", 14),
|
| 1388 |
+
... ("D", "B", 15),
|
| 1389 |
+
... ("D", "C", 2),
|
| 1390 |
+
... }
|
| 1391 |
+
... )
|
| 1392 |
+
>>> cycle = approx.threshold_accepting_tsp(G, "greedy", source="D")
|
| 1393 |
+
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
|
| 1394 |
+
>>> cycle
|
| 1395 |
+
['D', 'C', 'B', 'A', 'D']
|
| 1396 |
+
>>> cost
|
| 1397 |
+
31
|
| 1398 |
+
>>> incycle = ["D", "B", "A", "C", "D"]
|
| 1399 |
+
>>> cycle = approx.threshold_accepting_tsp(G, incycle, source="D")
|
| 1400 |
+
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
|
| 1401 |
+
>>> cycle
|
| 1402 |
+
['D', 'C', 'B', 'A', 'D']
|
| 1403 |
+
>>> cost
|
| 1404 |
+
31
|
| 1405 |
+
|
| 1406 |
+
Notes
|
| 1407 |
+
-----
|
| 1408 |
+
Threshold Accepting is a metaheuristic local search algorithm.
|
| 1409 |
+
The main characteristic of this algorithm is that it accepts
|
| 1410 |
+
even solutions which lead to the increase of the cost in order
|
| 1411 |
+
to escape from low quality local optimal solutions.
|
| 1412 |
+
|
| 1413 |
+
This algorithm needs an initial solution. This solution can be
|
| 1414 |
+
constructed by a simple greedy algorithm. At every iteration, it
|
| 1415 |
+
selects thoughtfully a neighbor solution.
|
| 1416 |
+
Consider $c(x)$ cost of current solution and $c(x')$ cost of
|
| 1417 |
+
neighbor solution.
|
| 1418 |
+
If $c(x') - c(x) <= threshold$ then the neighbor solution becomes the current
|
| 1419 |
+
solution for the next iteration, where the threshold is named threshold.
|
| 1420 |
+
|
| 1421 |
+
In comparison to the Simulated Annealing algorithm, the Threshold
|
| 1422 |
+
Accepting algorithm does not accept very low quality solutions
|
| 1423 |
+
(due to the presence of the threshold value). In the case of
|
| 1424 |
+
Simulated Annealing, even a very low quality solution can
|
| 1425 |
+
be accepted with probability $p$.
|
| 1426 |
+
|
| 1427 |
+
Time complexity:
|
| 1428 |
+
It has a running time $O(m * n * |V|)$ where $m$ and $n$ are the number
|
| 1429 |
+
of times the outer and inner loop run respectively.
|
| 1430 |
+
|
| 1431 |
+
For more information and how algorithm is inspired see:
|
| 1432 |
+
https://doi.org/10.1016/0021-9991(90)90201-B
|
| 1433 |
+
|
| 1434 |
+
See Also
|
| 1435 |
+
--------
|
| 1436 |
+
simulated_annealing_tsp
|
| 1437 |
+
|
| 1438 |
+
"""
|
| 1439 |
+
if move == "1-1":
|
| 1440 |
+
move = swap_two_nodes
|
| 1441 |
+
elif move == "1-0":
|
| 1442 |
+
move = move_one_node
|
| 1443 |
+
if init_cycle == "greedy":
|
| 1444 |
+
# Construct an initial solution using a greedy algorithm.
|
| 1445 |
+
cycle = greedy_tsp(G, weight=weight, source=source)
|
| 1446 |
+
if G.number_of_nodes() == 2:
|
| 1447 |
+
return cycle
|
| 1448 |
+
|
| 1449 |
+
else:
|
| 1450 |
+
cycle = list(init_cycle)
|
| 1451 |
+
if source is None:
|
| 1452 |
+
source = cycle[0]
|
| 1453 |
+
elif source != cycle[0]:
|
| 1454 |
+
raise nx.NetworkXError("source must be first node in init_cycle")
|
| 1455 |
+
if cycle[0] != cycle[-1]:
|
| 1456 |
+
raise nx.NetworkXError("init_cycle must be a cycle. (return to start)")
|
| 1457 |
+
|
| 1458 |
+
if len(cycle) - 1 != len(G) or len(set(G.nbunch_iter(cycle))) != len(G):
|
| 1459 |
+
raise nx.NetworkXError("init_cycle is not all and only nodes.")
|
| 1460 |
+
|
| 1461 |
+
# Check that G is a complete graph
|
| 1462 |
+
N = len(G) - 1
|
| 1463 |
+
# This check ignores selfloops which is what we want here.
|
| 1464 |
+
if any(len(nbrdict) - (n in nbrdict) != N for n, nbrdict in G.adj.items()):
|
| 1465 |
+
raise nx.NetworkXError("G must be a complete graph.")
|
| 1466 |
+
|
| 1467 |
+
if G.number_of_nodes() == 2:
|
| 1468 |
+
neighbor = list(G.neighbors(source))[0]
|
| 1469 |
+
return [source, neighbor, source]
|
| 1470 |
+
|
| 1471 |
+
# Find the cost of initial solution
|
| 1472 |
+
cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(cycle))
|
| 1473 |
+
|
| 1474 |
+
count = 0
|
| 1475 |
+
best_cycle = cycle.copy()
|
| 1476 |
+
best_cost = cost
|
| 1477 |
+
while count <= max_iterations:
|
| 1478 |
+
count += 1
|
| 1479 |
+
accepted = False
|
| 1480 |
+
for i in range(N_inner):
|
| 1481 |
+
adj_sol = move(cycle, seed)
|
| 1482 |
+
adj_cost = sum(G[u][v].get(weight, 1) for u, v in pairwise(adj_sol))
|
| 1483 |
+
delta = adj_cost - cost
|
| 1484 |
+
if delta <= threshold:
|
| 1485 |
+
accepted = True
|
| 1486 |
+
|
| 1487 |
+
# Set current solution the adjacent solution.
|
| 1488 |
+
cycle = adj_sol
|
| 1489 |
+
cost = adj_cost
|
| 1490 |
+
|
| 1491 |
+
if cost < best_cost:
|
| 1492 |
+
count = 0
|
| 1493 |
+
best_cycle = cycle.copy()
|
| 1494 |
+
best_cost = cost
|
| 1495 |
+
if accepted:
|
| 1496 |
+
threshold -= threshold * alpha
|
| 1497 |
+
|
| 1498 |
+
return best_cycle
|
parrot/lib/python3.10/site-packages/networkx/algorithms/approximation/treewidth.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
@nx._dispatchable(returns_graph=True)
|
| 45 |
+
def treewidth_min_degree(G):
|
| 46 |
+
"""Returns a treewidth decomposition using the Minimum Degree heuristic.
|
| 47 |
+
|
| 48 |
+
The heuristic chooses the nodes according to their degree, i.e., first
|
| 49 |
+
the node with the lowest degree is chosen, then the graph is updated
|
| 50 |
+
and the corresponding node is removed. Next, a new node with the lowest
|
| 51 |
+
degree is chosen, and so on.
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
G : NetworkX graph
|
| 56 |
+
|
| 57 |
+
Returns
|
| 58 |
+
-------
|
| 59 |
+
Treewidth decomposition : (int, Graph) tuple
|
| 60 |
+
2-tuple with treewidth and the corresponding decomposed tree.
|
| 61 |
+
"""
|
| 62 |
+
deg_heuristic = MinDegreeHeuristic(G)
|
| 63 |
+
return treewidth_decomp(G, lambda graph: deg_heuristic.best_node(graph))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@not_implemented_for("directed")
|
| 67 |
+
@not_implemented_for("multigraph")
|
| 68 |
+
@nx._dispatchable(returns_graph=True)
|
| 69 |
+
def treewidth_min_fill_in(G):
|
| 70 |
+
"""Returns a treewidth decomposition using the Minimum Fill-in heuristic.
|
| 71 |
+
|
| 72 |
+
The heuristic chooses a node from the graph, where the number of edges
|
| 73 |
+
added turning the neighborhood of the chosen node into clique is as
|
| 74 |
+
small as possible.
|
| 75 |
+
|
| 76 |
+
Parameters
|
| 77 |
+
----------
|
| 78 |
+
G : NetworkX graph
|
| 79 |
+
|
| 80 |
+
Returns
|
| 81 |
+
-------
|
| 82 |
+
Treewidth decomposition : (int, Graph) tuple
|
| 83 |
+
2-tuple with treewidth and the corresponding decomposed tree.
|
| 84 |
+
"""
|
| 85 |
+
return treewidth_decomp(G, min_fill_in_heuristic)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class MinDegreeHeuristic:
|
| 89 |
+
"""Implements the Minimum Degree heuristic.
|
| 90 |
+
|
| 91 |
+
The heuristic chooses the nodes according to their degree
|
| 92 |
+
(number of neighbors), i.e., first the node with the lowest degree is
|
| 93 |
+
chosen, then the graph is updated and the corresponding node is
|
| 94 |
+
removed. Next, a new node with the lowest degree is chosen, and so on.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, graph):
|
| 98 |
+
self._graph = graph
|
| 99 |
+
|
| 100 |
+
# nodes that have to be updated in the heap before each iteration
|
| 101 |
+
self._update_nodes = []
|
| 102 |
+
|
| 103 |
+
self._degreeq = [] # a heapq with 3-tuples (degree,unique_id,node)
|
| 104 |
+
self.count = itertools.count()
|
| 105 |
+
|
| 106 |
+
# build heap with initial degrees
|
| 107 |
+
for n in graph:
|
| 108 |
+
self._degreeq.append((len(graph[n]), next(self.count), n))
|
| 109 |
+
heapify(self._degreeq)
|
| 110 |
+
|
| 111 |
+
def best_node(self, graph):
|
| 112 |
+
# update nodes in self._update_nodes
|
| 113 |
+
for n in self._update_nodes:
|
| 114 |
+
# insert changed degrees into degreeq
|
| 115 |
+
heappush(self._degreeq, (len(graph[n]), next(self.count), n))
|
| 116 |
+
|
| 117 |
+
# get the next valid (minimum degree) node
|
| 118 |
+
while self._degreeq:
|
| 119 |
+
(min_degree, _, elim_node) = heappop(self._degreeq)
|
| 120 |
+
if elim_node not in graph or len(graph[elim_node]) != min_degree:
|
| 121 |
+
# outdated entry in degreeq
|
| 122 |
+
continue
|
| 123 |
+
elif min_degree == len(graph) - 1:
|
| 124 |
+
# fully connected: abort condition
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
# remember to update nodes in the heap before getting the next node
|
| 128 |
+
self._update_nodes = graph[elim_node]
|
| 129 |
+
return elim_node
|
| 130 |
+
|
| 131 |
+
# the heap is empty: abort
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def min_fill_in_heuristic(graph):
|
| 136 |
+
"""Implements the Minimum Degree heuristic.
|
| 137 |
+
|
| 138 |
+
Returns the node from the graph, where the number of edges added when
|
| 139 |
+
turning the neighborhood of the chosen node into clique is as small as
|
| 140 |
+
possible. This algorithm chooses the nodes using the Minimum Fill-In
|
| 141 |
+
heuristic. The running time of the algorithm is :math:`O(V^3)` and it uses
|
| 142 |
+
additional constant memory."""
|
| 143 |
+
|
| 144 |
+
if len(graph) == 0:
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
min_fill_in_node = None
|
| 148 |
+
|
| 149 |
+
min_fill_in = sys.maxsize
|
| 150 |
+
|
| 151 |
+
# sort nodes by degree
|
| 152 |
+
nodes_by_degree = sorted(graph, key=lambda x: len(graph[x]))
|
| 153 |
+
min_degree = len(graph[nodes_by_degree[0]])
|
| 154 |
+
|
| 155 |
+
# abort condition (handle complete graph)
|
| 156 |
+
if min_degree == len(graph) - 1:
|
| 157 |
+
return None
|
| 158 |
+
|
| 159 |
+
for node in nodes_by_degree:
|
| 160 |
+
num_fill_in = 0
|
| 161 |
+
nbrs = graph[node]
|
| 162 |
+
for nbr in nbrs:
|
| 163 |
+
# count how many nodes in nbrs current nbr is not connected to
|
| 164 |
+
# subtract 1 for the node itself
|
| 165 |
+
num_fill_in += len(nbrs - graph[nbr]) - 1
|
| 166 |
+
if num_fill_in >= 2 * min_fill_in:
|
| 167 |
+
break
|
| 168 |
+
|
| 169 |
+
num_fill_in /= 2 # divide by 2 because of double counting
|
| 170 |
+
|
| 171 |
+
if num_fill_in < min_fill_in: # update min-fill-in node
|
| 172 |
+
if num_fill_in == 0:
|
| 173 |
+
return node
|
| 174 |
+
min_fill_in = num_fill_in
|
| 175 |
+
min_fill_in_node = node
|
| 176 |
+
|
| 177 |
+
return min_fill_in_node
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@nx._dispatchable(returns_graph=True)
|
| 181 |
+
def treewidth_decomp(G, heuristic=min_fill_in_heuristic):
|
| 182 |
+
"""Returns a treewidth decomposition using the passed heuristic.
|
| 183 |
+
|
| 184 |
+
Parameters
|
| 185 |
+
----------
|
| 186 |
+
G : NetworkX graph
|
| 187 |
+
heuristic : heuristic function
|
| 188 |
+
|
| 189 |
+
Returns
|
| 190 |
+
-------
|
| 191 |
+
Treewidth decomposition : (int, Graph) tuple
|
| 192 |
+
2-tuple with treewidth and the corresponding decomposed tree.
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
# make dict-of-sets structure
|
| 196 |
+
graph = {n: set(G[n]) - {n} for n in G}
|
| 197 |
+
|
| 198 |
+
# stack containing nodes and neighbors in the order from the heuristic
|
| 199 |
+
node_stack = []
|
| 200 |
+
|
| 201 |
+
# get first node from heuristic
|
| 202 |
+
elim_node = heuristic(graph)
|
| 203 |
+
while elim_node is not None:
|
| 204 |
+
# connect all neighbors with each other
|
| 205 |
+
nbrs = graph[elim_node]
|
| 206 |
+
for u, v in itertools.permutations(nbrs, 2):
|
| 207 |
+
if v not in graph[u]:
|
| 208 |
+
graph[u].add(v)
|
| 209 |
+
|
| 210 |
+
# push node and its current neighbors on stack
|
| 211 |
+
node_stack.append((elim_node, nbrs))
|
| 212 |
+
|
| 213 |
+
# remove node from graph
|
| 214 |
+
for u in graph[elim_node]:
|
| 215 |
+
graph[u].remove(elim_node)
|
| 216 |
+
|
| 217 |
+
del graph[elim_node]
|
| 218 |
+
elim_node = heuristic(graph)
|
| 219 |
+
|
| 220 |
+
# the abort condition is met; put all remaining nodes into one bag
|
| 221 |
+
decomp = nx.Graph()
|
| 222 |
+
first_bag = frozenset(graph.keys())
|
| 223 |
+
decomp.add_node(first_bag)
|
| 224 |
+
|
| 225 |
+
treewidth = len(first_bag) - 1
|
| 226 |
+
|
| 227 |
+
while node_stack:
|
| 228 |
+
# get node and its neighbors from the stack
|
| 229 |
+
(curr_node, nbrs) = node_stack.pop()
|
| 230 |
+
|
| 231 |
+
# find a bag all neighbors are in
|
| 232 |
+
old_bag = None
|
| 233 |
+
for bag in decomp.nodes:
|
| 234 |
+
if nbrs <= bag:
|
| 235 |
+
old_bag = bag
|
| 236 |
+
break
|
| 237 |
+
|
| 238 |
+
if old_bag is None:
|
| 239 |
+
# no old_bag was found: just connect to the first_bag
|
| 240 |
+
old_bag = first_bag
|
| 241 |
+
|
| 242 |
+
# create new node for decomposition
|
| 243 |
+
nbrs.add(curr_node)
|
| 244 |
+
new_bag = frozenset(nbrs)
|
| 245 |
+
|
| 246 |
+
# update treewidth
|
| 247 |
+
treewidth = max(treewidth, len(new_bag) - 1)
|
| 248 |
+
|
| 249 |
+
# add edge to decomposition (implicitly also adds the new node)
|
| 250 |
+
decomp.add_edge(old_bag, new_bag)
|
| 251 |
+
|
| 252 |
+
return treewidth, decomp
|
parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.34 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/divisive.cpython-310.pyc
ADDED
|
Binary file (5.61 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/louvain.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/community/__pycache__/modularity_max.cpython-310.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (302 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/__pycache__/hits_alg.cpython-310.pyc
ADDED
|
Binary file (9.7 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/__pycache__/pagerank_alg.cpython-310.pyc
ADDED
|
Binary file (16.3 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/hits_alg.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hubs and authorities analysis of graph structure.
|
| 2 |
+
"""
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["hits"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
|
| 9 |
+
def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True):
|
| 10 |
+
"""Returns HITS hubs and authorities values for nodes.
|
| 11 |
+
|
| 12 |
+
The HITS algorithm computes two numbers for a node.
|
| 13 |
+
Authorities estimates the node value based on the incoming links.
|
| 14 |
+
Hubs estimates the node value based on outgoing links.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
G : graph
|
| 19 |
+
A NetworkX graph
|
| 20 |
+
|
| 21 |
+
max_iter : integer, optional
|
| 22 |
+
Maximum number of iterations in power method.
|
| 23 |
+
|
| 24 |
+
tol : float, optional
|
| 25 |
+
Error tolerance used to check convergence in power method iteration.
|
| 26 |
+
|
| 27 |
+
nstart : dictionary, optional
|
| 28 |
+
Starting value of each node for power method iteration.
|
| 29 |
+
|
| 30 |
+
normalized : bool (default=True)
|
| 31 |
+
Normalize results by the sum of all of the values.
|
| 32 |
+
|
| 33 |
+
Returns
|
| 34 |
+
-------
|
| 35 |
+
(hubs,authorities) : two-tuple of dictionaries
|
| 36 |
+
Two dictionaries keyed by node containing the hub and authority
|
| 37 |
+
values.
|
| 38 |
+
|
| 39 |
+
Raises
|
| 40 |
+
------
|
| 41 |
+
PowerIterationFailedConvergence
|
| 42 |
+
If the algorithm fails to converge to the specified tolerance
|
| 43 |
+
within the specified number of iterations of the power iteration
|
| 44 |
+
method.
|
| 45 |
+
|
| 46 |
+
Examples
|
| 47 |
+
--------
|
| 48 |
+
>>> G = nx.path_graph(4)
|
| 49 |
+
>>> h, a = nx.hits(G)
|
| 50 |
+
|
| 51 |
+
Notes
|
| 52 |
+
-----
|
| 53 |
+
The eigenvector calculation is done by the power iteration method
|
| 54 |
+
and has no guarantee of convergence. The iteration will stop
|
| 55 |
+
after max_iter iterations or an error tolerance of
|
| 56 |
+
number_of_nodes(G)*tol has been reached.
|
| 57 |
+
|
| 58 |
+
The HITS algorithm was designed for directed graphs but this
|
| 59 |
+
algorithm does not check if the input graph is directed and will
|
| 60 |
+
execute on undirected graphs.
|
| 61 |
+
|
| 62 |
+
References
|
| 63 |
+
----------
|
| 64 |
+
.. [1] A. Langville and C. Meyer,
|
| 65 |
+
"A survey of eigenvector methods of web information retrieval."
|
| 66 |
+
http://citeseer.ist.psu.edu/713792.html
|
| 67 |
+
.. [2] Jon Kleinberg,
|
| 68 |
+
Authoritative sources in a hyperlinked environment
|
| 69 |
+
Journal of the ACM 46 (5): 604-32, 1999.
|
| 70 |
+
doi:10.1145/324133.324140.
|
| 71 |
+
http://www.cs.cornell.edu/home/kleinber/auth.pdf.
|
| 72 |
+
"""
|
| 73 |
+
import numpy as np
|
| 74 |
+
import scipy as sp
|
| 75 |
+
|
| 76 |
+
if len(G) == 0:
|
| 77 |
+
return {}, {}
|
| 78 |
+
A = nx.adjacency_matrix(G, nodelist=list(G), dtype=float)
|
| 79 |
+
|
| 80 |
+
if nstart is not None:
|
| 81 |
+
nstart = np.array(list(nstart.values()))
|
| 82 |
+
if max_iter <= 0:
|
| 83 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 84 |
+
try:
|
| 85 |
+
_, _, vt = sp.sparse.linalg.svds(A, k=1, v0=nstart, maxiter=max_iter, tol=tol)
|
| 86 |
+
except sp.sparse.linalg.ArpackNoConvergence as exc:
|
| 87 |
+
raise nx.PowerIterationFailedConvergence(max_iter) from exc
|
| 88 |
+
|
| 89 |
+
a = vt.flatten().real
|
| 90 |
+
h = A @ a
|
| 91 |
+
if normalized:
|
| 92 |
+
h /= h.sum()
|
| 93 |
+
a /= a.sum()
|
| 94 |
+
hubs = dict(zip(G, map(float, h)))
|
| 95 |
+
authorities = dict(zip(G, map(float, a)))
|
| 96 |
+
return hubs, authorities
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _hits_python(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True):
|
| 100 |
+
if isinstance(G, nx.MultiGraph | nx.MultiDiGraph):
|
| 101 |
+
raise Exception("hits() not defined for graphs with multiedges.")
|
| 102 |
+
if len(G) == 0:
|
| 103 |
+
return {}, {}
|
| 104 |
+
# choose fixed starting vector if not given
|
| 105 |
+
if nstart is None:
|
| 106 |
+
h = dict.fromkeys(G, 1.0 / G.number_of_nodes())
|
| 107 |
+
else:
|
| 108 |
+
h = nstart
|
| 109 |
+
# normalize starting vector
|
| 110 |
+
s = 1.0 / sum(h.values())
|
| 111 |
+
for k in h:
|
| 112 |
+
h[k] *= s
|
| 113 |
+
for _ in range(max_iter): # power iteration: make up to max_iter iterations
|
| 114 |
+
hlast = h
|
| 115 |
+
h = dict.fromkeys(hlast.keys(), 0)
|
| 116 |
+
a = dict.fromkeys(hlast.keys(), 0)
|
| 117 |
+
# this "matrix multiply" looks odd because it is
|
| 118 |
+
# doing a left multiply a^T=hlast^T*G
|
| 119 |
+
for n in h:
|
| 120 |
+
for nbr in G[n]:
|
| 121 |
+
a[nbr] += hlast[n] * G[n][nbr].get("weight", 1)
|
| 122 |
+
# now multiply h=Ga
|
| 123 |
+
for n in h:
|
| 124 |
+
for nbr in G[n]:
|
| 125 |
+
h[n] += a[nbr] * G[n][nbr].get("weight", 1)
|
| 126 |
+
# normalize vector
|
| 127 |
+
s = 1.0 / max(h.values())
|
| 128 |
+
for n in h:
|
| 129 |
+
h[n] *= s
|
| 130 |
+
# normalize vector
|
| 131 |
+
s = 1.0 / max(a.values())
|
| 132 |
+
for n in a:
|
| 133 |
+
a[n] *= s
|
| 134 |
+
# check convergence, l1 norm
|
| 135 |
+
err = sum(abs(h[n] - hlast[n]) for n in h)
|
| 136 |
+
if err < tol:
|
| 137 |
+
break
|
| 138 |
+
else:
|
| 139 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 140 |
+
if normalized:
|
| 141 |
+
s = 1.0 / sum(a.values())
|
| 142 |
+
for n in a:
|
| 143 |
+
a[n] *= s
|
| 144 |
+
s = 1.0 / sum(h.values())
|
| 145 |
+
for n in h:
|
| 146 |
+
h[n] *= s
|
| 147 |
+
return h, a
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _hits_numpy(G, normalized=True):
|
| 151 |
+
"""Returns HITS hubs and authorities values for nodes.
|
| 152 |
+
|
| 153 |
+
The HITS algorithm computes two numbers for a node.
|
| 154 |
+
Authorities estimates the node value based on the incoming links.
|
| 155 |
+
Hubs estimates the node value based on outgoing links.
|
| 156 |
+
|
| 157 |
+
Parameters
|
| 158 |
+
----------
|
| 159 |
+
G : graph
|
| 160 |
+
A NetworkX graph
|
| 161 |
+
|
| 162 |
+
normalized : bool (default=True)
|
| 163 |
+
Normalize results by the sum of all of the values.
|
| 164 |
+
|
| 165 |
+
Returns
|
| 166 |
+
-------
|
| 167 |
+
(hubs,authorities) : two-tuple of dictionaries
|
| 168 |
+
Two dictionaries keyed by node containing the hub and authority
|
| 169 |
+
values.
|
| 170 |
+
|
| 171 |
+
Examples
|
| 172 |
+
--------
|
| 173 |
+
>>> G = nx.path_graph(4)
|
| 174 |
+
|
| 175 |
+
The `hubs` and `authorities` are given by the eigenvectors corresponding to the
|
| 176 |
+
maximum eigenvalues of the hubs_matrix and the authority_matrix, respectively.
|
| 177 |
+
|
| 178 |
+
The ``hubs`` and ``authority`` matrices are computed from the adjacency
|
| 179 |
+
matrix:
|
| 180 |
+
|
| 181 |
+
>>> adj_ary = nx.to_numpy_array(G)
|
| 182 |
+
>>> hubs_matrix = adj_ary @ adj_ary.T
|
| 183 |
+
>>> authority_matrix = adj_ary.T @ adj_ary
|
| 184 |
+
|
| 185 |
+
`_hits_numpy` maps the eigenvector corresponding to the maximum eigenvalue
|
| 186 |
+
of the respective matrices to the nodes in `G`:
|
| 187 |
+
|
| 188 |
+
>>> from networkx.algorithms.link_analysis.hits_alg import _hits_numpy
|
| 189 |
+
>>> hubs, authority = _hits_numpy(G)
|
| 190 |
+
|
| 191 |
+
Notes
|
| 192 |
+
-----
|
| 193 |
+
The eigenvector calculation uses NumPy's interface to LAPACK.
|
| 194 |
+
|
| 195 |
+
The HITS algorithm was designed for directed graphs but this
|
| 196 |
+
algorithm does not check if the input graph is directed and will
|
| 197 |
+
execute on undirected graphs.
|
| 198 |
+
|
| 199 |
+
References
|
| 200 |
+
----------
|
| 201 |
+
.. [1] A. Langville and C. Meyer,
|
| 202 |
+
"A survey of eigenvector methods of web information retrieval."
|
| 203 |
+
http://citeseer.ist.psu.edu/713792.html
|
| 204 |
+
.. [2] Jon Kleinberg,
|
| 205 |
+
Authoritative sources in a hyperlinked environment
|
| 206 |
+
Journal of the ACM 46 (5): 604-32, 1999.
|
| 207 |
+
doi:10.1145/324133.324140.
|
| 208 |
+
http://www.cs.cornell.edu/home/kleinber/auth.pdf.
|
| 209 |
+
"""
|
| 210 |
+
import numpy as np
|
| 211 |
+
|
| 212 |
+
if len(G) == 0:
|
| 213 |
+
return {}, {}
|
| 214 |
+
adj_ary = nx.to_numpy_array(G)
|
| 215 |
+
# Hub matrix
|
| 216 |
+
H = adj_ary @ adj_ary.T
|
| 217 |
+
e, ev = np.linalg.eig(H)
|
| 218 |
+
h = ev[:, np.argmax(e)] # eigenvector corresponding to the maximum eigenvalue
|
| 219 |
+
# Authority matrix
|
| 220 |
+
A = adj_ary.T @ adj_ary
|
| 221 |
+
e, ev = np.linalg.eig(A)
|
| 222 |
+
a = ev[:, np.argmax(e)] # eigenvector corresponding to the maximum eigenvalue
|
| 223 |
+
if normalized:
|
| 224 |
+
h /= h.sum()
|
| 225 |
+
a /= a.sum()
|
| 226 |
+
else:
|
| 227 |
+
h /= h.max()
|
| 228 |
+
a /= a.max()
|
| 229 |
+
hubs = dict(zip(G, map(float, h)))
|
| 230 |
+
authorities = dict(zip(G, map(float, a)))
|
| 231 |
+
return hubs, authorities
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _hits_scipy(G, max_iter=100, tol=1.0e-6, nstart=None, normalized=True):
|
| 235 |
+
"""Returns HITS hubs and authorities values for nodes.
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
The HITS algorithm computes two numbers for a node.
|
| 239 |
+
Authorities estimates the node value based on the incoming links.
|
| 240 |
+
Hubs estimates the node value based on outgoing links.
|
| 241 |
+
|
| 242 |
+
Parameters
|
| 243 |
+
----------
|
| 244 |
+
G : graph
|
| 245 |
+
A NetworkX graph
|
| 246 |
+
|
| 247 |
+
max_iter : integer, optional
|
| 248 |
+
Maximum number of iterations in power method.
|
| 249 |
+
|
| 250 |
+
tol : float, optional
|
| 251 |
+
Error tolerance used to check convergence in power method iteration.
|
| 252 |
+
|
| 253 |
+
nstart : dictionary, optional
|
| 254 |
+
Starting value of each node for power method iteration.
|
| 255 |
+
|
| 256 |
+
normalized : bool (default=True)
|
| 257 |
+
Normalize results by the sum of all of the values.
|
| 258 |
+
|
| 259 |
+
Returns
|
| 260 |
+
-------
|
| 261 |
+
(hubs,authorities) : two-tuple of dictionaries
|
| 262 |
+
Two dictionaries keyed by node containing the hub and authority
|
| 263 |
+
values.
|
| 264 |
+
|
| 265 |
+
Examples
|
| 266 |
+
--------
|
| 267 |
+
>>> from networkx.algorithms.link_analysis.hits_alg import _hits_scipy
|
| 268 |
+
>>> G = nx.path_graph(4)
|
| 269 |
+
>>> h, a = _hits_scipy(G)
|
| 270 |
+
|
| 271 |
+
Notes
|
| 272 |
+
-----
|
| 273 |
+
This implementation uses SciPy sparse matrices.
|
| 274 |
+
|
| 275 |
+
The eigenvector calculation is done by the power iteration method
|
| 276 |
+
and has no guarantee of convergence. The iteration will stop
|
| 277 |
+
after max_iter iterations or an error tolerance of
|
| 278 |
+
number_of_nodes(G)*tol has been reached.
|
| 279 |
+
|
| 280 |
+
The HITS algorithm was designed for directed graphs but this
|
| 281 |
+
algorithm does not check if the input graph is directed and will
|
| 282 |
+
execute on undirected graphs.
|
| 283 |
+
|
| 284 |
+
Raises
|
| 285 |
+
------
|
| 286 |
+
PowerIterationFailedConvergence
|
| 287 |
+
If the algorithm fails to converge to the specified tolerance
|
| 288 |
+
within the specified number of iterations of the power iteration
|
| 289 |
+
method.
|
| 290 |
+
|
| 291 |
+
References
|
| 292 |
+
----------
|
| 293 |
+
.. [1] A. Langville and C. Meyer,
|
| 294 |
+
"A survey of eigenvector methods of web information retrieval."
|
| 295 |
+
http://citeseer.ist.psu.edu/713792.html
|
| 296 |
+
.. [2] Jon Kleinberg,
|
| 297 |
+
Authoritative sources in a hyperlinked environment
|
| 298 |
+
Journal of the ACM 46 (5): 604-632, 1999.
|
| 299 |
+
doi:10.1145/324133.324140.
|
| 300 |
+
http://www.cs.cornell.edu/home/kleinber/auth.pdf.
|
| 301 |
+
"""
|
| 302 |
+
import numpy as np
|
| 303 |
+
|
| 304 |
+
if len(G) == 0:
|
| 305 |
+
return {}, {}
|
| 306 |
+
A = nx.to_scipy_sparse_array(G, nodelist=list(G))
|
| 307 |
+
(n, _) = A.shape # should be square
|
| 308 |
+
ATA = A.T @ A # authority matrix
|
| 309 |
+
# choose fixed starting vector if not given
|
| 310 |
+
if nstart is None:
|
| 311 |
+
x = np.ones((n, 1)) / n
|
| 312 |
+
else:
|
| 313 |
+
x = np.array([nstart.get(n, 0) for n in list(G)], dtype=float)
|
| 314 |
+
x /= x.sum()
|
| 315 |
+
|
| 316 |
+
# power iteration on authority matrix
|
| 317 |
+
i = 0
|
| 318 |
+
while True:
|
| 319 |
+
xlast = x
|
| 320 |
+
x = ATA @ x
|
| 321 |
+
x /= x.max()
|
| 322 |
+
# check convergence, l1 norm
|
| 323 |
+
err = np.absolute(x - xlast).sum()
|
| 324 |
+
if err < tol:
|
| 325 |
+
break
|
| 326 |
+
if i > max_iter:
|
| 327 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 328 |
+
i += 1
|
| 329 |
+
|
| 330 |
+
a = x.flatten()
|
| 331 |
+
h = A @ a
|
| 332 |
+
if normalized:
|
| 333 |
+
h /= h.sum()
|
| 334 |
+
a /= a.sum()
|
| 335 |
+
hubs = dict(zip(G, map(float, h)))
|
| 336 |
+
authorities = dict(zip(G, map(float, a)))
|
| 337 |
+
return hubs, authorities
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/pagerank_alg.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PageRank analysis of graph structure. """
|
| 2 |
+
from warnings import warn
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
__all__ = ["pagerank", "google_matrix"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 10 |
+
def pagerank(
|
| 11 |
+
G,
|
| 12 |
+
alpha=0.85,
|
| 13 |
+
personalization=None,
|
| 14 |
+
max_iter=100,
|
| 15 |
+
tol=1.0e-6,
|
| 16 |
+
nstart=None,
|
| 17 |
+
weight="weight",
|
| 18 |
+
dangling=None,
|
| 19 |
+
):
|
| 20 |
+
"""Returns the PageRank of the nodes in the graph.
|
| 21 |
+
|
| 22 |
+
PageRank computes a ranking of the nodes in the graph G based on
|
| 23 |
+
the structure of the incoming links. It was originally designed as
|
| 24 |
+
an algorithm to rank web pages.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
G : graph
|
| 29 |
+
A NetworkX graph. Undirected graphs will be converted to a directed
|
| 30 |
+
graph with two directed edges for each undirected edge.
|
| 31 |
+
|
| 32 |
+
alpha : float, optional
|
| 33 |
+
Damping parameter for PageRank, default=0.85.
|
| 34 |
+
|
| 35 |
+
personalization: dict, optional
|
| 36 |
+
The "personalization vector" consisting of a dictionary with a
|
| 37 |
+
key some subset of graph nodes and personalization value each of those.
|
| 38 |
+
At least one personalization value must be non-zero.
|
| 39 |
+
If not specified, a nodes personalization value will be zero.
|
| 40 |
+
By default, a uniform distribution is used.
|
| 41 |
+
|
| 42 |
+
max_iter : integer, optional
|
| 43 |
+
Maximum number of iterations in power method eigenvalue solver.
|
| 44 |
+
|
| 45 |
+
tol : float, optional
|
| 46 |
+
Error tolerance used to check convergence in power method solver.
|
| 47 |
+
The iteration will stop after a tolerance of ``len(G) * tol`` is reached.
|
| 48 |
+
|
| 49 |
+
nstart : dictionary, optional
|
| 50 |
+
Starting value of PageRank iteration for each node.
|
| 51 |
+
|
| 52 |
+
weight : key, optional
|
| 53 |
+
Edge data key to use as weight. If None weights are set to 1.
|
| 54 |
+
|
| 55 |
+
dangling: dict, optional
|
| 56 |
+
The outedges to be assigned to any "dangling" nodes, i.e., nodes without
|
| 57 |
+
any outedges. The dict key is the node the outedge points to and the dict
|
| 58 |
+
value is the weight of that outedge. By default, dangling nodes are given
|
| 59 |
+
outedges according to the personalization vector (uniform if not
|
| 60 |
+
specified). This must be selected to result in an irreducible transition
|
| 61 |
+
matrix (see notes under google_matrix). It may be common to have the
|
| 62 |
+
dangling dict to be the same as the personalization dict.
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
Returns
|
| 66 |
+
-------
|
| 67 |
+
pagerank : dictionary
|
| 68 |
+
Dictionary of nodes with PageRank as value
|
| 69 |
+
|
| 70 |
+
Examples
|
| 71 |
+
--------
|
| 72 |
+
>>> G = nx.DiGraph(nx.path_graph(4))
|
| 73 |
+
>>> pr = nx.pagerank(G, alpha=0.9)
|
| 74 |
+
|
| 75 |
+
Notes
|
| 76 |
+
-----
|
| 77 |
+
The eigenvector calculation is done by the power iteration method
|
| 78 |
+
and has no guarantee of convergence. The iteration will stop after
|
| 79 |
+
an error tolerance of ``len(G) * tol`` has been reached. If the
|
| 80 |
+
number of iterations exceed `max_iter`, a
|
| 81 |
+
:exc:`networkx.exception.PowerIterationFailedConvergence` exception
|
| 82 |
+
is raised.
|
| 83 |
+
|
| 84 |
+
The PageRank algorithm was designed for directed graphs but this
|
| 85 |
+
algorithm does not check if the input graph is directed and will
|
| 86 |
+
execute on undirected graphs by converting each edge in the
|
| 87 |
+
directed graph to two edges.
|
| 88 |
+
|
| 89 |
+
See Also
|
| 90 |
+
--------
|
| 91 |
+
google_matrix
|
| 92 |
+
|
| 93 |
+
Raises
|
| 94 |
+
------
|
| 95 |
+
PowerIterationFailedConvergence
|
| 96 |
+
If the algorithm fails to converge to the specified tolerance
|
| 97 |
+
within the specified number of iterations of the power iteration
|
| 98 |
+
method.
|
| 99 |
+
|
| 100 |
+
References
|
| 101 |
+
----------
|
| 102 |
+
.. [1] A. Langville and C. Meyer,
|
| 103 |
+
"A survey of eigenvector methods of web information retrieval."
|
| 104 |
+
http://citeseer.ist.psu.edu/713792.html
|
| 105 |
+
.. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
|
| 106 |
+
The PageRank citation ranking: Bringing order to the Web. 1999
|
| 107 |
+
http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
return _pagerank_scipy(
|
| 111 |
+
G, alpha, personalization, max_iter, tol, nstart, weight, dangling
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _pagerank_python(
|
| 116 |
+
G,
|
| 117 |
+
alpha=0.85,
|
| 118 |
+
personalization=None,
|
| 119 |
+
max_iter=100,
|
| 120 |
+
tol=1.0e-6,
|
| 121 |
+
nstart=None,
|
| 122 |
+
weight="weight",
|
| 123 |
+
dangling=None,
|
| 124 |
+
):
|
| 125 |
+
if len(G) == 0:
|
| 126 |
+
return {}
|
| 127 |
+
|
| 128 |
+
D = G.to_directed()
|
| 129 |
+
|
| 130 |
+
# Create a copy in (right) stochastic form
|
| 131 |
+
W = nx.stochastic_graph(D, weight=weight)
|
| 132 |
+
N = W.number_of_nodes()
|
| 133 |
+
|
| 134 |
+
# Choose fixed starting vector if not given
|
| 135 |
+
if nstart is None:
|
| 136 |
+
x = dict.fromkeys(W, 1.0 / N)
|
| 137 |
+
else:
|
| 138 |
+
# Normalized nstart vector
|
| 139 |
+
s = sum(nstart.values())
|
| 140 |
+
x = {k: v / s for k, v in nstart.items()}
|
| 141 |
+
|
| 142 |
+
if personalization is None:
|
| 143 |
+
# Assign uniform personalization vector if not given
|
| 144 |
+
p = dict.fromkeys(W, 1.0 / N)
|
| 145 |
+
else:
|
| 146 |
+
s = sum(personalization.values())
|
| 147 |
+
p = {k: v / s for k, v in personalization.items()}
|
| 148 |
+
|
| 149 |
+
if dangling is None:
|
| 150 |
+
# Use personalization vector if dangling vector not specified
|
| 151 |
+
dangling_weights = p
|
| 152 |
+
else:
|
| 153 |
+
s = sum(dangling.values())
|
| 154 |
+
dangling_weights = {k: v / s for k, v in dangling.items()}
|
| 155 |
+
dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0]
|
| 156 |
+
|
| 157 |
+
# power iteration: make up to max_iter iterations
|
| 158 |
+
for _ in range(max_iter):
|
| 159 |
+
xlast = x
|
| 160 |
+
x = dict.fromkeys(xlast.keys(), 0)
|
| 161 |
+
danglesum = alpha * sum(xlast[n] for n in dangling_nodes)
|
| 162 |
+
for n in x:
|
| 163 |
+
# this matrix multiply looks odd because it is
|
| 164 |
+
# doing a left multiply x^T=xlast^T*W
|
| 165 |
+
for _, nbr, wt in W.edges(n, data=weight):
|
| 166 |
+
x[nbr] += alpha * xlast[n] * wt
|
| 167 |
+
x[n] += danglesum * dangling_weights.get(n, 0) + (1.0 - alpha) * p.get(n, 0)
|
| 168 |
+
# check convergence, l1 norm
|
| 169 |
+
err = sum(abs(x[n] - xlast[n]) for n in x)
|
| 170 |
+
if err < N * tol:
|
| 171 |
+
return x
|
| 172 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 176 |
+
def google_matrix(
|
| 177 |
+
G, alpha=0.85, personalization=None, nodelist=None, weight="weight", dangling=None
|
| 178 |
+
):
|
| 179 |
+
"""Returns the Google matrix of the graph.
|
| 180 |
+
|
| 181 |
+
Parameters
|
| 182 |
+
----------
|
| 183 |
+
G : graph
|
| 184 |
+
A NetworkX graph. Undirected graphs will be converted to a directed
|
| 185 |
+
graph with two directed edges for each undirected edge.
|
| 186 |
+
|
| 187 |
+
alpha : float
|
| 188 |
+
The damping factor.
|
| 189 |
+
|
| 190 |
+
personalization: dict, optional
|
| 191 |
+
The "personalization vector" consisting of a dictionary with a
|
| 192 |
+
key some subset of graph nodes and personalization value each of those.
|
| 193 |
+
At least one personalization value must be non-zero.
|
| 194 |
+
If not specified, a nodes personalization value will be zero.
|
| 195 |
+
By default, a uniform distribution is used.
|
| 196 |
+
|
| 197 |
+
nodelist : list, optional
|
| 198 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
| 199 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
| 200 |
+
|
| 201 |
+
weight : key, optional
|
| 202 |
+
Edge data key to use as weight. If None weights are set to 1.
|
| 203 |
+
|
| 204 |
+
dangling: dict, optional
|
| 205 |
+
The outedges to be assigned to any "dangling" nodes, i.e., nodes without
|
| 206 |
+
any outedges. The dict key is the node the outedge points to and the dict
|
| 207 |
+
value is the weight of that outedge. By default, dangling nodes are given
|
| 208 |
+
outedges according to the personalization vector (uniform if not
|
| 209 |
+
specified) This must be selected to result in an irreducible transition
|
| 210 |
+
matrix (see notes below). It may be common to have the dangling dict to
|
| 211 |
+
be the same as the personalization dict.
|
| 212 |
+
|
| 213 |
+
Returns
|
| 214 |
+
-------
|
| 215 |
+
A : 2D NumPy ndarray
|
| 216 |
+
Google matrix of the graph
|
| 217 |
+
|
| 218 |
+
Notes
|
| 219 |
+
-----
|
| 220 |
+
The array returned represents the transition matrix that describes the
|
| 221 |
+
Markov chain used in PageRank. For PageRank to converge to a unique
|
| 222 |
+
solution (i.e., a unique stationary distribution in a Markov chain), the
|
| 223 |
+
transition matrix must be irreducible. In other words, it must be that
|
| 224 |
+
there exists a path between every pair of nodes in the graph, or else there
|
| 225 |
+
is the potential of "rank sinks."
|
| 226 |
+
|
| 227 |
+
This implementation works with Multi(Di)Graphs. For multigraphs the
|
| 228 |
+
weight between two nodes is set to be the sum of all edge weights
|
| 229 |
+
between those nodes.
|
| 230 |
+
|
| 231 |
+
See Also
|
| 232 |
+
--------
|
| 233 |
+
pagerank
|
| 234 |
+
"""
|
| 235 |
+
import numpy as np
|
| 236 |
+
|
| 237 |
+
if nodelist is None:
|
| 238 |
+
nodelist = list(G)
|
| 239 |
+
|
| 240 |
+
A = nx.to_numpy_array(G, nodelist=nodelist, weight=weight)
|
| 241 |
+
N = len(G)
|
| 242 |
+
if N == 0:
|
| 243 |
+
return A
|
| 244 |
+
|
| 245 |
+
# Personalization vector
|
| 246 |
+
if personalization is None:
|
| 247 |
+
p = np.repeat(1.0 / N, N)
|
| 248 |
+
else:
|
| 249 |
+
p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float)
|
| 250 |
+
if p.sum() == 0:
|
| 251 |
+
raise ZeroDivisionError
|
| 252 |
+
p /= p.sum()
|
| 253 |
+
|
| 254 |
+
# Dangling nodes
|
| 255 |
+
if dangling is None:
|
| 256 |
+
dangling_weights = p
|
| 257 |
+
else:
|
| 258 |
+
# Convert the dangling dictionary into an array in nodelist order
|
| 259 |
+
dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float)
|
| 260 |
+
dangling_weights /= dangling_weights.sum()
|
| 261 |
+
dangling_nodes = np.where(A.sum(axis=1) == 0)[0]
|
| 262 |
+
|
| 263 |
+
# Assign dangling_weights to any dangling nodes (nodes with no out links)
|
| 264 |
+
A[dangling_nodes] = dangling_weights
|
| 265 |
+
|
| 266 |
+
A /= A.sum(axis=1)[:, np.newaxis] # Normalize rows to sum to 1
|
| 267 |
+
|
| 268 |
+
return alpha * A + (1 - alpha) * p
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _pagerank_numpy(
|
| 272 |
+
G, alpha=0.85, personalization=None, weight="weight", dangling=None
|
| 273 |
+
):
|
| 274 |
+
"""Returns the PageRank of the nodes in the graph.
|
| 275 |
+
|
| 276 |
+
PageRank computes a ranking of the nodes in the graph G based on
|
| 277 |
+
the structure of the incoming links. It was originally designed as
|
| 278 |
+
an algorithm to rank web pages.
|
| 279 |
+
|
| 280 |
+
Parameters
|
| 281 |
+
----------
|
| 282 |
+
G : graph
|
| 283 |
+
A NetworkX graph. Undirected graphs will be converted to a directed
|
| 284 |
+
graph with two directed edges for each undirected edge.
|
| 285 |
+
|
| 286 |
+
alpha : float, optional
|
| 287 |
+
Damping parameter for PageRank, default=0.85.
|
| 288 |
+
|
| 289 |
+
personalization: dict, optional
|
| 290 |
+
The "personalization vector" consisting of a dictionary with a
|
| 291 |
+
key some subset of graph nodes and personalization value each of those.
|
| 292 |
+
At least one personalization value must be non-zero.
|
| 293 |
+
If not specified, a nodes personalization value will be zero.
|
| 294 |
+
By default, a uniform distribution is used.
|
| 295 |
+
|
| 296 |
+
weight : key, optional
|
| 297 |
+
Edge data key to use as weight. If None weights are set to 1.
|
| 298 |
+
|
| 299 |
+
dangling: dict, optional
|
| 300 |
+
The outedges to be assigned to any "dangling" nodes, i.e., nodes without
|
| 301 |
+
any outedges. The dict key is the node the outedge points to and the dict
|
| 302 |
+
value is the weight of that outedge. By default, dangling nodes are given
|
| 303 |
+
outedges according to the personalization vector (uniform if not
|
| 304 |
+
specified) This must be selected to result in an irreducible transition
|
| 305 |
+
matrix (see notes under google_matrix). It may be common to have the
|
| 306 |
+
dangling dict to be the same as the personalization dict.
|
| 307 |
+
|
| 308 |
+
Returns
|
| 309 |
+
-------
|
| 310 |
+
pagerank : dictionary
|
| 311 |
+
Dictionary of nodes with PageRank as value.
|
| 312 |
+
|
| 313 |
+
Examples
|
| 314 |
+
--------
|
| 315 |
+
>>> from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_numpy
|
| 316 |
+
>>> G = nx.DiGraph(nx.path_graph(4))
|
| 317 |
+
>>> pr = _pagerank_numpy(G, alpha=0.9)
|
| 318 |
+
|
| 319 |
+
Notes
|
| 320 |
+
-----
|
| 321 |
+
The eigenvector calculation uses NumPy's interface to the LAPACK
|
| 322 |
+
eigenvalue solvers. This will be the fastest and most accurate
|
| 323 |
+
for small graphs.
|
| 324 |
+
|
| 325 |
+
This implementation works with Multi(Di)Graphs. For multigraphs the
|
| 326 |
+
weight between two nodes is set to be the sum of all edge weights
|
| 327 |
+
between those nodes.
|
| 328 |
+
|
| 329 |
+
See Also
|
| 330 |
+
--------
|
| 331 |
+
pagerank, google_matrix
|
| 332 |
+
|
| 333 |
+
References
|
| 334 |
+
----------
|
| 335 |
+
.. [1] A. Langville and C. Meyer,
|
| 336 |
+
"A survey of eigenvector methods of web information retrieval."
|
| 337 |
+
http://citeseer.ist.psu.edu/713792.html
|
| 338 |
+
.. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
|
| 339 |
+
The PageRank citation ranking: Bringing order to the Web. 1999
|
| 340 |
+
http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
|
| 341 |
+
"""
|
| 342 |
+
import numpy as np
|
| 343 |
+
|
| 344 |
+
if len(G) == 0:
|
| 345 |
+
return {}
|
| 346 |
+
M = google_matrix(
|
| 347 |
+
G, alpha, personalization=personalization, weight=weight, dangling=dangling
|
| 348 |
+
)
|
| 349 |
+
# use numpy LAPACK solver
|
| 350 |
+
eigenvalues, eigenvectors = np.linalg.eig(M.T)
|
| 351 |
+
ind = np.argmax(eigenvalues)
|
| 352 |
+
# eigenvector of largest eigenvalue is at ind, normalized
|
| 353 |
+
largest = np.array(eigenvectors[:, ind]).flatten().real
|
| 354 |
+
norm = largest.sum()
|
| 355 |
+
return dict(zip(G, map(float, largest / norm)))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _pagerank_scipy(
|
| 359 |
+
G,
|
| 360 |
+
alpha=0.85,
|
| 361 |
+
personalization=None,
|
| 362 |
+
max_iter=100,
|
| 363 |
+
tol=1.0e-6,
|
| 364 |
+
nstart=None,
|
| 365 |
+
weight="weight",
|
| 366 |
+
dangling=None,
|
| 367 |
+
):
|
| 368 |
+
"""Returns the PageRank of the nodes in the graph.
|
| 369 |
+
|
| 370 |
+
PageRank computes a ranking of the nodes in the graph G based on
|
| 371 |
+
the structure of the incoming links. It was originally designed as
|
| 372 |
+
an algorithm to rank web pages.
|
| 373 |
+
|
| 374 |
+
Parameters
|
| 375 |
+
----------
|
| 376 |
+
G : graph
|
| 377 |
+
A NetworkX graph. Undirected graphs will be converted to a directed
|
| 378 |
+
graph with two directed edges for each undirected edge.
|
| 379 |
+
|
| 380 |
+
alpha : float, optional
|
| 381 |
+
Damping parameter for PageRank, default=0.85.
|
| 382 |
+
|
| 383 |
+
personalization: dict, optional
|
| 384 |
+
The "personalization vector" consisting of a dictionary with a
|
| 385 |
+
key some subset of graph nodes and personalization value each of those.
|
| 386 |
+
At least one personalization value must be non-zero.
|
| 387 |
+
If not specified, a nodes personalization value will be zero.
|
| 388 |
+
By default, a uniform distribution is used.
|
| 389 |
+
|
| 390 |
+
max_iter : integer, optional
|
| 391 |
+
Maximum number of iterations in power method eigenvalue solver.
|
| 392 |
+
|
| 393 |
+
tol : float, optional
|
| 394 |
+
Error tolerance used to check convergence in power method solver.
|
| 395 |
+
The iteration will stop after a tolerance of ``len(G) * tol`` is reached.
|
| 396 |
+
|
| 397 |
+
nstart : dictionary, optional
|
| 398 |
+
Starting value of PageRank iteration for each node.
|
| 399 |
+
|
| 400 |
+
weight : key, optional
|
| 401 |
+
Edge data key to use as weight. If None weights are set to 1.
|
| 402 |
+
|
| 403 |
+
dangling: dict, optional
|
| 404 |
+
The outedges to be assigned to any "dangling" nodes, i.e., nodes without
|
| 405 |
+
any outedges. The dict key is the node the outedge points to and the dict
|
| 406 |
+
value is the weight of that outedge. By default, dangling nodes are given
|
| 407 |
+
outedges according to the personalization vector (uniform if not
|
| 408 |
+
specified) This must be selected to result in an irreducible transition
|
| 409 |
+
matrix (see notes under google_matrix). It may be common to have the
|
| 410 |
+
dangling dict to be the same as the personalization dict.
|
| 411 |
+
|
| 412 |
+
Returns
|
| 413 |
+
-------
|
| 414 |
+
pagerank : dictionary
|
| 415 |
+
Dictionary of nodes with PageRank as value
|
| 416 |
+
|
| 417 |
+
Examples
|
| 418 |
+
--------
|
| 419 |
+
>>> from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_scipy
|
| 420 |
+
>>> G = nx.DiGraph(nx.path_graph(4))
|
| 421 |
+
>>> pr = _pagerank_scipy(G, alpha=0.9)
|
| 422 |
+
|
| 423 |
+
Notes
|
| 424 |
+
-----
|
| 425 |
+
The eigenvector calculation uses power iteration with a SciPy
|
| 426 |
+
sparse matrix representation.
|
| 427 |
+
|
| 428 |
+
This implementation works with Multi(Di)Graphs. For multigraphs the
|
| 429 |
+
weight between two nodes is set to be the sum of all edge weights
|
| 430 |
+
between those nodes.
|
| 431 |
+
|
| 432 |
+
See Also
|
| 433 |
+
--------
|
| 434 |
+
pagerank
|
| 435 |
+
|
| 436 |
+
Raises
|
| 437 |
+
------
|
| 438 |
+
PowerIterationFailedConvergence
|
| 439 |
+
If the algorithm fails to converge to the specified tolerance
|
| 440 |
+
within the specified number of iterations of the power iteration
|
| 441 |
+
method.
|
| 442 |
+
|
| 443 |
+
References
|
| 444 |
+
----------
|
| 445 |
+
.. [1] A. Langville and C. Meyer,
|
| 446 |
+
"A survey of eigenvector methods of web information retrieval."
|
| 447 |
+
http://citeseer.ist.psu.edu/713792.html
|
| 448 |
+
.. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
|
| 449 |
+
The PageRank citation ranking: Bringing order to the Web. 1999
|
| 450 |
+
http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
|
| 451 |
+
"""
|
| 452 |
+
import numpy as np
|
| 453 |
+
import scipy as sp
|
| 454 |
+
|
| 455 |
+
N = len(G)
|
| 456 |
+
if N == 0:
|
| 457 |
+
return {}
|
| 458 |
+
|
| 459 |
+
nodelist = list(G)
|
| 460 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
|
| 461 |
+
S = A.sum(axis=1)
|
| 462 |
+
S[S != 0] = 1.0 / S[S != 0]
|
| 463 |
+
# TODO: csr_array
|
| 464 |
+
Q = sp.sparse.csr_array(sp.sparse.spdiags(S.T, 0, *A.shape))
|
| 465 |
+
A = Q @ A
|
| 466 |
+
|
| 467 |
+
# initial vector
|
| 468 |
+
if nstart is None:
|
| 469 |
+
x = np.repeat(1.0 / N, N)
|
| 470 |
+
else:
|
| 471 |
+
x = np.array([nstart.get(n, 0) for n in nodelist], dtype=float)
|
| 472 |
+
x /= x.sum()
|
| 473 |
+
|
| 474 |
+
# Personalization vector
|
| 475 |
+
if personalization is None:
|
| 476 |
+
p = np.repeat(1.0 / N, N)
|
| 477 |
+
else:
|
| 478 |
+
p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float)
|
| 479 |
+
if p.sum() == 0:
|
| 480 |
+
raise ZeroDivisionError
|
| 481 |
+
p /= p.sum()
|
| 482 |
+
# Dangling nodes
|
| 483 |
+
if dangling is None:
|
| 484 |
+
dangling_weights = p
|
| 485 |
+
else:
|
| 486 |
+
# Convert the dangling dictionary into an array in nodelist order
|
| 487 |
+
dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float)
|
| 488 |
+
dangling_weights /= dangling_weights.sum()
|
| 489 |
+
is_dangling = np.where(S == 0)[0]
|
| 490 |
+
|
| 491 |
+
# power iteration: make up to max_iter iterations
|
| 492 |
+
for _ in range(max_iter):
|
| 493 |
+
xlast = x
|
| 494 |
+
x = alpha * (x @ A + sum(x[is_dangling]) * dangling_weights) + (1 - alpha) * p
|
| 495 |
+
# check convergence, l1 norm
|
| 496 |
+
err = np.absolute(x - xlast).sum()
|
| 497 |
+
if err < N * tol:
|
| 498 |
+
return dict(zip(nodelist, map(float, x)))
|
| 499 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__init__.py
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (191 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__pycache__/test_hits.cpython-310.pyc
ADDED
|
Binary file (2.96 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/__pycache__/test_pagerank.cpython-310.pyc
ADDED
|
Binary file (7.75 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/test_hits.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
np = pytest.importorskip("numpy")
|
| 6 |
+
sp = pytest.importorskip("scipy")
|
| 7 |
+
|
| 8 |
+
from networkx.algorithms.link_analysis.hits_alg import (
|
| 9 |
+
_hits_numpy,
|
| 10 |
+
_hits_python,
|
| 11 |
+
_hits_scipy,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Example from
|
| 15 |
+
# A. Langville and C. Meyer, "A survey of eigenvector methods of web
|
| 16 |
+
# information retrieval." http://citeseer.ist.psu.edu/713792.html
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestHITS:
|
| 20 |
+
@classmethod
|
| 21 |
+
def setup_class(cls):
|
| 22 |
+
G = nx.DiGraph()
|
| 23 |
+
|
| 24 |
+
edges = [(1, 3), (1, 5), (2, 1), (3, 5), (5, 4), (5, 3), (6, 5)]
|
| 25 |
+
|
| 26 |
+
G.add_edges_from(edges, weight=1)
|
| 27 |
+
cls.G = G
|
| 28 |
+
cls.G.a = dict(
|
| 29 |
+
zip(sorted(G), [0.000000, 0.000000, 0.366025, 0.133975, 0.500000, 0.000000])
|
| 30 |
+
)
|
| 31 |
+
cls.G.h = dict(
|
| 32 |
+
zip(sorted(G), [0.366025, 0.000000, 0.211325, 0.000000, 0.211325, 0.211325])
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def test_hits_numpy(self):
|
| 36 |
+
G = self.G
|
| 37 |
+
h, a = _hits_numpy(G)
|
| 38 |
+
for n in G:
|
| 39 |
+
assert h[n] == pytest.approx(G.h[n], abs=1e-4)
|
| 40 |
+
for n in G:
|
| 41 |
+
assert a[n] == pytest.approx(G.a[n], abs=1e-4)
|
| 42 |
+
|
| 43 |
+
@pytest.mark.parametrize("hits_alg", (nx.hits, _hits_python, _hits_scipy))
|
| 44 |
+
def test_hits(self, hits_alg):
|
| 45 |
+
G = self.G
|
| 46 |
+
h, a = hits_alg(G, tol=1.0e-08)
|
| 47 |
+
for n in G:
|
| 48 |
+
assert h[n] == pytest.approx(G.h[n], abs=1e-4)
|
| 49 |
+
for n in G:
|
| 50 |
+
assert a[n] == pytest.approx(G.a[n], abs=1e-4)
|
| 51 |
+
nstart = {i: 1.0 / 2 for i in G}
|
| 52 |
+
h, a = hits_alg(G, nstart=nstart)
|
| 53 |
+
for n in G:
|
| 54 |
+
assert h[n] == pytest.approx(G.h[n], abs=1e-4)
|
| 55 |
+
for n in G:
|
| 56 |
+
assert a[n] == pytest.approx(G.a[n], abs=1e-4)
|
| 57 |
+
|
| 58 |
+
def test_empty(self):
|
| 59 |
+
G = nx.Graph()
|
| 60 |
+
assert nx.hits(G) == ({}, {})
|
| 61 |
+
assert _hits_numpy(G) == ({}, {})
|
| 62 |
+
assert _hits_python(G) == ({}, {})
|
| 63 |
+
assert _hits_scipy(G) == ({}, {})
|
| 64 |
+
|
| 65 |
+
def test_hits_not_convergent(self):
|
| 66 |
+
G = nx.path_graph(50)
|
| 67 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 68 |
+
_hits_scipy(G, max_iter=1)
|
| 69 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 70 |
+
_hits_python(G, max_iter=1)
|
| 71 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 72 |
+
_hits_scipy(G, max_iter=0)
|
| 73 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 74 |
+
_hits_python(G, max_iter=0)
|
| 75 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 76 |
+
nx.hits(G, max_iter=0)
|
| 77 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 78 |
+
nx.hits(G, max_iter=1)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/link_analysis/tests/test_pagerank.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.classes.tests import dispatch_interface
|
| 7 |
+
|
| 8 |
+
np = pytest.importorskip("numpy")
|
| 9 |
+
pytest.importorskip("scipy")
|
| 10 |
+
|
| 11 |
+
from networkx.algorithms.link_analysis.pagerank_alg import (
|
| 12 |
+
_pagerank_numpy,
|
| 13 |
+
_pagerank_python,
|
| 14 |
+
_pagerank_scipy,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Example from
|
| 18 |
+
# A. Langville and C. Meyer, "A survey of eigenvector methods of web
|
| 19 |
+
# information retrieval." http://citeseer.ist.psu.edu/713792.html
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestPageRank:
|
| 23 |
+
@classmethod
|
| 24 |
+
def setup_class(cls):
|
| 25 |
+
G = nx.DiGraph()
|
| 26 |
+
edges = [
|
| 27 |
+
(1, 2),
|
| 28 |
+
(1, 3),
|
| 29 |
+
# 2 is a dangling node
|
| 30 |
+
(3, 1),
|
| 31 |
+
(3, 2),
|
| 32 |
+
(3, 5),
|
| 33 |
+
(4, 5),
|
| 34 |
+
(4, 6),
|
| 35 |
+
(5, 4),
|
| 36 |
+
(5, 6),
|
| 37 |
+
(6, 4),
|
| 38 |
+
]
|
| 39 |
+
G.add_edges_from(edges)
|
| 40 |
+
cls.G = G
|
| 41 |
+
cls.G.pagerank = dict(
|
| 42 |
+
zip(
|
| 43 |
+
sorted(G),
|
| 44 |
+
[
|
| 45 |
+
0.03721197,
|
| 46 |
+
0.05395735,
|
| 47 |
+
0.04150565,
|
| 48 |
+
0.37508082,
|
| 49 |
+
0.20599833,
|
| 50 |
+
0.28624589,
|
| 51 |
+
],
|
| 52 |
+
)
|
| 53 |
+
)
|
| 54 |
+
cls.dangling_node_index = 1
|
| 55 |
+
cls.dangling_edges = {1: 2, 2: 3, 3: 0, 4: 0, 5: 0, 6: 0}
|
| 56 |
+
cls.G.dangling_pagerank = dict(
|
| 57 |
+
zip(
|
| 58 |
+
sorted(G),
|
| 59 |
+
[0.10844518, 0.18618601, 0.0710892, 0.2683668, 0.15919783, 0.20671497],
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python))
|
| 64 |
+
def test_pagerank(self, alg):
|
| 65 |
+
G = self.G
|
| 66 |
+
p = alg(G, alpha=0.9, tol=1.0e-08)
|
| 67 |
+
for n in G:
|
| 68 |
+
assert p[n] == pytest.approx(G.pagerank[n], abs=1e-4)
|
| 69 |
+
|
| 70 |
+
nstart = {n: random.random() for n in G}
|
| 71 |
+
p = alg(G, alpha=0.9, tol=1.0e-08, nstart=nstart)
|
| 72 |
+
for n in G:
|
| 73 |
+
assert p[n] == pytest.approx(G.pagerank[n], abs=1e-4)
|
| 74 |
+
|
| 75 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python))
|
| 76 |
+
def test_pagerank_max_iter(self, alg):
|
| 77 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 78 |
+
alg(self.G, max_iter=0)
|
| 79 |
+
|
| 80 |
+
def test_numpy_pagerank(self):
|
| 81 |
+
G = self.G
|
| 82 |
+
p = _pagerank_numpy(G, alpha=0.9)
|
| 83 |
+
for n in G:
|
| 84 |
+
assert p[n] == pytest.approx(G.pagerank[n], abs=1e-4)
|
| 85 |
+
|
| 86 |
+
# This additionally tests the @nx._dispatchable mechanism, treating
|
| 87 |
+
# nx.google_matrix as if it were a re-implementation from another package
|
| 88 |
+
@pytest.mark.parametrize("wrapper", [lambda x: x, dispatch_interface.convert])
|
| 89 |
+
def test_google_matrix(self, wrapper):
|
| 90 |
+
G = wrapper(self.G)
|
| 91 |
+
M = nx.google_matrix(G, alpha=0.9, nodelist=sorted(G))
|
| 92 |
+
_, ev = np.linalg.eig(M.T)
|
| 93 |
+
p = ev[:, 0] / ev[:, 0].sum()
|
| 94 |
+
for a, b in zip(p, self.G.pagerank.values()):
|
| 95 |
+
assert a == pytest.approx(b, abs=1e-7)
|
| 96 |
+
|
| 97 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python, _pagerank_numpy))
|
| 98 |
+
def test_personalization(self, alg):
|
| 99 |
+
G = nx.complete_graph(4)
|
| 100 |
+
personalize = {0: 1, 1: 1, 2: 4, 3: 4}
|
| 101 |
+
answer = {
|
| 102 |
+
0: 0.23246732615667579,
|
| 103 |
+
1: 0.23246732615667579,
|
| 104 |
+
2: 0.267532673843324,
|
| 105 |
+
3: 0.2675326738433241,
|
| 106 |
+
}
|
| 107 |
+
p = alg(G, alpha=0.85, personalization=personalize)
|
| 108 |
+
for n in G:
|
| 109 |
+
assert p[n] == pytest.approx(answer[n], abs=1e-4)
|
| 110 |
+
|
| 111 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python, nx.google_matrix))
|
| 112 |
+
def test_zero_personalization_vector(self, alg):
|
| 113 |
+
G = nx.complete_graph(4)
|
| 114 |
+
personalize = {0: 0, 1: 0, 2: 0, 3: 0}
|
| 115 |
+
pytest.raises(ZeroDivisionError, alg, G, personalization=personalize)
|
| 116 |
+
|
| 117 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python))
|
| 118 |
+
def test_one_nonzero_personalization_value(self, alg):
|
| 119 |
+
G = nx.complete_graph(4)
|
| 120 |
+
personalize = {0: 0, 1: 0, 2: 0, 3: 1}
|
| 121 |
+
answer = {
|
| 122 |
+
0: 0.22077931820379187,
|
| 123 |
+
1: 0.22077931820379187,
|
| 124 |
+
2: 0.22077931820379187,
|
| 125 |
+
3: 0.3376620453886241,
|
| 126 |
+
}
|
| 127 |
+
p = alg(G, alpha=0.85, personalization=personalize)
|
| 128 |
+
for n in G:
|
| 129 |
+
assert p[n] == pytest.approx(answer[n], abs=1e-4)
|
| 130 |
+
|
| 131 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python))
|
| 132 |
+
def test_incomplete_personalization(self, alg):
|
| 133 |
+
G = nx.complete_graph(4)
|
| 134 |
+
personalize = {3: 1}
|
| 135 |
+
answer = {
|
| 136 |
+
0: 0.22077931820379187,
|
| 137 |
+
1: 0.22077931820379187,
|
| 138 |
+
2: 0.22077931820379187,
|
| 139 |
+
3: 0.3376620453886241,
|
| 140 |
+
}
|
| 141 |
+
p = alg(G, alpha=0.85, personalization=personalize)
|
| 142 |
+
for n in G:
|
| 143 |
+
assert p[n] == pytest.approx(answer[n], abs=1e-4)
|
| 144 |
+
|
| 145 |
+
def test_dangling_matrix(self):
|
| 146 |
+
"""
|
| 147 |
+
Tests that the google_matrix doesn't change except for the dangling
|
| 148 |
+
nodes.
|
| 149 |
+
"""
|
| 150 |
+
G = self.G
|
| 151 |
+
dangling = self.dangling_edges
|
| 152 |
+
dangling_sum = sum(dangling.values())
|
| 153 |
+
M1 = nx.google_matrix(G, personalization=dangling)
|
| 154 |
+
M2 = nx.google_matrix(G, personalization=dangling, dangling=dangling)
|
| 155 |
+
for i in range(len(G)):
|
| 156 |
+
for j in range(len(G)):
|
| 157 |
+
if i == self.dangling_node_index and (j + 1) in dangling:
|
| 158 |
+
assert M2[i, j] == pytest.approx(
|
| 159 |
+
dangling[j + 1] / dangling_sum, abs=1e-4
|
| 160 |
+
)
|
| 161 |
+
else:
|
| 162 |
+
assert M2[i, j] == pytest.approx(M1[i, j], abs=1e-4)
|
| 163 |
+
|
| 164 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python, _pagerank_numpy))
|
| 165 |
+
def test_dangling_pagerank(self, alg):
|
| 166 |
+
pr = alg(self.G, dangling=self.dangling_edges)
|
| 167 |
+
for n in self.G:
|
| 168 |
+
assert pr[n] == pytest.approx(self.G.dangling_pagerank[n], abs=1e-4)
|
| 169 |
+
|
| 170 |
+
def test_empty(self):
|
| 171 |
+
G = nx.Graph()
|
| 172 |
+
assert nx.pagerank(G) == {}
|
| 173 |
+
assert _pagerank_python(G) == {}
|
| 174 |
+
assert _pagerank_numpy(G) == {}
|
| 175 |
+
assert nx.google_matrix(G).shape == (0, 0)
|
| 176 |
+
|
| 177 |
+
@pytest.mark.parametrize("alg", (nx.pagerank, _pagerank_python))
|
| 178 |
+
def test_multigraph(self, alg):
|
| 179 |
+
G = nx.MultiGraph()
|
| 180 |
+
G.add_edges_from([(1, 2), (1, 2), (1, 2), (2, 3), (2, 3), ("3", 3), ("3", 3)])
|
| 181 |
+
answer = {
|
| 182 |
+
1: 0.21066048614468322,
|
| 183 |
+
2: 0.3395308825985378,
|
| 184 |
+
3: 0.28933951385531687,
|
| 185 |
+
"3": 0.16046911740146227,
|
| 186 |
+
}
|
| 187 |
+
p = alg(G)
|
| 188 |
+
for n in G:
|
| 189 |
+
assert p[n] == pytest.approx(answer[n], abs=1e-4)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class TestPageRankScipy(TestPageRank):
|
| 193 |
+
def test_scipy_pagerank(self):
|
| 194 |
+
G = self.G
|
| 195 |
+
p = _pagerank_scipy(G, alpha=0.9, tol=1.0e-08)
|
| 196 |
+
for n in G:
|
| 197 |
+
assert p[n] == pytest.approx(G.pagerank[n], abs=1e-4)
|
| 198 |
+
personalize = {n: random.random() for n in G}
|
| 199 |
+
p = _pagerank_scipy(G, alpha=0.9, tol=1.0e-08, personalization=personalize)
|
| 200 |
+
|
| 201 |
+
nstart = {n: random.random() for n in G}
|
| 202 |
+
p = _pagerank_scipy(G, alpha=0.9, tol=1.0e-08, nstart=nstart)
|
| 203 |
+
for n in G:
|
| 204 |
+
assert p[n] == pytest.approx(G.pagerank[n], abs=1e-4)
|
| 205 |
+
|
| 206 |
+
def test_scipy_pagerank_max_iter(self):
|
| 207 |
+
with pytest.raises(nx.PowerIterationFailedConvergence):
|
| 208 |
+
_pagerank_scipy(self.G, max_iter=0)
|
| 209 |
+
|
| 210 |
+
def test_dangling_scipy_pagerank(self):
|
| 211 |
+
pr = _pagerank_scipy(self.G, dangling=self.dangling_edges)
|
| 212 |
+
for n in self.G:
|
| 213 |
+
assert pr[n] == pytest.approx(self.G.dangling_pagerank[n], abs=1e-4)
|
| 214 |
+
|
| 215 |
+
def test_empty_scipy(self):
|
| 216 |
+
G = nx.Graph()
|
| 217 |
+
assert _pagerank_scipy(G) == {}
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__init__.py
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chains.cpython-310.pyc
ADDED
|
Binary file (4.48 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_core.cpython-310.pyc
ADDED
|
Binary file (9.59 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dominance.cpython-310.pyc
ADDED
|
Binary file (8.51 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_isolate.cpython-310.pyc
ADDED
|
Binary file (993 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_link_prediction.cpython-310.pyc
ADDED
|
Binary file (21.1 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_moral.cpython-310.pyc
ADDED
|
Binary file (752 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_regular.cpython-310.pyc
ADDED
|
Binary file (4.16 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_simple_paths.cpython-310.pyc
ADDED
|
Binary file (30.5 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_vitality.cpython-310.pyc
ADDED
|
Binary file (2.02 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_walks.cpython-310.pyc
ADDED
|
Binary file (1.86 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import networkx as nx
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_is_at_free():
|
| 5 |
+
is_at_free = nx.asteroidal.is_at_free
|
| 6 |
+
|
| 7 |
+
cycle = nx.cycle_graph(6)
|
| 8 |
+
assert not is_at_free(cycle)
|
| 9 |
+
|
| 10 |
+
path = nx.path_graph(6)
|
| 11 |
+
assert is_at_free(path)
|
| 12 |
+
|
| 13 |
+
small_graph = nx.complete_graph(2)
|
| 14 |
+
assert is_at_free(small_graph)
|
| 15 |
+
|
| 16 |
+
petersen = nx.petersen_graph()
|
| 17 |
+
assert not is_at_free(petersen)
|
| 18 |
+
|
| 19 |
+
clique = nx.complete_graph(6)
|
| 20 |
+
assert is_at_free(clique)
|
| 21 |
+
|
| 22 |
+
line_clique = nx.line_graph(clique)
|
| 23 |
+
assert not is_at_free(line_clique)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the :mod:`networkx.algorithms.boundary` module."""
|
| 2 |
+
|
| 3 |
+
from itertools import combinations
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
| 9 |
+
from networkx.utils import edges_equal
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestNodeBoundary:
|
| 13 |
+
"""Unit tests for the :func:`~networkx.node_boundary` function."""
|
| 14 |
+
|
| 15 |
+
def test_null_graph(self):
|
| 16 |
+
"""Tests that the null graph has empty node boundaries."""
|
| 17 |
+
null = nx.null_graph()
|
| 18 |
+
assert nx.node_boundary(null, []) == set()
|
| 19 |
+
assert nx.node_boundary(null, [], []) == set()
|
| 20 |
+
assert nx.node_boundary(null, [1, 2, 3]) == set()
|
| 21 |
+
assert nx.node_boundary(null, [1, 2, 3], [4, 5, 6]) == set()
|
| 22 |
+
assert nx.node_boundary(null, [1, 2, 3], [3, 4, 5]) == set()
|
| 23 |
+
|
| 24 |
+
def test_path_graph(self):
|
| 25 |
+
P10 = cnlti(nx.path_graph(10), first_label=1)
|
| 26 |
+
assert nx.node_boundary(P10, []) == set()
|
| 27 |
+
assert nx.node_boundary(P10, [], []) == set()
|
| 28 |
+
assert nx.node_boundary(P10, [1, 2, 3]) == {4}
|
| 29 |
+
assert nx.node_boundary(P10, [4, 5, 6]) == {3, 7}
|
| 30 |
+
assert nx.node_boundary(P10, [3, 4, 5, 6, 7]) == {2, 8}
|
| 31 |
+
assert nx.node_boundary(P10, [8, 9, 10]) == {7}
|
| 32 |
+
assert nx.node_boundary(P10, [4, 5, 6], [9, 10]) == set()
|
| 33 |
+
|
| 34 |
+
def test_complete_graph(self):
|
| 35 |
+
K10 = cnlti(nx.complete_graph(10), first_label=1)
|
| 36 |
+
assert nx.node_boundary(K10, []) == set()
|
| 37 |
+
assert nx.node_boundary(K10, [], []) == set()
|
| 38 |
+
assert nx.node_boundary(K10, [1, 2, 3]) == {4, 5, 6, 7, 8, 9, 10}
|
| 39 |
+
assert nx.node_boundary(K10, [4, 5, 6]) == {1, 2, 3, 7, 8, 9, 10}
|
| 40 |
+
assert nx.node_boundary(K10, [3, 4, 5, 6, 7]) == {1, 2, 8, 9, 10}
|
| 41 |
+
assert nx.node_boundary(K10, [4, 5, 6], []) == set()
|
| 42 |
+
assert nx.node_boundary(K10, K10) == set()
|
| 43 |
+
assert nx.node_boundary(K10, [1, 2, 3], [3, 4, 5]) == {4, 5}
|
| 44 |
+
|
| 45 |
+
def test_petersen(self):
|
| 46 |
+
"""Check boundaries in the petersen graph
|
| 47 |
+
|
| 48 |
+
cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0<k<=|V(G)|/2)
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def cheeger(G, k):
|
| 53 |
+
return min(len(nx.node_boundary(G, nn)) / k for nn in combinations(G, k))
|
| 54 |
+
|
| 55 |
+
P = nx.petersen_graph()
|
| 56 |
+
assert cheeger(P, 1) == pytest.approx(3.00, abs=1e-2)
|
| 57 |
+
assert cheeger(P, 2) == pytest.approx(2.00, abs=1e-2)
|
| 58 |
+
assert cheeger(P, 3) == pytest.approx(1.67, abs=1e-2)
|
| 59 |
+
assert cheeger(P, 4) == pytest.approx(1.00, abs=1e-2)
|
| 60 |
+
assert cheeger(P, 5) == pytest.approx(0.80, abs=1e-2)
|
| 61 |
+
|
| 62 |
+
def test_directed(self):
|
| 63 |
+
"""Tests the node boundary of a directed graph."""
|
| 64 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
|
| 65 |
+
S = {0, 1}
|
| 66 |
+
boundary = nx.node_boundary(G, S)
|
| 67 |
+
expected = {2}
|
| 68 |
+
assert boundary == expected
|
| 69 |
+
|
| 70 |
+
def test_multigraph(self):
|
| 71 |
+
"""Tests the node boundary of a multigraph."""
|
| 72 |
+
G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
|
| 73 |
+
S = {0, 1}
|
| 74 |
+
boundary = nx.node_boundary(G, S)
|
| 75 |
+
expected = {2, 4}
|
| 76 |
+
assert boundary == expected
|
| 77 |
+
|
| 78 |
+
def test_multidigraph(self):
|
| 79 |
+
"""Tests the edge boundary of a multidigraph."""
|
| 80 |
+
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
|
| 81 |
+
G = nx.MultiDiGraph(edges * 2)
|
| 82 |
+
S = {0, 1}
|
| 83 |
+
boundary = nx.node_boundary(G, S)
|
| 84 |
+
expected = {2}
|
| 85 |
+
assert boundary == expected
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class TestEdgeBoundary:
|
| 89 |
+
"""Unit tests for the :func:`~networkx.edge_boundary` function."""
|
| 90 |
+
|
| 91 |
+
def test_null_graph(self):
|
| 92 |
+
null = nx.null_graph()
|
| 93 |
+
assert list(nx.edge_boundary(null, [])) == []
|
| 94 |
+
assert list(nx.edge_boundary(null, [], [])) == []
|
| 95 |
+
assert list(nx.edge_boundary(null, [1, 2, 3])) == []
|
| 96 |
+
assert list(nx.edge_boundary(null, [1, 2, 3], [4, 5, 6])) == []
|
| 97 |
+
assert list(nx.edge_boundary(null, [1, 2, 3], [3, 4, 5])) == []
|
| 98 |
+
|
| 99 |
+
def test_path_graph(self):
|
| 100 |
+
P10 = cnlti(nx.path_graph(10), first_label=1)
|
| 101 |
+
assert list(nx.edge_boundary(P10, [])) == []
|
| 102 |
+
assert list(nx.edge_boundary(P10, [], [])) == []
|
| 103 |
+
assert list(nx.edge_boundary(P10, [1, 2, 3])) == [(3, 4)]
|
| 104 |
+
assert sorted(nx.edge_boundary(P10, [4, 5, 6])) == [(4, 3), (6, 7)]
|
| 105 |
+
assert sorted(nx.edge_boundary(P10, [3, 4, 5, 6, 7])) == [(3, 2), (7, 8)]
|
| 106 |
+
assert list(nx.edge_boundary(P10, [8, 9, 10])) == [(8, 7)]
|
| 107 |
+
assert sorted(nx.edge_boundary(P10, [4, 5, 6], [9, 10])) == []
|
| 108 |
+
assert list(nx.edge_boundary(P10, [1, 2, 3], [3, 4, 5])) == [(2, 3), (3, 4)]
|
| 109 |
+
|
| 110 |
+
def test_complete_graph(self):
|
| 111 |
+
K10 = cnlti(nx.complete_graph(10), first_label=1)
|
| 112 |
+
|
| 113 |
+
def ilen(iterable):
|
| 114 |
+
return sum(1 for i in iterable)
|
| 115 |
+
|
| 116 |
+
assert list(nx.edge_boundary(K10, [])) == []
|
| 117 |
+
assert list(nx.edge_boundary(K10, [], [])) == []
|
| 118 |
+
assert ilen(nx.edge_boundary(K10, [1, 2, 3])) == 21
|
| 119 |
+
assert ilen(nx.edge_boundary(K10, [4, 5, 6, 7])) == 24
|
| 120 |
+
assert ilen(nx.edge_boundary(K10, [3, 4, 5, 6, 7])) == 25
|
| 121 |
+
assert ilen(nx.edge_boundary(K10, [8, 9, 10])) == 21
|
| 122 |
+
assert edges_equal(
|
| 123 |
+
nx.edge_boundary(K10, [4, 5, 6], [9, 10]),
|
| 124 |
+
[(4, 9), (4, 10), (5, 9), (5, 10), (6, 9), (6, 10)],
|
| 125 |
+
)
|
| 126 |
+
assert edges_equal(
|
| 127 |
+
nx.edge_boundary(K10, [1, 2, 3], [3, 4, 5]),
|
| 128 |
+
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5)],
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def test_directed(self):
|
| 132 |
+
"""Tests the edge boundary of a directed graph."""
|
| 133 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
|
| 134 |
+
S = {0, 1}
|
| 135 |
+
boundary = list(nx.edge_boundary(G, S))
|
| 136 |
+
expected = [(1, 2)]
|
| 137 |
+
assert boundary == expected
|
| 138 |
+
|
| 139 |
+
def test_multigraph(self):
|
| 140 |
+
"""Tests the edge boundary of a multigraph."""
|
| 141 |
+
G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
|
| 142 |
+
S = {0, 1}
|
| 143 |
+
boundary = list(nx.edge_boundary(G, S))
|
| 144 |
+
expected = [(0, 4), (0, 4), (1, 2), (1, 2)]
|
| 145 |
+
assert boundary == expected
|
| 146 |
+
|
| 147 |
+
def test_multidigraph(self):
|
| 148 |
+
"""Tests the edge boundary of a multidigraph."""
|
| 149 |
+
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
|
| 150 |
+
G = nx.MultiDiGraph(edges * 2)
|
| 151 |
+
S = {0, 1}
|
| 152 |
+
boundary = list(nx.edge_boundary(G, S))
|
| 153 |
+
expected = [(1, 2), (1, 2)]
|
| 154 |
+
assert boundary == expected
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for bridge-finding algorithms."""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestBridges:
|
| 9 |
+
"""Unit tests for the bridge-finding function."""
|
| 10 |
+
|
| 11 |
+
def test_single_bridge(self):
|
| 12 |
+
edges = [
|
| 13 |
+
# DFS tree edges.
|
| 14 |
+
(1, 2),
|
| 15 |
+
(2, 3),
|
| 16 |
+
(3, 4),
|
| 17 |
+
(3, 5),
|
| 18 |
+
(5, 6),
|
| 19 |
+
(6, 7),
|
| 20 |
+
(7, 8),
|
| 21 |
+
(5, 9),
|
| 22 |
+
(9, 10),
|
| 23 |
+
# Nontree edges.
|
| 24 |
+
(1, 3),
|
| 25 |
+
(1, 4),
|
| 26 |
+
(2, 5),
|
| 27 |
+
(5, 10),
|
| 28 |
+
(6, 8),
|
| 29 |
+
]
|
| 30 |
+
G = nx.Graph(edges)
|
| 31 |
+
source = 1
|
| 32 |
+
bridges = list(nx.bridges(G, source))
|
| 33 |
+
assert bridges == [(5, 6)]
|
| 34 |
+
|
| 35 |
+
def test_barbell_graph(self):
|
| 36 |
+
# The (3, 0) barbell graph has two triangles joined by a single edge.
|
| 37 |
+
G = nx.barbell_graph(3, 0)
|
| 38 |
+
source = 0
|
| 39 |
+
bridges = list(nx.bridges(G, source))
|
| 40 |
+
assert bridges == [(2, 3)]
|
| 41 |
+
|
| 42 |
+
def test_multiedge_bridge(self):
|
| 43 |
+
edges = [
|
| 44 |
+
(0, 1),
|
| 45 |
+
(0, 2),
|
| 46 |
+
(1, 2),
|
| 47 |
+
(1, 2),
|
| 48 |
+
(2, 3),
|
| 49 |
+
(3, 4),
|
| 50 |
+
(3, 4),
|
| 51 |
+
]
|
| 52 |
+
G = nx.MultiGraph(edges)
|
| 53 |
+
assert list(nx.bridges(G)) == [(2, 3)]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class TestHasBridges:
|
| 57 |
+
"""Unit tests for the has bridges function."""
|
| 58 |
+
|
| 59 |
+
def test_single_bridge(self):
|
| 60 |
+
edges = [
|
| 61 |
+
# DFS tree edges.
|
| 62 |
+
(1, 2),
|
| 63 |
+
(2, 3),
|
| 64 |
+
(3, 4),
|
| 65 |
+
(3, 5),
|
| 66 |
+
(5, 6), # The only bridge edge
|
| 67 |
+
(6, 7),
|
| 68 |
+
(7, 8),
|
| 69 |
+
(5, 9),
|
| 70 |
+
(9, 10),
|
| 71 |
+
# Nontree edges.
|
| 72 |
+
(1, 3),
|
| 73 |
+
(1, 4),
|
| 74 |
+
(2, 5),
|
| 75 |
+
(5, 10),
|
| 76 |
+
(6, 8),
|
| 77 |
+
]
|
| 78 |
+
G = nx.Graph(edges)
|
| 79 |
+
assert nx.has_bridges(G) # Default root
|
| 80 |
+
assert nx.has_bridges(G, root=1) # arbitrary root in G
|
| 81 |
+
|
| 82 |
+
def test_has_bridges_raises_root_not_in_G(self):
|
| 83 |
+
G = nx.Graph()
|
| 84 |
+
G.add_nodes_from([1, 2, 3])
|
| 85 |
+
with pytest.raises(nx.NodeNotFound):
|
| 86 |
+
nx.has_bridges(G, root=6)
|
| 87 |
+
|
| 88 |
+
def test_multiedge_bridge(self):
|
| 89 |
+
edges = [
|
| 90 |
+
(0, 1),
|
| 91 |
+
(0, 2),
|
| 92 |
+
(1, 2),
|
| 93 |
+
(1, 2),
|
| 94 |
+
(2, 3),
|
| 95 |
+
(3, 4),
|
| 96 |
+
(3, 4),
|
| 97 |
+
]
|
| 98 |
+
G = nx.MultiGraph(edges)
|
| 99 |
+
assert nx.has_bridges(G)
|
| 100 |
+
# Make every edge a multiedge
|
| 101 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
| 102 |
+
assert not nx.has_bridges(G)
|
| 103 |
+
|
| 104 |
+
def test_bridges_multiple_components(self):
|
| 105 |
+
G = nx.Graph()
|
| 106 |
+
nx.add_path(G, [0, 1, 2]) # One connected component
|
| 107 |
+
nx.add_path(G, [4, 5, 6]) # Another connected component
|
| 108 |
+
assert list(nx.bridges(G, root=4)) == [(4, 5), (5, 6)]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class TestLocalBridges:
|
| 112 |
+
"""Unit tests for the local_bridge function."""
|
| 113 |
+
|
| 114 |
+
@classmethod
|
| 115 |
+
def setup_class(cls):
|
| 116 |
+
cls.BB = nx.barbell_graph(4, 0)
|
| 117 |
+
cls.square = nx.cycle_graph(4)
|
| 118 |
+
cls.tri = nx.cycle_graph(3)
|
| 119 |
+
|
| 120 |
+
def test_nospan(self):
|
| 121 |
+
expected = {(3, 4), (4, 3)}
|
| 122 |
+
assert next(nx.local_bridges(self.BB, with_span=False)) in expected
|
| 123 |
+
assert set(nx.local_bridges(self.square, with_span=False)) == self.square.edges
|
| 124 |
+
assert list(nx.local_bridges(self.tri, with_span=False)) == []
|
| 125 |
+
|
| 126 |
+
def test_no_weight(self):
|
| 127 |
+
inf = float("inf")
|
| 128 |
+
expected = {(3, 4, inf), (4, 3, inf)}
|
| 129 |
+
assert next(nx.local_bridges(self.BB)) in expected
|
| 130 |
+
expected = {(u, v, 3) for u, v in self.square.edges}
|
| 131 |
+
assert set(nx.local_bridges(self.square)) == expected
|
| 132 |
+
assert list(nx.local_bridges(self.tri)) == []
|
| 133 |
+
|
| 134 |
+
def test_weight(self):
|
| 135 |
+
inf = float("inf")
|
| 136 |
+
G = self.square.copy()
|
| 137 |
+
|
| 138 |
+
G.edges[1, 2]["weight"] = 2
|
| 139 |
+
expected = {(u, v, 5 - wt) for u, v, wt in G.edges(data="weight", default=1)}
|
| 140 |
+
assert set(nx.local_bridges(G, weight="weight")) == expected
|
| 141 |
+
|
| 142 |
+
expected = {(u, v, 6) for u, v in G.edges}
|
| 143 |
+
lb = nx.local_bridges(G, weight=lambda u, v, d: 2)
|
| 144 |
+
assert set(lb) == expected
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the broadcasting module."""
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_example_tree_broadcast():
|
| 8 |
+
"""
|
| 9 |
+
Test the BROADCAST algorithm on the example in the paper titled: "Information Dissemination in Trees"
|
| 10 |
+
"""
|
| 11 |
+
edge_list = [
|
| 12 |
+
(0, 1),
|
| 13 |
+
(1, 2),
|
| 14 |
+
(2, 7),
|
| 15 |
+
(3, 4),
|
| 16 |
+
(5, 4),
|
| 17 |
+
(4, 7),
|
| 18 |
+
(6, 7),
|
| 19 |
+
(7, 9),
|
| 20 |
+
(8, 9),
|
| 21 |
+
(9, 13),
|
| 22 |
+
(13, 14),
|
| 23 |
+
(14, 15),
|
| 24 |
+
(14, 16),
|
| 25 |
+
(14, 17),
|
| 26 |
+
(13, 11),
|
| 27 |
+
(11, 10),
|
| 28 |
+
(11, 12),
|
| 29 |
+
(13, 18),
|
| 30 |
+
(18, 19),
|
| 31 |
+
(18, 20),
|
| 32 |
+
]
|
| 33 |
+
G = nx.Graph(edge_list)
|
| 34 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
| 35 |
+
assert b_T == 6
|
| 36 |
+
assert b_C == {13, 9}
|
| 37 |
+
# test broadcast time from specific vertex
|
| 38 |
+
assert nx.tree_broadcast_time(G, 17) == 8
|
| 39 |
+
assert nx.tree_broadcast_time(G, 3) == 9
|
| 40 |
+
# test broadcast time of entire tree
|
| 41 |
+
assert nx.tree_broadcast_time(G) == 10
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_path_broadcast():
|
| 45 |
+
for i in range(2, 12):
|
| 46 |
+
G = nx.path_graph(i)
|
| 47 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
| 48 |
+
assert b_T == math.ceil(i / 2)
|
| 49 |
+
assert b_C == {
|
| 50 |
+
math.ceil(i / 2),
|
| 51 |
+
math.floor(i / 2),
|
| 52 |
+
math.ceil(i / 2 - 1),
|
| 53 |
+
math.floor(i / 2 - 1),
|
| 54 |
+
}
|
| 55 |
+
assert nx.tree_broadcast_time(G) == i - 1
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_empty_graph_broadcast():
|
| 59 |
+
H = nx.empty_graph(1)
|
| 60 |
+
b_T, b_C = nx.tree_broadcast_center(H)
|
| 61 |
+
assert b_T == 0
|
| 62 |
+
assert b_C == {0}
|
| 63 |
+
assert nx.tree_broadcast_time(H) == 0
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_star_broadcast():
|
| 67 |
+
for i in range(4, 12):
|
| 68 |
+
G = nx.star_graph(i)
|
| 69 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
| 70 |
+
assert b_T == i
|
| 71 |
+
assert b_C == set(G.nodes())
|
| 72 |
+
assert nx.tree_broadcast_time(G) == b_T
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_binomial_tree_broadcast():
|
| 76 |
+
for i in range(2, 8):
|
| 77 |
+
G = nx.binomial_tree(i)
|
| 78 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
| 79 |
+
assert b_T == i
|
| 80 |
+
assert b_C == {0, 2 ** (i - 1)}
|
| 81 |
+
assert nx.tree_broadcast_time(G) == 2 * i - 1
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_chains.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the chain decomposition functions."""
|
| 2 |
+
from itertools import cycle, islice
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def cycles(seq):
|
| 10 |
+
"""Yields cyclic permutations of the given sequence.
|
| 11 |
+
|
| 12 |
+
For example::
|
| 13 |
+
|
| 14 |
+
>>> list(cycles("abc"))
|
| 15 |
+
[('a', 'b', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b')]
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
n = len(seq)
|
| 19 |
+
cycled_seq = cycle(seq)
|
| 20 |
+
for x in seq:
|
| 21 |
+
yield tuple(islice(cycled_seq, n))
|
| 22 |
+
next(cycled_seq)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def cyclic_equals(seq1, seq2):
|
| 26 |
+
"""Decide whether two sequences are equal up to cyclic permutations.
|
| 27 |
+
|
| 28 |
+
For example::
|
| 29 |
+
|
| 30 |
+
>>> cyclic_equals("xyz", "zxy")
|
| 31 |
+
True
|
| 32 |
+
>>> cyclic_equals("xyz", "zyx")
|
| 33 |
+
False
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
# Cast seq2 to a tuple since `cycles()` yields tuples.
|
| 37 |
+
seq2 = tuple(seq2)
|
| 38 |
+
return any(x == tuple(seq2) for x in cycles(seq1))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TestChainDecomposition:
|
| 42 |
+
"""Unit tests for the chain decomposition function."""
|
| 43 |
+
|
| 44 |
+
def assertContainsChain(self, chain, expected):
|
| 45 |
+
# A cycle could be expressed in two different orientations, one
|
| 46 |
+
# forward and one backward, so we need to check for cyclic
|
| 47 |
+
# equality in both orientations.
|
| 48 |
+
reversed_chain = list(reversed([tuple(reversed(e)) for e in chain]))
|
| 49 |
+
for candidate in expected:
|
| 50 |
+
if cyclic_equals(chain, candidate):
|
| 51 |
+
break
|
| 52 |
+
if cyclic_equals(reversed_chain, candidate):
|
| 53 |
+
break
|
| 54 |
+
else:
|
| 55 |
+
self.fail("chain not found")
|
| 56 |
+
|
| 57 |
+
def test_decomposition(self):
|
| 58 |
+
edges = [
|
| 59 |
+
# DFS tree edges.
|
| 60 |
+
(1, 2),
|
| 61 |
+
(2, 3),
|
| 62 |
+
(3, 4),
|
| 63 |
+
(3, 5),
|
| 64 |
+
(5, 6),
|
| 65 |
+
(6, 7),
|
| 66 |
+
(7, 8),
|
| 67 |
+
(5, 9),
|
| 68 |
+
(9, 10),
|
| 69 |
+
# Nontree edges.
|
| 70 |
+
(1, 3),
|
| 71 |
+
(1, 4),
|
| 72 |
+
(2, 5),
|
| 73 |
+
(5, 10),
|
| 74 |
+
(6, 8),
|
| 75 |
+
]
|
| 76 |
+
G = nx.Graph(edges)
|
| 77 |
+
expected = [
|
| 78 |
+
[(1, 3), (3, 2), (2, 1)],
|
| 79 |
+
[(1, 4), (4, 3)],
|
| 80 |
+
[(2, 5), (5, 3)],
|
| 81 |
+
[(5, 10), (10, 9), (9, 5)],
|
| 82 |
+
[(6, 8), (8, 7), (7, 6)],
|
| 83 |
+
]
|
| 84 |
+
chains = list(nx.chain_decomposition(G, root=1))
|
| 85 |
+
assert len(chains) == len(expected)
|
| 86 |
+
|
| 87 |
+
# This chain decomposition isn't unique
|
| 88 |
+
# for chain in chains:
|
| 89 |
+
# print(chain)
|
| 90 |
+
# self.assertContainsChain(chain, expected)
|
| 91 |
+
|
| 92 |
+
def test_barbell_graph(self):
|
| 93 |
+
# The (3, 0) barbell graph has two triangles joined by a single edge.
|
| 94 |
+
G = nx.barbell_graph(3, 0)
|
| 95 |
+
chains = list(nx.chain_decomposition(G, root=0))
|
| 96 |
+
expected = [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]]
|
| 97 |
+
assert len(chains) == len(expected)
|
| 98 |
+
for chain in chains:
|
| 99 |
+
self.assertContainsChain(chain, expected)
|
| 100 |
+
|
| 101 |
+
def test_disconnected_graph(self):
|
| 102 |
+
"""Test for a graph with multiple connected components."""
|
| 103 |
+
G = nx.barbell_graph(3, 0)
|
| 104 |
+
H = nx.barbell_graph(3, 0)
|
| 105 |
+
mapping = dict(zip(range(6), "abcdef"))
|
| 106 |
+
nx.relabel_nodes(H, mapping, copy=False)
|
| 107 |
+
G = nx.union(G, H)
|
| 108 |
+
chains = list(nx.chain_decomposition(G))
|
| 109 |
+
expected = [
|
| 110 |
+
[(0, 1), (1, 2), (2, 0)],
|
| 111 |
+
[(3, 4), (4, 5), (5, 3)],
|
| 112 |
+
[("a", "b"), ("b", "c"), ("c", "a")],
|
| 113 |
+
[("d", "e"), ("e", "f"), ("f", "d")],
|
| 114 |
+
]
|
| 115 |
+
assert len(chains) == len(expected)
|
| 116 |
+
for chain in chains:
|
| 117 |
+
self.assertContainsChain(chain, expected)
|
| 118 |
+
|
| 119 |
+
def test_disconnected_graph_root_node(self):
|
| 120 |
+
"""Test for a single component of a disconnected graph."""
|
| 121 |
+
G = nx.barbell_graph(3, 0)
|
| 122 |
+
H = nx.barbell_graph(3, 0)
|
| 123 |
+
mapping = dict(zip(range(6), "abcdef"))
|
| 124 |
+
nx.relabel_nodes(H, mapping, copy=False)
|
| 125 |
+
G = nx.union(G, H)
|
| 126 |
+
chains = list(nx.chain_decomposition(G, root="a"))
|
| 127 |
+
expected = [
|
| 128 |
+
[("a", "b"), ("b", "c"), ("c", "a")],
|
| 129 |
+
[("d", "e"), ("e", "f"), ("f", "d")],
|
| 130 |
+
]
|
| 131 |
+
assert len(chains) == len(expected)
|
| 132 |
+
for chain in chains:
|
| 133 |
+
self.assertContainsChain(chain, expected)
|
| 134 |
+
|
| 135 |
+
def test_chain_decomposition_root_not_in_G(self):
|
| 136 |
+
"""Test chain decomposition when root is not in graph"""
|
| 137 |
+
G = nx.Graph()
|
| 138 |
+
G.add_nodes_from([1, 2, 3])
|
| 139 |
+
with pytest.raises(nx.NodeNotFound):
|
| 140 |
+
nx.has_bridges(G, root=6)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestMCS:
|
| 7 |
+
@classmethod
|
| 8 |
+
def setup_class(cls):
|
| 9 |
+
# simple graph
|
| 10 |
+
connected_chordal_G = nx.Graph()
|
| 11 |
+
connected_chordal_G.add_edges_from(
|
| 12 |
+
[
|
| 13 |
+
(1, 2),
|
| 14 |
+
(1, 3),
|
| 15 |
+
(2, 3),
|
| 16 |
+
(2, 4),
|
| 17 |
+
(3, 4),
|
| 18 |
+
(3, 5),
|
| 19 |
+
(3, 6),
|
| 20 |
+
(4, 5),
|
| 21 |
+
(4, 6),
|
| 22 |
+
(5, 6),
|
| 23 |
+
]
|
| 24 |
+
)
|
| 25 |
+
cls.connected_chordal_G = connected_chordal_G
|
| 26 |
+
|
| 27 |
+
chordal_G = nx.Graph()
|
| 28 |
+
chordal_G.add_edges_from(
|
| 29 |
+
[
|
| 30 |
+
(1, 2),
|
| 31 |
+
(1, 3),
|
| 32 |
+
(2, 3),
|
| 33 |
+
(2, 4),
|
| 34 |
+
(3, 4),
|
| 35 |
+
(3, 5),
|
| 36 |
+
(3, 6),
|
| 37 |
+
(4, 5),
|
| 38 |
+
(4, 6),
|
| 39 |
+
(5, 6),
|
| 40 |
+
(7, 8),
|
| 41 |
+
]
|
| 42 |
+
)
|
| 43 |
+
chordal_G.add_node(9)
|
| 44 |
+
cls.chordal_G = chordal_G
|
| 45 |
+
|
| 46 |
+
non_chordal_G = nx.Graph()
|
| 47 |
+
non_chordal_G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5), (3, 4), (3, 5)])
|
| 48 |
+
cls.non_chordal_G = non_chordal_G
|
| 49 |
+
|
| 50 |
+
self_loop_G = nx.Graph()
|
| 51 |
+
self_loop_G.add_edges_from([(1, 1)])
|
| 52 |
+
cls.self_loop_G = self_loop_G
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize("G", (nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()))
|
| 55 |
+
def test_is_chordal_not_implemented(self, G):
|
| 56 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 57 |
+
nx.is_chordal(G)
|
| 58 |
+
|
| 59 |
+
def test_is_chordal(self):
|
| 60 |
+
assert not nx.is_chordal(self.non_chordal_G)
|
| 61 |
+
assert nx.is_chordal(self.chordal_G)
|
| 62 |
+
assert nx.is_chordal(self.connected_chordal_G)
|
| 63 |
+
assert nx.is_chordal(nx.Graph())
|
| 64 |
+
assert nx.is_chordal(nx.complete_graph(3))
|
| 65 |
+
assert nx.is_chordal(nx.cycle_graph(3))
|
| 66 |
+
assert not nx.is_chordal(nx.cycle_graph(5))
|
| 67 |
+
assert nx.is_chordal(self.self_loop_G)
|
| 68 |
+
|
| 69 |
+
def test_induced_nodes(self):
|
| 70 |
+
G = nx.generators.classic.path_graph(10)
|
| 71 |
+
Induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
|
| 72 |
+
assert Induced_nodes == {1, 2, 3, 4, 5, 6, 7, 8, 9}
|
| 73 |
+
pytest.raises(
|
| 74 |
+
nx.NetworkXTreewidthBoundExceeded, nx.find_induced_nodes, G, 1, 9, 1
|
| 75 |
+
)
|
| 76 |
+
Induced_nodes = nx.find_induced_nodes(self.chordal_G, 1, 6)
|
| 77 |
+
assert Induced_nodes == {1, 2, 4, 6}
|
| 78 |
+
pytest.raises(nx.NetworkXError, nx.find_induced_nodes, self.non_chordal_G, 1, 5)
|
| 79 |
+
|
| 80 |
+
def test_graph_treewidth(self):
|
| 81 |
+
with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
|
| 82 |
+
nx.chordal_graph_treewidth(self.non_chordal_G)
|
| 83 |
+
|
| 84 |
+
def test_chordal_find_cliques(self):
|
| 85 |
+
cliques = {
|
| 86 |
+
frozenset([9]),
|
| 87 |
+
frozenset([7, 8]),
|
| 88 |
+
frozenset([1, 2, 3]),
|
| 89 |
+
frozenset([2, 3, 4]),
|
| 90 |
+
frozenset([3, 4, 5, 6]),
|
| 91 |
+
}
|
| 92 |
+
assert set(nx.chordal_graph_cliques(self.chordal_G)) == cliques
|
| 93 |
+
with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
|
| 94 |
+
set(nx.chordal_graph_cliques(self.non_chordal_G))
|
| 95 |
+
with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
|
| 96 |
+
set(nx.chordal_graph_cliques(self.self_loop_G))
|
| 97 |
+
|
| 98 |
+
def test_chordal_find_cliques_path(self):
|
| 99 |
+
G = nx.path_graph(10)
|
| 100 |
+
cliqueset = nx.chordal_graph_cliques(G)
|
| 101 |
+
for u, v in G.edges():
|
| 102 |
+
assert frozenset([u, v]) in cliqueset or frozenset([v, u]) in cliqueset
|
| 103 |
+
|
| 104 |
+
def test_chordal_find_cliquesCC(self):
|
| 105 |
+
cliques = {frozenset([1, 2, 3]), frozenset([2, 3, 4]), frozenset([3, 4, 5, 6])}
|
| 106 |
+
cgc = nx.chordal_graph_cliques
|
| 107 |
+
assert set(cgc(self.connected_chordal_G)) == cliques
|
| 108 |
+
|
| 109 |
+
def test_complete_to_chordal_graph(self):
|
| 110 |
+
fgrg = nx.fast_gnp_random_graph
|
| 111 |
+
test_graphs = [
|
| 112 |
+
nx.barbell_graph(6, 2),
|
| 113 |
+
nx.cycle_graph(15),
|
| 114 |
+
nx.wheel_graph(20),
|
| 115 |
+
nx.grid_graph([10, 4]),
|
| 116 |
+
nx.ladder_graph(15),
|
| 117 |
+
nx.star_graph(5),
|
| 118 |
+
nx.bull_graph(),
|
| 119 |
+
fgrg(20, 0.3, seed=1),
|
| 120 |
+
]
|
| 121 |
+
for G in test_graphs:
|
| 122 |
+
H, a = nx.complete_to_chordal_graph(G)
|
| 123 |
+
assert nx.is_chordal(H)
|
| 124 |
+
assert len(a) == H.number_of_nodes()
|
| 125 |
+
if nx.is_chordal(G):
|
| 126 |
+
assert G.number_of_edges() == H.number_of_edges()
|
| 127 |
+
assert set(a.values()) == {0}
|
| 128 |
+
else:
|
| 129 |
+
assert len(set(a.values())) == H.number_of_nodes()
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_clique.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestCliques:
|
| 8 |
+
def setup_method(self):
|
| 9 |
+
z = [3, 4, 3, 4, 2, 4, 2, 1, 1, 1, 1]
|
| 10 |
+
self.G = cnlti(nx.generators.havel_hakimi_graph(z), first_label=1)
|
| 11 |
+
self.cl = list(nx.find_cliques(self.G))
|
| 12 |
+
H = nx.complete_graph(6)
|
| 13 |
+
H = nx.relabel_nodes(H, {i: i + 1 for i in range(6)})
|
| 14 |
+
H.remove_edges_from([(2, 6), (2, 5), (2, 4), (1, 3), (5, 3)])
|
| 15 |
+
self.H = H
|
| 16 |
+
|
| 17 |
+
def test_find_cliques1(self):
|
| 18 |
+
cl = list(nx.find_cliques(self.G))
|
| 19 |
+
rcl = nx.find_cliques_recursive(self.G)
|
| 20 |
+
expected = [[2, 6, 1, 3], [2, 6, 4], [5, 4, 7], [8, 9], [10, 11]]
|
| 21 |
+
assert sorted(map(sorted, cl)) == sorted(map(sorted, rcl))
|
| 22 |
+
assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
|
| 23 |
+
|
| 24 |
+
def test_selfloops(self):
|
| 25 |
+
self.G.add_edge(1, 1)
|
| 26 |
+
cl = list(nx.find_cliques(self.G))
|
| 27 |
+
rcl = list(nx.find_cliques_recursive(self.G))
|
| 28 |
+
assert set(map(frozenset, cl)) == set(map(frozenset, rcl))
|
| 29 |
+
answer = [{2, 6, 1, 3}, {2, 6, 4}, {5, 4, 7}, {8, 9}, {10, 11}]
|
| 30 |
+
assert len(answer) == len(cl)
|
| 31 |
+
assert all(set(c) in answer for c in cl)
|
| 32 |
+
|
| 33 |
+
def test_find_cliques2(self):
|
| 34 |
+
hcl = list(nx.find_cliques(self.H))
|
| 35 |
+
assert sorted(map(sorted, hcl)) == [[1, 2], [1, 4, 5, 6], [2, 3], [3, 4, 6]]
|
| 36 |
+
|
| 37 |
+
def test_find_cliques3(self):
|
| 38 |
+
# all cliques are [[2, 6, 1, 3], [2, 6, 4], [5, 4, 7], [8, 9], [10, 11]]
|
| 39 |
+
|
| 40 |
+
cl = list(nx.find_cliques(self.G, [2]))
|
| 41 |
+
rcl = nx.find_cliques_recursive(self.G, [2])
|
| 42 |
+
expected = [[2, 6, 1, 3], [2, 6, 4]]
|
| 43 |
+
assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
|
| 44 |
+
assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
|
| 45 |
+
|
| 46 |
+
cl = list(nx.find_cliques(self.G, [2, 3]))
|
| 47 |
+
rcl = nx.find_cliques_recursive(self.G, [2, 3])
|
| 48 |
+
expected = [[2, 6, 1, 3]]
|
| 49 |
+
assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
|
| 50 |
+
assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
|
| 51 |
+
|
| 52 |
+
cl = list(nx.find_cliques(self.G, [2, 6, 4]))
|
| 53 |
+
rcl = nx.find_cliques_recursive(self.G, [2, 6, 4])
|
| 54 |
+
expected = [[2, 6, 4]]
|
| 55 |
+
assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
|
| 56 |
+
assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
|
| 57 |
+
|
| 58 |
+
cl = list(nx.find_cliques(self.G, [2, 6, 4]))
|
| 59 |
+
rcl = nx.find_cliques_recursive(self.G, [2, 6, 4])
|
| 60 |
+
expected = [[2, 6, 4]]
|
| 61 |
+
assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
|
| 62 |
+
assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
|
| 63 |
+
|
| 64 |
+
with pytest.raises(ValueError):
|
| 65 |
+
list(nx.find_cliques(self.G, [2, 6, 4, 1]))
|
| 66 |
+
|
| 67 |
+
with pytest.raises(ValueError):
|
| 68 |
+
list(nx.find_cliques_recursive(self.G, [2, 6, 4, 1]))
|
| 69 |
+
|
| 70 |
+
def test_number_of_cliques(self):
|
| 71 |
+
G = self.G
|
| 72 |
+
assert nx.number_of_cliques(G, 1) == 1
|
| 73 |
+
assert list(nx.number_of_cliques(G, [1]).values()) == [1]
|
| 74 |
+
assert list(nx.number_of_cliques(G, [1, 2]).values()) == [1, 2]
|
| 75 |
+
assert nx.number_of_cliques(G, [1, 2]) == {1: 1, 2: 2}
|
| 76 |
+
assert nx.number_of_cliques(G, 2) == 2
|
| 77 |
+
assert nx.number_of_cliques(G) == {
|
| 78 |
+
1: 1,
|
| 79 |
+
2: 2,
|
| 80 |
+
3: 1,
|
| 81 |
+
4: 2,
|
| 82 |
+
5: 1,
|
| 83 |
+
6: 2,
|
| 84 |
+
7: 1,
|
| 85 |
+
8: 1,
|
| 86 |
+
9: 1,
|
| 87 |
+
10: 1,
|
| 88 |
+
11: 1,
|
| 89 |
+
}
|
| 90 |
+
assert nx.number_of_cliques(G, nodes=list(G)) == {
|
| 91 |
+
1: 1,
|
| 92 |
+
2: 2,
|
| 93 |
+
3: 1,
|
| 94 |
+
4: 2,
|
| 95 |
+
5: 1,
|
| 96 |
+
6: 2,
|
| 97 |
+
7: 1,
|
| 98 |
+
8: 1,
|
| 99 |
+
9: 1,
|
| 100 |
+
10: 1,
|
| 101 |
+
11: 1,
|
| 102 |
+
}
|
| 103 |
+
assert nx.number_of_cliques(G, nodes=[2, 3, 4]) == {2: 2, 3: 1, 4: 2}
|
| 104 |
+
assert nx.number_of_cliques(G, cliques=self.cl) == {
|
| 105 |
+
1: 1,
|
| 106 |
+
2: 2,
|
| 107 |
+
3: 1,
|
| 108 |
+
4: 2,
|
| 109 |
+
5: 1,
|
| 110 |
+
6: 2,
|
| 111 |
+
7: 1,
|
| 112 |
+
8: 1,
|
| 113 |
+
9: 1,
|
| 114 |
+
10: 1,
|
| 115 |
+
11: 1,
|
| 116 |
+
}
|
| 117 |
+
assert nx.number_of_cliques(G, list(G), cliques=self.cl) == {
|
| 118 |
+
1: 1,
|
| 119 |
+
2: 2,
|
| 120 |
+
3: 1,
|
| 121 |
+
4: 2,
|
| 122 |
+
5: 1,
|
| 123 |
+
6: 2,
|
| 124 |
+
7: 1,
|
| 125 |
+
8: 1,
|
| 126 |
+
9: 1,
|
| 127 |
+
10: 1,
|
| 128 |
+
11: 1,
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
def test_node_clique_number(self):
|
| 132 |
+
G = self.G
|
| 133 |
+
assert nx.node_clique_number(G, 1) == 4
|
| 134 |
+
assert list(nx.node_clique_number(G, [1]).values()) == [4]
|
| 135 |
+
assert list(nx.node_clique_number(G, [1, 2]).values()) == [4, 4]
|
| 136 |
+
assert nx.node_clique_number(G, [1, 2]) == {1: 4, 2: 4}
|
| 137 |
+
assert nx.node_clique_number(G, 1) == 4
|
| 138 |
+
assert nx.node_clique_number(G) == {
|
| 139 |
+
1: 4,
|
| 140 |
+
2: 4,
|
| 141 |
+
3: 4,
|
| 142 |
+
4: 3,
|
| 143 |
+
5: 3,
|
| 144 |
+
6: 4,
|
| 145 |
+
7: 3,
|
| 146 |
+
8: 2,
|
| 147 |
+
9: 2,
|
| 148 |
+
10: 2,
|
| 149 |
+
11: 2,
|
| 150 |
+
}
|
| 151 |
+
assert nx.node_clique_number(G, cliques=self.cl) == {
|
| 152 |
+
1: 4,
|
| 153 |
+
2: 4,
|
| 154 |
+
3: 4,
|
| 155 |
+
4: 3,
|
| 156 |
+
5: 3,
|
| 157 |
+
6: 4,
|
| 158 |
+
7: 3,
|
| 159 |
+
8: 2,
|
| 160 |
+
9: 2,
|
| 161 |
+
10: 2,
|
| 162 |
+
11: 2,
|
| 163 |
+
}
|
| 164 |
+
assert nx.node_clique_number(G, [1, 2], cliques=self.cl) == {1: 4, 2: 4}
|
| 165 |
+
assert nx.node_clique_number(G, 1, cliques=self.cl) == 4
|
| 166 |
+
|
| 167 |
+
def test_make_clique_bipartite(self):
|
| 168 |
+
G = self.G
|
| 169 |
+
B = nx.make_clique_bipartite(G)
|
| 170 |
+
assert sorted(B) == [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
| 171 |
+
# Project onto the nodes of the original graph.
|
| 172 |
+
H = nx.projected_graph(B, range(1, 12))
|
| 173 |
+
assert H.adj == G.adj
|
| 174 |
+
# Project onto the nodes representing the cliques.
|
| 175 |
+
H1 = nx.projected_graph(B, range(-5, 0))
|
| 176 |
+
# Relabel the negative numbers as positive ones.
|
| 177 |
+
H1 = nx.relabel_nodes(H1, {-v: v for v in range(1, 6)})
|
| 178 |
+
assert sorted(H1) == [1, 2, 3, 4, 5]
|
| 179 |
+
|
| 180 |
+
def test_make_max_clique_graph(self):
|
| 181 |
+
"""Tests that the maximal clique graph is the same as the bipartite
|
| 182 |
+
clique graph after being projected onto the nodes representing the
|
| 183 |
+
cliques.
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
G = self.G
|
| 187 |
+
B = nx.make_clique_bipartite(G)
|
| 188 |
+
# Project onto the nodes representing the cliques.
|
| 189 |
+
H1 = nx.projected_graph(B, range(-5, 0))
|
| 190 |
+
# Relabel the negative numbers as nonnegative ones, starting at
|
| 191 |
+
# 0.
|
| 192 |
+
H1 = nx.relabel_nodes(H1, {-v: v - 1 for v in range(1, 6)})
|
| 193 |
+
H2 = nx.make_max_clique_graph(G)
|
| 194 |
+
assert H1.adj == H2.adj
|
| 195 |
+
|
| 196 |
+
def test_directed(self):
|
| 197 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 198 |
+
next(nx.find_cliques(nx.DiGraph()))
|
| 199 |
+
|
| 200 |
+
def test_find_cliques_trivial(self):
|
| 201 |
+
G = nx.Graph()
|
| 202 |
+
assert sorted(nx.find_cliques(G)) == []
|
| 203 |
+
assert sorted(nx.find_cliques_recursive(G)) == []
|
| 204 |
+
|
| 205 |
+
def test_make_max_clique_graph_create_using(self):
|
| 206 |
+
G = nx.Graph([(1, 2), (3, 1), (4, 1), (5, 6)])
|
| 207 |
+
E = nx.Graph([(0, 1), (0, 2), (1, 2)])
|
| 208 |
+
E.add_node(3)
|
| 209 |
+
assert nx.is_isomorphic(nx.make_max_clique_graph(G, create_using=nx.Graph), E)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class TestEnumerateAllCliques:
|
| 213 |
+
def test_paper_figure_4(self):
|
| 214 |
+
# Same graph as given in Fig. 4 of paper enumerate_all_cliques is
|
| 215 |
+
# based on.
|
| 216 |
+
# http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1559964&isnumber=33129
|
| 217 |
+
G = nx.Graph()
|
| 218 |
+
edges_fig_4 = [
|
| 219 |
+
("a", "b"),
|
| 220 |
+
("a", "c"),
|
| 221 |
+
("a", "d"),
|
| 222 |
+
("a", "e"),
|
| 223 |
+
("b", "c"),
|
| 224 |
+
("b", "d"),
|
| 225 |
+
("b", "e"),
|
| 226 |
+
("c", "d"),
|
| 227 |
+
("c", "e"),
|
| 228 |
+
("d", "e"),
|
| 229 |
+
("f", "b"),
|
| 230 |
+
("f", "c"),
|
| 231 |
+
("f", "g"),
|
| 232 |
+
("g", "f"),
|
| 233 |
+
("g", "c"),
|
| 234 |
+
("g", "d"),
|
| 235 |
+
("g", "e"),
|
| 236 |
+
]
|
| 237 |
+
G.add_edges_from(edges_fig_4)
|
| 238 |
+
|
| 239 |
+
cliques = list(nx.enumerate_all_cliques(G))
|
| 240 |
+
clique_sizes = list(map(len, cliques))
|
| 241 |
+
assert sorted(clique_sizes) == clique_sizes
|
| 242 |
+
|
| 243 |
+
expected_cliques = [
|
| 244 |
+
["a"],
|
| 245 |
+
["b"],
|
| 246 |
+
["c"],
|
| 247 |
+
["d"],
|
| 248 |
+
["e"],
|
| 249 |
+
["f"],
|
| 250 |
+
["g"],
|
| 251 |
+
["a", "b"],
|
| 252 |
+
["a", "b", "d"],
|
| 253 |
+
["a", "b", "d", "e"],
|
| 254 |
+
["a", "b", "e"],
|
| 255 |
+
["a", "c"],
|
| 256 |
+
["a", "c", "d"],
|
| 257 |
+
["a", "c", "d", "e"],
|
| 258 |
+
["a", "c", "e"],
|
| 259 |
+
["a", "d"],
|
| 260 |
+
["a", "d", "e"],
|
| 261 |
+
["a", "e"],
|
| 262 |
+
["b", "c"],
|
| 263 |
+
["b", "c", "d"],
|
| 264 |
+
["b", "c", "d", "e"],
|
| 265 |
+
["b", "c", "e"],
|
| 266 |
+
["b", "c", "f"],
|
| 267 |
+
["b", "d"],
|
| 268 |
+
["b", "d", "e"],
|
| 269 |
+
["b", "e"],
|
| 270 |
+
["b", "f"],
|
| 271 |
+
["c", "d"],
|
| 272 |
+
["c", "d", "e"],
|
| 273 |
+
["c", "d", "e", "g"],
|
| 274 |
+
["c", "d", "g"],
|
| 275 |
+
["c", "e"],
|
| 276 |
+
["c", "e", "g"],
|
| 277 |
+
["c", "f"],
|
| 278 |
+
["c", "f", "g"],
|
| 279 |
+
["c", "g"],
|
| 280 |
+
["d", "e"],
|
| 281 |
+
["d", "e", "g"],
|
| 282 |
+
["d", "g"],
|
| 283 |
+
["e", "g"],
|
| 284 |
+
["f", "g"],
|
| 285 |
+
["a", "b", "c"],
|
| 286 |
+
["a", "b", "c", "d"],
|
| 287 |
+
["a", "b", "c", "d", "e"],
|
| 288 |
+
["a", "b", "c", "e"],
|
| 289 |
+
]
|
| 290 |
+
|
| 291 |
+
assert sorted(map(sorted, cliques)) == sorted(map(sorted, expected_cliques))
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_cluster.py
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestTriangles:
|
| 7 |
+
def test_empty(self):
|
| 8 |
+
G = nx.Graph()
|
| 9 |
+
assert list(nx.triangles(G).values()) == []
|
| 10 |
+
|
| 11 |
+
def test_path(self):
|
| 12 |
+
G = nx.path_graph(10)
|
| 13 |
+
assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
| 14 |
+
assert nx.triangles(G) == {
|
| 15 |
+
0: 0,
|
| 16 |
+
1: 0,
|
| 17 |
+
2: 0,
|
| 18 |
+
3: 0,
|
| 19 |
+
4: 0,
|
| 20 |
+
5: 0,
|
| 21 |
+
6: 0,
|
| 22 |
+
7: 0,
|
| 23 |
+
8: 0,
|
| 24 |
+
9: 0,
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
def test_cubical(self):
|
| 28 |
+
G = nx.cubical_graph()
|
| 29 |
+
assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
|
| 30 |
+
assert nx.triangles(G, 1) == 0
|
| 31 |
+
assert list(nx.triangles(G, [1, 2]).values()) == [0, 0]
|
| 32 |
+
assert nx.triangles(G, 1) == 0
|
| 33 |
+
assert nx.triangles(G, [1, 2]) == {1: 0, 2: 0}
|
| 34 |
+
|
| 35 |
+
def test_k5(self):
|
| 36 |
+
G = nx.complete_graph(5)
|
| 37 |
+
assert list(nx.triangles(G).values()) == [6, 6, 6, 6, 6]
|
| 38 |
+
assert sum(nx.triangles(G).values()) / 3 == 10
|
| 39 |
+
assert nx.triangles(G, 1) == 6
|
| 40 |
+
G.remove_edge(1, 2)
|
| 41 |
+
assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
|
| 42 |
+
assert nx.triangles(G, 1) == 3
|
| 43 |
+
G.add_edge(3, 3) # ignore self-edges
|
| 44 |
+
assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
|
| 45 |
+
assert nx.triangles(G, 3) == 5
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestDirectedClustering:
|
| 49 |
+
def test_clustering(self):
|
| 50 |
+
G = nx.DiGraph()
|
| 51 |
+
assert list(nx.clustering(G).values()) == []
|
| 52 |
+
assert nx.clustering(G) == {}
|
| 53 |
+
|
| 54 |
+
def test_path(self):
|
| 55 |
+
G = nx.path_graph(10, create_using=nx.DiGraph())
|
| 56 |
+
assert list(nx.clustering(G).values()) == [
|
| 57 |
+
0,
|
| 58 |
+
0,
|
| 59 |
+
0,
|
| 60 |
+
0,
|
| 61 |
+
0,
|
| 62 |
+
0,
|
| 63 |
+
0,
|
| 64 |
+
0,
|
| 65 |
+
0,
|
| 66 |
+
0,
|
| 67 |
+
]
|
| 68 |
+
assert nx.clustering(G) == {
|
| 69 |
+
0: 0,
|
| 70 |
+
1: 0,
|
| 71 |
+
2: 0,
|
| 72 |
+
3: 0,
|
| 73 |
+
4: 0,
|
| 74 |
+
5: 0,
|
| 75 |
+
6: 0,
|
| 76 |
+
7: 0,
|
| 77 |
+
8: 0,
|
| 78 |
+
9: 0,
|
| 79 |
+
}
|
| 80 |
+
assert nx.clustering(G, 0) == 0
|
| 81 |
+
|
| 82 |
+
def test_k5(self):
|
| 83 |
+
G = nx.complete_graph(5, create_using=nx.DiGraph())
|
| 84 |
+
assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
|
| 85 |
+
assert nx.average_clustering(G) == 1
|
| 86 |
+
G.remove_edge(1, 2)
|
| 87 |
+
assert list(nx.clustering(G).values()) == [
|
| 88 |
+
11 / 12,
|
| 89 |
+
1,
|
| 90 |
+
1,
|
| 91 |
+
11 / 12,
|
| 92 |
+
11 / 12,
|
| 93 |
+
]
|
| 94 |
+
assert nx.clustering(G, [1, 4]) == {1: 1, 4: 11 / 12}
|
| 95 |
+
G.remove_edge(2, 1)
|
| 96 |
+
assert list(nx.clustering(G).values()) == [
|
| 97 |
+
5 / 6,
|
| 98 |
+
1,
|
| 99 |
+
1,
|
| 100 |
+
5 / 6,
|
| 101 |
+
5 / 6,
|
| 102 |
+
]
|
| 103 |
+
assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
|
| 104 |
+
assert nx.clustering(G, 4) == 5 / 6
|
| 105 |
+
|
| 106 |
+
def test_triangle_and_edge(self):
|
| 107 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
| 108 |
+
G.add_edge(0, 4)
|
| 109 |
+
assert nx.clustering(G)[0] == 1 / 6
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class TestDirectedWeightedClustering:
|
| 113 |
+
@classmethod
|
| 114 |
+
def setup_class(cls):
|
| 115 |
+
global np
|
| 116 |
+
np = pytest.importorskip("numpy")
|
| 117 |
+
|
| 118 |
+
def test_clustering(self):
|
| 119 |
+
G = nx.DiGraph()
|
| 120 |
+
assert list(nx.clustering(G, weight="weight").values()) == []
|
| 121 |
+
assert nx.clustering(G) == {}
|
| 122 |
+
|
| 123 |
+
def test_path(self):
|
| 124 |
+
G = nx.path_graph(10, create_using=nx.DiGraph())
|
| 125 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 126 |
+
0,
|
| 127 |
+
0,
|
| 128 |
+
0,
|
| 129 |
+
0,
|
| 130 |
+
0,
|
| 131 |
+
0,
|
| 132 |
+
0,
|
| 133 |
+
0,
|
| 134 |
+
0,
|
| 135 |
+
0,
|
| 136 |
+
]
|
| 137 |
+
assert nx.clustering(G, weight="weight") == {
|
| 138 |
+
0: 0,
|
| 139 |
+
1: 0,
|
| 140 |
+
2: 0,
|
| 141 |
+
3: 0,
|
| 142 |
+
4: 0,
|
| 143 |
+
5: 0,
|
| 144 |
+
6: 0,
|
| 145 |
+
7: 0,
|
| 146 |
+
8: 0,
|
| 147 |
+
9: 0,
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
def test_k5(self):
|
| 151 |
+
G = nx.complete_graph(5, create_using=nx.DiGraph())
|
| 152 |
+
assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
|
| 153 |
+
assert nx.average_clustering(G, weight="weight") == 1
|
| 154 |
+
G.remove_edge(1, 2)
|
| 155 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 156 |
+
11 / 12,
|
| 157 |
+
1,
|
| 158 |
+
1,
|
| 159 |
+
11 / 12,
|
| 160 |
+
11 / 12,
|
| 161 |
+
]
|
| 162 |
+
assert nx.clustering(G, [1, 4], weight="weight") == {1: 1, 4: 11 / 12}
|
| 163 |
+
G.remove_edge(2, 1)
|
| 164 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 165 |
+
5 / 6,
|
| 166 |
+
1,
|
| 167 |
+
1,
|
| 168 |
+
5 / 6,
|
| 169 |
+
5 / 6,
|
| 170 |
+
]
|
| 171 |
+
assert nx.clustering(G, [1, 4], weight="weight") == {
|
| 172 |
+
1: 1,
|
| 173 |
+
4: 0.83333333333333337,
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
def test_triangle_and_edge(self):
|
| 177 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
| 178 |
+
G.add_edge(0, 4, weight=2)
|
| 179 |
+
assert nx.clustering(G)[0] == 1 / 6
|
| 180 |
+
# Relaxed comparisons to allow graphblas-algorithms to pass tests
|
| 181 |
+
np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 12)
|
| 182 |
+
np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 12)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class TestWeightedClustering:
|
| 186 |
+
@classmethod
|
| 187 |
+
def setup_class(cls):
|
| 188 |
+
global np
|
| 189 |
+
np = pytest.importorskip("numpy")
|
| 190 |
+
|
| 191 |
+
def test_clustering(self):
|
| 192 |
+
G = nx.Graph()
|
| 193 |
+
assert list(nx.clustering(G, weight="weight").values()) == []
|
| 194 |
+
assert nx.clustering(G) == {}
|
| 195 |
+
|
| 196 |
+
def test_path(self):
|
| 197 |
+
G = nx.path_graph(10)
|
| 198 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 199 |
+
0,
|
| 200 |
+
0,
|
| 201 |
+
0,
|
| 202 |
+
0,
|
| 203 |
+
0,
|
| 204 |
+
0,
|
| 205 |
+
0,
|
| 206 |
+
0,
|
| 207 |
+
0,
|
| 208 |
+
0,
|
| 209 |
+
]
|
| 210 |
+
assert nx.clustering(G, weight="weight") == {
|
| 211 |
+
0: 0,
|
| 212 |
+
1: 0,
|
| 213 |
+
2: 0,
|
| 214 |
+
3: 0,
|
| 215 |
+
4: 0,
|
| 216 |
+
5: 0,
|
| 217 |
+
6: 0,
|
| 218 |
+
7: 0,
|
| 219 |
+
8: 0,
|
| 220 |
+
9: 0,
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
def test_cubical(self):
|
| 224 |
+
G = nx.cubical_graph()
|
| 225 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 226 |
+
0,
|
| 227 |
+
0,
|
| 228 |
+
0,
|
| 229 |
+
0,
|
| 230 |
+
0,
|
| 231 |
+
0,
|
| 232 |
+
0,
|
| 233 |
+
0,
|
| 234 |
+
]
|
| 235 |
+
assert nx.clustering(G, 1) == 0
|
| 236 |
+
assert list(nx.clustering(G, [1, 2], weight="weight").values()) == [0, 0]
|
| 237 |
+
assert nx.clustering(G, 1, weight="weight") == 0
|
| 238 |
+
assert nx.clustering(G, [1, 2], weight="weight") == {1: 0, 2: 0}
|
| 239 |
+
|
| 240 |
+
def test_k5(self):
|
| 241 |
+
G = nx.complete_graph(5)
|
| 242 |
+
assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
|
| 243 |
+
assert nx.average_clustering(G, weight="weight") == 1
|
| 244 |
+
G.remove_edge(1, 2)
|
| 245 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 246 |
+
5 / 6,
|
| 247 |
+
1,
|
| 248 |
+
1,
|
| 249 |
+
5 / 6,
|
| 250 |
+
5 / 6,
|
| 251 |
+
]
|
| 252 |
+
assert nx.clustering(G, [1, 4], weight="weight") == {
|
| 253 |
+
1: 1,
|
| 254 |
+
4: 0.83333333333333337,
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
def test_triangle_and_edge(self):
|
| 258 |
+
G = nx.cycle_graph(3)
|
| 259 |
+
G.add_edge(0, 4, weight=2)
|
| 260 |
+
assert nx.clustering(G)[0] == 1 / 3
|
| 261 |
+
np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 6)
|
| 262 |
+
np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 6)
|
| 263 |
+
|
| 264 |
+
def test_triangle_and_signed_edge(self):
|
| 265 |
+
G = nx.cycle_graph(3)
|
| 266 |
+
G.add_edge(0, 1, weight=-1)
|
| 267 |
+
G.add_edge(3, 0, weight=0)
|
| 268 |
+
assert nx.clustering(G)[0] == 1 / 3
|
| 269 |
+
assert nx.clustering(G, weight="weight")[0] == -1 / 3
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class TestClustering:
|
| 273 |
+
@classmethod
|
| 274 |
+
def setup_class(cls):
|
| 275 |
+
pytest.importorskip("numpy")
|
| 276 |
+
|
| 277 |
+
def test_clustering(self):
|
| 278 |
+
G = nx.Graph()
|
| 279 |
+
assert list(nx.clustering(G).values()) == []
|
| 280 |
+
assert nx.clustering(G) == {}
|
| 281 |
+
|
| 282 |
+
def test_path(self):
|
| 283 |
+
G = nx.path_graph(10)
|
| 284 |
+
assert list(nx.clustering(G).values()) == [
|
| 285 |
+
0,
|
| 286 |
+
0,
|
| 287 |
+
0,
|
| 288 |
+
0,
|
| 289 |
+
0,
|
| 290 |
+
0,
|
| 291 |
+
0,
|
| 292 |
+
0,
|
| 293 |
+
0,
|
| 294 |
+
0,
|
| 295 |
+
]
|
| 296 |
+
assert nx.clustering(G) == {
|
| 297 |
+
0: 0,
|
| 298 |
+
1: 0,
|
| 299 |
+
2: 0,
|
| 300 |
+
3: 0,
|
| 301 |
+
4: 0,
|
| 302 |
+
5: 0,
|
| 303 |
+
6: 0,
|
| 304 |
+
7: 0,
|
| 305 |
+
8: 0,
|
| 306 |
+
9: 0,
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
def test_cubical(self):
|
| 310 |
+
G = nx.cubical_graph()
|
| 311 |
+
assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
|
| 312 |
+
assert nx.clustering(G, 1) == 0
|
| 313 |
+
assert list(nx.clustering(G, [1, 2]).values()) == [0, 0]
|
| 314 |
+
assert nx.clustering(G, 1) == 0
|
| 315 |
+
assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0}
|
| 316 |
+
|
| 317 |
+
def test_k5(self):
|
| 318 |
+
G = nx.complete_graph(5)
|
| 319 |
+
assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
|
| 320 |
+
assert nx.average_clustering(G) == 1
|
| 321 |
+
G.remove_edge(1, 2)
|
| 322 |
+
assert list(nx.clustering(G).values()) == [
|
| 323 |
+
5 / 6,
|
| 324 |
+
1,
|
| 325 |
+
1,
|
| 326 |
+
5 / 6,
|
| 327 |
+
5 / 6,
|
| 328 |
+
]
|
| 329 |
+
assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
|
| 330 |
+
|
| 331 |
+
def test_k5_signed(self):
|
| 332 |
+
G = nx.complete_graph(5)
|
| 333 |
+
assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
|
| 334 |
+
assert nx.average_clustering(G) == 1
|
| 335 |
+
G.remove_edge(1, 2)
|
| 336 |
+
G.add_edge(0, 1, weight=-1)
|
| 337 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
| 338 |
+
1 / 6,
|
| 339 |
+
-1 / 3,
|
| 340 |
+
1,
|
| 341 |
+
3 / 6,
|
| 342 |
+
3 / 6,
|
| 343 |
+
]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class TestTransitivity:
|
| 347 |
+
def test_transitivity(self):
|
| 348 |
+
G = nx.Graph()
|
| 349 |
+
assert nx.transitivity(G) == 0
|
| 350 |
+
|
| 351 |
+
def test_path(self):
|
| 352 |
+
G = nx.path_graph(10)
|
| 353 |
+
assert nx.transitivity(G) == 0
|
| 354 |
+
|
| 355 |
+
def test_cubical(self):
|
| 356 |
+
G = nx.cubical_graph()
|
| 357 |
+
assert nx.transitivity(G) == 0
|
| 358 |
+
|
| 359 |
+
def test_k5(self):
|
| 360 |
+
G = nx.complete_graph(5)
|
| 361 |
+
assert nx.transitivity(G) == 1
|
| 362 |
+
G.remove_edge(1, 2)
|
| 363 |
+
assert nx.transitivity(G) == 0.875
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class TestSquareClustering:
|
| 367 |
+
def test_clustering(self):
|
| 368 |
+
G = nx.Graph()
|
| 369 |
+
assert list(nx.square_clustering(G).values()) == []
|
| 370 |
+
assert nx.square_clustering(G) == {}
|
| 371 |
+
|
| 372 |
+
def test_path(self):
|
| 373 |
+
G = nx.path_graph(10)
|
| 374 |
+
assert list(nx.square_clustering(G).values()) == [
|
| 375 |
+
0,
|
| 376 |
+
0,
|
| 377 |
+
0,
|
| 378 |
+
0,
|
| 379 |
+
0,
|
| 380 |
+
0,
|
| 381 |
+
0,
|
| 382 |
+
0,
|
| 383 |
+
0,
|
| 384 |
+
0,
|
| 385 |
+
]
|
| 386 |
+
assert nx.square_clustering(G) == {
|
| 387 |
+
0: 0,
|
| 388 |
+
1: 0,
|
| 389 |
+
2: 0,
|
| 390 |
+
3: 0,
|
| 391 |
+
4: 0,
|
| 392 |
+
5: 0,
|
| 393 |
+
6: 0,
|
| 394 |
+
7: 0,
|
| 395 |
+
8: 0,
|
| 396 |
+
9: 0,
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
def test_cubical(self):
|
| 400 |
+
G = nx.cubical_graph()
|
| 401 |
+
assert list(nx.square_clustering(G).values()) == [
|
| 402 |
+
1 / 3,
|
| 403 |
+
1 / 3,
|
| 404 |
+
1 / 3,
|
| 405 |
+
1 / 3,
|
| 406 |
+
1 / 3,
|
| 407 |
+
1 / 3,
|
| 408 |
+
1 / 3,
|
| 409 |
+
1 / 3,
|
| 410 |
+
]
|
| 411 |
+
assert list(nx.square_clustering(G, [1, 2]).values()) == [1 / 3, 1 / 3]
|
| 412 |
+
assert nx.square_clustering(G, [1])[1] == 1 / 3
|
| 413 |
+
assert nx.square_clustering(G, 1) == 1 / 3
|
| 414 |
+
assert nx.square_clustering(G, [1, 2]) == {1: 1 / 3, 2: 1 / 3}
|
| 415 |
+
|
| 416 |
+
def test_k5(self):
|
| 417 |
+
G = nx.complete_graph(5)
|
| 418 |
+
assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1]
|
| 419 |
+
|
| 420 |
+
def test_bipartite_k5(self):
|
| 421 |
+
G = nx.complete_bipartite_graph(5, 5)
|
| 422 |
+
assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
|
| 423 |
+
|
| 424 |
+
def test_lind_square_clustering(self):
|
| 425 |
+
"""Test C4 for figure 1 Lind et al (2005)"""
|
| 426 |
+
G = nx.Graph(
|
| 427 |
+
[
|
| 428 |
+
(1, 2),
|
| 429 |
+
(1, 3),
|
| 430 |
+
(1, 6),
|
| 431 |
+
(1, 7),
|
| 432 |
+
(2, 4),
|
| 433 |
+
(2, 5),
|
| 434 |
+
(3, 4),
|
| 435 |
+
(3, 5),
|
| 436 |
+
(6, 7),
|
| 437 |
+
(7, 8),
|
| 438 |
+
(6, 8),
|
| 439 |
+
(7, 9),
|
| 440 |
+
(7, 10),
|
| 441 |
+
(6, 11),
|
| 442 |
+
(6, 12),
|
| 443 |
+
(2, 13),
|
| 444 |
+
(2, 14),
|
| 445 |
+
(3, 15),
|
| 446 |
+
(3, 16),
|
| 447 |
+
]
|
| 448 |
+
)
|
| 449 |
+
G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16])
|
| 450 |
+
G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12])
|
| 451 |
+
assert nx.square_clustering(G, [1])[1] == 3 / 43
|
| 452 |
+
assert nx.square_clustering(G1, [1])[1] == 2 / 6
|
| 453 |
+
assert nx.square_clustering(G2, [1])[1] == 1 / 5
|
| 454 |
+
|
| 455 |
+
def test_peng_square_clustering(self):
|
| 456 |
+
"""Test eq2 for figure 1 Peng et al (2008)"""
|
| 457 |
+
G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (3, 6)])
|
| 458 |
+
assert nx.square_clustering(G, [1])[1] == 1 / 3
|
| 459 |
+
|
| 460 |
+
def test_self_loops_square_clustering(self):
|
| 461 |
+
G = nx.path_graph(5)
|
| 462 |
+
assert nx.square_clustering(G) == {0: 0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0}
|
| 463 |
+
G.add_edges_from([(0, 0), (1, 1), (2, 2)])
|
| 464 |
+
assert nx.square_clustering(G) == {0: 1, 1: 0.5, 2: 0.2, 3: 0.0, 4: 0}
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class TestAverageClustering:
|
| 468 |
+
@classmethod
|
| 469 |
+
def setup_class(cls):
|
| 470 |
+
pytest.importorskip("numpy")
|
| 471 |
+
|
| 472 |
+
def test_empty(self):
|
| 473 |
+
G = nx.Graph()
|
| 474 |
+
with pytest.raises(ZeroDivisionError):
|
| 475 |
+
nx.average_clustering(G)
|
| 476 |
+
|
| 477 |
+
def test_average_clustering(self):
|
| 478 |
+
G = nx.cycle_graph(3)
|
| 479 |
+
G.add_edge(2, 3)
|
| 480 |
+
assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 4
|
| 481 |
+
assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 4
|
| 482 |
+
assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 3
|
| 483 |
+
assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 3
|
| 484 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 3
|
| 485 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 2
|
| 486 |
+
|
| 487 |
+
def test_average_clustering_signed(self):
|
| 488 |
+
G = nx.cycle_graph(3)
|
| 489 |
+
G.add_edge(2, 3)
|
| 490 |
+
G.add_edge(0, 1, weight=-1)
|
| 491 |
+
assert nx.average_clustering(G, weight="weight") == (-1 - 1 - 1 / 3) / 4
|
| 492 |
+
assert (
|
| 493 |
+
nx.average_clustering(G, weight="weight", count_zeros=True)
|
| 494 |
+
== (-1 - 1 - 1 / 3) / 4
|
| 495 |
+
)
|
| 496 |
+
assert (
|
| 497 |
+
nx.average_clustering(G, weight="weight", count_zeros=False)
|
| 498 |
+
== (-1 - 1 - 1 / 3) / 3
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
class TestDirectedAverageClustering:
|
| 503 |
+
@classmethod
|
| 504 |
+
def setup_class(cls):
|
| 505 |
+
pytest.importorskip("numpy")
|
| 506 |
+
|
| 507 |
+
def test_empty(self):
|
| 508 |
+
G = nx.DiGraph()
|
| 509 |
+
with pytest.raises(ZeroDivisionError):
|
| 510 |
+
nx.average_clustering(G)
|
| 511 |
+
|
| 512 |
+
def test_average_clustering(self):
|
| 513 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
| 514 |
+
G.add_edge(2, 3)
|
| 515 |
+
assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 8
|
| 516 |
+
assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 8
|
| 517 |
+
assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 6
|
| 518 |
+
assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 6
|
| 519 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 6
|
| 520 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 4
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class TestGeneralizedDegree:
|
| 524 |
+
def test_generalized_degree(self):
|
| 525 |
+
G = nx.Graph()
|
| 526 |
+
assert nx.generalized_degree(G) == {}
|
| 527 |
+
|
| 528 |
+
def test_path(self):
|
| 529 |
+
G = nx.path_graph(5)
|
| 530 |
+
assert nx.generalized_degree(G, 0) == {0: 1}
|
| 531 |
+
assert nx.generalized_degree(G, 1) == {0: 2}
|
| 532 |
+
|
| 533 |
+
def test_cubical(self):
|
| 534 |
+
G = nx.cubical_graph()
|
| 535 |
+
assert nx.generalized_degree(G, 0) == {0: 3}
|
| 536 |
+
|
| 537 |
+
def test_k5(self):
|
| 538 |
+
G = nx.complete_graph(5)
|
| 539 |
+
assert nx.generalized_degree(G, 0) == {3: 4}
|
| 540 |
+
G.remove_edge(0, 1)
|
| 541 |
+
assert nx.generalized_degree(G, 0) == {2: 3}
|
| 542 |
+
assert nx.generalized_degree(G, [1, 2]) == {1: {2: 3}, 2: {2: 2, 3: 2}}
|
| 543 |
+
assert nx.generalized_degree(G) == {
|
| 544 |
+
0: {2: 3},
|
| 545 |
+
1: {2: 3},
|
| 546 |
+
2: {2: 2, 3: 2},
|
| 547 |
+
3: {2: 2, 3: 2},
|
| 548 |
+
4: {2: 2, 3: 2},
|
| 549 |
+
}
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
pytest.importorskip("numpy")
|
| 6 |
+
pytest.importorskip("scipy")
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
from networkx.algorithms.communicability_alg import communicability, communicability_exp
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestCommunicability:
|
| 13 |
+
def test_communicability(self):
|
| 14 |
+
answer = {
|
| 15 |
+
0: {0: 1.5430806348152435, 1: 1.1752011936438012},
|
| 16 |
+
1: {0: 1.1752011936438012, 1: 1.5430806348152435},
|
| 17 |
+
}
|
| 18 |
+
# answer={(0, 0): 1.5430806348152435,
|
| 19 |
+
# (0, 1): 1.1752011936438012,
|
| 20 |
+
# (1, 0): 1.1752011936438012,
|
| 21 |
+
# (1, 1): 1.5430806348152435}
|
| 22 |
+
|
| 23 |
+
result = communicability(nx.path_graph(2))
|
| 24 |
+
for k1, val in result.items():
|
| 25 |
+
for k2 in val:
|
| 26 |
+
assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
|
| 27 |
+
|
| 28 |
+
def test_communicability2(self):
|
| 29 |
+
answer_orig = {
|
| 30 |
+
("1", "1"): 1.6445956054135658,
|
| 31 |
+
("1", "Albert"): 0.7430186221096251,
|
| 32 |
+
("1", "Aric"): 0.7430186221096251,
|
| 33 |
+
("1", "Dan"): 1.6208126320442937,
|
| 34 |
+
("1", "Franck"): 0.42639707170035257,
|
| 35 |
+
("Albert", "1"): 0.7430186221096251,
|
| 36 |
+
("Albert", "Albert"): 2.4368257358712189,
|
| 37 |
+
("Albert", "Aric"): 1.4368257358712191,
|
| 38 |
+
("Albert", "Dan"): 2.0472097037446453,
|
| 39 |
+
("Albert", "Franck"): 1.8340111678944691,
|
| 40 |
+
("Aric", "1"): 0.7430186221096251,
|
| 41 |
+
("Aric", "Albert"): 1.4368257358712191,
|
| 42 |
+
("Aric", "Aric"): 2.4368257358712193,
|
| 43 |
+
("Aric", "Dan"): 2.0472097037446457,
|
| 44 |
+
("Aric", "Franck"): 1.8340111678944691,
|
| 45 |
+
("Dan", "1"): 1.6208126320442937,
|
| 46 |
+
("Dan", "Albert"): 2.0472097037446453,
|
| 47 |
+
("Dan", "Aric"): 2.0472097037446457,
|
| 48 |
+
("Dan", "Dan"): 3.1306328496328168,
|
| 49 |
+
("Dan", "Franck"): 1.4860372442192515,
|
| 50 |
+
("Franck", "1"): 0.42639707170035257,
|
| 51 |
+
("Franck", "Albert"): 1.8340111678944691,
|
| 52 |
+
("Franck", "Aric"): 1.8340111678944691,
|
| 53 |
+
("Franck", "Dan"): 1.4860372442192515,
|
| 54 |
+
("Franck", "Franck"): 2.3876142275231915,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
answer = defaultdict(dict)
|
| 58 |
+
for (k1, k2), v in answer_orig.items():
|
| 59 |
+
answer[k1][k2] = v
|
| 60 |
+
|
| 61 |
+
G1 = nx.Graph(
|
| 62 |
+
[
|
| 63 |
+
("Franck", "Aric"),
|
| 64 |
+
("Aric", "Dan"),
|
| 65 |
+
("Dan", "Albert"),
|
| 66 |
+
("Albert", "Franck"),
|
| 67 |
+
("Dan", "1"),
|
| 68 |
+
("Franck", "Albert"),
|
| 69 |
+
]
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
result = communicability(G1)
|
| 73 |
+
for k1, val in result.items():
|
| 74 |
+
for k2 in val:
|
| 75 |
+
assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
|
| 76 |
+
|
| 77 |
+
result = communicability_exp(G1)
|
| 78 |
+
for k1, val in result.items():
|
| 79 |
+
for k2 in val:
|
| 80 |
+
assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_core.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import nodes_equal
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestCore:
|
| 8 |
+
@classmethod
|
| 9 |
+
def setup_class(cls):
|
| 10 |
+
# G is the example graph in Figure 1 from Batagelj and
|
| 11 |
+
# Zaversnik's paper titled An O(m) Algorithm for Cores
|
| 12 |
+
# Decomposition of Networks, 2003,
|
| 13 |
+
# http://arXiv.org/abs/cs/0310049. With nodes labeled as
|
| 14 |
+
# shown, the 3-core is given by nodes 1-8, the 2-core by nodes
|
| 15 |
+
# 9-16, the 1-core by nodes 17-20 and node 21 is in the
|
| 16 |
+
# 0-core.
|
| 17 |
+
t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1)
|
| 18 |
+
t2 = nx.convert_node_labels_to_integers(t1, 5)
|
| 19 |
+
G = nx.union(t1, t2)
|
| 20 |
+
G.add_edges_from(
|
| 21 |
+
[
|
| 22 |
+
(3, 7),
|
| 23 |
+
(2, 11),
|
| 24 |
+
(11, 5),
|
| 25 |
+
(11, 12),
|
| 26 |
+
(5, 12),
|
| 27 |
+
(12, 19),
|
| 28 |
+
(12, 18),
|
| 29 |
+
(3, 9),
|
| 30 |
+
(7, 9),
|
| 31 |
+
(7, 10),
|
| 32 |
+
(9, 10),
|
| 33 |
+
(9, 20),
|
| 34 |
+
(17, 13),
|
| 35 |
+
(13, 14),
|
| 36 |
+
(14, 15),
|
| 37 |
+
(15, 16),
|
| 38 |
+
(16, 13),
|
| 39 |
+
]
|
| 40 |
+
)
|
| 41 |
+
G.add_node(21)
|
| 42 |
+
cls.G = G
|
| 43 |
+
|
| 44 |
+
# Create the graph H resulting from the degree sequence
|
| 45 |
+
# [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm.
|
| 46 |
+
|
| 47 |
+
degseq = [0, 1, 2, 2, 2, 2, 3]
|
| 48 |
+
H = nx.havel_hakimi_graph(degseq)
|
| 49 |
+
mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5}
|
| 50 |
+
cls.H = nx.relabel_nodes(H, mapping)
|
| 51 |
+
|
| 52 |
+
def test_trivial(self):
|
| 53 |
+
"""Empty graph"""
|
| 54 |
+
G = nx.Graph()
|
| 55 |
+
assert nx.core_number(G) == {}
|
| 56 |
+
|
| 57 |
+
def test_core_number(self):
|
| 58 |
+
core = nx.core_number(self.G)
|
| 59 |
+
nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(4)]
|
| 60 |
+
assert nodes_equal(nodes_by_core[0], [21])
|
| 61 |
+
assert nodes_equal(nodes_by_core[1], [17, 18, 19, 20])
|
| 62 |
+
assert nodes_equal(nodes_by_core[2], [9, 10, 11, 12, 13, 14, 15, 16])
|
| 63 |
+
assert nodes_equal(nodes_by_core[3], [1, 2, 3, 4, 5, 6, 7, 8])
|
| 64 |
+
|
| 65 |
+
def test_core_number2(self):
|
| 66 |
+
core = nx.core_number(self.H)
|
| 67 |
+
nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(3)]
|
| 68 |
+
assert nodes_equal(nodes_by_core[0], [0])
|
| 69 |
+
assert nodes_equal(nodes_by_core[1], [1, 3])
|
| 70 |
+
assert nodes_equal(nodes_by_core[2], [2, 4, 5, 6])
|
| 71 |
+
|
| 72 |
+
def test_core_number_multigraph(self):
|
| 73 |
+
G = nx.complete_graph(3)
|
| 74 |
+
G = nx.MultiGraph(G)
|
| 75 |
+
G.add_edge(1, 2)
|
| 76 |
+
with pytest.raises(
|
| 77 |
+
nx.NetworkXNotImplemented, match="not implemented for multigraph type"
|
| 78 |
+
):
|
| 79 |
+
nx.core_number(G)
|
| 80 |
+
|
| 81 |
+
def test_core_number_self_loop(self):
|
| 82 |
+
G = nx.cycle_graph(3)
|
| 83 |
+
G.add_edge(0, 0)
|
| 84 |
+
with pytest.raises(
|
| 85 |
+
nx.NetworkXNotImplemented, match="Input graph has self loops"
|
| 86 |
+
):
|
| 87 |
+
nx.core_number(G)
|
| 88 |
+
|
| 89 |
+
def test_directed_core_number(self):
|
| 90 |
+
"""core number had a bug for directed graphs found in issue #1959"""
|
| 91 |
+
# small example where too timid edge removal can make cn[2] = 3
|
| 92 |
+
G = nx.DiGraph()
|
| 93 |
+
edges = [(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)]
|
| 94 |
+
G.add_edges_from(edges)
|
| 95 |
+
assert nx.core_number(G) == {1: 2, 2: 2, 3: 2, 4: 2}
|
| 96 |
+
# small example where too aggressive edge removal can make cn[2] = 2
|
| 97 |
+
more_edges = [(1, 5), (3, 5), (4, 5), (3, 6), (4, 6), (5, 6)]
|
| 98 |
+
G.add_edges_from(more_edges)
|
| 99 |
+
assert nx.core_number(G) == {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3}
|
| 100 |
+
|
| 101 |
+
def test_main_core(self):
|
| 102 |
+
main_core_subgraph = nx.k_core(self.H)
|
| 103 |
+
assert sorted(main_core_subgraph.nodes()) == [2, 4, 5, 6]
|
| 104 |
+
|
| 105 |
+
def test_k_core(self):
|
| 106 |
+
# k=0
|
| 107 |
+
k_core_subgraph = nx.k_core(self.H, k=0)
|
| 108 |
+
assert sorted(k_core_subgraph.nodes()) == sorted(self.H.nodes())
|
| 109 |
+
# k=1
|
| 110 |
+
k_core_subgraph = nx.k_core(self.H, k=1)
|
| 111 |
+
assert sorted(k_core_subgraph.nodes()) == [1, 2, 3, 4, 5, 6]
|
| 112 |
+
# k = 2
|
| 113 |
+
k_core_subgraph = nx.k_core(self.H, k=2)
|
| 114 |
+
assert sorted(k_core_subgraph.nodes()) == [2, 4, 5, 6]
|
| 115 |
+
|
| 116 |
+
def test_k_core_multigraph(self):
|
| 117 |
+
core_number = nx.core_number(self.H)
|
| 118 |
+
H = nx.MultiGraph(self.H)
|
| 119 |
+
with pytest.deprecated_call():
|
| 120 |
+
nx.k_core(H, k=0, core_number=core_number)
|
| 121 |
+
|
| 122 |
+
def test_main_crust(self):
|
| 123 |
+
main_crust_subgraph = nx.k_crust(self.H)
|
| 124 |
+
assert sorted(main_crust_subgraph.nodes()) == [0, 1, 3]
|
| 125 |
+
|
| 126 |
+
def test_k_crust(self):
|
| 127 |
+
# k = 0
|
| 128 |
+
k_crust_subgraph = nx.k_crust(self.H, k=2)
|
| 129 |
+
assert sorted(k_crust_subgraph.nodes()) == sorted(self.H.nodes())
|
| 130 |
+
# k=1
|
| 131 |
+
k_crust_subgraph = nx.k_crust(self.H, k=1)
|
| 132 |
+
assert sorted(k_crust_subgraph.nodes()) == [0, 1, 3]
|
| 133 |
+
# k=2
|
| 134 |
+
k_crust_subgraph = nx.k_crust(self.H, k=0)
|
| 135 |
+
assert sorted(k_crust_subgraph.nodes()) == [0]
|
| 136 |
+
|
| 137 |
+
def test_k_crust_multigraph(self):
|
| 138 |
+
core_number = nx.core_number(self.H)
|
| 139 |
+
H = nx.MultiGraph(self.H)
|
| 140 |
+
with pytest.deprecated_call():
|
| 141 |
+
nx.k_crust(H, k=0, core_number=core_number)
|
| 142 |
+
|
| 143 |
+
def test_main_shell(self):
|
| 144 |
+
main_shell_subgraph = nx.k_shell(self.H)
|
| 145 |
+
assert sorted(main_shell_subgraph.nodes()) == [2, 4, 5, 6]
|
| 146 |
+
|
| 147 |
+
def test_k_shell(self):
|
| 148 |
+
# k=0
|
| 149 |
+
k_shell_subgraph = nx.k_shell(self.H, k=2)
|
| 150 |
+
assert sorted(k_shell_subgraph.nodes()) == [2, 4, 5, 6]
|
| 151 |
+
# k=1
|
| 152 |
+
k_shell_subgraph = nx.k_shell(self.H, k=1)
|
| 153 |
+
assert sorted(k_shell_subgraph.nodes()) == [1, 3]
|
| 154 |
+
# k=2
|
| 155 |
+
k_shell_subgraph = nx.k_shell(self.H, k=0)
|
| 156 |
+
assert sorted(k_shell_subgraph.nodes()) == [0]
|
| 157 |
+
|
| 158 |
+
def test_k_shell_multigraph(self):
|
| 159 |
+
core_number = nx.core_number(self.H)
|
| 160 |
+
H = nx.MultiGraph(self.H)
|
| 161 |
+
with pytest.deprecated_call():
|
| 162 |
+
nx.k_shell(H, k=0, core_number=core_number)
|
| 163 |
+
|
| 164 |
+
def test_k_corona(self):
|
| 165 |
+
# k=0
|
| 166 |
+
k_corona_subgraph = nx.k_corona(self.H, k=2)
|
| 167 |
+
assert sorted(k_corona_subgraph.nodes()) == [2, 4, 5, 6]
|
| 168 |
+
# k=1
|
| 169 |
+
k_corona_subgraph = nx.k_corona(self.H, k=1)
|
| 170 |
+
assert sorted(k_corona_subgraph.nodes()) == [1]
|
| 171 |
+
# k=2
|
| 172 |
+
k_corona_subgraph = nx.k_corona(self.H, k=0)
|
| 173 |
+
assert sorted(k_corona_subgraph.nodes()) == [0]
|
| 174 |
+
|
| 175 |
+
def test_k_corona_multigraph(self):
|
| 176 |
+
core_number = nx.core_number(self.H)
|
| 177 |
+
H = nx.MultiGraph(self.H)
|
| 178 |
+
with pytest.deprecated_call():
|
| 179 |
+
nx.k_corona(H, k=0, core_number=core_number)
|
| 180 |
+
|
| 181 |
+
def test_k_truss(self):
|
| 182 |
+
# k=-1
|
| 183 |
+
k_truss_subgraph = nx.k_truss(self.G, -1)
|
| 184 |
+
assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
|
| 185 |
+
# k=0
|
| 186 |
+
k_truss_subgraph = nx.k_truss(self.G, 0)
|
| 187 |
+
assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
|
| 188 |
+
# k=1
|
| 189 |
+
k_truss_subgraph = nx.k_truss(self.G, 1)
|
| 190 |
+
assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
|
| 191 |
+
# k=2
|
| 192 |
+
k_truss_subgraph = nx.k_truss(self.G, 2)
|
| 193 |
+
assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
|
| 194 |
+
# k=3
|
| 195 |
+
k_truss_subgraph = nx.k_truss(self.G, 3)
|
| 196 |
+
assert sorted(k_truss_subgraph.nodes()) == list(range(1, 13))
|
| 197 |
+
|
| 198 |
+
k_truss_subgraph = nx.k_truss(self.G, 4)
|
| 199 |
+
assert sorted(k_truss_subgraph.nodes()) == list(range(1, 9))
|
| 200 |
+
|
| 201 |
+
k_truss_subgraph = nx.k_truss(self.G, 5)
|
| 202 |
+
assert sorted(k_truss_subgraph.nodes()) == []
|
| 203 |
+
|
| 204 |
+
def test_k_truss_digraph(self):
|
| 205 |
+
G = nx.complete_graph(3)
|
| 206 |
+
G = nx.DiGraph(G)
|
| 207 |
+
G.add_edge(2, 1)
|
| 208 |
+
with pytest.raises(
|
| 209 |
+
nx.NetworkXNotImplemented, match="not implemented for directed type"
|
| 210 |
+
):
|
| 211 |
+
nx.k_truss(G, k=1)
|
| 212 |
+
|
| 213 |
+
def test_k_truss_multigraph(self):
|
| 214 |
+
G = nx.complete_graph(3)
|
| 215 |
+
G = nx.MultiGraph(G)
|
| 216 |
+
G.add_edge(1, 2)
|
| 217 |
+
with pytest.raises(
|
| 218 |
+
nx.NetworkXNotImplemented, match="not implemented for multigraph type"
|
| 219 |
+
):
|
| 220 |
+
nx.k_truss(G, k=1)
|
| 221 |
+
|
| 222 |
+
def test_k_truss_self_loop(self):
|
| 223 |
+
G = nx.cycle_graph(3)
|
| 224 |
+
G.add_edge(0, 0)
|
| 225 |
+
with pytest.raises(
|
| 226 |
+
nx.NetworkXNotImplemented, match="Input graph has self loops"
|
| 227 |
+
):
|
| 228 |
+
nx.k_truss(G, k=1)
|
| 229 |
+
|
| 230 |
+
def test_onion_layers(self):
|
| 231 |
+
layers = nx.onion_layers(self.G)
|
| 232 |
+
nodes_by_layer = [
|
| 233 |
+
sorted(n for n in layers if layers[n] == val) for val in range(1, 7)
|
| 234 |
+
]
|
| 235 |
+
assert nodes_equal(nodes_by_layer[0], [21])
|
| 236 |
+
assert nodes_equal(nodes_by_layer[1], [17, 18, 19, 20])
|
| 237 |
+
assert nodes_equal(nodes_by_layer[2], [10, 12, 13, 14, 15, 16])
|
| 238 |
+
assert nodes_equal(nodes_by_layer[3], [9, 11])
|
| 239 |
+
assert nodes_equal(nodes_by_layer[4], [1, 2, 4, 5, 6, 8])
|
| 240 |
+
assert nodes_equal(nodes_by_layer[5], [3, 7])
|
| 241 |
+
|
| 242 |
+
def test_onion_digraph(self):
|
| 243 |
+
G = nx.complete_graph(3)
|
| 244 |
+
G = nx.DiGraph(G)
|
| 245 |
+
G.add_edge(2, 1)
|
| 246 |
+
with pytest.raises(
|
| 247 |
+
nx.NetworkXNotImplemented, match="not implemented for directed type"
|
| 248 |
+
):
|
| 249 |
+
nx.onion_layers(G)
|
| 250 |
+
|
| 251 |
+
def test_onion_multigraph(self):
|
| 252 |
+
G = nx.complete_graph(3)
|
| 253 |
+
G = nx.MultiGraph(G)
|
| 254 |
+
G.add_edge(1, 2)
|
| 255 |
+
with pytest.raises(
|
| 256 |
+
nx.NetworkXNotImplemented, match="not implemented for multigraph type"
|
| 257 |
+
):
|
| 258 |
+
nx.onion_layers(G)
|
| 259 |
+
|
| 260 |
+
def test_onion_self_loop(self):
|
| 261 |
+
G = nx.cycle_graph(3)
|
| 262 |
+
G.add_edge(0, 0)
|
| 263 |
+
with pytest.raises(
|
| 264 |
+
nx.NetworkXNotImplemented, match="Input graph contains self loops"
|
| 265 |
+
):
|
| 266 |
+
nx.onion_layers(G)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_covering.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestMinEdgeCover:
|
| 7 |
+
"""Tests for :func:`networkx.algorithms.min_edge_cover`"""
|
| 8 |
+
|
| 9 |
+
def test_empty_graph(self):
|
| 10 |
+
G = nx.Graph()
|
| 11 |
+
assert nx.min_edge_cover(G) == set()
|
| 12 |
+
|
| 13 |
+
def test_graph_with_loop(self):
|
| 14 |
+
G = nx.Graph()
|
| 15 |
+
G.add_edge(0, 0)
|
| 16 |
+
assert nx.min_edge_cover(G) == {(0, 0)}
|
| 17 |
+
|
| 18 |
+
def test_graph_with_isolated_v(self):
|
| 19 |
+
G = nx.Graph()
|
| 20 |
+
G.add_node(1)
|
| 21 |
+
with pytest.raises(
|
| 22 |
+
nx.NetworkXException,
|
| 23 |
+
match="Graph has a node with no edge incident on it, so no edge cover exists.",
|
| 24 |
+
):
|
| 25 |
+
nx.min_edge_cover(G)
|
| 26 |
+
|
| 27 |
+
def test_graph_single_edge(self):
|
| 28 |
+
G = nx.Graph([(0, 1)])
|
| 29 |
+
assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
|
| 30 |
+
|
| 31 |
+
def test_graph_two_edge_path(self):
|
| 32 |
+
G = nx.path_graph(3)
|
| 33 |
+
min_cover = nx.min_edge_cover(G)
|
| 34 |
+
assert len(min_cover) == 2
|
| 35 |
+
for u, v in G.edges:
|
| 36 |
+
assert (u, v) in min_cover or (v, u) in min_cover
|
| 37 |
+
|
| 38 |
+
def test_bipartite_explicit(self):
|
| 39 |
+
G = nx.Graph()
|
| 40 |
+
G.add_nodes_from([1, 2, 3, 4], bipartite=0)
|
| 41 |
+
G.add_nodes_from(["a", "b", "c"], bipartite=1)
|
| 42 |
+
G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
|
| 43 |
+
# Use bipartite method by prescribing the algorithm
|
| 44 |
+
min_cover = nx.min_edge_cover(
|
| 45 |
+
G, nx.algorithms.bipartite.matching.eppstein_matching
|
| 46 |
+
)
|
| 47 |
+
assert nx.is_edge_cover(G, min_cover)
|
| 48 |
+
assert len(min_cover) == 8
|
| 49 |
+
# Use the default method which is not specialized for bipartite
|
| 50 |
+
min_cover2 = nx.min_edge_cover(G)
|
| 51 |
+
assert nx.is_edge_cover(G, min_cover2)
|
| 52 |
+
assert len(min_cover2) == 4
|
| 53 |
+
|
| 54 |
+
def test_complete_graph_even(self):
|
| 55 |
+
G = nx.complete_graph(10)
|
| 56 |
+
min_cover = nx.min_edge_cover(G)
|
| 57 |
+
assert nx.is_edge_cover(G, min_cover)
|
| 58 |
+
assert len(min_cover) == 5
|
| 59 |
+
|
| 60 |
+
def test_complete_graph_odd(self):
|
| 61 |
+
G = nx.complete_graph(11)
|
| 62 |
+
min_cover = nx.min_edge_cover(G)
|
| 63 |
+
assert nx.is_edge_cover(G, min_cover)
|
| 64 |
+
assert len(min_cover) == 6
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TestIsEdgeCover:
|
| 68 |
+
"""Tests for :func:`networkx.algorithms.is_edge_cover`"""
|
| 69 |
+
|
| 70 |
+
def test_empty_graph(self):
|
| 71 |
+
G = nx.Graph()
|
| 72 |
+
assert nx.is_edge_cover(G, set())
|
| 73 |
+
|
| 74 |
+
def test_graph_with_loop(self):
|
| 75 |
+
G = nx.Graph()
|
| 76 |
+
G.add_edge(1, 1)
|
| 77 |
+
assert nx.is_edge_cover(G, {(1, 1)})
|
| 78 |
+
|
| 79 |
+
def test_graph_single_edge(self):
|
| 80 |
+
G = nx.Graph()
|
| 81 |
+
G.add_edge(0, 1)
|
| 82 |
+
assert nx.is_edge_cover(G, {(0, 0), (1, 1)})
|
| 83 |
+
assert nx.is_edge_cover(G, {(0, 1), (1, 0)})
|
| 84 |
+
assert nx.is_edge_cover(G, {(0, 1)})
|
| 85 |
+
assert not nx.is_edge_cover(G, {(0, 0)})
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the :mod:`networkx.algorithms.cuts` module."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestCutSize:
|
| 8 |
+
"""Unit tests for the :func:`~networkx.cut_size` function."""
|
| 9 |
+
|
| 10 |
+
def test_symmetric(self):
|
| 11 |
+
"""Tests that the cut size is symmetric."""
|
| 12 |
+
G = nx.barbell_graph(3, 0)
|
| 13 |
+
S = {0, 1, 4}
|
| 14 |
+
T = {2, 3, 5}
|
| 15 |
+
assert nx.cut_size(G, S, T) == 4
|
| 16 |
+
assert nx.cut_size(G, T, S) == 4
|
| 17 |
+
|
| 18 |
+
def test_single_edge(self):
|
| 19 |
+
"""Tests for a cut of a single edge."""
|
| 20 |
+
G = nx.barbell_graph(3, 0)
|
| 21 |
+
S = {0, 1, 2}
|
| 22 |
+
T = {3, 4, 5}
|
| 23 |
+
assert nx.cut_size(G, S, T) == 1
|
| 24 |
+
assert nx.cut_size(G, T, S) == 1
|
| 25 |
+
|
| 26 |
+
def test_directed(self):
|
| 27 |
+
"""Tests that each directed edge is counted once in the cut."""
|
| 28 |
+
G = nx.barbell_graph(3, 0).to_directed()
|
| 29 |
+
S = {0, 1, 2}
|
| 30 |
+
T = {3, 4, 5}
|
| 31 |
+
assert nx.cut_size(G, S, T) == 2
|
| 32 |
+
assert nx.cut_size(G, T, S) == 2
|
| 33 |
+
|
| 34 |
+
def test_directed_symmetric(self):
|
| 35 |
+
"""Tests that a cut in a directed graph is symmetric."""
|
| 36 |
+
G = nx.barbell_graph(3, 0).to_directed()
|
| 37 |
+
S = {0, 1, 4}
|
| 38 |
+
T = {2, 3, 5}
|
| 39 |
+
assert nx.cut_size(G, S, T) == 8
|
| 40 |
+
assert nx.cut_size(G, T, S) == 8
|
| 41 |
+
|
| 42 |
+
def test_multigraph(self):
|
| 43 |
+
"""Tests that parallel edges are each counted for a cut."""
|
| 44 |
+
G = nx.MultiGraph(["ab", "ab"])
|
| 45 |
+
assert nx.cut_size(G, {"a"}, {"b"}) == 2
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestVolume:
|
| 49 |
+
"""Unit tests for the :func:`~networkx.volume` function."""
|
| 50 |
+
|
| 51 |
+
def test_graph(self):
|
| 52 |
+
G = nx.cycle_graph(4)
|
| 53 |
+
assert nx.volume(G, {0, 1}) == 4
|
| 54 |
+
|
| 55 |
+
def test_digraph(self):
|
| 56 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0)])
|
| 57 |
+
assert nx.volume(G, {0, 1}) == 2
|
| 58 |
+
|
| 59 |
+
def test_multigraph(self):
|
| 60 |
+
edges = list(nx.cycle_graph(4).edges())
|
| 61 |
+
G = nx.MultiGraph(edges * 2)
|
| 62 |
+
assert nx.volume(G, {0, 1}) == 8
|
| 63 |
+
|
| 64 |
+
def test_multidigraph(self):
|
| 65 |
+
edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
|
| 66 |
+
G = nx.MultiDiGraph(edges * 2)
|
| 67 |
+
assert nx.volume(G, {0, 1}) == 4
|
| 68 |
+
|
| 69 |
+
def test_barbell(self):
|
| 70 |
+
G = nx.barbell_graph(3, 0)
|
| 71 |
+
assert nx.volume(G, {0, 1, 2}) == 7
|
| 72 |
+
assert nx.volume(G, {3, 4, 5}) == 7
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TestNormalizedCutSize:
|
| 76 |
+
"""Unit tests for the :func:`~networkx.normalized_cut_size` function."""
|
| 77 |
+
|
| 78 |
+
def test_graph(self):
|
| 79 |
+
G = nx.path_graph(4)
|
| 80 |
+
S = {1, 2}
|
| 81 |
+
T = set(G) - S
|
| 82 |
+
size = nx.normalized_cut_size(G, S, T)
|
| 83 |
+
# The cut looks like this: o-{-o--o-}-o
|
| 84 |
+
expected = 2 * ((1 / 4) + (1 / 2))
|
| 85 |
+
assert expected == size
|
| 86 |
+
# Test with no input T
|
| 87 |
+
assert expected == nx.normalized_cut_size(G, S)
|
| 88 |
+
|
| 89 |
+
def test_directed(self):
|
| 90 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
|
| 91 |
+
S = {1, 2}
|
| 92 |
+
T = set(G) - S
|
| 93 |
+
size = nx.normalized_cut_size(G, S, T)
|
| 94 |
+
# The cut looks like this: o-{->o-->o-}->o
|
| 95 |
+
expected = 2 * ((1 / 2) + (1 / 1))
|
| 96 |
+
assert expected == size
|
| 97 |
+
# Test with no input T
|
| 98 |
+
assert expected == nx.normalized_cut_size(G, S)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TestConductance:
|
| 102 |
+
"""Unit tests for the :func:`~networkx.conductance` function."""
|
| 103 |
+
|
| 104 |
+
def test_graph(self):
|
| 105 |
+
G = nx.barbell_graph(5, 0)
|
| 106 |
+
# Consider the singleton sets containing the "bridge" nodes.
|
| 107 |
+
# There is only one cut edge, and each set has volume five.
|
| 108 |
+
S = {4}
|
| 109 |
+
T = {5}
|
| 110 |
+
conductance = nx.conductance(G, S, T)
|
| 111 |
+
expected = 1 / 5
|
| 112 |
+
assert expected == conductance
|
| 113 |
+
# Test with no input T
|
| 114 |
+
G2 = nx.barbell_graph(3, 0)
|
| 115 |
+
# There is only one cut edge, and each set has volume seven.
|
| 116 |
+
S2 = {0, 1, 2}
|
| 117 |
+
assert nx.conductance(G2, S2) == 1 / 7
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TestEdgeExpansion:
|
| 121 |
+
"""Unit tests for the :func:`~networkx.edge_expansion` function."""
|
| 122 |
+
|
| 123 |
+
def test_graph(self):
|
| 124 |
+
G = nx.barbell_graph(5, 0)
|
| 125 |
+
S = set(range(5))
|
| 126 |
+
T = set(G) - S
|
| 127 |
+
expansion = nx.edge_expansion(G, S, T)
|
| 128 |
+
expected = 1 / 5
|
| 129 |
+
assert expected == expansion
|
| 130 |
+
# Test with no input T
|
| 131 |
+
assert expected == nx.edge_expansion(G, S)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class TestNodeExpansion:
|
| 135 |
+
"""Unit tests for the :func:`~networkx.node_expansion` function."""
|
| 136 |
+
|
| 137 |
+
def test_graph(self):
|
| 138 |
+
G = nx.path_graph(8)
|
| 139 |
+
S = {3, 4, 5}
|
| 140 |
+
expansion = nx.node_expansion(G, S)
|
| 141 |
+
# The neighborhood of S has cardinality five, and S has
|
| 142 |
+
# cardinality three.
|
| 143 |
+
expected = 5 / 3
|
| 144 |
+
assert expected == expansion
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class TestBoundaryExpansion:
|
| 148 |
+
"""Unit tests for the :func:`~networkx.boundary_expansion` function."""
|
| 149 |
+
|
| 150 |
+
def test_graph(self):
|
| 151 |
+
G = nx.complete_graph(10)
|
| 152 |
+
S = set(range(4))
|
| 153 |
+
expansion = nx.boundary_expansion(G, S)
|
| 154 |
+
# The node boundary of S has cardinality six, and S has
|
| 155 |
+
# cardinality three.
|
| 156 |
+
expected = 6 / 4
|
| 157 |
+
assert expected == expansion
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class TestMixingExpansion:
|
| 161 |
+
"""Unit tests for the :func:`~networkx.mixing_expansion` function."""
|
| 162 |
+
|
| 163 |
+
def test_graph(self):
|
| 164 |
+
G = nx.barbell_graph(5, 0)
|
| 165 |
+
S = set(range(5))
|
| 166 |
+
T = set(G) - S
|
| 167 |
+
expansion = nx.mixing_expansion(G, S, T)
|
| 168 |
+
# There is one cut edge, and the total number of edges in the
|
| 169 |
+
# graph is twice the total number of edges in a clique of size
|
| 170 |
+
# five, plus one more for the bridge.
|
| 171 |
+
expected = 1 / (2 * (5 * 4 + 1))
|
| 172 |
+
assert expected == expansion
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_d_separation.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import combinations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def path_graph():
|
| 9 |
+
"""Return a path graph of length three."""
|
| 10 |
+
G = nx.path_graph(3, create_using=nx.DiGraph)
|
| 11 |
+
G.graph["name"] = "path"
|
| 12 |
+
nx.freeze(G)
|
| 13 |
+
return G
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def fork_graph():
|
| 17 |
+
"""Return a three node fork graph."""
|
| 18 |
+
G = nx.DiGraph(name="fork")
|
| 19 |
+
G.add_edges_from([(0, 1), (0, 2)])
|
| 20 |
+
nx.freeze(G)
|
| 21 |
+
return G
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def collider_graph():
|
| 25 |
+
"""Return a collider/v-structure graph with three nodes."""
|
| 26 |
+
G = nx.DiGraph(name="collider")
|
| 27 |
+
G.add_edges_from([(0, 2), (1, 2)])
|
| 28 |
+
nx.freeze(G)
|
| 29 |
+
return G
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def naive_bayes_graph():
|
| 33 |
+
"""Return a simply Naive Bayes PGM graph."""
|
| 34 |
+
G = nx.DiGraph(name="naive_bayes")
|
| 35 |
+
G.add_edges_from([(0, 1), (0, 2), (0, 3), (0, 4)])
|
| 36 |
+
nx.freeze(G)
|
| 37 |
+
return G
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def asia_graph():
|
| 41 |
+
"""Return the 'Asia' PGM graph."""
|
| 42 |
+
G = nx.DiGraph(name="asia")
|
| 43 |
+
G.add_edges_from(
|
| 44 |
+
[
|
| 45 |
+
("asia", "tuberculosis"),
|
| 46 |
+
("smoking", "cancer"),
|
| 47 |
+
("smoking", "bronchitis"),
|
| 48 |
+
("tuberculosis", "either"),
|
| 49 |
+
("cancer", "either"),
|
| 50 |
+
("either", "xray"),
|
| 51 |
+
("either", "dyspnea"),
|
| 52 |
+
("bronchitis", "dyspnea"),
|
| 53 |
+
]
|
| 54 |
+
)
|
| 55 |
+
nx.freeze(G)
|
| 56 |
+
return G
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.fixture(name="path_graph")
|
| 60 |
+
def path_graph_fixture():
|
| 61 |
+
return path_graph()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@pytest.fixture(name="fork_graph")
|
| 65 |
+
def fork_graph_fixture():
|
| 66 |
+
return fork_graph()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.fixture(name="collider_graph")
|
| 70 |
+
def collider_graph_fixture():
|
| 71 |
+
return collider_graph()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@pytest.fixture(name="naive_bayes_graph")
|
| 75 |
+
def naive_bayes_graph_fixture():
|
| 76 |
+
return naive_bayes_graph()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@pytest.fixture(name="asia_graph")
|
| 80 |
+
def asia_graph_fixture():
|
| 81 |
+
return asia_graph()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@pytest.fixture()
|
| 85 |
+
def large_collider_graph():
|
| 86 |
+
edge_list = [("A", "B"), ("C", "B"), ("B", "D"), ("D", "E"), ("B", "F"), ("G", "E")]
|
| 87 |
+
G = nx.DiGraph(edge_list)
|
| 88 |
+
return G
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@pytest.fixture()
|
| 92 |
+
def chain_and_fork_graph():
|
| 93 |
+
edge_list = [("A", "B"), ("B", "C"), ("B", "D"), ("D", "C")]
|
| 94 |
+
G = nx.DiGraph(edge_list)
|
| 95 |
+
return G
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.fixture()
|
| 99 |
+
def no_separating_set_graph():
|
| 100 |
+
edge_list = [("A", "B")]
|
| 101 |
+
G = nx.DiGraph(edge_list)
|
| 102 |
+
return G
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@pytest.fixture()
|
| 106 |
+
def large_no_separating_set_graph():
|
| 107 |
+
edge_list = [("A", "B"), ("C", "A"), ("C", "B")]
|
| 108 |
+
G = nx.DiGraph(edge_list)
|
| 109 |
+
return G
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.fixture()
|
| 113 |
+
def collider_trek_graph():
|
| 114 |
+
edge_list = [("A", "B"), ("C", "B"), ("C", "D")]
|
| 115 |
+
G = nx.DiGraph(edge_list)
|
| 116 |
+
return G
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@pytest.mark.parametrize(
|
| 120 |
+
"graph",
|
| 121 |
+
[path_graph(), fork_graph(), collider_graph(), naive_bayes_graph(), asia_graph()],
|
| 122 |
+
)
|
| 123 |
+
def test_markov_condition(graph):
|
| 124 |
+
"""Test that the Markov condition holds for each PGM graph."""
|
| 125 |
+
for node in graph.nodes:
|
| 126 |
+
parents = set(graph.predecessors(node))
|
| 127 |
+
non_descendants = graph.nodes - nx.descendants(graph, node) - {node} - parents
|
| 128 |
+
assert nx.is_d_separator(graph, {node}, non_descendants, parents)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_path_graph_dsep(path_graph):
|
| 132 |
+
"""Example-based test of d-separation for path_graph."""
|
| 133 |
+
assert nx.is_d_separator(path_graph, {0}, {2}, {1})
|
| 134 |
+
assert not nx.is_d_separator(path_graph, {0}, {2}, set())
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_fork_graph_dsep(fork_graph):
|
| 138 |
+
"""Example-based test of d-separation for fork_graph."""
|
| 139 |
+
assert nx.is_d_separator(fork_graph, {1}, {2}, {0})
|
| 140 |
+
assert not nx.is_d_separator(fork_graph, {1}, {2}, set())
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_collider_graph_dsep(collider_graph):
|
| 144 |
+
"""Example-based test of d-separation for collider_graph."""
|
| 145 |
+
assert nx.is_d_separator(collider_graph, {0}, {1}, set())
|
| 146 |
+
assert not nx.is_d_separator(collider_graph, {0}, {1}, {2})
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_naive_bayes_dsep(naive_bayes_graph):
|
| 150 |
+
"""Example-based test of d-separation for naive_bayes_graph."""
|
| 151 |
+
for u, v in combinations(range(1, 5), 2):
|
| 152 |
+
assert nx.is_d_separator(naive_bayes_graph, {u}, {v}, {0})
|
| 153 |
+
assert not nx.is_d_separator(naive_bayes_graph, {u}, {v}, set())
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_asia_graph_dsep(asia_graph):
|
| 157 |
+
"""Example-based test of d-separation for asia_graph."""
|
| 158 |
+
assert nx.is_d_separator(
|
| 159 |
+
asia_graph, {"asia", "smoking"}, {"dyspnea", "xray"}, {"bronchitis", "either"}
|
| 160 |
+
)
|
| 161 |
+
assert nx.is_d_separator(
|
| 162 |
+
asia_graph, {"tuberculosis", "cancer"}, {"bronchitis"}, {"smoking", "xray"}
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_undirected_graphs_are_not_supported():
|
| 167 |
+
"""
|
| 168 |
+
Test that undirected graphs are not supported.
|
| 169 |
+
|
| 170 |
+
d-separation and its related algorithms do not apply in
|
| 171 |
+
the case of undirected graphs.
|
| 172 |
+
"""
|
| 173 |
+
g = nx.path_graph(3, nx.Graph)
|
| 174 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 175 |
+
nx.is_d_separator(g, {0}, {1}, {2})
|
| 176 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 177 |
+
nx.is_minimal_d_separator(g, {0}, {1}, {2})
|
| 178 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 179 |
+
nx.find_minimal_d_separator(g, {0}, {1})
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_cyclic_graphs_raise_error():
|
| 183 |
+
"""
|
| 184 |
+
Test that cycle graphs should cause erroring.
|
| 185 |
+
|
| 186 |
+
This is because PGMs assume a directed acyclic graph.
|
| 187 |
+
"""
|
| 188 |
+
g = nx.cycle_graph(3, nx.DiGraph)
|
| 189 |
+
with pytest.raises(nx.NetworkXError):
|
| 190 |
+
nx.is_d_separator(g, {0}, {1}, {2})
|
| 191 |
+
with pytest.raises(nx.NetworkXError):
|
| 192 |
+
nx.find_minimal_d_separator(g, {0}, {1})
|
| 193 |
+
with pytest.raises(nx.NetworkXError):
|
| 194 |
+
nx.is_minimal_d_separator(g, {0}, {1}, {2})
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_invalid_nodes_raise_error(asia_graph):
|
| 198 |
+
"""
|
| 199 |
+
Test that graphs that have invalid nodes passed in raise errors.
|
| 200 |
+
"""
|
| 201 |
+
# Check both set and node arguments
|
| 202 |
+
with pytest.raises(nx.NodeNotFound):
|
| 203 |
+
nx.is_d_separator(asia_graph, {0}, {1}, {2})
|
| 204 |
+
with pytest.raises(nx.NodeNotFound):
|
| 205 |
+
nx.is_d_separator(asia_graph, 0, 1, 2)
|
| 206 |
+
with pytest.raises(nx.NodeNotFound):
|
| 207 |
+
nx.is_minimal_d_separator(asia_graph, {0}, {1}, {2})
|
| 208 |
+
with pytest.raises(nx.NodeNotFound):
|
| 209 |
+
nx.is_minimal_d_separator(asia_graph, 0, 1, 2)
|
| 210 |
+
with pytest.raises(nx.NodeNotFound):
|
| 211 |
+
nx.find_minimal_d_separator(asia_graph, {0}, {1})
|
| 212 |
+
with pytest.raises(nx.NodeNotFound):
|
| 213 |
+
nx.find_minimal_d_separator(asia_graph, 0, 1)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def test_nondisjoint_node_sets_raise_error(collider_graph):
|
| 217 |
+
"""
|
| 218 |
+
Test that error is raised when node sets aren't disjoint.
|
| 219 |
+
"""
|
| 220 |
+
with pytest.raises(nx.NetworkXError):
|
| 221 |
+
nx.is_d_separator(collider_graph, 0, 1, 0)
|
| 222 |
+
with pytest.raises(nx.NetworkXError):
|
| 223 |
+
nx.is_d_separator(collider_graph, 0, 2, 0)
|
| 224 |
+
with pytest.raises(nx.NetworkXError):
|
| 225 |
+
nx.is_d_separator(collider_graph, 0, 0, 1)
|
| 226 |
+
with pytest.raises(nx.NetworkXError):
|
| 227 |
+
nx.is_d_separator(collider_graph, 1, 0, 0)
|
| 228 |
+
with pytest.raises(nx.NetworkXError):
|
| 229 |
+
nx.find_minimal_d_separator(collider_graph, 0, 0)
|
| 230 |
+
with pytest.raises(nx.NetworkXError):
|
| 231 |
+
nx.find_minimal_d_separator(collider_graph, 0, 1, included=0)
|
| 232 |
+
with pytest.raises(nx.NetworkXError):
|
| 233 |
+
nx.find_minimal_d_separator(collider_graph, 1, 0, included=0)
|
| 234 |
+
with pytest.raises(nx.NetworkXError):
|
| 235 |
+
nx.is_minimal_d_separator(collider_graph, 0, 0, set())
|
| 236 |
+
with pytest.raises(nx.NetworkXError):
|
| 237 |
+
nx.is_minimal_d_separator(collider_graph, 0, 1, set(), included=0)
|
| 238 |
+
with pytest.raises(nx.NetworkXError):
|
| 239 |
+
nx.is_minimal_d_separator(collider_graph, 1, 0, set(), included=0)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_is_minimal_d_separator(
|
| 243 |
+
large_collider_graph,
|
| 244 |
+
chain_and_fork_graph,
|
| 245 |
+
no_separating_set_graph,
|
| 246 |
+
large_no_separating_set_graph,
|
| 247 |
+
collider_trek_graph,
|
| 248 |
+
):
|
| 249 |
+
# Case 1:
|
| 250 |
+
# create a graph A -> B <- C
|
| 251 |
+
# B -> D -> E;
|
| 252 |
+
# B -> F;
|
| 253 |
+
# G -> E;
|
| 254 |
+
assert not nx.is_d_separator(large_collider_graph, {"B"}, {"E"}, set())
|
| 255 |
+
|
| 256 |
+
# minimal set of the corresponding graph
|
| 257 |
+
# for B and E should be (D,)
|
| 258 |
+
Zmin = nx.find_minimal_d_separator(large_collider_graph, "B", "E")
|
| 259 |
+
# check that the minimal d-separator is a d-separating set
|
| 260 |
+
assert nx.is_d_separator(large_collider_graph, "B", "E", Zmin)
|
| 261 |
+
# the minimal separating set should also pass the test for minimality
|
| 262 |
+
assert nx.is_minimal_d_separator(large_collider_graph, "B", "E", Zmin)
|
| 263 |
+
# function should also work with set arguments
|
| 264 |
+
assert nx.is_minimal_d_separator(large_collider_graph, {"A", "B"}, {"G", "E"}, Zmin)
|
| 265 |
+
assert Zmin == {"D"}
|
| 266 |
+
|
| 267 |
+
# Case 2:
|
| 268 |
+
# create a graph A -> B -> C
|
| 269 |
+
# B -> D -> C;
|
| 270 |
+
assert not nx.is_d_separator(chain_and_fork_graph, {"A"}, {"C"}, set())
|
| 271 |
+
Zmin = nx.find_minimal_d_separator(chain_and_fork_graph, "A", "C")
|
| 272 |
+
|
| 273 |
+
# the minimal separating set should pass the test for minimality
|
| 274 |
+
assert nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Zmin)
|
| 275 |
+
assert Zmin == {"B"}
|
| 276 |
+
Znotmin = Zmin.union({"D"})
|
| 277 |
+
assert not nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Znotmin)
|
| 278 |
+
|
| 279 |
+
# Case 3:
|
| 280 |
+
# create a graph A -> B
|
| 281 |
+
|
| 282 |
+
# there is no m-separating set between A and B at all, so
|
| 283 |
+
# no minimal m-separating set can exist
|
| 284 |
+
assert not nx.is_d_separator(no_separating_set_graph, {"A"}, {"B"}, set())
|
| 285 |
+
assert nx.find_minimal_d_separator(no_separating_set_graph, "A", "B") is None
|
| 286 |
+
|
| 287 |
+
# Case 4:
|
| 288 |
+
# create a graph A -> B with A <- C -> B
|
| 289 |
+
|
| 290 |
+
# there is no m-separating set between A and B at all, so
|
| 291 |
+
# no minimal m-separating set can exist
|
| 292 |
+
# however, the algorithm will initially propose C as a
|
| 293 |
+
# minimal (but invalid) separating set
|
| 294 |
+
assert not nx.is_d_separator(large_no_separating_set_graph, {"A"}, {"B"}, {"C"})
|
| 295 |
+
assert nx.find_minimal_d_separator(large_no_separating_set_graph, "A", "B") is None
|
| 296 |
+
|
| 297 |
+
# Test `included` and `excluded` args
|
| 298 |
+
# create graph A -> B <- C -> D
|
| 299 |
+
assert nx.find_minimal_d_separator(collider_trek_graph, "A", "D", included="B") == {
|
| 300 |
+
"B",
|
| 301 |
+
"C",
|
| 302 |
+
}
|
| 303 |
+
assert (
|
| 304 |
+
nx.find_minimal_d_separator(
|
| 305 |
+
collider_trek_graph, "A", "D", included="B", restricted="B"
|
| 306 |
+
)
|
| 307 |
+
is None
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def test_is_minimal_d_separator_checks_dsep():
|
| 312 |
+
"""Test that is_minimal_d_separator checks for d-separation as well."""
|
| 313 |
+
g = nx.DiGraph()
|
| 314 |
+
g.add_edges_from(
|
| 315 |
+
[
|
| 316 |
+
("A", "B"),
|
| 317 |
+
("A", "E"),
|
| 318 |
+
("B", "C"),
|
| 319 |
+
("B", "D"),
|
| 320 |
+
("D", "C"),
|
| 321 |
+
("D", "F"),
|
| 322 |
+
("E", "D"),
|
| 323 |
+
("E", "F"),
|
| 324 |
+
]
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
assert not nx.is_d_separator(g, {"C"}, {"F"}, {"D"})
|
| 328 |
+
|
| 329 |
+
# since {'D'} and {} are not d-separators, we return false
|
| 330 |
+
assert not nx.is_minimal_d_separator(g, "C", "F", {"D"})
|
| 331 |
+
assert not nx.is_minimal_d_separator(g, "C", "F", set())
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def test__reachable(large_collider_graph):
|
| 335 |
+
reachable = nx.algorithms.d_separation._reachable
|
| 336 |
+
g = large_collider_graph
|
| 337 |
+
x = {"F", "D"}
|
| 338 |
+
ancestors = {"A", "B", "C", "D", "F"}
|
| 339 |
+
assert reachable(g, x, ancestors, {"B"}) == {"B", "F", "D"}
|
| 340 |
+
assert reachable(g, x, ancestors, set()) == ancestors
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def test_deprecations():
|
| 344 |
+
G = nx.DiGraph([(0, 1), (1, 2)])
|
| 345 |
+
with pytest.deprecated_call():
|
| 346 |
+
nx.d_separated(G, 0, 2, {1})
|
| 347 |
+
with pytest.deprecated_call():
|
| 348 |
+
z = nx.minimal_d_separator(G, 0, 2)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_distance_regular.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx import is_strongly_regular
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"f", (nx.is_distance_regular, nx.intersection_array, nx.is_strongly_regular)
|
| 9 |
+
)
|
| 10 |
+
@pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
|
| 11 |
+
def test_raises_on_directed_and_multigraphs(f, graph_constructor):
|
| 12 |
+
G = graph_constructor([(0, 1), (1, 2)])
|
| 13 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 14 |
+
f(G)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestDistanceRegular:
|
| 18 |
+
def test_is_distance_regular(self):
|
| 19 |
+
assert nx.is_distance_regular(nx.icosahedral_graph())
|
| 20 |
+
assert nx.is_distance_regular(nx.petersen_graph())
|
| 21 |
+
assert nx.is_distance_regular(nx.cubical_graph())
|
| 22 |
+
assert nx.is_distance_regular(nx.complete_bipartite_graph(3, 3))
|
| 23 |
+
assert nx.is_distance_regular(nx.tetrahedral_graph())
|
| 24 |
+
assert nx.is_distance_regular(nx.dodecahedral_graph())
|
| 25 |
+
assert nx.is_distance_regular(nx.pappus_graph())
|
| 26 |
+
assert nx.is_distance_regular(nx.heawood_graph())
|
| 27 |
+
assert nx.is_distance_regular(nx.cycle_graph(3))
|
| 28 |
+
# no distance regular
|
| 29 |
+
assert not nx.is_distance_regular(nx.path_graph(4))
|
| 30 |
+
|
| 31 |
+
def test_not_connected(self):
|
| 32 |
+
G = nx.cycle_graph(4)
|
| 33 |
+
nx.add_cycle(G, [5, 6, 7])
|
| 34 |
+
assert not nx.is_distance_regular(G)
|
| 35 |
+
|
| 36 |
+
def test_global_parameters(self):
|
| 37 |
+
b, c = nx.intersection_array(nx.cycle_graph(5))
|
| 38 |
+
g = nx.global_parameters(b, c)
|
| 39 |
+
assert list(g) == [(0, 0, 2), (1, 0, 1), (1, 1, 0)]
|
| 40 |
+
b, c = nx.intersection_array(nx.cycle_graph(3))
|
| 41 |
+
g = nx.global_parameters(b, c)
|
| 42 |
+
assert list(g) == [(0, 0, 2), (1, 1, 0)]
|
| 43 |
+
|
| 44 |
+
def test_intersection_array(self):
|
| 45 |
+
b, c = nx.intersection_array(nx.cycle_graph(5))
|
| 46 |
+
assert b == [2, 1]
|
| 47 |
+
assert c == [1, 1]
|
| 48 |
+
b, c = nx.intersection_array(nx.dodecahedral_graph())
|
| 49 |
+
assert b == [3, 2, 1, 1, 1]
|
| 50 |
+
assert c == [1, 1, 1, 2, 3]
|
| 51 |
+
b, c = nx.intersection_array(nx.icosahedral_graph())
|
| 52 |
+
assert b == [5, 2, 1]
|
| 53 |
+
assert c == [1, 2, 5]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@pytest.mark.parametrize("f", (nx.is_distance_regular, nx.is_strongly_regular))
|
| 57 |
+
def test_empty_graph_raises(f):
|
| 58 |
+
G = nx.Graph()
|
| 59 |
+
with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes"):
|
| 60 |
+
f(G)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TestStronglyRegular:
|
| 64 |
+
"""Unit tests for the :func:`~networkx.is_strongly_regular`
|
| 65 |
+
function.
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def test_cycle_graph(self):
|
| 70 |
+
"""Tests that the cycle graph on five vertices is strongly
|
| 71 |
+
regular.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
G = nx.cycle_graph(5)
|
| 75 |
+
assert is_strongly_regular(G)
|
| 76 |
+
|
| 77 |
+
def test_petersen_graph(self):
|
| 78 |
+
"""Tests that the Petersen graph is strongly regular."""
|
| 79 |
+
G = nx.petersen_graph()
|
| 80 |
+
assert is_strongly_regular(G)
|
| 81 |
+
|
| 82 |
+
def test_path_graph(self):
|
| 83 |
+
"""Tests that the path graph is not strongly regular."""
|
| 84 |
+
G = nx.path_graph(4)
|
| 85 |
+
assert not is_strongly_regular(G)
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_dominating_set():
|
| 7 |
+
G = nx.gnp_random_graph(100, 0.1)
|
| 8 |
+
D = nx.dominating_set(G)
|
| 9 |
+
assert nx.is_dominating_set(G, D)
|
| 10 |
+
D = nx.dominating_set(G, start_with=0)
|
| 11 |
+
assert nx.is_dominating_set(G, D)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_complete():
|
| 15 |
+
"""In complete graphs each node is a dominating set.
|
| 16 |
+
Thus the dominating set has to be of cardinality 1.
|
| 17 |
+
"""
|
| 18 |
+
K4 = nx.complete_graph(4)
|
| 19 |
+
assert len(nx.dominating_set(K4)) == 1
|
| 20 |
+
K5 = nx.complete_graph(5)
|
| 21 |
+
assert len(nx.dominating_set(K5)) == 1
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_raise_dominating_set():
|
| 25 |
+
with pytest.raises(nx.NetworkXError):
|
| 26 |
+
G = nx.path_graph(4)
|
| 27 |
+
D = nx.dominating_set(G, start_with=10)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_is_dominating_set():
|
| 31 |
+
G = nx.path_graph(4)
|
| 32 |
+
d = {1, 3}
|
| 33 |
+
assert nx.is_dominating_set(G, d)
|
| 34 |
+
d = {0, 2}
|
| 35 |
+
assert nx.is_dominating_set(G, d)
|
| 36 |
+
d = {1}
|
| 37 |
+
assert not nx.is_dominating_set(G, d)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_wikipedia_is_dominating_set():
|
| 41 |
+
"""Example from https://en.wikipedia.org/wiki/Dominating_set"""
|
| 42 |
+
G = nx.cycle_graph(4)
|
| 43 |
+
G.add_edges_from([(0, 4), (1, 4), (2, 5)])
|
| 44 |
+
assert nx.is_dominating_set(G, {4, 3, 5})
|
| 45 |
+
assert nx.is_dominating_set(G, {0, 2})
|
| 46 |
+
assert nx.is_dominating_set(G, {1, 2})
|
parrot/lib/python3.10/site-packages/networkx/algorithms/tests/test_euler.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize("f", (nx.is_eulerian, nx.is_semieulerian))
|
| 9 |
+
def test_empty_graph_raises(f):
|
| 10 |
+
G = nx.Graph()
|
| 11 |
+
with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
|
| 12 |
+
f(G)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestIsEulerian:
|
| 16 |
+
def test_is_eulerian(self):
|
| 17 |
+
assert nx.is_eulerian(nx.complete_graph(5))
|
| 18 |
+
assert nx.is_eulerian(nx.complete_graph(7))
|
| 19 |
+
assert nx.is_eulerian(nx.hypercube_graph(4))
|
| 20 |
+
assert nx.is_eulerian(nx.hypercube_graph(6))
|
| 21 |
+
|
| 22 |
+
assert not nx.is_eulerian(nx.complete_graph(4))
|
| 23 |
+
assert not nx.is_eulerian(nx.complete_graph(6))
|
| 24 |
+
assert not nx.is_eulerian(nx.hypercube_graph(3))
|
| 25 |
+
assert not nx.is_eulerian(nx.hypercube_graph(5))
|
| 26 |
+
|
| 27 |
+
assert not nx.is_eulerian(nx.petersen_graph())
|
| 28 |
+
assert not nx.is_eulerian(nx.path_graph(4))
|
| 29 |
+
|
| 30 |
+
def test_is_eulerian2(self):
|
| 31 |
+
# not connected
|
| 32 |
+
G = nx.Graph()
|
| 33 |
+
G.add_nodes_from([1, 2, 3])
|
| 34 |
+
assert not nx.is_eulerian(G)
|
| 35 |
+
# not strongly connected
|
| 36 |
+
G = nx.DiGraph()
|
| 37 |
+
G.add_nodes_from([1, 2, 3])
|
| 38 |
+
assert not nx.is_eulerian(G)
|
| 39 |
+
G = nx.MultiDiGraph()
|
| 40 |
+
G.add_edge(1, 2)
|
| 41 |
+
G.add_edge(2, 3)
|
| 42 |
+
G.add_edge(2, 3)
|
| 43 |
+
G.add_edge(3, 1)
|
| 44 |
+
assert not nx.is_eulerian(G)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class TestEulerianCircuit:
|
| 48 |
+
def test_eulerian_circuit_cycle(self):
|
| 49 |
+
G = nx.cycle_graph(4)
|
| 50 |
+
|
| 51 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
| 52 |
+
nodes = [u for u, v in edges]
|
| 53 |
+
assert nodes == [0, 3, 2, 1]
|
| 54 |
+
assert edges == [(0, 3), (3, 2), (2, 1), (1, 0)]
|
| 55 |
+
|
| 56 |
+
edges = list(nx.eulerian_circuit(G, source=1))
|
| 57 |
+
nodes = [u for u, v in edges]
|
| 58 |
+
assert nodes == [1, 2, 3, 0]
|
| 59 |
+
assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
|
| 60 |
+
|
| 61 |
+
G = nx.complete_graph(3)
|
| 62 |
+
|
| 63 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
| 64 |
+
nodes = [u for u, v in edges]
|
| 65 |
+
assert nodes == [0, 2, 1]
|
| 66 |
+
assert edges == [(0, 2), (2, 1), (1, 0)]
|
| 67 |
+
|
| 68 |
+
edges = list(nx.eulerian_circuit(G, source=1))
|
| 69 |
+
nodes = [u for u, v in edges]
|
| 70 |
+
assert nodes == [1, 2, 0]
|
| 71 |
+
assert edges == [(1, 2), (2, 0), (0, 1)]
|
| 72 |
+
|
| 73 |
+
def test_eulerian_circuit_digraph(self):
|
| 74 |
+
G = nx.DiGraph()
|
| 75 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
| 76 |
+
|
| 77 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
| 78 |
+
nodes = [u for u, v in edges]
|
| 79 |
+
assert nodes == [0, 1, 2, 3]
|
| 80 |
+
assert edges == [(0, 1), (1, 2), (2, 3), (3, 0)]
|
| 81 |
+
|
| 82 |
+
edges = list(nx.eulerian_circuit(G, source=1))
|
| 83 |
+
nodes = [u for u, v in edges]
|
| 84 |
+
assert nodes == [1, 2, 3, 0]
|
| 85 |
+
assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
|
| 86 |
+
|
| 87 |
+
def test_multigraph(self):
|
| 88 |
+
G = nx.MultiGraph()
|
| 89 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
| 90 |
+
G.add_edge(1, 2)
|
| 91 |
+
G.add_edge(1, 2)
|
| 92 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
| 93 |
+
nodes = [u for u, v in edges]
|
| 94 |
+
assert nodes == [0, 3, 2, 1, 2, 1]
|
| 95 |
+
assert edges == [(0, 3), (3, 2), (2, 1), (1, 2), (2, 1), (1, 0)]
|
| 96 |
+
|
| 97 |
+
def test_multigraph_with_keys(self):
|
| 98 |
+
G = nx.MultiGraph()
|
| 99 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
| 100 |
+
G.add_edge(1, 2)
|
| 101 |
+
G.add_edge(1, 2)
|
| 102 |
+
edges = list(nx.eulerian_circuit(G, source=0, keys=True))
|
| 103 |
+
nodes = [u for u, v, k in edges]
|
| 104 |
+
assert nodes == [0, 3, 2, 1, 2, 1]
|
| 105 |
+
assert edges[:2] == [(0, 3, 0), (3, 2, 0)]
|
| 106 |
+
assert collections.Counter(edges[2:5]) == collections.Counter(
|
| 107 |
+
[(2, 1, 0), (1, 2, 1), (2, 1, 2)]
|
| 108 |
+
)
|
| 109 |
+
assert edges[5:] == [(1, 0, 0)]
|
| 110 |
+
|
| 111 |
+
def test_not_eulerian(self):
|
| 112 |
+
with pytest.raises(nx.NetworkXError):
|
| 113 |
+
f = list(nx.eulerian_circuit(nx.complete_graph(4)))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TestIsSemiEulerian:
|
| 117 |
+
def test_is_semieulerian(self):
|
| 118 |
+
# Test graphs with Eulerian paths but no cycles return True.
|
| 119 |
+
assert nx.is_semieulerian(nx.path_graph(4))
|
| 120 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
| 121 |
+
assert nx.is_semieulerian(G)
|
| 122 |
+
|
| 123 |
+
# Test graphs with Eulerian cycles return False.
|
| 124 |
+
assert not nx.is_semieulerian(nx.complete_graph(5))
|
| 125 |
+
assert not nx.is_semieulerian(nx.complete_graph(7))
|
| 126 |
+
assert not nx.is_semieulerian(nx.hypercube_graph(4))
|
| 127 |
+
assert not nx.is_semieulerian(nx.hypercube_graph(6))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class TestHasEulerianPath:
|
| 131 |
+
def test_has_eulerian_path_cyclic(self):
|
| 132 |
+
# Test graphs with Eulerian cycles return True.
|
| 133 |
+
assert nx.has_eulerian_path(nx.complete_graph(5))
|
| 134 |
+
assert nx.has_eulerian_path(nx.complete_graph(7))
|
| 135 |
+
assert nx.has_eulerian_path(nx.hypercube_graph(4))
|
| 136 |
+
assert nx.has_eulerian_path(nx.hypercube_graph(6))
|
| 137 |
+
|
| 138 |
+
def test_has_eulerian_path_non_cyclic(self):
|
| 139 |
+
# Test graphs with Eulerian paths but no cycles return True.
|
| 140 |
+
assert nx.has_eulerian_path(nx.path_graph(4))
|
| 141 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
| 142 |
+
assert nx.has_eulerian_path(G)
|
| 143 |
+
|
| 144 |
+
def test_has_eulerian_path_directed_graph(self):
|
| 145 |
+
# Test directed graphs and returns False
|
| 146 |
+
G = nx.DiGraph()
|
| 147 |
+
G.add_edges_from([(0, 1), (1, 2), (0, 2)])
|
| 148 |
+
assert not nx.has_eulerian_path(G)
|
| 149 |
+
|
| 150 |
+
# Test directed graphs without isolated node returns True
|
| 151 |
+
G = nx.DiGraph()
|
| 152 |
+
G.add_edges_from([(0, 1), (1, 2), (2, 0)])
|
| 153 |
+
assert nx.has_eulerian_path(G)
|
| 154 |
+
|
| 155 |
+
# Test directed graphs with isolated node returns False
|
| 156 |
+
G.add_node(3)
|
| 157 |
+
assert not nx.has_eulerian_path(G)
|
| 158 |
+
|
| 159 |
+
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
|
| 160 |
+
def test_has_eulerian_path_not_weakly_connected(self, G):
|
| 161 |
+
G.add_edges_from([(0, 1), (2, 3), (3, 2)])
|
| 162 |
+
assert not nx.has_eulerian_path(G)
|
| 163 |
+
|
| 164 |
+
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
|
| 165 |
+
def test_has_eulerian_path_unbalancedins_more_than_one(self, G):
|
| 166 |
+
G.add_edges_from([(0, 1), (2, 3)])
|
| 167 |
+
assert not nx.has_eulerian_path(G)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class TestFindPathStart:
|
| 171 |
+
def testfind_path_start(self):
|
| 172 |
+
find_path_start = nx.algorithms.euler._find_path_start
|
| 173 |
+
# Test digraphs return correct starting node.
|
| 174 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
| 175 |
+
assert find_path_start(G) == 0
|
| 176 |
+
edges = [(0, 1), (1, 2), (2, 0), (4, 0)]
|
| 177 |
+
assert find_path_start(nx.DiGraph(edges)) == 4
|
| 178 |
+
|
| 179 |
+
# Test graph with no Eulerian path return None.
|
| 180 |
+
edges = [(0, 1), (1, 2), (2, 3), (2, 4)]
|
| 181 |
+
assert find_path_start(nx.DiGraph(edges)) is None
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class TestEulerianPath:
|
| 185 |
+
def test_eulerian_path(self):
|
| 186 |
+
x = [(4, 0), (0, 1), (1, 2), (2, 0)]
|
| 187 |
+
for e1, e2 in zip(x, nx.eulerian_path(nx.DiGraph(x))):
|
| 188 |
+
assert e1 == e2
|
| 189 |
+
|
| 190 |
+
def test_eulerian_path_straight_link(self):
|
| 191 |
+
G = nx.DiGraph()
|
| 192 |
+
result = [(1, 2), (2, 3), (3, 4), (4, 5)]
|
| 193 |
+
G.add_edges_from(result)
|
| 194 |
+
assert result == list(nx.eulerian_path(G))
|
| 195 |
+
assert result == list(nx.eulerian_path(G, source=1))
|
| 196 |
+
with pytest.raises(nx.NetworkXError):
|
| 197 |
+
list(nx.eulerian_path(G, source=3))
|
| 198 |
+
with pytest.raises(nx.NetworkXError):
|
| 199 |
+
list(nx.eulerian_path(G, source=4))
|
| 200 |
+
with pytest.raises(nx.NetworkXError):
|
| 201 |
+
list(nx.eulerian_path(G, source=5))
|
| 202 |
+
|
| 203 |
+
def test_eulerian_path_multigraph(self):
|
| 204 |
+
G = nx.MultiDiGraph()
|
| 205 |
+
result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4), (4, 3)]
|
| 206 |
+
G.add_edges_from(result)
|
| 207 |
+
assert result == list(nx.eulerian_path(G))
|
| 208 |
+
assert result == list(nx.eulerian_path(G, source=2))
|
| 209 |
+
with pytest.raises(nx.NetworkXError):
|
| 210 |
+
list(nx.eulerian_path(G, source=3))
|
| 211 |
+
with pytest.raises(nx.NetworkXError):
|
| 212 |
+
list(nx.eulerian_path(G, source=4))
|
| 213 |
+
|
| 214 |
+
def test_eulerian_path_eulerian_circuit(self):
|
| 215 |
+
G = nx.DiGraph()
|
| 216 |
+
result = [(1, 2), (2, 3), (3, 4), (4, 1)]
|
| 217 |
+
result2 = [(2, 3), (3, 4), (4, 1), (1, 2)]
|
| 218 |
+
result3 = [(3, 4), (4, 1), (1, 2), (2, 3)]
|
| 219 |
+
G.add_edges_from(result)
|
| 220 |
+
assert result == list(nx.eulerian_path(G))
|
| 221 |
+
assert result == list(nx.eulerian_path(G, source=1))
|
| 222 |
+
assert result2 == list(nx.eulerian_path(G, source=2))
|
| 223 |
+
assert result3 == list(nx.eulerian_path(G, source=3))
|
| 224 |
+
|
| 225 |
+
def test_eulerian_path_undirected(self):
|
| 226 |
+
G = nx.Graph()
|
| 227 |
+
result = [(1, 2), (2, 3), (3, 4), (4, 5)]
|
| 228 |
+
result2 = [(5, 4), (4, 3), (3, 2), (2, 1)]
|
| 229 |
+
G.add_edges_from(result)
|
| 230 |
+
assert list(nx.eulerian_path(G)) in (result, result2)
|
| 231 |
+
assert result == list(nx.eulerian_path(G, source=1))
|
| 232 |
+
assert result2 == list(nx.eulerian_path(G, source=5))
|
| 233 |
+
with pytest.raises(nx.NetworkXError):
|
| 234 |
+
list(nx.eulerian_path(G, source=3))
|
| 235 |
+
with pytest.raises(nx.NetworkXError):
|
| 236 |
+
list(nx.eulerian_path(G, source=2))
|
| 237 |
+
|
| 238 |
+
def test_eulerian_path_multigraph_undirected(self):
|
| 239 |
+
G = nx.MultiGraph()
|
| 240 |
+
result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4)]
|
| 241 |
+
G.add_edges_from(result)
|
| 242 |
+
assert result == list(nx.eulerian_path(G))
|
| 243 |
+
assert result == list(nx.eulerian_path(G, source=2))
|
| 244 |
+
with pytest.raises(nx.NetworkXError):
|
| 245 |
+
list(nx.eulerian_path(G, source=3))
|
| 246 |
+
with pytest.raises(nx.NetworkXError):
|
| 247 |
+
list(nx.eulerian_path(G, source=1))
|
| 248 |
+
|
| 249 |
+
@pytest.mark.parametrize(
|
| 250 |
+
("graph_type", "result"),
|
| 251 |
+
(
|
| 252 |
+
(nx.MultiGraph, [(0, 1, 0), (1, 0, 1)]),
|
| 253 |
+
(nx.MultiDiGraph, [(0, 1, 0), (1, 0, 0)]),
|
| 254 |
+
),
|
| 255 |
+
)
|
| 256 |
+
def test_eulerian_with_keys(self, graph_type, result):
|
| 257 |
+
G = graph_type([(0, 1), (1, 0)])
|
| 258 |
+
answer = nx.eulerian_path(G, keys=True)
|
| 259 |
+
assert list(answer) == result
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class TestEulerize:
|
| 263 |
+
def test_disconnected(self):
|
| 264 |
+
with pytest.raises(nx.NetworkXError):
|
| 265 |
+
G = nx.from_edgelist([(0, 1), (2, 3)])
|
| 266 |
+
nx.eulerize(G)
|
| 267 |
+
|
| 268 |
+
def test_null_graph(self):
|
| 269 |
+
with pytest.raises(nx.NetworkXPointlessConcept):
|
| 270 |
+
nx.eulerize(nx.Graph())
|
| 271 |
+
|
| 272 |
+
def test_null_multigraph(self):
|
| 273 |
+
with pytest.raises(nx.NetworkXPointlessConcept):
|
| 274 |
+
nx.eulerize(nx.MultiGraph())
|
| 275 |
+
|
| 276 |
+
def test_on_empty_graph(self):
|
| 277 |
+
with pytest.raises(nx.NetworkXError):
|
| 278 |
+
nx.eulerize(nx.empty_graph(3))
|
| 279 |
+
|
| 280 |
+
def test_on_eulerian(self):
|
| 281 |
+
G = nx.cycle_graph(3)
|
| 282 |
+
H = nx.eulerize(G)
|
| 283 |
+
assert nx.is_isomorphic(G, H)
|
| 284 |
+
|
| 285 |
+
def test_on_eulerian_multigraph(self):
|
| 286 |
+
G = nx.MultiGraph(nx.cycle_graph(3))
|
| 287 |
+
G.add_edge(0, 1)
|
| 288 |
+
H = nx.eulerize(G)
|
| 289 |
+
assert nx.is_eulerian(H)
|
| 290 |
+
|
| 291 |
+
def test_on_complete_graph(self):
|
| 292 |
+
G = nx.complete_graph(4)
|
| 293 |
+
assert nx.is_eulerian(nx.eulerize(G))
|
| 294 |
+
assert nx.is_eulerian(nx.eulerize(nx.MultiGraph(G)))
|
| 295 |
+
|
| 296 |
+
def test_on_non_eulerian_graph(self):
|
| 297 |
+
G = nx.cycle_graph(18)
|
| 298 |
+
G.add_edge(0, 18)
|
| 299 |
+
G.add_edge(18, 19)
|
| 300 |
+
G.add_edge(17, 19)
|
| 301 |
+
G.add_edge(4, 20)
|
| 302 |
+
G.add_edge(20, 21)
|
| 303 |
+
G.add_edge(21, 22)
|
| 304 |
+
G.add_edge(22, 23)
|
| 305 |
+
G.add_edge(23, 24)
|
| 306 |
+
G.add_edge(24, 25)
|
| 307 |
+
G.add_edge(25, 26)
|
| 308 |
+
G.add_edge(26, 27)
|
| 309 |
+
G.add_edge(27, 28)
|
| 310 |
+
G.add_edge(28, 13)
|
| 311 |
+
assert not nx.is_eulerian(G)
|
| 312 |
+
G = nx.eulerize(G)
|
| 313 |
+
assert nx.is_eulerian(G)
|
| 314 |
+
assert nx.number_of_edges(G) == 39
|