applied-ai-018 commited on
Commit
5d6ed72
·
verified ·
1 Parent(s): 885bfcf

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__init__.py +87 -0
  2. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/edgelist.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/extendability.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matching.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matrix.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/projection.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/redundancy.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/basic.py +321 -0
  9. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/centrality.py +290 -0
  10. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/cluster.py +280 -0
  11. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/covering.py +57 -0
  12. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/edgelist.py +359 -0
  13. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/extendability.py +106 -0
  14. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/generators.py +603 -0
  15. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/matching.py +589 -0
  16. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/matrix.py +167 -0
  17. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/projection.py +521 -0
  18. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/redundancy.py +111 -0
  19. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/spectral.py +68 -0
  20. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_closeness_centrality.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_current_flow_betweenness_centrality.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_degree_centrality.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_eigenvector_centrality.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_harmonic_centrality.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_reaching.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_trophic.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py +4 -0
  28. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/__init__.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/greedy_coloring.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/equitable_coloring.py +505 -0
  32. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py +564 -0
  33. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py +0 -0
  34. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/test_coloring.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py +865 -0
  37. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_boundary.cpython-310.pyc +0 -0
  39. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_bridges.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_broadcasting.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chains.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chordal.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_clique.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cluster.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_core.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cuts.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cycles.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dag.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dominance.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_efficiency.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__init__.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r""" This module provides functions and operations for bipartite
2
+ graphs. Bipartite graphs `B = (U, V, E)` have two node sets `U,V` and edges in
3
+ `E` that only connect nodes from opposite sets. It is common in the literature
4
+ to use an spatial analogy referring to the two node sets as top and bottom nodes.
5
+
6
+ The bipartite algorithms are not imported into the networkx namespace
7
+ at the top level so the easiest way to use them is with:
8
+
9
+ >>> from networkx.algorithms import bipartite
10
+
11
+ NetworkX does not have a custom bipartite graph class but the Graph()
12
+ or DiGraph() classes can be used to represent bipartite graphs. However,
13
+ you have to keep track of which set each node belongs to, and make
14
+ sure that there is no edge between nodes of the same set. The convention used
15
+ in NetworkX is to use a node attribute named `bipartite` with values 0 or 1 to
16
+ identify the sets each node belongs to. This convention is not enforced in
17
+ the source code of bipartite functions, it's only a recommendation.
18
+
19
+ For example:
20
+
21
+ >>> B = nx.Graph()
22
+ >>> # Add nodes with the node attribute "bipartite"
23
+ >>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
24
+ >>> B.add_nodes_from(["a", "b", "c"], bipartite=1)
25
+ >>> # Add edges only between nodes of opposite node sets
26
+ >>> B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
27
+
28
+ Many algorithms of the bipartite module of NetworkX require, as an argument, a
29
+ container with all the nodes that belong to one set, in addition to the bipartite
30
+ graph `B`. The functions in the bipartite package do not check that the node set
31
+ is actually correct nor that the input graph is actually bipartite.
32
+ If `B` is connected, you can find the two node sets using a two-coloring
33
+ algorithm:
34
+
35
+ >>> nx.is_connected(B)
36
+ True
37
+ >>> bottom_nodes, top_nodes = bipartite.sets(B)
38
+
39
+ However, if the input graph is not connected, there are more than one possible
40
+ colorations. This is the reason why we require the user to pass a container
41
+ with all nodes of one bipartite node set as an argument to most bipartite
42
+ functions. In the face of ambiguity, we refuse the temptation to guess and
43
+ raise an :exc:`AmbiguousSolution <networkx.AmbiguousSolution>`
44
+ Exception if the input graph for
45
+ :func:`bipartite.sets <networkx.algorithms.bipartite.basic.sets>`
46
+ is disconnected.
47
+
48
+ Using the `bipartite` node attribute, you can easily get the two node sets:
49
+
50
+ >>> top_nodes = {n for n, d in B.nodes(data=True) if d["bipartite"] == 0}
51
+ >>> bottom_nodes = set(B) - top_nodes
52
+
53
+ So you can easily use the bipartite algorithms that require, as an argument, a
54
+ container with all nodes that belong to one node set:
55
+
56
+ >>> print(round(bipartite.density(B, bottom_nodes), 2))
57
+ 0.5
58
+ >>> G = bipartite.projected_graph(B, top_nodes)
59
+
60
+ All bipartite graph generators in NetworkX build bipartite graphs with the
61
+ `bipartite` node attribute. Thus, you can use the same approach:
62
+
63
+ >>> RB = bipartite.random_graph(5, 7, 0.2)
64
+ >>> RB_top = {n for n, d in RB.nodes(data=True) if d["bipartite"] == 0}
65
+ >>> RB_bottom = set(RB) - RB_top
66
+ >>> list(RB_top)
67
+ [0, 1, 2, 3, 4]
68
+ >>> list(RB_bottom)
69
+ [5, 6, 7, 8, 9, 10, 11]
70
+
71
+ For other bipartite graph generators see
72
+ :mod:`Generators <networkx.algorithms.bipartite.generators>`.
73
+
74
+ """
75
+
76
+ from networkx.algorithms.bipartite.basic import *
77
+ from networkx.algorithms.bipartite.centrality import *
78
+ from networkx.algorithms.bipartite.cluster import *
79
+ from networkx.algorithms.bipartite.covering import *
80
+ from networkx.algorithms.bipartite.edgelist import *
81
+ from networkx.algorithms.bipartite.matching import *
82
+ from networkx.algorithms.bipartite.matrix import *
83
+ from networkx.algorithms.bipartite.projection import *
84
+ from networkx.algorithms.bipartite.redundancy import *
85
+ from networkx.algorithms.bipartite.spectral import *
86
+ from networkx.algorithms.bipartite.generators import *
87
+ from networkx.algorithms.bipartite.extendability import *
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/edgelist.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/extendability.cpython-310.pyc ADDED
Binary file (4.07 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matching.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matrix.cpython-310.pyc ADDED
Binary file (6.05 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/projection.cpython-310.pyc ADDED
Binary file (17.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/redundancy.cpython-310.pyc ADDED
Binary file (4.04 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/basic.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==========================
3
+ Bipartite Graph Algorithms
4
+ ==========================
5
+ """
6
+ import networkx as nx
7
+ from networkx.algorithms.components import connected_components
8
+ from networkx.exception import AmbiguousSolution
9
+
10
+ __all__ = [
11
+ "is_bipartite",
12
+ "is_bipartite_node_set",
13
+ "color",
14
+ "sets",
15
+ "density",
16
+ "degrees",
17
+ ]
18
+
19
+
20
+ @nx._dispatchable
21
+ def color(G):
22
+ """Returns a two-coloring of the graph.
23
+
24
+ Raises an exception if the graph is not bipartite.
25
+
26
+ Parameters
27
+ ----------
28
+ G : NetworkX graph
29
+
30
+ Returns
31
+ -------
32
+ color : dictionary
33
+ A dictionary keyed by node with a 1 or 0 as data for each node color.
34
+
35
+ Raises
36
+ ------
37
+ NetworkXError
38
+ If the graph is not two-colorable.
39
+
40
+ Examples
41
+ --------
42
+ >>> from networkx.algorithms import bipartite
43
+ >>> G = nx.path_graph(4)
44
+ >>> c = bipartite.color(G)
45
+ >>> print(c)
46
+ {0: 1, 1: 0, 2: 1, 3: 0}
47
+
48
+ You can use this to set a node attribute indicating the bipartite set:
49
+
50
+ >>> nx.set_node_attributes(G, c, "bipartite")
51
+ >>> print(G.nodes[0]["bipartite"])
52
+ 1
53
+ >>> print(G.nodes[1]["bipartite"])
54
+ 0
55
+ """
56
+ if G.is_directed():
57
+ import itertools
58
+
59
+ def neighbors(v):
60
+ return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
61
+
62
+ else:
63
+ neighbors = G.neighbors
64
+
65
+ color = {}
66
+ for n in G: # handle disconnected graphs
67
+ if n in color or len(G[n]) == 0: # skip isolates
68
+ continue
69
+ queue = [n]
70
+ color[n] = 1 # nodes seen with color (1 or 0)
71
+ while queue:
72
+ v = queue.pop()
73
+ c = 1 - color[v] # opposite color of node v
74
+ for w in neighbors(v):
75
+ if w in color:
76
+ if color[w] == color[v]:
77
+ raise nx.NetworkXError("Graph is not bipartite.")
78
+ else:
79
+ color[w] = c
80
+ queue.append(w)
81
+ # color isolates with 0
82
+ color.update(dict.fromkeys(nx.isolates(G), 0))
83
+ return color
84
+
85
+
86
+ @nx._dispatchable
87
+ def is_bipartite(G):
88
+ """Returns True if graph G is bipartite, False if not.
89
+
90
+ Parameters
91
+ ----------
92
+ G : NetworkX graph
93
+
94
+ Examples
95
+ --------
96
+ >>> from networkx.algorithms import bipartite
97
+ >>> G = nx.path_graph(4)
98
+ >>> print(bipartite.is_bipartite(G))
99
+ True
100
+
101
+ See Also
102
+ --------
103
+ color, is_bipartite_node_set
104
+ """
105
+ try:
106
+ color(G)
107
+ return True
108
+ except nx.NetworkXError:
109
+ return False
110
+
111
+
112
+ @nx._dispatchable
113
+ def is_bipartite_node_set(G, nodes):
114
+ """Returns True if nodes and G/nodes are a bipartition of G.
115
+
116
+ Parameters
117
+ ----------
118
+ G : NetworkX graph
119
+
120
+ nodes: list or container
121
+ Check if nodes are a one of a bipartite set.
122
+
123
+ Examples
124
+ --------
125
+ >>> from networkx.algorithms import bipartite
126
+ >>> G = nx.path_graph(4)
127
+ >>> X = set([1, 3])
128
+ >>> bipartite.is_bipartite_node_set(G, X)
129
+ True
130
+
131
+ Notes
132
+ -----
133
+ An exception is raised if the input nodes are not distinct, because in this
134
+ case some bipartite algorithms will yield incorrect results.
135
+ For connected graphs the bipartite sets are unique. This function handles
136
+ disconnected graphs.
137
+ """
138
+ S = set(nodes)
139
+
140
+ if len(S) < len(nodes):
141
+ # this should maybe just return False?
142
+ raise AmbiguousSolution(
143
+ "The input node set contains duplicates.\n"
144
+ "This may lead to incorrect results when using it in bipartite algorithms.\n"
145
+ "Consider using set(nodes) as the input"
146
+ )
147
+
148
+ for CC in (G.subgraph(c).copy() for c in connected_components(G)):
149
+ X, Y = sets(CC)
150
+ if not (
151
+ (X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S))
152
+ ):
153
+ return False
154
+ return True
155
+
156
+
157
+ @nx._dispatchable
158
+ def sets(G, top_nodes=None):
159
+ """Returns bipartite node sets of graph G.
160
+
161
+ Raises an exception if the graph is not bipartite or if the input
162
+ graph is disconnected and thus more than one valid solution exists.
163
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
164
+ for further details on how bipartite graphs are handled in NetworkX.
165
+
166
+ Parameters
167
+ ----------
168
+ G : NetworkX graph
169
+
170
+ top_nodes : container, optional
171
+ Container with all nodes in one bipartite node set. If not supplied
172
+ it will be computed. But if more than one solution exists an exception
173
+ will be raised.
174
+
175
+ Returns
176
+ -------
177
+ X : set
178
+ Nodes from one side of the bipartite graph.
179
+ Y : set
180
+ Nodes from the other side.
181
+
182
+ Raises
183
+ ------
184
+ AmbiguousSolution
185
+ Raised if the input bipartite graph is disconnected and no container
186
+ with all nodes in one bipartite set is provided. When determining
187
+ the nodes in each bipartite set more than one valid solution is
188
+ possible if the input graph is disconnected.
189
+ NetworkXError
190
+ Raised if the input graph is not bipartite.
191
+
192
+ Examples
193
+ --------
194
+ >>> from networkx.algorithms import bipartite
195
+ >>> G = nx.path_graph(4)
196
+ >>> X, Y = bipartite.sets(G)
197
+ >>> list(X)
198
+ [0, 2]
199
+ >>> list(Y)
200
+ [1, 3]
201
+
202
+ See Also
203
+ --------
204
+ color
205
+
206
+ """
207
+ if G.is_directed():
208
+ is_connected = nx.is_weakly_connected
209
+ else:
210
+ is_connected = nx.is_connected
211
+ if top_nodes is not None:
212
+ X = set(top_nodes)
213
+ Y = set(G) - X
214
+ else:
215
+ if not is_connected(G):
216
+ msg = "Disconnected graph: Ambiguous solution for bipartite sets."
217
+ raise nx.AmbiguousSolution(msg)
218
+ c = color(G)
219
+ X = {n for n, is_top in c.items() if is_top}
220
+ Y = {n for n, is_top in c.items() if not is_top}
221
+ return (X, Y)
222
+
223
+
224
+ @nx._dispatchable(graphs="B")
225
+ def density(B, nodes):
226
+ """Returns density of bipartite graph B.
227
+
228
+ Parameters
229
+ ----------
230
+ B : NetworkX graph
231
+
232
+ nodes: list or container
233
+ Nodes in one node set of the bipartite graph.
234
+
235
+ Returns
236
+ -------
237
+ d : float
238
+ The bipartite density
239
+
240
+ Examples
241
+ --------
242
+ >>> from networkx.algorithms import bipartite
243
+ >>> G = nx.complete_bipartite_graph(3, 2)
244
+ >>> X = set([0, 1, 2])
245
+ >>> bipartite.density(G, X)
246
+ 1.0
247
+ >>> Y = set([3, 4])
248
+ >>> bipartite.density(G, Y)
249
+ 1.0
250
+
251
+ Notes
252
+ -----
253
+ The container of nodes passed as argument must contain all nodes
254
+ in one of the two bipartite node sets to avoid ambiguity in the
255
+ case of disconnected graphs.
256
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
257
+ for further details on how bipartite graphs are handled in NetworkX.
258
+
259
+ See Also
260
+ --------
261
+ color
262
+ """
263
+ n = len(B)
264
+ m = nx.number_of_edges(B)
265
+ nb = len(nodes)
266
+ nt = n - nb
267
+ if m == 0: # includes cases n==0 and n==1
268
+ d = 0.0
269
+ else:
270
+ if B.is_directed():
271
+ d = m / (2 * nb * nt)
272
+ else:
273
+ d = m / (nb * nt)
274
+ return d
275
+
276
+
277
+ @nx._dispatchable(graphs="B", edge_attrs="weight")
278
+ def degrees(B, nodes, weight=None):
279
+ """Returns the degrees of the two node sets in the bipartite graph B.
280
+
281
+ Parameters
282
+ ----------
283
+ B : NetworkX graph
284
+
285
+ nodes: list or container
286
+ Nodes in one node set of the bipartite graph.
287
+
288
+ weight : string or None, optional (default=None)
289
+ The edge attribute that holds the numerical value used as a weight.
290
+ If None, then each edge has weight 1.
291
+ The degree is the sum of the edge weights adjacent to the node.
292
+
293
+ Returns
294
+ -------
295
+ (degX,degY) : tuple of dictionaries
296
+ The degrees of the two bipartite sets as dictionaries keyed by node.
297
+
298
+ Examples
299
+ --------
300
+ >>> from networkx.algorithms import bipartite
301
+ >>> G = nx.complete_bipartite_graph(3, 2)
302
+ >>> Y = set([3, 4])
303
+ >>> degX, degY = bipartite.degrees(G, Y)
304
+ >>> dict(degX)
305
+ {0: 2, 1: 2, 2: 2}
306
+
307
+ Notes
308
+ -----
309
+ The container of nodes passed as argument must contain all nodes
310
+ in one of the two bipartite node sets to avoid ambiguity in the
311
+ case of disconnected graphs.
312
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
313
+ for further details on how bipartite graphs are handled in NetworkX.
314
+
315
+ See Also
316
+ --------
317
+ color, density
318
+ """
319
+ bottom = set(nodes)
320
+ top = set(B) - bottom
321
+ return (B.degree(top, weight), B.degree(bottom, weight))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/centrality.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"]
4
+
5
+
6
+ @nx._dispatchable(name="bipartite_degree_centrality")
7
+ def degree_centrality(G, nodes):
8
+ r"""Compute the degree centrality for nodes in a bipartite network.
9
+
10
+ The degree centrality for a node `v` is the fraction of nodes
11
+ connected to it.
12
+
13
+ Parameters
14
+ ----------
15
+ G : graph
16
+ A bipartite network
17
+
18
+ nodes : list or container
19
+ Container with all nodes in one bipartite node set.
20
+
21
+ Returns
22
+ -------
23
+ centrality : dictionary
24
+ Dictionary keyed by node with bipartite degree centrality as the value.
25
+
26
+ Examples
27
+ --------
28
+ >>> G = nx.wheel_graph(5)
29
+ >>> top_nodes = {0, 1, 2}
30
+ >>> nx.bipartite.degree_centrality(G, nodes=top_nodes)
31
+ {0: 2.0, 1: 1.5, 2: 1.5, 3: 1.0, 4: 1.0}
32
+
33
+ See Also
34
+ --------
35
+ betweenness_centrality
36
+ closeness_centrality
37
+ :func:`~networkx.algorithms.bipartite.basic.sets`
38
+ :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
39
+
40
+ Notes
41
+ -----
42
+ The nodes input parameter must contain all nodes in one bipartite node set,
43
+ but the dictionary returned contains all nodes from both bipartite node
44
+ sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
45
+ for further details on how bipartite graphs are handled in NetworkX.
46
+
47
+ For unipartite networks, the degree centrality values are
48
+ normalized by dividing by the maximum possible degree (which is
49
+ `n-1` where `n` is the number of nodes in G).
50
+
51
+ In the bipartite case, the maximum possible degree of a node in a
52
+ bipartite node set is the number of nodes in the opposite node set
53
+ [1]_. The degree centrality for a node `v` in the bipartite
54
+ sets `U` with `n` nodes and `V` with `m` nodes is
55
+
56
+ .. math::
57
+
58
+ d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U ,
59
+
60
+ d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V ,
61
+
62
+
63
+ where `deg(v)` is the degree of node `v`.
64
+
65
+ References
66
+ ----------
67
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
68
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
69
+ of Social Network Analysis. Sage Publications.
70
+ https://dx.doi.org/10.4135/9781446294413.n28
71
+ """
72
+ top = set(nodes)
73
+ bottom = set(G) - top
74
+ s = 1.0 / len(bottom)
75
+ centrality = {n: d * s for n, d in G.degree(top)}
76
+ s = 1.0 / len(top)
77
+ centrality.update({n: d * s for n, d in G.degree(bottom)})
78
+ return centrality
79
+
80
+
81
+ @nx._dispatchable(name="bipartite_betweenness_centrality")
82
+ def betweenness_centrality(G, nodes):
83
+ r"""Compute betweenness centrality for nodes in a bipartite network.
84
+
85
+ Betweenness centrality of a node `v` is the sum of the
86
+ fraction of all-pairs shortest paths that pass through `v`.
87
+
88
+ Values of betweenness are normalized by the maximum possible
89
+ value which for bipartite graphs is limited by the relative size
90
+ of the two node sets [1]_.
91
+
92
+ Let `n` be the number of nodes in the node set `U` and
93
+ `m` be the number of nodes in the node set `V`, then
94
+ nodes in `U` are normalized by dividing by
95
+
96
+ .. math::
97
+
98
+ \frac{1}{2} [m^2 (s + 1)^2 + m (s + 1)(2t - s - 1) - t (2s - t + 3)] ,
99
+
100
+ where
101
+
102
+ .. math::
103
+
104
+ s = (n - 1) \div m , t = (n - 1) \mod m ,
105
+
106
+ and nodes in `V` are normalized by dividing by
107
+
108
+ .. math::
109
+
110
+ \frac{1}{2} [n^2 (p + 1)^2 + n (p + 1)(2r - p - 1) - r (2p - r + 3)] ,
111
+
112
+ where,
113
+
114
+ .. math::
115
+
116
+ p = (m - 1) \div n , r = (m - 1) \mod n .
117
+
118
+ Parameters
119
+ ----------
120
+ G : graph
121
+ A bipartite graph
122
+
123
+ nodes : list or container
124
+ Container with all nodes in one bipartite node set.
125
+
126
+ Returns
127
+ -------
128
+ betweenness : dictionary
129
+ Dictionary keyed by node with bipartite betweenness centrality
130
+ as the value.
131
+
132
+ Examples
133
+ --------
134
+ >>> G = nx.cycle_graph(4)
135
+ >>> top_nodes = {1, 2}
136
+ >>> nx.bipartite.betweenness_centrality(G, nodes=top_nodes)
137
+ {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
138
+
139
+ See Also
140
+ --------
141
+ degree_centrality
142
+ closeness_centrality
143
+ :func:`~networkx.algorithms.bipartite.basic.sets`
144
+ :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
145
+
146
+ Notes
147
+ -----
148
+ The nodes input parameter must contain all nodes in one bipartite node set,
149
+ but the dictionary returned contains all nodes from both node sets.
150
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
151
+ for further details on how bipartite graphs are handled in NetworkX.
152
+
153
+
154
+ References
155
+ ----------
156
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
157
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
158
+ of Social Network Analysis. Sage Publications.
159
+ https://dx.doi.org/10.4135/9781446294413.n28
160
+ """
161
+ top = set(nodes)
162
+ bottom = set(G) - top
163
+ n = len(top)
164
+ m = len(bottom)
165
+ s, t = divmod(n - 1, m)
166
+ bet_max_top = (
167
+ ((m**2) * ((s + 1) ** 2))
168
+ + (m * (s + 1) * (2 * t - s - 1))
169
+ - (t * ((2 * s) - t + 3))
170
+ ) / 2.0
171
+ p, r = divmod(m - 1, n)
172
+ bet_max_bot = (
173
+ ((n**2) * ((p + 1) ** 2))
174
+ + (n * (p + 1) * (2 * r - p - 1))
175
+ - (r * ((2 * p) - r + 3))
176
+ ) / 2.0
177
+ betweenness = nx.betweenness_centrality(G, normalized=False, weight=None)
178
+ for node in top:
179
+ betweenness[node] /= bet_max_top
180
+ for node in bottom:
181
+ betweenness[node] /= bet_max_bot
182
+ return betweenness
183
+
184
+
185
+ @nx._dispatchable(name="bipartite_closeness_centrality")
186
+ def closeness_centrality(G, nodes, normalized=True):
187
+ r"""Compute the closeness centrality for nodes in a bipartite network.
188
+
189
+ The closeness of a node is the distance to all other nodes in the
190
+ graph or in the case that the graph is not connected to all other nodes
191
+ in the connected component containing that node.
192
+
193
+ Parameters
194
+ ----------
195
+ G : graph
196
+ A bipartite network
197
+
198
+ nodes : list or container
199
+ Container with all nodes in one bipartite node set.
200
+
201
+ normalized : bool, optional
202
+ If True (default) normalize by connected component size.
203
+
204
+ Returns
205
+ -------
206
+ closeness : dictionary
207
+ Dictionary keyed by node with bipartite closeness centrality
208
+ as the value.
209
+
210
+ Examples
211
+ --------
212
+ >>> G = nx.wheel_graph(5)
213
+ >>> top_nodes = {0, 1, 2}
214
+ >>> nx.bipartite.closeness_centrality(G, nodes=top_nodes)
215
+ {0: 1.5, 1: 1.2, 2: 1.2, 3: 1.0, 4: 1.0}
216
+
217
+ See Also
218
+ --------
219
+ betweenness_centrality
220
+ degree_centrality
221
+ :func:`~networkx.algorithms.bipartite.basic.sets`
222
+ :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
223
+
224
+ Notes
225
+ -----
226
+ The nodes input parameter must contain all nodes in one bipartite node set,
227
+ but the dictionary returned contains all nodes from both node sets.
228
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
229
+ for further details on how bipartite graphs are handled in NetworkX.
230
+
231
+
232
+ Closeness centrality is normalized by the minimum distance possible.
233
+ In the bipartite case the minimum distance for a node in one bipartite
234
+ node set is 1 from all nodes in the other node set and 2 from all
235
+ other nodes in its own set [1]_. Thus the closeness centrality
236
+ for node `v` in the two bipartite sets `U` with
237
+ `n` nodes and `V` with `m` nodes is
238
+
239
+ .. math::
240
+
241
+ c_{v} = \frac{m + 2(n - 1)}{d}, \mbox{for} v \in U,
242
+
243
+ c_{v} = \frac{n + 2(m - 1)}{d}, \mbox{for} v \in V,
244
+
245
+ where `d` is the sum of the distances from `v` to all
246
+ other nodes.
247
+
248
+ Higher values of closeness indicate higher centrality.
249
+
250
+ As in the unipartite case, setting normalized=True causes the
251
+ values to normalized further to n-1 / size(G)-1 where n is the
252
+ number of nodes in the connected part of graph containing the
253
+ node. If the graph is not completely connected, this algorithm
254
+ computes the closeness centrality for each connected part
255
+ separately.
256
+
257
+ References
258
+ ----------
259
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
260
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
261
+ of Social Network Analysis. Sage Publications.
262
+ https://dx.doi.org/10.4135/9781446294413.n28
263
+ """
264
+ closeness = {}
265
+ path_length = nx.single_source_shortest_path_length
266
+ top = set(nodes)
267
+ bottom = set(G) - top
268
+ n = len(top)
269
+ m = len(bottom)
270
+ for node in top:
271
+ sp = dict(path_length(G, node))
272
+ totsp = sum(sp.values())
273
+ if totsp > 0.0 and len(G) > 1:
274
+ closeness[node] = (m + 2 * (n - 1)) / totsp
275
+ if normalized:
276
+ s = (len(sp) - 1) / (len(G) - 1)
277
+ closeness[node] *= s
278
+ else:
279
+ closeness[node] = 0.0
280
+ for node in bottom:
281
+ sp = dict(path_length(G, node))
282
+ totsp = sum(sp.values())
283
+ if totsp > 0.0 and len(G) > 1:
284
+ closeness[node] = (n + 2 * (m - 1)) / totsp
285
+ if normalized:
286
+ s = (len(sp) - 1) / (len(G) - 1)
287
+ closeness[node] *= s
288
+ else:
289
+ closeness[node] = 0.0
290
+ return closeness
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/cluster.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing clustering of pairs
2
+
3
+ """
4
+
5
+ import itertools
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = [
10
+ "clustering",
11
+ "average_clustering",
12
+ "latapy_clustering",
13
+ "robins_alexander_clustering",
14
+ ]
15
+
16
+
17
+ def cc_dot(nu, nv):
18
+ return len(nu & nv) / len(nu | nv)
19
+
20
+
21
+ def cc_max(nu, nv):
22
+ return len(nu & nv) / max(len(nu), len(nv))
23
+
24
+
25
+ def cc_min(nu, nv):
26
+ return len(nu & nv) / min(len(nu), len(nv))
27
+
28
+
29
+ modes = {"dot": cc_dot, "min": cc_min, "max": cc_max}
30
+
31
+
32
+ @nx._dispatchable
33
+ def latapy_clustering(G, nodes=None, mode="dot"):
34
+ r"""Compute a bipartite clustering coefficient for nodes.
35
+
36
+ The bipartite clustering coefficient is a measure of local density
37
+ of connections defined as [1]_:
38
+
39
+ .. math::
40
+
41
+ c_u = \frac{\sum_{v \in N(N(u))} c_{uv} }{|N(N(u))|}
42
+
43
+ where `N(N(u))` are the second order neighbors of `u` in `G` excluding `u`,
44
+ and `c_{uv}` is the pairwise clustering coefficient between nodes
45
+ `u` and `v`.
46
+
47
+ The mode selects the function for `c_{uv}` which can be:
48
+
49
+ `dot`:
50
+
51
+ .. math::
52
+
53
+ c_{uv}=\frac{|N(u)\cap N(v)|}{|N(u) \cup N(v)|}
54
+
55
+ `min`:
56
+
57
+ .. math::
58
+
59
+ c_{uv}=\frac{|N(u)\cap N(v)|}{min(|N(u)|,|N(v)|)}
60
+
61
+ `max`:
62
+
63
+ .. math::
64
+
65
+ c_{uv}=\frac{|N(u)\cap N(v)|}{max(|N(u)|,|N(v)|)}
66
+
67
+
68
+ Parameters
69
+ ----------
70
+ G : graph
71
+ A bipartite graph
72
+
73
+ nodes : list or iterable (optional)
74
+ Compute bipartite clustering for these nodes. The default
75
+ is all nodes in G.
76
+
77
+ mode : string
78
+ The pairwise bipartite clustering method to be used in the computation.
79
+ It must be "dot", "max", or "min".
80
+
81
+ Returns
82
+ -------
83
+ clustering : dictionary
84
+ A dictionary keyed by node with the clustering coefficient value.
85
+
86
+
87
+ Examples
88
+ --------
89
+ >>> from networkx.algorithms import bipartite
90
+ >>> G = nx.path_graph(4) # path graphs are bipartite
91
+ >>> c = bipartite.clustering(G)
92
+ >>> c[0]
93
+ 0.5
94
+ >>> c = bipartite.clustering(G, mode="min")
95
+ >>> c[0]
96
+ 1.0
97
+
98
+ See Also
99
+ --------
100
+ robins_alexander_clustering
101
+ average_clustering
102
+ networkx.algorithms.cluster.square_clustering
103
+
104
+ References
105
+ ----------
106
+ .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
107
+ Basic notions for the analysis of large two-mode networks.
108
+ Social Networks 30(1), 31--48.
109
+ """
110
+ if not nx.algorithms.bipartite.is_bipartite(G):
111
+ raise nx.NetworkXError("Graph is not bipartite")
112
+
113
+ try:
114
+ cc_func = modes[mode]
115
+ except KeyError as err:
116
+ raise nx.NetworkXError(
117
+ "Mode for bipartite clustering must be: dot, min or max"
118
+ ) from err
119
+
120
+ if nodes is None:
121
+ nodes = G
122
+ ccs = {}
123
+ for v in nodes:
124
+ cc = 0.0
125
+ nbrs2 = {u for nbr in G[v] for u in G[nbr]} - {v}
126
+ for u in nbrs2:
127
+ cc += cc_func(set(G[u]), set(G[v]))
128
+ if cc > 0.0: # len(nbrs2)>0
129
+ cc /= len(nbrs2)
130
+ ccs[v] = cc
131
+ return ccs
132
+
133
+
134
+ clustering = latapy_clustering
135
+
136
+
137
+ @nx._dispatchable(name="bipartite_average_clustering")
138
+ def average_clustering(G, nodes=None, mode="dot"):
139
+ r"""Compute the average bipartite clustering coefficient.
140
+
141
+ A clustering coefficient for the whole graph is the average,
142
+
143
+ .. math::
144
+
145
+ C = \frac{1}{n}\sum_{v \in G} c_v,
146
+
147
+ where `n` is the number of nodes in `G`.
148
+
149
+ Similar measures for the two bipartite sets can be defined [1]_
150
+
151
+ .. math::
152
+
153
+ C_X = \frac{1}{|X|}\sum_{v \in X} c_v,
154
+
155
+ where `X` is a bipartite set of `G`.
156
+
157
+ Parameters
158
+ ----------
159
+ G : graph
160
+ a bipartite graph
161
+
162
+ nodes : list or iterable, optional
163
+ A container of nodes to use in computing the average.
164
+ The nodes should be either the entire graph (the default) or one of the
165
+ bipartite sets.
166
+
167
+ mode : string
168
+ The pairwise bipartite clustering method.
169
+ It must be "dot", "max", or "min"
170
+
171
+ Returns
172
+ -------
173
+ clustering : float
174
+ The average bipartite clustering for the given set of nodes or the
175
+ entire graph if no nodes are specified.
176
+
177
+ Examples
178
+ --------
179
+ >>> from networkx.algorithms import bipartite
180
+ >>> G = nx.star_graph(3) # star graphs are bipartite
181
+ >>> bipartite.average_clustering(G)
182
+ 0.75
183
+ >>> X, Y = bipartite.sets(G)
184
+ >>> bipartite.average_clustering(G, X)
185
+ 0.0
186
+ >>> bipartite.average_clustering(G, Y)
187
+ 1.0
188
+
189
+ See Also
190
+ --------
191
+ clustering
192
+
193
+ Notes
194
+ -----
195
+ The container of nodes passed to this function must contain all of the nodes
196
+ in one of the bipartite sets ("top" or "bottom") in order to compute
197
+ the correct average bipartite clustering coefficients.
198
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
199
+ for further details on how bipartite graphs are handled in NetworkX.
200
+
201
+
202
+ References
203
+ ----------
204
+ .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
205
+ Basic notions for the analysis of large two-mode networks.
206
+ Social Networks 30(1), 31--48.
207
+ """
208
+ if nodes is None:
209
+ nodes = G
210
+ ccs = latapy_clustering(G, nodes=nodes, mode=mode)
211
+ return sum(ccs[v] for v in nodes) / len(nodes)
212
+
213
+
214
+ @nx._dispatchable
215
+ def robins_alexander_clustering(G):
216
+ r"""Compute the bipartite clustering of G.
217
+
218
+ Robins and Alexander [1]_ defined bipartite clustering coefficient as
219
+ four times the number of four cycles `C_4` divided by the number of
220
+ three paths `L_3` in a bipartite graph:
221
+
222
+ .. math::
223
+
224
+ CC_4 = \frac{4 * C_4}{L_3}
225
+
226
+ Parameters
227
+ ----------
228
+ G : graph
229
+ a bipartite graph
230
+
231
+ Returns
232
+ -------
233
+ clustering : float
234
+ The Robins and Alexander bipartite clustering for the input graph.
235
+
236
+ Examples
237
+ --------
238
+ >>> from networkx.algorithms import bipartite
239
+ >>> G = nx.davis_southern_women_graph()
240
+ >>> print(round(bipartite.robins_alexander_clustering(G), 3))
241
+ 0.468
242
+
243
+ See Also
244
+ --------
245
+ latapy_clustering
246
+ networkx.algorithms.cluster.square_clustering
247
+
248
+ References
249
+ ----------
250
+ .. [1] Robins, G. and M. Alexander (2004). Small worlds among interlocking
251
+ directors: Network structure and distance in bipartite graphs.
252
+ Computational & Mathematical Organization Theory 10(1), 69–94.
253
+
254
+ """
255
+ if G.order() < 4 or G.size() < 3:
256
+ return 0
257
+ L_3 = _threepaths(G)
258
+ if L_3 == 0:
259
+ return 0
260
+ C_4 = _four_cycles(G)
261
+ return (4.0 * C_4) / L_3
262
+
263
+
264
+ def _four_cycles(G):
265
+ cycles = 0
266
+ for v in G:
267
+ for u, w in itertools.combinations(G[v], 2):
268
+ cycles += len((set(G[u]) & set(G[w])) - {v})
269
+ return cycles / 4
270
+
271
+
272
+ def _threepaths(G):
273
+ paths = 0
274
+ for v in G:
275
+ for u in G[v]:
276
+ for w in set(G[u]) - {v}:
277
+ paths += len(set(G[w]) - {v, u})
278
+ # Divide by two because we count each three path twice
279
+ # one for each possible starting point
280
+ return paths / 2
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/covering.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Functions related to graph covers."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.bipartite.matching import hopcroft_karp_matching
5
+ from networkx.algorithms.covering import min_edge_cover as _min_edge_cover
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = ["min_edge_cover"]
9
+
10
+
11
+ @not_implemented_for("directed")
12
+ @not_implemented_for("multigraph")
13
+ @nx._dispatchable(name="bipartite_min_edge_cover")
14
+ def min_edge_cover(G, matching_algorithm=None):
15
+ """Returns a set of edges which constitutes
16
+ the minimum edge cover of the graph.
17
+
18
+ The smallest edge cover can be found in polynomial time by finding
19
+ a maximum matching and extending it greedily so that all nodes
20
+ are covered.
21
+
22
+ Parameters
23
+ ----------
24
+ G : NetworkX graph
25
+ An undirected bipartite graph.
26
+
27
+ matching_algorithm : function
28
+ A function that returns a maximum cardinality matching in a
29
+ given bipartite graph. The function must take one input, the
30
+ graph ``G``, and return a dictionary mapping each node to its
31
+ mate. If not specified,
32
+ :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
33
+ will be used. Other possibilities include
34
+ :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`,
35
+
36
+ Returns
37
+ -------
38
+ set
39
+ A set of the edges in a minimum edge cover of the graph, given as
40
+ pairs of nodes. It contains both the edges `(u, v)` and `(v, u)`
41
+ for given nodes `u` and `v` among the edges of minimum edge cover.
42
+
43
+ Notes
44
+ -----
45
+ An edge cover of a graph is a set of edges such that every node of
46
+ the graph is incident to at least one edge of the set.
47
+ A minimum edge cover is an edge covering of smallest cardinality.
48
+
49
+ Due to its implementation, the worst-case running time of this algorithm
50
+ is bounded by the worst-case running time of the function
51
+ ``matching_algorithm``.
52
+ """
53
+ if G.order() == 0: # Special case for the empty graph
54
+ return set()
55
+ if matching_algorithm is None:
56
+ matching_algorithm = hopcroft_karp_matching
57
+ return _min_edge_cover(G, matching_algorithm=matching_algorithm)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/edgelist.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ********************
3
+ Bipartite Edge Lists
4
+ ********************
5
+ Read and write NetworkX graphs as bipartite edge lists.
6
+
7
+ Format
8
+ ------
9
+ You can read or write three formats of edge lists with these functions.
10
+
11
+ Node pairs with no data::
12
+
13
+ 1 2
14
+
15
+ Python dictionary as data::
16
+
17
+ 1 2 {'weight':7, 'color':'green'}
18
+
19
+ Arbitrary data::
20
+
21
+ 1 2 7 green
22
+
23
+ For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.
24
+ """
25
+ __all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"]
26
+
27
+ import networkx as nx
28
+ from networkx.utils import not_implemented_for, open_file
29
+
30
+
31
+ @open_file(1, mode="wb")
32
+ def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"):
33
+ """Write a bipartite graph as a list of edges.
34
+
35
+ Parameters
36
+ ----------
37
+ G : Graph
38
+ A NetworkX bipartite graph
39
+ path : file or string
40
+ File or filename to write. If a file is provided, it must be
41
+ opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
42
+ comments : string, optional
43
+ The character used to indicate the start of a comment
44
+ delimiter : string, optional
45
+ The string used to separate values. The default is whitespace.
46
+ data : bool or list, optional
47
+ If False write no edge data.
48
+ If True write a string representation of the edge data dictionary..
49
+ If a list (or other iterable) is provided, write the keys specified
50
+ in the list.
51
+ encoding: string, optional
52
+ Specify which encoding to use when writing file.
53
+
54
+ Examples
55
+ --------
56
+ >>> G = nx.path_graph(4)
57
+ >>> G.add_nodes_from([0, 2], bipartite=0)
58
+ >>> G.add_nodes_from([1, 3], bipartite=1)
59
+ >>> nx.write_edgelist(G, "test.edgelist")
60
+ >>> fh = open("test.edgelist", "wb")
61
+ >>> nx.write_edgelist(G, fh)
62
+ >>> nx.write_edgelist(G, "test.edgelist.gz")
63
+ >>> nx.write_edgelist(G, "test.edgelist.gz", data=False)
64
+
65
+ >>> G = nx.Graph()
66
+ >>> G.add_edge(1, 2, weight=7, color="red")
67
+ >>> nx.write_edgelist(G, "test.edgelist", data=False)
68
+ >>> nx.write_edgelist(G, "test.edgelist", data=["color"])
69
+ >>> nx.write_edgelist(G, "test.edgelist", data=["color", "weight"])
70
+
71
+ See Also
72
+ --------
73
+ write_edgelist
74
+ generate_edgelist
75
+ """
76
+ for line in generate_edgelist(G, delimiter, data):
77
+ line += "\n"
78
+ path.write(line.encode(encoding))
79
+
80
+
81
+ @not_implemented_for("directed")
82
+ def generate_edgelist(G, delimiter=" ", data=True):
83
+ """Generate a single line of the bipartite graph G in edge list format.
84
+
85
+ Parameters
86
+ ----------
87
+ G : NetworkX graph
88
+ The graph is assumed to have node attribute `part` set to 0,1 representing
89
+ the two graph parts
90
+
91
+ delimiter : string, optional
92
+ Separator for node labels
93
+
94
+ data : bool or list of keys
95
+ If False generate no edge data. If True use a dictionary
96
+ representation of edge data. If a list of keys use a list of data
97
+ values corresponding to the keys.
98
+
99
+ Returns
100
+ -------
101
+ lines : string
102
+ Lines of data in adjlist format.
103
+
104
+ Examples
105
+ --------
106
+ >>> from networkx.algorithms import bipartite
107
+ >>> G = nx.path_graph(4)
108
+ >>> G.add_nodes_from([0, 2], bipartite=0)
109
+ >>> G.add_nodes_from([1, 3], bipartite=1)
110
+ >>> G[1][2]["weight"] = 3
111
+ >>> G[2][3]["capacity"] = 12
112
+ >>> for line in bipartite.generate_edgelist(G, data=False):
113
+ ... print(line)
114
+ 0 1
115
+ 2 1
116
+ 2 3
117
+
118
+ >>> for line in bipartite.generate_edgelist(G):
119
+ ... print(line)
120
+ 0 1 {}
121
+ 2 1 {'weight': 3}
122
+ 2 3 {'capacity': 12}
123
+
124
+ >>> for line in bipartite.generate_edgelist(G, data=["weight"]):
125
+ ... print(line)
126
+ 0 1
127
+ 2 1 3
128
+ 2 3
129
+ """
130
+ try:
131
+ part0 = [n for n, d in G.nodes.items() if d["bipartite"] == 0]
132
+ except BaseException as err:
133
+ raise AttributeError("Missing node attribute `bipartite`") from err
134
+ if data is True or data is False:
135
+ for n in part0:
136
+ for edge in G.edges(n, data=data):
137
+ yield delimiter.join(map(str, edge))
138
+ else:
139
+ for n in part0:
140
+ for u, v, d in G.edges(n, data=True):
141
+ edge = [u, v]
142
+ try:
143
+ edge.extend(d[k] for k in data)
144
+ except KeyError:
145
+ pass # missing data for this edge, should warn?
146
+ yield delimiter.join(map(str, edge))
147
+
148
+
149
+ @nx._dispatchable(name="bipartite_parse_edgelist", graphs=None, returns_graph=True)
150
+ def parse_edgelist(
151
+ lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True
152
+ ):
153
+ """Parse lines of an edge list representation of a bipartite graph.
154
+
155
+ Parameters
156
+ ----------
157
+ lines : list or iterator of strings
158
+ Input data in edgelist format
159
+ comments : string, optional
160
+ Marker for comment lines
161
+ delimiter : string, optional
162
+ Separator for node labels
163
+ create_using: NetworkX graph container, optional
164
+ Use given NetworkX graph for holding nodes or edges.
165
+ nodetype : Python type, optional
166
+ Convert nodes to this type.
167
+ data : bool or list of (label,type) tuples
168
+ If False generate no edge data or if True use a dictionary
169
+ representation of edge data or a list tuples specifying dictionary
170
+ key names and types for edge data.
171
+
172
+ Returns
173
+ -------
174
+ G: NetworkX Graph
175
+ The bipartite graph corresponding to lines
176
+
177
+ Examples
178
+ --------
179
+ Edgelist with no data:
180
+
181
+ >>> from networkx.algorithms import bipartite
182
+ >>> lines = ["1 2", "2 3", "3 4"]
183
+ >>> G = bipartite.parse_edgelist(lines, nodetype=int)
184
+ >>> sorted(G.nodes())
185
+ [1, 2, 3, 4]
186
+ >>> sorted(G.nodes(data=True))
187
+ [(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {'bipartite': 1})]
188
+ >>> sorted(G.edges())
189
+ [(1, 2), (2, 3), (3, 4)]
190
+
191
+ Edgelist with data in Python dictionary representation:
192
+
193
+ >>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"]
194
+ >>> G = bipartite.parse_edgelist(lines, nodetype=int)
195
+ >>> sorted(G.nodes())
196
+ [1, 2, 3, 4]
197
+ >>> sorted(G.edges(data=True))
198
+ [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
199
+
200
+ Edgelist with data in a list:
201
+
202
+ >>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]
203
+ >>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
204
+ >>> sorted(G.nodes())
205
+ [1, 2, 3, 4]
206
+ >>> sorted(G.edges(data=True))
207
+ [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
208
+
209
+ See Also
210
+ --------
211
+ """
212
+ from ast import literal_eval
213
+
214
+ G = nx.empty_graph(0, create_using)
215
+ for line in lines:
216
+ p = line.find(comments)
217
+ if p >= 0:
218
+ line = line[:p]
219
+ if not len(line):
220
+ continue
221
+ # split line, should have 2 or more
222
+ s = line.strip().split(delimiter)
223
+ if len(s) < 2:
224
+ continue
225
+ u = s.pop(0)
226
+ v = s.pop(0)
227
+ d = s
228
+ if nodetype is not None:
229
+ try:
230
+ u = nodetype(u)
231
+ v = nodetype(v)
232
+ except BaseException as err:
233
+ raise TypeError(
234
+ f"Failed to convert nodes {u},{v} to type {nodetype}."
235
+ ) from err
236
+
237
+ if len(d) == 0 or data is False:
238
+ # no data or data type specified
239
+ edgedata = {}
240
+ elif data is True:
241
+ # no edge types specified
242
+ try: # try to evaluate as dictionary
243
+ edgedata = dict(literal_eval(" ".join(d)))
244
+ except BaseException as err:
245
+ raise TypeError(
246
+ f"Failed to convert edge data ({d}) to dictionary."
247
+ ) from err
248
+ else:
249
+ # convert edge data to dictionary with specified keys and type
250
+ if len(d) != len(data):
251
+ raise IndexError(
252
+ f"Edge data {d} and data_keys {data} are not the same length"
253
+ )
254
+ edgedata = {}
255
+ for (edge_key, edge_type), edge_value in zip(data, d):
256
+ try:
257
+ edge_value = edge_type(edge_value)
258
+ except BaseException as err:
259
+ raise TypeError(
260
+ f"Failed to convert {edge_key} data "
261
+ f"{edge_value} to type {edge_type}."
262
+ ) from err
263
+ edgedata.update({edge_key: edge_value})
264
+ G.add_node(u, bipartite=0)
265
+ G.add_node(v, bipartite=1)
266
+ G.add_edge(u, v, **edgedata)
267
+ return G
268
+
269
+
270
+ @open_file(0, mode="rb")
271
+ @nx._dispatchable(name="bipartite_read_edgelist", graphs=None, returns_graph=True)
272
+ def read_edgelist(
273
+ path,
274
+ comments="#",
275
+ delimiter=None,
276
+ create_using=None,
277
+ nodetype=None,
278
+ data=True,
279
+ edgetype=None,
280
+ encoding="utf-8",
281
+ ):
282
+ """Read a bipartite graph from a list of edges.
283
+
284
+ Parameters
285
+ ----------
286
+ path : file or string
287
+ File or filename to read. If a file is provided, it must be
288
+ opened in 'rb' mode.
289
+ Filenames ending in .gz or .bz2 will be uncompressed.
290
+ comments : string, optional
291
+ The character used to indicate the start of a comment.
292
+ delimiter : string, optional
293
+ The string used to separate values. The default is whitespace.
294
+ create_using : Graph container, optional,
295
+ Use specified container to build graph. The default is networkx.Graph,
296
+ an undirected graph.
297
+ nodetype : int, float, str, Python type, optional
298
+ Convert node data from strings to specified type
299
+ data : bool or list of (label,type) tuples
300
+ Tuples specifying dictionary key names and types for edge data
301
+ edgetype : int, float, str, Python type, optional OBSOLETE
302
+ Convert edge data from strings to specified type and use as 'weight'
303
+ encoding: string, optional
304
+ Specify which encoding to use when reading file.
305
+
306
+ Returns
307
+ -------
308
+ G : graph
309
+ A networkx Graph or other type specified with create_using
310
+
311
+ Examples
312
+ --------
313
+ >>> from networkx.algorithms import bipartite
314
+ >>> G = nx.path_graph(4)
315
+ >>> G.add_nodes_from([0, 2], bipartite=0)
316
+ >>> G.add_nodes_from([1, 3], bipartite=1)
317
+ >>> bipartite.write_edgelist(G, "test.edgelist")
318
+ >>> G = bipartite.read_edgelist("test.edgelist")
319
+
320
+ >>> fh = open("test.edgelist", "rb")
321
+ >>> G = bipartite.read_edgelist(fh)
322
+ >>> fh.close()
323
+
324
+ >>> G = bipartite.read_edgelist("test.edgelist", nodetype=int)
325
+
326
+ Edgelist with data in a list:
327
+
328
+ >>> textline = "1 2 3"
329
+ >>> fh = open("test.edgelist", "w")
330
+ >>> d = fh.write(textline)
331
+ >>> fh.close()
332
+ >>> G = bipartite.read_edgelist(
333
+ ... "test.edgelist", nodetype=int, data=(("weight", float),)
334
+ ... )
335
+ >>> list(G)
336
+ [1, 2]
337
+ >>> list(G.edges(data=True))
338
+ [(1, 2, {'weight': 3.0})]
339
+
340
+ See parse_edgelist() for more examples of formatting.
341
+
342
+ See Also
343
+ --------
344
+ parse_edgelist
345
+
346
+ Notes
347
+ -----
348
+ Since nodes must be hashable, the function nodetype must return hashable
349
+ types (e.g. int, float, str, frozenset - or tuples of those, etc.)
350
+ """
351
+ lines = (line.decode(encoding) for line in path)
352
+ return parse_edgelist(
353
+ lines,
354
+ comments=comments,
355
+ delimiter=delimiter,
356
+ create_using=create_using,
357
+ nodetype=nodetype,
358
+ data=data,
359
+ )
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/extendability.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Provides a function for computing the extendability of a graph which is
2
+ undirected, simple, connected and bipartite and contains at least one perfect matching."""
3
+
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = ["maximal_extendability"]
9
+
10
+
11
+ @not_implemented_for("directed")
12
+ @not_implemented_for("multigraph")
13
+ @nx._dispatchable
14
+ def maximal_extendability(G):
15
+ """Computes the extendability of a graph.
16
+
17
+ The extendability of a graph is defined as the maximum $k$ for which `G`
18
+ is $k$-extendable. Graph `G` is $k$-extendable if and only if `G` has a
19
+ perfect matching and every set of $k$ independent edges can be extended
20
+ to a perfect matching in `G`.
21
+
22
+ Parameters
23
+ ----------
24
+ G : NetworkX Graph
25
+ A fully-connected bipartite graph without self-loops
26
+
27
+ Returns
28
+ -------
29
+ extendability : int
30
+
31
+ Raises
32
+ ------
33
+ NetworkXError
34
+ If the graph `G` is disconnected.
35
+ If the graph `G` is not bipartite.
36
+ If the graph `G` does not contain a perfect matching.
37
+ If the residual graph of `G` is not strongly connected.
38
+
39
+ Notes
40
+ -----
41
+ Definition:
42
+ Let `G` be a simple, connected, undirected and bipartite graph with a perfect
43
+ matching M and bipartition (U,V). The residual graph of `G`, denoted by $G_M$,
44
+ is the graph obtained from G by directing the edges of M from V to U and the
45
+ edges that do not belong to M from U to V.
46
+
47
+ Lemma [1]_ :
48
+ Let M be a perfect matching of `G`. `G` is $k$-extendable if and only if its residual
49
+ graph $G_M$ is strongly connected and there are $k$ vertex-disjoint directed
50
+ paths between every vertex of U and every vertex of V.
51
+
52
+ Assuming that input graph `G` is undirected, simple, connected, bipartite and contains
53
+ a perfect matching M, this function constructs the residual graph $G_M$ of G and
54
+ returns the minimum value among the maximum vertex-disjoint directed paths between
55
+ every vertex of U and every vertex of V in $G_M$. By combining the definitions
56
+ and the lemma, this value represents the extendability of the graph `G`.
57
+
58
+ Time complexity O($n^3$ $m^2$)) where $n$ is the number of vertices
59
+ and $m$ is the number of edges.
60
+
61
+ References
62
+ ----------
63
+ .. [1] "A polynomial algorithm for the extendability problem in bipartite graphs",
64
+ J. Lakhal, L. Litzler, Information Processing Letters, 1998.
65
+ .. [2] "On n-extendible graphs", M. D. Plummer, Discrete Mathematics, 31:201–210, 1980
66
+ https://doi.org/10.1016/0012-365X(80)90037-0
67
+
68
+ """
69
+ if not nx.is_connected(G):
70
+ raise nx.NetworkXError("Graph G is not connected")
71
+
72
+ if not nx.bipartite.is_bipartite(G):
73
+ raise nx.NetworkXError("Graph G is not bipartite")
74
+
75
+ U, V = nx.bipartite.sets(G)
76
+
77
+ maximum_matching = nx.bipartite.hopcroft_karp_matching(G)
78
+
79
+ if not nx.is_perfect_matching(G, maximum_matching):
80
+ raise nx.NetworkXError("Graph G does not contain a perfect matching")
81
+
82
+ # list of edges in perfect matching, directed from V to U
83
+ pm = [(node, maximum_matching[node]) for node in V & maximum_matching.keys()]
84
+
85
+ # Direct all the edges of G, from V to U if in matching, else from U to V
86
+ directed_edges = [
87
+ (x, y) if (x in V and (x, y) in pm) or (x in U and (y, x) not in pm) else (y, x)
88
+ for x, y in G.edges
89
+ ]
90
+
91
+ # Construct the residual graph of G
92
+ residual_G = nx.DiGraph()
93
+ residual_G.add_nodes_from(G)
94
+ residual_G.add_edges_from(directed_edges)
95
+
96
+ if not nx.is_strongly_connected(residual_G):
97
+ raise nx.NetworkXError("The residual graph of G is not strongly connected")
98
+
99
+ # For node-pairs between V & U, keep min of max number of node-disjoint paths
100
+ # Variable $k$ stands for the extendability of graph G
101
+ k = float("inf")
102
+ for u in U:
103
+ for v in V:
104
+ num_paths = sum(1 for _ in nx.node_disjoint_paths(residual_G, u, v))
105
+ k = k if k < num_paths else num_paths
106
+ return k
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/generators.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators and functions for bipartite graphs.
3
+ """
4
+ import math
5
+ import numbers
6
+ from functools import reduce
7
+
8
+ import networkx as nx
9
+ from networkx.utils import nodes_or_number, py_random_state
10
+
11
+ __all__ = [
12
+ "configuration_model",
13
+ "havel_hakimi_graph",
14
+ "reverse_havel_hakimi_graph",
15
+ "alternating_havel_hakimi_graph",
16
+ "preferential_attachment_graph",
17
+ "random_graph",
18
+ "gnmk_random_graph",
19
+ "complete_bipartite_graph",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(graphs=None, returns_graph=True)
24
+ @nodes_or_number([0, 1])
25
+ def complete_bipartite_graph(n1, n2, create_using=None):
26
+ """Returns the complete bipartite graph `K_{n_1,n_2}`.
27
+
28
+ The graph is composed of two partitions with nodes 0 to (n1 - 1)
29
+ in the first and nodes n1 to (n1 + n2 - 1) in the second.
30
+ Each node in the first is connected to each node in the second.
31
+
32
+ Parameters
33
+ ----------
34
+ n1, n2 : integer or iterable container of nodes
35
+ If integers, nodes are from `range(n1)` and `range(n1, n1 + n2)`.
36
+ If a container, the elements are the nodes.
37
+ create_using : NetworkX graph instance, (default: nx.Graph)
38
+ Return graph of this type.
39
+
40
+ Notes
41
+ -----
42
+ Nodes are the integers 0 to `n1 + n2 - 1` unless either n1 or n2 are
43
+ containers of nodes. If only one of n1 or n2 are integers, that
44
+ integer is replaced by `range` of that integer.
45
+
46
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
47
+ to indicate which bipartite set the node belongs to.
48
+
49
+ This function is not imported in the main namespace.
50
+ To use it use nx.bipartite.complete_bipartite_graph
51
+ """
52
+ G = nx.empty_graph(0, create_using)
53
+ if G.is_directed():
54
+ raise nx.NetworkXError("Directed Graph not supported")
55
+
56
+ n1, top = n1
57
+ n2, bottom = n2
58
+ if isinstance(n1, numbers.Integral) and isinstance(n2, numbers.Integral):
59
+ bottom = [n1 + i for i in bottom]
60
+ G.add_nodes_from(top, bipartite=0)
61
+ G.add_nodes_from(bottom, bipartite=1)
62
+ if len(G) != len(top) + len(bottom):
63
+ raise nx.NetworkXError("Inputs n1 and n2 must contain distinct nodes")
64
+ G.add_edges_from((u, v) for u in top for v in bottom)
65
+ G.graph["name"] = f"complete_bipartite_graph({n1}, {n2})"
66
+ return G
67
+
68
+
69
+ @py_random_state(3)
70
+ @nx._dispatchable(name="bipartite_configuration_model", graphs=None, returns_graph=True)
71
+ def configuration_model(aseq, bseq, create_using=None, seed=None):
72
+ """Returns a random bipartite graph from two given degree sequences.
73
+
74
+ Parameters
75
+ ----------
76
+ aseq : list
77
+ Degree sequence for node set A.
78
+ bseq : list
79
+ Degree sequence for node set B.
80
+ create_using : NetworkX graph instance, optional
81
+ Return graph of this type.
82
+ seed : integer, random_state, or None (default)
83
+ Indicator of random number generation state.
84
+ See :ref:`Randomness<randomness>`.
85
+
86
+ The graph is composed of two partitions. Set A has nodes 0 to
87
+ (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
88
+ Nodes from set A are connected to nodes in set B by choosing
89
+ randomly from the possible free stubs, one in A and one in B.
90
+
91
+ Notes
92
+ -----
93
+ The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
94
+ If no graph type is specified use MultiGraph with parallel edges.
95
+ If you want a graph with no parallel edges use create_using=Graph()
96
+ but then the resulting degree sequences might not be exact.
97
+
98
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
99
+ to indicate which bipartite set the node belongs to.
100
+
101
+ This function is not imported in the main namespace.
102
+ To use it use nx.bipartite.configuration_model
103
+ """
104
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
105
+ if G.is_directed():
106
+ raise nx.NetworkXError("Directed Graph not supported")
107
+
108
+ # length and sum of each sequence
109
+ lena = len(aseq)
110
+ lenb = len(bseq)
111
+ suma = sum(aseq)
112
+ sumb = sum(bseq)
113
+
114
+ if not suma == sumb:
115
+ raise nx.NetworkXError(
116
+ f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
117
+ )
118
+
119
+ G = _add_nodes_with_bipartite_label(G, lena, lenb)
120
+
121
+ if len(aseq) == 0 or max(aseq) == 0:
122
+ return G # done if no edges
123
+
124
+ # build lists of degree-repeated vertex numbers
125
+ stubs = [[v] * aseq[v] for v in range(lena)]
126
+ astubs = [x for subseq in stubs for x in subseq]
127
+
128
+ stubs = [[v] * bseq[v - lena] for v in range(lena, lena + lenb)]
129
+ bstubs = [x for subseq in stubs for x in subseq]
130
+
131
+ # shuffle lists
132
+ seed.shuffle(astubs)
133
+ seed.shuffle(bstubs)
134
+
135
+ G.add_edges_from([astubs[i], bstubs[i]] for i in range(suma))
136
+
137
+ G.name = "bipartite_configuration_model"
138
+ return G
139
+
140
+
141
+ @nx._dispatchable(name="bipartite_havel_hakimi_graph", graphs=None, returns_graph=True)
142
+ def havel_hakimi_graph(aseq, bseq, create_using=None):
143
+ """Returns a bipartite graph from two given degree sequences using a
144
+ Havel-Hakimi style construction.
145
+
146
+ The graph is composed of two partitions. Set A has nodes 0 to
147
+ (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
148
+ Nodes from the set A are connected to nodes in the set B by
149
+ connecting the highest degree nodes in set A to the highest degree
150
+ nodes in set B until all stubs are connected.
151
+
152
+ Parameters
153
+ ----------
154
+ aseq : list
155
+ Degree sequence for node set A.
156
+ bseq : list
157
+ Degree sequence for node set B.
158
+ create_using : NetworkX graph instance, optional
159
+ Return graph of this type.
160
+
161
+ Notes
162
+ -----
163
+ The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
164
+ If no graph type is specified use MultiGraph with parallel edges.
165
+ If you want a graph with no parallel edges use create_using=Graph()
166
+ but then the resulting degree sequences might not be exact.
167
+
168
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
169
+ to indicate which bipartite set the node belongs to.
170
+
171
+ This function is not imported in the main namespace.
172
+ To use it use nx.bipartite.havel_hakimi_graph
173
+ """
174
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
175
+ if G.is_directed():
176
+ raise nx.NetworkXError("Directed Graph not supported")
177
+
178
+ # length of the each sequence
179
+ naseq = len(aseq)
180
+ nbseq = len(bseq)
181
+
182
+ suma = sum(aseq)
183
+ sumb = sum(bseq)
184
+
185
+ if not suma == sumb:
186
+ raise nx.NetworkXError(
187
+ f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
188
+ )
189
+
190
+ G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
191
+
192
+ if len(aseq) == 0 or max(aseq) == 0:
193
+ return G # done if no edges
194
+
195
+ # build list of degree-repeated vertex numbers
196
+ astubs = [[aseq[v], v] for v in range(naseq)]
197
+ bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)]
198
+ astubs.sort()
199
+ while astubs:
200
+ (degree, u) = astubs.pop() # take of largest degree node in the a set
201
+ if degree == 0:
202
+ break # done, all are zero
203
+ # connect the source to largest degree nodes in the b set
204
+ bstubs.sort()
205
+ for target in bstubs[-degree:]:
206
+ v = target[1]
207
+ G.add_edge(u, v)
208
+ target[0] -= 1 # note this updates bstubs too.
209
+ if target[0] == 0:
210
+ bstubs.remove(target)
211
+
212
+ G.name = "bipartite_havel_hakimi_graph"
213
+ return G
214
+
215
+
216
+ @nx._dispatchable(graphs=None, returns_graph=True)
217
+ def reverse_havel_hakimi_graph(aseq, bseq, create_using=None):
218
+ """Returns a bipartite graph from two given degree sequences using a
219
+ Havel-Hakimi style construction.
220
+
221
+ The graph is composed of two partitions. Set A has nodes 0 to
222
+ (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
223
+ Nodes from set A are connected to nodes in the set B by connecting
224
+ the highest degree nodes in set A to the lowest degree nodes in
225
+ set B until all stubs are connected.
226
+
227
+ Parameters
228
+ ----------
229
+ aseq : list
230
+ Degree sequence for node set A.
231
+ bseq : list
232
+ Degree sequence for node set B.
233
+ create_using : NetworkX graph instance, optional
234
+ Return graph of this type.
235
+
236
+ Notes
237
+ -----
238
+ The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
239
+ If no graph type is specified use MultiGraph with parallel edges.
240
+ If you want a graph with no parallel edges use create_using=Graph()
241
+ but then the resulting degree sequences might not be exact.
242
+
243
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
244
+ to indicate which bipartite set the node belongs to.
245
+
246
+ This function is not imported in the main namespace.
247
+ To use it use nx.bipartite.reverse_havel_hakimi_graph
248
+ """
249
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
250
+ if G.is_directed():
251
+ raise nx.NetworkXError("Directed Graph not supported")
252
+
253
+ # length of the each sequence
254
+ lena = len(aseq)
255
+ lenb = len(bseq)
256
+ suma = sum(aseq)
257
+ sumb = sum(bseq)
258
+
259
+ if not suma == sumb:
260
+ raise nx.NetworkXError(
261
+ f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
262
+ )
263
+
264
+ G = _add_nodes_with_bipartite_label(G, lena, lenb)
265
+
266
+ if len(aseq) == 0 or max(aseq) == 0:
267
+ return G # done if no edges
268
+
269
+ # build list of degree-repeated vertex numbers
270
+ astubs = [[aseq[v], v] for v in range(lena)]
271
+ bstubs = [[bseq[v - lena], v] for v in range(lena, lena + lenb)]
272
+ astubs.sort()
273
+ bstubs.sort()
274
+ while astubs:
275
+ (degree, u) = astubs.pop() # take of largest degree node in the a set
276
+ if degree == 0:
277
+ break # done, all are zero
278
+ # connect the source to the smallest degree nodes in the b set
279
+ for target in bstubs[0:degree]:
280
+ v = target[1]
281
+ G.add_edge(u, v)
282
+ target[0] -= 1 # note this updates bstubs too.
283
+ if target[0] == 0:
284
+ bstubs.remove(target)
285
+
286
+ G.name = "bipartite_reverse_havel_hakimi_graph"
287
+ return G
288
+
289
+
290
+ @nx._dispatchable(graphs=None, returns_graph=True)
291
+ def alternating_havel_hakimi_graph(aseq, bseq, create_using=None):
292
+ """Returns a bipartite graph from two given degree sequences using
293
+ an alternating Havel-Hakimi style construction.
294
+
295
+ The graph is composed of two partitions. Set A has nodes 0 to
296
+ (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
297
+ Nodes from the set A are connected to nodes in the set B by
298
+ connecting the highest degree nodes in set A to alternatively the
299
+ highest and the lowest degree nodes in set B until all stubs are
300
+ connected.
301
+
302
+ Parameters
303
+ ----------
304
+ aseq : list
305
+ Degree sequence for node set A.
306
+ bseq : list
307
+ Degree sequence for node set B.
308
+ create_using : NetworkX graph instance, optional
309
+ Return graph of this type.
310
+
311
+ Notes
312
+ -----
313
+ The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
314
+ If no graph type is specified use MultiGraph with parallel edges.
315
+ If you want a graph with no parallel edges use create_using=Graph()
316
+ but then the resulting degree sequences might not be exact.
317
+
318
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
319
+ to indicate which bipartite set the node belongs to.
320
+
321
+ This function is not imported in the main namespace.
322
+ To use it use nx.bipartite.alternating_havel_hakimi_graph
323
+ """
324
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
325
+ if G.is_directed():
326
+ raise nx.NetworkXError("Directed Graph not supported")
327
+
328
+ # length of the each sequence
329
+ naseq = len(aseq)
330
+ nbseq = len(bseq)
331
+ suma = sum(aseq)
332
+ sumb = sum(bseq)
333
+
334
+ if not suma == sumb:
335
+ raise nx.NetworkXError(
336
+ f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
337
+ )
338
+
339
+ G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
340
+
341
+ if len(aseq) == 0 or max(aseq) == 0:
342
+ return G # done if no edges
343
+ # build list of degree-repeated vertex numbers
344
+ astubs = [[aseq[v], v] for v in range(naseq)]
345
+ bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)]
346
+ while astubs:
347
+ astubs.sort()
348
+ (degree, u) = astubs.pop() # take of largest degree node in the a set
349
+ if degree == 0:
350
+ break # done, all are zero
351
+ bstubs.sort()
352
+ small = bstubs[0 : degree // 2] # add these low degree targets
353
+ large = bstubs[(-degree + degree // 2) :] # now high degree targets
354
+ stubs = [x for z in zip(large, small) for x in z] # combine, sorry
355
+ if len(stubs) < len(small) + len(large): # check for zip truncation
356
+ stubs.append(large.pop())
357
+ for target in stubs:
358
+ v = target[1]
359
+ G.add_edge(u, v)
360
+ target[0] -= 1 # note this updates bstubs too.
361
+ if target[0] == 0:
362
+ bstubs.remove(target)
363
+
364
+ G.name = "bipartite_alternating_havel_hakimi_graph"
365
+ return G
366
+
367
+
368
+ @py_random_state(3)
369
+ @nx._dispatchable(graphs=None, returns_graph=True)
370
+ def preferential_attachment_graph(aseq, p, create_using=None, seed=None):
371
+ """Create a bipartite graph with a preferential attachment model from
372
+ a given single degree sequence.
373
+
374
+ The graph is composed of two partitions. Set A has nodes 0 to
375
+ (len(aseq) - 1) and set B has nodes starting with node len(aseq).
376
+ The number of nodes in set B is random.
377
+
378
+ Parameters
379
+ ----------
380
+ aseq : list
381
+ Degree sequence for node set A.
382
+ p : float
383
+ Probability that a new bottom node is added.
384
+ create_using : NetworkX graph instance, optional
385
+ Return graph of this type.
386
+ seed : integer, random_state, or None (default)
387
+ Indicator of random number generation state.
388
+ See :ref:`Randomness<randomness>`.
389
+
390
+ References
391
+ ----------
392
+ .. [1] Guillaume, J.L. and Latapy, M.,
393
+ Bipartite graphs as models of complex networks.
394
+ Physica A: Statistical Mechanics and its Applications,
395
+ 2006, 371(2), pp.795-813.
396
+ .. [2] Jean-Loup Guillaume and Matthieu Latapy,
397
+ Bipartite structure of all complex networks,
398
+ Inf. Process. Lett. 90, 2004, pg. 215-221
399
+ https://doi.org/10.1016/j.ipl.2004.03.007
400
+
401
+ Notes
402
+ -----
403
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
404
+ to indicate which bipartite set the node belongs to.
405
+
406
+ This function is not imported in the main namespace.
407
+ To use it use nx.bipartite.preferential_attachment_graph
408
+ """
409
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
410
+ if G.is_directed():
411
+ raise nx.NetworkXError("Directed Graph not supported")
412
+
413
+ if p > 1:
414
+ raise nx.NetworkXError(f"probability {p} > 1")
415
+
416
+ naseq = len(aseq)
417
+ G = _add_nodes_with_bipartite_label(G, naseq, 0)
418
+ vv = [[v] * aseq[v] for v in range(naseq)]
419
+ while vv:
420
+ while vv[0]:
421
+ source = vv[0][0]
422
+ vv[0].remove(source)
423
+ if seed.random() < p or len(G) == naseq:
424
+ target = len(G)
425
+ G.add_node(target, bipartite=1)
426
+ G.add_edge(source, target)
427
+ else:
428
+ bb = [[b] * G.degree(b) for b in range(naseq, len(G))]
429
+ # flatten the list of lists into a list.
430
+ bbstubs = reduce(lambda x, y: x + y, bb)
431
+ # choose preferentially a bottom node.
432
+ target = seed.choice(bbstubs)
433
+ G.add_node(target, bipartite=1)
434
+ G.add_edge(source, target)
435
+ vv.remove(vv[0])
436
+ G.name = "bipartite_preferential_attachment_model"
437
+ return G
438
+
439
+
440
+ @py_random_state(3)
441
+ @nx._dispatchable(graphs=None, returns_graph=True)
442
+ def random_graph(n, m, p, seed=None, directed=False):
443
+ """Returns a bipartite random graph.
444
+
445
+ This is a bipartite version of the binomial (Erdős-Rényi) graph.
446
+ The graph is composed of two partitions. Set A has nodes 0 to
447
+ (n - 1) and set B has nodes n to (n + m - 1).
448
+
449
+ Parameters
450
+ ----------
451
+ n : int
452
+ The number of nodes in the first bipartite set.
453
+ m : int
454
+ The number of nodes in the second bipartite set.
455
+ p : float
456
+ Probability for edge creation.
457
+ seed : integer, random_state, or None (default)
458
+ Indicator of random number generation state.
459
+ See :ref:`Randomness<randomness>`.
460
+ directed : bool, optional (default=False)
461
+ If True return a directed graph
462
+
463
+ Notes
464
+ -----
465
+ The bipartite random graph algorithm chooses each of the n*m (undirected)
466
+ or 2*nm (directed) possible edges with probability p.
467
+
468
+ This algorithm is $O(n+m)$ where $m$ is the expected number of edges.
469
+
470
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
471
+ to indicate which bipartite set the node belongs to.
472
+
473
+ This function is not imported in the main namespace.
474
+ To use it use nx.bipartite.random_graph
475
+
476
+ See Also
477
+ --------
478
+ gnp_random_graph, configuration_model
479
+
480
+ References
481
+ ----------
482
+ .. [1] Vladimir Batagelj and Ulrik Brandes,
483
+ "Efficient generation of large random networks",
484
+ Phys. Rev. E, 71, 036113, 2005.
485
+ """
486
+ G = nx.Graph()
487
+ G = _add_nodes_with_bipartite_label(G, n, m)
488
+ if directed:
489
+ G = nx.DiGraph(G)
490
+ G.name = f"fast_gnp_random_graph({n},{m},{p})"
491
+
492
+ if p <= 0:
493
+ return G
494
+ if p >= 1:
495
+ return nx.complete_bipartite_graph(n, m)
496
+
497
+ lp = math.log(1.0 - p)
498
+
499
+ v = 0
500
+ w = -1
501
+ while v < n:
502
+ lr = math.log(1.0 - seed.random())
503
+ w = w + 1 + int(lr / lp)
504
+ while w >= m and v < n:
505
+ w = w - m
506
+ v = v + 1
507
+ if v < n:
508
+ G.add_edge(v, n + w)
509
+
510
+ if directed:
511
+ # use the same algorithm to
512
+ # add edges from the "m" to "n" set
513
+ v = 0
514
+ w = -1
515
+ while v < n:
516
+ lr = math.log(1.0 - seed.random())
517
+ w = w + 1 + int(lr / lp)
518
+ while w >= m and v < n:
519
+ w = w - m
520
+ v = v + 1
521
+ if v < n:
522
+ G.add_edge(n + w, v)
523
+
524
+ return G
525
+
526
+
527
+ @py_random_state(3)
528
+ @nx._dispatchable(graphs=None, returns_graph=True)
529
+ def gnmk_random_graph(n, m, k, seed=None, directed=False):
530
+ """Returns a random bipartite graph G_{n,m,k}.
531
+
532
+ Produces a bipartite graph chosen randomly out of the set of all graphs
533
+ with n top nodes, m bottom nodes, and k edges.
534
+ The graph is composed of two sets of nodes.
535
+ Set A has nodes 0 to (n - 1) and set B has nodes n to (n + m - 1).
536
+
537
+ Parameters
538
+ ----------
539
+ n : int
540
+ The number of nodes in the first bipartite set.
541
+ m : int
542
+ The number of nodes in the second bipartite set.
543
+ k : int
544
+ The number of edges
545
+ seed : integer, random_state, or None (default)
546
+ Indicator of random number generation state.
547
+ See :ref:`Randomness<randomness>`.
548
+ directed : bool, optional (default=False)
549
+ If True return a directed graph
550
+
551
+ Examples
552
+ --------
553
+ from nx.algorithms import bipartite
554
+ G = bipartite.gnmk_random_graph(10,20,50)
555
+
556
+ See Also
557
+ --------
558
+ gnm_random_graph
559
+
560
+ Notes
561
+ -----
562
+ If k > m * n then a complete bipartite graph is returned.
563
+
564
+ This graph is a bipartite version of the `G_{nm}` random graph model.
565
+
566
+ The nodes are assigned the attribute 'bipartite' with the value 0 or 1
567
+ to indicate which bipartite set the node belongs to.
568
+
569
+ This function is not imported in the main namespace.
570
+ To use it use nx.bipartite.gnmk_random_graph
571
+ """
572
+ G = nx.Graph()
573
+ G = _add_nodes_with_bipartite_label(G, n, m)
574
+ if directed:
575
+ G = nx.DiGraph(G)
576
+ G.name = f"bipartite_gnm_random_graph({n},{m},{k})"
577
+ if n == 1 or m == 1:
578
+ return G
579
+ max_edges = n * m # max_edges for bipartite networks
580
+ if k >= max_edges: # Maybe we should raise an exception here
581
+ return nx.complete_bipartite_graph(n, m, create_using=G)
582
+
583
+ top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0]
584
+ bottom = list(set(G) - set(top))
585
+ edge_count = 0
586
+ while edge_count < k:
587
+ # generate random edge,u,v
588
+ u = seed.choice(top)
589
+ v = seed.choice(bottom)
590
+ if v in G[u]:
591
+ continue
592
+ else:
593
+ G.add_edge(u, v)
594
+ edge_count += 1
595
+ return G
596
+
597
+
598
+ def _add_nodes_with_bipartite_label(G, lena, lenb):
599
+ G.add_nodes_from(range(lena + lenb))
600
+ b = dict(zip(range(lena), [0] * lena))
601
+ b.update(dict(zip(range(lena, lena + lenb), [1] * lenb)))
602
+ nx.set_node_attributes(G, b, "bipartite")
603
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/matching.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module uses material from the Wikipedia article Hopcroft--Karp algorithm
2
+ # <https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>, accessed on
3
+ # January 3, 2015, which is released under the Creative Commons
4
+ # Attribution-Share-Alike License 3.0
5
+ # <http://creativecommons.org/licenses/by-sa/3.0/>. That article includes
6
+ # pseudocode, which has been translated into the corresponding Python code.
7
+ #
8
+ # Portions of this module use code from David Eppstein's Python Algorithms and
9
+ # Data Structures (PADS) library, which is dedicated to the public domain (for
10
+ # proof, see <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>).
11
+ """Provides functions for computing maximum cardinality matchings and minimum
12
+ weight full matchings in a bipartite graph.
13
+
14
+ If you don't care about the particular implementation of the maximum matching
15
+ algorithm, simply use the :func:`maximum_matching`. If you do care, you can
16
+ import one of the named maximum matching algorithms directly.
17
+
18
+ For example, to find a maximum matching in the complete bipartite graph with
19
+ two vertices on the left and three vertices on the right:
20
+
21
+ >>> G = nx.complete_bipartite_graph(2, 3)
22
+ >>> left, right = nx.bipartite.sets(G)
23
+ >>> list(left)
24
+ [0, 1]
25
+ >>> list(right)
26
+ [2, 3, 4]
27
+ >>> nx.bipartite.maximum_matching(G)
28
+ {0: 2, 1: 3, 2: 0, 3: 1}
29
+
30
+ The dictionary returned by :func:`maximum_matching` includes a mapping for
31
+ vertices in both the left and right vertex sets.
32
+
33
+ Similarly, :func:`minimum_weight_full_matching` produces, for a complete
34
+ weighted bipartite graph, a matching whose cardinality is the cardinality of
35
+ the smaller of the two partitions, and for which the sum of the weights of the
36
+ edges included in the matching is minimal.
37
+
38
+ """
39
+ import collections
40
+ import itertools
41
+
42
+ import networkx as nx
43
+ from networkx.algorithms.bipartite import sets as bipartite_sets
44
+ from networkx.algorithms.bipartite.matrix import biadjacency_matrix
45
+
46
+ __all__ = [
47
+ "maximum_matching",
48
+ "hopcroft_karp_matching",
49
+ "eppstein_matching",
50
+ "to_vertex_cover",
51
+ "minimum_weight_full_matching",
52
+ ]
53
+
54
+ INFINITY = float("inf")
55
+
56
+
57
+ @nx._dispatchable
58
+ def hopcroft_karp_matching(G, top_nodes=None):
59
+ """Returns the maximum cardinality matching of the bipartite graph `G`.
60
+
61
+ A matching is a set of edges that do not share any nodes. A maximum
62
+ cardinality matching is a matching with the most edges possible. It
63
+ is not always unique. Finding a matching in a bipartite graph can be
64
+ treated as a networkx flow problem.
65
+
66
+ The functions ``hopcroft_karp_matching`` and ``maximum_matching``
67
+ are aliases of the same function.
68
+
69
+ Parameters
70
+ ----------
71
+ G : NetworkX graph
72
+
73
+ Undirected bipartite graph
74
+
75
+ top_nodes : container of nodes
76
+
77
+ Container with all nodes in one bipartite node set. If not supplied
78
+ it will be computed. But if more than one solution exists an exception
79
+ will be raised.
80
+
81
+ Returns
82
+ -------
83
+ matches : dictionary
84
+
85
+ The matching is returned as a dictionary, `matches`, such that
86
+ ``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
87
+ nodes do not occur as a key in `matches`.
88
+
89
+ Raises
90
+ ------
91
+ AmbiguousSolution
92
+ Raised if the input bipartite graph is disconnected and no container
93
+ with all nodes in one bipartite set is provided. When determining
94
+ the nodes in each bipartite set more than one valid solution is
95
+ possible if the input graph is disconnected.
96
+
97
+ Notes
98
+ -----
99
+ This function is implemented with the `Hopcroft--Karp matching algorithm
100
+ <https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>`_ for
101
+ bipartite graphs.
102
+
103
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
104
+ for further details on how bipartite graphs are handled in NetworkX.
105
+
106
+ See Also
107
+ --------
108
+ maximum_matching
109
+ hopcroft_karp_matching
110
+ eppstein_matching
111
+
112
+ References
113
+ ----------
114
+ .. [1] John E. Hopcroft and Richard M. Karp. "An n^{5 / 2} Algorithm for
115
+ Maximum Matchings in Bipartite Graphs" In: **SIAM Journal of Computing**
116
+ 2.4 (1973), pp. 225--231. <https://doi.org/10.1137/0202019>.
117
+
118
+ """
119
+
120
+ # First we define some auxiliary search functions.
121
+ #
122
+ # If you are a human reading these auxiliary search functions, the "global"
123
+ # variables `leftmatches`, `rightmatches`, `distances`, etc. are defined
124
+ # below the functions, so that they are initialized close to the initial
125
+ # invocation of the search functions.
126
+ def breadth_first_search():
127
+ for v in left:
128
+ if leftmatches[v] is None:
129
+ distances[v] = 0
130
+ queue.append(v)
131
+ else:
132
+ distances[v] = INFINITY
133
+ distances[None] = INFINITY
134
+ while queue:
135
+ v = queue.popleft()
136
+ if distances[v] < distances[None]:
137
+ for u in G[v]:
138
+ if distances[rightmatches[u]] is INFINITY:
139
+ distances[rightmatches[u]] = distances[v] + 1
140
+ queue.append(rightmatches[u])
141
+ return distances[None] is not INFINITY
142
+
143
+ def depth_first_search(v):
144
+ if v is not None:
145
+ for u in G[v]:
146
+ if distances[rightmatches[u]] == distances[v] + 1:
147
+ if depth_first_search(rightmatches[u]):
148
+ rightmatches[u] = v
149
+ leftmatches[v] = u
150
+ return True
151
+ distances[v] = INFINITY
152
+ return False
153
+ return True
154
+
155
+ # Initialize the "global" variables that maintain state during the search.
156
+ left, right = bipartite_sets(G, top_nodes)
157
+ leftmatches = {v: None for v in left}
158
+ rightmatches = {v: None for v in right}
159
+ distances = {}
160
+ queue = collections.deque()
161
+
162
+ # Implementation note: this counter is incremented as pairs are matched but
163
+ # it is currently not used elsewhere in the computation.
164
+ num_matched_pairs = 0
165
+ while breadth_first_search():
166
+ for v in left:
167
+ if leftmatches[v] is None:
168
+ if depth_first_search(v):
169
+ num_matched_pairs += 1
170
+
171
+ # Strip the entries matched to `None`.
172
+ leftmatches = {k: v for k, v in leftmatches.items() if v is not None}
173
+ rightmatches = {k: v for k, v in rightmatches.items() if v is not None}
174
+
175
+ # At this point, the left matches and the right matches are inverses of one
176
+ # another. In other words,
177
+ #
178
+ # leftmatches == {v, k for k, v in rightmatches.items()}
179
+ #
180
+ # Finally, we combine both the left matches and right matches.
181
+ return dict(itertools.chain(leftmatches.items(), rightmatches.items()))
182
+
183
+
184
+ @nx._dispatchable
185
+ def eppstein_matching(G, top_nodes=None):
186
+ """Returns the maximum cardinality matching of the bipartite graph `G`.
187
+
188
+ Parameters
189
+ ----------
190
+ G : NetworkX graph
191
+
192
+ Undirected bipartite graph
193
+
194
+ top_nodes : container
195
+
196
+ Container with all nodes in one bipartite node set. If not supplied
197
+ it will be computed. But if more than one solution exists an exception
198
+ will be raised.
199
+
200
+ Returns
201
+ -------
202
+ matches : dictionary
203
+
204
+ The matching is returned as a dictionary, `matching`, such that
205
+ ``matching[v] == w`` if node `v` is matched to node `w`. Unmatched
206
+ nodes do not occur as a key in `matching`.
207
+
208
+ Raises
209
+ ------
210
+ AmbiguousSolution
211
+ Raised if the input bipartite graph is disconnected and no container
212
+ with all nodes in one bipartite set is provided. When determining
213
+ the nodes in each bipartite set more than one valid solution is
214
+ possible if the input graph is disconnected.
215
+
216
+ Notes
217
+ -----
218
+ This function is implemented with David Eppstein's version of the algorithm
219
+ Hopcroft--Karp algorithm (see :func:`hopcroft_karp_matching`), which
220
+ originally appeared in the `Python Algorithms and Data Structures library
221
+ (PADS) <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>`_.
222
+
223
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
224
+ for further details on how bipartite graphs are handled in NetworkX.
225
+
226
+ See Also
227
+ --------
228
+
229
+ hopcroft_karp_matching
230
+
231
+ """
232
+ # Due to its original implementation, a directed graph is needed
233
+ # so that the two sets of bipartite nodes can be distinguished
234
+ left, right = bipartite_sets(G, top_nodes)
235
+ G = nx.DiGraph(G.edges(left))
236
+ # initialize greedy matching (redundant, but faster than full search)
237
+ matching = {}
238
+ for u in G:
239
+ for v in G[u]:
240
+ if v not in matching:
241
+ matching[v] = u
242
+ break
243
+ while True:
244
+ # structure residual graph into layers
245
+ # pred[u] gives the neighbor in the previous layer for u in U
246
+ # preds[v] gives a list of neighbors in the previous layer for v in V
247
+ # unmatched gives a list of unmatched vertices in final layer of V,
248
+ # and is also used as a flag value for pred[u] when u is in the first
249
+ # layer
250
+ preds = {}
251
+ unmatched = []
252
+ pred = {u: unmatched for u in G}
253
+ for v in matching:
254
+ del pred[matching[v]]
255
+ layer = list(pred)
256
+
257
+ # repeatedly extend layering structure by another pair of layers
258
+ while layer and not unmatched:
259
+ newLayer = {}
260
+ for u in layer:
261
+ for v in G[u]:
262
+ if v not in preds:
263
+ newLayer.setdefault(v, []).append(u)
264
+ layer = []
265
+ for v in newLayer:
266
+ preds[v] = newLayer[v]
267
+ if v in matching:
268
+ layer.append(matching[v])
269
+ pred[matching[v]] = v
270
+ else:
271
+ unmatched.append(v)
272
+
273
+ # did we finish layering without finding any alternating paths?
274
+ if not unmatched:
275
+ # TODO - The lines between --- were unused and were thus commented
276
+ # out. This whole commented chunk should be reviewed to determine
277
+ # whether it should be built upon or completely removed.
278
+ # ---
279
+ # unlayered = {}
280
+ # for u in G:
281
+ # # TODO Why is extra inner loop necessary?
282
+ # for v in G[u]:
283
+ # if v not in preds:
284
+ # unlayered[v] = None
285
+ # ---
286
+ # TODO Originally, this function returned a three-tuple:
287
+ #
288
+ # return (matching, list(pred), list(unlayered))
289
+ #
290
+ # For some reason, the documentation for this function
291
+ # indicated that the second and third elements of the returned
292
+ # three-tuple would be the vertices in the left and right vertex
293
+ # sets, respectively, that are also in the maximum independent set.
294
+ # However, what I think the author meant was that the second
295
+ # element is the list of vertices that were unmatched and the third
296
+ # element was the list of vertices that were matched. Since that
297
+ # seems to be the case, they don't really need to be returned,
298
+ # since that information can be inferred from the matching
299
+ # dictionary.
300
+
301
+ # All the matched nodes must be a key in the dictionary
302
+ for key in matching.copy():
303
+ matching[matching[key]] = key
304
+ return matching
305
+
306
+ # recursively search backward through layers to find alternating paths
307
+ # recursion returns true if found path, false otherwise
308
+ def recurse(v):
309
+ if v in preds:
310
+ L = preds.pop(v)
311
+ for u in L:
312
+ if u in pred:
313
+ pu = pred.pop(u)
314
+ if pu is unmatched or recurse(pu):
315
+ matching[v] = u
316
+ return True
317
+ return False
318
+
319
+ for v in unmatched:
320
+ recurse(v)
321
+
322
+
323
+ def _is_connected_by_alternating_path(G, v, matched_edges, unmatched_edges, targets):
324
+ """Returns True if and only if the vertex `v` is connected to one of
325
+ the target vertices by an alternating path in `G`.
326
+
327
+ An *alternating path* is a path in which every other edge is in the
328
+ specified maximum matching (and the remaining edges in the path are not in
329
+ the matching). An alternating path may have matched edges in the even
330
+ positions or in the odd positions, as long as the edges alternate between
331
+ 'matched' and 'unmatched'.
332
+
333
+ `G` is an undirected bipartite NetworkX graph.
334
+
335
+ `v` is a vertex in `G`.
336
+
337
+ `matched_edges` is a set of edges present in a maximum matching in `G`.
338
+
339
+ `unmatched_edges` is a set of edges not present in a maximum
340
+ matching in `G`.
341
+
342
+ `targets` is a set of vertices.
343
+
344
+ """
345
+
346
+ def _alternating_dfs(u, along_matched=True):
347
+ """Returns True if and only if `u` is connected to one of the
348
+ targets by an alternating path.
349
+
350
+ `u` is a vertex in the graph `G`.
351
+
352
+ If `along_matched` is True, this step of the depth-first search
353
+ will continue only through edges in the given matching. Otherwise, it
354
+ will continue only through edges *not* in the given matching.
355
+
356
+ """
357
+ visited = set()
358
+ # Follow matched edges when depth is even,
359
+ # and follow unmatched edges when depth is odd.
360
+ initial_depth = 0 if along_matched else 1
361
+ stack = [(u, iter(G[u]), initial_depth)]
362
+ while stack:
363
+ parent, children, depth = stack[-1]
364
+ valid_edges = matched_edges if depth % 2 else unmatched_edges
365
+ try:
366
+ child = next(children)
367
+ if child not in visited:
368
+ if (parent, child) in valid_edges or (child, parent) in valid_edges:
369
+ if child in targets:
370
+ return True
371
+ visited.add(child)
372
+ stack.append((child, iter(G[child]), depth + 1))
373
+ except StopIteration:
374
+ stack.pop()
375
+ return False
376
+
377
+ # Check for alternating paths starting with edges in the matching, then
378
+ # check for alternating paths starting with edges not in the
379
+ # matching.
380
+ return _alternating_dfs(v, along_matched=True) or _alternating_dfs(
381
+ v, along_matched=False
382
+ )
383
+
384
+
385
+ def _connected_by_alternating_paths(G, matching, targets):
386
+ """Returns the set of vertices that are connected to one of the target
387
+ vertices by an alternating path in `G` or are themselves a target.
388
+
389
+ An *alternating path* is a path in which every other edge is in the
390
+ specified maximum matching (and the remaining edges in the path are not in
391
+ the matching). An alternating path may have matched edges in the even
392
+ positions or in the odd positions, as long as the edges alternate between
393
+ 'matched' and 'unmatched'.
394
+
395
+ `G` is an undirected bipartite NetworkX graph.
396
+
397
+ `matching` is a dictionary representing a maximum matching in `G`, as
398
+ returned by, for example, :func:`maximum_matching`.
399
+
400
+ `targets` is a set of vertices.
401
+
402
+ """
403
+ # Get the set of matched edges and the set of unmatched edges. Only include
404
+ # one version of each undirected edge (for example, include edge (1, 2) but
405
+ # not edge (2, 1)). Using frozensets as an intermediary step we do not
406
+ # require nodes to be orderable.
407
+ edge_sets = {frozenset((u, v)) for u, v in matching.items()}
408
+ matched_edges = {tuple(edge) for edge in edge_sets}
409
+ unmatched_edges = {
410
+ (u, v) for (u, v) in G.edges() if frozenset((u, v)) not in edge_sets
411
+ }
412
+
413
+ return {
414
+ v
415
+ for v in G
416
+ if v in targets
417
+ or _is_connected_by_alternating_path(
418
+ G, v, matched_edges, unmatched_edges, targets
419
+ )
420
+ }
421
+
422
+
423
+ @nx._dispatchable
424
+ def to_vertex_cover(G, matching, top_nodes=None):
425
+ """Returns the minimum vertex cover corresponding to the given maximum
426
+ matching of the bipartite graph `G`.
427
+
428
+ Parameters
429
+ ----------
430
+ G : NetworkX graph
431
+
432
+ Undirected bipartite graph
433
+
434
+ matching : dictionary
435
+
436
+ A dictionary whose keys are vertices in `G` and whose values are the
437
+ distinct neighbors comprising the maximum matching for `G`, as returned
438
+ by, for example, :func:`maximum_matching`. The dictionary *must*
439
+ represent the maximum matching.
440
+
441
+ top_nodes : container
442
+
443
+ Container with all nodes in one bipartite node set. If not supplied
444
+ it will be computed. But if more than one solution exists an exception
445
+ will be raised.
446
+
447
+ Returns
448
+ -------
449
+ vertex_cover : :class:`set`
450
+
451
+ The minimum vertex cover in `G`.
452
+
453
+ Raises
454
+ ------
455
+ AmbiguousSolution
456
+ Raised if the input bipartite graph is disconnected and no container
457
+ with all nodes in one bipartite set is provided. When determining
458
+ the nodes in each bipartite set more than one valid solution is
459
+ possible if the input graph is disconnected.
460
+
461
+ Notes
462
+ -----
463
+ This function is implemented using the procedure guaranteed by `Konig's
464
+ theorem
465
+ <https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29>`_,
466
+ which proves an equivalence between a maximum matching and a minimum vertex
467
+ cover in bipartite graphs.
468
+
469
+ Since a minimum vertex cover is the complement of a maximum independent set
470
+ for any graph, one can compute the maximum independent set of a bipartite
471
+ graph this way:
472
+
473
+ >>> G = nx.complete_bipartite_graph(2, 3)
474
+ >>> matching = nx.bipartite.maximum_matching(G)
475
+ >>> vertex_cover = nx.bipartite.to_vertex_cover(G, matching)
476
+ >>> independent_set = set(G) - vertex_cover
477
+ >>> print(list(independent_set))
478
+ [2, 3, 4]
479
+
480
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
481
+ for further details on how bipartite graphs are handled in NetworkX.
482
+
483
+ """
484
+ # This is a Python implementation of the algorithm described at
485
+ # <https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29#Proof>.
486
+ L, R = bipartite_sets(G, top_nodes)
487
+ # Let U be the set of unmatched vertices in the left vertex set.
488
+ unmatched_vertices = set(G) - set(matching)
489
+ U = unmatched_vertices & L
490
+ # Let Z be the set of vertices that are either in U or are connected to U
491
+ # by alternating paths.
492
+ Z = _connected_by_alternating_paths(G, matching, U)
493
+ # At this point, every edge either has a right endpoint in Z or a left
494
+ # endpoint not in Z. This gives us the vertex cover.
495
+ return (L - Z) | (R & Z)
496
+
497
+
498
+ #: Returns the maximum cardinality matching in the given bipartite graph.
499
+ #:
500
+ #: This function is simply an alias for :func:`hopcroft_karp_matching`.
501
+ maximum_matching = hopcroft_karp_matching
502
+
503
+
504
+ @nx._dispatchable(edge_attrs="weight")
505
+ def minimum_weight_full_matching(G, top_nodes=None, weight="weight"):
506
+ r"""Returns a minimum weight full matching of the bipartite graph `G`.
507
+
508
+ Let :math:`G = ((U, V), E)` be a weighted bipartite graph with real weights
509
+ :math:`w : E \to \mathbb{R}`. This function then produces a matching
510
+ :math:`M \subseteq E` with cardinality
511
+
512
+ .. math::
513
+ \lvert M \rvert = \min(\lvert U \rvert, \lvert V \rvert),
514
+
515
+ which minimizes the sum of the weights of the edges included in the
516
+ matching, :math:`\sum_{e \in M} w(e)`, or raises an error if no such
517
+ matching exists.
518
+
519
+ When :math:`\lvert U \rvert = \lvert V \rvert`, this is commonly
520
+ referred to as a perfect matching; here, since we allow
521
+ :math:`\lvert U \rvert` and :math:`\lvert V \rvert` to differ, we
522
+ follow Karp [1]_ and refer to the matching as *full*.
523
+
524
+ Parameters
525
+ ----------
526
+ G : NetworkX graph
527
+
528
+ Undirected bipartite graph
529
+
530
+ top_nodes : container
531
+
532
+ Container with all nodes in one bipartite node set. If not supplied
533
+ it will be computed.
534
+
535
+ weight : string, optional (default='weight')
536
+
537
+ The edge data key used to provide each value in the matrix.
538
+ If None, then each edge has weight 1.
539
+
540
+ Returns
541
+ -------
542
+ matches : dictionary
543
+
544
+ The matching is returned as a dictionary, `matches`, such that
545
+ ``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
546
+ nodes do not occur as a key in `matches`.
547
+
548
+ Raises
549
+ ------
550
+ ValueError
551
+ Raised if no full matching exists.
552
+
553
+ ImportError
554
+ Raised if SciPy is not available.
555
+
556
+ Notes
557
+ -----
558
+ The problem of determining a minimum weight full matching is also known as
559
+ the rectangular linear assignment problem. This implementation defers the
560
+ calculation of the assignment to SciPy.
561
+
562
+ References
563
+ ----------
564
+ .. [1] Richard Manning Karp:
565
+ An algorithm to Solve the m x n Assignment Problem in Expected Time
566
+ O(mn log n).
567
+ Networks, 10(2):143–152, 1980.
568
+
569
+ """
570
+ import numpy as np
571
+ import scipy as sp
572
+
573
+ left, right = nx.bipartite.sets(G, top_nodes)
574
+ U = list(left)
575
+ V = list(right)
576
+ # We explicitly create the biadjacency matrix having infinities
577
+ # where edges are missing (as opposed to zeros, which is what one would
578
+ # get by using toarray on the sparse matrix).
579
+ weights_sparse = biadjacency_matrix(
580
+ G, row_order=U, column_order=V, weight=weight, format="coo"
581
+ )
582
+ weights = np.full(weights_sparse.shape, np.inf)
583
+ weights[weights_sparse.row, weights_sparse.col] = weights_sparse.data
584
+ left_matches = sp.optimize.linear_sum_assignment(weights)
585
+ d = {U[u]: V[v] for u, v in zip(*left_matches)}
586
+ # d will contain the matching from edges in left to right; we need to
587
+ # add the ones from right to left as well.
588
+ d.update({v: u for u, v in d.items()})
589
+ return d
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/matrix.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ====================
3
+ Biadjacency matrices
4
+ ====================
5
+ """
6
+ import itertools
7
+
8
+ import networkx as nx
9
+ from networkx.convert_matrix import _generate_weighted_edges
10
+
11
+ __all__ = ["biadjacency_matrix", "from_biadjacency_matrix"]
12
+
13
+
14
+ @nx._dispatchable(edge_attrs="weight")
15
+ def biadjacency_matrix(
16
+ G, row_order, column_order=None, dtype=None, weight="weight", format="csr"
17
+ ):
18
+ r"""Returns the biadjacency matrix of the bipartite graph G.
19
+
20
+ Let `G = (U, V, E)` be a bipartite graph with node sets
21
+ `U = u_{1},...,u_{r}` and `V = v_{1},...,v_{s}`. The biadjacency
22
+ matrix [1]_ is the `r` x `s` matrix `B` in which `b_{i,j} = 1`
23
+ if, and only if, `(u_i, v_j) \in E`. If the parameter `weight` is
24
+ not `None` and matches the name of an edge attribute, its value is
25
+ used instead of 1.
26
+
27
+ Parameters
28
+ ----------
29
+ G : graph
30
+ A NetworkX graph
31
+
32
+ row_order : list of nodes
33
+ The rows of the matrix are ordered according to the list of nodes.
34
+
35
+ column_order : list, optional
36
+ The columns of the matrix are ordered according to the list of nodes.
37
+ If column_order is None, then the ordering of columns is arbitrary.
38
+
39
+ dtype : NumPy data-type, optional
40
+ A valid NumPy dtype used to initialize the array. If None, then the
41
+ NumPy default is used.
42
+
43
+ weight : string or None, optional (default='weight')
44
+ The edge data key used to provide each value in the matrix.
45
+ If None, then each edge has weight 1.
46
+
47
+ format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
48
+ The type of the matrix to be returned (default 'csr'). For
49
+ some algorithms different implementations of sparse matrices
50
+ can perform better. See [2]_ for details.
51
+
52
+ Returns
53
+ -------
54
+ M : SciPy sparse array
55
+ Biadjacency matrix representation of the bipartite graph G.
56
+
57
+ Notes
58
+ -----
59
+ No attempt is made to check that the input graph is bipartite.
60
+
61
+ For directed bipartite graphs only successors are considered as neighbors.
62
+ To obtain an adjacency matrix with ones (or weight values) for both
63
+ predecessors and successors you have to generate two biadjacency matrices
64
+ where the rows of one of them are the columns of the other, and then add
65
+ one to the transpose of the other.
66
+
67
+ See Also
68
+ --------
69
+ adjacency_matrix
70
+ from_biadjacency_matrix
71
+
72
+ References
73
+ ----------
74
+ .. [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
75
+ .. [2] Scipy Dev. References, "Sparse Matrices",
76
+ https://docs.scipy.org/doc/scipy/reference/sparse.html
77
+ """
78
+ import scipy as sp
79
+
80
+ nlen = len(row_order)
81
+ if nlen == 0:
82
+ raise nx.NetworkXError("row_order is empty list")
83
+ if len(row_order) != len(set(row_order)):
84
+ msg = "Ambiguous ordering: `row_order` contained duplicates."
85
+ raise nx.NetworkXError(msg)
86
+ if column_order is None:
87
+ column_order = list(set(G) - set(row_order))
88
+ mlen = len(column_order)
89
+ if len(column_order) != len(set(column_order)):
90
+ msg = "Ambiguous ordering: `column_order` contained duplicates."
91
+ raise nx.NetworkXError(msg)
92
+
93
+ row_index = dict(zip(row_order, itertools.count()))
94
+ col_index = dict(zip(column_order, itertools.count()))
95
+
96
+ if G.number_of_edges() == 0:
97
+ row, col, data = [], [], []
98
+ else:
99
+ row, col, data = zip(
100
+ *(
101
+ (row_index[u], col_index[v], d.get(weight, 1))
102
+ for u, v, d in G.edges(row_order, data=True)
103
+ if u in row_index and v in col_index
104
+ )
105
+ )
106
+ A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, mlen), dtype=dtype)
107
+ try:
108
+ return A.asformat(format)
109
+ except ValueError as err:
110
+ raise nx.NetworkXError(f"Unknown sparse array format: {format}") from err
111
+
112
+
113
+ @nx._dispatchable(graphs=None, returns_graph=True)
114
+ def from_biadjacency_matrix(A, create_using=None, edge_attribute="weight"):
115
+ r"""Creates a new bipartite graph from a biadjacency matrix given as a
116
+ SciPy sparse array.
117
+
118
+ Parameters
119
+ ----------
120
+ A: scipy sparse array
121
+ A biadjacency matrix representation of a graph
122
+
123
+ create_using: NetworkX graph
124
+ Use specified graph for result. The default is Graph()
125
+
126
+ edge_attribute: string
127
+ Name of edge attribute to store matrix numeric value. The data will
128
+ have the same type as the matrix entry (int, float, (real,imag)).
129
+
130
+ Notes
131
+ -----
132
+ The nodes are labeled with the attribute `bipartite` set to an integer
133
+ 0 or 1 representing membership in part 0 or part 1 of the bipartite graph.
134
+
135
+ If `create_using` is an instance of :class:`networkx.MultiGraph` or
136
+ :class:`networkx.MultiDiGraph` and the entries of `A` are of
137
+ type :class:`int`, then this function returns a multigraph (of the same
138
+ type as `create_using`) with parallel edges. In this case, `edge_attribute`
139
+ will be ignored.
140
+
141
+ See Also
142
+ --------
143
+ biadjacency_matrix
144
+ from_numpy_array
145
+
146
+ References
147
+ ----------
148
+ [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
149
+ """
150
+ G = nx.empty_graph(0, create_using)
151
+ n, m = A.shape
152
+ # Make sure we get even the isolated nodes of the graph.
153
+ G.add_nodes_from(range(n), bipartite=0)
154
+ G.add_nodes_from(range(n, n + m), bipartite=1)
155
+ # Create an iterable over (u, v, w) triples and for each triple, add an
156
+ # edge from u to v with weight w.
157
+ triples = ((u, n + v, d) for (u, v, d) in _generate_weighted_edges(A))
158
+ # If the entries in the adjacency matrix are integers and the graph is a
159
+ # multigraph, then create parallel edges, each with weight 1, for each
160
+ # entry in the adjacency matrix. Otherwise, create one edge for each
161
+ # positive entry in the adjacency matrix and set the weight of that edge to
162
+ # be the entry in the matrix.
163
+ if A.dtype.kind in ("i", "u") and G.is_multigraph():
164
+ chain = itertools.chain.from_iterable
165
+ triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
166
+ G.add_weighted_edges_from(triples, weight=edge_attribute)
167
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/projection.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One-mode (unipartite) projections of bipartite graphs."""
2
+ import networkx as nx
3
+ from networkx.exception import NetworkXAlgorithmError
4
+ from networkx.utils import not_implemented_for
5
+
6
+ __all__ = [
7
+ "projected_graph",
8
+ "weighted_projected_graph",
9
+ "collaboration_weighted_projected_graph",
10
+ "overlap_weighted_projected_graph",
11
+ "generic_weighted_projected_graph",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(
16
+ graphs="B", preserve_node_attrs=True, preserve_graph_attrs=True, returns_graph=True
17
+ )
18
+ def projected_graph(B, nodes, multigraph=False):
19
+ r"""Returns the projection of B onto one of its node sets.
20
+
21
+ Returns the graph G that is the projection of the bipartite graph B
22
+ onto the specified nodes. They retain their attributes and are connected
23
+ in G if they have a common neighbor in B.
24
+
25
+ Parameters
26
+ ----------
27
+ B : NetworkX graph
28
+ The input graph should be bipartite.
29
+
30
+ nodes : list or iterable
31
+ Nodes to project onto (the "bottom" nodes).
32
+
33
+ multigraph: bool (default=False)
34
+ If True return a multigraph where the multiple edges represent multiple
35
+ shared neighbors. They edge key in the multigraph is assigned to the
36
+ label of the neighbor.
37
+
38
+ Returns
39
+ -------
40
+ Graph : NetworkX graph or multigraph
41
+ A graph that is the projection onto the given nodes.
42
+
43
+ Examples
44
+ --------
45
+ >>> from networkx.algorithms import bipartite
46
+ >>> B = nx.path_graph(4)
47
+ >>> G = bipartite.projected_graph(B, [1, 3])
48
+ >>> list(G)
49
+ [1, 3]
50
+ >>> list(G.edges())
51
+ [(1, 3)]
52
+
53
+ If nodes `a`, and `b` are connected through both nodes 1 and 2 then
54
+ building a multigraph results in two edges in the projection onto
55
+ [`a`, `b`]:
56
+
57
+ >>> B = nx.Graph()
58
+ >>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
59
+ >>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
60
+ >>> print([sorted((u, v)) for u, v in G.edges()])
61
+ [['a', 'b'], ['a', 'b']]
62
+
63
+ Notes
64
+ -----
65
+ No attempt is made to verify that the input graph B is bipartite.
66
+ Returns a simple graph that is the projection of the bipartite graph B
67
+ onto the set of nodes given in list nodes. If multigraph=True then
68
+ a multigraph is returned with an edge for every shared neighbor.
69
+
70
+ Directed graphs are allowed as input. The output will also then
71
+ be a directed graph with edges if there is a directed path between
72
+ the nodes.
73
+
74
+ The graph and node properties are (shallow) copied to the projected graph.
75
+
76
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
77
+ for further details on how bipartite graphs are handled in NetworkX.
78
+
79
+ See Also
80
+ --------
81
+ is_bipartite,
82
+ is_bipartite_node_set,
83
+ sets,
84
+ weighted_projected_graph,
85
+ collaboration_weighted_projected_graph,
86
+ overlap_weighted_projected_graph,
87
+ generic_weighted_projected_graph
88
+ """
89
+ if B.is_multigraph():
90
+ raise nx.NetworkXError("not defined for multigraphs")
91
+ if B.is_directed():
92
+ directed = True
93
+ if multigraph:
94
+ G = nx.MultiDiGraph()
95
+ else:
96
+ G = nx.DiGraph()
97
+ else:
98
+ directed = False
99
+ if multigraph:
100
+ G = nx.MultiGraph()
101
+ else:
102
+ G = nx.Graph()
103
+ G.graph.update(B.graph)
104
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
105
+ for u in nodes:
106
+ nbrs2 = {v for nbr in B[u] for v in B[nbr] if v != u}
107
+ if multigraph:
108
+ for n in nbrs2:
109
+ if directed:
110
+ links = set(B[u]) & set(B.pred[n])
111
+ else:
112
+ links = set(B[u]) & set(B[n])
113
+ for l in links:
114
+ if not G.has_edge(u, n, l):
115
+ G.add_edge(u, n, key=l)
116
+ else:
117
+ G.add_edges_from((u, n) for n in nbrs2)
118
+ return G
119
+
120
+
121
+ @not_implemented_for("multigraph")
122
+ @nx._dispatchable(graphs="B", returns_graph=True)
123
+ def weighted_projected_graph(B, nodes, ratio=False):
124
+ r"""Returns a weighted projection of B onto one of its node sets.
125
+
126
+ The weighted projected graph is the projection of the bipartite
127
+ network B onto the specified nodes with weights representing the
128
+ number of shared neighbors or the ratio between actual shared
129
+ neighbors and possible shared neighbors if ``ratio is True`` [1]_.
130
+ The nodes retain their attributes and are connected in the resulting
131
+ graph if they have an edge to a common node in the original graph.
132
+
133
+ Parameters
134
+ ----------
135
+ B : NetworkX graph
136
+ The input graph should be bipartite.
137
+
138
+ nodes : list or iterable
139
+ Distinct nodes to project onto (the "bottom" nodes).
140
+
141
+ ratio: Bool (default=False)
142
+ If True, edge weight is the ratio between actual shared neighbors
143
+ and maximum possible shared neighbors (i.e., the size of the other
144
+ node set). If False, edges weight is the number of shared neighbors.
145
+
146
+ Returns
147
+ -------
148
+ Graph : NetworkX graph
149
+ A graph that is the projection onto the given nodes.
150
+
151
+ Examples
152
+ --------
153
+ >>> from networkx.algorithms import bipartite
154
+ >>> B = nx.path_graph(4)
155
+ >>> G = bipartite.weighted_projected_graph(B, [1, 3])
156
+ >>> list(G)
157
+ [1, 3]
158
+ >>> list(G.edges(data=True))
159
+ [(1, 3, {'weight': 1})]
160
+ >>> G = bipartite.weighted_projected_graph(B, [1, 3], ratio=True)
161
+ >>> list(G.edges(data=True))
162
+ [(1, 3, {'weight': 0.5})]
163
+
164
+ Notes
165
+ -----
166
+ No attempt is made to verify that the input graph B is bipartite, or that
167
+ the input nodes are distinct. However, if the length of the input nodes is
168
+ greater than or equal to the nodes in the graph B, an exception is raised.
169
+ If the nodes are not distinct but don't raise this error, the output weights
170
+ will be incorrect.
171
+ The graph and node properties are (shallow) copied to the projected graph.
172
+
173
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
174
+ for further details on how bipartite graphs are handled in NetworkX.
175
+
176
+ See Also
177
+ --------
178
+ is_bipartite,
179
+ is_bipartite_node_set,
180
+ sets,
181
+ collaboration_weighted_projected_graph,
182
+ overlap_weighted_projected_graph,
183
+ generic_weighted_projected_graph
184
+ projected_graph
185
+
186
+ References
187
+ ----------
188
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
189
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
190
+ of Social Network Analysis. Sage Publications.
191
+ """
192
+ if B.is_directed():
193
+ pred = B.pred
194
+ G = nx.DiGraph()
195
+ else:
196
+ pred = B.adj
197
+ G = nx.Graph()
198
+ G.graph.update(B.graph)
199
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
200
+ n_top = len(B) - len(nodes)
201
+
202
+ if n_top < 1:
203
+ raise NetworkXAlgorithmError(
204
+ f"the size of the nodes to project onto ({len(nodes)}) is >= the graph size ({len(B)}).\n"
205
+ "They are either not a valid bipartite partition or contain duplicates"
206
+ )
207
+
208
+ for u in nodes:
209
+ unbrs = set(B[u])
210
+ nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
211
+ for v in nbrs2:
212
+ vnbrs = set(pred[v])
213
+ common = unbrs & vnbrs
214
+ if not ratio:
215
+ weight = len(common)
216
+ else:
217
+ weight = len(common) / n_top
218
+ G.add_edge(u, v, weight=weight)
219
+ return G
220
+
221
+
222
+ @not_implemented_for("multigraph")
223
+ @nx._dispatchable(graphs="B", returns_graph=True)
224
+ def collaboration_weighted_projected_graph(B, nodes):
225
+ r"""Newman's weighted projection of B onto one of its node sets.
226
+
227
+ The collaboration weighted projection is the projection of the
228
+ bipartite network B onto the specified nodes with weights assigned
229
+ using Newman's collaboration model [1]_:
230
+
231
+ .. math::
232
+
233
+ w_{u, v} = \sum_k \frac{\delta_{u}^{k} \delta_{v}^{k}}{d_k - 1}
234
+
235
+ where `u` and `v` are nodes from the bottom bipartite node set,
236
+ and `k` is a node of the top node set.
237
+ The value `d_k` is the degree of node `k` in the bipartite
238
+ network and `\delta_{u}^{k}` is 1 if node `u` is
239
+ linked to node `k` in the original bipartite graph or 0 otherwise.
240
+
241
+ The nodes retain their attributes and are connected in the resulting
242
+ graph if have an edge to a common node in the original bipartite
243
+ graph.
244
+
245
+ Parameters
246
+ ----------
247
+ B : NetworkX graph
248
+ The input graph should be bipartite.
249
+
250
+ nodes : list or iterable
251
+ Nodes to project onto (the "bottom" nodes).
252
+
253
+ Returns
254
+ -------
255
+ Graph : NetworkX graph
256
+ A graph that is the projection onto the given nodes.
257
+
258
+ Examples
259
+ --------
260
+ >>> from networkx.algorithms import bipartite
261
+ >>> B = nx.path_graph(5)
262
+ >>> B.add_edge(1, 5)
263
+ >>> G = bipartite.collaboration_weighted_projected_graph(B, [0, 2, 4, 5])
264
+ >>> list(G)
265
+ [0, 2, 4, 5]
266
+ >>> for edge in sorted(G.edges(data=True)):
267
+ ... print(edge)
268
+ (0, 2, {'weight': 0.5})
269
+ (0, 5, {'weight': 0.5})
270
+ (2, 4, {'weight': 1.0})
271
+ (2, 5, {'weight': 0.5})
272
+
273
+ Notes
274
+ -----
275
+ No attempt is made to verify that the input graph B is bipartite.
276
+ The graph and node properties are (shallow) copied to the projected graph.
277
+
278
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
279
+ for further details on how bipartite graphs are handled in NetworkX.
280
+
281
+ See Also
282
+ --------
283
+ is_bipartite,
284
+ is_bipartite_node_set,
285
+ sets,
286
+ weighted_projected_graph,
287
+ overlap_weighted_projected_graph,
288
+ generic_weighted_projected_graph,
289
+ projected_graph
290
+
291
+ References
292
+ ----------
293
+ .. [1] Scientific collaboration networks: II.
294
+ Shortest paths, weighted networks, and centrality,
295
+ M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).
296
+ """
297
+ if B.is_directed():
298
+ pred = B.pred
299
+ G = nx.DiGraph()
300
+ else:
301
+ pred = B.adj
302
+ G = nx.Graph()
303
+ G.graph.update(B.graph)
304
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
305
+ for u in nodes:
306
+ unbrs = set(B[u])
307
+ nbrs2 = {n for nbr in unbrs for n in B[nbr] if n != u}
308
+ for v in nbrs2:
309
+ vnbrs = set(pred[v])
310
+ common_degree = (len(B[n]) for n in unbrs & vnbrs)
311
+ weight = sum(1.0 / (deg - 1) for deg in common_degree if deg > 1)
312
+ G.add_edge(u, v, weight=weight)
313
+ return G
314
+
315
+
316
+ @not_implemented_for("multigraph")
317
+ @nx._dispatchable(graphs="B", returns_graph=True)
318
+ def overlap_weighted_projected_graph(B, nodes, jaccard=True):
319
+ r"""Overlap weighted projection of B onto one of its node sets.
320
+
321
+ The overlap weighted projection is the projection of the bipartite
322
+ network B onto the specified nodes with weights representing
323
+ the Jaccard index between the neighborhoods of the two nodes in the
324
+ original bipartite network [1]_:
325
+
326
+ .. math::
327
+
328
+ w_{v, u} = \frac{|N(u) \cap N(v)|}{|N(u) \cup N(v)|}
329
+
330
+ or if the parameter 'jaccard' is False, the fraction of common
331
+ neighbors by minimum of both nodes degree in the original
332
+ bipartite graph [1]_:
333
+
334
+ .. math::
335
+
336
+ w_{v, u} = \frac{|N(u) \cap N(v)|}{min(|N(u)|, |N(v)|)}
337
+
338
+ The nodes retain their attributes and are connected in the resulting
339
+ graph if have an edge to a common node in the original bipartite graph.
340
+
341
+ Parameters
342
+ ----------
343
+ B : NetworkX graph
344
+ The input graph should be bipartite.
345
+
346
+ nodes : list or iterable
347
+ Nodes to project onto (the "bottom" nodes).
348
+
349
+ jaccard: Bool (default=True)
350
+
351
+ Returns
352
+ -------
353
+ Graph : NetworkX graph
354
+ A graph that is the projection onto the given nodes.
355
+
356
+ Examples
357
+ --------
358
+ >>> from networkx.algorithms import bipartite
359
+ >>> B = nx.path_graph(5)
360
+ >>> nodes = [0, 2, 4]
361
+ >>> G = bipartite.overlap_weighted_projected_graph(B, nodes)
362
+ >>> list(G)
363
+ [0, 2, 4]
364
+ >>> list(G.edges(data=True))
365
+ [(0, 2, {'weight': 0.5}), (2, 4, {'weight': 0.5})]
366
+ >>> G = bipartite.overlap_weighted_projected_graph(B, nodes, jaccard=False)
367
+ >>> list(G.edges(data=True))
368
+ [(0, 2, {'weight': 1.0}), (2, 4, {'weight': 1.0})]
369
+
370
+ Notes
371
+ -----
372
+ No attempt is made to verify that the input graph B is bipartite.
373
+ The graph and node properties are (shallow) copied to the projected graph.
374
+
375
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
376
+ for further details on how bipartite graphs are handled in NetworkX.
377
+
378
+ See Also
379
+ --------
380
+ is_bipartite,
381
+ is_bipartite_node_set,
382
+ sets,
383
+ weighted_projected_graph,
384
+ collaboration_weighted_projected_graph,
385
+ generic_weighted_projected_graph,
386
+ projected_graph
387
+
388
+ References
389
+ ----------
390
+ .. [1] Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation
391
+ Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook
392
+ of Social Network Analysis. Sage Publications.
393
+
394
+ """
395
+ if B.is_directed():
396
+ pred = B.pred
397
+ G = nx.DiGraph()
398
+ else:
399
+ pred = B.adj
400
+ G = nx.Graph()
401
+ G.graph.update(B.graph)
402
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
403
+ for u in nodes:
404
+ unbrs = set(B[u])
405
+ nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
406
+ for v in nbrs2:
407
+ vnbrs = set(pred[v])
408
+ if jaccard:
409
+ wt = len(unbrs & vnbrs) / len(unbrs | vnbrs)
410
+ else:
411
+ wt = len(unbrs & vnbrs) / min(len(unbrs), len(vnbrs))
412
+ G.add_edge(u, v, weight=wt)
413
+ return G
414
+
415
+
416
+ @not_implemented_for("multigraph")
417
+ @nx._dispatchable(graphs="B", preserve_all_attrs=True, returns_graph=True)
418
+ def generic_weighted_projected_graph(B, nodes, weight_function=None):
419
+ r"""Weighted projection of B with a user-specified weight function.
420
+
421
+ The bipartite network B is projected on to the specified nodes
422
+ with weights computed by a user-specified function. This function
423
+ must accept as a parameter the neighborhood sets of two nodes and
424
+ return an integer or a float.
425
+
426
+ The nodes retain their attributes and are connected in the resulting graph
427
+ if they have an edge to a common node in the original graph.
428
+
429
+ Parameters
430
+ ----------
431
+ B : NetworkX graph
432
+ The input graph should be bipartite.
433
+
434
+ nodes : list or iterable
435
+ Nodes to project onto (the "bottom" nodes).
436
+
437
+ weight_function : function
438
+ This function must accept as parameters the same input graph
439
+ that this function, and two nodes; and return an integer or a float.
440
+ The default function computes the number of shared neighbors.
441
+
442
+ Returns
443
+ -------
444
+ Graph : NetworkX graph
445
+ A graph that is the projection onto the given nodes.
446
+
447
+ Examples
448
+ --------
449
+ >>> from networkx.algorithms import bipartite
450
+ >>> # Define some custom weight functions
451
+ >>> def jaccard(G, u, v):
452
+ ... unbrs = set(G[u])
453
+ ... vnbrs = set(G[v])
454
+ ... return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs)
455
+ >>> def my_weight(G, u, v, weight="weight"):
456
+ ... w = 0
457
+ ... for nbr in set(G[u]) & set(G[v]):
458
+ ... w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1)
459
+ ... return w
460
+ >>> # A complete bipartite graph with 4 nodes and 4 edges
461
+ >>> B = nx.complete_bipartite_graph(2, 2)
462
+ >>> # Add some arbitrary weight to the edges
463
+ >>> for i, (u, v) in enumerate(B.edges()):
464
+ ... B.edges[u, v]["weight"] = i + 1
465
+ >>> for edge in B.edges(data=True):
466
+ ... print(edge)
467
+ (0, 2, {'weight': 1})
468
+ (0, 3, {'weight': 2})
469
+ (1, 2, {'weight': 3})
470
+ (1, 3, {'weight': 4})
471
+ >>> # By default, the weight is the number of shared neighbors
472
+ >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1])
473
+ >>> print(list(G.edges(data=True)))
474
+ [(0, 1, {'weight': 2})]
475
+ >>> # To specify a custom weight function use the weight_function parameter
476
+ >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=jaccard)
477
+ >>> print(list(G.edges(data=True)))
478
+ [(0, 1, {'weight': 1.0})]
479
+ >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=my_weight)
480
+ >>> print(list(G.edges(data=True)))
481
+ [(0, 1, {'weight': 10})]
482
+
483
+ Notes
484
+ -----
485
+ No attempt is made to verify that the input graph B is bipartite.
486
+ The graph and node properties are (shallow) copied to the projected graph.
487
+
488
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
489
+ for further details on how bipartite graphs are handled in NetworkX.
490
+
491
+ See Also
492
+ --------
493
+ is_bipartite,
494
+ is_bipartite_node_set,
495
+ sets,
496
+ weighted_projected_graph,
497
+ collaboration_weighted_projected_graph,
498
+ overlap_weighted_projected_graph,
499
+ projected_graph
500
+
501
+ """
502
+ if B.is_directed():
503
+ pred = B.pred
504
+ G = nx.DiGraph()
505
+ else:
506
+ pred = B.adj
507
+ G = nx.Graph()
508
+ if weight_function is None:
509
+
510
+ def weight_function(G, u, v):
511
+ # Notice that we use set(pred[v]) for handling the directed case.
512
+ return len(set(G[u]) & set(pred[v]))
513
+
514
+ G.graph.update(B.graph)
515
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
516
+ for u in nodes:
517
+ nbrs2 = {n for nbr in set(B[u]) for n in B[nbr]} - {u}
518
+ for v in nbrs2:
519
+ weight = weight_function(B, u, v)
520
+ G.add_edge(u, v, weight=weight)
521
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/redundancy.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Node redundancy for bipartite graphs."""
2
+ from itertools import combinations
3
+
4
+ import networkx as nx
5
+ from networkx import NetworkXError
6
+
7
+ __all__ = ["node_redundancy"]
8
+
9
+
10
+ @nx._dispatchable
11
+ def node_redundancy(G, nodes=None):
12
+ r"""Computes the node redundancy coefficients for the nodes in the bipartite
13
+ graph `G`.
14
+
15
+ The redundancy coefficient of a node `v` is the fraction of pairs of
16
+ neighbors of `v` that are both linked to other nodes. In a one-mode
17
+ projection these nodes would be linked together even if `v` were
18
+ not there.
19
+
20
+ More formally, for any vertex `v`, the *redundancy coefficient of `v`* is
21
+ defined by
22
+
23
+ .. math::
24
+
25
+ rc(v) = \frac{|\{\{u, w\} \subseteq N(v),
26
+ \: \exists v' \neq v,\: (v',u) \in E\:
27
+ \mathrm{and}\: (v',w) \in E\}|}{ \frac{|N(v)|(|N(v)|-1)}{2}},
28
+
29
+ where `N(v)` is the set of neighbors of `v` in `G`.
30
+
31
+ Parameters
32
+ ----------
33
+ G : graph
34
+ A bipartite graph
35
+
36
+ nodes : list or iterable (optional)
37
+ Compute redundancy for these nodes. The default is all nodes in G.
38
+
39
+ Returns
40
+ -------
41
+ redundancy : dictionary
42
+ A dictionary keyed by node with the node redundancy value.
43
+
44
+ Examples
45
+ --------
46
+ Compute the redundancy coefficient of each node in a graph::
47
+
48
+ >>> from networkx.algorithms import bipartite
49
+ >>> G = nx.cycle_graph(4)
50
+ >>> rc = bipartite.node_redundancy(G)
51
+ >>> rc[0]
52
+ 1.0
53
+
54
+ Compute the average redundancy for the graph::
55
+
56
+ >>> from networkx.algorithms import bipartite
57
+ >>> G = nx.cycle_graph(4)
58
+ >>> rc = bipartite.node_redundancy(G)
59
+ >>> sum(rc.values()) / len(G)
60
+ 1.0
61
+
62
+ Compute the average redundancy for a set of nodes::
63
+
64
+ >>> from networkx.algorithms import bipartite
65
+ >>> G = nx.cycle_graph(4)
66
+ >>> rc = bipartite.node_redundancy(G)
67
+ >>> nodes = [0, 2]
68
+ >>> sum(rc[n] for n in nodes) / len(nodes)
69
+ 1.0
70
+
71
+ Raises
72
+ ------
73
+ NetworkXError
74
+ If any of the nodes in the graph (or in `nodes`, if specified) has
75
+ (out-)degree less than two (which would result in division by zero,
76
+ according to the definition of the redundancy coefficient).
77
+
78
+ References
79
+ ----------
80
+ .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
81
+ Basic notions for the analysis of large two-mode networks.
82
+ Social Networks 30(1), 31--48.
83
+
84
+ """
85
+ if nodes is None:
86
+ nodes = G
87
+ if any(len(G[v]) < 2 for v in nodes):
88
+ raise NetworkXError(
89
+ "Cannot compute redundancy coefficient for a node"
90
+ " that has fewer than two neighbors."
91
+ )
92
+ # TODO This can be trivially parallelized.
93
+ return {v: _node_redundancy(G, v) for v in nodes}
94
+
95
+
96
+ def _node_redundancy(G, v):
97
+ """Returns the redundancy of the node `v` in the bipartite graph `G`.
98
+
99
+ If `G` is a graph with `n` nodes, the redundancy of a node is the ratio
100
+ of the "overlap" of `v` to the maximum possible overlap of `v`
101
+ according to its degree. The overlap of `v` is the number of pairs of
102
+ neighbors that have mutual neighbors themselves, other than `v`.
103
+
104
+ `v` must have at least two neighbors in `G`.
105
+
106
+ """
107
+ n = len(G[v])
108
+ overlap = sum(
109
+ 1 for (u, w) in combinations(G[v], 2) if (set(G[u]) & set(G[w])) - {v}
110
+ )
111
+ return (2 * overlap) / (n * (n - 1))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bipartite/spectral.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Spectral bipartivity measure.
3
+ """
4
+ import networkx as nx
5
+
6
+ __all__ = ["spectral_bipartivity"]
7
+
8
+
9
+ @nx._dispatchable(edge_attrs="weight")
10
+ def spectral_bipartivity(G, nodes=None, weight="weight"):
11
+ """Returns the spectral bipartivity.
12
+
13
+ Parameters
14
+ ----------
15
+ G : NetworkX graph
16
+
17
+ nodes : list or container optional(default is all nodes)
18
+ Nodes to return value of spectral bipartivity contribution.
19
+
20
+ weight : string or None optional (default = 'weight')
21
+ Edge data key to use for edge weights. If None, weights set to 1.
22
+
23
+ Returns
24
+ -------
25
+ sb : float or dict
26
+ A single number if the keyword nodes is not specified, or
27
+ a dictionary keyed by node with the spectral bipartivity contribution
28
+ of that node as the value.
29
+
30
+ Examples
31
+ --------
32
+ >>> from networkx.algorithms import bipartite
33
+ >>> G = nx.path_graph(4)
34
+ >>> bipartite.spectral_bipartivity(G)
35
+ 1.0
36
+
37
+ Notes
38
+ -----
39
+ This implementation uses Numpy (dense) matrices which are not efficient
40
+ for storing large sparse graphs.
41
+
42
+ See Also
43
+ --------
44
+ color
45
+
46
+ References
47
+ ----------
48
+ .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
49
+ bipartivity in complex networks", PhysRev E 72, 046105 (2005)
50
+ """
51
+ import scipy as sp
52
+
53
+ nodelist = list(G) # ordering of nodes in matrix
54
+ A = nx.to_numpy_array(G, nodelist, weight=weight)
55
+ expA = sp.linalg.expm(A)
56
+ expmA = sp.linalg.expm(-A)
57
+ coshA = 0.5 * (expA + expmA)
58
+ if nodes is None:
59
+ # return single number for entire graph
60
+ return float(coshA.diagonal().sum() / expA.diagonal().sum())
61
+ else:
62
+ # contribution for individual nodes
63
+ index = dict(zip(nodelist, range(len(nodelist))))
64
+ sb = {}
65
+ for n in nodes:
66
+ i = index[n]
67
+ sb[n] = coshA.item(i, i) / expA.item(i, i)
68
+ return sb
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_closeness_centrality.cpython-310.pyc ADDED
Binary file (9.32 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_current_flow_betweenness_centrality.cpython-310.pyc ADDED
Binary file (7.98 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_degree_centrality.cpython-310.pyc ADDED
Binary file (3.99 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_eigenvector_centrality.cpython-310.pyc ADDED
Binary file (5.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_harmonic_centrality.cpython-310.pyc ADDED
Binary file (5.07 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_reaching.cpython-310.pyc ADDED
Binary file (5.67 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_trophic.cpython-310.pyc ADDED
Binary file (7.15 kB). View file
 
env-llmeval/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"]
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (379 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/greedy_coloring.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
env-llmeval/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}
env-llmeval/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()}
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/test_coloring.cpython-310.pyc ADDED
Binary file (17.9 kB). View file
 
env-llmeval/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}
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_boundary.cpython-310.pyc ADDED
Binary file (7.15 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_bridges.cpython-310.pyc ADDED
Binary file (4.89 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_broadcasting.cpython-310.pyc ADDED
Binary file (2.18 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chains.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chordal.cpython-310.pyc ADDED
Binary file (4.41 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_clique.cpython-310.pyc ADDED
Binary file (8.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cluster.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_core.cpython-310.pyc ADDED
Binary file (9.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cuts.cpython-310.pyc ADDED
Binary file (6.28 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cycles.cpython-310.pyc ADDED
Binary file (35.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dag.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dominance.cpython-310.pyc ADDED
Binary file (8.52 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_efficiency.cpython-310.pyc ADDED
Binary file (2.86 kB). View file