applied-ai-018 commited on
Commit
4dd904e
·
verified ·
1 Parent(s): 8afcaf1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__init__.py +5 -0
  2. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/neighbor_degree.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/pairs.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/connectivity.py +122 -0
  9. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/correlation.py +302 -0
  10. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/mixing.py +254 -0
  11. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/neighbor_degree.py +160 -0
  12. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/pairs.py +118 -0
  13. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__init__.py +0 -0
  14. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/base_test.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_connectivity.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_correlation.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_mixing.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/base_test.py +81 -0
  22. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.py +143 -0
  23. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_correlation.py +123 -0
  24. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py +176 -0
  25. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py +108 -0
  26. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_pairs.py +87 -0
  27. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/katz.py +330 -0
  28. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/reaching.py +206 -0
  29. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/subgraph_alg.py +339 -0
  30. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/voterank_alg.py +94 -0
  31. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__init__.py +11 -0
  32. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-310.pyc +0 -0
  39. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/connectivity.py +816 -0
  43. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/cuts.py +611 -0
  44. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/disjoint_paths.py +407 -0
  45. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_augmentation.py +1269 -0
  46. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py +591 -0
  47. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcomponents.py +222 -0
  48. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcutsets.py +234 -0
  49. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/stoerwagner.py +151 -0
  50. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/tests/__init__.py +0 -0
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from networkx.algorithms.assortativity.connectivity import *
2
+ from networkx.algorithms.assortativity.correlation import *
3
+ from networkx.algorithms.assortativity.mixing import *
4
+ from networkx.algorithms.assortativity.neighbor_degree import *
5
+ from networkx.algorithms.assortativity.pairs import *
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (482 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-310.pyc ADDED
Binary file (9.28 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-310.pyc ADDED
Binary file (7.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/neighbor_degree.cpython-310.pyc ADDED
Binary file (4.71 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/pairs.cpython-310.pyc ADDED
Binary file (3.46 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/connectivity.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["average_degree_connectivity"]
6
+
7
+
8
+ @nx._dispatchable(edge_attrs="weight")
9
+ def average_degree_connectivity(
10
+ G, source="in+out", target="in+out", nodes=None, weight=None
11
+ ):
12
+ r"""Compute the average degree connectivity of graph.
13
+
14
+ The average degree connectivity is the average nearest neighbor degree of
15
+ nodes with degree k. For weighted graphs, an analogous measure can
16
+ be computed using the weighted average neighbors degree defined in
17
+ [1]_, for a node `i`, as
18
+
19
+ .. math::
20
+
21
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
22
+
23
+ where `s_i` is the weighted degree of node `i`,
24
+ `w_{ij}` is the weight of the edge that links `i` and `j`,
25
+ and `N(i)` are the neighbors of node `i`.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : "in"|"out"|"in+out" (default:"in+out")
32
+ Directed graphs only. Use "in"- or "out"-degree for source node.
33
+
34
+ target : "in"|"out"|"in+out" (default:"in+out"
35
+ Directed graphs only. Use "in"- or "out"-degree for target node.
36
+
37
+ nodes : list or iterable (optional)
38
+ Compute neighbor connectivity for these nodes. The default is all
39
+ nodes.
40
+
41
+ weight : string or None, optional (default=None)
42
+ The edge attribute that holds the numerical value used as a weight.
43
+ If None, then each edge has weight 1.
44
+
45
+ Returns
46
+ -------
47
+ d : dict
48
+ A dictionary keyed by degree k with the value of average connectivity.
49
+
50
+ Raises
51
+ ------
52
+ NetworkXError
53
+ If either `source` or `target` are not one of 'in',
54
+ 'out', or 'in+out'.
55
+ If either `source` or `target` is passed for an undirected graph.
56
+
57
+ Examples
58
+ --------
59
+ >>> G = nx.path_graph(4)
60
+ >>> G.edges[1, 2]["weight"] = 3
61
+ >>> nx.average_degree_connectivity(G)
62
+ {1: 2.0, 2: 1.5}
63
+ >>> nx.average_degree_connectivity(G, weight="weight")
64
+ {1: 2.0, 2: 1.75}
65
+
66
+ See Also
67
+ --------
68
+ average_neighbor_degree
69
+
70
+ References
71
+ ----------
72
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
73
+ "The architecture of complex weighted networks".
74
+ PNAS 101 (11): 3747–3752 (2004).
75
+ """
76
+ # First, determine the type of neighbors and the type of degree to use.
77
+ if G.is_directed():
78
+ if source not in ("in", "out", "in+out"):
79
+ raise nx.NetworkXError('source must be one of "in", "out", or "in+out"')
80
+ if target not in ("in", "out", "in+out"):
81
+ raise nx.NetworkXError('target must be one of "in", "out", or "in+out"')
82
+ direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree}
83
+ neighbor_funcs = {
84
+ "out": G.successors,
85
+ "in": G.predecessors,
86
+ "in+out": G.neighbors,
87
+ }
88
+ source_degree = direction[source]
89
+ target_degree = direction[target]
90
+ neighbors = neighbor_funcs[source]
91
+ # `reverse` indicates whether to look at the in-edge when
92
+ # computing the weight of an edge.
93
+ reverse = source == "in"
94
+ else:
95
+ if source != "in+out" or target != "in+out":
96
+ raise nx.NetworkXError(
97
+ f"source and target arguments are only supported for directed graphs"
98
+ )
99
+ source_degree = G.degree
100
+ target_degree = G.degree
101
+ neighbors = G.neighbors
102
+ reverse = False
103
+ dsum = defaultdict(int)
104
+ dnorm = defaultdict(int)
105
+ # Check if `source_nodes` is actually a single node in the graph.
106
+ source_nodes = source_degree(nodes)
107
+ if nodes in G:
108
+ source_nodes = [(nodes, source_degree(nodes))]
109
+ for n, k in source_nodes:
110
+ nbrdeg = target_degree(neighbors(n))
111
+ if weight is None:
112
+ s = sum(d for n, d in nbrdeg)
113
+ else: # weight nbr degree by weight of (n,nbr) edge
114
+ if reverse:
115
+ s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg)
116
+ else:
117
+ s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg)
118
+ dnorm[k] += source_degree(n, weight=weight)
119
+ dsum[k] += s
120
+
121
+ # normalize
122
+ return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/correlation.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Node assortativity coefficients and correlation measures.
2
+ """
3
+ import networkx as nx
4
+ from networkx.algorithms.assortativity.mixing import (
5
+ attribute_mixing_matrix,
6
+ degree_mixing_matrix,
7
+ )
8
+ from networkx.algorithms.assortativity.pairs import node_degree_xy
9
+
10
+ __all__ = [
11
+ "degree_pearson_correlation_coefficient",
12
+ "degree_assortativity_coefficient",
13
+ "attribute_assortativity_coefficient",
14
+ "numeric_assortativity_coefficient",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable(edge_attrs="weight")
19
+ def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
20
+ """Compute degree assortativity of graph.
21
+
22
+ Assortativity measures the similarity of connections
23
+ in the graph with respect to the node degree.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ x: string ('in','out')
30
+ The degree type for source node (directed graphs only).
31
+
32
+ y: string ('in','out')
33
+ The degree type for target node (directed graphs only).
34
+
35
+ weight: string or None, optional (default=None)
36
+ The edge attribute that holds the numerical value used
37
+ as a weight. If None, then each edge has weight 1.
38
+ The degree is the sum of the edge weights adjacent to the node.
39
+
40
+ nodes: list or iterable (optional)
41
+ Compute degree assortativity only for nodes in container.
42
+ The default is all nodes.
43
+
44
+ Returns
45
+ -------
46
+ r : float
47
+ Assortativity of graph by degree.
48
+
49
+ Examples
50
+ --------
51
+ >>> G = nx.path_graph(4)
52
+ >>> r = nx.degree_assortativity_coefficient(G)
53
+ >>> print(f"{r:3.1f}")
54
+ -0.5
55
+
56
+ See Also
57
+ --------
58
+ attribute_assortativity_coefficient
59
+ numeric_assortativity_coefficient
60
+ degree_mixing_dict
61
+ degree_mixing_matrix
62
+
63
+ Notes
64
+ -----
65
+ This computes Eq. (21) in Ref. [1]_ , where e is the joint
66
+ probability distribution (mixing matrix) of the degrees. If G is
67
+ directed than the matrix e is the joint probability of the
68
+ user-specified degree type for the source and target.
69
+
70
+ References
71
+ ----------
72
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
73
+ Physical Review E, 67 026126, 2003
74
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
75
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
76
+ """
77
+ if nodes is None:
78
+ nodes = G.nodes
79
+
80
+ degrees = None
81
+
82
+ if G.is_directed():
83
+ indeg = (
84
+ {d for _, d in G.in_degree(nodes, weight=weight)}
85
+ if "in" in (x, y)
86
+ else set()
87
+ )
88
+ outdeg = (
89
+ {d for _, d in G.out_degree(nodes, weight=weight)}
90
+ if "out" in (x, y)
91
+ else set()
92
+ )
93
+ degrees = set.union(indeg, outdeg)
94
+ else:
95
+ degrees = {d for _, d in G.degree(nodes, weight=weight)}
96
+
97
+ mapping = {d: i for i, d in enumerate(degrees)}
98
+ M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
99
+
100
+ return _numeric_ac(M, mapping=mapping)
101
+
102
+
103
+ @nx._dispatchable(edge_attrs="weight")
104
+ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
105
+ """Compute degree assortativity of graph.
106
+
107
+ Assortativity measures the similarity of connections
108
+ in the graph with respect to the node degree.
109
+
110
+ This is the same as degree_assortativity_coefficient but uses the
111
+ potentially faster scipy.stats.pearsonr function.
112
+
113
+ Parameters
114
+ ----------
115
+ G : NetworkX graph
116
+
117
+ x: string ('in','out')
118
+ The degree type for source node (directed graphs only).
119
+
120
+ y: string ('in','out')
121
+ The degree type for target node (directed graphs only).
122
+
123
+ weight: string or None, optional (default=None)
124
+ The edge attribute that holds the numerical value used
125
+ as a weight. If None, then each edge has weight 1.
126
+ The degree is the sum of the edge weights adjacent to the node.
127
+
128
+ nodes: list or iterable (optional)
129
+ Compute pearson correlation of degrees only for specified nodes.
130
+ The default is all nodes.
131
+
132
+ Returns
133
+ -------
134
+ r : float
135
+ Assortativity of graph by degree.
136
+
137
+ Examples
138
+ --------
139
+ >>> G = nx.path_graph(4)
140
+ >>> r = nx.degree_pearson_correlation_coefficient(G)
141
+ >>> print(f"{r:3.1f}")
142
+ -0.5
143
+
144
+ Notes
145
+ -----
146
+ This calls scipy.stats.pearsonr.
147
+
148
+ References
149
+ ----------
150
+ .. [1] M. E. J. Newman, Mixing patterns in networks
151
+ Physical Review E, 67 026126, 2003
152
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
153
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
154
+ """
155
+ import scipy as sp
156
+
157
+ xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
158
+ x, y = zip(*xy)
159
+ return float(sp.stats.pearsonr(x, y)[0])
160
+
161
+
162
+ @nx._dispatchable(node_attrs="attribute")
163
+ def attribute_assortativity_coefficient(G, attribute, nodes=None):
164
+ """Compute assortativity for node attributes.
165
+
166
+ Assortativity measures the similarity of connections
167
+ in the graph with respect to the given attribute.
168
+
169
+ Parameters
170
+ ----------
171
+ G : NetworkX graph
172
+
173
+ attribute : string
174
+ Node attribute key
175
+
176
+ nodes: list or iterable (optional)
177
+ Compute attribute assortativity for nodes in container.
178
+ The default is all nodes.
179
+
180
+ Returns
181
+ -------
182
+ r: float
183
+ Assortativity of graph for given attribute
184
+
185
+ Examples
186
+ --------
187
+ >>> G = nx.Graph()
188
+ >>> G.add_nodes_from([0, 1], color="red")
189
+ >>> G.add_nodes_from([2, 3], color="blue")
190
+ >>> G.add_edges_from([(0, 1), (2, 3)])
191
+ >>> print(nx.attribute_assortativity_coefficient(G, "color"))
192
+ 1.0
193
+
194
+ Notes
195
+ -----
196
+ This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
197
+ where M is the joint probability distribution (mixing matrix)
198
+ of the specified attribute.
199
+
200
+ References
201
+ ----------
202
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
203
+ Physical Review E, 67 026126, 2003
204
+ """
205
+ M = attribute_mixing_matrix(G, attribute, nodes)
206
+ return attribute_ac(M)
207
+
208
+
209
+ @nx._dispatchable(node_attrs="attribute")
210
+ def numeric_assortativity_coefficient(G, attribute, nodes=None):
211
+ """Compute assortativity for numerical node attributes.
212
+
213
+ Assortativity measures the similarity of connections
214
+ in the graph with respect to the given numeric attribute.
215
+
216
+ Parameters
217
+ ----------
218
+ G : NetworkX graph
219
+
220
+ attribute : string
221
+ Node attribute key.
222
+
223
+ nodes: list or iterable (optional)
224
+ Compute numeric assortativity only for attributes of nodes in
225
+ container. The default is all nodes.
226
+
227
+ Returns
228
+ -------
229
+ r: float
230
+ Assortativity of graph for given attribute
231
+
232
+ Examples
233
+ --------
234
+ >>> G = nx.Graph()
235
+ >>> G.add_nodes_from([0, 1], size=2)
236
+ >>> G.add_nodes_from([2, 3], size=3)
237
+ >>> G.add_edges_from([(0, 1), (2, 3)])
238
+ >>> print(nx.numeric_assortativity_coefficient(G, "size"))
239
+ 1.0
240
+
241
+ Notes
242
+ -----
243
+ This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
244
+ coefficient of the specified (scalar valued) attribute across edges.
245
+
246
+ References
247
+ ----------
248
+ .. [1] M. E. J. Newman, Mixing patterns in networks
249
+ Physical Review E, 67 026126, 2003
250
+ """
251
+ if nodes is None:
252
+ nodes = G.nodes
253
+ vals = {G.nodes[n][attribute] for n in nodes}
254
+ mapping = {d: i for i, d in enumerate(vals)}
255
+ M = attribute_mixing_matrix(G, attribute, nodes, mapping)
256
+ return _numeric_ac(M, mapping)
257
+
258
+
259
+ def attribute_ac(M):
260
+ """Compute assortativity for attribute matrix M.
261
+
262
+ Parameters
263
+ ----------
264
+ M : numpy.ndarray
265
+ 2D ndarray representing the attribute mixing matrix.
266
+
267
+ Notes
268
+ -----
269
+ This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
270
+ where e is the joint probability distribution (mixing matrix)
271
+ of the specified attribute.
272
+
273
+ References
274
+ ----------
275
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
276
+ Physical Review E, 67 026126, 2003
277
+ """
278
+ if M.sum() != 1.0:
279
+ M = M / M.sum()
280
+ s = (M @ M).sum()
281
+ t = M.trace()
282
+ r = (t - s) / (1 - s)
283
+ return float(r)
284
+
285
+
286
+ def _numeric_ac(M, mapping):
287
+ # M is a 2D numpy array
288
+ # numeric assortativity coefficient, pearsonr
289
+ import numpy as np
290
+
291
+ if M.sum() != 1.0:
292
+ M = M / M.sum()
293
+ x = np.array(list(mapping.keys()))
294
+ y = x # x and y have the same support
295
+ idx = list(mapping.values())
296
+ a = M.sum(axis=0)
297
+ b = M.sum(axis=1)
298
+ vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
299
+ varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
300
+ xy = np.outer(x, y)
301
+ ab = np.outer(a[idx], b[idx])
302
+ return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/mixing.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mixing matrices for node attributes and degree.
3
+ """
4
+ import networkx as nx
5
+ from networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xy
6
+ from networkx.utils import dict_to_numpy_array
7
+
8
+ __all__ = [
9
+ "attribute_mixing_matrix",
10
+ "attribute_mixing_dict",
11
+ "degree_mixing_matrix",
12
+ "degree_mixing_dict",
13
+ "mixing_dict",
14
+ ]
15
+
16
+
17
+ @nx._dispatchable(node_attrs="attribute")
18
+ def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
19
+ """Returns dictionary representation of mixing matrix for attribute.
20
+
21
+ Parameters
22
+ ----------
23
+ G : graph
24
+ NetworkX graph object.
25
+
26
+ attribute : string
27
+ Node attribute key.
28
+
29
+ nodes: list or iterable (optional)
30
+ Unse nodes in container to build the dict. The default is all nodes.
31
+
32
+ normalized : bool (default=False)
33
+ Return counts if False or probabilities if True.
34
+
35
+ Examples
36
+ --------
37
+ >>> G = nx.Graph()
38
+ >>> G.add_nodes_from([0, 1], color="red")
39
+ >>> G.add_nodes_from([2, 3], color="blue")
40
+ >>> G.add_edge(1, 3)
41
+ >>> d = nx.attribute_mixing_dict(G, "color")
42
+ >>> print(d["red"]["blue"])
43
+ 1
44
+ >>> print(d["blue"]["red"]) # d symmetric for undirected graphs
45
+ 1
46
+
47
+ Returns
48
+ -------
49
+ d : dictionary
50
+ Counts or joint probability of occurrence of attribute pairs.
51
+ """
52
+ xy_iter = node_attribute_xy(G, attribute, nodes)
53
+ return mixing_dict(xy_iter, normalized=normalized)
54
+
55
+
56
+ @nx._dispatchable(node_attrs="attribute")
57
+ def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True):
58
+ """Returns mixing matrix for attribute.
59
+
60
+ Parameters
61
+ ----------
62
+ G : graph
63
+ NetworkX graph object.
64
+
65
+ attribute : string
66
+ Node attribute key.
67
+
68
+ nodes: list or iterable (optional)
69
+ Use only nodes in container to build the matrix. The default is
70
+ all nodes.
71
+
72
+ mapping : dictionary, optional
73
+ Mapping from node attribute to integer index in matrix.
74
+ If not specified, an arbitrary ordering will be used.
75
+
76
+ normalized : bool (default=True)
77
+ Return counts if False or probabilities if True.
78
+
79
+ Returns
80
+ -------
81
+ m: numpy array
82
+ Counts or joint probability of occurrence of attribute pairs.
83
+
84
+ Notes
85
+ -----
86
+ If each node has a unique attribute value, the unnormalized mixing matrix
87
+ will be equal to the adjacency matrix. To get a denser mixing matrix,
88
+ the rounding can be performed to form groups of nodes with equal values.
89
+ For example, the exact height of persons in cm (180.79155222, 163.9080892,
90
+ 163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
91
+ 163, 168, 168, ...).
92
+
93
+ Definitions of attribute mixing matrix vary on whether the matrix
94
+ should include rows for attribute values that don't arise. Here we
95
+ do not include such empty-rows. But you can force them to appear
96
+ by inputting a `mapping` that includes those values.
97
+
98
+ Examples
99
+ --------
100
+ >>> G = nx.path_graph(3)
101
+ >>> gender = {0: "male", 1: "female", 2: "female"}
102
+ >>> nx.set_node_attributes(G, gender, "gender")
103
+ >>> mapping = {"male": 0, "female": 1}
104
+ >>> mix_mat = nx.attribute_mixing_matrix(G, "gender", mapping=mapping)
105
+ >>> mix_mat
106
+ array([[0. , 0.25],
107
+ [0.25, 0.5 ]])
108
+ """
109
+ d = attribute_mixing_dict(G, attribute, nodes)
110
+ a = dict_to_numpy_array(d, mapping=mapping)
111
+ if normalized:
112
+ a = a / a.sum()
113
+ return a
114
+
115
+
116
+ @nx._dispatchable(edge_attrs="weight")
117
+ def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False):
118
+ """Returns dictionary representation of mixing matrix for degree.
119
+
120
+ Parameters
121
+ ----------
122
+ G : graph
123
+ NetworkX graph object.
124
+
125
+ x: string ('in','out')
126
+ The degree type for source node (directed graphs only).
127
+
128
+ y: string ('in','out')
129
+ The degree type for target node (directed graphs only).
130
+
131
+ weight: string or None, optional (default=None)
132
+ The edge attribute that holds the numerical value used
133
+ as a weight. If None, then each edge has weight 1.
134
+ The degree is the sum of the edge weights adjacent to the node.
135
+
136
+ normalized : bool (default=False)
137
+ Return counts if False or probabilities if True.
138
+
139
+ Returns
140
+ -------
141
+ d: dictionary
142
+ Counts or joint probability of occurrence of degree pairs.
143
+ """
144
+ xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
145
+ return mixing_dict(xy_iter, normalized=normalized)
146
+
147
+
148
+ @nx._dispatchable(edge_attrs="weight")
149
+ def degree_mixing_matrix(
150
+ G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None
151
+ ):
152
+ """Returns mixing matrix for attribute.
153
+
154
+ Parameters
155
+ ----------
156
+ G : graph
157
+ NetworkX graph object.
158
+
159
+ x: string ('in','out')
160
+ The degree type for source node (directed graphs only).
161
+
162
+ y: string ('in','out')
163
+ The degree type for target node (directed graphs only).
164
+
165
+ nodes: list or iterable (optional)
166
+ Build the matrix using only nodes in container.
167
+ The default is all nodes.
168
+
169
+ weight: string or None, optional (default=None)
170
+ The edge attribute that holds the numerical value used
171
+ as a weight. If None, then each edge has weight 1.
172
+ The degree is the sum of the edge weights adjacent to the node.
173
+
174
+ normalized : bool (default=True)
175
+ Return counts if False or probabilities if True.
176
+
177
+ mapping : dictionary, optional
178
+ Mapping from node degree to integer index in matrix.
179
+ If not specified, an arbitrary ordering will be used.
180
+
181
+ Returns
182
+ -------
183
+ m: numpy array
184
+ Counts, or joint probability, of occurrence of node degree.
185
+
186
+ Notes
187
+ -----
188
+ Definitions of degree mixing matrix vary on whether the matrix
189
+ should include rows for degree values that don't arise. Here we
190
+ do not include such empty-rows. But you can force them to appear
191
+ by inputting a `mapping` that includes those values. See examples.
192
+
193
+ Examples
194
+ --------
195
+ >>> G = nx.star_graph(3)
196
+ >>> mix_mat = nx.degree_mixing_matrix(G)
197
+ >>> mix_mat
198
+ array([[0. , 0.5],
199
+ [0.5, 0. ]])
200
+
201
+ If you want every possible degree to appear as a row, even if no nodes
202
+ have that degree, use `mapping` as follows,
203
+
204
+ >>> max_degree = max(deg for n, deg in G.degree)
205
+ >>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping
206
+ >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping)
207
+ >>> mix_mat
208
+ array([[0. , 0. , 0. , 0. ],
209
+ [0. , 0. , 0. , 0.5],
210
+ [0. , 0. , 0. , 0. ],
211
+ [0. , 0.5, 0. , 0. ]])
212
+ """
213
+ d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
214
+ a = dict_to_numpy_array(d, mapping=mapping)
215
+ if normalized:
216
+ a = a / a.sum()
217
+ return a
218
+
219
+
220
+ def mixing_dict(xy, normalized=False):
221
+ """Returns a dictionary representation of mixing matrix.
222
+
223
+ Parameters
224
+ ----------
225
+ xy : list or container of two-tuples
226
+ Pairs of (x,y) items.
227
+
228
+ attribute : string
229
+ Node attribute key
230
+
231
+ normalized : bool (default=False)
232
+ Return counts if False or probabilities if True.
233
+
234
+ Returns
235
+ -------
236
+ d: dictionary
237
+ Counts or Joint probability of occurrence of values in xy.
238
+ """
239
+ d = {}
240
+ psum = 0.0
241
+ for x, y in xy:
242
+ if x not in d:
243
+ d[x] = {}
244
+ if y not in d:
245
+ d[y] = {}
246
+ v = d[x].get(y, 0)
247
+ d[x][y] = v + 1
248
+ psum += 1
249
+
250
+ if normalized:
251
+ for _, jdict in d.items():
252
+ for j in jdict:
253
+ jdict[j] /= psum
254
+ return d
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/neighbor_degree.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["average_neighbor_degree"]
4
+
5
+
6
+ @nx._dispatchable(edge_attrs="weight")
7
+ def average_neighbor_degree(G, source="out", target="out", nodes=None, weight=None):
8
+ r"""Returns the average degree of the neighborhood of each node.
9
+
10
+ In an undirected graph, the neighborhood `N(i)` of node `i` contains the
11
+ nodes that are connected to `i` by an edge.
12
+
13
+ For directed graphs, `N(i)` is defined according to the parameter `source`:
14
+
15
+ - if source is 'in', then `N(i)` consists of predecessors of node `i`.
16
+ - if source is 'out', then `N(i)` consists of successors of node `i`.
17
+ - if source is 'in+out', then `N(i)` is both predecessors and successors.
18
+
19
+ The average neighborhood degree of a node `i` is
20
+
21
+ .. math::
22
+
23
+ k_{nn,i} = \frac{1}{|N(i)|} \sum_{j \in N(i)} k_j
24
+
25
+ where `N(i)` are the neighbors of node `i` and `k_j` is
26
+ the degree of node `j` which belongs to `N(i)`. For weighted
27
+ graphs, an analogous measure can be defined [1]_,
28
+
29
+ .. math::
30
+
31
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
32
+
33
+ where `s_i` is the weighted degree of node `i`, `w_{ij}`
34
+ is the weight of the edge that links `i` and `j` and
35
+ `N(i)` are the neighbors of node `i`.
36
+
37
+
38
+ Parameters
39
+ ----------
40
+ G : NetworkX graph
41
+
42
+ source : string ("in"|"out"|"in+out"), optional (default="out")
43
+ Directed graphs only.
44
+ Use "in"- or "out"-neighbors of source node.
45
+
46
+ target : string ("in"|"out"|"in+out"), optional (default="out")
47
+ Directed graphs only.
48
+ Use "in"- or "out"-degree for target node.
49
+
50
+ nodes : list or iterable, optional (default=G.nodes)
51
+ Compute neighbor degree only for specified nodes.
52
+
53
+ weight : string or None, optional (default=None)
54
+ The edge attribute that holds the numerical value used as a weight.
55
+ If None, then each edge has weight 1.
56
+
57
+ Returns
58
+ -------
59
+ d: dict
60
+ A dictionary keyed by node to the average degree of its neighbors.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXError
65
+ If either `source` or `target` are not one of 'in', 'out', or 'in+out'.
66
+ If either `source` or `target` is passed for an undirected graph.
67
+
68
+ Examples
69
+ --------
70
+ >>> G = nx.path_graph(4)
71
+ >>> G.edges[0, 1]["weight"] = 5
72
+ >>> G.edges[2, 3]["weight"] = 3
73
+
74
+ >>> nx.average_neighbor_degree(G)
75
+ {0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
76
+ >>> nx.average_neighbor_degree(G, weight="weight")
77
+ {0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
78
+
79
+ >>> G = nx.DiGraph()
80
+ >>> nx.add_path(G, [0, 1, 2, 3])
81
+ >>> nx.average_neighbor_degree(G, source="in", target="in")
82
+ {0: 0.0, 1: 0.0, 2: 1.0, 3: 1.0}
83
+
84
+ >>> nx.average_neighbor_degree(G, source="out", target="out")
85
+ {0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}
86
+
87
+ See Also
88
+ --------
89
+ average_degree_connectivity
90
+
91
+ References
92
+ ----------
93
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
94
+ "The architecture of complex weighted networks".
95
+ PNAS 101 (11): 3747–3752 (2004).
96
+ """
97
+ if G.is_directed():
98
+ if source == "in":
99
+ source_degree = G.in_degree
100
+ elif source == "out":
101
+ source_degree = G.out_degree
102
+ elif source == "in+out":
103
+ source_degree = G.degree
104
+ else:
105
+ raise nx.NetworkXError(
106
+ f"source argument {source} must be 'in', 'out' or 'in+out'"
107
+ )
108
+
109
+ if target == "in":
110
+ target_degree = G.in_degree
111
+ elif target == "out":
112
+ target_degree = G.out_degree
113
+ elif target == "in+out":
114
+ target_degree = G.degree
115
+ else:
116
+ raise nx.NetworkXError(
117
+ f"target argument {target} must be 'in', 'out' or 'in+out'"
118
+ )
119
+ else:
120
+ if source != "out" or target != "out":
121
+ raise nx.NetworkXError(
122
+ f"source and target arguments are only supported for directed graphs"
123
+ )
124
+ source_degree = target_degree = G.degree
125
+
126
+ # precompute target degrees -- should *not* be weighted degree
127
+ t_deg = dict(target_degree())
128
+
129
+ # Set up both predecessor and successor neighbor dicts leaving empty if not needed
130
+ G_P = G_S = {n: {} for n in G}
131
+ if G.is_directed():
132
+ # "in" or "in+out" cases: G_P contains predecessors
133
+ if "in" in source:
134
+ G_P = G.pred
135
+ # "out" or "in+out" cases: G_S contains successors
136
+ if "out" in source:
137
+ G_S = G.succ
138
+ else:
139
+ # undirected leave G_P empty but G_S is the adjacency
140
+ G_S = G.adj
141
+
142
+ # Main loop: Compute average degree of neighbors
143
+ avg = {}
144
+ for n, deg in source_degree(nodes, weight=weight):
145
+ # handle degree zero average
146
+ if deg == 0:
147
+ avg[n] = 0.0
148
+ continue
149
+
150
+ # we sum over both G_P and G_S, but one of the two is usually empty.
151
+ if weight is None:
152
+ avg[n] = (
153
+ sum(t_deg[nbr] for nbr in G_S[n]) + sum(t_deg[nbr] for nbr in G_P[n])
154
+ ) / deg
155
+ else:
156
+ avg[n] = (
157
+ sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_S[n].items())
158
+ + sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_P[n].items())
159
+ ) / deg
160
+ return avg
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/pairs.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators of x-y pairs of node data."""
2
+ import networkx as nx
3
+
4
+ __all__ = ["node_attribute_xy", "node_degree_xy"]
5
+
6
+
7
+ @nx._dispatchable(node_attrs="attribute")
8
+ def node_attribute_xy(G, attribute, nodes=None):
9
+ """Returns iterator of node-attribute pairs for all edges in G.
10
+
11
+ Parameters
12
+ ----------
13
+ G: NetworkX graph
14
+
15
+ attribute: key
16
+ The node attribute key.
17
+
18
+ nodes: list or iterable (optional)
19
+ Use only edges that are incident to specified nodes.
20
+ The default is all nodes.
21
+
22
+ Returns
23
+ -------
24
+ (x, y): 2-tuple
25
+ Generates 2-tuple of (attribute, attribute) values.
26
+
27
+ Examples
28
+ --------
29
+ >>> G = nx.DiGraph()
30
+ >>> G.add_node(1, color="red")
31
+ >>> G.add_node(2, color="blue")
32
+ >>> G.add_edge(1, 2)
33
+ >>> list(nx.node_attribute_xy(G, "color"))
34
+ [('red', 'blue')]
35
+
36
+ Notes
37
+ -----
38
+ For undirected graphs each edge is produced twice, once for each edge
39
+ representation (u, v) and (v, u), with the exception of self-loop edges
40
+ which only appear once.
41
+ """
42
+ if nodes is None:
43
+ nodes = set(G)
44
+ else:
45
+ nodes = set(nodes)
46
+ Gnodes = G.nodes
47
+ for u, nbrsdict in G.adjacency():
48
+ if u not in nodes:
49
+ continue
50
+ uattr = Gnodes[u].get(attribute, None)
51
+ if G.is_multigraph():
52
+ for v, keys in nbrsdict.items():
53
+ vattr = Gnodes[v].get(attribute, None)
54
+ for _ in keys:
55
+ yield (uattr, vattr)
56
+ else:
57
+ for v in nbrsdict:
58
+ vattr = Gnodes[v].get(attribute, None)
59
+ yield (uattr, vattr)
60
+
61
+
62
+ @nx._dispatchable(edge_attrs="weight")
63
+ def node_degree_xy(G, x="out", y="in", weight=None, nodes=None):
64
+ """Generate node degree-degree pairs for edges in G.
65
+
66
+ Parameters
67
+ ----------
68
+ G: NetworkX graph
69
+
70
+ x: string ('in','out')
71
+ The degree type for source node (directed graphs only).
72
+
73
+ y: string ('in','out')
74
+ The degree type for target node (directed graphs only).
75
+
76
+ weight: string or None, optional (default=None)
77
+ The edge attribute that holds the numerical value used
78
+ as a weight. If None, then each edge has weight 1.
79
+ The degree is the sum of the edge weights adjacent to the node.
80
+
81
+ nodes: list or iterable (optional)
82
+ Use only edges that are adjacency to specified nodes.
83
+ The default is all nodes.
84
+
85
+ Returns
86
+ -------
87
+ (x, y): 2-tuple
88
+ Generates 2-tuple of (degree, degree) values.
89
+
90
+
91
+ Examples
92
+ --------
93
+ >>> G = nx.DiGraph()
94
+ >>> G.add_edge(1, 2)
95
+ >>> list(nx.node_degree_xy(G, x="out", y="in"))
96
+ [(1, 1)]
97
+ >>> list(nx.node_degree_xy(G, x="in", y="out"))
98
+ [(0, 0)]
99
+
100
+ Notes
101
+ -----
102
+ For undirected graphs each edge is produced twice, once for each edge
103
+ representation (u, v) and (v, u), with the exception of self-loop edges
104
+ which only appear once.
105
+ """
106
+ nodes = set(G) if nodes is None else set(nodes)
107
+ if G.is_directed():
108
+ direction = {"out": G.out_degree, "in": G.in_degree}
109
+ xdeg = direction[x]
110
+ ydeg = direction[y]
111
+ else:
112
+ xdeg = ydeg = G.degree
113
+
114
+ for u, degu in xdeg(nodes, weight=weight):
115
+ # use G.edges to treat multigraphs correctly
116
+ neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes)
117
+ for _, degv in ydeg(neighbors, weight=weight):
118
+ yield degu, degv
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (204 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/base_test.cpython-310.pyc ADDED
Binary file (2.48 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_connectivity.cpython-310.pyc ADDED
Binary file (4.41 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_correlation.cpython-310.pyc ADDED
Binary file (7.09 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_mixing.cpython-310.pyc ADDED
Binary file (7.59 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-310.pyc ADDED
Binary file (3.69 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/base_test.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+
4
+ class BaseTestAttributeMixing:
5
+ @classmethod
6
+ def setup_class(cls):
7
+ G = nx.Graph()
8
+ G.add_nodes_from([0, 1], fish="one")
9
+ G.add_nodes_from([2, 3], fish="two")
10
+ G.add_nodes_from([4], fish="red")
11
+ G.add_nodes_from([5], fish="blue")
12
+ G.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
13
+ cls.G = G
14
+
15
+ D = nx.DiGraph()
16
+ D.add_nodes_from([0, 1], fish="one")
17
+ D.add_nodes_from([2, 3], fish="two")
18
+ D.add_nodes_from([4], fish="red")
19
+ D.add_nodes_from([5], fish="blue")
20
+ D.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
21
+ cls.D = D
22
+
23
+ M = nx.MultiGraph()
24
+ M.add_nodes_from([0, 1], fish="one")
25
+ M.add_nodes_from([2, 3], fish="two")
26
+ M.add_nodes_from([4], fish="red")
27
+ M.add_nodes_from([5], fish="blue")
28
+ M.add_edges_from([(0, 1), (0, 1), (2, 3)])
29
+ cls.M = M
30
+
31
+ S = nx.Graph()
32
+ S.add_nodes_from([0, 1], fish="one")
33
+ S.add_nodes_from([2, 3], fish="two")
34
+ S.add_nodes_from([4], fish="red")
35
+ S.add_nodes_from([5], fish="blue")
36
+ S.add_edge(0, 0)
37
+ S.add_edge(2, 2)
38
+ cls.S = S
39
+
40
+ N = nx.Graph()
41
+ N.add_nodes_from([0, 1], margin=-2)
42
+ N.add_nodes_from([2, 3], margin=-2)
43
+ N.add_nodes_from([4], margin=-3)
44
+ N.add_nodes_from([5], margin=-4)
45
+ N.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
46
+ cls.N = N
47
+
48
+ F = nx.Graph()
49
+ F.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
50
+ F.add_edge(0, 2, weight=1)
51
+ nx.set_node_attributes(F, dict(F.degree(weight="weight")), "margin")
52
+ cls.F = F
53
+
54
+ K = nx.Graph()
55
+ K.add_nodes_from([1, 2], margin=-1)
56
+ K.add_nodes_from([3], margin=1)
57
+ K.add_nodes_from([4], margin=2)
58
+ K.add_edges_from([(3, 4), (1, 2), (1, 3)])
59
+ cls.K = K
60
+
61
+
62
+ class BaseTestDegreeMixing:
63
+ @classmethod
64
+ def setup_class(cls):
65
+ cls.P4 = nx.path_graph(4)
66
+ cls.D = nx.DiGraph()
67
+ cls.D.add_edges_from([(0, 2), (0, 3), (1, 3), (2, 3)])
68
+ cls.D2 = nx.DiGraph()
69
+ cls.D2.add_edges_from([(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)])
70
+ cls.M = nx.MultiGraph()
71
+ nx.add_path(cls.M, range(4))
72
+ cls.M.add_edge(0, 1)
73
+ cls.S = nx.Graph()
74
+ cls.S.add_edges_from([(0, 0), (1, 1)])
75
+ cls.W = nx.Graph()
76
+ cls.W.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
77
+ cls.W.add_edge(0, 2, weight=1)
78
+ S1 = nx.star_graph(4)
79
+ S2 = nx.star_graph(4)
80
+ cls.DS = nx.disjoint_union(S1, S2)
81
+ cls.DS.add_edge(4, 5)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import permutations
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestNeighborConnectivity:
9
+ def test_degree_p4(self):
10
+ G = nx.path_graph(4)
11
+ answer = {1: 2.0, 2: 1.5}
12
+ nd = nx.average_degree_connectivity(G)
13
+ assert nd == answer
14
+
15
+ D = G.to_directed()
16
+ answer = {2: 2.0, 4: 1.5}
17
+ nd = nx.average_degree_connectivity(D)
18
+ assert nd == answer
19
+
20
+ answer = {1: 2.0, 2: 1.5}
21
+ D = G.to_directed()
22
+ nd = nx.average_degree_connectivity(D, source="in", target="in")
23
+ assert nd == answer
24
+
25
+ D = G.to_directed()
26
+ nd = nx.average_degree_connectivity(D, source="in", target="in")
27
+ assert nd == answer
28
+
29
+ def test_degree_p4_weighted(self):
30
+ G = nx.path_graph(4)
31
+ G[1][2]["weight"] = 4
32
+ answer = {1: 2.0, 2: 1.8}
33
+ nd = nx.average_degree_connectivity(G, weight="weight")
34
+ assert nd == answer
35
+ answer = {1: 2.0, 2: 1.5}
36
+ nd = nx.average_degree_connectivity(G)
37
+ assert nd == answer
38
+
39
+ D = G.to_directed()
40
+ answer = {2: 2.0, 4: 1.8}
41
+ nd = nx.average_degree_connectivity(D, weight="weight")
42
+ assert nd == answer
43
+
44
+ answer = {1: 2.0, 2: 1.8}
45
+ D = G.to_directed()
46
+ nd = nx.average_degree_connectivity(
47
+ D, weight="weight", source="in", target="in"
48
+ )
49
+ assert nd == answer
50
+
51
+ D = G.to_directed()
52
+ nd = nx.average_degree_connectivity(
53
+ D, source="in", target="out", weight="weight"
54
+ )
55
+ assert nd == answer
56
+
57
+ def test_weight_keyword(self):
58
+ G = nx.path_graph(4)
59
+ G[1][2]["other"] = 4
60
+ answer = {1: 2.0, 2: 1.8}
61
+ nd = nx.average_degree_connectivity(G, weight="other")
62
+ assert nd == answer
63
+ answer = {1: 2.0, 2: 1.5}
64
+ nd = nx.average_degree_connectivity(G, weight=None)
65
+ assert nd == answer
66
+
67
+ D = G.to_directed()
68
+ answer = {2: 2.0, 4: 1.8}
69
+ nd = nx.average_degree_connectivity(D, weight="other")
70
+ assert nd == answer
71
+
72
+ answer = {1: 2.0, 2: 1.8}
73
+ D = G.to_directed()
74
+ nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in")
75
+ assert nd == answer
76
+
77
+ D = G.to_directed()
78
+ nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in")
79
+ assert nd == answer
80
+
81
+ def test_degree_barrat(self):
82
+ G = nx.star_graph(5)
83
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
84
+ G[0][5]["weight"] = 5
85
+ nd = nx.average_degree_connectivity(G)[5]
86
+ assert nd == 1.8
87
+ nd = nx.average_degree_connectivity(G, weight="weight")[5]
88
+ assert nd == pytest.approx(3.222222, abs=1e-5)
89
+
90
+ def test_zero_deg(self):
91
+ G = nx.DiGraph()
92
+ G.add_edge(1, 2)
93
+ G.add_edge(1, 3)
94
+ G.add_edge(1, 4)
95
+ c = nx.average_degree_connectivity(G)
96
+ assert c == {1: 0, 3: 1}
97
+ c = nx.average_degree_connectivity(G, source="in", target="in")
98
+ assert c == {0: 0, 1: 0}
99
+ c = nx.average_degree_connectivity(G, source="in", target="out")
100
+ assert c == {0: 0, 1: 3}
101
+ c = nx.average_degree_connectivity(G, source="in", target="in+out")
102
+ assert c == {0: 0, 1: 3}
103
+ c = nx.average_degree_connectivity(G, source="out", target="out")
104
+ assert c == {0: 0, 3: 0}
105
+ c = nx.average_degree_connectivity(G, source="out", target="in")
106
+ assert c == {0: 0, 3: 1}
107
+ c = nx.average_degree_connectivity(G, source="out", target="in+out")
108
+ assert c == {0: 0, 3: 1}
109
+
110
+ def test_in_out_weight(self):
111
+ G = nx.DiGraph()
112
+ G.add_edge(1, 2, weight=1)
113
+ G.add_edge(1, 3, weight=1)
114
+ G.add_edge(3, 1, weight=1)
115
+ for s, t in permutations(["in", "out", "in+out"], 2):
116
+ c = nx.average_degree_connectivity(G, source=s, target=t)
117
+ cw = nx.average_degree_connectivity(G, source=s, target=t, weight="weight")
118
+ assert c == cw
119
+
120
+ def test_invalid_source(self):
121
+ with pytest.raises(nx.NetworkXError):
122
+ G = nx.DiGraph()
123
+ nx.average_degree_connectivity(G, source="bogus")
124
+
125
+ def test_invalid_target(self):
126
+ with pytest.raises(nx.NetworkXError):
127
+ G = nx.DiGraph()
128
+ nx.average_degree_connectivity(G, target="bogus")
129
+
130
+ def test_invalid_undirected_graph(self):
131
+ G = nx.Graph()
132
+ with pytest.raises(nx.NetworkXError):
133
+ nx.average_degree_connectivity(G, target="bogus")
134
+ with pytest.raises(nx.NetworkXError):
135
+ nx.average_degree_connectivity(G, source="bogus")
136
+
137
+ def test_single_node(self):
138
+ # TODO Is this really the intended behavior for providing a
139
+ # single node as the argument `nodes`? Shouldn't the function
140
+ # just return the connectivity value itself?
141
+ G = nx.trivial_graph()
142
+ conn = nx.average_degree_connectivity(G, nodes=0)
143
+ assert conn == {0: 0}
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_correlation.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+ pytest.importorskip("scipy")
5
+
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.assortativity.correlation import attribute_ac
9
+
10
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
11
+
12
+
13
+ class TestDegreeMixingCorrelation(BaseTestDegreeMixing):
14
+ def test_degree_assortativity_undirected(self):
15
+ r = nx.degree_assortativity_coefficient(self.P4)
16
+ np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
17
+
18
+ def test_degree_assortativity_node_kwargs(self):
19
+ G = nx.Graph()
20
+ edges = [(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (5, 9), (9, 0)]
21
+ G.add_edges_from(edges)
22
+ r = nx.degree_assortativity_coefficient(G, nodes=[1, 2, 4])
23
+ np.testing.assert_almost_equal(r, -1.0, decimal=4)
24
+
25
+ def test_degree_assortativity_directed(self):
26
+ r = nx.degree_assortativity_coefficient(self.D)
27
+ np.testing.assert_almost_equal(r, -0.57735, decimal=4)
28
+
29
+ def test_degree_assortativity_directed2(self):
30
+ """Test degree assortativity for a directed graph where the set of
31
+ in/out degree does not equal the total degree."""
32
+ r = nx.degree_assortativity_coefficient(self.D2)
33
+ np.testing.assert_almost_equal(r, 0.14852, decimal=4)
34
+
35
+ def test_degree_assortativity_multigraph(self):
36
+ r = nx.degree_assortativity_coefficient(self.M)
37
+ np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
38
+
39
+ def test_degree_pearson_assortativity_undirected(self):
40
+ r = nx.degree_pearson_correlation_coefficient(self.P4)
41
+ np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
42
+
43
+ def test_degree_pearson_assortativity_directed(self):
44
+ r = nx.degree_pearson_correlation_coefficient(self.D)
45
+ np.testing.assert_almost_equal(r, -0.57735, decimal=4)
46
+
47
+ def test_degree_pearson_assortativity_directed2(self):
48
+ """Test degree assortativity with Pearson for a directed graph where
49
+ the set of in/out degree does not equal the total degree."""
50
+ r = nx.degree_pearson_correlation_coefficient(self.D2)
51
+ np.testing.assert_almost_equal(r, 0.14852, decimal=4)
52
+
53
+ def test_degree_pearson_assortativity_multigraph(self):
54
+ r = nx.degree_pearson_correlation_coefficient(self.M)
55
+ np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
56
+
57
+ def test_degree_assortativity_weighted(self):
58
+ r = nx.degree_assortativity_coefficient(self.W, weight="weight")
59
+ np.testing.assert_almost_equal(r, -0.1429, decimal=4)
60
+
61
+ def test_degree_assortativity_double_star(self):
62
+ r = nx.degree_assortativity_coefficient(self.DS)
63
+ np.testing.assert_almost_equal(r, -0.9339, decimal=4)
64
+
65
+
66
+ class TestAttributeMixingCorrelation(BaseTestAttributeMixing):
67
+ def test_attribute_assortativity_undirected(self):
68
+ r = nx.attribute_assortativity_coefficient(self.G, "fish")
69
+ assert r == 6.0 / 22.0
70
+
71
+ def test_attribute_assortativity_directed(self):
72
+ r = nx.attribute_assortativity_coefficient(self.D, "fish")
73
+ assert r == 1.0 / 3.0
74
+
75
+ def test_attribute_assortativity_multigraph(self):
76
+ r = nx.attribute_assortativity_coefficient(self.M, "fish")
77
+ assert r == 1.0
78
+
79
+ def test_attribute_assortativity_coefficient(self):
80
+ # from "Mixing patterns in networks"
81
+ # fmt: off
82
+ a = np.array([[0.258, 0.016, 0.035, 0.013],
83
+ [0.012, 0.157, 0.058, 0.019],
84
+ [0.013, 0.023, 0.306, 0.035],
85
+ [0.005, 0.007, 0.024, 0.016]])
86
+ # fmt: on
87
+ r = attribute_ac(a)
88
+ np.testing.assert_almost_equal(r, 0.623, decimal=3)
89
+
90
+ def test_attribute_assortativity_coefficient2(self):
91
+ # fmt: off
92
+ a = np.array([[0.18, 0.02, 0.01, 0.03],
93
+ [0.02, 0.20, 0.03, 0.02],
94
+ [0.01, 0.03, 0.16, 0.01],
95
+ [0.03, 0.02, 0.01, 0.22]])
96
+ # fmt: on
97
+ r = attribute_ac(a)
98
+ np.testing.assert_almost_equal(r, 0.68, decimal=2)
99
+
100
+ def test_attribute_assortativity(self):
101
+ a = np.array([[50, 50, 0], [50, 50, 0], [0, 0, 2]])
102
+ r = attribute_ac(a)
103
+ np.testing.assert_almost_equal(r, 0.029, decimal=3)
104
+
105
+ def test_attribute_assortativity_negative(self):
106
+ r = nx.numeric_assortativity_coefficient(self.N, "margin")
107
+ np.testing.assert_almost_equal(r, -0.2903, decimal=4)
108
+
109
+ def test_assortativity_node_kwargs(self):
110
+ G = nx.Graph()
111
+ G.add_nodes_from([0, 1], size=2)
112
+ G.add_nodes_from([2, 3], size=3)
113
+ G.add_edges_from([(0, 1), (2, 3)])
114
+ r = nx.numeric_assortativity_coefficient(G, "size", nodes=[0, 3])
115
+ np.testing.assert_almost_equal(r, 1.0, decimal=4)
116
+
117
+ def test_attribute_assortativity_float(self):
118
+ r = nx.numeric_assortativity_coefficient(self.F, "margin")
119
+ np.testing.assert_almost_equal(r, -0.1429, decimal=4)
120
+
121
+ def test_attribute_assortativity_mixed(self):
122
+ r = nx.numeric_assortativity_coefficient(self.K, "margin")
123
+ np.testing.assert_almost_equal(r, 0.4340, decimal=4)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+
6
+ import networkx as nx
7
+
8
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
9
+
10
+
11
+ class TestDegreeMixingDict(BaseTestDegreeMixing):
12
+ def test_degree_mixing_dict_undirected(self):
13
+ d = nx.degree_mixing_dict(self.P4)
14
+ d_result = {1: {2: 2}, 2: {1: 2, 2: 2}}
15
+ assert d == d_result
16
+
17
+ def test_degree_mixing_dict_undirected_normalized(self):
18
+ d = nx.degree_mixing_dict(self.P4, normalized=True)
19
+ d_result = {1: {2: 1.0 / 3}, 2: {1: 1.0 / 3, 2: 1.0 / 3}}
20
+ assert d == d_result
21
+
22
+ def test_degree_mixing_dict_directed(self):
23
+ d = nx.degree_mixing_dict(self.D)
24
+ print(d)
25
+ d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}}
26
+ assert d == d_result
27
+
28
+ def test_degree_mixing_dict_multigraph(self):
29
+ d = nx.degree_mixing_dict(self.M)
30
+ d_result = {1: {2: 1}, 2: {1: 1, 3: 3}, 3: {2: 3}}
31
+ assert d == d_result
32
+
33
+ def test_degree_mixing_dict_weighted(self):
34
+ d = nx.degree_mixing_dict(self.W, weight="weight")
35
+ d_result = {0.5: {1.5: 1}, 1.5: {1.5: 6, 0.5: 1}}
36
+ assert d == d_result
37
+
38
+
39
+ class TestDegreeMixingMatrix(BaseTestDegreeMixing):
40
+ def test_degree_mixing_matrix_undirected(self):
41
+ # fmt: off
42
+ a_result = np.array([[0, 2],
43
+ [2, 2]]
44
+ )
45
+ # fmt: on
46
+ a = nx.degree_mixing_matrix(self.P4, normalized=False)
47
+ np.testing.assert_equal(a, a_result)
48
+ a = nx.degree_mixing_matrix(self.P4)
49
+ np.testing.assert_equal(a, a_result / a_result.sum())
50
+
51
+ def test_degree_mixing_matrix_directed(self):
52
+ # fmt: off
53
+ a_result = np.array([[0, 0, 2],
54
+ [1, 0, 1],
55
+ [0, 0, 0]]
56
+ )
57
+ # fmt: on
58
+ a = nx.degree_mixing_matrix(self.D, normalized=False)
59
+ np.testing.assert_equal(a, a_result)
60
+ a = nx.degree_mixing_matrix(self.D)
61
+ np.testing.assert_equal(a, a_result / a_result.sum())
62
+
63
+ def test_degree_mixing_matrix_multigraph(self):
64
+ # fmt: off
65
+ a_result = np.array([[0, 1, 0],
66
+ [1, 0, 3],
67
+ [0, 3, 0]]
68
+ )
69
+ # fmt: on
70
+ a = nx.degree_mixing_matrix(self.M, normalized=False)
71
+ np.testing.assert_equal(a, a_result)
72
+ a = nx.degree_mixing_matrix(self.M)
73
+ np.testing.assert_equal(a, a_result / a_result.sum())
74
+
75
+ def test_degree_mixing_matrix_selfloop(self):
76
+ # fmt: off
77
+ a_result = np.array([[2]])
78
+ # fmt: on
79
+ a = nx.degree_mixing_matrix(self.S, normalized=False)
80
+ np.testing.assert_equal(a, a_result)
81
+ a = nx.degree_mixing_matrix(self.S)
82
+ np.testing.assert_equal(a, a_result / a_result.sum())
83
+
84
+ def test_degree_mixing_matrix_weighted(self):
85
+ a_result = np.array([[0.0, 1.0], [1.0, 6.0]])
86
+ a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False)
87
+ np.testing.assert_equal(a, a_result)
88
+ a = nx.degree_mixing_matrix(self.W, weight="weight")
89
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
90
+
91
+ def test_degree_mixing_matrix_mapping(self):
92
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
93
+ mapping = {0.5: 1, 1.5: 0}
94
+ a = nx.degree_mixing_matrix(
95
+ self.W, weight="weight", normalized=False, mapping=mapping
96
+ )
97
+ np.testing.assert_equal(a, a_result)
98
+
99
+
100
+ class TestAttributeMixingDict(BaseTestAttributeMixing):
101
+ def test_attribute_mixing_dict_undirected(self):
102
+ d = nx.attribute_mixing_dict(self.G, "fish")
103
+ d_result = {
104
+ "one": {"one": 2, "red": 1},
105
+ "two": {"two": 2, "blue": 1},
106
+ "red": {"one": 1},
107
+ "blue": {"two": 1},
108
+ }
109
+ assert d == d_result
110
+
111
+ def test_attribute_mixing_dict_directed(self):
112
+ d = nx.attribute_mixing_dict(self.D, "fish")
113
+ d_result = {
114
+ "one": {"one": 1, "red": 1},
115
+ "two": {"two": 1, "blue": 1},
116
+ "red": {},
117
+ "blue": {},
118
+ }
119
+ assert d == d_result
120
+
121
+ def test_attribute_mixing_dict_multigraph(self):
122
+ d = nx.attribute_mixing_dict(self.M, "fish")
123
+ d_result = {"one": {"one": 4}, "two": {"two": 2}}
124
+ assert d == d_result
125
+
126
+
127
+ class TestAttributeMixingMatrix(BaseTestAttributeMixing):
128
+ def test_attribute_mixing_matrix_undirected(self):
129
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
130
+ a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])
131
+ a = nx.attribute_mixing_matrix(
132
+ self.G, "fish", mapping=mapping, normalized=False
133
+ )
134
+ np.testing.assert_equal(a, a_result)
135
+ a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping)
136
+ np.testing.assert_equal(a, a_result / a_result.sum())
137
+
138
+ def test_attribute_mixing_matrix_directed(self):
139
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
140
+ a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
141
+ a = nx.attribute_mixing_matrix(
142
+ self.D, "fish", mapping=mapping, normalized=False
143
+ )
144
+ np.testing.assert_equal(a, a_result)
145
+ a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping)
146
+ np.testing.assert_equal(a, a_result / a_result.sum())
147
+
148
+ def test_attribute_mixing_matrix_multigraph(self):
149
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
150
+ a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
151
+ a = nx.attribute_mixing_matrix(
152
+ self.M, "fish", mapping=mapping, normalized=False
153
+ )
154
+ np.testing.assert_equal(a, a_result)
155
+ a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping)
156
+ np.testing.assert_equal(a, a_result / a_result.sum())
157
+
158
+ def test_attribute_mixing_matrix_negative(self):
159
+ mapping = {-2: 0, -3: 1, -4: 2}
160
+ a_result = np.array([[4.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
161
+ a = nx.attribute_mixing_matrix(
162
+ self.N, "margin", mapping=mapping, normalized=False
163
+ )
164
+ np.testing.assert_equal(a, a_result)
165
+ a = nx.attribute_mixing_matrix(self.N, "margin", mapping=mapping)
166
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
167
+
168
+ def test_attribute_mixing_matrix_float(self):
169
+ mapping = {0.5: 1, 1.5: 0}
170
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
171
+ a = nx.attribute_mixing_matrix(
172
+ self.F, "margin", mapping=mapping, normalized=False
173
+ )
174
+ np.testing.assert_equal(a, a_result)
175
+ a = nx.attribute_mixing_matrix(self.F, "margin", mapping=mapping)
176
+ np.testing.assert_equal(a, a_result / a_result.sum())
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestAverageNeighbor:
7
+ def test_degree_p4(self):
8
+ G = nx.path_graph(4)
9
+ answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2}
10
+ nd = nx.average_neighbor_degree(G)
11
+ assert nd == answer
12
+
13
+ D = G.to_directed()
14
+ nd = nx.average_neighbor_degree(D)
15
+ assert nd == answer
16
+
17
+ D = nx.DiGraph(G.edges(data=True))
18
+ nd = nx.average_neighbor_degree(D)
19
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
20
+ nd = nx.average_neighbor_degree(D, "in", "out")
21
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
22
+ nd = nx.average_neighbor_degree(D, "out", "in")
23
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
24
+ nd = nx.average_neighbor_degree(D, "in", "in")
25
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
26
+
27
+ def test_degree_p4_weighted(self):
28
+ G = nx.path_graph(4)
29
+ G[1][2]["weight"] = 4
30
+ answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2}
31
+ nd = nx.average_neighbor_degree(G, weight="weight")
32
+ assert nd == answer
33
+
34
+ D = G.to_directed()
35
+ nd = nx.average_neighbor_degree(D, weight="weight")
36
+ assert nd == answer
37
+
38
+ D = nx.DiGraph(G.edges(data=True))
39
+ print(D.edges(data=True))
40
+ nd = nx.average_neighbor_degree(D, weight="weight")
41
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
42
+ nd = nx.average_neighbor_degree(D, "out", "out", weight="weight")
43
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
44
+ nd = nx.average_neighbor_degree(D, "in", "in", weight="weight")
45
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
46
+ nd = nx.average_neighbor_degree(D, "in", "out", weight="weight")
47
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
48
+ nd = nx.average_neighbor_degree(D, "out", "in", weight="weight")
49
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
50
+ nd = nx.average_neighbor_degree(D, source="in+out", weight="weight")
51
+ assert nd == {0: 1.0, 1: 1.0, 2: 0.8, 3: 1.0}
52
+ nd = nx.average_neighbor_degree(D, target="in+out", weight="weight")
53
+ assert nd == {0: 2.0, 1: 2.0, 2: 1.0, 3: 0.0}
54
+
55
+ D = G.to_directed()
56
+ nd = nx.average_neighbor_degree(D, weight="weight")
57
+ assert nd == answer
58
+ nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight")
59
+ assert nd == answer
60
+
61
+ D = G.to_directed()
62
+ nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight")
63
+ assert nd == answer
64
+
65
+ def test_degree_k4(self):
66
+ G = nx.complete_graph(4)
67
+ answer = {0: 3, 1: 3, 2: 3, 3: 3}
68
+ nd = nx.average_neighbor_degree(G)
69
+ assert nd == answer
70
+
71
+ D = G.to_directed()
72
+ nd = nx.average_neighbor_degree(D)
73
+ assert nd == answer
74
+
75
+ D = G.to_directed()
76
+ nd = nx.average_neighbor_degree(D)
77
+ assert nd == answer
78
+
79
+ D = G.to_directed()
80
+ nd = nx.average_neighbor_degree(D, source="in", target="in")
81
+ assert nd == answer
82
+
83
+ def test_degree_k4_nodes(self):
84
+ G = nx.complete_graph(4)
85
+ answer = {1: 3.0, 2: 3.0}
86
+ nd = nx.average_neighbor_degree(G, nodes=[1, 2])
87
+ assert nd == answer
88
+
89
+ def test_degree_barrat(self):
90
+ G = nx.star_graph(5)
91
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
92
+ G[0][5]["weight"] = 5
93
+ nd = nx.average_neighbor_degree(G)[5]
94
+ assert nd == 1.8
95
+ nd = nx.average_neighbor_degree(G, weight="weight")[5]
96
+ assert nd == pytest.approx(3.222222, abs=1e-5)
97
+
98
+ def test_error_invalid_source_target(self):
99
+ G = nx.path_graph(4)
100
+ with pytest.raises(nx.NetworkXError):
101
+ nx.average_neighbor_degree(G, "error")
102
+ with pytest.raises(nx.NetworkXError):
103
+ nx.average_neighbor_degree(G, "in", "error")
104
+ G = G.to_directed()
105
+ with pytest.raises(nx.NetworkXError):
106
+ nx.average_neighbor_degree(G, "error")
107
+ with pytest.raises(nx.NetworkXError):
108
+ nx.average_neighbor_degree(G, "in", "error")
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_pairs.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
4
+
5
+
6
+ class TestAttributeMixingXY(BaseTestAttributeMixing):
7
+ def test_node_attribute_xy_undirected(self):
8
+ attrxy = sorted(nx.node_attribute_xy(self.G, "fish"))
9
+ attrxy_result = sorted(
10
+ [
11
+ ("one", "one"),
12
+ ("one", "one"),
13
+ ("two", "two"),
14
+ ("two", "two"),
15
+ ("one", "red"),
16
+ ("red", "one"),
17
+ ("blue", "two"),
18
+ ("two", "blue"),
19
+ ]
20
+ )
21
+ assert attrxy == attrxy_result
22
+
23
+ def test_node_attribute_xy_undirected_nodes(self):
24
+ attrxy = sorted(nx.node_attribute_xy(self.G, "fish", nodes=["one", "yellow"]))
25
+ attrxy_result = sorted([])
26
+ assert attrxy == attrxy_result
27
+
28
+ def test_node_attribute_xy_directed(self):
29
+ attrxy = sorted(nx.node_attribute_xy(self.D, "fish"))
30
+ attrxy_result = sorted(
31
+ [("one", "one"), ("two", "two"), ("one", "red"), ("two", "blue")]
32
+ )
33
+ assert attrxy == attrxy_result
34
+
35
+ def test_node_attribute_xy_multigraph(self):
36
+ attrxy = sorted(nx.node_attribute_xy(self.M, "fish"))
37
+ attrxy_result = [
38
+ ("one", "one"),
39
+ ("one", "one"),
40
+ ("one", "one"),
41
+ ("one", "one"),
42
+ ("two", "two"),
43
+ ("two", "two"),
44
+ ]
45
+ assert attrxy == attrxy_result
46
+
47
+ def test_node_attribute_xy_selfloop(self):
48
+ attrxy = sorted(nx.node_attribute_xy(self.S, "fish"))
49
+ attrxy_result = [("one", "one"), ("two", "two")]
50
+ assert attrxy == attrxy_result
51
+
52
+
53
+ class TestDegreeMixingXY(BaseTestDegreeMixing):
54
+ def test_node_degree_xy_undirected(self):
55
+ xy = sorted(nx.node_degree_xy(self.P4))
56
+ xy_result = sorted([(1, 2), (2, 1), (2, 2), (2, 2), (1, 2), (2, 1)])
57
+ assert xy == xy_result
58
+
59
+ def test_node_degree_xy_undirected_nodes(self):
60
+ xy = sorted(nx.node_degree_xy(self.P4, nodes=[0, 1, -1]))
61
+ xy_result = sorted([(1, 2), (2, 1)])
62
+ assert xy == xy_result
63
+
64
+ def test_node_degree_xy_directed(self):
65
+ xy = sorted(nx.node_degree_xy(self.D))
66
+ xy_result = sorted([(2, 1), (2, 3), (1, 3), (1, 3)])
67
+ assert xy == xy_result
68
+
69
+ def test_node_degree_xy_multigraph(self):
70
+ xy = sorted(nx.node_degree_xy(self.M))
71
+ xy_result = sorted(
72
+ [(2, 3), (2, 3), (3, 2), (3, 2), (2, 3), (3, 2), (1, 2), (2, 1)]
73
+ )
74
+ assert xy == xy_result
75
+
76
+ def test_node_degree_xy_selfloop(self):
77
+ xy = sorted(nx.node_degree_xy(self.S))
78
+ xy_result = sorted([(2, 2), (2, 2)])
79
+ assert xy == xy_result
80
+
81
+ def test_node_degree_xy_weighted(self):
82
+ G = nx.Graph()
83
+ G.add_edge(1, 2, weight=7)
84
+ G.add_edge(2, 3, weight=10)
85
+ xy = sorted(nx.node_degree_xy(G, weight="weight"))
86
+ xy_result = sorted([(7, 17), (17, 10), (17, 7), (10, 17)])
87
+ assert xy == xy_result
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/katz.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Katz centrality."""
2
+ import math
3
+
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = ["katz_centrality", "katz_centrality_numpy"]
8
+
9
+
10
+ @not_implemented_for("multigraph")
11
+ @nx._dispatchable(edge_attrs="weight")
12
+ def katz_centrality(
13
+ G,
14
+ alpha=0.1,
15
+ beta=1.0,
16
+ max_iter=1000,
17
+ tol=1.0e-6,
18
+ nstart=None,
19
+ normalized=True,
20
+ weight=None,
21
+ ):
22
+ r"""Compute the Katz centrality for the nodes of the graph G.
23
+
24
+ Katz centrality computes the centrality for a node based on the centrality
25
+ of its neighbors. It is a generalization of the eigenvector centrality. The
26
+ Katz centrality for node $i$ is
27
+
28
+ .. math::
29
+
30
+ x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
31
+
32
+ where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
33
+
34
+ The parameter $\beta$ controls the initial centrality and
35
+
36
+ .. math::
37
+
38
+ \alpha < \frac{1}{\lambda_{\max}}.
39
+
40
+ Katz centrality computes the relative influence of a node within a
41
+ network by measuring the number of the immediate neighbors (first
42
+ degree nodes) and also all other nodes in the network that connect
43
+ to the node under consideration through these immediate neighbors.
44
+
45
+ Extra weight can be provided to immediate neighbors through the
46
+ parameter $\beta$. Connections made with distant neighbors
47
+ are, however, penalized by an attenuation factor $\alpha$ which
48
+ should be strictly less than the inverse largest eigenvalue of the
49
+ adjacency matrix in order for the Katz centrality to be computed
50
+ correctly. More information is provided in [1]_.
51
+
52
+ Parameters
53
+ ----------
54
+ G : graph
55
+ A NetworkX graph.
56
+
57
+ alpha : float, optional (default=0.1)
58
+ Attenuation factor
59
+
60
+ beta : scalar or dictionary, optional (default=1.0)
61
+ Weight attributed to the immediate neighborhood. If not a scalar, the
62
+ dictionary must have a value for every node.
63
+
64
+ max_iter : integer, optional (default=1000)
65
+ Maximum number of iterations in power method.
66
+
67
+ tol : float, optional (default=1.0e-6)
68
+ Error tolerance used to check convergence in power method iteration.
69
+
70
+ nstart : dictionary, optional
71
+ Starting value of Katz iteration for each node.
72
+
73
+ normalized : bool, optional (default=True)
74
+ If True normalize the resulting values.
75
+
76
+ weight : None or string, optional (default=None)
77
+ If None, all edge weights are considered equal.
78
+ Otherwise holds the name of the edge attribute used as weight.
79
+ In this measure the weight is interpreted as the connection strength.
80
+
81
+ Returns
82
+ -------
83
+ nodes : dictionary
84
+ Dictionary of nodes with Katz centrality as the value.
85
+
86
+ Raises
87
+ ------
88
+ NetworkXError
89
+ If the parameter `beta` is not a scalar but lacks a value for at least
90
+ one node
91
+
92
+ PowerIterationFailedConvergence
93
+ If the algorithm fails to converge to the specified tolerance
94
+ within the specified number of iterations of the power iteration
95
+ method.
96
+
97
+ Examples
98
+ --------
99
+ >>> import math
100
+ >>> G = nx.path_graph(4)
101
+ >>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
102
+ >>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
103
+ >>> for n, c in sorted(centrality.items()):
104
+ ... print(f"{n} {c:.2f}")
105
+ 0 0.37
106
+ 1 0.60
107
+ 2 0.60
108
+ 3 0.37
109
+
110
+ See Also
111
+ --------
112
+ katz_centrality_numpy
113
+ eigenvector_centrality
114
+ eigenvector_centrality_numpy
115
+ :func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
116
+ :func:`~networkx.algorithms.link_analysis.hits_alg.hits`
117
+
118
+ Notes
119
+ -----
120
+ Katz centrality was introduced by [2]_.
121
+
122
+ This algorithm it uses the power method to find the eigenvector
123
+ corresponding to the largest eigenvalue of the adjacency matrix of ``G``.
124
+ The parameter ``alpha`` should be strictly less than the inverse of largest
125
+ eigenvalue of the adjacency matrix for the algorithm to converge.
126
+ You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
127
+ eigenvalue of the adjacency matrix.
128
+ The iteration will stop after ``max_iter`` iterations or an error tolerance of
129
+ ``number_of_nodes(G) * tol`` has been reached.
130
+
131
+ For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
132
+ Katz centrality approaches the results for eigenvector centrality.
133
+
134
+ For directed graphs this finds "left" eigenvectors which corresponds
135
+ to the in-edges in the graph. For out-edges Katz centrality,
136
+ first reverse the graph with ``G.reverse()``.
137
+
138
+ References
139
+ ----------
140
+ .. [1] Mark E. J. Newman:
141
+ Networks: An Introduction.
142
+ Oxford University Press, USA, 2010, p. 720.
143
+ .. [2] Leo Katz:
144
+ A New Status Index Derived from Sociometric Index.
145
+ Psychometrika 18(1):39–43, 1953
146
+ https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
147
+ """
148
+ if len(G) == 0:
149
+ return {}
150
+
151
+ nnodes = G.number_of_nodes()
152
+
153
+ if nstart is None:
154
+ # choose starting vector with entries of 0
155
+ x = {n: 0 for n in G}
156
+ else:
157
+ x = nstart
158
+
159
+ try:
160
+ b = dict.fromkeys(G, float(beta))
161
+ except (TypeError, ValueError, AttributeError) as err:
162
+ b = beta
163
+ if set(beta) != set(G):
164
+ raise nx.NetworkXError(
165
+ "beta dictionary must have a value for every node"
166
+ ) from err
167
+
168
+ # make up to max_iter iterations
169
+ for _ in range(max_iter):
170
+ xlast = x
171
+ x = dict.fromkeys(xlast, 0)
172
+ # do the multiplication y^T = Alpha * x^T A + Beta
173
+ for n in x:
174
+ for nbr in G[n]:
175
+ x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)
176
+ for n in x:
177
+ x[n] = alpha * x[n] + b[n]
178
+
179
+ # check convergence
180
+ error = sum(abs(x[n] - xlast[n]) for n in x)
181
+ if error < nnodes * tol:
182
+ if normalized:
183
+ # normalize vector
184
+ try:
185
+ s = 1.0 / math.hypot(*x.values())
186
+ except ZeroDivisionError:
187
+ s = 1.0
188
+ else:
189
+ s = 1
190
+ for n in x:
191
+ x[n] *= s
192
+ return x
193
+ raise nx.PowerIterationFailedConvergence(max_iter)
194
+
195
+
196
+ @not_implemented_for("multigraph")
197
+ @nx._dispatchable(edge_attrs="weight")
198
+ def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):
199
+ r"""Compute the Katz centrality for the graph G.
200
+
201
+ Katz centrality computes the centrality for a node based on the centrality
202
+ of its neighbors. It is a generalization of the eigenvector centrality. The
203
+ Katz centrality for node $i$ is
204
+
205
+ .. math::
206
+
207
+ x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
208
+
209
+ where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
210
+
211
+ The parameter $\beta$ controls the initial centrality and
212
+
213
+ .. math::
214
+
215
+ \alpha < \frac{1}{\lambda_{\max}}.
216
+
217
+ Katz centrality computes the relative influence of a node within a
218
+ network by measuring the number of the immediate neighbors (first
219
+ degree nodes) and also all other nodes in the network that connect
220
+ to the node under consideration through these immediate neighbors.
221
+
222
+ Extra weight can be provided to immediate neighbors through the
223
+ parameter $\beta$. Connections made with distant neighbors
224
+ are, however, penalized by an attenuation factor $\alpha$ which
225
+ should be strictly less than the inverse largest eigenvalue of the
226
+ adjacency matrix in order for the Katz centrality to be computed
227
+ correctly. More information is provided in [1]_.
228
+
229
+ Parameters
230
+ ----------
231
+ G : graph
232
+ A NetworkX graph
233
+
234
+ alpha : float
235
+ Attenuation factor
236
+
237
+ beta : scalar or dictionary, optional (default=1.0)
238
+ Weight attributed to the immediate neighborhood. If not a scalar the
239
+ dictionary must have an value for every node.
240
+
241
+ normalized : bool
242
+ If True normalize the resulting values.
243
+
244
+ weight : None or string, optional
245
+ If None, all edge weights are considered equal.
246
+ Otherwise holds the name of the edge attribute used as weight.
247
+ In this measure the weight is interpreted as the connection strength.
248
+
249
+ Returns
250
+ -------
251
+ nodes : dictionary
252
+ Dictionary of nodes with Katz centrality as the value.
253
+
254
+ Raises
255
+ ------
256
+ NetworkXError
257
+ If the parameter `beta` is not a scalar but lacks a value for at least
258
+ one node
259
+
260
+ Examples
261
+ --------
262
+ >>> import math
263
+ >>> G = nx.path_graph(4)
264
+ >>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
265
+ >>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
266
+ >>> for n, c in sorted(centrality.items()):
267
+ ... print(f"{n} {c:.2f}")
268
+ 0 0.37
269
+ 1 0.60
270
+ 2 0.60
271
+ 3 0.37
272
+
273
+ See Also
274
+ --------
275
+ katz_centrality
276
+ eigenvector_centrality_numpy
277
+ eigenvector_centrality
278
+ :func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
279
+ :func:`~networkx.algorithms.link_analysis.hits_alg.hits`
280
+
281
+ Notes
282
+ -----
283
+ Katz centrality was introduced by [2]_.
284
+
285
+ This algorithm uses a direct linear solver to solve the above equation.
286
+ The parameter ``alpha`` should be strictly less than the inverse of largest
287
+ eigenvalue of the adjacency matrix for there to be a solution.
288
+ You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
289
+ eigenvalue of the adjacency matrix.
290
+
291
+ For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
292
+ Katz centrality approaches the results for eigenvector centrality.
293
+
294
+ For directed graphs this finds "left" eigenvectors which corresponds
295
+ to the in-edges in the graph. For out-edges Katz centrality,
296
+ first reverse the graph with ``G.reverse()``.
297
+
298
+ References
299
+ ----------
300
+ .. [1] Mark E. J. Newman:
301
+ Networks: An Introduction.
302
+ Oxford University Press, USA, 2010, p. 173.
303
+ .. [2] Leo Katz:
304
+ A New Status Index Derived from Sociometric Index.
305
+ Psychometrika 18(1):39–43, 1953
306
+ https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
307
+ """
308
+ import numpy as np
309
+
310
+ if len(G) == 0:
311
+ return {}
312
+ try:
313
+ nodelist = beta.keys()
314
+ if set(nodelist) != set(G):
315
+ raise nx.NetworkXError("beta dictionary must have a value for every node")
316
+ b = np.array(list(beta.values()), dtype=float)
317
+ except AttributeError:
318
+ nodelist = list(G)
319
+ try:
320
+ b = np.ones((len(nodelist), 1)) * beta
321
+ except (TypeError, ValueError, AttributeError) as err:
322
+ raise nx.NetworkXError("beta must be a number") from err
323
+
324
+ A = nx.adjacency_matrix(G, nodelist=nodelist, weight=weight).todense().T
325
+ n = A.shape[0]
326
+ centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b).squeeze()
327
+
328
+ # Normalize: rely on truediv to cast to float, then tolist to make Python numbers
329
+ norm = np.sign(sum(centrality)) * np.linalg.norm(centrality) if normalized else 1
330
+ return dict(zip(nodelist, (centrality / norm).tolist()))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/reaching.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing reaching centrality of a node or a graph."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+ __all__ = ["global_reaching_centrality", "local_reaching_centrality"]
7
+
8
+
9
+ def _average_weight(G, path, weight=None):
10
+ """Returns the average weight of an edge in a weighted path.
11
+
12
+ Parameters
13
+ ----------
14
+ G : graph
15
+ A networkx graph.
16
+
17
+ path: list
18
+ A list of vertices that define the path.
19
+
20
+ weight : None or string, optional (default=None)
21
+ If None, edge weights are ignored. Then the average weight of an edge
22
+ is assumed to be the multiplicative inverse of the length of the path.
23
+ Otherwise holds the name of the edge attribute used as weight.
24
+ """
25
+ path_length = len(path) - 1
26
+ if path_length <= 0:
27
+ return 0
28
+ if weight is None:
29
+ return 1 / path_length
30
+ total_weight = sum(G.edges[i, j][weight] for i, j in pairwise(path))
31
+ return total_weight / path_length
32
+
33
+
34
+ @nx._dispatchable(edge_attrs="weight")
35
+ def global_reaching_centrality(G, weight=None, normalized=True):
36
+ """Returns the global reaching centrality of a directed graph.
37
+
38
+ The *global reaching centrality* of a weighted directed graph is the
39
+ average over all nodes of the difference between the local reaching
40
+ centrality of the node and the greatest local reaching centrality of
41
+ any node in the graph [1]_. For more information on the local
42
+ reaching centrality, see :func:`local_reaching_centrality`.
43
+ Informally, the local reaching centrality is the proportion of the
44
+ graph that is reachable from the neighbors of the node.
45
+
46
+ Parameters
47
+ ----------
48
+ G : DiGraph
49
+ A networkx DiGraph.
50
+
51
+ weight : None or string, optional (default=None)
52
+ Attribute to use for edge weights. If ``None``, each edge weight
53
+ is assumed to be one. A higher weight implies a stronger
54
+ connection between nodes and a *shorter* path length.
55
+
56
+ normalized : bool, optional (default=True)
57
+ Whether to normalize the edge weights by the total sum of edge
58
+ weights.
59
+
60
+ Returns
61
+ -------
62
+ h : float
63
+ The global reaching centrality of the graph.
64
+
65
+ Examples
66
+ --------
67
+ >>> G = nx.DiGraph()
68
+ >>> G.add_edge(1, 2)
69
+ >>> G.add_edge(1, 3)
70
+ >>> nx.global_reaching_centrality(G)
71
+ 1.0
72
+ >>> G.add_edge(3, 2)
73
+ >>> nx.global_reaching_centrality(G)
74
+ 0.75
75
+
76
+ See also
77
+ --------
78
+ local_reaching_centrality
79
+
80
+ References
81
+ ----------
82
+ .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
83
+ "Hierarchy Measure for Complex Networks."
84
+ *PLoS ONE* 7.3 (2012): e33799.
85
+ https://doi.org/10.1371/journal.pone.0033799
86
+ """
87
+ if nx.is_negatively_weighted(G, weight=weight):
88
+ raise nx.NetworkXError("edge weights must be positive")
89
+ total_weight = G.size(weight=weight)
90
+ if total_weight <= 0:
91
+ raise nx.NetworkXError("Size of G must be positive")
92
+
93
+ # If provided, weights must be interpreted as connection strength
94
+ # (so higher weights are more likely to be chosen). However, the
95
+ # shortest path algorithms in NetworkX assume the provided "weight"
96
+ # is actually a distance (so edges with higher weight are less
97
+ # likely to be chosen). Therefore we need to invert the weights when
98
+ # computing shortest paths.
99
+ #
100
+ # If weight is None, we leave it as-is so that the shortest path
101
+ # algorithm can use a faster, unweighted algorithm.
102
+ if weight is not None:
103
+
104
+ def as_distance(u, v, d):
105
+ return total_weight / d.get(weight, 1)
106
+
107
+ shortest_paths = nx.shortest_path(G, weight=as_distance)
108
+ else:
109
+ shortest_paths = nx.shortest_path(G)
110
+
111
+ centrality = local_reaching_centrality
112
+ # TODO This can be trivially parallelized.
113
+ lrc = [
114
+ centrality(G, node, paths=paths, weight=weight, normalized=normalized)
115
+ for node, paths in shortest_paths.items()
116
+ ]
117
+
118
+ max_lrc = max(lrc)
119
+ return sum(max_lrc - c for c in lrc) / (len(G) - 1)
120
+
121
+
122
+ @nx._dispatchable(edge_attrs="weight")
123
+ def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True):
124
+ """Returns the local reaching centrality of a node in a directed
125
+ graph.
126
+
127
+ The *local reaching centrality* of a node in a directed graph is the
128
+ proportion of other nodes reachable from that node [1]_.
129
+
130
+ Parameters
131
+ ----------
132
+ G : DiGraph
133
+ A NetworkX DiGraph.
134
+
135
+ v : node
136
+ A node in the directed graph `G`.
137
+
138
+ paths : dictionary (default=None)
139
+ If this is not `None` it must be a dictionary representation
140
+ of single-source shortest paths, as computed by, for example,
141
+ :func:`networkx.shortest_path` with source node `v`. Use this
142
+ keyword argument if you intend to invoke this function many
143
+ times but don't want the paths to be recomputed each time.
144
+
145
+ weight : None or string, optional (default=None)
146
+ Attribute to use for edge weights. If `None`, each edge weight
147
+ is assumed to be one. A higher weight implies a stronger
148
+ connection between nodes and a *shorter* path length.
149
+
150
+ normalized : bool, optional (default=True)
151
+ Whether to normalize the edge weights by the total sum of edge
152
+ weights.
153
+
154
+ Returns
155
+ -------
156
+ h : float
157
+ The local reaching centrality of the node ``v`` in the graph
158
+ ``G``.
159
+
160
+ Examples
161
+ --------
162
+ >>> G = nx.DiGraph()
163
+ >>> G.add_edges_from([(1, 2), (1, 3)])
164
+ >>> nx.local_reaching_centrality(G, 3)
165
+ 0.0
166
+ >>> G.add_edge(3, 2)
167
+ >>> nx.local_reaching_centrality(G, 3)
168
+ 0.5
169
+
170
+ See also
171
+ --------
172
+ global_reaching_centrality
173
+
174
+ References
175
+ ----------
176
+ .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
177
+ "Hierarchy Measure for Complex Networks."
178
+ *PLoS ONE* 7.3 (2012): e33799.
179
+ https://doi.org/10.1371/journal.pone.0033799
180
+ """
181
+ if paths is None:
182
+ if nx.is_negatively_weighted(G, weight=weight):
183
+ raise nx.NetworkXError("edge weights must be positive")
184
+ total_weight = G.size(weight=weight)
185
+ if total_weight <= 0:
186
+ raise nx.NetworkXError("Size of G must be positive")
187
+ if weight is not None:
188
+ # Interpret weights as lengths.
189
+ def as_distance(u, v, d):
190
+ return total_weight / d.get(weight, 1)
191
+
192
+ paths = nx.shortest_path(G, source=v, weight=as_distance)
193
+ else:
194
+ paths = nx.shortest_path(G, source=v)
195
+ # If the graph is unweighted, simply return the proportion of nodes
196
+ # reachable from the source node ``v``.
197
+ if weight is None and G.is_directed():
198
+ return (len(paths) - 1) / (len(G) - 1)
199
+ if normalized and weight is not None:
200
+ norm = G.size(weight=weight) / G.size()
201
+ else:
202
+ norm = 1
203
+ # TODO This can be trivially parallelized.
204
+ avgw = (_average_weight(G, path, weight=weight) for path in paths.values())
205
+ sum_avg_weight = sum(avgw) / norm
206
+ return sum_avg_weight / (len(G) - 1)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/subgraph_alg.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Subraph centrality and communicability betweenness.
3
+ """
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = [
8
+ "subgraph_centrality_exp",
9
+ "subgraph_centrality",
10
+ "communicability_betweenness_centrality",
11
+ "estrada_index",
12
+ ]
13
+
14
+
15
+ @not_implemented_for("directed")
16
+ @not_implemented_for("multigraph")
17
+ @nx._dispatchable
18
+ def subgraph_centrality_exp(G):
19
+ r"""Returns the subgraph centrality for each node of G.
20
+
21
+ Subgraph centrality of a node `n` is the sum of weighted closed
22
+ walks of all lengths starting and ending at node `n`. The weights
23
+ decrease with path length. Each closed walk is associated with a
24
+ connected subgraph ([1]_).
25
+
26
+ Parameters
27
+ ----------
28
+ G: graph
29
+
30
+ Returns
31
+ -------
32
+ nodes:dictionary
33
+ Dictionary of nodes with subgraph centrality as the value.
34
+
35
+ Raises
36
+ ------
37
+ NetworkXError
38
+ If the graph is not undirected and simple.
39
+
40
+ See Also
41
+ --------
42
+ subgraph_centrality:
43
+ Alternative algorithm of the subgraph centrality for each node of G.
44
+
45
+ Notes
46
+ -----
47
+ This version of the algorithm exponentiates the adjacency matrix.
48
+
49
+ The subgraph centrality of a node `u` in G can be found using
50
+ the matrix exponential of the adjacency matrix of G [1]_,
51
+
52
+ .. math::
53
+
54
+ SC(u)=(e^A)_{uu} .
55
+
56
+ References
57
+ ----------
58
+ .. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez,
59
+ "Subgraph centrality in complex networks",
60
+ Physical Review E 71, 056103 (2005).
61
+ https://arxiv.org/abs/cond-mat/0504730
62
+
63
+ Examples
64
+ --------
65
+ (Example from [1]_)
66
+ >>> G = nx.Graph(
67
+ ... [
68
+ ... (1, 2),
69
+ ... (1, 5),
70
+ ... (1, 8),
71
+ ... (2, 3),
72
+ ... (2, 8),
73
+ ... (3, 4),
74
+ ... (3, 6),
75
+ ... (4, 5),
76
+ ... (4, 7),
77
+ ... (5, 6),
78
+ ... (6, 7),
79
+ ... (7, 8),
80
+ ... ]
81
+ ... )
82
+ >>> sc = nx.subgraph_centrality_exp(G)
83
+ >>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)])
84
+ ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
85
+ """
86
+ # alternative implementation that calculates the matrix exponential
87
+ import scipy as sp
88
+
89
+ nodelist = list(G) # ordering of nodes in matrix
90
+ A = nx.to_numpy_array(G, nodelist)
91
+ # convert to 0-1 matrix
92
+ A[A != 0.0] = 1
93
+ expA = sp.linalg.expm(A)
94
+ # convert diagonal to dictionary keyed by node
95
+ sc = dict(zip(nodelist, map(float, expA.diagonal())))
96
+ return sc
97
+
98
+
99
+ @not_implemented_for("directed")
100
+ @not_implemented_for("multigraph")
101
+ @nx._dispatchable
102
+ def subgraph_centrality(G):
103
+ r"""Returns subgraph centrality for each node in G.
104
+
105
+ Subgraph centrality of a node `n` is the sum of weighted closed
106
+ walks of all lengths starting and ending at node `n`. The weights
107
+ decrease with path length. Each closed walk is associated with a
108
+ connected subgraph ([1]_).
109
+
110
+ Parameters
111
+ ----------
112
+ G: graph
113
+
114
+ Returns
115
+ -------
116
+ nodes : dictionary
117
+ Dictionary of nodes with subgraph centrality as the value.
118
+
119
+ Raises
120
+ ------
121
+ NetworkXError
122
+ If the graph is not undirected and simple.
123
+
124
+ See Also
125
+ --------
126
+ subgraph_centrality_exp:
127
+ Alternative algorithm of the subgraph centrality for each node of G.
128
+
129
+ Notes
130
+ -----
131
+ This version of the algorithm computes eigenvalues and eigenvectors
132
+ of the adjacency matrix.
133
+
134
+ Subgraph centrality of a node `u` in G can be found using
135
+ a spectral decomposition of the adjacency matrix [1]_,
136
+
137
+ .. math::
138
+
139
+ SC(u)=\sum_{j=1}^{N}(v_{j}^{u})^2 e^{\lambda_{j}},
140
+
141
+ where `v_j` is an eigenvector of the adjacency matrix `A` of G
142
+ corresponding to the eigenvalue `\lambda_j`.
143
+
144
+ Examples
145
+ --------
146
+ (Example from [1]_)
147
+ >>> G = nx.Graph(
148
+ ... [
149
+ ... (1, 2),
150
+ ... (1, 5),
151
+ ... (1, 8),
152
+ ... (2, 3),
153
+ ... (2, 8),
154
+ ... (3, 4),
155
+ ... (3, 6),
156
+ ... (4, 5),
157
+ ... (4, 7),
158
+ ... (5, 6),
159
+ ... (6, 7),
160
+ ... (7, 8),
161
+ ... ]
162
+ ... )
163
+ >>> sc = nx.subgraph_centrality(G)
164
+ >>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)])
165
+ ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
166
+
167
+ References
168
+ ----------
169
+ .. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez,
170
+ "Subgraph centrality in complex networks",
171
+ Physical Review E 71, 056103 (2005).
172
+ https://arxiv.org/abs/cond-mat/0504730
173
+
174
+ """
175
+ import numpy as np
176
+
177
+ nodelist = list(G) # ordering of nodes in matrix
178
+ A = nx.to_numpy_array(G, nodelist)
179
+ # convert to 0-1 matrix
180
+ A[np.nonzero(A)] = 1
181
+ w, v = np.linalg.eigh(A)
182
+ vsquare = np.array(v) ** 2
183
+ expw = np.exp(w)
184
+ xg = vsquare @ expw
185
+ # convert vector dictionary keyed by node
186
+ sc = dict(zip(nodelist, map(float, xg)))
187
+ return sc
188
+
189
+
190
+ @not_implemented_for("directed")
191
+ @not_implemented_for("multigraph")
192
+ @nx._dispatchable
193
+ def communicability_betweenness_centrality(G):
194
+ r"""Returns subgraph communicability for all pairs of nodes in G.
195
+
196
+ Communicability betweenness measure makes use of the number of walks
197
+ connecting every pair of nodes as the basis of a betweenness centrality
198
+ measure.
199
+
200
+ Parameters
201
+ ----------
202
+ G: graph
203
+
204
+ Returns
205
+ -------
206
+ nodes : dictionary
207
+ Dictionary of nodes with communicability betweenness as the value.
208
+
209
+ Raises
210
+ ------
211
+ NetworkXError
212
+ If the graph is not undirected and simple.
213
+
214
+ Notes
215
+ -----
216
+ Let `G=(V,E)` be a simple undirected graph with `n` nodes and `m` edges,
217
+ and `A` denote the adjacency matrix of `G`.
218
+
219
+ Let `G(r)=(V,E(r))` be the graph resulting from
220
+ removing all edges connected to node `r` but not the node itself.
221
+
222
+ The adjacency matrix for `G(r)` is `A+E(r)`, where `E(r)` has nonzeros
223
+ only in row and column `r`.
224
+
225
+ The subraph betweenness of a node `r` is [1]_
226
+
227
+ .. math::
228
+
229
+ \omega_{r} = \frac{1}{C}\sum_{p}\sum_{q}\frac{G_{prq}}{G_{pq}},
230
+ p\neq q, q\neq r,
231
+
232
+ where
233
+ `G_{prq}=(e^{A}_{pq} - (e^{A+E(r)})_{pq}` is the number of walks
234
+ involving node r,
235
+ `G_{pq}=(e^{A})_{pq}` is the number of closed walks starting
236
+ at node `p` and ending at node `q`,
237
+ and `C=(n-1)^{2}-(n-1)` is a normalization factor equal to the
238
+ number of terms in the sum.
239
+
240
+ The resulting `\omega_{r}` takes values between zero and one.
241
+ The lower bound cannot be attained for a connected
242
+ graph, and the upper bound is attained in the star graph.
243
+
244
+ References
245
+ ----------
246
+ .. [1] Ernesto Estrada, Desmond J. Higham, Naomichi Hatano,
247
+ "Communicability Betweenness in Complex Networks"
248
+ Physica A 388 (2009) 764-774.
249
+ https://arxiv.org/abs/0905.4102
250
+
251
+ Examples
252
+ --------
253
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
254
+ >>> cbc = nx.communicability_betweenness_centrality(G)
255
+ >>> print([f"{node} {cbc[node]:0.2f}" for node in sorted(cbc)])
256
+ ['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03']
257
+ """
258
+ import numpy as np
259
+ import scipy as sp
260
+
261
+ nodelist = list(G) # ordering of nodes in matrix
262
+ n = len(nodelist)
263
+ A = nx.to_numpy_array(G, nodelist)
264
+ # convert to 0-1 matrix
265
+ A[np.nonzero(A)] = 1
266
+ expA = sp.linalg.expm(A)
267
+ mapping = dict(zip(nodelist, range(n)))
268
+ cbc = {}
269
+ for v in G:
270
+ # remove row and col of node v
271
+ i = mapping[v]
272
+ row = A[i, :].copy()
273
+ col = A[:, i].copy()
274
+ A[i, :] = 0
275
+ A[:, i] = 0
276
+ B = (expA - sp.linalg.expm(A)) / expA
277
+ # sum with row/col of node v and diag set to zero
278
+ B[i, :] = 0
279
+ B[:, i] = 0
280
+ B -= np.diag(np.diag(B))
281
+ cbc[v] = float(B.sum())
282
+ # put row and col back
283
+ A[i, :] = row
284
+ A[:, i] = col
285
+ # rescale when more than two nodes
286
+ order = len(cbc)
287
+ if order > 2:
288
+ scale = 1.0 / ((order - 1.0) ** 2 - (order - 1.0))
289
+ cbc = {node: value * scale for node, value in cbc.items()}
290
+ return cbc
291
+
292
+
293
+ @nx._dispatchable
294
+ def estrada_index(G):
295
+ r"""Returns the Estrada index of a the graph G.
296
+
297
+ The Estrada Index is a topological index of folding or 3D "compactness" ([1]_).
298
+
299
+ Parameters
300
+ ----------
301
+ G: graph
302
+
303
+ Returns
304
+ -------
305
+ estrada index: float
306
+
307
+ Raises
308
+ ------
309
+ NetworkXError
310
+ If the graph is not undirected and simple.
311
+
312
+ Notes
313
+ -----
314
+ Let `G=(V,E)` be a simple undirected graph with `n` nodes and let
315
+ `\lambda_{1}\leq\lambda_{2}\leq\cdots\lambda_{n}`
316
+ be a non-increasing ordering of the eigenvalues of its adjacency
317
+ matrix `A`. The Estrada index is ([1]_, [2]_)
318
+
319
+ .. math::
320
+ EE(G)=\sum_{j=1}^n e^{\lambda _j}.
321
+
322
+ References
323
+ ----------
324
+ .. [1] E. Estrada, "Characterization of 3D molecular structure",
325
+ Chem. Phys. Lett. 319, 713 (2000).
326
+ https://doi.org/10.1016/S0009-2614(00)00158-5
327
+ .. [2] José Antonio de la Peñaa, Ivan Gutman, Juan Rada,
328
+ "Estimating the Estrada index",
329
+ Linear Algebra and its Applications. 427, 1 (2007).
330
+ https://doi.org/10.1016/j.laa.2007.06.020
331
+
332
+ Examples
333
+ --------
334
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
335
+ >>> ei = nx.estrada_index(G)
336
+ >>> print(f"{ei:0.5}")
337
+ 20.55
338
+ """
339
+ return sum(subgraph_centrality(G).values())
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/centrality/voterank_alg.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Algorithm to select influential nodes in a graph using VoteRank."""
2
+ import networkx as nx
3
+
4
+ __all__ = ["voterank"]
5
+
6
+
7
+ @nx._dispatchable
8
+ def voterank(G, number_of_nodes=None):
9
+ """Select a list of influential nodes in a graph using VoteRank algorithm
10
+
11
+ VoteRank [1]_ computes a ranking of the nodes in a graph G based on a
12
+ voting scheme. With VoteRank, all nodes vote for each of its in-neighbors
13
+ and the node with the highest votes is elected iteratively. The voting
14
+ ability of out-neighbors of elected nodes is decreased in subsequent turns.
15
+
16
+ Parameters
17
+ ----------
18
+ G : graph
19
+ A NetworkX graph.
20
+
21
+ number_of_nodes : integer, optional
22
+ Number of ranked nodes to extract (default all nodes).
23
+
24
+ Returns
25
+ -------
26
+ voterank : list
27
+ Ordered list of computed seeds.
28
+ Only nodes with positive number of votes are returned.
29
+
30
+ Examples
31
+ --------
32
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 4)])
33
+ >>> nx.voterank(G)
34
+ [0, 1]
35
+
36
+ The algorithm can be used both for undirected and directed graphs.
37
+ However, the directed version is different in two ways:
38
+ (i) nodes only vote for their in-neighbors and
39
+ (ii) only the voting ability of elected node and its out-neighbors are updated:
40
+
41
+ >>> G = nx.DiGraph([(0, 1), (2, 1), (2, 3), (3, 4)])
42
+ >>> nx.voterank(G)
43
+ [2, 3]
44
+
45
+ Notes
46
+ -----
47
+ Each edge is treated independently in case of multigraphs.
48
+
49
+ References
50
+ ----------
51
+ .. [1] Zhang, J.-X. et al. (2016).
52
+ Identifying a set of influential spreaders in complex networks.
53
+ Sci. Rep. 6, 27823; doi: 10.1038/srep27823.
54
+ """
55
+ influential_nodes = []
56
+ vote_rank = {}
57
+ if len(G) == 0:
58
+ return influential_nodes
59
+ if number_of_nodes is None or number_of_nodes > len(G):
60
+ number_of_nodes = len(G)
61
+ if G.is_directed():
62
+ # For directed graphs compute average out-degree
63
+ avgDegree = sum(deg for _, deg in G.out_degree()) / len(G)
64
+ else:
65
+ # For undirected graphs compute average degree
66
+ avgDegree = sum(deg for _, deg in G.degree()) / len(G)
67
+ # step 1 - initiate all nodes to (0,1) (score, voting ability)
68
+ for n in G.nodes():
69
+ vote_rank[n] = [0, 1]
70
+ # Repeat steps 1b to 4 until num_seeds are elected.
71
+ for _ in range(number_of_nodes):
72
+ # step 1b - reset rank
73
+ for n in G.nodes():
74
+ vote_rank[n][0] = 0
75
+ # step 2 - vote
76
+ for n, nbr in G.edges():
77
+ # In directed graphs nodes only vote for their in-neighbors
78
+ vote_rank[n][0] += vote_rank[nbr][1]
79
+ if not G.is_directed():
80
+ vote_rank[nbr][0] += vote_rank[n][1]
81
+ for n in influential_nodes:
82
+ vote_rank[n][0] = 0
83
+ # step 3 - select top node
84
+ n = max(G.nodes, key=lambda x: vote_rank[x][0])
85
+ if vote_rank[n][0] == 0:
86
+ return influential_nodes
87
+ influential_nodes.append(n)
88
+ # weaken the selected node
89
+ vote_rank[n] = [0, 0]
90
+ # step 4 - update voterank properties
91
+ for _, nbr in G.edges(n):
92
+ vote_rank[nbr][1] -= 1 / avgDegree
93
+ vote_rank[nbr][1] = max(vote_rank[nbr][1], 0)
94
+ return influential_nodes
env-llmeval/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 *
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (457 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-310.pyc ADDED
Binary file (26.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-310.pyc ADDED
Binary file (37.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-310.pyc ADDED
Binary file (18.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-310.pyc ADDED
Binary file (7.92 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-310.pyc ADDED
Binary file (6.32 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc ADDED
Binary file (4.51 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.19 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/connectivity.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ shortest_augmenting_path,
18
+ )
19
+
20
+ default_flow_func = edmonds_karp
21
+
22
+ from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
23
+
24
+ __all__ = [
25
+ "average_node_connectivity",
26
+ "local_node_connectivity",
27
+ "node_connectivity",
28
+ "local_edge_connectivity",
29
+ "edge_connectivity",
30
+ "all_pairs_node_connectivity",
31
+ ]
32
+
33
+
34
+ @nx._dispatchable(graphs={"G": 0, "auxiliary?": 4}, preserve_graph_attrs={"auxiliary"})
35
+ def local_node_connectivity(
36
+ G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None
37
+ ):
38
+ r"""Computes local node connectivity for nodes s and t.
39
+
40
+ Local node connectivity for two non adjacent nodes s and t is the
41
+ minimum number of nodes that must be removed (along with their incident
42
+ edges) to disconnect them.
43
+
44
+ This is a flow based implementation of node connectivity. We compute the
45
+ maximum flow on an auxiliary digraph build from the original input
46
+ graph (see below for details).
47
+
48
+ Parameters
49
+ ----------
50
+ G : NetworkX graph
51
+ Undirected graph
52
+
53
+ s : node
54
+ Source node
55
+
56
+ t : node
57
+ Target node
58
+
59
+ flow_func : function
60
+ A function for computing the maximum flow among a pair of nodes.
61
+ The function has to accept at least three parameters: a Digraph,
62
+ a source node, and a target node. And return a residual network
63
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
64
+ details). If flow_func is None, the default maximum flow function
65
+ (:meth:`edmonds_karp`) is used. See below for details. The choice
66
+ of the default function may change from version to version and
67
+ should not be relied on. Default value: None.
68
+
69
+ auxiliary : NetworkX DiGraph
70
+ Auxiliary digraph to compute flow based node connectivity. It has
71
+ to have a graph attribute called mapping with a dictionary mapping
72
+ node names in G and in the auxiliary digraph. If provided
73
+ it will be reused instead of recreated. Default value: None.
74
+
75
+ residual : NetworkX DiGraph
76
+ Residual network to compute maximum flow. If provided it will be
77
+ reused instead of recreated. Default value: None.
78
+
79
+ cutoff : integer, float, or None (default: None)
80
+ If specified, the maximum flow algorithm will terminate when the
81
+ flow value reaches or exceeds the cutoff. This only works for flows
82
+ that support the cutoff parameter (most do) and is ignored otherwise.
83
+
84
+ Returns
85
+ -------
86
+ K : integer
87
+ local node connectivity for nodes s and t
88
+
89
+ Examples
90
+ --------
91
+ This function is not imported in the base NetworkX namespace, so you
92
+ have to explicitly import it from the connectivity package:
93
+
94
+ >>> from networkx.algorithms.connectivity import local_node_connectivity
95
+
96
+ We use in this example the platonic icosahedral graph, which has node
97
+ connectivity 5.
98
+
99
+ >>> G = nx.icosahedral_graph()
100
+ >>> local_node_connectivity(G, 0, 6)
101
+ 5
102
+
103
+ If you need to compute local connectivity on several pairs of
104
+ nodes in the same graph, it is recommended that you reuse the
105
+ data structures that NetworkX uses in the computation: the
106
+ auxiliary digraph for node connectivity, and the residual
107
+ network for the underlying maximum flow computation.
108
+
109
+ Example of how to compute local node connectivity among
110
+ all pairs of nodes of the platonic icosahedral graph reusing
111
+ the data structures.
112
+
113
+ >>> import itertools
114
+ >>> # You also have to explicitly import the function for
115
+ >>> # building the auxiliary digraph from the connectivity package
116
+ >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
117
+ >>> H = build_auxiliary_node_connectivity(G)
118
+ >>> # And the function for building the residual network from the
119
+ >>> # flow package
120
+ >>> from networkx.algorithms.flow import build_residual_network
121
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
122
+ >>> R = build_residual_network(H, "capacity")
123
+ >>> result = dict.fromkeys(G, dict())
124
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
125
+ >>> # as parameters
126
+ >>> for u, v in itertools.combinations(G, 2):
127
+ ... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R)
128
+ ... result[u][v] = k
129
+ >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
130
+ True
131
+
132
+ You can also use alternative flow algorithms for computing node
133
+ connectivity. For instance, in dense networks the algorithm
134
+ :meth:`shortest_augmenting_path` will usually perform better than
135
+ the default :meth:`edmonds_karp` which is faster for sparse
136
+ networks with highly skewed degree distributions. Alternative flow
137
+ functions have to be explicitly imported from the flow package.
138
+
139
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
140
+ >>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
141
+ 5
142
+
143
+ Notes
144
+ -----
145
+ This is a flow based implementation of node connectivity. We compute the
146
+ maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see:
147
+ :meth:`maximum_flow`) on an auxiliary digraph build from the original
148
+ input graph:
149
+
150
+ For an undirected graph G having `n` nodes and `m` edges we derive a
151
+ directed graph H with `2n` nodes and `2m+n` arcs by replacing each
152
+ original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
153
+ arc in H. Then for each edge (`u`, `v`) in G we add two arcs
154
+ (`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute
155
+ capacity = 1 for each arc in H [1]_ .
156
+
157
+ For a directed graph G having `n` nodes and `m` arcs we derive a
158
+ directed graph H with `2n` nodes and `m+n` arcs by replacing each
159
+ original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
160
+ arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc
161
+ (`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for
162
+ each arc in H.
163
+
164
+ This is equal to the local node connectivity because the value of
165
+ a maximum s-t-flow is equal to the capacity of a minimum s-t-cut.
166
+
167
+ See also
168
+ --------
169
+ :meth:`local_edge_connectivity`
170
+ :meth:`node_connectivity`
171
+ :meth:`minimum_node_cut`
172
+ :meth:`maximum_flow`
173
+ :meth:`edmonds_karp`
174
+ :meth:`preflow_push`
175
+ :meth:`shortest_augmenting_path`
176
+
177
+ References
178
+ ----------
179
+ .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
180
+ Erlebach, 'Network Analysis: Methodological Foundations', Lecture
181
+ Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
182
+ http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
183
+
184
+ """
185
+ if flow_func is None:
186
+ flow_func = default_flow_func
187
+
188
+ if auxiliary is None:
189
+ H = build_auxiliary_node_connectivity(G)
190
+ else:
191
+ H = auxiliary
192
+
193
+ mapping = H.graph.get("mapping", None)
194
+ if mapping is None:
195
+ raise nx.NetworkXError("Invalid auxiliary digraph.")
196
+
197
+ kwargs = {"flow_func": flow_func, "residual": residual}
198
+ if flow_func is shortest_augmenting_path:
199
+ kwargs["cutoff"] = cutoff
200
+ kwargs["two_phase"] = True
201
+ elif flow_func is edmonds_karp:
202
+ kwargs["cutoff"] = cutoff
203
+ elif flow_func is dinitz:
204
+ kwargs["cutoff"] = cutoff
205
+ elif flow_func is boykov_kolmogorov:
206
+ kwargs["cutoff"] = cutoff
207
+
208
+ return nx.maximum_flow_value(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
209
+
210
+
211
+ @nx._dispatchable
212
+ def node_connectivity(G, s=None, t=None, flow_func=None):
213
+ r"""Returns node connectivity for a graph or digraph G.
214
+
215
+ Node connectivity is equal to the minimum number of nodes that
216
+ must be removed to disconnect G or render it trivial. If source
217
+ and target nodes are provided, this function returns the local node
218
+ connectivity: the minimum number of nodes that must be removed to break
219
+ all paths from source to target in G.
220
+
221
+ Parameters
222
+ ----------
223
+ G : NetworkX graph
224
+ Undirected graph
225
+
226
+ s : node
227
+ Source node. Optional. Default value: None.
228
+
229
+ t : node
230
+ Target node. Optional. Default value: None.
231
+
232
+ flow_func : function
233
+ A function for computing the maximum flow among a pair of nodes.
234
+ The function has to accept at least three parameters: a Digraph,
235
+ a source node, and a target node. And return a residual network
236
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
237
+ details). If flow_func is None, the default maximum flow function
238
+ (:meth:`edmonds_karp`) is used. See below for details. The
239
+ choice of the default function may change from version
240
+ to version and should not be relied on. Default value: None.
241
+
242
+ Returns
243
+ -------
244
+ K : integer
245
+ Node connectivity of G, or local node connectivity if source
246
+ and target are provided.
247
+
248
+ Examples
249
+ --------
250
+ >>> # Platonic icosahedral graph is 5-node-connected
251
+ >>> G = nx.icosahedral_graph()
252
+ >>> nx.node_connectivity(G)
253
+ 5
254
+
255
+ You can use alternative flow algorithms for the underlying maximum
256
+ flow computation. In dense networks the algorithm
257
+ :meth:`shortest_augmenting_path` will usually perform better
258
+ than the default :meth:`edmonds_karp`, which is faster for
259
+ sparse networks with highly skewed degree distributions. Alternative
260
+ flow functions have to be explicitly imported from the flow package.
261
+
262
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
263
+ >>> nx.node_connectivity(G, flow_func=shortest_augmenting_path)
264
+ 5
265
+
266
+ If you specify a pair of nodes (source and target) as parameters,
267
+ this function returns the value of local node connectivity.
268
+
269
+ >>> nx.node_connectivity(G, 3, 7)
270
+ 5
271
+
272
+ If you need to perform several local computations among different
273
+ pairs of nodes on the same graph, it is recommended that you reuse
274
+ the data structures used in the maximum flow computations. See
275
+ :meth:`local_node_connectivity` for details.
276
+
277
+ Notes
278
+ -----
279
+ This is a flow based implementation of node connectivity. The
280
+ algorithm works by solving $O((n-\delta-1+\delta(\delta-1)/2))$
281
+ maximum flow problems on an auxiliary digraph. Where $\delta$
282
+ is the minimum degree of G. For details about the auxiliary
283
+ digraph and the computation of local node connectivity see
284
+ :meth:`local_node_connectivity`. This implementation is based
285
+ on algorithm 11 in [1]_.
286
+
287
+ See also
288
+ --------
289
+ :meth:`local_node_connectivity`
290
+ :meth:`edge_connectivity`
291
+ :meth:`maximum_flow`
292
+ :meth:`edmonds_karp`
293
+ :meth:`preflow_push`
294
+ :meth:`shortest_augmenting_path`
295
+
296
+ References
297
+ ----------
298
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
299
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
300
+
301
+ """
302
+ if (s is not None and t is None) or (s is None and t is not None):
303
+ raise nx.NetworkXError("Both source and target must be specified.")
304
+
305
+ # Local node connectivity
306
+ if s is not None and t is not None:
307
+ if s not in G:
308
+ raise nx.NetworkXError(f"node {s} not in graph")
309
+ if t not in G:
310
+ raise nx.NetworkXError(f"node {t} not in graph")
311
+ return local_node_connectivity(G, s, t, flow_func=flow_func)
312
+
313
+ # Global node connectivity
314
+ if G.is_directed():
315
+ if not nx.is_weakly_connected(G):
316
+ return 0
317
+ iter_func = itertools.permutations
318
+ # It is necessary to consider both predecessors
319
+ # and successors for directed graphs
320
+
321
+ def neighbors(v):
322
+ return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
323
+
324
+ else:
325
+ if not nx.is_connected(G):
326
+ return 0
327
+ iter_func = itertools.combinations
328
+ neighbors = G.neighbors
329
+
330
+ # Reuse the auxiliary digraph and the residual network
331
+ H = build_auxiliary_node_connectivity(G)
332
+ R = build_residual_network(H, "capacity")
333
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
334
+
335
+ # Pick a node with minimum degree
336
+ # Node connectivity is bounded by degree.
337
+ v, K = min(G.degree(), key=itemgetter(1))
338
+ # compute local node connectivity with all its non-neighbors nodes
339
+ for w in set(G) - set(neighbors(v)) - {v}:
340
+ kwargs["cutoff"] = K
341
+ K = min(K, local_node_connectivity(G, v, w, **kwargs))
342
+ # Also for non adjacent pairs of neighbors of v
343
+ for x, y in iter_func(neighbors(v), 2):
344
+ if y in G[x]:
345
+ continue
346
+ kwargs["cutoff"] = K
347
+ K = min(K, local_node_connectivity(G, x, y, **kwargs))
348
+
349
+ return K
350
+
351
+
352
+ @nx._dispatchable
353
+ def average_node_connectivity(G, flow_func=None):
354
+ r"""Returns the average connectivity of a graph G.
355
+
356
+ The average connectivity `\bar{\kappa}` of a graph G is the average
357
+ of local node connectivity over all pairs of nodes of G [1]_ .
358
+
359
+ .. math::
360
+
361
+ \bar{\kappa}(G) = \frac{\sum_{u,v} \kappa_{G}(u,v)}{{n \choose 2}}
362
+
363
+ Parameters
364
+ ----------
365
+
366
+ G : NetworkX graph
367
+ Undirected graph
368
+
369
+ flow_func : function
370
+ A function for computing the maximum flow among a pair of nodes.
371
+ The function has to accept at least three parameters: a Digraph,
372
+ a source node, and a target node. And return a residual network
373
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
374
+ details). If flow_func is None, the default maximum flow function
375
+ (:meth:`edmonds_karp`) is used. See :meth:`local_node_connectivity`
376
+ for details. The choice of the default function may change from
377
+ version to version and should not be relied on. Default value: None.
378
+
379
+ Returns
380
+ -------
381
+ K : float
382
+ Average node connectivity
383
+
384
+ See also
385
+ --------
386
+ :meth:`local_node_connectivity`
387
+ :meth:`node_connectivity`
388
+ :meth:`edge_connectivity`
389
+ :meth:`maximum_flow`
390
+ :meth:`edmonds_karp`
391
+ :meth:`preflow_push`
392
+ :meth:`shortest_augmenting_path`
393
+
394
+ References
395
+ ----------
396
+ .. [1] Beineke, L., O. Oellermann, and R. Pippert (2002). The average
397
+ connectivity of a graph. Discrete mathematics 252(1-3), 31-45.
398
+ http://www.sciencedirect.com/science/article/pii/S0012365X01001807
399
+
400
+ """
401
+ if G.is_directed():
402
+ iter_func = itertools.permutations
403
+ else:
404
+ iter_func = itertools.combinations
405
+
406
+ # Reuse the auxiliary digraph and the residual network
407
+ H = build_auxiliary_node_connectivity(G)
408
+ R = build_residual_network(H, "capacity")
409
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
410
+
411
+ num, den = 0, 0
412
+ for u, v in iter_func(G, 2):
413
+ num += local_node_connectivity(G, u, v, **kwargs)
414
+ den += 1
415
+
416
+ if den == 0: # Null Graph
417
+ return 0
418
+ return num / den
419
+
420
+
421
+ @nx._dispatchable
422
+ def all_pairs_node_connectivity(G, nbunch=None, flow_func=None):
423
+ """Compute node connectivity between all pairs of nodes of G.
424
+
425
+ Parameters
426
+ ----------
427
+ G : NetworkX graph
428
+ Undirected graph
429
+
430
+ nbunch: container
431
+ Container of nodes. If provided node connectivity will be computed
432
+ only over pairs of nodes in nbunch.
433
+
434
+ flow_func : function
435
+ A function for computing the maximum flow among a pair of nodes.
436
+ The function has to accept at least three parameters: a Digraph,
437
+ a source node, and a target node. And return a residual network
438
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
439
+ details). If flow_func is None, the default maximum flow function
440
+ (:meth:`edmonds_karp`) is used. See below for details. The
441
+ choice of the default function may change from version
442
+ to version and should not be relied on. Default value: None.
443
+
444
+ Returns
445
+ -------
446
+ all_pairs : dict
447
+ A dictionary with node connectivity between all pairs of nodes
448
+ in G, or in nbunch if provided.
449
+
450
+ See also
451
+ --------
452
+ :meth:`local_node_connectivity`
453
+ :meth:`edge_connectivity`
454
+ :meth:`local_edge_connectivity`
455
+ :meth:`maximum_flow`
456
+ :meth:`edmonds_karp`
457
+ :meth:`preflow_push`
458
+ :meth:`shortest_augmenting_path`
459
+
460
+ """
461
+ if nbunch is None:
462
+ nbunch = G
463
+ else:
464
+ nbunch = set(nbunch)
465
+
466
+ directed = G.is_directed()
467
+ if directed:
468
+ iter_func = itertools.permutations
469
+ else:
470
+ iter_func = itertools.combinations
471
+
472
+ all_pairs = {n: {} for n in nbunch}
473
+
474
+ # Reuse auxiliary digraph and residual network
475
+ H = build_auxiliary_node_connectivity(G)
476
+ mapping = H.graph["mapping"]
477
+ R = build_residual_network(H, "capacity")
478
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
479
+
480
+ for u, v in iter_func(nbunch, 2):
481
+ K = local_node_connectivity(G, u, v, **kwargs)
482
+ all_pairs[u][v] = K
483
+ if not directed:
484
+ all_pairs[v][u] = K
485
+
486
+ return all_pairs
487
+
488
+
489
+ @nx._dispatchable(graphs={"G": 0, "auxiliary?": 4})
490
+ def local_edge_connectivity(
491
+ G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None
492
+ ):
493
+ r"""Returns local edge connectivity for nodes s and t in G.
494
+
495
+ Local edge connectivity for two nodes s and t is the minimum number
496
+ of edges that must be removed to disconnect them.
497
+
498
+ This is a flow based implementation of edge connectivity. We compute the
499
+ maximum flow on an auxiliary digraph build from the original
500
+ network (see below for details). This is equal to the local edge
501
+ connectivity because the value of a maximum s-t-flow is equal to the
502
+ capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .
503
+
504
+ Parameters
505
+ ----------
506
+ G : NetworkX graph
507
+ Undirected or directed graph
508
+
509
+ s : node
510
+ Source node
511
+
512
+ t : node
513
+ Target node
514
+
515
+ flow_func : function
516
+ A function for computing the maximum flow among a pair of nodes.
517
+ The function has to accept at least three parameters: a Digraph,
518
+ a source node, and a target node. And return a residual network
519
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
520
+ details). If flow_func is None, the default maximum flow function
521
+ (:meth:`edmonds_karp`) is used. See below for details. The
522
+ choice of the default function may change from version
523
+ to version and should not be relied on. Default value: None.
524
+
525
+ auxiliary : NetworkX DiGraph
526
+ Auxiliary digraph for computing flow based edge connectivity. If
527
+ provided it will be reused instead of recreated. Default value: None.
528
+
529
+ residual : NetworkX DiGraph
530
+ Residual network to compute maximum flow. If provided it will be
531
+ reused instead of recreated. Default value: None.
532
+
533
+ cutoff : integer, float, or None (default: None)
534
+ If specified, the maximum flow algorithm will terminate when the
535
+ flow value reaches or exceeds the cutoff. This only works for flows
536
+ that support the cutoff parameter (most do) and is ignored otherwise.
537
+
538
+ Returns
539
+ -------
540
+ K : integer
541
+ local edge connectivity for nodes s and t.
542
+
543
+ Examples
544
+ --------
545
+ This function is not imported in the base NetworkX namespace, so you
546
+ have to explicitly import it from the connectivity package:
547
+
548
+ >>> from networkx.algorithms.connectivity import local_edge_connectivity
549
+
550
+ We use in this example the platonic icosahedral graph, which has edge
551
+ connectivity 5.
552
+
553
+ >>> G = nx.icosahedral_graph()
554
+ >>> local_edge_connectivity(G, 0, 6)
555
+ 5
556
+
557
+ If you need to compute local connectivity on several pairs of
558
+ nodes in the same graph, it is recommended that you reuse the
559
+ data structures that NetworkX uses in the computation: the
560
+ auxiliary digraph for edge connectivity, and the residual
561
+ network for the underlying maximum flow computation.
562
+
563
+ Example of how to compute local edge connectivity among
564
+ all pairs of nodes of the platonic icosahedral graph reusing
565
+ the data structures.
566
+
567
+ >>> import itertools
568
+ >>> # You also have to explicitly import the function for
569
+ >>> # building the auxiliary digraph from the connectivity package
570
+ >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
571
+ >>> H = build_auxiliary_edge_connectivity(G)
572
+ >>> # And the function for building the residual network from the
573
+ >>> # flow package
574
+ >>> from networkx.algorithms.flow import build_residual_network
575
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
576
+ >>> R = build_residual_network(H, "capacity")
577
+ >>> result = dict.fromkeys(G, dict())
578
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
579
+ >>> # as parameters
580
+ >>> for u, v in itertools.combinations(G, 2):
581
+ ... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R)
582
+ ... result[u][v] = k
583
+ >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
584
+ True
585
+
586
+ You can also use alternative flow algorithms for computing edge
587
+ connectivity. For instance, in dense networks the algorithm
588
+ :meth:`shortest_augmenting_path` will usually perform better than
589
+ the default :meth:`edmonds_karp` which is faster for sparse
590
+ networks with highly skewed degree distributions. Alternative flow
591
+ functions have to be explicitly imported from the flow package.
592
+
593
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
594
+ >>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
595
+ 5
596
+
597
+ Notes
598
+ -----
599
+ This is a flow based implementation of edge connectivity. We compute the
600
+ maximum flow using, by default, the :meth:`edmonds_karp` algorithm on an
601
+ auxiliary digraph build from the original input graph:
602
+
603
+ If the input graph is undirected, we replace each edge (`u`,`v`) with
604
+ two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
605
+ 'capacity' for each arc to 1. If the input graph is directed we simply
606
+ add the 'capacity' attribute. This is an implementation of algorithm 1
607
+ in [1]_.
608
+
609
+ The maximum flow in the auxiliary network is equal to the local edge
610
+ connectivity because the value of a maximum s-t-flow is equal to the
611
+ capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
612
+
613
+ See also
614
+ --------
615
+ :meth:`edge_connectivity`
616
+ :meth:`local_node_connectivity`
617
+ :meth:`node_connectivity`
618
+ :meth:`maximum_flow`
619
+ :meth:`edmonds_karp`
620
+ :meth:`preflow_push`
621
+ :meth:`shortest_augmenting_path`
622
+
623
+ References
624
+ ----------
625
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
626
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
627
+
628
+ """
629
+ if flow_func is None:
630
+ flow_func = default_flow_func
631
+
632
+ if auxiliary is None:
633
+ H = build_auxiliary_edge_connectivity(G)
634
+ else:
635
+ H = auxiliary
636
+
637
+ kwargs = {"flow_func": flow_func, "residual": residual}
638
+ if flow_func is shortest_augmenting_path:
639
+ kwargs["cutoff"] = cutoff
640
+ kwargs["two_phase"] = True
641
+ elif flow_func is edmonds_karp:
642
+ kwargs["cutoff"] = cutoff
643
+ elif flow_func is dinitz:
644
+ kwargs["cutoff"] = cutoff
645
+ elif flow_func is boykov_kolmogorov:
646
+ kwargs["cutoff"] = cutoff
647
+
648
+ return nx.maximum_flow_value(H, s, t, **kwargs)
649
+
650
+
651
+ @nx._dispatchable
652
+ def edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None):
653
+ r"""Returns the edge connectivity of the graph or digraph G.
654
+
655
+ The edge connectivity is equal to the minimum number of edges that
656
+ must be removed to disconnect G or render it trivial. If source
657
+ and target nodes are provided, this function returns the local edge
658
+ connectivity: the minimum number of edges that must be removed to
659
+ break all paths from source to target in G.
660
+
661
+ Parameters
662
+ ----------
663
+ G : NetworkX graph
664
+ Undirected or directed graph
665
+
666
+ s : node
667
+ Source node. Optional. Default value: None.
668
+
669
+ t : node
670
+ Target node. Optional. Default value: None.
671
+
672
+ flow_func : function
673
+ A function for computing the maximum flow among a pair of nodes.
674
+ The function has to accept at least three parameters: a Digraph,
675
+ a source node, and a target node. And return a residual network
676
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
677
+ details). If flow_func is None, the default maximum flow function
678
+ (:meth:`edmonds_karp`) is used. See below for details. The
679
+ choice of the default function may change from version
680
+ to version and should not be relied on. Default value: None.
681
+
682
+ cutoff : integer, float, or None (default: None)
683
+ If specified, the maximum flow algorithm will terminate when the
684
+ flow value reaches or exceeds the cutoff. This only works for flows
685
+ that support the cutoff parameter (most do) and is ignored otherwise.
686
+
687
+ Returns
688
+ -------
689
+ K : integer
690
+ Edge connectivity for G, or local edge connectivity if source
691
+ and target were provided
692
+
693
+ Examples
694
+ --------
695
+ >>> # Platonic icosahedral graph is 5-edge-connected
696
+ >>> G = nx.icosahedral_graph()
697
+ >>> nx.edge_connectivity(G)
698
+ 5
699
+
700
+ You can use alternative flow algorithms for the underlying
701
+ maximum flow computation. In dense networks the algorithm
702
+ :meth:`shortest_augmenting_path` will usually perform better
703
+ than the default :meth:`edmonds_karp`, which is faster for
704
+ sparse networks with highly skewed degree distributions.
705
+ Alternative flow functions have to be explicitly imported
706
+ from the flow package.
707
+
708
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
709
+ >>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
710
+ 5
711
+
712
+ If you specify a pair of nodes (source and target) as parameters,
713
+ this function returns the value of local edge connectivity.
714
+
715
+ >>> nx.edge_connectivity(G, 3, 7)
716
+ 5
717
+
718
+ If you need to perform several local computations among different
719
+ pairs of nodes on the same graph, it is recommended that you reuse
720
+ the data structures used in the maximum flow computations. See
721
+ :meth:`local_edge_connectivity` for details.
722
+
723
+ Notes
724
+ -----
725
+ This is a flow based implementation of global edge connectivity.
726
+ For undirected graphs the algorithm works by finding a 'small'
727
+ dominating set of nodes of G (see algorithm 7 in [1]_ ) and
728
+ computing local maximum flow (see :meth:`local_edge_connectivity`)
729
+ between an arbitrary node in the dominating set and the rest of
730
+ nodes in it. This is an implementation of algorithm 6 in [1]_ .
731
+ For directed graphs, the algorithm does n calls to the maximum
732
+ flow function. This is an implementation of algorithm 8 in [1]_ .
733
+
734
+ See also
735
+ --------
736
+ :meth:`local_edge_connectivity`
737
+ :meth:`local_node_connectivity`
738
+ :meth:`node_connectivity`
739
+ :meth:`maximum_flow`
740
+ :meth:`edmonds_karp`
741
+ :meth:`preflow_push`
742
+ :meth:`shortest_augmenting_path`
743
+ :meth:`k_edge_components`
744
+ :meth:`k_edge_subgraphs`
745
+
746
+ References
747
+ ----------
748
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
749
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
750
+
751
+ """
752
+ if (s is not None and t is None) or (s is None and t is not None):
753
+ raise nx.NetworkXError("Both source and target must be specified.")
754
+
755
+ # Local edge connectivity
756
+ if s is not None and t is not None:
757
+ if s not in G:
758
+ raise nx.NetworkXError(f"node {s} not in graph")
759
+ if t not in G:
760
+ raise nx.NetworkXError(f"node {t} not in graph")
761
+ return local_edge_connectivity(G, s, t, flow_func=flow_func, cutoff=cutoff)
762
+
763
+ # Global edge connectivity
764
+ # reuse auxiliary digraph and residual network
765
+ H = build_auxiliary_edge_connectivity(G)
766
+ R = build_residual_network(H, "capacity")
767
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
768
+
769
+ if G.is_directed():
770
+ # Algorithm 8 in [1]
771
+ if not nx.is_weakly_connected(G):
772
+ return 0
773
+
774
+ # initial value for \lambda is minimum degree
775
+ L = min(d for n, d in G.degree())
776
+ nodes = list(G)
777
+ n = len(nodes)
778
+
779
+ if cutoff is not None:
780
+ L = min(cutoff, L)
781
+
782
+ for i in range(n):
783
+ kwargs["cutoff"] = L
784
+ try:
785
+ L = min(L, local_edge_connectivity(G, nodes[i], nodes[i + 1], **kwargs))
786
+ except IndexError: # last node!
787
+ L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs))
788
+ return L
789
+ else: # undirected
790
+ # Algorithm 6 in [1]
791
+ if not nx.is_connected(G):
792
+ return 0
793
+
794
+ # initial value for \lambda is minimum degree
795
+ L = min(d for n, d in G.degree())
796
+
797
+ if cutoff is not None:
798
+ L = min(cutoff, L)
799
+
800
+ # A dominating set is \lambda-covering
801
+ # We need a dominating set with at least two nodes
802
+ for node in G:
803
+ D = nx.dominating_set(G, start_with=node)
804
+ v = D.pop()
805
+ if D:
806
+ break
807
+ else:
808
+ # in complete graphs the dominating sets will always be of one node
809
+ # thus we return min degree
810
+ return L
811
+
812
+ for w in D:
813
+ kwargs["cutoff"] = L
814
+ L = min(L, local_edge_connectivity(G, v, w, **kwargs))
815
+
816
+ return L
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/cuts.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flow based cut algorithms
3
+ """
4
+ import itertools
5
+
6
+ import networkx as nx
7
+
8
+ # Define the default maximum flow function to use in all flow based
9
+ # cut algorithms.
10
+ from networkx.algorithms.flow import build_residual_network, edmonds_karp
11
+
12
+ default_flow_func = edmonds_karp
13
+
14
+ from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
15
+
16
+ __all__ = [
17
+ "minimum_st_node_cut",
18
+ "minimum_node_cut",
19
+ "minimum_st_edge_cut",
20
+ "minimum_edge_cut",
21
+ ]
22
+
23
+
24
+ @nx._dispatchable(
25
+ graphs={"G": 0, "auxiliary?": 4},
26
+ preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}},
27
+ preserve_graph_attrs={"auxiliary"},
28
+ )
29
+ def minimum_st_edge_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
30
+ """Returns the edges of the cut-set of a minimum (s, t)-cut.
31
+
32
+ This function returns the set of edges of minimum cardinality that,
33
+ if removed, would destroy all paths among source and target in G.
34
+ Edge weights are not considered. See :meth:`minimum_cut` for
35
+ computing minimum cuts considering edge weights.
36
+
37
+ Parameters
38
+ ----------
39
+ G : NetworkX graph
40
+
41
+ s : node
42
+ Source node for the flow.
43
+
44
+ t : node
45
+ Sink node for the flow.
46
+
47
+ auxiliary : NetworkX DiGraph
48
+ Auxiliary digraph to compute flow based node connectivity. It has
49
+ to have a graph attribute called mapping with a dictionary mapping
50
+ node names in G and in the auxiliary digraph. If provided
51
+ it will be reused instead of recreated. Default value: None.
52
+
53
+ flow_func : function
54
+ A function for computing the maximum flow among a pair of nodes.
55
+ The function has to accept at least three parameters: a Digraph,
56
+ a source node, and a target node. And return a residual network
57
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
58
+ details). If flow_func is None, the default maximum flow function
59
+ (:meth:`edmonds_karp`) is used. See :meth:`node_connectivity` for
60
+ details. The choice of the default function may change from version
61
+ to version and should not be relied on. Default value: None.
62
+
63
+ residual : NetworkX DiGraph
64
+ Residual network to compute maximum flow. If provided it will be
65
+ reused instead of recreated. Default value: None.
66
+
67
+ Returns
68
+ -------
69
+ cutset : set
70
+ Set of edges that, if removed from the graph, will disconnect it.
71
+
72
+ See also
73
+ --------
74
+ :meth:`minimum_cut`
75
+ :meth:`minimum_node_cut`
76
+ :meth:`minimum_edge_cut`
77
+ :meth:`stoer_wagner`
78
+ :meth:`node_connectivity`
79
+ :meth:`edge_connectivity`
80
+ :meth:`maximum_flow`
81
+ :meth:`edmonds_karp`
82
+ :meth:`preflow_push`
83
+ :meth:`shortest_augmenting_path`
84
+
85
+ Examples
86
+ --------
87
+ This function is not imported in the base NetworkX namespace, so you
88
+ have to explicitly import it from the connectivity package:
89
+
90
+ >>> from networkx.algorithms.connectivity import minimum_st_edge_cut
91
+
92
+ We use in this example the platonic icosahedral graph, which has edge
93
+ connectivity 5.
94
+
95
+ >>> G = nx.icosahedral_graph()
96
+ >>> len(minimum_st_edge_cut(G, 0, 6))
97
+ 5
98
+
99
+ If you need to compute local edge cuts on several pairs of
100
+ nodes in the same graph, it is recommended that you reuse the
101
+ data structures that NetworkX uses in the computation: the
102
+ auxiliary digraph for edge connectivity, and the residual
103
+ network for the underlying maximum flow computation.
104
+
105
+ Example of how to compute local edge cuts among all pairs of
106
+ nodes of the platonic icosahedral graph reusing the data
107
+ structures.
108
+
109
+ >>> import itertools
110
+ >>> # You also have to explicitly import the function for
111
+ >>> # building the auxiliary digraph from the connectivity package
112
+ >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
113
+ >>> H = build_auxiliary_edge_connectivity(G)
114
+ >>> # And the function for building the residual network from the
115
+ >>> # flow package
116
+ >>> from networkx.algorithms.flow import build_residual_network
117
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
118
+ >>> R = build_residual_network(H, "capacity")
119
+ >>> result = dict.fromkeys(G, dict())
120
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
121
+ >>> # as parameters
122
+ >>> for u, v in itertools.combinations(G, 2):
123
+ ... k = len(minimum_st_edge_cut(G, u, v, auxiliary=H, residual=R))
124
+ ... result[u][v] = k
125
+ >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
126
+ True
127
+
128
+ You can also use alternative flow algorithms for computing edge
129
+ cuts. For instance, in dense networks the algorithm
130
+ :meth:`shortest_augmenting_path` will usually perform better than
131
+ the default :meth:`edmonds_karp` which is faster for sparse
132
+ networks with highly skewed degree distributions. Alternative flow
133
+ functions have to be explicitly imported from the flow package.
134
+
135
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
136
+ >>> len(minimum_st_edge_cut(G, 0, 6, flow_func=shortest_augmenting_path))
137
+ 5
138
+
139
+ """
140
+ if flow_func is None:
141
+ flow_func = default_flow_func
142
+
143
+ if auxiliary is None:
144
+ H = build_auxiliary_edge_connectivity(G)
145
+ else:
146
+ H = auxiliary
147
+
148
+ kwargs = {"capacity": "capacity", "flow_func": flow_func, "residual": residual}
149
+
150
+ cut_value, partition = nx.minimum_cut(H, s, t, **kwargs)
151
+ reachable, non_reachable = partition
152
+ # Any edge in the original graph linking the two sets in the
153
+ # partition is part of the edge cutset
154
+ cutset = set()
155
+ for u, nbrs in ((n, G[n]) for n in reachable):
156
+ cutset.update((u, v) for v in nbrs if v in non_reachable)
157
+
158
+ return cutset
159
+
160
+
161
+ @nx._dispatchable(
162
+ graphs={"G": 0, "auxiliary?": 4},
163
+ preserve_node_attrs={"auxiliary": {"id": None}},
164
+ preserve_graph_attrs={"auxiliary"},
165
+ )
166
+ def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
167
+ r"""Returns a set of nodes of minimum cardinality that disconnect source
168
+ from target in G.
169
+
170
+ This function returns the set of nodes of minimum cardinality that,
171
+ if removed, would destroy all paths among source and target in G.
172
+
173
+ Parameters
174
+ ----------
175
+ G : NetworkX graph
176
+
177
+ s : node
178
+ Source node.
179
+
180
+ t : node
181
+ Target node.
182
+
183
+ flow_func : function
184
+ A function for computing the maximum flow among a pair of nodes.
185
+ The function has to accept at least three parameters: a Digraph,
186
+ a source node, and a target node. And return a residual network
187
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
188
+ details). If flow_func is None, the default maximum flow function
189
+ (:meth:`edmonds_karp`) is used. See below for details. The choice
190
+ of the default function may change from version to version and
191
+ should not be relied on. Default value: None.
192
+
193
+ auxiliary : NetworkX DiGraph
194
+ Auxiliary digraph to compute flow based node connectivity. It has
195
+ to have a graph attribute called mapping with a dictionary mapping
196
+ node names in G and in the auxiliary digraph. If provided
197
+ it will be reused instead of recreated. Default value: None.
198
+
199
+ residual : NetworkX DiGraph
200
+ Residual network to compute maximum flow. If provided it will be
201
+ reused instead of recreated. Default value: None.
202
+
203
+ Returns
204
+ -------
205
+ cutset : set
206
+ Set of nodes that, if removed, would destroy all paths between
207
+ source and target in G.
208
+
209
+ Examples
210
+ --------
211
+ This function is not imported in the base NetworkX namespace, so you
212
+ have to explicitly import it from the connectivity package:
213
+
214
+ >>> from networkx.algorithms.connectivity import minimum_st_node_cut
215
+
216
+ We use in this example the platonic icosahedral graph, which has node
217
+ connectivity 5.
218
+
219
+ >>> G = nx.icosahedral_graph()
220
+ >>> len(minimum_st_node_cut(G, 0, 6))
221
+ 5
222
+
223
+ If you need to compute local st cuts between several pairs of
224
+ nodes in the same graph, it is recommended that you reuse the
225
+ data structures that NetworkX uses in the computation: the
226
+ auxiliary digraph for node connectivity and node cuts, and the
227
+ residual network for the underlying maximum flow computation.
228
+
229
+ Example of how to compute local st node cuts reusing the data
230
+ structures:
231
+
232
+ >>> # You also have to explicitly import the function for
233
+ >>> # building the auxiliary digraph from the connectivity package
234
+ >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
235
+ >>> H = build_auxiliary_node_connectivity(G)
236
+ >>> # And the function for building the residual network from the
237
+ >>> # flow package
238
+ >>> from networkx.algorithms.flow import build_residual_network
239
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
240
+ >>> R = build_residual_network(H, "capacity")
241
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
242
+ >>> # as parameters
243
+ >>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R))
244
+ 5
245
+
246
+ You can also use alternative flow algorithms for computing minimum st
247
+ node cuts. For instance, in dense networks the algorithm
248
+ :meth:`shortest_augmenting_path` will usually perform better than
249
+ the default :meth:`edmonds_karp` which is faster for sparse
250
+ networks with highly skewed degree distributions. Alternative flow
251
+ functions have to be explicitly imported from the flow package.
252
+
253
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
254
+ >>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path))
255
+ 5
256
+
257
+ Notes
258
+ -----
259
+ This is a flow based implementation of minimum node cut. The algorithm
260
+ is based in solving a number of maximum flow computations to determine
261
+ the capacity of the minimum cut on an auxiliary directed network that
262
+ corresponds to the minimum node cut of G. It handles both directed
263
+ and undirected graphs. This implementation is based on algorithm 11
264
+ in [1]_.
265
+
266
+ See also
267
+ --------
268
+ :meth:`minimum_node_cut`
269
+ :meth:`minimum_edge_cut`
270
+ :meth:`stoer_wagner`
271
+ :meth:`node_connectivity`
272
+ :meth:`edge_connectivity`
273
+ :meth:`maximum_flow`
274
+ :meth:`edmonds_karp`
275
+ :meth:`preflow_push`
276
+ :meth:`shortest_augmenting_path`
277
+
278
+ References
279
+ ----------
280
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
281
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
282
+
283
+ """
284
+ if auxiliary is None:
285
+ H = build_auxiliary_node_connectivity(G)
286
+ else:
287
+ H = auxiliary
288
+
289
+ mapping = H.graph.get("mapping", None)
290
+ if mapping is None:
291
+ raise nx.NetworkXError("Invalid auxiliary digraph.")
292
+ if G.has_edge(s, t) or G.has_edge(t, s):
293
+ return {}
294
+ kwargs = {"flow_func": flow_func, "residual": residual, "auxiliary": H}
295
+
296
+ # The edge cut in the auxiliary digraph corresponds to the node cut in the
297
+ # original graph.
298
+ edge_cut = minimum_st_edge_cut(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
299
+ # Each node in the original graph maps to two nodes of the auxiliary graph
300
+ node_cut = {H.nodes[node]["id"] for edge in edge_cut for node in edge}
301
+ return node_cut - {s, t}
302
+
303
+
304
+ @nx._dispatchable
305
+ def minimum_node_cut(G, s=None, t=None, flow_func=None):
306
+ r"""Returns a set of nodes of minimum cardinality that disconnects G.
307
+
308
+ If source and target nodes are provided, this function returns the
309
+ set of nodes of minimum cardinality that, if removed, would destroy
310
+ all paths among source and target in G. If not, it returns a set
311
+ of nodes of minimum cardinality that disconnects G.
312
+
313
+ Parameters
314
+ ----------
315
+ G : NetworkX graph
316
+
317
+ s : node
318
+ Source node. Optional. Default value: None.
319
+
320
+ t : node
321
+ Target node. Optional. Default value: None.
322
+
323
+ flow_func : function
324
+ A function for computing the maximum flow among a pair of nodes.
325
+ The function has to accept at least three parameters: a Digraph,
326
+ a source node, and a target node. And return a residual network
327
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
328
+ details). If flow_func is None, the default maximum flow function
329
+ (:meth:`edmonds_karp`) is used. See below for details. The
330
+ choice of the default function may change from version
331
+ to version and should not be relied on. Default value: None.
332
+
333
+ Returns
334
+ -------
335
+ cutset : set
336
+ Set of nodes that, if removed, would disconnect G. If source
337
+ and target nodes are provided, the set contains the nodes that
338
+ if removed, would destroy all paths between source and target.
339
+
340
+ Examples
341
+ --------
342
+ >>> # Platonic icosahedral graph has node connectivity 5
343
+ >>> G = nx.icosahedral_graph()
344
+ >>> node_cut = nx.minimum_node_cut(G)
345
+ >>> len(node_cut)
346
+ 5
347
+
348
+ You can use alternative flow algorithms for the underlying maximum
349
+ flow computation. In dense networks the algorithm
350
+ :meth:`shortest_augmenting_path` will usually perform better
351
+ than the default :meth:`edmonds_karp`, which is faster for
352
+ sparse networks with highly skewed degree distributions. Alternative
353
+ flow functions have to be explicitly imported from the flow package.
354
+
355
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
356
+ >>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path)
357
+ True
358
+
359
+ If you specify a pair of nodes (source and target) as parameters,
360
+ this function returns a local st node cut.
361
+
362
+ >>> len(nx.minimum_node_cut(G, 3, 7))
363
+ 5
364
+
365
+ If you need to perform several local st cuts among different
366
+ pairs of nodes on the same graph, it is recommended that you reuse
367
+ the data structures used in the maximum flow computations. See
368
+ :meth:`minimum_st_node_cut` for details.
369
+
370
+ Notes
371
+ -----
372
+ This is a flow based implementation of minimum node cut. The algorithm
373
+ is based in solving a number of maximum flow computations to determine
374
+ the capacity of the minimum cut on an auxiliary directed network that
375
+ corresponds to the minimum node cut of G. It handles both directed
376
+ and undirected graphs. This implementation is based on algorithm 11
377
+ in [1]_.
378
+
379
+ See also
380
+ --------
381
+ :meth:`minimum_st_node_cut`
382
+ :meth:`minimum_cut`
383
+ :meth:`minimum_edge_cut`
384
+ :meth:`stoer_wagner`
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] Abdol-Hossein Esfahanian. Connectivity Algorithms.
395
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
396
+
397
+ """
398
+ if (s is not None and t is None) or (s is None and t is not None):
399
+ raise nx.NetworkXError("Both source and target must be specified.")
400
+
401
+ # Local minimum node cut.
402
+ if s is not None and t is not None:
403
+ if s not in G:
404
+ raise nx.NetworkXError(f"node {s} not in graph")
405
+ if t not in G:
406
+ raise nx.NetworkXError(f"node {t} not in graph")
407
+ return minimum_st_node_cut(G, s, t, flow_func=flow_func)
408
+
409
+ # Global minimum node cut.
410
+ # Analog to the algorithm 11 for global node connectivity in [1].
411
+ if G.is_directed():
412
+ if not nx.is_weakly_connected(G):
413
+ raise nx.NetworkXError("Input graph is not connected")
414
+ iter_func = itertools.permutations
415
+
416
+ def neighbors(v):
417
+ return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
418
+
419
+ else:
420
+ if not nx.is_connected(G):
421
+ raise nx.NetworkXError("Input graph is not connected")
422
+ iter_func = itertools.combinations
423
+ neighbors = G.neighbors
424
+
425
+ # Reuse the auxiliary digraph and the residual network.
426
+ H = build_auxiliary_node_connectivity(G)
427
+ R = build_residual_network(H, "capacity")
428
+ kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
429
+
430
+ # Choose a node with minimum degree.
431
+ v = min(G, key=G.degree)
432
+ # Initial node cutset is all neighbors of the node with minimum degree.
433
+ min_cut = set(G[v])
434
+ # Compute st node cuts between v and all its non-neighbors nodes in G.
435
+ for w in set(G) - set(neighbors(v)) - {v}:
436
+ this_cut = minimum_st_node_cut(G, v, w, **kwargs)
437
+ if len(min_cut) >= len(this_cut):
438
+ min_cut = this_cut
439
+ # Also for non adjacent pairs of neighbors of v.
440
+ for x, y in iter_func(neighbors(v), 2):
441
+ if y in G[x]:
442
+ continue
443
+ this_cut = minimum_st_node_cut(G, x, y, **kwargs)
444
+ if len(min_cut) >= len(this_cut):
445
+ min_cut = this_cut
446
+
447
+ return min_cut
448
+
449
+
450
+ @nx._dispatchable
451
+ def minimum_edge_cut(G, s=None, t=None, flow_func=None):
452
+ r"""Returns a set of edges of minimum cardinality that disconnects G.
453
+
454
+ If source and target nodes are provided, this function returns the
455
+ set of edges of minimum cardinality that, if removed, would break
456
+ all paths among source and target in G. If not, it returns a set of
457
+ edges of minimum cardinality that disconnects G.
458
+
459
+ Parameters
460
+ ----------
461
+ G : NetworkX graph
462
+
463
+ s : node
464
+ Source node. Optional. Default value: None.
465
+
466
+ t : node
467
+ Target node. Optional. Default value: None.
468
+
469
+ flow_func : function
470
+ A function for computing the maximum flow among a pair of nodes.
471
+ The function has to accept at least three parameters: a Digraph,
472
+ a source node, and a target node. And return a residual network
473
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
474
+ details). If flow_func is None, the default maximum flow function
475
+ (:meth:`edmonds_karp`) is used. See below for details. The
476
+ choice of the default function may change from version
477
+ to version and should not be relied on. Default value: None.
478
+
479
+ Returns
480
+ -------
481
+ cutset : set
482
+ Set of edges that, if removed, would disconnect G. If source
483
+ and target nodes are provided, the set contains the edges that
484
+ if removed, would destroy all paths between source and target.
485
+
486
+ Examples
487
+ --------
488
+ >>> # Platonic icosahedral graph has edge connectivity 5
489
+ >>> G = nx.icosahedral_graph()
490
+ >>> len(nx.minimum_edge_cut(G))
491
+ 5
492
+
493
+ You can use alternative flow algorithms for the underlying
494
+ maximum flow computation. In dense networks the algorithm
495
+ :meth:`shortest_augmenting_path` will usually perform better
496
+ than the default :meth:`edmonds_karp`, which is faster for
497
+ sparse networks with highly skewed degree distributions.
498
+ Alternative flow functions have to be explicitly imported
499
+ from the flow package.
500
+
501
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
502
+ >>> len(nx.minimum_edge_cut(G, flow_func=shortest_augmenting_path))
503
+ 5
504
+
505
+ If you specify a pair of nodes (source and target) as parameters,
506
+ this function returns the value of local edge connectivity.
507
+
508
+ >>> nx.edge_connectivity(G, 3, 7)
509
+ 5
510
+
511
+ If you need to perform several local computations among different
512
+ pairs of nodes on the same graph, it is recommended that you reuse
513
+ the data structures used in the maximum flow computations. See
514
+ :meth:`local_edge_connectivity` for details.
515
+
516
+ Notes
517
+ -----
518
+ This is a flow based implementation of minimum edge cut. For
519
+ undirected graphs the algorithm works by finding a 'small' dominating
520
+ set of nodes of G (see algorithm 7 in [1]_) and computing the maximum
521
+ flow between an arbitrary node in the dominating set and the rest of
522
+ nodes in it. This is an implementation of algorithm 6 in [1]_. For
523
+ directed graphs, the algorithm does n calls to the max flow function.
524
+ The function raises an error if the directed graph is not weakly
525
+ connected and returns an empty set if it is weakly connected.
526
+ It is an implementation of algorithm 8 in [1]_.
527
+
528
+ See also
529
+ --------
530
+ :meth:`minimum_st_edge_cut`
531
+ :meth:`minimum_node_cut`
532
+ :meth:`stoer_wagner`
533
+ :meth:`node_connectivity`
534
+ :meth:`edge_connectivity`
535
+ :meth:`maximum_flow`
536
+ :meth:`edmonds_karp`
537
+ :meth:`preflow_push`
538
+ :meth:`shortest_augmenting_path`
539
+
540
+ References
541
+ ----------
542
+ .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
543
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
544
+
545
+ """
546
+ if (s is not None and t is None) or (s is None and t is not None):
547
+ raise nx.NetworkXError("Both source and target must be specified.")
548
+
549
+ # reuse auxiliary digraph and residual network
550
+ H = build_auxiliary_edge_connectivity(G)
551
+ R = build_residual_network(H, "capacity")
552
+ kwargs = {"flow_func": flow_func, "residual": R, "auxiliary": H}
553
+
554
+ # Local minimum edge cut if s and t are not None
555
+ if s is not None and t is not None:
556
+ if s not in G:
557
+ raise nx.NetworkXError(f"node {s} not in graph")
558
+ if t not in G:
559
+ raise nx.NetworkXError(f"node {t} not in graph")
560
+ return minimum_st_edge_cut(H, s, t, **kwargs)
561
+
562
+ # Global minimum edge cut
563
+ # Analog to the algorithm for global edge connectivity
564
+ if G.is_directed():
565
+ # Based on algorithm 8 in [1]
566
+ if not nx.is_weakly_connected(G):
567
+ raise nx.NetworkXError("Input graph is not connected")
568
+
569
+ # Initial cutset is all edges of a node with minimum degree
570
+ node = min(G, key=G.degree)
571
+ min_cut = set(G.edges(node))
572
+ nodes = list(G)
573
+ n = len(nodes)
574
+ for i in range(n):
575
+ try:
576
+ this_cut = minimum_st_edge_cut(H, nodes[i], nodes[i + 1], **kwargs)
577
+ if len(this_cut) <= len(min_cut):
578
+ min_cut = this_cut
579
+ except IndexError: # Last node!
580
+ this_cut = minimum_st_edge_cut(H, nodes[i], nodes[0], **kwargs)
581
+ if len(this_cut) <= len(min_cut):
582
+ min_cut = this_cut
583
+
584
+ return min_cut
585
+
586
+ else: # undirected
587
+ # Based on algorithm 6 in [1]
588
+ if not nx.is_connected(G):
589
+ raise nx.NetworkXError("Input graph is not connected")
590
+
591
+ # Initial cutset is all edges of a node with minimum degree
592
+ node = min(G, key=G.degree)
593
+ min_cut = set(G.edges(node))
594
+ # A dominating set is \lambda-covering
595
+ # We need a dominating set with at least two nodes
596
+ for node in G:
597
+ D = nx.dominating_set(G, start_with=node)
598
+ v = D.pop()
599
+ if D:
600
+ break
601
+ else:
602
+ # in complete graphs the dominating set will always be of one node
603
+ # thus we return min_cut, which now contains the edges of a node
604
+ # with minimum degree
605
+ return min_cut
606
+ for w in D:
607
+ this_cut = minimum_st_edge_cut(H, v, w, **kwargs)
608
+ if len(this_cut) <= len(min_cut):
609
+ min_cut = this_cut
610
+
611
+ return min_cut
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/disjoint_paths.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flow based node and edge disjoint paths."""
2
+ import networkx as nx
3
+
4
+ # Define the default maximum flow function to use for the underlying
5
+ # maximum flow computations
6
+ from networkx.algorithms.flow import (
7
+ edmonds_karp,
8
+ preflow_push,
9
+ shortest_augmenting_path,
10
+ )
11
+ from networkx.exception import NetworkXNoPath
12
+
13
+ default_flow_func = edmonds_karp
14
+ from itertools import filterfalse as _filterfalse
15
+
16
+ # Functions to build auxiliary data structures.
17
+ from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
18
+
19
+ __all__ = ["edge_disjoint_paths", "node_disjoint_paths"]
20
+
21
+
22
+ @nx._dispatchable(
23
+ graphs={"G": 0, "auxiliary?": 5},
24
+ preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}},
25
+ )
26
+ def edge_disjoint_paths(
27
+ G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None
28
+ ):
29
+ """Returns the edges disjoint paths between source and target.
30
+
31
+ Edge disjoint paths are paths that do not share any edge. The
32
+ number of edge disjoint paths between source and target is equal
33
+ to their edge connectivity.
34
+
35
+ Parameters
36
+ ----------
37
+ G : NetworkX graph
38
+
39
+ s : node
40
+ Source node for the flow.
41
+
42
+ t : node
43
+ Sink node for the flow.
44
+
45
+ flow_func : function
46
+ A function for computing the maximum flow among a pair of nodes.
47
+ The function has to accept at least three parameters: a Digraph,
48
+ a source node, and a target node. And return a residual network
49
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
50
+ details). If flow_func is None, the default maximum flow function
51
+ (:meth:`edmonds_karp`) is used. The choice of the default function
52
+ may change from version to version and should not be relied on.
53
+ Default value: None.
54
+
55
+ cutoff : integer or None (default: None)
56
+ Maximum number of paths to yield. If specified, the maximum flow
57
+ algorithm will terminate when the flow value reaches or exceeds the
58
+ cutoff. This only works for flows that support the cutoff parameter
59
+ (most do) and is ignored otherwise.
60
+
61
+ auxiliary : NetworkX DiGraph
62
+ Auxiliary digraph to compute flow based edge connectivity. It has
63
+ to have a graph attribute called mapping with a dictionary mapping
64
+ node names in G and in the auxiliary digraph. If provided
65
+ it will be reused instead of recreated. Default value: None.
66
+
67
+ residual : NetworkX DiGraph
68
+ Residual network to compute maximum flow. If provided it will be
69
+ reused instead of recreated. Default value: None.
70
+
71
+ Returns
72
+ -------
73
+ paths : generator
74
+ A generator of edge independent paths.
75
+
76
+ Raises
77
+ ------
78
+ NetworkXNoPath
79
+ If there is no path between source and target.
80
+
81
+ NetworkXError
82
+ If source or target are not in the graph G.
83
+
84
+ See also
85
+ --------
86
+ :meth:`node_disjoint_paths`
87
+ :meth:`edge_connectivity`
88
+ :meth:`maximum_flow`
89
+ :meth:`edmonds_karp`
90
+ :meth:`preflow_push`
91
+ :meth:`shortest_augmenting_path`
92
+
93
+ Examples
94
+ --------
95
+ We use in this example the platonic icosahedral graph, which has node
96
+ edge connectivity 5, thus there are 5 edge disjoint paths between any
97
+ pair of nodes.
98
+
99
+ >>> G = nx.icosahedral_graph()
100
+ >>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
101
+ 5
102
+
103
+
104
+ If you need to compute edge disjoint paths 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 edge connectivity, and the residual
108
+ network for the underlying maximum flow computation.
109
+
110
+ Example of how to compute edge disjoint paths among all pairs of
111
+ nodes of the platonic icosahedral graph reusing the data
112
+ 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_edge_connectivity
118
+ >>> H = build_auxiliary_edge_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 = {n: {} for n in G}
125
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
126
+ >>> # as arguments
127
+ >>> for u, v in itertools.combinations(G, 2):
128
+ ... k = len(list(nx.edge_disjoint_paths(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 edge disjoint
134
+ paths. 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
+ >>> len(list(nx.edge_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
142
+ 5
143
+
144
+ Notes
145
+ -----
146
+ This is a flow based implementation of edge disjoint paths. We compute
147
+ the maximum flow between source and target on an auxiliary directed
148
+ network. The saturated edges in the residual network after running the
149
+ maximum flow algorithm correspond to edge disjoint paths between source
150
+ and target in the original network. This function handles both directed
151
+ and undirected graphs, and can use all flow algorithms from NetworkX flow
152
+ package.
153
+
154
+ """
155
+ if s not in G:
156
+ raise nx.NetworkXError(f"node {s} not in graph")
157
+ if t not in G:
158
+ raise nx.NetworkXError(f"node {t} not in graph")
159
+
160
+ if flow_func is None:
161
+ flow_func = default_flow_func
162
+
163
+ if auxiliary is None:
164
+ H = build_auxiliary_edge_connectivity(G)
165
+ else:
166
+ H = auxiliary
167
+
168
+ # Maximum possible edge disjoint paths
169
+ possible = min(H.out_degree(s), H.in_degree(t))
170
+ if not possible:
171
+ raise NetworkXNoPath
172
+
173
+ if cutoff is None:
174
+ cutoff = possible
175
+ else:
176
+ cutoff = min(cutoff, possible)
177
+
178
+ # Compute maximum flow between source and target. Flow functions in
179
+ # NetworkX return a residual network.
180
+ kwargs = {
181
+ "capacity": "capacity",
182
+ "residual": residual,
183
+ "cutoff": cutoff,
184
+ "value_only": True,
185
+ }
186
+ if flow_func is preflow_push:
187
+ del kwargs["cutoff"]
188
+ if flow_func is shortest_augmenting_path:
189
+ kwargs["two_phase"] = True
190
+ R = flow_func(H, s, t, **kwargs)
191
+
192
+ if R.graph["flow_value"] == 0:
193
+ raise NetworkXNoPath
194
+
195
+ # Saturated edges in the residual network form the edge disjoint paths
196
+ # between source and target
197
+ cutset = [
198
+ (u, v)
199
+ for u, v, d in R.edges(data=True)
200
+ if d["capacity"] == d["flow"] and d["flow"] > 0
201
+ ]
202
+ # This is equivalent of what flow.utils.build_flow_dict returns, but
203
+ # only for the nodes with saturated edges and without reporting 0 flows.
204
+ flow_dict = {n: {} for edge in cutset for n in edge}
205
+ for u, v in cutset:
206
+ flow_dict[u][v] = 1
207
+
208
+ # Rebuild the edge disjoint paths from the flow dictionary.
209
+ paths_found = 0
210
+ for v in list(flow_dict[s]):
211
+ if paths_found >= cutoff:
212
+ # preflow_push does not support cutoff: we have to
213
+ # keep track of the paths founds and stop at cutoff.
214
+ break
215
+ path = [s]
216
+ if v == t:
217
+ path.append(v)
218
+ yield path
219
+ continue
220
+ u = v
221
+ while u != t:
222
+ path.append(u)
223
+ try:
224
+ u, _ = flow_dict[u].popitem()
225
+ except KeyError:
226
+ break
227
+ else:
228
+ path.append(t)
229
+ yield path
230
+ paths_found += 1
231
+
232
+
233
+ @nx._dispatchable(
234
+ graphs={"G": 0, "auxiliary?": 5},
235
+ preserve_node_attrs={"auxiliary": {"id": None}},
236
+ preserve_graph_attrs={"auxiliary"},
237
+ )
238
+ def node_disjoint_paths(
239
+ G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None
240
+ ):
241
+ r"""Computes node disjoint paths between source and target.
242
+
243
+ Node disjoint paths are paths that only share their first and last
244
+ nodes. The number of node independent paths between two nodes is
245
+ equal to their local node connectivity.
246
+
247
+ Parameters
248
+ ----------
249
+ G : NetworkX graph
250
+
251
+ s : node
252
+ Source node.
253
+
254
+ t : node
255
+ Target node.
256
+
257
+ flow_func : function
258
+ A function for computing the maximum flow among a pair of nodes.
259
+ The function has to accept at least three parameters: a Digraph,
260
+ a source node, and a target node. And return a residual network
261
+ that follows NetworkX conventions (see :meth:`maximum_flow` for
262
+ details). If flow_func is None, the default maximum flow function
263
+ (:meth:`edmonds_karp`) is used. See below for details. The choice
264
+ of the default function may change from version to version and
265
+ should not be relied on. Default value: None.
266
+
267
+ cutoff : integer or None (default: None)
268
+ Maximum number of paths to yield. If specified, the maximum flow
269
+ algorithm will terminate when the flow value reaches or exceeds the
270
+ cutoff. This only works for flows that support the cutoff parameter
271
+ (most do) and is ignored otherwise.
272
+
273
+ auxiliary : NetworkX DiGraph
274
+ Auxiliary digraph to compute flow based node connectivity. It has
275
+ to have a graph attribute called mapping with a dictionary mapping
276
+ node names in G and in the auxiliary digraph. If provided
277
+ it will be reused instead of recreated. Default value: None.
278
+
279
+ residual : NetworkX DiGraph
280
+ Residual network to compute maximum flow. If provided it will be
281
+ reused instead of recreated. Default value: None.
282
+
283
+ Returns
284
+ -------
285
+ paths : generator
286
+ Generator of node disjoint paths.
287
+
288
+ Raises
289
+ ------
290
+ NetworkXNoPath
291
+ If there is no path between source and target.
292
+
293
+ NetworkXError
294
+ If source or target are not in the graph G.
295
+
296
+ Examples
297
+ --------
298
+ We use in this example the platonic icosahedral graph, which has node
299
+ connectivity 5, thus there are 5 node disjoint paths between any pair
300
+ of non neighbor nodes.
301
+
302
+ >>> G = nx.icosahedral_graph()
303
+ >>> len(list(nx.node_disjoint_paths(G, 0, 6)))
304
+ 5
305
+
306
+ If you need to compute node disjoint paths between several pairs of
307
+ nodes in the same graph, it is recommended that you reuse the
308
+ data structures that NetworkX uses in the computation: the
309
+ auxiliary digraph for node connectivity and node cuts, and the
310
+ residual network for the underlying maximum flow computation.
311
+
312
+ Example of how to compute node disjoint paths reusing the data
313
+ structures:
314
+
315
+ >>> # You also have to explicitly import the function for
316
+ >>> # building the auxiliary digraph from the connectivity package
317
+ >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
318
+ >>> H = build_auxiliary_node_connectivity(G)
319
+ >>> # And the function for building the residual network from the
320
+ >>> # flow package
321
+ >>> from networkx.algorithms.flow import build_residual_network
322
+ >>> # Note that the auxiliary digraph has an edge attribute named capacity
323
+ >>> R = build_residual_network(H, "capacity")
324
+ >>> # Reuse the auxiliary digraph and the residual network by passing them
325
+ >>> # as arguments
326
+ >>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R)))
327
+ 5
328
+
329
+ You can also use alternative flow algorithms for computing node disjoint
330
+ paths. For instance, in dense networks the algorithm
331
+ :meth:`shortest_augmenting_path` will usually perform better than
332
+ the default :meth:`edmonds_karp` which is faster for sparse
333
+ networks with highly skewed degree distributions. Alternative flow
334
+ functions have to be explicitly imported from the flow package.
335
+
336
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
337
+ >>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
338
+ 5
339
+
340
+ Notes
341
+ -----
342
+ This is a flow based implementation of node disjoint paths. We compute
343
+ the maximum flow between source and target on an auxiliary directed
344
+ network. The saturated edges in the residual network after running the
345
+ maximum flow algorithm correspond to node disjoint paths between source
346
+ and target in the original network. This function handles both directed
347
+ and undirected graphs, and can use all flow algorithms from NetworkX flow
348
+ package.
349
+
350
+ See also
351
+ --------
352
+ :meth:`edge_disjoint_paths`
353
+ :meth:`node_connectivity`
354
+ :meth:`maximum_flow`
355
+ :meth:`edmonds_karp`
356
+ :meth:`preflow_push`
357
+ :meth:`shortest_augmenting_path`
358
+
359
+ """
360
+ if s not in G:
361
+ raise nx.NetworkXError(f"node {s} not in graph")
362
+ if t not in G:
363
+ raise nx.NetworkXError(f"node {t} not in graph")
364
+
365
+ if auxiliary is None:
366
+ H = build_auxiliary_node_connectivity(G)
367
+ else:
368
+ H = auxiliary
369
+
370
+ mapping = H.graph.get("mapping", None)
371
+ if mapping is None:
372
+ raise nx.NetworkXError("Invalid auxiliary digraph.")
373
+
374
+ # Maximum possible edge disjoint paths
375
+ possible = min(H.out_degree(f"{mapping[s]}B"), H.in_degree(f"{mapping[t]}A"))
376
+ if not possible:
377
+ raise NetworkXNoPath
378
+
379
+ if cutoff is None:
380
+ cutoff = possible
381
+ else:
382
+ cutoff = min(cutoff, possible)
383
+
384
+ kwargs = {
385
+ "flow_func": flow_func,
386
+ "residual": residual,
387
+ "auxiliary": H,
388
+ "cutoff": cutoff,
389
+ }
390
+
391
+ # The edge disjoint paths in the auxiliary digraph correspond to the node
392
+ # disjoint paths in the original graph.
393
+ paths_edges = edge_disjoint_paths(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
394
+ for path in paths_edges:
395
+ # Each node in the original graph maps to two nodes in auxiliary graph
396
+ yield list(_unique_everseen(H.nodes[node]["id"] for node in path))
397
+
398
+
399
+ def _unique_everseen(iterable):
400
+ # Adapted from https://docs.python.org/3/library/itertools.html examples
401
+ "List unique elements, preserving order. Remember all elements ever seen."
402
+ # unique_everseen('AAAABBBCCDAABBB') --> A B C D
403
+ seen = set()
404
+ seen_add = seen.add
405
+ for element in _filterfalse(seen.__contains__, iterable):
406
+ seen_add(element)
407
+ yield element
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_augmentation.py ADDED
@@ -0,0 +1,1269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import itertools as it
16
+ import math
17
+ from collections import defaultdict, namedtuple
18
+
19
+ import networkx as nx
20
+ from networkx.utils import not_implemented_for, py_random_state
21
+
22
+ __all__ = ["k_edge_augmentation", "is_k_edge_connected", "is_locally_k_edge_connected"]
23
+
24
+
25
+ @not_implemented_for("directed")
26
+ @not_implemented_for("multigraph")
27
+ @nx._dispatchable
28
+ def is_k_edge_connected(G, k):
29
+ """Tests to see if a graph is k-edge-connected.
30
+
31
+ Is it impossible to disconnect the graph by removing fewer than k edges?
32
+ If so, then G is k-edge-connected.
33
+
34
+ Parameters
35
+ ----------
36
+ G : NetworkX graph
37
+ An undirected graph.
38
+
39
+ k : integer
40
+ edge connectivity to test for
41
+
42
+ Returns
43
+ -------
44
+ boolean
45
+ True if G is k-edge-connected.
46
+
47
+ See Also
48
+ --------
49
+ :func:`is_locally_k_edge_connected`
50
+
51
+ Examples
52
+ --------
53
+ >>> G = nx.barbell_graph(10, 0)
54
+ >>> nx.is_k_edge_connected(G, k=1)
55
+ True
56
+ >>> nx.is_k_edge_connected(G, k=2)
57
+ False
58
+ """
59
+ if k < 1:
60
+ raise ValueError(f"k must be positive, not {k}")
61
+ # First try to quickly determine if G is not k-edge-connected
62
+ if G.number_of_nodes() < k + 1:
63
+ return False
64
+ elif any(d < k for n, d in G.degree()):
65
+ return False
66
+ else:
67
+ # Otherwise perform the full check
68
+ if k == 1:
69
+ return nx.is_connected(G)
70
+ elif k == 2:
71
+ return nx.is_connected(G) and not nx.has_bridges(G)
72
+ else:
73
+ return nx.edge_connectivity(G, cutoff=k) >= k
74
+
75
+
76
+ @not_implemented_for("directed")
77
+ @not_implemented_for("multigraph")
78
+ @nx._dispatchable
79
+ def is_locally_k_edge_connected(G, s, t, k):
80
+ """Tests to see if an edge in a graph is locally k-edge-connected.
81
+
82
+ Is it impossible to disconnect s and t by removing fewer than k edges?
83
+ If so, then s and t are locally k-edge-connected in G.
84
+
85
+ Parameters
86
+ ----------
87
+ G : NetworkX graph
88
+ An undirected graph.
89
+
90
+ s : node
91
+ Source node
92
+
93
+ t : node
94
+ Target node
95
+
96
+ k : integer
97
+ local edge connectivity for nodes s and t
98
+
99
+ Returns
100
+ -------
101
+ boolean
102
+ True if s and t are locally k-edge-connected in G.
103
+
104
+ See Also
105
+ --------
106
+ :func:`is_k_edge_connected`
107
+
108
+ Examples
109
+ --------
110
+ >>> from networkx.algorithms.connectivity import is_locally_k_edge_connected
111
+ >>> G = nx.barbell_graph(10, 0)
112
+ >>> is_locally_k_edge_connected(G, 5, 15, k=1)
113
+ True
114
+ >>> is_locally_k_edge_connected(G, 5, 15, k=2)
115
+ False
116
+ >>> is_locally_k_edge_connected(G, 1, 5, k=2)
117
+ True
118
+ """
119
+ if k < 1:
120
+ raise ValueError(f"k must be positive, not {k}")
121
+
122
+ # First try to quickly determine s, t is not k-locally-edge-connected in G
123
+ if G.degree(s) < k or G.degree(t) < k:
124
+ return False
125
+ else:
126
+ # Otherwise perform the full check
127
+ if k == 1:
128
+ return nx.has_path(G, s, t)
129
+ else:
130
+ localk = nx.connectivity.local_edge_connectivity(G, s, t, cutoff=k)
131
+ return localk >= k
132
+
133
+
134
+ @not_implemented_for("directed")
135
+ @not_implemented_for("multigraph")
136
+ @nx._dispatchable
137
+ def k_edge_augmentation(G, k, avail=None, weight=None, partial=False):
138
+ """Finds set of edges to k-edge-connect G.
139
+
140
+ Adding edges from the augmentation to G make it impossible to disconnect G
141
+ unless k or more edges are removed. This function uses the most efficient
142
+ function available (depending on the value of k and if the problem is
143
+ weighted or unweighted) to search for a minimum weight subset of available
144
+ edges that k-edge-connects G. In general, finding a k-edge-augmentation is
145
+ NP-hard, so solutions are not guaranteed to be minimal. Furthermore, a
146
+ k-edge-augmentation may not exist.
147
+
148
+ Parameters
149
+ ----------
150
+ G : NetworkX graph
151
+ An undirected graph.
152
+
153
+ k : integer
154
+ Desired edge connectivity
155
+
156
+ avail : dict or a set of 2 or 3 tuples
157
+ The available edges that can be used in the augmentation.
158
+
159
+ If unspecified, then all edges in the complement of G are available.
160
+ Otherwise, each item is an available edge (with an optional weight).
161
+
162
+ In the unweighted case, each item is an edge ``(u, v)``.
163
+
164
+ In the weighted case, each item is a 3-tuple ``(u, v, d)`` or a dict
165
+ with items ``(u, v): d``. The third item, ``d``, can be a dictionary
166
+ or a real number. If ``d`` is a dictionary ``d[weight]``
167
+ correspondings to the weight.
168
+
169
+ weight : string
170
+ key to use to find weights if ``avail`` is a set of 3-tuples where the
171
+ third item in each tuple is a dictionary.
172
+
173
+ partial : boolean
174
+ If partial is True and no feasible k-edge-augmentation exists, then all
175
+ a partial k-edge-augmentation is generated. Adding the edges in a
176
+ partial augmentation to G, minimizes the number of k-edge-connected
177
+ components and maximizes the edge connectivity between those
178
+ components. For details, see :func:`partial_k_edge_augmentation`.
179
+
180
+ Yields
181
+ ------
182
+ edge : tuple
183
+ Edges that, once added to G, would cause G to become k-edge-connected.
184
+ If partial is False, an error is raised if this is not possible.
185
+ Otherwise, generated edges form a partial augmentation, which
186
+ k-edge-connects any part of G where it is possible, and maximally
187
+ connects the remaining parts.
188
+
189
+ Raises
190
+ ------
191
+ NetworkXUnfeasible
192
+ If partial is False and no k-edge-augmentation exists.
193
+
194
+ NetworkXNotImplemented
195
+ If the input graph is directed or a multigraph.
196
+
197
+ ValueError:
198
+ If k is less than 1
199
+
200
+ Notes
201
+ -----
202
+ When k=1 this returns an optimal solution.
203
+
204
+ When k=2 and ``avail`` is None, this returns an optimal solution.
205
+ Otherwise when k=2, this returns a 2-approximation of the optimal solution.
206
+
207
+ For k>3, this problem is NP-hard and this uses a randomized algorithm that
208
+ produces a feasible solution, but provides no guarantees on the
209
+ solution weight.
210
+
211
+ Examples
212
+ --------
213
+ >>> # Unweighted cases
214
+ >>> G = nx.path_graph((1, 2, 3, 4))
215
+ >>> G.add_node(5)
216
+ >>> sorted(nx.k_edge_augmentation(G, k=1))
217
+ [(1, 5)]
218
+ >>> sorted(nx.k_edge_augmentation(G, k=2))
219
+ [(1, 5), (5, 4)]
220
+ >>> sorted(nx.k_edge_augmentation(G, k=3))
221
+ [(1, 4), (1, 5), (2, 5), (3, 5), (4, 5)]
222
+ >>> complement = list(nx.k_edge_augmentation(G, k=5, partial=True))
223
+ >>> G.add_edges_from(complement)
224
+ >>> nx.edge_connectivity(G)
225
+ 4
226
+
227
+ >>> # Weighted cases
228
+ >>> G = nx.path_graph((1, 2, 3, 4))
229
+ >>> G.add_node(5)
230
+ >>> # avail can be a tuple with a dict
231
+ >>> avail = [(1, 5, {"weight": 11}), (2, 5, {"weight": 10})]
232
+ >>> sorted(nx.k_edge_augmentation(G, k=1, avail=avail, weight="weight"))
233
+ [(2, 5)]
234
+ >>> # or avail can be a 3-tuple with a real number
235
+ >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
236
+ >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
237
+ [(1, 5), (2, 5), (4, 5)]
238
+ >>> # or avail can be a dict
239
+ >>> avail = {(1, 5): 11, (2, 5): 10, (4, 3): 1, (4, 5): 51}
240
+ >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
241
+ [(1, 5), (2, 5), (4, 5)]
242
+ >>> # If augmentation is infeasible, then a partial solution can be found
243
+ >>> avail = {(1, 5): 11}
244
+ >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail, partial=True))
245
+ [(1, 5)]
246
+ """
247
+ try:
248
+ if k <= 0:
249
+ raise ValueError(f"k must be a positive integer, not {k}")
250
+ elif G.number_of_nodes() < k + 1:
251
+ msg = f"impossible to {k} connect in graph with less than {k + 1} nodes"
252
+ raise nx.NetworkXUnfeasible(msg)
253
+ elif avail is not None and len(avail) == 0:
254
+ if not nx.is_k_edge_connected(G, k):
255
+ raise nx.NetworkXUnfeasible("no available edges")
256
+ aug_edges = []
257
+ elif k == 1:
258
+ aug_edges = one_edge_augmentation(
259
+ G, avail=avail, weight=weight, partial=partial
260
+ )
261
+ elif k == 2:
262
+ aug_edges = bridge_augmentation(G, avail=avail, weight=weight)
263
+ else:
264
+ # raise NotImplementedError(f'not implemented for k>2. k={k}')
265
+ aug_edges = greedy_k_edge_augmentation(
266
+ G, k=k, avail=avail, weight=weight, seed=0
267
+ )
268
+ # Do eager evaluation so we can catch any exceptions
269
+ # Before executing partial code.
270
+ yield from list(aug_edges)
271
+ except nx.NetworkXUnfeasible:
272
+ if partial:
273
+ # Return all available edges
274
+ if avail is None:
275
+ aug_edges = complement_edges(G)
276
+ else:
277
+ # If we can't k-edge-connect the entire graph, try to
278
+ # k-edge-connect as much as possible
279
+ aug_edges = partial_k_edge_augmentation(
280
+ G, k=k, avail=avail, weight=weight
281
+ )
282
+ yield from aug_edges
283
+ else:
284
+ raise
285
+
286
+
287
+ @nx._dispatchable
288
+ def partial_k_edge_augmentation(G, k, avail, weight=None):
289
+ """Finds augmentation that k-edge-connects as much of the graph as possible.
290
+
291
+ When a k-edge-augmentation is not possible, we can still try to find a
292
+ small set of edges that partially k-edge-connects as much of the graph as
293
+ possible. All possible edges are generated between remaining parts.
294
+ This minimizes the number of k-edge-connected subgraphs in the resulting
295
+ graph and maximizes the edge connectivity between those subgraphs.
296
+
297
+ Parameters
298
+ ----------
299
+ G : NetworkX graph
300
+ An undirected graph.
301
+
302
+ k : integer
303
+ Desired edge connectivity
304
+
305
+ avail : dict or a set of 2 or 3 tuples
306
+ For more details, see :func:`k_edge_augmentation`.
307
+
308
+ weight : string
309
+ key to use to find weights if ``avail`` is a set of 3-tuples.
310
+ For more details, see :func:`k_edge_augmentation`.
311
+
312
+ Yields
313
+ ------
314
+ edge : tuple
315
+ Edges in the partial augmentation of G. These edges k-edge-connect any
316
+ part of G where it is possible, and maximally connects the remaining
317
+ parts. In other words, all edges from avail are generated except for
318
+ those within subgraphs that have already become k-edge-connected.
319
+
320
+ Notes
321
+ -----
322
+ Construct H that augments G with all edges in avail.
323
+ Find the k-edge-subgraphs of H.
324
+ For each k-edge-subgraph, if the number of nodes is more than k, then find
325
+ the k-edge-augmentation of that graph and add it to the solution. Then add
326
+ all edges in avail between k-edge subgraphs to the solution.
327
+
328
+ See Also
329
+ --------
330
+ :func:`k_edge_augmentation`
331
+
332
+ Examples
333
+ --------
334
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
335
+ >>> G.add_node(8)
336
+ >>> avail = [(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5), (1, 8)]
337
+ >>> sorted(partial_k_edge_augmentation(G, k=2, avail=avail))
338
+ [(1, 5), (1, 8)]
339
+ """
340
+
341
+ def _edges_between_disjoint(H, only1, only2):
342
+ """finds edges between disjoint nodes"""
343
+ only1_adj = {u: set(H.adj[u]) for u in only1}
344
+ for u, neighbs in only1_adj.items():
345
+ # Find the neighbors of u in only1 that are also in only2
346
+ neighbs12 = neighbs.intersection(only2)
347
+ for v in neighbs12:
348
+ yield (u, v)
349
+
350
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
351
+
352
+ # Find which parts of the graph can be k-edge-connected
353
+ H = G.copy()
354
+ H.add_edges_from(
355
+ (
356
+ (u, v, {"weight": w, "generator": (u, v)})
357
+ for (u, v), w in zip(avail, avail_w)
358
+ )
359
+ )
360
+ k_edge_subgraphs = list(nx.k_edge_subgraphs(H, k=k))
361
+
362
+ # Generate edges to k-edge-connect internal subgraphs
363
+ for nodes in k_edge_subgraphs:
364
+ if len(nodes) > 1:
365
+ # Get the k-edge-connected subgraph
366
+ C = H.subgraph(nodes).copy()
367
+ # Find the internal edges that were available
368
+ sub_avail = {
369
+ d["generator"]: d["weight"]
370
+ for (u, v, d) in C.edges(data=True)
371
+ if "generator" in d
372
+ }
373
+ # Remove potential augmenting edges
374
+ C.remove_edges_from(sub_avail.keys())
375
+ # Find a subset of these edges that makes the component
376
+ # k-edge-connected and ignore the rest
377
+ yield from nx.k_edge_augmentation(C, k=k, avail=sub_avail)
378
+
379
+ # Generate all edges between CCs that could not be k-edge-connected
380
+ for cc1, cc2 in it.combinations(k_edge_subgraphs, 2):
381
+ for u, v in _edges_between_disjoint(H, cc1, cc2):
382
+ d = H.get_edge_data(u, v)
383
+ edge = d.get("generator", None)
384
+ if edge is not None:
385
+ yield edge
386
+
387
+
388
+ @not_implemented_for("multigraph")
389
+ @not_implemented_for("directed")
390
+ @nx._dispatchable
391
+ def one_edge_augmentation(G, avail=None, weight=None, partial=False):
392
+ """Finds minimum weight set of edges to connect G.
393
+
394
+ Equivalent to :func:`k_edge_augmentation` when k=1. Adding the resulting
395
+ edges to G will make it 1-edge-connected. The solution is optimal for both
396
+ weighted and non-weighted variants.
397
+
398
+ Parameters
399
+ ----------
400
+ G : NetworkX graph
401
+ An undirected graph.
402
+
403
+ avail : dict or a set of 2 or 3 tuples
404
+ For more details, see :func:`k_edge_augmentation`.
405
+
406
+ weight : string
407
+ key to use to find weights if ``avail`` is a set of 3-tuples.
408
+ For more details, see :func:`k_edge_augmentation`.
409
+
410
+ partial : boolean
411
+ If partial is True and no feasible k-edge-augmentation exists, then the
412
+ augmenting edges minimize the number of connected components.
413
+
414
+ Yields
415
+ ------
416
+ edge : tuple
417
+ Edges in the one-augmentation of G
418
+
419
+ Raises
420
+ ------
421
+ NetworkXUnfeasible
422
+ If partial is False and no one-edge-augmentation exists.
423
+
424
+ Notes
425
+ -----
426
+ Uses either :func:`unconstrained_one_edge_augmentation` or
427
+ :func:`weighted_one_edge_augmentation` depending on whether ``avail`` is
428
+ specified. Both algorithms are based on finding a minimum spanning tree.
429
+ As such both algorithms find optimal solutions and run in linear time.
430
+
431
+ See Also
432
+ --------
433
+ :func:`k_edge_augmentation`
434
+ """
435
+ if avail is None:
436
+ return unconstrained_one_edge_augmentation(G)
437
+ else:
438
+ return weighted_one_edge_augmentation(
439
+ G, avail=avail, weight=weight, partial=partial
440
+ )
441
+
442
+
443
+ @not_implemented_for("multigraph")
444
+ @not_implemented_for("directed")
445
+ @nx._dispatchable
446
+ def bridge_augmentation(G, avail=None, weight=None):
447
+ """Finds the a set of edges that bridge connects G.
448
+
449
+ Equivalent to :func:`k_edge_augmentation` when k=2, and partial=False.
450
+ Adding the resulting edges to G will make it 2-edge-connected. If no
451
+ constraints are specified the returned set of edges is minimum an optimal,
452
+ otherwise the solution is approximated.
453
+
454
+ Parameters
455
+ ----------
456
+ G : NetworkX graph
457
+ An undirected graph.
458
+
459
+ avail : dict or a set of 2 or 3 tuples
460
+ For more details, see :func:`k_edge_augmentation`.
461
+
462
+ weight : string
463
+ key to use to find weights if ``avail`` is a set of 3-tuples.
464
+ For more details, see :func:`k_edge_augmentation`.
465
+
466
+ Yields
467
+ ------
468
+ edge : tuple
469
+ Edges in the bridge-augmentation of G
470
+
471
+ Raises
472
+ ------
473
+ NetworkXUnfeasible
474
+ If no bridge-augmentation exists.
475
+
476
+ Notes
477
+ -----
478
+ If there are no constraints the solution can be computed in linear time
479
+ using :func:`unconstrained_bridge_augmentation`. Otherwise, the problem
480
+ becomes NP-hard and is the solution is approximated by
481
+ :func:`weighted_bridge_augmentation`.
482
+
483
+ See Also
484
+ --------
485
+ :func:`k_edge_augmentation`
486
+ """
487
+ if G.number_of_nodes() < 3:
488
+ raise nx.NetworkXUnfeasible("impossible to bridge connect less than 3 nodes")
489
+ if avail is None:
490
+ return unconstrained_bridge_augmentation(G)
491
+ else:
492
+ return weighted_bridge_augmentation(G, avail, weight=weight)
493
+
494
+
495
+ # --- Algorithms and Helpers ---
496
+
497
+
498
+ def _ordered(u, v):
499
+ """Returns the nodes in an undirected edge in lower-triangular order"""
500
+ return (u, v) if u < v else (v, u)
501
+
502
+
503
+ def _unpack_available_edges(avail, weight=None, G=None):
504
+ """Helper to separate avail into edges and corresponding weights"""
505
+ if weight is None:
506
+ weight = "weight"
507
+ if isinstance(avail, dict):
508
+ avail_uv = list(avail.keys())
509
+ avail_w = list(avail.values())
510
+ else:
511
+
512
+ def _try_getitem(d):
513
+ try:
514
+ return d[weight]
515
+ except TypeError:
516
+ return d
517
+
518
+ avail_uv = [tup[0:2] for tup in avail]
519
+ avail_w = [1 if len(tup) == 2 else _try_getitem(tup[-1]) for tup in avail]
520
+
521
+ if G is not None:
522
+ # Edges already in the graph are filtered
523
+ flags = [not G.has_edge(u, v) for u, v in avail_uv]
524
+ avail_uv = list(it.compress(avail_uv, flags))
525
+ avail_w = list(it.compress(avail_w, flags))
526
+ return avail_uv, avail_w
527
+
528
+
529
+ MetaEdge = namedtuple("MetaEdge", ("meta_uv", "uv", "w"))
530
+
531
+
532
+ def _lightest_meta_edges(mapping, avail_uv, avail_w):
533
+ """Maps available edges in the original graph to edges in the metagraph.
534
+
535
+ Parameters
536
+ ----------
537
+ mapping : dict
538
+ mapping produced by :func:`collapse`, that maps each node in the
539
+ original graph to a node in the meta graph
540
+
541
+ avail_uv : list
542
+ list of edges
543
+
544
+ avail_w : list
545
+ list of edge weights
546
+
547
+ Notes
548
+ -----
549
+ Each node in the metagraph is a k-edge-connected component in the original
550
+ graph. We don't care about any edge within the same k-edge-connected
551
+ component, so we ignore self edges. We also are only interested in the
552
+ minimum weight edge bridging each k-edge-connected component so, we group
553
+ the edges by meta-edge and take the lightest in each group.
554
+
555
+ Examples
556
+ --------
557
+ >>> # Each group represents a meta-node
558
+ >>> groups = ([1, 2, 3], [4, 5], [6])
559
+ >>> mapping = {n: meta_n for meta_n, ns in enumerate(groups) for n in ns}
560
+ >>> avail_uv = [(1, 2), (3, 6), (1, 4), (5, 2), (6, 1), (2, 6), (3, 1)]
561
+ >>> avail_w = [20, 99, 20, 15, 50, 99, 20]
562
+ >>> sorted(_lightest_meta_edges(mapping, avail_uv, avail_w))
563
+ [MetaEdge(meta_uv=(0, 1), uv=(5, 2), w=15), MetaEdge(meta_uv=(0, 2), uv=(6, 1), w=50)]
564
+ """
565
+ grouped_wuv = defaultdict(list)
566
+ for w, (u, v) in zip(avail_w, avail_uv):
567
+ # Order the meta-edge so it can be used as a dict key
568
+ meta_uv = _ordered(mapping[u], mapping[v])
569
+ # Group each available edge using the meta-edge as a key
570
+ grouped_wuv[meta_uv].append((w, u, v))
571
+
572
+ # Now that all available edges are grouped, choose one per group
573
+ for (mu, mv), choices_wuv in grouped_wuv.items():
574
+ # Ignore available edges within the same meta-node
575
+ if mu != mv:
576
+ # Choose the lightest available edge belonging to each meta-edge
577
+ w, u, v = min(choices_wuv)
578
+ yield MetaEdge((mu, mv), (u, v), w)
579
+
580
+
581
+ @nx._dispatchable
582
+ def unconstrained_one_edge_augmentation(G):
583
+ """Finds the smallest set of edges to connect G.
584
+
585
+ This is a variant of the unweighted MST problem.
586
+ If G is not empty, a feasible solution always exists.
587
+
588
+ Parameters
589
+ ----------
590
+ G : NetworkX graph
591
+ An undirected graph.
592
+
593
+ Yields
594
+ ------
595
+ edge : tuple
596
+ Edges in the one-edge-augmentation of G
597
+
598
+ See Also
599
+ --------
600
+ :func:`one_edge_augmentation`
601
+ :func:`k_edge_augmentation`
602
+
603
+ Examples
604
+ --------
605
+ >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
606
+ >>> G.add_nodes_from([6, 7, 8])
607
+ >>> sorted(unconstrained_one_edge_augmentation(G))
608
+ [(1, 4), (4, 6), (6, 7), (7, 8)]
609
+ """
610
+ ccs1 = list(nx.connected_components(G))
611
+ C = collapse(G, ccs1)
612
+ # When we are not constrained, we can just make a meta graph tree.
613
+ meta_nodes = list(C.nodes())
614
+ # build a path in the metagraph
615
+ meta_aug = list(zip(meta_nodes, meta_nodes[1:]))
616
+ # map that path to the original graph
617
+ inverse = defaultdict(list)
618
+ for k, v in C.graph["mapping"].items():
619
+ inverse[v].append(k)
620
+ for mu, mv in meta_aug:
621
+ yield (inverse[mu][0], inverse[mv][0])
622
+
623
+
624
+ @nx._dispatchable
625
+ def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
626
+ """Finds the minimum weight set of edges to connect G if one exists.
627
+
628
+ This is a variant of the weighted MST problem.
629
+
630
+ Parameters
631
+ ----------
632
+ G : NetworkX graph
633
+ An undirected graph.
634
+
635
+ avail : dict or a set of 2 or 3 tuples
636
+ For more details, see :func:`k_edge_augmentation`.
637
+
638
+ weight : string
639
+ key to use to find weights if ``avail`` is a set of 3-tuples.
640
+ For more details, see :func:`k_edge_augmentation`.
641
+
642
+ partial : boolean
643
+ If partial is True and no feasible k-edge-augmentation exists, then the
644
+ augmenting edges minimize the number of connected components.
645
+
646
+ Yields
647
+ ------
648
+ edge : tuple
649
+ Edges in the subset of avail chosen to connect G.
650
+
651
+ See Also
652
+ --------
653
+ :func:`one_edge_augmentation`
654
+ :func:`k_edge_augmentation`
655
+
656
+ Examples
657
+ --------
658
+ >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
659
+ >>> G.add_nodes_from([6, 7, 8])
660
+ >>> # any edge not in avail has an implicit weight of infinity
661
+ >>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
662
+ >>> sorted(weighted_one_edge_augmentation(G, avail))
663
+ [(1, 5), (4, 7), (6, 1), (8, 1)]
664
+ >>> # find another solution by giving large weights to edges in the
665
+ >>> # previous solution (note some of the old edges must be used)
666
+ >>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
667
+ >>> sorted(weighted_one_edge_augmentation(G, avail))
668
+ [(1, 5), (4, 7), (6, 1), (8, 2)]
669
+ """
670
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
671
+ # Collapse CCs in the original graph into nodes in a metagraph
672
+ # Then find an MST of the metagraph instead of the original graph
673
+ C = collapse(G, nx.connected_components(G))
674
+ mapping = C.graph["mapping"]
675
+ # Assign each available edge to an edge in the metagraph
676
+ candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
677
+ # nx.set_edge_attributes(C, name='weight', values=0)
678
+ C.add_edges_from(
679
+ (mu, mv, {"weight": w, "generator": uv})
680
+ for (mu, mv), uv, w in candidate_mapping
681
+ )
682
+ # Find MST of the meta graph
683
+ meta_mst = nx.minimum_spanning_tree(C)
684
+ if not partial and not nx.is_connected(meta_mst):
685
+ raise nx.NetworkXUnfeasible("Not possible to connect G with available edges")
686
+ # Yield the edge that generated the meta-edge
687
+ for mu, mv, d in meta_mst.edges(data=True):
688
+ if "generator" in d:
689
+ edge = d["generator"]
690
+ yield edge
691
+
692
+
693
+ @nx._dispatchable
694
+ def unconstrained_bridge_augmentation(G):
695
+ """Finds an optimal 2-edge-augmentation of G using the fewest edges.
696
+
697
+ This is an implementation of the algorithm detailed in [1]_.
698
+ The basic idea is to construct a meta-graph of bridge-ccs, connect leaf
699
+ nodes of the trees to connect the entire graph, and finally connect the
700
+ leafs of the tree in dfs-preorder to bridge connect the entire graph.
701
+
702
+ Parameters
703
+ ----------
704
+ G : NetworkX graph
705
+ An undirected graph.
706
+
707
+ Yields
708
+ ------
709
+ edge : tuple
710
+ Edges in the bridge augmentation of G
711
+
712
+ Notes
713
+ -----
714
+ Input: a graph G.
715
+ First find the bridge components of G and collapse each bridge-cc into a
716
+ node of a metagraph graph C, which is guaranteed to be a forest of trees.
717
+
718
+ C contains p "leafs" --- nodes with exactly one incident edge.
719
+ C contains q "isolated nodes" --- nodes with no incident edges.
720
+
721
+ Theorem: If p + q > 1, then at least :math:`ceil(p / 2) + q` edges are
722
+ needed to bridge connect C. This algorithm achieves this min number.
723
+
724
+ The method first adds enough edges to make G into a tree and then pairs
725
+ leafs in a simple fashion.
726
+
727
+ Let n be the number of trees in C. Let v(i) be an isolated vertex in the
728
+ i-th tree if one exists, otherwise it is a pair of distinct leafs nodes
729
+ in the i-th tree. Alternating edges from these sets (i.e. adding edges
730
+ A1 = [(v(i)[0], v(i + 1)[1]), v(i + 1)[0], v(i + 2)[1])...]) connects C
731
+ into a tree T. This tree has p' = p + 2q - 2(n -1) leafs and no isolated
732
+ vertices. A1 has n - 1 edges. The next step finds ceil(p' / 2) edges to
733
+ biconnect any tree with p' leafs.
734
+
735
+ Convert T into an arborescence T' by picking an arbitrary root node with
736
+ degree >= 2 and directing all edges away from the root. Note the
737
+ implementation implicitly constructs T'.
738
+
739
+ The leafs of T are the nodes with no existing edges in T'.
740
+ Order the leafs of T' by DFS preorder. Then break this list in half
741
+ and add the zipped pairs to A2.
742
+
743
+ The set A = A1 + A2 is the minimum augmentation in the metagraph.
744
+
745
+ To convert this to edges in the original graph
746
+
747
+ References
748
+ ----------
749
+ .. [1] Eswaran, Kapali P., and R. Endre Tarjan. (1975) Augmentation problems.
750
+ http://epubs.siam.org/doi/abs/10.1137/0205044
751
+
752
+ See Also
753
+ --------
754
+ :func:`bridge_augmentation`
755
+ :func:`k_edge_augmentation`
756
+
757
+ Examples
758
+ --------
759
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
760
+ >>> sorted(unconstrained_bridge_augmentation(G))
761
+ [(1, 7)]
762
+ >>> G = nx.path_graph((1, 2, 3, 2, 4, 5, 6, 7))
763
+ >>> sorted(unconstrained_bridge_augmentation(G))
764
+ [(1, 3), (3, 7)]
765
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
766
+ >>> G.add_node(4)
767
+ >>> sorted(unconstrained_bridge_augmentation(G))
768
+ [(1, 4), (4, 0)]
769
+ """
770
+ # -----
771
+ # Mapping of terms from (Eswaran and Tarjan):
772
+ # G = G_0 - the input graph
773
+ # C = G_0' - the bridge condensation of G. (This is a forest of trees)
774
+ # A1 = A_1 - the edges to connect the forest into a tree
775
+ # leaf = pendant - a node with degree of 1
776
+
777
+ # alpha(v) = maps the node v in G to its meta-node in C
778
+ # beta(x) = maps the meta-node x in C to any node in the bridge
779
+ # component of G corresponding to x.
780
+
781
+ # find the 2-edge-connected components of G
782
+ bridge_ccs = list(nx.connectivity.bridge_components(G))
783
+ # condense G into an forest C
784
+ C = collapse(G, bridge_ccs)
785
+
786
+ # Choose pairs of distinct leaf nodes in each tree. If this is not
787
+ # possible then make a pair using the single isolated node in the tree.
788
+ vset1 = [
789
+ tuple(cc) * 2 # case1: an isolated node
790
+ if len(cc) == 1
791
+ else sorted(cc, key=C.degree)[0:2] # case2: pair of leaf nodes
792
+ for cc in nx.connected_components(C)
793
+ ]
794
+ if len(vset1) > 1:
795
+ # Use this set to construct edges that connect C into a tree.
796
+ nodes1 = [vs[0] for vs in vset1]
797
+ nodes2 = [vs[1] for vs in vset1]
798
+ A1 = list(zip(nodes1[1:], nodes2))
799
+ else:
800
+ A1 = []
801
+ # Connect each tree in the forest to construct an arborescence
802
+ T = C.copy()
803
+ T.add_edges_from(A1)
804
+
805
+ # If there are only two leaf nodes, we simply connect them.
806
+ leafs = [n for n, d in T.degree() if d == 1]
807
+ if len(leafs) == 1:
808
+ A2 = []
809
+ if len(leafs) == 2:
810
+ A2 = [tuple(leafs)]
811
+ else:
812
+ # Choose an arbitrary non-leaf root
813
+ try:
814
+ root = next(n for n, d in T.degree() if d > 1)
815
+ except StopIteration: # no nodes found with degree > 1
816
+ return
817
+ # order the leaves of C by (induced directed) preorder
818
+ v2 = [n for n in nx.dfs_preorder_nodes(T, root) if T.degree(n) == 1]
819
+ # connecting first half of the leafs in pre-order to the second
820
+ # half will bridge connect the tree with the fewest edges.
821
+ half = math.ceil(len(v2) / 2)
822
+ A2 = list(zip(v2[:half], v2[-half:]))
823
+
824
+ # collect the edges used to augment the original forest
825
+ aug_tree_edges = A1 + A2
826
+
827
+ # Construct the mapping (beta) from meta-nodes to regular nodes
828
+ inverse = defaultdict(list)
829
+ for k, v in C.graph["mapping"].items():
830
+ inverse[v].append(k)
831
+ # sort so we choose minimum degree nodes first
832
+ inverse = {
833
+ mu: sorted(mapped, key=lambda u: (G.degree(u), u))
834
+ for mu, mapped in inverse.items()
835
+ }
836
+
837
+ # For each meta-edge, map back to an arbitrary pair in the original graph
838
+ G2 = G.copy()
839
+ for mu, mv in aug_tree_edges:
840
+ # Find the first available edge that doesn't exist and return it
841
+ for u, v in it.product(inverse[mu], inverse[mv]):
842
+ if not G2.has_edge(u, v):
843
+ G2.add_edge(u, v)
844
+ yield u, v
845
+ break
846
+
847
+
848
+ @nx._dispatchable
849
+ def weighted_bridge_augmentation(G, avail, weight=None):
850
+ """Finds an approximate min-weight 2-edge-augmentation of G.
851
+
852
+ This is an implementation of the approximation algorithm detailed in [1]_.
853
+ It chooses a set of edges from avail to add to G that renders it
854
+ 2-edge-connected if such a subset exists. This is done by finding a
855
+ minimum spanning arborescence of a specially constructed metagraph.
856
+
857
+ Parameters
858
+ ----------
859
+ G : NetworkX graph
860
+ An undirected graph.
861
+
862
+ avail : set of 2 or 3 tuples.
863
+ candidate edges (with optional weights) to choose from
864
+
865
+ weight : string
866
+ key to use to find weights if avail is a set of 3-tuples where the
867
+ third item in each tuple is a dictionary.
868
+
869
+ Yields
870
+ ------
871
+ edge : tuple
872
+ Edges in the subset of avail chosen to bridge augment G.
873
+
874
+ Notes
875
+ -----
876
+ Finding a weighted 2-edge-augmentation is NP-hard.
877
+ Any edge not in ``avail`` is considered to have a weight of infinity.
878
+ The approximation factor is 2 if ``G`` is connected and 3 if it is not.
879
+ Runs in :math:`O(m + n log(n))` time
880
+
881
+ References
882
+ ----------
883
+ .. [1] Khuller, Samir, and Ramakrishna Thurimella. (1993) Approximation
884
+ algorithms for graph augmentation.
885
+ http://www.sciencedirect.com/science/article/pii/S0196677483710102
886
+
887
+ See Also
888
+ --------
889
+ :func:`bridge_augmentation`
890
+ :func:`k_edge_augmentation`
891
+
892
+ Examples
893
+ --------
894
+ >>> G = nx.path_graph((1, 2, 3, 4))
895
+ >>> # When the weights are equal, (1, 4) is the best
896
+ >>> avail = [(1, 4, 1), (1, 3, 1), (2, 4, 1)]
897
+ >>> sorted(weighted_bridge_augmentation(G, avail))
898
+ [(1, 4)]
899
+ >>> # Giving (1, 4) a high weight makes the two edge solution the best.
900
+ >>> avail = [(1, 4, 1000), (1, 3, 1), (2, 4, 1)]
901
+ >>> sorted(weighted_bridge_augmentation(G, avail))
902
+ [(1, 3), (2, 4)]
903
+ >>> # ------
904
+ >>> G = nx.path_graph((1, 2, 3, 4))
905
+ >>> G.add_node(5)
906
+ >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 1)]
907
+ >>> sorted(weighted_bridge_augmentation(G, avail=avail))
908
+ [(1, 5), (4, 5)]
909
+ >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
910
+ >>> sorted(weighted_bridge_augmentation(G, avail=avail))
911
+ [(1, 5), (2, 5), (4, 5)]
912
+ """
913
+
914
+ if weight is None:
915
+ weight = "weight"
916
+
917
+ # If input G is not connected the approximation factor increases to 3
918
+ if not nx.is_connected(G):
919
+ H = G.copy()
920
+ connectors = list(one_edge_augmentation(H, avail=avail, weight=weight))
921
+ H.add_edges_from(connectors)
922
+
923
+ yield from connectors
924
+ else:
925
+ connectors = []
926
+ H = G
927
+
928
+ if len(avail) == 0:
929
+ if nx.has_bridges(H):
930
+ raise nx.NetworkXUnfeasible("no augmentation possible")
931
+
932
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=H)
933
+
934
+ # Collapse input into a metagraph. Meta nodes are bridge-ccs
935
+ bridge_ccs = nx.connectivity.bridge_components(H)
936
+ C = collapse(H, bridge_ccs)
937
+
938
+ # Use the meta graph to shrink avail to a small feasible subset
939
+ mapping = C.graph["mapping"]
940
+ # Choose the minimum weight feasible edge in each group
941
+ meta_to_wuv = {
942
+ (mu, mv): (w, uv)
943
+ for (mu, mv), uv, w in _lightest_meta_edges(mapping, avail_uv, avail_w)
944
+ }
945
+
946
+ # Mapping of terms from (Khuller and Thurimella):
947
+ # C : G_0 = (V, E^0)
948
+ # This is the metagraph where each node is a 2-edge-cc in G.
949
+ # The edges in C represent bridges in the original graph.
950
+ # (mu, mv) : E - E^0 # they group both avail and given edges in E
951
+ # T : \Gamma
952
+ # D : G^D = (V, E_D)
953
+
954
+ # The paper uses ancestor because children point to parents, which is
955
+ # contrary to networkx standards. So, we actually need to run
956
+ # nx.least_common_ancestor on the reversed Tree.
957
+
958
+ # Pick an arbitrary leaf from C as the root
959
+ try:
960
+ root = next(n for n, d in C.degree() if d == 1)
961
+ except StopIteration: # no nodes found with degree == 1
962
+ return
963
+ # Root C into a tree TR by directing all edges away from the root
964
+ # Note in their paper T directs edges towards the root
965
+ TR = nx.dfs_tree(C, root)
966
+
967
+ # Add to D the directed edges of T and set their weight to zero
968
+ # This indicates that it costs nothing to use edges that were given.
969
+ D = nx.reverse(TR).copy()
970
+
971
+ nx.set_edge_attributes(D, name="weight", values=0)
972
+
973
+ # The LCA of mu and mv in T is the shared ancestor of mu and mv that is
974
+ # located farthest from the root.
975
+ lca_gen = nx.tree_all_pairs_lowest_common_ancestor(
976
+ TR, root=root, pairs=meta_to_wuv.keys()
977
+ )
978
+
979
+ for (mu, mv), lca in lca_gen:
980
+ w, uv = meta_to_wuv[(mu, mv)]
981
+ if lca == mu:
982
+ # If u is an ancestor of v in TR, then add edge u->v to D
983
+ D.add_edge(lca, mv, weight=w, generator=uv)
984
+ elif lca == mv:
985
+ # If v is an ancestor of u in TR, then add edge v->u to D
986
+ D.add_edge(lca, mu, weight=w, generator=uv)
987
+ else:
988
+ # If neither u nor v is a ancestor of the other in TR
989
+ # let t = lca(TR, u, v) and add edges t->u and t->v
990
+ # Track the original edge that GENERATED these edges.
991
+ D.add_edge(lca, mu, weight=w, generator=uv)
992
+ D.add_edge(lca, mv, weight=w, generator=uv)
993
+
994
+ # Then compute a minimum rooted branching
995
+ try:
996
+ # Note the original edges must be directed towards to root for the
997
+ # branching to give us a bridge-augmentation.
998
+ A = _minimum_rooted_branching(D, root)
999
+ except nx.NetworkXException as err:
1000
+ # If there is no branching then augmentation is not possible
1001
+ raise nx.NetworkXUnfeasible("no 2-edge-augmentation possible") from err
1002
+
1003
+ # For each edge e, in the branching that did not belong to the directed
1004
+ # tree T, add the corresponding edge that **GENERATED** it (this is not
1005
+ # necessarily e itself!)
1006
+
1007
+ # ensure the third case does not generate edges twice
1008
+ bridge_connectors = set()
1009
+ for mu, mv in A.edges():
1010
+ data = D.get_edge_data(mu, mv)
1011
+ if "generator" in data:
1012
+ # Add the avail edge that generated the branching edge.
1013
+ edge = data["generator"]
1014
+ bridge_connectors.add(edge)
1015
+
1016
+ yield from bridge_connectors
1017
+
1018
+
1019
+ def _minimum_rooted_branching(D, root):
1020
+ """Helper function to compute a minimum rooted branching (aka rooted
1021
+ arborescence)
1022
+
1023
+ Before the branching can be computed, the directed graph must be rooted by
1024
+ removing the predecessors of root.
1025
+
1026
+ A branching / arborescence of rooted graph G is a subgraph that contains a
1027
+ directed path from the root to every other vertex. It is the directed
1028
+ analog of the minimum spanning tree problem.
1029
+
1030
+ References
1031
+ ----------
1032
+ [1] Khuller, Samir (2002) Advanced Algorithms Lecture 24 Notes.
1033
+ https://web.archive.org/web/20121030033722/https://www.cs.umd.edu/class/spring2011/cmsc651/lec07.pdf
1034
+ """
1035
+ rooted = D.copy()
1036
+ # root the graph by removing all predecessors to `root`.
1037
+ rooted.remove_edges_from([(u, root) for u in D.predecessors(root)])
1038
+ # Then compute the branching / arborescence.
1039
+ A = nx.minimum_spanning_arborescence(rooted)
1040
+ return A
1041
+
1042
+
1043
+ @nx._dispatchable(returns_graph=True)
1044
+ def collapse(G, grouped_nodes):
1045
+ """Collapses each group of nodes into a single node.
1046
+
1047
+ This is similar to condensation, but works on undirected graphs.
1048
+
1049
+ Parameters
1050
+ ----------
1051
+ G : NetworkX Graph
1052
+
1053
+ grouped_nodes: list or generator
1054
+ Grouping of nodes to collapse. The grouping must be disjoint.
1055
+ If grouped_nodes are strongly_connected_components then this is
1056
+ equivalent to :func:`condensation`.
1057
+
1058
+ Returns
1059
+ -------
1060
+ C : NetworkX Graph
1061
+ The collapsed graph C of G with respect to the node grouping. The node
1062
+ labels are integers corresponding to the index of the component in the
1063
+ list of grouped_nodes. C has a graph attribute named 'mapping' with a
1064
+ dictionary mapping the original nodes to the nodes in C to which they
1065
+ belong. Each node in C also has a node attribute 'members' with the set
1066
+ of original nodes in G that form the group that the node in C
1067
+ represents.
1068
+
1069
+ Examples
1070
+ --------
1071
+ >>> # Collapses a graph using disjoint groups, but not necessarily connected
1072
+ >>> G = nx.Graph([(1, 0), (2, 3), (3, 1), (3, 4), (4, 5), (5, 6), (5, 7)])
1073
+ >>> G.add_node("A")
1074
+ >>> grouped_nodes = [{0, 1, 2, 3}, {5, 6, 7}]
1075
+ >>> C = collapse(G, grouped_nodes)
1076
+ >>> members = nx.get_node_attributes(C, "members")
1077
+ >>> sorted(members.keys())
1078
+ [0, 1, 2, 3]
1079
+ >>> member_values = set(map(frozenset, members.values()))
1080
+ >>> assert {0, 1, 2, 3} in member_values
1081
+ >>> assert {4} in member_values
1082
+ >>> assert {5, 6, 7} in member_values
1083
+ >>> assert {"A"} in member_values
1084
+ """
1085
+ mapping = {}
1086
+ members = {}
1087
+ C = G.__class__()
1088
+ i = 0 # required if G is empty
1089
+ remaining = set(G.nodes())
1090
+ for i, group in enumerate(grouped_nodes):
1091
+ group = set(group)
1092
+ assert remaining.issuperset(
1093
+ group
1094
+ ), "grouped nodes must exist in G and be disjoint"
1095
+ remaining.difference_update(group)
1096
+ members[i] = group
1097
+ mapping.update((n, i) for n in group)
1098
+ # remaining nodes are in their own group
1099
+ for i, node in enumerate(remaining, start=i + 1):
1100
+ group = {node}
1101
+ members[i] = group
1102
+ mapping.update((n, i) for n in group)
1103
+ number_of_groups = i + 1
1104
+ C.add_nodes_from(range(number_of_groups))
1105
+ C.add_edges_from(
1106
+ (mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
1107
+ )
1108
+ # Add a list of members (ie original nodes) to each node (ie scc) in C.
1109
+ nx.set_node_attributes(C, name="members", values=members)
1110
+ # Add mapping dict as graph attribute
1111
+ C.graph["mapping"] = mapping
1112
+ return C
1113
+
1114
+
1115
+ @nx._dispatchable
1116
+ def complement_edges(G):
1117
+ """Returns only the edges in the complement of G
1118
+
1119
+ Parameters
1120
+ ----------
1121
+ G : NetworkX Graph
1122
+
1123
+ Yields
1124
+ ------
1125
+ edge : tuple
1126
+ Edges in the complement of G
1127
+
1128
+ Examples
1129
+ --------
1130
+ >>> G = nx.path_graph((1, 2, 3, 4))
1131
+ >>> sorted(complement_edges(G))
1132
+ [(1, 3), (1, 4), (2, 4)]
1133
+ >>> G = nx.path_graph((1, 2, 3, 4), nx.DiGraph())
1134
+ >>> sorted(complement_edges(G))
1135
+ [(1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
1136
+ >>> G = nx.complete_graph(1000)
1137
+ >>> sorted(complement_edges(G))
1138
+ []
1139
+ """
1140
+ G_adj = G._adj # Store as a variable to eliminate attribute lookup
1141
+ if G.is_directed():
1142
+ for u, v in it.combinations(G.nodes(), 2):
1143
+ if v not in G_adj[u]:
1144
+ yield (u, v)
1145
+ if u not in G_adj[v]:
1146
+ yield (v, u)
1147
+ else:
1148
+ for u, v in it.combinations(G.nodes(), 2):
1149
+ if v not in G_adj[u]:
1150
+ yield (u, v)
1151
+
1152
+
1153
+ def _compat_shuffle(rng, input):
1154
+ """wrapper around rng.shuffle for python 2 compatibility reasons"""
1155
+ rng.shuffle(input)
1156
+
1157
+
1158
+ @not_implemented_for("multigraph")
1159
+ @not_implemented_for("directed")
1160
+ @py_random_state(4)
1161
+ @nx._dispatchable
1162
+ def greedy_k_edge_augmentation(G, k, avail=None, weight=None, seed=None):
1163
+ """Greedy algorithm for finding a k-edge-augmentation
1164
+
1165
+ Parameters
1166
+ ----------
1167
+ G : NetworkX graph
1168
+ An undirected graph.
1169
+
1170
+ k : integer
1171
+ Desired edge connectivity
1172
+
1173
+ avail : dict or a set of 2 or 3 tuples
1174
+ For more details, see :func:`k_edge_augmentation`.
1175
+
1176
+ weight : string
1177
+ key to use to find weights if ``avail`` is a set of 3-tuples.
1178
+ For more details, see :func:`k_edge_augmentation`.
1179
+
1180
+ seed : integer, random_state, or None (default)
1181
+ Indicator of random number generation state.
1182
+ See :ref:`Randomness<randomness>`.
1183
+
1184
+ Yields
1185
+ ------
1186
+ edge : tuple
1187
+ Edges in the greedy augmentation of G
1188
+
1189
+ Notes
1190
+ -----
1191
+ The algorithm is simple. Edges are incrementally added between parts of the
1192
+ graph that are not yet locally k-edge-connected. Then edges are from the
1193
+ augmenting set are pruned as long as local-edge-connectivity is not broken.
1194
+
1195
+ This algorithm is greedy and does not provide optimality guarantees. It
1196
+ exists only to provide :func:`k_edge_augmentation` with the ability to
1197
+ generate a feasible solution for arbitrary k.
1198
+
1199
+ See Also
1200
+ --------
1201
+ :func:`k_edge_augmentation`
1202
+
1203
+ Examples
1204
+ --------
1205
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
1206
+ >>> sorted(greedy_k_edge_augmentation(G, k=2))
1207
+ [(1, 7)]
1208
+ >>> sorted(greedy_k_edge_augmentation(G, k=1, avail=[]))
1209
+ []
1210
+ >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
1211
+ >>> avail = {(u, v): 1 for (u, v) in complement_edges(G)}
1212
+ >>> # randomized pruning process can produce different solutions
1213
+ >>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=2))
1214
+ [(1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 6), (3, 7), (5, 7)]
1215
+ >>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=3))
1216
+ [(1, 3), (1, 5), (1, 6), (2, 4), (2, 6), (3, 7), (4, 7), (5, 7)]
1217
+ """
1218
+ # Result set
1219
+ aug_edges = []
1220
+
1221
+ done = is_k_edge_connected(G, k)
1222
+ if done:
1223
+ return
1224
+ if avail is None:
1225
+ # all edges are available
1226
+ avail_uv = list(complement_edges(G))
1227
+ avail_w = [1] * len(avail_uv)
1228
+ else:
1229
+ # Get the unique set of unweighted edges
1230
+ avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
1231
+
1232
+ # Greedy: order lightest edges. Use degree sum to tie-break
1233
+ tiebreaker = [sum(map(G.degree, uv)) for uv in avail_uv]
1234
+ avail_wduv = sorted(zip(avail_w, tiebreaker, avail_uv))
1235
+ avail_uv = [uv for w, d, uv in avail_wduv]
1236
+
1237
+ # Incrementally add edges in until we are k-connected
1238
+ H = G.copy()
1239
+ for u, v in avail_uv:
1240
+ done = False
1241
+ if not is_locally_k_edge_connected(H, u, v, k=k):
1242
+ # Only add edges in parts that are not yet locally k-edge-connected
1243
+ aug_edges.append((u, v))
1244
+ H.add_edge(u, v)
1245
+ # Did adding this edge help?
1246
+ if H.degree(u) >= k and H.degree(v) >= k:
1247
+ done = is_k_edge_connected(H, k)
1248
+ if done:
1249
+ break
1250
+
1251
+ # Check for feasibility
1252
+ if not done:
1253
+ raise nx.NetworkXUnfeasible("not able to k-edge-connect with available edges")
1254
+
1255
+ # Randomized attempt to reduce the size of the solution
1256
+ _compat_shuffle(seed, aug_edges)
1257
+ for u, v in list(aug_edges):
1258
+ # Don't remove if we know it would break connectivity
1259
+ if H.degree(u) <= k or H.degree(v) <= k:
1260
+ continue
1261
+ H.remove_edge(u, v)
1262
+ aug_edges.remove((u, v))
1263
+ if not is_k_edge_connected(H, k=k):
1264
+ # If removing this edge breaks feasibility, undo
1265
+ H.add_edge(u, v)
1266
+ aug_edges.append((u, v))
1267
+
1268
+ # Generate results
1269
+ yield from aug_edges
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import itertools as it
12
+ from functools import partial
13
+
14
+ import networkx as nx
15
+ from networkx.utils import arbitrary_element, not_implemented_for
16
+
17
+ __all__ = [
18
+ "k_edge_components",
19
+ "k_edge_subgraphs",
20
+ "bridge_components",
21
+ "EdgeComponentAuxGraph",
22
+ ]
23
+
24
+
25
+ @not_implemented_for("multigraph")
26
+ @nx._dispatchable
27
+ def k_edge_components(G, k):
28
+ """Generates nodes in each maximal k-edge-connected component in G.
29
+
30
+ Parameters
31
+ ----------
32
+ G : NetworkX graph
33
+
34
+ k : Integer
35
+ Desired edge connectivity
36
+
37
+ Returns
38
+ -------
39
+ k_edge_components : a generator of k-edge-ccs. Each set of returned nodes
40
+ will have k-edge-connectivity in the graph G.
41
+
42
+ See Also
43
+ --------
44
+ :func:`local_edge_connectivity`
45
+ :func:`k_edge_subgraphs` : similar to this function, but the subgraph
46
+ defined by the nodes must also have k-edge-connectivity.
47
+ :func:`k_components` : similar to this function, but uses node-connectivity
48
+ instead of edge-connectivity
49
+
50
+ Raises
51
+ ------
52
+ NetworkXNotImplemented
53
+ If the input graph is a multigraph.
54
+
55
+ ValueError:
56
+ If k is less than 1
57
+
58
+ Notes
59
+ -----
60
+ Attempts to use the most efficient implementation available based on k.
61
+ If k=1, this is simply connected components for directed graphs and
62
+ connected components for undirected graphs.
63
+ If k=2 on an efficient bridge connected component algorithm from _[1] is
64
+ run based on the chain decomposition.
65
+ Otherwise, the algorithm from _[2] is used.
66
+
67
+ Examples
68
+ --------
69
+ >>> import itertools as it
70
+ >>> from networkx.utils import pairwise
71
+ >>> paths = [
72
+ ... (1, 2, 4, 3, 1, 4),
73
+ ... (5, 6, 7, 8, 5, 7, 8, 6),
74
+ ... ]
75
+ >>> G = nx.Graph()
76
+ >>> G.add_nodes_from(it.chain(*paths))
77
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
78
+ >>> # note this returns {1, 4} unlike k_edge_subgraphs
79
+ >>> sorted(map(sorted, nx.k_edge_components(G, k=3)))
80
+ [[1, 4], [2], [3], [5, 6, 7, 8]]
81
+
82
+ References
83
+ ----------
84
+ .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29
85
+ .. [2] Wang, Tianhao, et al. (2015) A simple algorithm for finding all
86
+ k-edge-connected components.
87
+ http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
88
+ """
89
+ # Compute k-edge-ccs using the most efficient algorithms available.
90
+ if k < 1:
91
+ raise ValueError("k cannot be less than 1")
92
+ if G.is_directed():
93
+ if k == 1:
94
+ return nx.strongly_connected_components(G)
95
+ else:
96
+ # TODO: investigate https://arxiv.org/abs/1412.6466 for k=2
97
+ aux_graph = EdgeComponentAuxGraph.construct(G)
98
+ return aux_graph.k_edge_components(k)
99
+ else:
100
+ if k == 1:
101
+ return nx.connected_components(G)
102
+ elif k == 2:
103
+ return bridge_components(G)
104
+ else:
105
+ aux_graph = EdgeComponentAuxGraph.construct(G)
106
+ return aux_graph.k_edge_components(k)
107
+
108
+
109
+ @not_implemented_for("multigraph")
110
+ @nx._dispatchable
111
+ def k_edge_subgraphs(G, k):
112
+ """Generates nodes in each maximal k-edge-connected subgraph in G.
113
+
114
+ Parameters
115
+ ----------
116
+ G : NetworkX graph
117
+
118
+ k : Integer
119
+ Desired edge connectivity
120
+
121
+ Returns
122
+ -------
123
+ k_edge_subgraphs : a generator of k-edge-subgraphs
124
+ Each k-edge-subgraph is a maximal set of nodes that defines a subgraph
125
+ of G that is k-edge-connected.
126
+
127
+ See Also
128
+ --------
129
+ :func:`edge_connectivity`
130
+ :func:`k_edge_components` : similar to this function, but nodes only
131
+ need to have k-edge-connectivity within the graph G and the subgraphs
132
+ might not be k-edge-connected.
133
+
134
+ Raises
135
+ ------
136
+ NetworkXNotImplemented
137
+ If the input graph is a multigraph.
138
+
139
+ ValueError:
140
+ If k is less than 1
141
+
142
+ Notes
143
+ -----
144
+ Attempts to use the most efficient implementation available based on k.
145
+ If k=1, or k=2 and the graph is undirected, then this simply calls
146
+ `k_edge_components`. Otherwise the algorithm from _[1] is used.
147
+
148
+ Examples
149
+ --------
150
+ >>> import itertools as it
151
+ >>> from networkx.utils import pairwise
152
+ >>> paths = [
153
+ ... (1, 2, 4, 3, 1, 4),
154
+ ... (5, 6, 7, 8, 5, 7, 8, 6),
155
+ ... ]
156
+ >>> G = nx.Graph()
157
+ >>> G.add_nodes_from(it.chain(*paths))
158
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
159
+ >>> # note this does not return {1, 4} unlike k_edge_components
160
+ >>> sorted(map(sorted, nx.k_edge_subgraphs(G, k=3)))
161
+ [[1], [2], [3], [4], [5, 6, 7, 8]]
162
+
163
+ References
164
+ ----------
165
+ .. [1] Zhou, Liu, et al. (2012) Finding maximal k-edge-connected subgraphs
166
+ from a large graph. ACM International Conference on Extending Database
167
+ Technology 2012 480-–491.
168
+ https://openproceedings.org/2012/conf/edbt/ZhouLYLCL12.pdf
169
+ """
170
+ if k < 1:
171
+ raise ValueError("k cannot be less than 1")
172
+ if G.is_directed():
173
+ if k <= 1:
174
+ # For directed graphs ,
175
+ # When k == 1, k-edge-ccs and k-edge-subgraphs are the same
176
+ return k_edge_components(G, k)
177
+ else:
178
+ return _k_edge_subgraphs_nodes(G, k)
179
+ else:
180
+ if k <= 2:
181
+ # For undirected graphs,
182
+ # when k <= 2, k-edge-ccs and k-edge-subgraphs are the same
183
+ return k_edge_components(G, k)
184
+ else:
185
+ return _k_edge_subgraphs_nodes(G, k)
186
+
187
+
188
+ def _k_edge_subgraphs_nodes(G, k):
189
+ """Helper to get the nodes from the subgraphs.
190
+
191
+ This allows k_edge_subgraphs to return a generator.
192
+ """
193
+ for C in general_k_edge_subgraphs(G, k):
194
+ yield set(C.nodes())
195
+
196
+
197
+ @not_implemented_for("directed")
198
+ @not_implemented_for("multigraph")
199
+ @nx._dispatchable
200
+ def bridge_components(G):
201
+ """Finds all bridge-connected components G.
202
+
203
+ Parameters
204
+ ----------
205
+ G : NetworkX undirected graph
206
+
207
+ Returns
208
+ -------
209
+ bridge_components : a generator of 2-edge-connected components
210
+
211
+
212
+ See Also
213
+ --------
214
+ :func:`k_edge_subgraphs` : this function is a special case for an
215
+ undirected graph where k=2.
216
+ :func:`biconnected_components` : similar to this function, but is defined
217
+ using 2-node-connectivity instead of 2-edge-connectivity.
218
+
219
+ Raises
220
+ ------
221
+ NetworkXNotImplemented
222
+ If the input graph is directed or a multigraph.
223
+
224
+ Notes
225
+ -----
226
+ Bridge-connected components are also known as 2-edge-connected components.
227
+
228
+ Examples
229
+ --------
230
+ >>> # The barbell graph with parameter zero has a single bridge
231
+ >>> G = nx.barbell_graph(5, 0)
232
+ >>> from networkx.algorithms.connectivity.edge_kcomponents import bridge_components
233
+ >>> sorted(map(sorted, bridge_components(G)))
234
+ [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
235
+ """
236
+ H = G.copy()
237
+ H.remove_edges_from(nx.bridges(G))
238
+ yield from nx.connected_components(H)
239
+
240
+
241
+ class EdgeComponentAuxGraph:
242
+ r"""A simple algorithm to find all k-edge-connected components in a graph.
243
+
244
+ Constructing the auxiliary graph (which may take some time) allows for the
245
+ k-edge-ccs to be found in linear time for arbitrary k.
246
+
247
+ Notes
248
+ -----
249
+ This implementation is based on [1]_. The idea is to construct an auxiliary
250
+ graph from which the k-edge-ccs can be extracted in linear time. The
251
+ auxiliary graph is constructed in $O(|V|\cdot F)$ operations, where F is the
252
+ complexity of max flow. Querying the components takes an additional $O(|V|)$
253
+ operations. This algorithm can be slow for large graphs, but it handles an
254
+ arbitrary k and works for both directed and undirected inputs.
255
+
256
+ The undirected case for k=1 is exactly connected components.
257
+ The undirected case for k=2 is exactly bridge connected components.
258
+ The directed case for k=1 is exactly strongly connected components.
259
+
260
+ References
261
+ ----------
262
+ .. [1] Wang, Tianhao, et al. (2015) A simple algorithm for finding all
263
+ k-edge-connected components.
264
+ http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
265
+
266
+ Examples
267
+ --------
268
+ >>> import itertools as it
269
+ >>> from networkx.utils import pairwise
270
+ >>> from networkx.algorithms.connectivity import EdgeComponentAuxGraph
271
+ >>> # Build an interesting graph with multiple levels of k-edge-ccs
272
+ >>> paths = [
273
+ ... (1, 2, 3, 4, 1, 3, 4, 2), # a 3-edge-cc (a 4 clique)
274
+ ... (5, 6, 7, 5), # a 2-edge-cc (a 3 clique)
275
+ ... (1, 5), # combine first two ccs into a 1-edge-cc
276
+ ... (0,), # add an additional disconnected 1-edge-cc
277
+ ... ]
278
+ >>> G = nx.Graph()
279
+ >>> G.add_nodes_from(it.chain(*paths))
280
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
281
+ >>> # Constructing the AuxGraph takes about O(n ** 4)
282
+ >>> aux_graph = EdgeComponentAuxGraph.construct(G)
283
+ >>> # Once constructed, querying takes O(n)
284
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=1)))
285
+ [[0], [1, 2, 3, 4, 5, 6, 7]]
286
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=2)))
287
+ [[0], [1, 2, 3, 4], [5, 6, 7]]
288
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
289
+ [[0], [1, 2, 3, 4], [5], [6], [7]]
290
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=4)))
291
+ [[0], [1], [2], [3], [4], [5], [6], [7]]
292
+
293
+ The auxiliary graph is primarily used for k-edge-ccs but it
294
+ can also speed up the queries of k-edge-subgraphs by refining the
295
+ search space.
296
+
297
+ >>> import itertools as it
298
+ >>> from networkx.utils import pairwise
299
+ >>> from networkx.algorithms.connectivity import EdgeComponentAuxGraph
300
+ >>> paths = [
301
+ ... (1, 2, 4, 3, 1, 4),
302
+ ... ]
303
+ >>> G = nx.Graph()
304
+ >>> G.add_nodes_from(it.chain(*paths))
305
+ >>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
306
+ >>> aux_graph = EdgeComponentAuxGraph.construct(G)
307
+ >>> sorted(map(sorted, aux_graph.k_edge_subgraphs(k=3)))
308
+ [[1], [2], [3], [4]]
309
+ >>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
310
+ [[1, 4], [2], [3]]
311
+ """
312
+
313
+ # @not_implemented_for('multigraph') # TODO: fix decor for classmethods
314
+ @classmethod
315
+ def construct(EdgeComponentAuxGraph, G):
316
+ """Builds an auxiliary graph encoding edge-connectivity between nodes.
317
+
318
+ Notes
319
+ -----
320
+ Given G=(V, E), initialize an empty auxiliary graph A.
321
+ Choose an arbitrary source node s. Initialize a set N of available
322
+ nodes (that can be used as the sink). The algorithm picks an
323
+ arbitrary node t from N - {s}, and then computes the minimum st-cut
324
+ (S, T) with value w. If G is directed the minimum of the st-cut or
325
+ the ts-cut is used instead. Then, the edge (s, t) is added to the
326
+ auxiliary graph with weight w. The algorithm is called recursively
327
+ first using S as the available nodes and s as the source, and then
328
+ using T and t. Recursion stops when the source is the only available
329
+ node.
330
+
331
+ Parameters
332
+ ----------
333
+ G : NetworkX graph
334
+ """
335
+ # workaround for classmethod decorator
336
+ not_implemented_for("multigraph")(lambda G: G)(G)
337
+
338
+ def _recursive_build(H, A, source, avail):
339
+ # Terminate once the flow has been compute to every node.
340
+ if {source} == avail:
341
+ return
342
+ # pick an arbitrary node as the sink
343
+ sink = arbitrary_element(avail - {source})
344
+ # find the minimum cut and its weight
345
+ value, (S, T) = nx.minimum_cut(H, source, sink)
346
+ if H.is_directed():
347
+ # check if the reverse direction has a smaller cut
348
+ value_, (T_, S_) = nx.minimum_cut(H, sink, source)
349
+ if value_ < value:
350
+ value, S, T = value_, S_, T_
351
+ # add edge with weight of cut to the aux graph
352
+ A.add_edge(source, sink, weight=value)
353
+ # recursively call until all but one node is used
354
+ _recursive_build(H, A, source, avail.intersection(S))
355
+ _recursive_build(H, A, sink, avail.intersection(T))
356
+
357
+ # Copy input to ensure all edges have unit capacity
358
+ H = G.__class__()
359
+ H.add_nodes_from(G.nodes())
360
+ H.add_edges_from(G.edges(), capacity=1)
361
+
362
+ # A is the auxiliary graph to be constructed
363
+ # It is a weighted undirected tree
364
+ A = nx.Graph()
365
+
366
+ # Pick an arbitrary node as the source
367
+ if H.number_of_nodes() > 0:
368
+ source = arbitrary_element(H.nodes())
369
+ # Initialize a set of elements that can be chosen as the sink
370
+ avail = set(H.nodes())
371
+
372
+ # This constructs A
373
+ _recursive_build(H, A, source, avail)
374
+
375
+ # This class is a container the holds the auxiliary graph A and
376
+ # provides access the k_edge_components function.
377
+ self = EdgeComponentAuxGraph()
378
+ self.A = A
379
+ self.H = H
380
+ return self
381
+
382
+ def k_edge_components(self, k):
383
+ """Queries the auxiliary graph for k-edge-connected components.
384
+
385
+ Parameters
386
+ ----------
387
+ k : Integer
388
+ Desired edge connectivity
389
+
390
+ Returns
391
+ -------
392
+ k_edge_components : a generator of k-edge-ccs
393
+
394
+ Notes
395
+ -----
396
+ Given the auxiliary graph, the k-edge-connected components can be
397
+ determined in linear time by removing all edges with weights less than
398
+ k from the auxiliary graph. The resulting connected components are the
399
+ k-edge-ccs in the original graph.
400
+ """
401
+ if k < 1:
402
+ raise ValueError("k cannot be less than 1")
403
+ A = self.A
404
+ # "traverse the auxiliary graph A and delete all edges with weights less
405
+ # than k"
406
+ aux_weights = nx.get_edge_attributes(A, "weight")
407
+ # Create a relevant graph with the auxiliary edges with weights >= k
408
+ R = nx.Graph()
409
+ R.add_nodes_from(A.nodes())
410
+ R.add_edges_from(e for e, w in aux_weights.items() if w >= k)
411
+
412
+ # Return the nodes that are k-edge-connected in the original graph
413
+ yield from nx.connected_components(R)
414
+
415
+ def k_edge_subgraphs(self, k):
416
+ """Queries the auxiliary graph for k-edge-connected subgraphs.
417
+
418
+ Parameters
419
+ ----------
420
+ k : Integer
421
+ Desired edge connectivity
422
+
423
+ Returns
424
+ -------
425
+ k_edge_subgraphs : a generator of k-edge-subgraphs
426
+
427
+ Notes
428
+ -----
429
+ Refines the k-edge-ccs into k-edge-subgraphs. The running time is more
430
+ than $O(|V|)$.
431
+
432
+ For single values of k it is faster to use `nx.k_edge_subgraphs`.
433
+ But for multiple values of k, it can be faster to build AuxGraph and
434
+ then use this method.
435
+ """
436
+ if k < 1:
437
+ raise ValueError("k cannot be less than 1")
438
+ H = self.H
439
+ A = self.A
440
+ # "traverse the auxiliary graph A and delete all edges with weights less
441
+ # than k"
442
+ aux_weights = nx.get_edge_attributes(A, "weight")
443
+ # Create a relevant graph with the auxiliary edges with weights >= k
444
+ R = nx.Graph()
445
+ R.add_nodes_from(A.nodes())
446
+ R.add_edges_from(e for e, w in aux_weights.items() if w >= k)
447
+
448
+ # Return the components whose subgraphs are k-edge-connected
449
+ for cc in nx.connected_components(R):
450
+ if len(cc) < k:
451
+ # Early return optimization
452
+ for node in cc:
453
+ yield {node}
454
+ else:
455
+ # Call subgraph solution to refine the results
456
+ C = H.subgraph(cc)
457
+ yield from k_edge_subgraphs(C, k)
458
+
459
+
460
+ def _low_degree_nodes(G, k, nbunch=None):
461
+ """Helper for finding nodes with degree less than k."""
462
+ # Nodes with degree less than k cannot be k-edge-connected.
463
+ if G.is_directed():
464
+ # Consider both in and out degree in the directed case
465
+ seen = set()
466
+ for node, degree in G.out_degree(nbunch):
467
+ if degree < k:
468
+ seen.add(node)
469
+ yield node
470
+ for node, degree in G.in_degree(nbunch):
471
+ if node not in seen and degree < k:
472
+ seen.add(node)
473
+ yield node
474
+ else:
475
+ # Only the degree matters in the undirected case
476
+ for node, degree in G.degree(nbunch):
477
+ if degree < k:
478
+ yield node
479
+
480
+
481
+ def _high_degree_components(G, k):
482
+ """Helper for filtering components that can't be k-edge-connected.
483
+
484
+ Removes and generates each node with degree less than k. Then generates
485
+ remaining components where all nodes have degree at least k.
486
+ """
487
+ # Iteratively remove parts of the graph that are not k-edge-connected
488
+ H = G.copy()
489
+ singletons = set(_low_degree_nodes(H, k))
490
+ while singletons:
491
+ # Only search neighbors of removed nodes
492
+ nbunch = set(it.chain.from_iterable(map(H.neighbors, singletons)))
493
+ nbunch.difference_update(singletons)
494
+ H.remove_nodes_from(singletons)
495
+ for node in singletons:
496
+ yield {node}
497
+ singletons = set(_low_degree_nodes(H, k, nbunch))
498
+
499
+ # Note: remaining connected components may not be k-edge-connected
500
+ if G.is_directed():
501
+ yield from nx.strongly_connected_components(H)
502
+ else:
503
+ yield from nx.connected_components(H)
504
+
505
+
506
+ @nx._dispatchable(returns_graph=True)
507
+ def general_k_edge_subgraphs(G, k):
508
+ """General algorithm to find all maximal k-edge-connected subgraphs in `G`.
509
+
510
+ Parameters
511
+ ----------
512
+ G : nx.Graph
513
+ Graph in which all maximal k-edge-connected subgraphs will be found.
514
+
515
+ k : int
516
+
517
+ Yields
518
+ ------
519
+ k_edge_subgraphs : Graph instances that are k-edge-subgraphs
520
+ Each k-edge-subgraph contains a maximal set of nodes that defines a
521
+ subgraph of `G` that is k-edge-connected.
522
+
523
+ Notes
524
+ -----
525
+ Implementation of the basic algorithm from [1]_. The basic idea is to find
526
+ a global minimum cut of the graph. If the cut value is at least k, then the
527
+ graph is a k-edge-connected subgraph and can be added to the results.
528
+ Otherwise, the cut is used to split the graph in two and the procedure is
529
+ applied recursively. If the graph is just a single node, then it is also
530
+ added to the results. At the end, each result is either guaranteed to be
531
+ a single node or a subgraph of G that is k-edge-connected.
532
+
533
+ This implementation contains optimizations for reducing the number of calls
534
+ to max-flow, but there are other optimizations in [1]_ that could be
535
+ implemented.
536
+
537
+ References
538
+ ----------
539
+ .. [1] Zhou, Liu, et al. (2012) Finding maximal k-edge-connected subgraphs
540
+ from a large graph. ACM International Conference on Extending Database
541
+ Technology 2012 480-–491.
542
+ https://openproceedings.org/2012/conf/edbt/ZhouLYLCL12.pdf
543
+
544
+ Examples
545
+ --------
546
+ >>> from networkx.utils import pairwise
547
+ >>> paths = [
548
+ ... (11, 12, 13, 14, 11, 13, 14, 12), # a 4-clique
549
+ ... (21, 22, 23, 24, 21, 23, 24, 22), # another 4-clique
550
+ ... # connect the cliques with high degree but low connectivity
551
+ ... (50, 13),
552
+ ... (12, 50, 22),
553
+ ... (13, 102, 23),
554
+ ... (14, 101, 24),
555
+ ... ]
556
+ >>> G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
557
+ >>> sorted(len(k_sg) for k_sg in k_edge_subgraphs(G, k=3))
558
+ [1, 1, 1, 4, 4]
559
+ """
560
+ if k < 1:
561
+ raise ValueError("k cannot be less than 1")
562
+
563
+ # Node pruning optimization (incorporates early return)
564
+ # find_ccs is either connected_components/strongly_connected_components
565
+ find_ccs = partial(_high_degree_components, k=k)
566
+
567
+ # Quick return optimization
568
+ if G.number_of_nodes() < k:
569
+ for node in G.nodes():
570
+ yield G.subgraph([node]).copy()
571
+ return
572
+
573
+ # Intermediate results
574
+ R0 = {G.subgraph(cc).copy() for cc in find_ccs(G)}
575
+ # Subdivide CCs in the intermediate results until they are k-conn
576
+ while R0:
577
+ G1 = R0.pop()
578
+ if G1.number_of_nodes() == 1:
579
+ yield G1
580
+ else:
581
+ # Find a global minimum cut
582
+ cut_edges = nx.minimum_edge_cut(G1)
583
+ cut_value = len(cut_edges)
584
+ if cut_value < k:
585
+ # G1 is not k-edge-connected, so subdivide it
586
+ G1.remove_edges_from(cut_edges)
587
+ for cc in find_ccs(G1):
588
+ R0.add(G1.subgraph(cc).copy())
589
+ else:
590
+ # Otherwise we found a k-edge-connected subgraph
591
+ yield G1
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcomponents.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Moody and White algorithm for k-components
3
+ """
4
+ from collections import defaultdict
5
+ from itertools import combinations
6
+ from operator import itemgetter
7
+
8
+ import networkx as nx
9
+
10
+ # Define the default maximum flow function.
11
+ from networkx.algorithms.flow import edmonds_karp
12
+ from networkx.utils import not_implemented_for
13
+
14
+ default_flow_func = edmonds_karp
15
+
16
+ __all__ = ["k_components"]
17
+
18
+
19
+ @not_implemented_for("directed")
20
+ @nx._dispatchable
21
+ def k_components(G, flow_func=None):
22
+ r"""Returns the k-component structure of a graph G.
23
+
24
+ A `k`-component is a maximal subgraph of a graph G that has, at least,
25
+ node connectivity `k`: we need to remove at least `k` nodes to break it
26
+ into more components. `k`-components have an inherent hierarchical
27
+ structure because they are nested in terms of connectivity: a connected
28
+ graph can contain several 2-components, each of which can contain
29
+ one or more 3-components, and so forth.
30
+
31
+ Parameters
32
+ ----------
33
+ G : NetworkX graph
34
+
35
+ flow_func : function
36
+ Function to perform the underlying flow computations. Default value
37
+ :meth:`edmonds_karp`. This function performs better in sparse graphs with
38
+ right tailed degree distributions. :meth:`shortest_augmenting_path` will
39
+ perform better in denser graphs.
40
+
41
+ Returns
42
+ -------
43
+ k_components : dict
44
+ Dictionary with all connectivity levels `k` in the input Graph as keys
45
+ and a list of sets of nodes that form a k-component of level `k` as
46
+ values.
47
+
48
+ Raises
49
+ ------
50
+ NetworkXNotImplemented
51
+ If the input graph is directed.
52
+
53
+ Examples
54
+ --------
55
+ >>> # Petersen graph has 10 nodes and it is triconnected, thus all
56
+ >>> # nodes are in a single component on all three connectivity levels
57
+ >>> G = nx.petersen_graph()
58
+ >>> k_components = nx.k_components(G)
59
+
60
+ Notes
61
+ -----
62
+ Moody and White [1]_ (appendix A) provide an algorithm for identifying
63
+ k-components in a graph, which is based on Kanevsky's algorithm [2]_
64
+ for finding all minimum-size node cut-sets of a graph (implemented in
65
+ :meth:`all_node_cuts` function):
66
+
67
+ 1. Compute node connectivity, k, of the input graph G.
68
+
69
+ 2. Identify all k-cutsets at the current level of connectivity using
70
+ Kanevsky's algorithm.
71
+
72
+ 3. Generate new graph components based on the removal of
73
+ these cutsets. Nodes in a cutset belong to both sides
74
+ of the induced cut.
75
+
76
+ 4. If the graph is neither complete nor trivial, return to 1;
77
+ else end.
78
+
79
+ This implementation also uses some heuristics (see [3]_ for details)
80
+ to speed up the computation.
81
+
82
+ See also
83
+ --------
84
+ node_connectivity
85
+ all_node_cuts
86
+ biconnected_components : special case of this function when k=2
87
+ k_edge_components : similar to this function, but uses edge-connectivity
88
+ instead of node-connectivity
89
+
90
+ References
91
+ ----------
92
+ .. [1] Moody, J. and D. White (2003). Social cohesion and embeddedness:
93
+ A hierarchical conception of social groups.
94
+ American Sociological Review 68(1), 103--28.
95
+ http://www2.asanet.org/journals/ASRFeb03MoodyWhite.pdf
96
+
97
+ .. [2] Kanevsky, A. (1993). Finding all minimum-size separating vertex
98
+ sets in a graph. Networks 23(6), 533--541.
99
+ http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract
100
+
101
+ .. [3] Torrents, J. and F. Ferraro (2015). Structural Cohesion:
102
+ Visualization and Heuristics for Fast Computation.
103
+ https://arxiv.org/pdf/1503.04476v1
104
+
105
+ """
106
+ # Dictionary with connectivity level (k) as keys and a list of
107
+ # sets of nodes that form a k-component as values. Note that
108
+ # k-components can overlap (but only k - 1 nodes).
109
+ k_components = defaultdict(list)
110
+ # Define default flow function
111
+ if flow_func is None:
112
+ flow_func = default_flow_func
113
+ # Bicomponents as a base to check for higher order k-components
114
+ for component in nx.connected_components(G):
115
+ # isolated nodes have connectivity 0
116
+ comp = set(component)
117
+ if len(comp) > 1:
118
+ k_components[1].append(comp)
119
+ bicomponents = [G.subgraph(c) for c in nx.biconnected_components(G)]
120
+ for bicomponent in bicomponents:
121
+ bicomp = set(bicomponent)
122
+ # avoid considering dyads as bicomponents
123
+ if len(bicomp) > 2:
124
+ k_components[2].append(bicomp)
125
+ for B in bicomponents:
126
+ if len(B) <= 2:
127
+ continue
128
+ k = nx.node_connectivity(B, flow_func=flow_func)
129
+ if k > 2:
130
+ k_components[k].append(set(B))
131
+ # Perform cuts in a DFS like order.
132
+ cuts = list(nx.all_node_cuts(B, k=k, flow_func=flow_func))
133
+ stack = [(k, _generate_partition(B, cuts, k))]
134
+ while stack:
135
+ (parent_k, partition) = stack[-1]
136
+ try:
137
+ nodes = next(partition)
138
+ C = B.subgraph(nodes)
139
+ this_k = nx.node_connectivity(C, flow_func=flow_func)
140
+ if this_k > parent_k and this_k > 2:
141
+ k_components[this_k].append(set(C))
142
+ cuts = list(nx.all_node_cuts(C, k=this_k, flow_func=flow_func))
143
+ if cuts:
144
+ stack.append((this_k, _generate_partition(C, cuts, this_k)))
145
+ except StopIteration:
146
+ stack.pop()
147
+
148
+ # This is necessary because k-components may only be reported at their
149
+ # maximum k level. But we want to return a dictionary in which keys are
150
+ # connectivity levels and values list of sets of components, without
151
+ # skipping any connectivity level. Also, it's possible that subsets of
152
+ # an already detected k-component appear at a level k. Checking for this
153
+ # in the while loop above penalizes the common case. Thus we also have to
154
+ # _consolidate all connectivity levels in _reconstruct_k_components.
155
+ return _reconstruct_k_components(k_components)
156
+
157
+
158
+ def _consolidate(sets, k):
159
+ """Merge sets that share k or more elements.
160
+
161
+ See: http://rosettacode.org/wiki/Set_consolidation
162
+
163
+ The iterative python implementation posted there is
164
+ faster than this because of the overhead of building a
165
+ Graph and calling nx.connected_components, but it's not
166
+ clear for us if we can use it in NetworkX because there
167
+ is no licence for the code.
168
+
169
+ """
170
+ G = nx.Graph()
171
+ nodes = dict(enumerate(sets))
172
+ G.add_nodes_from(nodes)
173
+ G.add_edges_from(
174
+ (u, v) for u, v in combinations(nodes, 2) if len(nodes[u] & nodes[v]) >= k
175
+ )
176
+ for component in nx.connected_components(G):
177
+ yield set.union(*[nodes[n] for n in component])
178
+
179
+
180
+ def _generate_partition(G, cuts, k):
181
+ def has_nbrs_in_partition(G, node, partition):
182
+ return any(n in partition for n in G[node])
183
+
184
+ components = []
185
+ nodes = {n for n, d in G.degree() if d > k} - {n for cut in cuts for n in cut}
186
+ H = G.subgraph(nodes)
187
+ for cc in nx.connected_components(H):
188
+ component = set(cc)
189
+ for cut in cuts:
190
+ for node in cut:
191
+ if has_nbrs_in_partition(G, node, cc):
192
+ component.add(node)
193
+ if len(component) < G.order():
194
+ components.append(component)
195
+ yield from _consolidate(components, k + 1)
196
+
197
+
198
+ def _reconstruct_k_components(k_comps):
199
+ result = {}
200
+ max_k = max(k_comps)
201
+ for k in reversed(range(1, max_k + 1)):
202
+ if k == max_k:
203
+ result[k] = list(_consolidate(k_comps[k], k))
204
+ elif k not in k_comps:
205
+ result[k] = list(_consolidate(result[k + 1], k))
206
+ else:
207
+ nodes_at_k = set.union(*k_comps[k])
208
+ to_add = [c for c in result[k + 1] if any(n not in nodes_at_k for n in c)]
209
+ if to_add:
210
+ result[k] = list(_consolidate(k_comps[k] + to_add, k))
211
+ else:
212
+ result[k] = list(_consolidate(k_comps[k], k))
213
+ return result
214
+
215
+
216
+ def build_k_number_dict(kcomps):
217
+ result = {}
218
+ for k, comps in sorted(kcomps.items(), key=itemgetter(0)):
219
+ for comp in comps:
220
+ for node in comp:
221
+ result[node] = k
222
+ return result
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcutsets.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kanevsky all minimum node k cutsets algorithm.
3
+ """
4
+ import copy
5
+ from collections import defaultdict
6
+ from itertools import combinations
7
+ from operator import itemgetter
8
+
9
+ import networkx as nx
10
+ from networkx.algorithms.flow import (
11
+ build_residual_network,
12
+ edmonds_karp,
13
+ shortest_augmenting_path,
14
+ )
15
+
16
+ from .utils import build_auxiliary_node_connectivity
17
+
18
+ default_flow_func = edmonds_karp
19
+
20
+
21
+ __all__ = ["all_node_cuts"]
22
+
23
+
24
+ @nx._dispatchable
25
+ def all_node_cuts(G, k=None, flow_func=None):
26
+ r"""Returns all minimum k cutsets of an undirected graph G.
27
+
28
+ This implementation is based on Kanevsky's algorithm [1]_ for finding all
29
+ minimum-size node cut-sets of an undirected graph G; ie the set (or sets)
30
+ of nodes of cardinality equal to the node connectivity of G. Thus if
31
+ removed, would break G into two or more connected components.
32
+
33
+ Parameters
34
+ ----------
35
+ G : NetworkX graph
36
+ Undirected graph
37
+
38
+ k : Integer
39
+ Node connectivity of the input graph. If k is None, then it is
40
+ computed. Default value: None.
41
+
42
+ flow_func : function
43
+ Function to perform the underlying flow computations. Default value is
44
+ :func:`~networkx.algorithms.flow.edmonds_karp`. This function performs
45
+ better in sparse graphs with right tailed degree distributions.
46
+ :func:`~networkx.algorithms.flow.shortest_augmenting_path` will
47
+ perform better in denser graphs.
48
+
49
+
50
+ Returns
51
+ -------
52
+ cuts : a generator of node cutsets
53
+ Each node cutset has cardinality equal to the node connectivity of
54
+ the input graph.
55
+
56
+ Examples
57
+ --------
58
+ >>> # A two-dimensional grid graph has 4 cutsets of cardinality 2
59
+ >>> G = nx.grid_2d_graph(5, 5)
60
+ >>> cutsets = list(nx.all_node_cuts(G))
61
+ >>> len(cutsets)
62
+ 4
63
+ >>> all(2 == len(cutset) for cutset in cutsets)
64
+ True
65
+ >>> nx.node_connectivity(G)
66
+ 2
67
+
68
+ Notes
69
+ -----
70
+ This implementation is based on the sequential algorithm for finding all
71
+ minimum-size separating vertex sets in a graph [1]_. The main idea is to
72
+ compute minimum cuts using local maximum flow computations among a set
73
+ of nodes of highest degree and all other non-adjacent nodes in the Graph.
74
+ Once we find a minimum cut, we add an edge between the high degree
75
+ node and the target node of the local maximum flow computation to make
76
+ sure that we will not find that minimum cut again.
77
+
78
+ See also
79
+ --------
80
+ node_connectivity
81
+ edmonds_karp
82
+ shortest_augmenting_path
83
+
84
+ References
85
+ ----------
86
+ .. [1] Kanevsky, A. (1993). Finding all minimum-size separating vertex
87
+ sets in a graph. Networks 23(6), 533--541.
88
+ http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract
89
+
90
+ """
91
+ if not nx.is_connected(G):
92
+ raise nx.NetworkXError("Input graph is disconnected.")
93
+
94
+ # Address some corner cases first.
95
+ # For complete Graphs
96
+
97
+ if nx.density(G) == 1:
98
+ yield from ()
99
+ return
100
+
101
+ # Initialize data structures.
102
+ # Keep track of the cuts already computed so we do not repeat them.
103
+ seen = []
104
+ # Even-Tarjan reduction is what we call auxiliary digraph
105
+ # for node connectivity.
106
+ H = build_auxiliary_node_connectivity(G)
107
+ H_nodes = H.nodes # for speed
108
+ mapping = H.graph["mapping"]
109
+ # Keep a copy of original predecessors, H will be modified later.
110
+ # Shallow copy is enough.
111
+ original_H_pred = copy.copy(H._pred)
112
+ R = build_residual_network(H, "capacity")
113
+ kwargs = {"capacity": "capacity", "residual": R}
114
+ # Define default flow function
115
+ if flow_func is None:
116
+ flow_func = default_flow_func
117
+ if flow_func is shortest_augmenting_path:
118
+ kwargs["two_phase"] = True
119
+ # Begin the actual algorithm
120
+ # step 1: Find node connectivity k of G
121
+ if k is None:
122
+ k = nx.node_connectivity(G, flow_func=flow_func)
123
+ # step 2:
124
+ # Find k nodes with top degree, call it X:
125
+ X = {n for n, d in sorted(G.degree(), key=itemgetter(1), reverse=True)[:k]}
126
+ # Check if X is a k-node-cutset
127
+ if _is_separating_set(G, X):
128
+ seen.append(X)
129
+ yield X
130
+
131
+ for x in X:
132
+ # step 3: Compute local connectivity flow of x with all other
133
+ # non adjacent nodes in G
134
+ non_adjacent = set(G) - {x} - set(G[x])
135
+ for v in non_adjacent:
136
+ # step 4: compute maximum flow in an Even-Tarjan reduction H of G
137
+ # and step 5: build the associated residual network R
138
+ R = flow_func(H, f"{mapping[x]}B", f"{mapping[v]}A", **kwargs)
139
+ flow_value = R.graph["flow_value"]
140
+
141
+ if flow_value == k:
142
+ # Find the nodes incident to the flow.
143
+ E1 = flowed_edges = [
144
+ (u, w) for (u, w, d) in R.edges(data=True) if d["flow"] != 0
145
+ ]
146
+ VE1 = incident_nodes = {n for edge in E1 for n in edge}
147
+ # Remove saturated edges form the residual network.
148
+ # Note that reversed edges are introduced with capacity 0
149
+ # in the residual graph and they need to be removed too.
150
+ saturated_edges = [
151
+ (u, w, d)
152
+ for (u, w, d) in R.edges(data=True)
153
+ if d["capacity"] == d["flow"] or d["capacity"] == 0
154
+ ]
155
+ R.remove_edges_from(saturated_edges)
156
+ R_closure = nx.transitive_closure(R)
157
+ # step 6: shrink the strongly connected components of
158
+ # residual flow network R and call it L.
159
+ L = nx.condensation(R)
160
+ cmap = L.graph["mapping"]
161
+ inv_cmap = defaultdict(list)
162
+ for n, scc in cmap.items():
163
+ inv_cmap[scc].append(n)
164
+ # Find the incident nodes in the condensed graph.
165
+ VE1 = {cmap[n] for n in VE1}
166
+ # step 7: Compute all antichains of L;
167
+ # they map to closed sets in H.
168
+ # Any edge in H that links a closed set is part of a cutset.
169
+ for antichain in nx.antichains(L):
170
+ # Only antichains that are subsets of incident nodes counts.
171
+ # Lemma 8 in reference.
172
+ if not set(antichain).issubset(VE1):
173
+ continue
174
+ # Nodes in an antichain of the condensation graph of
175
+ # the residual network map to a closed set of nodes that
176
+ # define a node partition of the auxiliary digraph H
177
+ # through taking all of antichain's predecessors in the
178
+ # transitive closure.
179
+ S = set()
180
+ for scc in antichain:
181
+ S.update(inv_cmap[scc])
182
+ S_ancestors = set()
183
+ for n in S:
184
+ S_ancestors.update(R_closure._pred[n])
185
+ S.update(S_ancestors)
186
+ if f"{mapping[x]}B" not in S or f"{mapping[v]}A" in S:
187
+ continue
188
+ # Find the cutset that links the node partition (S,~S) in H
189
+ cutset = set()
190
+ for u in S:
191
+ cutset.update((u, w) for w in original_H_pred[u] if w not in S)
192
+ # The edges in H that form the cutset are internal edges
193
+ # (ie edges that represent a node of the original graph G)
194
+ if any(H_nodes[u]["id"] != H_nodes[w]["id"] for u, w in cutset):
195
+ continue
196
+ node_cut = {H_nodes[u]["id"] for u, _ in cutset}
197
+
198
+ if len(node_cut) == k:
199
+ # The cut is invalid if it includes internal edges of
200
+ # end nodes. The other half of Lemma 8 in ref.
201
+ if x in node_cut or v in node_cut:
202
+ continue
203
+ if node_cut not in seen:
204
+ yield node_cut
205
+ seen.append(node_cut)
206
+
207
+ # Add an edge (x, v) to make sure that we do not
208
+ # find this cutset again. This is equivalent
209
+ # of adding the edge in the input graph
210
+ # G.add_edge(x, v) and then regenerate H and R:
211
+ # Add edges to the auxiliary digraph.
212
+ # See build_residual_network for convention we used
213
+ # in residual graphs.
214
+ H.add_edge(f"{mapping[x]}B", f"{mapping[v]}A", capacity=1)
215
+ H.add_edge(f"{mapping[v]}B", f"{mapping[x]}A", capacity=1)
216
+ # Add edges to the residual network.
217
+ R.add_edge(f"{mapping[x]}B", f"{mapping[v]}A", capacity=1)
218
+ R.add_edge(f"{mapping[v]}A", f"{mapping[x]}B", capacity=0)
219
+ R.add_edge(f"{mapping[v]}B", f"{mapping[x]}A", capacity=1)
220
+ R.add_edge(f"{mapping[x]}A", f"{mapping[v]}B", capacity=0)
221
+
222
+ # Add again the saturated edges to reuse the residual network
223
+ R.add_edges_from(saturated_edges)
224
+
225
+
226
+ def _is_separating_set(G, cut):
227
+ """Assumes that the input graph is connected"""
228
+ if len(cut) == len(G) - 1:
229
+ return True
230
+
231
+ H = nx.restricted_view(G, cut, [])
232
+ if nx.is_connected(H):
233
+ return False
234
+ return True
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/stoerwagner.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stoer-Wagner minimum cut algorithm.
3
+ """
4
+ from itertools import islice
5
+
6
+ import networkx as nx
7
+
8
+ from ...utils import BinaryHeap, arbitrary_element, not_implemented_for
9
+
10
+ __all__ = ["stoer_wagner"]
11
+
12
+
13
+ @not_implemented_for("directed")
14
+ @not_implemented_for("multigraph")
15
+ @nx._dispatchable(edge_attrs="weight")
16
+ def stoer_wagner(G, weight="weight", heap=BinaryHeap):
17
+ r"""Returns the weighted minimum edge cut using the Stoer-Wagner algorithm.
18
+
19
+ Determine the minimum edge cut of a connected graph using the
20
+ Stoer-Wagner algorithm. In weighted cases, all weights must be
21
+ nonnegative.
22
+
23
+ The running time of the algorithm depends on the type of heaps used:
24
+
25
+ ============== =============================================
26
+ Type of heap Running time
27
+ ============== =============================================
28
+ Binary heap $O(n (m + n) \log n)$
29
+ Fibonacci heap $O(nm + n^2 \log n)$
30
+ Pairing heap $O(2^{2 \sqrt{\log \log n}} nm + n^2 \log n)$
31
+ ============== =============================================
32
+
33
+ Parameters
34
+ ----------
35
+ G : NetworkX graph
36
+ Edges of the graph are expected to have an attribute named by the
37
+ weight parameter below. If this attribute is not present, the edge is
38
+ considered to have unit weight.
39
+
40
+ weight : string
41
+ Name of the weight attribute of the edges. If the attribute is not
42
+ present, unit weight is assumed. Default value: 'weight'.
43
+
44
+ heap : class
45
+ Type of heap to be used in the algorithm. It should be a subclass of
46
+ :class:`MinHeap` or implement a compatible interface.
47
+
48
+ If a stock heap implementation is to be used, :class:`BinaryHeap` is
49
+ recommended over :class:`PairingHeap` for Python implementations without
50
+ optimized attribute accesses (e.g., CPython) despite a slower
51
+ asymptotic running time. For Python implementations with optimized
52
+ attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better
53
+ performance. Default value: :class:`BinaryHeap`.
54
+
55
+ Returns
56
+ -------
57
+ cut_value : integer or float
58
+ The sum of weights of edges in a minimum cut.
59
+
60
+ partition : pair of node lists
61
+ A partitioning of the nodes that defines a minimum cut.
62
+
63
+ Raises
64
+ ------
65
+ NetworkXNotImplemented
66
+ If the graph is directed or a multigraph.
67
+
68
+ NetworkXError
69
+ If the graph has less than two nodes, is not connected or has a
70
+ negative-weighted edge.
71
+
72
+ Examples
73
+ --------
74
+ >>> G = nx.Graph()
75
+ >>> G.add_edge("x", "a", weight=3)
76
+ >>> G.add_edge("x", "b", weight=1)
77
+ >>> G.add_edge("a", "c", weight=3)
78
+ >>> G.add_edge("b", "c", weight=5)
79
+ >>> G.add_edge("b", "d", weight=4)
80
+ >>> G.add_edge("d", "e", weight=2)
81
+ >>> G.add_edge("c", "y", weight=2)
82
+ >>> G.add_edge("e", "y", weight=3)
83
+ >>> cut_value, partition = nx.stoer_wagner(G)
84
+ >>> cut_value
85
+ 4
86
+ """
87
+ n = len(G)
88
+ if n < 2:
89
+ raise nx.NetworkXError("graph has less than two nodes.")
90
+ if not nx.is_connected(G):
91
+ raise nx.NetworkXError("graph is not connected.")
92
+
93
+ # Make a copy of the graph for internal use.
94
+ G = nx.Graph(
95
+ (u, v, {"weight": e.get(weight, 1)}) for u, v, e in G.edges(data=True) if u != v
96
+ )
97
+ G.__networkx_cache__ = None # Disable caching
98
+
99
+ for u, v, e in G.edges(data=True):
100
+ if e["weight"] < 0:
101
+ raise nx.NetworkXError("graph has a negative-weighted edge.")
102
+
103
+ cut_value = float("inf")
104
+ nodes = set(G)
105
+ contractions = [] # contracted node pairs
106
+
107
+ # Repeatedly pick a pair of nodes to contract until only one node is left.
108
+ for i in range(n - 1):
109
+ # Pick an arbitrary node u and create a set A = {u}.
110
+ u = arbitrary_element(G)
111
+ A = {u}
112
+ # Repeatedly pick the node "most tightly connected" to A and add it to
113
+ # A. The tightness of connectivity of a node not in A is defined by the
114
+ # of edges connecting it to nodes in A.
115
+ h = heap() # min-heap emulating a max-heap
116
+ for v, e in G[u].items():
117
+ h.insert(v, -e["weight"])
118
+ # Repeat until all but one node has been added to A.
119
+ for j in range(n - i - 2):
120
+ u = h.pop()[0]
121
+ A.add(u)
122
+ for v, e in G[u].items():
123
+ if v not in A:
124
+ h.insert(v, h.get(v, 0) - e["weight"])
125
+ # A and the remaining node v define a "cut of the phase". There is a
126
+ # minimum cut of the original graph that is also a cut of the phase.
127
+ # Due to contractions in earlier phases, v may in fact represent
128
+ # multiple nodes in the original graph.
129
+ v, w = h.min()
130
+ w = -w
131
+ if w < cut_value:
132
+ cut_value = w
133
+ best_phase = i
134
+ # Contract v and the last node added to A.
135
+ contractions.append((u, v))
136
+ for w, e in G[v].items():
137
+ if w != u:
138
+ if w not in G[u]:
139
+ G.add_edge(u, w, weight=e["weight"])
140
+ else:
141
+ G[u][w]["weight"] += e["weight"]
142
+ G.remove_node(v)
143
+
144
+ # Recover the optimal partitioning from the contractions.
145
+ G = nx.Graph(islice(contractions, best_phase))
146
+ v = contractions[best_phase][1]
147
+ G.add_node(v)
148
+ reachable = set(nx.single_source_shortest_path_length(G, v))
149
+ partition = (list(reachable), list(nodes - reachable))
150
+
151
+ return cut_value, partition
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/connectivity/tests/__init__.py ADDED
File without changes