Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/15.input_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/26.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/5.attention.query_key_value.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/clique.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/clustering_coefficient.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/connectivity.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/distance_measures.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/dominating_set.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/kcomponents.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/matching.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/maxcut.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/ramsey.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/steinertree.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/traveling_salesman.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/treewidth.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/vertex_cover.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/clustering_coefficient.py +71 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/steinertree.py +220 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_clique.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_connectivity.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_distance_measures.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_dominating_set.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_matching.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_ramsey.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_traveling_salesman.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_treewidth.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_vertex_cover.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py +41 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_clique.py +113 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py +199 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py +60 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py +78 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py +303 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_matching.py +8 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py +94 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py +31 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py +226 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py +979 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py +280 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py +68 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/flow/__init__.py +11 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/edmondskarp.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/15.input_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:75aa5fca114361bd216a803a1813058de0b4aa6c92e3e101ce9a26ae1dcba82e
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/26.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cbf49f5a4ec265b628bf6bbeb41696db2b3b4729260c7ed01b9478d4b9f042b4
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/5.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4b5c625e2aa4a056eff48d5f9f6c8a14a7e9ed6d9505de62f49846e7ad3c707e
|
3 |
+
size 50332749
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.36 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/clique.cpython-310.pyc
ADDED
Binary file (7.97 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/clustering_coefficient.cpython-310.pyc
ADDED
Binary file (2.53 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/connectivity.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/distance_measures.cpython-310.pyc
ADDED
Binary file (5.03 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/dominating_set.cpython-310.pyc
ADDED
Binary file (4.47 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/kcomponents.cpython-310.pyc
ADDED
Binary file (13.9 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/matching.cpython-310.pyc
ADDED
Binary file (1.44 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/maxcut.cpython-310.pyc
ADDED
Binary file (4.33 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/ramsey.cpython-310.pyc
ADDED
Binary file (1.58 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/steinertree.cpython-310.pyc
ADDED
Binary file (7.23 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/traveling_salesman.cpython-310.pyc
ADDED
Binary file (46.1 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/treewidth.cpython-310.pyc
ADDED
Binary file (6.64 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/__pycache__/vertex_cover.cpython-310.pyc
ADDED
Binary file (2.87 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/clustering_coefficient.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
from networkx.utils import not_implemented_for, py_random_state
|
3 |
+
|
4 |
+
__all__ = ["average_clustering"]
|
5 |
+
|
6 |
+
|
7 |
+
@not_implemented_for("directed")
|
8 |
+
@py_random_state(2)
|
9 |
+
@nx._dispatchable(name="approximate_average_clustering")
|
10 |
+
def average_clustering(G, trials=1000, seed=None):
|
11 |
+
r"""Estimates the average clustering coefficient of G.
|
12 |
+
|
13 |
+
The local clustering of each node in `G` is the fraction of triangles
|
14 |
+
that actually exist over all possible triangles in its neighborhood.
|
15 |
+
The average clustering coefficient of a graph `G` is the mean of
|
16 |
+
local clusterings.
|
17 |
+
|
18 |
+
This function finds an approximate average clustering coefficient
|
19 |
+
for G by repeating `n` times (defined in `trials`) the following
|
20 |
+
experiment: choose a node at random, choose two of its neighbors
|
21 |
+
at random, and check if they are connected. The approximate
|
22 |
+
coefficient is the fraction of triangles found over the number
|
23 |
+
of trials [1]_.
|
24 |
+
|
25 |
+
Parameters
|
26 |
+
----------
|
27 |
+
G : NetworkX graph
|
28 |
+
|
29 |
+
trials : integer
|
30 |
+
Number of trials to perform (default 1000).
|
31 |
+
|
32 |
+
seed : integer, random_state, or None (default)
|
33 |
+
Indicator of random number generation state.
|
34 |
+
See :ref:`Randomness<randomness>`.
|
35 |
+
|
36 |
+
Returns
|
37 |
+
-------
|
38 |
+
c : float
|
39 |
+
Approximated average clustering coefficient.
|
40 |
+
|
41 |
+
Examples
|
42 |
+
--------
|
43 |
+
>>> from networkx.algorithms import approximation
|
44 |
+
>>> G = nx.erdos_renyi_graph(10, 0.2, seed=10)
|
45 |
+
>>> approximation.average_clustering(G, trials=1000, seed=10)
|
46 |
+
0.214
|
47 |
+
|
48 |
+
Raises
|
49 |
+
------
|
50 |
+
NetworkXNotImplemented
|
51 |
+
If G is directed.
|
52 |
+
|
53 |
+
References
|
54 |
+
----------
|
55 |
+
.. [1] Schank, Thomas, and Dorothea Wagner. Approximating clustering
|
56 |
+
coefficient and transitivity. Universität Karlsruhe, Fakultät für
|
57 |
+
Informatik, 2004.
|
58 |
+
https://doi.org/10.5445/IR/1000001239
|
59 |
+
|
60 |
+
"""
|
61 |
+
n = len(G)
|
62 |
+
triangles = 0
|
63 |
+
nodes = list(G)
|
64 |
+
for i in [int(seed.random() * n) for i in range(trials)]:
|
65 |
+
nbrs = list(G[nodes[i]])
|
66 |
+
if len(nbrs) < 2:
|
67 |
+
continue
|
68 |
+
u, v = seed.sample(nbrs, 2)
|
69 |
+
if u in G[v]:
|
70 |
+
triangles += 1
|
71 |
+
return triangles / trials
|
venv/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
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (207 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-310.pyc
ADDED
Binary file (1.41 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_clique.cpython-310.pyc
ADDED
Binary file (4.41 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_connectivity.cpython-310.pyc
ADDED
Binary file (5.84 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_distance_measures.cpython-310.pyc
ADDED
Binary file (3.11 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_dominating_set.cpython-310.pyc
ADDED
Binary file (2.56 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-310.pyc
ADDED
Binary file (9.63 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_matching.cpython-310.pyc
ADDED
Binary file (519 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-310.pyc
ADDED
Binary file (3.03 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_ramsey.cpython-310.pyc
ADDED
Binary file (1.18 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-310.pyc
ADDED
Binary file (7.07 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_traveling_salesman.cpython-310.pyc
ADDED
Binary file (27 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_treewidth.cpython-310.pyc
ADDED
Binary file (7.18 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_vertex_cover.cpython-310.pyc
ADDED
Binary file (2.82 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
from networkx.algorithms.approximation import average_clustering
|
3 |
+
|
4 |
+
# This approximation has to be exact in regular graphs
|
5 |
+
# with no triangles or with all possible triangles.
|
6 |
+
|
7 |
+
|
8 |
+
def test_petersen():
|
9 |
+
# Actual coefficient is 0
|
10 |
+
G = nx.petersen_graph()
|
11 |
+
assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
|
12 |
+
|
13 |
+
|
14 |
+
def test_petersen_seed():
|
15 |
+
# Actual coefficient is 0
|
16 |
+
G = nx.petersen_graph()
|
17 |
+
assert average_clustering(G, trials=len(G) // 2, seed=1) == nx.average_clustering(G)
|
18 |
+
|
19 |
+
|
20 |
+
def test_tetrahedral():
|
21 |
+
# Actual coefficient is 1
|
22 |
+
G = nx.tetrahedral_graph()
|
23 |
+
assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
|
24 |
+
|
25 |
+
|
26 |
+
def test_dodecahedral():
|
27 |
+
# Actual coefficient is 0
|
28 |
+
G = nx.dodecahedral_graph()
|
29 |
+
assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
|
30 |
+
|
31 |
+
|
32 |
+
def test_empty():
|
33 |
+
G = nx.empty_graph(5)
|
34 |
+
assert average_clustering(G, trials=len(G) // 2) == 0
|
35 |
+
|
36 |
+
|
37 |
+
def test_complete():
|
38 |
+
G = nx.complete_graph(5)
|
39 |
+
assert average_clustering(G, trials=len(G) // 2) == 1
|
40 |
+
G = nx.complete_graph(7)
|
41 |
+
assert average_clustering(G, trials=len(G) // 2) == 1
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_clique.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.approximation.clique` module."""
|
2 |
+
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
from networkx.algorithms.approximation import (
|
6 |
+
clique_removal,
|
7 |
+
large_clique_size,
|
8 |
+
max_clique,
|
9 |
+
maximum_independent_set,
|
10 |
+
)
|
11 |
+
|
12 |
+
|
13 |
+
def is_independent_set(G, nodes):
|
14 |
+
"""Returns True if and only if `nodes` is a clique in `G`.
|
15 |
+
|
16 |
+
`G` is a NetworkX graph. `nodes` is an iterable of nodes in
|
17 |
+
`G`.
|
18 |
+
|
19 |
+
"""
|
20 |
+
return G.subgraph(nodes).number_of_edges() == 0
|
21 |
+
|
22 |
+
|
23 |
+
def is_clique(G, nodes):
|
24 |
+
"""Returns True if and only if `nodes` is an independent set
|
25 |
+
in `G`.
|
26 |
+
|
27 |
+
`G` is an undirected simple graph. `nodes` is an iterable of
|
28 |
+
nodes in `G`.
|
29 |
+
|
30 |
+
"""
|
31 |
+
H = G.subgraph(nodes)
|
32 |
+
n = len(H)
|
33 |
+
return H.number_of_edges() == n * (n - 1) // 2
|
34 |
+
|
35 |
+
|
36 |
+
class TestCliqueRemoval:
|
37 |
+
"""Unit tests for the
|
38 |
+
:func:`~networkx.algorithms.approximation.clique_removal` function.
|
39 |
+
|
40 |
+
"""
|
41 |
+
|
42 |
+
def test_trivial_graph(self):
|
43 |
+
G = nx.trivial_graph()
|
44 |
+
independent_set, cliques = clique_removal(G)
|
45 |
+
assert is_independent_set(G, independent_set)
|
46 |
+
assert all(is_clique(G, clique) for clique in cliques)
|
47 |
+
# In fact, we should only have 1-cliques, that is, singleton nodes.
|
48 |
+
assert all(len(clique) == 1 for clique in cliques)
|
49 |
+
|
50 |
+
def test_complete_graph(self):
|
51 |
+
G = nx.complete_graph(10)
|
52 |
+
independent_set, cliques = clique_removal(G)
|
53 |
+
assert is_independent_set(G, independent_set)
|
54 |
+
assert all(is_clique(G, clique) for clique in cliques)
|
55 |
+
|
56 |
+
def test_barbell_graph(self):
|
57 |
+
G = nx.barbell_graph(10, 5)
|
58 |
+
independent_set, cliques = clique_removal(G)
|
59 |
+
assert is_independent_set(G, independent_set)
|
60 |
+
assert all(is_clique(G, clique) for clique in cliques)
|
61 |
+
|
62 |
+
|
63 |
+
class TestMaxClique:
|
64 |
+
"""Unit tests for the :func:`networkx.algorithms.approximation.max_clique`
|
65 |
+
function.
|
66 |
+
|
67 |
+
"""
|
68 |
+
|
69 |
+
def test_null_graph(self):
|
70 |
+
G = nx.null_graph()
|
71 |
+
assert len(max_clique(G)) == 0
|
72 |
+
|
73 |
+
def test_complete_graph(self):
|
74 |
+
graph = nx.complete_graph(30)
|
75 |
+
# this should return the entire graph
|
76 |
+
mc = max_clique(graph)
|
77 |
+
assert 30 == len(mc)
|
78 |
+
|
79 |
+
def test_maximal_by_cardinality(self):
|
80 |
+
"""Tests that the maximal clique is computed according to maximum
|
81 |
+
cardinality of the sets.
|
82 |
+
|
83 |
+
For more information, see pull request #1531.
|
84 |
+
|
85 |
+
"""
|
86 |
+
G = nx.complete_graph(5)
|
87 |
+
G.add_edge(4, 5)
|
88 |
+
clique = max_clique(G)
|
89 |
+
assert len(clique) > 1
|
90 |
+
|
91 |
+
G = nx.lollipop_graph(30, 2)
|
92 |
+
clique = max_clique(G)
|
93 |
+
assert len(clique) > 2
|
94 |
+
|
95 |
+
|
96 |
+
def test_large_clique_size():
|
97 |
+
G = nx.complete_graph(9)
|
98 |
+
nx.add_cycle(G, [9, 10, 11])
|
99 |
+
G.add_edge(8, 9)
|
100 |
+
G.add_edge(1, 12)
|
101 |
+
G.add_node(13)
|
102 |
+
|
103 |
+
assert large_clique_size(G) == 9
|
104 |
+
G.remove_node(5)
|
105 |
+
assert large_clique_size(G) == 8
|
106 |
+
G.remove_edge(2, 3)
|
107 |
+
assert large_clique_size(G) == 7
|
108 |
+
|
109 |
+
|
110 |
+
def test_independent_set():
|
111 |
+
# smoke test
|
112 |
+
G = nx.Graph()
|
113 |
+
assert len(maximum_independent_set(G)) == 0
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_connectivity.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms import approximation as approx
|
5 |
+
|
6 |
+
|
7 |
+
def test_global_node_connectivity():
|
8 |
+
# Figure 1 chapter on Connectivity
|
9 |
+
G = nx.Graph()
|
10 |
+
G.add_edges_from(
|
11 |
+
[
|
12 |
+
(1, 2),
|
13 |
+
(1, 3),
|
14 |
+
(1, 4),
|
15 |
+
(1, 5),
|
16 |
+
(2, 3),
|
17 |
+
(2, 6),
|
18 |
+
(3, 4),
|
19 |
+
(3, 6),
|
20 |
+
(4, 6),
|
21 |
+
(4, 7),
|
22 |
+
(5, 7),
|
23 |
+
(6, 8),
|
24 |
+
(6, 9),
|
25 |
+
(7, 8),
|
26 |
+
(7, 10),
|
27 |
+
(8, 11),
|
28 |
+
(9, 10),
|
29 |
+
(9, 11),
|
30 |
+
(10, 11),
|
31 |
+
]
|
32 |
+
)
|
33 |
+
assert 2 == approx.local_node_connectivity(G, 1, 11)
|
34 |
+
assert 2 == approx.node_connectivity(G)
|
35 |
+
assert 2 == approx.node_connectivity(G, 1, 11)
|
36 |
+
|
37 |
+
|
38 |
+
def test_white_harary1():
|
39 |
+
# Figure 1b white and harary (2001)
|
40 |
+
# A graph with high adhesion (edge connectivity) and low cohesion
|
41 |
+
# (node connectivity)
|
42 |
+
G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
|
43 |
+
G.remove_node(7)
|
44 |
+
for i in range(4, 7):
|
45 |
+
G.add_edge(0, i)
|
46 |
+
G = nx.disjoint_union(G, nx.complete_graph(4))
|
47 |
+
G.remove_node(G.order() - 1)
|
48 |
+
for i in range(7, 10):
|
49 |
+
G.add_edge(0, i)
|
50 |
+
assert 1 == approx.node_connectivity(G)
|
51 |
+
|
52 |
+
|
53 |
+
def test_complete_graphs():
|
54 |
+
for n in range(5, 25, 5):
|
55 |
+
G = nx.complete_graph(n)
|
56 |
+
assert n - 1 == approx.node_connectivity(G)
|
57 |
+
assert n - 1 == approx.node_connectivity(G, 0, 3)
|
58 |
+
|
59 |
+
|
60 |
+
def test_empty_graphs():
|
61 |
+
for k in range(5, 25, 5):
|
62 |
+
G = nx.empty_graph(k)
|
63 |
+
assert 0 == approx.node_connectivity(G)
|
64 |
+
assert 0 == approx.node_connectivity(G, 0, 3)
|
65 |
+
|
66 |
+
|
67 |
+
def test_petersen():
|
68 |
+
G = nx.petersen_graph()
|
69 |
+
assert 3 == approx.node_connectivity(G)
|
70 |
+
assert 3 == approx.node_connectivity(G, 0, 5)
|
71 |
+
|
72 |
+
|
73 |
+
# Approximation fails with tutte graph
|
74 |
+
# def test_tutte():
|
75 |
+
# G = nx.tutte_graph()
|
76 |
+
# assert_equal(3, approx.node_connectivity(G))
|
77 |
+
|
78 |
+
|
79 |
+
def test_dodecahedral():
|
80 |
+
G = nx.dodecahedral_graph()
|
81 |
+
assert 3 == approx.node_connectivity(G)
|
82 |
+
assert 3 == approx.node_connectivity(G, 0, 5)
|
83 |
+
|
84 |
+
|
85 |
+
def test_octahedral():
|
86 |
+
G = nx.octahedral_graph()
|
87 |
+
assert 4 == approx.node_connectivity(G)
|
88 |
+
assert 4 == approx.node_connectivity(G, 0, 5)
|
89 |
+
|
90 |
+
|
91 |
+
# Approximation can fail with icosahedral graph depending
|
92 |
+
# on iteration order.
|
93 |
+
# def test_icosahedral():
|
94 |
+
# G=nx.icosahedral_graph()
|
95 |
+
# assert_equal(5, approx.node_connectivity(G))
|
96 |
+
# assert_equal(5, approx.node_connectivity(G, 0, 5))
|
97 |
+
|
98 |
+
|
99 |
+
def test_only_source():
|
100 |
+
G = nx.complete_graph(5)
|
101 |
+
pytest.raises(nx.NetworkXError, approx.node_connectivity, G, s=0)
|
102 |
+
|
103 |
+
|
104 |
+
def test_only_target():
|
105 |
+
G = nx.complete_graph(5)
|
106 |
+
pytest.raises(nx.NetworkXError, approx.node_connectivity, G, t=0)
|
107 |
+
|
108 |
+
|
109 |
+
def test_missing_source():
|
110 |
+
G = nx.path_graph(4)
|
111 |
+
pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 10, 1)
|
112 |
+
|
113 |
+
|
114 |
+
def test_missing_target():
|
115 |
+
G = nx.path_graph(4)
|
116 |
+
pytest.raises(nx.NetworkXError, approx.node_connectivity, G, 1, 10)
|
117 |
+
|
118 |
+
|
119 |
+
def test_source_equals_target():
|
120 |
+
G = nx.complete_graph(5)
|
121 |
+
pytest.raises(nx.NetworkXError, approx.local_node_connectivity, G, 0, 0)
|
122 |
+
|
123 |
+
|
124 |
+
def test_directed_node_connectivity():
|
125 |
+
G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
|
126 |
+
D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
|
127 |
+
assert 1 == approx.node_connectivity(G)
|
128 |
+
assert 1 == approx.node_connectivity(G, 1, 4)
|
129 |
+
assert 2 == approx.node_connectivity(D)
|
130 |
+
assert 2 == approx.node_connectivity(D, 1, 4)
|
131 |
+
|
132 |
+
|
133 |
+
class TestAllPairsNodeConnectivityApprox:
|
134 |
+
@classmethod
|
135 |
+
def setup_class(cls):
|
136 |
+
cls.path = nx.path_graph(7)
|
137 |
+
cls.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
|
138 |
+
cls.cycle = nx.cycle_graph(7)
|
139 |
+
cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
|
140 |
+
cls.gnp = nx.gnp_random_graph(30, 0.1)
|
141 |
+
cls.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
|
142 |
+
cls.K20 = nx.complete_graph(20)
|
143 |
+
cls.K10 = nx.complete_graph(10)
|
144 |
+
cls.K5 = nx.complete_graph(5)
|
145 |
+
cls.G_list = [
|
146 |
+
cls.path,
|
147 |
+
cls.directed_path,
|
148 |
+
cls.cycle,
|
149 |
+
cls.directed_cycle,
|
150 |
+
cls.gnp,
|
151 |
+
cls.directed_gnp,
|
152 |
+
cls.K10,
|
153 |
+
cls.K5,
|
154 |
+
cls.K20,
|
155 |
+
]
|
156 |
+
|
157 |
+
def test_cycles(self):
|
158 |
+
K_undir = approx.all_pairs_node_connectivity(self.cycle)
|
159 |
+
for source in K_undir:
|
160 |
+
for target, k in K_undir[source].items():
|
161 |
+
assert k == 2
|
162 |
+
K_dir = approx.all_pairs_node_connectivity(self.directed_cycle)
|
163 |
+
for source in K_dir:
|
164 |
+
for target, k in K_dir[source].items():
|
165 |
+
assert k == 1
|
166 |
+
|
167 |
+
def test_complete(self):
|
168 |
+
for G in [self.K10, self.K5, self.K20]:
|
169 |
+
K = approx.all_pairs_node_connectivity(G)
|
170 |
+
for source in K:
|
171 |
+
for target, k in K[source].items():
|
172 |
+
assert k == len(G) - 1
|
173 |
+
|
174 |
+
def test_paths(self):
|
175 |
+
K_undir = approx.all_pairs_node_connectivity(self.path)
|
176 |
+
for source in K_undir:
|
177 |
+
for target, k in K_undir[source].items():
|
178 |
+
assert k == 1
|
179 |
+
K_dir = approx.all_pairs_node_connectivity(self.directed_path)
|
180 |
+
for source in K_dir:
|
181 |
+
for target, k in K_dir[source].items():
|
182 |
+
if source < target:
|
183 |
+
assert k == 1
|
184 |
+
else:
|
185 |
+
assert k == 0
|
186 |
+
|
187 |
+
def test_cutoff(self):
|
188 |
+
for G in [self.K10, self.K5, self.K20]:
|
189 |
+
for mp in [2, 3, 4]:
|
190 |
+
paths = approx.all_pairs_node_connectivity(G, cutoff=mp)
|
191 |
+
for source in paths:
|
192 |
+
for target, K in paths[source].items():
|
193 |
+
assert K == mp
|
194 |
+
|
195 |
+
def test_all_pairs_connectivity_nbunch(self):
|
196 |
+
G = nx.complete_graph(5)
|
197 |
+
nbunch = [0, 2, 3]
|
198 |
+
C = approx.all_pairs_node_connectivity(G, nbunch=nbunch)
|
199 |
+
assert len(C) == len(nbunch)
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_distance_measures.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.approximation.distance_measures` module.
|
2 |
+
"""
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
from networkx.algorithms.approximation import diameter
|
8 |
+
|
9 |
+
|
10 |
+
class TestDiameter:
|
11 |
+
"""Unit tests for the approximate diameter function
|
12 |
+
:func:`~networkx.algorithms.approximation.distance_measures.diameter`.
|
13 |
+
"""
|
14 |
+
|
15 |
+
def test_null_graph(self):
|
16 |
+
"""Test empty graph."""
|
17 |
+
G = nx.null_graph()
|
18 |
+
with pytest.raises(
|
19 |
+
nx.NetworkXError, match="Expected non-empty NetworkX graph!"
|
20 |
+
):
|
21 |
+
diameter(G)
|
22 |
+
|
23 |
+
def test_undirected_non_connected(self):
|
24 |
+
"""Test an undirected disconnected graph."""
|
25 |
+
graph = nx.path_graph(10)
|
26 |
+
graph.remove_edge(3, 4)
|
27 |
+
with pytest.raises(nx.NetworkXError, match="Graph not connected."):
|
28 |
+
diameter(graph)
|
29 |
+
|
30 |
+
def test_directed_non_strongly_connected(self):
|
31 |
+
"""Test a directed non strongly connected graph."""
|
32 |
+
graph = nx.path_graph(10, create_using=nx.DiGraph())
|
33 |
+
with pytest.raises(nx.NetworkXError, match="DiGraph not strongly connected."):
|
34 |
+
diameter(graph)
|
35 |
+
|
36 |
+
def test_complete_undirected_graph(self):
|
37 |
+
"""Test a complete undirected graph."""
|
38 |
+
graph = nx.complete_graph(10)
|
39 |
+
assert diameter(graph) == 1
|
40 |
+
|
41 |
+
def test_complete_directed_graph(self):
|
42 |
+
"""Test a complete directed graph."""
|
43 |
+
graph = nx.complete_graph(10, create_using=nx.DiGraph())
|
44 |
+
assert diameter(graph) == 1
|
45 |
+
|
46 |
+
def test_undirected_path_graph(self):
|
47 |
+
"""Test an undirected path graph with 10 nodes."""
|
48 |
+
graph = nx.path_graph(10)
|
49 |
+
assert diameter(graph) == 9
|
50 |
+
|
51 |
+
def test_directed_path_graph(self):
|
52 |
+
"""Test a directed path graph with 10 nodes."""
|
53 |
+
graph = nx.path_graph(10).to_directed()
|
54 |
+
assert diameter(graph) == 9
|
55 |
+
|
56 |
+
def test_single_node(self):
|
57 |
+
"""Test a graph which contains just a node."""
|
58 |
+
graph = nx.Graph()
|
59 |
+
graph.add_node(1)
|
60 |
+
assert diameter(graph) == 0
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms.approximation import (
|
5 |
+
min_edge_dominating_set,
|
6 |
+
min_weighted_dominating_set,
|
7 |
+
)
|
8 |
+
|
9 |
+
|
10 |
+
class TestMinWeightDominatingSet:
|
11 |
+
def test_min_weighted_dominating_set(self):
|
12 |
+
graph = nx.Graph()
|
13 |
+
graph.add_edge(1, 2)
|
14 |
+
graph.add_edge(1, 5)
|
15 |
+
graph.add_edge(2, 3)
|
16 |
+
graph.add_edge(2, 5)
|
17 |
+
graph.add_edge(3, 4)
|
18 |
+
graph.add_edge(3, 6)
|
19 |
+
graph.add_edge(5, 6)
|
20 |
+
|
21 |
+
vertices = {1, 2, 3, 4, 5, 6}
|
22 |
+
# due to ties, this might be hard to test tight bounds
|
23 |
+
dom_set = min_weighted_dominating_set(graph)
|
24 |
+
for vertex in vertices - dom_set:
|
25 |
+
neighbors = set(graph.neighbors(vertex))
|
26 |
+
assert len(neighbors & dom_set) > 0, "Non dominating set found!"
|
27 |
+
|
28 |
+
def test_star_graph(self):
|
29 |
+
"""Tests that an approximate dominating set for the star graph,
|
30 |
+
even when the center node does not have the smallest integer
|
31 |
+
label, gives just the center node.
|
32 |
+
|
33 |
+
For more information, see #1527.
|
34 |
+
|
35 |
+
"""
|
36 |
+
# Create a star graph in which the center node has the highest
|
37 |
+
# label instead of the lowest.
|
38 |
+
G = nx.star_graph(10)
|
39 |
+
G = nx.relabel_nodes(G, {0: 9, 9: 0})
|
40 |
+
assert min_weighted_dominating_set(G) == {9}
|
41 |
+
|
42 |
+
def test_null_graph(self):
|
43 |
+
"""Tests that the unique dominating set for the null graph is an empty set"""
|
44 |
+
G = nx.Graph()
|
45 |
+
assert min_weighted_dominating_set(G) == set()
|
46 |
+
|
47 |
+
def test_min_edge_dominating_set(self):
|
48 |
+
graph = nx.path_graph(5)
|
49 |
+
dom_set = min_edge_dominating_set(graph)
|
50 |
+
|
51 |
+
# this is a crappy way to test, but good enough for now.
|
52 |
+
for edge in graph.edges():
|
53 |
+
if edge in dom_set:
|
54 |
+
continue
|
55 |
+
else:
|
56 |
+
u, v = edge
|
57 |
+
found = False
|
58 |
+
for dom_edge in dom_set:
|
59 |
+
found |= u == dom_edge[0] or u == dom_edge[1]
|
60 |
+
assert found, "Non adjacent edge found!"
|
61 |
+
|
62 |
+
graph = nx.complete_graph(10)
|
63 |
+
dom_set = min_edge_dominating_set(graph)
|
64 |
+
|
65 |
+
# this is a crappy way to test, but good enough for now.
|
66 |
+
for edge in graph.edges():
|
67 |
+
if edge in dom_set:
|
68 |
+
continue
|
69 |
+
else:
|
70 |
+
u, v = edge
|
71 |
+
found = False
|
72 |
+
for dom_edge in dom_set:
|
73 |
+
found |= u == dom_edge[0] or u == dom_edge[1]
|
74 |
+
assert found, "Non adjacent edge found!"
|
75 |
+
|
76 |
+
graph = nx.Graph() # empty Networkx graph
|
77 |
+
with pytest.raises(ValueError, match="Expected non-empty NetworkX graph!"):
|
78 |
+
min_edge_dominating_set(graph)
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_kcomponents.py
ADDED
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Test for approximation to k-components algorithm
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
from networkx.algorithms.approximation import k_components
|
6 |
+
from networkx.algorithms.approximation.kcomponents import _AntiGraph, _same
|
7 |
+
|
8 |
+
|
9 |
+
def build_k_number_dict(k_components):
|
10 |
+
k_num = {}
|
11 |
+
for k, comps in sorted(k_components.items()):
|
12 |
+
for comp in comps:
|
13 |
+
for node in comp:
|
14 |
+
k_num[node] = k
|
15 |
+
return k_num
|
16 |
+
|
17 |
+
|
18 |
+
##
|
19 |
+
# Some nice synthetic graphs
|
20 |
+
##
|
21 |
+
|
22 |
+
|
23 |
+
def graph_example_1():
|
24 |
+
G = nx.convert_node_labels_to_integers(
|
25 |
+
nx.grid_graph([5, 5]), label_attribute="labels"
|
26 |
+
)
|
27 |
+
rlabels = nx.get_node_attributes(G, "labels")
|
28 |
+
labels = {v: k for k, v in rlabels.items()}
|
29 |
+
|
30 |
+
for nodes in [
|
31 |
+
(labels[(0, 0)], labels[(1, 0)]),
|
32 |
+
(labels[(0, 4)], labels[(1, 4)]),
|
33 |
+
(labels[(3, 0)], labels[(4, 0)]),
|
34 |
+
(labels[(3, 4)], labels[(4, 4)]),
|
35 |
+
]:
|
36 |
+
new_node = G.order() + 1
|
37 |
+
# Petersen graph is triconnected
|
38 |
+
P = nx.petersen_graph()
|
39 |
+
G = nx.disjoint_union(G, P)
|
40 |
+
# Add two edges between the grid and P
|
41 |
+
G.add_edge(new_node + 1, nodes[0])
|
42 |
+
G.add_edge(new_node, nodes[1])
|
43 |
+
# K5 is 4-connected
|
44 |
+
K = nx.complete_graph(5)
|
45 |
+
G = nx.disjoint_union(G, K)
|
46 |
+
# Add three edges between P and K5
|
47 |
+
G.add_edge(new_node + 2, new_node + 11)
|
48 |
+
G.add_edge(new_node + 3, new_node + 12)
|
49 |
+
G.add_edge(new_node + 4, new_node + 13)
|
50 |
+
# Add another K5 sharing a node
|
51 |
+
G = nx.disjoint_union(G, K)
|
52 |
+
nbrs = G[new_node + 10]
|
53 |
+
G.remove_node(new_node + 10)
|
54 |
+
for nbr in nbrs:
|
55 |
+
G.add_edge(new_node + 17, nbr)
|
56 |
+
G.add_edge(new_node + 16, new_node + 5)
|
57 |
+
return G
|
58 |
+
|
59 |
+
|
60 |
+
def torrents_and_ferraro_graph():
|
61 |
+
G = nx.convert_node_labels_to_integers(
|
62 |
+
nx.grid_graph([5, 5]), label_attribute="labels"
|
63 |
+
)
|
64 |
+
rlabels = nx.get_node_attributes(G, "labels")
|
65 |
+
labels = {v: k for k, v in rlabels.items()}
|
66 |
+
|
67 |
+
for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]:
|
68 |
+
new_node = G.order() + 1
|
69 |
+
# Petersen graph is triconnected
|
70 |
+
P = nx.petersen_graph()
|
71 |
+
G = nx.disjoint_union(G, P)
|
72 |
+
# Add two edges between the grid and P
|
73 |
+
G.add_edge(new_node + 1, nodes[0])
|
74 |
+
G.add_edge(new_node, nodes[1])
|
75 |
+
# K5 is 4-connected
|
76 |
+
K = nx.complete_graph(5)
|
77 |
+
G = nx.disjoint_union(G, K)
|
78 |
+
# Add three edges between P and K5
|
79 |
+
G.add_edge(new_node + 2, new_node + 11)
|
80 |
+
G.add_edge(new_node + 3, new_node + 12)
|
81 |
+
G.add_edge(new_node + 4, new_node + 13)
|
82 |
+
# Add another K5 sharing a node
|
83 |
+
G = nx.disjoint_union(G, K)
|
84 |
+
nbrs = G[new_node + 10]
|
85 |
+
G.remove_node(new_node + 10)
|
86 |
+
for nbr in nbrs:
|
87 |
+
G.add_edge(new_node + 17, nbr)
|
88 |
+
# Commenting this makes the graph not biconnected !!
|
89 |
+
# This stupid mistake make one reviewer very angry :P
|
90 |
+
G.add_edge(new_node + 16, new_node + 8)
|
91 |
+
|
92 |
+
for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]:
|
93 |
+
new_node = G.order() + 1
|
94 |
+
# Petersen graph is triconnected
|
95 |
+
P = nx.petersen_graph()
|
96 |
+
G = nx.disjoint_union(G, P)
|
97 |
+
# Add two edges between the grid and P
|
98 |
+
G.add_edge(new_node + 1, nodes[0])
|
99 |
+
G.add_edge(new_node, nodes[1])
|
100 |
+
# K5 is 4-connected
|
101 |
+
K = nx.complete_graph(5)
|
102 |
+
G = nx.disjoint_union(G, K)
|
103 |
+
# Add three edges between P and K5
|
104 |
+
G.add_edge(new_node + 2, new_node + 11)
|
105 |
+
G.add_edge(new_node + 3, new_node + 12)
|
106 |
+
G.add_edge(new_node + 4, new_node + 13)
|
107 |
+
# Add another K5 sharing two nodes
|
108 |
+
G = nx.disjoint_union(G, K)
|
109 |
+
nbrs = G[new_node + 10]
|
110 |
+
G.remove_node(new_node + 10)
|
111 |
+
for nbr in nbrs:
|
112 |
+
G.add_edge(new_node + 17, nbr)
|
113 |
+
nbrs2 = G[new_node + 9]
|
114 |
+
G.remove_node(new_node + 9)
|
115 |
+
for nbr in nbrs2:
|
116 |
+
G.add_edge(new_node + 18, nbr)
|
117 |
+
return G
|
118 |
+
|
119 |
+
|
120 |
+
# Helper function
|
121 |
+
|
122 |
+
|
123 |
+
def _check_connectivity(G):
|
124 |
+
result = k_components(G)
|
125 |
+
for k, components in result.items():
|
126 |
+
if k < 3:
|
127 |
+
continue
|
128 |
+
for component in components:
|
129 |
+
C = G.subgraph(component)
|
130 |
+
K = nx.node_connectivity(C)
|
131 |
+
assert K >= k
|
132 |
+
|
133 |
+
|
134 |
+
def test_torrents_and_ferraro_graph():
|
135 |
+
G = torrents_and_ferraro_graph()
|
136 |
+
_check_connectivity(G)
|
137 |
+
|
138 |
+
|
139 |
+
def test_example_1():
|
140 |
+
G = graph_example_1()
|
141 |
+
_check_connectivity(G)
|
142 |
+
|
143 |
+
|
144 |
+
def test_karate_0():
|
145 |
+
G = nx.karate_club_graph()
|
146 |
+
_check_connectivity(G)
|
147 |
+
|
148 |
+
|
149 |
+
def test_karate_1():
|
150 |
+
karate_k_num = {
|
151 |
+
0: 4,
|
152 |
+
1: 4,
|
153 |
+
2: 4,
|
154 |
+
3: 4,
|
155 |
+
4: 3,
|
156 |
+
5: 3,
|
157 |
+
6: 3,
|
158 |
+
7: 4,
|
159 |
+
8: 4,
|
160 |
+
9: 2,
|
161 |
+
10: 3,
|
162 |
+
11: 1,
|
163 |
+
12: 2,
|
164 |
+
13: 4,
|
165 |
+
14: 2,
|
166 |
+
15: 2,
|
167 |
+
16: 2,
|
168 |
+
17: 2,
|
169 |
+
18: 2,
|
170 |
+
19: 3,
|
171 |
+
20: 2,
|
172 |
+
21: 2,
|
173 |
+
22: 2,
|
174 |
+
23: 3,
|
175 |
+
24: 3,
|
176 |
+
25: 3,
|
177 |
+
26: 2,
|
178 |
+
27: 3,
|
179 |
+
28: 3,
|
180 |
+
29: 3,
|
181 |
+
30: 4,
|
182 |
+
31: 3,
|
183 |
+
32: 4,
|
184 |
+
33: 4,
|
185 |
+
}
|
186 |
+
approx_karate_k_num = karate_k_num.copy()
|
187 |
+
approx_karate_k_num[24] = 2
|
188 |
+
approx_karate_k_num[25] = 2
|
189 |
+
G = nx.karate_club_graph()
|
190 |
+
k_comps = k_components(G)
|
191 |
+
k_num = build_k_number_dict(k_comps)
|
192 |
+
assert k_num in (karate_k_num, approx_karate_k_num)
|
193 |
+
|
194 |
+
|
195 |
+
def test_example_1_detail_3_and_4():
|
196 |
+
G = graph_example_1()
|
197 |
+
result = k_components(G)
|
198 |
+
# In this example graph there are 8 3-components, 4 with 15 nodes
|
199 |
+
# and 4 with 5 nodes.
|
200 |
+
assert len(result[3]) == 8
|
201 |
+
assert len([c for c in result[3] if len(c) == 15]) == 4
|
202 |
+
assert len([c for c in result[3] if len(c) == 5]) == 4
|
203 |
+
# There are also 8 4-components all with 5 nodes.
|
204 |
+
assert len(result[4]) == 8
|
205 |
+
assert all(len(c) == 5 for c in result[4])
|
206 |
+
# Finally check that the k-components detected have actually node
|
207 |
+
# connectivity >= k.
|
208 |
+
for k, components in result.items():
|
209 |
+
if k < 3:
|
210 |
+
continue
|
211 |
+
for component in components:
|
212 |
+
K = nx.node_connectivity(G.subgraph(component))
|
213 |
+
assert K >= k
|
214 |
+
|
215 |
+
|
216 |
+
def test_directed():
|
217 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
218 |
+
G = nx.gnp_random_graph(10, 0.4, directed=True)
|
219 |
+
kc = k_components(G)
|
220 |
+
|
221 |
+
|
222 |
+
def test_same():
|
223 |
+
equal = {"A": 2, "B": 2, "C": 2}
|
224 |
+
slightly_different = {"A": 2, "B": 1, "C": 2}
|
225 |
+
different = {"A": 2, "B": 8, "C": 18}
|
226 |
+
assert _same(equal)
|
227 |
+
assert not _same(slightly_different)
|
228 |
+
assert _same(slightly_different, tol=1)
|
229 |
+
assert not _same(different)
|
230 |
+
assert not _same(different, tol=4)
|
231 |
+
|
232 |
+
|
233 |
+
class TestAntiGraph:
|
234 |
+
@classmethod
|
235 |
+
def setup_class(cls):
|
236 |
+
cls.Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
|
237 |
+
cls.Anp = _AntiGraph(nx.complement(cls.Gnp))
|
238 |
+
cls.Gd = nx.davis_southern_women_graph()
|
239 |
+
cls.Ad = _AntiGraph(nx.complement(cls.Gd))
|
240 |
+
cls.Gk = nx.karate_club_graph()
|
241 |
+
cls.Ak = _AntiGraph(nx.complement(cls.Gk))
|
242 |
+
cls.GA = [(cls.Gnp, cls.Anp), (cls.Gd, cls.Ad), (cls.Gk, cls.Ak)]
|
243 |
+
|
244 |
+
def test_size(self):
|
245 |
+
for G, A in self.GA:
|
246 |
+
n = G.order()
|
247 |
+
s = len(list(G.edges())) + len(list(A.edges()))
|
248 |
+
assert s == (n * (n - 1)) / 2
|
249 |
+
|
250 |
+
def test_degree(self):
|
251 |
+
for G, A in self.GA:
|
252 |
+
assert sorted(G.degree()) == sorted(A.degree())
|
253 |
+
|
254 |
+
def test_core_number(self):
|
255 |
+
for G, A in self.GA:
|
256 |
+
assert nx.core_number(G) == nx.core_number(A)
|
257 |
+
|
258 |
+
def test_connected_components(self):
|
259 |
+
# ccs are same unless isolated nodes or any node has degree=len(G)-1
|
260 |
+
# graphs in self.GA avoid this problem
|
261 |
+
for G, A in self.GA:
|
262 |
+
gc = [set(c) for c in nx.connected_components(G)]
|
263 |
+
ac = [set(c) for c in nx.connected_components(A)]
|
264 |
+
for comp in ac:
|
265 |
+
assert comp in gc
|
266 |
+
|
267 |
+
def test_adj(self):
|
268 |
+
for G, A in self.GA:
|
269 |
+
for n, nbrs in G.adj.items():
|
270 |
+
a_adj = sorted((n, sorted(ad)) for n, ad in A.adj.items())
|
271 |
+
g_adj = sorted((n, sorted(ad)) for n, ad in G.adj.items())
|
272 |
+
assert a_adj == g_adj
|
273 |
+
|
274 |
+
def test_adjacency(self):
|
275 |
+
for G, A in self.GA:
|
276 |
+
a_adj = list(A.adjacency())
|
277 |
+
for n, nbrs in G.adjacency():
|
278 |
+
assert (n, set(nbrs)) in a_adj
|
279 |
+
|
280 |
+
def test_neighbors(self):
|
281 |
+
for G, A in self.GA:
|
282 |
+
node = list(G.nodes())[0]
|
283 |
+
assert set(G.neighbors(node)) == set(A.neighbors(node))
|
284 |
+
|
285 |
+
def test_node_not_in_graph(self):
|
286 |
+
for G, A in self.GA:
|
287 |
+
node = "non_existent_node"
|
288 |
+
pytest.raises(nx.NetworkXError, A.neighbors, node)
|
289 |
+
pytest.raises(nx.NetworkXError, G.neighbors, node)
|
290 |
+
|
291 |
+
def test_degree_thingraph(self):
|
292 |
+
for G, A in self.GA:
|
293 |
+
node = list(G.nodes())[0]
|
294 |
+
nodes = list(G.nodes())[1:4]
|
295 |
+
assert G.degree(node) == A.degree(node)
|
296 |
+
assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
|
297 |
+
# AntiGraph is a ThinGraph, so all the weights are 1
|
298 |
+
assert sum(d for n, d in A.degree()) == sum(
|
299 |
+
d for n, d in A.degree(weight="weight")
|
300 |
+
)
|
301 |
+
assert sum(d for n, d in G.degree(nodes)) == sum(
|
302 |
+
d for n, d in A.degree(nodes)
|
303 |
+
)
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_matching.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
import networkx.algorithms.approximation as a
|
3 |
+
|
4 |
+
|
5 |
+
def test_min_maximal_matching():
|
6 |
+
# smoke test
|
7 |
+
G = nx.Graph()
|
8 |
+
assert len(a.min_maximal_matching(G)) == 0
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx.algorithms.approximation import maxcut
|
7 |
+
|
8 |
+
|
9 |
+
@pytest.mark.parametrize(
|
10 |
+
"f", (nx.approximation.randomized_partitioning, nx.approximation.one_exchange)
|
11 |
+
)
|
12 |
+
@pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
|
13 |
+
def test_raises_on_directed_and_multigraphs(f, graph_constructor):
|
14 |
+
G = graph_constructor([(0, 1), (1, 2)])
|
15 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
16 |
+
f(G)
|
17 |
+
|
18 |
+
|
19 |
+
def _is_valid_cut(G, set1, set2):
|
20 |
+
union = set1.union(set2)
|
21 |
+
assert union == set(G.nodes)
|
22 |
+
assert len(set1) + len(set2) == G.number_of_nodes()
|
23 |
+
|
24 |
+
|
25 |
+
def _cut_is_locally_optimal(G, cut_size, set1):
|
26 |
+
# test if cut can be locally improved
|
27 |
+
for i, node in enumerate(set1):
|
28 |
+
cut_size_without_node = nx.algorithms.cut_size(
|
29 |
+
G, set1 - {node}, weight="weight"
|
30 |
+
)
|
31 |
+
assert cut_size_without_node <= cut_size
|
32 |
+
|
33 |
+
|
34 |
+
def test_random_partitioning():
|
35 |
+
G = nx.complete_graph(5)
|
36 |
+
_, (set1, set2) = maxcut.randomized_partitioning(G, seed=5)
|
37 |
+
_is_valid_cut(G, set1, set2)
|
38 |
+
|
39 |
+
|
40 |
+
def test_random_partitioning_all_to_one():
|
41 |
+
G = nx.complete_graph(5)
|
42 |
+
_, (set1, set2) = maxcut.randomized_partitioning(G, p=1)
|
43 |
+
_is_valid_cut(G, set1, set2)
|
44 |
+
assert len(set1) == G.number_of_nodes()
|
45 |
+
assert len(set2) == 0
|
46 |
+
|
47 |
+
|
48 |
+
def test_one_exchange_basic():
|
49 |
+
G = nx.complete_graph(5)
|
50 |
+
random.seed(5)
|
51 |
+
for u, v, w in G.edges(data=True):
|
52 |
+
w["weight"] = random.randrange(-100, 100, 1) / 10
|
53 |
+
|
54 |
+
initial_cut = set(random.sample(sorted(G.nodes()), k=5))
|
55 |
+
cut_size, (set1, set2) = maxcut.one_exchange(
|
56 |
+
G, initial_cut, weight="weight", seed=5
|
57 |
+
)
|
58 |
+
|
59 |
+
_is_valid_cut(G, set1, set2)
|
60 |
+
_cut_is_locally_optimal(G, cut_size, set1)
|
61 |
+
|
62 |
+
|
63 |
+
def test_one_exchange_optimal():
|
64 |
+
# Greedy one exchange should find the optimal solution for this graph (14)
|
65 |
+
G = nx.Graph()
|
66 |
+
G.add_edge(1, 2, weight=3)
|
67 |
+
G.add_edge(1, 3, weight=3)
|
68 |
+
G.add_edge(1, 4, weight=3)
|
69 |
+
G.add_edge(1, 5, weight=3)
|
70 |
+
G.add_edge(2, 3, weight=5)
|
71 |
+
|
72 |
+
cut_size, (set1, set2) = maxcut.one_exchange(G, weight="weight", seed=5)
|
73 |
+
|
74 |
+
_is_valid_cut(G, set1, set2)
|
75 |
+
_cut_is_locally_optimal(G, cut_size, set1)
|
76 |
+
# check global optimality
|
77 |
+
assert cut_size == 14
|
78 |
+
|
79 |
+
|
80 |
+
def test_negative_weights():
|
81 |
+
G = nx.complete_graph(5)
|
82 |
+
random.seed(5)
|
83 |
+
for u, v, w in G.edges(data=True):
|
84 |
+
w["weight"] = -1 * random.random()
|
85 |
+
|
86 |
+
initial_cut = set(random.sample(sorted(G.nodes()), k=5))
|
87 |
+
cut_size, (set1, set2) = maxcut.one_exchange(G, initial_cut, weight="weight")
|
88 |
+
|
89 |
+
# make sure it is a valid cut
|
90 |
+
_is_valid_cut(G, set1, set2)
|
91 |
+
# check local optimality
|
92 |
+
_cut_is_locally_optimal(G, cut_size, set1)
|
93 |
+
# test that all nodes are in the same partition
|
94 |
+
assert len(set1) == len(G.nodes) or len(set2) == len(G.nodes)
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_ramsey.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
import networkx.algorithms.approximation as apxa
|
3 |
+
|
4 |
+
|
5 |
+
def test_ramsey():
|
6 |
+
# this should only find the complete graph
|
7 |
+
graph = nx.complete_graph(10)
|
8 |
+
c, i = apxa.ramsey_R2(graph)
|
9 |
+
cdens = nx.density(graph.subgraph(c))
|
10 |
+
assert cdens == 1.0, "clique not correctly found by ramsey!"
|
11 |
+
idens = nx.density(graph.subgraph(i))
|
12 |
+
assert idens == 0.0, "i-set not correctly found by ramsey!"
|
13 |
+
|
14 |
+
# this trivial graph has no cliques. should just find i-sets
|
15 |
+
graph = nx.trivial_graph()
|
16 |
+
c, i = apxa.ramsey_R2(graph)
|
17 |
+
assert c == {0}, "clique not correctly found by ramsey!"
|
18 |
+
assert i == {0}, "i-set not correctly found by ramsey!"
|
19 |
+
|
20 |
+
graph = nx.barbell_graph(10, 5, nx.Graph())
|
21 |
+
c, i = apxa.ramsey_R2(graph)
|
22 |
+
cdens = nx.density(graph.subgraph(c))
|
23 |
+
assert cdens == 1.0, "clique not correctly found by ramsey!"
|
24 |
+
idens = nx.density(graph.subgraph(i))
|
25 |
+
assert idens == 0.0, "i-set not correctly found by ramsey!"
|
26 |
+
|
27 |
+
# add self-loops and test again
|
28 |
+
graph.add_edges_from([(n, n) for n in range(0, len(graph), 2)])
|
29 |
+
cc, ii = apxa.ramsey_R2(graph)
|
30 |
+
assert cc == c
|
31 |
+
assert ii == i
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_steinertree.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms.approximation.steinertree import metric_closure, steiner_tree
|
5 |
+
from networkx.utils import edges_equal
|
6 |
+
|
7 |
+
|
8 |
+
class TestSteinerTree:
|
9 |
+
@classmethod
|
10 |
+
def setup_class(cls):
|
11 |
+
G1 = nx.Graph()
|
12 |
+
G1.add_edge(1, 2, weight=10)
|
13 |
+
G1.add_edge(2, 3, weight=10)
|
14 |
+
G1.add_edge(3, 4, weight=10)
|
15 |
+
G1.add_edge(4, 5, weight=10)
|
16 |
+
G1.add_edge(5, 6, weight=10)
|
17 |
+
G1.add_edge(2, 7, weight=1)
|
18 |
+
G1.add_edge(7, 5, weight=1)
|
19 |
+
|
20 |
+
G2 = nx.Graph()
|
21 |
+
G2.add_edge(0, 5, weight=6)
|
22 |
+
G2.add_edge(1, 2, weight=2)
|
23 |
+
G2.add_edge(1, 5, weight=3)
|
24 |
+
G2.add_edge(2, 4, weight=4)
|
25 |
+
G2.add_edge(3, 5, weight=5)
|
26 |
+
G2.add_edge(4, 5, weight=1)
|
27 |
+
|
28 |
+
G3 = nx.Graph()
|
29 |
+
G3.add_edge(1, 2, weight=8)
|
30 |
+
G3.add_edge(1, 9, weight=3)
|
31 |
+
G3.add_edge(1, 8, weight=6)
|
32 |
+
G3.add_edge(1, 10, weight=2)
|
33 |
+
G3.add_edge(1, 14, weight=3)
|
34 |
+
G3.add_edge(2, 3, weight=6)
|
35 |
+
G3.add_edge(3, 4, weight=3)
|
36 |
+
G3.add_edge(3, 10, weight=2)
|
37 |
+
G3.add_edge(3, 11, weight=1)
|
38 |
+
G3.add_edge(4, 5, weight=1)
|
39 |
+
G3.add_edge(4, 11, weight=1)
|
40 |
+
G3.add_edge(5, 6, weight=4)
|
41 |
+
G3.add_edge(5, 11, weight=2)
|
42 |
+
G3.add_edge(5, 12, weight=1)
|
43 |
+
G3.add_edge(5, 13, weight=3)
|
44 |
+
G3.add_edge(6, 7, weight=2)
|
45 |
+
G3.add_edge(6, 12, weight=3)
|
46 |
+
G3.add_edge(6, 13, weight=1)
|
47 |
+
G3.add_edge(7, 8, weight=3)
|
48 |
+
G3.add_edge(7, 9, weight=3)
|
49 |
+
G3.add_edge(7, 11, weight=5)
|
50 |
+
G3.add_edge(7, 13, weight=2)
|
51 |
+
G3.add_edge(7, 14, weight=4)
|
52 |
+
G3.add_edge(8, 9, weight=2)
|
53 |
+
G3.add_edge(9, 14, weight=1)
|
54 |
+
G3.add_edge(10, 11, weight=2)
|
55 |
+
G3.add_edge(10, 14, weight=1)
|
56 |
+
G3.add_edge(11, 12, weight=1)
|
57 |
+
G3.add_edge(11, 14, weight=7)
|
58 |
+
G3.add_edge(12, 14, weight=3)
|
59 |
+
G3.add_edge(12, 15, weight=1)
|
60 |
+
G3.add_edge(13, 14, weight=4)
|
61 |
+
G3.add_edge(13, 15, weight=1)
|
62 |
+
G3.add_edge(14, 15, weight=2)
|
63 |
+
|
64 |
+
cls.G1 = G1
|
65 |
+
cls.G2 = G2
|
66 |
+
cls.G3 = G3
|
67 |
+
cls.G1_term_nodes = [1, 2, 3, 4, 5]
|
68 |
+
cls.G2_term_nodes = [0, 2, 3]
|
69 |
+
cls.G3_term_nodes = [1, 3, 5, 6, 8, 10, 11, 12, 13]
|
70 |
+
|
71 |
+
cls.methods = ["kou", "mehlhorn"]
|
72 |
+
|
73 |
+
def test_connected_metric_closure(self):
|
74 |
+
G = self.G1.copy()
|
75 |
+
G.add_node(100)
|
76 |
+
pytest.raises(nx.NetworkXError, metric_closure, G)
|
77 |
+
|
78 |
+
def test_metric_closure(self):
|
79 |
+
M = metric_closure(self.G1)
|
80 |
+
mc = [
|
81 |
+
(1, 2, {"distance": 10, "path": [1, 2]}),
|
82 |
+
(1, 3, {"distance": 20, "path": [1, 2, 3]}),
|
83 |
+
(1, 4, {"distance": 22, "path": [1, 2, 7, 5, 4]}),
|
84 |
+
(1, 5, {"distance": 12, "path": [1, 2, 7, 5]}),
|
85 |
+
(1, 6, {"distance": 22, "path": [1, 2, 7, 5, 6]}),
|
86 |
+
(1, 7, {"distance": 11, "path": [1, 2, 7]}),
|
87 |
+
(2, 3, {"distance": 10, "path": [2, 3]}),
|
88 |
+
(2, 4, {"distance": 12, "path": [2, 7, 5, 4]}),
|
89 |
+
(2, 5, {"distance": 2, "path": [2, 7, 5]}),
|
90 |
+
(2, 6, {"distance": 12, "path": [2, 7, 5, 6]}),
|
91 |
+
(2, 7, {"distance": 1, "path": [2, 7]}),
|
92 |
+
(3, 4, {"distance": 10, "path": [3, 4]}),
|
93 |
+
(3, 5, {"distance": 12, "path": [3, 2, 7, 5]}),
|
94 |
+
(3, 6, {"distance": 22, "path": [3, 2, 7, 5, 6]}),
|
95 |
+
(3, 7, {"distance": 11, "path": [3, 2, 7]}),
|
96 |
+
(4, 5, {"distance": 10, "path": [4, 5]}),
|
97 |
+
(4, 6, {"distance": 20, "path": [4, 5, 6]}),
|
98 |
+
(4, 7, {"distance": 11, "path": [4, 5, 7]}),
|
99 |
+
(5, 6, {"distance": 10, "path": [5, 6]}),
|
100 |
+
(5, 7, {"distance": 1, "path": [5, 7]}),
|
101 |
+
(6, 7, {"distance": 11, "path": [6, 5, 7]}),
|
102 |
+
]
|
103 |
+
assert edges_equal(list(M.edges(data=True)), mc)
|
104 |
+
|
105 |
+
def test_steiner_tree(self):
|
106 |
+
valid_steiner_trees = [
|
107 |
+
[
|
108 |
+
[
|
109 |
+
(1, 2, {"weight": 10}),
|
110 |
+
(2, 3, {"weight": 10}),
|
111 |
+
(2, 7, {"weight": 1}),
|
112 |
+
(3, 4, {"weight": 10}),
|
113 |
+
(5, 7, {"weight": 1}),
|
114 |
+
],
|
115 |
+
[
|
116 |
+
(1, 2, {"weight": 10}),
|
117 |
+
(2, 7, {"weight": 1}),
|
118 |
+
(3, 4, {"weight": 10}),
|
119 |
+
(4, 5, {"weight": 10}),
|
120 |
+
(5, 7, {"weight": 1}),
|
121 |
+
],
|
122 |
+
[
|
123 |
+
(1, 2, {"weight": 10}),
|
124 |
+
(2, 3, {"weight": 10}),
|
125 |
+
(2, 7, {"weight": 1}),
|
126 |
+
(4, 5, {"weight": 10}),
|
127 |
+
(5, 7, {"weight": 1}),
|
128 |
+
],
|
129 |
+
],
|
130 |
+
[
|
131 |
+
[
|
132 |
+
(0, 5, {"weight": 6}),
|
133 |
+
(1, 2, {"weight": 2}),
|
134 |
+
(1, 5, {"weight": 3}),
|
135 |
+
(3, 5, {"weight": 5}),
|
136 |
+
],
|
137 |
+
[
|
138 |
+
(0, 5, {"weight": 6}),
|
139 |
+
(4, 2, {"weight": 4}),
|
140 |
+
(4, 5, {"weight": 1}),
|
141 |
+
(3, 5, {"weight": 5}),
|
142 |
+
],
|
143 |
+
],
|
144 |
+
[
|
145 |
+
[
|
146 |
+
(1, 10, {"weight": 2}),
|
147 |
+
(3, 10, {"weight": 2}),
|
148 |
+
(3, 11, {"weight": 1}),
|
149 |
+
(5, 12, {"weight": 1}),
|
150 |
+
(6, 13, {"weight": 1}),
|
151 |
+
(8, 9, {"weight": 2}),
|
152 |
+
(9, 14, {"weight": 1}),
|
153 |
+
(10, 14, {"weight": 1}),
|
154 |
+
(11, 12, {"weight": 1}),
|
155 |
+
(12, 15, {"weight": 1}),
|
156 |
+
(13, 15, {"weight": 1}),
|
157 |
+
]
|
158 |
+
],
|
159 |
+
]
|
160 |
+
for method in self.methods:
|
161 |
+
for G, term_nodes, valid_trees in zip(
|
162 |
+
[self.G1, self.G2, self.G3],
|
163 |
+
[self.G1_term_nodes, self.G2_term_nodes, self.G3_term_nodes],
|
164 |
+
valid_steiner_trees,
|
165 |
+
):
|
166 |
+
S = steiner_tree(G, term_nodes, method=method)
|
167 |
+
assert any(
|
168 |
+
edges_equal(list(S.edges(data=True)), valid_tree)
|
169 |
+
for valid_tree in valid_trees
|
170 |
+
)
|
171 |
+
|
172 |
+
def test_multigraph_steiner_tree(self):
|
173 |
+
G = nx.MultiGraph()
|
174 |
+
G.add_edges_from(
|
175 |
+
[
|
176 |
+
(1, 2, 0, {"weight": 1}),
|
177 |
+
(2, 3, 0, {"weight": 999}),
|
178 |
+
(2, 3, 1, {"weight": 1}),
|
179 |
+
(3, 4, 0, {"weight": 1}),
|
180 |
+
(3, 5, 0, {"weight": 1}),
|
181 |
+
]
|
182 |
+
)
|
183 |
+
terminal_nodes = [2, 4, 5]
|
184 |
+
expected_edges = [
|
185 |
+
(2, 3, 1, {"weight": 1}), # edge with key 1 has lower weight
|
186 |
+
(3, 4, 0, {"weight": 1}),
|
187 |
+
(3, 5, 0, {"weight": 1}),
|
188 |
+
]
|
189 |
+
for method in self.methods:
|
190 |
+
S = steiner_tree(G, terminal_nodes, method=method)
|
191 |
+
assert edges_equal(S.edges(data=True, keys=True), expected_edges)
|
192 |
+
|
193 |
+
|
194 |
+
@pytest.mark.parametrize("method", ("kou", "mehlhorn"))
|
195 |
+
def test_steiner_tree_weight_attribute(method):
|
196 |
+
G = nx.star_graph(4)
|
197 |
+
# Add an edge attribute that is named something other than "weight"
|
198 |
+
nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
|
199 |
+
H = nx.approximation.steiner_tree(G, [1, 3], method=method, weight="distance")
|
200 |
+
assert nx.utils.edges_equal(H.edges, [(0, 1), (0, 3)])
|
201 |
+
|
202 |
+
|
203 |
+
@pytest.mark.parametrize("method", ("kou", "mehlhorn"))
|
204 |
+
def test_steiner_tree_multigraph_weight_attribute(method):
|
205 |
+
G = nx.cycle_graph(3, create_using=nx.MultiGraph)
|
206 |
+
nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
|
207 |
+
G.add_edge(2, 0, distance=5)
|
208 |
+
H = nx.approximation.steiner_tree(G, list(G), method=method, weight="distance")
|
209 |
+
assert len(H.edges) == 2 and H.has_edge(2, 0, key=1)
|
210 |
+
assert sum(dist for *_, dist in H.edges(data="distance")) == 15
|
211 |
+
|
212 |
+
|
213 |
+
@pytest.mark.parametrize("method", (None, "mehlhorn", "kou"))
|
214 |
+
def test_steiner_tree_methods(method):
|
215 |
+
G = nx.star_graph(4)
|
216 |
+
expected = nx.Graph([(0, 1), (0, 3)])
|
217 |
+
st = nx.approximation.steiner_tree(G, [1, 3], method=method)
|
218 |
+
assert nx.utils.edges_equal(st.edges, expected.edges)
|
219 |
+
|
220 |
+
|
221 |
+
def test_steiner_tree_method_invalid():
|
222 |
+
G = nx.star_graph(4)
|
223 |
+
with pytest.raises(
|
224 |
+
ValueError, match="invalid_method is not a valid choice for an algorithm."
|
225 |
+
):
|
226 |
+
nx.approximation.steiner_tree(G, terminal_nodes=[1, 3], method="invalid_method")
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_traveling_salesman.py
ADDED
@@ -0,0 +1,979 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the traveling_salesman module."""
|
2 |
+
|
3 |
+
import random
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
import networkx.algorithms.approximation as nx_app
|
9 |
+
|
10 |
+
pairwise = nx.utils.pairwise
|
11 |
+
|
12 |
+
|
13 |
+
def test_christofides_hamiltonian():
|
14 |
+
random.seed(42)
|
15 |
+
G = nx.complete_graph(20)
|
16 |
+
for u, v in G.edges():
|
17 |
+
G[u][v]["weight"] = random.randint(0, 10)
|
18 |
+
|
19 |
+
H = nx.Graph()
|
20 |
+
H.add_edges_from(pairwise(nx_app.christofides(G)))
|
21 |
+
H.remove_edges_from(nx.find_cycle(H))
|
22 |
+
assert len(H.edges) == 0
|
23 |
+
|
24 |
+
tree = nx.minimum_spanning_tree(G, weight="weight")
|
25 |
+
H = nx.Graph()
|
26 |
+
H.add_edges_from(pairwise(nx_app.christofides(G, tree)))
|
27 |
+
H.remove_edges_from(nx.find_cycle(H))
|
28 |
+
assert len(H.edges) == 0
|
29 |
+
|
30 |
+
|
31 |
+
def test_christofides_incomplete_graph():
|
32 |
+
G = nx.complete_graph(10)
|
33 |
+
G.remove_edge(0, 1)
|
34 |
+
pytest.raises(nx.NetworkXError, nx_app.christofides, G)
|
35 |
+
|
36 |
+
|
37 |
+
def test_christofides_ignore_selfloops():
|
38 |
+
G = nx.complete_graph(5)
|
39 |
+
G.add_edge(3, 3)
|
40 |
+
cycle = nx_app.christofides(G)
|
41 |
+
assert len(cycle) - 1 == len(G) == len(set(cycle))
|
42 |
+
|
43 |
+
|
44 |
+
# set up graphs for other tests
|
45 |
+
class TestBase:
|
46 |
+
@classmethod
|
47 |
+
def setup_class(cls):
|
48 |
+
cls.DG = nx.DiGraph()
|
49 |
+
cls.DG.add_weighted_edges_from(
|
50 |
+
{
|
51 |
+
("A", "B", 3),
|
52 |
+
("A", "C", 17),
|
53 |
+
("A", "D", 14),
|
54 |
+
("B", "A", 3),
|
55 |
+
("B", "C", 12),
|
56 |
+
("B", "D", 16),
|
57 |
+
("C", "A", 13),
|
58 |
+
("C", "B", 12),
|
59 |
+
("C", "D", 4),
|
60 |
+
("D", "A", 14),
|
61 |
+
("D", "B", 15),
|
62 |
+
("D", "C", 2),
|
63 |
+
}
|
64 |
+
)
|
65 |
+
cls.DG_cycle = ["D", "C", "B", "A", "D"]
|
66 |
+
cls.DG_cost = 31.0
|
67 |
+
|
68 |
+
cls.DG2 = nx.DiGraph()
|
69 |
+
cls.DG2.add_weighted_edges_from(
|
70 |
+
{
|
71 |
+
("A", "B", 3),
|
72 |
+
("A", "C", 17),
|
73 |
+
("A", "D", 14),
|
74 |
+
("B", "A", 30),
|
75 |
+
("B", "C", 2),
|
76 |
+
("B", "D", 16),
|
77 |
+
("C", "A", 33),
|
78 |
+
("C", "B", 32),
|
79 |
+
("C", "D", 34),
|
80 |
+
("D", "A", 14),
|
81 |
+
("D", "B", 15),
|
82 |
+
("D", "C", 2),
|
83 |
+
}
|
84 |
+
)
|
85 |
+
cls.DG2_cycle = ["D", "A", "B", "C", "D"]
|
86 |
+
cls.DG2_cost = 53.0
|
87 |
+
|
88 |
+
cls.unweightedUG = nx.complete_graph(5, nx.Graph())
|
89 |
+
cls.unweightedDG = nx.complete_graph(5, nx.DiGraph())
|
90 |
+
|
91 |
+
cls.incompleteUG = nx.Graph()
|
92 |
+
cls.incompleteUG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
|
93 |
+
cls.incompleteDG = nx.DiGraph()
|
94 |
+
cls.incompleteDG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)})
|
95 |
+
|
96 |
+
cls.UG = nx.Graph()
|
97 |
+
cls.UG.add_weighted_edges_from(
|
98 |
+
{
|
99 |
+
("A", "B", 3),
|
100 |
+
("A", "C", 17),
|
101 |
+
("A", "D", 14),
|
102 |
+
("B", "C", 12),
|
103 |
+
("B", "D", 16),
|
104 |
+
("C", "D", 4),
|
105 |
+
}
|
106 |
+
)
|
107 |
+
cls.UG_cycle = ["D", "C", "B", "A", "D"]
|
108 |
+
cls.UG_cost = 33.0
|
109 |
+
|
110 |
+
cls.UG2 = nx.Graph()
|
111 |
+
cls.UG2.add_weighted_edges_from(
|
112 |
+
{
|
113 |
+
("A", "B", 1),
|
114 |
+
("A", "C", 15),
|
115 |
+
("A", "D", 5),
|
116 |
+
("B", "C", 16),
|
117 |
+
("B", "D", 8),
|
118 |
+
("C", "D", 3),
|
119 |
+
}
|
120 |
+
)
|
121 |
+
cls.UG2_cycle = ["D", "C", "B", "A", "D"]
|
122 |
+
cls.UG2_cost = 25.0
|
123 |
+
|
124 |
+
|
125 |
+
def validate_solution(soln, cost, exp_soln, exp_cost):
|
126 |
+
assert soln == exp_soln
|
127 |
+
assert cost == exp_cost
|
128 |
+
|
129 |
+
|
130 |
+
def validate_symmetric_solution(soln, cost, exp_soln, exp_cost):
|
131 |
+
assert soln == exp_soln or soln == exp_soln[::-1]
|
132 |
+
assert cost == exp_cost
|
133 |
+
|
134 |
+
|
135 |
+
class TestGreedyTSP(TestBase):
|
136 |
+
def test_greedy(self):
|
137 |
+
cycle = nx_app.greedy_tsp(self.DG, source="D")
|
138 |
+
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
139 |
+
validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 31.0)
|
140 |
+
|
141 |
+
cycle = nx_app.greedy_tsp(self.DG2, source="D")
|
142 |
+
cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
143 |
+
validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 78.0)
|
144 |
+
|
145 |
+
cycle = nx_app.greedy_tsp(self.UG, source="D")
|
146 |
+
cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
147 |
+
validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 33.0)
|
148 |
+
|
149 |
+
cycle = nx_app.greedy_tsp(self.UG2, source="D")
|
150 |
+
cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
151 |
+
validate_solution(cycle, cost, ["D", "C", "A", "B", "D"], 27.0)
|
152 |
+
|
153 |
+
def test_not_complete_graph(self):
|
154 |
+
pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteUG)
|
155 |
+
pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteDG)
|
156 |
+
|
157 |
+
def test_not_weighted_graph(self):
|
158 |
+
nx_app.greedy_tsp(self.unweightedUG)
|
159 |
+
nx_app.greedy_tsp(self.unweightedDG)
|
160 |
+
|
161 |
+
def test_two_nodes(self):
|
162 |
+
G = nx.Graph()
|
163 |
+
G.add_weighted_edges_from({(1, 2, 1)})
|
164 |
+
cycle = nx_app.greedy_tsp(G)
|
165 |
+
cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
166 |
+
validate_solution(cycle, cost, [1, 2, 1], 2)
|
167 |
+
|
168 |
+
def test_ignore_selfloops(self):
|
169 |
+
G = nx.complete_graph(5)
|
170 |
+
G.add_edge(3, 3)
|
171 |
+
cycle = nx_app.greedy_tsp(G)
|
172 |
+
assert len(cycle) - 1 == len(G) == len(set(cycle))
|
173 |
+
|
174 |
+
|
175 |
+
class TestSimulatedAnnealingTSP(TestBase):
|
176 |
+
tsp = staticmethod(nx_app.simulated_annealing_tsp)
|
177 |
+
|
178 |
+
def test_simulated_annealing_directed(self):
|
179 |
+
cycle = self.tsp(self.DG, "greedy", source="D", seed=42)
|
180 |
+
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
181 |
+
validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
|
182 |
+
|
183 |
+
initial_sol = ["D", "B", "A", "C", "D"]
|
184 |
+
cycle = self.tsp(self.DG, initial_sol, source="D", seed=42)
|
185 |
+
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
186 |
+
validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
|
187 |
+
|
188 |
+
initial_sol = ["D", "A", "C", "B", "D"]
|
189 |
+
cycle = self.tsp(self.DG, initial_sol, move="1-0", source="D", seed=42)
|
190 |
+
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
191 |
+
validate_solution(cycle, cost, self.DG_cycle, self.DG_cost)
|
192 |
+
|
193 |
+
cycle = self.tsp(self.DG2, "greedy", source="D", seed=42)
|
194 |
+
cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
195 |
+
validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
|
196 |
+
|
197 |
+
cycle = self.tsp(self.DG2, "greedy", move="1-0", source="D", seed=42)
|
198 |
+
cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
199 |
+
validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost)
|
200 |
+
|
201 |
+
def test_simulated_annealing_undirected(self):
|
202 |
+
cycle = self.tsp(self.UG, "greedy", source="D", seed=42)
|
203 |
+
cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
204 |
+
validate_solution(cycle, cost, self.UG_cycle, self.UG_cost)
|
205 |
+
|
206 |
+
cycle = self.tsp(self.UG2, "greedy", source="D", seed=42)
|
207 |
+
cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
208 |
+
validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
|
209 |
+
|
210 |
+
cycle = self.tsp(self.UG2, "greedy", move="1-0", source="D", seed=42)
|
211 |
+
cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
212 |
+
validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost)
|
213 |
+
|
214 |
+
def test_error_on_input_order_mistake(self):
|
215 |
+
# see issue #4846 https://github.com/networkx/networkx/issues/4846
|
216 |
+
pytest.raises(TypeError, self.tsp, self.UG, weight="weight")
|
217 |
+
pytest.raises(nx.NetworkXError, self.tsp, self.UG, "weight")
|
218 |
+
|
219 |
+
def test_not_complete_graph(self):
|
220 |
+
pytest.raises(nx.NetworkXError, self.tsp, self.incompleteUG, "greedy", source=0)
|
221 |
+
pytest.raises(nx.NetworkXError, self.tsp, self.incompleteDG, "greedy", source=0)
|
222 |
+
|
223 |
+
def test_ignore_selfloops(self):
|
224 |
+
G = nx.complete_graph(5)
|
225 |
+
G.add_edge(3, 3)
|
226 |
+
cycle = self.tsp(G, "greedy")
|
227 |
+
assert len(cycle) - 1 == len(G) == len(set(cycle))
|
228 |
+
|
229 |
+
def test_not_weighted_graph(self):
|
230 |
+
self.tsp(self.unweightedUG, "greedy")
|
231 |
+
self.tsp(self.unweightedDG, "greedy")
|
232 |
+
|
233 |
+
def test_two_nodes(self):
|
234 |
+
G = nx.Graph()
|
235 |
+
G.add_weighted_edges_from({(1, 2, 1)})
|
236 |
+
|
237 |
+
cycle = self.tsp(G, "greedy", source=1, seed=42)
|
238 |
+
cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
239 |
+
validate_solution(cycle, cost, [1, 2, 1], 2)
|
240 |
+
|
241 |
+
cycle = self.tsp(G, [1, 2, 1], source=1, seed=42)
|
242 |
+
cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
243 |
+
validate_solution(cycle, cost, [1, 2, 1], 2)
|
244 |
+
|
245 |
+
def test_failure_of_costs_too_high_when_iterations_low(self):
|
246 |
+
# Simulated Annealing Version:
|
247 |
+
# set number of moves low and alpha high
|
248 |
+
cycle = self.tsp(
|
249 |
+
self.DG2, "greedy", source="D", move="1-0", alpha=1, N_inner=1, seed=42
|
250 |
+
)
|
251 |
+
cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
252 |
+
print(cycle, cost)
|
253 |
+
assert cost > self.DG2_cost
|
254 |
+
|
255 |
+
# Try with an incorrect initial guess
|
256 |
+
initial_sol = ["D", "A", "B", "C", "D"]
|
257 |
+
cycle = self.tsp(
|
258 |
+
self.DG,
|
259 |
+
initial_sol,
|
260 |
+
source="D",
|
261 |
+
move="1-0",
|
262 |
+
alpha=0.1,
|
263 |
+
N_inner=1,
|
264 |
+
max_iterations=1,
|
265 |
+
seed=42,
|
266 |
+
)
|
267 |
+
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
268 |
+
print(cycle, cost)
|
269 |
+
assert cost > self.DG_cost
|
270 |
+
|
271 |
+
|
272 |
+
class TestThresholdAcceptingTSP(TestSimulatedAnnealingTSP):
|
273 |
+
tsp = staticmethod(nx_app.threshold_accepting_tsp)
|
274 |
+
|
275 |
+
def test_failure_of_costs_too_high_when_iterations_low(self):
|
276 |
+
# Threshold Version:
|
277 |
+
# set number of moves low and number of iterations low
|
278 |
+
cycle = self.tsp(
|
279 |
+
self.DG2,
|
280 |
+
"greedy",
|
281 |
+
source="D",
|
282 |
+
move="1-0",
|
283 |
+
N_inner=1,
|
284 |
+
max_iterations=1,
|
285 |
+
seed=4,
|
286 |
+
)
|
287 |
+
cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
288 |
+
assert cost > self.DG2_cost
|
289 |
+
|
290 |
+
# set threshold too low
|
291 |
+
initial_sol = ["D", "A", "B", "C", "D"]
|
292 |
+
cycle = self.tsp(
|
293 |
+
self.DG, initial_sol, source="D", move="1-0", threshold=-3, seed=42
|
294 |
+
)
|
295 |
+
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
|
296 |
+
assert cost > self.DG_cost
|
297 |
+
|
298 |
+
|
299 |
+
# Tests for function traveling_salesman_problem
|
300 |
+
def test_TSP_method():
|
301 |
+
G = nx.cycle_graph(9)
|
302 |
+
G[4][5]["weight"] = 10
|
303 |
+
|
304 |
+
# Test using the old currying method
|
305 |
+
sa_tsp = lambda G, weight: nx_app.simulated_annealing_tsp(
|
306 |
+
G, "greedy", weight, source=4, seed=1
|
307 |
+
)
|
308 |
+
|
309 |
+
path = nx_app.traveling_salesman_problem(
|
310 |
+
G,
|
311 |
+
method=sa_tsp,
|
312 |
+
cycle=False,
|
313 |
+
)
|
314 |
+
print(path)
|
315 |
+
assert path == [4, 3, 2, 1, 0, 8, 7, 6, 5]
|
316 |
+
|
317 |
+
|
318 |
+
def test_TSP_unweighted():
|
319 |
+
G = nx.cycle_graph(9)
|
320 |
+
path = nx_app.traveling_salesman_problem(G, nodes=[3, 6], cycle=False)
|
321 |
+
assert path in ([3, 4, 5, 6], [6, 5, 4, 3])
|
322 |
+
|
323 |
+
cycle = nx_app.traveling_salesman_problem(G, nodes=[3, 6])
|
324 |
+
assert cycle in ([3, 4, 5, 6, 5, 4, 3], [6, 5, 4, 3, 4, 5, 6])
|
325 |
+
|
326 |
+
|
327 |
+
def test_TSP_weighted():
|
328 |
+
G = nx.cycle_graph(9)
|
329 |
+
G[0][1]["weight"] = 2
|
330 |
+
G[1][2]["weight"] = 2
|
331 |
+
G[2][3]["weight"] = 2
|
332 |
+
G[3][4]["weight"] = 4
|
333 |
+
G[4][5]["weight"] = 5
|
334 |
+
G[5][6]["weight"] = 4
|
335 |
+
G[6][7]["weight"] = 2
|
336 |
+
G[7][8]["weight"] = 2
|
337 |
+
G[8][0]["weight"] = 2
|
338 |
+
tsp = nx_app.traveling_salesman_problem
|
339 |
+
|
340 |
+
# path between 3 and 6
|
341 |
+
expected_paths = ([3, 2, 1, 0, 8, 7, 6], [6, 7, 8, 0, 1, 2, 3])
|
342 |
+
# cycle between 3 and 6
|
343 |
+
expected_cycles = (
|
344 |
+
[3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3],
|
345 |
+
[6, 7, 8, 0, 1, 2, 3, 2, 1, 0, 8, 7, 6],
|
346 |
+
)
|
347 |
+
# path through all nodes
|
348 |
+
expected_tourpaths = ([5, 6, 7, 8, 0, 1, 2, 3, 4], [4, 3, 2, 1, 0, 8, 7, 6, 5])
|
349 |
+
|
350 |
+
# Check default method
|
351 |
+
cycle = tsp(G, nodes=[3, 6], weight="weight")
|
352 |
+
assert cycle in expected_cycles
|
353 |
+
|
354 |
+
path = tsp(G, nodes=[3, 6], weight="weight", cycle=False)
|
355 |
+
assert path in expected_paths
|
356 |
+
|
357 |
+
tourpath = tsp(G, weight="weight", cycle=False)
|
358 |
+
assert tourpath in expected_tourpaths
|
359 |
+
|
360 |
+
# Check all methods
|
361 |
+
methods = [
|
362 |
+
(nx_app.christofides, {}),
|
363 |
+
(nx_app.greedy_tsp, {}),
|
364 |
+
(
|
365 |
+
nx_app.simulated_annealing_tsp,
|
366 |
+
{"init_cycle": "greedy"},
|
367 |
+
),
|
368 |
+
(
|
369 |
+
nx_app.threshold_accepting_tsp,
|
370 |
+
{"init_cycle": "greedy"},
|
371 |
+
),
|
372 |
+
]
|
373 |
+
for method, kwargs in methods:
|
374 |
+
cycle = tsp(G, nodes=[3, 6], weight="weight", method=method, **kwargs)
|
375 |
+
assert cycle in expected_cycles
|
376 |
+
|
377 |
+
path = tsp(
|
378 |
+
G, nodes=[3, 6], weight="weight", method=method, cycle=False, **kwargs
|
379 |
+
)
|
380 |
+
assert path in expected_paths
|
381 |
+
|
382 |
+
tourpath = tsp(G, weight="weight", method=method, cycle=False, **kwargs)
|
383 |
+
assert tourpath in expected_tourpaths
|
384 |
+
|
385 |
+
|
386 |
+
def test_TSP_incomplete_graph_short_path():
|
387 |
+
G = nx.cycle_graph(9)
|
388 |
+
G.add_edges_from([(4, 9), (9, 10), (10, 11), (11, 0)])
|
389 |
+
G[4][5]["weight"] = 5
|
390 |
+
|
391 |
+
cycle = nx_app.traveling_salesman_problem(G)
|
392 |
+
print(cycle)
|
393 |
+
assert len(cycle) == 17 and len(set(cycle)) == 12
|
394 |
+
|
395 |
+
# make sure that cutting one edge out of complete graph formulation
|
396 |
+
# cuts out many edges out of the path of the TSP
|
397 |
+
path = nx_app.traveling_salesman_problem(G, cycle=False)
|
398 |
+
print(path)
|
399 |
+
assert len(path) == 13 and len(set(path)) == 12
|
400 |
+
|
401 |
+
|
402 |
+
def test_held_karp_ascent():
|
403 |
+
"""
|
404 |
+
Test the Held-Karp relaxation with the ascent method
|
405 |
+
"""
|
406 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
407 |
+
|
408 |
+
np = pytest.importorskip("numpy")
|
409 |
+
pytest.importorskip("scipy")
|
410 |
+
|
411 |
+
# Adjacency matrix from page 1153 of the 1970 Held and Karp paper
|
412 |
+
# which have been edited to be directional, but also symmetric
|
413 |
+
G_array = np.array(
|
414 |
+
[
|
415 |
+
[0, 97, 60, 73, 17, 52],
|
416 |
+
[97, 0, 41, 52, 90, 30],
|
417 |
+
[60, 41, 0, 21, 35, 41],
|
418 |
+
[73, 52, 21, 0, 95, 46],
|
419 |
+
[17, 90, 35, 95, 0, 81],
|
420 |
+
[52, 30, 41, 46, 81, 0],
|
421 |
+
]
|
422 |
+
)
|
423 |
+
|
424 |
+
solution_edges = [(1, 3), (2, 4), (3, 2), (4, 0), (5, 1), (0, 5)]
|
425 |
+
|
426 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
427 |
+
opt_hk, z_star = tsp.held_karp_ascent(G)
|
428 |
+
|
429 |
+
# Check that the optimal weights are the same
|
430 |
+
assert round(opt_hk, 2) == 207.00
|
431 |
+
# Check that the z_stars are the same
|
432 |
+
solution = nx.DiGraph()
|
433 |
+
solution.add_edges_from(solution_edges)
|
434 |
+
assert nx.utils.edges_equal(z_star.edges, solution.edges)
|
435 |
+
|
436 |
+
|
437 |
+
def test_ascent_fractional_solution():
|
438 |
+
"""
|
439 |
+
Test the ascent method using a modified version of Figure 2 on page 1140
|
440 |
+
in 'The Traveling Salesman Problem and Minimum Spanning Trees' by Held and
|
441 |
+
Karp
|
442 |
+
"""
|
443 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
444 |
+
|
445 |
+
np = pytest.importorskip("numpy")
|
446 |
+
pytest.importorskip("scipy")
|
447 |
+
|
448 |
+
# This version of Figure 2 has all of the edge weights multiplied by 100
|
449 |
+
# and is a complete directed graph with infinite edge weights for the
|
450 |
+
# edges not listed in the original graph
|
451 |
+
G_array = np.array(
|
452 |
+
[
|
453 |
+
[0, 100, 100, 100000, 100000, 1],
|
454 |
+
[100, 0, 100, 100000, 1, 100000],
|
455 |
+
[100, 100, 0, 1, 100000, 100000],
|
456 |
+
[100000, 100000, 1, 0, 100, 100],
|
457 |
+
[100000, 1, 100000, 100, 0, 100],
|
458 |
+
[1, 100000, 100000, 100, 100, 0],
|
459 |
+
]
|
460 |
+
)
|
461 |
+
|
462 |
+
solution_z_star = {
|
463 |
+
(0, 1): 5 / 12,
|
464 |
+
(0, 2): 5 / 12,
|
465 |
+
(0, 5): 5 / 6,
|
466 |
+
(1, 0): 5 / 12,
|
467 |
+
(1, 2): 1 / 3,
|
468 |
+
(1, 4): 5 / 6,
|
469 |
+
(2, 0): 5 / 12,
|
470 |
+
(2, 1): 1 / 3,
|
471 |
+
(2, 3): 5 / 6,
|
472 |
+
(3, 2): 5 / 6,
|
473 |
+
(3, 4): 1 / 3,
|
474 |
+
(3, 5): 1 / 2,
|
475 |
+
(4, 1): 5 / 6,
|
476 |
+
(4, 3): 1 / 3,
|
477 |
+
(4, 5): 1 / 2,
|
478 |
+
(5, 0): 5 / 6,
|
479 |
+
(5, 3): 1 / 2,
|
480 |
+
(5, 4): 1 / 2,
|
481 |
+
}
|
482 |
+
|
483 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
484 |
+
opt_hk, z_star = tsp.held_karp_ascent(G)
|
485 |
+
|
486 |
+
# Check that the optimal weights are the same
|
487 |
+
assert round(opt_hk, 2) == 303.00
|
488 |
+
# Check that the z_stars are the same
|
489 |
+
assert {key: round(z_star[key], 4) for key in z_star} == {
|
490 |
+
key: round(solution_z_star[key], 4) for key in solution_z_star
|
491 |
+
}
|
492 |
+
|
493 |
+
|
494 |
+
def test_ascent_method_asymmetric():
|
495 |
+
"""
|
496 |
+
Tests the ascent method using a truly asymmetric graph for which the
|
497 |
+
solution has been brute forced
|
498 |
+
"""
|
499 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
500 |
+
|
501 |
+
np = pytest.importorskip("numpy")
|
502 |
+
pytest.importorskip("scipy")
|
503 |
+
|
504 |
+
G_array = np.array(
|
505 |
+
[
|
506 |
+
[0, 26, 63, 59, 69, 31, 41],
|
507 |
+
[62, 0, 91, 53, 75, 87, 47],
|
508 |
+
[47, 82, 0, 90, 15, 9, 18],
|
509 |
+
[68, 19, 5, 0, 58, 34, 93],
|
510 |
+
[11, 58, 53, 55, 0, 61, 79],
|
511 |
+
[88, 75, 13, 76, 98, 0, 40],
|
512 |
+
[41, 61, 55, 88, 46, 45, 0],
|
513 |
+
]
|
514 |
+
)
|
515 |
+
|
516 |
+
solution_edges = [(0, 1), (1, 3), (3, 2), (2, 5), (5, 6), (4, 0), (6, 4)]
|
517 |
+
|
518 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
519 |
+
opt_hk, z_star = tsp.held_karp_ascent(G)
|
520 |
+
|
521 |
+
# Check that the optimal weights are the same
|
522 |
+
assert round(opt_hk, 2) == 190.00
|
523 |
+
# Check that the z_stars match.
|
524 |
+
solution = nx.DiGraph()
|
525 |
+
solution.add_edges_from(solution_edges)
|
526 |
+
assert nx.utils.edges_equal(z_star.edges, solution.edges)
|
527 |
+
|
528 |
+
|
529 |
+
def test_ascent_method_asymmetric_2():
|
530 |
+
"""
|
531 |
+
Tests the ascent method using a truly asymmetric graph for which the
|
532 |
+
solution has been brute forced
|
533 |
+
"""
|
534 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
535 |
+
|
536 |
+
np = pytest.importorskip("numpy")
|
537 |
+
pytest.importorskip("scipy")
|
538 |
+
|
539 |
+
G_array = np.array(
|
540 |
+
[
|
541 |
+
[0, 45, 39, 92, 29, 31],
|
542 |
+
[72, 0, 4, 12, 21, 60],
|
543 |
+
[81, 6, 0, 98, 70, 53],
|
544 |
+
[49, 71, 59, 0, 98, 94],
|
545 |
+
[74, 95, 24, 43, 0, 47],
|
546 |
+
[56, 43, 3, 65, 22, 0],
|
547 |
+
]
|
548 |
+
)
|
549 |
+
|
550 |
+
solution_edges = [(0, 5), (5, 4), (1, 3), (3, 0), (2, 1), (4, 2)]
|
551 |
+
|
552 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
553 |
+
opt_hk, z_star = tsp.held_karp_ascent(G)
|
554 |
+
|
555 |
+
# Check that the optimal weights are the same
|
556 |
+
assert round(opt_hk, 2) == 144.00
|
557 |
+
# Check that the z_stars match.
|
558 |
+
solution = nx.DiGraph()
|
559 |
+
solution.add_edges_from(solution_edges)
|
560 |
+
assert nx.utils.edges_equal(z_star.edges, solution.edges)
|
561 |
+
|
562 |
+
|
563 |
+
def test_held_karp_ascent_asymmetric_3():
|
564 |
+
"""
|
565 |
+
Tests the ascent method using a truly asymmetric graph with a fractional
|
566 |
+
solution for which the solution has been brute forced.
|
567 |
+
|
568 |
+
In this graph their are two different optimal, integral solutions (which
|
569 |
+
are also the overall atsp solutions) to the Held Karp relaxation. However,
|
570 |
+
this particular graph has two different tours of optimal value and the
|
571 |
+
possible solutions in the held_karp_ascent function are not stored in an
|
572 |
+
ordered data structure.
|
573 |
+
"""
|
574 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
575 |
+
|
576 |
+
np = pytest.importorskip("numpy")
|
577 |
+
pytest.importorskip("scipy")
|
578 |
+
|
579 |
+
G_array = np.array(
|
580 |
+
[
|
581 |
+
[0, 1, 5, 2, 7, 4],
|
582 |
+
[7, 0, 7, 7, 1, 4],
|
583 |
+
[4, 7, 0, 9, 2, 1],
|
584 |
+
[7, 2, 7, 0, 4, 4],
|
585 |
+
[5, 5, 4, 4, 0, 3],
|
586 |
+
[3, 9, 1, 3, 4, 0],
|
587 |
+
]
|
588 |
+
)
|
589 |
+
|
590 |
+
solution1_edges = [(0, 3), (1, 4), (2, 5), (3, 1), (4, 2), (5, 0)]
|
591 |
+
|
592 |
+
solution2_edges = [(0, 3), (3, 1), (1, 4), (4, 5), (2, 0), (5, 2)]
|
593 |
+
|
594 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
595 |
+
opt_hk, z_star = tsp.held_karp_ascent(G)
|
596 |
+
|
597 |
+
assert round(opt_hk, 2) == 13.00
|
598 |
+
# Check that the z_stars are the same
|
599 |
+
solution1 = nx.DiGraph()
|
600 |
+
solution1.add_edges_from(solution1_edges)
|
601 |
+
solution2 = nx.DiGraph()
|
602 |
+
solution2.add_edges_from(solution2_edges)
|
603 |
+
assert nx.utils.edges_equal(z_star.edges, solution1.edges) or nx.utils.edges_equal(
|
604 |
+
z_star.edges, solution2.edges
|
605 |
+
)
|
606 |
+
|
607 |
+
|
608 |
+
def test_held_karp_ascent_fractional_asymmetric():
|
609 |
+
"""
|
610 |
+
Tests the ascent method using a truly asymmetric graph with a fractional
|
611 |
+
solution for which the solution has been brute forced
|
612 |
+
"""
|
613 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
614 |
+
|
615 |
+
np = pytest.importorskip("numpy")
|
616 |
+
pytest.importorskip("scipy")
|
617 |
+
|
618 |
+
G_array = np.array(
|
619 |
+
[
|
620 |
+
[0, 100, 150, 100000, 100000, 1],
|
621 |
+
[150, 0, 100, 100000, 1, 100000],
|
622 |
+
[100, 150, 0, 1, 100000, 100000],
|
623 |
+
[100000, 100000, 1, 0, 150, 100],
|
624 |
+
[100000, 2, 100000, 100, 0, 150],
|
625 |
+
[2, 100000, 100000, 150, 100, 0],
|
626 |
+
]
|
627 |
+
)
|
628 |
+
|
629 |
+
solution_z_star = {
|
630 |
+
(0, 1): 5 / 12,
|
631 |
+
(0, 2): 5 / 12,
|
632 |
+
(0, 5): 5 / 6,
|
633 |
+
(1, 0): 5 / 12,
|
634 |
+
(1, 2): 5 / 12,
|
635 |
+
(1, 4): 5 / 6,
|
636 |
+
(2, 0): 5 / 12,
|
637 |
+
(2, 1): 5 / 12,
|
638 |
+
(2, 3): 5 / 6,
|
639 |
+
(3, 2): 5 / 6,
|
640 |
+
(3, 4): 5 / 12,
|
641 |
+
(3, 5): 5 / 12,
|
642 |
+
(4, 1): 5 / 6,
|
643 |
+
(4, 3): 5 / 12,
|
644 |
+
(4, 5): 5 / 12,
|
645 |
+
(5, 0): 5 / 6,
|
646 |
+
(5, 3): 5 / 12,
|
647 |
+
(5, 4): 5 / 12,
|
648 |
+
}
|
649 |
+
|
650 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
651 |
+
opt_hk, z_star = tsp.held_karp_ascent(G)
|
652 |
+
|
653 |
+
# Check that the optimal weights are the same
|
654 |
+
assert round(opt_hk, 2) == 304.00
|
655 |
+
# Check that the z_stars are the same
|
656 |
+
assert {key: round(z_star[key], 4) for key in z_star} == {
|
657 |
+
key: round(solution_z_star[key], 4) for key in solution_z_star
|
658 |
+
}
|
659 |
+
|
660 |
+
|
661 |
+
def test_spanning_tree_distribution():
|
662 |
+
"""
|
663 |
+
Test that we can create an exponential distribution of spanning trees such
|
664 |
+
that the probability of each tree is proportional to the product of edge
|
665 |
+
weights.
|
666 |
+
|
667 |
+
Results of this test have been confirmed with hypothesis testing from the
|
668 |
+
created distribution.
|
669 |
+
|
670 |
+
This test uses the symmetric, fractional Held Karp solution.
|
671 |
+
"""
|
672 |
+
import networkx.algorithms.approximation.traveling_salesman as tsp
|
673 |
+
|
674 |
+
pytest.importorskip("numpy")
|
675 |
+
pytest.importorskip("scipy")
|
676 |
+
|
677 |
+
z_star = {
|
678 |
+
(0, 1): 5 / 12,
|
679 |
+
(0, 2): 5 / 12,
|
680 |
+
(0, 5): 5 / 6,
|
681 |
+
(1, 0): 5 / 12,
|
682 |
+
(1, 2): 1 / 3,
|
683 |
+
(1, 4): 5 / 6,
|
684 |
+
(2, 0): 5 / 12,
|
685 |
+
(2, 1): 1 / 3,
|
686 |
+
(2, 3): 5 / 6,
|
687 |
+
(3, 2): 5 / 6,
|
688 |
+
(3, 4): 1 / 3,
|
689 |
+
(3, 5): 1 / 2,
|
690 |
+
(4, 1): 5 / 6,
|
691 |
+
(4, 3): 1 / 3,
|
692 |
+
(4, 5): 1 / 2,
|
693 |
+
(5, 0): 5 / 6,
|
694 |
+
(5, 3): 1 / 2,
|
695 |
+
(5, 4): 1 / 2,
|
696 |
+
}
|
697 |
+
|
698 |
+
solution_gamma = {
|
699 |
+
(0, 1): -0.6383,
|
700 |
+
(0, 2): -0.6827,
|
701 |
+
(0, 5): 0,
|
702 |
+
(1, 2): -1.0781,
|
703 |
+
(1, 4): 0,
|
704 |
+
(2, 3): 0,
|
705 |
+
(5, 3): -0.2820,
|
706 |
+
(5, 4): -0.3327,
|
707 |
+
(4, 3): -0.9927,
|
708 |
+
}
|
709 |
+
|
710 |
+
# The undirected support of z_star
|
711 |
+
G = nx.MultiGraph()
|
712 |
+
for u, v in z_star:
|
713 |
+
if (u, v) in G.edges or (v, u) in G.edges:
|
714 |
+
continue
|
715 |
+
G.add_edge(u, v)
|
716 |
+
|
717 |
+
gamma = tsp.spanning_tree_distribution(G, z_star)
|
718 |
+
|
719 |
+
assert {key: round(gamma[key], 4) for key in gamma} == solution_gamma
|
720 |
+
|
721 |
+
|
722 |
+
def test_asadpour_tsp():
|
723 |
+
"""
|
724 |
+
Test the complete asadpour tsp algorithm with the fractional, symmetric
|
725 |
+
Held Karp solution. This test also uses an incomplete graph as input.
|
726 |
+
"""
|
727 |
+
# This version of Figure 2 has all of the edge weights multiplied by 100
|
728 |
+
# and the 0 weight edges have a weight of 1.
|
729 |
+
pytest.importorskip("numpy")
|
730 |
+
pytest.importorskip("scipy")
|
731 |
+
|
732 |
+
edge_list = [
|
733 |
+
(0, 1, 100),
|
734 |
+
(0, 2, 100),
|
735 |
+
(0, 5, 1),
|
736 |
+
(1, 2, 100),
|
737 |
+
(1, 4, 1),
|
738 |
+
(2, 3, 1),
|
739 |
+
(3, 4, 100),
|
740 |
+
(3, 5, 100),
|
741 |
+
(4, 5, 100),
|
742 |
+
(1, 0, 100),
|
743 |
+
(2, 0, 100),
|
744 |
+
(5, 0, 1),
|
745 |
+
(2, 1, 100),
|
746 |
+
(4, 1, 1),
|
747 |
+
(3, 2, 1),
|
748 |
+
(4, 3, 100),
|
749 |
+
(5, 3, 100),
|
750 |
+
(5, 4, 100),
|
751 |
+
]
|
752 |
+
|
753 |
+
G = nx.DiGraph()
|
754 |
+
G.add_weighted_edges_from(edge_list)
|
755 |
+
|
756 |
+
tour = nx_app.traveling_salesman_problem(
|
757 |
+
G, weight="weight", method=nx_app.asadpour_atsp, seed=19
|
758 |
+
)
|
759 |
+
|
760 |
+
# Check that the returned list is a valid tour. Because this is an
|
761 |
+
# incomplete graph, the conditions are not as strict. We need the tour to
|
762 |
+
#
|
763 |
+
# Start and end at the same node
|
764 |
+
# Pass through every vertex at least once
|
765 |
+
# Have a total cost at most ln(6) / ln(ln(6)) = 3.0723 times the optimal
|
766 |
+
#
|
767 |
+
# For the second condition it is possible to have the tour pass through the
|
768 |
+
# same vertex more then. Imagine that the tour on the complete version takes
|
769 |
+
# an edge not in the original graph. In the output this is substituted with
|
770 |
+
# the shortest path between those vertices, allowing vertices to appear more
|
771 |
+
# than once.
|
772 |
+
#
|
773 |
+
# Even though we are using a fixed seed, multiple tours have been known to
|
774 |
+
# be returned. The first two are from the original delevopment of this test,
|
775 |
+
# and the third one from issue #5913 on GitHub. If other tours are returned,
|
776 |
+
# add it on the list of expected tours.
|
777 |
+
expected_tours = [
|
778 |
+
[1, 4, 5, 0, 2, 3, 2, 1],
|
779 |
+
[3, 2, 0, 1, 4, 5, 3],
|
780 |
+
[3, 2, 1, 0, 5, 4, 3],
|
781 |
+
]
|
782 |
+
|
783 |
+
assert tour in expected_tours
|
784 |
+
|
785 |
+
|
786 |
+
def test_asadpour_real_world():
|
787 |
+
"""
|
788 |
+
This test uses airline prices between the six largest cities in the US.
|
789 |
+
|
790 |
+
* New York City -> JFK
|
791 |
+
* Los Angeles -> LAX
|
792 |
+
* Chicago -> ORD
|
793 |
+
* Houston -> IAH
|
794 |
+
* Phoenix -> PHX
|
795 |
+
* Philadelphia -> PHL
|
796 |
+
|
797 |
+
Flight prices from August 2021 using Delta or American airlines to get
|
798 |
+
nonstop flight. The brute force solution found the optimal tour to cost $872
|
799 |
+
|
800 |
+
This test also uses the `source` keyword argument to ensure that the tour
|
801 |
+
always starts at city 0.
|
802 |
+
"""
|
803 |
+
np = pytest.importorskip("numpy")
|
804 |
+
pytest.importorskip("scipy")
|
805 |
+
|
806 |
+
G_array = np.array(
|
807 |
+
[
|
808 |
+
# JFK LAX ORD IAH PHX PHL
|
809 |
+
[0, 243, 199, 208, 169, 183], # JFK
|
810 |
+
[277, 0, 217, 123, 127, 252], # LAX
|
811 |
+
[297, 197, 0, 197, 123, 177], # ORD
|
812 |
+
[303, 169, 197, 0, 117, 117], # IAH
|
813 |
+
[257, 127, 160, 117, 0, 319], # PHX
|
814 |
+
[183, 332, 217, 117, 319, 0], # PHL
|
815 |
+
]
|
816 |
+
)
|
817 |
+
|
818 |
+
node_map = {0: "JFK", 1: "LAX", 2: "ORD", 3: "IAH", 4: "PHX", 5: "PHL"}
|
819 |
+
|
820 |
+
expected_tours = [
|
821 |
+
["JFK", "LAX", "PHX", "ORD", "IAH", "PHL", "JFK"],
|
822 |
+
["JFK", "ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
|
823 |
+
]
|
824 |
+
|
825 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
826 |
+
nx.relabel_nodes(G, node_map, copy=False)
|
827 |
+
|
828 |
+
tour = nx_app.traveling_salesman_problem(
|
829 |
+
G, weight="weight", method=nx_app.asadpour_atsp, seed=37, source="JFK"
|
830 |
+
)
|
831 |
+
|
832 |
+
assert tour in expected_tours
|
833 |
+
|
834 |
+
|
835 |
+
def test_asadpour_real_world_path():
|
836 |
+
"""
|
837 |
+
This test uses airline prices between the six largest cities in the US. This
|
838 |
+
time using a path, not a cycle.
|
839 |
+
|
840 |
+
* New York City -> JFK
|
841 |
+
* Los Angeles -> LAX
|
842 |
+
* Chicago -> ORD
|
843 |
+
* Houston -> IAH
|
844 |
+
* Phoenix -> PHX
|
845 |
+
* Philadelphia -> PHL
|
846 |
+
|
847 |
+
Flight prices from August 2021 using Delta or American airlines to get
|
848 |
+
nonstop flight. The brute force solution found the optimal tour to cost $872
|
849 |
+
"""
|
850 |
+
np = pytest.importorskip("numpy")
|
851 |
+
pytest.importorskip("scipy")
|
852 |
+
|
853 |
+
G_array = np.array(
|
854 |
+
[
|
855 |
+
# JFK LAX ORD IAH PHX PHL
|
856 |
+
[0, 243, 199, 208, 169, 183], # JFK
|
857 |
+
[277, 0, 217, 123, 127, 252], # LAX
|
858 |
+
[297, 197, 0, 197, 123, 177], # ORD
|
859 |
+
[303, 169, 197, 0, 117, 117], # IAH
|
860 |
+
[257, 127, 160, 117, 0, 319], # PHX
|
861 |
+
[183, 332, 217, 117, 319, 0], # PHL
|
862 |
+
]
|
863 |
+
)
|
864 |
+
|
865 |
+
node_map = {0: "JFK", 1: "LAX", 2: "ORD", 3: "IAH", 4: "PHX", 5: "PHL"}
|
866 |
+
|
867 |
+
expected_paths = [
|
868 |
+
["ORD", "PHX", "LAX", "IAH", "PHL", "JFK"],
|
869 |
+
["JFK", "PHL", "IAH", "ORD", "PHX", "LAX"],
|
870 |
+
]
|
871 |
+
|
872 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
873 |
+
nx.relabel_nodes(G, node_map, copy=False)
|
874 |
+
|
875 |
+
path = nx_app.traveling_salesman_problem(
|
876 |
+
G, weight="weight", cycle=False, method=nx_app.asadpour_atsp, seed=56
|
877 |
+
)
|
878 |
+
|
879 |
+
assert path in expected_paths
|
880 |
+
|
881 |
+
|
882 |
+
def test_asadpour_disconnected_graph():
|
883 |
+
"""
|
884 |
+
Test that the proper exception is raised when asadpour_atsp is given an
|
885 |
+
disconnected graph.
|
886 |
+
"""
|
887 |
+
|
888 |
+
G = nx.complete_graph(4, create_using=nx.DiGraph)
|
889 |
+
# have to set edge weights so that if the exception is not raised, the
|
890 |
+
# function will complete and we will fail the test
|
891 |
+
nx.set_edge_attributes(G, 1, "weight")
|
892 |
+
G.add_node(5)
|
893 |
+
|
894 |
+
pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
|
895 |
+
|
896 |
+
|
897 |
+
def test_asadpour_incomplete_graph():
|
898 |
+
"""
|
899 |
+
Test that the proper exception is raised when asadpour_atsp is given an
|
900 |
+
incomplete graph
|
901 |
+
"""
|
902 |
+
|
903 |
+
G = nx.complete_graph(4, create_using=nx.DiGraph)
|
904 |
+
# have to set edge weights so that if the exception is not raised, the
|
905 |
+
# function will complete and we will fail the test
|
906 |
+
nx.set_edge_attributes(G, 1, "weight")
|
907 |
+
G.remove_edge(0, 1)
|
908 |
+
|
909 |
+
pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
|
910 |
+
|
911 |
+
|
912 |
+
def test_asadpour_empty_graph():
|
913 |
+
"""
|
914 |
+
Test the asadpour_atsp function with an empty graph
|
915 |
+
"""
|
916 |
+
G = nx.DiGraph()
|
917 |
+
|
918 |
+
pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G)
|
919 |
+
|
920 |
+
|
921 |
+
@pytest.mark.slow
|
922 |
+
def test_asadpour_integral_held_karp():
|
923 |
+
"""
|
924 |
+
This test uses an integral held karp solution and the held karp function
|
925 |
+
will return a graph rather than a dict, bypassing most of the asadpour
|
926 |
+
algorithm.
|
927 |
+
|
928 |
+
At first glance, this test probably doesn't look like it ensures that we
|
929 |
+
skip the rest of the asadpour algorithm, but it does. We are not fixing a
|
930 |
+
see for the random number generator, so if we sample any spanning trees
|
931 |
+
the approximation would be different basically every time this test is
|
932 |
+
executed but it is not since held karp is deterministic and we do not
|
933 |
+
reach the portion of the code with the dependence on random numbers.
|
934 |
+
"""
|
935 |
+
np = pytest.importorskip("numpy")
|
936 |
+
|
937 |
+
G_array = np.array(
|
938 |
+
[
|
939 |
+
[0, 26, 63, 59, 69, 31, 41],
|
940 |
+
[62, 0, 91, 53, 75, 87, 47],
|
941 |
+
[47, 82, 0, 90, 15, 9, 18],
|
942 |
+
[68, 19, 5, 0, 58, 34, 93],
|
943 |
+
[11, 58, 53, 55, 0, 61, 79],
|
944 |
+
[88, 75, 13, 76, 98, 0, 40],
|
945 |
+
[41, 61, 55, 88, 46, 45, 0],
|
946 |
+
]
|
947 |
+
)
|
948 |
+
|
949 |
+
G = nx.from_numpy_array(G_array, create_using=nx.DiGraph)
|
950 |
+
|
951 |
+
for _ in range(2):
|
952 |
+
tour = nx_app.traveling_salesman_problem(G, method=nx_app.asadpour_atsp)
|
953 |
+
|
954 |
+
assert [1, 3, 2, 5, 2, 6, 4, 0, 1] == tour
|
955 |
+
|
956 |
+
|
957 |
+
def test_directed_tsp_impossible():
|
958 |
+
"""
|
959 |
+
Test the asadpour algorithm with a graph without a hamiltonian circuit
|
960 |
+
"""
|
961 |
+
pytest.importorskip("numpy")
|
962 |
+
|
963 |
+
# In this graph, once we leave node 0 we cannot return
|
964 |
+
edges = [
|
965 |
+
(0, 1, 10),
|
966 |
+
(0, 2, 11),
|
967 |
+
(0, 3, 12),
|
968 |
+
(1, 2, 4),
|
969 |
+
(1, 3, 6),
|
970 |
+
(2, 1, 3),
|
971 |
+
(2, 3, 2),
|
972 |
+
(3, 1, 5),
|
973 |
+
(3, 2, 1),
|
974 |
+
]
|
975 |
+
|
976 |
+
G = nx.DiGraph()
|
977 |
+
G.add_weighted_edges_from(edges)
|
978 |
+
|
979 |
+
pytest.raises(nx.NetworkXError, nx_app.traveling_salesman_problem, G)
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_treewidth.py
ADDED
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import itertools
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms.approximation import (
|
5 |
+
treewidth_min_degree,
|
6 |
+
treewidth_min_fill_in,
|
7 |
+
)
|
8 |
+
from networkx.algorithms.approximation.treewidth import (
|
9 |
+
MinDegreeHeuristic,
|
10 |
+
min_fill_in_heuristic,
|
11 |
+
)
|
12 |
+
|
13 |
+
|
14 |
+
def is_tree_decomp(graph, decomp):
|
15 |
+
"""Check if the given tree decomposition is valid."""
|
16 |
+
for x in graph.nodes():
|
17 |
+
appear_once = False
|
18 |
+
for bag in decomp.nodes():
|
19 |
+
if x in bag:
|
20 |
+
appear_once = True
|
21 |
+
break
|
22 |
+
assert appear_once
|
23 |
+
|
24 |
+
# Check if each connected pair of nodes are at least once together in a bag
|
25 |
+
for x, y in graph.edges():
|
26 |
+
appear_together = False
|
27 |
+
for bag in decomp.nodes():
|
28 |
+
if x in bag and y in bag:
|
29 |
+
appear_together = True
|
30 |
+
break
|
31 |
+
assert appear_together
|
32 |
+
|
33 |
+
# Check if the nodes associated with vertex v form a connected subset of T
|
34 |
+
for v in graph.nodes():
|
35 |
+
subset = []
|
36 |
+
for bag in decomp.nodes():
|
37 |
+
if v in bag:
|
38 |
+
subset.append(bag)
|
39 |
+
sub_graph = decomp.subgraph(subset)
|
40 |
+
assert nx.is_connected(sub_graph)
|
41 |
+
|
42 |
+
|
43 |
+
class TestTreewidthMinDegree:
|
44 |
+
"""Unit tests for the min_degree function"""
|
45 |
+
|
46 |
+
@classmethod
|
47 |
+
def setup_class(cls):
|
48 |
+
"""Setup for different kinds of trees"""
|
49 |
+
cls.complete = nx.Graph()
|
50 |
+
cls.complete.add_edge(1, 2)
|
51 |
+
cls.complete.add_edge(2, 3)
|
52 |
+
cls.complete.add_edge(1, 3)
|
53 |
+
|
54 |
+
cls.small_tree = nx.Graph()
|
55 |
+
cls.small_tree.add_edge(1, 3)
|
56 |
+
cls.small_tree.add_edge(4, 3)
|
57 |
+
cls.small_tree.add_edge(2, 3)
|
58 |
+
cls.small_tree.add_edge(3, 5)
|
59 |
+
cls.small_tree.add_edge(5, 6)
|
60 |
+
cls.small_tree.add_edge(5, 7)
|
61 |
+
cls.small_tree.add_edge(6, 7)
|
62 |
+
|
63 |
+
cls.deterministic_graph = nx.Graph()
|
64 |
+
cls.deterministic_graph.add_edge(0, 1) # deg(0) = 1
|
65 |
+
|
66 |
+
cls.deterministic_graph.add_edge(1, 2) # deg(1) = 2
|
67 |
+
|
68 |
+
cls.deterministic_graph.add_edge(2, 3)
|
69 |
+
cls.deterministic_graph.add_edge(2, 4) # deg(2) = 3
|
70 |
+
|
71 |
+
cls.deterministic_graph.add_edge(3, 4)
|
72 |
+
cls.deterministic_graph.add_edge(3, 5)
|
73 |
+
cls.deterministic_graph.add_edge(3, 6) # deg(3) = 4
|
74 |
+
|
75 |
+
cls.deterministic_graph.add_edge(4, 5)
|
76 |
+
cls.deterministic_graph.add_edge(4, 6)
|
77 |
+
cls.deterministic_graph.add_edge(4, 7) # deg(4) = 5
|
78 |
+
|
79 |
+
cls.deterministic_graph.add_edge(5, 6)
|
80 |
+
cls.deterministic_graph.add_edge(5, 7)
|
81 |
+
cls.deterministic_graph.add_edge(5, 8)
|
82 |
+
cls.deterministic_graph.add_edge(5, 9) # deg(5) = 6
|
83 |
+
|
84 |
+
cls.deterministic_graph.add_edge(6, 7)
|
85 |
+
cls.deterministic_graph.add_edge(6, 8)
|
86 |
+
cls.deterministic_graph.add_edge(6, 9) # deg(6) = 6
|
87 |
+
|
88 |
+
cls.deterministic_graph.add_edge(7, 8)
|
89 |
+
cls.deterministic_graph.add_edge(7, 9) # deg(7) = 5
|
90 |
+
|
91 |
+
cls.deterministic_graph.add_edge(8, 9) # deg(8) = 4
|
92 |
+
|
93 |
+
def test_petersen_graph(self):
|
94 |
+
"""Test Petersen graph tree decomposition result"""
|
95 |
+
G = nx.petersen_graph()
|
96 |
+
_, decomp = treewidth_min_degree(G)
|
97 |
+
is_tree_decomp(G, decomp)
|
98 |
+
|
99 |
+
def test_small_tree_treewidth(self):
|
100 |
+
"""Test small tree
|
101 |
+
|
102 |
+
Test if the computed treewidth of the known self.small_tree is 2.
|
103 |
+
As we know which value we can expect from our heuristic, values other
|
104 |
+
than two are regressions
|
105 |
+
"""
|
106 |
+
G = self.small_tree
|
107 |
+
# the order of removal should be [1,2,4]3[5,6,7]
|
108 |
+
# (with [] denoting any order of the containing nodes)
|
109 |
+
# resulting in treewidth 2 for the heuristic
|
110 |
+
treewidth, _ = treewidth_min_fill_in(G)
|
111 |
+
assert treewidth == 2
|
112 |
+
|
113 |
+
def test_heuristic_abort(self):
|
114 |
+
"""Test heuristic abort condition for fully connected graph"""
|
115 |
+
graph = {}
|
116 |
+
for u in self.complete:
|
117 |
+
graph[u] = set()
|
118 |
+
for v in self.complete[u]:
|
119 |
+
if u != v: # ignore self-loop
|
120 |
+
graph[u].add(v)
|
121 |
+
|
122 |
+
deg_heuristic = MinDegreeHeuristic(graph)
|
123 |
+
node = deg_heuristic.best_node(graph)
|
124 |
+
if node is None:
|
125 |
+
pass
|
126 |
+
else:
|
127 |
+
assert False
|
128 |
+
|
129 |
+
def test_empty_graph(self):
|
130 |
+
"""Test empty graph"""
|
131 |
+
G = nx.Graph()
|
132 |
+
_, _ = treewidth_min_degree(G)
|
133 |
+
|
134 |
+
def test_two_component_graph(self):
|
135 |
+
G = nx.Graph()
|
136 |
+
G.add_node(1)
|
137 |
+
G.add_node(2)
|
138 |
+
treewidth, _ = treewidth_min_degree(G)
|
139 |
+
assert treewidth == 0
|
140 |
+
|
141 |
+
def test_not_sortable_nodes(self):
|
142 |
+
G = nx.Graph([(0, "a")])
|
143 |
+
treewidth_min_degree(G)
|
144 |
+
|
145 |
+
def test_heuristic_first_steps(self):
|
146 |
+
"""Test first steps of min_degree heuristic"""
|
147 |
+
graph = {
|
148 |
+
n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
|
149 |
+
}
|
150 |
+
deg_heuristic = MinDegreeHeuristic(graph)
|
151 |
+
elim_node = deg_heuristic.best_node(graph)
|
152 |
+
print(f"Graph {graph}:")
|
153 |
+
steps = []
|
154 |
+
|
155 |
+
while elim_node is not None:
|
156 |
+
print(f"Removing {elim_node}:")
|
157 |
+
steps.append(elim_node)
|
158 |
+
nbrs = graph[elim_node]
|
159 |
+
|
160 |
+
for u, v in itertools.permutations(nbrs, 2):
|
161 |
+
if v not in graph[u]:
|
162 |
+
graph[u].add(v)
|
163 |
+
|
164 |
+
for u in graph:
|
165 |
+
if elim_node in graph[u]:
|
166 |
+
graph[u].remove(elim_node)
|
167 |
+
|
168 |
+
del graph[elim_node]
|
169 |
+
print(f"Graph {graph}:")
|
170 |
+
elim_node = deg_heuristic.best_node(graph)
|
171 |
+
|
172 |
+
# check only the first 5 elements for equality
|
173 |
+
assert steps[:5] == [0, 1, 2, 3, 4]
|
174 |
+
|
175 |
+
|
176 |
+
class TestTreewidthMinFillIn:
|
177 |
+
"""Unit tests for the treewidth_min_fill_in function."""
|
178 |
+
|
179 |
+
@classmethod
|
180 |
+
def setup_class(cls):
|
181 |
+
"""Setup for different kinds of trees"""
|
182 |
+
cls.complete = nx.Graph()
|
183 |
+
cls.complete.add_edge(1, 2)
|
184 |
+
cls.complete.add_edge(2, 3)
|
185 |
+
cls.complete.add_edge(1, 3)
|
186 |
+
|
187 |
+
cls.small_tree = nx.Graph()
|
188 |
+
cls.small_tree.add_edge(1, 2)
|
189 |
+
cls.small_tree.add_edge(2, 3)
|
190 |
+
cls.small_tree.add_edge(3, 4)
|
191 |
+
cls.small_tree.add_edge(1, 4)
|
192 |
+
cls.small_tree.add_edge(2, 4)
|
193 |
+
cls.small_tree.add_edge(4, 5)
|
194 |
+
cls.small_tree.add_edge(5, 6)
|
195 |
+
cls.small_tree.add_edge(5, 7)
|
196 |
+
cls.small_tree.add_edge(6, 7)
|
197 |
+
|
198 |
+
cls.deterministic_graph = nx.Graph()
|
199 |
+
cls.deterministic_graph.add_edge(1, 2)
|
200 |
+
cls.deterministic_graph.add_edge(1, 3)
|
201 |
+
cls.deterministic_graph.add_edge(3, 4)
|
202 |
+
cls.deterministic_graph.add_edge(2, 4)
|
203 |
+
cls.deterministic_graph.add_edge(3, 5)
|
204 |
+
cls.deterministic_graph.add_edge(4, 5)
|
205 |
+
cls.deterministic_graph.add_edge(3, 6)
|
206 |
+
cls.deterministic_graph.add_edge(5, 6)
|
207 |
+
|
208 |
+
def test_petersen_graph(self):
|
209 |
+
"""Test Petersen graph tree decomposition result"""
|
210 |
+
G = nx.petersen_graph()
|
211 |
+
_, decomp = treewidth_min_fill_in(G)
|
212 |
+
is_tree_decomp(G, decomp)
|
213 |
+
|
214 |
+
def test_small_tree_treewidth(self):
|
215 |
+
"""Test if the computed treewidth of the known self.small_tree is 2"""
|
216 |
+
G = self.small_tree
|
217 |
+
# the order of removal should be [1,2,4]3[5,6,7]
|
218 |
+
# (with [] denoting any order of the containing nodes)
|
219 |
+
# resulting in treewidth 2 for the heuristic
|
220 |
+
treewidth, _ = treewidth_min_fill_in(G)
|
221 |
+
assert treewidth == 2
|
222 |
+
|
223 |
+
def test_heuristic_abort(self):
|
224 |
+
"""Test if min_fill_in returns None for fully connected graph"""
|
225 |
+
graph = {}
|
226 |
+
for u in self.complete:
|
227 |
+
graph[u] = set()
|
228 |
+
for v in self.complete[u]:
|
229 |
+
if u != v: # ignore self-loop
|
230 |
+
graph[u].add(v)
|
231 |
+
next_node = min_fill_in_heuristic(graph)
|
232 |
+
if next_node is None:
|
233 |
+
pass
|
234 |
+
else:
|
235 |
+
assert False
|
236 |
+
|
237 |
+
def test_empty_graph(self):
|
238 |
+
"""Test empty graph"""
|
239 |
+
G = nx.Graph()
|
240 |
+
_, _ = treewidth_min_fill_in(G)
|
241 |
+
|
242 |
+
def test_two_component_graph(self):
|
243 |
+
G = nx.Graph()
|
244 |
+
G.add_node(1)
|
245 |
+
G.add_node(2)
|
246 |
+
treewidth, _ = treewidth_min_fill_in(G)
|
247 |
+
assert treewidth == 0
|
248 |
+
|
249 |
+
def test_not_sortable_nodes(self):
|
250 |
+
G = nx.Graph([(0, "a")])
|
251 |
+
treewidth_min_fill_in(G)
|
252 |
+
|
253 |
+
def test_heuristic_first_steps(self):
|
254 |
+
"""Test first steps of min_fill_in heuristic"""
|
255 |
+
graph = {
|
256 |
+
n: set(self.deterministic_graph[n]) - {n} for n in self.deterministic_graph
|
257 |
+
}
|
258 |
+
print(f"Graph {graph}:")
|
259 |
+
elim_node = min_fill_in_heuristic(graph)
|
260 |
+
steps = []
|
261 |
+
|
262 |
+
while elim_node is not None:
|
263 |
+
print(f"Removing {elim_node}:")
|
264 |
+
steps.append(elim_node)
|
265 |
+
nbrs = graph[elim_node]
|
266 |
+
|
267 |
+
for u, v in itertools.permutations(nbrs, 2):
|
268 |
+
if v not in graph[u]:
|
269 |
+
graph[u].add(v)
|
270 |
+
|
271 |
+
for u in graph:
|
272 |
+
if elim_node in graph[u]:
|
273 |
+
graph[u].remove(elim_node)
|
274 |
+
|
275 |
+
del graph[elim_node]
|
276 |
+
print(f"Graph {graph}:")
|
277 |
+
elim_node = min_fill_in_heuristic(graph)
|
278 |
+
|
279 |
+
# check only the first 2 elements for equality
|
280 |
+
assert steps[:2] == [6, 5]
|
venv/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
from networkx.algorithms.approximation import min_weighted_vertex_cover
|
3 |
+
|
4 |
+
|
5 |
+
def is_cover(G, node_cover):
|
6 |
+
return all({u, v} & node_cover for u, v in G.edges())
|
7 |
+
|
8 |
+
|
9 |
+
class TestMWVC:
|
10 |
+
"""Unit tests for the approximate minimum weighted vertex cover
|
11 |
+
function,
|
12 |
+
:func:`~networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover`.
|
13 |
+
|
14 |
+
"""
|
15 |
+
|
16 |
+
def test_unweighted_directed(self):
|
17 |
+
# Create a star graph in which half the nodes are directed in
|
18 |
+
# and half are directed out.
|
19 |
+
G = nx.DiGraph()
|
20 |
+
G.add_edges_from((0, v) for v in range(1, 26))
|
21 |
+
G.add_edges_from((v, 0) for v in range(26, 51))
|
22 |
+
cover = min_weighted_vertex_cover(G)
|
23 |
+
assert 1 == len(cover)
|
24 |
+
assert is_cover(G, cover)
|
25 |
+
|
26 |
+
def test_unweighted_undirected(self):
|
27 |
+
# create a simple star graph
|
28 |
+
size = 50
|
29 |
+
sg = nx.star_graph(size)
|
30 |
+
cover = min_weighted_vertex_cover(sg)
|
31 |
+
assert 1 == len(cover)
|
32 |
+
assert is_cover(sg, cover)
|
33 |
+
|
34 |
+
def test_weighted(self):
|
35 |
+
wg = nx.Graph()
|
36 |
+
wg.add_node(0, weight=10)
|
37 |
+
wg.add_node(1, weight=1)
|
38 |
+
wg.add_node(2, weight=1)
|
39 |
+
wg.add_node(3, weight=1)
|
40 |
+
wg.add_node(4, weight=1)
|
41 |
+
|
42 |
+
wg.add_edge(0, 1)
|
43 |
+
wg.add_edge(0, 2)
|
44 |
+
wg.add_edge(0, 3)
|
45 |
+
wg.add_edge(0, 4)
|
46 |
+
|
47 |
+
wg.add_edge(1, 2)
|
48 |
+
wg.add_edge(2, 3)
|
49 |
+
wg.add_edge(3, 4)
|
50 |
+
wg.add_edge(4, 1)
|
51 |
+
|
52 |
+
cover = min_weighted_vertex_cover(wg, weight="weight")
|
53 |
+
csum = sum(wg.nodes[node]["weight"] for node in cover)
|
54 |
+
assert 4 == csum
|
55 |
+
assert is_cover(wg, cover)
|
56 |
+
|
57 |
+
def test_unweighted_self_loop(self):
|
58 |
+
slg = nx.Graph()
|
59 |
+
slg.add_node(0)
|
60 |
+
slg.add_node(1)
|
61 |
+
slg.add_node(2)
|
62 |
+
|
63 |
+
slg.add_edge(0, 1)
|
64 |
+
slg.add_edge(2, 2)
|
65 |
+
|
66 |
+
cover = min_weighted_vertex_cover(slg)
|
67 |
+
assert 2 == len(cover)
|
68 |
+
assert is_cover(slg, cover)
|
venv/lib/python3.10/site-packages/networkx/algorithms/flow/__init__.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .maxflow import *
|
2 |
+
from .mincost import *
|
3 |
+
from .boykovkolmogorov import *
|
4 |
+
from .dinitz_alg import *
|
5 |
+
from .edmondskarp import *
|
6 |
+
from .gomory_hu import *
|
7 |
+
from .preflowpush import *
|
8 |
+
from .shortestaugmentingpath import *
|
9 |
+
from .capacityscaling import *
|
10 |
+
from .networksimplex import *
|
11 |
+
from .utils import build_flow_dict, build_residual_network
|
venv/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (517 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/edmondskarp.cpython-310.pyc
ADDED
Binary file (7.18 kB). View file
|
|