Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py +4 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/greedy_coloring.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/equitable_coloring.py +505 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py +564 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py +865 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/__pycache__/test_utils.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/test_kernighan_lin.py +91 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/test_quality.py +138 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/test_utils.py +28 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py +23 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py +154 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py +144 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py +81 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py +129 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_cluster.py +549 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py +80 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_covering.py +85 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py +172 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_cycles.py +974 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_distance_regular.py +85 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py +46 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_efficiency.py +58 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_euler.py +314 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_graph_hashing.py +686 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_graphical.py +163 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_isolate.py +26 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_link_prediction.py +586 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_matching.py +605 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_max_weight_clique.py +181 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_node_classification.py +140 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_non_randomness.py +37 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_polynomials.py +57 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_reciprocity.py +37 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_richclub.py +149 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_similarity.py +946 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_simple_paths.py +792 -0
- llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_smallworld.py +78 -0
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from networkx.algorithms.coloring.greedy_coloring import *
|
2 |
+
from networkx.algorithms.coloring.equitable_coloring import equitable_color
|
3 |
+
|
4 |
+
__all__ = ["greedy_color", "equitable_color"]
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (387 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc
ADDED
Binary file (10.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/greedy_coloring.cpython-310.pyc
ADDED
Binary file (16.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/equitable_coloring.py
ADDED
@@ -0,0 +1,505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Equitable coloring of graphs with bounded degree.
|
3 |
+
"""
|
4 |
+
|
5 |
+
from collections import defaultdict
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
|
9 |
+
__all__ = ["equitable_color"]
|
10 |
+
|
11 |
+
|
12 |
+
@nx._dispatchable
|
13 |
+
def is_coloring(G, coloring):
|
14 |
+
"""Determine if the coloring is a valid coloring for the graph G."""
|
15 |
+
# Verify that the coloring is valid.
|
16 |
+
return all(coloring[s] != coloring[d] for s, d in G.edges)
|
17 |
+
|
18 |
+
|
19 |
+
@nx._dispatchable
|
20 |
+
def is_equitable(G, coloring, num_colors=None):
|
21 |
+
"""Determines if the coloring is valid and equitable for the graph G."""
|
22 |
+
|
23 |
+
if not is_coloring(G, coloring):
|
24 |
+
return False
|
25 |
+
|
26 |
+
# Verify whether it is equitable.
|
27 |
+
color_set_size = defaultdict(int)
|
28 |
+
for color in coloring.values():
|
29 |
+
color_set_size[color] += 1
|
30 |
+
|
31 |
+
if num_colors is not None:
|
32 |
+
for color in range(num_colors):
|
33 |
+
if color not in color_set_size:
|
34 |
+
# These colors do not have any vertices attached to them.
|
35 |
+
color_set_size[color] = 0
|
36 |
+
|
37 |
+
# If there are more than 2 distinct values, the coloring cannot be equitable
|
38 |
+
all_set_sizes = set(color_set_size.values())
|
39 |
+
if len(all_set_sizes) == 0 and num_colors is None: # Was an empty graph
|
40 |
+
return True
|
41 |
+
elif len(all_set_sizes) == 1:
|
42 |
+
return True
|
43 |
+
elif len(all_set_sizes) == 2:
|
44 |
+
a, b = list(all_set_sizes)
|
45 |
+
return abs(a - b) <= 1
|
46 |
+
else: # len(all_set_sizes) > 2:
|
47 |
+
return False
|
48 |
+
|
49 |
+
|
50 |
+
def make_C_from_F(F):
|
51 |
+
C = defaultdict(list)
|
52 |
+
for node, color in F.items():
|
53 |
+
C[color].append(node)
|
54 |
+
|
55 |
+
return C
|
56 |
+
|
57 |
+
|
58 |
+
def make_N_from_L_C(L, C):
|
59 |
+
nodes = L.keys()
|
60 |
+
colors = C.keys()
|
61 |
+
return {
|
62 |
+
(node, color): sum(1 for v in L[node] if v in C[color])
|
63 |
+
for node in nodes
|
64 |
+
for color in colors
|
65 |
+
}
|
66 |
+
|
67 |
+
|
68 |
+
def make_H_from_C_N(C, N):
|
69 |
+
return {
|
70 |
+
(c1, c2): sum(1 for node in C[c1] if N[(node, c2)] == 0) for c1 in C for c2 in C
|
71 |
+
}
|
72 |
+
|
73 |
+
|
74 |
+
def change_color(u, X, Y, N, H, F, C, L):
|
75 |
+
"""Change the color of 'u' from X to Y and update N, H, F, C."""
|
76 |
+
assert F[u] == X and X != Y
|
77 |
+
|
78 |
+
# Change the class of 'u' from X to Y
|
79 |
+
F[u] = Y
|
80 |
+
|
81 |
+
for k in C:
|
82 |
+
# 'u' witnesses an edge from k -> Y instead of from k -> X now.
|
83 |
+
if N[u, k] == 0:
|
84 |
+
H[(X, k)] -= 1
|
85 |
+
H[(Y, k)] += 1
|
86 |
+
|
87 |
+
for v in L[u]:
|
88 |
+
# 'v' has lost a neighbor in X and gained one in Y
|
89 |
+
N[(v, X)] -= 1
|
90 |
+
N[(v, Y)] += 1
|
91 |
+
|
92 |
+
if N[(v, X)] == 0:
|
93 |
+
# 'v' witnesses F[v] -> X
|
94 |
+
H[(F[v], X)] += 1
|
95 |
+
|
96 |
+
if N[(v, Y)] == 1:
|
97 |
+
# 'v' no longer witnesses F[v] -> Y
|
98 |
+
H[(F[v], Y)] -= 1
|
99 |
+
|
100 |
+
C[X].remove(u)
|
101 |
+
C[Y].append(u)
|
102 |
+
|
103 |
+
|
104 |
+
def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L):
|
105 |
+
"""Move witness along a path from src_color to dst_color."""
|
106 |
+
X = src_color
|
107 |
+
while X != dst_color:
|
108 |
+
Y = T_cal[X]
|
109 |
+
# Move _any_ witness from X to Y = T_cal[X]
|
110 |
+
w = next(x for x in C[X] if N[(x, Y)] == 0)
|
111 |
+
change_color(w, X, Y, N=N, H=H, F=F, C=C, L=L)
|
112 |
+
X = Y
|
113 |
+
|
114 |
+
|
115 |
+
@nx._dispatchable(mutates_input=True)
|
116 |
+
def pad_graph(G, num_colors):
|
117 |
+
"""Add a disconnected complete clique K_p such that the number of nodes in
|
118 |
+
the graph becomes a multiple of `num_colors`.
|
119 |
+
|
120 |
+
Assumes that the graph's nodes are labelled using integers.
|
121 |
+
|
122 |
+
Returns the number of nodes with each color.
|
123 |
+
"""
|
124 |
+
|
125 |
+
n_ = len(G)
|
126 |
+
r = num_colors - 1
|
127 |
+
|
128 |
+
# Ensure that the number of nodes in G is a multiple of (r + 1)
|
129 |
+
s = n_ // (r + 1)
|
130 |
+
if n_ != s * (r + 1):
|
131 |
+
p = (r + 1) - n_ % (r + 1)
|
132 |
+
s += 1
|
133 |
+
|
134 |
+
# Complete graph K_p between (imaginary) nodes [n_, ... , n_ + p]
|
135 |
+
K = nx.relabel_nodes(nx.complete_graph(p), {idx: idx + n_ for idx in range(p)})
|
136 |
+
G.add_edges_from(K.edges)
|
137 |
+
|
138 |
+
return s
|
139 |
+
|
140 |
+
|
141 |
+
def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None):
|
142 |
+
"""Procedure P as described in the paper."""
|
143 |
+
|
144 |
+
if excluded_colors is None:
|
145 |
+
excluded_colors = set()
|
146 |
+
|
147 |
+
A_cal = set()
|
148 |
+
T_cal = {}
|
149 |
+
R_cal = []
|
150 |
+
|
151 |
+
# BFS to determine A_cal, i.e. colors reachable from V-
|
152 |
+
reachable = [V_minus]
|
153 |
+
marked = set(reachable)
|
154 |
+
idx = 0
|
155 |
+
|
156 |
+
while idx < len(reachable):
|
157 |
+
pop = reachable[idx]
|
158 |
+
idx += 1
|
159 |
+
|
160 |
+
A_cal.add(pop)
|
161 |
+
R_cal.append(pop)
|
162 |
+
|
163 |
+
# TODO: Checking whether a color has been visited can be made faster by
|
164 |
+
# using a look-up table instead of testing for membership in a set by a
|
165 |
+
# logarithmic factor.
|
166 |
+
next_layer = []
|
167 |
+
for k in C:
|
168 |
+
if (
|
169 |
+
H[(k, pop)] > 0
|
170 |
+
and k not in A_cal
|
171 |
+
and k not in excluded_colors
|
172 |
+
and k not in marked
|
173 |
+
):
|
174 |
+
next_layer.append(k)
|
175 |
+
|
176 |
+
for dst in next_layer:
|
177 |
+
# Record that `dst` can reach `pop`
|
178 |
+
T_cal[dst] = pop
|
179 |
+
|
180 |
+
marked.update(next_layer)
|
181 |
+
reachable.extend(next_layer)
|
182 |
+
|
183 |
+
# Variables for the algorithm
|
184 |
+
b = len(C) - len(A_cal)
|
185 |
+
|
186 |
+
if V_plus in A_cal:
|
187 |
+
# Easy case: V+ is in A_cal
|
188 |
+
# Move one node from V+ to V- using T_cal to find the parents.
|
189 |
+
move_witnesses(V_plus, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L)
|
190 |
+
else:
|
191 |
+
# If there is a solo edge, we can resolve the situation by
|
192 |
+
# moving witnesses from B to A, making G[A] equitable and then
|
193 |
+
# recursively balancing G[B - w] with a different V_minus and
|
194 |
+
# but the same V_plus.
|
195 |
+
|
196 |
+
A_0 = set()
|
197 |
+
A_cal_0 = set()
|
198 |
+
num_terminal_sets_found = 0
|
199 |
+
made_equitable = False
|
200 |
+
|
201 |
+
for W_1 in R_cal[::-1]:
|
202 |
+
for v in C[W_1]:
|
203 |
+
X = None
|
204 |
+
|
205 |
+
for U in C:
|
206 |
+
if N[(v, U)] == 0 and U in A_cal and U != W_1:
|
207 |
+
X = U
|
208 |
+
|
209 |
+
# v does not witness an edge in H[A_cal]
|
210 |
+
if X is None:
|
211 |
+
continue
|
212 |
+
|
213 |
+
for U in C:
|
214 |
+
# Note: Departing from the paper here.
|
215 |
+
if N[(v, U)] >= 1 and U not in A_cal:
|
216 |
+
X_prime = U
|
217 |
+
w = v
|
218 |
+
|
219 |
+
try:
|
220 |
+
# Finding the solo neighbor of w in X_prime
|
221 |
+
y = next(
|
222 |
+
node
|
223 |
+
for node in L[w]
|
224 |
+
if F[node] == X_prime and N[(node, W_1)] == 1
|
225 |
+
)
|
226 |
+
except StopIteration:
|
227 |
+
pass
|
228 |
+
else:
|
229 |
+
W = W_1
|
230 |
+
|
231 |
+
# Move w from W to X, now X has one extra node.
|
232 |
+
change_color(w, W, X, N=N, H=H, F=F, C=C, L=L)
|
233 |
+
|
234 |
+
# Move witness from X to V_minus, making the coloring
|
235 |
+
# equitable.
|
236 |
+
move_witnesses(
|
237 |
+
src_color=X,
|
238 |
+
dst_color=V_minus,
|
239 |
+
N=N,
|
240 |
+
H=H,
|
241 |
+
F=F,
|
242 |
+
C=C,
|
243 |
+
T_cal=T_cal,
|
244 |
+
L=L,
|
245 |
+
)
|
246 |
+
|
247 |
+
# Move y from X_prime to W, making W the correct size.
|
248 |
+
change_color(y, X_prime, W, N=N, H=H, F=F, C=C, L=L)
|
249 |
+
|
250 |
+
# Then call the procedure on G[B - y]
|
251 |
+
procedure_P(
|
252 |
+
V_minus=X_prime,
|
253 |
+
V_plus=V_plus,
|
254 |
+
N=N,
|
255 |
+
H=H,
|
256 |
+
C=C,
|
257 |
+
F=F,
|
258 |
+
L=L,
|
259 |
+
excluded_colors=excluded_colors.union(A_cal),
|
260 |
+
)
|
261 |
+
made_equitable = True
|
262 |
+
break
|
263 |
+
|
264 |
+
if made_equitable:
|
265 |
+
break
|
266 |
+
else:
|
267 |
+
# No node in W_1 was found such that
|
268 |
+
# it had a solo-neighbor.
|
269 |
+
A_cal_0.add(W_1)
|
270 |
+
A_0.update(C[W_1])
|
271 |
+
num_terminal_sets_found += 1
|
272 |
+
|
273 |
+
if num_terminal_sets_found == b:
|
274 |
+
# Otherwise, construct the maximal independent set and find
|
275 |
+
# a pair of z_1, z_2 as in Case II.
|
276 |
+
|
277 |
+
# BFS to determine B_cal': the set of colors reachable from V+
|
278 |
+
B_cal_prime = set()
|
279 |
+
T_cal_prime = {}
|
280 |
+
|
281 |
+
reachable = [V_plus]
|
282 |
+
marked = set(reachable)
|
283 |
+
idx = 0
|
284 |
+
while idx < len(reachable):
|
285 |
+
pop = reachable[idx]
|
286 |
+
idx += 1
|
287 |
+
|
288 |
+
B_cal_prime.add(pop)
|
289 |
+
|
290 |
+
# No need to check for excluded_colors here because
|
291 |
+
# they only exclude colors from A_cal
|
292 |
+
next_layer = [
|
293 |
+
k
|
294 |
+
for k in C
|
295 |
+
if H[(pop, k)] > 0 and k not in B_cal_prime and k not in marked
|
296 |
+
]
|
297 |
+
|
298 |
+
for dst in next_layer:
|
299 |
+
T_cal_prime[pop] = dst
|
300 |
+
|
301 |
+
marked.update(next_layer)
|
302 |
+
reachable.extend(next_layer)
|
303 |
+
|
304 |
+
# Construct the independent set of G[B']
|
305 |
+
I_set = set()
|
306 |
+
I_covered = set()
|
307 |
+
W_covering = {}
|
308 |
+
|
309 |
+
B_prime = [node for k in B_cal_prime for node in C[k]]
|
310 |
+
|
311 |
+
# Add the nodes in V_plus to I first.
|
312 |
+
for z in C[V_plus] + B_prime:
|
313 |
+
if z in I_covered or F[z] not in B_cal_prime:
|
314 |
+
continue
|
315 |
+
|
316 |
+
I_set.add(z)
|
317 |
+
I_covered.add(z)
|
318 |
+
I_covered.update(list(L[z]))
|
319 |
+
|
320 |
+
for w in L[z]:
|
321 |
+
if F[w] in A_cal_0 and N[(z, F[w])] == 1:
|
322 |
+
if w not in W_covering:
|
323 |
+
W_covering[w] = z
|
324 |
+
else:
|
325 |
+
# Found z1, z2 which have the same solo
|
326 |
+
# neighbor in some W
|
327 |
+
z_1 = W_covering[w]
|
328 |
+
# z_2 = z
|
329 |
+
|
330 |
+
Z = F[z_1]
|
331 |
+
W = F[w]
|
332 |
+
|
333 |
+
# shift nodes along W, V-
|
334 |
+
move_witnesses(
|
335 |
+
W, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L
|
336 |
+
)
|
337 |
+
|
338 |
+
# shift nodes along V+ to Z
|
339 |
+
move_witnesses(
|
340 |
+
V_plus,
|
341 |
+
Z,
|
342 |
+
N=N,
|
343 |
+
H=H,
|
344 |
+
F=F,
|
345 |
+
C=C,
|
346 |
+
T_cal=T_cal_prime,
|
347 |
+
L=L,
|
348 |
+
)
|
349 |
+
|
350 |
+
# change color of z_1 to W
|
351 |
+
change_color(z_1, Z, W, N=N, H=H, F=F, C=C, L=L)
|
352 |
+
|
353 |
+
# change color of w to some color in B_cal
|
354 |
+
W_plus = next(
|
355 |
+
k for k in C if N[(w, k)] == 0 and k not in A_cal
|
356 |
+
)
|
357 |
+
change_color(w, W, W_plus, N=N, H=H, F=F, C=C, L=L)
|
358 |
+
|
359 |
+
# recurse with G[B \cup W*]
|
360 |
+
excluded_colors.update(
|
361 |
+
[k for k in C if k != W and k not in B_cal_prime]
|
362 |
+
)
|
363 |
+
procedure_P(
|
364 |
+
V_minus=W,
|
365 |
+
V_plus=W_plus,
|
366 |
+
N=N,
|
367 |
+
H=H,
|
368 |
+
C=C,
|
369 |
+
F=F,
|
370 |
+
L=L,
|
371 |
+
excluded_colors=excluded_colors,
|
372 |
+
)
|
373 |
+
|
374 |
+
made_equitable = True
|
375 |
+
break
|
376 |
+
|
377 |
+
if made_equitable:
|
378 |
+
break
|
379 |
+
else:
|
380 |
+
assert False, (
|
381 |
+
"Must find a w which is the solo neighbor "
|
382 |
+
"of two vertices in B_cal_prime."
|
383 |
+
)
|
384 |
+
|
385 |
+
if made_equitable:
|
386 |
+
break
|
387 |
+
|
388 |
+
|
389 |
+
@nx._dispatchable
|
390 |
+
def equitable_color(G, num_colors):
|
391 |
+
"""Provides an equitable coloring for nodes of `G`.
|
392 |
+
|
393 |
+
Attempts to color a graph using `num_colors` colors, where no neighbors of
|
394 |
+
a node can have same color as the node itself and the number of nodes with
|
395 |
+
each color differ by at most 1. `num_colors` must be greater than the
|
396 |
+
maximum degree of `G`. The algorithm is described in [1]_ and has
|
397 |
+
complexity O(num_colors * n**2).
|
398 |
+
|
399 |
+
Parameters
|
400 |
+
----------
|
401 |
+
G : networkX graph
|
402 |
+
The nodes of this graph will be colored.
|
403 |
+
|
404 |
+
num_colors : number of colors to use
|
405 |
+
This number must be at least one more than the maximum degree of nodes
|
406 |
+
in the graph.
|
407 |
+
|
408 |
+
Returns
|
409 |
+
-------
|
410 |
+
A dictionary with keys representing nodes and values representing
|
411 |
+
corresponding coloring.
|
412 |
+
|
413 |
+
Examples
|
414 |
+
--------
|
415 |
+
>>> G = nx.cycle_graph(4)
|
416 |
+
>>> nx.coloring.equitable_color(G, num_colors=3) # doctest: +SKIP
|
417 |
+
{0: 2, 1: 1, 2: 2, 3: 0}
|
418 |
+
|
419 |
+
Raises
|
420 |
+
------
|
421 |
+
NetworkXAlgorithmError
|
422 |
+
If `num_colors` is not at least the maximum degree of the graph `G`
|
423 |
+
|
424 |
+
References
|
425 |
+
----------
|
426 |
+
.. [1] Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E.
|
427 |
+
(2010). A fast algorithm for equitable coloring. Combinatorica, 30(2),
|
428 |
+
217-224.
|
429 |
+
"""
|
430 |
+
|
431 |
+
# Map nodes to integers for simplicity later.
|
432 |
+
nodes_to_int = {}
|
433 |
+
int_to_nodes = {}
|
434 |
+
|
435 |
+
for idx, node in enumerate(G.nodes):
|
436 |
+
nodes_to_int[node] = idx
|
437 |
+
int_to_nodes[idx] = node
|
438 |
+
|
439 |
+
G = nx.relabel_nodes(G, nodes_to_int, copy=True)
|
440 |
+
|
441 |
+
# Basic graph statistics and sanity check.
|
442 |
+
if len(G.nodes) > 0:
|
443 |
+
r_ = max(G.degree(node) for node in G.nodes)
|
444 |
+
else:
|
445 |
+
r_ = 0
|
446 |
+
|
447 |
+
if r_ >= num_colors:
|
448 |
+
raise nx.NetworkXAlgorithmError(
|
449 |
+
f"Graph has maximum degree {r_}, needs "
|
450 |
+
f"{r_ + 1} (> {num_colors}) colors for guaranteed coloring."
|
451 |
+
)
|
452 |
+
|
453 |
+
# Ensure that the number of nodes in G is a multiple of (r + 1)
|
454 |
+
pad_graph(G, num_colors)
|
455 |
+
|
456 |
+
# Starting the algorithm.
|
457 |
+
# L = {node: list(G.neighbors(node)) for node in G.nodes}
|
458 |
+
L_ = {node: [] for node in G.nodes}
|
459 |
+
|
460 |
+
# Arbitrary equitable allocation of colors to nodes.
|
461 |
+
F = {node: idx % num_colors for idx, node in enumerate(G.nodes)}
|
462 |
+
|
463 |
+
C = make_C_from_F(F)
|
464 |
+
|
465 |
+
# The neighborhood is empty initially.
|
466 |
+
N = make_N_from_L_C(L_, C)
|
467 |
+
|
468 |
+
# Currently all nodes witness all edges.
|
469 |
+
H = make_H_from_C_N(C, N)
|
470 |
+
|
471 |
+
# Start of algorithm.
|
472 |
+
edges_seen = set()
|
473 |
+
|
474 |
+
for u in sorted(G.nodes):
|
475 |
+
for v in sorted(G.neighbors(u)):
|
476 |
+
# Do not double count edges if (v, u) has already been seen.
|
477 |
+
if (v, u) in edges_seen:
|
478 |
+
continue
|
479 |
+
|
480 |
+
edges_seen.add((u, v))
|
481 |
+
|
482 |
+
L_[u].append(v)
|
483 |
+
L_[v].append(u)
|
484 |
+
|
485 |
+
N[(u, F[v])] += 1
|
486 |
+
N[(v, F[u])] += 1
|
487 |
+
|
488 |
+
if F[u] != F[v]:
|
489 |
+
# Were 'u' and 'v' witnesses for F[u] -> F[v] or F[v] -> F[u]?
|
490 |
+
if N[(u, F[v])] == 1:
|
491 |
+
H[F[u], F[v]] -= 1 # u cannot witness an edge between F[u], F[v]
|
492 |
+
|
493 |
+
if N[(v, F[u])] == 1:
|
494 |
+
H[F[v], F[u]] -= 1 # v cannot witness an edge between F[v], F[u]
|
495 |
+
|
496 |
+
if N[(u, F[u])] != 0:
|
497 |
+
# Find the first color where 'u' does not have any neighbors.
|
498 |
+
Y = next(k for k in C if N[(u, k)] == 0)
|
499 |
+
X = F[u]
|
500 |
+
change_color(u, X, Y, N=N, H=H, F=F, C=C, L=L_)
|
501 |
+
|
502 |
+
# Procedure P
|
503 |
+
procedure_P(V_minus=X, V_plus=Y, N=N, H=H, F=F, C=C, L=L_)
|
504 |
+
|
505 |
+
return {int_to_nodes[x]: F[x] for x in int_to_nodes}
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py
ADDED
@@ -0,0 +1,564 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Greedy graph coloring using various strategies.
|
3 |
+
"""
|
4 |
+
import itertools
|
5 |
+
from collections import defaultdict, deque
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
from networkx.utils import arbitrary_element, py_random_state
|
9 |
+
|
10 |
+
__all__ = [
|
11 |
+
"greedy_color",
|
12 |
+
"strategy_connected_sequential",
|
13 |
+
"strategy_connected_sequential_bfs",
|
14 |
+
"strategy_connected_sequential_dfs",
|
15 |
+
"strategy_independent_set",
|
16 |
+
"strategy_largest_first",
|
17 |
+
"strategy_random_sequential",
|
18 |
+
"strategy_saturation_largest_first",
|
19 |
+
"strategy_smallest_last",
|
20 |
+
]
|
21 |
+
|
22 |
+
|
23 |
+
def strategy_largest_first(G, colors):
|
24 |
+
"""Returns a list of the nodes of ``G`` in decreasing order by
|
25 |
+
degree.
|
26 |
+
|
27 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
28 |
+
|
29 |
+
"""
|
30 |
+
return sorted(G, key=G.degree, reverse=True)
|
31 |
+
|
32 |
+
|
33 |
+
@py_random_state(2)
|
34 |
+
def strategy_random_sequential(G, colors, seed=None):
|
35 |
+
"""Returns a random permutation of the nodes of ``G`` as a list.
|
36 |
+
|
37 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
38 |
+
|
39 |
+
seed : integer, random_state, or None (default)
|
40 |
+
Indicator of random number generation state.
|
41 |
+
See :ref:`Randomness<randomness>`.
|
42 |
+
"""
|
43 |
+
nodes = list(G)
|
44 |
+
seed.shuffle(nodes)
|
45 |
+
return nodes
|
46 |
+
|
47 |
+
|
48 |
+
def strategy_smallest_last(G, colors):
|
49 |
+
"""Returns a deque of the nodes of ``G``, "smallest" last.
|
50 |
+
|
51 |
+
Specifically, the degrees of each node are tracked in a bucket queue.
|
52 |
+
From this, the node of minimum degree is repeatedly popped from the
|
53 |
+
graph, updating its neighbors' degrees.
|
54 |
+
|
55 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
56 |
+
|
57 |
+
This implementation of the strategy runs in $O(n + m)$ time
|
58 |
+
(ignoring polylogarithmic factors), where $n$ is the number of nodes
|
59 |
+
and $m$ is the number of edges.
|
60 |
+
|
61 |
+
This strategy is related to :func:`strategy_independent_set`: if we
|
62 |
+
interpret each node removed as an independent set of size one, then
|
63 |
+
this strategy chooses an independent set of size one instead of a
|
64 |
+
maximal independent set.
|
65 |
+
|
66 |
+
"""
|
67 |
+
H = G.copy()
|
68 |
+
result = deque()
|
69 |
+
|
70 |
+
# Build initial degree list (i.e. the bucket queue data structure)
|
71 |
+
degrees = defaultdict(set) # set(), for fast random-access removals
|
72 |
+
lbound = float("inf")
|
73 |
+
for node, d in H.degree():
|
74 |
+
degrees[d].add(node)
|
75 |
+
lbound = min(lbound, d) # Lower bound on min-degree.
|
76 |
+
|
77 |
+
def find_min_degree():
|
78 |
+
# Save time by starting the iterator at `lbound`, not 0.
|
79 |
+
# The value that we find will be our new `lbound`, which we set later.
|
80 |
+
return next(d for d in itertools.count(lbound) if d in degrees)
|
81 |
+
|
82 |
+
for _ in G:
|
83 |
+
# Pop a min-degree node and add it to the list.
|
84 |
+
min_degree = find_min_degree()
|
85 |
+
u = degrees[min_degree].pop()
|
86 |
+
if not degrees[min_degree]: # Clean up the degree list.
|
87 |
+
del degrees[min_degree]
|
88 |
+
result.appendleft(u)
|
89 |
+
|
90 |
+
# Update degrees of removed node's neighbors.
|
91 |
+
for v in H[u]:
|
92 |
+
degree = H.degree(v)
|
93 |
+
degrees[degree].remove(v)
|
94 |
+
if not degrees[degree]: # Clean up the degree list.
|
95 |
+
del degrees[degree]
|
96 |
+
degrees[degree - 1].add(v)
|
97 |
+
|
98 |
+
# Finally, remove the node.
|
99 |
+
H.remove_node(u)
|
100 |
+
lbound = min_degree - 1 # Subtract 1 in case of tied neighbors.
|
101 |
+
|
102 |
+
return result
|
103 |
+
|
104 |
+
|
105 |
+
def _maximal_independent_set(G):
|
106 |
+
"""Returns a maximal independent set of nodes in ``G`` by repeatedly
|
107 |
+
choosing an independent node of minimum degree (with respect to the
|
108 |
+
subgraph of unchosen nodes).
|
109 |
+
|
110 |
+
"""
|
111 |
+
result = set()
|
112 |
+
remaining = set(G)
|
113 |
+
while remaining:
|
114 |
+
G = G.subgraph(remaining)
|
115 |
+
v = min(remaining, key=G.degree)
|
116 |
+
result.add(v)
|
117 |
+
remaining -= set(G[v]) | {v}
|
118 |
+
return result
|
119 |
+
|
120 |
+
|
121 |
+
def strategy_independent_set(G, colors):
|
122 |
+
"""Uses a greedy independent set removal strategy to determine the
|
123 |
+
colors.
|
124 |
+
|
125 |
+
This function updates ``colors`` **in-place** and return ``None``,
|
126 |
+
unlike the other strategy functions in this module.
|
127 |
+
|
128 |
+
This algorithm repeatedly finds and removes a maximal independent
|
129 |
+
set, assigning each node in the set an unused color.
|
130 |
+
|
131 |
+
``G`` is a NetworkX graph.
|
132 |
+
|
133 |
+
This strategy is related to :func:`strategy_smallest_last`: in that
|
134 |
+
strategy, an independent set of size one is chosen at each step
|
135 |
+
instead of a maximal independent set.
|
136 |
+
|
137 |
+
"""
|
138 |
+
remaining_nodes = set(G)
|
139 |
+
while len(remaining_nodes) > 0:
|
140 |
+
nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
|
141 |
+
remaining_nodes -= nodes
|
142 |
+
yield from nodes
|
143 |
+
|
144 |
+
|
145 |
+
def strategy_connected_sequential_bfs(G, colors):
|
146 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
147 |
+
breadth-first traversal.
|
148 |
+
|
149 |
+
The generated sequence has the property that for each node except
|
150 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
151 |
+
|
152 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
153 |
+
|
154 |
+
"""
|
155 |
+
return strategy_connected_sequential(G, colors, "bfs")
|
156 |
+
|
157 |
+
|
158 |
+
def strategy_connected_sequential_dfs(G, colors):
|
159 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
160 |
+
depth-first traversal.
|
161 |
+
|
162 |
+
The generated sequence has the property that for each node except
|
163 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
164 |
+
|
165 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
166 |
+
|
167 |
+
"""
|
168 |
+
return strategy_connected_sequential(G, colors, "dfs")
|
169 |
+
|
170 |
+
|
171 |
+
def strategy_connected_sequential(G, colors, traversal="bfs"):
|
172 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
173 |
+
breadth-first or depth-first traversal.
|
174 |
+
|
175 |
+
``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
|
176 |
+
representing depth-first traversal or breadth-first traversal,
|
177 |
+
respectively.
|
178 |
+
|
179 |
+
The generated sequence has the property that for each node except
|
180 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
181 |
+
|
182 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
183 |
+
|
184 |
+
"""
|
185 |
+
if traversal == "bfs":
|
186 |
+
traverse = nx.bfs_edges
|
187 |
+
elif traversal == "dfs":
|
188 |
+
traverse = nx.dfs_edges
|
189 |
+
else:
|
190 |
+
raise nx.NetworkXError(
|
191 |
+
"Please specify one of the strings 'bfs' or"
|
192 |
+
" 'dfs' for connected sequential ordering"
|
193 |
+
)
|
194 |
+
for component in nx.connected_components(G):
|
195 |
+
source = arbitrary_element(component)
|
196 |
+
# Yield the source node, then all the nodes in the specified
|
197 |
+
# traversal order.
|
198 |
+
yield source
|
199 |
+
for _, end in traverse(G.subgraph(component), source):
|
200 |
+
yield end
|
201 |
+
|
202 |
+
|
203 |
+
def strategy_saturation_largest_first(G, colors):
|
204 |
+
"""Iterates over all the nodes of ``G`` in "saturation order" (also
|
205 |
+
known as "DSATUR").
|
206 |
+
|
207 |
+
``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
|
208 |
+
``G`` to colors, for those nodes that have already been colored.
|
209 |
+
|
210 |
+
"""
|
211 |
+
distinct_colors = {v: set() for v in G}
|
212 |
+
|
213 |
+
# Add the node color assignments given in colors to the
|
214 |
+
# distinct colors set for each neighbor of that node
|
215 |
+
for node, color in colors.items():
|
216 |
+
for neighbor in G[node]:
|
217 |
+
distinct_colors[neighbor].add(color)
|
218 |
+
|
219 |
+
# Check that the color assignments in colors are valid
|
220 |
+
# i.e. no neighboring nodes have the same color
|
221 |
+
if len(colors) >= 2:
|
222 |
+
for node, color in colors.items():
|
223 |
+
if color in distinct_colors[node]:
|
224 |
+
raise nx.NetworkXError("Neighboring nodes must have different colors")
|
225 |
+
|
226 |
+
# If 0 nodes have been colored, simply choose the node of highest degree.
|
227 |
+
if not colors:
|
228 |
+
node = max(G, key=G.degree)
|
229 |
+
yield node
|
230 |
+
# Add the color 0 to the distinct colors set for each
|
231 |
+
# neighbor of that node.
|
232 |
+
for v in G[node]:
|
233 |
+
distinct_colors[v].add(0)
|
234 |
+
|
235 |
+
while len(G) != len(colors):
|
236 |
+
# Update the distinct color sets for the neighbors.
|
237 |
+
for node, color in colors.items():
|
238 |
+
for neighbor in G[node]:
|
239 |
+
distinct_colors[neighbor].add(color)
|
240 |
+
|
241 |
+
# Compute the maximum saturation and the set of nodes that
|
242 |
+
# achieve that saturation.
|
243 |
+
saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}
|
244 |
+
# Yield the node with the highest saturation, and break ties by
|
245 |
+
# degree.
|
246 |
+
node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
|
247 |
+
yield node
|
248 |
+
|
249 |
+
|
250 |
+
#: Dictionary mapping name of a strategy as a string to the strategy function.
|
251 |
+
STRATEGIES = {
|
252 |
+
"largest_first": strategy_largest_first,
|
253 |
+
"random_sequential": strategy_random_sequential,
|
254 |
+
"smallest_last": strategy_smallest_last,
|
255 |
+
"independent_set": strategy_independent_set,
|
256 |
+
"connected_sequential_bfs": strategy_connected_sequential_bfs,
|
257 |
+
"connected_sequential_dfs": strategy_connected_sequential_dfs,
|
258 |
+
"connected_sequential": strategy_connected_sequential,
|
259 |
+
"saturation_largest_first": strategy_saturation_largest_first,
|
260 |
+
"DSATUR": strategy_saturation_largest_first,
|
261 |
+
}
|
262 |
+
|
263 |
+
|
264 |
+
@nx._dispatchable
|
265 |
+
def greedy_color(G, strategy="largest_first", interchange=False):
|
266 |
+
"""Color a graph using various strategies of greedy graph coloring.
|
267 |
+
|
268 |
+
Attempts to color a graph using as few colors as possible, where no
|
269 |
+
neighbors of a node can have same color as the node itself. The
|
270 |
+
given strategy determines the order in which nodes are colored.
|
271 |
+
|
272 |
+
The strategies are described in [1]_, and smallest-last is based on
|
273 |
+
[2]_.
|
274 |
+
|
275 |
+
Parameters
|
276 |
+
----------
|
277 |
+
G : NetworkX graph
|
278 |
+
|
279 |
+
strategy : string or function(G, colors)
|
280 |
+
A function (or a string representing a function) that provides
|
281 |
+
the coloring strategy, by returning nodes in the ordering they
|
282 |
+
should be colored. ``G`` is the graph, and ``colors`` is a
|
283 |
+
dictionary of the currently assigned colors, keyed by nodes. The
|
284 |
+
function must return an iterable over all the nodes in ``G``.
|
285 |
+
|
286 |
+
If the strategy function is an iterator generator (that is, a
|
287 |
+
function with ``yield`` statements), keep in mind that the
|
288 |
+
``colors`` dictionary will be updated after each ``yield``, since
|
289 |
+
this function chooses colors greedily.
|
290 |
+
|
291 |
+
If ``strategy`` is a string, it must be one of the following,
|
292 |
+
each of which represents one of the built-in strategy functions.
|
293 |
+
|
294 |
+
* ``'largest_first'``
|
295 |
+
* ``'random_sequential'``
|
296 |
+
* ``'smallest_last'``
|
297 |
+
* ``'independent_set'``
|
298 |
+
* ``'connected_sequential_bfs'``
|
299 |
+
* ``'connected_sequential_dfs'``
|
300 |
+
* ``'connected_sequential'`` (alias for the previous strategy)
|
301 |
+
* ``'saturation_largest_first'``
|
302 |
+
* ``'DSATUR'`` (alias for the previous strategy)
|
303 |
+
|
304 |
+
interchange: bool
|
305 |
+
Will use the color interchange algorithm described by [3]_ if set
|
306 |
+
to ``True``.
|
307 |
+
|
308 |
+
Note that ``saturation_largest_first`` and ``independent_set``
|
309 |
+
do not work with interchange. Furthermore, if you use
|
310 |
+
interchange with your own strategy function, you cannot rely
|
311 |
+
on the values in the ``colors`` argument.
|
312 |
+
|
313 |
+
Returns
|
314 |
+
-------
|
315 |
+
A dictionary with keys representing nodes and values representing
|
316 |
+
corresponding coloring.
|
317 |
+
|
318 |
+
Examples
|
319 |
+
--------
|
320 |
+
>>> G = nx.cycle_graph(4)
|
321 |
+
>>> d = nx.coloring.greedy_color(G, strategy="largest_first")
|
322 |
+
>>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
|
323 |
+
True
|
324 |
+
|
325 |
+
Raises
|
326 |
+
------
|
327 |
+
NetworkXPointlessConcept
|
328 |
+
If ``strategy`` is ``saturation_largest_first`` or
|
329 |
+
``independent_set`` and ``interchange`` is ``True``.
|
330 |
+
|
331 |
+
References
|
332 |
+
----------
|
333 |
+
.. [1] Adrian Kosowski, and Krzysztof Manuszewski,
|
334 |
+
Classical Coloring of Graphs, Graph Colorings, 2-19, 2004.
|
335 |
+
ISBN 0-8218-3458-4.
|
336 |
+
.. [2] David W. Matula, and Leland L. Beck, "Smallest-last
|
337 |
+
ordering and clustering and graph coloring algorithms." *J. ACM* 30,
|
338 |
+
3 (July 1983), 417–427. <https://doi.org/10.1145/2402.322385>
|
339 |
+
.. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik,
|
340 |
+
Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
|
341 |
+
ISBN 0-486-45353-7.
|
342 |
+
|
343 |
+
"""
|
344 |
+
if len(G) == 0:
|
345 |
+
return {}
|
346 |
+
# Determine the strategy provided by the caller.
|
347 |
+
strategy = STRATEGIES.get(strategy, strategy)
|
348 |
+
if not callable(strategy):
|
349 |
+
raise nx.NetworkXError(
|
350 |
+
f"strategy must be callable or a valid string. {strategy} not valid."
|
351 |
+
)
|
352 |
+
# Perform some validation on the arguments before executing any
|
353 |
+
# strategy functions.
|
354 |
+
if interchange:
|
355 |
+
if strategy is strategy_independent_set:
|
356 |
+
msg = "interchange cannot be used with independent_set"
|
357 |
+
raise nx.NetworkXPointlessConcept(msg)
|
358 |
+
if strategy is strategy_saturation_largest_first:
|
359 |
+
msg = "interchange cannot be used with" " saturation_largest_first"
|
360 |
+
raise nx.NetworkXPointlessConcept(msg)
|
361 |
+
colors = {}
|
362 |
+
nodes = strategy(G, colors)
|
363 |
+
if interchange:
|
364 |
+
return _greedy_coloring_with_interchange(G, nodes)
|
365 |
+
for u in nodes:
|
366 |
+
# Set to keep track of colors of neighbors
|
367 |
+
nbr_colors = {colors[v] for v in G[u] if v in colors}
|
368 |
+
# Find the first unused color.
|
369 |
+
for color in itertools.count():
|
370 |
+
if color not in nbr_colors:
|
371 |
+
break
|
372 |
+
# Assign the new color to the current node.
|
373 |
+
colors[u] = color
|
374 |
+
return colors
|
375 |
+
|
376 |
+
|
377 |
+
# Tools for coloring with interchanges
|
378 |
+
class _Node:
|
379 |
+
__slots__ = ["node_id", "color", "adj_list", "adj_color"]
|
380 |
+
|
381 |
+
def __init__(self, node_id, n):
|
382 |
+
self.node_id = node_id
|
383 |
+
self.color = -1
|
384 |
+
self.adj_list = None
|
385 |
+
self.adj_color = [None for _ in range(n)]
|
386 |
+
|
387 |
+
def __repr__(self):
|
388 |
+
return (
|
389 |
+
f"Node_id: {self.node_id}, Color: {self.color}, "
|
390 |
+
f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})"
|
391 |
+
)
|
392 |
+
|
393 |
+
def assign_color(self, adj_entry, color):
|
394 |
+
adj_entry.col_prev = None
|
395 |
+
adj_entry.col_next = self.adj_color[color]
|
396 |
+
self.adj_color[color] = adj_entry
|
397 |
+
if adj_entry.col_next is not None:
|
398 |
+
adj_entry.col_next.col_prev = adj_entry
|
399 |
+
|
400 |
+
def clear_color(self, adj_entry, color):
|
401 |
+
if adj_entry.col_prev is None:
|
402 |
+
self.adj_color[color] = adj_entry.col_next
|
403 |
+
else:
|
404 |
+
adj_entry.col_prev.col_next = adj_entry.col_next
|
405 |
+
if adj_entry.col_next is not None:
|
406 |
+
adj_entry.col_next.col_prev = adj_entry.col_prev
|
407 |
+
|
408 |
+
def iter_neighbors(self):
|
409 |
+
adj_node = self.adj_list
|
410 |
+
while adj_node is not None:
|
411 |
+
yield adj_node
|
412 |
+
adj_node = adj_node.next
|
413 |
+
|
414 |
+
def iter_neighbors_color(self, color):
|
415 |
+
adj_color_node = self.adj_color[color]
|
416 |
+
while adj_color_node is not None:
|
417 |
+
yield adj_color_node.node_id
|
418 |
+
adj_color_node = adj_color_node.col_next
|
419 |
+
|
420 |
+
|
421 |
+
class _AdjEntry:
|
422 |
+
__slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
|
423 |
+
|
424 |
+
def __init__(self, node_id):
|
425 |
+
self.node_id = node_id
|
426 |
+
self.next = None
|
427 |
+
self.mate = None
|
428 |
+
self.col_next = None
|
429 |
+
self.col_prev = None
|
430 |
+
|
431 |
+
def __repr__(self):
|
432 |
+
col_next = None if self.col_next is None else self.col_next.node_id
|
433 |
+
col_prev = None if self.col_prev is None else self.col_prev.node_id
|
434 |
+
return (
|
435 |
+
f"Node_id: {self.node_id}, Next: ({self.next}), "
|
436 |
+
f"Mate: ({self.mate.node_id}), "
|
437 |
+
f"col_next: ({col_next}), col_prev: ({col_prev})"
|
438 |
+
)
|
439 |
+
|
440 |
+
|
441 |
+
def _greedy_coloring_with_interchange(G, nodes):
|
442 |
+
"""Return a coloring for `original_graph` using interchange approach
|
443 |
+
|
444 |
+
This procedure is an adaption of the algorithm described by [1]_,
|
445 |
+
and is an implementation of coloring with interchange. Please be
|
446 |
+
advised, that the datastructures used are rather complex because
|
447 |
+
they are optimized to minimize the time spent identifying
|
448 |
+
subcomponents of the graph, which are possible candidates for color
|
449 |
+
interchange.
|
450 |
+
|
451 |
+
Parameters
|
452 |
+
----------
|
453 |
+
G : NetworkX graph
|
454 |
+
The graph to be colored
|
455 |
+
|
456 |
+
nodes : list
|
457 |
+
nodes ordered using the strategy of choice
|
458 |
+
|
459 |
+
Returns
|
460 |
+
-------
|
461 |
+
dict :
|
462 |
+
A dictionary keyed by node to a color value
|
463 |
+
|
464 |
+
References
|
465 |
+
----------
|
466 |
+
.. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik,
|
467 |
+
Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
|
468 |
+
ISBN 0-486-45353-7.
|
469 |
+
"""
|
470 |
+
n = len(G)
|
471 |
+
|
472 |
+
graph = {node: _Node(node, n) for node in G}
|
473 |
+
|
474 |
+
for node1, node2 in G.edges():
|
475 |
+
adj_entry1 = _AdjEntry(node2)
|
476 |
+
adj_entry2 = _AdjEntry(node1)
|
477 |
+
adj_entry1.mate = adj_entry2
|
478 |
+
adj_entry2.mate = adj_entry1
|
479 |
+
node1_head = graph[node1].adj_list
|
480 |
+
adj_entry1.next = node1_head
|
481 |
+
graph[node1].adj_list = adj_entry1
|
482 |
+
node2_head = graph[node2].adj_list
|
483 |
+
adj_entry2.next = node2_head
|
484 |
+
graph[node2].adj_list = adj_entry2
|
485 |
+
|
486 |
+
k = 0
|
487 |
+
for node in nodes:
|
488 |
+
# Find the smallest possible, unused color
|
489 |
+
neighbors = graph[node].iter_neighbors()
|
490 |
+
col_used = {graph[adj_node.node_id].color for adj_node in neighbors}
|
491 |
+
col_used.discard(-1)
|
492 |
+
k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
|
493 |
+
|
494 |
+
# k1 is now the lowest available color
|
495 |
+
if k1 > k:
|
496 |
+
connected = True
|
497 |
+
visited = set()
|
498 |
+
col1 = -1
|
499 |
+
col2 = -1
|
500 |
+
while connected and col1 < k:
|
501 |
+
col1 += 1
|
502 |
+
neighbor_cols = graph[node].iter_neighbors_color(col1)
|
503 |
+
col1_adj = list(neighbor_cols)
|
504 |
+
|
505 |
+
col2 = col1
|
506 |
+
while connected and col2 < k:
|
507 |
+
col2 += 1
|
508 |
+
visited = set(col1_adj)
|
509 |
+
frontier = list(col1_adj)
|
510 |
+
i = 0
|
511 |
+
while i < len(frontier):
|
512 |
+
search_node = frontier[i]
|
513 |
+
i += 1
|
514 |
+
col_opp = col2 if graph[search_node].color == col1 else col1
|
515 |
+
neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
|
516 |
+
|
517 |
+
for neighbor in neighbor_cols:
|
518 |
+
if neighbor not in visited:
|
519 |
+
visited.add(neighbor)
|
520 |
+
frontier.append(neighbor)
|
521 |
+
|
522 |
+
# Search if node is not adj to any col2 vertex
|
523 |
+
connected = (
|
524 |
+
len(
|
525 |
+
visited.intersection(graph[node].iter_neighbors_color(col2))
|
526 |
+
)
|
527 |
+
> 0
|
528 |
+
)
|
529 |
+
|
530 |
+
# If connected is false then we can swap !!!
|
531 |
+
if not connected:
|
532 |
+
# Update all the nodes in the component
|
533 |
+
for search_node in visited:
|
534 |
+
graph[search_node].color = (
|
535 |
+
col2 if graph[search_node].color == col1 else col1
|
536 |
+
)
|
537 |
+
col2_adj = graph[search_node].adj_color[col2]
|
538 |
+
graph[search_node].adj_color[col2] = graph[search_node].adj_color[
|
539 |
+
col1
|
540 |
+
]
|
541 |
+
graph[search_node].adj_color[col1] = col2_adj
|
542 |
+
|
543 |
+
# Update all the neighboring nodes
|
544 |
+
for search_node in visited:
|
545 |
+
col = graph[search_node].color
|
546 |
+
col_opp = col1 if col == col2 else col2
|
547 |
+
for adj_node in graph[search_node].iter_neighbors():
|
548 |
+
if graph[adj_node.node_id].color != col_opp:
|
549 |
+
# Direct reference to entry
|
550 |
+
adj_mate = adj_node.mate
|
551 |
+
graph[adj_node.node_id].clear_color(adj_mate, col_opp)
|
552 |
+
graph[adj_node.node_id].assign_color(adj_mate, col)
|
553 |
+
k1 = col1
|
554 |
+
|
555 |
+
# We can color this node color k1
|
556 |
+
graph[node].color = k1
|
557 |
+
k = max(k1, k)
|
558 |
+
|
559 |
+
# Update the neighbors of this node
|
560 |
+
for adj_node in graph[node].iter_neighbors():
|
561 |
+
adj_mate = adj_node.mate
|
562 |
+
graph[adj_node.node_id].assign_color(adj_mate, k1)
|
563 |
+
|
564 |
+
return {node.node_id: node.color for node in graph.values()}
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (207 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py
ADDED
@@ -0,0 +1,865 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Greedy coloring test suite.
|
2 |
+
|
3 |
+
"""
|
4 |
+
|
5 |
+
import itertools
|
6 |
+
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
import networkx as nx
|
10 |
+
|
11 |
+
is_coloring = nx.algorithms.coloring.equitable_coloring.is_coloring
|
12 |
+
is_equitable = nx.algorithms.coloring.equitable_coloring.is_equitable
|
13 |
+
|
14 |
+
|
15 |
+
ALL_STRATEGIES = [
|
16 |
+
"largest_first",
|
17 |
+
"random_sequential",
|
18 |
+
"smallest_last",
|
19 |
+
"independent_set",
|
20 |
+
"connected_sequential_bfs",
|
21 |
+
"connected_sequential_dfs",
|
22 |
+
"connected_sequential",
|
23 |
+
"saturation_largest_first",
|
24 |
+
"DSATUR",
|
25 |
+
]
|
26 |
+
|
27 |
+
# List of strategies where interchange=True results in an error
|
28 |
+
INTERCHANGE_INVALID = ["independent_set", "saturation_largest_first", "DSATUR"]
|
29 |
+
|
30 |
+
|
31 |
+
class TestColoring:
|
32 |
+
def test_basic_cases(self):
|
33 |
+
def check_basic_case(graph_func, n_nodes, strategy, interchange):
|
34 |
+
graph = graph_func()
|
35 |
+
coloring = nx.coloring.greedy_color(
|
36 |
+
graph, strategy=strategy, interchange=interchange
|
37 |
+
)
|
38 |
+
assert verify_length(coloring, n_nodes)
|
39 |
+
assert verify_coloring(graph, coloring)
|
40 |
+
|
41 |
+
for graph_func, n_nodes in BASIC_TEST_CASES.items():
|
42 |
+
for interchange in [True, False]:
|
43 |
+
for strategy in ALL_STRATEGIES:
|
44 |
+
check_basic_case(graph_func, n_nodes, strategy, False)
|
45 |
+
if strategy not in INTERCHANGE_INVALID:
|
46 |
+
check_basic_case(graph_func, n_nodes, strategy, True)
|
47 |
+
|
48 |
+
def test_special_cases(self):
|
49 |
+
def check_special_case(strategy, graph_func, interchange, colors):
|
50 |
+
graph = graph_func()
|
51 |
+
coloring = nx.coloring.greedy_color(
|
52 |
+
graph, strategy=strategy, interchange=interchange
|
53 |
+
)
|
54 |
+
if not hasattr(colors, "__len__"):
|
55 |
+
colors = [colors]
|
56 |
+
assert any(verify_length(coloring, n_colors) for n_colors in colors)
|
57 |
+
assert verify_coloring(graph, coloring)
|
58 |
+
|
59 |
+
for strategy, arglist in SPECIAL_TEST_CASES.items():
|
60 |
+
for args in arglist:
|
61 |
+
check_special_case(strategy, args[0], args[1], args[2])
|
62 |
+
|
63 |
+
def test_interchange_invalid(self):
|
64 |
+
graph = one_node_graph()
|
65 |
+
for strategy in INTERCHANGE_INVALID:
|
66 |
+
pytest.raises(
|
67 |
+
nx.NetworkXPointlessConcept,
|
68 |
+
nx.coloring.greedy_color,
|
69 |
+
graph,
|
70 |
+
strategy=strategy,
|
71 |
+
interchange=True,
|
72 |
+
)
|
73 |
+
|
74 |
+
def test_bad_inputs(self):
|
75 |
+
graph = one_node_graph()
|
76 |
+
pytest.raises(
|
77 |
+
nx.NetworkXError,
|
78 |
+
nx.coloring.greedy_color,
|
79 |
+
graph,
|
80 |
+
strategy="invalid strategy",
|
81 |
+
)
|
82 |
+
|
83 |
+
def test_strategy_as_function(self):
|
84 |
+
graph = lf_shc()
|
85 |
+
colors_1 = nx.coloring.greedy_color(graph, "largest_first")
|
86 |
+
colors_2 = nx.coloring.greedy_color(graph, nx.coloring.strategy_largest_first)
|
87 |
+
assert colors_1 == colors_2
|
88 |
+
|
89 |
+
def test_seed_argument(self):
|
90 |
+
graph = lf_shc()
|
91 |
+
rs = nx.coloring.strategy_random_sequential
|
92 |
+
c1 = nx.coloring.greedy_color(graph, lambda g, c: rs(g, c, seed=1))
|
93 |
+
for u, v in graph.edges:
|
94 |
+
assert c1[u] != c1[v]
|
95 |
+
|
96 |
+
def test_is_coloring(self):
|
97 |
+
G = nx.Graph()
|
98 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
99 |
+
coloring = {0: 0, 1: 1, 2: 0}
|
100 |
+
assert is_coloring(G, coloring)
|
101 |
+
|
102 |
+
coloring[0] = 1
|
103 |
+
assert not is_coloring(G, coloring)
|
104 |
+
assert not is_equitable(G, coloring)
|
105 |
+
|
106 |
+
def test_is_equitable(self):
|
107 |
+
G = nx.Graph()
|
108 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
109 |
+
coloring = {0: 0, 1: 1, 2: 0}
|
110 |
+
assert is_equitable(G, coloring)
|
111 |
+
|
112 |
+
G.add_edges_from([(2, 3), (2, 4), (2, 5)])
|
113 |
+
coloring[3] = 1
|
114 |
+
coloring[4] = 1
|
115 |
+
coloring[5] = 1
|
116 |
+
assert is_coloring(G, coloring)
|
117 |
+
assert not is_equitable(G, coloring)
|
118 |
+
|
119 |
+
def test_num_colors(self):
|
120 |
+
G = nx.Graph()
|
121 |
+
G.add_edges_from([(0, 1), (0, 2), (0, 3)])
|
122 |
+
pytest.raises(nx.NetworkXAlgorithmError, nx.coloring.equitable_color, G, 2)
|
123 |
+
|
124 |
+
def test_equitable_color(self):
|
125 |
+
G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
|
126 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
127 |
+
assert is_equitable(G, coloring)
|
128 |
+
|
129 |
+
def test_equitable_color_empty(self):
|
130 |
+
G = nx.empty_graph()
|
131 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
132 |
+
assert is_equitable(G, coloring)
|
133 |
+
|
134 |
+
def test_equitable_color_large(self):
|
135 |
+
G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
|
136 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
137 |
+
assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
|
138 |
+
|
139 |
+
def test_case_V_plus_not_in_A_cal(self):
|
140 |
+
# Hand crafted case to avoid the easy case.
|
141 |
+
L = {
|
142 |
+
0: [2, 5],
|
143 |
+
1: [3, 4],
|
144 |
+
2: [0, 8],
|
145 |
+
3: [1, 7],
|
146 |
+
4: [1, 6],
|
147 |
+
5: [0, 6],
|
148 |
+
6: [4, 5],
|
149 |
+
7: [3],
|
150 |
+
8: [2],
|
151 |
+
}
|
152 |
+
|
153 |
+
F = {
|
154 |
+
# Color 0
|
155 |
+
0: 0,
|
156 |
+
1: 0,
|
157 |
+
# Color 1
|
158 |
+
2: 1,
|
159 |
+
3: 1,
|
160 |
+
4: 1,
|
161 |
+
5: 1,
|
162 |
+
# Color 2
|
163 |
+
6: 2,
|
164 |
+
7: 2,
|
165 |
+
8: 2,
|
166 |
+
}
|
167 |
+
|
168 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
169 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
170 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
171 |
+
|
172 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
173 |
+
V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
|
174 |
+
)
|
175 |
+
check_state(L=L, N=N, H=H, F=F, C=C)
|
176 |
+
|
177 |
+
def test_cast_no_solo(self):
|
178 |
+
L = {
|
179 |
+
0: [8, 9],
|
180 |
+
1: [10, 11],
|
181 |
+
2: [8],
|
182 |
+
3: [9],
|
183 |
+
4: [10, 11],
|
184 |
+
5: [8],
|
185 |
+
6: [9],
|
186 |
+
7: [10, 11],
|
187 |
+
8: [0, 2, 5],
|
188 |
+
9: [0, 3, 6],
|
189 |
+
10: [1, 4, 7],
|
190 |
+
11: [1, 4, 7],
|
191 |
+
}
|
192 |
+
|
193 |
+
F = {0: 0, 1: 0, 2: 2, 3: 2, 4: 2, 5: 3, 6: 3, 7: 3, 8: 1, 9: 1, 10: 1, 11: 1}
|
194 |
+
|
195 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
196 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
197 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
198 |
+
|
199 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
200 |
+
V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
|
201 |
+
)
|
202 |
+
check_state(L=L, N=N, H=H, F=F, C=C)
|
203 |
+
|
204 |
+
def test_hard_prob(self):
|
205 |
+
# Tests for two levels of recursion.
|
206 |
+
num_colors, s = 5, 5
|
207 |
+
|
208 |
+
G = nx.Graph()
|
209 |
+
G.add_edges_from(
|
210 |
+
[
|
211 |
+
(0, 10),
|
212 |
+
(0, 11),
|
213 |
+
(0, 12),
|
214 |
+
(0, 23),
|
215 |
+
(10, 4),
|
216 |
+
(10, 9),
|
217 |
+
(10, 20),
|
218 |
+
(11, 4),
|
219 |
+
(11, 8),
|
220 |
+
(11, 16),
|
221 |
+
(12, 9),
|
222 |
+
(12, 22),
|
223 |
+
(12, 23),
|
224 |
+
(23, 7),
|
225 |
+
(1, 17),
|
226 |
+
(1, 18),
|
227 |
+
(1, 19),
|
228 |
+
(1, 24),
|
229 |
+
(17, 5),
|
230 |
+
(17, 13),
|
231 |
+
(17, 22),
|
232 |
+
(18, 5),
|
233 |
+
(19, 5),
|
234 |
+
(19, 6),
|
235 |
+
(19, 8),
|
236 |
+
(24, 7),
|
237 |
+
(24, 16),
|
238 |
+
(2, 4),
|
239 |
+
(2, 13),
|
240 |
+
(2, 14),
|
241 |
+
(2, 15),
|
242 |
+
(4, 6),
|
243 |
+
(13, 5),
|
244 |
+
(13, 21),
|
245 |
+
(14, 6),
|
246 |
+
(14, 15),
|
247 |
+
(15, 6),
|
248 |
+
(15, 21),
|
249 |
+
(3, 16),
|
250 |
+
(3, 20),
|
251 |
+
(3, 21),
|
252 |
+
(3, 22),
|
253 |
+
(16, 8),
|
254 |
+
(20, 8),
|
255 |
+
(21, 9),
|
256 |
+
(22, 7),
|
257 |
+
]
|
258 |
+
)
|
259 |
+
F = {node: node // s for node in range(num_colors * s)}
|
260 |
+
F[s - 1] = num_colors - 1
|
261 |
+
|
262 |
+
params = make_params_from_graph(G=G, F=F)
|
263 |
+
|
264 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
265 |
+
V_minus=0, V_plus=num_colors - 1, **params
|
266 |
+
)
|
267 |
+
check_state(**params)
|
268 |
+
|
269 |
+
def test_hardest_prob(self):
|
270 |
+
# Tests for two levels of recursion.
|
271 |
+
num_colors, s = 10, 4
|
272 |
+
|
273 |
+
G = nx.Graph()
|
274 |
+
G.add_edges_from(
|
275 |
+
[
|
276 |
+
(0, 19),
|
277 |
+
(0, 24),
|
278 |
+
(0, 29),
|
279 |
+
(0, 30),
|
280 |
+
(0, 35),
|
281 |
+
(19, 3),
|
282 |
+
(19, 7),
|
283 |
+
(19, 9),
|
284 |
+
(19, 15),
|
285 |
+
(19, 21),
|
286 |
+
(19, 24),
|
287 |
+
(19, 30),
|
288 |
+
(19, 38),
|
289 |
+
(24, 5),
|
290 |
+
(24, 11),
|
291 |
+
(24, 13),
|
292 |
+
(24, 20),
|
293 |
+
(24, 30),
|
294 |
+
(24, 37),
|
295 |
+
(24, 38),
|
296 |
+
(29, 6),
|
297 |
+
(29, 10),
|
298 |
+
(29, 13),
|
299 |
+
(29, 15),
|
300 |
+
(29, 16),
|
301 |
+
(29, 17),
|
302 |
+
(29, 20),
|
303 |
+
(29, 26),
|
304 |
+
(30, 6),
|
305 |
+
(30, 10),
|
306 |
+
(30, 15),
|
307 |
+
(30, 22),
|
308 |
+
(30, 23),
|
309 |
+
(30, 39),
|
310 |
+
(35, 6),
|
311 |
+
(35, 9),
|
312 |
+
(35, 14),
|
313 |
+
(35, 18),
|
314 |
+
(35, 22),
|
315 |
+
(35, 23),
|
316 |
+
(35, 25),
|
317 |
+
(35, 27),
|
318 |
+
(1, 20),
|
319 |
+
(1, 26),
|
320 |
+
(1, 31),
|
321 |
+
(1, 34),
|
322 |
+
(1, 38),
|
323 |
+
(20, 4),
|
324 |
+
(20, 8),
|
325 |
+
(20, 14),
|
326 |
+
(20, 18),
|
327 |
+
(20, 28),
|
328 |
+
(20, 33),
|
329 |
+
(26, 7),
|
330 |
+
(26, 10),
|
331 |
+
(26, 14),
|
332 |
+
(26, 18),
|
333 |
+
(26, 21),
|
334 |
+
(26, 32),
|
335 |
+
(26, 39),
|
336 |
+
(31, 5),
|
337 |
+
(31, 8),
|
338 |
+
(31, 13),
|
339 |
+
(31, 16),
|
340 |
+
(31, 17),
|
341 |
+
(31, 21),
|
342 |
+
(31, 25),
|
343 |
+
(31, 27),
|
344 |
+
(34, 7),
|
345 |
+
(34, 8),
|
346 |
+
(34, 13),
|
347 |
+
(34, 18),
|
348 |
+
(34, 22),
|
349 |
+
(34, 23),
|
350 |
+
(34, 25),
|
351 |
+
(34, 27),
|
352 |
+
(38, 4),
|
353 |
+
(38, 9),
|
354 |
+
(38, 12),
|
355 |
+
(38, 14),
|
356 |
+
(38, 21),
|
357 |
+
(38, 27),
|
358 |
+
(2, 3),
|
359 |
+
(2, 18),
|
360 |
+
(2, 21),
|
361 |
+
(2, 28),
|
362 |
+
(2, 32),
|
363 |
+
(2, 33),
|
364 |
+
(2, 36),
|
365 |
+
(2, 37),
|
366 |
+
(2, 39),
|
367 |
+
(3, 5),
|
368 |
+
(3, 9),
|
369 |
+
(3, 13),
|
370 |
+
(3, 22),
|
371 |
+
(3, 23),
|
372 |
+
(3, 25),
|
373 |
+
(3, 27),
|
374 |
+
(18, 6),
|
375 |
+
(18, 11),
|
376 |
+
(18, 15),
|
377 |
+
(18, 39),
|
378 |
+
(21, 4),
|
379 |
+
(21, 10),
|
380 |
+
(21, 14),
|
381 |
+
(21, 36),
|
382 |
+
(28, 6),
|
383 |
+
(28, 10),
|
384 |
+
(28, 14),
|
385 |
+
(28, 16),
|
386 |
+
(28, 17),
|
387 |
+
(28, 25),
|
388 |
+
(28, 27),
|
389 |
+
(32, 5),
|
390 |
+
(32, 10),
|
391 |
+
(32, 12),
|
392 |
+
(32, 16),
|
393 |
+
(32, 17),
|
394 |
+
(32, 22),
|
395 |
+
(32, 23),
|
396 |
+
(33, 7),
|
397 |
+
(33, 10),
|
398 |
+
(33, 12),
|
399 |
+
(33, 16),
|
400 |
+
(33, 17),
|
401 |
+
(33, 25),
|
402 |
+
(33, 27),
|
403 |
+
(36, 5),
|
404 |
+
(36, 8),
|
405 |
+
(36, 15),
|
406 |
+
(36, 16),
|
407 |
+
(36, 17),
|
408 |
+
(36, 25),
|
409 |
+
(36, 27),
|
410 |
+
(37, 5),
|
411 |
+
(37, 11),
|
412 |
+
(37, 15),
|
413 |
+
(37, 16),
|
414 |
+
(37, 17),
|
415 |
+
(37, 22),
|
416 |
+
(37, 23),
|
417 |
+
(39, 7),
|
418 |
+
(39, 8),
|
419 |
+
(39, 15),
|
420 |
+
(39, 22),
|
421 |
+
(39, 23),
|
422 |
+
]
|
423 |
+
)
|
424 |
+
F = {node: node // s for node in range(num_colors * s)}
|
425 |
+
F[s - 1] = num_colors - 1 # V- = 0, V+ = num_colors - 1
|
426 |
+
|
427 |
+
params = make_params_from_graph(G=G, F=F)
|
428 |
+
|
429 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
430 |
+
V_minus=0, V_plus=num_colors - 1, **params
|
431 |
+
)
|
432 |
+
check_state(**params)
|
433 |
+
|
434 |
+
def test_strategy_saturation_largest_first(self):
|
435 |
+
def color_remaining_nodes(
|
436 |
+
G,
|
437 |
+
colored_nodes,
|
438 |
+
full_color_assignment=None,
|
439 |
+
nodes_to_add_between_calls=1,
|
440 |
+
):
|
441 |
+
color_assignments = []
|
442 |
+
aux_colored_nodes = colored_nodes.copy()
|
443 |
+
|
444 |
+
node_iterator = nx.algorithms.coloring.greedy_coloring.strategy_saturation_largest_first(
|
445 |
+
G, aux_colored_nodes
|
446 |
+
)
|
447 |
+
|
448 |
+
for u in node_iterator:
|
449 |
+
# Set to keep track of colors of neighbors
|
450 |
+
nbr_colors = {
|
451 |
+
aux_colored_nodes[v] for v in G[u] if v in aux_colored_nodes
|
452 |
+
}
|
453 |
+
# Find the first unused color.
|
454 |
+
for color in itertools.count():
|
455 |
+
if color not in nbr_colors:
|
456 |
+
break
|
457 |
+
aux_colored_nodes[u] = color
|
458 |
+
color_assignments.append((u, color))
|
459 |
+
|
460 |
+
# Color nodes between iterations
|
461 |
+
for i in range(nodes_to_add_between_calls - 1):
|
462 |
+
if not len(color_assignments) + len(colored_nodes) >= len(
|
463 |
+
full_color_assignment
|
464 |
+
):
|
465 |
+
full_color_assignment_node, color = full_color_assignment[
|
466 |
+
len(color_assignments) + len(colored_nodes)
|
467 |
+
]
|
468 |
+
|
469 |
+
# Assign the new color to the current node.
|
470 |
+
aux_colored_nodes[full_color_assignment_node] = color
|
471 |
+
color_assignments.append((full_color_assignment_node, color))
|
472 |
+
|
473 |
+
return color_assignments, aux_colored_nodes
|
474 |
+
|
475 |
+
for G, _, _ in SPECIAL_TEST_CASES["saturation_largest_first"]:
|
476 |
+
G = G()
|
477 |
+
|
478 |
+
# Check that function still works when nodes are colored between iterations
|
479 |
+
for nodes_to_add_between_calls in range(1, 5):
|
480 |
+
# Get a full color assignment, (including the order in which nodes were colored)
|
481 |
+
colored_nodes = {}
|
482 |
+
full_color_assignment, full_colored_nodes = color_remaining_nodes(
|
483 |
+
G, colored_nodes
|
484 |
+
)
|
485 |
+
|
486 |
+
# For each node in the color assignment, add it to colored_nodes and re-run the function
|
487 |
+
for ind, (node, color) in enumerate(full_color_assignment):
|
488 |
+
colored_nodes[node] = color
|
489 |
+
|
490 |
+
(
|
491 |
+
partial_color_assignment,
|
492 |
+
partial_colored_nodes,
|
493 |
+
) = color_remaining_nodes(
|
494 |
+
G,
|
495 |
+
colored_nodes,
|
496 |
+
full_color_assignment=full_color_assignment,
|
497 |
+
nodes_to_add_between_calls=nodes_to_add_between_calls,
|
498 |
+
)
|
499 |
+
|
500 |
+
# Check that the color assignment and order of remaining nodes are the same
|
501 |
+
assert full_color_assignment[ind + 1 :] == partial_color_assignment
|
502 |
+
assert full_colored_nodes == partial_colored_nodes
|
503 |
+
|
504 |
+
|
505 |
+
# ############################ Utility functions ############################
|
506 |
+
def verify_coloring(graph, coloring):
|
507 |
+
for node in graph.nodes():
|
508 |
+
if node not in coloring:
|
509 |
+
return False
|
510 |
+
|
511 |
+
color = coloring[node]
|
512 |
+
for neighbor in graph.neighbors(node):
|
513 |
+
if coloring[neighbor] == color:
|
514 |
+
return False
|
515 |
+
|
516 |
+
return True
|
517 |
+
|
518 |
+
|
519 |
+
def verify_length(coloring, expected):
|
520 |
+
coloring = dict_to_sets(coloring)
|
521 |
+
return len(coloring) == expected
|
522 |
+
|
523 |
+
|
524 |
+
def dict_to_sets(colors):
|
525 |
+
if len(colors) == 0:
|
526 |
+
return []
|
527 |
+
|
528 |
+
k = max(colors.values()) + 1
|
529 |
+
sets = [set() for _ in range(k)]
|
530 |
+
|
531 |
+
for node, color in colors.items():
|
532 |
+
sets[color].add(node)
|
533 |
+
|
534 |
+
return sets
|
535 |
+
|
536 |
+
|
537 |
+
# ############################ Graph Generation ############################
|
538 |
+
|
539 |
+
|
540 |
+
def empty_graph():
|
541 |
+
return nx.Graph()
|
542 |
+
|
543 |
+
|
544 |
+
def one_node_graph():
|
545 |
+
graph = nx.Graph()
|
546 |
+
graph.add_nodes_from([1])
|
547 |
+
return graph
|
548 |
+
|
549 |
+
|
550 |
+
def two_node_graph():
|
551 |
+
graph = nx.Graph()
|
552 |
+
graph.add_nodes_from([1, 2])
|
553 |
+
graph.add_edges_from([(1, 2)])
|
554 |
+
return graph
|
555 |
+
|
556 |
+
|
557 |
+
def three_node_clique():
|
558 |
+
graph = nx.Graph()
|
559 |
+
graph.add_nodes_from([1, 2, 3])
|
560 |
+
graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
|
561 |
+
return graph
|
562 |
+
|
563 |
+
|
564 |
+
def disconnected():
|
565 |
+
graph = nx.Graph()
|
566 |
+
graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
|
567 |
+
return graph
|
568 |
+
|
569 |
+
|
570 |
+
def rs_shc():
|
571 |
+
graph = nx.Graph()
|
572 |
+
graph.add_nodes_from([1, 2, 3, 4])
|
573 |
+
graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
|
574 |
+
return graph
|
575 |
+
|
576 |
+
|
577 |
+
def slf_shc():
|
578 |
+
graph = nx.Graph()
|
579 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
580 |
+
graph.add_edges_from(
|
581 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
|
582 |
+
)
|
583 |
+
return graph
|
584 |
+
|
585 |
+
|
586 |
+
def slf_hc():
|
587 |
+
graph = nx.Graph()
|
588 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
|
589 |
+
graph.add_edges_from(
|
590 |
+
[
|
591 |
+
(1, 2),
|
592 |
+
(1, 3),
|
593 |
+
(1, 4),
|
594 |
+
(1, 5),
|
595 |
+
(2, 3),
|
596 |
+
(2, 4),
|
597 |
+
(2, 6),
|
598 |
+
(5, 7),
|
599 |
+
(5, 8),
|
600 |
+
(6, 7),
|
601 |
+
(6, 8),
|
602 |
+
(7, 8),
|
603 |
+
]
|
604 |
+
)
|
605 |
+
return graph
|
606 |
+
|
607 |
+
|
608 |
+
def lf_shc():
|
609 |
+
graph = nx.Graph()
|
610 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
611 |
+
graph.add_edges_from([(6, 1), (1, 4), (4, 3), (3, 2), (2, 5)])
|
612 |
+
return graph
|
613 |
+
|
614 |
+
|
615 |
+
def lf_hc():
|
616 |
+
graph = nx.Graph()
|
617 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
618 |
+
graph.add_edges_from(
|
619 |
+
[
|
620 |
+
(1, 7),
|
621 |
+
(1, 6),
|
622 |
+
(1, 3),
|
623 |
+
(1, 4),
|
624 |
+
(7, 2),
|
625 |
+
(2, 6),
|
626 |
+
(2, 3),
|
627 |
+
(2, 5),
|
628 |
+
(5, 3),
|
629 |
+
(5, 4),
|
630 |
+
(4, 3),
|
631 |
+
]
|
632 |
+
)
|
633 |
+
return graph
|
634 |
+
|
635 |
+
|
636 |
+
def sl_shc():
|
637 |
+
graph = nx.Graph()
|
638 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
639 |
+
graph.add_edges_from(
|
640 |
+
[(1, 2), (1, 3), (2, 3), (1, 4), (2, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
|
641 |
+
)
|
642 |
+
return graph
|
643 |
+
|
644 |
+
|
645 |
+
def sl_hc():
|
646 |
+
graph = nx.Graph()
|
647 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
|
648 |
+
graph.add_edges_from(
|
649 |
+
[
|
650 |
+
(1, 2),
|
651 |
+
(1, 3),
|
652 |
+
(1, 5),
|
653 |
+
(1, 7),
|
654 |
+
(2, 3),
|
655 |
+
(2, 4),
|
656 |
+
(2, 8),
|
657 |
+
(8, 4),
|
658 |
+
(8, 6),
|
659 |
+
(8, 7),
|
660 |
+
(7, 5),
|
661 |
+
(7, 6),
|
662 |
+
(3, 4),
|
663 |
+
(4, 6),
|
664 |
+
(6, 5),
|
665 |
+
(5, 3),
|
666 |
+
]
|
667 |
+
)
|
668 |
+
return graph
|
669 |
+
|
670 |
+
|
671 |
+
def gis_shc():
|
672 |
+
graph = nx.Graph()
|
673 |
+
graph.add_nodes_from([1, 2, 3, 4])
|
674 |
+
graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
|
675 |
+
return graph
|
676 |
+
|
677 |
+
|
678 |
+
def gis_hc():
|
679 |
+
graph = nx.Graph()
|
680 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
681 |
+
graph.add_edges_from([(1, 5), (2, 5), (3, 6), (4, 6), (5, 6)])
|
682 |
+
return graph
|
683 |
+
|
684 |
+
|
685 |
+
def cs_shc():
|
686 |
+
graph = nx.Graph()
|
687 |
+
graph.add_nodes_from([1, 2, 3, 4, 5])
|
688 |
+
graph.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)])
|
689 |
+
return graph
|
690 |
+
|
691 |
+
|
692 |
+
def rsi_shc():
|
693 |
+
graph = nx.Graph()
|
694 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
695 |
+
graph.add_edges_from(
|
696 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (3, 4), (4, 5), (4, 6), (5, 6)]
|
697 |
+
)
|
698 |
+
return graph
|
699 |
+
|
700 |
+
|
701 |
+
def lfi_shc():
|
702 |
+
graph = nx.Graph()
|
703 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
704 |
+
graph.add_edges_from(
|
705 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
|
706 |
+
)
|
707 |
+
return graph
|
708 |
+
|
709 |
+
|
710 |
+
def lfi_hc():
|
711 |
+
graph = nx.Graph()
|
712 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
713 |
+
graph.add_edges_from(
|
714 |
+
[
|
715 |
+
(1, 2),
|
716 |
+
(1, 5),
|
717 |
+
(1, 6),
|
718 |
+
(1, 7),
|
719 |
+
(2, 3),
|
720 |
+
(2, 8),
|
721 |
+
(2, 9),
|
722 |
+
(3, 4),
|
723 |
+
(3, 8),
|
724 |
+
(3, 9),
|
725 |
+
(4, 5),
|
726 |
+
(4, 6),
|
727 |
+
(4, 7),
|
728 |
+
(5, 6),
|
729 |
+
]
|
730 |
+
)
|
731 |
+
return graph
|
732 |
+
|
733 |
+
|
734 |
+
def sli_shc():
|
735 |
+
graph = nx.Graph()
|
736 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
737 |
+
graph.add_edges_from(
|
738 |
+
[
|
739 |
+
(1, 2),
|
740 |
+
(1, 3),
|
741 |
+
(1, 5),
|
742 |
+
(1, 7),
|
743 |
+
(2, 3),
|
744 |
+
(2, 6),
|
745 |
+
(3, 4),
|
746 |
+
(4, 5),
|
747 |
+
(4, 6),
|
748 |
+
(5, 7),
|
749 |
+
(6, 7),
|
750 |
+
]
|
751 |
+
)
|
752 |
+
return graph
|
753 |
+
|
754 |
+
|
755 |
+
def sli_hc():
|
756 |
+
graph = nx.Graph()
|
757 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
758 |
+
graph.add_edges_from(
|
759 |
+
[
|
760 |
+
(1, 2),
|
761 |
+
(1, 3),
|
762 |
+
(1, 4),
|
763 |
+
(1, 5),
|
764 |
+
(2, 3),
|
765 |
+
(2, 7),
|
766 |
+
(2, 8),
|
767 |
+
(2, 9),
|
768 |
+
(3, 6),
|
769 |
+
(3, 7),
|
770 |
+
(3, 9),
|
771 |
+
(4, 5),
|
772 |
+
(4, 6),
|
773 |
+
(4, 8),
|
774 |
+
(4, 9),
|
775 |
+
(5, 6),
|
776 |
+
(5, 7),
|
777 |
+
(5, 8),
|
778 |
+
(6, 7),
|
779 |
+
(6, 9),
|
780 |
+
(7, 8),
|
781 |
+
(8, 9),
|
782 |
+
]
|
783 |
+
)
|
784 |
+
return graph
|
785 |
+
|
786 |
+
|
787 |
+
# --------------------------------------------------------------------------
|
788 |
+
# Basic tests for all strategies
|
789 |
+
# For each basic graph function, specify the number of expected colors.
|
790 |
+
BASIC_TEST_CASES = {
|
791 |
+
empty_graph: 0,
|
792 |
+
one_node_graph: 1,
|
793 |
+
two_node_graph: 2,
|
794 |
+
disconnected: 2,
|
795 |
+
three_node_clique: 3,
|
796 |
+
}
|
797 |
+
|
798 |
+
|
799 |
+
# --------------------------------------------------------------------------
|
800 |
+
# Special test cases. Each strategy has a list of tuples of the form
|
801 |
+
# (graph function, interchange, valid # of colors)
|
802 |
+
SPECIAL_TEST_CASES = {
|
803 |
+
"random_sequential": [
|
804 |
+
(rs_shc, False, (2, 3)),
|
805 |
+
(rs_shc, True, 2),
|
806 |
+
(rsi_shc, True, (3, 4)),
|
807 |
+
],
|
808 |
+
"saturation_largest_first": [(slf_shc, False, (3, 4)), (slf_hc, False, 4)],
|
809 |
+
"largest_first": [
|
810 |
+
(lf_shc, False, (2, 3)),
|
811 |
+
(lf_hc, False, 4),
|
812 |
+
(lf_shc, True, 2),
|
813 |
+
(lf_hc, True, 3),
|
814 |
+
(lfi_shc, True, (3, 4)),
|
815 |
+
(lfi_hc, True, 4),
|
816 |
+
],
|
817 |
+
"smallest_last": [
|
818 |
+
(sl_shc, False, (3, 4)),
|
819 |
+
(sl_hc, False, 5),
|
820 |
+
(sl_shc, True, 3),
|
821 |
+
(sl_hc, True, 4),
|
822 |
+
(sli_shc, True, (3, 4)),
|
823 |
+
(sli_hc, True, 5),
|
824 |
+
],
|
825 |
+
"independent_set": [(gis_shc, False, (2, 3)), (gis_hc, False, 3)],
|
826 |
+
"connected_sequential": [(cs_shc, False, (3, 4)), (cs_shc, True, 3)],
|
827 |
+
"connected_sequential_dfs": [(cs_shc, False, (3, 4))],
|
828 |
+
}
|
829 |
+
|
830 |
+
|
831 |
+
# --------------------------------------------------------------------------
|
832 |
+
# Helper functions to test
|
833 |
+
# (graph function, interchange, valid # of colors)
|
834 |
+
|
835 |
+
|
836 |
+
def check_state(L, N, H, F, C):
|
837 |
+
s = len(C[0])
|
838 |
+
num_colors = len(C.keys())
|
839 |
+
|
840 |
+
assert all(u in L[v] for u in L for v in L[u])
|
841 |
+
assert all(F[u] != F[v] for u in L for v in L[u])
|
842 |
+
assert all(len(L[u]) < num_colors for u in L)
|
843 |
+
assert all(len(C[x]) == s for x in C)
|
844 |
+
assert all(H[(c1, c2)] >= 0 for c1 in C for c2 in C)
|
845 |
+
assert all(N[(u, F[u])] == 0 for u in F)
|
846 |
+
|
847 |
+
|
848 |
+
def max_degree(G):
|
849 |
+
"""Get the maximum degree of any node in G."""
|
850 |
+
return max(G.degree(node) for node in G.nodes) if len(G.nodes) > 0 else 0
|
851 |
+
|
852 |
+
|
853 |
+
def make_params_from_graph(G, F):
|
854 |
+
"""Returns {N, L, H, C} from the given graph."""
|
855 |
+
num_nodes = len(G)
|
856 |
+
L = {u: [] for u in range(num_nodes)}
|
857 |
+
for u, v in G.edges:
|
858 |
+
L[u].append(v)
|
859 |
+
L[v].append(u)
|
860 |
+
|
861 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
862 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
863 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
864 |
+
|
865 |
+
return {"N": N, "F": F, "C": C, "H": H, "L": L}
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/__pycache__/test_utils.cpython-310.pyc
ADDED
Binary file (1.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/test_kernighan_lin.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.community.kernighan_lin`
|
2 |
+
module.
|
3 |
+
"""
|
4 |
+
from itertools import permutations
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
from networkx.algorithms.community import kernighan_lin_bisection
|
10 |
+
|
11 |
+
|
12 |
+
def assert_partition_equal(x, y):
|
13 |
+
assert set(map(frozenset, x)) == set(map(frozenset, y))
|
14 |
+
|
15 |
+
|
16 |
+
def test_partition():
|
17 |
+
G = nx.barbell_graph(3, 0)
|
18 |
+
C = kernighan_lin_bisection(G)
|
19 |
+
assert_partition_equal(C, [{0, 1, 2}, {3, 4, 5}])
|
20 |
+
|
21 |
+
|
22 |
+
def test_partition_argument():
|
23 |
+
G = nx.barbell_graph(3, 0)
|
24 |
+
partition = [{0, 1, 2}, {3, 4, 5}]
|
25 |
+
C = kernighan_lin_bisection(G, partition)
|
26 |
+
assert_partition_equal(C, partition)
|
27 |
+
|
28 |
+
|
29 |
+
def test_partition_argument_non_integer_nodes():
|
30 |
+
G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
|
31 |
+
partition = ({"A", "B"}, {"C", "D"})
|
32 |
+
C = kernighan_lin_bisection(G, partition)
|
33 |
+
assert_partition_equal(C, partition)
|
34 |
+
|
35 |
+
|
36 |
+
def test_seed_argument():
|
37 |
+
G = nx.barbell_graph(3, 0)
|
38 |
+
C = kernighan_lin_bisection(G, seed=1)
|
39 |
+
assert_partition_equal(C, [{0, 1, 2}, {3, 4, 5}])
|
40 |
+
|
41 |
+
|
42 |
+
def test_non_disjoint_partition():
|
43 |
+
with pytest.raises(nx.NetworkXError):
|
44 |
+
G = nx.barbell_graph(3, 0)
|
45 |
+
partition = ({0, 1, 2}, {2, 3, 4, 5})
|
46 |
+
kernighan_lin_bisection(G, partition)
|
47 |
+
|
48 |
+
|
49 |
+
def test_too_many_blocks():
|
50 |
+
with pytest.raises(nx.NetworkXError):
|
51 |
+
G = nx.barbell_graph(3, 0)
|
52 |
+
partition = ({0, 1}, {2}, {3, 4, 5})
|
53 |
+
kernighan_lin_bisection(G, partition)
|
54 |
+
|
55 |
+
|
56 |
+
def test_multigraph():
|
57 |
+
G = nx.cycle_graph(4)
|
58 |
+
M = nx.MultiGraph(G.edges())
|
59 |
+
M.add_edges_from(G.edges())
|
60 |
+
M.remove_edge(1, 2)
|
61 |
+
for labels in permutations(range(4)):
|
62 |
+
mapping = dict(zip(M, labels))
|
63 |
+
A, B = kernighan_lin_bisection(nx.relabel_nodes(M, mapping), seed=0)
|
64 |
+
assert_partition_equal(
|
65 |
+
[A, B], [{mapping[0], mapping[1]}, {mapping[2], mapping[3]}]
|
66 |
+
)
|
67 |
+
|
68 |
+
|
69 |
+
def test_max_iter_argument():
|
70 |
+
G = nx.Graph(
|
71 |
+
[
|
72 |
+
("A", "B", {"weight": 1}),
|
73 |
+
("A", "C", {"weight": 2}),
|
74 |
+
("A", "D", {"weight": 3}),
|
75 |
+
("A", "E", {"weight": 2}),
|
76 |
+
("A", "F", {"weight": 4}),
|
77 |
+
("B", "C", {"weight": 1}),
|
78 |
+
("B", "D", {"weight": 4}),
|
79 |
+
("B", "E", {"weight": 2}),
|
80 |
+
("B", "F", {"weight": 1}),
|
81 |
+
("C", "D", {"weight": 3}),
|
82 |
+
("C", "E", {"weight": 2}),
|
83 |
+
("C", "F", {"weight": 1}),
|
84 |
+
("D", "E", {"weight": 4}),
|
85 |
+
("D", "F", {"weight": 3}),
|
86 |
+
("E", "F", {"weight": 2}),
|
87 |
+
]
|
88 |
+
)
|
89 |
+
partition = ({"A", "B", "C"}, {"D", "E", "F"})
|
90 |
+
C = kernighan_lin_bisection(G, partition, max_iter=1)
|
91 |
+
assert_partition_equal(C, ({"A", "F", "C"}, {"D", "E", "B"}))
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/test_quality.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.community.quality`
|
2 |
+
module.
|
3 |
+
|
4 |
+
"""
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
from networkx import barbell_graph
|
9 |
+
from networkx.algorithms.community import modularity, partition_quality
|
10 |
+
from networkx.algorithms.community.quality import inter_community_edges
|
11 |
+
|
12 |
+
|
13 |
+
class TestPerformance:
|
14 |
+
"""Unit tests for the :func:`performance` function."""
|
15 |
+
|
16 |
+
def test_bad_partition(self):
|
17 |
+
"""Tests that a poor partition has a low performance measure."""
|
18 |
+
G = barbell_graph(3, 0)
|
19 |
+
partition = [{0, 1, 4}, {2, 3, 5}]
|
20 |
+
assert 8 / 15 == pytest.approx(partition_quality(G, partition)[1], abs=1e-7)
|
21 |
+
|
22 |
+
def test_good_partition(self):
|
23 |
+
"""Tests that a good partition has a high performance measure."""
|
24 |
+
G = barbell_graph(3, 0)
|
25 |
+
partition = [{0, 1, 2}, {3, 4, 5}]
|
26 |
+
assert 14 / 15 == pytest.approx(partition_quality(G, partition)[1], abs=1e-7)
|
27 |
+
|
28 |
+
|
29 |
+
class TestCoverage:
|
30 |
+
"""Unit tests for the :func:`coverage` function."""
|
31 |
+
|
32 |
+
def test_bad_partition(self):
|
33 |
+
"""Tests that a poor partition has a low coverage measure."""
|
34 |
+
G = barbell_graph(3, 0)
|
35 |
+
partition = [{0, 1, 4}, {2, 3, 5}]
|
36 |
+
assert 3 / 7 == pytest.approx(partition_quality(G, partition)[0], abs=1e-7)
|
37 |
+
|
38 |
+
def test_good_partition(self):
|
39 |
+
"""Tests that a good partition has a high coverage measure."""
|
40 |
+
G = barbell_graph(3, 0)
|
41 |
+
partition = [{0, 1, 2}, {3, 4, 5}]
|
42 |
+
assert 6 / 7 == pytest.approx(partition_quality(G, partition)[0], abs=1e-7)
|
43 |
+
|
44 |
+
|
45 |
+
def test_modularity():
|
46 |
+
G = nx.barbell_graph(3, 0)
|
47 |
+
C = [{0, 1, 4}, {2, 3, 5}]
|
48 |
+
assert (-16 / (14**2)) == pytest.approx(modularity(G, C), abs=1e-7)
|
49 |
+
C = [{0, 1, 2}, {3, 4, 5}]
|
50 |
+
assert (35 * 2) / (14**2) == pytest.approx(modularity(G, C), abs=1e-7)
|
51 |
+
|
52 |
+
n = 1000
|
53 |
+
G = nx.erdos_renyi_graph(n, 0.09, seed=42, directed=True)
|
54 |
+
C = [set(range(n // 2)), set(range(n // 2, n))]
|
55 |
+
assert 0.00017154251389292754 == pytest.approx(modularity(G, C), abs=1e-7)
|
56 |
+
|
57 |
+
G = nx.margulis_gabber_galil_graph(10)
|
58 |
+
mid_value = G.number_of_nodes() // 2
|
59 |
+
nodes = list(G.nodes)
|
60 |
+
C = [set(nodes[:mid_value]), set(nodes[mid_value:])]
|
61 |
+
assert 0.13 == pytest.approx(modularity(G, C), abs=1e-7)
|
62 |
+
|
63 |
+
G = nx.DiGraph()
|
64 |
+
G.add_edges_from([(2, 1), (2, 3), (3, 4)])
|
65 |
+
C = [{1, 2}, {3, 4}]
|
66 |
+
assert 2 / 9 == pytest.approx(modularity(G, C), abs=1e-7)
|
67 |
+
|
68 |
+
|
69 |
+
def test_modularity_resolution():
|
70 |
+
G = nx.barbell_graph(3, 0)
|
71 |
+
C = [{0, 1, 4}, {2, 3, 5}]
|
72 |
+
assert modularity(G, C) == pytest.approx(3 / 7 - 100 / 14**2)
|
73 |
+
gamma = 2
|
74 |
+
result = modularity(G, C, resolution=gamma)
|
75 |
+
assert result == pytest.approx(3 / 7 - gamma * 100 / 14**2)
|
76 |
+
gamma = 0.2
|
77 |
+
result = modularity(G, C, resolution=gamma)
|
78 |
+
assert result == pytest.approx(3 / 7 - gamma * 100 / 14**2)
|
79 |
+
|
80 |
+
C = [{0, 1, 2}, {3, 4, 5}]
|
81 |
+
assert modularity(G, C) == pytest.approx(6 / 7 - 98 / 14**2)
|
82 |
+
gamma = 2
|
83 |
+
result = modularity(G, C, resolution=gamma)
|
84 |
+
assert result == pytest.approx(6 / 7 - gamma * 98 / 14**2)
|
85 |
+
gamma = 0.2
|
86 |
+
result = modularity(G, C, resolution=gamma)
|
87 |
+
assert result == pytest.approx(6 / 7 - gamma * 98 / 14**2)
|
88 |
+
|
89 |
+
G = nx.barbell_graph(5, 3)
|
90 |
+
C = [frozenset(range(5)), frozenset(range(8, 13)), frozenset(range(5, 8))]
|
91 |
+
gamma = 1
|
92 |
+
result = modularity(G, C, resolution=gamma)
|
93 |
+
# This C is maximal for gamma=1: modularity = 0.518229
|
94 |
+
assert result == pytest.approx((22 / 24) - gamma * (918 / (48**2)))
|
95 |
+
gamma = 2
|
96 |
+
result = modularity(G, C, resolution=gamma)
|
97 |
+
assert result == pytest.approx((22 / 24) - gamma * (918 / (48**2)))
|
98 |
+
gamma = 0.2
|
99 |
+
result = modularity(G, C, resolution=gamma)
|
100 |
+
assert result == pytest.approx((22 / 24) - gamma * (918 / (48**2)))
|
101 |
+
|
102 |
+
C = [{0, 1, 2, 3}, {9, 10, 11, 12}, {5, 6, 7}, {4}, {8}]
|
103 |
+
gamma = 1
|
104 |
+
result = modularity(G, C, resolution=gamma)
|
105 |
+
assert result == pytest.approx((14 / 24) - gamma * (598 / (48**2)))
|
106 |
+
gamma = 2.5
|
107 |
+
result = modularity(G, C, resolution=gamma)
|
108 |
+
# This C is maximal for gamma=2.5: modularity = -0.06553819
|
109 |
+
assert result == pytest.approx((14 / 24) - gamma * (598 / (48**2)))
|
110 |
+
gamma = 0.2
|
111 |
+
result = modularity(G, C, resolution=gamma)
|
112 |
+
assert result == pytest.approx((14 / 24) - gamma * (598 / (48**2)))
|
113 |
+
|
114 |
+
C = [frozenset(range(8)), frozenset(range(8, 13))]
|
115 |
+
gamma = 1
|
116 |
+
result = modularity(G, C, resolution=gamma)
|
117 |
+
assert result == pytest.approx((23 / 24) - gamma * (1170 / (48**2)))
|
118 |
+
gamma = 2
|
119 |
+
result = modularity(G, C, resolution=gamma)
|
120 |
+
assert result == pytest.approx((23 / 24) - gamma * (1170 / (48**2)))
|
121 |
+
gamma = 0.3
|
122 |
+
result = modularity(G, C, resolution=gamma)
|
123 |
+
# This C is maximal for gamma=0.3: modularity = 0.805990
|
124 |
+
assert result == pytest.approx((23 / 24) - gamma * (1170 / (48**2)))
|
125 |
+
|
126 |
+
|
127 |
+
def test_inter_community_edges_with_digraphs():
|
128 |
+
G = nx.complete_graph(2, create_using=nx.DiGraph())
|
129 |
+
partition = [{0}, {1}]
|
130 |
+
assert inter_community_edges(G, partition) == 2
|
131 |
+
|
132 |
+
G = nx.complete_graph(10, create_using=nx.DiGraph())
|
133 |
+
partition = [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}]
|
134 |
+
assert inter_community_edges(G, partition) == 70
|
135 |
+
|
136 |
+
G = nx.cycle_graph(4, create_using=nx.DiGraph())
|
137 |
+
partition = [{0, 1}, {2, 3}]
|
138 |
+
assert inter_community_edges(G, partition) == 2
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/community/tests/test_utils.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.community.utils` module.
|
2 |
+
|
3 |
+
"""
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
|
8 |
+
def test_is_partition():
|
9 |
+
G = nx.empty_graph(3)
|
10 |
+
assert nx.community.is_partition(G, [{0, 1}, {2}])
|
11 |
+
assert nx.community.is_partition(G, ({0, 1}, {2}))
|
12 |
+
assert nx.community.is_partition(G, ([0, 1], [2]))
|
13 |
+
assert nx.community.is_partition(G, [[0, 1], [2]])
|
14 |
+
|
15 |
+
|
16 |
+
def test_not_covering():
|
17 |
+
G = nx.empty_graph(3)
|
18 |
+
assert not nx.community.is_partition(G, [{0}, {1}])
|
19 |
+
|
20 |
+
|
21 |
+
def test_not_disjoint():
|
22 |
+
G = nx.empty_graph(3)
|
23 |
+
assert not nx.community.is_partition(G, [{0, 1}, {1, 2}])
|
24 |
+
|
25 |
+
|
26 |
+
def test_not_node():
|
27 |
+
G = nx.empty_graph(3)
|
28 |
+
assert not nx.community.is_partition(G, [{0, 1}, {3}])
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (357 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc
ADDED
Binary file (3.12 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc
ADDED
Binary file (4.83 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc
ADDED
Binary file (2.42 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc
ADDED
Binary file (4.47 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc
ADDED
Binary file (2.77 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc
ADDED
Binary file (7.21 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_asteroidal.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
|
3 |
+
|
4 |
+
def test_is_at_free():
|
5 |
+
is_at_free = nx.asteroidal.is_at_free
|
6 |
+
|
7 |
+
cycle = nx.cycle_graph(6)
|
8 |
+
assert not is_at_free(cycle)
|
9 |
+
|
10 |
+
path = nx.path_graph(6)
|
11 |
+
assert is_at_free(path)
|
12 |
+
|
13 |
+
small_graph = nx.complete_graph(2)
|
14 |
+
assert is_at_free(small_graph)
|
15 |
+
|
16 |
+
petersen = nx.petersen_graph()
|
17 |
+
assert not is_at_free(petersen)
|
18 |
+
|
19 |
+
clique = nx.complete_graph(6)
|
20 |
+
assert is_at_free(clique)
|
21 |
+
|
22 |
+
line_clique = nx.line_graph(clique)
|
23 |
+
assert not is_at_free(line_clique)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_boundary.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.boundary` module."""
|
2 |
+
|
3 |
+
from itertools import combinations
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
9 |
+
from networkx.utils import edges_equal
|
10 |
+
|
11 |
+
|
12 |
+
class TestNodeBoundary:
|
13 |
+
"""Unit tests for the :func:`~networkx.node_boundary` function."""
|
14 |
+
|
15 |
+
def test_null_graph(self):
|
16 |
+
"""Tests that the null graph has empty node boundaries."""
|
17 |
+
null = nx.null_graph()
|
18 |
+
assert nx.node_boundary(null, []) == set()
|
19 |
+
assert nx.node_boundary(null, [], []) == set()
|
20 |
+
assert nx.node_boundary(null, [1, 2, 3]) == set()
|
21 |
+
assert nx.node_boundary(null, [1, 2, 3], [4, 5, 6]) == set()
|
22 |
+
assert nx.node_boundary(null, [1, 2, 3], [3, 4, 5]) == set()
|
23 |
+
|
24 |
+
def test_path_graph(self):
|
25 |
+
P10 = cnlti(nx.path_graph(10), first_label=1)
|
26 |
+
assert nx.node_boundary(P10, []) == set()
|
27 |
+
assert nx.node_boundary(P10, [], []) == set()
|
28 |
+
assert nx.node_boundary(P10, [1, 2, 3]) == {4}
|
29 |
+
assert nx.node_boundary(P10, [4, 5, 6]) == {3, 7}
|
30 |
+
assert nx.node_boundary(P10, [3, 4, 5, 6, 7]) == {2, 8}
|
31 |
+
assert nx.node_boundary(P10, [8, 9, 10]) == {7}
|
32 |
+
assert nx.node_boundary(P10, [4, 5, 6], [9, 10]) == set()
|
33 |
+
|
34 |
+
def test_complete_graph(self):
|
35 |
+
K10 = cnlti(nx.complete_graph(10), first_label=1)
|
36 |
+
assert nx.node_boundary(K10, []) == set()
|
37 |
+
assert nx.node_boundary(K10, [], []) == set()
|
38 |
+
assert nx.node_boundary(K10, [1, 2, 3]) == {4, 5, 6, 7, 8, 9, 10}
|
39 |
+
assert nx.node_boundary(K10, [4, 5, 6]) == {1, 2, 3, 7, 8, 9, 10}
|
40 |
+
assert nx.node_boundary(K10, [3, 4, 5, 6, 7]) == {1, 2, 8, 9, 10}
|
41 |
+
assert nx.node_boundary(K10, [4, 5, 6], []) == set()
|
42 |
+
assert nx.node_boundary(K10, K10) == set()
|
43 |
+
assert nx.node_boundary(K10, [1, 2, 3], [3, 4, 5]) == {4, 5}
|
44 |
+
|
45 |
+
def test_petersen(self):
|
46 |
+
"""Check boundaries in the petersen graph
|
47 |
+
|
48 |
+
cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0<k<=|V(G)|/2)
|
49 |
+
|
50 |
+
"""
|
51 |
+
|
52 |
+
def cheeger(G, k):
|
53 |
+
return min(len(nx.node_boundary(G, nn)) / k for nn in combinations(G, k))
|
54 |
+
|
55 |
+
P = nx.petersen_graph()
|
56 |
+
assert cheeger(P, 1) == pytest.approx(3.00, abs=1e-2)
|
57 |
+
assert cheeger(P, 2) == pytest.approx(2.00, abs=1e-2)
|
58 |
+
assert cheeger(P, 3) == pytest.approx(1.67, abs=1e-2)
|
59 |
+
assert cheeger(P, 4) == pytest.approx(1.00, abs=1e-2)
|
60 |
+
assert cheeger(P, 5) == pytest.approx(0.80, abs=1e-2)
|
61 |
+
|
62 |
+
def test_directed(self):
|
63 |
+
"""Tests the node boundary of a directed graph."""
|
64 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
|
65 |
+
S = {0, 1}
|
66 |
+
boundary = nx.node_boundary(G, S)
|
67 |
+
expected = {2}
|
68 |
+
assert boundary == expected
|
69 |
+
|
70 |
+
def test_multigraph(self):
|
71 |
+
"""Tests the node boundary of a multigraph."""
|
72 |
+
G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
|
73 |
+
S = {0, 1}
|
74 |
+
boundary = nx.node_boundary(G, S)
|
75 |
+
expected = {2, 4}
|
76 |
+
assert boundary == expected
|
77 |
+
|
78 |
+
def test_multidigraph(self):
|
79 |
+
"""Tests the edge boundary of a multidigraph."""
|
80 |
+
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
|
81 |
+
G = nx.MultiDiGraph(edges * 2)
|
82 |
+
S = {0, 1}
|
83 |
+
boundary = nx.node_boundary(G, S)
|
84 |
+
expected = {2}
|
85 |
+
assert boundary == expected
|
86 |
+
|
87 |
+
|
88 |
+
class TestEdgeBoundary:
|
89 |
+
"""Unit tests for the :func:`~networkx.edge_boundary` function."""
|
90 |
+
|
91 |
+
def test_null_graph(self):
|
92 |
+
null = nx.null_graph()
|
93 |
+
assert list(nx.edge_boundary(null, [])) == []
|
94 |
+
assert list(nx.edge_boundary(null, [], [])) == []
|
95 |
+
assert list(nx.edge_boundary(null, [1, 2, 3])) == []
|
96 |
+
assert list(nx.edge_boundary(null, [1, 2, 3], [4, 5, 6])) == []
|
97 |
+
assert list(nx.edge_boundary(null, [1, 2, 3], [3, 4, 5])) == []
|
98 |
+
|
99 |
+
def test_path_graph(self):
|
100 |
+
P10 = cnlti(nx.path_graph(10), first_label=1)
|
101 |
+
assert list(nx.edge_boundary(P10, [])) == []
|
102 |
+
assert list(nx.edge_boundary(P10, [], [])) == []
|
103 |
+
assert list(nx.edge_boundary(P10, [1, 2, 3])) == [(3, 4)]
|
104 |
+
assert sorted(nx.edge_boundary(P10, [4, 5, 6])) == [(4, 3), (6, 7)]
|
105 |
+
assert sorted(nx.edge_boundary(P10, [3, 4, 5, 6, 7])) == [(3, 2), (7, 8)]
|
106 |
+
assert list(nx.edge_boundary(P10, [8, 9, 10])) == [(8, 7)]
|
107 |
+
assert sorted(nx.edge_boundary(P10, [4, 5, 6], [9, 10])) == []
|
108 |
+
assert list(nx.edge_boundary(P10, [1, 2, 3], [3, 4, 5])) == [(2, 3), (3, 4)]
|
109 |
+
|
110 |
+
def test_complete_graph(self):
|
111 |
+
K10 = cnlti(nx.complete_graph(10), first_label=1)
|
112 |
+
|
113 |
+
def ilen(iterable):
|
114 |
+
return sum(1 for i in iterable)
|
115 |
+
|
116 |
+
assert list(nx.edge_boundary(K10, [])) == []
|
117 |
+
assert list(nx.edge_boundary(K10, [], [])) == []
|
118 |
+
assert ilen(nx.edge_boundary(K10, [1, 2, 3])) == 21
|
119 |
+
assert ilen(nx.edge_boundary(K10, [4, 5, 6, 7])) == 24
|
120 |
+
assert ilen(nx.edge_boundary(K10, [3, 4, 5, 6, 7])) == 25
|
121 |
+
assert ilen(nx.edge_boundary(K10, [8, 9, 10])) == 21
|
122 |
+
assert edges_equal(
|
123 |
+
nx.edge_boundary(K10, [4, 5, 6], [9, 10]),
|
124 |
+
[(4, 9), (4, 10), (5, 9), (5, 10), (6, 9), (6, 10)],
|
125 |
+
)
|
126 |
+
assert edges_equal(
|
127 |
+
nx.edge_boundary(K10, [1, 2, 3], [3, 4, 5]),
|
128 |
+
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5)],
|
129 |
+
)
|
130 |
+
|
131 |
+
def test_directed(self):
|
132 |
+
"""Tests the edge boundary of a directed graph."""
|
133 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
|
134 |
+
S = {0, 1}
|
135 |
+
boundary = list(nx.edge_boundary(G, S))
|
136 |
+
expected = [(1, 2)]
|
137 |
+
assert boundary == expected
|
138 |
+
|
139 |
+
def test_multigraph(self):
|
140 |
+
"""Tests the edge boundary of a multigraph."""
|
141 |
+
G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
|
142 |
+
S = {0, 1}
|
143 |
+
boundary = list(nx.edge_boundary(G, S))
|
144 |
+
expected = [(0, 4), (0, 4), (1, 2), (1, 2)]
|
145 |
+
assert boundary == expected
|
146 |
+
|
147 |
+
def test_multidigraph(self):
|
148 |
+
"""Tests the edge boundary of a multidigraph."""
|
149 |
+
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
|
150 |
+
G = nx.MultiDiGraph(edges * 2)
|
151 |
+
S = {0, 1}
|
152 |
+
boundary = list(nx.edge_boundary(G, S))
|
153 |
+
expected = [(1, 2), (1, 2)]
|
154 |
+
assert boundary == expected
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_bridges.py
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for bridge-finding algorithms."""
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
|
8 |
+
class TestBridges:
|
9 |
+
"""Unit tests for the bridge-finding function."""
|
10 |
+
|
11 |
+
def test_single_bridge(self):
|
12 |
+
edges = [
|
13 |
+
# DFS tree edges.
|
14 |
+
(1, 2),
|
15 |
+
(2, 3),
|
16 |
+
(3, 4),
|
17 |
+
(3, 5),
|
18 |
+
(5, 6),
|
19 |
+
(6, 7),
|
20 |
+
(7, 8),
|
21 |
+
(5, 9),
|
22 |
+
(9, 10),
|
23 |
+
# Nontree edges.
|
24 |
+
(1, 3),
|
25 |
+
(1, 4),
|
26 |
+
(2, 5),
|
27 |
+
(5, 10),
|
28 |
+
(6, 8),
|
29 |
+
]
|
30 |
+
G = nx.Graph(edges)
|
31 |
+
source = 1
|
32 |
+
bridges = list(nx.bridges(G, source))
|
33 |
+
assert bridges == [(5, 6)]
|
34 |
+
|
35 |
+
def test_barbell_graph(self):
|
36 |
+
# The (3, 0) barbell graph has two triangles joined by a single edge.
|
37 |
+
G = nx.barbell_graph(3, 0)
|
38 |
+
source = 0
|
39 |
+
bridges = list(nx.bridges(G, source))
|
40 |
+
assert bridges == [(2, 3)]
|
41 |
+
|
42 |
+
def test_multiedge_bridge(self):
|
43 |
+
edges = [
|
44 |
+
(0, 1),
|
45 |
+
(0, 2),
|
46 |
+
(1, 2),
|
47 |
+
(1, 2),
|
48 |
+
(2, 3),
|
49 |
+
(3, 4),
|
50 |
+
(3, 4),
|
51 |
+
]
|
52 |
+
G = nx.MultiGraph(edges)
|
53 |
+
assert list(nx.bridges(G)) == [(2, 3)]
|
54 |
+
|
55 |
+
|
56 |
+
class TestHasBridges:
|
57 |
+
"""Unit tests for the has bridges function."""
|
58 |
+
|
59 |
+
def test_single_bridge(self):
|
60 |
+
edges = [
|
61 |
+
# DFS tree edges.
|
62 |
+
(1, 2),
|
63 |
+
(2, 3),
|
64 |
+
(3, 4),
|
65 |
+
(3, 5),
|
66 |
+
(5, 6), # The only bridge edge
|
67 |
+
(6, 7),
|
68 |
+
(7, 8),
|
69 |
+
(5, 9),
|
70 |
+
(9, 10),
|
71 |
+
# Nontree edges.
|
72 |
+
(1, 3),
|
73 |
+
(1, 4),
|
74 |
+
(2, 5),
|
75 |
+
(5, 10),
|
76 |
+
(6, 8),
|
77 |
+
]
|
78 |
+
G = nx.Graph(edges)
|
79 |
+
assert nx.has_bridges(G) # Default root
|
80 |
+
assert nx.has_bridges(G, root=1) # arbitrary root in G
|
81 |
+
|
82 |
+
def test_has_bridges_raises_root_not_in_G(self):
|
83 |
+
G = nx.Graph()
|
84 |
+
G.add_nodes_from([1, 2, 3])
|
85 |
+
with pytest.raises(nx.NodeNotFound):
|
86 |
+
nx.has_bridges(G, root=6)
|
87 |
+
|
88 |
+
def test_multiedge_bridge(self):
|
89 |
+
edges = [
|
90 |
+
(0, 1),
|
91 |
+
(0, 2),
|
92 |
+
(1, 2),
|
93 |
+
(1, 2),
|
94 |
+
(2, 3),
|
95 |
+
(3, 4),
|
96 |
+
(3, 4),
|
97 |
+
]
|
98 |
+
G = nx.MultiGraph(edges)
|
99 |
+
assert nx.has_bridges(G)
|
100 |
+
# Make every edge a multiedge
|
101 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
102 |
+
assert not nx.has_bridges(G)
|
103 |
+
|
104 |
+
def test_bridges_multiple_components(self):
|
105 |
+
G = nx.Graph()
|
106 |
+
nx.add_path(G, [0, 1, 2]) # One connected component
|
107 |
+
nx.add_path(G, [4, 5, 6]) # Another connected component
|
108 |
+
assert list(nx.bridges(G, root=4)) == [(4, 5), (5, 6)]
|
109 |
+
|
110 |
+
|
111 |
+
class TestLocalBridges:
|
112 |
+
"""Unit tests for the local_bridge function."""
|
113 |
+
|
114 |
+
@classmethod
|
115 |
+
def setup_class(cls):
|
116 |
+
cls.BB = nx.barbell_graph(4, 0)
|
117 |
+
cls.square = nx.cycle_graph(4)
|
118 |
+
cls.tri = nx.cycle_graph(3)
|
119 |
+
|
120 |
+
def test_nospan(self):
|
121 |
+
expected = {(3, 4), (4, 3)}
|
122 |
+
assert next(nx.local_bridges(self.BB, with_span=False)) in expected
|
123 |
+
assert set(nx.local_bridges(self.square, with_span=False)) == self.square.edges
|
124 |
+
assert list(nx.local_bridges(self.tri, with_span=False)) == []
|
125 |
+
|
126 |
+
def test_no_weight(self):
|
127 |
+
inf = float("inf")
|
128 |
+
expected = {(3, 4, inf), (4, 3, inf)}
|
129 |
+
assert next(nx.local_bridges(self.BB)) in expected
|
130 |
+
expected = {(u, v, 3) for u, v in self.square.edges}
|
131 |
+
assert set(nx.local_bridges(self.square)) == expected
|
132 |
+
assert list(nx.local_bridges(self.tri)) == []
|
133 |
+
|
134 |
+
def test_weight(self):
|
135 |
+
inf = float("inf")
|
136 |
+
G = self.square.copy()
|
137 |
+
|
138 |
+
G.edges[1, 2]["weight"] = 2
|
139 |
+
expected = {(u, v, 5 - wt) for u, v, wt in G.edges(data="weight", default=1)}
|
140 |
+
assert set(nx.local_bridges(G, weight="weight")) == expected
|
141 |
+
|
142 |
+
expected = {(u, v, 6) for u, v in G.edges}
|
143 |
+
lb = nx.local_bridges(G, weight=lambda u, v, d: 2)
|
144 |
+
assert set(lb) == expected
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_broadcasting.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the broadcasting module."""
|
2 |
+
import math
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
|
7 |
+
def test_example_tree_broadcast():
|
8 |
+
"""
|
9 |
+
Test the BROADCAST algorithm on the example in the paper titled: "Information Dissemination in Trees"
|
10 |
+
"""
|
11 |
+
edge_list = [
|
12 |
+
(0, 1),
|
13 |
+
(1, 2),
|
14 |
+
(2, 7),
|
15 |
+
(3, 4),
|
16 |
+
(5, 4),
|
17 |
+
(4, 7),
|
18 |
+
(6, 7),
|
19 |
+
(7, 9),
|
20 |
+
(8, 9),
|
21 |
+
(9, 13),
|
22 |
+
(13, 14),
|
23 |
+
(14, 15),
|
24 |
+
(14, 16),
|
25 |
+
(14, 17),
|
26 |
+
(13, 11),
|
27 |
+
(11, 10),
|
28 |
+
(11, 12),
|
29 |
+
(13, 18),
|
30 |
+
(18, 19),
|
31 |
+
(18, 20),
|
32 |
+
]
|
33 |
+
G = nx.Graph(edge_list)
|
34 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
35 |
+
assert b_T == 6
|
36 |
+
assert b_C == {13, 9}
|
37 |
+
# test broadcast time from specific vertex
|
38 |
+
assert nx.tree_broadcast_time(G, 17) == 8
|
39 |
+
assert nx.tree_broadcast_time(G, 3) == 9
|
40 |
+
# test broadcast time of entire tree
|
41 |
+
assert nx.tree_broadcast_time(G) == 10
|
42 |
+
|
43 |
+
|
44 |
+
def test_path_broadcast():
|
45 |
+
for i in range(2, 12):
|
46 |
+
G = nx.path_graph(i)
|
47 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
48 |
+
assert b_T == math.ceil(i / 2)
|
49 |
+
assert b_C == {
|
50 |
+
math.ceil(i / 2),
|
51 |
+
math.floor(i / 2),
|
52 |
+
math.ceil(i / 2 - 1),
|
53 |
+
math.floor(i / 2 - 1),
|
54 |
+
}
|
55 |
+
assert nx.tree_broadcast_time(G) == i - 1
|
56 |
+
|
57 |
+
|
58 |
+
def test_empty_graph_broadcast():
|
59 |
+
H = nx.empty_graph(1)
|
60 |
+
b_T, b_C = nx.tree_broadcast_center(H)
|
61 |
+
assert b_T == 0
|
62 |
+
assert b_C == {0}
|
63 |
+
assert nx.tree_broadcast_time(H) == 0
|
64 |
+
|
65 |
+
|
66 |
+
def test_star_broadcast():
|
67 |
+
for i in range(4, 12):
|
68 |
+
G = nx.star_graph(i)
|
69 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
70 |
+
assert b_T == i
|
71 |
+
assert b_C == set(G.nodes())
|
72 |
+
assert nx.tree_broadcast_time(G) == b_T
|
73 |
+
|
74 |
+
|
75 |
+
def test_binomial_tree_broadcast():
|
76 |
+
for i in range(2, 8):
|
77 |
+
G = nx.binomial_tree(i)
|
78 |
+
b_T, b_C = nx.tree_broadcast_center(G)
|
79 |
+
assert b_T == i
|
80 |
+
assert b_C == {0, 2 ** (i - 1)}
|
81 |
+
assert nx.tree_broadcast_time(G) == 2 * i - 1
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_chordal.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
class TestMCS:
|
7 |
+
@classmethod
|
8 |
+
def setup_class(cls):
|
9 |
+
# simple graph
|
10 |
+
connected_chordal_G = nx.Graph()
|
11 |
+
connected_chordal_G.add_edges_from(
|
12 |
+
[
|
13 |
+
(1, 2),
|
14 |
+
(1, 3),
|
15 |
+
(2, 3),
|
16 |
+
(2, 4),
|
17 |
+
(3, 4),
|
18 |
+
(3, 5),
|
19 |
+
(3, 6),
|
20 |
+
(4, 5),
|
21 |
+
(4, 6),
|
22 |
+
(5, 6),
|
23 |
+
]
|
24 |
+
)
|
25 |
+
cls.connected_chordal_G = connected_chordal_G
|
26 |
+
|
27 |
+
chordal_G = nx.Graph()
|
28 |
+
chordal_G.add_edges_from(
|
29 |
+
[
|
30 |
+
(1, 2),
|
31 |
+
(1, 3),
|
32 |
+
(2, 3),
|
33 |
+
(2, 4),
|
34 |
+
(3, 4),
|
35 |
+
(3, 5),
|
36 |
+
(3, 6),
|
37 |
+
(4, 5),
|
38 |
+
(4, 6),
|
39 |
+
(5, 6),
|
40 |
+
(7, 8),
|
41 |
+
]
|
42 |
+
)
|
43 |
+
chordal_G.add_node(9)
|
44 |
+
cls.chordal_G = chordal_G
|
45 |
+
|
46 |
+
non_chordal_G = nx.Graph()
|
47 |
+
non_chordal_G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5), (3, 4), (3, 5)])
|
48 |
+
cls.non_chordal_G = non_chordal_G
|
49 |
+
|
50 |
+
self_loop_G = nx.Graph()
|
51 |
+
self_loop_G.add_edges_from([(1, 1)])
|
52 |
+
cls.self_loop_G = self_loop_G
|
53 |
+
|
54 |
+
@pytest.mark.parametrize("G", (nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()))
|
55 |
+
def test_is_chordal_not_implemented(self, G):
|
56 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
57 |
+
nx.is_chordal(G)
|
58 |
+
|
59 |
+
def test_is_chordal(self):
|
60 |
+
assert not nx.is_chordal(self.non_chordal_G)
|
61 |
+
assert nx.is_chordal(self.chordal_G)
|
62 |
+
assert nx.is_chordal(self.connected_chordal_G)
|
63 |
+
assert nx.is_chordal(nx.Graph())
|
64 |
+
assert nx.is_chordal(nx.complete_graph(3))
|
65 |
+
assert nx.is_chordal(nx.cycle_graph(3))
|
66 |
+
assert not nx.is_chordal(nx.cycle_graph(5))
|
67 |
+
assert nx.is_chordal(self.self_loop_G)
|
68 |
+
|
69 |
+
def test_induced_nodes(self):
|
70 |
+
G = nx.generators.classic.path_graph(10)
|
71 |
+
Induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
|
72 |
+
assert Induced_nodes == {1, 2, 3, 4, 5, 6, 7, 8, 9}
|
73 |
+
pytest.raises(
|
74 |
+
nx.NetworkXTreewidthBoundExceeded, nx.find_induced_nodes, G, 1, 9, 1
|
75 |
+
)
|
76 |
+
Induced_nodes = nx.find_induced_nodes(self.chordal_G, 1, 6)
|
77 |
+
assert Induced_nodes == {1, 2, 4, 6}
|
78 |
+
pytest.raises(nx.NetworkXError, nx.find_induced_nodes, self.non_chordal_G, 1, 5)
|
79 |
+
|
80 |
+
def test_graph_treewidth(self):
|
81 |
+
with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
|
82 |
+
nx.chordal_graph_treewidth(self.non_chordal_G)
|
83 |
+
|
84 |
+
def test_chordal_find_cliques(self):
|
85 |
+
cliques = {
|
86 |
+
frozenset([9]),
|
87 |
+
frozenset([7, 8]),
|
88 |
+
frozenset([1, 2, 3]),
|
89 |
+
frozenset([2, 3, 4]),
|
90 |
+
frozenset([3, 4, 5, 6]),
|
91 |
+
}
|
92 |
+
assert set(nx.chordal_graph_cliques(self.chordal_G)) == cliques
|
93 |
+
with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
|
94 |
+
set(nx.chordal_graph_cliques(self.non_chordal_G))
|
95 |
+
with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
|
96 |
+
set(nx.chordal_graph_cliques(self.self_loop_G))
|
97 |
+
|
98 |
+
def test_chordal_find_cliques_path(self):
|
99 |
+
G = nx.path_graph(10)
|
100 |
+
cliqueset = nx.chordal_graph_cliques(G)
|
101 |
+
for u, v in G.edges():
|
102 |
+
assert frozenset([u, v]) in cliqueset or frozenset([v, u]) in cliqueset
|
103 |
+
|
104 |
+
def test_chordal_find_cliquesCC(self):
|
105 |
+
cliques = {frozenset([1, 2, 3]), frozenset([2, 3, 4]), frozenset([3, 4, 5, 6])}
|
106 |
+
cgc = nx.chordal_graph_cliques
|
107 |
+
assert set(cgc(self.connected_chordal_G)) == cliques
|
108 |
+
|
109 |
+
def test_complete_to_chordal_graph(self):
|
110 |
+
fgrg = nx.fast_gnp_random_graph
|
111 |
+
test_graphs = [
|
112 |
+
nx.barbell_graph(6, 2),
|
113 |
+
nx.cycle_graph(15),
|
114 |
+
nx.wheel_graph(20),
|
115 |
+
nx.grid_graph([10, 4]),
|
116 |
+
nx.ladder_graph(15),
|
117 |
+
nx.star_graph(5),
|
118 |
+
nx.bull_graph(),
|
119 |
+
fgrg(20, 0.3, seed=1),
|
120 |
+
]
|
121 |
+
for G in test_graphs:
|
122 |
+
H, a = nx.complete_to_chordal_graph(G)
|
123 |
+
assert nx.is_chordal(H)
|
124 |
+
assert len(a) == H.number_of_nodes()
|
125 |
+
if nx.is_chordal(G):
|
126 |
+
assert G.number_of_edges() == H.number_of_edges()
|
127 |
+
assert set(a.values()) == {0}
|
128 |
+
else:
|
129 |
+
assert len(set(a.values())) == H.number_of_nodes()
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_cluster.py
ADDED
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
class TestTriangles:
|
7 |
+
def test_empty(self):
|
8 |
+
G = nx.Graph()
|
9 |
+
assert list(nx.triangles(G).values()) == []
|
10 |
+
|
11 |
+
def test_path(self):
|
12 |
+
G = nx.path_graph(10)
|
13 |
+
assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
14 |
+
assert nx.triangles(G) == {
|
15 |
+
0: 0,
|
16 |
+
1: 0,
|
17 |
+
2: 0,
|
18 |
+
3: 0,
|
19 |
+
4: 0,
|
20 |
+
5: 0,
|
21 |
+
6: 0,
|
22 |
+
7: 0,
|
23 |
+
8: 0,
|
24 |
+
9: 0,
|
25 |
+
}
|
26 |
+
|
27 |
+
def test_cubical(self):
|
28 |
+
G = nx.cubical_graph()
|
29 |
+
assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
|
30 |
+
assert nx.triangles(G, 1) == 0
|
31 |
+
assert list(nx.triangles(G, [1, 2]).values()) == [0, 0]
|
32 |
+
assert nx.triangles(G, 1) == 0
|
33 |
+
assert nx.triangles(G, [1, 2]) == {1: 0, 2: 0}
|
34 |
+
|
35 |
+
def test_k5(self):
|
36 |
+
G = nx.complete_graph(5)
|
37 |
+
assert list(nx.triangles(G).values()) == [6, 6, 6, 6, 6]
|
38 |
+
assert sum(nx.triangles(G).values()) / 3 == 10
|
39 |
+
assert nx.triangles(G, 1) == 6
|
40 |
+
G.remove_edge(1, 2)
|
41 |
+
assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
|
42 |
+
assert nx.triangles(G, 1) == 3
|
43 |
+
G.add_edge(3, 3) # ignore self-edges
|
44 |
+
assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
|
45 |
+
assert nx.triangles(G, 3) == 5
|
46 |
+
|
47 |
+
|
48 |
+
class TestDirectedClustering:
|
49 |
+
def test_clustering(self):
|
50 |
+
G = nx.DiGraph()
|
51 |
+
assert list(nx.clustering(G).values()) == []
|
52 |
+
assert nx.clustering(G) == {}
|
53 |
+
|
54 |
+
def test_path(self):
|
55 |
+
G = nx.path_graph(10, create_using=nx.DiGraph())
|
56 |
+
assert list(nx.clustering(G).values()) == [
|
57 |
+
0,
|
58 |
+
0,
|
59 |
+
0,
|
60 |
+
0,
|
61 |
+
0,
|
62 |
+
0,
|
63 |
+
0,
|
64 |
+
0,
|
65 |
+
0,
|
66 |
+
0,
|
67 |
+
]
|
68 |
+
assert nx.clustering(G) == {
|
69 |
+
0: 0,
|
70 |
+
1: 0,
|
71 |
+
2: 0,
|
72 |
+
3: 0,
|
73 |
+
4: 0,
|
74 |
+
5: 0,
|
75 |
+
6: 0,
|
76 |
+
7: 0,
|
77 |
+
8: 0,
|
78 |
+
9: 0,
|
79 |
+
}
|
80 |
+
assert nx.clustering(G, 0) == 0
|
81 |
+
|
82 |
+
def test_k5(self):
|
83 |
+
G = nx.complete_graph(5, create_using=nx.DiGraph())
|
84 |
+
assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
|
85 |
+
assert nx.average_clustering(G) == 1
|
86 |
+
G.remove_edge(1, 2)
|
87 |
+
assert list(nx.clustering(G).values()) == [
|
88 |
+
11 / 12,
|
89 |
+
1,
|
90 |
+
1,
|
91 |
+
11 / 12,
|
92 |
+
11 / 12,
|
93 |
+
]
|
94 |
+
assert nx.clustering(G, [1, 4]) == {1: 1, 4: 11 / 12}
|
95 |
+
G.remove_edge(2, 1)
|
96 |
+
assert list(nx.clustering(G).values()) == [
|
97 |
+
5 / 6,
|
98 |
+
1,
|
99 |
+
1,
|
100 |
+
5 / 6,
|
101 |
+
5 / 6,
|
102 |
+
]
|
103 |
+
assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
|
104 |
+
assert nx.clustering(G, 4) == 5 / 6
|
105 |
+
|
106 |
+
def test_triangle_and_edge(self):
|
107 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
108 |
+
G.add_edge(0, 4)
|
109 |
+
assert nx.clustering(G)[0] == 1 / 6
|
110 |
+
|
111 |
+
|
112 |
+
class TestDirectedWeightedClustering:
|
113 |
+
@classmethod
|
114 |
+
def setup_class(cls):
|
115 |
+
global np
|
116 |
+
np = pytest.importorskip("numpy")
|
117 |
+
|
118 |
+
def test_clustering(self):
|
119 |
+
G = nx.DiGraph()
|
120 |
+
assert list(nx.clustering(G, weight="weight").values()) == []
|
121 |
+
assert nx.clustering(G) == {}
|
122 |
+
|
123 |
+
def test_path(self):
|
124 |
+
G = nx.path_graph(10, create_using=nx.DiGraph())
|
125 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
126 |
+
0,
|
127 |
+
0,
|
128 |
+
0,
|
129 |
+
0,
|
130 |
+
0,
|
131 |
+
0,
|
132 |
+
0,
|
133 |
+
0,
|
134 |
+
0,
|
135 |
+
0,
|
136 |
+
]
|
137 |
+
assert nx.clustering(G, weight="weight") == {
|
138 |
+
0: 0,
|
139 |
+
1: 0,
|
140 |
+
2: 0,
|
141 |
+
3: 0,
|
142 |
+
4: 0,
|
143 |
+
5: 0,
|
144 |
+
6: 0,
|
145 |
+
7: 0,
|
146 |
+
8: 0,
|
147 |
+
9: 0,
|
148 |
+
}
|
149 |
+
|
150 |
+
def test_k5(self):
|
151 |
+
G = nx.complete_graph(5, create_using=nx.DiGraph())
|
152 |
+
assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
|
153 |
+
assert nx.average_clustering(G, weight="weight") == 1
|
154 |
+
G.remove_edge(1, 2)
|
155 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
156 |
+
11 / 12,
|
157 |
+
1,
|
158 |
+
1,
|
159 |
+
11 / 12,
|
160 |
+
11 / 12,
|
161 |
+
]
|
162 |
+
assert nx.clustering(G, [1, 4], weight="weight") == {1: 1, 4: 11 / 12}
|
163 |
+
G.remove_edge(2, 1)
|
164 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
165 |
+
5 / 6,
|
166 |
+
1,
|
167 |
+
1,
|
168 |
+
5 / 6,
|
169 |
+
5 / 6,
|
170 |
+
]
|
171 |
+
assert nx.clustering(G, [1, 4], weight="weight") == {
|
172 |
+
1: 1,
|
173 |
+
4: 0.83333333333333337,
|
174 |
+
}
|
175 |
+
|
176 |
+
def test_triangle_and_edge(self):
|
177 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
178 |
+
G.add_edge(0, 4, weight=2)
|
179 |
+
assert nx.clustering(G)[0] == 1 / 6
|
180 |
+
# Relaxed comparisons to allow graphblas-algorithms to pass tests
|
181 |
+
np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 12)
|
182 |
+
np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 12)
|
183 |
+
|
184 |
+
|
185 |
+
class TestWeightedClustering:
|
186 |
+
@classmethod
|
187 |
+
def setup_class(cls):
|
188 |
+
global np
|
189 |
+
np = pytest.importorskip("numpy")
|
190 |
+
|
191 |
+
def test_clustering(self):
|
192 |
+
G = nx.Graph()
|
193 |
+
assert list(nx.clustering(G, weight="weight").values()) == []
|
194 |
+
assert nx.clustering(G) == {}
|
195 |
+
|
196 |
+
def test_path(self):
|
197 |
+
G = nx.path_graph(10)
|
198 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
199 |
+
0,
|
200 |
+
0,
|
201 |
+
0,
|
202 |
+
0,
|
203 |
+
0,
|
204 |
+
0,
|
205 |
+
0,
|
206 |
+
0,
|
207 |
+
0,
|
208 |
+
0,
|
209 |
+
]
|
210 |
+
assert nx.clustering(G, weight="weight") == {
|
211 |
+
0: 0,
|
212 |
+
1: 0,
|
213 |
+
2: 0,
|
214 |
+
3: 0,
|
215 |
+
4: 0,
|
216 |
+
5: 0,
|
217 |
+
6: 0,
|
218 |
+
7: 0,
|
219 |
+
8: 0,
|
220 |
+
9: 0,
|
221 |
+
}
|
222 |
+
|
223 |
+
def test_cubical(self):
|
224 |
+
G = nx.cubical_graph()
|
225 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
226 |
+
0,
|
227 |
+
0,
|
228 |
+
0,
|
229 |
+
0,
|
230 |
+
0,
|
231 |
+
0,
|
232 |
+
0,
|
233 |
+
0,
|
234 |
+
]
|
235 |
+
assert nx.clustering(G, 1) == 0
|
236 |
+
assert list(nx.clustering(G, [1, 2], weight="weight").values()) == [0, 0]
|
237 |
+
assert nx.clustering(G, 1, weight="weight") == 0
|
238 |
+
assert nx.clustering(G, [1, 2], weight="weight") == {1: 0, 2: 0}
|
239 |
+
|
240 |
+
def test_k5(self):
|
241 |
+
G = nx.complete_graph(5)
|
242 |
+
assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
|
243 |
+
assert nx.average_clustering(G, weight="weight") == 1
|
244 |
+
G.remove_edge(1, 2)
|
245 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
246 |
+
5 / 6,
|
247 |
+
1,
|
248 |
+
1,
|
249 |
+
5 / 6,
|
250 |
+
5 / 6,
|
251 |
+
]
|
252 |
+
assert nx.clustering(G, [1, 4], weight="weight") == {
|
253 |
+
1: 1,
|
254 |
+
4: 0.83333333333333337,
|
255 |
+
}
|
256 |
+
|
257 |
+
def test_triangle_and_edge(self):
|
258 |
+
G = nx.cycle_graph(3)
|
259 |
+
G.add_edge(0, 4, weight=2)
|
260 |
+
assert nx.clustering(G)[0] == 1 / 3
|
261 |
+
np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 6)
|
262 |
+
np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 6)
|
263 |
+
|
264 |
+
def test_triangle_and_signed_edge(self):
|
265 |
+
G = nx.cycle_graph(3)
|
266 |
+
G.add_edge(0, 1, weight=-1)
|
267 |
+
G.add_edge(3, 0, weight=0)
|
268 |
+
assert nx.clustering(G)[0] == 1 / 3
|
269 |
+
assert nx.clustering(G, weight="weight")[0] == -1 / 3
|
270 |
+
|
271 |
+
|
272 |
+
class TestClustering:
|
273 |
+
@classmethod
|
274 |
+
def setup_class(cls):
|
275 |
+
pytest.importorskip("numpy")
|
276 |
+
|
277 |
+
def test_clustering(self):
|
278 |
+
G = nx.Graph()
|
279 |
+
assert list(nx.clustering(G).values()) == []
|
280 |
+
assert nx.clustering(G) == {}
|
281 |
+
|
282 |
+
def test_path(self):
|
283 |
+
G = nx.path_graph(10)
|
284 |
+
assert list(nx.clustering(G).values()) == [
|
285 |
+
0,
|
286 |
+
0,
|
287 |
+
0,
|
288 |
+
0,
|
289 |
+
0,
|
290 |
+
0,
|
291 |
+
0,
|
292 |
+
0,
|
293 |
+
0,
|
294 |
+
0,
|
295 |
+
]
|
296 |
+
assert nx.clustering(G) == {
|
297 |
+
0: 0,
|
298 |
+
1: 0,
|
299 |
+
2: 0,
|
300 |
+
3: 0,
|
301 |
+
4: 0,
|
302 |
+
5: 0,
|
303 |
+
6: 0,
|
304 |
+
7: 0,
|
305 |
+
8: 0,
|
306 |
+
9: 0,
|
307 |
+
}
|
308 |
+
|
309 |
+
def test_cubical(self):
|
310 |
+
G = nx.cubical_graph()
|
311 |
+
assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
|
312 |
+
assert nx.clustering(G, 1) == 0
|
313 |
+
assert list(nx.clustering(G, [1, 2]).values()) == [0, 0]
|
314 |
+
assert nx.clustering(G, 1) == 0
|
315 |
+
assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0}
|
316 |
+
|
317 |
+
def test_k5(self):
|
318 |
+
G = nx.complete_graph(5)
|
319 |
+
assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
|
320 |
+
assert nx.average_clustering(G) == 1
|
321 |
+
G.remove_edge(1, 2)
|
322 |
+
assert list(nx.clustering(G).values()) == [
|
323 |
+
5 / 6,
|
324 |
+
1,
|
325 |
+
1,
|
326 |
+
5 / 6,
|
327 |
+
5 / 6,
|
328 |
+
]
|
329 |
+
assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
|
330 |
+
|
331 |
+
def test_k5_signed(self):
|
332 |
+
G = nx.complete_graph(5)
|
333 |
+
assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
|
334 |
+
assert nx.average_clustering(G) == 1
|
335 |
+
G.remove_edge(1, 2)
|
336 |
+
G.add_edge(0, 1, weight=-1)
|
337 |
+
assert list(nx.clustering(G, weight="weight").values()) == [
|
338 |
+
1 / 6,
|
339 |
+
-1 / 3,
|
340 |
+
1,
|
341 |
+
3 / 6,
|
342 |
+
3 / 6,
|
343 |
+
]
|
344 |
+
|
345 |
+
|
346 |
+
class TestTransitivity:
|
347 |
+
def test_transitivity(self):
|
348 |
+
G = nx.Graph()
|
349 |
+
assert nx.transitivity(G) == 0
|
350 |
+
|
351 |
+
def test_path(self):
|
352 |
+
G = nx.path_graph(10)
|
353 |
+
assert nx.transitivity(G) == 0
|
354 |
+
|
355 |
+
def test_cubical(self):
|
356 |
+
G = nx.cubical_graph()
|
357 |
+
assert nx.transitivity(G) == 0
|
358 |
+
|
359 |
+
def test_k5(self):
|
360 |
+
G = nx.complete_graph(5)
|
361 |
+
assert nx.transitivity(G) == 1
|
362 |
+
G.remove_edge(1, 2)
|
363 |
+
assert nx.transitivity(G) == 0.875
|
364 |
+
|
365 |
+
|
366 |
+
class TestSquareClustering:
|
367 |
+
def test_clustering(self):
|
368 |
+
G = nx.Graph()
|
369 |
+
assert list(nx.square_clustering(G).values()) == []
|
370 |
+
assert nx.square_clustering(G) == {}
|
371 |
+
|
372 |
+
def test_path(self):
|
373 |
+
G = nx.path_graph(10)
|
374 |
+
assert list(nx.square_clustering(G).values()) == [
|
375 |
+
0,
|
376 |
+
0,
|
377 |
+
0,
|
378 |
+
0,
|
379 |
+
0,
|
380 |
+
0,
|
381 |
+
0,
|
382 |
+
0,
|
383 |
+
0,
|
384 |
+
0,
|
385 |
+
]
|
386 |
+
assert nx.square_clustering(G) == {
|
387 |
+
0: 0,
|
388 |
+
1: 0,
|
389 |
+
2: 0,
|
390 |
+
3: 0,
|
391 |
+
4: 0,
|
392 |
+
5: 0,
|
393 |
+
6: 0,
|
394 |
+
7: 0,
|
395 |
+
8: 0,
|
396 |
+
9: 0,
|
397 |
+
}
|
398 |
+
|
399 |
+
def test_cubical(self):
|
400 |
+
G = nx.cubical_graph()
|
401 |
+
assert list(nx.square_clustering(G).values()) == [
|
402 |
+
1 / 3,
|
403 |
+
1 / 3,
|
404 |
+
1 / 3,
|
405 |
+
1 / 3,
|
406 |
+
1 / 3,
|
407 |
+
1 / 3,
|
408 |
+
1 / 3,
|
409 |
+
1 / 3,
|
410 |
+
]
|
411 |
+
assert list(nx.square_clustering(G, [1, 2]).values()) == [1 / 3, 1 / 3]
|
412 |
+
assert nx.square_clustering(G, [1])[1] == 1 / 3
|
413 |
+
assert nx.square_clustering(G, 1) == 1 / 3
|
414 |
+
assert nx.square_clustering(G, [1, 2]) == {1: 1 / 3, 2: 1 / 3}
|
415 |
+
|
416 |
+
def test_k5(self):
|
417 |
+
G = nx.complete_graph(5)
|
418 |
+
assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1]
|
419 |
+
|
420 |
+
def test_bipartite_k5(self):
|
421 |
+
G = nx.complete_bipartite_graph(5, 5)
|
422 |
+
assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
|
423 |
+
|
424 |
+
def test_lind_square_clustering(self):
|
425 |
+
"""Test C4 for figure 1 Lind et al (2005)"""
|
426 |
+
G = nx.Graph(
|
427 |
+
[
|
428 |
+
(1, 2),
|
429 |
+
(1, 3),
|
430 |
+
(1, 6),
|
431 |
+
(1, 7),
|
432 |
+
(2, 4),
|
433 |
+
(2, 5),
|
434 |
+
(3, 4),
|
435 |
+
(3, 5),
|
436 |
+
(6, 7),
|
437 |
+
(7, 8),
|
438 |
+
(6, 8),
|
439 |
+
(7, 9),
|
440 |
+
(7, 10),
|
441 |
+
(6, 11),
|
442 |
+
(6, 12),
|
443 |
+
(2, 13),
|
444 |
+
(2, 14),
|
445 |
+
(3, 15),
|
446 |
+
(3, 16),
|
447 |
+
]
|
448 |
+
)
|
449 |
+
G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16])
|
450 |
+
G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12])
|
451 |
+
assert nx.square_clustering(G, [1])[1] == 3 / 43
|
452 |
+
assert nx.square_clustering(G1, [1])[1] == 2 / 6
|
453 |
+
assert nx.square_clustering(G2, [1])[1] == 1 / 5
|
454 |
+
|
455 |
+
def test_peng_square_clustering(self):
|
456 |
+
"""Test eq2 for figure 1 Peng et al (2008)"""
|
457 |
+
G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (3, 6)])
|
458 |
+
assert nx.square_clustering(G, [1])[1] == 1 / 3
|
459 |
+
|
460 |
+
def test_self_loops_square_clustering(self):
|
461 |
+
G = nx.path_graph(5)
|
462 |
+
assert nx.square_clustering(G) == {0: 0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0}
|
463 |
+
G.add_edges_from([(0, 0), (1, 1), (2, 2)])
|
464 |
+
assert nx.square_clustering(G) == {0: 1, 1: 0.5, 2: 0.2, 3: 0.0, 4: 0}
|
465 |
+
|
466 |
+
|
467 |
+
class TestAverageClustering:
|
468 |
+
@classmethod
|
469 |
+
def setup_class(cls):
|
470 |
+
pytest.importorskip("numpy")
|
471 |
+
|
472 |
+
def test_empty(self):
|
473 |
+
G = nx.Graph()
|
474 |
+
with pytest.raises(ZeroDivisionError):
|
475 |
+
nx.average_clustering(G)
|
476 |
+
|
477 |
+
def test_average_clustering(self):
|
478 |
+
G = nx.cycle_graph(3)
|
479 |
+
G.add_edge(2, 3)
|
480 |
+
assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 4
|
481 |
+
assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 4
|
482 |
+
assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 3
|
483 |
+
assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 3
|
484 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 3
|
485 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 2
|
486 |
+
|
487 |
+
def test_average_clustering_signed(self):
|
488 |
+
G = nx.cycle_graph(3)
|
489 |
+
G.add_edge(2, 3)
|
490 |
+
G.add_edge(0, 1, weight=-1)
|
491 |
+
assert nx.average_clustering(G, weight="weight") == (-1 - 1 - 1 / 3) / 4
|
492 |
+
assert (
|
493 |
+
nx.average_clustering(G, weight="weight", count_zeros=True)
|
494 |
+
== (-1 - 1 - 1 / 3) / 4
|
495 |
+
)
|
496 |
+
assert (
|
497 |
+
nx.average_clustering(G, weight="weight", count_zeros=False)
|
498 |
+
== (-1 - 1 - 1 / 3) / 3
|
499 |
+
)
|
500 |
+
|
501 |
+
|
502 |
+
class TestDirectedAverageClustering:
|
503 |
+
@classmethod
|
504 |
+
def setup_class(cls):
|
505 |
+
pytest.importorskip("numpy")
|
506 |
+
|
507 |
+
def test_empty(self):
|
508 |
+
G = nx.DiGraph()
|
509 |
+
with pytest.raises(ZeroDivisionError):
|
510 |
+
nx.average_clustering(G)
|
511 |
+
|
512 |
+
def test_average_clustering(self):
|
513 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
514 |
+
G.add_edge(2, 3)
|
515 |
+
assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 8
|
516 |
+
assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 8
|
517 |
+
assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 6
|
518 |
+
assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 6
|
519 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 6
|
520 |
+
assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 4
|
521 |
+
|
522 |
+
|
523 |
+
class TestGeneralizedDegree:
|
524 |
+
def test_generalized_degree(self):
|
525 |
+
G = nx.Graph()
|
526 |
+
assert nx.generalized_degree(G) == {}
|
527 |
+
|
528 |
+
def test_path(self):
|
529 |
+
G = nx.path_graph(5)
|
530 |
+
assert nx.generalized_degree(G, 0) == {0: 1}
|
531 |
+
assert nx.generalized_degree(G, 1) == {0: 2}
|
532 |
+
|
533 |
+
def test_cubical(self):
|
534 |
+
G = nx.cubical_graph()
|
535 |
+
assert nx.generalized_degree(G, 0) == {0: 3}
|
536 |
+
|
537 |
+
def test_k5(self):
|
538 |
+
G = nx.complete_graph(5)
|
539 |
+
assert nx.generalized_degree(G, 0) == {3: 4}
|
540 |
+
G.remove_edge(0, 1)
|
541 |
+
assert nx.generalized_degree(G, 0) == {2: 3}
|
542 |
+
assert nx.generalized_degree(G, [1, 2]) == {1: {2: 3}, 2: {2: 2, 3: 2}}
|
543 |
+
assert nx.generalized_degree(G) == {
|
544 |
+
0: {2: 3},
|
545 |
+
1: {2: 3},
|
546 |
+
2: {2: 2, 3: 2},
|
547 |
+
3: {2: 2, 3: 2},
|
548 |
+
4: {2: 2, 3: 2},
|
549 |
+
}
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_communicability.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import defaultdict
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
pytest.importorskip("numpy")
|
6 |
+
pytest.importorskip("scipy")
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
from networkx.algorithms.communicability_alg import communicability, communicability_exp
|
10 |
+
|
11 |
+
|
12 |
+
class TestCommunicability:
|
13 |
+
def test_communicability(self):
|
14 |
+
answer = {
|
15 |
+
0: {0: 1.5430806348152435, 1: 1.1752011936438012},
|
16 |
+
1: {0: 1.1752011936438012, 1: 1.5430806348152435},
|
17 |
+
}
|
18 |
+
# answer={(0, 0): 1.5430806348152435,
|
19 |
+
# (0, 1): 1.1752011936438012,
|
20 |
+
# (1, 0): 1.1752011936438012,
|
21 |
+
# (1, 1): 1.5430806348152435}
|
22 |
+
|
23 |
+
result = communicability(nx.path_graph(2))
|
24 |
+
for k1, val in result.items():
|
25 |
+
for k2 in val:
|
26 |
+
assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
|
27 |
+
|
28 |
+
def test_communicability2(self):
|
29 |
+
answer_orig = {
|
30 |
+
("1", "1"): 1.6445956054135658,
|
31 |
+
("1", "Albert"): 0.7430186221096251,
|
32 |
+
("1", "Aric"): 0.7430186221096251,
|
33 |
+
("1", "Dan"): 1.6208126320442937,
|
34 |
+
("1", "Franck"): 0.42639707170035257,
|
35 |
+
("Albert", "1"): 0.7430186221096251,
|
36 |
+
("Albert", "Albert"): 2.4368257358712189,
|
37 |
+
("Albert", "Aric"): 1.4368257358712191,
|
38 |
+
("Albert", "Dan"): 2.0472097037446453,
|
39 |
+
("Albert", "Franck"): 1.8340111678944691,
|
40 |
+
("Aric", "1"): 0.7430186221096251,
|
41 |
+
("Aric", "Albert"): 1.4368257358712191,
|
42 |
+
("Aric", "Aric"): 2.4368257358712193,
|
43 |
+
("Aric", "Dan"): 2.0472097037446457,
|
44 |
+
("Aric", "Franck"): 1.8340111678944691,
|
45 |
+
("Dan", "1"): 1.6208126320442937,
|
46 |
+
("Dan", "Albert"): 2.0472097037446453,
|
47 |
+
("Dan", "Aric"): 2.0472097037446457,
|
48 |
+
("Dan", "Dan"): 3.1306328496328168,
|
49 |
+
("Dan", "Franck"): 1.4860372442192515,
|
50 |
+
("Franck", "1"): 0.42639707170035257,
|
51 |
+
("Franck", "Albert"): 1.8340111678944691,
|
52 |
+
("Franck", "Aric"): 1.8340111678944691,
|
53 |
+
("Franck", "Dan"): 1.4860372442192515,
|
54 |
+
("Franck", "Franck"): 2.3876142275231915,
|
55 |
+
}
|
56 |
+
|
57 |
+
answer = defaultdict(dict)
|
58 |
+
for (k1, k2), v in answer_orig.items():
|
59 |
+
answer[k1][k2] = v
|
60 |
+
|
61 |
+
G1 = nx.Graph(
|
62 |
+
[
|
63 |
+
("Franck", "Aric"),
|
64 |
+
("Aric", "Dan"),
|
65 |
+
("Dan", "Albert"),
|
66 |
+
("Albert", "Franck"),
|
67 |
+
("Dan", "1"),
|
68 |
+
("Franck", "Albert"),
|
69 |
+
]
|
70 |
+
)
|
71 |
+
|
72 |
+
result = communicability(G1)
|
73 |
+
for k1, val in result.items():
|
74 |
+
for k2 in val:
|
75 |
+
assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
|
76 |
+
|
77 |
+
result = communicability_exp(G1)
|
78 |
+
for k1, val in result.items():
|
79 |
+
for k2 in val:
|
80 |
+
assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_covering.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
class TestMinEdgeCover:
|
7 |
+
"""Tests for :func:`networkx.algorithms.min_edge_cover`"""
|
8 |
+
|
9 |
+
def test_empty_graph(self):
|
10 |
+
G = nx.Graph()
|
11 |
+
assert nx.min_edge_cover(G) == set()
|
12 |
+
|
13 |
+
def test_graph_with_loop(self):
|
14 |
+
G = nx.Graph()
|
15 |
+
G.add_edge(0, 0)
|
16 |
+
assert nx.min_edge_cover(G) == {(0, 0)}
|
17 |
+
|
18 |
+
def test_graph_with_isolated_v(self):
|
19 |
+
G = nx.Graph()
|
20 |
+
G.add_node(1)
|
21 |
+
with pytest.raises(
|
22 |
+
nx.NetworkXException,
|
23 |
+
match="Graph has a node with no edge incident on it, so no edge cover exists.",
|
24 |
+
):
|
25 |
+
nx.min_edge_cover(G)
|
26 |
+
|
27 |
+
def test_graph_single_edge(self):
|
28 |
+
G = nx.Graph([(0, 1)])
|
29 |
+
assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
|
30 |
+
|
31 |
+
def test_graph_two_edge_path(self):
|
32 |
+
G = nx.path_graph(3)
|
33 |
+
min_cover = nx.min_edge_cover(G)
|
34 |
+
assert len(min_cover) == 2
|
35 |
+
for u, v in G.edges:
|
36 |
+
assert (u, v) in min_cover or (v, u) in min_cover
|
37 |
+
|
38 |
+
def test_bipartite_explicit(self):
|
39 |
+
G = nx.Graph()
|
40 |
+
G.add_nodes_from([1, 2, 3, 4], bipartite=0)
|
41 |
+
G.add_nodes_from(["a", "b", "c"], bipartite=1)
|
42 |
+
G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
|
43 |
+
# Use bipartite method by prescribing the algorithm
|
44 |
+
min_cover = nx.min_edge_cover(
|
45 |
+
G, nx.algorithms.bipartite.matching.eppstein_matching
|
46 |
+
)
|
47 |
+
assert nx.is_edge_cover(G, min_cover)
|
48 |
+
assert len(min_cover) == 8
|
49 |
+
# Use the default method which is not specialized for bipartite
|
50 |
+
min_cover2 = nx.min_edge_cover(G)
|
51 |
+
assert nx.is_edge_cover(G, min_cover2)
|
52 |
+
assert len(min_cover2) == 4
|
53 |
+
|
54 |
+
def test_complete_graph_even(self):
|
55 |
+
G = nx.complete_graph(10)
|
56 |
+
min_cover = nx.min_edge_cover(G)
|
57 |
+
assert nx.is_edge_cover(G, min_cover)
|
58 |
+
assert len(min_cover) == 5
|
59 |
+
|
60 |
+
def test_complete_graph_odd(self):
|
61 |
+
G = nx.complete_graph(11)
|
62 |
+
min_cover = nx.min_edge_cover(G)
|
63 |
+
assert nx.is_edge_cover(G, min_cover)
|
64 |
+
assert len(min_cover) == 6
|
65 |
+
|
66 |
+
|
67 |
+
class TestIsEdgeCover:
|
68 |
+
"""Tests for :func:`networkx.algorithms.is_edge_cover`"""
|
69 |
+
|
70 |
+
def test_empty_graph(self):
|
71 |
+
G = nx.Graph()
|
72 |
+
assert nx.is_edge_cover(G, set())
|
73 |
+
|
74 |
+
def test_graph_with_loop(self):
|
75 |
+
G = nx.Graph()
|
76 |
+
G.add_edge(1, 1)
|
77 |
+
assert nx.is_edge_cover(G, {(1, 1)})
|
78 |
+
|
79 |
+
def test_graph_single_edge(self):
|
80 |
+
G = nx.Graph()
|
81 |
+
G.add_edge(0, 1)
|
82 |
+
assert nx.is_edge_cover(G, {(0, 0), (1, 1)})
|
83 |
+
assert nx.is_edge_cover(G, {(0, 1), (1, 0)})
|
84 |
+
assert nx.is_edge_cover(G, {(0, 1)})
|
85 |
+
assert not nx.is_edge_cover(G, {(0, 0)})
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_cuts.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.cuts` module."""
|
2 |
+
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
|
7 |
+
class TestCutSize:
|
8 |
+
"""Unit tests for the :func:`~networkx.cut_size` function."""
|
9 |
+
|
10 |
+
def test_symmetric(self):
|
11 |
+
"""Tests that the cut size is symmetric."""
|
12 |
+
G = nx.barbell_graph(3, 0)
|
13 |
+
S = {0, 1, 4}
|
14 |
+
T = {2, 3, 5}
|
15 |
+
assert nx.cut_size(G, S, T) == 4
|
16 |
+
assert nx.cut_size(G, T, S) == 4
|
17 |
+
|
18 |
+
def test_single_edge(self):
|
19 |
+
"""Tests for a cut of a single edge."""
|
20 |
+
G = nx.barbell_graph(3, 0)
|
21 |
+
S = {0, 1, 2}
|
22 |
+
T = {3, 4, 5}
|
23 |
+
assert nx.cut_size(G, S, T) == 1
|
24 |
+
assert nx.cut_size(G, T, S) == 1
|
25 |
+
|
26 |
+
def test_directed(self):
|
27 |
+
"""Tests that each directed edge is counted once in the cut."""
|
28 |
+
G = nx.barbell_graph(3, 0).to_directed()
|
29 |
+
S = {0, 1, 2}
|
30 |
+
T = {3, 4, 5}
|
31 |
+
assert nx.cut_size(G, S, T) == 2
|
32 |
+
assert nx.cut_size(G, T, S) == 2
|
33 |
+
|
34 |
+
def test_directed_symmetric(self):
|
35 |
+
"""Tests that a cut in a directed graph is symmetric."""
|
36 |
+
G = nx.barbell_graph(3, 0).to_directed()
|
37 |
+
S = {0, 1, 4}
|
38 |
+
T = {2, 3, 5}
|
39 |
+
assert nx.cut_size(G, S, T) == 8
|
40 |
+
assert nx.cut_size(G, T, S) == 8
|
41 |
+
|
42 |
+
def test_multigraph(self):
|
43 |
+
"""Tests that parallel edges are each counted for a cut."""
|
44 |
+
G = nx.MultiGraph(["ab", "ab"])
|
45 |
+
assert nx.cut_size(G, {"a"}, {"b"}) == 2
|
46 |
+
|
47 |
+
|
48 |
+
class TestVolume:
|
49 |
+
"""Unit tests for the :func:`~networkx.volume` function."""
|
50 |
+
|
51 |
+
def test_graph(self):
|
52 |
+
G = nx.cycle_graph(4)
|
53 |
+
assert nx.volume(G, {0, 1}) == 4
|
54 |
+
|
55 |
+
def test_digraph(self):
|
56 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0)])
|
57 |
+
assert nx.volume(G, {0, 1}) == 2
|
58 |
+
|
59 |
+
def test_multigraph(self):
|
60 |
+
edges = list(nx.cycle_graph(4).edges())
|
61 |
+
G = nx.MultiGraph(edges * 2)
|
62 |
+
assert nx.volume(G, {0, 1}) == 8
|
63 |
+
|
64 |
+
def test_multidigraph(self):
|
65 |
+
edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
|
66 |
+
G = nx.MultiDiGraph(edges * 2)
|
67 |
+
assert nx.volume(G, {0, 1}) == 4
|
68 |
+
|
69 |
+
def test_barbell(self):
|
70 |
+
G = nx.barbell_graph(3, 0)
|
71 |
+
assert nx.volume(G, {0, 1, 2}) == 7
|
72 |
+
assert nx.volume(G, {3, 4, 5}) == 7
|
73 |
+
|
74 |
+
|
75 |
+
class TestNormalizedCutSize:
|
76 |
+
"""Unit tests for the :func:`~networkx.normalized_cut_size` function."""
|
77 |
+
|
78 |
+
def test_graph(self):
|
79 |
+
G = nx.path_graph(4)
|
80 |
+
S = {1, 2}
|
81 |
+
T = set(G) - S
|
82 |
+
size = nx.normalized_cut_size(G, S, T)
|
83 |
+
# The cut looks like this: o-{-o--o-}-o
|
84 |
+
expected = 2 * ((1 / 4) + (1 / 2))
|
85 |
+
assert expected == size
|
86 |
+
# Test with no input T
|
87 |
+
assert expected == nx.normalized_cut_size(G, S)
|
88 |
+
|
89 |
+
def test_directed(self):
|
90 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
|
91 |
+
S = {1, 2}
|
92 |
+
T = set(G) - S
|
93 |
+
size = nx.normalized_cut_size(G, S, T)
|
94 |
+
# The cut looks like this: o-{->o-->o-}->o
|
95 |
+
expected = 2 * ((1 / 2) + (1 / 1))
|
96 |
+
assert expected == size
|
97 |
+
# Test with no input T
|
98 |
+
assert expected == nx.normalized_cut_size(G, S)
|
99 |
+
|
100 |
+
|
101 |
+
class TestConductance:
|
102 |
+
"""Unit tests for the :func:`~networkx.conductance` function."""
|
103 |
+
|
104 |
+
def test_graph(self):
|
105 |
+
G = nx.barbell_graph(5, 0)
|
106 |
+
# Consider the singleton sets containing the "bridge" nodes.
|
107 |
+
# There is only one cut edge, and each set has volume five.
|
108 |
+
S = {4}
|
109 |
+
T = {5}
|
110 |
+
conductance = nx.conductance(G, S, T)
|
111 |
+
expected = 1 / 5
|
112 |
+
assert expected == conductance
|
113 |
+
# Test with no input T
|
114 |
+
G2 = nx.barbell_graph(3, 0)
|
115 |
+
# There is only one cut edge, and each set has volume seven.
|
116 |
+
S2 = {0, 1, 2}
|
117 |
+
assert nx.conductance(G2, S2) == 1 / 7
|
118 |
+
|
119 |
+
|
120 |
+
class TestEdgeExpansion:
|
121 |
+
"""Unit tests for the :func:`~networkx.edge_expansion` function."""
|
122 |
+
|
123 |
+
def test_graph(self):
|
124 |
+
G = nx.barbell_graph(5, 0)
|
125 |
+
S = set(range(5))
|
126 |
+
T = set(G) - S
|
127 |
+
expansion = nx.edge_expansion(G, S, T)
|
128 |
+
expected = 1 / 5
|
129 |
+
assert expected == expansion
|
130 |
+
# Test with no input T
|
131 |
+
assert expected == nx.edge_expansion(G, S)
|
132 |
+
|
133 |
+
|
134 |
+
class TestNodeExpansion:
|
135 |
+
"""Unit tests for the :func:`~networkx.node_expansion` function."""
|
136 |
+
|
137 |
+
def test_graph(self):
|
138 |
+
G = nx.path_graph(8)
|
139 |
+
S = {3, 4, 5}
|
140 |
+
expansion = nx.node_expansion(G, S)
|
141 |
+
# The neighborhood of S has cardinality five, and S has
|
142 |
+
# cardinality three.
|
143 |
+
expected = 5 / 3
|
144 |
+
assert expected == expansion
|
145 |
+
|
146 |
+
|
147 |
+
class TestBoundaryExpansion:
|
148 |
+
"""Unit tests for the :func:`~networkx.boundary_expansion` function."""
|
149 |
+
|
150 |
+
def test_graph(self):
|
151 |
+
G = nx.complete_graph(10)
|
152 |
+
S = set(range(4))
|
153 |
+
expansion = nx.boundary_expansion(G, S)
|
154 |
+
# The node boundary of S has cardinality six, and S has
|
155 |
+
# cardinality three.
|
156 |
+
expected = 6 / 4
|
157 |
+
assert expected == expansion
|
158 |
+
|
159 |
+
|
160 |
+
class TestMixingExpansion:
|
161 |
+
"""Unit tests for the :func:`~networkx.mixing_expansion` function."""
|
162 |
+
|
163 |
+
def test_graph(self):
|
164 |
+
G = nx.barbell_graph(5, 0)
|
165 |
+
S = set(range(5))
|
166 |
+
T = set(G) - S
|
167 |
+
expansion = nx.mixing_expansion(G, S, T)
|
168 |
+
# There is one cut edge, and the total number of edges in the
|
169 |
+
# graph is twice the total number of edges in a clique of size
|
170 |
+
# five, plus one more for the bridge.
|
171 |
+
expected = 1 / (2 * (5 * 4 + 1))
|
172 |
+
assert expected == expansion
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_cycles.py
ADDED
@@ -0,0 +1,974 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import chain, islice, tee
|
2 |
+
from math import inf
|
3 |
+
from random import shuffle
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
from networkx.algorithms.traversal.edgedfs import FORWARD, REVERSE
|
9 |
+
|
10 |
+
|
11 |
+
def check_independent(basis):
|
12 |
+
if len(basis) == 0:
|
13 |
+
return
|
14 |
+
|
15 |
+
np = pytest.importorskip("numpy")
|
16 |
+
sp = pytest.importorskip("scipy") # Required by incidence_matrix
|
17 |
+
|
18 |
+
H = nx.Graph()
|
19 |
+
for b in basis:
|
20 |
+
nx.add_cycle(H, b)
|
21 |
+
inc = nx.incidence_matrix(H, oriented=True)
|
22 |
+
rank = np.linalg.matrix_rank(inc.toarray(), tol=None, hermitian=False)
|
23 |
+
assert inc.shape[1] - rank == len(basis)
|
24 |
+
|
25 |
+
|
26 |
+
class TestCycles:
|
27 |
+
@classmethod
|
28 |
+
def setup_class(cls):
|
29 |
+
G = nx.Graph()
|
30 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
31 |
+
nx.add_cycle(G, [0, 3, 4, 5])
|
32 |
+
nx.add_cycle(G, [0, 1, 6, 7, 8])
|
33 |
+
G.add_edge(8, 9)
|
34 |
+
cls.G = G
|
35 |
+
|
36 |
+
def is_cyclic_permutation(self, a, b):
|
37 |
+
n = len(a)
|
38 |
+
if len(b) != n:
|
39 |
+
return False
|
40 |
+
l = a + a
|
41 |
+
return any(l[i : i + n] == b for i in range(n))
|
42 |
+
|
43 |
+
def test_cycle_basis(self):
|
44 |
+
G = self.G
|
45 |
+
cy = nx.cycle_basis(G, 0)
|
46 |
+
sort_cy = sorted(sorted(c) for c in cy)
|
47 |
+
assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
|
48 |
+
cy = nx.cycle_basis(G, 1)
|
49 |
+
sort_cy = sorted(sorted(c) for c in cy)
|
50 |
+
assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
|
51 |
+
cy = nx.cycle_basis(G, 9)
|
52 |
+
sort_cy = sorted(sorted(c) for c in cy)
|
53 |
+
assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
|
54 |
+
# test disconnected graphs
|
55 |
+
nx.add_cycle(G, "ABC")
|
56 |
+
cy = nx.cycle_basis(G, 9)
|
57 |
+
sort_cy = sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
|
58 |
+
assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5], ["A", "B", "C"]]
|
59 |
+
|
60 |
+
def test_cycle_basis2(self):
|
61 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
62 |
+
G = nx.DiGraph()
|
63 |
+
cy = nx.cycle_basis(G, 0)
|
64 |
+
|
65 |
+
def test_cycle_basis3(self):
|
66 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
67 |
+
G = nx.MultiGraph()
|
68 |
+
cy = nx.cycle_basis(G, 0)
|
69 |
+
|
70 |
+
def test_cycle_basis_ordered(self):
|
71 |
+
# see gh-6654 replace sets with (ordered) dicts
|
72 |
+
G = nx.cycle_graph(5)
|
73 |
+
G.update(nx.cycle_graph(range(3, 8)))
|
74 |
+
cbG = nx.cycle_basis(G)
|
75 |
+
|
76 |
+
perm = {1: 0, 0: 1} # switch 0 and 1
|
77 |
+
H = nx.relabel_nodes(G, perm)
|
78 |
+
cbH = [[perm.get(n, n) for n in cyc] for cyc in nx.cycle_basis(H)]
|
79 |
+
assert cbG == cbH
|
80 |
+
|
81 |
+
def test_cycle_basis_self_loop(self):
|
82 |
+
"""Tests the function for graphs with self loops"""
|
83 |
+
G = nx.Graph()
|
84 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
85 |
+
nx.add_cycle(G, [0, 0, 6, 2])
|
86 |
+
cy = nx.cycle_basis(G)
|
87 |
+
sort_cy = sorted(sorted(c) for c in cy)
|
88 |
+
assert sort_cy == [[0], [0, 1, 2], [0, 2, 3], [0, 2, 6]]
|
89 |
+
|
90 |
+
def test_simple_cycles(self):
|
91 |
+
edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
|
92 |
+
G = nx.DiGraph(edges)
|
93 |
+
cc = sorted(nx.simple_cycles(G))
|
94 |
+
ca = [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
|
95 |
+
assert len(cc) == len(ca)
|
96 |
+
for c in cc:
|
97 |
+
assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
|
98 |
+
|
99 |
+
def test_simple_cycles_singleton(self):
|
100 |
+
G = nx.Graph([(0, 0)]) # self-loop
|
101 |
+
assert list(nx.simple_cycles(G)) == [[0]]
|
102 |
+
|
103 |
+
def test_unsortable(self):
|
104 |
+
# this test ensures that graphs whose nodes without an intrinsic
|
105 |
+
# ordering do not cause issues
|
106 |
+
G = nx.DiGraph()
|
107 |
+
nx.add_cycle(G, ["a", 1])
|
108 |
+
c = list(nx.simple_cycles(G))
|
109 |
+
assert len(c) == 1
|
110 |
+
|
111 |
+
def test_simple_cycles_small(self):
|
112 |
+
G = nx.DiGraph()
|
113 |
+
nx.add_cycle(G, [1, 2, 3])
|
114 |
+
c = sorted(nx.simple_cycles(G))
|
115 |
+
assert len(c) == 1
|
116 |
+
assert self.is_cyclic_permutation(c[0], [1, 2, 3])
|
117 |
+
nx.add_cycle(G, [10, 20, 30])
|
118 |
+
cc = sorted(nx.simple_cycles(G))
|
119 |
+
assert len(cc) == 2
|
120 |
+
ca = [[1, 2, 3], [10, 20, 30]]
|
121 |
+
for c in cc:
|
122 |
+
assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
|
123 |
+
|
124 |
+
def test_simple_cycles_empty(self):
|
125 |
+
G = nx.DiGraph()
|
126 |
+
assert list(nx.simple_cycles(G)) == []
|
127 |
+
|
128 |
+
def worst_case_graph(self, k):
|
129 |
+
# see figure 1 in Johnson's paper
|
130 |
+
# this graph has exactly 3k simple cycles
|
131 |
+
G = nx.DiGraph()
|
132 |
+
for n in range(2, k + 2):
|
133 |
+
G.add_edge(1, n)
|
134 |
+
G.add_edge(n, k + 2)
|
135 |
+
G.add_edge(2 * k + 1, 1)
|
136 |
+
for n in range(k + 2, 2 * k + 2):
|
137 |
+
G.add_edge(n, 2 * k + 2)
|
138 |
+
G.add_edge(n, n + 1)
|
139 |
+
G.add_edge(2 * k + 3, k + 2)
|
140 |
+
for n in range(2 * k + 3, 3 * k + 3):
|
141 |
+
G.add_edge(2 * k + 2, n)
|
142 |
+
G.add_edge(n, 3 * k + 3)
|
143 |
+
G.add_edge(3 * k + 3, 2 * k + 2)
|
144 |
+
return G
|
145 |
+
|
146 |
+
def test_worst_case_graph(self):
|
147 |
+
# see figure 1 in Johnson's paper
|
148 |
+
for k in range(3, 10):
|
149 |
+
G = self.worst_case_graph(k)
|
150 |
+
l = len(list(nx.simple_cycles(G)))
|
151 |
+
assert l == 3 * k
|
152 |
+
|
153 |
+
def test_recursive_simple_and_not(self):
|
154 |
+
for k in range(2, 10):
|
155 |
+
G = self.worst_case_graph(k)
|
156 |
+
cc = sorted(nx.simple_cycles(G))
|
157 |
+
rcc = sorted(nx.recursive_simple_cycles(G))
|
158 |
+
assert len(cc) == len(rcc)
|
159 |
+
for c in cc:
|
160 |
+
assert any(self.is_cyclic_permutation(c, r) for r in rcc)
|
161 |
+
for rc in rcc:
|
162 |
+
assert any(self.is_cyclic_permutation(rc, c) for c in cc)
|
163 |
+
|
164 |
+
def test_simple_graph_with_reported_bug(self):
|
165 |
+
G = nx.DiGraph()
|
166 |
+
edges = [
|
167 |
+
(0, 2),
|
168 |
+
(0, 3),
|
169 |
+
(1, 0),
|
170 |
+
(1, 3),
|
171 |
+
(2, 1),
|
172 |
+
(2, 4),
|
173 |
+
(3, 2),
|
174 |
+
(3, 4),
|
175 |
+
(4, 0),
|
176 |
+
(4, 1),
|
177 |
+
(4, 5),
|
178 |
+
(5, 0),
|
179 |
+
(5, 1),
|
180 |
+
(5, 2),
|
181 |
+
(5, 3),
|
182 |
+
]
|
183 |
+
G.add_edges_from(edges)
|
184 |
+
cc = sorted(nx.simple_cycles(G))
|
185 |
+
assert len(cc) == 26
|
186 |
+
rcc = sorted(nx.recursive_simple_cycles(G))
|
187 |
+
assert len(cc) == len(rcc)
|
188 |
+
for c in cc:
|
189 |
+
assert any(self.is_cyclic_permutation(c, rc) for rc in rcc)
|
190 |
+
for rc in rcc:
|
191 |
+
assert any(self.is_cyclic_permutation(rc, c) for c in cc)
|
192 |
+
|
193 |
+
|
194 |
+
def pairwise(iterable):
|
195 |
+
a, b = tee(iterable)
|
196 |
+
next(b, None)
|
197 |
+
return zip(a, b)
|
198 |
+
|
199 |
+
|
200 |
+
def cycle_edges(c):
|
201 |
+
return pairwise(chain(c, islice(c, 1)))
|
202 |
+
|
203 |
+
|
204 |
+
def directed_cycle_edgeset(c):
|
205 |
+
return frozenset(cycle_edges(c))
|
206 |
+
|
207 |
+
|
208 |
+
def undirected_cycle_edgeset(c):
|
209 |
+
if len(c) == 1:
|
210 |
+
return frozenset(cycle_edges(c))
|
211 |
+
return frozenset(map(frozenset, cycle_edges(c)))
|
212 |
+
|
213 |
+
|
214 |
+
def multigraph_cycle_edgeset(c):
|
215 |
+
if len(c) <= 2:
|
216 |
+
return frozenset(cycle_edges(c))
|
217 |
+
else:
|
218 |
+
return frozenset(map(frozenset, cycle_edges(c)))
|
219 |
+
|
220 |
+
|
221 |
+
class TestCycleEnumeration:
|
222 |
+
@staticmethod
|
223 |
+
def K(n):
|
224 |
+
return nx.complete_graph(n)
|
225 |
+
|
226 |
+
@staticmethod
|
227 |
+
def D(n):
|
228 |
+
return nx.complete_graph(n).to_directed()
|
229 |
+
|
230 |
+
@staticmethod
|
231 |
+
def edgeset_function(g):
|
232 |
+
if g.is_directed():
|
233 |
+
return directed_cycle_edgeset
|
234 |
+
elif g.is_multigraph():
|
235 |
+
return multigraph_cycle_edgeset
|
236 |
+
else:
|
237 |
+
return undirected_cycle_edgeset
|
238 |
+
|
239 |
+
def check_cycle(self, g, c, es, cache, source, original_c, length_bound, chordless):
|
240 |
+
if length_bound is not None and len(c) > length_bound:
|
241 |
+
raise RuntimeError(
|
242 |
+
f"computed cycle {original_c} exceeds length bound {length_bound}"
|
243 |
+
)
|
244 |
+
if source == "computed":
|
245 |
+
if es in cache:
|
246 |
+
raise RuntimeError(
|
247 |
+
f"computed cycle {original_c} has already been found!"
|
248 |
+
)
|
249 |
+
else:
|
250 |
+
cache[es] = tuple(original_c)
|
251 |
+
else:
|
252 |
+
if es in cache:
|
253 |
+
cache.pop(es)
|
254 |
+
else:
|
255 |
+
raise RuntimeError(f"expected cycle {original_c} was not computed")
|
256 |
+
|
257 |
+
if not all(g.has_edge(*e) for e in es):
|
258 |
+
raise RuntimeError(
|
259 |
+
f"{source} claimed cycle {original_c} is not a cycle of g"
|
260 |
+
)
|
261 |
+
if chordless and len(g.subgraph(c).edges) > len(c):
|
262 |
+
raise RuntimeError(f"{source} cycle {original_c} is not chordless")
|
263 |
+
|
264 |
+
def check_cycle_algorithm(
|
265 |
+
self,
|
266 |
+
g,
|
267 |
+
expected_cycles,
|
268 |
+
length_bound=None,
|
269 |
+
chordless=False,
|
270 |
+
algorithm=None,
|
271 |
+
):
|
272 |
+
if algorithm is None:
|
273 |
+
algorithm = nx.chordless_cycles if chordless else nx.simple_cycles
|
274 |
+
|
275 |
+
# note: we shuffle the labels of g to rule out accidentally-correct
|
276 |
+
# behavior which occurred during the development of chordless cycle
|
277 |
+
# enumeration algorithms
|
278 |
+
|
279 |
+
relabel = list(range(len(g)))
|
280 |
+
shuffle(relabel)
|
281 |
+
label = dict(zip(g, relabel))
|
282 |
+
unlabel = dict(zip(relabel, g))
|
283 |
+
h = nx.relabel_nodes(g, label, copy=True)
|
284 |
+
|
285 |
+
edgeset = self.edgeset_function(h)
|
286 |
+
|
287 |
+
params = {}
|
288 |
+
if length_bound is not None:
|
289 |
+
params["length_bound"] = length_bound
|
290 |
+
|
291 |
+
cycle_cache = {}
|
292 |
+
for c in algorithm(h, **params):
|
293 |
+
original_c = [unlabel[x] for x in c]
|
294 |
+
es = edgeset(c)
|
295 |
+
self.check_cycle(
|
296 |
+
h, c, es, cycle_cache, "computed", original_c, length_bound, chordless
|
297 |
+
)
|
298 |
+
|
299 |
+
if isinstance(expected_cycles, int):
|
300 |
+
if len(cycle_cache) != expected_cycles:
|
301 |
+
raise RuntimeError(
|
302 |
+
f"expected {expected_cycles} cycles, got {len(cycle_cache)}"
|
303 |
+
)
|
304 |
+
return
|
305 |
+
for original_c in expected_cycles:
|
306 |
+
c = [label[x] for x in original_c]
|
307 |
+
es = edgeset(c)
|
308 |
+
self.check_cycle(
|
309 |
+
h, c, es, cycle_cache, "expected", original_c, length_bound, chordless
|
310 |
+
)
|
311 |
+
|
312 |
+
if len(cycle_cache):
|
313 |
+
for c in cycle_cache.values():
|
314 |
+
raise RuntimeError(
|
315 |
+
f"computed cycle {c} is valid but not in the expected cycle set!"
|
316 |
+
)
|
317 |
+
|
318 |
+
def check_cycle_enumeration_integer_sequence(
|
319 |
+
self,
|
320 |
+
g_family,
|
321 |
+
cycle_counts,
|
322 |
+
length_bound=None,
|
323 |
+
chordless=False,
|
324 |
+
algorithm=None,
|
325 |
+
):
|
326 |
+
for g, num_cycles in zip(g_family, cycle_counts):
|
327 |
+
self.check_cycle_algorithm(
|
328 |
+
g,
|
329 |
+
num_cycles,
|
330 |
+
length_bound=length_bound,
|
331 |
+
chordless=chordless,
|
332 |
+
algorithm=algorithm,
|
333 |
+
)
|
334 |
+
|
335 |
+
def test_directed_chordless_cycle_digons(self):
|
336 |
+
g = nx.DiGraph()
|
337 |
+
nx.add_cycle(g, range(5))
|
338 |
+
nx.add_cycle(g, range(5)[::-1])
|
339 |
+
g.add_edge(0, 0)
|
340 |
+
expected_cycles = [(0,), (1, 2), (2, 3), (3, 4)]
|
341 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
342 |
+
|
343 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=2)
|
344 |
+
|
345 |
+
expected_cycles = [c for c in expected_cycles if len(c) < 2]
|
346 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=1)
|
347 |
+
|
348 |
+
def test_directed_chordless_cycle_undirected(self):
|
349 |
+
g = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (5, 1), (0, 2)])
|
350 |
+
expected_cycles = [(0, 2, 3, 4, 5), (1, 2, 3, 4, 5)]
|
351 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
352 |
+
|
353 |
+
g = nx.DiGraph()
|
354 |
+
nx.add_cycle(g, range(5))
|
355 |
+
nx.add_cycle(g, range(4, 9))
|
356 |
+
g.add_edge(7, 3)
|
357 |
+
expected_cycles = [(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (4, 5, 6, 7, 8)]
|
358 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
359 |
+
|
360 |
+
g.add_edge(3, 7)
|
361 |
+
expected_cycles = [(0, 1, 2, 3, 4), (3, 7), (4, 5, 6, 7, 8)]
|
362 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
363 |
+
|
364 |
+
expected_cycles = [(3, 7)]
|
365 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=4)
|
366 |
+
|
367 |
+
g.remove_edge(7, 3)
|
368 |
+
expected_cycles = [(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)]
|
369 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
370 |
+
|
371 |
+
g = nx.DiGraph((i, j) for i in range(10) for j in range(i))
|
372 |
+
expected_cycles = []
|
373 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
374 |
+
|
375 |
+
def test_chordless_cycles_directed(self):
|
376 |
+
G = nx.DiGraph()
|
377 |
+
nx.add_cycle(G, range(5))
|
378 |
+
nx.add_cycle(G, range(4, 12))
|
379 |
+
expected = [[*range(5)], [*range(4, 12)]]
|
380 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
381 |
+
self.check_cycle_algorithm(
|
382 |
+
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
|
383 |
+
)
|
384 |
+
|
385 |
+
G.add_edge(7, 3)
|
386 |
+
expected.append([*range(3, 8)])
|
387 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
388 |
+
self.check_cycle_algorithm(
|
389 |
+
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
|
390 |
+
)
|
391 |
+
|
392 |
+
G.add_edge(3, 7)
|
393 |
+
expected[-1] = [7, 3]
|
394 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
395 |
+
self.check_cycle_algorithm(
|
396 |
+
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
|
397 |
+
)
|
398 |
+
|
399 |
+
expected.pop()
|
400 |
+
G.remove_edge(7, 3)
|
401 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
402 |
+
self.check_cycle_algorithm(
|
403 |
+
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
|
404 |
+
)
|
405 |
+
|
406 |
+
def test_directed_chordless_cycle_diclique(self):
|
407 |
+
g_family = [self.D(n) for n in range(10)]
|
408 |
+
expected_cycles = [(n * n - n) // 2 for n in range(10)]
|
409 |
+
self.check_cycle_enumeration_integer_sequence(
|
410 |
+
g_family, expected_cycles, chordless=True
|
411 |
+
)
|
412 |
+
|
413 |
+
expected_cycles = [(n * n - n) // 2 for n in range(10)]
|
414 |
+
self.check_cycle_enumeration_integer_sequence(
|
415 |
+
g_family, expected_cycles, length_bound=2
|
416 |
+
)
|
417 |
+
|
418 |
+
def test_directed_chordless_loop_blockade(self):
|
419 |
+
g = nx.DiGraph((i, i) for i in range(10))
|
420 |
+
nx.add_cycle(g, range(10))
|
421 |
+
expected_cycles = [(i,) for i in range(10)]
|
422 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
423 |
+
|
424 |
+
self.check_cycle_algorithm(g, expected_cycles, length_bound=1)
|
425 |
+
|
426 |
+
g = nx.MultiDiGraph(g)
|
427 |
+
g.add_edges_from((i, i) for i in range(0, 10, 2))
|
428 |
+
expected_cycles = [(i,) for i in range(1, 10, 2)]
|
429 |
+
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
|
430 |
+
|
431 |
+
def test_simple_cycles_notable_clique_sequences(self):
|
432 |
+
# A000292: Number of labeled graphs on n+3 nodes that are triangles.
|
433 |
+
g_family = [self.K(n) for n in range(2, 12)]
|
434 |
+
expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220]
|
435 |
+
self.check_cycle_enumeration_integer_sequence(
|
436 |
+
g_family, expected, length_bound=3
|
437 |
+
)
|
438 |
+
|
439 |
+
def triangles(g, **kwargs):
|
440 |
+
yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 3)
|
441 |
+
|
442 |
+
# directed complete graphs have twice as many triangles thanks to reversal
|
443 |
+
g_family = [self.D(n) for n in range(2, 12)]
|
444 |
+
expected = [2 * e for e in expected]
|
445 |
+
self.check_cycle_enumeration_integer_sequence(
|
446 |
+
g_family, expected, length_bound=3, algorithm=triangles
|
447 |
+
)
|
448 |
+
|
449 |
+
def four_cycles(g, **kwargs):
|
450 |
+
yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 4)
|
451 |
+
|
452 |
+
# A050534: the number of 4-cycles in the complete graph K_{n+1}
|
453 |
+
expected = [0, 0, 0, 3, 15, 45, 105, 210, 378, 630, 990]
|
454 |
+
g_family = [self.K(n) for n in range(1, 12)]
|
455 |
+
self.check_cycle_enumeration_integer_sequence(
|
456 |
+
g_family, expected, length_bound=4, algorithm=four_cycles
|
457 |
+
)
|
458 |
+
|
459 |
+
# directed complete graphs have twice as many 4-cycles thanks to reversal
|
460 |
+
expected = [2 * e for e in expected]
|
461 |
+
g_family = [self.D(n) for n in range(1, 15)]
|
462 |
+
self.check_cycle_enumeration_integer_sequence(
|
463 |
+
g_family, expected, length_bound=4, algorithm=four_cycles
|
464 |
+
)
|
465 |
+
|
466 |
+
# A006231: the number of elementary circuits in a complete directed graph with n nodes
|
467 |
+
expected = [0, 1, 5, 20, 84, 409, 2365]
|
468 |
+
g_family = [self.D(n) for n in range(1, 8)]
|
469 |
+
self.check_cycle_enumeration_integer_sequence(g_family, expected)
|
470 |
+
|
471 |
+
# A002807: Number of cycles in the complete graph on n nodes K_{n}.
|
472 |
+
expected = [0, 0, 0, 1, 7, 37, 197, 1172]
|
473 |
+
g_family = [self.K(n) for n in range(8)]
|
474 |
+
self.check_cycle_enumeration_integer_sequence(g_family, expected)
|
475 |
+
|
476 |
+
def test_directed_chordless_cycle_parallel_multiedges(self):
|
477 |
+
g = nx.MultiGraph()
|
478 |
+
|
479 |
+
nx.add_cycle(g, range(5))
|
480 |
+
expected = [[*range(5)]]
|
481 |
+
self.check_cycle_algorithm(g, expected, chordless=True)
|
482 |
+
|
483 |
+
nx.add_cycle(g, range(5))
|
484 |
+
expected = [*cycle_edges(range(5))]
|
485 |
+
self.check_cycle_algorithm(g, expected, chordless=True)
|
486 |
+
|
487 |
+
nx.add_cycle(g, range(5))
|
488 |
+
expected = []
|
489 |
+
self.check_cycle_algorithm(g, expected, chordless=True)
|
490 |
+
|
491 |
+
g = nx.MultiDiGraph()
|
492 |
+
|
493 |
+
nx.add_cycle(g, range(5))
|
494 |
+
expected = [[*range(5)]]
|
495 |
+
self.check_cycle_algorithm(g, expected, chordless=True)
|
496 |
+
|
497 |
+
nx.add_cycle(g, range(5))
|
498 |
+
self.check_cycle_algorithm(g, [], chordless=True)
|
499 |
+
|
500 |
+
nx.add_cycle(g, range(5))
|
501 |
+
self.check_cycle_algorithm(g, [], chordless=True)
|
502 |
+
|
503 |
+
g = nx.MultiDiGraph()
|
504 |
+
|
505 |
+
nx.add_cycle(g, range(5))
|
506 |
+
nx.add_cycle(g, range(5)[::-1])
|
507 |
+
expected = [*cycle_edges(range(5))]
|
508 |
+
self.check_cycle_algorithm(g, expected, chordless=True)
|
509 |
+
|
510 |
+
nx.add_cycle(g, range(5))
|
511 |
+
self.check_cycle_algorithm(g, [], chordless=True)
|
512 |
+
|
513 |
+
def test_chordless_cycles_graph(self):
|
514 |
+
G = nx.Graph()
|
515 |
+
nx.add_cycle(G, range(5))
|
516 |
+
nx.add_cycle(G, range(4, 12))
|
517 |
+
expected = [[*range(5)], [*range(4, 12)]]
|
518 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
519 |
+
self.check_cycle_algorithm(
|
520 |
+
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
|
521 |
+
)
|
522 |
+
|
523 |
+
G.add_edge(7, 3)
|
524 |
+
expected.append([*range(3, 8)])
|
525 |
+
expected.append([4, 3, 7, 8, 9, 10, 11])
|
526 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
527 |
+
self.check_cycle_algorithm(
|
528 |
+
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
|
529 |
+
)
|
530 |
+
|
531 |
+
def test_chordless_cycles_giant_hamiltonian(self):
|
532 |
+
# ... o - e - o - e - o ... # o = odd, e = even
|
533 |
+
# ... ---/ \-----/ \--- ... # <-- "long" edges
|
534 |
+
#
|
535 |
+
# each long edge belongs to exactly one triangle, and one giant cycle
|
536 |
+
# of length n/2. The remaining edges each belong to a triangle
|
537 |
+
|
538 |
+
n = 1000
|
539 |
+
assert n % 2 == 0
|
540 |
+
G = nx.Graph()
|
541 |
+
for v in range(n):
|
542 |
+
if not v % 2:
|
543 |
+
G.add_edge(v, (v + 2) % n)
|
544 |
+
G.add_edge(v, (v + 1) % n)
|
545 |
+
|
546 |
+
expected = [[*range(0, n, 2)]] + [
|
547 |
+
[x % n for x in range(i, i + 3)] for i in range(0, n, 2)
|
548 |
+
]
|
549 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
550 |
+
self.check_cycle_algorithm(
|
551 |
+
G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
|
552 |
+
)
|
553 |
+
|
554 |
+
# ... o -> e -> o -> e -> o ... # o = odd, e = even
|
555 |
+
# ... <---/ \---<---/ \---< ... # <-- "long" edges
|
556 |
+
#
|
557 |
+
# this time, we orient the short and long edges in opposition
|
558 |
+
# the cycle structure of this graph is the same, but we need to reverse
|
559 |
+
# the long one in our representation. Also, we need to drop the size
|
560 |
+
# because our partitioning algorithm uses strongly connected components
|
561 |
+
# instead of separating graphs by their strong articulation points
|
562 |
+
|
563 |
+
n = 100
|
564 |
+
assert n % 2 == 0
|
565 |
+
G = nx.DiGraph()
|
566 |
+
for v in range(n):
|
567 |
+
G.add_edge(v, (v + 1) % n)
|
568 |
+
if not v % 2:
|
569 |
+
G.add_edge((v + 2) % n, v)
|
570 |
+
|
571 |
+
expected = [[*range(n - 2, -2, -2)]] + [
|
572 |
+
[x % n for x in range(i, i + 3)] for i in range(0, n, 2)
|
573 |
+
]
|
574 |
+
self.check_cycle_algorithm(G, expected, chordless=True)
|
575 |
+
self.check_cycle_algorithm(
|
576 |
+
G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
|
577 |
+
)
|
578 |
+
|
579 |
+
def test_simple_cycles_acyclic_tournament(self):
|
580 |
+
n = 10
|
581 |
+
G = nx.DiGraph((x, y) for x in range(n) for y in range(x))
|
582 |
+
self.check_cycle_algorithm(G, [])
|
583 |
+
self.check_cycle_algorithm(G, [], chordless=True)
|
584 |
+
|
585 |
+
for k in range(n + 1):
|
586 |
+
self.check_cycle_algorithm(G, [], length_bound=k)
|
587 |
+
self.check_cycle_algorithm(G, [], length_bound=k, chordless=True)
|
588 |
+
|
589 |
+
def test_simple_cycles_graph(self):
|
590 |
+
testG = nx.cycle_graph(8)
|
591 |
+
cyc1 = tuple(range(8))
|
592 |
+
self.check_cycle_algorithm(testG, [cyc1])
|
593 |
+
|
594 |
+
testG.add_edge(4, -1)
|
595 |
+
nx.add_path(testG, [3, -2, -3, -4])
|
596 |
+
self.check_cycle_algorithm(testG, [cyc1])
|
597 |
+
|
598 |
+
testG.update(nx.cycle_graph(range(8, 16)))
|
599 |
+
cyc2 = tuple(range(8, 16))
|
600 |
+
self.check_cycle_algorithm(testG, [cyc1, cyc2])
|
601 |
+
|
602 |
+
testG.update(nx.cycle_graph(range(4, 12)))
|
603 |
+
cyc3 = tuple(range(4, 12))
|
604 |
+
expected = {
|
605 |
+
(0, 1, 2, 3, 4, 5, 6, 7), # cyc1
|
606 |
+
(8, 9, 10, 11, 12, 13, 14, 15), # cyc2
|
607 |
+
(4, 5, 6, 7, 8, 9, 10, 11), # cyc3
|
608 |
+
(4, 5, 6, 7, 8, 15, 14, 13, 12, 11), # cyc2 + cyc3
|
609 |
+
(0, 1, 2, 3, 4, 11, 10, 9, 8, 7), # cyc1 + cyc3
|
610 |
+
(0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 8, 7), # cyc1 + cyc2 + cyc3
|
611 |
+
}
|
612 |
+
self.check_cycle_algorithm(testG, expected)
|
613 |
+
assert len(expected) == (2**3 - 1) - 1 # 1 disjoint comb: cyc1 + cyc2
|
614 |
+
|
615 |
+
# Basis size = 5 (2 loops overlapping gives 5 small loops
|
616 |
+
# E
|
617 |
+
# / \ Note: A-F = 10-15
|
618 |
+
# 1-2-3-4-5
|
619 |
+
# / | | \ cyc1=012DAB -- left
|
620 |
+
# 0 D F 6 cyc2=234E -- top
|
621 |
+
# \ | | / cyc3=45678F -- right
|
622 |
+
# B-A-9-8-7 cyc4=89AC -- bottom
|
623 |
+
# \ / cyc5=234F89AD -- middle
|
624 |
+
# C
|
625 |
+
#
|
626 |
+
# combinations of 5 basis elements: 2^5 - 1 (one includes no cycles)
|
627 |
+
#
|
628 |
+
# disjoint combs: (11 total) not simple cycles
|
629 |
+
# Any pair not including cyc5 => choose(4, 2) = 6
|
630 |
+
# Any triple not including cyc5 => choose(4, 3) = 4
|
631 |
+
# Any quad not including cyc5 => choose(4, 4) = 1
|
632 |
+
#
|
633 |
+
# we expect 31 - 11 = 20 simple cycles
|
634 |
+
#
|
635 |
+
testG = nx.cycle_graph(12)
|
636 |
+
testG.update(nx.cycle_graph([12, 10, 13, 2, 14, 4, 15, 8]).edges)
|
637 |
+
expected = (2**5 - 1) - 11 # 11 disjoint combinations
|
638 |
+
self.check_cycle_algorithm(testG, expected)
|
639 |
+
|
640 |
+
def test_simple_cycles_bounded(self):
|
641 |
+
# iteratively construct a cluster of nested cycles running in the same direction
|
642 |
+
# there should be one cycle of every length
|
643 |
+
d = nx.DiGraph()
|
644 |
+
expected = []
|
645 |
+
for n in range(10):
|
646 |
+
nx.add_cycle(d, range(n))
|
647 |
+
expected.append(n)
|
648 |
+
for k, e in enumerate(expected):
|
649 |
+
self.check_cycle_algorithm(d, e, length_bound=k)
|
650 |
+
|
651 |
+
# iteratively construct a path of undirected cycles, connected at articulation
|
652 |
+
# points. there should be one cycle of every length except 2: no digons
|
653 |
+
g = nx.Graph()
|
654 |
+
top = 0
|
655 |
+
expected = []
|
656 |
+
for n in range(10):
|
657 |
+
expected.append(n if n < 2 else n - 1)
|
658 |
+
if n == 2:
|
659 |
+
# no digons in undirected graphs
|
660 |
+
continue
|
661 |
+
nx.add_cycle(g, range(top, top + n))
|
662 |
+
top += n
|
663 |
+
for k, e in enumerate(expected):
|
664 |
+
self.check_cycle_algorithm(g, e, length_bound=k)
|
665 |
+
|
666 |
+
def test_simple_cycles_bound_corner_cases(self):
|
667 |
+
G = nx.cycle_graph(4)
|
668 |
+
DG = nx.cycle_graph(4, create_using=nx.DiGraph)
|
669 |
+
assert list(nx.simple_cycles(G, length_bound=0)) == []
|
670 |
+
assert list(nx.simple_cycles(DG, length_bound=0)) == []
|
671 |
+
assert list(nx.chordless_cycles(G, length_bound=0)) == []
|
672 |
+
assert list(nx.chordless_cycles(DG, length_bound=0)) == []
|
673 |
+
|
674 |
+
def test_simple_cycles_bound_error(self):
|
675 |
+
with pytest.raises(ValueError):
|
676 |
+
G = nx.DiGraph()
|
677 |
+
for c in nx.simple_cycles(G, -1):
|
678 |
+
assert False
|
679 |
+
|
680 |
+
with pytest.raises(ValueError):
|
681 |
+
G = nx.Graph()
|
682 |
+
for c in nx.simple_cycles(G, -1):
|
683 |
+
assert False
|
684 |
+
|
685 |
+
with pytest.raises(ValueError):
|
686 |
+
G = nx.Graph()
|
687 |
+
for c in nx.chordless_cycles(G, -1):
|
688 |
+
assert False
|
689 |
+
|
690 |
+
with pytest.raises(ValueError):
|
691 |
+
G = nx.DiGraph()
|
692 |
+
for c in nx.chordless_cycles(G, -1):
|
693 |
+
assert False
|
694 |
+
|
695 |
+
def test_chordless_cycles_clique(self):
|
696 |
+
g_family = [self.K(n) for n in range(2, 15)]
|
697 |
+
expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364]
|
698 |
+
self.check_cycle_enumeration_integer_sequence(
|
699 |
+
g_family, expected, chordless=True
|
700 |
+
)
|
701 |
+
|
702 |
+
# directed cliques have as many digons as undirected graphs have edges
|
703 |
+
expected = [(n * n - n) // 2 for n in range(15)]
|
704 |
+
g_family = [self.D(n) for n in range(15)]
|
705 |
+
self.check_cycle_enumeration_integer_sequence(
|
706 |
+
g_family, expected, chordless=True
|
707 |
+
)
|
708 |
+
|
709 |
+
|
710 |
+
# These tests might fail with hash randomization since they depend on
|
711 |
+
# edge_dfs. For more information, see the comments in:
|
712 |
+
# networkx/algorithms/traversal/tests/test_edgedfs.py
|
713 |
+
|
714 |
+
|
715 |
+
class TestFindCycle:
|
716 |
+
@classmethod
|
717 |
+
def setup_class(cls):
|
718 |
+
cls.nodes = [0, 1, 2, 3]
|
719 |
+
cls.edges = [(-1, 0), (0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
|
720 |
+
|
721 |
+
def test_graph_nocycle(self):
|
722 |
+
G = nx.Graph(self.edges)
|
723 |
+
pytest.raises(nx.exception.NetworkXNoCycle, nx.find_cycle, G, self.nodes)
|
724 |
+
|
725 |
+
def test_graph_cycle(self):
|
726 |
+
G = nx.Graph(self.edges)
|
727 |
+
G.add_edge(2, 0)
|
728 |
+
x = list(nx.find_cycle(G, self.nodes))
|
729 |
+
x_ = [(0, 1), (1, 2), (2, 0)]
|
730 |
+
assert x == x_
|
731 |
+
|
732 |
+
def test_graph_orientation_none(self):
|
733 |
+
G = nx.Graph(self.edges)
|
734 |
+
G.add_edge(2, 0)
|
735 |
+
x = list(nx.find_cycle(G, self.nodes, orientation=None))
|
736 |
+
x_ = [(0, 1), (1, 2), (2, 0)]
|
737 |
+
assert x == x_
|
738 |
+
|
739 |
+
def test_graph_orientation_original(self):
|
740 |
+
G = nx.Graph(self.edges)
|
741 |
+
G.add_edge(2, 0)
|
742 |
+
x = list(nx.find_cycle(G, self.nodes, orientation="original"))
|
743 |
+
x_ = [(0, 1, FORWARD), (1, 2, FORWARD), (2, 0, FORWARD)]
|
744 |
+
assert x == x_
|
745 |
+
|
746 |
+
def test_digraph(self):
|
747 |
+
G = nx.DiGraph(self.edges)
|
748 |
+
x = list(nx.find_cycle(G, self.nodes))
|
749 |
+
x_ = [(0, 1), (1, 0)]
|
750 |
+
assert x == x_
|
751 |
+
|
752 |
+
def test_digraph_orientation_none(self):
|
753 |
+
G = nx.DiGraph(self.edges)
|
754 |
+
x = list(nx.find_cycle(G, self.nodes, orientation=None))
|
755 |
+
x_ = [(0, 1), (1, 0)]
|
756 |
+
assert x == x_
|
757 |
+
|
758 |
+
def test_digraph_orientation_original(self):
|
759 |
+
G = nx.DiGraph(self.edges)
|
760 |
+
x = list(nx.find_cycle(G, self.nodes, orientation="original"))
|
761 |
+
x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
|
762 |
+
assert x == x_
|
763 |
+
|
764 |
+
def test_multigraph(self):
|
765 |
+
G = nx.MultiGraph(self.edges)
|
766 |
+
x = list(nx.find_cycle(G, self.nodes))
|
767 |
+
x_ = [(0, 1, 0), (1, 0, 1)] # or (1, 0, 2)
|
768 |
+
# Hash randomization...could be any edge.
|
769 |
+
assert x[0] == x_[0]
|
770 |
+
assert x[1][:2] == x_[1][:2]
|
771 |
+
|
772 |
+
def test_multidigraph(self):
|
773 |
+
G = nx.MultiDiGraph(self.edges)
|
774 |
+
x = list(nx.find_cycle(G, self.nodes))
|
775 |
+
x_ = [(0, 1, 0), (1, 0, 0)] # (1, 0, 1)
|
776 |
+
assert x[0] == x_[0]
|
777 |
+
assert x[1][:2] == x_[1][:2]
|
778 |
+
|
779 |
+
def test_digraph_ignore(self):
|
780 |
+
G = nx.DiGraph(self.edges)
|
781 |
+
x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
|
782 |
+
x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
|
783 |
+
assert x == x_
|
784 |
+
|
785 |
+
def test_digraph_reverse(self):
|
786 |
+
G = nx.DiGraph(self.edges)
|
787 |
+
x = list(nx.find_cycle(G, self.nodes, orientation="reverse"))
|
788 |
+
x_ = [(1, 0, REVERSE), (0, 1, REVERSE)]
|
789 |
+
assert x == x_
|
790 |
+
|
791 |
+
def test_multidigraph_ignore(self):
|
792 |
+
G = nx.MultiDiGraph(self.edges)
|
793 |
+
x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
|
794 |
+
x_ = [(0, 1, 0, FORWARD), (1, 0, 0, FORWARD)] # or (1, 0, 1, 1)
|
795 |
+
assert x[0] == x_[0]
|
796 |
+
assert x[1][:2] == x_[1][:2]
|
797 |
+
assert x[1][3] == x_[1][3]
|
798 |
+
|
799 |
+
def test_multidigraph_ignore2(self):
|
800 |
+
# Loop traversed an edge while ignoring its orientation.
|
801 |
+
G = nx.MultiDiGraph([(0, 1), (1, 2), (1, 2)])
|
802 |
+
x = list(nx.find_cycle(G, [0, 1, 2], orientation="ignore"))
|
803 |
+
x_ = [(1, 2, 0, FORWARD), (1, 2, 1, REVERSE)]
|
804 |
+
assert x == x_
|
805 |
+
|
806 |
+
def test_multidigraph_original(self):
|
807 |
+
# Node 2 doesn't need to be searched again from visited from 4.
|
808 |
+
# The goal here is to cover the case when 2 to be researched from 4,
|
809 |
+
# when 4 is visited from the first time (so we must make sure that 4
|
810 |
+
# is not visited from 2, and hence, we respect the edge orientation).
|
811 |
+
G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 3), (4, 2)])
|
812 |
+
pytest.raises(
|
813 |
+
nx.exception.NetworkXNoCycle,
|
814 |
+
nx.find_cycle,
|
815 |
+
G,
|
816 |
+
[0, 1, 2, 3, 4],
|
817 |
+
orientation="original",
|
818 |
+
)
|
819 |
+
|
820 |
+
def test_dag(self):
|
821 |
+
G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
|
822 |
+
pytest.raises(
|
823 |
+
nx.exception.NetworkXNoCycle, nx.find_cycle, G, orientation="original"
|
824 |
+
)
|
825 |
+
x = list(nx.find_cycle(G, orientation="ignore"))
|
826 |
+
assert x == [(0, 1, FORWARD), (1, 2, FORWARD), (0, 2, REVERSE)]
|
827 |
+
|
828 |
+
def test_prev_explored(self):
|
829 |
+
# https://github.com/networkx/networkx/issues/2323
|
830 |
+
|
831 |
+
G = nx.DiGraph()
|
832 |
+
G.add_edges_from([(1, 0), (2, 0), (1, 2), (2, 1)])
|
833 |
+
pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
|
834 |
+
x = list(nx.find_cycle(G, 1))
|
835 |
+
x_ = [(1, 2), (2, 1)]
|
836 |
+
assert x == x_
|
837 |
+
|
838 |
+
x = list(nx.find_cycle(G, 2))
|
839 |
+
x_ = [(2, 1), (1, 2)]
|
840 |
+
assert x == x_
|
841 |
+
|
842 |
+
x = list(nx.find_cycle(G))
|
843 |
+
x_ = [(1, 2), (2, 1)]
|
844 |
+
assert x == x_
|
845 |
+
|
846 |
+
def test_no_cycle(self):
|
847 |
+
# https://github.com/networkx/networkx/issues/2439
|
848 |
+
|
849 |
+
G = nx.DiGraph()
|
850 |
+
G.add_edges_from([(1, 2), (2, 0), (3, 1), (3, 2)])
|
851 |
+
pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
|
852 |
+
pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G)
|
853 |
+
|
854 |
+
|
855 |
+
def assert_basis_equal(a, b):
|
856 |
+
assert sorted(a) == sorted(b)
|
857 |
+
|
858 |
+
|
859 |
+
class TestMinimumCycleBasis:
|
860 |
+
@classmethod
|
861 |
+
def setup_class(cls):
|
862 |
+
T = nx.Graph()
|
863 |
+
nx.add_cycle(T, [1, 2, 3, 4], weight=1)
|
864 |
+
T.add_edge(2, 4, weight=5)
|
865 |
+
cls.diamond_graph = T
|
866 |
+
|
867 |
+
def test_unweighted_diamond(self):
|
868 |
+
mcb = nx.minimum_cycle_basis(self.diamond_graph)
|
869 |
+
assert_basis_equal(mcb, [[2, 4, 1], [3, 4, 2]])
|
870 |
+
|
871 |
+
def test_weighted_diamond(self):
|
872 |
+
mcb = nx.minimum_cycle_basis(self.diamond_graph, weight="weight")
|
873 |
+
assert_basis_equal(mcb, [[2, 4, 1], [4, 3, 2, 1]])
|
874 |
+
|
875 |
+
def test_dimensionality(self):
|
876 |
+
# checks |MCB|=|E|-|V|+|NC|
|
877 |
+
ntrial = 10
|
878 |
+
for seed in range(1234, 1234 + ntrial):
|
879 |
+
rg = nx.erdos_renyi_graph(10, 0.3, seed=seed)
|
880 |
+
nnodes = rg.number_of_nodes()
|
881 |
+
nedges = rg.number_of_edges()
|
882 |
+
ncomp = nx.number_connected_components(rg)
|
883 |
+
|
884 |
+
mcb = nx.minimum_cycle_basis(rg)
|
885 |
+
assert len(mcb) == nedges - nnodes + ncomp
|
886 |
+
check_independent(mcb)
|
887 |
+
|
888 |
+
def test_complete_graph(self):
|
889 |
+
cg = nx.complete_graph(5)
|
890 |
+
mcb = nx.minimum_cycle_basis(cg)
|
891 |
+
assert all(len(cycle) == 3 for cycle in mcb)
|
892 |
+
check_independent(mcb)
|
893 |
+
|
894 |
+
def test_tree_graph(self):
|
895 |
+
tg = nx.balanced_tree(3, 3)
|
896 |
+
assert not nx.minimum_cycle_basis(tg)
|
897 |
+
|
898 |
+
def test_petersen_graph(self):
|
899 |
+
G = nx.petersen_graph()
|
900 |
+
mcb = list(nx.minimum_cycle_basis(G))
|
901 |
+
expected = [
|
902 |
+
[4, 9, 7, 5, 0],
|
903 |
+
[1, 2, 3, 4, 0],
|
904 |
+
[1, 6, 8, 5, 0],
|
905 |
+
[4, 3, 8, 5, 0],
|
906 |
+
[1, 6, 9, 4, 0],
|
907 |
+
[1, 2, 7, 5, 0],
|
908 |
+
]
|
909 |
+
assert len(mcb) == len(expected)
|
910 |
+
assert all(c in expected for c in mcb)
|
911 |
+
|
912 |
+
# check that order of the nodes is a path
|
913 |
+
for c in mcb:
|
914 |
+
assert all(G.has_edge(u, v) for u, v in nx.utils.pairwise(c, cyclic=True))
|
915 |
+
# check independence of the basis
|
916 |
+
check_independent(mcb)
|
917 |
+
|
918 |
+
def test_gh6787_variable_weighted_complete_graph(self):
|
919 |
+
N = 8
|
920 |
+
cg = nx.complete_graph(N)
|
921 |
+
cg.add_weighted_edges_from([(u, v, 9) for u, v in cg.edges])
|
922 |
+
cg.add_weighted_edges_from([(u, v, 1) for u, v in nx.cycle_graph(N).edges])
|
923 |
+
mcb = nx.minimum_cycle_basis(cg, weight="weight")
|
924 |
+
check_independent(mcb)
|
925 |
+
|
926 |
+
def test_gh6787_and_edge_attribute_names(self):
|
927 |
+
G = nx.cycle_graph(4)
|
928 |
+
G.add_weighted_edges_from([(0, 2, 10), (1, 3, 10)], weight="dist")
|
929 |
+
expected = [[1, 3, 0], [3, 2, 1, 0], [1, 2, 0]]
|
930 |
+
mcb = list(nx.minimum_cycle_basis(G, weight="dist"))
|
931 |
+
assert len(mcb) == len(expected)
|
932 |
+
assert all(c in expected for c in mcb)
|
933 |
+
|
934 |
+
# test not using a weight with weight attributes
|
935 |
+
expected = [[1, 3, 0], [1, 2, 0], [3, 2, 0]]
|
936 |
+
mcb = list(nx.minimum_cycle_basis(G))
|
937 |
+
assert len(mcb) == len(expected)
|
938 |
+
assert all(c in expected for c in mcb)
|
939 |
+
|
940 |
+
|
941 |
+
class TestGirth:
|
942 |
+
@pytest.mark.parametrize(
|
943 |
+
("G", "expected"),
|
944 |
+
(
|
945 |
+
(nx.chvatal_graph(), 4),
|
946 |
+
(nx.tutte_graph(), 4),
|
947 |
+
(nx.petersen_graph(), 5),
|
948 |
+
(nx.heawood_graph(), 6),
|
949 |
+
(nx.pappus_graph(), 6),
|
950 |
+
(nx.random_tree(10, seed=42), inf),
|
951 |
+
(nx.empty_graph(10), inf),
|
952 |
+
(nx.Graph(chain(cycle_edges(range(5)), cycle_edges(range(6, 10)))), 4),
|
953 |
+
(
|
954 |
+
nx.Graph(
|
955 |
+
[
|
956 |
+
(0, 6),
|
957 |
+
(0, 8),
|
958 |
+
(0, 9),
|
959 |
+
(1, 8),
|
960 |
+
(2, 8),
|
961 |
+
(2, 9),
|
962 |
+
(4, 9),
|
963 |
+
(5, 9),
|
964 |
+
(6, 8),
|
965 |
+
(6, 9),
|
966 |
+
(7, 8),
|
967 |
+
]
|
968 |
+
),
|
969 |
+
3,
|
970 |
+
),
|
971 |
+
),
|
972 |
+
)
|
973 |
+
def test_girth(self, G, expected):
|
974 |
+
assert nx.girth(G) == expected
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_distance_regular.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx import is_strongly_regular
|
5 |
+
|
6 |
+
|
7 |
+
@pytest.mark.parametrize(
|
8 |
+
"f", (nx.is_distance_regular, nx.intersection_array, nx.is_strongly_regular)
|
9 |
+
)
|
10 |
+
@pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
|
11 |
+
def test_raises_on_directed_and_multigraphs(f, graph_constructor):
|
12 |
+
G = graph_constructor([(0, 1), (1, 2)])
|
13 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
14 |
+
f(G)
|
15 |
+
|
16 |
+
|
17 |
+
class TestDistanceRegular:
|
18 |
+
def test_is_distance_regular(self):
|
19 |
+
assert nx.is_distance_regular(nx.icosahedral_graph())
|
20 |
+
assert nx.is_distance_regular(nx.petersen_graph())
|
21 |
+
assert nx.is_distance_regular(nx.cubical_graph())
|
22 |
+
assert nx.is_distance_regular(nx.complete_bipartite_graph(3, 3))
|
23 |
+
assert nx.is_distance_regular(nx.tetrahedral_graph())
|
24 |
+
assert nx.is_distance_regular(nx.dodecahedral_graph())
|
25 |
+
assert nx.is_distance_regular(nx.pappus_graph())
|
26 |
+
assert nx.is_distance_regular(nx.heawood_graph())
|
27 |
+
assert nx.is_distance_regular(nx.cycle_graph(3))
|
28 |
+
# no distance regular
|
29 |
+
assert not nx.is_distance_regular(nx.path_graph(4))
|
30 |
+
|
31 |
+
def test_not_connected(self):
|
32 |
+
G = nx.cycle_graph(4)
|
33 |
+
nx.add_cycle(G, [5, 6, 7])
|
34 |
+
assert not nx.is_distance_regular(G)
|
35 |
+
|
36 |
+
def test_global_parameters(self):
|
37 |
+
b, c = nx.intersection_array(nx.cycle_graph(5))
|
38 |
+
g = nx.global_parameters(b, c)
|
39 |
+
assert list(g) == [(0, 0, 2), (1, 0, 1), (1, 1, 0)]
|
40 |
+
b, c = nx.intersection_array(nx.cycle_graph(3))
|
41 |
+
g = nx.global_parameters(b, c)
|
42 |
+
assert list(g) == [(0, 0, 2), (1, 1, 0)]
|
43 |
+
|
44 |
+
def test_intersection_array(self):
|
45 |
+
b, c = nx.intersection_array(nx.cycle_graph(5))
|
46 |
+
assert b == [2, 1]
|
47 |
+
assert c == [1, 1]
|
48 |
+
b, c = nx.intersection_array(nx.dodecahedral_graph())
|
49 |
+
assert b == [3, 2, 1, 1, 1]
|
50 |
+
assert c == [1, 1, 1, 2, 3]
|
51 |
+
b, c = nx.intersection_array(nx.icosahedral_graph())
|
52 |
+
assert b == [5, 2, 1]
|
53 |
+
assert c == [1, 2, 5]
|
54 |
+
|
55 |
+
|
56 |
+
@pytest.mark.parametrize("f", (nx.is_distance_regular, nx.is_strongly_regular))
|
57 |
+
def test_empty_graph_raises(f):
|
58 |
+
G = nx.Graph()
|
59 |
+
with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes"):
|
60 |
+
f(G)
|
61 |
+
|
62 |
+
|
63 |
+
class TestStronglyRegular:
|
64 |
+
"""Unit tests for the :func:`~networkx.is_strongly_regular`
|
65 |
+
function.
|
66 |
+
|
67 |
+
"""
|
68 |
+
|
69 |
+
def test_cycle_graph(self):
|
70 |
+
"""Tests that the cycle graph on five vertices is strongly
|
71 |
+
regular.
|
72 |
+
|
73 |
+
"""
|
74 |
+
G = nx.cycle_graph(5)
|
75 |
+
assert is_strongly_regular(G)
|
76 |
+
|
77 |
+
def test_petersen_graph(self):
|
78 |
+
"""Tests that the Petersen graph is strongly regular."""
|
79 |
+
G = nx.petersen_graph()
|
80 |
+
assert is_strongly_regular(G)
|
81 |
+
|
82 |
+
def test_path_graph(self):
|
83 |
+
"""Tests that the path graph is not strongly regular."""
|
84 |
+
G = nx.path_graph(4)
|
85 |
+
assert not is_strongly_regular(G)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_dominating.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
def test_dominating_set():
|
7 |
+
G = nx.gnp_random_graph(100, 0.1)
|
8 |
+
D = nx.dominating_set(G)
|
9 |
+
assert nx.is_dominating_set(G, D)
|
10 |
+
D = nx.dominating_set(G, start_with=0)
|
11 |
+
assert nx.is_dominating_set(G, D)
|
12 |
+
|
13 |
+
|
14 |
+
def test_complete():
|
15 |
+
"""In complete graphs each node is a dominating set.
|
16 |
+
Thus the dominating set has to be of cardinality 1.
|
17 |
+
"""
|
18 |
+
K4 = nx.complete_graph(4)
|
19 |
+
assert len(nx.dominating_set(K4)) == 1
|
20 |
+
K5 = nx.complete_graph(5)
|
21 |
+
assert len(nx.dominating_set(K5)) == 1
|
22 |
+
|
23 |
+
|
24 |
+
def test_raise_dominating_set():
|
25 |
+
with pytest.raises(nx.NetworkXError):
|
26 |
+
G = nx.path_graph(4)
|
27 |
+
D = nx.dominating_set(G, start_with=10)
|
28 |
+
|
29 |
+
|
30 |
+
def test_is_dominating_set():
|
31 |
+
G = nx.path_graph(4)
|
32 |
+
d = {1, 3}
|
33 |
+
assert nx.is_dominating_set(G, d)
|
34 |
+
d = {0, 2}
|
35 |
+
assert nx.is_dominating_set(G, d)
|
36 |
+
d = {1}
|
37 |
+
assert not nx.is_dominating_set(G, d)
|
38 |
+
|
39 |
+
|
40 |
+
def test_wikipedia_is_dominating_set():
|
41 |
+
"""Example from https://en.wikipedia.org/wiki/Dominating_set"""
|
42 |
+
G = nx.cycle_graph(4)
|
43 |
+
G.add_edges_from([(0, 4), (1, 4), (2, 5)])
|
44 |
+
assert nx.is_dominating_set(G, {4, 3, 5})
|
45 |
+
assert nx.is_dominating_set(G, {0, 2})
|
46 |
+
assert nx.is_dominating_set(G, {1, 2})
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_efficiency.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.efficiency` module."""
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
class TestEfficiency:
|
7 |
+
def setup_method(self):
|
8 |
+
# G1 is a disconnected graph
|
9 |
+
self.G1 = nx.Graph()
|
10 |
+
self.G1.add_nodes_from([1, 2, 3])
|
11 |
+
# G2 is a cycle graph
|
12 |
+
self.G2 = nx.cycle_graph(4)
|
13 |
+
# G3 is the triangle graph with one additional edge
|
14 |
+
self.G3 = nx.lollipop_graph(3, 1)
|
15 |
+
|
16 |
+
def test_efficiency_disconnected_nodes(self):
|
17 |
+
"""
|
18 |
+
When nodes are disconnected, efficiency is 0
|
19 |
+
"""
|
20 |
+
assert nx.efficiency(self.G1, 1, 2) == 0
|
21 |
+
|
22 |
+
def test_local_efficiency_disconnected_graph(self):
|
23 |
+
"""
|
24 |
+
In a disconnected graph the efficiency is 0
|
25 |
+
"""
|
26 |
+
assert nx.local_efficiency(self.G1) == 0
|
27 |
+
|
28 |
+
def test_efficiency(self):
|
29 |
+
assert nx.efficiency(self.G2, 0, 1) == 1
|
30 |
+
assert nx.efficiency(self.G2, 0, 2) == 1 / 2
|
31 |
+
|
32 |
+
def test_global_efficiency(self):
|
33 |
+
assert nx.global_efficiency(self.G2) == 5 / 6
|
34 |
+
|
35 |
+
def test_global_efficiency_complete_graph(self):
|
36 |
+
"""
|
37 |
+
Tests that the average global efficiency of the complete graph is one.
|
38 |
+
"""
|
39 |
+
for n in range(2, 10):
|
40 |
+
G = nx.complete_graph(n)
|
41 |
+
assert nx.global_efficiency(G) == 1
|
42 |
+
|
43 |
+
def test_local_efficiency_complete_graph(self):
|
44 |
+
"""
|
45 |
+
Test that the local efficiency for a complete graph with at least 3
|
46 |
+
nodes should be one. For a graph with only 2 nodes, the induced
|
47 |
+
subgraph has no edges.
|
48 |
+
"""
|
49 |
+
for n in range(3, 10):
|
50 |
+
G = nx.complete_graph(n)
|
51 |
+
assert nx.local_efficiency(G) == 1
|
52 |
+
|
53 |
+
def test_using_ego_graph(self):
|
54 |
+
"""
|
55 |
+
Test that the ego graph is used when computing local efficiency.
|
56 |
+
For more information, see GitHub issue #2710.
|
57 |
+
"""
|
58 |
+
assert nx.local_efficiency(self.G3) == 7 / 12
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_euler.py
ADDED
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import collections
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
|
8 |
+
@pytest.mark.parametrize("f", (nx.is_eulerian, nx.is_semieulerian))
|
9 |
+
def test_empty_graph_raises(f):
|
10 |
+
G = nx.Graph()
|
11 |
+
with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
|
12 |
+
f(G)
|
13 |
+
|
14 |
+
|
15 |
+
class TestIsEulerian:
|
16 |
+
def test_is_eulerian(self):
|
17 |
+
assert nx.is_eulerian(nx.complete_graph(5))
|
18 |
+
assert nx.is_eulerian(nx.complete_graph(7))
|
19 |
+
assert nx.is_eulerian(nx.hypercube_graph(4))
|
20 |
+
assert nx.is_eulerian(nx.hypercube_graph(6))
|
21 |
+
|
22 |
+
assert not nx.is_eulerian(nx.complete_graph(4))
|
23 |
+
assert not nx.is_eulerian(nx.complete_graph(6))
|
24 |
+
assert not nx.is_eulerian(nx.hypercube_graph(3))
|
25 |
+
assert not nx.is_eulerian(nx.hypercube_graph(5))
|
26 |
+
|
27 |
+
assert not nx.is_eulerian(nx.petersen_graph())
|
28 |
+
assert not nx.is_eulerian(nx.path_graph(4))
|
29 |
+
|
30 |
+
def test_is_eulerian2(self):
|
31 |
+
# not connected
|
32 |
+
G = nx.Graph()
|
33 |
+
G.add_nodes_from([1, 2, 3])
|
34 |
+
assert not nx.is_eulerian(G)
|
35 |
+
# not strongly connected
|
36 |
+
G = nx.DiGraph()
|
37 |
+
G.add_nodes_from([1, 2, 3])
|
38 |
+
assert not nx.is_eulerian(G)
|
39 |
+
G = nx.MultiDiGraph()
|
40 |
+
G.add_edge(1, 2)
|
41 |
+
G.add_edge(2, 3)
|
42 |
+
G.add_edge(2, 3)
|
43 |
+
G.add_edge(3, 1)
|
44 |
+
assert not nx.is_eulerian(G)
|
45 |
+
|
46 |
+
|
47 |
+
class TestEulerianCircuit:
|
48 |
+
def test_eulerian_circuit_cycle(self):
|
49 |
+
G = nx.cycle_graph(4)
|
50 |
+
|
51 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
52 |
+
nodes = [u for u, v in edges]
|
53 |
+
assert nodes == [0, 3, 2, 1]
|
54 |
+
assert edges == [(0, 3), (3, 2), (2, 1), (1, 0)]
|
55 |
+
|
56 |
+
edges = list(nx.eulerian_circuit(G, source=1))
|
57 |
+
nodes = [u for u, v in edges]
|
58 |
+
assert nodes == [1, 2, 3, 0]
|
59 |
+
assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
|
60 |
+
|
61 |
+
G = nx.complete_graph(3)
|
62 |
+
|
63 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
64 |
+
nodes = [u for u, v in edges]
|
65 |
+
assert nodes == [0, 2, 1]
|
66 |
+
assert edges == [(0, 2), (2, 1), (1, 0)]
|
67 |
+
|
68 |
+
edges = list(nx.eulerian_circuit(G, source=1))
|
69 |
+
nodes = [u for u, v in edges]
|
70 |
+
assert nodes == [1, 2, 0]
|
71 |
+
assert edges == [(1, 2), (2, 0), (0, 1)]
|
72 |
+
|
73 |
+
def test_eulerian_circuit_digraph(self):
|
74 |
+
G = nx.DiGraph()
|
75 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
76 |
+
|
77 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
78 |
+
nodes = [u for u, v in edges]
|
79 |
+
assert nodes == [0, 1, 2, 3]
|
80 |
+
assert edges == [(0, 1), (1, 2), (2, 3), (3, 0)]
|
81 |
+
|
82 |
+
edges = list(nx.eulerian_circuit(G, source=1))
|
83 |
+
nodes = [u for u, v in edges]
|
84 |
+
assert nodes == [1, 2, 3, 0]
|
85 |
+
assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
|
86 |
+
|
87 |
+
def test_multigraph(self):
|
88 |
+
G = nx.MultiGraph()
|
89 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
90 |
+
G.add_edge(1, 2)
|
91 |
+
G.add_edge(1, 2)
|
92 |
+
edges = list(nx.eulerian_circuit(G, source=0))
|
93 |
+
nodes = [u for u, v in edges]
|
94 |
+
assert nodes == [0, 3, 2, 1, 2, 1]
|
95 |
+
assert edges == [(0, 3), (3, 2), (2, 1), (1, 2), (2, 1), (1, 0)]
|
96 |
+
|
97 |
+
def test_multigraph_with_keys(self):
|
98 |
+
G = nx.MultiGraph()
|
99 |
+
nx.add_cycle(G, [0, 1, 2, 3])
|
100 |
+
G.add_edge(1, 2)
|
101 |
+
G.add_edge(1, 2)
|
102 |
+
edges = list(nx.eulerian_circuit(G, source=0, keys=True))
|
103 |
+
nodes = [u for u, v, k in edges]
|
104 |
+
assert nodes == [0, 3, 2, 1, 2, 1]
|
105 |
+
assert edges[:2] == [(0, 3, 0), (3, 2, 0)]
|
106 |
+
assert collections.Counter(edges[2:5]) == collections.Counter(
|
107 |
+
[(2, 1, 0), (1, 2, 1), (2, 1, 2)]
|
108 |
+
)
|
109 |
+
assert edges[5:] == [(1, 0, 0)]
|
110 |
+
|
111 |
+
def test_not_eulerian(self):
|
112 |
+
with pytest.raises(nx.NetworkXError):
|
113 |
+
f = list(nx.eulerian_circuit(nx.complete_graph(4)))
|
114 |
+
|
115 |
+
|
116 |
+
class TestIsSemiEulerian:
|
117 |
+
def test_is_semieulerian(self):
|
118 |
+
# Test graphs with Eulerian paths but no cycles return True.
|
119 |
+
assert nx.is_semieulerian(nx.path_graph(4))
|
120 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
121 |
+
assert nx.is_semieulerian(G)
|
122 |
+
|
123 |
+
# Test graphs with Eulerian cycles return False.
|
124 |
+
assert not nx.is_semieulerian(nx.complete_graph(5))
|
125 |
+
assert not nx.is_semieulerian(nx.complete_graph(7))
|
126 |
+
assert not nx.is_semieulerian(nx.hypercube_graph(4))
|
127 |
+
assert not nx.is_semieulerian(nx.hypercube_graph(6))
|
128 |
+
|
129 |
+
|
130 |
+
class TestHasEulerianPath:
|
131 |
+
def test_has_eulerian_path_cyclic(self):
|
132 |
+
# Test graphs with Eulerian cycles return True.
|
133 |
+
assert nx.has_eulerian_path(nx.complete_graph(5))
|
134 |
+
assert nx.has_eulerian_path(nx.complete_graph(7))
|
135 |
+
assert nx.has_eulerian_path(nx.hypercube_graph(4))
|
136 |
+
assert nx.has_eulerian_path(nx.hypercube_graph(6))
|
137 |
+
|
138 |
+
def test_has_eulerian_path_non_cyclic(self):
|
139 |
+
# Test graphs with Eulerian paths but no cycles return True.
|
140 |
+
assert nx.has_eulerian_path(nx.path_graph(4))
|
141 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
142 |
+
assert nx.has_eulerian_path(G)
|
143 |
+
|
144 |
+
def test_has_eulerian_path_directed_graph(self):
|
145 |
+
# Test directed graphs and returns False
|
146 |
+
G = nx.DiGraph()
|
147 |
+
G.add_edges_from([(0, 1), (1, 2), (0, 2)])
|
148 |
+
assert not nx.has_eulerian_path(G)
|
149 |
+
|
150 |
+
# Test directed graphs without isolated node returns True
|
151 |
+
G = nx.DiGraph()
|
152 |
+
G.add_edges_from([(0, 1), (1, 2), (2, 0)])
|
153 |
+
assert nx.has_eulerian_path(G)
|
154 |
+
|
155 |
+
# Test directed graphs with isolated node returns False
|
156 |
+
G.add_node(3)
|
157 |
+
assert not nx.has_eulerian_path(G)
|
158 |
+
|
159 |
+
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
|
160 |
+
def test_has_eulerian_path_not_weakly_connected(self, G):
|
161 |
+
G.add_edges_from([(0, 1), (2, 3), (3, 2)])
|
162 |
+
assert not nx.has_eulerian_path(G)
|
163 |
+
|
164 |
+
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
|
165 |
+
def test_has_eulerian_path_unbalancedins_more_than_one(self, G):
|
166 |
+
G.add_edges_from([(0, 1), (2, 3)])
|
167 |
+
assert not nx.has_eulerian_path(G)
|
168 |
+
|
169 |
+
|
170 |
+
class TestFindPathStart:
|
171 |
+
def testfind_path_start(self):
|
172 |
+
find_path_start = nx.algorithms.euler._find_path_start
|
173 |
+
# Test digraphs return correct starting node.
|
174 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
175 |
+
assert find_path_start(G) == 0
|
176 |
+
edges = [(0, 1), (1, 2), (2, 0), (4, 0)]
|
177 |
+
assert find_path_start(nx.DiGraph(edges)) == 4
|
178 |
+
|
179 |
+
# Test graph with no Eulerian path return None.
|
180 |
+
edges = [(0, 1), (1, 2), (2, 3), (2, 4)]
|
181 |
+
assert find_path_start(nx.DiGraph(edges)) is None
|
182 |
+
|
183 |
+
|
184 |
+
class TestEulerianPath:
|
185 |
+
def test_eulerian_path(self):
|
186 |
+
x = [(4, 0), (0, 1), (1, 2), (2, 0)]
|
187 |
+
for e1, e2 in zip(x, nx.eulerian_path(nx.DiGraph(x))):
|
188 |
+
assert e1 == e2
|
189 |
+
|
190 |
+
def test_eulerian_path_straight_link(self):
|
191 |
+
G = nx.DiGraph()
|
192 |
+
result = [(1, 2), (2, 3), (3, 4), (4, 5)]
|
193 |
+
G.add_edges_from(result)
|
194 |
+
assert result == list(nx.eulerian_path(G))
|
195 |
+
assert result == list(nx.eulerian_path(G, source=1))
|
196 |
+
with pytest.raises(nx.NetworkXError):
|
197 |
+
list(nx.eulerian_path(G, source=3))
|
198 |
+
with pytest.raises(nx.NetworkXError):
|
199 |
+
list(nx.eulerian_path(G, source=4))
|
200 |
+
with pytest.raises(nx.NetworkXError):
|
201 |
+
list(nx.eulerian_path(G, source=5))
|
202 |
+
|
203 |
+
def test_eulerian_path_multigraph(self):
|
204 |
+
G = nx.MultiDiGraph()
|
205 |
+
result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4), (4, 3)]
|
206 |
+
G.add_edges_from(result)
|
207 |
+
assert result == list(nx.eulerian_path(G))
|
208 |
+
assert result == list(nx.eulerian_path(G, source=2))
|
209 |
+
with pytest.raises(nx.NetworkXError):
|
210 |
+
list(nx.eulerian_path(G, source=3))
|
211 |
+
with pytest.raises(nx.NetworkXError):
|
212 |
+
list(nx.eulerian_path(G, source=4))
|
213 |
+
|
214 |
+
def test_eulerian_path_eulerian_circuit(self):
|
215 |
+
G = nx.DiGraph()
|
216 |
+
result = [(1, 2), (2, 3), (3, 4), (4, 1)]
|
217 |
+
result2 = [(2, 3), (3, 4), (4, 1), (1, 2)]
|
218 |
+
result3 = [(3, 4), (4, 1), (1, 2), (2, 3)]
|
219 |
+
G.add_edges_from(result)
|
220 |
+
assert result == list(nx.eulerian_path(G))
|
221 |
+
assert result == list(nx.eulerian_path(G, source=1))
|
222 |
+
assert result2 == list(nx.eulerian_path(G, source=2))
|
223 |
+
assert result3 == list(nx.eulerian_path(G, source=3))
|
224 |
+
|
225 |
+
def test_eulerian_path_undirected(self):
|
226 |
+
G = nx.Graph()
|
227 |
+
result = [(1, 2), (2, 3), (3, 4), (4, 5)]
|
228 |
+
result2 = [(5, 4), (4, 3), (3, 2), (2, 1)]
|
229 |
+
G.add_edges_from(result)
|
230 |
+
assert list(nx.eulerian_path(G)) in (result, result2)
|
231 |
+
assert result == list(nx.eulerian_path(G, source=1))
|
232 |
+
assert result2 == list(nx.eulerian_path(G, source=5))
|
233 |
+
with pytest.raises(nx.NetworkXError):
|
234 |
+
list(nx.eulerian_path(G, source=3))
|
235 |
+
with pytest.raises(nx.NetworkXError):
|
236 |
+
list(nx.eulerian_path(G, source=2))
|
237 |
+
|
238 |
+
def test_eulerian_path_multigraph_undirected(self):
|
239 |
+
G = nx.MultiGraph()
|
240 |
+
result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4)]
|
241 |
+
G.add_edges_from(result)
|
242 |
+
assert result == list(nx.eulerian_path(G))
|
243 |
+
assert result == list(nx.eulerian_path(G, source=2))
|
244 |
+
with pytest.raises(nx.NetworkXError):
|
245 |
+
list(nx.eulerian_path(G, source=3))
|
246 |
+
with pytest.raises(nx.NetworkXError):
|
247 |
+
list(nx.eulerian_path(G, source=1))
|
248 |
+
|
249 |
+
@pytest.mark.parametrize(
|
250 |
+
("graph_type", "result"),
|
251 |
+
(
|
252 |
+
(nx.MultiGraph, [(0, 1, 0), (1, 0, 1)]),
|
253 |
+
(nx.MultiDiGraph, [(0, 1, 0), (1, 0, 0)]),
|
254 |
+
),
|
255 |
+
)
|
256 |
+
def test_eulerian_with_keys(self, graph_type, result):
|
257 |
+
G = graph_type([(0, 1), (1, 0)])
|
258 |
+
answer = nx.eulerian_path(G, keys=True)
|
259 |
+
assert list(answer) == result
|
260 |
+
|
261 |
+
|
262 |
+
class TestEulerize:
|
263 |
+
def test_disconnected(self):
|
264 |
+
with pytest.raises(nx.NetworkXError):
|
265 |
+
G = nx.from_edgelist([(0, 1), (2, 3)])
|
266 |
+
nx.eulerize(G)
|
267 |
+
|
268 |
+
def test_null_graph(self):
|
269 |
+
with pytest.raises(nx.NetworkXPointlessConcept):
|
270 |
+
nx.eulerize(nx.Graph())
|
271 |
+
|
272 |
+
def test_null_multigraph(self):
|
273 |
+
with pytest.raises(nx.NetworkXPointlessConcept):
|
274 |
+
nx.eulerize(nx.MultiGraph())
|
275 |
+
|
276 |
+
def test_on_empty_graph(self):
|
277 |
+
with pytest.raises(nx.NetworkXError):
|
278 |
+
nx.eulerize(nx.empty_graph(3))
|
279 |
+
|
280 |
+
def test_on_eulerian(self):
|
281 |
+
G = nx.cycle_graph(3)
|
282 |
+
H = nx.eulerize(G)
|
283 |
+
assert nx.is_isomorphic(G, H)
|
284 |
+
|
285 |
+
def test_on_eulerian_multigraph(self):
|
286 |
+
G = nx.MultiGraph(nx.cycle_graph(3))
|
287 |
+
G.add_edge(0, 1)
|
288 |
+
H = nx.eulerize(G)
|
289 |
+
assert nx.is_eulerian(H)
|
290 |
+
|
291 |
+
def test_on_complete_graph(self):
|
292 |
+
G = nx.complete_graph(4)
|
293 |
+
assert nx.is_eulerian(nx.eulerize(G))
|
294 |
+
assert nx.is_eulerian(nx.eulerize(nx.MultiGraph(G)))
|
295 |
+
|
296 |
+
def test_on_non_eulerian_graph(self):
|
297 |
+
G = nx.cycle_graph(18)
|
298 |
+
G.add_edge(0, 18)
|
299 |
+
G.add_edge(18, 19)
|
300 |
+
G.add_edge(17, 19)
|
301 |
+
G.add_edge(4, 20)
|
302 |
+
G.add_edge(20, 21)
|
303 |
+
G.add_edge(21, 22)
|
304 |
+
G.add_edge(22, 23)
|
305 |
+
G.add_edge(23, 24)
|
306 |
+
G.add_edge(24, 25)
|
307 |
+
G.add_edge(25, 26)
|
308 |
+
G.add_edge(26, 27)
|
309 |
+
G.add_edge(27, 28)
|
310 |
+
G.add_edge(28, 13)
|
311 |
+
assert not nx.is_eulerian(G)
|
312 |
+
G = nx.eulerize(G)
|
313 |
+
assert nx.is_eulerian(G)
|
314 |
+
assert nx.number_of_edges(G) == 39
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_graph_hashing.py
ADDED
@@ -0,0 +1,686 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.generators import directed
|
5 |
+
|
6 |
+
# Unit tests for the :func:`~networkx.weisfeiler_lehman_graph_hash` function
|
7 |
+
|
8 |
+
|
9 |
+
def test_empty_graph_hash():
|
10 |
+
"""
|
11 |
+
empty graphs should give hashes regardless of other params
|
12 |
+
"""
|
13 |
+
G1 = nx.empty_graph()
|
14 |
+
G2 = nx.empty_graph()
|
15 |
+
|
16 |
+
h1 = nx.weisfeiler_lehman_graph_hash(G1)
|
17 |
+
h2 = nx.weisfeiler_lehman_graph_hash(G2)
|
18 |
+
h3 = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="edge_attr1")
|
19 |
+
h4 = nx.weisfeiler_lehman_graph_hash(G2, node_attr="node_attr1")
|
20 |
+
h5 = nx.weisfeiler_lehman_graph_hash(
|
21 |
+
G2, edge_attr="edge_attr1", node_attr="node_attr1"
|
22 |
+
)
|
23 |
+
h6 = nx.weisfeiler_lehman_graph_hash(G2, iterations=10)
|
24 |
+
|
25 |
+
assert h1 == h2
|
26 |
+
assert h1 == h3
|
27 |
+
assert h1 == h4
|
28 |
+
assert h1 == h5
|
29 |
+
assert h1 == h6
|
30 |
+
|
31 |
+
|
32 |
+
def test_directed():
|
33 |
+
"""
|
34 |
+
A directed graph with no bi-directional edges should yield different a graph hash
|
35 |
+
to the same graph taken as undirected if there are no hash collisions.
|
36 |
+
"""
|
37 |
+
r = 10
|
38 |
+
for i in range(r):
|
39 |
+
G_directed = nx.gn_graph(10 + r, seed=100 + i)
|
40 |
+
G_undirected = nx.to_undirected(G_directed)
|
41 |
+
|
42 |
+
h_directed = nx.weisfeiler_lehman_graph_hash(G_directed)
|
43 |
+
h_undirected = nx.weisfeiler_lehman_graph_hash(G_undirected)
|
44 |
+
|
45 |
+
assert h_directed != h_undirected
|
46 |
+
|
47 |
+
|
48 |
+
def test_reversed():
|
49 |
+
"""
|
50 |
+
A directed graph with no bi-directional edges should yield different a graph hash
|
51 |
+
to the same graph taken with edge directions reversed if there are no hash collisions.
|
52 |
+
Here we test a cycle graph which is the minimal counterexample
|
53 |
+
"""
|
54 |
+
G = nx.cycle_graph(5, create_using=nx.DiGraph)
|
55 |
+
nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
|
56 |
+
|
57 |
+
G_reversed = G.reverse()
|
58 |
+
|
59 |
+
h = nx.weisfeiler_lehman_graph_hash(G, node_attr="label")
|
60 |
+
h_reversed = nx.weisfeiler_lehman_graph_hash(G_reversed, node_attr="label")
|
61 |
+
|
62 |
+
assert h != h_reversed
|
63 |
+
|
64 |
+
|
65 |
+
def test_isomorphic():
|
66 |
+
"""
|
67 |
+
graph hashes should be invariant to node-relabeling (when the output is reindexed
|
68 |
+
by the same mapping)
|
69 |
+
"""
|
70 |
+
n, r = 100, 10
|
71 |
+
p = 1.0 / r
|
72 |
+
for i in range(1, r + 1):
|
73 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
|
74 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
75 |
+
|
76 |
+
g1_hash = nx.weisfeiler_lehman_graph_hash(G1)
|
77 |
+
g2_hash = nx.weisfeiler_lehman_graph_hash(G2)
|
78 |
+
|
79 |
+
assert g1_hash == g2_hash
|
80 |
+
|
81 |
+
|
82 |
+
def test_isomorphic_edge_attr():
|
83 |
+
"""
|
84 |
+
Isomorphic graphs with differing edge attributes should yield different graph
|
85 |
+
hashes if the 'edge_attr' argument is supplied and populated in the graph,
|
86 |
+
and there are no hash collisions.
|
87 |
+
The output should still be invariant to node-relabeling
|
88 |
+
"""
|
89 |
+
n, r = 100, 10
|
90 |
+
p = 1.0 / r
|
91 |
+
for i in range(1, r + 1):
|
92 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
|
93 |
+
|
94 |
+
for a, b in G1.edges:
|
95 |
+
G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
|
96 |
+
G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
|
97 |
+
|
98 |
+
g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
|
99 |
+
G1, edge_attr="edge_attr1"
|
100 |
+
)
|
101 |
+
g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
|
102 |
+
G1, edge_attr="edge_attr2"
|
103 |
+
)
|
104 |
+
g1_hash_no_edge_attr = nx.weisfeiler_lehman_graph_hash(G1, edge_attr=None)
|
105 |
+
|
106 |
+
assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
|
107 |
+
assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
|
108 |
+
assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
|
109 |
+
|
110 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
111 |
+
|
112 |
+
g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
|
113 |
+
G2, edge_attr="edge_attr1"
|
114 |
+
)
|
115 |
+
g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
|
116 |
+
G2, edge_attr="edge_attr2"
|
117 |
+
)
|
118 |
+
|
119 |
+
assert g1_hash_with_edge_attr1 == g2_hash_with_edge_attr1
|
120 |
+
assert g1_hash_with_edge_attr2 == g2_hash_with_edge_attr2
|
121 |
+
|
122 |
+
|
123 |
+
def test_missing_edge_attr():
|
124 |
+
"""
|
125 |
+
If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
|
126 |
+
we should raise a KeyError
|
127 |
+
"""
|
128 |
+
G = nx.Graph()
|
129 |
+
G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
|
130 |
+
pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, edge_attr="edge_attr1")
|
131 |
+
|
132 |
+
|
133 |
+
def test_isomorphic_node_attr():
|
134 |
+
"""
|
135 |
+
Isomorphic graphs with differing node attributes should yield different graph
|
136 |
+
hashes if the 'node_attr' argument is supplied and populated in the graph, and
|
137 |
+
there are no hash collisions.
|
138 |
+
The output should still be invariant to node-relabeling
|
139 |
+
"""
|
140 |
+
n, r = 100, 10
|
141 |
+
p = 1.0 / r
|
142 |
+
for i in range(1, r + 1):
|
143 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
|
144 |
+
|
145 |
+
for u in G1.nodes():
|
146 |
+
G1.nodes[u]["node_attr1"] = f"{u}-1"
|
147 |
+
G1.nodes[u]["node_attr2"] = f"{u}-2"
|
148 |
+
|
149 |
+
g1_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
|
150 |
+
G1, node_attr="node_attr1"
|
151 |
+
)
|
152 |
+
g1_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
|
153 |
+
G1, node_attr="node_attr2"
|
154 |
+
)
|
155 |
+
g1_hash_no_node_attr = nx.weisfeiler_lehman_graph_hash(G1, node_attr=None)
|
156 |
+
|
157 |
+
assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
|
158 |
+
assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
|
159 |
+
assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
|
160 |
+
|
161 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
162 |
+
|
163 |
+
g2_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
|
164 |
+
G2, node_attr="node_attr1"
|
165 |
+
)
|
166 |
+
g2_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
|
167 |
+
G2, node_attr="node_attr2"
|
168 |
+
)
|
169 |
+
|
170 |
+
assert g1_hash_with_node_attr1 == g2_hash_with_node_attr1
|
171 |
+
assert g1_hash_with_node_attr2 == g2_hash_with_node_attr2
|
172 |
+
|
173 |
+
|
174 |
+
def test_missing_node_attr():
|
175 |
+
"""
|
176 |
+
If the 'node_attr' argument is supplied but is missing from a node in the graph,
|
177 |
+
we should raise a KeyError
|
178 |
+
"""
|
179 |
+
G = nx.Graph()
|
180 |
+
G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
|
181 |
+
G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
|
182 |
+
pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, node_attr="node_attr1")
|
183 |
+
|
184 |
+
|
185 |
+
def test_isomorphic_edge_attr_and_node_attr():
|
186 |
+
"""
|
187 |
+
Isomorphic graphs with differing node attributes should yield different graph
|
188 |
+
hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
|
189 |
+
the graph, and there are no hash collisions.
|
190 |
+
The output should still be invariant to node-relabeling
|
191 |
+
"""
|
192 |
+
n, r = 100, 10
|
193 |
+
p = 1.0 / r
|
194 |
+
for i in range(1, r + 1):
|
195 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
|
196 |
+
|
197 |
+
for u in G1.nodes():
|
198 |
+
G1.nodes[u]["node_attr1"] = f"{u}-1"
|
199 |
+
G1.nodes[u]["node_attr2"] = f"{u}-2"
|
200 |
+
|
201 |
+
for a, b in G1.edges:
|
202 |
+
G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
|
203 |
+
G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
|
204 |
+
|
205 |
+
g1_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
|
206 |
+
G1, edge_attr="edge_attr1", node_attr="node_attr1"
|
207 |
+
)
|
208 |
+
g1_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
|
209 |
+
G1, edge_attr="edge_attr2", node_attr="node_attr2"
|
210 |
+
)
|
211 |
+
g1_hash_edge1_node2 = nx.weisfeiler_lehman_graph_hash(
|
212 |
+
G1, edge_attr="edge_attr1", node_attr="node_attr2"
|
213 |
+
)
|
214 |
+
g1_hash_no_attr = nx.weisfeiler_lehman_graph_hash(G1)
|
215 |
+
|
216 |
+
assert g1_hash_edge1_node1 != g1_hash_no_attr
|
217 |
+
assert g1_hash_edge2_node2 != g1_hash_no_attr
|
218 |
+
assert g1_hash_edge1_node1 != g1_hash_edge2_node2
|
219 |
+
assert g1_hash_edge1_node2 != g1_hash_edge2_node2
|
220 |
+
assert g1_hash_edge1_node2 != g1_hash_edge1_node1
|
221 |
+
|
222 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
223 |
+
|
224 |
+
g2_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
|
225 |
+
G2, edge_attr="edge_attr1", node_attr="node_attr1"
|
226 |
+
)
|
227 |
+
g2_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
|
228 |
+
G2, edge_attr="edge_attr2", node_attr="node_attr2"
|
229 |
+
)
|
230 |
+
|
231 |
+
assert g1_hash_edge1_node1 == g2_hash_edge1_node1
|
232 |
+
assert g1_hash_edge2_node2 == g2_hash_edge2_node2
|
233 |
+
|
234 |
+
|
235 |
+
def test_digest_size():
|
236 |
+
"""
|
237 |
+
The hash string lengths should be as expected for a variety of graphs and
|
238 |
+
digest sizes
|
239 |
+
"""
|
240 |
+
n, r = 100, 10
|
241 |
+
p = 1.0 / r
|
242 |
+
for i in range(1, r + 1):
|
243 |
+
G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
|
244 |
+
|
245 |
+
h16 = nx.weisfeiler_lehman_graph_hash(G)
|
246 |
+
h32 = nx.weisfeiler_lehman_graph_hash(G, digest_size=32)
|
247 |
+
|
248 |
+
assert h16 != h32
|
249 |
+
assert len(h16) == 16 * 2
|
250 |
+
assert len(h32) == 32 * 2
|
251 |
+
|
252 |
+
|
253 |
+
# Unit tests for the :func:`~networkx.weisfeiler_lehman_hash_subgraphs` function
|
254 |
+
|
255 |
+
|
256 |
+
def is_subiteration(a, b):
|
257 |
+
"""
|
258 |
+
returns True if that each hash sequence in 'a' is a prefix for
|
259 |
+
the corresponding sequence indexed by the same node in 'b'.
|
260 |
+
"""
|
261 |
+
return all(b[node][: len(hashes)] == hashes for node, hashes in a.items())
|
262 |
+
|
263 |
+
|
264 |
+
def hexdigest_sizes_correct(a, digest_size):
|
265 |
+
"""
|
266 |
+
returns True if all hex digest sizes are the expected length in a node:subgraph-hashes
|
267 |
+
dictionary. Hex digest string length == 2 * bytes digest length since each pair of hex
|
268 |
+
digits encodes 1 byte (https://docs.python.org/3/library/hashlib.html)
|
269 |
+
"""
|
270 |
+
hexdigest_size = digest_size * 2
|
271 |
+
list_digest_sizes_correct = lambda l: all(len(x) == hexdigest_size for x in l)
|
272 |
+
return all(list_digest_sizes_correct(hashes) for hashes in a.values())
|
273 |
+
|
274 |
+
|
275 |
+
def test_empty_graph_subgraph_hash():
|
276 |
+
""" "
|
277 |
+
empty graphs should give empty dict subgraph hashes regardless of other params
|
278 |
+
"""
|
279 |
+
G = nx.empty_graph()
|
280 |
+
|
281 |
+
subgraph_hashes1 = nx.weisfeiler_lehman_subgraph_hashes(G)
|
282 |
+
subgraph_hashes2 = nx.weisfeiler_lehman_subgraph_hashes(G, edge_attr="edge_attr")
|
283 |
+
subgraph_hashes3 = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="edge_attr")
|
284 |
+
subgraph_hashes4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=2)
|
285 |
+
subgraph_hashes5 = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=64)
|
286 |
+
|
287 |
+
assert subgraph_hashes1 == {}
|
288 |
+
assert subgraph_hashes2 == {}
|
289 |
+
assert subgraph_hashes3 == {}
|
290 |
+
assert subgraph_hashes4 == {}
|
291 |
+
assert subgraph_hashes5 == {}
|
292 |
+
|
293 |
+
|
294 |
+
def test_directed_subgraph_hash():
|
295 |
+
"""
|
296 |
+
A directed graph with no bi-directional edges should yield different subgraph hashes
|
297 |
+
to the same graph taken as undirected, if all hashes don't collide.
|
298 |
+
"""
|
299 |
+
r = 10
|
300 |
+
for i in range(r):
|
301 |
+
G_directed = nx.gn_graph(10 + r, seed=100 + i)
|
302 |
+
G_undirected = nx.to_undirected(G_directed)
|
303 |
+
|
304 |
+
directed_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_directed)
|
305 |
+
undirected_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_undirected)
|
306 |
+
|
307 |
+
assert directed_subgraph_hashes != undirected_subgraph_hashes
|
308 |
+
|
309 |
+
|
310 |
+
def test_reversed_subgraph_hash():
|
311 |
+
"""
|
312 |
+
A directed graph with no bi-directional edges should yield different subgraph hashes
|
313 |
+
to the same graph taken with edge directions reversed if there are no hash collisions.
|
314 |
+
Here we test a cycle graph which is the minimal counterexample
|
315 |
+
"""
|
316 |
+
G = nx.cycle_graph(5, create_using=nx.DiGraph)
|
317 |
+
nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
|
318 |
+
|
319 |
+
G_reversed = G.reverse()
|
320 |
+
|
321 |
+
h = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
|
322 |
+
h_reversed = nx.weisfeiler_lehman_subgraph_hashes(G_reversed, node_attr="label")
|
323 |
+
|
324 |
+
assert h != h_reversed
|
325 |
+
|
326 |
+
|
327 |
+
def test_isomorphic_subgraph_hash():
|
328 |
+
"""
|
329 |
+
the subgraph hashes should be invariant to node-relabeling when the output is reindexed
|
330 |
+
by the same mapping and all hashes don't collide.
|
331 |
+
"""
|
332 |
+
n, r = 100, 10
|
333 |
+
p = 1.0 / r
|
334 |
+
for i in range(1, r + 1):
|
335 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
|
336 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
337 |
+
|
338 |
+
g1_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G1)
|
339 |
+
g2_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G2)
|
340 |
+
|
341 |
+
assert g1_subgraph_hashes == {-1 * k: v for k, v in g2_subgraph_hashes.items()}
|
342 |
+
|
343 |
+
|
344 |
+
def test_isomorphic_edge_attr_subgraph_hash():
|
345 |
+
"""
|
346 |
+
Isomorphic graphs with differing edge attributes should yield different subgraph
|
347 |
+
hashes if the 'edge_attr' argument is supplied and populated in the graph, and
|
348 |
+
all hashes don't collide.
|
349 |
+
The output should still be invariant to node-relabeling
|
350 |
+
"""
|
351 |
+
n, r = 100, 10
|
352 |
+
p = 1.0 / r
|
353 |
+
for i in range(1, r + 1):
|
354 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
|
355 |
+
|
356 |
+
for a, b in G1.edges:
|
357 |
+
G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
|
358 |
+
G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
|
359 |
+
|
360 |
+
g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
|
361 |
+
G1, edge_attr="edge_attr1"
|
362 |
+
)
|
363 |
+
g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
|
364 |
+
G1, edge_attr="edge_attr2"
|
365 |
+
)
|
366 |
+
g1_hash_no_edge_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, edge_attr=None)
|
367 |
+
|
368 |
+
assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
|
369 |
+
assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
|
370 |
+
assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
|
371 |
+
|
372 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
373 |
+
|
374 |
+
g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
|
375 |
+
G2, edge_attr="edge_attr1"
|
376 |
+
)
|
377 |
+
g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
|
378 |
+
G2, edge_attr="edge_attr2"
|
379 |
+
)
|
380 |
+
|
381 |
+
assert g1_hash_with_edge_attr1 == {
|
382 |
+
-1 * k: v for k, v in g2_hash_with_edge_attr1.items()
|
383 |
+
}
|
384 |
+
assert g1_hash_with_edge_attr2 == {
|
385 |
+
-1 * k: v for k, v in g2_hash_with_edge_attr2.items()
|
386 |
+
}
|
387 |
+
|
388 |
+
|
389 |
+
def test_missing_edge_attr_subgraph_hash():
|
390 |
+
"""
|
391 |
+
If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
|
392 |
+
we should raise a KeyError
|
393 |
+
"""
|
394 |
+
G = nx.Graph()
|
395 |
+
G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
|
396 |
+
pytest.raises(
|
397 |
+
KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, edge_attr="edge_attr1"
|
398 |
+
)
|
399 |
+
|
400 |
+
|
401 |
+
def test_isomorphic_node_attr_subgraph_hash():
|
402 |
+
"""
|
403 |
+
Isomorphic graphs with differing node attributes should yield different subgraph
|
404 |
+
hashes if the 'node_attr' argument is supplied and populated in the graph, and
|
405 |
+
all hashes don't collide.
|
406 |
+
The output should still be invariant to node-relabeling
|
407 |
+
"""
|
408 |
+
n, r = 100, 10
|
409 |
+
p = 1.0 / r
|
410 |
+
for i in range(1, r + 1):
|
411 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
|
412 |
+
|
413 |
+
for u in G1.nodes():
|
414 |
+
G1.nodes[u]["node_attr1"] = f"{u}-1"
|
415 |
+
G1.nodes[u]["node_attr2"] = f"{u}-2"
|
416 |
+
|
417 |
+
g1_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
|
418 |
+
G1, node_attr="node_attr1"
|
419 |
+
)
|
420 |
+
g1_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
|
421 |
+
G1, node_attr="node_attr2"
|
422 |
+
)
|
423 |
+
g1_hash_no_node_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, node_attr=None)
|
424 |
+
|
425 |
+
assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
|
426 |
+
assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
|
427 |
+
assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
|
428 |
+
|
429 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
430 |
+
|
431 |
+
g2_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
|
432 |
+
G2, node_attr="node_attr1"
|
433 |
+
)
|
434 |
+
g2_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
|
435 |
+
G2, node_attr="node_attr2"
|
436 |
+
)
|
437 |
+
|
438 |
+
assert g1_hash_with_node_attr1 == {
|
439 |
+
-1 * k: v for k, v in g2_hash_with_node_attr1.items()
|
440 |
+
}
|
441 |
+
assert g1_hash_with_node_attr2 == {
|
442 |
+
-1 * k: v for k, v in g2_hash_with_node_attr2.items()
|
443 |
+
}
|
444 |
+
|
445 |
+
|
446 |
+
def test_missing_node_attr_subgraph_hash():
|
447 |
+
"""
|
448 |
+
If the 'node_attr' argument is supplied but is missing from a node in the graph,
|
449 |
+
we should raise a KeyError
|
450 |
+
"""
|
451 |
+
G = nx.Graph()
|
452 |
+
G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
|
453 |
+
G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
|
454 |
+
pytest.raises(
|
455 |
+
KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, node_attr="node_attr1"
|
456 |
+
)
|
457 |
+
|
458 |
+
|
459 |
+
def test_isomorphic_edge_attr_and_node_attr_subgraph_hash():
|
460 |
+
"""
|
461 |
+
Isomorphic graphs with differing node attributes should yield different subgraph
|
462 |
+
hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
|
463 |
+
the graph, and all hashes don't collide
|
464 |
+
The output should still be invariant to node-relabeling
|
465 |
+
"""
|
466 |
+
n, r = 100, 10
|
467 |
+
p = 1.0 / r
|
468 |
+
for i in range(1, r + 1):
|
469 |
+
G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
|
470 |
+
|
471 |
+
for u in G1.nodes():
|
472 |
+
G1.nodes[u]["node_attr1"] = f"{u}-1"
|
473 |
+
G1.nodes[u]["node_attr2"] = f"{u}-2"
|
474 |
+
|
475 |
+
for a, b in G1.edges:
|
476 |
+
G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
|
477 |
+
G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
|
478 |
+
|
479 |
+
g1_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
|
480 |
+
G1, edge_attr="edge_attr1", node_attr="node_attr1"
|
481 |
+
)
|
482 |
+
g1_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
|
483 |
+
G1, edge_attr="edge_attr2", node_attr="node_attr2"
|
484 |
+
)
|
485 |
+
g1_hash_edge1_node2 = nx.weisfeiler_lehman_subgraph_hashes(
|
486 |
+
G1, edge_attr="edge_attr1", node_attr="node_attr2"
|
487 |
+
)
|
488 |
+
g1_hash_no_attr = nx.weisfeiler_lehman_subgraph_hashes(G1)
|
489 |
+
|
490 |
+
assert g1_hash_edge1_node1 != g1_hash_no_attr
|
491 |
+
assert g1_hash_edge2_node2 != g1_hash_no_attr
|
492 |
+
assert g1_hash_edge1_node1 != g1_hash_edge2_node2
|
493 |
+
assert g1_hash_edge1_node2 != g1_hash_edge2_node2
|
494 |
+
assert g1_hash_edge1_node2 != g1_hash_edge1_node1
|
495 |
+
|
496 |
+
G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
|
497 |
+
|
498 |
+
g2_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
|
499 |
+
G2, edge_attr="edge_attr1", node_attr="node_attr1"
|
500 |
+
)
|
501 |
+
g2_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
|
502 |
+
G2, edge_attr="edge_attr2", node_attr="node_attr2"
|
503 |
+
)
|
504 |
+
|
505 |
+
assert g1_hash_edge1_node1 == {
|
506 |
+
-1 * k: v for k, v in g2_hash_edge1_node1.items()
|
507 |
+
}
|
508 |
+
assert g1_hash_edge2_node2 == {
|
509 |
+
-1 * k: v for k, v in g2_hash_edge2_node2.items()
|
510 |
+
}
|
511 |
+
|
512 |
+
|
513 |
+
def test_iteration_depth():
|
514 |
+
"""
|
515 |
+
All nodes should have the correct number of subgraph hashes in the output when
|
516 |
+
using degree as initial node labels
|
517 |
+
Subsequent iteration depths for the same graph should be additive for each node
|
518 |
+
"""
|
519 |
+
n, r = 100, 10
|
520 |
+
p = 1.0 / r
|
521 |
+
for i in range(1, r + 1):
|
522 |
+
G = nx.erdos_renyi_graph(n, p * i, seed=600 + i)
|
523 |
+
|
524 |
+
depth3 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=3)
|
525 |
+
depth4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=4)
|
526 |
+
depth5 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=5)
|
527 |
+
|
528 |
+
assert all(len(hashes) == 3 for hashes in depth3.values())
|
529 |
+
assert all(len(hashes) == 4 for hashes in depth4.values())
|
530 |
+
assert all(len(hashes) == 5 for hashes in depth5.values())
|
531 |
+
|
532 |
+
assert is_subiteration(depth3, depth4)
|
533 |
+
assert is_subiteration(depth4, depth5)
|
534 |
+
assert is_subiteration(depth3, depth5)
|
535 |
+
|
536 |
+
|
537 |
+
def test_iteration_depth_edge_attr():
|
538 |
+
"""
|
539 |
+
All nodes should have the correct number of subgraph hashes in the output when
|
540 |
+
setting initial node labels empty and using an edge attribute when aggregating
|
541 |
+
neighborhoods.
|
542 |
+
Subsequent iteration depths for the same graph should be additive for each node
|
543 |
+
"""
|
544 |
+
n, r = 100, 10
|
545 |
+
p = 1.0 / r
|
546 |
+
for i in range(1, r + 1):
|
547 |
+
G = nx.erdos_renyi_graph(n, p * i, seed=700 + i)
|
548 |
+
|
549 |
+
for a, b in G.edges:
|
550 |
+
G[a][b]["edge_attr1"] = f"{a}-{b}-1"
|
551 |
+
|
552 |
+
depth3 = nx.weisfeiler_lehman_subgraph_hashes(
|
553 |
+
G, edge_attr="edge_attr1", iterations=3
|
554 |
+
)
|
555 |
+
depth4 = nx.weisfeiler_lehman_subgraph_hashes(
|
556 |
+
G, edge_attr="edge_attr1", iterations=4
|
557 |
+
)
|
558 |
+
depth5 = nx.weisfeiler_lehman_subgraph_hashes(
|
559 |
+
G, edge_attr="edge_attr1", iterations=5
|
560 |
+
)
|
561 |
+
|
562 |
+
assert all(len(hashes) == 3 for hashes in depth3.values())
|
563 |
+
assert all(len(hashes) == 4 for hashes in depth4.values())
|
564 |
+
assert all(len(hashes) == 5 for hashes in depth5.values())
|
565 |
+
|
566 |
+
assert is_subiteration(depth3, depth4)
|
567 |
+
assert is_subiteration(depth4, depth5)
|
568 |
+
assert is_subiteration(depth3, depth5)
|
569 |
+
|
570 |
+
|
571 |
+
def test_iteration_depth_node_attr():
|
572 |
+
"""
|
573 |
+
All nodes should have the correct number of subgraph hashes in the output when
|
574 |
+
setting initial node labels to an attribute.
|
575 |
+
Subsequent iteration depths for the same graph should be additive for each node
|
576 |
+
"""
|
577 |
+
n, r = 100, 10
|
578 |
+
p = 1.0 / r
|
579 |
+
for i in range(1, r + 1):
|
580 |
+
G = nx.erdos_renyi_graph(n, p * i, seed=800 + i)
|
581 |
+
|
582 |
+
for u in G.nodes():
|
583 |
+
G.nodes[u]["node_attr1"] = f"{u}-1"
|
584 |
+
|
585 |
+
depth3 = nx.weisfeiler_lehman_subgraph_hashes(
|
586 |
+
G, node_attr="node_attr1", iterations=3
|
587 |
+
)
|
588 |
+
depth4 = nx.weisfeiler_lehman_subgraph_hashes(
|
589 |
+
G, node_attr="node_attr1", iterations=4
|
590 |
+
)
|
591 |
+
depth5 = nx.weisfeiler_lehman_subgraph_hashes(
|
592 |
+
G, node_attr="node_attr1", iterations=5
|
593 |
+
)
|
594 |
+
|
595 |
+
assert all(len(hashes) == 3 for hashes in depth3.values())
|
596 |
+
assert all(len(hashes) == 4 for hashes in depth4.values())
|
597 |
+
assert all(len(hashes) == 5 for hashes in depth5.values())
|
598 |
+
|
599 |
+
assert is_subiteration(depth3, depth4)
|
600 |
+
assert is_subiteration(depth4, depth5)
|
601 |
+
assert is_subiteration(depth3, depth5)
|
602 |
+
|
603 |
+
|
604 |
+
def test_iteration_depth_node_edge_attr():
|
605 |
+
"""
|
606 |
+
All nodes should have the correct number of subgraph hashes in the output when
|
607 |
+
setting initial node labels to an attribute and also using an edge attribute when
|
608 |
+
aggregating neighborhoods.
|
609 |
+
Subsequent iteration depths for the same graph should be additive for each node
|
610 |
+
"""
|
611 |
+
n, r = 100, 10
|
612 |
+
p = 1.0 / r
|
613 |
+
for i in range(1, r + 1):
|
614 |
+
G = nx.erdos_renyi_graph(n, p * i, seed=900 + i)
|
615 |
+
|
616 |
+
for u in G.nodes():
|
617 |
+
G.nodes[u]["node_attr1"] = f"{u}-1"
|
618 |
+
|
619 |
+
for a, b in G.edges:
|
620 |
+
G[a][b]["edge_attr1"] = f"{a}-{b}-1"
|
621 |
+
|
622 |
+
depth3 = nx.weisfeiler_lehman_subgraph_hashes(
|
623 |
+
G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=3
|
624 |
+
)
|
625 |
+
depth4 = nx.weisfeiler_lehman_subgraph_hashes(
|
626 |
+
G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=4
|
627 |
+
)
|
628 |
+
depth5 = nx.weisfeiler_lehman_subgraph_hashes(
|
629 |
+
G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=5
|
630 |
+
)
|
631 |
+
|
632 |
+
assert all(len(hashes) == 3 for hashes in depth3.values())
|
633 |
+
assert all(len(hashes) == 4 for hashes in depth4.values())
|
634 |
+
assert all(len(hashes) == 5 for hashes in depth5.values())
|
635 |
+
|
636 |
+
assert is_subiteration(depth3, depth4)
|
637 |
+
assert is_subiteration(depth4, depth5)
|
638 |
+
assert is_subiteration(depth3, depth5)
|
639 |
+
|
640 |
+
|
641 |
+
def test_digest_size_subgraph_hash():
|
642 |
+
"""
|
643 |
+
The hash string lengths should be as expected for a variety of graphs and
|
644 |
+
digest sizes
|
645 |
+
"""
|
646 |
+
n, r = 100, 10
|
647 |
+
p = 1.0 / r
|
648 |
+
for i in range(1, r + 1):
|
649 |
+
G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
|
650 |
+
|
651 |
+
digest_size16_hashes = nx.weisfeiler_lehman_subgraph_hashes(G)
|
652 |
+
digest_size32_hashes = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=32)
|
653 |
+
|
654 |
+
assert digest_size16_hashes != digest_size32_hashes
|
655 |
+
|
656 |
+
assert hexdigest_sizes_correct(digest_size16_hashes, 16)
|
657 |
+
assert hexdigest_sizes_correct(digest_size32_hashes, 32)
|
658 |
+
|
659 |
+
|
660 |
+
def test_initial_node_labels_subgraph_hash():
|
661 |
+
"""
|
662 |
+
Including the hashed initial label prepends an extra hash to the lists
|
663 |
+
"""
|
664 |
+
G = nx.path_graph(5)
|
665 |
+
nx.set_node_attributes(G, {i: int(0 < i < 4) for i in G}, "label")
|
666 |
+
# initial node labels:
|
667 |
+
# 0--1--1--1--0
|
668 |
+
|
669 |
+
without_initial_label = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
|
670 |
+
assert all(len(v) == 3 for v in without_initial_label.values())
|
671 |
+
# 3 different 1 hop nhds
|
672 |
+
assert len({v[0] for v in without_initial_label.values()}) == 3
|
673 |
+
|
674 |
+
with_initial_label = nx.weisfeiler_lehman_subgraph_hashes(
|
675 |
+
G, node_attr="label", include_initial_labels=True
|
676 |
+
)
|
677 |
+
assert all(len(v) == 4 for v in with_initial_label.values())
|
678 |
+
# 2 different initial labels
|
679 |
+
assert len({v[0] for v in with_initial_label.values()}) == 2
|
680 |
+
|
681 |
+
# check hashes match otherwise
|
682 |
+
for u in G:
|
683 |
+
for a, b in zip(
|
684 |
+
with_initial_label[u][1:], without_initial_label[u], strict=True
|
685 |
+
):
|
686 |
+
assert a == b
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_graphical.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
def test_valid_degree_sequence1():
|
7 |
+
n = 100
|
8 |
+
p = 0.3
|
9 |
+
for i in range(10):
|
10 |
+
G = nx.erdos_renyi_graph(n, p)
|
11 |
+
deg = (d for n, d in G.degree())
|
12 |
+
assert nx.is_graphical(deg, method="eg")
|
13 |
+
assert nx.is_graphical(deg, method="hh")
|
14 |
+
|
15 |
+
|
16 |
+
def test_valid_degree_sequence2():
|
17 |
+
n = 100
|
18 |
+
for i in range(10):
|
19 |
+
G = nx.barabasi_albert_graph(n, 1)
|
20 |
+
deg = (d for n, d in G.degree())
|
21 |
+
assert nx.is_graphical(deg, method="eg")
|
22 |
+
assert nx.is_graphical(deg, method="hh")
|
23 |
+
|
24 |
+
|
25 |
+
def test_string_input():
|
26 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, [], "foo")
|
27 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, ["red"], "hh")
|
28 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, ["red"], "eg")
|
29 |
+
|
30 |
+
|
31 |
+
def test_non_integer_input():
|
32 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, [72.5], "eg")
|
33 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, [72.5], "hh")
|
34 |
+
|
35 |
+
|
36 |
+
def test_negative_input():
|
37 |
+
assert not nx.is_graphical([-1], "hh")
|
38 |
+
assert not nx.is_graphical([-1], "eg")
|
39 |
+
|
40 |
+
|
41 |
+
class TestAtlas:
|
42 |
+
@classmethod
|
43 |
+
def setup_class(cls):
|
44 |
+
global atlas
|
45 |
+
from networkx.generators import atlas
|
46 |
+
|
47 |
+
cls.GAG = atlas.graph_atlas_g()
|
48 |
+
|
49 |
+
def test_atlas(self):
|
50 |
+
for graph in self.GAG:
|
51 |
+
deg = (d for n, d in graph.degree())
|
52 |
+
assert nx.is_graphical(deg, method="eg")
|
53 |
+
assert nx.is_graphical(deg, method="hh")
|
54 |
+
|
55 |
+
|
56 |
+
def test_small_graph_true():
|
57 |
+
z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
|
58 |
+
assert nx.is_graphical(z, method="hh")
|
59 |
+
assert nx.is_graphical(z, method="eg")
|
60 |
+
z = [10, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
|
61 |
+
assert nx.is_graphical(z, method="hh")
|
62 |
+
assert nx.is_graphical(z, method="eg")
|
63 |
+
z = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
|
64 |
+
assert nx.is_graphical(z, method="hh")
|
65 |
+
assert nx.is_graphical(z, method="eg")
|
66 |
+
|
67 |
+
|
68 |
+
def test_small_graph_false():
|
69 |
+
z = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
|
70 |
+
assert not nx.is_graphical(z, method="hh")
|
71 |
+
assert not nx.is_graphical(z, method="eg")
|
72 |
+
z = [6, 5, 4, 4, 2, 1, 1, 1]
|
73 |
+
assert not nx.is_graphical(z, method="hh")
|
74 |
+
assert not nx.is_graphical(z, method="eg")
|
75 |
+
z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
|
76 |
+
assert not nx.is_graphical(z, method="hh")
|
77 |
+
assert not nx.is_graphical(z, method="eg")
|
78 |
+
|
79 |
+
|
80 |
+
def test_directed_degree_sequence():
|
81 |
+
# Test a range of valid directed degree sequences
|
82 |
+
n, r = 100, 10
|
83 |
+
p = 1.0 / r
|
84 |
+
for i in range(r):
|
85 |
+
G = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
|
86 |
+
din = (d for n, d in G.in_degree())
|
87 |
+
dout = (d for n, d in G.out_degree())
|
88 |
+
assert nx.is_digraphical(din, dout)
|
89 |
+
|
90 |
+
|
91 |
+
def test_small_directed_sequences():
|
92 |
+
dout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
|
93 |
+
din = [3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1]
|
94 |
+
assert nx.is_digraphical(din, dout)
|
95 |
+
# Test nongraphical directed sequence
|
96 |
+
dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
|
97 |
+
din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
|
98 |
+
assert not nx.is_digraphical(din, dout)
|
99 |
+
# Test digraphical small sequence
|
100 |
+
dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
|
101 |
+
din = [2, 2, 2, 2, 2, 2, 2, 2, 1, 1]
|
102 |
+
assert nx.is_digraphical(din, dout)
|
103 |
+
# Test nonmatching sum
|
104 |
+
din = [2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1]
|
105 |
+
assert not nx.is_digraphical(din, dout)
|
106 |
+
# Test for negative integer in sequence
|
107 |
+
din = [2, 2, 2, -2, 2, 2, 2, 2, 1, 1, 4]
|
108 |
+
assert not nx.is_digraphical(din, dout)
|
109 |
+
# Test for noninteger
|
110 |
+
din = dout = [1, 1, 1.1, 1]
|
111 |
+
assert not nx.is_digraphical(din, dout)
|
112 |
+
din = dout = [1, 1, "rer", 1]
|
113 |
+
assert not nx.is_digraphical(din, dout)
|
114 |
+
|
115 |
+
|
116 |
+
def test_multi_sequence():
|
117 |
+
# Test nongraphical multi sequence
|
118 |
+
seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1]
|
119 |
+
assert not nx.is_multigraphical(seq)
|
120 |
+
# Test small graphical multi sequence
|
121 |
+
seq = [6, 5, 4, 4, 2, 1, 1, 1]
|
122 |
+
assert nx.is_multigraphical(seq)
|
123 |
+
# Test for negative integer in sequence
|
124 |
+
seq = [6, 5, 4, -4, 2, 1, 1, 1]
|
125 |
+
assert not nx.is_multigraphical(seq)
|
126 |
+
# Test for sequence with odd sum
|
127 |
+
seq = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
|
128 |
+
assert not nx.is_multigraphical(seq)
|
129 |
+
# Test for noninteger
|
130 |
+
seq = [1, 1, 1.1, 1]
|
131 |
+
assert not nx.is_multigraphical(seq)
|
132 |
+
seq = [1, 1, "rer", 1]
|
133 |
+
assert not nx.is_multigraphical(seq)
|
134 |
+
|
135 |
+
|
136 |
+
def test_pseudo_sequence():
|
137 |
+
# Test small valid pseudo sequence
|
138 |
+
seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1]
|
139 |
+
assert nx.is_pseudographical(seq)
|
140 |
+
# Test for sequence with odd sum
|
141 |
+
seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
|
142 |
+
assert not nx.is_pseudographical(seq)
|
143 |
+
# Test for negative integer in sequence
|
144 |
+
seq = [1000, 3, 3, 3, 3, 2, 2, -2, 1, 1]
|
145 |
+
assert not nx.is_pseudographical(seq)
|
146 |
+
# Test for noninteger
|
147 |
+
seq = [1, 1, 1.1, 1]
|
148 |
+
assert not nx.is_pseudographical(seq)
|
149 |
+
seq = [1, 1, "rer", 1]
|
150 |
+
assert not nx.is_pseudographical(seq)
|
151 |
+
|
152 |
+
|
153 |
+
def test_numpy_degree_sequence():
|
154 |
+
np = pytest.importorskip("numpy")
|
155 |
+
ds = np.array([1, 2, 2, 2, 1], dtype=np.int64)
|
156 |
+
assert nx.is_graphical(ds, "eg")
|
157 |
+
assert nx.is_graphical(ds, "hh")
|
158 |
+
ds = np.array([1, 2, 2, 2, 1], dtype=np.float64)
|
159 |
+
assert nx.is_graphical(ds, "eg")
|
160 |
+
assert nx.is_graphical(ds, "hh")
|
161 |
+
ds = np.array([1.1, 2, 2, 2, 1], dtype=np.float64)
|
162 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "eg")
|
163 |
+
pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "hh")
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_isolate.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.isolates` module."""
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
def test_is_isolate():
|
7 |
+
G = nx.Graph()
|
8 |
+
G.add_edge(0, 1)
|
9 |
+
G.add_node(2)
|
10 |
+
assert not nx.is_isolate(G, 0)
|
11 |
+
assert not nx.is_isolate(G, 1)
|
12 |
+
assert nx.is_isolate(G, 2)
|
13 |
+
|
14 |
+
|
15 |
+
def test_isolates():
|
16 |
+
G = nx.Graph()
|
17 |
+
G.add_edge(0, 1)
|
18 |
+
G.add_nodes_from([2, 3])
|
19 |
+
assert sorted(nx.isolates(G)) == [2, 3]
|
20 |
+
|
21 |
+
|
22 |
+
def test_number_of_isolates():
|
23 |
+
G = nx.Graph()
|
24 |
+
G.add_edge(0, 1)
|
25 |
+
G.add_nodes_from([2, 3])
|
26 |
+
assert nx.number_of_isolates(G) == 2
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_link_prediction.py
ADDED
@@ -0,0 +1,586 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from functools import partial
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
|
8 |
+
|
9 |
+
def _test_func(G, ebunch, expected, predict_func, **kwargs):
|
10 |
+
result = predict_func(G, ebunch, **kwargs)
|
11 |
+
exp_dict = {tuple(sorted([u, v])): score for u, v, score in expected}
|
12 |
+
res_dict = {tuple(sorted([u, v])): score for u, v, score in result}
|
13 |
+
|
14 |
+
assert len(exp_dict) == len(res_dict)
|
15 |
+
for p in exp_dict:
|
16 |
+
assert exp_dict[p] == pytest.approx(res_dict[p], abs=1e-7)
|
17 |
+
|
18 |
+
|
19 |
+
class TestResourceAllocationIndex:
|
20 |
+
@classmethod
|
21 |
+
def setup_class(cls):
|
22 |
+
cls.func = staticmethod(nx.resource_allocation_index)
|
23 |
+
cls.test = partial(_test_func, predict_func=cls.func)
|
24 |
+
|
25 |
+
def test_K5(self):
|
26 |
+
G = nx.complete_graph(5)
|
27 |
+
self.test(G, [(0, 1)], [(0, 1, 0.75)])
|
28 |
+
|
29 |
+
def test_P3(self):
|
30 |
+
G = nx.path_graph(3)
|
31 |
+
self.test(G, [(0, 2)], [(0, 2, 0.5)])
|
32 |
+
|
33 |
+
def test_S4(self):
|
34 |
+
G = nx.star_graph(4)
|
35 |
+
self.test(G, [(1, 2)], [(1, 2, 0.25)])
|
36 |
+
|
37 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
38 |
+
def test_notimplemented(self, graph_type):
|
39 |
+
assert pytest.raises(
|
40 |
+
nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
|
41 |
+
)
|
42 |
+
|
43 |
+
def test_node_not_found(self):
|
44 |
+
G = nx.Graph()
|
45 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
46 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
47 |
+
|
48 |
+
def test_no_common_neighbor(self):
|
49 |
+
G = nx.Graph()
|
50 |
+
G.add_nodes_from([0, 1])
|
51 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
52 |
+
|
53 |
+
def test_equal_nodes(self):
|
54 |
+
G = nx.complete_graph(4)
|
55 |
+
self.test(G, [(0, 0)], [(0, 0, 1)])
|
56 |
+
|
57 |
+
def test_all_nonexistent_edges(self):
|
58 |
+
G = nx.Graph()
|
59 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
60 |
+
self.test(G, None, [(0, 3, 0.5), (1, 2, 0.5), (1, 3, 0)])
|
61 |
+
|
62 |
+
|
63 |
+
class TestJaccardCoefficient:
|
64 |
+
@classmethod
|
65 |
+
def setup_class(cls):
|
66 |
+
cls.func = staticmethod(nx.jaccard_coefficient)
|
67 |
+
cls.test = partial(_test_func, predict_func=cls.func)
|
68 |
+
|
69 |
+
def test_K5(self):
|
70 |
+
G = nx.complete_graph(5)
|
71 |
+
self.test(G, [(0, 1)], [(0, 1, 0.6)])
|
72 |
+
|
73 |
+
def test_P4(self):
|
74 |
+
G = nx.path_graph(4)
|
75 |
+
self.test(G, [(0, 2)], [(0, 2, 0.5)])
|
76 |
+
|
77 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
78 |
+
def test_notimplemented(self, graph_type):
|
79 |
+
assert pytest.raises(
|
80 |
+
nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
|
81 |
+
)
|
82 |
+
|
83 |
+
def test_node_not_found(self):
|
84 |
+
G = nx.Graph()
|
85 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
86 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
87 |
+
|
88 |
+
def test_no_common_neighbor(self):
|
89 |
+
G = nx.Graph()
|
90 |
+
G.add_edges_from([(0, 1), (2, 3)])
|
91 |
+
self.test(G, [(0, 2)], [(0, 2, 0)])
|
92 |
+
|
93 |
+
def test_isolated_nodes(self):
|
94 |
+
G = nx.Graph()
|
95 |
+
G.add_nodes_from([0, 1])
|
96 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
97 |
+
|
98 |
+
def test_all_nonexistent_edges(self):
|
99 |
+
G = nx.Graph()
|
100 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
101 |
+
self.test(G, None, [(0, 3, 0.5), (1, 2, 0.5), (1, 3, 0)])
|
102 |
+
|
103 |
+
|
104 |
+
class TestAdamicAdarIndex:
|
105 |
+
@classmethod
|
106 |
+
def setup_class(cls):
|
107 |
+
cls.func = staticmethod(nx.adamic_adar_index)
|
108 |
+
cls.test = partial(_test_func, predict_func=cls.func)
|
109 |
+
|
110 |
+
def test_K5(self):
|
111 |
+
G = nx.complete_graph(5)
|
112 |
+
self.test(G, [(0, 1)], [(0, 1, 3 / math.log(4))])
|
113 |
+
|
114 |
+
def test_P3(self):
|
115 |
+
G = nx.path_graph(3)
|
116 |
+
self.test(G, [(0, 2)], [(0, 2, 1 / math.log(2))])
|
117 |
+
|
118 |
+
def test_S4(self):
|
119 |
+
G = nx.star_graph(4)
|
120 |
+
self.test(G, [(1, 2)], [(1, 2, 1 / math.log(4))])
|
121 |
+
|
122 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
123 |
+
def test_notimplemented(self, graph_type):
|
124 |
+
assert pytest.raises(
|
125 |
+
nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
|
126 |
+
)
|
127 |
+
|
128 |
+
def test_node_not_found(self):
|
129 |
+
G = nx.Graph()
|
130 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
131 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
132 |
+
|
133 |
+
def test_no_common_neighbor(self):
|
134 |
+
G = nx.Graph()
|
135 |
+
G.add_nodes_from([0, 1])
|
136 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
137 |
+
|
138 |
+
def test_equal_nodes(self):
|
139 |
+
G = nx.complete_graph(4)
|
140 |
+
self.test(G, [(0, 0)], [(0, 0, 3 / math.log(3))])
|
141 |
+
|
142 |
+
def test_all_nonexistent_edges(self):
|
143 |
+
G = nx.Graph()
|
144 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
145 |
+
self.test(
|
146 |
+
G, None, [(0, 3, 1 / math.log(2)), (1, 2, 1 / math.log(2)), (1, 3, 0)]
|
147 |
+
)
|
148 |
+
|
149 |
+
|
150 |
+
class TestCommonNeighborCentrality:
|
151 |
+
@classmethod
|
152 |
+
def setup_class(cls):
|
153 |
+
cls.func = staticmethod(nx.common_neighbor_centrality)
|
154 |
+
cls.test = partial(_test_func, predict_func=cls.func)
|
155 |
+
|
156 |
+
def test_K5(self):
|
157 |
+
G = nx.complete_graph(5)
|
158 |
+
self.test(G, [(0, 1)], [(0, 1, 3.0)], alpha=1)
|
159 |
+
self.test(G, [(0, 1)], [(0, 1, 5.0)], alpha=0)
|
160 |
+
|
161 |
+
def test_P3(self):
|
162 |
+
G = nx.path_graph(3)
|
163 |
+
self.test(G, [(0, 2)], [(0, 2, 1.25)], alpha=0.5)
|
164 |
+
|
165 |
+
def test_S4(self):
|
166 |
+
G = nx.star_graph(4)
|
167 |
+
self.test(G, [(1, 2)], [(1, 2, 1.75)], alpha=0.5)
|
168 |
+
|
169 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
170 |
+
def test_notimplemented(self, graph_type):
|
171 |
+
assert pytest.raises(
|
172 |
+
nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
|
173 |
+
)
|
174 |
+
|
175 |
+
def test_node_u_not_found(self):
|
176 |
+
G = nx.Graph()
|
177 |
+
G.add_edges_from([(1, 3), (2, 3)])
|
178 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 1)])
|
179 |
+
|
180 |
+
def test_node_v_not_found(self):
|
181 |
+
G = nx.Graph()
|
182 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
183 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
184 |
+
|
185 |
+
def test_no_common_neighbor(self):
|
186 |
+
G = nx.Graph()
|
187 |
+
G.add_nodes_from([0, 1])
|
188 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
189 |
+
|
190 |
+
def test_equal_nodes(self):
|
191 |
+
G = nx.complete_graph(4)
|
192 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, self.test, G, [(0, 0)], [])
|
193 |
+
|
194 |
+
def test_equal_nodes_with_alpha_one_raises_error(self):
|
195 |
+
G = nx.complete_graph(4)
|
196 |
+
assert pytest.raises(
|
197 |
+
nx.NetworkXAlgorithmError, self.test, G, [(0, 0)], [], alpha=1.0
|
198 |
+
)
|
199 |
+
|
200 |
+
def test_all_nonexistent_edges(self):
|
201 |
+
G = nx.Graph()
|
202 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
203 |
+
self.test(G, None, [(0, 3, 1.5), (1, 2, 1.5), (1, 3, 2 / 3)], alpha=0.5)
|
204 |
+
|
205 |
+
|
206 |
+
class TestPreferentialAttachment:
|
207 |
+
@classmethod
|
208 |
+
def setup_class(cls):
|
209 |
+
cls.func = staticmethod(nx.preferential_attachment)
|
210 |
+
cls.test = partial(_test_func, predict_func=cls.func)
|
211 |
+
|
212 |
+
def test_K5(self):
|
213 |
+
G = nx.complete_graph(5)
|
214 |
+
self.test(G, [(0, 1)], [(0, 1, 16)])
|
215 |
+
|
216 |
+
def test_P3(self):
|
217 |
+
G = nx.path_graph(3)
|
218 |
+
self.test(G, [(0, 1)], [(0, 1, 2)])
|
219 |
+
|
220 |
+
def test_S4(self):
|
221 |
+
G = nx.star_graph(4)
|
222 |
+
self.test(G, [(0, 2)], [(0, 2, 4)])
|
223 |
+
|
224 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
225 |
+
def test_notimplemented(self, graph_type):
|
226 |
+
assert pytest.raises(
|
227 |
+
nx.NetworkXNotImplemented, self.func, graph_type([(0, 1), (1, 2)]), [(0, 2)]
|
228 |
+
)
|
229 |
+
|
230 |
+
def test_node_not_found(self):
|
231 |
+
G = nx.Graph()
|
232 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
233 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
234 |
+
|
235 |
+
def test_zero_degrees(self):
|
236 |
+
G = nx.Graph()
|
237 |
+
G.add_nodes_from([0, 1])
|
238 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
239 |
+
|
240 |
+
def test_all_nonexistent_edges(self):
|
241 |
+
G = nx.Graph()
|
242 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
243 |
+
self.test(G, None, [(0, 3, 2), (1, 2, 2), (1, 3, 1)])
|
244 |
+
|
245 |
+
|
246 |
+
class TestCNSoundarajanHopcroft:
|
247 |
+
@classmethod
|
248 |
+
def setup_class(cls):
|
249 |
+
cls.func = staticmethod(nx.cn_soundarajan_hopcroft)
|
250 |
+
cls.test = partial(_test_func, predict_func=cls.func, community="community")
|
251 |
+
|
252 |
+
def test_K5(self):
|
253 |
+
G = nx.complete_graph(5)
|
254 |
+
G.nodes[0]["community"] = 0
|
255 |
+
G.nodes[1]["community"] = 0
|
256 |
+
G.nodes[2]["community"] = 0
|
257 |
+
G.nodes[3]["community"] = 0
|
258 |
+
G.nodes[4]["community"] = 1
|
259 |
+
self.test(G, [(0, 1)], [(0, 1, 5)])
|
260 |
+
|
261 |
+
def test_P3(self):
|
262 |
+
G = nx.path_graph(3)
|
263 |
+
G.nodes[0]["community"] = 0
|
264 |
+
G.nodes[1]["community"] = 1
|
265 |
+
G.nodes[2]["community"] = 0
|
266 |
+
self.test(G, [(0, 2)], [(0, 2, 1)])
|
267 |
+
|
268 |
+
def test_S4(self):
|
269 |
+
G = nx.star_graph(4)
|
270 |
+
G.nodes[0]["community"] = 1
|
271 |
+
G.nodes[1]["community"] = 1
|
272 |
+
G.nodes[2]["community"] = 1
|
273 |
+
G.nodes[3]["community"] = 0
|
274 |
+
G.nodes[4]["community"] = 0
|
275 |
+
self.test(G, [(1, 2)], [(1, 2, 2)])
|
276 |
+
|
277 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
278 |
+
def test_notimplemented(self, graph_type):
|
279 |
+
G = graph_type([(0, 1), (1, 2)])
|
280 |
+
G.add_nodes_from([0, 1, 2], community=0)
|
281 |
+
assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)])
|
282 |
+
|
283 |
+
def test_node_not_found(self):
|
284 |
+
G = nx.Graph()
|
285 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
286 |
+
G.nodes[0]["community"] = 0
|
287 |
+
G.nodes[1]["community"] = 1
|
288 |
+
G.nodes[2]["community"] = 0
|
289 |
+
G.nodes[3]["community"] = 0
|
290 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
291 |
+
|
292 |
+
def test_no_common_neighbor(self):
|
293 |
+
G = nx.Graph()
|
294 |
+
G.add_nodes_from([0, 1])
|
295 |
+
G.nodes[0]["community"] = 0
|
296 |
+
G.nodes[1]["community"] = 0
|
297 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
298 |
+
|
299 |
+
def test_equal_nodes(self):
|
300 |
+
G = nx.complete_graph(3)
|
301 |
+
G.nodes[0]["community"] = 0
|
302 |
+
G.nodes[1]["community"] = 0
|
303 |
+
G.nodes[2]["community"] = 0
|
304 |
+
self.test(G, [(0, 0)], [(0, 0, 4)])
|
305 |
+
|
306 |
+
def test_different_community(self):
|
307 |
+
G = nx.Graph()
|
308 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
309 |
+
G.nodes[0]["community"] = 0
|
310 |
+
G.nodes[1]["community"] = 0
|
311 |
+
G.nodes[2]["community"] = 0
|
312 |
+
G.nodes[3]["community"] = 1
|
313 |
+
self.test(G, [(0, 3)], [(0, 3, 2)])
|
314 |
+
|
315 |
+
def test_no_community_information(self):
|
316 |
+
G = nx.complete_graph(5)
|
317 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 1)]))
|
318 |
+
|
319 |
+
def test_insufficient_community_information(self):
|
320 |
+
G = nx.Graph()
|
321 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
322 |
+
G.nodes[0]["community"] = 0
|
323 |
+
G.nodes[1]["community"] = 0
|
324 |
+
G.nodes[3]["community"] = 0
|
325 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 3)]))
|
326 |
+
|
327 |
+
def test_sufficient_community_information(self):
|
328 |
+
G = nx.Graph()
|
329 |
+
G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
|
330 |
+
G.nodes[1]["community"] = 0
|
331 |
+
G.nodes[2]["community"] = 0
|
332 |
+
G.nodes[3]["community"] = 0
|
333 |
+
G.nodes[4]["community"] = 0
|
334 |
+
self.test(G, [(1, 4)], [(1, 4, 4)])
|
335 |
+
|
336 |
+
def test_custom_community_attribute_name(self):
|
337 |
+
G = nx.Graph()
|
338 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
339 |
+
G.nodes[0]["cmty"] = 0
|
340 |
+
G.nodes[1]["cmty"] = 0
|
341 |
+
G.nodes[2]["cmty"] = 0
|
342 |
+
G.nodes[3]["cmty"] = 1
|
343 |
+
self.test(G, [(0, 3)], [(0, 3, 2)], community="cmty")
|
344 |
+
|
345 |
+
def test_all_nonexistent_edges(self):
|
346 |
+
G = nx.Graph()
|
347 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
348 |
+
G.nodes[0]["community"] = 0
|
349 |
+
G.nodes[1]["community"] = 1
|
350 |
+
G.nodes[2]["community"] = 0
|
351 |
+
G.nodes[3]["community"] = 0
|
352 |
+
self.test(G, None, [(0, 3, 2), (1, 2, 1), (1, 3, 0)])
|
353 |
+
|
354 |
+
|
355 |
+
class TestRAIndexSoundarajanHopcroft:
|
356 |
+
@classmethod
|
357 |
+
def setup_class(cls):
|
358 |
+
cls.func = staticmethod(nx.ra_index_soundarajan_hopcroft)
|
359 |
+
cls.test = partial(_test_func, predict_func=cls.func, community="community")
|
360 |
+
|
361 |
+
def test_K5(self):
|
362 |
+
G = nx.complete_graph(5)
|
363 |
+
G.nodes[0]["community"] = 0
|
364 |
+
G.nodes[1]["community"] = 0
|
365 |
+
G.nodes[2]["community"] = 0
|
366 |
+
G.nodes[3]["community"] = 0
|
367 |
+
G.nodes[4]["community"] = 1
|
368 |
+
self.test(G, [(0, 1)], [(0, 1, 0.5)])
|
369 |
+
|
370 |
+
def test_P3(self):
|
371 |
+
G = nx.path_graph(3)
|
372 |
+
G.nodes[0]["community"] = 0
|
373 |
+
G.nodes[1]["community"] = 1
|
374 |
+
G.nodes[2]["community"] = 0
|
375 |
+
self.test(G, [(0, 2)], [(0, 2, 0)])
|
376 |
+
|
377 |
+
def test_S4(self):
|
378 |
+
G = nx.star_graph(4)
|
379 |
+
G.nodes[0]["community"] = 1
|
380 |
+
G.nodes[1]["community"] = 1
|
381 |
+
G.nodes[2]["community"] = 1
|
382 |
+
G.nodes[3]["community"] = 0
|
383 |
+
G.nodes[4]["community"] = 0
|
384 |
+
self.test(G, [(1, 2)], [(1, 2, 0.25)])
|
385 |
+
|
386 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
387 |
+
def test_notimplemented(self, graph_type):
|
388 |
+
G = graph_type([(0, 1), (1, 2)])
|
389 |
+
G.add_nodes_from([0, 1, 2], community=0)
|
390 |
+
assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)])
|
391 |
+
|
392 |
+
def test_node_not_found(self):
|
393 |
+
G = nx.Graph()
|
394 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
395 |
+
G.nodes[0]["community"] = 0
|
396 |
+
G.nodes[1]["community"] = 1
|
397 |
+
G.nodes[2]["community"] = 0
|
398 |
+
G.nodes[3]["community"] = 0
|
399 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
400 |
+
|
401 |
+
def test_no_common_neighbor(self):
|
402 |
+
G = nx.Graph()
|
403 |
+
G.add_nodes_from([0, 1])
|
404 |
+
G.nodes[0]["community"] = 0
|
405 |
+
G.nodes[1]["community"] = 0
|
406 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
407 |
+
|
408 |
+
def test_equal_nodes(self):
|
409 |
+
G = nx.complete_graph(3)
|
410 |
+
G.nodes[0]["community"] = 0
|
411 |
+
G.nodes[1]["community"] = 0
|
412 |
+
G.nodes[2]["community"] = 0
|
413 |
+
self.test(G, [(0, 0)], [(0, 0, 1)])
|
414 |
+
|
415 |
+
def test_different_community(self):
|
416 |
+
G = nx.Graph()
|
417 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
418 |
+
G.nodes[0]["community"] = 0
|
419 |
+
G.nodes[1]["community"] = 0
|
420 |
+
G.nodes[2]["community"] = 0
|
421 |
+
G.nodes[3]["community"] = 1
|
422 |
+
self.test(G, [(0, 3)], [(0, 3, 0)])
|
423 |
+
|
424 |
+
def test_no_community_information(self):
|
425 |
+
G = nx.complete_graph(5)
|
426 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 1)]))
|
427 |
+
|
428 |
+
def test_insufficient_community_information(self):
|
429 |
+
G = nx.Graph()
|
430 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
431 |
+
G.nodes[0]["community"] = 0
|
432 |
+
G.nodes[1]["community"] = 0
|
433 |
+
G.nodes[3]["community"] = 0
|
434 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 3)]))
|
435 |
+
|
436 |
+
def test_sufficient_community_information(self):
|
437 |
+
G = nx.Graph()
|
438 |
+
G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
|
439 |
+
G.nodes[1]["community"] = 0
|
440 |
+
G.nodes[2]["community"] = 0
|
441 |
+
G.nodes[3]["community"] = 0
|
442 |
+
G.nodes[4]["community"] = 0
|
443 |
+
self.test(G, [(1, 4)], [(1, 4, 1)])
|
444 |
+
|
445 |
+
def test_custom_community_attribute_name(self):
|
446 |
+
G = nx.Graph()
|
447 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
448 |
+
G.nodes[0]["cmty"] = 0
|
449 |
+
G.nodes[1]["cmty"] = 0
|
450 |
+
G.nodes[2]["cmty"] = 0
|
451 |
+
G.nodes[3]["cmty"] = 1
|
452 |
+
self.test(G, [(0, 3)], [(0, 3, 0)], community="cmty")
|
453 |
+
|
454 |
+
def test_all_nonexistent_edges(self):
|
455 |
+
G = nx.Graph()
|
456 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
457 |
+
G.nodes[0]["community"] = 0
|
458 |
+
G.nodes[1]["community"] = 1
|
459 |
+
G.nodes[2]["community"] = 0
|
460 |
+
G.nodes[3]["community"] = 0
|
461 |
+
self.test(G, None, [(0, 3, 0.5), (1, 2, 0), (1, 3, 0)])
|
462 |
+
|
463 |
+
|
464 |
+
class TestWithinInterCluster:
|
465 |
+
@classmethod
|
466 |
+
def setup_class(cls):
|
467 |
+
cls.delta = 0.001
|
468 |
+
cls.func = staticmethod(nx.within_inter_cluster)
|
469 |
+
cls.test = partial(
|
470 |
+
_test_func, predict_func=cls.func, delta=cls.delta, community="community"
|
471 |
+
)
|
472 |
+
|
473 |
+
def test_K5(self):
|
474 |
+
G = nx.complete_graph(5)
|
475 |
+
G.nodes[0]["community"] = 0
|
476 |
+
G.nodes[1]["community"] = 0
|
477 |
+
G.nodes[2]["community"] = 0
|
478 |
+
G.nodes[3]["community"] = 0
|
479 |
+
G.nodes[4]["community"] = 1
|
480 |
+
self.test(G, [(0, 1)], [(0, 1, 2 / (1 + self.delta))])
|
481 |
+
|
482 |
+
def test_P3(self):
|
483 |
+
G = nx.path_graph(3)
|
484 |
+
G.nodes[0]["community"] = 0
|
485 |
+
G.nodes[1]["community"] = 1
|
486 |
+
G.nodes[2]["community"] = 0
|
487 |
+
self.test(G, [(0, 2)], [(0, 2, 0)])
|
488 |
+
|
489 |
+
def test_S4(self):
|
490 |
+
G = nx.star_graph(4)
|
491 |
+
G.nodes[0]["community"] = 1
|
492 |
+
G.nodes[1]["community"] = 1
|
493 |
+
G.nodes[2]["community"] = 1
|
494 |
+
G.nodes[3]["community"] = 0
|
495 |
+
G.nodes[4]["community"] = 0
|
496 |
+
self.test(G, [(1, 2)], [(1, 2, 1 / self.delta)])
|
497 |
+
|
498 |
+
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
|
499 |
+
def test_notimplemented(self, graph_type):
|
500 |
+
G = graph_type([(0, 1), (1, 2)])
|
501 |
+
G.add_nodes_from([0, 1, 2], community=0)
|
502 |
+
assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)])
|
503 |
+
|
504 |
+
def test_node_not_found(self):
|
505 |
+
G = nx.Graph()
|
506 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
507 |
+
G.nodes[0]["community"] = 0
|
508 |
+
G.nodes[1]["community"] = 1
|
509 |
+
G.nodes[2]["community"] = 0
|
510 |
+
G.nodes[3]["community"] = 0
|
511 |
+
assert pytest.raises(nx.NodeNotFound, self.func, G, [(0, 4)])
|
512 |
+
|
513 |
+
def test_no_common_neighbor(self):
|
514 |
+
G = nx.Graph()
|
515 |
+
G.add_nodes_from([0, 1])
|
516 |
+
G.nodes[0]["community"] = 0
|
517 |
+
G.nodes[1]["community"] = 0
|
518 |
+
self.test(G, [(0, 1)], [(0, 1, 0)])
|
519 |
+
|
520 |
+
def test_equal_nodes(self):
|
521 |
+
G = nx.complete_graph(3)
|
522 |
+
G.nodes[0]["community"] = 0
|
523 |
+
G.nodes[1]["community"] = 0
|
524 |
+
G.nodes[2]["community"] = 0
|
525 |
+
self.test(G, [(0, 0)], [(0, 0, 2 / self.delta)])
|
526 |
+
|
527 |
+
def test_different_community(self):
|
528 |
+
G = nx.Graph()
|
529 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
530 |
+
G.nodes[0]["community"] = 0
|
531 |
+
G.nodes[1]["community"] = 0
|
532 |
+
G.nodes[2]["community"] = 0
|
533 |
+
G.nodes[3]["community"] = 1
|
534 |
+
self.test(G, [(0, 3)], [(0, 3, 0)])
|
535 |
+
|
536 |
+
def test_no_inter_cluster_common_neighbor(self):
|
537 |
+
G = nx.complete_graph(4)
|
538 |
+
G.nodes[0]["community"] = 0
|
539 |
+
G.nodes[1]["community"] = 0
|
540 |
+
G.nodes[2]["community"] = 0
|
541 |
+
G.nodes[3]["community"] = 0
|
542 |
+
self.test(G, [(0, 3)], [(0, 3, 2 / self.delta)])
|
543 |
+
|
544 |
+
def test_no_community_information(self):
|
545 |
+
G = nx.complete_graph(5)
|
546 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 1)]))
|
547 |
+
|
548 |
+
def test_insufficient_community_information(self):
|
549 |
+
G = nx.Graph()
|
550 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
551 |
+
G.nodes[0]["community"] = 0
|
552 |
+
G.nodes[1]["community"] = 0
|
553 |
+
G.nodes[3]["community"] = 0
|
554 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, list, self.func(G, [(0, 3)]))
|
555 |
+
|
556 |
+
def test_sufficient_community_information(self):
|
557 |
+
G = nx.Graph()
|
558 |
+
G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
|
559 |
+
G.nodes[1]["community"] = 0
|
560 |
+
G.nodes[2]["community"] = 0
|
561 |
+
G.nodes[3]["community"] = 0
|
562 |
+
G.nodes[4]["community"] = 0
|
563 |
+
self.test(G, [(1, 4)], [(1, 4, 2 / self.delta)])
|
564 |
+
|
565 |
+
def test_invalid_delta(self):
|
566 |
+
G = nx.complete_graph(3)
|
567 |
+
G.add_nodes_from([0, 1, 2], community=0)
|
568 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, self.func, G, [(0, 1)], 0)
|
569 |
+
assert pytest.raises(nx.NetworkXAlgorithmError, self.func, G, [(0, 1)], -0.5)
|
570 |
+
|
571 |
+
def test_custom_community_attribute_name(self):
|
572 |
+
G = nx.complete_graph(4)
|
573 |
+
G.nodes[0]["cmty"] = 0
|
574 |
+
G.nodes[1]["cmty"] = 0
|
575 |
+
G.nodes[2]["cmty"] = 0
|
576 |
+
G.nodes[3]["cmty"] = 0
|
577 |
+
self.test(G, [(0, 3)], [(0, 3, 2 / self.delta)], community="cmty")
|
578 |
+
|
579 |
+
def test_all_nonexistent_edges(self):
|
580 |
+
G = nx.Graph()
|
581 |
+
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
|
582 |
+
G.nodes[0]["community"] = 0
|
583 |
+
G.nodes[1]["community"] = 1
|
584 |
+
G.nodes[2]["community"] = 0
|
585 |
+
G.nodes[3]["community"] = 0
|
586 |
+
self.test(G, None, [(0, 3, 1 / self.delta), (1, 2, 0), (1, 3, 0)])
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_matching.py
ADDED
@@ -0,0 +1,605 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from itertools import permutations
|
3 |
+
|
4 |
+
from pytest import raises
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
from networkx.algorithms.matching import matching_dict_to_set
|
8 |
+
from networkx.utils import edges_equal
|
9 |
+
|
10 |
+
|
11 |
+
class TestMaxWeightMatching:
|
12 |
+
"""Unit tests for the
|
13 |
+
:func:`~networkx.algorithms.matching.max_weight_matching` function.
|
14 |
+
|
15 |
+
"""
|
16 |
+
|
17 |
+
def test_trivial1(self):
|
18 |
+
"""Empty graph"""
|
19 |
+
G = nx.Graph()
|
20 |
+
assert nx.max_weight_matching(G) == set()
|
21 |
+
assert nx.min_weight_matching(G) == set()
|
22 |
+
|
23 |
+
def test_selfloop(self):
|
24 |
+
G = nx.Graph()
|
25 |
+
G.add_edge(0, 0, weight=100)
|
26 |
+
assert nx.max_weight_matching(G) == set()
|
27 |
+
assert nx.min_weight_matching(G) == set()
|
28 |
+
|
29 |
+
def test_single_edge(self):
|
30 |
+
G = nx.Graph()
|
31 |
+
G.add_edge(0, 1)
|
32 |
+
assert edges_equal(
|
33 |
+
nx.max_weight_matching(G), matching_dict_to_set({0: 1, 1: 0})
|
34 |
+
)
|
35 |
+
assert edges_equal(
|
36 |
+
nx.min_weight_matching(G), matching_dict_to_set({0: 1, 1: 0})
|
37 |
+
)
|
38 |
+
|
39 |
+
def test_two_path(self):
|
40 |
+
G = nx.Graph()
|
41 |
+
G.add_edge("one", "two", weight=10)
|
42 |
+
G.add_edge("two", "three", weight=11)
|
43 |
+
assert edges_equal(
|
44 |
+
nx.max_weight_matching(G),
|
45 |
+
matching_dict_to_set({"three": "two", "two": "three"}),
|
46 |
+
)
|
47 |
+
assert edges_equal(
|
48 |
+
nx.min_weight_matching(G),
|
49 |
+
matching_dict_to_set({"one": "two", "two": "one"}),
|
50 |
+
)
|
51 |
+
|
52 |
+
def test_path(self):
|
53 |
+
G = nx.Graph()
|
54 |
+
G.add_edge(1, 2, weight=5)
|
55 |
+
G.add_edge(2, 3, weight=11)
|
56 |
+
G.add_edge(3, 4, weight=5)
|
57 |
+
assert edges_equal(
|
58 |
+
nx.max_weight_matching(G), matching_dict_to_set({2: 3, 3: 2})
|
59 |
+
)
|
60 |
+
assert edges_equal(
|
61 |
+
nx.max_weight_matching(G, 1), matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3})
|
62 |
+
)
|
63 |
+
assert edges_equal(
|
64 |
+
nx.min_weight_matching(G), matching_dict_to_set({1: 2, 3: 4})
|
65 |
+
)
|
66 |
+
assert edges_equal(
|
67 |
+
nx.min_weight_matching(G, 1), matching_dict_to_set({1: 2, 3: 4})
|
68 |
+
)
|
69 |
+
|
70 |
+
def test_square(self):
|
71 |
+
G = nx.Graph()
|
72 |
+
G.add_edge(1, 4, weight=2)
|
73 |
+
G.add_edge(2, 3, weight=2)
|
74 |
+
G.add_edge(1, 2, weight=1)
|
75 |
+
G.add_edge(3, 4, weight=4)
|
76 |
+
assert edges_equal(
|
77 |
+
nx.max_weight_matching(G), matching_dict_to_set({1: 2, 3: 4})
|
78 |
+
)
|
79 |
+
assert edges_equal(
|
80 |
+
nx.min_weight_matching(G), matching_dict_to_set({1: 4, 2: 3})
|
81 |
+
)
|
82 |
+
|
83 |
+
def test_edge_attribute_name(self):
|
84 |
+
G = nx.Graph()
|
85 |
+
G.add_edge("one", "two", weight=10, abcd=11)
|
86 |
+
G.add_edge("two", "three", weight=11, abcd=10)
|
87 |
+
assert edges_equal(
|
88 |
+
nx.max_weight_matching(G, weight="abcd"),
|
89 |
+
matching_dict_to_set({"one": "two", "two": "one"}),
|
90 |
+
)
|
91 |
+
assert edges_equal(
|
92 |
+
nx.min_weight_matching(G, weight="abcd"),
|
93 |
+
matching_dict_to_set({"three": "two"}),
|
94 |
+
)
|
95 |
+
|
96 |
+
def test_floating_point_weights(self):
|
97 |
+
G = nx.Graph()
|
98 |
+
G.add_edge(1, 2, weight=math.pi)
|
99 |
+
G.add_edge(2, 3, weight=math.exp(1))
|
100 |
+
G.add_edge(1, 3, weight=3.0)
|
101 |
+
G.add_edge(1, 4, weight=math.sqrt(2.0))
|
102 |
+
assert edges_equal(
|
103 |
+
nx.max_weight_matching(G), matching_dict_to_set({1: 4, 2: 3, 3: 2, 4: 1})
|
104 |
+
)
|
105 |
+
assert edges_equal(
|
106 |
+
nx.min_weight_matching(G), matching_dict_to_set({1: 4, 2: 3, 3: 2, 4: 1})
|
107 |
+
)
|
108 |
+
|
109 |
+
def test_negative_weights(self):
|
110 |
+
G = nx.Graph()
|
111 |
+
G.add_edge(1, 2, weight=2)
|
112 |
+
G.add_edge(1, 3, weight=-2)
|
113 |
+
G.add_edge(2, 3, weight=1)
|
114 |
+
G.add_edge(2, 4, weight=-1)
|
115 |
+
G.add_edge(3, 4, weight=-6)
|
116 |
+
assert edges_equal(
|
117 |
+
nx.max_weight_matching(G), matching_dict_to_set({1: 2, 2: 1})
|
118 |
+
)
|
119 |
+
assert edges_equal(
|
120 |
+
nx.max_weight_matching(G, maxcardinality=True),
|
121 |
+
matching_dict_to_set({1: 3, 2: 4, 3: 1, 4: 2}),
|
122 |
+
)
|
123 |
+
assert edges_equal(
|
124 |
+
nx.min_weight_matching(G), matching_dict_to_set({1: 2, 3: 4})
|
125 |
+
)
|
126 |
+
|
127 |
+
def test_s_blossom(self):
|
128 |
+
"""Create S-blossom and use it for augmentation:"""
|
129 |
+
G = nx.Graph()
|
130 |
+
G.add_weighted_edges_from([(1, 2, 8), (1, 3, 9), (2, 3, 10), (3, 4, 7)])
|
131 |
+
answer = matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3})
|
132 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
133 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
134 |
+
|
135 |
+
G.add_weighted_edges_from([(1, 6, 5), (4, 5, 6)])
|
136 |
+
answer = matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1})
|
137 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
138 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
139 |
+
|
140 |
+
def test_s_t_blossom(self):
|
141 |
+
"""Create S-blossom, relabel as T-blossom, use for augmentation:"""
|
142 |
+
G = nx.Graph()
|
143 |
+
G.add_weighted_edges_from(
|
144 |
+
[(1, 2, 9), (1, 3, 8), (2, 3, 10), (1, 4, 5), (4, 5, 4), (1, 6, 3)]
|
145 |
+
)
|
146 |
+
answer = matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1})
|
147 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
148 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
149 |
+
|
150 |
+
G.add_edge(4, 5, weight=3)
|
151 |
+
G.add_edge(1, 6, weight=4)
|
152 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
153 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
154 |
+
|
155 |
+
G.remove_edge(1, 6)
|
156 |
+
G.add_edge(3, 6, weight=4)
|
157 |
+
answer = matching_dict_to_set({1: 2, 2: 1, 3: 6, 4: 5, 5: 4, 6: 3})
|
158 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
159 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
160 |
+
|
161 |
+
def test_nested_s_blossom(self):
|
162 |
+
"""Create nested S-blossom, use for augmentation:"""
|
163 |
+
|
164 |
+
G = nx.Graph()
|
165 |
+
G.add_weighted_edges_from(
|
166 |
+
[
|
167 |
+
(1, 2, 9),
|
168 |
+
(1, 3, 9),
|
169 |
+
(2, 3, 10),
|
170 |
+
(2, 4, 8),
|
171 |
+
(3, 5, 8),
|
172 |
+
(4, 5, 10),
|
173 |
+
(5, 6, 6),
|
174 |
+
]
|
175 |
+
)
|
176 |
+
dict_format = {1: 3, 2: 4, 3: 1, 4: 2, 5: 6, 6: 5}
|
177 |
+
expected = {frozenset(e) for e in matching_dict_to_set(dict_format)}
|
178 |
+
answer = {frozenset(e) for e in nx.max_weight_matching(G)}
|
179 |
+
assert answer == expected
|
180 |
+
answer = {frozenset(e) for e in nx.min_weight_matching(G)}
|
181 |
+
assert answer == expected
|
182 |
+
|
183 |
+
def test_nested_s_blossom_relabel(self):
|
184 |
+
"""Create S-blossom, relabel as S, include in nested S-blossom:"""
|
185 |
+
G = nx.Graph()
|
186 |
+
G.add_weighted_edges_from(
|
187 |
+
[
|
188 |
+
(1, 2, 10),
|
189 |
+
(1, 7, 10),
|
190 |
+
(2, 3, 12),
|
191 |
+
(3, 4, 20),
|
192 |
+
(3, 5, 20),
|
193 |
+
(4, 5, 25),
|
194 |
+
(5, 6, 10),
|
195 |
+
(6, 7, 10),
|
196 |
+
(7, 8, 8),
|
197 |
+
]
|
198 |
+
)
|
199 |
+
answer = matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3, 5: 6, 6: 5, 7: 8, 8: 7})
|
200 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
201 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
202 |
+
|
203 |
+
def test_nested_s_blossom_expand(self):
|
204 |
+
"""Create nested S-blossom, augment, expand recursively:"""
|
205 |
+
G = nx.Graph()
|
206 |
+
G.add_weighted_edges_from(
|
207 |
+
[
|
208 |
+
(1, 2, 8),
|
209 |
+
(1, 3, 8),
|
210 |
+
(2, 3, 10),
|
211 |
+
(2, 4, 12),
|
212 |
+
(3, 5, 12),
|
213 |
+
(4, 5, 14),
|
214 |
+
(4, 6, 12),
|
215 |
+
(5, 7, 12),
|
216 |
+
(6, 7, 14),
|
217 |
+
(7, 8, 12),
|
218 |
+
]
|
219 |
+
)
|
220 |
+
answer = matching_dict_to_set({1: 2, 2: 1, 3: 5, 4: 6, 5: 3, 6: 4, 7: 8, 8: 7})
|
221 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
222 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
223 |
+
|
224 |
+
def test_s_blossom_relabel_expand(self):
|
225 |
+
"""Create S-blossom, relabel as T, expand:"""
|
226 |
+
G = nx.Graph()
|
227 |
+
G.add_weighted_edges_from(
|
228 |
+
[
|
229 |
+
(1, 2, 23),
|
230 |
+
(1, 5, 22),
|
231 |
+
(1, 6, 15),
|
232 |
+
(2, 3, 25),
|
233 |
+
(3, 4, 22),
|
234 |
+
(4, 5, 25),
|
235 |
+
(4, 8, 14),
|
236 |
+
(5, 7, 13),
|
237 |
+
]
|
238 |
+
)
|
239 |
+
answer = matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4})
|
240 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
241 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
242 |
+
|
243 |
+
def test_nested_s_blossom_relabel_expand(self):
|
244 |
+
"""Create nested S-blossom, relabel as T, expand:"""
|
245 |
+
G = nx.Graph()
|
246 |
+
G.add_weighted_edges_from(
|
247 |
+
[
|
248 |
+
(1, 2, 19),
|
249 |
+
(1, 3, 20),
|
250 |
+
(1, 8, 8),
|
251 |
+
(2, 3, 25),
|
252 |
+
(2, 4, 18),
|
253 |
+
(3, 5, 18),
|
254 |
+
(4, 5, 13),
|
255 |
+
(4, 7, 7),
|
256 |
+
(5, 6, 7),
|
257 |
+
]
|
258 |
+
)
|
259 |
+
answer = matching_dict_to_set({1: 8, 2: 3, 3: 2, 4: 7, 5: 6, 6: 5, 7: 4, 8: 1})
|
260 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
261 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
262 |
+
|
263 |
+
def test_nasty_blossom1(self):
|
264 |
+
"""Create blossom, relabel as T in more than one way, expand,
|
265 |
+
augment:
|
266 |
+
"""
|
267 |
+
G = nx.Graph()
|
268 |
+
G.add_weighted_edges_from(
|
269 |
+
[
|
270 |
+
(1, 2, 45),
|
271 |
+
(1, 5, 45),
|
272 |
+
(2, 3, 50),
|
273 |
+
(3, 4, 45),
|
274 |
+
(4, 5, 50),
|
275 |
+
(1, 6, 30),
|
276 |
+
(3, 9, 35),
|
277 |
+
(4, 8, 35),
|
278 |
+
(5, 7, 26),
|
279 |
+
(9, 10, 5),
|
280 |
+
]
|
281 |
+
)
|
282 |
+
ansdict = {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4, 9: 10, 10: 9}
|
283 |
+
answer = matching_dict_to_set(ansdict)
|
284 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
285 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
286 |
+
|
287 |
+
def test_nasty_blossom2(self):
|
288 |
+
"""Again but slightly different:"""
|
289 |
+
G = nx.Graph()
|
290 |
+
G.add_weighted_edges_from(
|
291 |
+
[
|
292 |
+
(1, 2, 45),
|
293 |
+
(1, 5, 45),
|
294 |
+
(2, 3, 50),
|
295 |
+
(3, 4, 45),
|
296 |
+
(4, 5, 50),
|
297 |
+
(1, 6, 30),
|
298 |
+
(3, 9, 35),
|
299 |
+
(4, 8, 26),
|
300 |
+
(5, 7, 40),
|
301 |
+
(9, 10, 5),
|
302 |
+
]
|
303 |
+
)
|
304 |
+
ans = {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4, 9: 10, 10: 9}
|
305 |
+
answer = matching_dict_to_set(ans)
|
306 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
307 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
308 |
+
|
309 |
+
def test_nasty_blossom_least_slack(self):
|
310 |
+
"""Create blossom, relabel as T, expand such that a new
|
311 |
+
least-slack S-to-free dge is produced, augment:
|
312 |
+
"""
|
313 |
+
G = nx.Graph()
|
314 |
+
G.add_weighted_edges_from(
|
315 |
+
[
|
316 |
+
(1, 2, 45),
|
317 |
+
(1, 5, 45),
|
318 |
+
(2, 3, 50),
|
319 |
+
(3, 4, 45),
|
320 |
+
(4, 5, 50),
|
321 |
+
(1, 6, 30),
|
322 |
+
(3, 9, 35),
|
323 |
+
(4, 8, 28),
|
324 |
+
(5, 7, 26),
|
325 |
+
(9, 10, 5),
|
326 |
+
]
|
327 |
+
)
|
328 |
+
ans = {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4, 9: 10, 10: 9}
|
329 |
+
answer = matching_dict_to_set(ans)
|
330 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
331 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
332 |
+
|
333 |
+
def test_nasty_blossom_augmenting(self):
|
334 |
+
"""Create nested blossom, relabel as T in more than one way"""
|
335 |
+
# expand outer blossom such that inner blossom ends up on an
|
336 |
+
# augmenting path:
|
337 |
+
G = nx.Graph()
|
338 |
+
G.add_weighted_edges_from(
|
339 |
+
[
|
340 |
+
(1, 2, 45),
|
341 |
+
(1, 7, 45),
|
342 |
+
(2, 3, 50),
|
343 |
+
(3, 4, 45),
|
344 |
+
(4, 5, 95),
|
345 |
+
(4, 6, 94),
|
346 |
+
(5, 6, 94),
|
347 |
+
(6, 7, 50),
|
348 |
+
(1, 8, 30),
|
349 |
+
(3, 11, 35),
|
350 |
+
(5, 9, 36),
|
351 |
+
(7, 10, 26),
|
352 |
+
(11, 12, 5),
|
353 |
+
]
|
354 |
+
)
|
355 |
+
ans = {
|
356 |
+
1: 8,
|
357 |
+
2: 3,
|
358 |
+
3: 2,
|
359 |
+
4: 6,
|
360 |
+
5: 9,
|
361 |
+
6: 4,
|
362 |
+
7: 10,
|
363 |
+
8: 1,
|
364 |
+
9: 5,
|
365 |
+
10: 7,
|
366 |
+
11: 12,
|
367 |
+
12: 11,
|
368 |
+
}
|
369 |
+
answer = matching_dict_to_set(ans)
|
370 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
371 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
372 |
+
|
373 |
+
def test_nasty_blossom_expand_recursively(self):
|
374 |
+
"""Create nested S-blossom, relabel as S, expand recursively:"""
|
375 |
+
G = nx.Graph()
|
376 |
+
G.add_weighted_edges_from(
|
377 |
+
[
|
378 |
+
(1, 2, 40),
|
379 |
+
(1, 3, 40),
|
380 |
+
(2, 3, 60),
|
381 |
+
(2, 4, 55),
|
382 |
+
(3, 5, 55),
|
383 |
+
(4, 5, 50),
|
384 |
+
(1, 8, 15),
|
385 |
+
(5, 7, 30),
|
386 |
+
(7, 6, 10),
|
387 |
+
(8, 10, 10),
|
388 |
+
(4, 9, 30),
|
389 |
+
]
|
390 |
+
)
|
391 |
+
ans = {1: 2, 2: 1, 3: 5, 4: 9, 5: 3, 6: 7, 7: 6, 8: 10, 9: 4, 10: 8}
|
392 |
+
answer = matching_dict_to_set(ans)
|
393 |
+
assert edges_equal(nx.max_weight_matching(G), answer)
|
394 |
+
assert edges_equal(nx.min_weight_matching(G), answer)
|
395 |
+
|
396 |
+
def test_wrong_graph_type(self):
|
397 |
+
error = nx.NetworkXNotImplemented
|
398 |
+
raises(error, nx.max_weight_matching, nx.MultiGraph())
|
399 |
+
raises(error, nx.max_weight_matching, nx.MultiDiGraph())
|
400 |
+
raises(error, nx.max_weight_matching, nx.DiGraph())
|
401 |
+
raises(error, nx.min_weight_matching, nx.DiGraph())
|
402 |
+
|
403 |
+
|
404 |
+
class TestIsMatching:
|
405 |
+
"""Unit tests for the
|
406 |
+
:func:`~networkx.algorithms.matching.is_matching` function.
|
407 |
+
|
408 |
+
"""
|
409 |
+
|
410 |
+
def test_dict(self):
|
411 |
+
G = nx.path_graph(4)
|
412 |
+
assert nx.is_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
|
413 |
+
|
414 |
+
def test_empty_matching(self):
|
415 |
+
G = nx.path_graph(4)
|
416 |
+
assert nx.is_matching(G, set())
|
417 |
+
|
418 |
+
def test_single_edge(self):
|
419 |
+
G = nx.path_graph(4)
|
420 |
+
assert nx.is_matching(G, {(1, 2)})
|
421 |
+
|
422 |
+
def test_edge_order(self):
|
423 |
+
G = nx.path_graph(4)
|
424 |
+
assert nx.is_matching(G, {(0, 1), (2, 3)})
|
425 |
+
assert nx.is_matching(G, {(1, 0), (2, 3)})
|
426 |
+
assert nx.is_matching(G, {(0, 1), (3, 2)})
|
427 |
+
assert nx.is_matching(G, {(1, 0), (3, 2)})
|
428 |
+
|
429 |
+
def test_valid_matching(self):
|
430 |
+
G = nx.path_graph(4)
|
431 |
+
assert nx.is_matching(G, {(0, 1), (2, 3)})
|
432 |
+
|
433 |
+
def test_invalid_input(self):
|
434 |
+
error = nx.NetworkXError
|
435 |
+
G = nx.path_graph(4)
|
436 |
+
# edge to node not in G
|
437 |
+
raises(error, nx.is_matching, G, {(0, 5), (2, 3)})
|
438 |
+
# edge not a 2-tuple
|
439 |
+
raises(error, nx.is_matching, G, {(0, 1, 2), (2, 3)})
|
440 |
+
raises(error, nx.is_matching, G, {(0,), (2, 3)})
|
441 |
+
|
442 |
+
def test_selfloops(self):
|
443 |
+
error = nx.NetworkXError
|
444 |
+
G = nx.path_graph(4)
|
445 |
+
# selfloop for node not in G
|
446 |
+
raises(error, nx.is_matching, G, {(5, 5), (2, 3)})
|
447 |
+
# selfloop edge not in G
|
448 |
+
assert not nx.is_matching(G, {(0, 0), (1, 2), (2, 3)})
|
449 |
+
# selfloop edge in G
|
450 |
+
G.add_edge(0, 0)
|
451 |
+
assert not nx.is_matching(G, {(0, 0), (1, 2)})
|
452 |
+
|
453 |
+
def test_invalid_matching(self):
|
454 |
+
G = nx.path_graph(4)
|
455 |
+
assert not nx.is_matching(G, {(0, 1), (1, 2), (2, 3)})
|
456 |
+
|
457 |
+
def test_invalid_edge(self):
|
458 |
+
G = nx.path_graph(4)
|
459 |
+
assert not nx.is_matching(G, {(0, 3), (1, 2)})
|
460 |
+
raises(nx.NetworkXError, nx.is_matching, G, {(0, 55)})
|
461 |
+
|
462 |
+
G = nx.DiGraph(G.edges)
|
463 |
+
assert nx.is_matching(G, {(0, 1)})
|
464 |
+
assert not nx.is_matching(G, {(1, 0)})
|
465 |
+
|
466 |
+
|
467 |
+
class TestIsMaximalMatching:
|
468 |
+
"""Unit tests for the
|
469 |
+
:func:`~networkx.algorithms.matching.is_maximal_matching` function.
|
470 |
+
|
471 |
+
"""
|
472 |
+
|
473 |
+
def test_dict(self):
|
474 |
+
G = nx.path_graph(4)
|
475 |
+
assert nx.is_maximal_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
|
476 |
+
|
477 |
+
def test_invalid_input(self):
|
478 |
+
error = nx.NetworkXError
|
479 |
+
G = nx.path_graph(4)
|
480 |
+
# edge to node not in G
|
481 |
+
raises(error, nx.is_maximal_matching, G, {(0, 5)})
|
482 |
+
raises(error, nx.is_maximal_matching, G, {(5, 0)})
|
483 |
+
# edge not a 2-tuple
|
484 |
+
raises(error, nx.is_maximal_matching, G, {(0, 1, 2), (2, 3)})
|
485 |
+
raises(error, nx.is_maximal_matching, G, {(0,), (2, 3)})
|
486 |
+
|
487 |
+
def test_valid(self):
|
488 |
+
G = nx.path_graph(4)
|
489 |
+
assert nx.is_maximal_matching(G, {(0, 1), (2, 3)})
|
490 |
+
|
491 |
+
def test_not_matching(self):
|
492 |
+
G = nx.path_graph(4)
|
493 |
+
assert not nx.is_maximal_matching(G, {(0, 1), (1, 2), (2, 3)})
|
494 |
+
assert not nx.is_maximal_matching(G, {(0, 3)})
|
495 |
+
G.add_edge(0, 0)
|
496 |
+
assert not nx.is_maximal_matching(G, {(0, 0)})
|
497 |
+
|
498 |
+
def test_not_maximal(self):
|
499 |
+
G = nx.path_graph(4)
|
500 |
+
assert not nx.is_maximal_matching(G, {(0, 1)})
|
501 |
+
|
502 |
+
|
503 |
+
class TestIsPerfectMatching:
|
504 |
+
"""Unit tests for the
|
505 |
+
:func:`~networkx.algorithms.matching.is_perfect_matching` function.
|
506 |
+
|
507 |
+
"""
|
508 |
+
|
509 |
+
def test_dict(self):
|
510 |
+
G = nx.path_graph(4)
|
511 |
+
assert nx.is_perfect_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
|
512 |
+
|
513 |
+
def test_valid(self):
|
514 |
+
G = nx.path_graph(4)
|
515 |
+
assert nx.is_perfect_matching(G, {(0, 1), (2, 3)})
|
516 |
+
|
517 |
+
def test_valid_not_path(self):
|
518 |
+
G = nx.cycle_graph(4)
|
519 |
+
G.add_edge(0, 4)
|
520 |
+
G.add_edge(1, 4)
|
521 |
+
G.add_edge(5, 2)
|
522 |
+
|
523 |
+
assert nx.is_perfect_matching(G, {(1, 4), (0, 3), (5, 2)})
|
524 |
+
|
525 |
+
def test_invalid_input(self):
|
526 |
+
error = nx.NetworkXError
|
527 |
+
G = nx.path_graph(4)
|
528 |
+
# edge to node not in G
|
529 |
+
raises(error, nx.is_perfect_matching, G, {(0, 5)})
|
530 |
+
raises(error, nx.is_perfect_matching, G, {(5, 0)})
|
531 |
+
# edge not a 2-tuple
|
532 |
+
raises(error, nx.is_perfect_matching, G, {(0, 1, 2), (2, 3)})
|
533 |
+
raises(error, nx.is_perfect_matching, G, {(0,), (2, 3)})
|
534 |
+
|
535 |
+
def test_selfloops(self):
|
536 |
+
error = nx.NetworkXError
|
537 |
+
G = nx.path_graph(4)
|
538 |
+
# selfloop for node not in G
|
539 |
+
raises(error, nx.is_perfect_matching, G, {(5, 5), (2, 3)})
|
540 |
+
# selfloop edge not in G
|
541 |
+
assert not nx.is_perfect_matching(G, {(0, 0), (1, 2), (2, 3)})
|
542 |
+
# selfloop edge in G
|
543 |
+
G.add_edge(0, 0)
|
544 |
+
assert not nx.is_perfect_matching(G, {(0, 0), (1, 2)})
|
545 |
+
|
546 |
+
def test_not_matching(self):
|
547 |
+
G = nx.path_graph(4)
|
548 |
+
assert not nx.is_perfect_matching(G, {(0, 3)})
|
549 |
+
assert not nx.is_perfect_matching(G, {(0, 1), (1, 2), (2, 3)})
|
550 |
+
|
551 |
+
def test_maximal_but_not_perfect(self):
|
552 |
+
G = nx.cycle_graph(4)
|
553 |
+
G.add_edge(0, 4)
|
554 |
+
G.add_edge(1, 4)
|
555 |
+
|
556 |
+
assert not nx.is_perfect_matching(G, {(1, 4), (0, 3)})
|
557 |
+
|
558 |
+
|
559 |
+
class TestMaximalMatching:
|
560 |
+
"""Unit tests for the
|
561 |
+
:func:`~networkx.algorithms.matching.maximal_matching`.
|
562 |
+
|
563 |
+
"""
|
564 |
+
|
565 |
+
def test_valid_matching(self):
|
566 |
+
edges = [(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (3, 6), (5, 6)]
|
567 |
+
G = nx.Graph(edges)
|
568 |
+
matching = nx.maximal_matching(G)
|
569 |
+
assert nx.is_maximal_matching(G, matching)
|
570 |
+
|
571 |
+
def test_single_edge_matching(self):
|
572 |
+
# In the star graph, any maximal matching has just one edge.
|
573 |
+
G = nx.star_graph(5)
|
574 |
+
matching = nx.maximal_matching(G)
|
575 |
+
assert 1 == len(matching)
|
576 |
+
assert nx.is_maximal_matching(G, matching)
|
577 |
+
|
578 |
+
def test_self_loops(self):
|
579 |
+
# Create the path graph with two self-loops.
|
580 |
+
G = nx.path_graph(3)
|
581 |
+
G.add_edges_from([(0, 0), (1, 1)])
|
582 |
+
matching = nx.maximal_matching(G)
|
583 |
+
assert len(matching) == 1
|
584 |
+
# The matching should never include self-loops.
|
585 |
+
assert not any(u == v for u, v in matching)
|
586 |
+
assert nx.is_maximal_matching(G, matching)
|
587 |
+
|
588 |
+
def test_ordering(self):
|
589 |
+
"""Tests that a maximal matching is computed correctly
|
590 |
+
regardless of the order in which nodes are added to the graph.
|
591 |
+
|
592 |
+
"""
|
593 |
+
for nodes in permutations(range(3)):
|
594 |
+
G = nx.Graph()
|
595 |
+
G.add_nodes_from(nodes)
|
596 |
+
G.add_edges_from([(0, 1), (0, 2)])
|
597 |
+
matching = nx.maximal_matching(G)
|
598 |
+
assert len(matching) == 1
|
599 |
+
assert nx.is_maximal_matching(G, matching)
|
600 |
+
|
601 |
+
def test_wrong_graph_type(self):
|
602 |
+
error = nx.NetworkXNotImplemented
|
603 |
+
raises(error, nx.maximal_matching, nx.MultiGraph())
|
604 |
+
raises(error, nx.maximal_matching, nx.MultiDiGraph())
|
605 |
+
raises(error, nx.maximal_matching, nx.DiGraph())
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_max_weight_clique.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Maximum weight clique test suite.
|
2 |
+
|
3 |
+
"""
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
|
9 |
+
|
10 |
+
class TestMaximumWeightClique:
|
11 |
+
def test_basic_cases(self):
|
12 |
+
def check_basic_case(graph_func, expected_weight, weight_accessor):
|
13 |
+
graph = graph_func()
|
14 |
+
clique, weight = nx.algorithms.max_weight_clique(graph, weight_accessor)
|
15 |
+
assert verify_clique(
|
16 |
+
graph, clique, weight, expected_weight, weight_accessor
|
17 |
+
)
|
18 |
+
|
19 |
+
for graph_func, (expected_weight, expected_size) in TEST_CASES.items():
|
20 |
+
check_basic_case(graph_func, expected_weight, "weight")
|
21 |
+
check_basic_case(graph_func, expected_size, None)
|
22 |
+
|
23 |
+
def test_key_error(self):
|
24 |
+
graph = two_node_graph()
|
25 |
+
with pytest.raises(KeyError):
|
26 |
+
nx.algorithms.max_weight_clique(graph, "nonexistent-key")
|
27 |
+
|
28 |
+
def test_error_on_non_integer_weight(self):
|
29 |
+
graph = two_node_graph()
|
30 |
+
graph.nodes[2]["weight"] = 1.5
|
31 |
+
with pytest.raises(ValueError):
|
32 |
+
nx.algorithms.max_weight_clique(graph)
|
33 |
+
|
34 |
+
def test_unaffected_by_self_loops(self):
|
35 |
+
graph = two_node_graph()
|
36 |
+
graph.add_edge(1, 1)
|
37 |
+
graph.add_edge(2, 2)
|
38 |
+
clique, weight = nx.algorithms.max_weight_clique(graph, "weight")
|
39 |
+
assert verify_clique(graph, clique, weight, 30, "weight")
|
40 |
+
graph = three_node_independent_set()
|
41 |
+
graph.add_edge(1, 1)
|
42 |
+
clique, weight = nx.algorithms.max_weight_clique(graph, "weight")
|
43 |
+
assert verify_clique(graph, clique, weight, 20, "weight")
|
44 |
+
|
45 |
+
def test_30_node_prob(self):
|
46 |
+
G = nx.Graph()
|
47 |
+
G.add_nodes_from(range(1, 31))
|
48 |
+
for i in range(1, 31):
|
49 |
+
G.nodes[i]["weight"] = i + 1
|
50 |
+
# fmt: off
|
51 |
+
G.add_edges_from(
|
52 |
+
[
|
53 |
+
(1, 12), (1, 13), (1, 15), (1, 16), (1, 18), (1, 19), (1, 20),
|
54 |
+
(1, 23), (1, 26), (1, 28), (1, 29), (1, 30), (2, 3), (2, 4),
|
55 |
+
(2, 5), (2, 8), (2, 9), (2, 10), (2, 14), (2, 17), (2, 18),
|
56 |
+
(2, 21), (2, 22), (2, 23), (2, 27), (3, 9), (3, 15), (3, 21),
|
57 |
+
(3, 22), (3, 23), (3, 24), (3, 27), (3, 28), (3, 29), (4, 5),
|
58 |
+
(4, 6), (4, 8), (4, 21), (4, 22), (4, 23), (4, 26), (4, 28),
|
59 |
+
(4, 30), (5, 6), (5, 8), (5, 9), (5, 13), (5, 14), (5, 15),
|
60 |
+
(5, 16), (5, 20), (5, 21), (5, 22), (5, 25), (5, 28), (5, 29),
|
61 |
+
(6, 7), (6, 8), (6, 13), (6, 17), (6, 18), (6, 19), (6, 24),
|
62 |
+
(6, 26), (6, 27), (6, 28), (6, 29), (7, 12), (7, 14), (7, 15),
|
63 |
+
(7, 16), (7, 17), (7, 20), (7, 25), (7, 27), (7, 29), (7, 30),
|
64 |
+
(8, 10), (8, 15), (8, 16), (8, 18), (8, 20), (8, 22), (8, 24),
|
65 |
+
(8, 26), (8, 27), (8, 28), (8, 30), (9, 11), (9, 12), (9, 13),
|
66 |
+
(9, 14), (9, 15), (9, 16), (9, 19), (9, 20), (9, 21), (9, 24),
|
67 |
+
(9, 30), (10, 12), (10, 15), (10, 18), (10, 19), (10, 20),
|
68 |
+
(10, 22), (10, 23), (10, 24), (10, 26), (10, 27), (10, 29),
|
69 |
+
(10, 30), (11, 13), (11, 15), (11, 16), (11, 17), (11, 18),
|
70 |
+
(11, 19), (11, 20), (11, 22), (11, 29), (11, 30), (12, 14),
|
71 |
+
(12, 17), (12, 18), (12, 19), (12, 20), (12, 21), (12, 23),
|
72 |
+
(12, 25), (12, 26), (12, 30), (13, 20), (13, 22), (13, 23),
|
73 |
+
(13, 24), (13, 30), (14, 16), (14, 20), (14, 21), (14, 22),
|
74 |
+
(14, 23), (14, 25), (14, 26), (14, 27), (14, 29), (14, 30),
|
75 |
+
(15, 17), (15, 18), (15, 20), (15, 21), (15, 26), (15, 27),
|
76 |
+
(15, 28), (16, 17), (16, 18), (16, 19), (16, 20), (16, 21),
|
77 |
+
(16, 29), (16, 30), (17, 18), (17, 21), (17, 22), (17, 25),
|
78 |
+
(17, 27), (17, 28), (17, 30), (18, 19), (18, 20), (18, 21),
|
79 |
+
(18, 22), (18, 23), (18, 24), (19, 20), (19, 22), (19, 23),
|
80 |
+
(19, 24), (19, 25), (19, 27), (19, 30), (20, 21), (20, 23),
|
81 |
+
(20, 24), (20, 26), (20, 28), (20, 29), (21, 23), (21, 26),
|
82 |
+
(21, 27), (21, 29), (22, 24), (22, 25), (22, 26), (22, 29),
|
83 |
+
(23, 25), (23, 30), (24, 25), (24, 26), (25, 27), (25, 29),
|
84 |
+
(26, 27), (26, 28), (26, 30), (28, 29), (29, 30),
|
85 |
+
]
|
86 |
+
)
|
87 |
+
# fmt: on
|
88 |
+
clique, weight = nx.algorithms.max_weight_clique(G)
|
89 |
+
assert verify_clique(G, clique, weight, 111, "weight")
|
90 |
+
|
91 |
+
|
92 |
+
# ############################ Utility functions ############################
|
93 |
+
def verify_clique(
|
94 |
+
graph, clique, reported_clique_weight, expected_clique_weight, weight_accessor
|
95 |
+
):
|
96 |
+
for node1 in clique:
|
97 |
+
for node2 in clique:
|
98 |
+
if node1 == node2:
|
99 |
+
continue
|
100 |
+
if not graph.has_edge(node1, node2):
|
101 |
+
return False
|
102 |
+
|
103 |
+
if weight_accessor is None:
|
104 |
+
clique_weight = len(clique)
|
105 |
+
else:
|
106 |
+
clique_weight = sum(graph.nodes[v]["weight"] for v in clique)
|
107 |
+
|
108 |
+
if clique_weight != expected_clique_weight:
|
109 |
+
return False
|
110 |
+
if clique_weight != reported_clique_weight:
|
111 |
+
return False
|
112 |
+
|
113 |
+
return True
|
114 |
+
|
115 |
+
|
116 |
+
# ############################ Graph Generation ############################
|
117 |
+
|
118 |
+
|
119 |
+
def empty_graph():
|
120 |
+
return nx.Graph()
|
121 |
+
|
122 |
+
|
123 |
+
def one_node_graph():
|
124 |
+
graph = nx.Graph()
|
125 |
+
graph.add_nodes_from([1])
|
126 |
+
graph.nodes[1]["weight"] = 10
|
127 |
+
return graph
|
128 |
+
|
129 |
+
|
130 |
+
def two_node_graph():
|
131 |
+
graph = nx.Graph()
|
132 |
+
graph.add_nodes_from([1, 2])
|
133 |
+
graph.add_edges_from([(1, 2)])
|
134 |
+
graph.nodes[1]["weight"] = 10
|
135 |
+
graph.nodes[2]["weight"] = 20
|
136 |
+
return graph
|
137 |
+
|
138 |
+
|
139 |
+
def three_node_clique():
|
140 |
+
graph = nx.Graph()
|
141 |
+
graph.add_nodes_from([1, 2, 3])
|
142 |
+
graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
|
143 |
+
graph.nodes[1]["weight"] = 10
|
144 |
+
graph.nodes[2]["weight"] = 20
|
145 |
+
graph.nodes[3]["weight"] = 5
|
146 |
+
return graph
|
147 |
+
|
148 |
+
|
149 |
+
def three_node_independent_set():
|
150 |
+
graph = nx.Graph()
|
151 |
+
graph.add_nodes_from([1, 2, 3])
|
152 |
+
graph.nodes[1]["weight"] = 10
|
153 |
+
graph.nodes[2]["weight"] = 20
|
154 |
+
graph.nodes[3]["weight"] = 5
|
155 |
+
return graph
|
156 |
+
|
157 |
+
|
158 |
+
def disconnected():
|
159 |
+
graph = nx.Graph()
|
160 |
+
graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
|
161 |
+
graph.nodes[1]["weight"] = 10
|
162 |
+
graph.nodes[2]["weight"] = 20
|
163 |
+
graph.nodes[3]["weight"] = 5
|
164 |
+
graph.nodes[4]["weight"] = 100
|
165 |
+
graph.nodes[5]["weight"] = 200
|
166 |
+
graph.nodes[6]["weight"] = 50
|
167 |
+
return graph
|
168 |
+
|
169 |
+
|
170 |
+
# --------------------------------------------------------------------------
|
171 |
+
# Basic tests for all strategies
|
172 |
+
# For each basic graph function, specify expected weight of max weight clique
|
173 |
+
# and expected size of maximum clique
|
174 |
+
TEST_CASES = {
|
175 |
+
empty_graph: (0, 0),
|
176 |
+
one_node_graph: (10, 1),
|
177 |
+
two_node_graph: (30, 2),
|
178 |
+
three_node_clique: (35, 3),
|
179 |
+
three_node_independent_set: (20, 1),
|
180 |
+
disconnected: (300, 2),
|
181 |
+
}
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_node_classification.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
pytest.importorskip("numpy")
|
4 |
+
pytest.importorskip("scipy")
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
from networkx.algorithms import node_classification
|
8 |
+
|
9 |
+
|
10 |
+
class TestHarmonicFunction:
|
11 |
+
def test_path_graph(self):
|
12 |
+
G = nx.path_graph(4)
|
13 |
+
label_name = "label"
|
14 |
+
G.nodes[0][label_name] = "A"
|
15 |
+
G.nodes[3][label_name] = "B"
|
16 |
+
predicted = node_classification.harmonic_function(G, label_name=label_name)
|
17 |
+
assert predicted[0] == "A"
|
18 |
+
assert predicted[1] == "A"
|
19 |
+
assert predicted[2] == "B"
|
20 |
+
assert predicted[3] == "B"
|
21 |
+
|
22 |
+
def test_no_labels(self):
|
23 |
+
with pytest.raises(nx.NetworkXError):
|
24 |
+
G = nx.path_graph(4)
|
25 |
+
node_classification.harmonic_function(G)
|
26 |
+
|
27 |
+
def test_no_nodes(self):
|
28 |
+
with pytest.raises(nx.NetworkXError):
|
29 |
+
G = nx.Graph()
|
30 |
+
node_classification.harmonic_function(G)
|
31 |
+
|
32 |
+
def test_no_edges(self):
|
33 |
+
with pytest.raises(nx.NetworkXError):
|
34 |
+
G = nx.Graph()
|
35 |
+
G.add_node(1)
|
36 |
+
G.add_node(2)
|
37 |
+
node_classification.harmonic_function(G)
|
38 |
+
|
39 |
+
def test_digraph(self):
|
40 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
41 |
+
G = nx.DiGraph()
|
42 |
+
G.add_edge(0, 1)
|
43 |
+
G.add_edge(1, 2)
|
44 |
+
G.add_edge(2, 3)
|
45 |
+
label_name = "label"
|
46 |
+
G.nodes[0][label_name] = "A"
|
47 |
+
G.nodes[3][label_name] = "B"
|
48 |
+
node_classification.harmonic_function(G)
|
49 |
+
|
50 |
+
def test_one_labeled_node(self):
|
51 |
+
G = nx.path_graph(4)
|
52 |
+
label_name = "label"
|
53 |
+
G.nodes[0][label_name] = "A"
|
54 |
+
predicted = node_classification.harmonic_function(G, label_name=label_name)
|
55 |
+
assert predicted[0] == "A"
|
56 |
+
assert predicted[1] == "A"
|
57 |
+
assert predicted[2] == "A"
|
58 |
+
assert predicted[3] == "A"
|
59 |
+
|
60 |
+
def test_nodes_all_labeled(self):
|
61 |
+
G = nx.karate_club_graph()
|
62 |
+
label_name = "club"
|
63 |
+
predicted = node_classification.harmonic_function(G, label_name=label_name)
|
64 |
+
for i in range(len(G)):
|
65 |
+
assert predicted[i] == G.nodes[i][label_name]
|
66 |
+
|
67 |
+
def test_labeled_nodes_are_not_changed(self):
|
68 |
+
G = nx.karate_club_graph()
|
69 |
+
label_name = "club"
|
70 |
+
label_removed = {0, 1, 2, 3, 4, 5, 6, 7}
|
71 |
+
for i in label_removed:
|
72 |
+
del G.nodes[i][label_name]
|
73 |
+
predicted = node_classification.harmonic_function(G, label_name=label_name)
|
74 |
+
label_not_removed = set(range(len(G))) - label_removed
|
75 |
+
for i in label_not_removed:
|
76 |
+
assert predicted[i] == G.nodes[i][label_name]
|
77 |
+
|
78 |
+
|
79 |
+
class TestLocalAndGlobalConsistency:
|
80 |
+
def test_path_graph(self):
|
81 |
+
G = nx.path_graph(4)
|
82 |
+
label_name = "label"
|
83 |
+
G.nodes[0][label_name] = "A"
|
84 |
+
G.nodes[3][label_name] = "B"
|
85 |
+
predicted = node_classification.local_and_global_consistency(
|
86 |
+
G, label_name=label_name
|
87 |
+
)
|
88 |
+
assert predicted[0] == "A"
|
89 |
+
assert predicted[1] == "A"
|
90 |
+
assert predicted[2] == "B"
|
91 |
+
assert predicted[3] == "B"
|
92 |
+
|
93 |
+
def test_no_labels(self):
|
94 |
+
with pytest.raises(nx.NetworkXError):
|
95 |
+
G = nx.path_graph(4)
|
96 |
+
node_classification.local_and_global_consistency(G)
|
97 |
+
|
98 |
+
def test_no_nodes(self):
|
99 |
+
with pytest.raises(nx.NetworkXError):
|
100 |
+
G = nx.Graph()
|
101 |
+
node_classification.local_and_global_consistency(G)
|
102 |
+
|
103 |
+
def test_no_edges(self):
|
104 |
+
with pytest.raises(nx.NetworkXError):
|
105 |
+
G = nx.Graph()
|
106 |
+
G.add_node(1)
|
107 |
+
G.add_node(2)
|
108 |
+
node_classification.local_and_global_consistency(G)
|
109 |
+
|
110 |
+
def test_digraph(self):
|
111 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
112 |
+
G = nx.DiGraph()
|
113 |
+
G.add_edge(0, 1)
|
114 |
+
G.add_edge(1, 2)
|
115 |
+
G.add_edge(2, 3)
|
116 |
+
label_name = "label"
|
117 |
+
G.nodes[0][label_name] = "A"
|
118 |
+
G.nodes[3][label_name] = "B"
|
119 |
+
node_classification.harmonic_function(G)
|
120 |
+
|
121 |
+
def test_one_labeled_node(self):
|
122 |
+
G = nx.path_graph(4)
|
123 |
+
label_name = "label"
|
124 |
+
G.nodes[0][label_name] = "A"
|
125 |
+
predicted = node_classification.local_and_global_consistency(
|
126 |
+
G, label_name=label_name
|
127 |
+
)
|
128 |
+
assert predicted[0] == "A"
|
129 |
+
assert predicted[1] == "A"
|
130 |
+
assert predicted[2] == "A"
|
131 |
+
assert predicted[3] == "A"
|
132 |
+
|
133 |
+
def test_nodes_all_labeled(self):
|
134 |
+
G = nx.karate_club_graph()
|
135 |
+
label_name = "club"
|
136 |
+
predicted = node_classification.local_and_global_consistency(
|
137 |
+
G, alpha=0, label_name=label_name
|
138 |
+
)
|
139 |
+
for i in range(len(G)):
|
140 |
+
assert predicted[i] == G.nodes[i][label_name]
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_non_randomness.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
np = pytest.importorskip("numpy")
|
6 |
+
|
7 |
+
|
8 |
+
@pytest.mark.parametrize(
|
9 |
+
"k, weight, expected",
|
10 |
+
[
|
11 |
+
(None, None, 7.21), # infers 3 communities
|
12 |
+
(2, None, 11.7),
|
13 |
+
(None, "weight", 25.45),
|
14 |
+
(2, "weight", 38.8),
|
15 |
+
],
|
16 |
+
)
|
17 |
+
def test_non_randomness(k, weight, expected):
|
18 |
+
G = nx.karate_club_graph()
|
19 |
+
np.testing.assert_almost_equal(
|
20 |
+
nx.non_randomness(G, k, weight)[0], expected, decimal=2
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
def test_non_connected():
|
25 |
+
G = nx.Graph()
|
26 |
+
G.add_edge(1, 2)
|
27 |
+
G.add_node(3)
|
28 |
+
with pytest.raises(nx.NetworkXException):
|
29 |
+
nx.non_randomness(G)
|
30 |
+
|
31 |
+
|
32 |
+
def test_self_loops():
|
33 |
+
G = nx.Graph()
|
34 |
+
G.add_edge(1, 2)
|
35 |
+
G.add_edge(1, 1)
|
36 |
+
with pytest.raises(nx.NetworkXError):
|
37 |
+
nx.non_randomness(G)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_polynomials.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for the :mod:`networkx.algorithms.polynomials` module."""
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
sympy = pytest.importorskip("sympy")
|
8 |
+
|
9 |
+
|
10 |
+
# Mapping of input graphs to a string representation of their tutte polynomials
|
11 |
+
_test_tutte_graphs = {
|
12 |
+
nx.complete_graph(1): "1",
|
13 |
+
nx.complete_graph(4): "x**3 + 3*x**2 + 4*x*y + 2*x + y**3 + 3*y**2 + 2*y",
|
14 |
+
nx.cycle_graph(5): "x**4 + x**3 + x**2 + x + y",
|
15 |
+
nx.diamond_graph(): "x**3 + 2*x**2 + 2*x*y + x + y**2 + y",
|
16 |
+
}
|
17 |
+
|
18 |
+
_test_chromatic_graphs = {
|
19 |
+
nx.complete_graph(1): "x",
|
20 |
+
nx.complete_graph(4): "x**4 - 6*x**3 + 11*x**2 - 6*x",
|
21 |
+
nx.cycle_graph(5): "x**5 - 5*x**4 + 10*x**3 - 10*x**2 + 4*x",
|
22 |
+
nx.diamond_graph(): "x**4 - 5*x**3 + 8*x**2 - 4*x",
|
23 |
+
nx.path_graph(5): "x**5 - 4*x**4 + 6*x**3 - 4*x**2 + x",
|
24 |
+
}
|
25 |
+
|
26 |
+
|
27 |
+
@pytest.mark.parametrize(("G", "expected"), _test_tutte_graphs.items())
|
28 |
+
def test_tutte_polynomial(G, expected):
|
29 |
+
assert nx.tutte_polynomial(G).equals(expected)
|
30 |
+
|
31 |
+
|
32 |
+
@pytest.mark.parametrize("G", _test_tutte_graphs.keys())
|
33 |
+
def test_tutte_polynomial_disjoint(G):
|
34 |
+
"""Tutte polynomial factors into the Tutte polynomials of its components.
|
35 |
+
Verify this property with the disjoint union of two copies of the input graph.
|
36 |
+
"""
|
37 |
+
t_g = nx.tutte_polynomial(G)
|
38 |
+
H = nx.disjoint_union(G, G)
|
39 |
+
t_h = nx.tutte_polynomial(H)
|
40 |
+
assert sympy.simplify(t_g * t_g).equals(t_h)
|
41 |
+
|
42 |
+
|
43 |
+
@pytest.mark.parametrize(("G", "expected"), _test_chromatic_graphs.items())
|
44 |
+
def test_chromatic_polynomial(G, expected):
|
45 |
+
assert nx.chromatic_polynomial(G).equals(expected)
|
46 |
+
|
47 |
+
|
48 |
+
@pytest.mark.parametrize("G", _test_chromatic_graphs.keys())
|
49 |
+
def test_chromatic_polynomial_disjoint(G):
|
50 |
+
"""Chromatic polynomial factors into the Chromatic polynomials of its
|
51 |
+
components. Verify this property with the disjoint union of two copies of
|
52 |
+
the input graph.
|
53 |
+
"""
|
54 |
+
x_g = nx.chromatic_polynomial(G)
|
55 |
+
H = nx.disjoint_union(G, G)
|
56 |
+
x_h = nx.chromatic_polynomial(H)
|
57 |
+
assert sympy.simplify(x_g * x_g).equals(x_h)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_reciprocity.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
class TestReciprocity:
|
7 |
+
# test overall reciprocity by passing whole graph
|
8 |
+
def test_reciprocity_digraph(self):
|
9 |
+
DG = nx.DiGraph([(1, 2), (2, 1)])
|
10 |
+
reciprocity = nx.reciprocity(DG)
|
11 |
+
assert reciprocity == 1.0
|
12 |
+
|
13 |
+
# test empty graph's overall reciprocity which will throw an error
|
14 |
+
def test_overall_reciprocity_empty_graph(self):
|
15 |
+
with pytest.raises(nx.NetworkXError):
|
16 |
+
DG = nx.DiGraph()
|
17 |
+
nx.overall_reciprocity(DG)
|
18 |
+
|
19 |
+
# test for reciprocity for a list of nodes
|
20 |
+
def test_reciprocity_graph_nodes(self):
|
21 |
+
DG = nx.DiGraph([(1, 2), (2, 3), (3, 2)])
|
22 |
+
reciprocity = nx.reciprocity(DG, [1, 2])
|
23 |
+
expected_reciprocity = {1: 0.0, 2: 0.6666666666666666}
|
24 |
+
assert reciprocity == expected_reciprocity
|
25 |
+
|
26 |
+
# test for reciprocity for a single node
|
27 |
+
def test_reciprocity_graph_node(self):
|
28 |
+
DG = nx.DiGraph([(1, 2), (2, 3), (3, 2)])
|
29 |
+
reciprocity = nx.reciprocity(DG, 2)
|
30 |
+
assert reciprocity == 0.6666666666666666
|
31 |
+
|
32 |
+
# test for reciprocity for an isolated node
|
33 |
+
def test_reciprocity_graph_isolated_nodes(self):
|
34 |
+
with pytest.raises(nx.NetworkXError):
|
35 |
+
DG = nx.DiGraph([(1, 2)])
|
36 |
+
DG.add_node(4)
|
37 |
+
nx.reciprocity(DG, 4)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_richclub.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
def test_richclub():
|
7 |
+
G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
|
8 |
+
rc = nx.richclub.rich_club_coefficient(G, normalized=False)
|
9 |
+
assert rc == {0: 12.0 / 30, 1: 8.0 / 12}
|
10 |
+
|
11 |
+
# test single value
|
12 |
+
rc0 = nx.richclub.rich_club_coefficient(G, normalized=False)[0]
|
13 |
+
assert rc0 == 12.0 / 30.0
|
14 |
+
|
15 |
+
|
16 |
+
def test_richclub_seed():
|
17 |
+
G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
|
18 |
+
rcNorm = nx.richclub.rich_club_coefficient(G, Q=2, seed=1)
|
19 |
+
assert rcNorm == {0: 1.0, 1: 1.0}
|
20 |
+
|
21 |
+
|
22 |
+
def test_richclub_normalized():
|
23 |
+
G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
|
24 |
+
rcNorm = nx.richclub.rich_club_coefficient(G, Q=2, seed=42)
|
25 |
+
assert rcNorm == {0: 1.0, 1: 1.0}
|
26 |
+
|
27 |
+
|
28 |
+
def test_richclub2():
|
29 |
+
T = nx.balanced_tree(2, 10)
|
30 |
+
rc = nx.richclub.rich_club_coefficient(T, normalized=False)
|
31 |
+
assert rc == {
|
32 |
+
0: 4092 / (2047 * 2046.0),
|
33 |
+
1: (2044.0 / (1023 * 1022)),
|
34 |
+
2: (2040.0 / (1022 * 1021)),
|
35 |
+
}
|
36 |
+
|
37 |
+
|
38 |
+
def test_richclub3():
|
39 |
+
# tests edgecase
|
40 |
+
G = nx.karate_club_graph()
|
41 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
42 |
+
assert rc == {
|
43 |
+
0: 156.0 / 1122,
|
44 |
+
1: 154.0 / 1056,
|
45 |
+
2: 110.0 / 462,
|
46 |
+
3: 78.0 / 240,
|
47 |
+
4: 44.0 / 90,
|
48 |
+
5: 22.0 / 42,
|
49 |
+
6: 10.0 / 20,
|
50 |
+
7: 10.0 / 20,
|
51 |
+
8: 10.0 / 20,
|
52 |
+
9: 6.0 / 12,
|
53 |
+
10: 2.0 / 6,
|
54 |
+
11: 2.0 / 6,
|
55 |
+
12: 0.0,
|
56 |
+
13: 0.0,
|
57 |
+
14: 0.0,
|
58 |
+
15: 0.0,
|
59 |
+
}
|
60 |
+
|
61 |
+
|
62 |
+
def test_richclub4():
|
63 |
+
G = nx.Graph()
|
64 |
+
G.add_edges_from(
|
65 |
+
[(0, 1), (0, 2), (0, 3), (0, 4), (4, 5), (5, 9), (6, 9), (7, 9), (8, 9)]
|
66 |
+
)
|
67 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
68 |
+
assert rc == {0: 18 / 90.0, 1: 6 / 12.0, 2: 0.0, 3: 0.0}
|
69 |
+
|
70 |
+
|
71 |
+
def test_richclub_exception():
|
72 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
73 |
+
G = nx.DiGraph()
|
74 |
+
nx.rich_club_coefficient(G)
|
75 |
+
|
76 |
+
|
77 |
+
def test_rich_club_exception2():
|
78 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
79 |
+
G = nx.MultiGraph()
|
80 |
+
nx.rich_club_coefficient(G)
|
81 |
+
|
82 |
+
|
83 |
+
def test_rich_club_selfloop():
|
84 |
+
G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
85 |
+
G.add_edge(1, 1) # self loop
|
86 |
+
G.add_edge(1, 2)
|
87 |
+
with pytest.raises(
|
88 |
+
Exception,
|
89 |
+
match="rich_club_coefficient is not implemented for " "graphs with self loops.",
|
90 |
+
):
|
91 |
+
nx.rich_club_coefficient(G)
|
92 |
+
|
93 |
+
|
94 |
+
def test_rich_club_leq_3_nodes_unnormalized():
|
95 |
+
# edgeless graphs upto 3 nodes
|
96 |
+
G = nx.Graph()
|
97 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
98 |
+
assert rc == {}
|
99 |
+
|
100 |
+
for i in range(3):
|
101 |
+
G.add_node(i)
|
102 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
103 |
+
assert rc == {}
|
104 |
+
|
105 |
+
# 2 nodes, single edge
|
106 |
+
G = nx.Graph()
|
107 |
+
G.add_edge(0, 1)
|
108 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
109 |
+
assert rc == {0: 1}
|
110 |
+
|
111 |
+
# 3 nodes, single edge
|
112 |
+
G = nx.Graph()
|
113 |
+
G.add_nodes_from([0, 1, 2])
|
114 |
+
G.add_edge(0, 1)
|
115 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
116 |
+
assert rc == {0: 1}
|
117 |
+
|
118 |
+
# 3 nodes, 2 edges
|
119 |
+
G.add_edge(1, 2)
|
120 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
121 |
+
assert rc == {0: 2 / 3}
|
122 |
+
|
123 |
+
# 3 nodes, 3 edges
|
124 |
+
G.add_edge(0, 2)
|
125 |
+
rc = nx.rich_club_coefficient(G, normalized=False)
|
126 |
+
assert rc == {0: 1, 1: 1}
|
127 |
+
|
128 |
+
|
129 |
+
def test_rich_club_leq_3_nodes_normalized():
|
130 |
+
G = nx.Graph()
|
131 |
+
with pytest.raises(
|
132 |
+
nx.exception.NetworkXError,
|
133 |
+
match="Graph has fewer than four nodes",
|
134 |
+
):
|
135 |
+
rc = nx.rich_club_coefficient(G, normalized=True)
|
136 |
+
|
137 |
+
for i in range(3):
|
138 |
+
G.add_node(i)
|
139 |
+
with pytest.raises(
|
140 |
+
nx.exception.NetworkXError,
|
141 |
+
match="Graph has fewer than four nodes",
|
142 |
+
):
|
143 |
+
rc = nx.rich_club_coefficient(G, normalized=True)
|
144 |
+
|
145 |
+
|
146 |
+
# def test_richclub2_normalized():
|
147 |
+
# T = nx.balanced_tree(2,10)
|
148 |
+
# rcNorm = nx.richclub.rich_club_coefficient(T,Q=2)
|
149 |
+
# assert_true(rcNorm[0] ==1.0 and rcNorm[1] < 0.9 and rcNorm[2] < 0.9)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_similarity.py
ADDED
@@ -0,0 +1,946 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms.similarity import (
|
5 |
+
graph_edit_distance,
|
6 |
+
optimal_edit_paths,
|
7 |
+
optimize_graph_edit_distance,
|
8 |
+
)
|
9 |
+
from networkx.generators.classic import (
|
10 |
+
circular_ladder_graph,
|
11 |
+
cycle_graph,
|
12 |
+
path_graph,
|
13 |
+
wheel_graph,
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
def nmatch(n1, n2):
|
18 |
+
return n1 == n2
|
19 |
+
|
20 |
+
|
21 |
+
def ematch(e1, e2):
|
22 |
+
return e1 == e2
|
23 |
+
|
24 |
+
|
25 |
+
def getCanonical():
|
26 |
+
G = nx.Graph()
|
27 |
+
G.add_node("A", label="A")
|
28 |
+
G.add_node("B", label="B")
|
29 |
+
G.add_node("C", label="C")
|
30 |
+
G.add_node("D", label="D")
|
31 |
+
G.add_edge("A", "B", label="a-b")
|
32 |
+
G.add_edge("B", "C", label="b-c")
|
33 |
+
G.add_edge("B", "D", label="b-d")
|
34 |
+
return G
|
35 |
+
|
36 |
+
|
37 |
+
class TestSimilarity:
|
38 |
+
@classmethod
|
39 |
+
def setup_class(cls):
|
40 |
+
global np
|
41 |
+
np = pytest.importorskip("numpy")
|
42 |
+
pytest.importorskip("scipy")
|
43 |
+
|
44 |
+
def test_graph_edit_distance_roots_and_timeout(self):
|
45 |
+
G0 = nx.star_graph(5)
|
46 |
+
G1 = G0.copy()
|
47 |
+
pytest.raises(ValueError, graph_edit_distance, G0, G1, roots=[2])
|
48 |
+
pytest.raises(ValueError, graph_edit_distance, G0, G1, roots=[2, 3, 4])
|
49 |
+
pytest.raises(nx.NodeNotFound, graph_edit_distance, G0, G1, roots=(9, 3))
|
50 |
+
pytest.raises(nx.NodeNotFound, graph_edit_distance, G0, G1, roots=(3, 9))
|
51 |
+
pytest.raises(nx.NodeNotFound, graph_edit_distance, G0, G1, roots=(9, 9))
|
52 |
+
assert graph_edit_distance(G0, G1, roots=(1, 2)) == 0
|
53 |
+
assert graph_edit_distance(G0, G1, roots=(0, 1)) == 8
|
54 |
+
assert graph_edit_distance(G0, G1, roots=(1, 2), timeout=5) == 0
|
55 |
+
assert graph_edit_distance(G0, G1, roots=(0, 1), timeout=5) == 8
|
56 |
+
assert graph_edit_distance(G0, G1, roots=(0, 1), timeout=0.0001) is None
|
57 |
+
# test raise on 0 timeout
|
58 |
+
pytest.raises(nx.NetworkXError, graph_edit_distance, G0, G1, timeout=0)
|
59 |
+
|
60 |
+
def test_graph_edit_distance(self):
|
61 |
+
G0 = nx.Graph()
|
62 |
+
G1 = path_graph(6)
|
63 |
+
G2 = cycle_graph(6)
|
64 |
+
G3 = wheel_graph(7)
|
65 |
+
|
66 |
+
assert graph_edit_distance(G0, G0) == 0
|
67 |
+
assert graph_edit_distance(G0, G1) == 11
|
68 |
+
assert graph_edit_distance(G1, G0) == 11
|
69 |
+
assert graph_edit_distance(G0, G2) == 12
|
70 |
+
assert graph_edit_distance(G2, G0) == 12
|
71 |
+
assert graph_edit_distance(G0, G3) == 19
|
72 |
+
assert graph_edit_distance(G3, G0) == 19
|
73 |
+
|
74 |
+
assert graph_edit_distance(G1, G1) == 0
|
75 |
+
assert graph_edit_distance(G1, G2) == 1
|
76 |
+
assert graph_edit_distance(G2, G1) == 1
|
77 |
+
assert graph_edit_distance(G1, G3) == 8
|
78 |
+
assert graph_edit_distance(G3, G1) == 8
|
79 |
+
|
80 |
+
assert graph_edit_distance(G2, G2) == 0
|
81 |
+
assert graph_edit_distance(G2, G3) == 7
|
82 |
+
assert graph_edit_distance(G3, G2) == 7
|
83 |
+
|
84 |
+
assert graph_edit_distance(G3, G3) == 0
|
85 |
+
|
86 |
+
def test_graph_edit_distance_node_match(self):
|
87 |
+
G1 = cycle_graph(5)
|
88 |
+
G2 = cycle_graph(5)
|
89 |
+
for n, attr in G1.nodes.items():
|
90 |
+
attr["color"] = "red" if n % 2 == 0 else "blue"
|
91 |
+
for n, attr in G2.nodes.items():
|
92 |
+
attr["color"] = "red" if n % 2 == 1 else "blue"
|
93 |
+
assert graph_edit_distance(G1, G2) == 0
|
94 |
+
assert (
|
95 |
+
graph_edit_distance(
|
96 |
+
G1, G2, node_match=lambda n1, n2: n1["color"] == n2["color"]
|
97 |
+
)
|
98 |
+
== 1
|
99 |
+
)
|
100 |
+
|
101 |
+
def test_graph_edit_distance_edge_match(self):
|
102 |
+
G1 = path_graph(6)
|
103 |
+
G2 = path_graph(6)
|
104 |
+
for e, attr in G1.edges.items():
|
105 |
+
attr["color"] = "red" if min(e) % 2 == 0 else "blue"
|
106 |
+
for e, attr in G2.edges.items():
|
107 |
+
attr["color"] = "red" if min(e) // 3 == 0 else "blue"
|
108 |
+
assert graph_edit_distance(G1, G2) == 0
|
109 |
+
assert (
|
110 |
+
graph_edit_distance(
|
111 |
+
G1, G2, edge_match=lambda e1, e2: e1["color"] == e2["color"]
|
112 |
+
)
|
113 |
+
== 2
|
114 |
+
)
|
115 |
+
|
116 |
+
def test_graph_edit_distance_node_cost(self):
|
117 |
+
G1 = path_graph(6)
|
118 |
+
G2 = path_graph(6)
|
119 |
+
for n, attr in G1.nodes.items():
|
120 |
+
attr["color"] = "red" if n % 2 == 0 else "blue"
|
121 |
+
for n, attr in G2.nodes.items():
|
122 |
+
attr["color"] = "red" if n % 2 == 1 else "blue"
|
123 |
+
|
124 |
+
def node_subst_cost(uattr, vattr):
|
125 |
+
if uattr["color"] == vattr["color"]:
|
126 |
+
return 1
|
127 |
+
else:
|
128 |
+
return 10
|
129 |
+
|
130 |
+
def node_del_cost(attr):
|
131 |
+
if attr["color"] == "blue":
|
132 |
+
return 20
|
133 |
+
else:
|
134 |
+
return 50
|
135 |
+
|
136 |
+
def node_ins_cost(attr):
|
137 |
+
if attr["color"] == "blue":
|
138 |
+
return 40
|
139 |
+
else:
|
140 |
+
return 100
|
141 |
+
|
142 |
+
assert (
|
143 |
+
graph_edit_distance(
|
144 |
+
G1,
|
145 |
+
G2,
|
146 |
+
node_subst_cost=node_subst_cost,
|
147 |
+
node_del_cost=node_del_cost,
|
148 |
+
node_ins_cost=node_ins_cost,
|
149 |
+
)
|
150 |
+
== 6
|
151 |
+
)
|
152 |
+
|
153 |
+
def test_graph_edit_distance_edge_cost(self):
|
154 |
+
G1 = path_graph(6)
|
155 |
+
G2 = path_graph(6)
|
156 |
+
for e, attr in G1.edges.items():
|
157 |
+
attr["color"] = "red" if min(e) % 2 == 0 else "blue"
|
158 |
+
for e, attr in G2.edges.items():
|
159 |
+
attr["color"] = "red" if min(e) // 3 == 0 else "blue"
|
160 |
+
|
161 |
+
def edge_subst_cost(gattr, hattr):
|
162 |
+
if gattr["color"] == hattr["color"]:
|
163 |
+
return 0.01
|
164 |
+
else:
|
165 |
+
return 0.1
|
166 |
+
|
167 |
+
def edge_del_cost(attr):
|
168 |
+
if attr["color"] == "blue":
|
169 |
+
return 0.2
|
170 |
+
else:
|
171 |
+
return 0.5
|
172 |
+
|
173 |
+
def edge_ins_cost(attr):
|
174 |
+
if attr["color"] == "blue":
|
175 |
+
return 0.4
|
176 |
+
else:
|
177 |
+
return 1.0
|
178 |
+
|
179 |
+
assert (
|
180 |
+
graph_edit_distance(
|
181 |
+
G1,
|
182 |
+
G2,
|
183 |
+
edge_subst_cost=edge_subst_cost,
|
184 |
+
edge_del_cost=edge_del_cost,
|
185 |
+
edge_ins_cost=edge_ins_cost,
|
186 |
+
)
|
187 |
+
== 0.23
|
188 |
+
)
|
189 |
+
|
190 |
+
def test_graph_edit_distance_upper_bound(self):
|
191 |
+
G1 = circular_ladder_graph(2)
|
192 |
+
G2 = circular_ladder_graph(6)
|
193 |
+
assert graph_edit_distance(G1, G2, upper_bound=5) is None
|
194 |
+
assert graph_edit_distance(G1, G2, upper_bound=24) == 22
|
195 |
+
assert graph_edit_distance(G1, G2) == 22
|
196 |
+
|
197 |
+
def test_optimal_edit_paths(self):
|
198 |
+
G1 = path_graph(3)
|
199 |
+
G2 = cycle_graph(3)
|
200 |
+
paths, cost = optimal_edit_paths(G1, G2)
|
201 |
+
assert cost == 1
|
202 |
+
assert len(paths) == 6
|
203 |
+
|
204 |
+
def canonical(vertex_path, edge_path):
|
205 |
+
return (
|
206 |
+
tuple(sorted(vertex_path)),
|
207 |
+
tuple(sorted(edge_path, key=lambda x: (None in x, x))),
|
208 |
+
)
|
209 |
+
|
210 |
+
expected_paths = [
|
211 |
+
(
|
212 |
+
[(0, 0), (1, 1), (2, 2)],
|
213 |
+
[((0, 1), (0, 1)), ((1, 2), (1, 2)), (None, (0, 2))],
|
214 |
+
),
|
215 |
+
(
|
216 |
+
[(0, 0), (1, 2), (2, 1)],
|
217 |
+
[((0, 1), (0, 2)), ((1, 2), (1, 2)), (None, (0, 1))],
|
218 |
+
),
|
219 |
+
(
|
220 |
+
[(0, 1), (1, 0), (2, 2)],
|
221 |
+
[((0, 1), (0, 1)), ((1, 2), (0, 2)), (None, (1, 2))],
|
222 |
+
),
|
223 |
+
(
|
224 |
+
[(0, 1), (1, 2), (2, 0)],
|
225 |
+
[((0, 1), (1, 2)), ((1, 2), (0, 2)), (None, (0, 1))],
|
226 |
+
),
|
227 |
+
(
|
228 |
+
[(0, 2), (1, 0), (2, 1)],
|
229 |
+
[((0, 1), (0, 2)), ((1, 2), (0, 1)), (None, (1, 2))],
|
230 |
+
),
|
231 |
+
(
|
232 |
+
[(0, 2), (1, 1), (2, 0)],
|
233 |
+
[((0, 1), (1, 2)), ((1, 2), (0, 1)), (None, (0, 2))],
|
234 |
+
),
|
235 |
+
]
|
236 |
+
assert {canonical(*p) for p in paths} == {canonical(*p) for p in expected_paths}
|
237 |
+
|
238 |
+
def test_optimize_graph_edit_distance(self):
|
239 |
+
G1 = circular_ladder_graph(2)
|
240 |
+
G2 = circular_ladder_graph(6)
|
241 |
+
bestcost = 1000
|
242 |
+
for cost in optimize_graph_edit_distance(G1, G2):
|
243 |
+
assert cost < bestcost
|
244 |
+
bestcost = cost
|
245 |
+
assert bestcost == 22
|
246 |
+
|
247 |
+
# def test_graph_edit_distance_bigger(self):
|
248 |
+
# G1 = circular_ladder_graph(12)
|
249 |
+
# G2 = circular_ladder_graph(16)
|
250 |
+
# assert_equal(graph_edit_distance(G1, G2), 22)
|
251 |
+
|
252 |
+
def test_selfloops(self):
|
253 |
+
G0 = nx.Graph()
|
254 |
+
G1 = nx.Graph()
|
255 |
+
G1.add_edges_from((("A", "A"), ("A", "B")))
|
256 |
+
G2 = nx.Graph()
|
257 |
+
G2.add_edges_from((("A", "B"), ("B", "B")))
|
258 |
+
G3 = nx.Graph()
|
259 |
+
G3.add_edges_from((("A", "A"), ("A", "B"), ("B", "B")))
|
260 |
+
|
261 |
+
assert graph_edit_distance(G0, G0) == 0
|
262 |
+
assert graph_edit_distance(G0, G1) == 4
|
263 |
+
assert graph_edit_distance(G1, G0) == 4
|
264 |
+
assert graph_edit_distance(G0, G2) == 4
|
265 |
+
assert graph_edit_distance(G2, G0) == 4
|
266 |
+
assert graph_edit_distance(G0, G3) == 5
|
267 |
+
assert graph_edit_distance(G3, G0) == 5
|
268 |
+
|
269 |
+
assert graph_edit_distance(G1, G1) == 0
|
270 |
+
assert graph_edit_distance(G1, G2) == 0
|
271 |
+
assert graph_edit_distance(G2, G1) == 0
|
272 |
+
assert graph_edit_distance(G1, G3) == 1
|
273 |
+
assert graph_edit_distance(G3, G1) == 1
|
274 |
+
|
275 |
+
assert graph_edit_distance(G2, G2) == 0
|
276 |
+
assert graph_edit_distance(G2, G3) == 1
|
277 |
+
assert graph_edit_distance(G3, G2) == 1
|
278 |
+
|
279 |
+
assert graph_edit_distance(G3, G3) == 0
|
280 |
+
|
281 |
+
def test_digraph(self):
|
282 |
+
G0 = nx.DiGraph()
|
283 |
+
G1 = nx.DiGraph()
|
284 |
+
G1.add_edges_from((("A", "B"), ("B", "C"), ("C", "D"), ("D", "A")))
|
285 |
+
G2 = nx.DiGraph()
|
286 |
+
G2.add_edges_from((("A", "B"), ("B", "C"), ("C", "D"), ("A", "D")))
|
287 |
+
G3 = nx.DiGraph()
|
288 |
+
G3.add_edges_from((("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")))
|
289 |
+
|
290 |
+
assert graph_edit_distance(G0, G0) == 0
|
291 |
+
assert graph_edit_distance(G0, G1) == 8
|
292 |
+
assert graph_edit_distance(G1, G0) == 8
|
293 |
+
assert graph_edit_distance(G0, G2) == 8
|
294 |
+
assert graph_edit_distance(G2, G0) == 8
|
295 |
+
assert graph_edit_distance(G0, G3) == 8
|
296 |
+
assert graph_edit_distance(G3, G0) == 8
|
297 |
+
|
298 |
+
assert graph_edit_distance(G1, G1) == 0
|
299 |
+
assert graph_edit_distance(G1, G2) == 2
|
300 |
+
assert graph_edit_distance(G2, G1) == 2
|
301 |
+
assert graph_edit_distance(G1, G3) == 4
|
302 |
+
assert graph_edit_distance(G3, G1) == 4
|
303 |
+
|
304 |
+
assert graph_edit_distance(G2, G2) == 0
|
305 |
+
assert graph_edit_distance(G2, G3) == 2
|
306 |
+
assert graph_edit_distance(G3, G2) == 2
|
307 |
+
|
308 |
+
assert graph_edit_distance(G3, G3) == 0
|
309 |
+
|
310 |
+
def test_multigraph(self):
|
311 |
+
G0 = nx.MultiGraph()
|
312 |
+
G1 = nx.MultiGraph()
|
313 |
+
G1.add_edges_from((("A", "B"), ("B", "C"), ("A", "C")))
|
314 |
+
G2 = nx.MultiGraph()
|
315 |
+
G2.add_edges_from((("A", "B"), ("B", "C"), ("B", "C"), ("A", "C")))
|
316 |
+
G3 = nx.MultiGraph()
|
317 |
+
G3.add_edges_from((("A", "B"), ("B", "C"), ("A", "C"), ("A", "C"), ("A", "C")))
|
318 |
+
|
319 |
+
assert graph_edit_distance(G0, G0) == 0
|
320 |
+
assert graph_edit_distance(G0, G1) == 6
|
321 |
+
assert graph_edit_distance(G1, G0) == 6
|
322 |
+
assert graph_edit_distance(G0, G2) == 7
|
323 |
+
assert graph_edit_distance(G2, G0) == 7
|
324 |
+
assert graph_edit_distance(G0, G3) == 8
|
325 |
+
assert graph_edit_distance(G3, G0) == 8
|
326 |
+
|
327 |
+
assert graph_edit_distance(G1, G1) == 0
|
328 |
+
assert graph_edit_distance(G1, G2) == 1
|
329 |
+
assert graph_edit_distance(G2, G1) == 1
|
330 |
+
assert graph_edit_distance(G1, G3) == 2
|
331 |
+
assert graph_edit_distance(G3, G1) == 2
|
332 |
+
|
333 |
+
assert graph_edit_distance(G2, G2) == 0
|
334 |
+
assert graph_edit_distance(G2, G3) == 1
|
335 |
+
assert graph_edit_distance(G3, G2) == 1
|
336 |
+
|
337 |
+
assert graph_edit_distance(G3, G3) == 0
|
338 |
+
|
339 |
+
def test_multidigraph(self):
|
340 |
+
G1 = nx.MultiDiGraph()
|
341 |
+
G1.add_edges_from(
|
342 |
+
(
|
343 |
+
("hardware", "kernel"),
|
344 |
+
("kernel", "hardware"),
|
345 |
+
("kernel", "userspace"),
|
346 |
+
("userspace", "kernel"),
|
347 |
+
)
|
348 |
+
)
|
349 |
+
G2 = nx.MultiDiGraph()
|
350 |
+
G2.add_edges_from(
|
351 |
+
(
|
352 |
+
("winter", "spring"),
|
353 |
+
("spring", "summer"),
|
354 |
+
("summer", "autumn"),
|
355 |
+
("autumn", "winter"),
|
356 |
+
)
|
357 |
+
)
|
358 |
+
|
359 |
+
assert graph_edit_distance(G1, G2) == 5
|
360 |
+
assert graph_edit_distance(G2, G1) == 5
|
361 |
+
|
362 |
+
# by https://github.com/jfbeaumont
|
363 |
+
def testCopy(self):
|
364 |
+
G = nx.Graph()
|
365 |
+
G.add_node("A", label="A")
|
366 |
+
G.add_node("B", label="B")
|
367 |
+
G.add_edge("A", "B", label="a-b")
|
368 |
+
assert (
|
369 |
+
graph_edit_distance(G, G.copy(), node_match=nmatch, edge_match=ematch) == 0
|
370 |
+
)
|
371 |
+
|
372 |
+
def testSame(self):
|
373 |
+
G1 = nx.Graph()
|
374 |
+
G1.add_node("A", label="A")
|
375 |
+
G1.add_node("B", label="B")
|
376 |
+
G1.add_edge("A", "B", label="a-b")
|
377 |
+
G2 = nx.Graph()
|
378 |
+
G2.add_node("A", label="A")
|
379 |
+
G2.add_node("B", label="B")
|
380 |
+
G2.add_edge("A", "B", label="a-b")
|
381 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 0
|
382 |
+
|
383 |
+
def testOneEdgeLabelDiff(self):
|
384 |
+
G1 = nx.Graph()
|
385 |
+
G1.add_node("A", label="A")
|
386 |
+
G1.add_node("B", label="B")
|
387 |
+
G1.add_edge("A", "B", label="a-b")
|
388 |
+
G2 = nx.Graph()
|
389 |
+
G2.add_node("A", label="A")
|
390 |
+
G2.add_node("B", label="B")
|
391 |
+
G2.add_edge("A", "B", label="bad")
|
392 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
|
393 |
+
|
394 |
+
def testOneNodeLabelDiff(self):
|
395 |
+
G1 = nx.Graph()
|
396 |
+
G1.add_node("A", label="A")
|
397 |
+
G1.add_node("B", label="B")
|
398 |
+
G1.add_edge("A", "B", label="a-b")
|
399 |
+
G2 = nx.Graph()
|
400 |
+
G2.add_node("A", label="Z")
|
401 |
+
G2.add_node("B", label="B")
|
402 |
+
G2.add_edge("A", "B", label="a-b")
|
403 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
|
404 |
+
|
405 |
+
def testOneExtraNode(self):
|
406 |
+
G1 = nx.Graph()
|
407 |
+
G1.add_node("A", label="A")
|
408 |
+
G1.add_node("B", label="B")
|
409 |
+
G1.add_edge("A", "B", label="a-b")
|
410 |
+
G2 = nx.Graph()
|
411 |
+
G2.add_node("A", label="A")
|
412 |
+
G2.add_node("B", label="B")
|
413 |
+
G2.add_edge("A", "B", label="a-b")
|
414 |
+
G2.add_node("C", label="C")
|
415 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
|
416 |
+
|
417 |
+
def testOneExtraEdge(self):
|
418 |
+
G1 = nx.Graph()
|
419 |
+
G1.add_node("A", label="A")
|
420 |
+
G1.add_node("B", label="B")
|
421 |
+
G1.add_node("C", label="C")
|
422 |
+
G1.add_node("C", label="C")
|
423 |
+
G1.add_edge("A", "B", label="a-b")
|
424 |
+
G2 = nx.Graph()
|
425 |
+
G2.add_node("A", label="A")
|
426 |
+
G2.add_node("B", label="B")
|
427 |
+
G2.add_node("C", label="C")
|
428 |
+
G2.add_edge("A", "B", label="a-b")
|
429 |
+
G2.add_edge("A", "C", label="a-c")
|
430 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
|
431 |
+
|
432 |
+
def testOneExtraNodeAndEdge(self):
|
433 |
+
G1 = nx.Graph()
|
434 |
+
G1.add_node("A", label="A")
|
435 |
+
G1.add_node("B", label="B")
|
436 |
+
G1.add_edge("A", "B", label="a-b")
|
437 |
+
G2 = nx.Graph()
|
438 |
+
G2.add_node("A", label="A")
|
439 |
+
G2.add_node("B", label="B")
|
440 |
+
G2.add_node("C", label="C")
|
441 |
+
G2.add_edge("A", "B", label="a-b")
|
442 |
+
G2.add_edge("A", "C", label="a-c")
|
443 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 2
|
444 |
+
|
445 |
+
def testGraph1(self):
|
446 |
+
G1 = getCanonical()
|
447 |
+
G2 = nx.Graph()
|
448 |
+
G2.add_node("A", label="A")
|
449 |
+
G2.add_node("B", label="B")
|
450 |
+
G2.add_node("D", label="D")
|
451 |
+
G2.add_node("E", label="E")
|
452 |
+
G2.add_edge("A", "B", label="a-b")
|
453 |
+
G2.add_edge("B", "D", label="b-d")
|
454 |
+
G2.add_edge("D", "E", label="d-e")
|
455 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 3
|
456 |
+
|
457 |
+
def testGraph2(self):
|
458 |
+
G1 = getCanonical()
|
459 |
+
G2 = nx.Graph()
|
460 |
+
G2.add_node("A", label="A")
|
461 |
+
G2.add_node("B", label="B")
|
462 |
+
G2.add_node("C", label="C")
|
463 |
+
G2.add_node("D", label="D")
|
464 |
+
G2.add_node("E", label="E")
|
465 |
+
G2.add_edge("A", "B", label="a-b")
|
466 |
+
G2.add_edge("B", "C", label="b-c")
|
467 |
+
G2.add_edge("C", "D", label="c-d")
|
468 |
+
G2.add_edge("C", "E", label="c-e")
|
469 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 4
|
470 |
+
|
471 |
+
def testGraph3(self):
|
472 |
+
G1 = getCanonical()
|
473 |
+
G2 = nx.Graph()
|
474 |
+
G2.add_node("A", label="A")
|
475 |
+
G2.add_node("B", label="B")
|
476 |
+
G2.add_node("C", label="C")
|
477 |
+
G2.add_node("D", label="D")
|
478 |
+
G2.add_node("E", label="E")
|
479 |
+
G2.add_node("F", label="F")
|
480 |
+
G2.add_node("G", label="G")
|
481 |
+
G2.add_edge("A", "C", label="a-c")
|
482 |
+
G2.add_edge("A", "D", label="a-d")
|
483 |
+
G2.add_edge("D", "E", label="d-e")
|
484 |
+
G2.add_edge("D", "F", label="d-f")
|
485 |
+
G2.add_edge("D", "G", label="d-g")
|
486 |
+
G2.add_edge("E", "B", label="e-b")
|
487 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 12
|
488 |
+
|
489 |
+
def testGraph4(self):
|
490 |
+
G1 = getCanonical()
|
491 |
+
G2 = nx.Graph()
|
492 |
+
G2.add_node("A", label="A")
|
493 |
+
G2.add_node("B", label="B")
|
494 |
+
G2.add_node("C", label="C")
|
495 |
+
G2.add_node("D", label="D")
|
496 |
+
G2.add_edge("A", "B", label="a-b")
|
497 |
+
G2.add_edge("B", "C", label="b-c")
|
498 |
+
G2.add_edge("C", "D", label="c-d")
|
499 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 2
|
500 |
+
|
501 |
+
def testGraph4_a(self):
|
502 |
+
G1 = getCanonical()
|
503 |
+
G2 = nx.Graph()
|
504 |
+
G2.add_node("A", label="A")
|
505 |
+
G2.add_node("B", label="B")
|
506 |
+
G2.add_node("C", label="C")
|
507 |
+
G2.add_node("D", label="D")
|
508 |
+
G2.add_edge("A", "B", label="a-b")
|
509 |
+
G2.add_edge("B", "C", label="b-c")
|
510 |
+
G2.add_edge("A", "D", label="a-d")
|
511 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 2
|
512 |
+
|
513 |
+
def testGraph4_b(self):
|
514 |
+
G1 = getCanonical()
|
515 |
+
G2 = nx.Graph()
|
516 |
+
G2.add_node("A", label="A")
|
517 |
+
G2.add_node("B", label="B")
|
518 |
+
G2.add_node("C", label="C")
|
519 |
+
G2.add_node("D", label="D")
|
520 |
+
G2.add_edge("A", "B", label="a-b")
|
521 |
+
G2.add_edge("B", "C", label="b-c")
|
522 |
+
G2.add_edge("B", "D", label="bad")
|
523 |
+
assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
|
524 |
+
|
525 |
+
# note: nx.simrank_similarity_numpy not included because returns np.array
|
526 |
+
simrank_algs = [
|
527 |
+
nx.simrank_similarity,
|
528 |
+
nx.algorithms.similarity._simrank_similarity_python,
|
529 |
+
]
|
530 |
+
|
531 |
+
@pytest.mark.parametrize("simrank_similarity", simrank_algs)
|
532 |
+
def test_simrank_no_source_no_target(self, simrank_similarity):
|
533 |
+
G = nx.cycle_graph(5)
|
534 |
+
expected = {
|
535 |
+
0: {
|
536 |
+
0: 1,
|
537 |
+
1: 0.3951219505902448,
|
538 |
+
2: 0.5707317069281646,
|
539 |
+
3: 0.5707317069281646,
|
540 |
+
4: 0.3951219505902449,
|
541 |
+
},
|
542 |
+
1: {
|
543 |
+
0: 0.3951219505902448,
|
544 |
+
1: 1,
|
545 |
+
2: 0.3951219505902449,
|
546 |
+
3: 0.5707317069281646,
|
547 |
+
4: 0.5707317069281646,
|
548 |
+
},
|
549 |
+
2: {
|
550 |
+
0: 0.5707317069281646,
|
551 |
+
1: 0.3951219505902449,
|
552 |
+
2: 1,
|
553 |
+
3: 0.3951219505902449,
|
554 |
+
4: 0.5707317069281646,
|
555 |
+
},
|
556 |
+
3: {
|
557 |
+
0: 0.5707317069281646,
|
558 |
+
1: 0.5707317069281646,
|
559 |
+
2: 0.3951219505902449,
|
560 |
+
3: 1,
|
561 |
+
4: 0.3951219505902449,
|
562 |
+
},
|
563 |
+
4: {
|
564 |
+
0: 0.3951219505902449,
|
565 |
+
1: 0.5707317069281646,
|
566 |
+
2: 0.5707317069281646,
|
567 |
+
3: 0.3951219505902449,
|
568 |
+
4: 1,
|
569 |
+
},
|
570 |
+
}
|
571 |
+
actual = simrank_similarity(G)
|
572 |
+
for k, v in expected.items():
|
573 |
+
assert v == pytest.approx(actual[k], abs=1e-2)
|
574 |
+
|
575 |
+
# For a DiGraph test, use the first graph from the paper cited in
|
576 |
+
# the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
|
577 |
+
G = nx.DiGraph()
|
578 |
+
G.add_node(0, label="Univ")
|
579 |
+
G.add_node(1, label="ProfA")
|
580 |
+
G.add_node(2, label="ProfB")
|
581 |
+
G.add_node(3, label="StudentA")
|
582 |
+
G.add_node(4, label="StudentB")
|
583 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
|
584 |
+
|
585 |
+
expected = {
|
586 |
+
0: {0: 1, 1: 0.0, 2: 0.1323363991265798, 3: 0.0, 4: 0.03387811817640443},
|
587 |
+
1: {0: 0.0, 1: 1, 2: 0.4135512472705618, 3: 0.0, 4: 0.10586911930126384},
|
588 |
+
2: {
|
589 |
+
0: 0.1323363991265798,
|
590 |
+
1: 0.4135512472705618,
|
591 |
+
2: 1,
|
592 |
+
3: 0.04234764772050554,
|
593 |
+
4: 0.08822426608438655,
|
594 |
+
},
|
595 |
+
3: {0: 0.0, 1: 0.0, 2: 0.04234764772050554, 3: 1, 4: 0.3308409978164495},
|
596 |
+
4: {
|
597 |
+
0: 0.03387811817640443,
|
598 |
+
1: 0.10586911930126384,
|
599 |
+
2: 0.08822426608438655,
|
600 |
+
3: 0.3308409978164495,
|
601 |
+
4: 1,
|
602 |
+
},
|
603 |
+
}
|
604 |
+
# Use the importance_factor from the paper to get the same numbers.
|
605 |
+
actual = simrank_similarity(G, importance_factor=0.8)
|
606 |
+
for k, v in expected.items():
|
607 |
+
assert v == pytest.approx(actual[k], abs=1e-2)
|
608 |
+
|
609 |
+
@pytest.mark.parametrize("simrank_similarity", simrank_algs)
|
610 |
+
def test_simrank_source_no_target(self, simrank_similarity):
|
611 |
+
G = nx.cycle_graph(5)
|
612 |
+
expected = {
|
613 |
+
0: 1,
|
614 |
+
1: 0.3951219505902448,
|
615 |
+
2: 0.5707317069281646,
|
616 |
+
3: 0.5707317069281646,
|
617 |
+
4: 0.3951219505902449,
|
618 |
+
}
|
619 |
+
actual = simrank_similarity(G, source=0)
|
620 |
+
assert expected == pytest.approx(actual, abs=1e-2)
|
621 |
+
|
622 |
+
# For a DiGraph test, use the first graph from the paper cited in
|
623 |
+
# the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
|
624 |
+
G = nx.DiGraph()
|
625 |
+
G.add_node(0, label="Univ")
|
626 |
+
G.add_node(1, label="ProfA")
|
627 |
+
G.add_node(2, label="ProfB")
|
628 |
+
G.add_node(3, label="StudentA")
|
629 |
+
G.add_node(4, label="StudentB")
|
630 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
|
631 |
+
|
632 |
+
expected = {0: 1, 1: 0.0, 2: 0.1323363991265798, 3: 0.0, 4: 0.03387811817640443}
|
633 |
+
# Use the importance_factor from the paper to get the same numbers.
|
634 |
+
actual = simrank_similarity(G, importance_factor=0.8, source=0)
|
635 |
+
assert expected == pytest.approx(actual, abs=1e-2)
|
636 |
+
|
637 |
+
@pytest.mark.parametrize("simrank_similarity", simrank_algs)
|
638 |
+
def test_simrank_noninteger_nodes(self, simrank_similarity):
|
639 |
+
G = nx.cycle_graph(5)
|
640 |
+
G = nx.relabel_nodes(G, dict(enumerate("abcde")))
|
641 |
+
expected = {
|
642 |
+
"a": 1,
|
643 |
+
"b": 0.3951219505902448,
|
644 |
+
"c": 0.5707317069281646,
|
645 |
+
"d": 0.5707317069281646,
|
646 |
+
"e": 0.3951219505902449,
|
647 |
+
}
|
648 |
+
actual = simrank_similarity(G, source="a")
|
649 |
+
assert expected == pytest.approx(actual, abs=1e-2)
|
650 |
+
|
651 |
+
# For a DiGraph test, use the first graph from the paper cited in
|
652 |
+
# the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
|
653 |
+
G = nx.DiGraph()
|
654 |
+
G.add_node(0, label="Univ")
|
655 |
+
G.add_node(1, label="ProfA")
|
656 |
+
G.add_node(2, label="ProfB")
|
657 |
+
G.add_node(3, label="StudentA")
|
658 |
+
G.add_node(4, label="StudentB")
|
659 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
|
660 |
+
node_labels = dict(enumerate(nx.get_node_attributes(G, "label").values()))
|
661 |
+
G = nx.relabel_nodes(G, node_labels)
|
662 |
+
|
663 |
+
expected = {
|
664 |
+
"Univ": 1,
|
665 |
+
"ProfA": 0.0,
|
666 |
+
"ProfB": 0.1323363991265798,
|
667 |
+
"StudentA": 0.0,
|
668 |
+
"StudentB": 0.03387811817640443,
|
669 |
+
}
|
670 |
+
# Use the importance_factor from the paper to get the same numbers.
|
671 |
+
actual = simrank_similarity(G, importance_factor=0.8, source="Univ")
|
672 |
+
assert expected == pytest.approx(actual, abs=1e-2)
|
673 |
+
|
674 |
+
@pytest.mark.parametrize("simrank_similarity", simrank_algs)
|
675 |
+
def test_simrank_source_and_target(self, simrank_similarity):
|
676 |
+
G = nx.cycle_graph(5)
|
677 |
+
expected = 1
|
678 |
+
actual = simrank_similarity(G, source=0, target=0)
|
679 |
+
assert expected == pytest.approx(actual, abs=1e-2)
|
680 |
+
|
681 |
+
# For a DiGraph test, use the first graph from the paper cited in
|
682 |
+
# the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
|
683 |
+
G = nx.DiGraph()
|
684 |
+
G.add_node(0, label="Univ")
|
685 |
+
G.add_node(1, label="ProfA")
|
686 |
+
G.add_node(2, label="ProfB")
|
687 |
+
G.add_node(3, label="StudentA")
|
688 |
+
G.add_node(4, label="StudentB")
|
689 |
+
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
|
690 |
+
|
691 |
+
expected = 0.1323363991265798
|
692 |
+
# Use the importance_factor from the paper to get the same numbers.
|
693 |
+
# Use the pair (0,2) because (0,0) and (0,1) have trivial results.
|
694 |
+
actual = simrank_similarity(G, importance_factor=0.8, source=0, target=2)
|
695 |
+
assert expected == pytest.approx(actual, abs=1e-5)
|
696 |
+
|
697 |
+
@pytest.mark.parametrize("alg", simrank_algs)
|
698 |
+
def test_simrank_max_iterations(self, alg):
|
699 |
+
G = nx.cycle_graph(5)
|
700 |
+
pytest.raises(nx.ExceededMaxIterations, alg, G, max_iterations=10)
|
701 |
+
|
702 |
+
def test_simrank_source_not_found(self):
|
703 |
+
G = nx.cycle_graph(5)
|
704 |
+
with pytest.raises(nx.NodeNotFound, match="Source node 10 not in G"):
|
705 |
+
nx.simrank_similarity(G, source=10)
|
706 |
+
|
707 |
+
def test_simrank_target_not_found(self):
|
708 |
+
G = nx.cycle_graph(5)
|
709 |
+
with pytest.raises(nx.NodeNotFound, match="Target node 10 not in G"):
|
710 |
+
nx.simrank_similarity(G, target=10)
|
711 |
+
|
712 |
+
def test_simrank_between_versions(self):
|
713 |
+
G = nx.cycle_graph(5)
|
714 |
+
# _python tolerance 1e-4
|
715 |
+
expected_python_tol4 = {
|
716 |
+
0: 1,
|
717 |
+
1: 0.394512499239852,
|
718 |
+
2: 0.5703550452791322,
|
719 |
+
3: 0.5703550452791323,
|
720 |
+
4: 0.394512499239852,
|
721 |
+
}
|
722 |
+
# _numpy tolerance 1e-4
|
723 |
+
expected_numpy_tol4 = {
|
724 |
+
0: 1.0,
|
725 |
+
1: 0.3947180735764555,
|
726 |
+
2: 0.570482097206368,
|
727 |
+
3: 0.570482097206368,
|
728 |
+
4: 0.3947180735764555,
|
729 |
+
}
|
730 |
+
actual = nx.simrank_similarity(G, source=0)
|
731 |
+
assert expected_numpy_tol4 == pytest.approx(actual, abs=1e-7)
|
732 |
+
# versions differ at 1e-4 level but equal at 1e-3
|
733 |
+
assert expected_python_tol4 != pytest.approx(actual, abs=1e-4)
|
734 |
+
assert expected_python_tol4 == pytest.approx(actual, abs=1e-3)
|
735 |
+
|
736 |
+
actual = nx.similarity._simrank_similarity_python(G, source=0)
|
737 |
+
assert expected_python_tol4 == pytest.approx(actual, abs=1e-7)
|
738 |
+
# versions differ at 1e-4 level but equal at 1e-3
|
739 |
+
assert expected_numpy_tol4 != pytest.approx(actual, abs=1e-4)
|
740 |
+
assert expected_numpy_tol4 == pytest.approx(actual, abs=1e-3)
|
741 |
+
|
742 |
+
def test_simrank_numpy_no_source_no_target(self):
|
743 |
+
G = nx.cycle_graph(5)
|
744 |
+
expected = np.array(
|
745 |
+
[
|
746 |
+
[
|
747 |
+
1.0,
|
748 |
+
0.3947180735764555,
|
749 |
+
0.570482097206368,
|
750 |
+
0.570482097206368,
|
751 |
+
0.3947180735764555,
|
752 |
+
],
|
753 |
+
[
|
754 |
+
0.3947180735764555,
|
755 |
+
1.0,
|
756 |
+
0.3947180735764555,
|
757 |
+
0.570482097206368,
|
758 |
+
0.570482097206368,
|
759 |
+
],
|
760 |
+
[
|
761 |
+
0.570482097206368,
|
762 |
+
0.3947180735764555,
|
763 |
+
1.0,
|
764 |
+
0.3947180735764555,
|
765 |
+
0.570482097206368,
|
766 |
+
],
|
767 |
+
[
|
768 |
+
0.570482097206368,
|
769 |
+
0.570482097206368,
|
770 |
+
0.3947180735764555,
|
771 |
+
1.0,
|
772 |
+
0.3947180735764555,
|
773 |
+
],
|
774 |
+
[
|
775 |
+
0.3947180735764555,
|
776 |
+
0.570482097206368,
|
777 |
+
0.570482097206368,
|
778 |
+
0.3947180735764555,
|
779 |
+
1.0,
|
780 |
+
],
|
781 |
+
]
|
782 |
+
)
|
783 |
+
actual = nx.similarity._simrank_similarity_numpy(G)
|
784 |
+
np.testing.assert_allclose(expected, actual, atol=1e-7)
|
785 |
+
|
786 |
+
def test_simrank_numpy_source_no_target(self):
|
787 |
+
G = nx.cycle_graph(5)
|
788 |
+
expected = np.array(
|
789 |
+
[
|
790 |
+
1.0,
|
791 |
+
0.3947180735764555,
|
792 |
+
0.570482097206368,
|
793 |
+
0.570482097206368,
|
794 |
+
0.3947180735764555,
|
795 |
+
]
|
796 |
+
)
|
797 |
+
actual = nx.similarity._simrank_similarity_numpy(G, source=0)
|
798 |
+
np.testing.assert_allclose(expected, actual, atol=1e-7)
|
799 |
+
|
800 |
+
def test_simrank_numpy_source_and_target(self):
|
801 |
+
G = nx.cycle_graph(5)
|
802 |
+
expected = 1.0
|
803 |
+
actual = nx.similarity._simrank_similarity_numpy(G, source=0, target=0)
|
804 |
+
np.testing.assert_allclose(expected, actual, atol=1e-7)
|
805 |
+
|
806 |
+
def test_panther_similarity_unweighted(self):
|
807 |
+
np.random.seed(42)
|
808 |
+
|
809 |
+
G = nx.Graph()
|
810 |
+
G.add_edge(0, 1)
|
811 |
+
G.add_edge(0, 2)
|
812 |
+
G.add_edge(0, 3)
|
813 |
+
G.add_edge(1, 2)
|
814 |
+
G.add_edge(2, 4)
|
815 |
+
expected = {3: 0.5, 2: 0.5, 1: 0.5, 4: 0.125}
|
816 |
+
sim = nx.panther_similarity(G, 0, path_length=2)
|
817 |
+
assert sim == expected
|
818 |
+
|
819 |
+
def test_panther_similarity_weighted(self):
|
820 |
+
np.random.seed(42)
|
821 |
+
|
822 |
+
G = nx.Graph()
|
823 |
+
G.add_edge("v1", "v2", w=5)
|
824 |
+
G.add_edge("v1", "v3", w=1)
|
825 |
+
G.add_edge("v1", "v4", w=2)
|
826 |
+
G.add_edge("v2", "v3", w=0.1)
|
827 |
+
G.add_edge("v3", "v5", w=1)
|
828 |
+
expected = {"v3": 0.75, "v4": 0.5, "v2": 0.5, "v5": 0.25}
|
829 |
+
sim = nx.panther_similarity(G, "v1", path_length=2, weight="w")
|
830 |
+
assert sim == expected
|
831 |
+
|
832 |
+
def test_panther_similarity_source_not_found(self):
|
833 |
+
G = nx.Graph()
|
834 |
+
G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 2), (2, 4)])
|
835 |
+
with pytest.raises(nx.NodeNotFound, match="Source node 10 not in G"):
|
836 |
+
nx.panther_similarity(G, source=10)
|
837 |
+
|
838 |
+
def test_panther_similarity_isolated(self):
|
839 |
+
G = nx.Graph()
|
840 |
+
G.add_nodes_from(range(5))
|
841 |
+
with pytest.raises(
|
842 |
+
nx.NetworkXUnfeasible,
|
843 |
+
match="Panther similarity is not defined for the isolated source node 1.",
|
844 |
+
):
|
845 |
+
nx.panther_similarity(G, source=1)
|
846 |
+
|
847 |
+
def test_generate_random_paths_unweighted(self):
|
848 |
+
index_map = {}
|
849 |
+
num_paths = 10
|
850 |
+
path_length = 2
|
851 |
+
G = nx.Graph()
|
852 |
+
G.add_edge(0, 1)
|
853 |
+
G.add_edge(0, 2)
|
854 |
+
G.add_edge(0, 3)
|
855 |
+
G.add_edge(1, 2)
|
856 |
+
G.add_edge(2, 4)
|
857 |
+
paths = nx.generate_random_paths(
|
858 |
+
G, num_paths, path_length=path_length, index_map=index_map, seed=42
|
859 |
+
)
|
860 |
+
expected_paths = [
|
861 |
+
[3, 0, 3],
|
862 |
+
[4, 2, 1],
|
863 |
+
[2, 1, 0],
|
864 |
+
[2, 0, 3],
|
865 |
+
[3, 0, 1],
|
866 |
+
[3, 0, 1],
|
867 |
+
[4, 2, 0],
|
868 |
+
[2, 1, 0],
|
869 |
+
[3, 0, 2],
|
870 |
+
[2, 1, 2],
|
871 |
+
]
|
872 |
+
expected_map = {
|
873 |
+
0: {0, 2, 3, 4, 5, 6, 7, 8},
|
874 |
+
1: {1, 2, 4, 5, 7, 9},
|
875 |
+
2: {1, 2, 3, 6, 7, 8, 9},
|
876 |
+
3: {0, 3, 4, 5, 8},
|
877 |
+
4: {1, 6},
|
878 |
+
}
|
879 |
+
|
880 |
+
assert expected_paths == list(paths)
|
881 |
+
assert expected_map == index_map
|
882 |
+
|
883 |
+
def test_generate_random_paths_weighted(self):
|
884 |
+
np.random.seed(42)
|
885 |
+
|
886 |
+
index_map = {}
|
887 |
+
num_paths = 10
|
888 |
+
path_length = 6
|
889 |
+
G = nx.Graph()
|
890 |
+
G.add_edge("a", "b", weight=0.6)
|
891 |
+
G.add_edge("a", "c", weight=0.2)
|
892 |
+
G.add_edge("c", "d", weight=0.1)
|
893 |
+
G.add_edge("c", "e", weight=0.7)
|
894 |
+
G.add_edge("c", "f", weight=0.9)
|
895 |
+
G.add_edge("a", "d", weight=0.3)
|
896 |
+
paths = nx.generate_random_paths(
|
897 |
+
G, num_paths, path_length=path_length, index_map=index_map
|
898 |
+
)
|
899 |
+
|
900 |
+
expected_paths = [
|
901 |
+
["d", "c", "f", "c", "d", "a", "b"],
|
902 |
+
["e", "c", "f", "c", "f", "c", "e"],
|
903 |
+
["d", "a", "b", "a", "b", "a", "c"],
|
904 |
+
["b", "a", "d", "a", "b", "a", "b"],
|
905 |
+
["d", "a", "b", "a", "b", "a", "d"],
|
906 |
+
["d", "a", "b", "a", "b", "a", "c"],
|
907 |
+
["d", "a", "b", "a", "b", "a", "b"],
|
908 |
+
["f", "c", "f", "c", "f", "c", "e"],
|
909 |
+
["d", "a", "d", "a", "b", "a", "b"],
|
910 |
+
["e", "c", "f", "c", "e", "c", "d"],
|
911 |
+
]
|
912 |
+
expected_map = {
|
913 |
+
"d": {0, 2, 3, 4, 5, 6, 8, 9},
|
914 |
+
"c": {0, 1, 2, 5, 7, 9},
|
915 |
+
"f": {0, 1, 9, 7},
|
916 |
+
"a": {0, 2, 3, 4, 5, 6, 8},
|
917 |
+
"b": {0, 2, 3, 4, 5, 6, 8},
|
918 |
+
"e": {1, 9, 7},
|
919 |
+
}
|
920 |
+
|
921 |
+
assert expected_paths == list(paths)
|
922 |
+
assert expected_map == index_map
|
923 |
+
|
924 |
+
def test_symmetry_with_custom_matching(self):
|
925 |
+
print("G2 is edge (a,b) and G3 is edge (a,a)")
|
926 |
+
print("but node order for G2 is (a,b) while for G3 it is (b,a)")
|
927 |
+
|
928 |
+
a, b = "A", "B"
|
929 |
+
G2 = nx.Graph()
|
930 |
+
G2.add_nodes_from((a, b))
|
931 |
+
G2.add_edges_from([(a, b)])
|
932 |
+
G3 = nx.Graph()
|
933 |
+
G3.add_nodes_from((b, a))
|
934 |
+
G3.add_edges_from([(a, a)])
|
935 |
+
for G in (G2, G3):
|
936 |
+
for n in G:
|
937 |
+
G.nodes[n]["attr"] = n
|
938 |
+
for e in G.edges:
|
939 |
+
G.edges[e]["attr"] = e
|
940 |
+
match = lambda x, y: x == y
|
941 |
+
|
942 |
+
print("Starting G2 to G3 GED calculation")
|
943 |
+
assert nx.graph_edit_distance(G2, G3, node_match=match, edge_match=match) == 1
|
944 |
+
|
945 |
+
print("Starting G3 to G2 GED calculation")
|
946 |
+
assert nx.graph_edit_distance(G3, G2, node_match=match, edge_match=match) == 1
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_simple_paths.py
ADDED
@@ -0,0 +1,792 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
7 |
+
from networkx.algorithms.simple_paths import (
|
8 |
+
_bidirectional_dijkstra,
|
9 |
+
_bidirectional_shortest_path,
|
10 |
+
)
|
11 |
+
from networkx.utils import arbitrary_element, pairwise
|
12 |
+
|
13 |
+
|
14 |
+
class TestIsSimplePath:
|
15 |
+
"""Unit tests for the
|
16 |
+
:func:`networkx.algorithms.simple_paths.is_simple_path` function.
|
17 |
+
|
18 |
+
"""
|
19 |
+
|
20 |
+
def test_empty_list(self):
|
21 |
+
"""Tests that the empty list is not a valid path, since there
|
22 |
+
should be a one-to-one correspondence between paths as lists of
|
23 |
+
nodes and paths as lists of edges.
|
24 |
+
|
25 |
+
"""
|
26 |
+
G = nx.trivial_graph()
|
27 |
+
assert not nx.is_simple_path(G, [])
|
28 |
+
|
29 |
+
def test_trivial_path(self):
|
30 |
+
"""Tests that the trivial path, a path of length one, is
|
31 |
+
considered a simple path in a graph.
|
32 |
+
|
33 |
+
"""
|
34 |
+
G = nx.trivial_graph()
|
35 |
+
assert nx.is_simple_path(G, [0])
|
36 |
+
|
37 |
+
def test_trivial_nonpath(self):
|
38 |
+
"""Tests that a list whose sole element is an object not in the
|
39 |
+
graph is not considered a simple path.
|
40 |
+
|
41 |
+
"""
|
42 |
+
G = nx.trivial_graph()
|
43 |
+
assert not nx.is_simple_path(G, ["not a node"])
|
44 |
+
|
45 |
+
def test_simple_path(self):
|
46 |
+
G = nx.path_graph(2)
|
47 |
+
assert nx.is_simple_path(G, [0, 1])
|
48 |
+
|
49 |
+
def test_non_simple_path(self):
|
50 |
+
G = nx.path_graph(2)
|
51 |
+
assert not nx.is_simple_path(G, [0, 1, 0])
|
52 |
+
|
53 |
+
def test_cycle(self):
|
54 |
+
G = nx.cycle_graph(3)
|
55 |
+
assert not nx.is_simple_path(G, [0, 1, 2, 0])
|
56 |
+
|
57 |
+
def test_missing_node(self):
|
58 |
+
G = nx.path_graph(2)
|
59 |
+
assert not nx.is_simple_path(G, [0, 2])
|
60 |
+
|
61 |
+
def test_missing_starting_node(self):
|
62 |
+
G = nx.path_graph(2)
|
63 |
+
assert not nx.is_simple_path(G, [2, 0])
|
64 |
+
|
65 |
+
def test_directed_path(self):
|
66 |
+
G = nx.DiGraph([(0, 1), (1, 2)])
|
67 |
+
assert nx.is_simple_path(G, [0, 1, 2])
|
68 |
+
|
69 |
+
def test_directed_non_path(self):
|
70 |
+
G = nx.DiGraph([(0, 1), (1, 2)])
|
71 |
+
assert not nx.is_simple_path(G, [2, 1, 0])
|
72 |
+
|
73 |
+
def test_directed_cycle(self):
|
74 |
+
G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
|
75 |
+
assert not nx.is_simple_path(G, [0, 1, 2, 0])
|
76 |
+
|
77 |
+
def test_multigraph(self):
|
78 |
+
G = nx.MultiGraph([(0, 1), (0, 1)])
|
79 |
+
assert nx.is_simple_path(G, [0, 1])
|
80 |
+
|
81 |
+
def test_multidigraph(self):
|
82 |
+
G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 0), (1, 0)])
|
83 |
+
assert nx.is_simple_path(G, [0, 1])
|
84 |
+
|
85 |
+
|
86 |
+
# Tests for all_simple_paths
|
87 |
+
def test_all_simple_paths():
|
88 |
+
G = nx.path_graph(4)
|
89 |
+
paths = nx.all_simple_paths(G, 0, 3)
|
90 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2, 3)}
|
91 |
+
|
92 |
+
|
93 |
+
def test_all_simple_paths_with_two_targets_emits_two_paths():
|
94 |
+
G = nx.path_graph(4)
|
95 |
+
G.add_edge(2, 4)
|
96 |
+
paths = nx.all_simple_paths(G, 0, [3, 4])
|
97 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
|
98 |
+
|
99 |
+
|
100 |
+
def test_digraph_all_simple_paths_with_two_targets_emits_two_paths():
|
101 |
+
G = nx.path_graph(4, create_using=nx.DiGraph())
|
102 |
+
G.add_edge(2, 4)
|
103 |
+
paths = nx.all_simple_paths(G, 0, [3, 4])
|
104 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
|
105 |
+
|
106 |
+
|
107 |
+
def test_all_simple_paths_with_two_targets_cutoff():
|
108 |
+
G = nx.path_graph(4)
|
109 |
+
G.add_edge(2, 4)
|
110 |
+
paths = nx.all_simple_paths(G, 0, [3, 4], cutoff=3)
|
111 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
|
112 |
+
|
113 |
+
|
114 |
+
def test_digraph_all_simple_paths_with_two_targets_cutoff():
|
115 |
+
G = nx.path_graph(4, create_using=nx.DiGraph())
|
116 |
+
G.add_edge(2, 4)
|
117 |
+
paths = nx.all_simple_paths(G, 0, [3, 4], cutoff=3)
|
118 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
|
119 |
+
|
120 |
+
|
121 |
+
def test_all_simple_paths_with_two_targets_in_line_emits_two_paths():
|
122 |
+
G = nx.path_graph(4)
|
123 |
+
paths = nx.all_simple_paths(G, 0, [2, 3])
|
124 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2), (0, 1, 2, 3)}
|
125 |
+
|
126 |
+
|
127 |
+
def test_all_simple_paths_ignores_cycle():
|
128 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
129 |
+
G.add_edge(1, 3)
|
130 |
+
paths = nx.all_simple_paths(G, 0, 3)
|
131 |
+
assert {tuple(p) for p in paths} == {(0, 1, 3)}
|
132 |
+
|
133 |
+
|
134 |
+
def test_all_simple_paths_with_two_targets_inside_cycle_emits_two_paths():
|
135 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
136 |
+
G.add_edge(1, 3)
|
137 |
+
paths = nx.all_simple_paths(G, 0, [2, 3])
|
138 |
+
assert {tuple(p) for p in paths} == {(0, 1, 2), (0, 1, 3)}
|
139 |
+
|
140 |
+
|
141 |
+
def test_all_simple_paths_source_target():
|
142 |
+
G = nx.path_graph(4)
|
143 |
+
assert list(nx.all_simple_paths(G, 1, 1)) == [[1]]
|
144 |
+
|
145 |
+
|
146 |
+
def test_all_simple_paths_cutoff():
|
147 |
+
G = nx.complete_graph(4)
|
148 |
+
paths = nx.all_simple_paths(G, 0, 1, cutoff=1)
|
149 |
+
assert {tuple(p) for p in paths} == {(0, 1)}
|
150 |
+
paths = nx.all_simple_paths(G, 0, 1, cutoff=2)
|
151 |
+
assert {tuple(p) for p in paths} == {(0, 1), (0, 2, 1), (0, 3, 1)}
|
152 |
+
|
153 |
+
|
154 |
+
def test_all_simple_paths_on_non_trivial_graph():
|
155 |
+
"""you may need to draw this graph to make sure it is reasonable"""
|
156 |
+
G = nx.path_graph(5, create_using=nx.DiGraph())
|
157 |
+
G.add_edges_from([(0, 5), (1, 5), (1, 3), (5, 4), (4, 2), (4, 3)])
|
158 |
+
paths = nx.all_simple_paths(G, 1, [2, 3])
|
159 |
+
assert {tuple(p) for p in paths} == {
|
160 |
+
(1, 2),
|
161 |
+
(1, 3, 4, 2),
|
162 |
+
(1, 5, 4, 2),
|
163 |
+
(1, 3),
|
164 |
+
(1, 2, 3),
|
165 |
+
(1, 5, 4, 3),
|
166 |
+
(1, 5, 4, 2, 3),
|
167 |
+
}
|
168 |
+
paths = nx.all_simple_paths(G, 1, [2, 3], cutoff=3)
|
169 |
+
assert {tuple(p) for p in paths} == {
|
170 |
+
(1, 2),
|
171 |
+
(1, 3, 4, 2),
|
172 |
+
(1, 5, 4, 2),
|
173 |
+
(1, 3),
|
174 |
+
(1, 2, 3),
|
175 |
+
(1, 5, 4, 3),
|
176 |
+
}
|
177 |
+
paths = nx.all_simple_paths(G, 1, [2, 3], cutoff=2)
|
178 |
+
assert {tuple(p) for p in paths} == {(1, 2), (1, 3), (1, 2, 3)}
|
179 |
+
|
180 |
+
|
181 |
+
def test_all_simple_paths_multigraph():
|
182 |
+
G = nx.MultiGraph([(1, 2), (1, 2)])
|
183 |
+
assert list(nx.all_simple_paths(G, 1, 1)) == [[1]]
|
184 |
+
nx.add_path(G, [3, 1, 10, 2])
|
185 |
+
paths = list(nx.all_simple_paths(G, 1, 2))
|
186 |
+
assert len(paths) == 3
|
187 |
+
assert {tuple(p) for p in paths} == {(1, 2), (1, 2), (1, 10, 2)}
|
188 |
+
|
189 |
+
|
190 |
+
def test_all_simple_paths_multigraph_with_cutoff():
|
191 |
+
G = nx.MultiGraph([(1, 2), (1, 2), (1, 10), (10, 2)])
|
192 |
+
paths = list(nx.all_simple_paths(G, 1, 2, cutoff=1))
|
193 |
+
assert len(paths) == 2
|
194 |
+
assert {tuple(p) for p in paths} == {(1, 2), (1, 2)}
|
195 |
+
|
196 |
+
# See GitHub issue #6732.
|
197 |
+
G = nx.MultiGraph([(0, 1), (0, 2)])
|
198 |
+
assert list(nx.all_simple_paths(G, 0, {1, 2}, cutoff=1)) == [[0, 1], [0, 2]]
|
199 |
+
|
200 |
+
|
201 |
+
def test_all_simple_paths_directed():
|
202 |
+
G = nx.DiGraph()
|
203 |
+
nx.add_path(G, [1, 2, 3])
|
204 |
+
nx.add_path(G, [3, 2, 1])
|
205 |
+
paths = nx.all_simple_paths(G, 1, 3)
|
206 |
+
assert {tuple(p) for p in paths} == {(1, 2, 3)}
|
207 |
+
|
208 |
+
|
209 |
+
def test_all_simple_paths_empty():
|
210 |
+
G = nx.path_graph(4)
|
211 |
+
paths = nx.all_simple_paths(G, 0, 3, cutoff=2)
|
212 |
+
assert list(paths) == []
|
213 |
+
|
214 |
+
|
215 |
+
def test_all_simple_paths_corner_cases():
|
216 |
+
assert list(nx.all_simple_paths(nx.empty_graph(2), 0, 0)) == [[0]]
|
217 |
+
assert list(nx.all_simple_paths(nx.empty_graph(2), 0, 1)) == []
|
218 |
+
assert list(nx.all_simple_paths(nx.path_graph(9), 0, 8, 0)) == []
|
219 |
+
|
220 |
+
|
221 |
+
def test_all_simple_paths_source_in_targets():
|
222 |
+
# See GitHub issue #6690.
|
223 |
+
G = nx.path_graph(3)
|
224 |
+
assert list(nx.all_simple_paths(G, 0, {0, 1, 2})) == [[0], [0, 1], [0, 1, 2]]
|
225 |
+
|
226 |
+
|
227 |
+
def hamiltonian_path(G, source):
|
228 |
+
source = arbitrary_element(G)
|
229 |
+
neighbors = set(G[source]) - {source}
|
230 |
+
n = len(G)
|
231 |
+
for target in neighbors:
|
232 |
+
for path in nx.all_simple_paths(G, source, target):
|
233 |
+
if len(path) == n:
|
234 |
+
yield path
|
235 |
+
|
236 |
+
|
237 |
+
def test_hamiltonian_path():
|
238 |
+
from itertools import permutations
|
239 |
+
|
240 |
+
G = nx.complete_graph(4)
|
241 |
+
paths = [list(p) for p in hamiltonian_path(G, 0)]
|
242 |
+
exact = [[0] + list(p) for p in permutations([1, 2, 3], 3)]
|
243 |
+
assert sorted(paths) == sorted(exact)
|
244 |
+
|
245 |
+
|
246 |
+
def test_cutoff_zero():
|
247 |
+
G = nx.complete_graph(4)
|
248 |
+
paths = nx.all_simple_paths(G, 0, 3, cutoff=0)
|
249 |
+
assert [list(p) for p in paths] == []
|
250 |
+
paths = nx.all_simple_paths(nx.MultiGraph(G), 0, 3, cutoff=0)
|
251 |
+
assert [list(p) for p in paths] == []
|
252 |
+
|
253 |
+
|
254 |
+
def test_source_missing():
|
255 |
+
with pytest.raises(nx.NodeNotFound):
|
256 |
+
G = nx.Graph()
|
257 |
+
nx.add_path(G, [1, 2, 3])
|
258 |
+
list(nx.all_simple_paths(nx.MultiGraph(G), 0, 3))
|
259 |
+
|
260 |
+
|
261 |
+
def test_target_missing():
|
262 |
+
with pytest.raises(nx.NodeNotFound):
|
263 |
+
G = nx.Graph()
|
264 |
+
nx.add_path(G, [1, 2, 3])
|
265 |
+
list(nx.all_simple_paths(nx.MultiGraph(G), 1, 4))
|
266 |
+
|
267 |
+
|
268 |
+
# Tests for all_simple_edge_paths
|
269 |
+
def test_all_simple_edge_paths():
|
270 |
+
G = nx.path_graph(4)
|
271 |
+
paths = nx.all_simple_edge_paths(G, 0, 3)
|
272 |
+
assert {tuple(p) for p in paths} == {((0, 1), (1, 2), (2, 3))}
|
273 |
+
|
274 |
+
|
275 |
+
def test_all_simple_edge_paths_empty_path():
|
276 |
+
G = nx.empty_graph(1)
|
277 |
+
assert list(nx.all_simple_edge_paths(G, 0, 0)) == [[]]
|
278 |
+
|
279 |
+
|
280 |
+
def test_all_simple_edge_paths_with_two_targets_emits_two_paths():
|
281 |
+
G = nx.path_graph(4)
|
282 |
+
G.add_edge(2, 4)
|
283 |
+
paths = nx.all_simple_edge_paths(G, 0, [3, 4])
|
284 |
+
assert {tuple(p) for p in paths} == {
|
285 |
+
((0, 1), (1, 2), (2, 3)),
|
286 |
+
((0, 1), (1, 2), (2, 4)),
|
287 |
+
}
|
288 |
+
|
289 |
+
|
290 |
+
def test_digraph_all_simple_edge_paths_with_two_targets_emits_two_paths():
|
291 |
+
G = nx.path_graph(4, create_using=nx.DiGraph())
|
292 |
+
G.add_edge(2, 4)
|
293 |
+
paths = nx.all_simple_edge_paths(G, 0, [3, 4])
|
294 |
+
assert {tuple(p) for p in paths} == {
|
295 |
+
((0, 1), (1, 2), (2, 3)),
|
296 |
+
((0, 1), (1, 2), (2, 4)),
|
297 |
+
}
|
298 |
+
|
299 |
+
|
300 |
+
def test_all_simple_edge_paths_with_two_targets_cutoff():
|
301 |
+
G = nx.path_graph(4)
|
302 |
+
G.add_edge(2, 4)
|
303 |
+
paths = nx.all_simple_edge_paths(G, 0, [3, 4], cutoff=3)
|
304 |
+
assert {tuple(p) for p in paths} == {
|
305 |
+
((0, 1), (1, 2), (2, 3)),
|
306 |
+
((0, 1), (1, 2), (2, 4)),
|
307 |
+
}
|
308 |
+
|
309 |
+
|
310 |
+
def test_digraph_all_simple_edge_paths_with_two_targets_cutoff():
|
311 |
+
G = nx.path_graph(4, create_using=nx.DiGraph())
|
312 |
+
G.add_edge(2, 4)
|
313 |
+
paths = nx.all_simple_edge_paths(G, 0, [3, 4], cutoff=3)
|
314 |
+
assert {tuple(p) for p in paths} == {
|
315 |
+
((0, 1), (1, 2), (2, 3)),
|
316 |
+
((0, 1), (1, 2), (2, 4)),
|
317 |
+
}
|
318 |
+
|
319 |
+
|
320 |
+
def test_all_simple_edge_paths_with_two_targets_in_line_emits_two_paths():
|
321 |
+
G = nx.path_graph(4)
|
322 |
+
paths = nx.all_simple_edge_paths(G, 0, [2, 3])
|
323 |
+
assert {tuple(p) for p in paths} == {((0, 1), (1, 2)), ((0, 1), (1, 2), (2, 3))}
|
324 |
+
|
325 |
+
|
326 |
+
def test_all_simple_edge_paths_ignores_cycle():
|
327 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
328 |
+
G.add_edge(1, 3)
|
329 |
+
paths = nx.all_simple_edge_paths(G, 0, 3)
|
330 |
+
assert {tuple(p) for p in paths} == {((0, 1), (1, 3))}
|
331 |
+
|
332 |
+
|
333 |
+
def test_all_simple_edge_paths_with_two_targets_inside_cycle_emits_two_paths():
|
334 |
+
G = nx.cycle_graph(3, create_using=nx.DiGraph())
|
335 |
+
G.add_edge(1, 3)
|
336 |
+
paths = nx.all_simple_edge_paths(G, 0, [2, 3])
|
337 |
+
assert {tuple(p) for p in paths} == {((0, 1), (1, 2)), ((0, 1), (1, 3))}
|
338 |
+
|
339 |
+
|
340 |
+
def test_all_simple_edge_paths_source_target():
|
341 |
+
G = nx.path_graph(4)
|
342 |
+
paths = nx.all_simple_edge_paths(G, 1, 1)
|
343 |
+
assert list(paths) == [[]]
|
344 |
+
|
345 |
+
|
346 |
+
def test_all_simple_edge_paths_cutoff():
|
347 |
+
G = nx.complete_graph(4)
|
348 |
+
paths = nx.all_simple_edge_paths(G, 0, 1, cutoff=1)
|
349 |
+
assert {tuple(p) for p in paths} == {((0, 1),)}
|
350 |
+
paths = nx.all_simple_edge_paths(G, 0, 1, cutoff=2)
|
351 |
+
assert {tuple(p) for p in paths} == {((0, 1),), ((0, 2), (2, 1)), ((0, 3), (3, 1))}
|
352 |
+
|
353 |
+
|
354 |
+
def test_all_simple_edge_paths_on_non_trivial_graph():
|
355 |
+
"""you may need to draw this graph to make sure it is reasonable"""
|
356 |
+
G = nx.path_graph(5, create_using=nx.DiGraph())
|
357 |
+
G.add_edges_from([(0, 5), (1, 5), (1, 3), (5, 4), (4, 2), (4, 3)])
|
358 |
+
paths = nx.all_simple_edge_paths(G, 1, [2, 3])
|
359 |
+
assert {tuple(p) for p in paths} == {
|
360 |
+
((1, 2),),
|
361 |
+
((1, 3), (3, 4), (4, 2)),
|
362 |
+
((1, 5), (5, 4), (4, 2)),
|
363 |
+
((1, 3),),
|
364 |
+
((1, 2), (2, 3)),
|
365 |
+
((1, 5), (5, 4), (4, 3)),
|
366 |
+
((1, 5), (5, 4), (4, 2), (2, 3)),
|
367 |
+
}
|
368 |
+
paths = nx.all_simple_edge_paths(G, 1, [2, 3], cutoff=3)
|
369 |
+
assert {tuple(p) for p in paths} == {
|
370 |
+
((1, 2),),
|
371 |
+
((1, 3), (3, 4), (4, 2)),
|
372 |
+
((1, 5), (5, 4), (4, 2)),
|
373 |
+
((1, 3),),
|
374 |
+
((1, 2), (2, 3)),
|
375 |
+
((1, 5), (5, 4), (4, 3)),
|
376 |
+
}
|
377 |
+
paths = nx.all_simple_edge_paths(G, 1, [2, 3], cutoff=2)
|
378 |
+
assert {tuple(p) for p in paths} == {((1, 2),), ((1, 3),), ((1, 2), (2, 3))}
|
379 |
+
|
380 |
+
|
381 |
+
def test_all_simple_edge_paths_multigraph():
|
382 |
+
G = nx.MultiGraph([(1, 2), (1, 2)])
|
383 |
+
paths = nx.all_simple_edge_paths(G, 1, 1)
|
384 |
+
assert list(paths) == [[]]
|
385 |
+
nx.add_path(G, [3, 1, 10, 2])
|
386 |
+
paths = list(nx.all_simple_edge_paths(G, 1, 2))
|
387 |
+
assert len(paths) == 3
|
388 |
+
assert {tuple(p) for p in paths} == {
|
389 |
+
((1, 2, 0),),
|
390 |
+
((1, 2, 1),),
|
391 |
+
((1, 10, 0), (10, 2, 0)),
|
392 |
+
}
|
393 |
+
|
394 |
+
|
395 |
+
def test_all_simple_edge_paths_multigraph_with_cutoff():
|
396 |
+
G = nx.MultiGraph([(1, 2), (1, 2), (1, 10), (10, 2)])
|
397 |
+
paths = list(nx.all_simple_edge_paths(G, 1, 2, cutoff=1))
|
398 |
+
assert len(paths) == 2
|
399 |
+
assert {tuple(p) for p in paths} == {((1, 2, 0),), ((1, 2, 1),)}
|
400 |
+
|
401 |
+
|
402 |
+
def test_all_simple_edge_paths_directed():
|
403 |
+
G = nx.DiGraph()
|
404 |
+
nx.add_path(G, [1, 2, 3])
|
405 |
+
nx.add_path(G, [3, 2, 1])
|
406 |
+
paths = nx.all_simple_edge_paths(G, 1, 3)
|
407 |
+
assert {tuple(p) for p in paths} == {((1, 2), (2, 3))}
|
408 |
+
|
409 |
+
|
410 |
+
def test_all_simple_edge_paths_empty():
|
411 |
+
G = nx.path_graph(4)
|
412 |
+
paths = nx.all_simple_edge_paths(G, 0, 3, cutoff=2)
|
413 |
+
assert list(paths) == []
|
414 |
+
|
415 |
+
|
416 |
+
def test_all_simple_edge_paths_corner_cases():
|
417 |
+
assert list(nx.all_simple_edge_paths(nx.empty_graph(2), 0, 0)) == [[]]
|
418 |
+
assert list(nx.all_simple_edge_paths(nx.empty_graph(2), 0, 1)) == []
|
419 |
+
assert list(nx.all_simple_edge_paths(nx.path_graph(9), 0, 8, 0)) == []
|
420 |
+
|
421 |
+
|
422 |
+
def test_all_simple_edge_paths_ignores_self_loop():
|
423 |
+
G = nx.Graph([(0, 0), (0, 1), (1, 1), (1, 2)])
|
424 |
+
assert list(nx.all_simple_edge_paths(G, 0, 2)) == [[(0, 1), (1, 2)]]
|
425 |
+
|
426 |
+
|
427 |
+
def hamiltonian_edge_path(G, source):
|
428 |
+
source = arbitrary_element(G)
|
429 |
+
neighbors = set(G[source]) - {source}
|
430 |
+
n = len(G)
|
431 |
+
for target in neighbors:
|
432 |
+
for path in nx.all_simple_edge_paths(G, source, target):
|
433 |
+
if len(path) == n - 1:
|
434 |
+
yield path
|
435 |
+
|
436 |
+
|
437 |
+
def test_hamiltonian__edge_path():
|
438 |
+
from itertools import permutations
|
439 |
+
|
440 |
+
G = nx.complete_graph(4)
|
441 |
+
paths = hamiltonian_edge_path(G, 0)
|
442 |
+
exact = [list(pairwise([0] + list(p))) for p in permutations([1, 2, 3], 3)]
|
443 |
+
assert sorted(exact) == sorted(paths)
|
444 |
+
|
445 |
+
|
446 |
+
def test_edge_cutoff_zero():
|
447 |
+
G = nx.complete_graph(4)
|
448 |
+
paths = nx.all_simple_edge_paths(G, 0, 3, cutoff=0)
|
449 |
+
assert [list(p) for p in paths] == []
|
450 |
+
paths = nx.all_simple_edge_paths(nx.MultiGraph(G), 0, 3, cutoff=0)
|
451 |
+
assert [list(p) for p in paths] == []
|
452 |
+
|
453 |
+
|
454 |
+
def test_edge_source_missing():
|
455 |
+
with pytest.raises(nx.NodeNotFound):
|
456 |
+
G = nx.Graph()
|
457 |
+
nx.add_path(G, [1, 2, 3])
|
458 |
+
list(nx.all_simple_edge_paths(nx.MultiGraph(G), 0, 3))
|
459 |
+
|
460 |
+
|
461 |
+
def test_edge_target_missing():
|
462 |
+
with pytest.raises(nx.NodeNotFound):
|
463 |
+
G = nx.Graph()
|
464 |
+
nx.add_path(G, [1, 2, 3])
|
465 |
+
list(nx.all_simple_edge_paths(nx.MultiGraph(G), 1, 4))
|
466 |
+
|
467 |
+
|
468 |
+
# Tests for shortest_simple_paths
|
469 |
+
def test_shortest_simple_paths():
|
470 |
+
G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
|
471 |
+
paths = nx.shortest_simple_paths(G, 1, 12)
|
472 |
+
assert next(paths) == [1, 2, 3, 4, 8, 12]
|
473 |
+
assert next(paths) == [1, 5, 6, 7, 8, 12]
|
474 |
+
assert [len(path) for path in nx.shortest_simple_paths(G, 1, 12)] == sorted(
|
475 |
+
len(path) for path in nx.all_simple_paths(G, 1, 12)
|
476 |
+
)
|
477 |
+
|
478 |
+
|
479 |
+
def test_shortest_simple_paths_singleton_path():
|
480 |
+
G = nx.empty_graph(3)
|
481 |
+
assert list(nx.shortest_simple_paths(G, 0, 0)) == [[0]]
|
482 |
+
|
483 |
+
|
484 |
+
def test_shortest_simple_paths_directed():
|
485 |
+
G = nx.cycle_graph(7, create_using=nx.DiGraph())
|
486 |
+
paths = nx.shortest_simple_paths(G, 0, 3)
|
487 |
+
assert list(paths) == [[0, 1, 2, 3]]
|
488 |
+
|
489 |
+
|
490 |
+
def test_shortest_simple_paths_directed_with_weight_function():
|
491 |
+
def cost(u, v, x):
|
492 |
+
return 1
|
493 |
+
|
494 |
+
G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
|
495 |
+
paths = nx.shortest_simple_paths(G, 1, 12)
|
496 |
+
assert next(paths) == [1, 2, 3, 4, 8, 12]
|
497 |
+
assert next(paths) == [1, 5, 6, 7, 8, 12]
|
498 |
+
assert [
|
499 |
+
len(path) for path in nx.shortest_simple_paths(G, 1, 12, weight=cost)
|
500 |
+
] == sorted(len(path) for path in nx.all_simple_paths(G, 1, 12))
|
501 |
+
|
502 |
+
|
503 |
+
def test_shortest_simple_paths_with_weight_function():
|
504 |
+
def cost(u, v, x):
|
505 |
+
return 1
|
506 |
+
|
507 |
+
G = nx.cycle_graph(7, create_using=nx.DiGraph())
|
508 |
+
paths = nx.shortest_simple_paths(G, 0, 3, weight=cost)
|
509 |
+
assert list(paths) == [[0, 1, 2, 3]]
|
510 |
+
|
511 |
+
|
512 |
+
def test_Greg_Bernstein():
|
513 |
+
g1 = nx.Graph()
|
514 |
+
g1.add_nodes_from(["N0", "N1", "N2", "N3", "N4"])
|
515 |
+
g1.add_edge("N4", "N1", weight=10.0, capacity=50, name="L5")
|
516 |
+
g1.add_edge("N4", "N0", weight=7.0, capacity=40, name="L4")
|
517 |
+
g1.add_edge("N0", "N1", weight=10.0, capacity=45, name="L1")
|
518 |
+
g1.add_edge("N3", "N0", weight=10.0, capacity=50, name="L0")
|
519 |
+
g1.add_edge("N2", "N3", weight=12.0, capacity=30, name="L2")
|
520 |
+
g1.add_edge("N1", "N2", weight=15.0, capacity=42, name="L3")
|
521 |
+
solution = [["N1", "N0", "N3"], ["N1", "N2", "N3"], ["N1", "N4", "N0", "N3"]]
|
522 |
+
result = list(nx.shortest_simple_paths(g1, "N1", "N3", weight="weight"))
|
523 |
+
assert result == solution
|
524 |
+
|
525 |
+
|
526 |
+
def test_weighted_shortest_simple_path():
|
527 |
+
def cost_func(path):
|
528 |
+
return sum(G.adj[u][v]["weight"] for (u, v) in zip(path, path[1:]))
|
529 |
+
|
530 |
+
G = nx.complete_graph(5)
|
531 |
+
weight = {(u, v): random.randint(1, 100) for (u, v) in G.edges()}
|
532 |
+
nx.set_edge_attributes(G, weight, "weight")
|
533 |
+
cost = 0
|
534 |
+
for path in nx.shortest_simple_paths(G, 0, 3, weight="weight"):
|
535 |
+
this_cost = cost_func(path)
|
536 |
+
assert cost <= this_cost
|
537 |
+
cost = this_cost
|
538 |
+
|
539 |
+
|
540 |
+
def test_directed_weighted_shortest_simple_path():
|
541 |
+
def cost_func(path):
|
542 |
+
return sum(G.adj[u][v]["weight"] for (u, v) in zip(path, path[1:]))
|
543 |
+
|
544 |
+
G = nx.complete_graph(5)
|
545 |
+
G = G.to_directed()
|
546 |
+
weight = {(u, v): random.randint(1, 100) for (u, v) in G.edges()}
|
547 |
+
nx.set_edge_attributes(G, weight, "weight")
|
548 |
+
cost = 0
|
549 |
+
for path in nx.shortest_simple_paths(G, 0, 3, weight="weight"):
|
550 |
+
this_cost = cost_func(path)
|
551 |
+
assert cost <= this_cost
|
552 |
+
cost = this_cost
|
553 |
+
|
554 |
+
|
555 |
+
def test_weighted_shortest_simple_path_issue2427():
|
556 |
+
G = nx.Graph()
|
557 |
+
G.add_edge("IN", "OUT", weight=2)
|
558 |
+
G.add_edge("IN", "A", weight=1)
|
559 |
+
G.add_edge("IN", "B", weight=2)
|
560 |
+
G.add_edge("B", "OUT", weight=2)
|
561 |
+
assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
|
562 |
+
["IN", "OUT"],
|
563 |
+
["IN", "B", "OUT"],
|
564 |
+
]
|
565 |
+
G = nx.Graph()
|
566 |
+
G.add_edge("IN", "OUT", weight=10)
|
567 |
+
G.add_edge("IN", "A", weight=1)
|
568 |
+
G.add_edge("IN", "B", weight=1)
|
569 |
+
G.add_edge("B", "OUT", weight=1)
|
570 |
+
assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
|
571 |
+
["IN", "B", "OUT"],
|
572 |
+
["IN", "OUT"],
|
573 |
+
]
|
574 |
+
|
575 |
+
|
576 |
+
def test_directed_weighted_shortest_simple_path_issue2427():
|
577 |
+
G = nx.DiGraph()
|
578 |
+
G.add_edge("IN", "OUT", weight=2)
|
579 |
+
G.add_edge("IN", "A", weight=1)
|
580 |
+
G.add_edge("IN", "B", weight=2)
|
581 |
+
G.add_edge("B", "OUT", weight=2)
|
582 |
+
assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
|
583 |
+
["IN", "OUT"],
|
584 |
+
["IN", "B", "OUT"],
|
585 |
+
]
|
586 |
+
G = nx.DiGraph()
|
587 |
+
G.add_edge("IN", "OUT", weight=10)
|
588 |
+
G.add_edge("IN", "A", weight=1)
|
589 |
+
G.add_edge("IN", "B", weight=1)
|
590 |
+
G.add_edge("B", "OUT", weight=1)
|
591 |
+
assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
|
592 |
+
["IN", "B", "OUT"],
|
593 |
+
["IN", "OUT"],
|
594 |
+
]
|
595 |
+
|
596 |
+
|
597 |
+
def test_weight_name():
|
598 |
+
G = nx.cycle_graph(7)
|
599 |
+
nx.set_edge_attributes(G, 1, "weight")
|
600 |
+
nx.set_edge_attributes(G, 1, "foo")
|
601 |
+
G.adj[1][2]["foo"] = 7
|
602 |
+
paths = list(nx.shortest_simple_paths(G, 0, 3, weight="foo"))
|
603 |
+
solution = [[0, 6, 5, 4, 3], [0, 1, 2, 3]]
|
604 |
+
assert paths == solution
|
605 |
+
|
606 |
+
|
607 |
+
def test_ssp_source_missing():
|
608 |
+
with pytest.raises(nx.NodeNotFound):
|
609 |
+
G = nx.Graph()
|
610 |
+
nx.add_path(G, [1, 2, 3])
|
611 |
+
list(nx.shortest_simple_paths(G, 0, 3))
|
612 |
+
|
613 |
+
|
614 |
+
def test_ssp_target_missing():
|
615 |
+
with pytest.raises(nx.NodeNotFound):
|
616 |
+
G = nx.Graph()
|
617 |
+
nx.add_path(G, [1, 2, 3])
|
618 |
+
list(nx.shortest_simple_paths(G, 1, 4))
|
619 |
+
|
620 |
+
|
621 |
+
def test_ssp_multigraph():
|
622 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
623 |
+
G = nx.MultiGraph()
|
624 |
+
nx.add_path(G, [1, 2, 3])
|
625 |
+
list(nx.shortest_simple_paths(G, 1, 4))
|
626 |
+
|
627 |
+
|
628 |
+
def test_ssp_source_missing2():
|
629 |
+
with pytest.raises(nx.NetworkXNoPath):
|
630 |
+
G = nx.Graph()
|
631 |
+
nx.add_path(G, [0, 1, 2])
|
632 |
+
nx.add_path(G, [3, 4, 5])
|
633 |
+
list(nx.shortest_simple_paths(G, 0, 3))
|
634 |
+
|
635 |
+
|
636 |
+
def test_bidirectional_shortest_path_restricted_cycle():
|
637 |
+
cycle = nx.cycle_graph(7)
|
638 |
+
length, path = _bidirectional_shortest_path(cycle, 0, 3)
|
639 |
+
assert path == [0, 1, 2, 3]
|
640 |
+
length, path = _bidirectional_shortest_path(cycle, 0, 3, ignore_nodes=[1])
|
641 |
+
assert path == [0, 6, 5, 4, 3]
|
642 |
+
|
643 |
+
|
644 |
+
def test_bidirectional_shortest_path_restricted_wheel():
|
645 |
+
wheel = nx.wheel_graph(6)
|
646 |
+
length, path = _bidirectional_shortest_path(wheel, 1, 3)
|
647 |
+
assert path in [[1, 0, 3], [1, 2, 3]]
|
648 |
+
length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_nodes=[0])
|
649 |
+
assert path == [1, 2, 3]
|
650 |
+
length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_nodes=[0, 2])
|
651 |
+
assert path == [1, 5, 4, 3]
|
652 |
+
length, path = _bidirectional_shortest_path(
|
653 |
+
wheel, 1, 3, ignore_edges=[(1, 0), (5, 0), (2, 3)]
|
654 |
+
)
|
655 |
+
assert path in [[1, 2, 0, 3], [1, 5, 4, 3]]
|
656 |
+
|
657 |
+
|
658 |
+
def test_bidirectional_shortest_path_restricted_directed_cycle():
|
659 |
+
directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
|
660 |
+
length, path = _bidirectional_shortest_path(directed_cycle, 0, 3)
|
661 |
+
assert path == [0, 1, 2, 3]
|
662 |
+
pytest.raises(
|
663 |
+
nx.NetworkXNoPath,
|
664 |
+
_bidirectional_shortest_path,
|
665 |
+
directed_cycle,
|
666 |
+
0,
|
667 |
+
3,
|
668 |
+
ignore_nodes=[1],
|
669 |
+
)
|
670 |
+
length, path = _bidirectional_shortest_path(
|
671 |
+
directed_cycle, 0, 3, ignore_edges=[(2, 1)]
|
672 |
+
)
|
673 |
+
assert path == [0, 1, 2, 3]
|
674 |
+
pytest.raises(
|
675 |
+
nx.NetworkXNoPath,
|
676 |
+
_bidirectional_shortest_path,
|
677 |
+
directed_cycle,
|
678 |
+
0,
|
679 |
+
3,
|
680 |
+
ignore_edges=[(1, 2)],
|
681 |
+
)
|
682 |
+
|
683 |
+
|
684 |
+
def test_bidirectional_shortest_path_ignore():
|
685 |
+
G = nx.Graph()
|
686 |
+
nx.add_path(G, [1, 2])
|
687 |
+
nx.add_path(G, [1, 3])
|
688 |
+
nx.add_path(G, [1, 4])
|
689 |
+
pytest.raises(
|
690 |
+
nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[1]
|
691 |
+
)
|
692 |
+
pytest.raises(
|
693 |
+
nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[2]
|
694 |
+
)
|
695 |
+
G = nx.Graph()
|
696 |
+
nx.add_path(G, [1, 3])
|
697 |
+
nx.add_path(G, [1, 4])
|
698 |
+
nx.add_path(G, [3, 2])
|
699 |
+
pytest.raises(
|
700 |
+
nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[1, 2]
|
701 |
+
)
|
702 |
+
|
703 |
+
|
704 |
+
def validate_path(G, s, t, soln_len, path):
|
705 |
+
assert path[0] == s
|
706 |
+
assert path[-1] == t
|
707 |
+
assert soln_len == sum(
|
708 |
+
G[u][v].get("weight", 1) for u, v in zip(path[:-1], path[1:])
|
709 |
+
)
|
710 |
+
|
711 |
+
|
712 |
+
def validate_length_path(G, s, t, soln_len, length, path):
|
713 |
+
assert soln_len == length
|
714 |
+
validate_path(G, s, t, length, path)
|
715 |
+
|
716 |
+
|
717 |
+
def test_bidirectional_dijkstra_restricted():
|
718 |
+
XG = nx.DiGraph()
|
719 |
+
XG.add_weighted_edges_from(
|
720 |
+
[
|
721 |
+
("s", "u", 10),
|
722 |
+
("s", "x", 5),
|
723 |
+
("u", "v", 1),
|
724 |
+
("u", "x", 2),
|
725 |
+
("v", "y", 1),
|
726 |
+
("x", "u", 3),
|
727 |
+
("x", "v", 5),
|
728 |
+
("x", "y", 2),
|
729 |
+
("y", "s", 7),
|
730 |
+
("y", "v", 6),
|
731 |
+
]
|
732 |
+
)
|
733 |
+
|
734 |
+
XG3 = nx.Graph()
|
735 |
+
XG3.add_weighted_edges_from(
|
736 |
+
[[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
|
737 |
+
)
|
738 |
+
validate_length_path(XG, "s", "v", 9, *_bidirectional_dijkstra(XG, "s", "v"))
|
739 |
+
validate_length_path(
|
740 |
+
XG, "s", "v", 10, *_bidirectional_dijkstra(XG, "s", "v", ignore_nodes=["u"])
|
741 |
+
)
|
742 |
+
validate_length_path(
|
743 |
+
XG,
|
744 |
+
"s",
|
745 |
+
"v",
|
746 |
+
11,
|
747 |
+
*_bidirectional_dijkstra(XG, "s", "v", ignore_edges=[("s", "x")]),
|
748 |
+
)
|
749 |
+
pytest.raises(
|
750 |
+
nx.NetworkXNoPath,
|
751 |
+
_bidirectional_dijkstra,
|
752 |
+
XG,
|
753 |
+
"s",
|
754 |
+
"v",
|
755 |
+
ignore_nodes=["u"],
|
756 |
+
ignore_edges=[("s", "x")],
|
757 |
+
)
|
758 |
+
validate_length_path(XG3, 0, 3, 15, *_bidirectional_dijkstra(XG3, 0, 3))
|
759 |
+
validate_length_path(
|
760 |
+
XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_nodes=[1])
|
761 |
+
)
|
762 |
+
validate_length_path(
|
763 |
+
XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_edges=[(2, 3)])
|
764 |
+
)
|
765 |
+
pytest.raises(
|
766 |
+
nx.NetworkXNoPath,
|
767 |
+
_bidirectional_dijkstra,
|
768 |
+
XG3,
|
769 |
+
0,
|
770 |
+
3,
|
771 |
+
ignore_nodes=[1],
|
772 |
+
ignore_edges=[(5, 4)],
|
773 |
+
)
|
774 |
+
|
775 |
+
|
776 |
+
def test_bidirectional_dijkstra_no_path():
|
777 |
+
with pytest.raises(nx.NetworkXNoPath):
|
778 |
+
G = nx.Graph()
|
779 |
+
nx.add_path(G, [1, 2, 3])
|
780 |
+
nx.add_path(G, [4, 5, 6])
|
781 |
+
_bidirectional_dijkstra(G, 1, 6)
|
782 |
+
|
783 |
+
|
784 |
+
def test_bidirectional_dijkstra_ignore():
|
785 |
+
G = nx.Graph()
|
786 |
+
nx.add_path(G, [1, 2, 10])
|
787 |
+
nx.add_path(G, [1, 3, 10])
|
788 |
+
pytest.raises(nx.NetworkXNoPath, _bidirectional_dijkstra, G, 1, 2, ignore_nodes=[1])
|
789 |
+
pytest.raises(nx.NetworkXNoPath, _bidirectional_dijkstra, G, 1, 2, ignore_nodes=[2])
|
790 |
+
pytest.raises(
|
791 |
+
nx.NetworkXNoPath, _bidirectional_dijkstra, G, 1, 2, ignore_nodes=[1, 2]
|
792 |
+
)
|
llmeval-env/lib/python3.10/site-packages/networkx/algorithms/tests/test_smallworld.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
pytest.importorskip("numpy")
|
4 |
+
|
5 |
+
import random
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
from networkx import lattice_reference, omega, random_reference, sigma
|
9 |
+
|
10 |
+
rng = 42
|
11 |
+
|
12 |
+
|
13 |
+
def test_random_reference():
|
14 |
+
G = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
|
15 |
+
Gr = random_reference(G, niter=1, seed=rng)
|
16 |
+
C = nx.average_clustering(G)
|
17 |
+
Cr = nx.average_clustering(Gr)
|
18 |
+
assert C > Cr
|
19 |
+
|
20 |
+
with pytest.raises(nx.NetworkXError):
|
21 |
+
next(random_reference(nx.Graph()))
|
22 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
23 |
+
next(random_reference(nx.DiGraph()))
|
24 |
+
|
25 |
+
H = nx.Graph(((0, 1), (2, 3)))
|
26 |
+
Hl = random_reference(H, niter=1, seed=rng)
|
27 |
+
|
28 |
+
|
29 |
+
def test_lattice_reference():
|
30 |
+
G = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
|
31 |
+
Gl = lattice_reference(G, niter=1, seed=rng)
|
32 |
+
L = nx.average_shortest_path_length(G)
|
33 |
+
Ll = nx.average_shortest_path_length(Gl)
|
34 |
+
assert Ll > L
|
35 |
+
|
36 |
+
pytest.raises(nx.NetworkXError, lattice_reference, nx.Graph())
|
37 |
+
pytest.raises(nx.NetworkXNotImplemented, lattice_reference, nx.DiGraph())
|
38 |
+
|
39 |
+
H = nx.Graph(((0, 1), (2, 3)))
|
40 |
+
Hl = lattice_reference(H, niter=1)
|
41 |
+
|
42 |
+
|
43 |
+
def test_sigma():
|
44 |
+
Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
|
45 |
+
Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
|
46 |
+
sigmas = sigma(Gs, niter=1, nrand=2, seed=rng)
|
47 |
+
sigmar = sigma(Gr, niter=1, nrand=2, seed=rng)
|
48 |
+
assert sigmar < sigmas
|
49 |
+
|
50 |
+
|
51 |
+
def test_omega():
|
52 |
+
Gl = nx.connected_watts_strogatz_graph(50, 6, 0, seed=rng)
|
53 |
+
Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
|
54 |
+
Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
|
55 |
+
omegal = omega(Gl, niter=1, nrand=1, seed=rng)
|
56 |
+
omegar = omega(Gr, niter=1, nrand=1, seed=rng)
|
57 |
+
omegas = omega(Gs, niter=1, nrand=1, seed=rng)
|
58 |
+
assert omegal < omegas and omegas < omegar
|
59 |
+
|
60 |
+
# Test that omega lies within the [-1, 1] bounds
|
61 |
+
G_barbell = nx.barbell_graph(5, 1)
|
62 |
+
G_karate = nx.karate_club_graph()
|
63 |
+
|
64 |
+
omega_barbell = nx.omega(G_barbell)
|
65 |
+
omega_karate = nx.omega(G_karate, nrand=2)
|
66 |
+
|
67 |
+
omegas = (omegal, omegar, omegas, omega_barbell, omega_karate)
|
68 |
+
|
69 |
+
for o in omegas:
|
70 |
+
assert -1 <= o <= 1
|
71 |
+
|
72 |
+
|
73 |
+
@pytest.mark.parametrize("f", (nx.random_reference, nx.lattice_reference))
|
74 |
+
def test_graph_no_edges(f):
|
75 |
+
G = nx.Graph()
|
76 |
+
G.add_nodes_from([0, 1, 2, 3])
|
77 |
+
with pytest.raises(nx.NetworkXError, match="Graph has fewer that 2 edges"):
|
78 |
+
f(G)
|