ZTWHHH commited on
Commit
e5d283b
·
verified ·
1 Parent(s): 9f0c790

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. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/__pycache__/__init__.cpython-310.pyc +0 -0
  2. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/__init__.py +11 -0
  3. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/connectivity.py +811 -0
  4. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/cuts.py +612 -0
  5. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_augmentation.py +1270 -0
  6. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py +592 -0
  7. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcomponents.py +223 -0
  8. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcutsets.py +235 -0
  9. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/stoerwagner.py +152 -0
  10. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/utils.py +88 -0
  11. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc +0 -0
  12. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc +0 -0
  13. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc +0 -0
  14. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc +0 -0
  15. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc +0 -0
  16. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc +0 -0
  17. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc +0 -0
  18. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc +0 -0
  19. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc +0 -0
  20. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc +0 -0
  21. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz +3 -0
  22. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/classic.py +1068 -0
  23. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/directed.py +501 -0
  24. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/duplication.py +174 -0
  25. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/harary_graph.py +199 -0
  26. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/interval_graph.py +70 -0
  27. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/nonisomorphic_trees.py +212 -0
  28. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/random_clustered.py +117 -0
  29. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/social.py +554 -0
  30. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/spectral_graph_forge.py +120 -0
  31. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/sudoku.py +131 -0
  32. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc +0 -0
  33. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc +0 -0
  34. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-310.pyc +0 -0
  35. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc +0 -0
  36. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc +0 -0
  37. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc +0 -0
  38. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc +0 -0
  39. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc +0 -0
  40. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc +0 -0
  41. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc +0 -0
  42. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc +0 -0
  43. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc +0 -0
  44. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc +0 -0
  45. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc +0 -0
  46. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc +0 -0
  47. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc +0 -0
  48. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc +0 -0
  49. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc +0 -0
  50. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc +0 -0
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.5 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Connectivity and cut algorithms"""
2
+
3
+ from .connectivity import *
4
+ from .cuts import *
5
+ from .edge_augmentation import *
6
+ from .edge_kcomponents import *
7
+ from .disjoint_paths import *
8
+ from .kcomponents import *
9
+ from .kcutsets import *
10
+ from .stoerwagner import *
11
+ from .utils import *
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/connectivity.py ADDED
@@ -0,0 +1,811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flow based connectivity algorithms
3
+ """
4
+
5
+ import itertools
6
+ from operator import itemgetter
7
+
8
+ import networkx as nx
9
+
10
+ # Define the default maximum flow function to use in all flow based
11
+ # connectivity algorithms.
12
+ from networkx.algorithms.flow import (
13
+ boykov_kolmogorov,
14
+ build_residual_network,
15
+ dinitz,
16
+ edmonds_karp,
17
+ preflow_push,
18
+ shortest_augmenting_path,
19
+ )
20
+
21
+ default_flow_func = edmonds_karp
22
+
23
+ from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
24
+
25
+ __all__ = [
26
+ "average_node_connectivity",
27
+ "local_node_connectivity",
28
+ "node_connectivity",
29
+ "local_edge_connectivity",
30
+ "edge_connectivity",
31
+ "all_pairs_node_connectivity",
32
+ ]
33
+
34
+
35
+ @nx._dispatchable(graphs={"G": 0, "auxiliary?": 4}, preserve_graph_attrs={"auxiliary"})
36
+ def local_node_connectivity(
37
+ G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None
38
+ ):
39
+ r"""Computes local node connectivity for nodes s and t.
40
+
41
+ Local node connectivity for two non adjacent nodes s and t is the
42
+ minimum number of nodes that must be removed (along with their incident
43
+ edges) to disconnect them.
44
+
45
+ This is a flow based implementation of node connectivity. We compute the
46
+ maximum flow on an auxiliary digraph build from the original input
47
+ graph (see below for details).
48
+
49
+ Parameters
50
+ ----------
51
+ G : NetworkX graph
52
+ Undirected graph
53
+
54
+ s : node
55
+ Source node
56
+
57
+ t : node
58
+ Target node
59
+
60
+ flow_func : function
61
+ A function for computing the maximum flow among a pair of nodes.
62
+ The function has to accept at least three parameters: a Digraph,
63
+ a source node, and a target node. And return a residual network
64
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
65
+ details). If flow_func is None, the default maximum flow function
66
+ (:meth:`edmonds_karp`) is used. See below for details. The choice
67
+ of the default function may change from version to version and
68
+ should not be relied on. Default value: None.
69
+
70
+ auxiliary : NetworkX DiGraph
71
+ Auxiliary digraph to compute flow based node connectivity. It has
72
+ to have a graph attribute called mapping with a dictionary mapping
73
+ node names in G and in the auxiliary digraph. If provided
74
+ it will be reused instead of recreated. Default value: None.
75
+
76
+ residual : NetworkX DiGraph
77
+ Residual network to compute maximum flow. If provided it will be
78
+ reused instead of recreated. Default value: None.
79
+
80
+ cutoff : integer, float, or None (default: None)
81
+ If specified, the maximum flow algorithm will terminate when the
82
+ flow value reaches or exceeds the cutoff. This only works for flows
83
+ that support the cutoff parameter (most do) and is ignored otherwise.
84
+
85
+ Returns
86
+ -------
87
+ K : integer
88
+ local node connectivity for nodes s and t
89
+
90
+ Examples
91
+ --------
92
+ This function is not imported in the base NetworkX namespace, so you
93
+ have to explicitly import it from the connectivity package:
94
+
95
+ >>> from networkx.algorithms.connectivity import local_node_connectivity
96
+
97
+ We use in this example the platonic icosahedral graph, which has node
98
+ connectivity 5.
99
+
100
+ >>> G = nx.icosahedral_graph()
101
+ >>> local_node_connectivity(G, 0, 6)
102
+ 5
103
+
104
+ If you need to compute local connectivity on several pairs of
105
+ nodes in the same graph, it is recommended that you reuse the
106
+ data structures that NetworkX uses in the computation: the
107
+ auxiliary digraph for node connectivity, and the residual
108
+ network for the underlying maximum flow computation.
109
+
110
+ Example of how to compute local node connectivity among
111
+ all pairs of nodes of the platonic icosahedral graph reusing
112
+ the data structures.
113
+
114
+ >>> import itertools
115
+ >>> # You also have to explicitly import the function for
116
+ >>> # building the auxiliary digraph from the connectivity package
117
+ >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
118
+ >>> H = build_auxiliary_node_connectivity(G)
119
+ >>> # And the function for building the residual network from the
120
+ >>> # flow package
121
+ >>> from networkx.algorithms.flow import build_residual_network
122
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
123
+ >>> R = build_residual_network(H, "capacity")
124
+ >>> result = dict.fromkeys(G, dict())
125
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
126
+ >>> # as parameters
127
+ >>> for u, v in itertools.combinations(G, 2):
128
+ ... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R)
129
+ ... result[u][v] = k
130
+ >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
131
+ True
132
+
133
+ You can also use alternative flow algorithms for computing node
134
+ connectivity. For instance, in dense networks the algorithm
135
+ :meth:`shortest_augmenting_path` will usually perform better than
136
+ the default :meth:`edmonds_karp` which is faster for sparse
137
+ networks with highly skewed degree distributions. Alternative flow
138
+ functions have to be explicitly imported from the flow package.
139
+
140
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
141
+ >>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
142
+ 5
143
+
144
+ Notes
145
+ -----
146
+ This is a flow based implementation of node connectivity. We compute the
147
+ maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see:
148
+ :meth:`maximum_flow`) on an auxiliary digraph build from the original
149
+ input graph:
150
+
151
+ For an undirected graph G having `n` nodes and `m` edges we derive a
152
+ directed graph H with `2n` nodes and `2m+n` arcs by replacing each
153
+ original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
154
+ arc in H. Then for each edge (`u`, `v`) in G we add two arcs
155
+ (`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute
156
+ capacity = 1 for each arc in H [1]_ .
157
+
158
+ For a directed graph G having `n` nodes and `m` arcs we derive a
159
+ directed graph H with `2n` nodes and `m+n` arcs by replacing each
160
+ original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
161
+ arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc
162
+ (`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for
163
+ each arc in H.
164
+
165
+ This is equal to the local node connectivity because the value of
166
+ a maximum s-t-flow is equal to the capacity of a minimum s-t-cut.
167
+
168
+ See also
169
+ --------
170
+ :meth:`local_edge_connectivity`
171
+ :meth:`node_connectivity`
172
+ :meth:`minimum_node_cut`
173
+ :meth:`maximum_flow`
174
+ :meth:`edmonds_karp`
175
+ :meth:`preflow_push`
176
+ :meth:`shortest_augmenting_path`
177
+
178
+ References
179
+ ----------
180
+ .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
181
+ Erlebach, 'Network Analysis: Methodological Foundations', Lecture
182
+ Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
183
+ http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
184
+
185
+ """
186
+ if flow_func is None:
187
+ flow_func = default_flow_func
188
+
189
+ if auxiliary is None:
190
+ H = build_auxiliary_node_connectivity(G)
191
+ else:
192
+ H = auxiliary
193
+
194
+ mapping = H.graph.get("mapping", None)
195
+ if mapping is None:
196
+ raise nx.NetworkXError("Invalid auxiliary digraph.")
197
+
198
+ kwargs = {"flow_func": flow_func, "residual": residual}
199
+
200
+ if flow_func is not preflow_push:
201
+ kwargs["cutoff"] = cutoff
202
+
203
+ if flow_func is shortest_augmenting_path:
204
+ kwargs["two_phase"] = True
205
+
206
+ return nx.maximum_flow_value(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
207
+
208
+
209
+ @nx._dispatchable
210
+ def node_connectivity(G, s=None, t=None, flow_func=None):
211
+ r"""Returns node connectivity for a graph or digraph G.
212
+
213
+ Node connectivity is equal to the minimum number of nodes that
214
+ must be removed to disconnect G or render it trivial. If source
215
+ and target nodes are provided, this function returns the local node
216
+ connectivity: the minimum number of nodes that must be removed to break
217
+ all paths from source to target in G.
218
+
219
+ Parameters
220
+ ----------
221
+ G : NetworkX graph
222
+ Undirected graph
223
+
224
+ s : node
225
+ Source node. Optional. Default value: None.
226
+
227
+ t : node
228
+ Target node. Optional. Default value: None.
229
+
230
+ flow_func : function
231
+ A function for computing the maximum flow among a pair of nodes.
232
+ The function has to accept at least three parameters: a Digraph,
233
+ a source node, and a target node. And return a residual network
234
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
235
+ details). If flow_func is None, the default maximum flow function
236
+ (:meth:`edmonds_karp`) is used. See below for details. The
237
+ choice of the default function may change from version
238
+ to version and should not be relied on. Default value: None.
239
+
240
+ Returns
241
+ -------
242
+ K : integer
243
+ Node connectivity of G, or local node connectivity if source
244
+ and target are provided.
245
+
246
+ Examples
247
+ --------
248
+ >>> # Platonic icosahedral graph is 5-node-connected
249
+ >>> G = nx.icosahedral_graph()
250
+ >>> nx.node_connectivity(G)
251
+ 5
252
+
253
+ You can use alternative flow algorithms for the underlying maximum
254
+ flow computation. In dense networks the algorithm
255
+ :meth:`shortest_augmenting_path` will usually perform better
256
+ than the default :meth:`edmonds_karp`, which is faster for
257
+ sparse networks with highly skewed degree distributions. Alternative
258
+ flow functions have to be explicitly imported from the flow package.
259
+
260
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
261
+ >>> nx.node_connectivity(G, flow_func=shortest_augmenting_path)
262
+ 5
263
+
264
+ If you specify a pair of nodes (source and target) as parameters,
265
+ this function returns the value of local node connectivity.
266
+
267
+ >>> nx.node_connectivity(G, 3, 7)
268
+ 5
269
+
270
+ If you need to perform several local computations among different
271
+ pairs of nodes on the same graph, it is recommended that you reuse
272
+ the data structures used in the maximum flow computations. See
273
+ :meth:`local_node_connectivity` for details.
274
+
275
+ Notes
276
+ -----
277
+ This is a flow based implementation of node connectivity. The
278
+ algorithm works by solving $O((n-\delta-1+\delta(\delta-1)/2))$
279
+ maximum flow problems on an auxiliary digraph. Where $\delta$
280
+ is the minimum degree of G. For details about the auxiliary
281
+ digraph and the computation of local node connectivity see
282
+ :meth:`local_node_connectivity`. This implementation is based
283
+ on algorithm 11 in [1]_.
284
+
285
+ See also
286
+ --------
287
+ :meth:`local_node_connectivity`
288
+ :meth:`edge_connectivity`
289
+ :meth:`maximum_flow`
290
+ :meth:`edmonds_karp`
291
+ :meth:`preflow_push`
292
+ :meth:`shortest_augmenting_path`
293
+
294
+ References
295
+ ----------
296
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
297
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
298
+
299
+ """
300
+ if (s is not None and t is None) or (s is None and t is not None):
301
+ raise nx.NetworkXError("Both source and target must be specified.")
302
+
303
+ # Local node connectivity
304
+ if s is not None and t is not None:
305
+ if s not in G:
306
+ raise nx.NetworkXError(f"node {s} not in graph")
307
+ if t not in G:
308
+ raise nx.NetworkXError(f"node {t} not in graph")
309
+ return local_node_connectivity(G, s, t, flow_func=flow_func)
310
+
311
+ # Global node connectivity
312
+ if G.is_directed():
313
+ if not nx.is_weakly_connected(G):
314
+ return 0
315
+ iter_func = itertools.permutations
316
+ # It is necessary to consider both predecessors
317
+ # and successors for directed graphs
318
+
319
+ def neighbors(v):
320
+ return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
321
+
322
+ else:
323
+ if not nx.is_connected(G):
324
+ return 0
325
+ iter_func = itertools.combinations
326
+ neighbors = G.neighbors
327
+
328
+ # Reuse the auxiliary digraph and the residual network
329
+ H = build_auxiliary_node_connectivity(G)
330
+ R = build_residual_network(H, "capacity")
331
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
332
+
333
+ # Pick a node with minimum degree
334
+ # Node connectivity is bounded by degree.
335
+ v, K = min(G.degree(), key=itemgetter(1))
336
+ # compute local node connectivity with all its non-neighbors nodes
337
+ for w in set(G) - set(neighbors(v)) - {v}:
338
+ kwargs["cutoff"] = K
339
+ K = min(K, local_node_connectivity(G, v, w, **kwargs))
340
+ # Also for non adjacent pairs of neighbors of v
341
+ for x, y in iter_func(neighbors(v), 2):
342
+ if y in G[x]:
343
+ continue
344
+ kwargs["cutoff"] = K
345
+ K = min(K, local_node_connectivity(G, x, y, **kwargs))
346
+
347
+ return K
348
+
349
+
350
+ @nx._dispatchable
351
+ def average_node_connectivity(G, flow_func=None):
352
+ r"""Returns the average connectivity of a graph G.
353
+
354
+ The average connectivity `\bar{\kappa}` of a graph G is the average
355
+ of local node connectivity over all pairs of nodes of G [1]_ .
356
+
357
+ .. math::
358
+
359
+ \bar{\kappa}(G) = \frac{\sum_{u,v} \kappa_{G}(u,v)}{{n \choose 2}}
360
+
361
+ Parameters
362
+ ----------
363
+
364
+ G : NetworkX graph
365
+ Undirected graph
366
+
367
+ flow_func : function
368
+ A function for computing the maximum flow among a pair of nodes.
369
+ The function has to accept at least three parameters: a Digraph,
370
+ a source node, and a target node. And return a residual network
371
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
372
+ details). If flow_func is None, the default maximum flow function
373
+ (:meth:`edmonds_karp`) is used. See :meth:`local_node_connectivity`
374
+ for details. The choice of the default function may change from
375
+ version to version and should not be relied on. Default value: None.
376
+
377
+ Returns
378
+ -------
379
+ K : float
380
+ Average node connectivity
381
+
382
+ See also
383
+ --------
384
+ :meth:`local_node_connectivity`
385
+ :meth:`node_connectivity`
386
+ :meth:`edge_connectivity`
387
+ :meth:`maximum_flow`
388
+ :meth:`edmonds_karp`
389
+ :meth:`preflow_push`
390
+ :meth:`shortest_augmenting_path`
391
+
392
+ References
393
+ ----------
394
+ .. [1] Beineke, L., O. Oellermann, and R. Pippert (2002). The average
395
+ connectivity of a graph. Discrete mathematics 252(1-3), 31-45.
396
+ http://www.sciencedirect.com/science/article/pii/S0012365X01001807
397
+
398
+ """
399
+ if G.is_directed():
400
+ iter_func = itertools.permutations
401
+ else:
402
+ iter_func = itertools.combinations
403
+
404
+ # Reuse the auxiliary digraph and the residual network
405
+ H = build_auxiliary_node_connectivity(G)
406
+ R = build_residual_network(H, "capacity")
407
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
408
+
409
+ num, den = 0, 0
410
+ for u, v in iter_func(G, 2):
411
+ num += local_node_connectivity(G, u, v, **kwargs)
412
+ den += 1
413
+
414
+ if den == 0: # Null Graph
415
+ return 0
416
+ return num / den
417
+
418
+
419
+ @nx._dispatchable
420
+ def all_pairs_node_connectivity(G, nbunch=None, flow_func=None):
421
+ """Compute node connectivity between all pairs of nodes of G.
422
+
423
+ Parameters
424
+ ----------
425
+ G : NetworkX graph
426
+ Undirected graph
427
+
428
+ nbunch: container
429
+ Container of nodes. If provided node connectivity will be computed
430
+ only over pairs of nodes in nbunch.
431
+
432
+ flow_func : function
433
+ A function for computing the maximum flow among a pair of nodes.
434
+ The function has to accept at least three parameters: a Digraph,
435
+ a source node, and a target node. And return a residual network
436
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
437
+ details). If flow_func is None, the default maximum flow function
438
+ (:meth:`edmonds_karp`) is used. See below for details. The
439
+ choice of the default function may change from version
440
+ to version and should not be relied on. Default value: None.
441
+
442
+ Returns
443
+ -------
444
+ all_pairs : dict
445
+ A dictionary with node connectivity between all pairs of nodes
446
+ in G, or in nbunch if provided.
447
+
448
+ See also
449
+ --------
450
+ :meth:`local_node_connectivity`
451
+ :meth:`edge_connectivity`
452
+ :meth:`local_edge_connectivity`
453
+ :meth:`maximum_flow`
454
+ :meth:`edmonds_karp`
455
+ :meth:`preflow_push`
456
+ :meth:`shortest_augmenting_path`
457
+
458
+ """
459
+ if nbunch is None:
460
+ nbunch = G
461
+ else:
462
+ nbunch = set(nbunch)
463
+
464
+ directed = G.is_directed()
465
+ if directed:
466
+ iter_func = itertools.permutations
467
+ else:
468
+ iter_func = itertools.combinations
469
+
470
+ all_pairs = {n: {} for n in nbunch}
471
+
472
+ # Reuse auxiliary digraph and residual network
473
+ H = build_auxiliary_node_connectivity(G)
474
+ mapping = H.graph["mapping"]
475
+ R = build_residual_network(H, "capacity")
476
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
477
+
478
+ for u, v in iter_func(nbunch, 2):
479
+ K = local_node_connectivity(G, u, v, **kwargs)
480
+ all_pairs[u][v] = K
481
+ if not directed:
482
+ all_pairs[v][u] = K
483
+
484
+ return all_pairs
485
+
486
+
487
+ @nx._dispatchable(graphs={"G": 0, "auxiliary?": 4})
488
+ def local_edge_connectivity(
489
+ G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None
490
+ ):
491
+ r"""Returns local edge connectivity for nodes s and t in G.
492
+
493
+ Local edge connectivity for two nodes s and t is the minimum number
494
+ of edges that must be removed to disconnect them.
495
+
496
+ This is a flow based implementation of edge connectivity. We compute the
497
+ maximum flow on an auxiliary digraph build from the original
498
+ network (see below for details). This is equal to the local edge
499
+ connectivity because the value of a maximum s-t-flow is equal to the
500
+ capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .
501
+
502
+ Parameters
503
+ ----------
504
+ G : NetworkX graph
505
+ Undirected or directed graph
506
+
507
+ s : node
508
+ Source node
509
+
510
+ t : node
511
+ Target node
512
+
513
+ flow_func : function
514
+ A function for computing the maximum flow among a pair of nodes.
515
+ The function has to accept at least three parameters: a Digraph,
516
+ a source node, and a target node. And return a residual network
517
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
518
+ details). If flow_func is None, the default maximum flow function
519
+ (:meth:`edmonds_karp`) is used. See below for details. The
520
+ choice of the default function may change from version
521
+ to version and should not be relied on. Default value: None.
522
+
523
+ auxiliary : NetworkX DiGraph
524
+ Auxiliary digraph for computing flow based edge connectivity. If
525
+ provided it will be reused instead of recreated. Default value: None.
526
+
527
+ residual : NetworkX DiGraph
528
+ Residual network to compute maximum flow. If provided it will be
529
+ reused instead of recreated. Default value: None.
530
+
531
+ cutoff : integer, float, or None (default: None)
532
+ If specified, the maximum flow algorithm will terminate when the
533
+ flow value reaches or exceeds the cutoff. This only works for flows
534
+ that support the cutoff parameter (most do) and is ignored otherwise.
535
+
536
+ Returns
537
+ -------
538
+ K : integer
539
+ local edge connectivity for nodes s and t.
540
+
541
+ Examples
542
+ --------
543
+ This function is not imported in the base NetworkX namespace, so you
544
+ have to explicitly import it from the connectivity package:
545
+
546
+ >>> from networkx.algorithms.connectivity import local_edge_connectivity
547
+
548
+ We use in this example the platonic icosahedral graph, which has edge
549
+ connectivity 5.
550
+
551
+ >>> G = nx.icosahedral_graph()
552
+ >>> local_edge_connectivity(G, 0, 6)
553
+ 5
554
+
555
+ If you need to compute local connectivity on several pairs of
556
+ nodes in the same graph, it is recommended that you reuse the
557
+ data structures that NetworkX uses in the computation: the
558
+ auxiliary digraph for edge connectivity, and the residual
559
+ network for the underlying maximum flow computation.
560
+
561
+ Example of how to compute local edge connectivity among
562
+ all pairs of nodes of the platonic icosahedral graph reusing
563
+ the data structures.
564
+
565
+ >>> import itertools
566
+ >>> # You also have to explicitly import the function for
567
+ >>> # building the auxiliary digraph from the connectivity package
568
+ >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
569
+ >>> H = build_auxiliary_edge_connectivity(G)
570
+ >>> # And the function for building the residual network from the
571
+ >>> # flow package
572
+ >>> from networkx.algorithms.flow import build_residual_network
573
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
574
+ >>> R = build_residual_network(H, "capacity")
575
+ >>> result = dict.fromkeys(G, dict())
576
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
577
+ >>> # as parameters
578
+ >>> for u, v in itertools.combinations(G, 2):
579
+ ... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R)
580
+ ... result[u][v] = k
581
+ >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
582
+ True
583
+
584
+ You can also use alternative flow algorithms for computing edge
585
+ connectivity. For instance, in dense networks the algorithm
586
+ :meth:`shortest_augmenting_path` will usually perform better than
587
+ the default :meth:`edmonds_karp` which is faster for sparse
588
+ networks with highly skewed degree distributions. Alternative flow
589
+ functions have to be explicitly imported from the flow package.
590
+
591
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
592
+ >>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
593
+ 5
594
+
595
+ Notes
596
+ -----
597
+ This is a flow based implementation of edge connectivity. We compute the
598
+ maximum flow using, by default, the :meth:`edmonds_karp` algorithm on an
599
+ auxiliary digraph build from the original input graph:
600
+
601
+ If the input graph is undirected, we replace each edge (`u`,`v`) with
602
+ two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
603
+ 'capacity' for each arc to 1. If the input graph is directed we simply
604
+ add the 'capacity' attribute. This is an implementation of algorithm 1
605
+ in [1]_.
606
+
607
+ The maximum flow in the auxiliary network is equal to the local edge
608
+ connectivity because the value of a maximum s-t-flow is equal to the
609
+ capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
610
+
611
+ See also
612
+ --------
613
+ :meth:`edge_connectivity`
614
+ :meth:`local_node_connectivity`
615
+ :meth:`node_connectivity`
616
+ :meth:`maximum_flow`
617
+ :meth:`edmonds_karp`
618
+ :meth:`preflow_push`
619
+ :meth:`shortest_augmenting_path`
620
+
621
+ References
622
+ ----------
623
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
624
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
625
+
626
+ """
627
+ if flow_func is None:
628
+ flow_func = default_flow_func
629
+
630
+ if auxiliary is None:
631
+ H = build_auxiliary_edge_connectivity(G)
632
+ else:
633
+ H = auxiliary
634
+
635
+ kwargs = {"flow_func": flow_func, "residual": residual}
636
+
637
+ if flow_func is not preflow_push:
638
+ kwargs["cutoff"] = cutoff
639
+
640
+ if flow_func is shortest_augmenting_path:
641
+ kwargs["two_phase"] = True
642
+
643
+ return nx.maximum_flow_value(H, s, t, **kwargs)
644
+
645
+
646
+ @nx._dispatchable
647
+ def edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None):
648
+ r"""Returns the edge connectivity of the graph or digraph G.
649
+
650
+ The edge connectivity is equal to the minimum number of edges that
651
+ must be removed to disconnect G or render it trivial. If source
652
+ and target nodes are provided, this function returns the local edge
653
+ connectivity: the minimum number of edges that must be removed to
654
+ break all paths from source to target in G.
655
+
656
+ Parameters
657
+ ----------
658
+ G : NetworkX graph
659
+ Undirected or directed graph
660
+
661
+ s : node
662
+ Source node. Optional. Default value: None.
663
+
664
+ t : node
665
+ Target node. Optional. Default value: None.
666
+
667
+ flow_func : function
668
+ A function for computing the maximum flow among a pair of nodes.
669
+ The function has to accept at least three parameters: a Digraph,
670
+ a source node, and a target node. And return a residual network
671
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
672
+ details). If flow_func is None, the default maximum flow function
673
+ (:meth:`edmonds_karp`) is used. See below for details. The
674
+ choice of the default function may change from version
675
+ to version and should not be relied on. Default value: None.
676
+
677
+ cutoff : integer, float, or None (default: None)
678
+ If specified, the maximum flow algorithm will terminate when the
679
+ flow value reaches or exceeds the cutoff. This only works for flows
680
+ that support the cutoff parameter (most do) and is ignored otherwise.
681
+
682
+ Returns
683
+ -------
684
+ K : integer
685
+ Edge connectivity for G, or local edge connectivity if source
686
+ and target were provided
687
+
688
+ Examples
689
+ --------
690
+ >>> # Platonic icosahedral graph is 5-edge-connected
691
+ >>> G = nx.icosahedral_graph()
692
+ >>> nx.edge_connectivity(G)
693
+ 5
694
+
695
+ You can use alternative flow algorithms for the underlying
696
+ maximum flow computation. In dense networks the algorithm
697
+ :meth:`shortest_augmenting_path` will usually perform better
698
+ than the default :meth:`edmonds_karp`, which is faster for
699
+ sparse networks with highly skewed degree distributions.
700
+ Alternative flow functions have to be explicitly imported
701
+ from the flow package.
702
+
703
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
704
+ >>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
705
+ 5
706
+
707
+ If you specify a pair of nodes (source and target) as parameters,
708
+ this function returns the value of local edge connectivity.
709
+
710
+ >>> nx.edge_connectivity(G, 3, 7)
711
+ 5
712
+
713
+ If you need to perform several local computations among different
714
+ pairs of nodes on the same graph, it is recommended that you reuse
715
+ the data structures used in the maximum flow computations. See
716
+ :meth:`local_edge_connectivity` for details.
717
+
718
+ Notes
719
+ -----
720
+ This is a flow based implementation of global edge connectivity.
721
+ For undirected graphs the algorithm works by finding a 'small'
722
+ dominating set of nodes of G (see algorithm 7 in [1]_ ) and
723
+ computing local maximum flow (see :meth:`local_edge_connectivity`)
724
+ between an arbitrary node in the dominating set and the rest of
725
+ nodes in it. This is an implementation of algorithm 6 in [1]_ .
726
+ For directed graphs, the algorithm does n calls to the maximum
727
+ flow function. This is an implementation of algorithm 8 in [1]_ .
728
+
729
+ See also
730
+ --------
731
+ :meth:`local_edge_connectivity`
732
+ :meth:`local_node_connectivity`
733
+ :meth:`node_connectivity`
734
+ :meth:`maximum_flow`
735
+ :meth:`edmonds_karp`
736
+ :meth:`preflow_push`
737
+ :meth:`shortest_augmenting_path`
738
+ :meth:`k_edge_components`
739
+ :meth:`k_edge_subgraphs`
740
+
741
+ References
742
+ ----------
743
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
744
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
745
+
746
+ """
747
+ if (s is not None and t is None) or (s is None and t is not None):
748
+ raise nx.NetworkXError("Both source and target must be specified.")
749
+
750
+ # Local edge connectivity
751
+ if s is not None and t is not None:
752
+ if s not in G:
753
+ raise nx.NetworkXError(f"node {s} not in graph")
754
+ if t not in G:
755
+ raise nx.NetworkXError(f"node {t} not in graph")
756
+ return local_edge_connectivity(G, s, t, flow_func=flow_func, cutoff=cutoff)
757
+
758
+ # Global edge connectivity
759
+ # reuse auxiliary digraph and residual network
760
+ H = build_auxiliary_edge_connectivity(G)
761
+ R = build_residual_network(H, "capacity")
762
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
763
+
764
+ if G.is_directed():
765
+ # Algorithm 8 in [1]
766
+ if not nx.is_weakly_connected(G):
767
+ return 0
768
+
769
+ # initial value for \lambda is minimum degree
770
+ L = min(d for n, d in G.degree())
771
+ nodes = list(G)
772
+ n = len(nodes)
773
+
774
+ if cutoff is not None:
775
+ L = min(cutoff, L)
776
+
777
+ for i in range(n):
778
+ kwargs["cutoff"] = L
779
+ try:
780
+ L = min(L, local_edge_connectivity(G, nodes[i], nodes[i + 1], **kwargs))
781
+ except IndexError: # last node!
782
+ L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs))
783
+ return L
784
+ else: # undirected
785
+ # Algorithm 6 in [1]
786
+ if not nx.is_connected(G):
787
+ return 0
788
+
789
+ # initial value for \lambda is minimum degree
790
+ L = min(d for n, d in G.degree())
791
+
792
+ if cutoff is not None:
793
+ L = min(cutoff, L)
794
+
795
+ # A dominating set is \lambda-covering
796
+ # We need a dominating set with at least two nodes
797
+ for node in G:
798
+ D = nx.dominating_set(G, start_with=node)
799
+ v = D.pop()
800
+ if D:
801
+ break
802
+ else:
803
+ # in complete graphs the dominating sets will always be of one node
804
+ # thus we return min degree
805
+ return L
806
+
807
+ for w in D:
808
+ kwargs["cutoff"] = L
809
+ L = min(L, local_edge_connectivity(G, v, w, **kwargs))
810
+
811
+ return L
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/cuts.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flow based cut algorithms
3
+ """
4
+
5
+ import itertools
6
+
7
+ import networkx as nx
8
+
9
+ # Define the default maximum flow function to use in all flow based
10
+ # cut algorithms.
11
+ from networkx.algorithms.flow import build_residual_network, edmonds_karp
12
+
13
+ default_flow_func = edmonds_karp
14
+
15
+ from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
16
+
17
+ __all__ = [
18
+ "minimum_st_node_cut",
19
+ "minimum_node_cut",
20
+ "minimum_st_edge_cut",
21
+ "minimum_edge_cut",
22
+ ]
23
+
24
+
25
+ @nx._dispatchable(
26
+ graphs={"G": 0, "auxiliary?": 4},
27
+ preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}},
28
+ preserve_graph_attrs={"auxiliary"},
29
+ )
30
+ def minimum_st_edge_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
31
+ """Returns the edges of the cut-set of a minimum (s, t)-cut.
32
+
33
+ This function returns the set of edges of minimum cardinality that,
34
+ if removed, would destroy all paths among source and target in G.
35
+ Edge weights are not considered. See :meth:`minimum_cut` for
36
+ computing minimum cuts considering edge weights.
37
+
38
+ Parameters
39
+ ----------
40
+ G : NetworkX graph
41
+
42
+ s : node
43
+ Source node for the flow.
44
+
45
+ t : node
46
+ Sink node for the flow.
47
+
48
+ auxiliary : NetworkX DiGraph
49
+ Auxiliary digraph to compute flow based node connectivity. It has
50
+ to have a graph attribute called mapping with a dictionary mapping
51
+ node names in G and in the auxiliary digraph. If provided
52
+ it will be reused instead of recreated. Default value: None.
53
+
54
+ flow_func : function
55
+ A function for computing the maximum flow among a pair of nodes.
56
+ The function has to accept at least three parameters: a Digraph,
57
+ a source node, and a target node. And return a residual network
58
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
59
+ details). If flow_func is None, the default maximum flow function
60
+ (:meth:`edmonds_karp`) is used. See :meth:`node_connectivity` for
61
+ details. The choice of the default function may change from version
62
+ to version and should not be relied on. Default value: None.
63
+
64
+ residual : NetworkX DiGraph
65
+ Residual network to compute maximum flow. If provided it will be
66
+ reused instead of recreated. Default value: None.
67
+
68
+ Returns
69
+ -------
70
+ cutset : set
71
+ Set of edges that, if removed from the graph, will disconnect it.
72
+
73
+ See also
74
+ --------
75
+ :meth:`minimum_cut`
76
+ :meth:`minimum_node_cut`
77
+ :meth:`minimum_edge_cut`
78
+ :meth:`stoer_wagner`
79
+ :meth:`node_connectivity`
80
+ :meth:`edge_connectivity`
81
+ :meth:`maximum_flow`
82
+ :meth:`edmonds_karp`
83
+ :meth:`preflow_push`
84
+ :meth:`shortest_augmenting_path`
85
+
86
+ Examples
87
+ --------
88
+ This function is not imported in the base NetworkX namespace, so you
89
+ have to explicitly import it from the connectivity package:
90
+
91
+ >>> from networkx.algorithms.connectivity import minimum_st_edge_cut
92
+
93
+ We use in this example the platonic icosahedral graph, which has edge
94
+ connectivity 5.
95
+
96
+ >>> G = nx.icosahedral_graph()
97
+ >>> len(minimum_st_edge_cut(G, 0, 6))
98
+ 5
99
+
100
+ If you need to compute local edge cuts on several pairs of
101
+ nodes in the same graph, it is recommended that you reuse the
102
+ data structures that NetworkX uses in the computation: the
103
+ auxiliary digraph for edge connectivity, and the residual
104
+ network for the underlying maximum flow computation.
105
+
106
+ Example of how to compute local edge cuts among all pairs of
107
+ nodes of the platonic icosahedral graph reusing the data
108
+ structures.
109
+
110
+ >>> import itertools
111
+ >>> # You also have to explicitly import the function for
112
+ >>> # building the auxiliary digraph from the connectivity package
113
+ >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
114
+ >>> H = build_auxiliary_edge_connectivity(G)
115
+ >>> # And the function for building the residual network from the
116
+ >>> # flow package
117
+ >>> from networkx.algorithms.flow import build_residual_network
118
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
119
+ >>> R = build_residual_network(H, "capacity")
120
+ >>> result = dict.fromkeys(G, dict())
121
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
122
+ >>> # as parameters
123
+ >>> for u, v in itertools.combinations(G, 2):
124
+ ... k = len(minimum_st_edge_cut(G, u, v, auxiliary=H, residual=R))
125
+ ... result[u][v] = k
126
+ >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
127
+ True
128
+
129
+ You can also use alternative flow algorithms for computing edge
130
+ cuts. For instance, in dense networks the algorithm
131
+ :meth:`shortest_augmenting_path` will usually perform better than
132
+ the default :meth:`edmonds_karp` which is faster for sparse
133
+ networks with highly skewed degree distributions. Alternative flow
134
+ functions have to be explicitly imported from the flow package.
135
+
136
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
137
+ >>> len(minimum_st_edge_cut(G, 0, 6, flow_func=shortest_augmenting_path))
138
+ 5
139
+
140
+ """
141
+ if flow_func is None:
142
+ flow_func = default_flow_func
143
+
144
+ if auxiliary is None:
145
+ H = build_auxiliary_edge_connectivity(G)
146
+ else:
147
+ H = auxiliary
148
+
149
+ kwargs = {"capacity": "capacity", "flow_func": flow_func, "residual": residual}
150
+
151
+ cut_value, partition = nx.minimum_cut(H, s, t, **kwargs)
152
+ reachable, non_reachable = partition
153
+ # Any edge in the original graph linking the two sets in the
154
+ # partition is part of the edge cutset
155
+ cutset = set()
156
+ for u, nbrs in ((n, G[n]) for n in reachable):
157
+ cutset.update((u, v) for v in nbrs if v in non_reachable)
158
+
159
+ return cutset
160
+
161
+
162
+ @nx._dispatchable(
163
+ graphs={"G": 0, "auxiliary?": 4},
164
+ preserve_node_attrs={"auxiliary": {"id": None}},
165
+ preserve_graph_attrs={"auxiliary"},
166
+ )
167
+ def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
168
+ r"""Returns a set of nodes of minimum cardinality that disconnect source
169
+ from target in G.
170
+
171
+ This function returns the set of nodes of minimum cardinality that,
172
+ if removed, would destroy all paths among source and target in G.
173
+
174
+ Parameters
175
+ ----------
176
+ G : NetworkX graph
177
+
178
+ s : node
179
+ Source node.
180
+
181
+ t : node
182
+ Target node.
183
+
184
+ flow_func : function
185
+ A function for computing the maximum flow among a pair of nodes.
186
+ The function has to accept at least three parameters: a Digraph,
187
+ a source node, and a target node. And return a residual network
188
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
189
+ details). If flow_func is None, the default maximum flow function
190
+ (:meth:`edmonds_karp`) is used. See below for details. The choice
191
+ of the default function may change from version to version and
192
+ should not be relied on. Default value: None.
193
+
194
+ auxiliary : NetworkX DiGraph
195
+ Auxiliary digraph to compute flow based node connectivity. It has
196
+ to have a graph attribute called mapping with a dictionary mapping
197
+ node names in G and in the auxiliary digraph. If provided
198
+ it will be reused instead of recreated. Default value: None.
199
+
200
+ residual : NetworkX DiGraph
201
+ Residual network to compute maximum flow. If provided it will be
202
+ reused instead of recreated. Default value: None.
203
+
204
+ Returns
205
+ -------
206
+ cutset : set
207
+ Set of nodes that, if removed, would destroy all paths between
208
+ source and target in G.
209
+
210
+ Examples
211
+ --------
212
+ This function is not imported in the base NetworkX namespace, so you
213
+ have to explicitly import it from the connectivity package:
214
+
215
+ >>> from networkx.algorithms.connectivity import minimum_st_node_cut
216
+
217
+ We use in this example the platonic icosahedral graph, which has node
218
+ connectivity 5.
219
+
220
+ >>> G = nx.icosahedral_graph()
221
+ >>> len(minimum_st_node_cut(G, 0, 6))
222
+ 5
223
+
224
+ If you need to compute local st cuts between several pairs of
225
+ nodes in the same graph, it is recommended that you reuse the
226
+ data structures that NetworkX uses in the computation: the
227
+ auxiliary digraph for node connectivity and node cuts, and the
228
+ residual network for the underlying maximum flow computation.
229
+
230
+ Example of how to compute local st node cuts reusing the data
231
+ structures:
232
+
233
+ >>> # You also have to explicitly import the function for
234
+ >>> # building the auxiliary digraph from the connectivity package
235
+ >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
236
+ >>> H = build_auxiliary_node_connectivity(G)
237
+ >>> # And the function for building the residual network from the
238
+ >>> # flow package
239
+ >>> from networkx.algorithms.flow import build_residual_network
240
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
241
+ >>> R = build_residual_network(H, "capacity")
242
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
243
+ >>> # as parameters
244
+ >>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R))
245
+ 5
246
+
247
+ You can also use alternative flow algorithms for computing minimum st
248
+ node cuts. For instance, in dense networks the algorithm
249
+ :meth:`shortest_augmenting_path` will usually perform better than
250
+ the default :meth:`edmonds_karp` which is faster for sparse
251
+ networks with highly skewed degree distributions. Alternative flow
252
+ functions have to be explicitly imported from the flow package.
253
+
254
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
255
+ >>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path))
256
+ 5
257
+
258
+ Notes
259
+ -----
260
+ This is a flow based implementation of minimum node cut. The algorithm
261
+ is based in solving a number of maximum flow computations to determine
262
+ the capacity of the minimum cut on an auxiliary directed network that
263
+ corresponds to the minimum node cut of G. It handles both directed
264
+ and undirected graphs. This implementation is based on algorithm 11
265
+ in [1]_.
266
+
267
+ See also
268
+ --------
269
+ :meth:`minimum_node_cut`
270
+ :meth:`minimum_edge_cut`
271
+ :meth:`stoer_wagner`
272
+ :meth:`node_connectivity`
273
+ :meth:`edge_connectivity`
274
+ :meth:`maximum_flow`
275
+ :meth:`edmonds_karp`
276
+ :meth:`preflow_push`
277
+ :meth:`shortest_augmenting_path`
278
+
279
+ References
280
+ ----------
281
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
282
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
283
+
284
+ """
285
+ if auxiliary is None:
286
+ H = build_auxiliary_node_connectivity(G)
287
+ else:
288
+ H = auxiliary
289
+
290
+ mapping = H.graph.get("mapping", None)
291
+ if mapping is None:
292
+ raise nx.NetworkXError("Invalid auxiliary digraph.")
293
+ if G.has_edge(s, t) or G.has_edge(t, s):
294
+ return {}
295
+ kwargs = {"flow_func": flow_func, "residual": residual, "auxiliary": H}
296
+
297
+ # The edge cut in the auxiliary digraph corresponds to the node cut in the
298
+ # original graph.
299
+ edge_cut = minimum_st_edge_cut(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
300
+ # Each node in the original graph maps to two nodes of the auxiliary graph
301
+ node_cut = {H.nodes[node]["id"] for edge in edge_cut for node in edge}
302
+ return node_cut - {s, t}
303
+
304
+
305
+ @nx._dispatchable
306
+ def minimum_node_cut(G, s=None, t=None, flow_func=None):
307
+ r"""Returns a set of nodes of minimum cardinality that disconnects G.
308
+
309
+ If source and target nodes are provided, this function returns the
310
+ set of nodes of minimum cardinality that, if removed, would destroy
311
+ all paths among source and target in G. If not, it returns a set
312
+ of nodes of minimum cardinality that disconnects G.
313
+
314
+ Parameters
315
+ ----------
316
+ G : NetworkX graph
317
+
318
+ s : node
319
+ Source node. Optional. Default value: None.
320
+
321
+ t : node
322
+ Target node. Optional. Default value: None.
323
+
324
+ flow_func : function
325
+ A function for computing the maximum flow among a pair of nodes.
326
+ The function has to accept at least three parameters: a Digraph,
327
+ a source node, and a target node. And return a residual network
328
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
329
+ details). If flow_func is None, the default maximum flow function
330
+ (:meth:`edmonds_karp`) is used. See below for details. The
331
+ choice of the default function may change from version
332
+ to version and should not be relied on. Default value: None.
333
+
334
+ Returns
335
+ -------
336
+ cutset : set
337
+ Set of nodes that, if removed, would disconnect G. If source
338
+ and target nodes are provided, the set contains the nodes that
339
+ if removed, would destroy all paths between source and target.
340
+
341
+ Examples
342
+ --------
343
+ >>> # Platonic icosahedral graph has node connectivity 5
344
+ >>> G = nx.icosahedral_graph()
345
+ >>> node_cut = nx.minimum_node_cut(G)
346
+ >>> len(node_cut)
347
+ 5
348
+
349
+ You can use alternative flow algorithms for the underlying maximum
350
+ flow computation. In dense networks the algorithm
351
+ :meth:`shortest_augmenting_path` will usually perform better
352
+ than the default :meth:`edmonds_karp`, which is faster for
353
+ sparse networks with highly skewed degree distributions. Alternative
354
+ flow functions have to be explicitly imported from the flow package.
355
+
356
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
357
+ >>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path)
358
+ True
359
+
360
+ If you specify a pair of nodes (source and target) as parameters,
361
+ this function returns a local st node cut.
362
+
363
+ >>> len(nx.minimum_node_cut(G, 3, 7))
364
+ 5
365
+
366
+ If you need to perform several local st cuts among different
367
+ pairs of nodes on the same graph, it is recommended that you reuse
368
+ the data structures used in the maximum flow computations. See
369
+ :meth:`minimum_st_node_cut` for details.
370
+
371
+ Notes
372
+ -----
373
+ This is a flow based implementation of minimum node cut. The algorithm
374
+ is based in solving a number of maximum flow computations to determine
375
+ the capacity of the minimum cut on an auxiliary directed network that
376
+ corresponds to the minimum node cut of G. It handles both directed
377
+ and undirected graphs. This implementation is based on algorithm 11
378
+ in [1]_.
379
+
380
+ See also
381
+ --------
382
+ :meth:`minimum_st_node_cut`
383
+ :meth:`minimum_cut`
384
+ :meth:`minimum_edge_cut`
385
+ :meth:`stoer_wagner`
386
+ :meth:`node_connectivity`
387
+ :meth:`edge_connectivity`
388
+ :meth:`maximum_flow`
389
+ :meth:`edmonds_karp`
390
+ :meth:`preflow_push`
391
+ :meth:`shortest_augmenting_path`
392
+
393
+ References
394
+ ----------
395
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
396
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
397
+
398
+ """
399
+ if (s is not None and t is None) or (s is None and t is not None):
400
+ raise nx.NetworkXError("Both source and target must be specified.")
401
+
402
+ # Local minimum node cut.
403
+ if s is not None and t is not None:
404
+ if s not in G:
405
+ raise nx.NetworkXError(f"node {s} not in graph")
406
+ if t not in G:
407
+ raise nx.NetworkXError(f"node {t} not in graph")
408
+ return minimum_st_node_cut(G, s, t, flow_func=flow_func)
409
+
410
+ # Global minimum node cut.
411
+ # Analog to the algorithm 11 for global node connectivity in [1].
412
+ if G.is_directed():
413
+ if not nx.is_weakly_connected(G):
414
+ raise nx.NetworkXError("Input graph is not connected")
415
+ iter_func = itertools.permutations
416
+
417
+ def neighbors(v):
418
+ return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
419
+
420
+ else:
421
+ if not nx.is_connected(G):
422
+ raise nx.NetworkXError("Input graph is not connected")
423
+ iter_func = itertools.combinations
424
+ neighbors = G.neighbors
425
+
426
+ # Reuse the auxiliary digraph and the residual network.
427
+ H = build_auxiliary_node_connectivity(G)
428
+ R = build_residual_network(H, "capacity")
429
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
430
+
431
+ # Choose a node with minimum degree.
432
+ v = min(G, key=G.degree)
433
+ # Initial node cutset is all neighbors of the node with minimum degree.
434
+ min_cut = set(G[v])
435
+ # Compute st node cuts between v and all its non-neighbors nodes in G.
436
+ for w in set(G) - set(neighbors(v)) - {v}:
437
+ this_cut = minimum_st_node_cut(G, v, w, **kwargs)
438
+ if len(min_cut) >= len(this_cut):
439
+ min_cut = this_cut
440
+ # Also for non adjacent pairs of neighbors of v.
441
+ for x, y in iter_func(neighbors(v), 2):
442
+ if y in G[x]:
443
+ continue
444
+ this_cut = minimum_st_node_cut(G, x, y, **kwargs)
445
+ if len(min_cut) >= len(this_cut):
446
+ min_cut = this_cut
447
+
448
+ return min_cut
449
+
450
+
451
+ @nx._dispatchable
452
+ def minimum_edge_cut(G, s=None, t=None, flow_func=None):
453
+ r"""Returns a set of edges of minimum cardinality that disconnects G.
454
+
455
+ If source and target nodes are provided, this function returns the
456
+ set of edges of minimum cardinality that, if removed, would break
457
+ all paths among source and target in G. If not, it returns a set of
458
+ edges of minimum cardinality that disconnects G.
459
+
460
+ Parameters
461
+ ----------
462
+ G : NetworkX graph
463
+
464
+ s : node
465
+ Source node. Optional. Default value: None.
466
+
467
+ t : node
468
+ Target node. Optional. Default value: None.
469
+
470
+ flow_func : function
471
+ A function for computing the maximum flow among a pair of nodes.
472
+ The function has to accept at least three parameters: a Digraph,
473
+ a source node, and a target node. And return a residual network
474
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
475
+ details). If flow_func is None, the default maximum flow function
476
+ (:meth:`edmonds_karp`) is used. See below for details. The
477
+ choice of the default function may change from version
478
+ to version and should not be relied on. Default value: None.
479
+
480
+ Returns
481
+ -------
482
+ cutset : set
483
+ Set of edges that, if removed, would disconnect G. If source
484
+ and target nodes are provided, the set contains the edges that
485
+ if removed, would destroy all paths between source and target.
486
+
487
+ Examples
488
+ --------
489
+ >>> # Platonic icosahedral graph has edge connectivity 5
490
+ >>> G = nx.icosahedral_graph()
491
+ >>> len(nx.minimum_edge_cut(G))
492
+ 5
493
+
494
+ You can use alternative flow algorithms for the underlying
495
+ maximum flow computation. In dense networks the algorithm
496
+ :meth:`shortest_augmenting_path` will usually perform better
497
+ than the default :meth:`edmonds_karp`, which is faster for
498
+ sparse networks with highly skewed degree distributions.
499
+ Alternative flow functions have to be explicitly imported
500
+ from the flow package.
501
+
502
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
503
+ >>> len(nx.minimum_edge_cut(G, flow_func=shortest_augmenting_path))
504
+ 5
505
+
506
+ If you specify a pair of nodes (source and target) as parameters,
507
+ this function returns the value of local edge connectivity.
508
+
509
+ >>> nx.edge_connectivity(G, 3, 7)
510
+ 5
511
+
512
+ If you need to perform several local computations among different
513
+ pairs of nodes on the same graph, it is recommended that you reuse
514
+ the data structures used in the maximum flow computations. See
515
+ :meth:`local_edge_connectivity` for details.
516
+
517
+ Notes
518
+ -----
519
+ This is a flow based implementation of minimum edge cut. For
520
+ undirected graphs the algorithm works by finding a 'small' dominating
521
+ set of nodes of G (see algorithm 7 in [1]_) and computing the maximum
522
+ flow between an arbitrary node in the dominating set and the rest of
523
+ nodes in it. This is an implementation of algorithm 6 in [1]_. For
524
+ directed graphs, the algorithm does n calls to the max flow function.
525
+ The function raises an error if the directed graph is not weakly
526
+ connected and returns an empty set if it is weakly connected.
527
+ It is an implementation of algorithm 8 in [1]_.
528
+
529
+ See also
530
+ --------
531
+ :meth:`minimum_st_edge_cut`
532
+ :meth:`minimum_node_cut`
533
+ :meth:`stoer_wagner`
534
+ :meth:`node_connectivity`
535
+ :meth:`edge_connectivity`
536
+ :meth:`maximum_flow`
537
+ :meth:`edmonds_karp`
538
+ :meth:`preflow_push`
539
+ :meth:`shortest_augmenting_path`
540
+
541
+ References
542
+ ----------
543
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
544
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
545
+
546
+ """
547
+ if (s is not None and t is None) or (s is None and t is not None):
548
+ raise nx.NetworkXError("Both source and target must be specified.")
549
+
550
+ # reuse auxiliary digraph and residual network
551
+ H = build_auxiliary_edge_connectivity(G)
552
+ R = build_residual_network(H, "capacity")
553
+ kwargs = {"flow_func": flow_func, "residual": R, "auxiliary": H}
554
+
555
+ # Local minimum edge cut if s and t are not None
556
+ if s is not None and t is not None:
557
+ if s not in G:
558
+ raise nx.NetworkXError(f"node {s} not in graph")
559
+ if t not in G:
560
+ raise nx.NetworkXError(f"node {t} not in graph")
561
+ return minimum_st_edge_cut(H, s, t, **kwargs)
562
+
563
+ # Global minimum edge cut
564
+ # Analog to the algorithm for global edge connectivity
565
+ if G.is_directed():
566
+ # Based on algorithm 8 in [1]
567
+ if not nx.is_weakly_connected(G):
568
+ raise nx.NetworkXError("Input graph is not connected")
569
+
570
+ # Initial cutset is all edges of a node with minimum degree
571
+ node = min(G, key=G.degree)
572
+ min_cut = set(G.edges(node))
573
+ nodes = list(G)
574
+ n = len(nodes)
575
+ for i in range(n):
576
+ try:
577
+ this_cut = minimum_st_edge_cut(H, nodes[i], nodes[i + 1], **kwargs)
578
+ if len(this_cut) <= len(min_cut):
579
+ min_cut = this_cut
580
+ except IndexError: # Last node!
581
+ this_cut = minimum_st_edge_cut(H, nodes[i], nodes[0], **kwargs)
582
+ if len(this_cut) <= len(min_cut):
583
+ min_cut = this_cut
584
+
585
+ return min_cut
586
+
587
+ else: # undirected
588
+ # Based on algorithm 6 in [1]
589
+ if not nx.is_connected(G):
590
+ raise nx.NetworkXError("Input graph is not connected")
591
+
592
+ # Initial cutset is all edges of a node with minimum degree
593
+ node = min(G, key=G.degree)
594
+ min_cut = set(G.edges(node))
595
+ # A dominating set is \lambda-covering
596
+ # We need a dominating set with at least two nodes
597
+ for node in G:
598
+ D = nx.dominating_set(G, start_with=node)
599
+ v = D.pop()
600
+ if D:
601
+ break
602
+ else:
603
+ # in complete graphs the dominating set will always be of one node
604
+ # thus we return min_cut, which now contains the edges of a node
605
+ # with minimum degree
606
+ return min_cut
607
+ for w in D:
608
+ this_cut = minimum_st_edge_cut(H, v, w, **kwargs)
609
+ if len(this_cut) <= len(min_cut):
610
+ min_cut = this_cut
611
+
612
+ return min_cut
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_augmentation.py ADDED
@@ -0,0 +1,1270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Algorithms for finding k-edge-augmentations
3
+
4
+ A k-edge-augmentation is a set of edges, that once added to a graph, ensures
5
+ that the graph is k-edge-connected; i.e. the graph cannot be disconnected
6
+ unless k or more edges are removed. Typically, the goal is to find the
7
+ augmentation with minimum weight. In general, it is not guaranteed that a
8
+ k-edge-augmentation exists.
9
+
10
+ See Also
11
+ --------
12
+ :mod:`edge_kcomponents` : algorithms for finding k-edge-connected components
13
+ :mod:`connectivity` : algorithms for determining edge connectivity.
14
+ """
15
+
16
+ import itertools as it
17
+ import math
18
+ from collections import defaultdict, namedtuple
19
+
20
+ import networkx as nx
21
+ from networkx.utils import not_implemented_for, py_random_state
22
+
23
+ __all__ = ["k_edge_augmentation", "is_k_edge_connected", "is_locally_k_edge_connected"]
24
+
25
+
26
+ @not_implemented_for("directed")
27
+ @not_implemented_for("multigraph")
28
+ @nx._dispatchable
29
+ def is_k_edge_connected(G, k):
30
+ """Tests to see if a graph is k-edge-connected.
31
+
32
+ Is it impossible to disconnect the graph by removing fewer than k edges?
33
+ If so, then G is k-edge-connected.
34
+
35
+ Parameters
36
+ ----------
37
+ G : NetworkX graph
38
+ An undirected graph.
39
+
40
+ k : integer
41
+ edge connectivity to test for
42
+
43
+ Returns
44
+ -------
45
+ boolean
46
+ True if G is k-edge-connected.
47
+
48
+ See Also
49
+ --------
50
+ :func:`is_locally_k_edge_connected`
51
+
52
+ Examples
53
+ --------
54
+ >>> G = nx.barbell_graph(10, 0)
55
+ >>> nx.is_k_edge_connected(G, k=1)
56
+ True
57
+ >>> nx.is_k_edge_connected(G, k=2)
58
+ False
59
+ """
60
+ if k < 1:
61
+ raise ValueError(f"k must be positive, not {k}")
62
+ # First try to quickly determine if G is not k-edge-connected
63
+ if G.number_of_nodes() < k + 1:
64
+ return False
65
+ elif any(d < k for n, d in G.degree()):
66
+ return False
67
+ else:
68
+ # Otherwise perform the full check
69
+ if k == 1:
70
+ return nx.is_connected(G)
71
+ elif k == 2:
72
+ return nx.is_connected(G) and not nx.has_bridges(G)
73
+ else:
74
+ return nx.edge_connectivity(G, cutoff=k) >= k
75
+
76
+
77
+ @not_implemented_for("directed")
78
+ @not_implemented_for("multigraph")
79
+ @nx._dispatchable
80
+ def is_locally_k_edge_connected(G, s, t, k):
81
+ """Tests to see if an edge in a graph is locally k-edge-connected.
82
+
83
+ Is it impossible to disconnect s and t by removing fewer than k edges?
84
+ If so, then s and t are locally k-edge-connected in G.
85
+
86
+ Parameters
87
+ ----------
88
+ G : NetworkX graph
89
+ An undirected graph.
90
+
91
+ s : node
92
+ Source node
93
+
94
+ t : node
95
+ Target node
96
+
97
+ k : integer
98
+ local edge connectivity for nodes s and t
99
+
100
+ Returns
101
+ -------
102
+ boolean
103
+ True if s and t are locally k-edge-connected in G.
104
+
105
+ See Also
106
+ --------
107
+ :func:`is_k_edge_connected`
108
+
109
+ Examples
110
+ --------
111
+ >>> from networkx.algorithms.connectivity import is_locally_k_edge_connected
112
+ >>> G = nx.barbell_graph(10, 0)
113
+ >>> is_locally_k_edge_connected(G, 5, 15, k=1)
114
+ True
115
+ >>> is_locally_k_edge_connected(G, 5, 15, k=2)
116
+ False
117
+ >>> is_locally_k_edge_connected(G, 1, 5, k=2)
118
+ True
119
+ """
120
+ if k < 1:
121
+ raise ValueError(f"k must be positive, not {k}")
122
+
123
+ # First try to quickly determine s, t is not k-locally-edge-connected in G
124
+ if G.degree(s) < k or G.degree(t) < k:
125
+ return False
126
+ else:
127
+ # Otherwise perform the full check
128
+ if k == 1:
129
+ return nx.has_path(G, s, t)
130
+ else:
131
+ localk = nx.connectivity.local_edge_connectivity(G, s, t, cutoff=k)
132
+ return localk >= k
133
+
134
+
135
+ @not_implemented_for("directed")
136
+ @not_implemented_for("multigraph")
137
+ @nx._dispatchable
138
+ def k_edge_augmentation(G, k, avail=None, weight=None, partial=False):
139
+ """Finds set of edges to k-edge-connect G.
140
+
141
+ Adding edges from the augmentation to G make it impossible to disconnect G
142
+ unless k or more edges are removed. This function uses the most efficient
143
+ function available (depending on the value of k and if the problem is
144
+ weighted or unweighted) to search for a minimum weight subset of available
145
+ edges that k-edge-connects G. In general, finding a k-edge-augmentation is
146
+ NP-hard, so solutions are not guaranteed to be minimal. Furthermore, a
147
+ k-edge-augmentation may not exist.
148
+
149
+ Parameters
150
+ ----------
151
+ G : NetworkX graph
152
+ An undirected graph.
153
+
154
+ k : integer
155
+ Desired edge connectivity
156
+
157
+ avail : dict or a set of 2 or 3 tuples
158
+ The available edges that can be used in the augmentation.
159
+
160
+ If unspecified, then all edges in the complement of G are available.
161
+ Otherwise, each item is an available edge (with an optional weight).
162
+
163
+ In the unweighted case, each item is an edge ``(u, v)``.
164
+
165
+ In the weighted case, each item is a 3-tuple ``(u, v, d)`` or a dict
166
+ with items ``(u, v): d``. The third item, ``d``, can be a dictionary
167
+ or a real number. If ``d`` is a dictionary ``d[weight]``
168
+ correspondings to the weight.
169
+
170
+ weight : string
171
+ key to use to find weights if ``avail`` is a set of 3-tuples where the
172
+ third item in each tuple is a dictionary.
173
+
174
+ partial : boolean
175
+ If partial is True and no feasible k-edge-augmentation exists, then all
176
+ a partial k-edge-augmentation is generated. Adding the edges in a
177
+ partial augmentation to G, minimizes the number of k-edge-connected
178
+ components and maximizes the edge connectivity between those
179
+ components. For details, see :func:`partial_k_edge_augmentation`.
180
+
181
+ Yields
182
+ ------
183
+ edge : tuple
184
+ Edges that, once added to G, would cause G to become k-edge-connected.
185
+ If partial is False, an error is raised if this is not possible.
186
+ Otherwise, generated edges form a partial augmentation, which
187
+ k-edge-connects any part of G where it is possible, and maximally
188
+ connects the remaining parts.
189
+
190
+ Raises
191
+ ------
192
+ NetworkXUnfeasible
193
+ If partial is False and no k-edge-augmentation exists.
194
+
195
+ NetworkXNotImplemented
196
+ If the input graph is directed or a multigraph.
197
+
198
+ ValueError:
199
+ If k is less than 1
200
+
201
+ Notes
202
+ -----
203
+ When k=1 this returns an optimal solution.
204
+
205
+ When k=2 and ``avail`` is None, this returns an optimal solution.
206
+ Otherwise when k=2, this returns a 2-approximation of the optimal solution.
207
+
208
+ For k>3, this problem is NP-hard and this uses a randomized algorithm that
209
+ produces a feasible solution, but provides no guarantees on the
210
+ solution weight.
211
+
212
+ Examples
213
+ --------
214
+ >>> # Unweighted cases
215
+ >>> G = nx.path_graph((1, 2, 3, 4))
216
+ >>> G.add_node(5)
217
+ >>> sorted(nx.k_edge_augmentation(G, k=1))
218
+ [(1, 5)]
219
+ >>> sorted(nx.k_edge_augmentation(G, k=2))
220
+ [(1, 5), (5, 4)]
221
+ >>> sorted(nx.k_edge_augmentation(G, k=3))
222
+ [(1, 4), (1, 5), (2, 5), (3, 5), (4, 5)]
223
+ >>> complement = list(nx.k_edge_augmentation(G, k=5, partial=True))
224
+ >>> G.add_edges_from(complement)
225
+ >>> nx.edge_connectivity(G)
226
+ 4
227
+
228
+ >>> # Weighted cases
229
+ >>> G = nx.path_graph((1, 2, 3, 4))
230
+ >>> G.add_node(5)
231
+ >>> # avail can be a tuple with a dict
232
+ >>> avail = [(1, 5, {"weight": 11}), (2, 5, {"weight": 10})]
233
+ >>> sorted(nx.k_edge_augmentation(G, k=1, avail=avail, weight="weight"))
234
+ [(2, 5)]
235
+ >>> # or avail can be a 3-tuple with a real number
236
+ >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
237
+ >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
238
+ [(1, 5), (2, 5), (4, 5)]
239
+ >>> # or avail can be a dict
240
+ >>> avail = {(1, 5): 11, (2, 5): 10, (4, 3): 1, (4, 5): 51}
241
+ >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
242
+ [(1, 5), (2, 5), (4, 5)]
243
+ >>> # If augmentation is infeasible, then a partial solution can be found
244
+ >>> avail = {(1, 5): 11}
245
+ >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail, partial=True))
246
+ [(1, 5)]
247
+ """
248
+ try:
249
+ if k <= 0:
250
+ raise ValueError(f"k must be a positive integer, not {k}")
251
+ elif G.number_of_nodes() < k + 1:
252
+ msg = f"impossible to {k} connect in graph with less than {k + 1} nodes"
253
+ raise nx.NetworkXUnfeasible(msg)
254
+ elif avail is not None and len(avail) == 0:
255
+ if not nx.is_k_edge_connected(G, k):
256
+ raise nx.NetworkXUnfeasible("no available edges")
257
+ aug_edges = []
258
+ elif k == 1:
259
+ aug_edges = one_edge_augmentation(
260
+ G, avail=avail, weight=weight, partial=partial
261
+ )
262
+ elif k == 2:
263
+ aug_edges = bridge_augmentation(G, avail=avail, weight=weight)
264
+ else:
265
+ # raise NotImplementedError(f'not implemented for k>2. k={k}')
266
+ aug_edges = greedy_k_edge_augmentation(
267
+ G, k=k, avail=avail, weight=weight, seed=0
268
+ )
269
+ # Do eager evaluation so we can catch any exceptions
270
+ # Before executing partial code.
271
+ yield from list(aug_edges)
272
+ except nx.NetworkXUnfeasible:
273
+ if partial:
274
+ # Return all available edges
275
+ if avail is None:
276
+ aug_edges = complement_edges(G)
277
+ else:
278
+ # If we can't k-edge-connect the entire graph, try to
279
+ # k-edge-connect as much as possible
280
+ aug_edges = partial_k_edge_augmentation(
281
+ G, k=k, avail=avail, weight=weight
282
+ )
283
+ yield from aug_edges
284
+ else:
285
+ raise
286
+
287
+
288
+ @nx._dispatchable
289
+ def partial_k_edge_augmentation(G, k, avail, weight=None):
290
+ """Finds augmentation that k-edge-connects as much of the graph as possible.
291
+
292
+ When a k-edge-augmentation is not possible, we can still try to find a
293
+ small set of edges that partially k-edge-connects as much of the graph as
294
+ possible. All possible edges are generated between remaining parts.
295
+ This minimizes the number of k-edge-connected subgraphs in the resulting
296
+ graph and maximizes the edge connectivity between those subgraphs.
297
+
298
+ Parameters
299
+ ----------
300
+ G : NetworkX graph
301
+ An undirected graph.
302
+
303
+ k : integer
304
+ Desired edge connectivity
305
+
306
+ avail : dict or a set of 2 or 3 tuples
307
+ For more details, see :func:`k_edge_augmentation`.
308
+
309
+ weight : string
310
+ key to use to find weights if ``avail`` is a set of 3-tuples.
311
+ For more details, see :func:`k_edge_augmentation`.
312
+
313
+ Yields
314
+ ------
315
+ edge : tuple
316
+ Edges in the partial augmentation of G. These edges k-edge-connect any
317
+ part of G where it is possible, and maximally connects the remaining
318
+ parts. In other words, all edges from avail are generated except for
319
+ those within subgraphs that have already become k-edge-connected.
320
+
321
+ Notes
322
+ -----
323
+ Construct H that augments G with all edges in avail.
324
+ Find the k-edge-subgraphs of H.
325
+ For each k-edge-subgraph, if the number of nodes is more than k, then find
326
+ the k-edge-augmentation of that graph and add it to the solution. Then add
327
+ all edges in avail between k-edge subgraphs to the solution.
328
+
329
+ See Also
330
+ --------
331
+ :func:`k_edge_augmentation`
332
+
333
+ Examples
334
+ --------
335
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
336
+ >>> G.add_node(8)
337
+ >>> avail = [(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5), (1, 8)]
338
+ >>> sorted(partial_k_edge_augmentation(G, k=2, avail=avail))
339
+ [(1, 5), (1, 8)]
340
+ """
341
+
342
+ def _edges_between_disjoint(H, only1, only2):
343
+ """finds edges between disjoint nodes"""
344
+ only1_adj = {u: set(H.adj[u]) for u in only1}
345
+ for u, neighbs in only1_adj.items():
346
+ # Find the neighbors of u in only1 that are also in only2
347
+ neighbs12 = neighbs.intersection(only2)
348
+ for v in neighbs12:
349
+ yield (u, v)
350
+
351
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
352
+
353
+ # Find which parts of the graph can be k-edge-connected
354
+ H = G.copy()
355
+ H.add_edges_from(
356
+ (
357
+ (u, v, {"weight": w, "generator": (u, v)})
358
+ for (u, v), w in zip(avail, avail_w)
359
+ )
360
+ )
361
+ k_edge_subgraphs = list(nx.k_edge_subgraphs(H, k=k))
362
+
363
+ # Generate edges to k-edge-connect internal subgraphs
364
+ for nodes in k_edge_subgraphs:
365
+ if len(nodes) > 1:
366
+ # Get the k-edge-connected subgraph
367
+ C = H.subgraph(nodes).copy()
368
+ # Find the internal edges that were available
369
+ sub_avail = {
370
+ d["generator"]: d["weight"]
371
+ for (u, v, d) in C.edges(data=True)
372
+ if "generator" in d
373
+ }
374
+ # Remove potential augmenting edges
375
+ C.remove_edges_from(sub_avail.keys())
376
+ # Find a subset of these edges that makes the component
377
+ # k-edge-connected and ignore the rest
378
+ yield from nx.k_edge_augmentation(C, k=k, avail=sub_avail)
379
+
380
+ # Generate all edges between CCs that could not be k-edge-connected
381
+ for cc1, cc2 in it.combinations(k_edge_subgraphs, 2):
382
+ for u, v in _edges_between_disjoint(H, cc1, cc2):
383
+ d = H.get_edge_data(u, v)
384
+ edge = d.get("generator", None)
385
+ if edge is not None:
386
+ yield edge
387
+
388
+
389
+ @not_implemented_for("multigraph")
390
+ @not_implemented_for("directed")
391
+ @nx._dispatchable
392
+ def one_edge_augmentation(G, avail=None, weight=None, partial=False):
393
+ """Finds minimum weight set of edges to connect G.
394
+
395
+ Equivalent to :func:`k_edge_augmentation` when k=1. Adding the resulting
396
+ edges to G will make it 1-edge-connected. The solution is optimal for both
397
+ weighted and non-weighted variants.
398
+
399
+ Parameters
400
+ ----------
401
+ G : NetworkX graph
402
+ An undirected graph.
403
+
404
+ avail : dict or a set of 2 or 3 tuples
405
+ For more details, see :func:`k_edge_augmentation`.
406
+
407
+ weight : string
408
+ key to use to find weights if ``avail`` is a set of 3-tuples.
409
+ For more details, see :func:`k_edge_augmentation`.
410
+
411
+ partial : boolean
412
+ If partial is True and no feasible k-edge-augmentation exists, then the
413
+ augmenting edges minimize the number of connected components.
414
+
415
+ Yields
416
+ ------
417
+ edge : tuple
418
+ Edges in the one-augmentation of G
419
+
420
+ Raises
421
+ ------
422
+ NetworkXUnfeasible
423
+ If partial is False and no one-edge-augmentation exists.
424
+
425
+ Notes
426
+ -----
427
+ Uses either :func:`unconstrained_one_edge_augmentation` or
428
+ :func:`weighted_one_edge_augmentation` depending on whether ``avail`` is
429
+ specified. Both algorithms are based on finding a minimum spanning tree.
430
+ As such both algorithms find optimal solutions and run in linear time.
431
+
432
+ See Also
433
+ --------
434
+ :func:`k_edge_augmentation`
435
+ """
436
+ if avail is None:
437
+ return unconstrained_one_edge_augmentation(G)
438
+ else:
439
+ return weighted_one_edge_augmentation(
440
+ G, avail=avail, weight=weight, partial=partial
441
+ )
442
+
443
+
444
+ @not_implemented_for("multigraph")
445
+ @not_implemented_for("directed")
446
+ @nx._dispatchable
447
+ def bridge_augmentation(G, avail=None, weight=None):
448
+ """Finds the a set of edges that bridge connects G.
449
+
450
+ Equivalent to :func:`k_edge_augmentation` when k=2, and partial=False.
451
+ Adding the resulting edges to G will make it 2-edge-connected. If no
452
+ constraints are specified the returned set of edges is minimum an optimal,
453
+ otherwise the solution is approximated.
454
+
455
+ Parameters
456
+ ----------
457
+ G : NetworkX graph
458
+ An undirected graph.
459
+
460
+ avail : dict or a set of 2 or 3 tuples
461
+ For more details, see :func:`k_edge_augmentation`.
462
+
463
+ weight : string
464
+ key to use to find weights if ``avail`` is a set of 3-tuples.
465
+ For more details, see :func:`k_edge_augmentation`.
466
+
467
+ Yields
468
+ ------
469
+ edge : tuple
470
+ Edges in the bridge-augmentation of G
471
+
472
+ Raises
473
+ ------
474
+ NetworkXUnfeasible
475
+ If no bridge-augmentation exists.
476
+
477
+ Notes
478
+ -----
479
+ If there are no constraints the solution can be computed in linear time
480
+ using :func:`unconstrained_bridge_augmentation`. Otherwise, the problem
481
+ becomes NP-hard and is the solution is approximated by
482
+ :func:`weighted_bridge_augmentation`.
483
+
484
+ See Also
485
+ --------
486
+ :func:`k_edge_augmentation`
487
+ """
488
+ if G.number_of_nodes() < 3:
489
+ raise nx.NetworkXUnfeasible("impossible to bridge connect less than 3 nodes")
490
+ if avail is None:
491
+ return unconstrained_bridge_augmentation(G)
492
+ else:
493
+ return weighted_bridge_augmentation(G, avail, weight=weight)
494
+
495
+
496
+ # --- Algorithms and Helpers ---
497
+
498
+
499
+ def _ordered(u, v):
500
+ """Returns the nodes in an undirected edge in lower-triangular order"""
501
+ return (u, v) if u < v else (v, u)
502
+
503
+
504
+ def _unpack_available_edges(avail, weight=None, G=None):
505
+ """Helper to separate avail into edges and corresponding weights"""
506
+ if weight is None:
507
+ weight = "weight"
508
+ if isinstance(avail, dict):
509
+ avail_uv = list(avail.keys())
510
+ avail_w = list(avail.values())
511
+ else:
512
+
513
+ def _try_getitem(d):
514
+ try:
515
+ return d[weight]
516
+ except TypeError:
517
+ return d
518
+
519
+ avail_uv = [tup[0:2] for tup in avail]
520
+ avail_w = [1 if len(tup) == 2 else _try_getitem(tup[-1]) for tup in avail]
521
+
522
+ if G is not None:
523
+ # Edges already in the graph are filtered
524
+ flags = [not G.has_edge(u, v) for u, v in avail_uv]
525
+ avail_uv = list(it.compress(avail_uv, flags))
526
+ avail_w = list(it.compress(avail_w, flags))
527
+ return avail_uv, avail_w
528
+
529
+
530
+ MetaEdge = namedtuple("MetaEdge", ("meta_uv", "uv", "w"))
531
+
532
+
533
+ def _lightest_meta_edges(mapping, avail_uv, avail_w):
534
+ """Maps available edges in the original graph to edges in the metagraph.
535
+
536
+ Parameters
537
+ ----------
538
+ mapping : dict
539
+ mapping produced by :func:`collapse`, that maps each node in the
540
+ original graph to a node in the meta graph
541
+
542
+ avail_uv : list
543
+ list of edges
544
+
545
+ avail_w : list
546
+ list of edge weights
547
+
548
+ Notes
549
+ -----
550
+ Each node in the metagraph is a k-edge-connected component in the original
551
+ graph. We don't care about any edge within the same k-edge-connected
552
+ component, so we ignore self edges. We also are only interested in the
553
+ minimum weight edge bridging each k-edge-connected component so, we group
554
+ the edges by meta-edge and take the lightest in each group.
555
+
556
+ Examples
557
+ --------
558
+ >>> # Each group represents a meta-node
559
+ >>> groups = ([1, 2, 3], [4, 5], [6])
560
+ >>> mapping = {n: meta_n for meta_n, ns in enumerate(groups) for n in ns}
561
+ >>> avail_uv = [(1, 2), (3, 6), (1, 4), (5, 2), (6, 1), (2, 6), (3, 1)]
562
+ >>> avail_w = [20, 99, 20, 15, 50, 99, 20]
563
+ >>> sorted(_lightest_meta_edges(mapping, avail_uv, avail_w))
564
+ [MetaEdge(meta_uv=(0, 1), uv=(5, 2), w=15), MetaEdge(meta_uv=(0, 2), uv=(6, 1), w=50)]
565
+ """
566
+ grouped_wuv = defaultdict(list)
567
+ for w, (u, v) in zip(avail_w, avail_uv):
568
+ # Order the meta-edge so it can be used as a dict key
569
+ meta_uv = _ordered(mapping[u], mapping[v])
570
+ # Group each available edge using the meta-edge as a key
571
+ grouped_wuv[meta_uv].append((w, u, v))
572
+
573
+ # Now that all available edges are grouped, choose one per group
574
+ for (mu, mv), choices_wuv in grouped_wuv.items():
575
+ # Ignore available edges within the same meta-node
576
+ if mu != mv:
577
+ # Choose the lightest available edge belonging to each meta-edge
578
+ w, u, v = min(choices_wuv)
579
+ yield MetaEdge((mu, mv), (u, v), w)
580
+
581
+
582
+ @nx._dispatchable
583
+ def unconstrained_one_edge_augmentation(G):
584
+ """Finds the smallest set of edges to connect G.
585
+
586
+ This is a variant of the unweighted MST problem.
587
+ If G is not empty, a feasible solution always exists.
588
+
589
+ Parameters
590
+ ----------
591
+ G : NetworkX graph
592
+ An undirected graph.
593
+
594
+ Yields
595
+ ------
596
+ edge : tuple
597
+ Edges in the one-edge-augmentation of G
598
+
599
+ See Also
600
+ --------
601
+ :func:`one_edge_augmentation`
602
+ :func:`k_edge_augmentation`
603
+
604
+ Examples
605
+ --------
606
+ >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
607
+ >>> G.add_nodes_from([6, 7, 8])
608
+ >>> sorted(unconstrained_one_edge_augmentation(G))
609
+ [(1, 4), (4, 6), (6, 7), (7, 8)]
610
+ """
611
+ ccs1 = list(nx.connected_components(G))
612
+ C = collapse(G, ccs1)
613
+ # When we are not constrained, we can just make a meta graph tree.
614
+ meta_nodes = list(C.nodes())
615
+ # build a path in the metagraph
616
+ meta_aug = list(zip(meta_nodes, meta_nodes[1:]))
617
+ # map that path to the original graph
618
+ inverse = defaultdict(list)
619
+ for k, v in C.graph["mapping"].items():
620
+ inverse[v].append(k)
621
+ for mu, mv in meta_aug:
622
+ yield (inverse[mu][0], inverse[mv][0])
623
+
624
+
625
+ @nx._dispatchable
626
+ def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
627
+ """Finds the minimum weight set of edges to connect G if one exists.
628
+
629
+ This is a variant of the weighted MST problem.
630
+
631
+ Parameters
632
+ ----------
633
+ G : NetworkX graph
634
+ An undirected graph.
635
+
636
+ avail : dict or a set of 2 or 3 tuples
637
+ For more details, see :func:`k_edge_augmentation`.
638
+
639
+ weight : string
640
+ key to use to find weights if ``avail`` is a set of 3-tuples.
641
+ For more details, see :func:`k_edge_augmentation`.
642
+
643
+ partial : boolean
644
+ If partial is True and no feasible k-edge-augmentation exists, then the
645
+ augmenting edges minimize the number of connected components.
646
+
647
+ Yields
648
+ ------
649
+ edge : tuple
650
+ Edges in the subset of avail chosen to connect G.
651
+
652
+ See Also
653
+ --------
654
+ :func:`one_edge_augmentation`
655
+ :func:`k_edge_augmentation`
656
+
657
+ Examples
658
+ --------
659
+ >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
660
+ >>> G.add_nodes_from([6, 7, 8])
661
+ >>> # any edge not in avail has an implicit weight of infinity
662
+ >>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
663
+ >>> sorted(weighted_one_edge_augmentation(G, avail))
664
+ [(1, 5), (4, 7), (6, 1), (8, 1)]
665
+ >>> # find another solution by giving large weights to edges in the
666
+ >>> # previous solution (note some of the old edges must be used)
667
+ >>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
668
+ >>> sorted(weighted_one_edge_augmentation(G, avail))
669
+ [(1, 5), (4, 7), (6, 1), (8, 2)]
670
+ """
671
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
672
+ # Collapse CCs in the original graph into nodes in a metagraph
673
+ # Then find an MST of the metagraph instead of the original graph
674
+ C = collapse(G, nx.connected_components(G))
675
+ mapping = C.graph["mapping"]
676
+ # Assign each available edge to an edge in the metagraph
677
+ candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
678
+ # nx.set_edge_attributes(C, name='weight', values=0)
679
+ C.add_edges_from(
680
+ (mu, mv, {"weight": w, "generator": uv})
681
+ for (mu, mv), uv, w in candidate_mapping
682
+ )
683
+ # Find MST of the meta graph
684
+ meta_mst = nx.minimum_spanning_tree(C)
685
+ if not partial and not nx.is_connected(meta_mst):
686
+ raise nx.NetworkXUnfeasible("Not possible to connect G with available edges")
687
+ # Yield the edge that generated the meta-edge
688
+ for mu, mv, d in meta_mst.edges(data=True):
689
+ if "generator" in d:
690
+ edge = d["generator"]
691
+ yield edge
692
+
693
+
694
+ @nx._dispatchable
695
+ def unconstrained_bridge_augmentation(G):
696
+ """Finds an optimal 2-edge-augmentation of G using the fewest edges.
697
+
698
+ This is an implementation of the algorithm detailed in [1]_.
699
+ The basic idea is to construct a meta-graph of bridge-ccs, connect leaf
700
+ nodes of the trees to connect the entire graph, and finally connect the
701
+ leafs of the tree in dfs-preorder to bridge connect the entire graph.
702
+
703
+ Parameters
704
+ ----------
705
+ G : NetworkX graph
706
+ An undirected graph.
707
+
708
+ Yields
709
+ ------
710
+ edge : tuple
711
+ Edges in the bridge augmentation of G
712
+
713
+ Notes
714
+ -----
715
+ Input: a graph G.
716
+ First find the bridge components of G and collapse each bridge-cc into a
717
+ node of a metagraph graph C, which is guaranteed to be a forest of trees.
718
+
719
+ C contains p "leafs" --- nodes with exactly one incident edge.
720
+ C contains q "isolated nodes" --- nodes with no incident edges.
721
+
722
+ Theorem: If p + q > 1, then at least :math:`ceil(p / 2) + q` edges are
723
+ needed to bridge connect C. This algorithm achieves this min number.
724
+
725
+ The method first adds enough edges to make G into a tree and then pairs
726
+ leafs in a simple fashion.
727
+
728
+ Let n be the number of trees in C. Let v(i) be an isolated vertex in the
729
+ i-th tree if one exists, otherwise it is a pair of distinct leafs nodes
730
+ in the i-th tree. Alternating edges from these sets (i.e. adding edges
731
+ A1 = [(v(i)[0], v(i + 1)[1]), v(i + 1)[0], v(i + 2)[1])...]) connects C
732
+ into a tree T. This tree has p' = p + 2q - 2(n -1) leafs and no isolated
733
+ vertices. A1 has n - 1 edges. The next step finds ceil(p' / 2) edges to
734
+ biconnect any tree with p' leafs.
735
+
736
+ Convert T into an arborescence T' by picking an arbitrary root node with
737
+ degree >= 2 and directing all edges away from the root. Note the
738
+ implementation implicitly constructs T'.
739
+
740
+ The leafs of T are the nodes with no existing edges in T'.
741
+ Order the leafs of T' by DFS preorder. Then break this list in half
742
+ and add the zipped pairs to A2.
743
+
744
+ The set A = A1 + A2 is the minimum augmentation in the metagraph.
745
+
746
+ To convert this to edges in the original graph
747
+
748
+ References
749
+ ----------
750
+ .. [1] Eswaran, Kapali P., and R. Endre Tarjan. (1975) Augmentation problems.
751
+ http://epubs.siam.org/doi/abs/10.1137/0205044
752
+
753
+ See Also
754
+ --------
755
+ :func:`bridge_augmentation`
756
+ :func:`k_edge_augmentation`
757
+
758
+ Examples
759
+ --------
760
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
761
+ >>> sorted(unconstrained_bridge_augmentation(G))
762
+ [(1, 7)]
763
+ >>> G = nx.path_graph((1, 2, 3, 2, 4, 5, 6, 7))
764
+ >>> sorted(unconstrained_bridge_augmentation(G))
765
+ [(1, 3), (3, 7)]
766
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
767
+ >>> G.add_node(4)
768
+ >>> sorted(unconstrained_bridge_augmentation(G))
769
+ [(1, 4), (4, 0)]
770
+ """
771
+ # -----
772
+ # Mapping of terms from (Eswaran and Tarjan):
773
+ # G = G_0 - the input graph
774
+ # C = G_0' - the bridge condensation of G. (This is a forest of trees)
775
+ # A1 = A_1 - the edges to connect the forest into a tree
776
+ # leaf = pendant - a node with degree of 1
777
+
778
+ # alpha(v) = maps the node v in G to its meta-node in C
779
+ # beta(x) = maps the meta-node x in C to any node in the bridge
780
+ # component of G corresponding to x.
781
+
782
+ # find the 2-edge-connected components of G
783
+ bridge_ccs = list(nx.connectivity.bridge_components(G))
784
+ # condense G into an forest C
785
+ C = collapse(G, bridge_ccs)
786
+
787
+ # Choose pairs of distinct leaf nodes in each tree. If this is not
788
+ # possible then make a pair using the single isolated node in the tree.
789
+ vset1 = [
790
+ tuple(cc) * 2 # case1: an isolated node
791
+ if len(cc) == 1
792
+ else sorted(cc, key=C.degree)[0:2] # case2: pair of leaf nodes
793
+ for cc in nx.connected_components(C)
794
+ ]
795
+ if len(vset1) > 1:
796
+ # Use this set to construct edges that connect C into a tree.
797
+ nodes1 = [vs[0] for vs in vset1]
798
+ nodes2 = [vs[1] for vs in vset1]
799
+ A1 = list(zip(nodes1[1:], nodes2))
800
+ else:
801
+ A1 = []
802
+ # Connect each tree in the forest to construct an arborescence
803
+ T = C.copy()
804
+ T.add_edges_from(A1)
805
+
806
+ # If there are only two leaf nodes, we simply connect them.
807
+ leafs = [n for n, d in T.degree() if d == 1]
808
+ if len(leafs) == 1:
809
+ A2 = []
810
+ if len(leafs) == 2:
811
+ A2 = [tuple(leafs)]
812
+ else:
813
+ # Choose an arbitrary non-leaf root
814
+ try:
815
+ root = next(n for n, d in T.degree() if d > 1)
816
+ except StopIteration: # no nodes found with degree > 1
817
+ return
818
+ # order the leaves of C by (induced directed) preorder
819
+ v2 = [n for n in nx.dfs_preorder_nodes(T, root) if T.degree(n) == 1]
820
+ # connecting first half of the leafs in pre-order to the second
821
+ # half will bridge connect the tree with the fewest edges.
822
+ half = math.ceil(len(v2) / 2)
823
+ A2 = list(zip(v2[:half], v2[-half:]))
824
+
825
+ # collect the edges used to augment the original forest
826
+ aug_tree_edges = A1 + A2
827
+
828
+ # Construct the mapping (beta) from meta-nodes to regular nodes
829
+ inverse = defaultdict(list)
830
+ for k, v in C.graph["mapping"].items():
831
+ inverse[v].append(k)
832
+ # sort so we choose minimum degree nodes first
833
+ inverse = {
834
+ mu: sorted(mapped, key=lambda u: (G.degree(u), u))
835
+ for mu, mapped in inverse.items()
836
+ }
837
+
838
+ # For each meta-edge, map back to an arbitrary pair in the original graph
839
+ G2 = G.copy()
840
+ for mu, mv in aug_tree_edges:
841
+ # Find the first available edge that doesn't exist and return it
842
+ for u, v in it.product(inverse[mu], inverse[mv]):
843
+ if not G2.has_edge(u, v):
844
+ G2.add_edge(u, v)
845
+ yield u, v
846
+ break
847
+
848
+
849
+ @nx._dispatchable
850
+ def weighted_bridge_augmentation(G, avail, weight=None):
851
+ """Finds an approximate min-weight 2-edge-augmentation of G.
852
+
853
+ This is an implementation of the approximation algorithm detailed in [1]_.
854
+ It chooses a set of edges from avail to add to G that renders it
855
+ 2-edge-connected if such a subset exists. This is done by finding a
856
+ minimum spanning arborescence of a specially constructed metagraph.
857
+
858
+ Parameters
859
+ ----------
860
+ G : NetworkX graph
861
+ An undirected graph.
862
+
863
+ avail : set of 2 or 3 tuples.
864
+ candidate edges (with optional weights) to choose from
865
+
866
+ weight : string
867
+ key to use to find weights if avail is a set of 3-tuples where the
868
+ third item in each tuple is a dictionary.
869
+
870
+ Yields
871
+ ------
872
+ edge : tuple
873
+ Edges in the subset of avail chosen to bridge augment G.
874
+
875
+ Notes
876
+ -----
877
+ Finding a weighted 2-edge-augmentation is NP-hard.
878
+ Any edge not in ``avail`` is considered to have a weight of infinity.
879
+ The approximation factor is 2 if ``G`` is connected and 3 if it is not.
880
+ Runs in :math:`O(m + n log(n))` time
881
+
882
+ References
883
+ ----------
884
+ .. [1] Khuller, Samir, and Ramakrishna Thurimella. (1993) Approximation
885
+ algorithms for graph augmentation.
886
+ http://www.sciencedirect.com/science/article/pii/S0196677483710102
887
+
888
+ See Also
889
+ --------
890
+ :func:`bridge_augmentation`
891
+ :func:`k_edge_augmentation`
892
+
893
+ Examples
894
+ --------
895
+ >>> G = nx.path_graph((1, 2, 3, 4))
896
+ >>> # When the weights are equal, (1, 4) is the best
897
+ >>> avail = [(1, 4, 1), (1, 3, 1), (2, 4, 1)]
898
+ >>> sorted(weighted_bridge_augmentation(G, avail))
899
+ [(1, 4)]
900
+ >>> # Giving (1, 4) a high weight makes the two edge solution the best.
901
+ >>> avail = [(1, 4, 1000), (1, 3, 1), (2, 4, 1)]
902
+ >>> sorted(weighted_bridge_augmentation(G, avail))
903
+ [(1, 3), (2, 4)]
904
+ >>> # ------
905
+ >>> G = nx.path_graph((1, 2, 3, 4))
906
+ >>> G.add_node(5)
907
+ >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 1)]
908
+ >>> sorted(weighted_bridge_augmentation(G, avail=avail))
909
+ [(1, 5), (4, 5)]
910
+ >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
911
+ >>> sorted(weighted_bridge_augmentation(G, avail=avail))
912
+ [(1, 5), (2, 5), (4, 5)]
913
+ """
914
+
915
+ if weight is None:
916
+ weight = "weight"
917
+
918
+ # If input G is not connected the approximation factor increases to 3
919
+ if not nx.is_connected(G):
920
+ H = G.copy()
921
+ connectors = list(one_edge_augmentation(H, avail=avail, weight=weight))
922
+ H.add_edges_from(connectors)
923
+
924
+ yield from connectors
925
+ else:
926
+ connectors = []
927
+ H = G
928
+
929
+ if len(avail) == 0:
930
+ if nx.has_bridges(H):
931
+ raise nx.NetworkXUnfeasible("no augmentation possible")
932
+
933
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=H)
934
+
935
+ # Collapse input into a metagraph. Meta nodes are bridge-ccs
936
+ bridge_ccs = nx.connectivity.bridge_components(H)
937
+ C = collapse(H, bridge_ccs)
938
+
939
+ # Use the meta graph to shrink avail to a small feasible subset
940
+ mapping = C.graph["mapping"]
941
+ # Choose the minimum weight feasible edge in each group
942
+ meta_to_wuv = {
943
+ (mu, mv): (w, uv)
944
+ for (mu, mv), uv, w in _lightest_meta_edges(mapping, avail_uv, avail_w)
945
+ }
946
+
947
+ # Mapping of terms from (Khuller and Thurimella):
948
+ # C : G_0 = (V, E^0)
949
+ # This is the metagraph where each node is a 2-edge-cc in G.
950
+ # The edges in C represent bridges in the original graph.
951
+ # (mu, mv) : E - E^0 # they group both avail and given edges in E
952
+ # T : \Gamma
953
+ # D : G^D = (V, E_D)
954
+
955
+ # The paper uses ancestor because children point to parents, which is
956
+ # contrary to networkx standards. So, we actually need to run
957
+ # nx.least_common_ancestor on the reversed Tree.
958
+
959
+ # Pick an arbitrary leaf from C as the root
960
+ try:
961
+ root = next(n for n, d in C.degree() if d == 1)
962
+ except StopIteration: # no nodes found with degree == 1
963
+ return
964
+ # Root C into a tree TR by directing all edges away from the root
965
+ # Note in their paper T directs edges towards the root
966
+ TR = nx.dfs_tree(C, root)
967
+
968
+ # Add to D the directed edges of T and set their weight to zero
969
+ # This indicates that it costs nothing to use edges that were given.
970
+ D = nx.reverse(TR).copy()
971
+
972
+ nx.set_edge_attributes(D, name="weight", values=0)
973
+
974
+ # The LCA of mu and mv in T is the shared ancestor of mu and mv that is
975
+ # located farthest from the root.
976
+ lca_gen = nx.tree_all_pairs_lowest_common_ancestor(
977
+ TR, root=root, pairs=meta_to_wuv.keys()
978
+ )
979
+
980
+ for (mu, mv), lca in lca_gen:
981
+ w, uv = meta_to_wuv[(mu, mv)]
982
+ if lca == mu:
983
+ # If u is an ancestor of v in TR, then add edge u->v to D
984
+ D.add_edge(lca, mv, weight=w, generator=uv)
985
+ elif lca == mv:
986
+ # If v is an ancestor of u in TR, then add edge v->u to D
987
+ D.add_edge(lca, mu, weight=w, generator=uv)
988
+ else:
989
+ # If neither u nor v is a ancestor of the other in TR
990
+ # let t = lca(TR, u, v) and add edges t->u and t->v
991
+ # Track the original edge that GENERATED these edges.
992
+ D.add_edge(lca, mu, weight=w, generator=uv)
993
+ D.add_edge(lca, mv, weight=w, generator=uv)
994
+
995
+ # Then compute a minimum rooted branching
996
+ try:
997
+ # Note the original edges must be directed towards to root for the
998
+ # branching to give us a bridge-augmentation.
999
+ A = _minimum_rooted_branching(D, root)
1000
+ except nx.NetworkXException as err:
1001
+ # If there is no branching then augmentation is not possible
1002
+ raise nx.NetworkXUnfeasible("no 2-edge-augmentation possible") from err
1003
+
1004
+ # For each edge e, in the branching that did not belong to the directed
1005
+ # tree T, add the corresponding edge that **GENERATED** it (this is not
1006
+ # necessarily e itself!)
1007
+
1008
+ # ensure the third case does not generate edges twice
1009
+ bridge_connectors = set()
1010
+ for mu, mv in A.edges():
1011
+ data = D.get_edge_data(mu, mv)
1012
+ if "generator" in data:
1013
+ # Add the avail edge that generated the branching edge.
1014
+ edge = data["generator"]
1015
+ bridge_connectors.add(edge)
1016
+
1017
+ yield from bridge_connectors
1018
+
1019
+
1020
+ def _minimum_rooted_branching(D, root):
1021
+ """Helper function to compute a minimum rooted branching (aka rooted
1022
+ arborescence)
1023
+
1024
+ Before the branching can be computed, the directed graph must be rooted by
1025
+ removing the predecessors of root.
1026
+
1027
+ A branching / arborescence of rooted graph G is a subgraph that contains a
1028
+ directed path from the root to every other vertex. It is the directed
1029
+ analog of the minimum spanning tree problem.
1030
+
1031
+ References
1032
+ ----------
1033
+ [1] Khuller, Samir (2002) Advanced Algorithms Lecture 24 Notes.
1034
+ https://web.archive.org/web/20121030033722/https://www.cs.umd.edu/class/spring2011/cmsc651/lec07.pdf
1035
+ """
1036
+ rooted = D.copy()
1037
+ # root the graph by removing all predecessors to `root`.
1038
+ rooted.remove_edges_from([(u, root) for u in D.predecessors(root)])
1039
+ # Then compute the branching / arborescence.
1040
+ A = nx.minimum_spanning_arborescence(rooted)
1041
+ return A
1042
+
1043
+
1044
+ @nx._dispatchable(returns_graph=True)
1045
+ def collapse(G, grouped_nodes):
1046
+ """Collapses each group of nodes into a single node.
1047
+
1048
+ This is similar to condensation, but works on undirected graphs.
1049
+
1050
+ Parameters
1051
+ ----------
1052
+ G : NetworkX Graph
1053
+
1054
+ grouped_nodes: list or generator
1055
+ Grouping of nodes to collapse. The grouping must be disjoint.
1056
+ If grouped_nodes are strongly_connected_components then this is
1057
+ equivalent to :func:`condensation`.
1058
+
1059
+ Returns
1060
+ -------
1061
+ C : NetworkX Graph
1062
+ The collapsed graph C of G with respect to the node grouping. The node
1063
+ labels are integers corresponding to the index of the component in the
1064
+ list of grouped_nodes. C has a graph attribute named 'mapping' with a
1065
+ dictionary mapping the original nodes to the nodes in C to which they
1066
+ belong. Each node in C also has a node attribute 'members' with the set
1067
+ of original nodes in G that form the group that the node in C
1068
+ represents.
1069
+
1070
+ Examples
1071
+ --------
1072
+ >>> # Collapses a graph using disjoint groups, but not necessarily connected
1073
+ >>> G = nx.Graph([(1, 0), (2, 3), (3, 1), (3, 4), (4, 5), (5, 6), (5, 7)])
1074
+ >>> G.add_node("A")
1075
+ >>> grouped_nodes = [{0, 1, 2, 3}, {5, 6, 7}]
1076
+ >>> C = collapse(G, grouped_nodes)
1077
+ >>> members = nx.get_node_attributes(C, "members")
1078
+ >>> sorted(members.keys())
1079
+ [0, 1, 2, 3]
1080
+ >>> member_values = set(map(frozenset, members.values()))
1081
+ >>> assert {0, 1, 2, 3} in member_values
1082
+ >>> assert {4} in member_values
1083
+ >>> assert {5, 6, 7} in member_values
1084
+ >>> assert {"A"} in member_values
1085
+ """
1086
+ mapping = {}
1087
+ members = {}
1088
+ C = G.__class__()
1089
+ i = 0 # required if G is empty
1090
+ remaining = set(G.nodes())
1091
+ for i, group in enumerate(grouped_nodes):
1092
+ group = set(group)
1093
+ assert remaining.issuperset(
1094
+ group
1095
+ ), "grouped nodes must exist in G and be disjoint"
1096
+ remaining.difference_update(group)
1097
+ members[i] = group
1098
+ mapping.update((n, i) for n in group)
1099
+ # remaining nodes are in their own group
1100
+ for i, node in enumerate(remaining, start=i + 1):
1101
+ group = {node}
1102
+ members[i] = group
1103
+ mapping.update((n, i) for n in group)
1104
+ number_of_groups = i + 1
1105
+ C.add_nodes_from(range(number_of_groups))
1106
+ C.add_edges_from(
1107
+ (mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
1108
+ )
1109
+ # Add a list of members (ie original nodes) to each node (ie scc) in C.
1110
+ nx.set_node_attributes(C, name="members", values=members)
1111
+ # Add mapping dict as graph attribute
1112
+ C.graph["mapping"] = mapping
1113
+ return C
1114
+
1115
+
1116
+ @nx._dispatchable
1117
+ def complement_edges(G):
1118
+ """Returns only the edges in the complement of G
1119
+
1120
+ Parameters
1121
+ ----------
1122
+ G : NetworkX Graph
1123
+
1124
+ Yields
1125
+ ------
1126
+ edge : tuple
1127
+ Edges in the complement of G
1128
+
1129
+ Examples
1130
+ --------
1131
+ >>> G = nx.path_graph((1, 2, 3, 4))
1132
+ >>> sorted(complement_edges(G))
1133
+ [(1, 3), (1, 4), (2, 4)]
1134
+ >>> G = nx.path_graph((1, 2, 3, 4), nx.DiGraph())
1135
+ >>> sorted(complement_edges(G))
1136
+ [(1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
1137
+ >>> G = nx.complete_graph(1000)
1138
+ >>> sorted(complement_edges(G))
1139
+ []
1140
+ """
1141
+ G_adj = G._adj # Store as a variable to eliminate attribute lookup
1142
+ if G.is_directed():
1143
+ for u, v in it.combinations(G.nodes(), 2):
1144
+ if v not in G_adj[u]:
1145
+ yield (u, v)
1146
+ if u not in G_adj[v]:
1147
+ yield (v, u)
1148
+ else:
1149
+ for u, v in it.combinations(G.nodes(), 2):
1150
+ if v not in G_adj[u]:
1151
+ yield (u, v)
1152
+
1153
+
1154
+ def _compat_shuffle(rng, input):
1155
+ """wrapper around rng.shuffle for python 2 compatibility reasons"""
1156
+ rng.shuffle(input)
1157
+
1158
+
1159
+ @not_implemented_for("multigraph")
1160
+ @not_implemented_for("directed")
1161
+ @py_random_state(4)
1162
+ @nx._dispatchable
1163
+ def greedy_k_edge_augmentation(G, k, avail=None, weight=None, seed=None):
1164
+ """Greedy algorithm for finding a k-edge-augmentation
1165
+
1166
+ Parameters
1167
+ ----------
1168
+ G : NetworkX graph
1169
+ An undirected graph.
1170
+
1171
+ k : integer
1172
+ Desired edge connectivity
1173
+
1174
+ avail : dict or a set of 2 or 3 tuples
1175
+ For more details, see :func:`k_edge_augmentation`.
1176
+
1177
+ weight : string
1178
+ key to use to find weights if ``avail`` is a set of 3-tuples.
1179
+ For more details, see :func:`k_edge_augmentation`.
1180
+
1181
+ seed : integer, random_state, or None (default)
1182
+ Indicator of random number generation state.
1183
+ See :ref:`Randomness<randomness>`.
1184
+
1185
+ Yields
1186
+ ------
1187
+ edge : tuple
1188
+ Edges in the greedy augmentation of G
1189
+
1190
+ Notes
1191
+ -----
1192
+ The algorithm is simple. Edges are incrementally added between parts of the
1193
+ graph that are not yet locally k-edge-connected. Then edges are from the
1194
+ augmenting set are pruned as long as local-edge-connectivity is not broken.
1195
+
1196
+ This algorithm is greedy and does not provide optimality guarantees. It
1197
+ exists only to provide :func:`k_edge_augmentation` with the ability to
1198
+ generate a feasible solution for arbitrary k.
1199
+
1200
+ See Also
1201
+ --------
1202
+ :func:`k_edge_augmentation`
1203
+
1204
+ Examples
1205
+ --------
1206
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
1207
+ >>> sorted(greedy_k_edge_augmentation(G, k=2))
1208
+ [(1, 7)]
1209
+ >>> sorted(greedy_k_edge_augmentation(G, k=1, avail=[]))
1210
+ []
1211
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
1212
+ >>> avail = {(u, v): 1 for (u, v) in complement_edges(G)}
1213
+ >>> # randomized pruning process can produce different solutions
1214
+ >>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=2))
1215
+ [(1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 6), (3, 7), (5, 7)]
1216
+ >>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=3))
1217
+ [(1, 3), (1, 5), (1, 6), (2, 4), (2, 6), (3, 7), (4, 7), (5, 7)]
1218
+ """
1219
+ # Result set
1220
+ aug_edges = []
1221
+
1222
+ done = is_k_edge_connected(G, k)
1223
+ if done:
1224
+ return
1225
+ if avail is None:
1226
+ # all edges are available
1227
+ avail_uv = list(complement_edges(G))
1228
+ avail_w = [1] * len(avail_uv)
1229
+ else:
1230
+ # Get the unique set of unweighted edges
1231
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
1232
+
1233
+ # Greedy: order lightest edges. Use degree sum to tie-break
1234
+ tiebreaker = [sum(map(G.degree, uv)) for uv in avail_uv]
1235
+ avail_wduv = sorted(zip(avail_w, tiebreaker, avail_uv))
1236
+ avail_uv = [uv for w, d, uv in avail_wduv]
1237
+
1238
+ # Incrementally add edges in until we are k-connected
1239
+ H = G.copy()
1240
+ for u, v in avail_uv:
1241
+ done = False
1242
+ if not is_locally_k_edge_connected(H, u, v, k=k):
1243
+ # Only add edges in parts that are not yet locally k-edge-connected
1244
+ aug_edges.append((u, v))
1245
+ H.add_edge(u, v)
1246
+ # Did adding this edge help?
1247
+ if H.degree(u) >= k and H.degree(v) >= k:
1248
+ done = is_k_edge_connected(H, k)
1249
+ if done:
1250
+ break
1251
+
1252
+ # Check for feasibility
1253
+ if not done:
1254
+ raise nx.NetworkXUnfeasible("not able to k-edge-connect with available edges")
1255
+
1256
+ # Randomized attempt to reduce the size of the solution
1257
+ _compat_shuffle(seed, aug_edges)
1258
+ for u, v in list(aug_edges):
1259
+ # Don't remove if we know it would break connectivity
1260
+ if H.degree(u) <= k or H.degree(v) <= k:
1261
+ continue
1262
+ H.remove_edge(u, v)
1263
+ aug_edges.remove((u, v))
1264
+ if not is_k_edge_connected(H, k=k):
1265
+ # If removing this edge breaks feasibility, undo
1266
+ H.add_edge(u, v)
1267
+ aug_edges.append((u, v))
1268
+
1269
+ # Generate results
1270
+ yield from aug_edges
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Algorithms for finding k-edge-connected components and subgraphs.
3
+
4
+ A k-edge-connected component (k-edge-cc) is a maximal set of nodes in G, such
5
+ that all pairs of node have an edge-connectivity of at least k.
6
+
7
+ A k-edge-connected subgraph (k-edge-subgraph) is a maximal set of nodes in G,
8
+ such that the subgraph of G defined by the nodes has an edge-connectivity at
9
+ least k.
10
+ """
11
+
12
+ import itertools as it
13
+ from functools import partial
14
+
15
+ import networkx as nx
16
+ from networkx.utils import arbitrary_element, not_implemented_for
17
+
18
+ __all__ = [
19
+ "k_edge_components",
20
+ "k_edge_subgraphs",
21
+ "bridge_components",
22
+ "EdgeComponentAuxGraph",
23
+ ]
24
+
25
+
26
+ @not_implemented_for("multigraph")
27
+ @nx._dispatchable
28
+ def k_edge_components(G, k):
29
+ """Generates nodes in each maximal k-edge-connected component in G.
30
+
31
+ Parameters
32
+ ----------
33
+ G : NetworkX graph
34
+
35
+ k : Integer
36
+ Desired edge connectivity
37
+
38
+ Returns
39
+ -------
40
+ k_edge_components : a generator of k-edge-ccs. Each set of returned nodes
41
+ will have k-edge-connectivity in the graph G.
42
+
43
+ See Also
44
+ --------
45
+ :func:`local_edge_connectivity`
46
+ :func:`k_edge_subgraphs` : similar to this function, but the subgraph
47
+ defined by the nodes must also have k-edge-connectivity.
48
+ :func:`k_components` : similar to this function, but uses node-connectivity
49
+ instead of edge-connectivity
50
+
51
+ Raises
52
+ ------
53
+ NetworkXNotImplemented
54
+ If the input graph is a multigraph.
55
+
56
+ ValueError:
57
+ If k is less than 1
58
+
59
+ Notes
60
+ -----
61
+ Attempts to use the most efficient implementation available based on k.
62
+ If k=1, this is simply connected components for directed graphs and
63
+ connected components for undirected graphs.
64
+ If k=2 on an efficient bridge connected component algorithm from _[1] is
65
+ run based on the chain decomposition.
66
+ Otherwise, the algorithm from _[2] is used.
67
+
68
+ Examples
69
+ --------
70
+ >>> import itertools as it
71
+ >>> from networkx.utils import pairwise
72
+ >>> paths = [
73
+ ... (1, 2, 4, 3, 1, 4),
74
+ ... (5, 6, 7, 8, 5, 7, 8, 6),
75
+ ... ]
76
+ >>> G = nx.Graph()
77
+ >>> G.add_nodes_from(it.chain(*paths))
78
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
79
+ >>> # note this returns {1, 4} unlike k_edge_subgraphs
80
+ >>> sorted(map(sorted, nx.k_edge_components(G, k=3)))
81
+ [[1, 4], [2], [3], [5, 6, 7, 8]]
82
+
83
+ References
84
+ ----------
85
+ .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29
86
+ .. [2] Wang, Tianhao, et al. (2015) A simple algorithm for finding all
87
+ k-edge-connected components.
88
+ http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
89
+ """
90
+ # Compute k-edge-ccs using the most efficient algorithms available.
91
+ if k < 1:
92
+ raise ValueError("k cannot be less than 1")
93
+ if G.is_directed():
94
+ if k == 1:
95
+ return nx.strongly_connected_components(G)
96
+ else:
97
+ # TODO: investigate https://arxiv.org/abs/1412.6466 for k=2
98
+ aux_graph = EdgeComponentAuxGraph.construct(G)
99
+ return aux_graph.k_edge_components(k)
100
+ else:
101
+ if k == 1:
102
+ return nx.connected_components(G)
103
+ elif k == 2:
104
+ return bridge_components(G)
105
+ else:
106
+ aux_graph = EdgeComponentAuxGraph.construct(G)
107
+ return aux_graph.k_edge_components(k)
108
+
109
+
110
+ @not_implemented_for("multigraph")
111
+ @nx._dispatchable
112
+ def k_edge_subgraphs(G, k):
113
+ """Generates nodes in each maximal k-edge-connected subgraph in G.
114
+
115
+ Parameters
116
+ ----------
117
+ G : NetworkX graph
118
+
119
+ k : Integer
120
+ Desired edge connectivity
121
+
122
+ Returns
123
+ -------
124
+ k_edge_subgraphs : a generator of k-edge-subgraphs
125
+ Each k-edge-subgraph is a maximal set of nodes that defines a subgraph
126
+ of G that is k-edge-connected.
127
+
128
+ See Also
129
+ --------
130
+ :func:`edge_connectivity`
131
+ :func:`k_edge_components` : similar to this function, but nodes only
132
+ need to have k-edge-connectivity within the graph G and the subgraphs
133
+ might not be k-edge-connected.
134
+
135
+ Raises
136
+ ------
137
+ NetworkXNotImplemented
138
+ If the input graph is a multigraph.
139
+
140
+ ValueError:
141
+ If k is less than 1
142
+
143
+ Notes
144
+ -----
145
+ Attempts to use the most efficient implementation available based on k.
146
+ If k=1, or k=2 and the graph is undirected, then this simply calls
147
+ `k_edge_components`. Otherwise the algorithm from _[1] is used.
148
+
149
+ Examples
150
+ --------
151
+ >>> import itertools as it
152
+ >>> from networkx.utils import pairwise
153
+ >>> paths = [
154
+ ... (1, 2, 4, 3, 1, 4),
155
+ ... (5, 6, 7, 8, 5, 7, 8, 6),
156
+ ... ]
157
+ >>> G = nx.Graph()
158
+ >>> G.add_nodes_from(it.chain(*paths))
159
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
160
+ >>> # note this does not return {1, 4} unlike k_edge_components
161
+ >>> sorted(map(sorted, nx.k_edge_subgraphs(G, k=3)))
162
+ [[1], [2], [3], [4], [5, 6, 7, 8]]
163
+
164
+ References
165
+ ----------
166
+ .. [1] Zhou, Liu, et al. (2012) Finding maximal k-edge-connected subgraphs
167
+ from a large graph. ACM International Conference on Extending Database
168
+ Technology 2012 480-–491.
169
+ https://openproceedings.org/2012/conf/edbt/ZhouLYLCL12.pdf
170
+ """
171
+ if k < 1:
172
+ raise ValueError("k cannot be less than 1")
173
+ if G.is_directed():
174
+ if k <= 1:
175
+ # For directed graphs ,
176
+ # When k == 1, k-edge-ccs and k-edge-subgraphs are the same
177
+ return k_edge_components(G, k)
178
+ else:
179
+ return _k_edge_subgraphs_nodes(G, k)
180
+ else:
181
+ if k <= 2:
182
+ # For undirected graphs,
183
+ # when k <= 2, k-edge-ccs and k-edge-subgraphs are the same
184
+ return k_edge_components(G, k)
185
+ else:
186
+ return _k_edge_subgraphs_nodes(G, k)
187
+
188
+
189
+ def _k_edge_subgraphs_nodes(G, k):
190
+ """Helper to get the nodes from the subgraphs.
191
+
192
+ This allows k_edge_subgraphs to return a generator.
193
+ """
194
+ for C in general_k_edge_subgraphs(G, k):
195
+ yield set(C.nodes())
196
+
197
+
198
+ @not_implemented_for("directed")
199
+ @not_implemented_for("multigraph")
200
+ @nx._dispatchable
201
+ def bridge_components(G):
202
+ """Finds all bridge-connected components G.
203
+
204
+ Parameters
205
+ ----------
206
+ G : NetworkX undirected graph
207
+
208
+ Returns
209
+ -------
210
+ bridge_components : a generator of 2-edge-connected components
211
+
212
+
213
+ See Also
214
+ --------
215
+ :func:`k_edge_subgraphs` : this function is a special case for an
216
+ undirected graph where k=2.
217
+ :func:`biconnected_components` : similar to this function, but is defined
218
+ using 2-node-connectivity instead of 2-edge-connectivity.
219
+
220
+ Raises
221
+ ------
222
+ NetworkXNotImplemented
223
+ If the input graph is directed or a multigraph.
224
+
225
+ Notes
226
+ -----
227
+ Bridge-connected components are also known as 2-edge-connected components.
228
+
229
+ Examples
230
+ --------
231
+ >>> # The barbell graph with parameter zero has a single bridge
232
+ >>> G = nx.barbell_graph(5, 0)
233
+ >>> from networkx.algorithms.connectivity.edge_kcomponents import bridge_components
234
+ >>> sorted(map(sorted, bridge_components(G)))
235
+ [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
236
+ """
237
+ H = G.copy()
238
+ H.remove_edges_from(nx.bridges(G))
239
+ yield from nx.connected_components(H)
240
+
241
+
242
+ class EdgeComponentAuxGraph:
243
+ r"""A simple algorithm to find all k-edge-connected components in a graph.
244
+
245
+ Constructing the auxiliary graph (which may take some time) allows for the
246
+ k-edge-ccs to be found in linear time for arbitrary k.
247
+
248
+ Notes
249
+ -----
250
+ This implementation is based on [1]_. The idea is to construct an auxiliary
251
+ graph from which the k-edge-ccs can be extracted in linear time. The
252
+ auxiliary graph is constructed in $O(|V|\cdot F)$ operations, where F is the
253
+ complexity of max flow. Querying the components takes an additional $O(|V|)$
254
+ operations. This algorithm can be slow for large graphs, but it handles an
255
+ arbitrary k and works for both directed and undirected inputs.
256
+
257
+ The undirected case for k=1 is exactly connected components.
258
+ The undirected case for k=2 is exactly bridge connected components.
259
+ The directed case for k=1 is exactly strongly connected components.
260
+
261
+ References
262
+ ----------
263
+ .. [1] Wang, Tianhao, et al. (2015) A simple algorithm for finding all
264
+ k-edge-connected components.
265
+ http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
266
+
267
+ Examples
268
+ --------
269
+ >>> import itertools as it
270
+ >>> from networkx.utils import pairwise
271
+ >>> from networkx.algorithms.connectivity import EdgeComponentAuxGraph
272
+ >>> # Build an interesting graph with multiple levels of k-edge-ccs
273
+ >>> paths = [
274
+ ... (1, 2, 3, 4, 1, 3, 4, 2), # a 3-edge-cc (a 4 clique)
275
+ ... (5, 6, 7, 5), # a 2-edge-cc (a 3 clique)
276
+ ... (1, 5), # combine first two ccs into a 1-edge-cc
277
+ ... (0,), # add an additional disconnected 1-edge-cc
278
+ ... ]
279
+ >>> G = nx.Graph()
280
+ >>> G.add_nodes_from(it.chain(*paths))
281
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
282
+ >>> # Constructing the AuxGraph takes about O(n ** 4)
283
+ >>> aux_graph = EdgeComponentAuxGraph.construct(G)
284
+ >>> # Once constructed, querying takes O(n)
285
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=1)))
286
+ [[0], [1, 2, 3, 4, 5, 6, 7]]
287
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=2)))
288
+ [[0], [1, 2, 3, 4], [5, 6, 7]]
289
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
290
+ [[0], [1, 2, 3, 4], [5], [6], [7]]
291
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=4)))
292
+ [[0], [1], [2], [3], [4], [5], [6], [7]]
293
+
294
+ The auxiliary graph is primarily used for k-edge-ccs but it
295
+ can also speed up the queries of k-edge-subgraphs by refining the
296
+ search space.
297
+
298
+ >>> import itertools as it
299
+ >>> from networkx.utils import pairwise
300
+ >>> from networkx.algorithms.connectivity import EdgeComponentAuxGraph
301
+ >>> paths = [
302
+ ... (1, 2, 4, 3, 1, 4),
303
+ ... ]
304
+ >>> G = nx.Graph()
305
+ >>> G.add_nodes_from(it.chain(*paths))
306
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
307
+ >>> aux_graph = EdgeComponentAuxGraph.construct(G)
308
+ >>> sorted(map(sorted, aux_graph.k_edge_subgraphs(k=3)))
309
+ [[1], [2], [3], [4]]
310
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
311
+ [[1, 4], [2], [3]]
312
+ """
313
+
314
+ # @not_implemented_for('multigraph') # TODO: fix decor for classmethods
315
+ @classmethod
316
+ def construct(EdgeComponentAuxGraph, G):
317
+ """Builds an auxiliary graph encoding edge-connectivity between nodes.
318
+
319
+ Notes
320
+ -----
321
+ Given G=(V, E), initialize an empty auxiliary graph A.
322
+ Choose an arbitrary source node s. Initialize a set N of available
323
+ nodes (that can be used as the sink). The algorithm picks an
324
+ arbitrary node t from N - {s}, and then computes the minimum st-cut
325
+ (S, T) with value w. If G is directed the minimum of the st-cut or
326
+ the ts-cut is used instead. Then, the edge (s, t) is added to the
327
+ auxiliary graph with weight w. The algorithm is called recursively
328
+ first using S as the available nodes and s as the source, and then
329
+ using T and t. Recursion stops when the source is the only available
330
+ node.
331
+
332
+ Parameters
333
+ ----------
334
+ G : NetworkX graph
335
+ """
336
+ # workaround for classmethod decorator
337
+ not_implemented_for("multigraph")(lambda G: G)(G)
338
+
339
+ def _recursive_build(H, A, source, avail):
340
+ # Terminate once the flow has been compute to every node.
341
+ if {source} == avail:
342
+ return
343
+ # pick an arbitrary node as the sink
344
+ sink = arbitrary_element(avail - {source})
345
+ # find the minimum cut and its weight
346
+ value, (S, T) = nx.minimum_cut(H, source, sink)
347
+ if H.is_directed():
348
+ # check if the reverse direction has a smaller cut
349
+ value_, (T_, S_) = nx.minimum_cut(H, sink, source)
350
+ if value_ < value:
351
+ value, S, T = value_, S_, T_
352
+ # add edge with weight of cut to the aux graph
353
+ A.add_edge(source, sink, weight=value)
354
+ # recursively call until all but one node is used
355
+ _recursive_build(H, A, source, avail.intersection(S))
356
+ _recursive_build(H, A, sink, avail.intersection(T))
357
+
358
+ # Copy input to ensure all edges have unit capacity
359
+ H = G.__class__()
360
+ H.add_nodes_from(G.nodes())
361
+ H.add_edges_from(G.edges(), capacity=1)
362
+
363
+ # A is the auxiliary graph to be constructed
364
+ # It is a weighted undirected tree
365
+ A = nx.Graph()
366
+
367
+ # Pick an arbitrary node as the source
368
+ if H.number_of_nodes() > 0:
369
+ source = arbitrary_element(H.nodes())
370
+ # Initialize a set of elements that can be chosen as the sink
371
+ avail = set(H.nodes())
372
+
373
+ # This constructs A
374
+ _recursive_build(H, A, source, avail)
375
+
376
+ # This class is a container the holds the auxiliary graph A and
377
+ # provides access the k_edge_components function.
378
+ self = EdgeComponentAuxGraph()
379
+ self.A = A
380
+ self.H = H
381
+ return self
382
+
383
+ def k_edge_components(self, k):
384
+ """Queries the auxiliary graph for k-edge-connected components.
385
+
386
+ Parameters
387
+ ----------
388
+ k : Integer
389
+ Desired edge connectivity
390
+
391
+ Returns
392
+ -------
393
+ k_edge_components : a generator of k-edge-ccs
394
+
395
+ Notes
396
+ -----
397
+ Given the auxiliary graph, the k-edge-connected components can be
398
+ determined in linear time by removing all edges with weights less than
399
+ k from the auxiliary graph. The resulting connected components are the
400
+ k-edge-ccs in the original graph.
401
+ """
402
+ if k < 1:
403
+ raise ValueError("k cannot be less than 1")
404
+ A = self.A
405
+ # "traverse the auxiliary graph A and delete all edges with weights less
406
+ # than k"
407
+ aux_weights = nx.get_edge_attributes(A, "weight")
408
+ # Create a relevant graph with the auxiliary edges with weights >= k
409
+ R = nx.Graph()
410
+ R.add_nodes_from(A.nodes())
411
+ R.add_edges_from(e for e, w in aux_weights.items() if w >= k)
412
+
413
+ # Return the nodes that are k-edge-connected in the original graph
414
+ yield from nx.connected_components(R)
415
+
416
+ def k_edge_subgraphs(self, k):
417
+ """Queries the auxiliary graph for k-edge-connected subgraphs.
418
+
419
+ Parameters
420
+ ----------
421
+ k : Integer
422
+ Desired edge connectivity
423
+
424
+ Returns
425
+ -------
426
+ k_edge_subgraphs : a generator of k-edge-subgraphs
427
+
428
+ Notes
429
+ -----
430
+ Refines the k-edge-ccs into k-edge-subgraphs. The running time is more
431
+ than $O(|V|)$.
432
+
433
+ For single values of k it is faster to use `nx.k_edge_subgraphs`.
434
+ But for multiple values of k, it can be faster to build AuxGraph and
435
+ then use this method.
436
+ """
437
+ if k < 1:
438
+ raise ValueError("k cannot be less than 1")
439
+ H = self.H
440
+ A = self.A
441
+ # "traverse the auxiliary graph A and delete all edges with weights less
442
+ # than k"
443
+ aux_weights = nx.get_edge_attributes(A, "weight")
444
+ # Create a relevant graph with the auxiliary edges with weights >= k
445
+ R = nx.Graph()
446
+ R.add_nodes_from(A.nodes())
447
+ R.add_edges_from(e for e, w in aux_weights.items() if w >= k)
448
+
449
+ # Return the components whose subgraphs are k-edge-connected
450
+ for cc in nx.connected_components(R):
451
+ if len(cc) < k:
452
+ # Early return optimization
453
+ for node in cc:
454
+ yield {node}
455
+ else:
456
+ # Call subgraph solution to refine the results
457
+ C = H.subgraph(cc)
458
+ yield from k_edge_subgraphs(C, k)
459
+
460
+
461
+ def _low_degree_nodes(G, k, nbunch=None):
462
+ """Helper for finding nodes with degree less than k."""
463
+ # Nodes with degree less than k cannot be k-edge-connected.
464
+ if G.is_directed():
465
+ # Consider both in and out degree in the directed case
466
+ seen = set()
467
+ for node, degree in G.out_degree(nbunch):
468
+ if degree < k:
469
+ seen.add(node)
470
+ yield node
471
+ for node, degree in G.in_degree(nbunch):
472
+ if node not in seen and degree < k:
473
+ seen.add(node)
474
+ yield node
475
+ else:
476
+ # Only the degree matters in the undirected case
477
+ for node, degree in G.degree(nbunch):
478
+ if degree < k:
479
+ yield node
480
+
481
+
482
+ def _high_degree_components(G, k):
483
+ """Helper for filtering components that can't be k-edge-connected.
484
+
485
+ Removes and generates each node with degree less than k. Then generates
486
+ remaining components where all nodes have degree at least k.
487
+ """
488
+ # Iteratively remove parts of the graph that are not k-edge-connected
489
+ H = G.copy()
490
+ singletons = set(_low_degree_nodes(H, k))
491
+ while singletons:
492
+ # Only search neighbors of removed nodes
493
+ nbunch = set(it.chain.from_iterable(map(H.neighbors, singletons)))
494
+ nbunch.difference_update(singletons)
495
+ H.remove_nodes_from(singletons)
496
+ for node in singletons:
497
+ yield {node}
498
+ singletons = set(_low_degree_nodes(H, k, nbunch))
499
+
500
+ # Note: remaining connected components may not be k-edge-connected
501
+ if G.is_directed():
502
+ yield from nx.strongly_connected_components(H)
503
+ else:
504
+ yield from nx.connected_components(H)
505
+
506
+
507
+ @nx._dispatchable(returns_graph=True)
508
+ def general_k_edge_subgraphs(G, k):
509
+ """General algorithm to find all maximal k-edge-connected subgraphs in `G`.
510
+
511
+ Parameters
512
+ ----------
513
+ G : nx.Graph
514
+ Graph in which all maximal k-edge-connected subgraphs will be found.
515
+
516
+ k : int
517
+
518
+ Yields
519
+ ------
520
+ k_edge_subgraphs : Graph instances that are k-edge-subgraphs
521
+ Each k-edge-subgraph contains a maximal set of nodes that defines a
522
+ subgraph of `G` that is k-edge-connected.
523
+
524
+ Notes
525
+ -----
526
+ Implementation of the basic algorithm from [1]_. The basic idea is to find
527
+ a global minimum cut of the graph. If the cut value is at least k, then the
528
+ graph is a k-edge-connected subgraph and can be added to the results.
529
+ Otherwise, the cut is used to split the graph in two and the procedure is
530
+ applied recursively. If the graph is just a single node, then it is also
531
+ added to the results. At the end, each result is either guaranteed to be
532
+ a single node or a subgraph of G that is k-edge-connected.
533
+
534
+ This implementation contains optimizations for reducing the number of calls
535
+ to max-flow, but there are other optimizations in [1]_ that could be
536
+ implemented.
537
+
538
+ References
539
+ ----------
540
+ .. [1] Zhou, Liu, et al. (2012) Finding maximal k-edge-connected subgraphs
541
+ from a large graph. ACM International Conference on Extending Database
542
+ Technology 2012 480-–491.
543
+ https://openproceedings.org/2012/conf/edbt/ZhouLYLCL12.pdf
544
+
545
+ Examples
546
+ --------
547
+ >>> from networkx.utils import pairwise
548
+ >>> paths = [
549
+ ... (11, 12, 13, 14, 11, 13, 14, 12), # a 4-clique
550
+ ... (21, 22, 23, 24, 21, 23, 24, 22), # another 4-clique
551
+ ... # connect the cliques with high degree but low connectivity
552
+ ... (50, 13),
553
+ ... (12, 50, 22),
554
+ ... (13, 102, 23),
555
+ ... (14, 101, 24),
556
+ ... ]
557
+ >>> G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
558
+ >>> sorted(len(k_sg) for k_sg in k_edge_subgraphs(G, k=3))
559
+ [1, 1, 1, 4, 4]
560
+ """
561
+ if k < 1:
562
+ raise ValueError("k cannot be less than 1")
563
+
564
+ # Node pruning optimization (incorporates early return)
565
+ # find_ccs is either connected_components/strongly_connected_components
566
+ find_ccs = partial(_high_degree_components, k=k)
567
+
568
+ # Quick return optimization
569
+ if G.number_of_nodes() < k:
570
+ for node in G.nodes():
571
+ yield G.subgraph([node]).copy()
572
+ return
573
+
574
+ # Intermediate results
575
+ R0 = {G.subgraph(cc).copy() for cc in find_ccs(G)}
576
+ # Subdivide CCs in the intermediate results until they are k-conn
577
+ while R0:
578
+ G1 = R0.pop()
579
+ if G1.number_of_nodes() == 1:
580
+ yield G1
581
+ else:
582
+ # Find a global minimum cut
583
+ cut_edges = nx.minimum_edge_cut(G1)
584
+ cut_value = len(cut_edges)
585
+ if cut_value < k:
586
+ # G1 is not k-edge-connected, so subdivide it
587
+ G1.remove_edges_from(cut_edges)
588
+ for cc in find_ccs(G1):
589
+ R0.add(G1.subgraph(cc).copy())
590
+ else:
591
+ # Otherwise we found a k-edge-connected subgraph
592
+ yield G1
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcomponents.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Moody and White algorithm for k-components
3
+ """
4
+
5
+ from collections import defaultdict
6
+ from itertools import combinations
7
+ from operator import itemgetter
8
+
9
+ import networkx as nx
10
+
11
+ # Define the default maximum flow function.
12
+ from networkx.algorithms.flow import edmonds_karp
13
+ from networkx.utils import not_implemented_for
14
+
15
+ default_flow_func = edmonds_karp
16
+
17
+ __all__ = ["k_components"]
18
+
19
+
20
+ @not_implemented_for("directed")
21
+ @nx._dispatchable
22
+ def k_components(G, flow_func=None):
23
+ r"""Returns the k-component structure of a graph G.
24
+
25
+ A `k`-component is a maximal subgraph of a graph G that has, at least,
26
+ node connectivity `k`: we need to remove at least `k` nodes to break it
27
+ into more components. `k`-components have an inherent hierarchical
28
+ structure because they are nested in terms of connectivity: a connected
29
+ graph can contain several 2-components, each of which can contain
30
+ one or more 3-components, and so forth.
31
+
32
+ Parameters
33
+ ----------
34
+ G : NetworkX graph
35
+
36
+ flow_func : function
37
+ Function to perform the underlying flow computations. Default value
38
+ :meth:`edmonds_karp`. This function performs better in sparse graphs with
39
+ right tailed degree distributions. :meth:`shortest_augmenting_path` will
40
+ perform better in denser graphs.
41
+
42
+ Returns
43
+ -------
44
+ k_components : dict
45
+ Dictionary with all connectivity levels `k` in the input Graph as keys
46
+ and a list of sets of nodes that form a k-component of level `k` as
47
+ values.
48
+
49
+ Raises
50
+ ------
51
+ NetworkXNotImplemented
52
+ If the input graph is directed.
53
+
54
+ Examples
55
+ --------
56
+ >>> # Petersen graph has 10 nodes and it is triconnected, thus all
57
+ >>> # nodes are in a single component on all three connectivity levels
58
+ >>> G = nx.petersen_graph()
59
+ >>> k_components = nx.k_components(G)
60
+
61
+ Notes
62
+ -----
63
+ Moody and White [1]_ (appendix A) provide an algorithm for identifying
64
+ k-components in a graph, which is based on Kanevsky's algorithm [2]_
65
+ for finding all minimum-size node cut-sets of a graph (implemented in
66
+ :meth:`all_node_cuts` function):
67
+
68
+ 1. Compute node connectivity, k, of the input graph G.
69
+
70
+ 2. Identify all k-cutsets at the current level of connectivity using
71
+ Kanevsky's algorithm.
72
+
73
+ 3. Generate new graph components based on the removal of
74
+ these cutsets. Nodes in a cutset belong to both sides
75
+ of the induced cut.
76
+
77
+ 4. If the graph is neither complete nor trivial, return to 1;
78
+ else end.
79
+
80
+ This implementation also uses some heuristics (see [3]_ for details)
81
+ to speed up the computation.
82
+
83
+ See also
84
+ --------
85
+ node_connectivity
86
+ all_node_cuts
87
+ biconnected_components : special case of this function when k=2
88
+ k_edge_components : similar to this function, but uses edge-connectivity
89
+ instead of node-connectivity
90
+
91
+ References
92
+ ----------
93
+ .. [1] Moody, J. and D. White (2003). Social cohesion and embeddedness:
94
+ A hierarchical conception of social groups.
95
+ American Sociological Review 68(1), 103--28.
96
+ http://www2.asanet.org/journals/ASRFeb03MoodyWhite.pdf
97
+
98
+ .. [2] Kanevsky, A. (1993). Finding all minimum-size separating vertex
99
+ sets in a graph. Networks 23(6), 533--541.
100
+ http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract
101
+
102
+ .. [3] Torrents, J. and F. Ferraro (2015). Structural Cohesion:
103
+ Visualization and Heuristics for Fast Computation.
104
+ https://arxiv.org/pdf/1503.04476v1
105
+
106
+ """
107
+ # Dictionary with connectivity level (k) as keys and a list of
108
+ # sets of nodes that form a k-component as values. Note that
109
+ # k-components can overlap (but only k - 1 nodes).
110
+ k_components = defaultdict(list)
111
+ # Define default flow function
112
+ if flow_func is None:
113
+ flow_func = default_flow_func
114
+ # Bicomponents as a base to check for higher order k-components
115
+ for component in nx.connected_components(G):
116
+ # isolated nodes have connectivity 0
117
+ comp = set(component)
118
+ if len(comp) > 1:
119
+ k_components[1].append(comp)
120
+ bicomponents = [G.subgraph(c) for c in nx.biconnected_components(G)]
121
+ for bicomponent in bicomponents:
122
+ bicomp = set(bicomponent)
123
+ # avoid considering dyads as bicomponents
124
+ if len(bicomp) > 2:
125
+ k_components[2].append(bicomp)
126
+ for B in bicomponents:
127
+ if len(B) <= 2:
128
+ continue
129
+ k = nx.node_connectivity(B, flow_func=flow_func)
130
+ if k > 2:
131
+ k_components[k].append(set(B))
132
+ # Perform cuts in a DFS like order.
133
+ cuts = list(nx.all_node_cuts(B, k=k, flow_func=flow_func))
134
+ stack = [(k, _generate_partition(B, cuts, k))]
135
+ while stack:
136
+ (parent_k, partition) = stack[-1]
137
+ try:
138
+ nodes = next(partition)
139
+ C = B.subgraph(nodes)
140
+ this_k = nx.node_connectivity(C, flow_func=flow_func)
141
+ if this_k > parent_k and this_k > 2:
142
+ k_components[this_k].append(set(C))
143
+ cuts = list(nx.all_node_cuts(C, k=this_k, flow_func=flow_func))
144
+ if cuts:
145
+ stack.append((this_k, _generate_partition(C, cuts, this_k)))
146
+ except StopIteration:
147
+ stack.pop()
148
+
149
+ # This is necessary because k-components may only be reported at their
150
+ # maximum k level. But we want to return a dictionary in which keys are
151
+ # connectivity levels and values list of sets of components, without
152
+ # skipping any connectivity level. Also, it's possible that subsets of
153
+ # an already detected k-component appear at a level k. Checking for this
154
+ # in the while loop above penalizes the common case. Thus we also have to
155
+ # _consolidate all connectivity levels in _reconstruct_k_components.
156
+ return _reconstruct_k_components(k_components)
157
+
158
+
159
+ def _consolidate(sets, k):
160
+ """Merge sets that share k or more elements.
161
+
162
+ See: http://rosettacode.org/wiki/Set_consolidation
163
+
164
+ The iterative python implementation posted there is
165
+ faster than this because of the overhead of building a
166
+ Graph and calling nx.connected_components, but it's not
167
+ clear for us if we can use it in NetworkX because there
168
+ is no licence for the code.
169
+
170
+ """
171
+ G = nx.Graph()
172
+ nodes = dict(enumerate(sets))
173
+ G.add_nodes_from(nodes)
174
+ G.add_edges_from(
175
+ (u, v) for u, v in combinations(nodes, 2) if len(nodes[u] & nodes[v]) >= k
176
+ )
177
+ for component in nx.connected_components(G):
178
+ yield set.union(*[nodes[n] for n in component])
179
+
180
+
181
+ def _generate_partition(G, cuts, k):
182
+ def has_nbrs_in_partition(G, node, partition):
183
+ return any(n in partition for n in G[node])
184
+
185
+ components = []
186
+ nodes = {n for n, d in G.degree() if d > k} - {n for cut in cuts for n in cut}
187
+ H = G.subgraph(nodes)
188
+ for cc in nx.connected_components(H):
189
+ component = set(cc)
190
+ for cut in cuts:
191
+ for node in cut:
192
+ if has_nbrs_in_partition(G, node, cc):
193
+ component.add(node)
194
+ if len(component) < G.order():
195
+ components.append(component)
196
+ yield from _consolidate(components, k + 1)
197
+
198
+
199
+ def _reconstruct_k_components(k_comps):
200
+ result = {}
201
+ max_k = max(k_comps)
202
+ for k in reversed(range(1, max_k + 1)):
203
+ if k == max_k:
204
+ result[k] = list(_consolidate(k_comps[k], k))
205
+ elif k not in k_comps:
206
+ result[k] = list(_consolidate(result[k + 1], k))
207
+ else:
208
+ nodes_at_k = set.union(*k_comps[k])
209
+ to_add = [c for c in result[k + 1] if any(n not in nodes_at_k for n in c)]
210
+ if to_add:
211
+ result[k] = list(_consolidate(k_comps[k] + to_add, k))
212
+ else:
213
+ result[k] = list(_consolidate(k_comps[k], k))
214
+ return result
215
+
216
+
217
+ def build_k_number_dict(kcomps):
218
+ result = {}
219
+ for k, comps in sorted(kcomps.items(), key=itemgetter(0)):
220
+ for comp in comps:
221
+ for node in comp:
222
+ result[node] = k
223
+ return result
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcutsets.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kanevsky all minimum node k cutsets algorithm.
3
+ """
4
+
5
+ import copy
6
+ from collections import defaultdict
7
+ from itertools import combinations
8
+ from operator import itemgetter
9
+
10
+ import networkx as nx
11
+ from networkx.algorithms.flow import (
12
+ build_residual_network,
13
+ edmonds_karp,
14
+ shortest_augmenting_path,
15
+ )
16
+
17
+ from .utils import build_auxiliary_node_connectivity
18
+
19
+ default_flow_func = edmonds_karp
20
+
21
+
22
+ __all__ = ["all_node_cuts"]
23
+
24
+
25
+ @nx._dispatchable
26
+ def all_node_cuts(G, k=None, flow_func=None):
27
+ r"""Returns all minimum k cutsets of an undirected graph G.
28
+
29
+ This implementation is based on Kanevsky's algorithm [1]_ for finding all
30
+ minimum-size node cut-sets of an undirected graph G; ie the set (or sets)
31
+ of nodes of cardinality equal to the node connectivity of G. Thus if
32
+ removed, would break G into two or more connected components.
33
+
34
+ Parameters
35
+ ----------
36
+ G : NetworkX graph
37
+ Undirected graph
38
+
39
+ k : Integer
40
+ Node connectivity of the input graph. If k is None, then it is
41
+ computed. Default value: None.
42
+
43
+ flow_func : function
44
+ Function to perform the underlying flow computations. Default value is
45
+ :func:`~networkx.algorithms.flow.edmonds_karp`. This function performs
46
+ better in sparse graphs with right tailed degree distributions.
47
+ :func:`~networkx.algorithms.flow.shortest_augmenting_path` will
48
+ perform better in denser graphs.
49
+
50
+
51
+ Returns
52
+ -------
53
+ cuts : a generator of node cutsets
54
+ Each node cutset has cardinality equal to the node connectivity of
55
+ the input graph.
56
+
57
+ Examples
58
+ --------
59
+ >>> # A two-dimensional grid graph has 4 cutsets of cardinality 2
60
+ >>> G = nx.grid_2d_graph(5, 5)
61
+ >>> cutsets = list(nx.all_node_cuts(G))
62
+ >>> len(cutsets)
63
+ 4
64
+ >>> all(2 == len(cutset) for cutset in cutsets)
65
+ True
66
+ >>> nx.node_connectivity(G)
67
+ 2
68
+
69
+ Notes
70
+ -----
71
+ This implementation is based on the sequential algorithm for finding all
72
+ minimum-size separating vertex sets in a graph [1]_. The main idea is to
73
+ compute minimum cuts using local maximum flow computations among a set
74
+ of nodes of highest degree and all other non-adjacent nodes in the Graph.
75
+ Once we find a minimum cut, we add an edge between the high degree
76
+ node and the target node of the local maximum flow computation to make
77
+ sure that we will not find that minimum cut again.
78
+
79
+ See also
80
+ --------
81
+ node_connectivity
82
+ edmonds_karp
83
+ shortest_augmenting_path
84
+
85
+ References
86
+ ----------
87
+ .. [1] Kanevsky, A. (1993). Finding all minimum-size separating vertex
88
+ sets in a graph. Networks 23(6), 533--541.
89
+ http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract
90
+
91
+ """
92
+ if not nx.is_connected(G):
93
+ raise nx.NetworkXError("Input graph is disconnected.")
94
+
95
+ # Address some corner cases first.
96
+ # For complete Graphs
97
+
98
+ if nx.density(G) == 1:
99
+ yield from ()
100
+ return
101
+
102
+ # Initialize data structures.
103
+ # Keep track of the cuts already computed so we do not repeat them.
104
+ seen = []
105
+ # Even-Tarjan reduction is what we call auxiliary digraph
106
+ # for node connectivity.
107
+ H = build_auxiliary_node_connectivity(G)
108
+ H_nodes = H.nodes # for speed
109
+ mapping = H.graph["mapping"]
110
+ # Keep a copy of original predecessors, H will be modified later.
111
+ # Shallow copy is enough.
112
+ original_H_pred = copy.copy(H._pred)
113
+ R = build_residual_network(H, "capacity")
114
+ kwargs = {"capacity": "capacity", "residual": R}
115
+ # Define default flow function
116
+ if flow_func is None:
117
+ flow_func = default_flow_func
118
+ if flow_func is shortest_augmenting_path:
119
+ kwargs["two_phase"] = True
120
+ # Begin the actual algorithm
121
+ # step 1: Find node connectivity k of G
122
+ if k is None:
123
+ k = nx.node_connectivity(G, flow_func=flow_func)
124
+ # step 2:
125
+ # Find k nodes with top degree, call it X:
126
+ X = {n for n, d in sorted(G.degree(), key=itemgetter(1), reverse=True)[:k]}
127
+ # Check if X is a k-node-cutset
128
+ if _is_separating_set(G, X):
129
+ seen.append(X)
130
+ yield X
131
+
132
+ for x in X:
133
+ # step 3: Compute local connectivity flow of x with all other
134
+ # non adjacent nodes in G
135
+ non_adjacent = set(G) - {x} - set(G[x])
136
+ for v in non_adjacent:
137
+ # step 4: compute maximum flow in an Even-Tarjan reduction H of G
138
+ # and step 5: build the associated residual network R
139
+ R = flow_func(H, f"{mapping[x]}B", f"{mapping[v]}A", **kwargs)
140
+ flow_value = R.graph["flow_value"]
141
+
142
+ if flow_value == k:
143
+ # Find the nodes incident to the flow.
144
+ E1 = flowed_edges = [
145
+ (u, w) for (u, w, d) in R.edges(data=True) if d["flow"] != 0
146
+ ]
147
+ VE1 = incident_nodes = {n for edge in E1 for n in edge}
148
+ # Remove saturated edges form the residual network.
149
+ # Note that reversed edges are introduced with capacity 0
150
+ # in the residual graph and they need to be removed too.
151
+ saturated_edges = [
152
+ (u, w, d)
153
+ for (u, w, d) in R.edges(data=True)
154
+ if d["capacity"] == d["flow"] or d["capacity"] == 0
155
+ ]
156
+ R.remove_edges_from(saturated_edges)
157
+ R_closure = nx.transitive_closure(R)
158
+ # step 6: shrink the strongly connected components of
159
+ # residual flow network R and call it L.
160
+ L = nx.condensation(R)
161
+ cmap = L.graph["mapping"]
162
+ inv_cmap = defaultdict(list)
163
+ for n, scc in cmap.items():
164
+ inv_cmap[scc].append(n)
165
+ # Find the incident nodes in the condensed graph.
166
+ VE1 = {cmap[n] for n in VE1}
167
+ # step 7: Compute all antichains of L;
168
+ # they map to closed sets in H.
169
+ # Any edge in H that links a closed set is part of a cutset.
170
+ for antichain in nx.antichains(L):
171
+ # Only antichains that are subsets of incident nodes counts.
172
+ # Lemma 8 in reference.
173
+ if not set(antichain).issubset(VE1):
174
+ continue
175
+ # Nodes in an antichain of the condensation graph of
176
+ # the residual network map to a closed set of nodes that
177
+ # define a node partition of the auxiliary digraph H
178
+ # through taking all of antichain's predecessors in the
179
+ # transitive closure.
180
+ S = set()
181
+ for scc in antichain:
182
+ S.update(inv_cmap[scc])
183
+ S_ancestors = set()
184
+ for n in S:
185
+ S_ancestors.update(R_closure._pred[n])
186
+ S.update(S_ancestors)
187
+ if f"{mapping[x]}B" not in S or f"{mapping[v]}A" in S:
188
+ continue
189
+ # Find the cutset that links the node partition (S,~S) in H
190
+ cutset = set()
191
+ for u in S:
192
+ cutset.update((u, w) for w in original_H_pred[u] if w not in S)
193
+ # The edges in H that form the cutset are internal edges
194
+ # (ie edges that represent a node of the original graph G)
195
+ if any(H_nodes[u]["id"] != H_nodes[w]["id"] for u, w in cutset):
196
+ continue
197
+ node_cut = {H_nodes[u]["id"] for u, _ in cutset}
198
+
199
+ if len(node_cut) == k:
200
+ # The cut is invalid if it includes internal edges of
201
+ # end nodes. The other half of Lemma 8 in ref.
202
+ if x in node_cut or v in node_cut:
203
+ continue
204
+ if node_cut not in seen:
205
+ yield node_cut
206
+ seen.append(node_cut)
207
+
208
+ # Add an edge (x, v) to make sure that we do not
209
+ # find this cutset again. This is equivalent
210
+ # of adding the edge in the input graph
211
+ # G.add_edge(x, v) and then regenerate H and R:
212
+ # Add edges to the auxiliary digraph.
213
+ # See build_residual_network for convention we used
214
+ # in residual graphs.
215
+ H.add_edge(f"{mapping[x]}B", f"{mapping[v]}A", capacity=1)
216
+ H.add_edge(f"{mapping[v]}B", f"{mapping[x]}A", capacity=1)
217
+ # Add edges to the residual network.
218
+ R.add_edge(f"{mapping[x]}B", f"{mapping[v]}A", capacity=1)
219
+ R.add_edge(f"{mapping[v]}A", f"{mapping[x]}B", capacity=0)
220
+ R.add_edge(f"{mapping[v]}B", f"{mapping[x]}A", capacity=1)
221
+ R.add_edge(f"{mapping[x]}A", f"{mapping[v]}B", capacity=0)
222
+
223
+ # Add again the saturated edges to reuse the residual network
224
+ R.add_edges_from(saturated_edges)
225
+
226
+
227
+ def _is_separating_set(G, cut):
228
+ """Assumes that the input graph is connected"""
229
+ if len(cut) == len(G) - 1:
230
+ return True
231
+
232
+ H = nx.restricted_view(G, cut, [])
233
+ if nx.is_connected(H):
234
+ return False
235
+ return True
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/stoerwagner.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stoer-Wagner minimum cut algorithm.
3
+ """
4
+
5
+ from itertools import islice
6
+
7
+ import networkx as nx
8
+
9
+ from ...utils import BinaryHeap, arbitrary_element, not_implemented_for
10
+
11
+ __all__ = ["stoer_wagner"]
12
+
13
+
14
+ @not_implemented_for("directed")
15
+ @not_implemented_for("multigraph")
16
+ @nx._dispatchable(edge_attrs="weight")
17
+ def stoer_wagner(G, weight="weight", heap=BinaryHeap):
18
+ r"""Returns the weighted minimum edge cut using the Stoer-Wagner algorithm.
19
+
20
+ Determine the minimum edge cut of a connected graph using the
21
+ Stoer-Wagner algorithm. In weighted cases, all weights must be
22
+ nonnegative.
23
+
24
+ The running time of the algorithm depends on the type of heaps used:
25
+
26
+ ============== =============================================
27
+ Type of heap Running time
28
+ ============== =============================================
29
+ Binary heap $O(n (m + n) \log n)$
30
+ Fibonacci heap $O(nm + n^2 \log n)$
31
+ Pairing heap $O(2^{2 \sqrt{\log \log n}} nm + n^2 \log n)$
32
+ ============== =============================================
33
+
34
+ Parameters
35
+ ----------
36
+ G : NetworkX graph
37
+ Edges of the graph are expected to have an attribute named by the
38
+ weight parameter below. If this attribute is not present, the edge is
39
+ considered to have unit weight.
40
+
41
+ weight : string
42
+ Name of the weight attribute of the edges. If the attribute is not
43
+ present, unit weight is assumed. Default value: 'weight'.
44
+
45
+ heap : class
46
+ Type of heap to be used in the algorithm. It should be a subclass of
47
+ :class:`MinHeap` or implement a compatible interface.
48
+
49
+ If a stock heap implementation is to be used, :class:`BinaryHeap` is
50
+ recommended over :class:`PairingHeap` for Python implementations without
51
+ optimized attribute accesses (e.g., CPython) despite a slower
52
+ asymptotic running time. For Python implementations with optimized
53
+ attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better
54
+ performance. Default value: :class:`BinaryHeap`.
55
+
56
+ Returns
57
+ -------
58
+ cut_value : integer or float
59
+ The sum of weights of edges in a minimum cut.
60
+
61
+ partition : pair of node lists
62
+ A partitioning of the nodes that defines a minimum cut.
63
+
64
+ Raises
65
+ ------
66
+ NetworkXNotImplemented
67
+ If the graph is directed or a multigraph.
68
+
69
+ NetworkXError
70
+ If the graph has less than two nodes, is not connected or has a
71
+ negative-weighted edge.
72
+
73
+ Examples
74
+ --------
75
+ >>> G = nx.Graph()
76
+ >>> G.add_edge("x", "a", weight=3)
77
+ >>> G.add_edge("x", "b", weight=1)
78
+ >>> G.add_edge("a", "c", weight=3)
79
+ >>> G.add_edge("b", "c", weight=5)
80
+ >>> G.add_edge("b", "d", weight=4)
81
+ >>> G.add_edge("d", "e", weight=2)
82
+ >>> G.add_edge("c", "y", weight=2)
83
+ >>> G.add_edge("e", "y", weight=3)
84
+ >>> cut_value, partition = nx.stoer_wagner(G)
85
+ >>> cut_value
86
+ 4
87
+ """
88
+ n = len(G)
89
+ if n < 2:
90
+ raise nx.NetworkXError("graph has less than two nodes.")
91
+ if not nx.is_connected(G):
92
+ raise nx.NetworkXError("graph is not connected.")
93
+
94
+ # Make a copy of the graph for internal use.
95
+ G = nx.Graph(
96
+ (u, v, {"weight": e.get(weight, 1)}) for u, v, e in G.edges(data=True) if u != v
97
+ )
98
+ G.__networkx_cache__ = None # Disable caching
99
+
100
+ for u, v, e in G.edges(data=True):
101
+ if e["weight"] < 0:
102
+ raise nx.NetworkXError("graph has a negative-weighted edge.")
103
+
104
+ cut_value = float("inf")
105
+ nodes = set(G)
106
+ contractions = [] # contracted node pairs
107
+
108
+ # Repeatedly pick a pair of nodes to contract until only one node is left.
109
+ for i in range(n - 1):
110
+ # Pick an arbitrary node u and create a set A = {u}.
111
+ u = arbitrary_element(G)
112
+ A = {u}
113
+ # Repeatedly pick the node "most tightly connected" to A and add it to
114
+ # A. The tightness of connectivity of a node not in A is defined by the
115
+ # of edges connecting it to nodes in A.
116
+ h = heap() # min-heap emulating a max-heap
117
+ for v, e in G[u].items():
118
+ h.insert(v, -e["weight"])
119
+ # Repeat until all but one node has been added to A.
120
+ for j in range(n - i - 2):
121
+ u = h.pop()[0]
122
+ A.add(u)
123
+ for v, e in G[u].items():
124
+ if v not in A:
125
+ h.insert(v, h.get(v, 0) - e["weight"])
126
+ # A and the remaining node v define a "cut of the phase". There is a
127
+ # minimum cut of the original graph that is also a cut of the phase.
128
+ # Due to contractions in earlier phases, v may in fact represent
129
+ # multiple nodes in the original graph.
130
+ v, w = h.min()
131
+ w = -w
132
+ if w < cut_value:
133
+ cut_value = w
134
+ best_phase = i
135
+ # Contract v and the last node added to A.
136
+ contractions.append((u, v))
137
+ for w, e in G[v].items():
138
+ if w != u:
139
+ if w not in G[u]:
140
+ G.add_edge(u, w, weight=e["weight"])
141
+ else:
142
+ G[u][w]["weight"] += e["weight"]
143
+ G.remove_node(v)
144
+
145
+ # Recover the optimal partitioning from the contractions.
146
+ G = nx.Graph(islice(contractions, best_phase))
147
+ v = contractions[best_phase][1]
148
+ G.add_node(v)
149
+ reachable = set(nx.single_source_shortest_path_length(G, v))
150
+ partition = (list(reachable), list(nodes - reachable))
151
+
152
+ return cut_value, partition
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/connectivity/utils.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities for connectivity package
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["build_auxiliary_node_connectivity", "build_auxiliary_edge_connectivity"]
8
+
9
+
10
+ @nx._dispatchable(returns_graph=True)
11
+ def build_auxiliary_node_connectivity(G):
12
+ r"""Creates a directed graph D from an undirected graph G to compute flow
13
+ based node connectivity.
14
+
15
+ For an undirected graph G having `n` nodes and `m` edges we derive a
16
+ directed graph D with `2n` nodes and `2m+n` arcs by replacing each
17
+ original node `v` with two nodes `vA`, `vB` linked by an (internal)
18
+ arc in D. Then for each edge (`u`, `v`) in G we add two arcs (`uB`, `vA`)
19
+ and (`vB`, `uA`) in D. Finally we set the attribute capacity = 1 for each
20
+ arc in D [1]_.
21
+
22
+ For a directed graph having `n` nodes and `m` arcs we derive a
23
+ directed graph D with `2n` nodes and `m+n` arcs by replacing each
24
+ original node `v` with two nodes `vA`, `vB` linked by an (internal)
25
+ arc (`vA`, `vB`) in D. Then for each arc (`u`, `v`) in G we add one
26
+ arc (`uB`, `vA`) in D. Finally we set the attribute capacity = 1 for
27
+ each arc in D.
28
+
29
+ A dictionary with a mapping between nodes in the original graph and the
30
+ auxiliary digraph is stored as a graph attribute: D.graph['mapping'].
31
+
32
+ References
33
+ ----------
34
+ .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
35
+ Erlebach, 'Network Analysis: Methodological Foundations', Lecture
36
+ Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
37
+ https://doi.org/10.1007/978-3-540-31955-9_7
38
+
39
+ """
40
+ directed = G.is_directed()
41
+
42
+ mapping = {}
43
+ H = nx.DiGraph()
44
+
45
+ for i, node in enumerate(G):
46
+ mapping[node] = i
47
+ H.add_node(f"{i}A", id=node)
48
+ H.add_node(f"{i}B", id=node)
49
+ H.add_edge(f"{i}A", f"{i}B", capacity=1)
50
+
51
+ edges = []
52
+ for source, target in G.edges():
53
+ edges.append((f"{mapping[source]}B", f"{mapping[target]}A"))
54
+ if not directed:
55
+ edges.append((f"{mapping[target]}B", f"{mapping[source]}A"))
56
+ H.add_edges_from(edges, capacity=1)
57
+
58
+ # Store mapping as graph attribute
59
+ H.graph["mapping"] = mapping
60
+ return H
61
+
62
+
63
+ @nx._dispatchable(returns_graph=True)
64
+ def build_auxiliary_edge_connectivity(G):
65
+ """Auxiliary digraph for computing flow based edge connectivity
66
+
67
+ If the input graph is undirected, we replace each edge (`u`,`v`) with
68
+ two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
69
+ 'capacity' for each arc to 1. If the input graph is directed we simply
70
+ add the 'capacity' attribute. Part of algorithm 1 in [1]_ .
71
+
72
+ References
73
+ ----------
74
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. (this is a
75
+ chapter, look for the reference of the book).
76
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
77
+ """
78
+ if G.is_directed():
79
+ H = nx.DiGraph()
80
+ H.add_nodes_from(G.nodes())
81
+ H.add_edges_from(G.edges(), capacity=1)
82
+ return H
83
+ else:
84
+ H = nx.DiGraph()
85
+ H.add_nodes_from(G.nodes())
86
+ for source, target in G.edges():
87
+ H.add_edges_from([(source, target), (target, source)], capacity=1)
88
+ return H
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc ADDED
Binary file (29.9 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc ADDED
Binary file (25.6 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc ADDED
Binary file (38.9 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc ADDED
Binary file (4.26 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc ADDED
Binary file (3.85 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc ADDED
Binary file (4.13 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc ADDED
Binary file (40.2 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc ADDED
Binary file (26.4 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73fc416df0164923607751cb759f4ae81deb5f6550bf25be59c86de3b747e41d
3
+ size 8887
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/classic.py ADDED
@@ -0,0 +1,1068 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for some classic graphs.
2
+
3
+ The typical graph builder function is called as follows:
4
+
5
+ >>> G = nx.complete_graph(100)
6
+
7
+ returning the complete graph on n nodes labeled 0, .., 99
8
+ as a simple graph. Except for `empty_graph`, all the functions
9
+ in this module return a Graph class (i.e. a simple, undirected graph).
10
+
11
+ """
12
+
13
+ import itertools
14
+ import numbers
15
+
16
+ import networkx as nx
17
+ from networkx.classes import Graph
18
+ from networkx.exception import NetworkXError
19
+ from networkx.utils import nodes_or_number, pairwise
20
+
21
+ __all__ = [
22
+ "balanced_tree",
23
+ "barbell_graph",
24
+ "binomial_tree",
25
+ "complete_graph",
26
+ "complete_multipartite_graph",
27
+ "circular_ladder_graph",
28
+ "circulant_graph",
29
+ "cycle_graph",
30
+ "dorogovtsev_goltsev_mendes_graph",
31
+ "empty_graph",
32
+ "full_rary_tree",
33
+ "kneser_graph",
34
+ "ladder_graph",
35
+ "lollipop_graph",
36
+ "null_graph",
37
+ "path_graph",
38
+ "star_graph",
39
+ "tadpole_graph",
40
+ "trivial_graph",
41
+ "turan_graph",
42
+ "wheel_graph",
43
+ ]
44
+
45
+
46
+ # -------------------------------------------------------------------
47
+ # Some Classic Graphs
48
+ # -------------------------------------------------------------------
49
+
50
+
51
+ def _tree_edges(n, r):
52
+ if n == 0:
53
+ return
54
+ # helper function for trees
55
+ # yields edges in rooted tree at 0 with n nodes and branching ratio r
56
+ nodes = iter(range(n))
57
+ parents = [next(nodes)] # stack of max length r
58
+ while parents:
59
+ source = parents.pop(0)
60
+ for i in range(r):
61
+ try:
62
+ target = next(nodes)
63
+ parents.append(target)
64
+ yield source, target
65
+ except StopIteration:
66
+ break
67
+
68
+
69
+ @nx._dispatchable(graphs=None, returns_graph=True)
70
+ def full_rary_tree(r, n, create_using=None):
71
+ """Creates a full r-ary tree of `n` nodes.
72
+
73
+ Sometimes called a k-ary, n-ary, or m-ary tree.
74
+ "... all non-leaf nodes have exactly r children and all levels
75
+ are full except for some rightmost position of the bottom level
76
+ (if a leaf at the bottom level is missing, then so are all of the
77
+ leaves to its right." [1]_
78
+
79
+ .. plot::
80
+
81
+ >>> nx.draw(nx.full_rary_tree(2, 10))
82
+
83
+ Parameters
84
+ ----------
85
+ r : int
86
+ branching factor of the tree
87
+ n : int
88
+ Number of nodes in the tree
89
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
90
+ Graph type to create. If graph instance, then cleared before populated.
91
+
92
+ Returns
93
+ -------
94
+ G : networkx Graph
95
+ An r-ary tree with n nodes
96
+
97
+ References
98
+ ----------
99
+ .. [1] An introduction to data structures and algorithms,
100
+ James Andrew Storer, Birkhauser Boston 2001, (page 225).
101
+ """
102
+ G = empty_graph(n, create_using)
103
+ G.add_edges_from(_tree_edges(n, r))
104
+ return G
105
+
106
+
107
+ @nx._dispatchable(graphs=None, returns_graph=True)
108
+ def kneser_graph(n, k):
109
+ """Returns the Kneser Graph with parameters `n` and `k`.
110
+
111
+ The Kneser Graph has nodes that are k-tuples (subsets) of the integers
112
+ between 0 and ``n-1``. Nodes are adjacent if their corresponding sets are disjoint.
113
+
114
+ Parameters
115
+ ----------
116
+ n: int
117
+ Number of integers from which to make node subsets.
118
+ Subsets are drawn from ``set(range(n))``.
119
+ k: int
120
+ Size of the subsets.
121
+
122
+ Returns
123
+ -------
124
+ G : NetworkX Graph
125
+
126
+ Examples
127
+ --------
128
+ >>> G = nx.kneser_graph(5, 2)
129
+ >>> G.number_of_nodes()
130
+ 10
131
+ >>> G.number_of_edges()
132
+ 15
133
+ >>> nx.is_isomorphic(G, nx.petersen_graph())
134
+ True
135
+ """
136
+ if n <= 0:
137
+ raise NetworkXError("n should be greater than zero")
138
+ if k <= 0 or k > n:
139
+ raise NetworkXError("k should be greater than zero and smaller than n")
140
+
141
+ G = nx.Graph()
142
+ # Create all k-subsets of [0, 1, ..., n-1]
143
+ subsets = list(itertools.combinations(range(n), k))
144
+
145
+ if 2 * k > n:
146
+ G.add_nodes_from(subsets)
147
+
148
+ universe = set(range(n))
149
+ comb = itertools.combinations # only to make it all fit on one line
150
+ G.add_edges_from((s, t) for s in subsets for t in comb(universe - set(s), k))
151
+ return G
152
+
153
+
154
+ @nx._dispatchable(graphs=None, returns_graph=True)
155
+ def balanced_tree(r, h, create_using=None):
156
+ """Returns the perfectly balanced `r`-ary tree of height `h`.
157
+
158
+ .. plot::
159
+
160
+ >>> nx.draw(nx.balanced_tree(2, 3))
161
+
162
+ Parameters
163
+ ----------
164
+ r : int
165
+ Branching factor of the tree; each node will have `r`
166
+ children.
167
+
168
+ h : int
169
+ Height of the tree.
170
+
171
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
172
+ Graph type to create. If graph instance, then cleared before populated.
173
+
174
+ Returns
175
+ -------
176
+ G : NetworkX graph
177
+ A balanced `r`-ary tree of height `h`.
178
+
179
+ Notes
180
+ -----
181
+ This is the rooted tree where all leaves are at distance `h` from
182
+ the root. The root has degree `r` and all other internal nodes
183
+ have degree `r + 1`.
184
+
185
+ Node labels are integers, starting from zero.
186
+
187
+ A balanced tree is also known as a *complete r-ary tree*.
188
+
189
+ """
190
+ # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
191
+ # which is computed by using the closed-form formula for a geometric
192
+ # sum with ratio `r`. In the special case that `r` is 1, the number
193
+ # of nodes is simply `h + 1` (since the tree is actually a path
194
+ # graph).
195
+ if r == 1:
196
+ n = h + 1
197
+ else:
198
+ # This must be an integer if both `r` and `h` are integers. If
199
+ # they are not, we force integer division anyway.
200
+ n = (1 - r ** (h + 1)) // (1 - r)
201
+ return full_rary_tree(r, n, create_using=create_using)
202
+
203
+
204
+ @nx._dispatchable(graphs=None, returns_graph=True)
205
+ def barbell_graph(m1, m2, create_using=None):
206
+ """Returns the Barbell Graph: two complete graphs connected by a path.
207
+
208
+ .. plot::
209
+
210
+ >>> nx.draw(nx.barbell_graph(4, 2))
211
+
212
+ Parameters
213
+ ----------
214
+ m1 : int
215
+ Size of the left and right barbells, must be greater than 2.
216
+
217
+ m2 : int
218
+ Length of the path connecting the barbells.
219
+
220
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
221
+ Graph type to create. If graph instance, then cleared before populated.
222
+ Only undirected Graphs are supported.
223
+
224
+ Returns
225
+ -------
226
+ G : NetworkX graph
227
+ A barbell graph.
228
+
229
+ Notes
230
+ -----
231
+
232
+
233
+ Two identical complete graphs $K_{m1}$ form the left and right bells,
234
+ and are connected by a path $P_{m2}$.
235
+
236
+ The `2*m1+m2` nodes are numbered
237
+ `0, ..., m1-1` for the left barbell,
238
+ `m1, ..., m1+m2-1` for the path,
239
+ and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
240
+
241
+ The 3 subgraphs are joined via the edges `(m1-1, m1)` and
242
+ `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
243
+ graphs joined together.
244
+
245
+ This graph is an extremal example in David Aldous
246
+ and Jim Fill's e-text on Random Walks on Graphs.
247
+
248
+ """
249
+ if m1 < 2:
250
+ raise NetworkXError("Invalid graph description, m1 should be >=2")
251
+ if m2 < 0:
252
+ raise NetworkXError("Invalid graph description, m2 should be >=0")
253
+
254
+ # left barbell
255
+ G = complete_graph(m1, create_using)
256
+ if G.is_directed():
257
+ raise NetworkXError("Directed Graph not supported")
258
+
259
+ # connecting path
260
+ G.add_nodes_from(range(m1, m1 + m2 - 1))
261
+ if m2 > 1:
262
+ G.add_edges_from(pairwise(range(m1, m1 + m2)))
263
+
264
+ # right barbell
265
+ G.add_edges_from(
266
+ (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
267
+ )
268
+
269
+ # connect it up
270
+ G.add_edge(m1 - 1, m1)
271
+ if m2 > 0:
272
+ G.add_edge(m1 + m2 - 1, m1 + m2)
273
+
274
+ return G
275
+
276
+
277
+ @nx._dispatchable(graphs=None, returns_graph=True)
278
+ def binomial_tree(n, create_using=None):
279
+ """Returns the Binomial Tree of order n.
280
+
281
+ The binomial tree of order 0 consists of a single node. A binomial tree of order k
282
+ is defined recursively by linking two binomial trees of order k-1: the root of one is
283
+ the leftmost child of the root of the other.
284
+
285
+ .. plot::
286
+
287
+ >>> nx.draw(nx.binomial_tree(3))
288
+
289
+ Parameters
290
+ ----------
291
+ n : int
292
+ Order of the binomial tree.
293
+
294
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
295
+ Graph type to create. If graph instance, then cleared before populated.
296
+
297
+ Returns
298
+ -------
299
+ G : NetworkX graph
300
+ A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
301
+
302
+ """
303
+ G = nx.empty_graph(1, create_using)
304
+
305
+ N = 1
306
+ for i in range(n):
307
+ # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
308
+ edges = [(u + N, v + N) for (u, v) in G.edges()]
309
+ G.add_edges_from(edges)
310
+ G.add_edge(0, N)
311
+ N *= 2
312
+ return G
313
+
314
+
315
+ @nx._dispatchable(graphs=None, returns_graph=True)
316
+ @nodes_or_number(0)
317
+ def complete_graph(n, create_using=None):
318
+ """Return the complete graph `K_n` with n nodes.
319
+
320
+ A complete graph on `n` nodes means that all pairs
321
+ of distinct nodes have an edge connecting them.
322
+
323
+ .. plot::
324
+
325
+ >>> nx.draw(nx.complete_graph(5))
326
+
327
+ Parameters
328
+ ----------
329
+ n : int or iterable container of nodes
330
+ If n is an integer, nodes are from range(n).
331
+ If n is a container of nodes, those nodes appear in the graph.
332
+ Warning: n is not checked for duplicates and if present the
333
+ resulting graph may not be as desired. Make sure you have no duplicates.
334
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
335
+ Graph type to create. If graph instance, then cleared before populated.
336
+
337
+ Examples
338
+ --------
339
+ >>> G = nx.complete_graph(9)
340
+ >>> len(G)
341
+ 9
342
+ >>> G.size()
343
+ 36
344
+ >>> G = nx.complete_graph(range(11, 14))
345
+ >>> list(G.nodes())
346
+ [11, 12, 13]
347
+ >>> G = nx.complete_graph(4, nx.DiGraph())
348
+ >>> G.is_directed()
349
+ True
350
+
351
+ """
352
+ _, nodes = n
353
+ G = empty_graph(nodes, create_using)
354
+ if len(nodes) > 1:
355
+ if G.is_directed():
356
+ edges = itertools.permutations(nodes, 2)
357
+ else:
358
+ edges = itertools.combinations(nodes, 2)
359
+ G.add_edges_from(edges)
360
+ return G
361
+
362
+
363
+ @nx._dispatchable(graphs=None, returns_graph=True)
364
+ def circular_ladder_graph(n, create_using=None):
365
+ """Returns the circular ladder graph $CL_n$ of length n.
366
+
367
+ $CL_n$ consists of two concentric n-cycles in which
368
+ each of the n pairs of concentric nodes are joined by an edge.
369
+
370
+ Node labels are the integers 0 to n-1
371
+
372
+ .. plot::
373
+
374
+ >>> nx.draw(nx.circular_ladder_graph(5))
375
+
376
+ """
377
+ G = ladder_graph(n, create_using)
378
+ G.add_edge(0, n - 1)
379
+ G.add_edge(n, 2 * n - 1)
380
+ return G
381
+
382
+
383
+ @nx._dispatchable(graphs=None, returns_graph=True)
384
+ def circulant_graph(n, offsets, create_using=None):
385
+ r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
386
+
387
+ The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
388
+ such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
389
+ for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
390
+
391
+ .. plot::
392
+
393
+ >>> nx.draw(nx.circulant_graph(10, [1]))
394
+
395
+ Parameters
396
+ ----------
397
+ n : integer
398
+ The number of nodes in the graph.
399
+ offsets : list of integers
400
+ A list of node offsets, $x_1$ up to $x_m$, as described above.
401
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
402
+ Graph type to create. If graph instance, then cleared before populated.
403
+
404
+ Returns
405
+ -------
406
+ NetworkX Graph of type create_using
407
+
408
+ Examples
409
+ --------
410
+ Many well-known graph families are subfamilies of the circulant graphs;
411
+ for example, to create the cycle graph on n points, we connect every
412
+ node to nodes on either side (with offset plus or minus one). For n = 10,
413
+
414
+ >>> G = nx.circulant_graph(10, [1])
415
+ >>> edges = [
416
+ ... (0, 9),
417
+ ... (0, 1),
418
+ ... (1, 2),
419
+ ... (2, 3),
420
+ ... (3, 4),
421
+ ... (4, 5),
422
+ ... (5, 6),
423
+ ... (6, 7),
424
+ ... (7, 8),
425
+ ... (8, 9),
426
+ ... ]
427
+ >>> sorted(edges) == sorted(G.edges())
428
+ True
429
+
430
+ Similarly, we can create the complete graph
431
+ on 5 points with the set of offsets [1, 2]:
432
+
433
+ >>> G = nx.circulant_graph(5, [1, 2])
434
+ >>> edges = [
435
+ ... (0, 1),
436
+ ... (0, 2),
437
+ ... (0, 3),
438
+ ... (0, 4),
439
+ ... (1, 2),
440
+ ... (1, 3),
441
+ ... (1, 4),
442
+ ... (2, 3),
443
+ ... (2, 4),
444
+ ... (3, 4),
445
+ ... ]
446
+ >>> sorted(edges) == sorted(G.edges())
447
+ True
448
+
449
+ """
450
+ G = empty_graph(n, create_using)
451
+ for i in range(n):
452
+ for j in offsets:
453
+ G.add_edge(i, (i - j) % n)
454
+ G.add_edge(i, (i + j) % n)
455
+ return G
456
+
457
+
458
+ @nx._dispatchable(graphs=None, returns_graph=True)
459
+ @nodes_or_number(0)
460
+ def cycle_graph(n, create_using=None):
461
+ """Returns the cycle graph $C_n$ of cyclically connected nodes.
462
+
463
+ $C_n$ is a path with its two end-nodes connected.
464
+
465
+ .. plot::
466
+
467
+ >>> nx.draw(nx.cycle_graph(5))
468
+
469
+ Parameters
470
+ ----------
471
+ n : int or iterable container of nodes
472
+ If n is an integer, nodes are from `range(n)`.
473
+ If n is a container of nodes, those nodes appear in the graph.
474
+ Warning: n is not checked for duplicates and if present the
475
+ resulting graph may not be as desired. Make sure you have no duplicates.
476
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
477
+ Graph type to create. If graph instance, then cleared before populated.
478
+
479
+ Notes
480
+ -----
481
+ If create_using is directed, the direction is in increasing order.
482
+
483
+ """
484
+ _, nodes = n
485
+ G = empty_graph(nodes, create_using)
486
+ G.add_edges_from(pairwise(nodes, cyclic=True))
487
+ return G
488
+
489
+
490
+ @nx._dispatchable(graphs=None, returns_graph=True)
491
+ def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
492
+ """Returns the hierarchically constructed Dorogovtsev--Goltsev--Mendes graph.
493
+
494
+ The Dorogovtsev--Goltsev--Mendes [1]_ procedure deterministically produces a
495
+ scale-free graph with ``3/2 * (3**(n-1) + 1)`` nodes
496
+ and ``3**n`` edges for a given `n`.
497
+
498
+ Note that `n` denotes the number of times the state transition is applied,
499
+ starting from the base graph with ``n = 0`` (no transitions), as in [2]_.
500
+ This is different from the parameter ``t = n - 1`` in [1]_.
501
+
502
+ .. plot::
503
+
504
+ >>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
505
+
506
+ Parameters
507
+ ----------
508
+ n : integer
509
+ The generation number.
510
+
511
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
512
+ Graph type to create. Directed graphs and multigraphs are not supported.
513
+
514
+ Returns
515
+ -------
516
+ G : NetworkX `Graph`
517
+
518
+ Raises
519
+ ------
520
+ NetworkXError
521
+ If `n` is less than zero.
522
+
523
+ If `create_using` is a directed graph or multigraph.
524
+
525
+ Examples
526
+ --------
527
+ >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
528
+ >>> G.number_of_nodes()
529
+ 15
530
+ >>> G.number_of_edges()
531
+ 27
532
+ >>> nx.is_planar(G)
533
+ True
534
+
535
+ References
536
+ ----------
537
+ .. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
538
+ "Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
539
+ https://arxiv.org/pdf/cond-mat/0112143.pdf
540
+ .. [2] Weisstein, Eric W. "Dorogovtsev--Goltsev--Mendes Graph".
541
+ From MathWorld--A Wolfram Web Resource.
542
+ https://mathworld.wolfram.com/Dorogovtsev-Goltsev-MendesGraph.html
543
+ """
544
+ if n < 0:
545
+ raise NetworkXError("n must be greater than or equal to 0")
546
+
547
+ G = empty_graph(0, create_using)
548
+ if G.is_directed():
549
+ raise NetworkXError("directed graph not supported")
550
+ if G.is_multigraph():
551
+ raise NetworkXError("multigraph not supported")
552
+
553
+ G.add_edge(0, 1)
554
+ new_node = 2 # next node to be added
555
+ for _ in range(n): # iterate over number of generations.
556
+ new_edges = []
557
+ for u, v in G.edges():
558
+ new_edges.append((u, new_node))
559
+ new_edges.append((v, new_node))
560
+ new_node += 1
561
+
562
+ G.add_edges_from(new_edges)
563
+ return G
564
+
565
+
566
+ @nx._dispatchable(graphs=None, returns_graph=True)
567
+ @nodes_or_number(0)
568
+ def empty_graph(n=0, create_using=None, default=Graph):
569
+ """Returns the empty graph with n nodes and zero edges.
570
+
571
+ .. plot::
572
+
573
+ >>> nx.draw(nx.empty_graph(5))
574
+
575
+ Parameters
576
+ ----------
577
+ n : int or iterable container of nodes (default = 0)
578
+ If n is an integer, nodes are from `range(n)`.
579
+ If n is a container of nodes, those nodes appear in the graph.
580
+ create_using : Graph Instance, Constructor or None
581
+ Indicator of type of graph to return.
582
+ If a Graph-type instance, then clear and use it.
583
+ If None, use the `default` constructor.
584
+ If a constructor, call it to create an empty graph.
585
+ default : Graph constructor (optional, default = nx.Graph)
586
+ The constructor to use if create_using is None.
587
+ If None, then nx.Graph is used.
588
+ This is used when passing an unknown `create_using` value
589
+ through your home-grown function to `empty_graph` and
590
+ you want a default constructor other than nx.Graph.
591
+
592
+ Examples
593
+ --------
594
+ >>> G = nx.empty_graph(10)
595
+ >>> G.number_of_nodes()
596
+ 10
597
+ >>> G.number_of_edges()
598
+ 0
599
+ >>> G = nx.empty_graph("ABC")
600
+ >>> G.number_of_nodes()
601
+ 3
602
+ >>> sorted(G)
603
+ ['A', 'B', 'C']
604
+
605
+ Notes
606
+ -----
607
+ The variable create_using should be a Graph Constructor or a
608
+ "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
609
+ will be used to create the returned graph. "graph"-like objects
610
+ will be cleared (nodes and edges will be removed) and refitted as
611
+ an empty "graph" with nodes specified in n. This capability
612
+ is useful for specifying the class-nature of the resulting empty
613
+ "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
614
+
615
+ The variable create_using has three main uses:
616
+ Firstly, the variable create_using can be used to create an
617
+ empty digraph, multigraph, etc. For example,
618
+
619
+ >>> n = 10
620
+ >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
621
+
622
+ will create an empty digraph on n nodes.
623
+
624
+ Secondly, one can pass an existing graph (digraph, multigraph,
625
+ etc.) via create_using. For example, if G is an existing graph
626
+ (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
627
+ will empty G (i.e. delete all nodes and edges using G.clear())
628
+ and then add n nodes and zero edges, and return the modified graph.
629
+
630
+ Thirdly, when constructing your home-grown graph creation function
631
+ you can use empty_graph to construct the graph by passing a user
632
+ defined create_using to empty_graph. In this case, if you want the
633
+ default constructor to be other than nx.Graph, specify `default`.
634
+
635
+ >>> def mygraph(n, create_using=None):
636
+ ... G = nx.empty_graph(n, create_using, nx.MultiGraph)
637
+ ... G.add_edges_from([(0, 1), (0, 1)])
638
+ ... return G
639
+ >>> G = mygraph(3)
640
+ >>> G.is_multigraph()
641
+ True
642
+ >>> G = mygraph(3, nx.Graph)
643
+ >>> G.is_multigraph()
644
+ False
645
+
646
+ See also create_empty_copy(G).
647
+
648
+ """
649
+ if create_using is None:
650
+ G = default()
651
+ elif isinstance(create_using, type):
652
+ G = create_using()
653
+ elif not hasattr(create_using, "adj"):
654
+ raise TypeError("create_using is not a valid NetworkX graph type or instance")
655
+ else:
656
+ # create_using is a NetworkX style Graph
657
+ create_using.clear()
658
+ G = create_using
659
+
660
+ _, nodes = n
661
+ G.add_nodes_from(nodes)
662
+ return G
663
+
664
+
665
+ @nx._dispatchable(graphs=None, returns_graph=True)
666
+ def ladder_graph(n, create_using=None):
667
+ """Returns the Ladder graph of length n.
668
+
669
+ This is two paths of n nodes, with
670
+ each pair connected by a single edge.
671
+
672
+ Node labels are the integers 0 to 2*n - 1.
673
+
674
+ .. plot::
675
+
676
+ >>> nx.draw(nx.ladder_graph(5))
677
+
678
+ """
679
+ G = empty_graph(2 * n, create_using)
680
+ if G.is_directed():
681
+ raise NetworkXError("Directed Graph not supported")
682
+ G.add_edges_from(pairwise(range(n)))
683
+ G.add_edges_from(pairwise(range(n, 2 * n)))
684
+ G.add_edges_from((v, v + n) for v in range(n))
685
+ return G
686
+
687
+
688
+ @nx._dispatchable(graphs=None, returns_graph=True)
689
+ @nodes_or_number([0, 1])
690
+ def lollipop_graph(m, n, create_using=None):
691
+ """Returns the Lollipop Graph; ``K_m`` connected to ``P_n``.
692
+
693
+ This is the Barbell Graph without the right barbell.
694
+
695
+ .. plot::
696
+
697
+ >>> nx.draw(nx.lollipop_graph(3, 4))
698
+
699
+ Parameters
700
+ ----------
701
+ m, n : int or iterable container of nodes
702
+ If an integer, nodes are from ``range(m)`` and ``range(m, m+n)``.
703
+ If a container of nodes, those nodes appear in the graph.
704
+ Warning: `m` and `n` are not checked for duplicates and if present the
705
+ resulting graph may not be as desired. Make sure you have no duplicates.
706
+
707
+ The nodes for `m` appear in the complete graph $K_m$ and the nodes
708
+ for `n` appear in the path $P_n$
709
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
710
+ Graph type to create. If graph instance, then cleared before populated.
711
+
712
+ Returns
713
+ -------
714
+ Networkx graph
715
+ A complete graph with `m` nodes connected to a path of length `n`.
716
+
717
+ Notes
718
+ -----
719
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
720
+ If ``n=0``, this is merely a complete graph.
721
+
722
+ (This graph is an extremal example in David Aldous and Jim
723
+ Fill's etext on Random Walks on Graphs.)
724
+
725
+ """
726
+ m, m_nodes = m
727
+ M = len(m_nodes)
728
+ if M < 2:
729
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
730
+
731
+ n, n_nodes = n
732
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
733
+ n_nodes = list(range(M, M + n))
734
+ N = len(n_nodes)
735
+
736
+ # the ball
737
+ G = complete_graph(m_nodes, create_using)
738
+ if G.is_directed():
739
+ raise NetworkXError("Directed Graph not supported")
740
+
741
+ # the stick
742
+ G.add_nodes_from(n_nodes)
743
+ if N > 1:
744
+ G.add_edges_from(pairwise(n_nodes))
745
+
746
+ if len(G) != M + N:
747
+ raise NetworkXError("Nodes must be distinct in containers m and n")
748
+
749
+ # connect ball to stick
750
+ if M > 0 and N > 0:
751
+ G.add_edge(m_nodes[-1], n_nodes[0])
752
+ return G
753
+
754
+
755
+ @nx._dispatchable(graphs=None, returns_graph=True)
756
+ def null_graph(create_using=None):
757
+ """Returns the Null graph with no nodes or edges.
758
+
759
+ See empty_graph for the use of create_using.
760
+
761
+ """
762
+ G = empty_graph(0, create_using)
763
+ return G
764
+
765
+
766
+ @nx._dispatchable(graphs=None, returns_graph=True)
767
+ @nodes_or_number(0)
768
+ def path_graph(n, create_using=None):
769
+ """Returns the Path graph `P_n` of linearly connected nodes.
770
+
771
+ .. plot::
772
+
773
+ >>> nx.draw(nx.path_graph(5))
774
+
775
+ Parameters
776
+ ----------
777
+ n : int or iterable
778
+ If an integer, nodes are 0 to n - 1.
779
+ If an iterable of nodes, in the order they appear in the path.
780
+ Warning: n is not checked for duplicates and if present the
781
+ resulting graph may not be as desired. Make sure you have no duplicates.
782
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
783
+ Graph type to create. If graph instance, then cleared before populated.
784
+
785
+ """
786
+ _, nodes = n
787
+ G = empty_graph(nodes, create_using)
788
+ G.add_edges_from(pairwise(nodes))
789
+ return G
790
+
791
+
792
+ @nx._dispatchable(graphs=None, returns_graph=True)
793
+ @nodes_or_number(0)
794
+ def star_graph(n, create_using=None):
795
+ """Return the star graph
796
+
797
+ The star graph consists of one center node connected to n outer nodes.
798
+
799
+ .. plot::
800
+
801
+ >>> nx.draw(nx.star_graph(6))
802
+
803
+ Parameters
804
+ ----------
805
+ n : int or iterable
806
+ If an integer, node labels are 0 to n with center 0.
807
+ If an iterable of nodes, the center is the first.
808
+ Warning: n is not checked for duplicates and if present the
809
+ resulting graph may not be as desired. Make sure you have no duplicates.
810
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
811
+ Graph type to create. If graph instance, then cleared before populated.
812
+
813
+ Notes
814
+ -----
815
+ The graph has n+1 nodes for integer n.
816
+ So star_graph(3) is the same as star_graph(range(4)).
817
+ """
818
+ n, nodes = n
819
+ if isinstance(n, numbers.Integral):
820
+ nodes.append(int(n)) # there should be n+1 nodes
821
+ G = empty_graph(nodes, create_using)
822
+ if G.is_directed():
823
+ raise NetworkXError("Directed Graph not supported")
824
+
825
+ if len(nodes) > 1:
826
+ hub, *spokes = nodes
827
+ G.add_edges_from((hub, node) for node in spokes)
828
+ return G
829
+
830
+
831
+ @nx._dispatchable(graphs=None, returns_graph=True)
832
+ @nodes_or_number([0, 1])
833
+ def tadpole_graph(m, n, create_using=None):
834
+ """Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``.
835
+
836
+ This graph on m+n nodes connects a cycle of size `m` to a path of length `n`.
837
+ It looks like a tadpole. It is also called a kite graph or a dragon graph.
838
+
839
+ .. plot::
840
+
841
+ >>> nx.draw(nx.tadpole_graph(3, 5))
842
+
843
+ Parameters
844
+ ----------
845
+ m, n : int or iterable container of nodes
846
+ If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``.
847
+ If a container of nodes, those nodes appear in the graph.
848
+ Warning: `m` and `n` are not checked for duplicates and if present the
849
+ resulting graph may not be as desired.
850
+
851
+ The nodes for `m` appear in the cycle graph $C_m$ and the nodes
852
+ for `n` appear in the path $P_n$.
853
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
854
+ Graph type to create. If graph instance, then cleared before populated.
855
+
856
+ Returns
857
+ -------
858
+ Networkx graph
859
+ A cycle of size `m` connected to a path of length `n`.
860
+
861
+ Raises
862
+ ------
863
+ NetworkXError
864
+ If ``m < 2``. The tadpole graph is undefined for ``m<2``.
865
+
866
+ Notes
867
+ -----
868
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
869
+ If ``n=0``, this is a cycle graph.
870
+ `m` and/or `n` can be a container of nodes instead of an integer.
871
+
872
+ """
873
+ m, m_nodes = m
874
+ M = len(m_nodes)
875
+ if M < 2:
876
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
877
+
878
+ n, n_nodes = n
879
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
880
+ n_nodes = list(range(M, M + n))
881
+
882
+ # the circle
883
+ G = cycle_graph(m_nodes, create_using)
884
+ if G.is_directed():
885
+ raise NetworkXError("Directed Graph not supported")
886
+
887
+ # the stick
888
+ nx.add_path(G, [m_nodes[-1]] + list(n_nodes))
889
+
890
+ return G
891
+
892
+
893
+ @nx._dispatchable(graphs=None, returns_graph=True)
894
+ def trivial_graph(create_using=None):
895
+ """Return the Trivial graph with one node (with label 0) and no edges.
896
+
897
+ .. plot::
898
+
899
+ >>> nx.draw(nx.trivial_graph(), with_labels=True)
900
+
901
+ """
902
+ G = empty_graph(1, create_using)
903
+ return G
904
+
905
+
906
+ @nx._dispatchable(graphs=None, returns_graph=True)
907
+ def turan_graph(n, r):
908
+ r"""Return the Turan Graph
909
+
910
+ The Turan Graph is a complete multipartite graph on $n$ nodes
911
+ with $r$ disjoint subsets. That is, edges connect each node to
912
+ every node not in its subset.
913
+
914
+ Given $n$ and $r$, we create a complete multipartite graph with
915
+ $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
916
+ $n \mod r$ partitions of size $n/r+1$, rounded down.
917
+
918
+ .. plot::
919
+
920
+ >>> nx.draw(nx.turan_graph(6, 2))
921
+
922
+ Parameters
923
+ ----------
924
+ n : int
925
+ The number of nodes.
926
+ r : int
927
+ The number of partitions.
928
+ Must be less than or equal to n.
929
+
930
+ Notes
931
+ -----
932
+ Must satisfy $1 <= r <= n$.
933
+ The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
934
+ """
935
+
936
+ if not 1 <= r <= n:
937
+ raise NetworkXError("Must satisfy 1 <= r <= n")
938
+
939
+ partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
940
+ G = complete_multipartite_graph(*partitions)
941
+ return G
942
+
943
+
944
+ @nx._dispatchable(graphs=None, returns_graph=True)
945
+ @nodes_or_number(0)
946
+ def wheel_graph(n, create_using=None):
947
+ """Return the wheel graph
948
+
949
+ The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
950
+
951
+ .. plot::
952
+
953
+ >>> nx.draw(nx.wheel_graph(5))
954
+
955
+ Parameters
956
+ ----------
957
+ n : int or iterable
958
+ If an integer, node labels are 0 to n with center 0.
959
+ If an iterable of nodes, the center is the first.
960
+ Warning: n is not checked for duplicates and if present the
961
+ resulting graph may not be as desired. Make sure you have no duplicates.
962
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
963
+ Graph type to create. If graph instance, then cleared before populated.
964
+
965
+ Node labels are the integers 0 to n - 1.
966
+ """
967
+ _, nodes = n
968
+ G = empty_graph(nodes, create_using)
969
+ if G.is_directed():
970
+ raise NetworkXError("Directed Graph not supported")
971
+
972
+ if len(nodes) > 1:
973
+ hub, *rim = nodes
974
+ G.add_edges_from((hub, node) for node in rim)
975
+ if len(rim) > 1:
976
+ G.add_edges_from(pairwise(rim, cyclic=True))
977
+ return G
978
+
979
+
980
+ @nx._dispatchable(graphs=None, returns_graph=True)
981
+ def complete_multipartite_graph(*subset_sizes):
982
+ """Returns the complete multipartite graph with the specified subset sizes.
983
+
984
+ .. plot::
985
+
986
+ >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3))
987
+
988
+ Parameters
989
+ ----------
990
+ subset_sizes : tuple of integers or tuple of node iterables
991
+ The arguments can either all be integer number of nodes or they
992
+ can all be iterables of nodes. If integers, they represent the
993
+ number of nodes in each subset of the multipartite graph.
994
+ If iterables, each is used to create the nodes for that subset.
995
+ The length of subset_sizes is the number of subsets.
996
+
997
+ Returns
998
+ -------
999
+ G : NetworkX Graph
1000
+ Returns the complete multipartite graph with the specified subsets.
1001
+
1002
+ For each node, the node attribute 'subset' is an integer
1003
+ indicating which subset contains the node.
1004
+
1005
+ Examples
1006
+ --------
1007
+ Creating a complete tripartite graph, with subsets of one, two, and three
1008
+ nodes, respectively.
1009
+
1010
+ >>> G = nx.complete_multipartite_graph(1, 2, 3)
1011
+ >>> [G.nodes[u]["subset"] for u in G]
1012
+ [0, 1, 1, 2, 2, 2]
1013
+ >>> list(G.edges(0))
1014
+ [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
1015
+ >>> list(G.edges(2))
1016
+ [(2, 0), (2, 3), (2, 4), (2, 5)]
1017
+ >>> list(G.edges(4))
1018
+ [(4, 0), (4, 1), (4, 2)]
1019
+
1020
+ >>> G = nx.complete_multipartite_graph("a", "bc", "def")
1021
+ >>> [G.nodes[u]["subset"] for u in sorted(G)]
1022
+ [0, 1, 1, 2, 2, 2]
1023
+
1024
+ Notes
1025
+ -----
1026
+ This function generalizes several other graph builder functions.
1027
+
1028
+ - If no subset sizes are given, this returns the null graph.
1029
+ - If a single subset size `n` is given, this returns the empty graph on
1030
+ `n` nodes.
1031
+ - If two subset sizes `m` and `n` are given, this returns the complete
1032
+ bipartite graph on `m + n` nodes.
1033
+ - If subset sizes `1` and `n` are given, this returns the star graph on
1034
+ `n + 1` nodes.
1035
+
1036
+ See also
1037
+ --------
1038
+ complete_bipartite_graph
1039
+ """
1040
+ # The complete multipartite graph is an undirected simple graph.
1041
+ G = Graph()
1042
+
1043
+ if len(subset_sizes) == 0:
1044
+ return G
1045
+
1046
+ # set up subsets of nodes
1047
+ try:
1048
+ extents = pairwise(itertools.accumulate((0,) + subset_sizes))
1049
+ subsets = [range(start, end) for start, end in extents]
1050
+ except TypeError:
1051
+ subsets = subset_sizes
1052
+ else:
1053
+ if any(size < 0 for size in subset_sizes):
1054
+ raise NetworkXError(f"Negative number of nodes not valid: {subset_sizes}")
1055
+
1056
+ # add nodes with subset attribute
1057
+ # while checking that ints are not mixed with iterables
1058
+ try:
1059
+ for i, subset in enumerate(subsets):
1060
+ G.add_nodes_from(subset, subset=i)
1061
+ except TypeError as err:
1062
+ raise NetworkXError("Arguments must be all ints or all iterables") from err
1063
+
1064
+ # Across subsets, all nodes should be adjacent.
1065
+ # We can use itertools.combinations() because undirected.
1066
+ for subset1, subset2 in itertools.combinations(subsets, 2):
1067
+ G.add_edges_from(itertools.product(subset1, subset2))
1068
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/directed.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for some directed graphs, including growing network (GN) graphs and
3
+ scale-free graphs.
4
+
5
+ """
6
+
7
+ import numbers
8
+ from collections import Counter
9
+
10
+ import networkx as nx
11
+ from networkx.generators.classic import empty_graph
12
+ from networkx.utils import discrete_sequence, py_random_state, weighted_choice
13
+
14
+ __all__ = [
15
+ "gn_graph",
16
+ "gnc_graph",
17
+ "gnr_graph",
18
+ "random_k_out_graph",
19
+ "scale_free_graph",
20
+ ]
21
+
22
+
23
+ @py_random_state(3)
24
+ @nx._dispatchable(graphs=None, returns_graph=True)
25
+ def gn_graph(n, kernel=None, create_using=None, seed=None):
26
+ """Returns the growing network (GN) digraph with `n` nodes.
27
+
28
+ The GN graph is built by adding nodes one at a time with a link to one
29
+ previously added node. The target node for the link is chosen with
30
+ probability based on degree. The default attachment kernel is a linear
31
+ function of the degree of a node.
32
+
33
+ The graph is always a (directed) tree.
34
+
35
+ Parameters
36
+ ----------
37
+ n : int
38
+ The number of nodes for the generated graph.
39
+ kernel : function
40
+ The attachment kernel.
41
+ create_using : NetworkX graph constructor, optional (default DiGraph)
42
+ Graph type to create. If graph instance, then cleared before populated.
43
+ seed : integer, random_state, or None (default)
44
+ Indicator of random number generation state.
45
+ See :ref:`Randomness<randomness>`.
46
+
47
+ Examples
48
+ --------
49
+ To create the undirected GN graph, use the :meth:`~DiGraph.to_directed`
50
+ method::
51
+
52
+ >>> D = nx.gn_graph(10) # the GN graph
53
+ >>> G = D.to_undirected() # the undirected version
54
+
55
+ To specify an attachment kernel, use the `kernel` keyword argument::
56
+
57
+ >>> D = nx.gn_graph(10, kernel=lambda x: x**1.5) # A_k = k^1.5
58
+
59
+ References
60
+ ----------
61
+ .. [1] P. L. Krapivsky and S. Redner,
62
+ Organization of Growing Random Networks,
63
+ Phys. Rev. E, 63, 066123, 2001.
64
+ """
65
+ G = empty_graph(1, create_using, default=nx.DiGraph)
66
+ if not G.is_directed():
67
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
68
+
69
+ if kernel is None:
70
+
71
+ def kernel(x):
72
+ return x
73
+
74
+ if n == 1:
75
+ return G
76
+
77
+ G.add_edge(1, 0) # get started
78
+ ds = [1, 1] # degree sequence
79
+
80
+ for source in range(2, n):
81
+ # compute distribution from kernel and degree
82
+ dist = [kernel(d) for d in ds]
83
+ # choose target from discrete distribution
84
+ target = discrete_sequence(1, distribution=dist, seed=seed)[0]
85
+ G.add_edge(source, target)
86
+ ds.append(1) # the source has only one link (degree one)
87
+ ds[target] += 1 # add one to the target link degree
88
+ return G
89
+
90
+
91
+ @py_random_state(3)
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def gnr_graph(n, p, create_using=None, seed=None):
94
+ """Returns the growing network with redirection (GNR) digraph with `n`
95
+ nodes and redirection probability `p`.
96
+
97
+ The GNR graph is built by adding nodes one at a time with a link to one
98
+ previously added node. The previous target node is chosen uniformly at
99
+ random. With probability `p` the link is instead "redirected" to the
100
+ successor node of the target.
101
+
102
+ The graph is always a (directed) tree.
103
+
104
+ Parameters
105
+ ----------
106
+ n : int
107
+ The number of nodes for the generated graph.
108
+ p : float
109
+ The redirection probability.
110
+ create_using : NetworkX graph constructor, optional (default DiGraph)
111
+ Graph type to create. If graph instance, then cleared before populated.
112
+ seed : integer, random_state, or None (default)
113
+ Indicator of random number generation state.
114
+ See :ref:`Randomness<randomness>`.
115
+
116
+ Examples
117
+ --------
118
+ To create the undirected GNR graph, use the :meth:`~DiGraph.to_directed`
119
+ method::
120
+
121
+ >>> D = nx.gnr_graph(10, 0.5) # the GNR graph
122
+ >>> G = D.to_undirected() # the undirected version
123
+
124
+ References
125
+ ----------
126
+ .. [1] P. L. Krapivsky and S. Redner,
127
+ Organization of Growing Random Networks,
128
+ Phys. Rev. E, 63, 066123, 2001.
129
+ """
130
+ G = empty_graph(1, create_using, default=nx.DiGraph)
131
+ if not G.is_directed():
132
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
133
+
134
+ if n == 1:
135
+ return G
136
+
137
+ for source in range(1, n):
138
+ target = seed.randrange(0, source)
139
+ if seed.random() < p and target != 0:
140
+ target = next(G.successors(target))
141
+ G.add_edge(source, target)
142
+ return G
143
+
144
+
145
+ @py_random_state(2)
146
+ @nx._dispatchable(graphs=None, returns_graph=True)
147
+ def gnc_graph(n, create_using=None, seed=None):
148
+ """Returns the growing network with copying (GNC) digraph with `n` nodes.
149
+
150
+ The GNC graph is built by adding nodes one at a time with a link to one
151
+ previously added node (chosen uniformly at random) and to all of that
152
+ node's successors.
153
+
154
+ Parameters
155
+ ----------
156
+ n : int
157
+ The number of nodes for the generated graph.
158
+ create_using : NetworkX graph constructor, optional (default DiGraph)
159
+ Graph type to create. If graph instance, then cleared before populated.
160
+ seed : integer, random_state, or None (default)
161
+ Indicator of random number generation state.
162
+ See :ref:`Randomness<randomness>`.
163
+
164
+ References
165
+ ----------
166
+ .. [1] P. L. Krapivsky and S. Redner,
167
+ Network Growth by Copying,
168
+ Phys. Rev. E, 71, 036118, 2005k.},
169
+ """
170
+ G = empty_graph(1, create_using, default=nx.DiGraph)
171
+ if not G.is_directed():
172
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
173
+
174
+ if n == 1:
175
+ return G
176
+
177
+ for source in range(1, n):
178
+ target = seed.randrange(0, source)
179
+ for succ in G.successors(target):
180
+ G.add_edge(source, succ)
181
+ G.add_edge(source, target)
182
+ return G
183
+
184
+
185
+ @py_random_state(6)
186
+ @nx._dispatchable(graphs=None, returns_graph=True)
187
+ def scale_free_graph(
188
+ n,
189
+ alpha=0.41,
190
+ beta=0.54,
191
+ gamma=0.05,
192
+ delta_in=0.2,
193
+ delta_out=0,
194
+ seed=None,
195
+ initial_graph=None,
196
+ ):
197
+ """Returns a scale-free directed graph.
198
+
199
+ Parameters
200
+ ----------
201
+ n : integer
202
+ Number of nodes in graph
203
+ alpha : float
204
+ Probability for adding a new node connected to an existing node
205
+ chosen randomly according to the in-degree distribution.
206
+ beta : float
207
+ Probability for adding an edge between two existing nodes.
208
+ One existing node is chosen randomly according the in-degree
209
+ distribution and the other chosen randomly according to the out-degree
210
+ distribution.
211
+ gamma : float
212
+ Probability for adding a new node connected to an existing node
213
+ chosen randomly according to the out-degree distribution.
214
+ delta_in : float
215
+ Bias for choosing nodes from in-degree distribution.
216
+ delta_out : float
217
+ Bias for choosing nodes from out-degree distribution.
218
+ seed : integer, random_state, or None (default)
219
+ Indicator of random number generation state.
220
+ See :ref:`Randomness<randomness>`.
221
+ initial_graph : MultiDiGraph instance, optional
222
+ Build the scale-free graph starting from this initial MultiDiGraph,
223
+ if provided.
224
+
225
+ Returns
226
+ -------
227
+ MultiDiGraph
228
+
229
+ Examples
230
+ --------
231
+ Create a scale-free graph on one hundred nodes::
232
+
233
+ >>> G = nx.scale_free_graph(100)
234
+
235
+ Notes
236
+ -----
237
+ The sum of `alpha`, `beta`, and `gamma` must be 1.
238
+
239
+ References
240
+ ----------
241
+ .. [1] B. Bollobás, C. Borgs, J. Chayes, and O. Riordan,
242
+ Directed scale-free graphs,
243
+ Proceedings of the fourteenth annual ACM-SIAM Symposium on
244
+ Discrete Algorithms, 132--139, 2003.
245
+ """
246
+
247
+ def _choose_node(candidates, node_list, delta):
248
+ if delta > 0:
249
+ bias_sum = len(node_list) * delta
250
+ p_delta = bias_sum / (bias_sum + len(candidates))
251
+ if seed.random() < p_delta:
252
+ return seed.choice(node_list)
253
+ return seed.choice(candidates)
254
+
255
+ if initial_graph is not None and hasattr(initial_graph, "_adj"):
256
+ if not isinstance(initial_graph, nx.MultiDiGraph):
257
+ raise nx.NetworkXError("initial_graph must be a MultiDiGraph.")
258
+ G = initial_graph
259
+ else:
260
+ # Start with 3-cycle
261
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 0)])
262
+
263
+ if alpha <= 0:
264
+ raise ValueError("alpha must be > 0.")
265
+ if beta <= 0:
266
+ raise ValueError("beta must be > 0.")
267
+ if gamma <= 0:
268
+ raise ValueError("gamma must be > 0.")
269
+
270
+ if abs(alpha + beta + gamma - 1.0) >= 1e-9:
271
+ raise ValueError("alpha+beta+gamma must equal 1.")
272
+
273
+ if delta_in < 0:
274
+ raise ValueError("delta_in must be >= 0.")
275
+
276
+ if delta_out < 0:
277
+ raise ValueError("delta_out must be >= 0.")
278
+
279
+ # pre-populate degree states
280
+ vs = sum((count * [idx] for idx, count in G.out_degree()), [])
281
+ ws = sum((count * [idx] for idx, count in G.in_degree()), [])
282
+
283
+ # pre-populate node state
284
+ node_list = list(G.nodes())
285
+
286
+ # see if there already are number-based nodes
287
+ numeric_nodes = [n for n in node_list if isinstance(n, numbers.Number)]
288
+ if len(numeric_nodes) > 0:
289
+ # set cursor for new nodes appropriately
290
+ cursor = max(int(n.real) for n in numeric_nodes) + 1
291
+ else:
292
+ # or start at zero
293
+ cursor = 0
294
+
295
+ while len(G) < n:
296
+ r = seed.random()
297
+
298
+ # random choice in alpha,beta,gamma ranges
299
+ if r < alpha:
300
+ # alpha
301
+ # add new node v
302
+ v = cursor
303
+ cursor += 1
304
+ # also add to node state
305
+ node_list.append(v)
306
+ # choose w according to in-degree and delta_in
307
+ w = _choose_node(ws, node_list, delta_in)
308
+
309
+ elif r < alpha + beta:
310
+ # beta
311
+ # choose v according to out-degree and delta_out
312
+ v = _choose_node(vs, node_list, delta_out)
313
+ # choose w according to in-degree and delta_in
314
+ w = _choose_node(ws, node_list, delta_in)
315
+
316
+ else:
317
+ # gamma
318
+ # choose v according to out-degree and delta_out
319
+ v = _choose_node(vs, node_list, delta_out)
320
+ # add new node w
321
+ w = cursor
322
+ cursor += 1
323
+ # also add to node state
324
+ node_list.append(w)
325
+
326
+ # add edge to graph
327
+ G.add_edge(v, w)
328
+
329
+ # update degree states
330
+ vs.append(v)
331
+ ws.append(w)
332
+
333
+ return G
334
+
335
+
336
+ @py_random_state(4)
337
+ @nx._dispatchable(graphs=None, returns_graph=True)
338
+ def random_uniform_k_out_graph(n, k, self_loops=True, with_replacement=True, seed=None):
339
+ """Returns a random `k`-out graph with uniform attachment.
340
+
341
+ A random `k`-out graph with uniform attachment is a multidigraph
342
+ generated by the following algorithm. For each node *u*, choose
343
+ `k` nodes *v* uniformly at random (with replacement). Add a
344
+ directed edge joining *u* to *v*.
345
+
346
+ Parameters
347
+ ----------
348
+ n : int
349
+ The number of nodes in the returned graph.
350
+
351
+ k : int
352
+ The out-degree of each node in the returned graph.
353
+
354
+ self_loops : bool
355
+ If True, self-loops are allowed when generating the graph.
356
+
357
+ with_replacement : bool
358
+ If True, neighbors are chosen with replacement and the
359
+ returned graph will be a directed multigraph. Otherwise,
360
+ neighbors are chosen without replacement and the returned graph
361
+ will be a directed graph.
362
+
363
+ seed : integer, random_state, or None (default)
364
+ Indicator of random number generation state.
365
+ See :ref:`Randomness<randomness>`.
366
+
367
+ Returns
368
+ -------
369
+ NetworkX graph
370
+ A `k`-out-regular directed graph generated according to the
371
+ above algorithm. It will be a multigraph if and only if
372
+ `with_replacement` is True.
373
+
374
+ Raises
375
+ ------
376
+ ValueError
377
+ If `with_replacement` is False and `k` is greater than
378
+ `n`.
379
+
380
+ See also
381
+ --------
382
+ random_k_out_graph
383
+
384
+ Notes
385
+ -----
386
+ The return digraph or multidigraph may not be strongly connected, or
387
+ even weakly connected.
388
+
389
+ If `with_replacement` is True, this function is similar to
390
+ :func:`random_k_out_graph`, if that function had parameter `alpha`
391
+ set to positive infinity.
392
+
393
+ """
394
+ if with_replacement:
395
+ create_using = nx.MultiDiGraph()
396
+
397
+ def sample(v, nodes):
398
+ if not self_loops:
399
+ nodes = nodes - {v}
400
+ return (seed.choice(list(nodes)) for i in range(k))
401
+
402
+ else:
403
+ create_using = nx.DiGraph()
404
+
405
+ def sample(v, nodes):
406
+ if not self_loops:
407
+ nodes = nodes - {v}
408
+ return seed.sample(list(nodes), k)
409
+
410
+ G = nx.empty_graph(n, create_using)
411
+ nodes = set(G)
412
+ for u in G:
413
+ G.add_edges_from((u, v) for v in sample(u, nodes))
414
+ return G
415
+
416
+
417
+ @py_random_state(4)
418
+ @nx._dispatchable(graphs=None, returns_graph=True)
419
+ def random_k_out_graph(n, k, alpha, self_loops=True, seed=None):
420
+ """Returns a random `k`-out graph with preferential attachment.
421
+
422
+ A random `k`-out graph with preferential attachment is a
423
+ multidigraph generated by the following algorithm.
424
+
425
+ 1. Begin with an empty digraph, and initially set each node to have
426
+ weight `alpha`.
427
+ 2. Choose a node `u` with out-degree less than `k` uniformly at
428
+ random.
429
+ 3. Choose a node `v` from with probability proportional to its
430
+ weight.
431
+ 4. Add a directed edge from `u` to `v`, and increase the weight
432
+ of `v` by one.
433
+ 5. If each node has out-degree `k`, halt, otherwise repeat from
434
+ step 2.
435
+
436
+ For more information on this model of random graph, see [1].
437
+
438
+ Parameters
439
+ ----------
440
+ n : int
441
+ The number of nodes in the returned graph.
442
+
443
+ k : int
444
+ The out-degree of each node in the returned graph.
445
+
446
+ alpha : float
447
+ A positive :class:`float` representing the initial weight of
448
+ each vertex. A higher number means that in step 3 above, nodes
449
+ will be chosen more like a true uniformly random sample, and a
450
+ lower number means that nodes are more likely to be chosen as
451
+ their in-degree increases. If this parameter is not positive, a
452
+ :exc:`ValueError` is raised.
453
+
454
+ self_loops : bool
455
+ If True, self-loops are allowed when generating the graph.
456
+
457
+ seed : integer, random_state, or None (default)
458
+ Indicator of random number generation state.
459
+ See :ref:`Randomness<randomness>`.
460
+
461
+ Returns
462
+ -------
463
+ :class:`~networkx.classes.MultiDiGraph`
464
+ A `k`-out-regular multidigraph generated according to the above
465
+ algorithm.
466
+
467
+ Raises
468
+ ------
469
+ ValueError
470
+ If `alpha` is not positive.
471
+
472
+ Notes
473
+ -----
474
+ The returned multidigraph may not be strongly connected, or even
475
+ weakly connected.
476
+
477
+ References
478
+ ----------
479
+ [1]: Peterson, Nicholas R., and Boris Pittel.
480
+ "Distance between two random `k`-out digraphs, with and without
481
+ preferential attachment."
482
+ arXiv preprint arXiv:1311.5961 (2013).
483
+ <https://arxiv.org/abs/1311.5961>
484
+
485
+ """
486
+ if alpha < 0:
487
+ raise ValueError("alpha must be positive")
488
+ G = nx.empty_graph(n, create_using=nx.MultiDiGraph)
489
+ weights = Counter({v: alpha for v in G})
490
+ for i in range(k * n):
491
+ u = seed.choice([v for v, d in G.out_degree() if d < k])
492
+ # If self-loops are not allowed, make the source node `u` have
493
+ # weight zero.
494
+ if not self_loops:
495
+ adjustment = Counter({u: weights[u]})
496
+ else:
497
+ adjustment = Counter()
498
+ v = weighted_choice(weights - adjustment, seed=seed)
499
+ G.add_edge(u, v)
500
+ weights[v] += 1
501
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/duplication.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating graphs based on the "duplication" method.
2
+
3
+ These graph generators start with a small initial graph then duplicate
4
+ nodes and (partially) duplicate their edges. These functions are
5
+ generally inspired by biological networks.
6
+
7
+ """
8
+
9
+ import networkx as nx
10
+ from networkx.exception import NetworkXError
11
+ from networkx.utils import py_random_state
12
+ from networkx.utils.misc import check_create_using
13
+
14
+ __all__ = ["partial_duplication_graph", "duplication_divergence_graph"]
15
+
16
+
17
+ @py_random_state(4)
18
+ @nx._dispatchable(graphs=None, returns_graph=True)
19
+ def partial_duplication_graph(N, n, p, q, seed=None, *, create_using=None):
20
+ """Returns a random graph using the partial duplication model.
21
+
22
+ Parameters
23
+ ----------
24
+ N : int
25
+ The total number of nodes in the final graph.
26
+
27
+ n : int
28
+ The number of nodes in the initial clique.
29
+
30
+ p : float
31
+ The probability of joining each neighbor of a node to the
32
+ duplicate node. Must be a number in the between zero and one,
33
+ inclusive.
34
+
35
+ q : float
36
+ The probability of joining the source node to the duplicate
37
+ node. Must be a number in the between zero and one, inclusive.
38
+
39
+ seed : integer, random_state, or None (default)
40
+ Indicator of random number generation state.
41
+ See :ref:`Randomness<randomness>`.
42
+
43
+ create_using : Graph constructor, optional (default=nx.Graph)
44
+ Graph type to create. If graph instance, then cleared before populated.
45
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
46
+
47
+ Notes
48
+ -----
49
+ A graph of nodes is grown by creating a fully connected graph
50
+ of size `n`. The following procedure is then repeated until
51
+ a total of `N` nodes have been reached.
52
+
53
+ 1. A random node, *u*, is picked and a new node, *v*, is created.
54
+ 2. For each neighbor of *u* an edge from the neighbor to *v* is created
55
+ with probability `p`.
56
+ 3. An edge from *u* to *v* is created with probability `q`.
57
+
58
+ This algorithm appears in [1].
59
+
60
+ This implementation allows the possibility of generating
61
+ disconnected graphs.
62
+
63
+ References
64
+ ----------
65
+ .. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
66
+ randomly grown graphs." Journal of Applied Mathematics 2008.
67
+ <https://doi.org/10.1155/2008/190836>
68
+
69
+ """
70
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
71
+ if p < 0 or p > 1 or q < 0 or q > 1:
72
+ msg = "partial duplication graph must have 0 <= p, q <= 1."
73
+ raise NetworkXError(msg)
74
+ if n > N:
75
+ raise NetworkXError("partial duplication graph must have n <= N.")
76
+
77
+ G = nx.complete_graph(n, create_using)
78
+ for new_node in range(n, N):
79
+ # Pick a random vertex, u, already in the graph.
80
+ src_node = seed.randint(0, new_node - 1)
81
+
82
+ # Add a new vertex, v, to the graph.
83
+ G.add_node(new_node)
84
+
85
+ # For each neighbor of u...
86
+ for nbr_node in list(nx.all_neighbors(G, src_node)):
87
+ # Add the neighbor to v with probability p.
88
+ if seed.random() < p:
89
+ G.add_edge(new_node, nbr_node)
90
+
91
+ # Join v and u with probability q.
92
+ if seed.random() < q:
93
+ G.add_edge(new_node, src_node)
94
+ return G
95
+
96
+
97
+ @py_random_state(2)
98
+ @nx._dispatchable(graphs=None, returns_graph=True)
99
+ def duplication_divergence_graph(n, p, seed=None, *, create_using=None):
100
+ """Returns an undirected graph using the duplication-divergence model.
101
+
102
+ A graph of `n` nodes is created by duplicating the initial nodes
103
+ and retaining edges incident to the original nodes with a retention
104
+ probability `p`.
105
+
106
+ Parameters
107
+ ----------
108
+ n : int
109
+ The desired number of nodes in the graph.
110
+ p : float
111
+ The probability for retaining the edge of the replicated node.
112
+ seed : integer, random_state, or None (default)
113
+ Indicator of random number generation state.
114
+ See :ref:`Randomness<randomness>`.
115
+ create_using : Graph constructor, optional (default=nx.Graph)
116
+ Graph type to create. If graph instance, then cleared before populated.
117
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
118
+
119
+ Returns
120
+ -------
121
+ G : Graph
122
+
123
+ Raises
124
+ ------
125
+ NetworkXError
126
+ If `p` is not a valid probability.
127
+ If `n` is less than 2.
128
+
129
+ Notes
130
+ -----
131
+ This algorithm appears in [1].
132
+
133
+ This implementation disallows the possibility of generating
134
+ disconnected graphs.
135
+
136
+ References
137
+ ----------
138
+ .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
139
+ "Duplication-divergence model of protein interaction network",
140
+ Phys. Rev. E, 71, 061911, 2005.
141
+
142
+ """
143
+ if p > 1 or p < 0:
144
+ msg = f"NetworkXError p={p} is not in [0,1]."
145
+ raise nx.NetworkXError(msg)
146
+ if n < 2:
147
+ msg = "n must be greater than or equal to 2"
148
+ raise nx.NetworkXError(msg)
149
+
150
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
151
+ G = nx.empty_graph(create_using=create_using)
152
+
153
+ # Initialize the graph with two connected nodes.
154
+ G.add_edge(0, 1)
155
+ i = 2
156
+ while i < n:
157
+ # Choose a random node from current graph to duplicate.
158
+ random_node = seed.choice(list(G))
159
+ # Make the replica.
160
+ G.add_node(i)
161
+ # flag indicates whether at least one edge is connected on the replica.
162
+ flag = False
163
+ for nbr in G.neighbors(random_node):
164
+ if seed.random() < p:
165
+ # Link retention step.
166
+ G.add_edge(i, nbr)
167
+ flag = True
168
+ if not flag:
169
+ # Delete replica if no edges retained.
170
+ G.remove_node(i)
171
+ else:
172
+ # Successful duplication.
173
+ i += 1
174
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/harary_graph.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for Harary graphs
2
+
3
+ This module gives two generators for the Harary graph, which was
4
+ introduced by the famous mathematician Frank Harary in his 1962 work [H]_.
5
+ The first generator gives the Harary graph that maximizes the node
6
+ connectivity with given number of nodes and given number of edges.
7
+ The second generator gives the Harary graph that minimizes
8
+ the number of edges in the graph with given node connectivity and
9
+ number of nodes.
10
+
11
+ References
12
+ ----------
13
+ .. [H] Harary, F. "The Maximum Connectivity of a Graph."
14
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
15
+
16
+ """
17
+
18
+ import networkx as nx
19
+ from networkx.exception import NetworkXError
20
+
21
+ __all__ = ["hnm_harary_graph", "hkn_harary_graph"]
22
+
23
+
24
+ @nx._dispatchable(graphs=None, returns_graph=True)
25
+ def hnm_harary_graph(n, m, create_using=None):
26
+ """Returns the Harary graph with given numbers of nodes and edges.
27
+
28
+ The Harary graph $H_{n,m}$ is the graph that maximizes node connectivity
29
+ with $n$ nodes and $m$ edges.
30
+
31
+ This maximum node connectivity is known to be floor($2m/n$). [1]_
32
+
33
+ Parameters
34
+ ----------
35
+ n: integer
36
+ The number of nodes the generated graph is to contain
37
+
38
+ m: integer
39
+ The number of edges the generated graph is to contain
40
+
41
+ create_using : NetworkX graph constructor, optional Graph type
42
+ to create (default=nx.Graph). If graph instance, then cleared
43
+ before populated.
44
+
45
+ Returns
46
+ -------
47
+ NetworkX graph
48
+ The Harary graph $H_{n,m}$.
49
+
50
+ See Also
51
+ --------
52
+ hkn_harary_graph
53
+
54
+ Notes
55
+ -----
56
+ This algorithm runs in $O(m)$ time.
57
+ It is implemented by following the Reference [2]_.
58
+
59
+ References
60
+ ----------
61
+ .. [1] F. T. Boesch, A. Satyanarayana, and C. L. Suffel,
62
+ "A Survey of Some Network Reliability Analysis and Synthesis Results,"
63
+ Networks, pp. 99-107, 2009.
64
+
65
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
66
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
67
+ """
68
+
69
+ if n < 1:
70
+ raise NetworkXError("The number of nodes must be >= 1!")
71
+ if m < n - 1:
72
+ raise NetworkXError("The number of edges must be >= n - 1 !")
73
+ if m > n * (n - 1) // 2:
74
+ raise NetworkXError("The number of edges must be <= n(n-1)/2")
75
+
76
+ # Construct an empty graph with n nodes first
77
+ H = nx.empty_graph(n, create_using)
78
+ # Get the floor of average node degree
79
+ d = 2 * m // n
80
+
81
+ # Test the parity of n and d
82
+ if (n % 2 == 0) or (d % 2 == 0):
83
+ # Start with a regular graph of d degrees
84
+ offset = d // 2
85
+ for i in range(n):
86
+ for j in range(1, offset + 1):
87
+ H.add_edge(i, (i - j) % n)
88
+ H.add_edge(i, (i + j) % n)
89
+ if d & 1:
90
+ # in case d is odd; n must be even in this case
91
+ half = n // 2
92
+ for i in range(half):
93
+ # add edges diagonally
94
+ H.add_edge(i, i + half)
95
+ # Get the remainder of 2*m modulo n
96
+ r = 2 * m % n
97
+ if r > 0:
98
+ # add remaining edges at offset+1
99
+ for i in range(r // 2):
100
+ H.add_edge(i, i + offset + 1)
101
+ else:
102
+ # Start with a regular graph of (d - 1) degrees
103
+ offset = (d - 1) // 2
104
+ for i in range(n):
105
+ for j in range(1, offset + 1):
106
+ H.add_edge(i, (i - j) % n)
107
+ H.add_edge(i, (i + j) % n)
108
+ half = n // 2
109
+ for i in range(m - n * offset):
110
+ # add the remaining m - n*offset edges between i and i+half
111
+ H.add_edge(i, (i + half) % n)
112
+
113
+ return H
114
+
115
+
116
+ @nx._dispatchable(graphs=None, returns_graph=True)
117
+ def hkn_harary_graph(k, n, create_using=None):
118
+ """Returns the Harary graph with given node connectivity and node number.
119
+
120
+ The Harary graph $H_{k,n}$ is the graph that minimizes the number of
121
+ edges needed with given node connectivity $k$ and node number $n$.
122
+
123
+ This smallest number of edges is known to be ceil($kn/2$) [1]_.
124
+
125
+ Parameters
126
+ ----------
127
+ k: integer
128
+ The node connectivity of the generated graph
129
+
130
+ n: integer
131
+ The number of nodes the generated graph is to contain
132
+
133
+ create_using : NetworkX graph constructor, optional Graph type
134
+ to create (default=nx.Graph). If graph instance, then cleared
135
+ before populated.
136
+
137
+ Returns
138
+ -------
139
+ NetworkX graph
140
+ The Harary graph $H_{k,n}$.
141
+
142
+ See Also
143
+ --------
144
+ hnm_harary_graph
145
+
146
+ Notes
147
+ -----
148
+ This algorithm runs in $O(kn)$ time.
149
+ It is implemented by following the Reference [2]_.
150
+
151
+ References
152
+ ----------
153
+ .. [1] Weisstein, Eric W. "Harary Graph." From MathWorld--A Wolfram Web
154
+ Resource. http://mathworld.wolfram.com/HararyGraph.html.
155
+
156
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
157
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
158
+ """
159
+
160
+ if k < 1:
161
+ raise NetworkXError("The node connectivity must be >= 1!")
162
+ if n < k + 1:
163
+ raise NetworkXError("The number of nodes must be >= k+1 !")
164
+
165
+ # in case of connectivity 1, simply return the path graph
166
+ if k == 1:
167
+ H = nx.path_graph(n, create_using)
168
+ return H
169
+
170
+ # Construct an empty graph with n nodes first
171
+ H = nx.empty_graph(n, create_using)
172
+
173
+ # Test the parity of k and n
174
+ if (k % 2 == 0) or (n % 2 == 0):
175
+ # Construct a regular graph with k degrees
176
+ offset = k // 2
177
+ for i in range(n):
178
+ for j in range(1, offset + 1):
179
+ H.add_edge(i, (i - j) % n)
180
+ H.add_edge(i, (i + j) % n)
181
+ if k & 1:
182
+ # odd degree; n must be even in this case
183
+ half = n // 2
184
+ for i in range(half):
185
+ # add edges diagonally
186
+ H.add_edge(i, i + half)
187
+ else:
188
+ # Construct a regular graph with (k - 1) degrees
189
+ offset = (k - 1) // 2
190
+ for i in range(n):
191
+ for j in range(1, offset + 1):
192
+ H.add_edge(i, (i - j) % n)
193
+ H.add_edge(i, (i + j) % n)
194
+ half = n // 2
195
+ for i in range(half + 1):
196
+ # add half+1 edges between i and i+half
197
+ H.add_edge(i, (i + half) % n)
198
+
199
+ return H
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/interval_graph.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for interval graph.
3
+ """
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = ["interval_graph"]
10
+
11
+
12
+ @nx._dispatchable(graphs=None, returns_graph=True)
13
+ def interval_graph(intervals):
14
+ """Generates an interval graph for a list of intervals given.
15
+
16
+ In graph theory, an interval graph is an undirected graph formed from a set
17
+ of closed intervals on the real line, with a vertex for each interval
18
+ and an edge between vertices whose intervals intersect.
19
+ It is the intersection graph of the intervals.
20
+
21
+ More information can be found at:
22
+ https://en.wikipedia.org/wiki/Interval_graph
23
+
24
+ Parameters
25
+ ----------
26
+ intervals : a sequence of intervals, say (l, r) where l is the left end,
27
+ and r is the right end of the closed interval.
28
+
29
+ Returns
30
+ -------
31
+ G : networkx graph
32
+
33
+ Examples
34
+ --------
35
+ >>> intervals = [(-2, 3), [1, 4], (2, 3), (4, 6)]
36
+ >>> G = nx.interval_graph(intervals)
37
+ >>> sorted(G.edges)
38
+ [((-2, 3), (1, 4)), ((-2, 3), (2, 3)), ((1, 4), (2, 3)), ((1, 4), (4, 6))]
39
+
40
+ Raises
41
+ ------
42
+ :exc:`TypeError`
43
+ if `intervals` contains None or an element which is not
44
+ collections.abc.Sequence or not a length of 2.
45
+ :exc:`ValueError`
46
+ if `intervals` contains an interval such that min1 > max1
47
+ where min1,max1 = interval
48
+ """
49
+ intervals = list(intervals)
50
+ for interval in intervals:
51
+ if not (isinstance(interval, Sequence) and len(interval) == 2):
52
+ raise TypeError(
53
+ "Each interval must have length 2, and be a "
54
+ "collections.abc.Sequence such as tuple or list."
55
+ )
56
+ if interval[0] > interval[1]:
57
+ raise ValueError(f"Interval must have lower value first. Got {interval}")
58
+
59
+ graph = nx.Graph()
60
+
61
+ tupled_intervals = [tuple(interval) for interval in intervals]
62
+ graph.add_nodes_from(tupled_intervals)
63
+
64
+ while tupled_intervals:
65
+ min1, max1 = interval1 = tupled_intervals.pop()
66
+ for interval2 in tupled_intervals:
67
+ min2, max2 = interval2
68
+ if max1 >= min2 and max2 >= min1:
69
+ graph.add_edge(interval1, interval2)
70
+ return graph
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/nonisomorphic_trees.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of the Wright, Richmond, Odlyzko and McKay (WROM)
3
+ algorithm for the enumeration of all non-isomorphic free trees of a
4
+ given order. Rooted trees are represented by level sequences, i.e.,
5
+ lists in which the i-th element specifies the distance of vertex i to
6
+ the root.
7
+
8
+ """
9
+
10
+ __all__ = ["nonisomorphic_trees", "number_of_nonisomorphic_trees"]
11
+
12
+ import networkx as nx
13
+
14
+
15
+ @nx._dispatchable(graphs=None, returns_graph=True)
16
+ def nonisomorphic_trees(order, create="graph"):
17
+ """Generates lists of nonisomorphic trees
18
+
19
+ Parameters
20
+ ----------
21
+ order : int
22
+ order of the desired tree(s)
23
+
24
+ create : one of {"graph", "matrix"} (default="graph")
25
+ If ``"graph"`` is selected a list of ``Graph`` instances will be returned,
26
+ if matrix is selected a list of adjacency matrices will be returned.
27
+
28
+ .. deprecated:: 3.3
29
+
30
+ The `create` argument is deprecated and will be removed in NetworkX
31
+ version 3.5. In the future, `nonisomorphic_trees` will yield graph
32
+ instances by default. To generate adjacency matrices, call
33
+ ``nx.to_numpy_array`` on the output, e.g.::
34
+
35
+ [nx.to_numpy_array(G) for G in nx.nonisomorphic_trees(N)]
36
+
37
+ Yields
38
+ ------
39
+ list
40
+ A list of nonisomorphic trees, in one of two formats depending on the
41
+ value of the `create` parameter:
42
+ - ``create="graph"``: yields a list of `networkx.Graph` instances
43
+ - ``create="matrix"``: yields a list of list-of-lists representing adjacency matrices
44
+ """
45
+
46
+ if order < 2:
47
+ raise ValueError
48
+ # start at the path graph rooted at its center
49
+ layout = list(range(order // 2 + 1)) + list(range(1, (order + 1) // 2))
50
+
51
+ while layout is not None:
52
+ layout = _next_tree(layout)
53
+ if layout is not None:
54
+ if create == "graph":
55
+ yield _layout_to_graph(layout)
56
+ elif create == "matrix":
57
+ import warnings
58
+
59
+ warnings.warn(
60
+ (
61
+ "\n\nThe 'create=matrix' argument of nonisomorphic_trees\n"
62
+ "is deprecated and will be removed in version 3.5.\n"
63
+ "Use ``nx.to_numpy_array`` to convert graphs to adjacency "
64
+ "matrices, e.g.::\n\n"
65
+ " [nx.to_numpy_array(G) for G in nx.nonisomorphic_trees(N)]"
66
+ ),
67
+ category=DeprecationWarning,
68
+ stacklevel=2,
69
+ )
70
+
71
+ yield _layout_to_matrix(layout)
72
+ layout = _next_rooted_tree(layout)
73
+
74
+
75
+ @nx._dispatchable(graphs=None)
76
+ def number_of_nonisomorphic_trees(order):
77
+ """Returns the number of nonisomorphic trees
78
+
79
+ Parameters
80
+ ----------
81
+ order : int
82
+ order of the desired tree(s)
83
+
84
+ Returns
85
+ -------
86
+ length : Number of nonisomorphic graphs for the given order
87
+
88
+ References
89
+ ----------
90
+
91
+ """
92
+ return sum(1 for _ in nonisomorphic_trees(order))
93
+
94
+
95
+ def _next_rooted_tree(predecessor, p=None):
96
+ """One iteration of the Beyer-Hedetniemi algorithm."""
97
+
98
+ if p is None:
99
+ p = len(predecessor) - 1
100
+ while predecessor[p] == 1:
101
+ p -= 1
102
+ if p == 0:
103
+ return None
104
+
105
+ q = p - 1
106
+ while predecessor[q] != predecessor[p] - 1:
107
+ q -= 1
108
+ result = list(predecessor)
109
+ for i in range(p, len(result)):
110
+ result[i] = result[i - p + q]
111
+ return result
112
+
113
+
114
+ def _next_tree(candidate):
115
+ """One iteration of the Wright, Richmond, Odlyzko and McKay
116
+ algorithm."""
117
+
118
+ # valid representation of a free tree if:
119
+ # there are at least two vertices at layer 1
120
+ # (this is always the case because we start at the path graph)
121
+ left, rest = _split_tree(candidate)
122
+
123
+ # and the left subtree of the root
124
+ # is less high than the tree with the left subtree removed
125
+ left_height = max(left)
126
+ rest_height = max(rest)
127
+ valid = rest_height >= left_height
128
+
129
+ if valid and rest_height == left_height:
130
+ # and, if left and rest are of the same height,
131
+ # if left does not encompass more vertices
132
+ if len(left) > len(rest):
133
+ valid = False
134
+ # and, if they have the same number or vertices,
135
+ # if left does not come after rest lexicographically
136
+ elif len(left) == len(rest) and left > rest:
137
+ valid = False
138
+
139
+ if valid:
140
+ return candidate
141
+ else:
142
+ # jump to the next valid free tree
143
+ p = len(left)
144
+ new_candidate = _next_rooted_tree(candidate, p)
145
+ if candidate[p] > 2:
146
+ new_left, new_rest = _split_tree(new_candidate)
147
+ new_left_height = max(new_left)
148
+ suffix = range(1, new_left_height + 2)
149
+ new_candidate[-len(suffix) :] = suffix
150
+ return new_candidate
151
+
152
+
153
+ def _split_tree(layout):
154
+ """Returns a tuple of two layouts, one containing the left
155
+ subtree of the root vertex, and one containing the original tree
156
+ with the left subtree removed."""
157
+
158
+ one_found = False
159
+ m = None
160
+ for i in range(len(layout)):
161
+ if layout[i] == 1:
162
+ if one_found:
163
+ m = i
164
+ break
165
+ else:
166
+ one_found = True
167
+
168
+ if m is None:
169
+ m = len(layout)
170
+
171
+ left = [layout[i] - 1 for i in range(1, m)]
172
+ rest = [0] + [layout[i] for i in range(m, len(layout))]
173
+ return (left, rest)
174
+
175
+
176
+ def _layout_to_matrix(layout):
177
+ """Create the adjacency matrix for the tree specified by the
178
+ given layout (level sequence)."""
179
+
180
+ result = [[0] * len(layout) for i in range(len(layout))]
181
+ stack = []
182
+ for i in range(len(layout)):
183
+ i_level = layout[i]
184
+ if stack:
185
+ j = stack[-1]
186
+ j_level = layout[j]
187
+ while j_level >= i_level:
188
+ stack.pop()
189
+ j = stack[-1]
190
+ j_level = layout[j]
191
+ result[i][j] = result[j][i] = 1
192
+ stack.append(i)
193
+ return result
194
+
195
+
196
+ def _layout_to_graph(layout):
197
+ """Create a NetworkX Graph for the tree specified by the
198
+ given layout(level sequence)"""
199
+ G = nx.Graph()
200
+ stack = []
201
+ for i in range(len(layout)):
202
+ i_level = layout[i]
203
+ if stack:
204
+ j = stack[-1]
205
+ j_level = layout[j]
206
+ while j_level >= i_level:
207
+ stack.pop()
208
+ j = stack[-1]
209
+ j_level = layout[j]
210
+ G.add_edge(i, j)
211
+ stack.append(i)
212
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/random_clustered.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with given degree and triangle sequence."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = ["random_clustered_graph"]
7
+
8
+
9
+ @py_random_state(2)
10
+ @nx._dispatchable(graphs=None, returns_graph=True)
11
+ def random_clustered_graph(joint_degree_sequence, create_using=None, seed=None):
12
+ r"""Generate a random graph with the given joint independent edge degree and
13
+ triangle degree sequence.
14
+
15
+ This uses a configuration model-like approach to generate a random graph
16
+ (with parallel edges and self-loops) by randomly assigning edges to match
17
+ the given joint degree sequence.
18
+
19
+ The joint degree sequence is a list of pairs of integers of the form
20
+ $[(d_{1,i}, d_{1,t}), \dotsc, (d_{n,i}, d_{n,t})]$. According to this list,
21
+ vertex $u$ is a member of $d_{u,t}$ triangles and has $d_{u, i}$ other
22
+ edges. The number $d_{u,t}$ is the *triangle degree* of $u$ and the number
23
+ $d_{u,i}$ is the *independent edge degree*.
24
+
25
+ Parameters
26
+ ----------
27
+ joint_degree_sequence : list of integer pairs
28
+ Each list entry corresponds to the independent edge degree and
29
+ triangle degree of a node.
30
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
31
+ Graph type to create. If graph instance, then cleared before populated.
32
+ seed : integer, random_state, or None (default)
33
+ Indicator of random number generation state.
34
+ See :ref:`Randomness<randomness>`.
35
+
36
+ Returns
37
+ -------
38
+ G : MultiGraph
39
+ A graph with the specified degree sequence. Nodes are labeled
40
+ starting at 0 with an index corresponding to the position in
41
+ deg_sequence.
42
+
43
+ Raises
44
+ ------
45
+ NetworkXError
46
+ If the independent edge degree sequence sum is not even
47
+ or the triangle degree sequence sum is not divisible by 3.
48
+
49
+ Notes
50
+ -----
51
+ As described by Miller [1]_ (see also Newman [2]_ for an equivalent
52
+ description).
53
+
54
+ A non-graphical degree sequence (not realizable by some simple
55
+ graph) is allowed since this function returns graphs with self
56
+ loops and parallel edges. An exception is raised if the
57
+ independent degree sequence does not have an even sum or the
58
+ triangle degree sequence sum is not divisible by 3.
59
+
60
+ This configuration model-like construction process can lead to
61
+ duplicate edges and loops. You can remove the self-loops and
62
+ parallel edges (see below) which will likely result in a graph
63
+ that doesn't have the exact degree sequence specified. This
64
+ "finite-size effect" decreases as the size of the graph increases.
65
+
66
+ References
67
+ ----------
68
+ .. [1] Joel C. Miller. "Percolation and epidemics in random clustered
69
+ networks". In: Physical review. E, Statistical, nonlinear, and soft
70
+ matter physics 80 (2 Part 1 August 2009).
71
+ .. [2] M. E. J. Newman. "Random Graphs with Clustering".
72
+ In: Physical Review Letters 103 (5 July 2009)
73
+
74
+ Examples
75
+ --------
76
+ >>> deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)]
77
+ >>> G = nx.random_clustered_graph(deg)
78
+
79
+ To remove parallel edges:
80
+
81
+ >>> G = nx.Graph(G)
82
+
83
+ To remove self loops:
84
+
85
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
86
+
87
+ """
88
+ # In Python 3, zip() returns an iterator. Make this into a list.
89
+ joint_degree_sequence = list(joint_degree_sequence)
90
+
91
+ N = len(joint_degree_sequence)
92
+ G = nx.empty_graph(N, create_using, default=nx.MultiGraph)
93
+ if G.is_directed():
94
+ raise nx.NetworkXError("Directed Graph not supported")
95
+
96
+ ilist = []
97
+ tlist = []
98
+ for n in G:
99
+ degrees = joint_degree_sequence[n]
100
+ for icount in range(degrees[0]):
101
+ ilist.append(n)
102
+ for tcount in range(degrees[1]):
103
+ tlist.append(n)
104
+
105
+ if len(ilist) % 2 != 0 or len(tlist) % 3 != 0:
106
+ raise nx.NetworkXError("Invalid degree sequence")
107
+
108
+ seed.shuffle(ilist)
109
+ seed.shuffle(tlist)
110
+ while ilist:
111
+ G.add_edge(ilist.pop(), ilist.pop())
112
+ while tlist:
113
+ n1 = tlist.pop()
114
+ n2 = tlist.pop()
115
+ n3 = tlist.pop()
116
+ G.add_edges_from([(n1, n2), (n1, n3), (n2, n3)])
117
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/social.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Famous social networks.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "karate_club_graph",
9
+ "davis_southern_women_graph",
10
+ "florentine_families_graph",
11
+ "les_miserables_graph",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(graphs=None, returns_graph=True)
16
+ def karate_club_graph():
17
+ """Returns Zachary's Karate Club graph.
18
+
19
+ Each node in the returned graph has a node attribute 'club' that
20
+ indicates the name of the club to which the member represented by that node
21
+ belongs, either 'Mr. Hi' or 'Officer'. Each edge has a weight based on the
22
+ number of contexts in which that edge's incident node members interacted.
23
+
24
+ The dataset is derived from the 'Club After Split From Data' column of Table 3 in [1]_.
25
+ This was in turn derived from the 'Club After Fission' column of Table 1 in the
26
+ same paper. Note that the nodes are 0-indexed in NetworkX, but 1-indexed in the
27
+ paper (the 'Individual Number in Matrix C' column of Table 3 starts at 1). This
28
+ means, for example, that ``G.nodes[9]["club"]`` returns 'Officer', which
29
+ corresponds to row 10 of Table 3 in the paper.
30
+
31
+ Examples
32
+ --------
33
+ To get the name of the club to which a node belongs::
34
+
35
+ >>> G = nx.karate_club_graph()
36
+ >>> G.nodes[5]["club"]
37
+ 'Mr. Hi'
38
+ >>> G.nodes[9]["club"]
39
+ 'Officer'
40
+
41
+ References
42
+ ----------
43
+ .. [1] Zachary, Wayne W.
44
+ "An Information Flow Model for Conflict and Fission in Small Groups."
45
+ *Journal of Anthropological Research*, 33, 452--473, (1977).
46
+ """
47
+ # Create the set of all members, and the members of each club.
48
+ all_members = set(range(34))
49
+ club1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21}
50
+ # club2 = all_members - club1
51
+
52
+ G = nx.Graph()
53
+ G.add_nodes_from(all_members)
54
+ G.name = "Zachary's Karate Club"
55
+
56
+ zacharydat = """\
57
+ 0 4 5 3 3 3 3 2 2 0 2 3 2 3 0 0 0 2 0 2 0 2 0 0 0 0 0 0 0 0 0 2 0 0
58
+ 4 0 6 3 0 0 0 4 0 0 0 0 0 5 0 0 0 1 0 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0
59
+ 5 6 0 3 0 0 0 4 5 1 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 0 0 0 3 0
60
+ 3 3 3 0 0 0 0 3 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
61
+ 3 0 0 0 0 0 2 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
62
+ 3 0 0 0 0 0 5 0 0 0 3 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
63
+ 3 0 0 0 2 5 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
64
+ 2 4 4 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
65
+ 2 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 4 3
66
+ 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
67
+ 2 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
68
+ 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
69
+ 1 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
70
+ 3 5 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3
71
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2
72
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 4
73
+ 0 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
74
+ 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
75
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2
76
+ 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
77
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1
78
+ 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
79
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0
80
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 4 0 2 0 0 5 4
81
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 3 0 0 0 2 0 0
82
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 2 0 0 0 0 0 0 7 0 0
83
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 2
84
+ 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 3 0 0 0 0 0 0 0 0 4
85
+ 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 2
86
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 4 0 0 0 0 0 3 2
87
+ 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3
88
+ 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 7 0 0 2 0 0 0 4 4
89
+ 0 0 2 0 0 0 0 0 3 0 0 0 0 0 3 3 0 0 1 0 3 0 2 5 0 0 0 0 0 4 3 4 0 5
90
+ 0 0 0 0 0 0 0 0 4 2 0 0 0 3 2 4 0 0 2 1 1 0 3 4 0 0 2 4 2 2 3 4 5 0"""
91
+
92
+ for row, line in enumerate(zacharydat.split("\n")):
93
+ thisrow = [int(b) for b in line.split()]
94
+ for col, entry in enumerate(thisrow):
95
+ if entry >= 1:
96
+ G.add_edge(row, col, weight=entry)
97
+
98
+ # Add the name of each member's club as a node attribute.
99
+ for v in G:
100
+ G.nodes[v]["club"] = "Mr. Hi" if v in club1 else "Officer"
101
+ return G
102
+
103
+
104
+ @nx._dispatchable(graphs=None, returns_graph=True)
105
+ def davis_southern_women_graph():
106
+ """Returns Davis Southern women social network.
107
+
108
+ This is a bipartite graph.
109
+
110
+ References
111
+ ----------
112
+ .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.
113
+ University of Chicago Press, Chicago, IL.
114
+ """
115
+ G = nx.Graph()
116
+ # Top nodes
117
+ women = [
118
+ "Evelyn Jefferson",
119
+ "Laura Mandeville",
120
+ "Theresa Anderson",
121
+ "Brenda Rogers",
122
+ "Charlotte McDowd",
123
+ "Frances Anderson",
124
+ "Eleanor Nye",
125
+ "Pearl Oglethorpe",
126
+ "Ruth DeSand",
127
+ "Verne Sanderson",
128
+ "Myra Liddel",
129
+ "Katherina Rogers",
130
+ "Sylvia Avondale",
131
+ "Nora Fayette",
132
+ "Helen Lloyd",
133
+ "Dorothy Murchison",
134
+ "Olivia Carleton",
135
+ "Flora Price",
136
+ ]
137
+ G.add_nodes_from(women, bipartite=0)
138
+ # Bottom nodes
139
+ events = [
140
+ "E1",
141
+ "E2",
142
+ "E3",
143
+ "E4",
144
+ "E5",
145
+ "E6",
146
+ "E7",
147
+ "E8",
148
+ "E9",
149
+ "E10",
150
+ "E11",
151
+ "E12",
152
+ "E13",
153
+ "E14",
154
+ ]
155
+ G.add_nodes_from(events, bipartite=1)
156
+
157
+ G.add_edges_from(
158
+ [
159
+ ("Evelyn Jefferson", "E1"),
160
+ ("Evelyn Jefferson", "E2"),
161
+ ("Evelyn Jefferson", "E3"),
162
+ ("Evelyn Jefferson", "E4"),
163
+ ("Evelyn Jefferson", "E5"),
164
+ ("Evelyn Jefferson", "E6"),
165
+ ("Evelyn Jefferson", "E8"),
166
+ ("Evelyn Jefferson", "E9"),
167
+ ("Laura Mandeville", "E1"),
168
+ ("Laura Mandeville", "E2"),
169
+ ("Laura Mandeville", "E3"),
170
+ ("Laura Mandeville", "E5"),
171
+ ("Laura Mandeville", "E6"),
172
+ ("Laura Mandeville", "E7"),
173
+ ("Laura Mandeville", "E8"),
174
+ ("Theresa Anderson", "E2"),
175
+ ("Theresa Anderson", "E3"),
176
+ ("Theresa Anderson", "E4"),
177
+ ("Theresa Anderson", "E5"),
178
+ ("Theresa Anderson", "E6"),
179
+ ("Theresa Anderson", "E7"),
180
+ ("Theresa Anderson", "E8"),
181
+ ("Theresa Anderson", "E9"),
182
+ ("Brenda Rogers", "E1"),
183
+ ("Brenda Rogers", "E3"),
184
+ ("Brenda Rogers", "E4"),
185
+ ("Brenda Rogers", "E5"),
186
+ ("Brenda Rogers", "E6"),
187
+ ("Brenda Rogers", "E7"),
188
+ ("Brenda Rogers", "E8"),
189
+ ("Charlotte McDowd", "E3"),
190
+ ("Charlotte McDowd", "E4"),
191
+ ("Charlotte McDowd", "E5"),
192
+ ("Charlotte McDowd", "E7"),
193
+ ("Frances Anderson", "E3"),
194
+ ("Frances Anderson", "E5"),
195
+ ("Frances Anderson", "E6"),
196
+ ("Frances Anderson", "E8"),
197
+ ("Eleanor Nye", "E5"),
198
+ ("Eleanor Nye", "E6"),
199
+ ("Eleanor Nye", "E7"),
200
+ ("Eleanor Nye", "E8"),
201
+ ("Pearl Oglethorpe", "E6"),
202
+ ("Pearl Oglethorpe", "E8"),
203
+ ("Pearl Oglethorpe", "E9"),
204
+ ("Ruth DeSand", "E5"),
205
+ ("Ruth DeSand", "E7"),
206
+ ("Ruth DeSand", "E8"),
207
+ ("Ruth DeSand", "E9"),
208
+ ("Verne Sanderson", "E7"),
209
+ ("Verne Sanderson", "E8"),
210
+ ("Verne Sanderson", "E9"),
211
+ ("Verne Sanderson", "E12"),
212
+ ("Myra Liddel", "E8"),
213
+ ("Myra Liddel", "E9"),
214
+ ("Myra Liddel", "E10"),
215
+ ("Myra Liddel", "E12"),
216
+ ("Katherina Rogers", "E8"),
217
+ ("Katherina Rogers", "E9"),
218
+ ("Katherina Rogers", "E10"),
219
+ ("Katherina Rogers", "E12"),
220
+ ("Katherina Rogers", "E13"),
221
+ ("Katherina Rogers", "E14"),
222
+ ("Sylvia Avondale", "E7"),
223
+ ("Sylvia Avondale", "E8"),
224
+ ("Sylvia Avondale", "E9"),
225
+ ("Sylvia Avondale", "E10"),
226
+ ("Sylvia Avondale", "E12"),
227
+ ("Sylvia Avondale", "E13"),
228
+ ("Sylvia Avondale", "E14"),
229
+ ("Nora Fayette", "E6"),
230
+ ("Nora Fayette", "E7"),
231
+ ("Nora Fayette", "E9"),
232
+ ("Nora Fayette", "E10"),
233
+ ("Nora Fayette", "E11"),
234
+ ("Nora Fayette", "E12"),
235
+ ("Nora Fayette", "E13"),
236
+ ("Nora Fayette", "E14"),
237
+ ("Helen Lloyd", "E7"),
238
+ ("Helen Lloyd", "E8"),
239
+ ("Helen Lloyd", "E10"),
240
+ ("Helen Lloyd", "E11"),
241
+ ("Helen Lloyd", "E12"),
242
+ ("Dorothy Murchison", "E8"),
243
+ ("Dorothy Murchison", "E9"),
244
+ ("Olivia Carleton", "E9"),
245
+ ("Olivia Carleton", "E11"),
246
+ ("Flora Price", "E9"),
247
+ ("Flora Price", "E11"),
248
+ ]
249
+ )
250
+ G.graph["top"] = women
251
+ G.graph["bottom"] = events
252
+ return G
253
+
254
+
255
+ @nx._dispatchable(graphs=None, returns_graph=True)
256
+ def florentine_families_graph():
257
+ """Returns Florentine families graph.
258
+
259
+ References
260
+ ----------
261
+ .. [1] Ronald L. Breiger and Philippa E. Pattison
262
+ Cumulated social roles: The duality of persons and their algebras,1
263
+ Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
264
+ """
265
+ G = nx.Graph()
266
+ G.add_edge("Acciaiuoli", "Medici")
267
+ G.add_edge("Castellani", "Peruzzi")
268
+ G.add_edge("Castellani", "Strozzi")
269
+ G.add_edge("Castellani", "Barbadori")
270
+ G.add_edge("Medici", "Barbadori")
271
+ G.add_edge("Medici", "Ridolfi")
272
+ G.add_edge("Medici", "Tornabuoni")
273
+ G.add_edge("Medici", "Albizzi")
274
+ G.add_edge("Medici", "Salviati")
275
+ G.add_edge("Salviati", "Pazzi")
276
+ G.add_edge("Peruzzi", "Strozzi")
277
+ G.add_edge("Peruzzi", "Bischeri")
278
+ G.add_edge("Strozzi", "Ridolfi")
279
+ G.add_edge("Strozzi", "Bischeri")
280
+ G.add_edge("Ridolfi", "Tornabuoni")
281
+ G.add_edge("Tornabuoni", "Guadagni")
282
+ G.add_edge("Albizzi", "Ginori")
283
+ G.add_edge("Albizzi", "Guadagni")
284
+ G.add_edge("Bischeri", "Guadagni")
285
+ G.add_edge("Guadagni", "Lamberteschi")
286
+ return G
287
+
288
+
289
+ @nx._dispatchable(graphs=None, returns_graph=True)
290
+ def les_miserables_graph():
291
+ """Returns coappearance network of characters in the novel Les Miserables.
292
+
293
+ References
294
+ ----------
295
+ .. [1] D. E. Knuth, 1993.
296
+ The Stanford GraphBase: a platform for combinatorial computing,
297
+ pp. 74-87. New York: AcM Press.
298
+ """
299
+ G = nx.Graph()
300
+ G.add_edge("Napoleon", "Myriel", weight=1)
301
+ G.add_edge("MlleBaptistine", "Myriel", weight=8)
302
+ G.add_edge("MmeMagloire", "Myriel", weight=10)
303
+ G.add_edge("MmeMagloire", "MlleBaptistine", weight=6)
304
+ G.add_edge("CountessDeLo", "Myriel", weight=1)
305
+ G.add_edge("Geborand", "Myriel", weight=1)
306
+ G.add_edge("Champtercier", "Myriel", weight=1)
307
+ G.add_edge("Cravatte", "Myriel", weight=1)
308
+ G.add_edge("Count", "Myriel", weight=2)
309
+ G.add_edge("OldMan", "Myriel", weight=1)
310
+ G.add_edge("Valjean", "Labarre", weight=1)
311
+ G.add_edge("Valjean", "MmeMagloire", weight=3)
312
+ G.add_edge("Valjean", "MlleBaptistine", weight=3)
313
+ G.add_edge("Valjean", "Myriel", weight=5)
314
+ G.add_edge("Marguerite", "Valjean", weight=1)
315
+ G.add_edge("MmeDeR", "Valjean", weight=1)
316
+ G.add_edge("Isabeau", "Valjean", weight=1)
317
+ G.add_edge("Gervais", "Valjean", weight=1)
318
+ G.add_edge("Listolier", "Tholomyes", weight=4)
319
+ G.add_edge("Fameuil", "Tholomyes", weight=4)
320
+ G.add_edge("Fameuil", "Listolier", weight=4)
321
+ G.add_edge("Blacheville", "Tholomyes", weight=4)
322
+ G.add_edge("Blacheville", "Listolier", weight=4)
323
+ G.add_edge("Blacheville", "Fameuil", weight=4)
324
+ G.add_edge("Favourite", "Tholomyes", weight=3)
325
+ G.add_edge("Favourite", "Listolier", weight=3)
326
+ G.add_edge("Favourite", "Fameuil", weight=3)
327
+ G.add_edge("Favourite", "Blacheville", weight=4)
328
+ G.add_edge("Dahlia", "Tholomyes", weight=3)
329
+ G.add_edge("Dahlia", "Listolier", weight=3)
330
+ G.add_edge("Dahlia", "Fameuil", weight=3)
331
+ G.add_edge("Dahlia", "Blacheville", weight=3)
332
+ G.add_edge("Dahlia", "Favourite", weight=5)
333
+ G.add_edge("Zephine", "Tholomyes", weight=3)
334
+ G.add_edge("Zephine", "Listolier", weight=3)
335
+ G.add_edge("Zephine", "Fameuil", weight=3)
336
+ G.add_edge("Zephine", "Blacheville", weight=3)
337
+ G.add_edge("Zephine", "Favourite", weight=4)
338
+ G.add_edge("Zephine", "Dahlia", weight=4)
339
+ G.add_edge("Fantine", "Tholomyes", weight=3)
340
+ G.add_edge("Fantine", "Listolier", weight=3)
341
+ G.add_edge("Fantine", "Fameuil", weight=3)
342
+ G.add_edge("Fantine", "Blacheville", weight=3)
343
+ G.add_edge("Fantine", "Favourite", weight=4)
344
+ G.add_edge("Fantine", "Dahlia", weight=4)
345
+ G.add_edge("Fantine", "Zephine", weight=4)
346
+ G.add_edge("Fantine", "Marguerite", weight=2)
347
+ G.add_edge("Fantine", "Valjean", weight=9)
348
+ G.add_edge("MmeThenardier", "Fantine", weight=2)
349
+ G.add_edge("MmeThenardier", "Valjean", weight=7)
350
+ G.add_edge("Thenardier", "MmeThenardier", weight=13)
351
+ G.add_edge("Thenardier", "Fantine", weight=1)
352
+ G.add_edge("Thenardier", "Valjean", weight=12)
353
+ G.add_edge("Cosette", "MmeThenardier", weight=4)
354
+ G.add_edge("Cosette", "Valjean", weight=31)
355
+ G.add_edge("Cosette", "Tholomyes", weight=1)
356
+ G.add_edge("Cosette", "Thenardier", weight=1)
357
+ G.add_edge("Javert", "Valjean", weight=17)
358
+ G.add_edge("Javert", "Fantine", weight=5)
359
+ G.add_edge("Javert", "Thenardier", weight=5)
360
+ G.add_edge("Javert", "MmeThenardier", weight=1)
361
+ G.add_edge("Javert", "Cosette", weight=1)
362
+ G.add_edge("Fauchelevent", "Valjean", weight=8)
363
+ G.add_edge("Fauchelevent", "Javert", weight=1)
364
+ G.add_edge("Bamatabois", "Fantine", weight=1)
365
+ G.add_edge("Bamatabois", "Javert", weight=1)
366
+ G.add_edge("Bamatabois", "Valjean", weight=2)
367
+ G.add_edge("Perpetue", "Fantine", weight=1)
368
+ G.add_edge("Simplice", "Perpetue", weight=2)
369
+ G.add_edge("Simplice", "Valjean", weight=3)
370
+ G.add_edge("Simplice", "Fantine", weight=2)
371
+ G.add_edge("Simplice", "Javert", weight=1)
372
+ G.add_edge("Scaufflaire", "Valjean", weight=1)
373
+ G.add_edge("Woman1", "Valjean", weight=2)
374
+ G.add_edge("Woman1", "Javert", weight=1)
375
+ G.add_edge("Judge", "Valjean", weight=3)
376
+ G.add_edge("Judge", "Bamatabois", weight=2)
377
+ G.add_edge("Champmathieu", "Valjean", weight=3)
378
+ G.add_edge("Champmathieu", "Judge", weight=3)
379
+ G.add_edge("Champmathieu", "Bamatabois", weight=2)
380
+ G.add_edge("Brevet", "Judge", weight=2)
381
+ G.add_edge("Brevet", "Champmathieu", weight=2)
382
+ G.add_edge("Brevet", "Valjean", weight=2)
383
+ G.add_edge("Brevet", "Bamatabois", weight=1)
384
+ G.add_edge("Chenildieu", "Judge", weight=2)
385
+ G.add_edge("Chenildieu", "Champmathieu", weight=2)
386
+ G.add_edge("Chenildieu", "Brevet", weight=2)
387
+ G.add_edge("Chenildieu", "Valjean", weight=2)
388
+ G.add_edge("Chenildieu", "Bamatabois", weight=1)
389
+ G.add_edge("Cochepaille", "Judge", weight=2)
390
+ G.add_edge("Cochepaille", "Champmathieu", weight=2)
391
+ G.add_edge("Cochepaille", "Brevet", weight=2)
392
+ G.add_edge("Cochepaille", "Chenildieu", weight=2)
393
+ G.add_edge("Cochepaille", "Valjean", weight=2)
394
+ G.add_edge("Cochepaille", "Bamatabois", weight=1)
395
+ G.add_edge("Pontmercy", "Thenardier", weight=1)
396
+ G.add_edge("Boulatruelle", "Thenardier", weight=1)
397
+ G.add_edge("Eponine", "MmeThenardier", weight=2)
398
+ G.add_edge("Eponine", "Thenardier", weight=3)
399
+ G.add_edge("Anzelma", "Eponine", weight=2)
400
+ G.add_edge("Anzelma", "Thenardier", weight=2)
401
+ G.add_edge("Anzelma", "MmeThenardier", weight=1)
402
+ G.add_edge("Woman2", "Valjean", weight=3)
403
+ G.add_edge("Woman2", "Cosette", weight=1)
404
+ G.add_edge("Woman2", "Javert", weight=1)
405
+ G.add_edge("MotherInnocent", "Fauchelevent", weight=3)
406
+ G.add_edge("MotherInnocent", "Valjean", weight=1)
407
+ G.add_edge("Gribier", "Fauchelevent", weight=2)
408
+ G.add_edge("MmeBurgon", "Jondrette", weight=1)
409
+ G.add_edge("Gavroche", "MmeBurgon", weight=2)
410
+ G.add_edge("Gavroche", "Thenardier", weight=1)
411
+ G.add_edge("Gavroche", "Javert", weight=1)
412
+ G.add_edge("Gavroche", "Valjean", weight=1)
413
+ G.add_edge("Gillenormand", "Cosette", weight=3)
414
+ G.add_edge("Gillenormand", "Valjean", weight=2)
415
+ G.add_edge("Magnon", "Gillenormand", weight=1)
416
+ G.add_edge("Magnon", "MmeThenardier", weight=1)
417
+ G.add_edge("MlleGillenormand", "Gillenormand", weight=9)
418
+ G.add_edge("MlleGillenormand", "Cosette", weight=2)
419
+ G.add_edge("MlleGillenormand", "Valjean", weight=2)
420
+ G.add_edge("MmePontmercy", "MlleGillenormand", weight=1)
421
+ G.add_edge("MmePontmercy", "Pontmercy", weight=1)
422
+ G.add_edge("MlleVaubois", "MlleGillenormand", weight=1)
423
+ G.add_edge("LtGillenormand", "MlleGillenormand", weight=2)
424
+ G.add_edge("LtGillenormand", "Gillenormand", weight=1)
425
+ G.add_edge("LtGillenormand", "Cosette", weight=1)
426
+ G.add_edge("Marius", "MlleGillenormand", weight=6)
427
+ G.add_edge("Marius", "Gillenormand", weight=12)
428
+ G.add_edge("Marius", "Pontmercy", weight=1)
429
+ G.add_edge("Marius", "LtGillenormand", weight=1)
430
+ G.add_edge("Marius", "Cosette", weight=21)
431
+ G.add_edge("Marius", "Valjean", weight=19)
432
+ G.add_edge("Marius", "Tholomyes", weight=1)
433
+ G.add_edge("Marius", "Thenardier", weight=2)
434
+ G.add_edge("Marius", "Eponine", weight=5)
435
+ G.add_edge("Marius", "Gavroche", weight=4)
436
+ G.add_edge("BaronessT", "Gillenormand", weight=1)
437
+ G.add_edge("BaronessT", "Marius", weight=1)
438
+ G.add_edge("Mabeuf", "Marius", weight=1)
439
+ G.add_edge("Mabeuf", "Eponine", weight=1)
440
+ G.add_edge("Mabeuf", "Gavroche", weight=1)
441
+ G.add_edge("Enjolras", "Marius", weight=7)
442
+ G.add_edge("Enjolras", "Gavroche", weight=7)
443
+ G.add_edge("Enjolras", "Javert", weight=6)
444
+ G.add_edge("Enjolras", "Mabeuf", weight=1)
445
+ G.add_edge("Enjolras", "Valjean", weight=4)
446
+ G.add_edge("Combeferre", "Enjolras", weight=15)
447
+ G.add_edge("Combeferre", "Marius", weight=5)
448
+ G.add_edge("Combeferre", "Gavroche", weight=6)
449
+ G.add_edge("Combeferre", "Mabeuf", weight=2)
450
+ G.add_edge("Prouvaire", "Gavroche", weight=1)
451
+ G.add_edge("Prouvaire", "Enjolras", weight=4)
452
+ G.add_edge("Prouvaire", "Combeferre", weight=2)
453
+ G.add_edge("Feuilly", "Gavroche", weight=2)
454
+ G.add_edge("Feuilly", "Enjolras", weight=6)
455
+ G.add_edge("Feuilly", "Prouvaire", weight=2)
456
+ G.add_edge("Feuilly", "Combeferre", weight=5)
457
+ G.add_edge("Feuilly", "Mabeuf", weight=1)
458
+ G.add_edge("Feuilly", "Marius", weight=1)
459
+ G.add_edge("Courfeyrac", "Marius", weight=9)
460
+ G.add_edge("Courfeyrac", "Enjolras", weight=17)
461
+ G.add_edge("Courfeyrac", "Combeferre", weight=13)
462
+ G.add_edge("Courfeyrac", "Gavroche", weight=7)
463
+ G.add_edge("Courfeyrac", "Mabeuf", weight=2)
464
+ G.add_edge("Courfeyrac", "Eponine", weight=1)
465
+ G.add_edge("Courfeyrac", "Feuilly", weight=6)
466
+ G.add_edge("Courfeyrac", "Prouvaire", weight=3)
467
+ G.add_edge("Bahorel", "Combeferre", weight=5)
468
+ G.add_edge("Bahorel", "Gavroche", weight=5)
469
+ G.add_edge("Bahorel", "Courfeyrac", weight=6)
470
+ G.add_edge("Bahorel", "Mabeuf", weight=2)
471
+ G.add_edge("Bahorel", "Enjolras", weight=4)
472
+ G.add_edge("Bahorel", "Feuilly", weight=3)
473
+ G.add_edge("Bahorel", "Prouvaire", weight=2)
474
+ G.add_edge("Bahorel", "Marius", weight=1)
475
+ G.add_edge("Bossuet", "Marius", weight=5)
476
+ G.add_edge("Bossuet", "Courfeyrac", weight=12)
477
+ G.add_edge("Bossuet", "Gavroche", weight=5)
478
+ G.add_edge("Bossuet", "Bahorel", weight=4)
479
+ G.add_edge("Bossuet", "Enjolras", weight=10)
480
+ G.add_edge("Bossuet", "Feuilly", weight=6)
481
+ G.add_edge("Bossuet", "Prouvaire", weight=2)
482
+ G.add_edge("Bossuet", "Combeferre", weight=9)
483
+ G.add_edge("Bossuet", "Mabeuf", weight=1)
484
+ G.add_edge("Bossuet", "Valjean", weight=1)
485
+ G.add_edge("Joly", "Bahorel", weight=5)
486
+ G.add_edge("Joly", "Bossuet", weight=7)
487
+ G.add_edge("Joly", "Gavroche", weight=3)
488
+ G.add_edge("Joly", "Courfeyrac", weight=5)
489
+ G.add_edge("Joly", "Enjolras", weight=5)
490
+ G.add_edge("Joly", "Feuilly", weight=5)
491
+ G.add_edge("Joly", "Prouvaire", weight=2)
492
+ G.add_edge("Joly", "Combeferre", weight=5)
493
+ G.add_edge("Joly", "Mabeuf", weight=1)
494
+ G.add_edge("Joly", "Marius", weight=2)
495
+ G.add_edge("Grantaire", "Bossuet", weight=3)
496
+ G.add_edge("Grantaire", "Enjolras", weight=3)
497
+ G.add_edge("Grantaire", "Combeferre", weight=1)
498
+ G.add_edge("Grantaire", "Courfeyrac", weight=2)
499
+ G.add_edge("Grantaire", "Joly", weight=2)
500
+ G.add_edge("Grantaire", "Gavroche", weight=1)
501
+ G.add_edge("Grantaire", "Bahorel", weight=1)
502
+ G.add_edge("Grantaire", "Feuilly", weight=1)
503
+ G.add_edge("Grantaire", "Prouvaire", weight=1)
504
+ G.add_edge("MotherPlutarch", "Mabeuf", weight=3)
505
+ G.add_edge("Gueulemer", "Thenardier", weight=5)
506
+ G.add_edge("Gueulemer", "Valjean", weight=1)
507
+ G.add_edge("Gueulemer", "MmeThenardier", weight=1)
508
+ G.add_edge("Gueulemer", "Javert", weight=1)
509
+ G.add_edge("Gueulemer", "Gavroche", weight=1)
510
+ G.add_edge("Gueulemer", "Eponine", weight=1)
511
+ G.add_edge("Babet", "Thenardier", weight=6)
512
+ G.add_edge("Babet", "Gueulemer", weight=6)
513
+ G.add_edge("Babet", "Valjean", weight=1)
514
+ G.add_edge("Babet", "MmeThenardier", weight=1)
515
+ G.add_edge("Babet", "Javert", weight=2)
516
+ G.add_edge("Babet", "Gavroche", weight=1)
517
+ G.add_edge("Babet", "Eponine", weight=1)
518
+ G.add_edge("Claquesous", "Thenardier", weight=4)
519
+ G.add_edge("Claquesous", "Babet", weight=4)
520
+ G.add_edge("Claquesous", "Gueulemer", weight=4)
521
+ G.add_edge("Claquesous", "Valjean", weight=1)
522
+ G.add_edge("Claquesous", "MmeThenardier", weight=1)
523
+ G.add_edge("Claquesous", "Javert", weight=1)
524
+ G.add_edge("Claquesous", "Eponine", weight=1)
525
+ G.add_edge("Claquesous", "Enjolras", weight=1)
526
+ G.add_edge("Montparnasse", "Javert", weight=1)
527
+ G.add_edge("Montparnasse", "Babet", weight=2)
528
+ G.add_edge("Montparnasse", "Gueulemer", weight=2)
529
+ G.add_edge("Montparnasse", "Claquesous", weight=2)
530
+ G.add_edge("Montparnasse", "Valjean", weight=1)
531
+ G.add_edge("Montparnasse", "Gavroche", weight=1)
532
+ G.add_edge("Montparnasse", "Eponine", weight=1)
533
+ G.add_edge("Montparnasse", "Thenardier", weight=1)
534
+ G.add_edge("Toussaint", "Cosette", weight=2)
535
+ G.add_edge("Toussaint", "Javert", weight=1)
536
+ G.add_edge("Toussaint", "Valjean", weight=1)
537
+ G.add_edge("Child1", "Gavroche", weight=2)
538
+ G.add_edge("Child2", "Gavroche", weight=2)
539
+ G.add_edge("Child2", "Child1", weight=3)
540
+ G.add_edge("Brujon", "Babet", weight=3)
541
+ G.add_edge("Brujon", "Gueulemer", weight=3)
542
+ G.add_edge("Brujon", "Thenardier", weight=3)
543
+ G.add_edge("Brujon", "Gavroche", weight=1)
544
+ G.add_edge("Brujon", "Eponine", weight=1)
545
+ G.add_edge("Brujon", "Claquesous", weight=1)
546
+ G.add_edge("Brujon", "Montparnasse", weight=1)
547
+ G.add_edge("MmeHucheloup", "Bossuet", weight=1)
548
+ G.add_edge("MmeHucheloup", "Joly", weight=1)
549
+ G.add_edge("MmeHucheloup", "Grantaire", weight=1)
550
+ G.add_edge("MmeHucheloup", "Bahorel", weight=1)
551
+ G.add_edge("MmeHucheloup", "Courfeyrac", weight=1)
552
+ G.add_edge("MmeHucheloup", "Gavroche", weight=1)
553
+ G.add_edge("MmeHucheloup", "Enjolras", weight=1)
554
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/spectral_graph_forge.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates graphs with a given eigenvector structure"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import np_random_state
5
+
6
+ __all__ = ["spectral_graph_forge"]
7
+
8
+
9
+ @np_random_state(3)
10
+ @nx._dispatchable(returns_graph=True)
11
+ def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
12
+ """Returns a random simple graph with spectrum resembling that of `G`
13
+
14
+ This algorithm, called Spectral Graph Forge (SGF), computes the
15
+ eigenvectors of a given graph adjacency matrix, filters them and
16
+ builds a random graph with a similar eigenstructure.
17
+ SGF has been proved to be particularly useful for synthesizing
18
+ realistic social networks and it can also be used to anonymize
19
+ graph sensitive data.
20
+
21
+ Parameters
22
+ ----------
23
+ G : Graph
24
+ alpha : float
25
+ Ratio representing the percentage of eigenvectors of G to consider,
26
+ values in [0,1].
27
+ transformation : string, optional
28
+ Represents the intended matrix linear transformation, possible values
29
+ are 'identity' and 'modularity'
30
+ seed : integer, random_state, or None (default)
31
+ Indicator of numpy random number generation state.
32
+ See :ref:`Randomness<randomness>`.
33
+
34
+ Returns
35
+ -------
36
+ H : Graph
37
+ A graph with a similar eigenvector structure of the input one.
38
+
39
+ Raises
40
+ ------
41
+ NetworkXError
42
+ If transformation has a value different from 'identity' or 'modularity'
43
+
44
+ Notes
45
+ -----
46
+ Spectral Graph Forge (SGF) generates a random simple graph resembling the
47
+ global properties of the given one.
48
+ It leverages the low-rank approximation of the associated adjacency matrix
49
+ driven by the *alpha* precision parameter.
50
+ SGF preserves the number of nodes of the input graph and their ordering.
51
+ This way, nodes of output graphs resemble the properties of the input one
52
+ and attributes can be directly mapped.
53
+
54
+ It considers the graph adjacency matrices which can optionally be
55
+ transformed to other symmetric real matrices (currently transformation
56
+ options include *identity* and *modularity*).
57
+ The *modularity* transformation, in the sense of Newman's modularity matrix
58
+ allows the focusing on community structure related properties of the graph.
59
+
60
+ SGF applies a low-rank approximation whose fixed rank is computed from the
61
+ ratio *alpha* of the input graph adjacency matrix dimension.
62
+ This step performs a filtering on the input eigenvectors similar to the low
63
+ pass filtering common in telecommunications.
64
+
65
+ The filtered values (after truncation) are used as input to a Bernoulli
66
+ sampling for constructing a random adjacency matrix.
67
+
68
+ References
69
+ ----------
70
+ .. [1] L. Baldesi, C. T. Butts, A. Markopoulou, "Spectral Graph Forge:
71
+ Graph Generation Targeting Modularity", IEEE Infocom, '18.
72
+ https://arxiv.org/abs/1801.01715
73
+ .. [2] M. Newman, "Networks: an introduction", Oxford university press,
74
+ 2010
75
+
76
+ Examples
77
+ --------
78
+ >>> G = nx.karate_club_graph()
79
+ >>> H = nx.spectral_graph_forge(G, 0.3)
80
+ >>>
81
+ """
82
+ import numpy as np
83
+ import scipy as sp
84
+
85
+ available_transformations = ["identity", "modularity"]
86
+ alpha = np.clip(alpha, 0, 1)
87
+ A = nx.to_numpy_array(G)
88
+ n = A.shape[1]
89
+ level = round(n * alpha)
90
+
91
+ if transformation not in available_transformations:
92
+ msg = f"{transformation!r} is not a valid transformation. "
93
+ msg += f"Transformations: {available_transformations}"
94
+ raise nx.NetworkXError(msg)
95
+
96
+ K = np.ones((1, n)) @ A
97
+
98
+ B = A
99
+ if transformation == "modularity":
100
+ B -= K.T @ K / K.sum()
101
+
102
+ # Compute low-rank approximation of B
103
+ evals, evecs = np.linalg.eigh(B)
104
+ k = np.argsort(np.abs(evals))[::-1] # indices of evals in descending order
105
+ evecs[:, k[np.arange(level, n)]] = 0 # set smallest eigenvectors to 0
106
+ B = evecs @ np.diag(evals) @ evecs.T
107
+
108
+ if transformation == "modularity":
109
+ B += K.T @ K / K.sum()
110
+
111
+ B = np.clip(B, 0, 1)
112
+ np.fill_diagonal(B, 0)
113
+
114
+ for i in range(n - 1):
115
+ B[i, i + 1 :] = sp.stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed)
116
+ B[i + 1 :, i] = np.transpose(B[i, i + 1 :])
117
+
118
+ H = nx.from_numpy_array(B)
119
+
120
+ return H
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/sudoku.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generator for Sudoku graphs
2
+
3
+ This module gives a generator for n-Sudoku graphs. It can be used to develop
4
+ algorithms for solving or generating Sudoku puzzles.
5
+
6
+ A completed Sudoku grid is a 9x9 array of integers between 1 and 9, with no
7
+ number appearing twice in the same row, column, or 3x3 box.
8
+
9
+ +---------+---------+---------+
10
+ | | 8 6 4 | | 3 7 1 | | 2 5 9 |
11
+ | | 3 2 5 | | 8 4 9 | | 7 6 1 |
12
+ | | 9 7 1 | | 2 6 5 | | 8 4 3 |
13
+ +---------+---------+---------+
14
+ | | 4 3 6 | | 1 9 2 | | 5 8 7 |
15
+ | | 1 9 8 | | 6 5 7 | | 4 3 2 |
16
+ | | 2 5 7 | | 4 8 3 | | 9 1 6 |
17
+ +---------+---------+---------+
18
+ | | 6 8 9 | | 7 3 4 | | 1 2 5 |
19
+ | | 7 1 3 | | 5 2 8 | | 6 9 4 |
20
+ | | 5 4 2 | | 9 1 6 | | 3 7 8 |
21
+ +---------+---------+---------+
22
+
23
+
24
+ The Sudoku graph is an undirected graph with 81 vertices, corresponding to
25
+ the cells of a Sudoku grid. It is a regular graph of degree 20. Two distinct
26
+ vertices are adjacent if and only if the corresponding cells belong to the
27
+ same row, column, or box. A completed Sudoku grid corresponds to a vertex
28
+ coloring of the Sudoku graph with nine colors.
29
+
30
+ More generally, the n-Sudoku graph is a graph with n^4 vertices, corresponding
31
+ to the cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
32
+ only if they belong to the same row, column, or n by n box.
33
+
34
+ References
35
+ ----------
36
+ .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
37
+ polynomials. Notices of the AMS, 54(6), 708-717.
38
+ .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
39
+ Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
40
+ .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
41
+ Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
42
+ """
43
+
44
+ import networkx as nx
45
+ from networkx.exception import NetworkXError
46
+
47
+ __all__ = ["sudoku_graph"]
48
+
49
+
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def sudoku_graph(n=3):
52
+ """Returns the n-Sudoku graph. The default value of n is 3.
53
+
54
+ The n-Sudoku graph is a graph with n^4 vertices, corresponding to the
55
+ cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
56
+ only if they belong to the same row, column, or n-by-n box.
57
+
58
+ Parameters
59
+ ----------
60
+ n: integer
61
+ The order of the Sudoku graph, equal to the square root of the
62
+ number of rows. The default is 3.
63
+
64
+ Returns
65
+ -------
66
+ NetworkX graph
67
+ The n-Sudoku graph Sud(n).
68
+
69
+ Examples
70
+ --------
71
+ >>> G = nx.sudoku_graph()
72
+ >>> G.number_of_nodes()
73
+ 81
74
+ >>> G.number_of_edges()
75
+ 810
76
+ >>> sorted(G.neighbors(42))
77
+ [6, 15, 24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 51, 52, 53, 60, 69, 78]
78
+ >>> G = nx.sudoku_graph(2)
79
+ >>> G.number_of_nodes()
80
+ 16
81
+ >>> G.number_of_edges()
82
+ 56
83
+
84
+ References
85
+ ----------
86
+ .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
87
+ polynomials. Notices of the AMS, 54(6), 708-717.
88
+ .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
89
+ Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
90
+ .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
91
+ Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
92
+ """
93
+
94
+ if n < 0:
95
+ raise NetworkXError("The order must be greater than or equal to zero.")
96
+
97
+ n2 = n * n
98
+ n3 = n2 * n
99
+ n4 = n3 * n
100
+
101
+ # Construct an empty graph with n^4 nodes
102
+ G = nx.empty_graph(n4)
103
+
104
+ # A Sudoku graph of order 0 or 1 has no edges
105
+ if n < 2:
106
+ return G
107
+
108
+ # Add edges for cells in the same row
109
+ for row_no in range(n2):
110
+ row_start = row_no * n2
111
+ for j in range(1, n2):
112
+ for i in range(j):
113
+ G.add_edge(row_start + i, row_start + j)
114
+
115
+ # Add edges for cells in the same column
116
+ for col_no in range(n2):
117
+ for j in range(col_no, n4, n2):
118
+ for i in range(col_no, j, n2):
119
+ G.add_edge(i, j)
120
+
121
+ # Add edges for cells in the same box
122
+ for band_no in range(n):
123
+ for stack_no in range(n):
124
+ box_start = n3 * band_no + n * stack_no
125
+ for j in range(1, n2):
126
+ for i in range(j):
127
+ u = box_start + (i % n) + n2 * (i // n)
128
+ v = box_start + (j % n) + n2 * (j // n)
129
+ G.add_edge(u, v)
130
+
131
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc ADDED
Binary file (3.58 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-310.pyc ADDED
Binary file (647 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc ADDED
Binary file (8.64 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc ADDED
Binary file (7.01 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc ADDED
Binary file (4.96 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc ADDED
Binary file (1.56 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc ADDED
Binary file (5.84 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc ADDED
Binary file (4.82 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc ADDED
Binary file (4.18 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc ADDED
Binary file (1.48 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc ADDED
Binary file (2.18 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc ADDED
Binary file (7.42 kB). View file