ZTWHHH commited on
Commit
da3cce8
·
verified ·
1 Parent(s): 7379169

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. janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/threshold.cpython-310.pyc +0 -0
  2. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__init__.py +11 -0
  3. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/boykovkolmogorov.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/capacityscaling.cpython-310.pyc +0 -0
  5. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/edmondskarp.cpython-310.pyc +0 -0
  6. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/mincost.cpython-310.pyc +0 -0
  7. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/networksimplex.cpython-310.pyc +0 -0
  8. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/preflowpush.cpython-310.pyc +0 -0
  9. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/shortestaugmentingpath.cpython-310.pyc +0 -0
  10. janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/utils.cpython-310.pyc +0 -0
  11. janus/lib/python3.10/site-packages/networkx/algorithms/flow/boykovkolmogorov.py +370 -0
  12. janus/lib/python3.10/site-packages/networkx/algorithms/flow/capacityscaling.py +407 -0
  13. janus/lib/python3.10/site-packages/networkx/algorithms/flow/dinitz_alg.py +238 -0
  14. janus/lib/python3.10/site-packages/networkx/algorithms/flow/edmondskarp.py +241 -0
  15. janus/lib/python3.10/site-packages/networkx/algorithms/flow/gomory_hu.py +178 -0
  16. janus/lib/python3.10/site-packages/networkx/algorithms/flow/maxflow.py +607 -0
  17. janus/lib/python3.10/site-packages/networkx/algorithms/flow/mincost.py +356 -0
  18. janus/lib/python3.10/site-packages/networkx/algorithms/flow/networksimplex.py +666 -0
  19. janus/lib/python3.10/site-packages/networkx/algorithms/flow/preflowpush.py +425 -0
  20. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__init__.py +0 -0
  21. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  22. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_maxflow.cpython-310.pyc +0 -0
  23. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_mincost.cpython-310.pyc +0 -0
  24. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_networksimplex.cpython-310.pyc +0 -0
  25. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_gomory_hu.py +128 -0
  26. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_maxflow.py +573 -0
  27. janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_networksimplex.py +387 -0
  28. janus/lib/python3.10/site-packages/networkx/algorithms/flow/utils.py +189 -0
  29. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  30. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_boundary.cpython-310.pyc +0 -0
  31. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_broadcasting.cpython-310.pyc +0 -0
  32. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_clique.cpython-310.pyc +0 -0
  33. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_communicability.cpython-310.pyc +0 -0
  34. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cuts.cpython-310.pyc +0 -0
  35. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_d_separation.cpython-310.pyc +0 -0
  36. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dag.cpython-310.pyc +0 -0
  37. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_distance_measures.cpython-310.pyc +0 -0
  38. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_graph_hashing.cpython-310.pyc +0 -0
  39. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_hybrid.cpython-310.pyc +0 -0
  40. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_non_randomness.cpython-310.pyc +0 -0
  41. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_smetric.cpython-310.pyc +0 -0
  42. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_swap.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_time_dependent.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_tournament.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/__init__.cpython-310.pyc +0 -0
  46. janus/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/edgedfs.cpython-310.pyc +0 -0
  47. janus/lib/python3.10/site-packages/networkx/algorithms/traversal/beamsearch.py +90 -0
  48. janus/lib/python3.10/site-packages/networkx/algorithms/traversal/breadth_first_search.py +575 -0
  49. janus/lib/python3.10/site-packages/networkx/algorithms/traversal/depth_first_search.py +529 -0
  50. janus/lib/python3.10/site-packages/networkx/algorithms/traversal/edgebfs.py +178 -0
janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/threshold.cpython-310.pyc ADDED
Binary file (24.7 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .maxflow import *
2
+ from .mincost import *
3
+ from .boykovkolmogorov import *
4
+ from .dinitz_alg import *
5
+ from .edmondskarp import *
6
+ from .gomory_hu import *
7
+ from .preflowpush import *
8
+ from .shortestaugmentingpath import *
9
+ from .capacityscaling import *
10
+ from .networksimplex import *
11
+ from .utils import build_flow_dict, build_residual_network
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/boykovkolmogorov.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/capacityscaling.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/edmondskarp.cpython-310.pyc ADDED
Binary file (7.16 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/mincost.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/networksimplex.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/preflowpush.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/shortestaugmentingpath.cpython-310.pyc ADDED
Binary file (7.99 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/utils.cpython-310.pyc ADDED
Binary file (6.39 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/boykovkolmogorov.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Boykov-Kolmogorov algorithm for maximum flow problems.
3
+ """
4
+
5
+ from collections import deque
6
+ from operator import itemgetter
7
+
8
+ import networkx as nx
9
+ from networkx.algorithms.flow.utils import build_residual_network
10
+
11
+ __all__ = ["boykov_kolmogorov"]
12
+
13
+
14
+ @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
15
+ def boykov_kolmogorov(
16
+ G, s, t, capacity="capacity", residual=None, value_only=False, cutoff=None
17
+ ):
18
+ r"""Find a maximum single-commodity flow using Boykov-Kolmogorov algorithm.
19
+
20
+ This function returns the residual network resulting after computing
21
+ the maximum flow. See below for details about the conventions
22
+ NetworkX uses for defining residual networks.
23
+
24
+ This algorithm has worse case complexity $O(n^2 m |C|)$ for $n$ nodes, $m$
25
+ edges, and $|C|$ the cost of the minimum cut [1]_. This implementation
26
+ uses the marking heuristic defined in [2]_ which improves its running
27
+ time in many practical problems.
28
+
29
+ Parameters
30
+ ----------
31
+ G : NetworkX graph
32
+ Edges of the graph are expected to have an attribute called
33
+ 'capacity'. If this attribute is not present, the edge is
34
+ considered to have infinite capacity.
35
+
36
+ s : node
37
+ Source node for the flow.
38
+
39
+ t : node
40
+ Sink node for the flow.
41
+
42
+ capacity : string
43
+ Edges of the graph G are expected to have an attribute capacity
44
+ that indicates how much flow the edge can support. If this
45
+ attribute is not present, the edge is considered to have
46
+ infinite capacity. Default value: 'capacity'.
47
+
48
+ residual : NetworkX graph
49
+ Residual network on which the algorithm is to be executed. If None, a
50
+ new residual network is created. Default value: None.
51
+
52
+ value_only : bool
53
+ If True compute only the value of the maximum flow. This parameter
54
+ will be ignored by this algorithm because it is not applicable.
55
+
56
+ cutoff : integer, float
57
+ If specified, the algorithm will terminate when the flow value reaches
58
+ or exceeds the cutoff. In this case, it may be unable to immediately
59
+ determine a minimum cut. Default value: None.
60
+
61
+ Returns
62
+ -------
63
+ R : NetworkX DiGraph
64
+ Residual network after computing the maximum flow.
65
+
66
+ Raises
67
+ ------
68
+ NetworkXError
69
+ The algorithm does not support MultiGraph and MultiDiGraph. If
70
+ the input graph is an instance of one of these two classes, a
71
+ NetworkXError is raised.
72
+
73
+ NetworkXUnbounded
74
+ If the graph has a path of infinite capacity, the value of a
75
+ feasible flow on the graph is unbounded above and the function
76
+ raises a NetworkXUnbounded.
77
+
78
+ See also
79
+ --------
80
+ :meth:`maximum_flow`
81
+ :meth:`minimum_cut`
82
+ :meth:`preflow_push`
83
+ :meth:`shortest_augmenting_path`
84
+
85
+ Notes
86
+ -----
87
+ The residual network :samp:`R` from an input graph :samp:`G` has the
88
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
89
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
90
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
91
+ in :samp:`G`.
92
+
93
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
94
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
95
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
96
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
97
+ that does not affect the solution of the problem. This value is stored in
98
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
99
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
100
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
101
+
102
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
103
+ stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
104
+ specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
105
+ that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
106
+ :samp:`s`-:samp:`t` cut.
107
+
108
+ Examples
109
+ --------
110
+ >>> from networkx.algorithms.flow import boykov_kolmogorov
111
+
112
+ The functions that implement flow algorithms and output a residual
113
+ network, such as this one, are not imported to the base NetworkX
114
+ namespace, so you have to explicitly import them from the flow package.
115
+
116
+ >>> G = nx.DiGraph()
117
+ >>> G.add_edge("x", "a", capacity=3.0)
118
+ >>> G.add_edge("x", "b", capacity=1.0)
119
+ >>> G.add_edge("a", "c", capacity=3.0)
120
+ >>> G.add_edge("b", "c", capacity=5.0)
121
+ >>> G.add_edge("b", "d", capacity=4.0)
122
+ >>> G.add_edge("d", "e", capacity=2.0)
123
+ >>> G.add_edge("c", "y", capacity=2.0)
124
+ >>> G.add_edge("e", "y", capacity=3.0)
125
+ >>> R = boykov_kolmogorov(G, "x", "y")
126
+ >>> flow_value = nx.maximum_flow_value(G, "x", "y")
127
+ >>> flow_value
128
+ 3.0
129
+ >>> flow_value == R.graph["flow_value"]
130
+ True
131
+
132
+ A nice feature of the Boykov-Kolmogorov algorithm is that a partition
133
+ of the nodes that defines a minimum cut can be easily computed based
134
+ on the search trees used during the algorithm. These trees are stored
135
+ in the graph attribute `trees` of the residual network.
136
+
137
+ >>> source_tree, target_tree = R.graph["trees"]
138
+ >>> partition = (set(source_tree), set(G) - set(source_tree))
139
+
140
+ Or equivalently:
141
+
142
+ >>> partition = (set(G) - set(target_tree), set(target_tree))
143
+
144
+ References
145
+ ----------
146
+ .. [1] Boykov, Y., & Kolmogorov, V. (2004). An experimental comparison
147
+ of min-cut/max-flow algorithms for energy minimization in vision.
148
+ Pattern Analysis and Machine Intelligence, IEEE Transactions on,
149
+ 26(9), 1124-1137.
150
+ https://doi.org/10.1109/TPAMI.2004.60
151
+
152
+ .. [2] Vladimir Kolmogorov. Graph-based Algorithms for Multi-camera
153
+ Reconstruction Problem. PhD thesis, Cornell University, CS Department,
154
+ 2003. pp. 109-114.
155
+ https://web.archive.org/web/20170809091249/https://pub.ist.ac.at/~vnk/papers/thesis.pdf
156
+
157
+ """
158
+ R = boykov_kolmogorov_impl(G, s, t, capacity, residual, cutoff)
159
+ R.graph["algorithm"] = "boykov_kolmogorov"
160
+ nx._clear_cache(R)
161
+ return R
162
+
163
+
164
+ def boykov_kolmogorov_impl(G, s, t, capacity, residual, cutoff):
165
+ if s not in G:
166
+ raise nx.NetworkXError(f"node {str(s)} not in graph")
167
+ if t not in G:
168
+ raise nx.NetworkXError(f"node {str(t)} not in graph")
169
+ if s == t:
170
+ raise nx.NetworkXError("source and sink are the same node")
171
+
172
+ if residual is None:
173
+ R = build_residual_network(G, capacity)
174
+ else:
175
+ R = residual
176
+
177
+ # Initialize/reset the residual network.
178
+ # This is way too slow
179
+ # nx.set_edge_attributes(R, 0, 'flow')
180
+ for u in R:
181
+ for e in R[u].values():
182
+ e["flow"] = 0
183
+
184
+ # Use an arbitrary high value as infinite. It is computed
185
+ # when building the residual network.
186
+ INF = R.graph["inf"]
187
+
188
+ if cutoff is None:
189
+ cutoff = INF
190
+
191
+ R_succ = R.succ
192
+ R_pred = R.pred
193
+
194
+ def grow():
195
+ """Bidirectional breadth-first search for the growth stage.
196
+
197
+ Returns a connecting edge, that is and edge that connects
198
+ a node from the source search tree with a node from the
199
+ target search tree.
200
+ The first node in the connecting edge is always from the
201
+ source tree and the last node from the target tree.
202
+ """
203
+ while active:
204
+ u = active[0]
205
+ if u in source_tree:
206
+ this_tree = source_tree
207
+ other_tree = target_tree
208
+ neighbors = R_succ
209
+ else:
210
+ this_tree = target_tree
211
+ other_tree = source_tree
212
+ neighbors = R_pred
213
+ for v, attr in neighbors[u].items():
214
+ if attr["capacity"] - attr["flow"] > 0:
215
+ if v not in this_tree:
216
+ if v in other_tree:
217
+ return (u, v) if this_tree is source_tree else (v, u)
218
+ this_tree[v] = u
219
+ dist[v] = dist[u] + 1
220
+ timestamp[v] = timestamp[u]
221
+ active.append(v)
222
+ elif v in this_tree and _is_closer(u, v):
223
+ this_tree[v] = u
224
+ dist[v] = dist[u] + 1
225
+ timestamp[v] = timestamp[u]
226
+ _ = active.popleft()
227
+ return None, None
228
+
229
+ def augment(u, v):
230
+ """Augmentation stage.
231
+
232
+ Reconstruct path and determine its residual capacity.
233
+ We start from a connecting edge, which links a node
234
+ from the source tree to a node from the target tree.
235
+ The connecting edge is the output of the grow function
236
+ and the input of this function.
237
+ """
238
+ attr = R_succ[u][v]
239
+ flow = min(INF, attr["capacity"] - attr["flow"])
240
+ path = [u]
241
+ # Trace a path from u to s in source_tree.
242
+ w = u
243
+ while w != s:
244
+ n = w
245
+ w = source_tree[n]
246
+ attr = R_pred[n][w]
247
+ flow = min(flow, attr["capacity"] - attr["flow"])
248
+ path.append(w)
249
+ path.reverse()
250
+ # Trace a path from v to t in target_tree.
251
+ path.append(v)
252
+ w = v
253
+ while w != t:
254
+ n = w
255
+ w = target_tree[n]
256
+ attr = R_succ[n][w]
257
+ flow = min(flow, attr["capacity"] - attr["flow"])
258
+ path.append(w)
259
+ # Augment flow along the path and check for saturated edges.
260
+ it = iter(path)
261
+ u = next(it)
262
+ these_orphans = []
263
+ for v in it:
264
+ R_succ[u][v]["flow"] += flow
265
+ R_succ[v][u]["flow"] -= flow
266
+ if R_succ[u][v]["flow"] == R_succ[u][v]["capacity"]:
267
+ if v in source_tree:
268
+ source_tree[v] = None
269
+ these_orphans.append(v)
270
+ if u in target_tree:
271
+ target_tree[u] = None
272
+ these_orphans.append(u)
273
+ u = v
274
+ orphans.extend(sorted(these_orphans, key=dist.get))
275
+ return flow
276
+
277
+ def adopt():
278
+ """Adoption stage.
279
+
280
+ Reconstruct search trees by adopting or discarding orphans.
281
+ During augmentation stage some edges got saturated and thus
282
+ the source and target search trees broke down to forests, with
283
+ orphans as roots of some of its trees. We have to reconstruct
284
+ the search trees rooted to source and target before we can grow
285
+ them again.
286
+ """
287
+ while orphans:
288
+ u = orphans.popleft()
289
+ if u in source_tree:
290
+ tree = source_tree
291
+ neighbors = R_pred
292
+ else:
293
+ tree = target_tree
294
+ neighbors = R_succ
295
+ nbrs = ((n, attr, dist[n]) for n, attr in neighbors[u].items() if n in tree)
296
+ for v, attr, d in sorted(nbrs, key=itemgetter(2)):
297
+ if attr["capacity"] - attr["flow"] > 0:
298
+ if _has_valid_root(v, tree):
299
+ tree[u] = v
300
+ dist[u] = dist[v] + 1
301
+ timestamp[u] = time
302
+ break
303
+ else:
304
+ nbrs = (
305
+ (n, attr, dist[n]) for n, attr in neighbors[u].items() if n in tree
306
+ )
307
+ for v, attr, d in sorted(nbrs, key=itemgetter(2)):
308
+ if attr["capacity"] - attr["flow"] > 0:
309
+ if v not in active:
310
+ active.append(v)
311
+ if tree[v] == u:
312
+ tree[v] = None
313
+ orphans.appendleft(v)
314
+ if u in active:
315
+ active.remove(u)
316
+ del tree[u]
317
+
318
+ def _has_valid_root(n, tree):
319
+ path = []
320
+ v = n
321
+ while v is not None:
322
+ path.append(v)
323
+ if v in (s, t):
324
+ base_dist = 0
325
+ break
326
+ elif timestamp[v] == time:
327
+ base_dist = dist[v]
328
+ break
329
+ v = tree[v]
330
+ else:
331
+ return False
332
+ length = len(path)
333
+ for i, u in enumerate(path, 1):
334
+ dist[u] = base_dist + length - i
335
+ timestamp[u] = time
336
+ return True
337
+
338
+ def _is_closer(u, v):
339
+ return timestamp[v] <= timestamp[u] and dist[v] > dist[u] + 1
340
+
341
+ source_tree = {s: None}
342
+ target_tree = {t: None}
343
+ active = deque([s, t])
344
+ orphans = deque()
345
+ flow_value = 0
346
+ # data structures for the marking heuristic
347
+ time = 1
348
+ timestamp = {s: time, t: time}
349
+ dist = {s: 0, t: 0}
350
+ while flow_value < cutoff:
351
+ # Growth stage
352
+ u, v = grow()
353
+ if u is None:
354
+ break
355
+ time += 1
356
+ # Augmentation stage
357
+ flow_value += augment(u, v)
358
+ # Adoption stage
359
+ adopt()
360
+
361
+ if flow_value * 2 > INF:
362
+ raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
363
+
364
+ # Add source and target tree in a graph attribute.
365
+ # A partition that defines a minimum cut can be directly
366
+ # computed from the search trees as explained in the docstrings.
367
+ R.graph["trees"] = (source_tree, target_tree)
368
+ # Add the standard flow_value graph attribute.
369
+ R.graph["flow_value"] = flow_value
370
+ return R
janus/lib/python3.10/site-packages/networkx/algorithms/flow/capacityscaling.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Capacity scaling minimum cost flow algorithm.
3
+ """
4
+
5
+ __all__ = ["capacity_scaling"]
6
+
7
+ from itertools import chain
8
+ from math import log
9
+
10
+ import networkx as nx
11
+
12
+ from ...utils import BinaryHeap, arbitrary_element, not_implemented_for
13
+
14
+
15
+ def _detect_unboundedness(R):
16
+ """Detect infinite-capacity negative cycles."""
17
+ G = nx.DiGraph()
18
+ G.add_nodes_from(R)
19
+
20
+ # Value simulating infinity.
21
+ inf = R.graph["inf"]
22
+ # True infinity.
23
+ f_inf = float("inf")
24
+ for u in R:
25
+ for v, e in R[u].items():
26
+ # Compute the minimum weight of infinite-capacity (u, v) edges.
27
+ w = f_inf
28
+ for k, e in e.items():
29
+ if e["capacity"] == inf:
30
+ w = min(w, e["weight"])
31
+ if w != f_inf:
32
+ G.add_edge(u, v, weight=w)
33
+
34
+ if nx.negative_edge_cycle(G):
35
+ raise nx.NetworkXUnbounded(
36
+ "Negative cost cycle of infinite capacity found. "
37
+ "Min cost flow may be unbounded below."
38
+ )
39
+
40
+
41
+ @not_implemented_for("undirected")
42
+ def _build_residual_network(G, demand, capacity, weight):
43
+ """Build a residual network and initialize a zero flow."""
44
+ if sum(G.nodes[u].get(demand, 0) for u in G) != 0:
45
+ raise nx.NetworkXUnfeasible("Sum of the demands should be 0.")
46
+
47
+ R = nx.MultiDiGraph()
48
+ R.add_nodes_from(
49
+ (u, {"excess": -G.nodes[u].get(demand, 0), "potential": 0}) for u in G
50
+ )
51
+
52
+ inf = float("inf")
53
+ # Detect selfloops with infinite capacities and negative weights.
54
+ for u, v, e in nx.selfloop_edges(G, data=True):
55
+ if e.get(weight, 0) < 0 and e.get(capacity, inf) == inf:
56
+ raise nx.NetworkXUnbounded(
57
+ "Negative cost cycle of infinite capacity found. "
58
+ "Min cost flow may be unbounded below."
59
+ )
60
+
61
+ # Extract edges with positive capacities. Self loops excluded.
62
+ if G.is_multigraph():
63
+ edge_list = [
64
+ (u, v, k, e)
65
+ for u, v, k, e in G.edges(data=True, keys=True)
66
+ if u != v and e.get(capacity, inf) > 0
67
+ ]
68
+ else:
69
+ edge_list = [
70
+ (u, v, 0, e)
71
+ for u, v, e in G.edges(data=True)
72
+ if u != v and e.get(capacity, inf) > 0
73
+ ]
74
+ # Simulate infinity with the larger of the sum of absolute node imbalances
75
+ # the sum of finite edge capacities or any positive value if both sums are
76
+ # zero. This allows the infinite-capacity edges to be distinguished for
77
+ # unboundedness detection and directly participate in residual capacity
78
+ # calculation.
79
+ inf = (
80
+ max(
81
+ sum(abs(R.nodes[u]["excess"]) for u in R),
82
+ 2
83
+ * sum(
84
+ e[capacity]
85
+ for u, v, k, e in edge_list
86
+ if capacity in e and e[capacity] != inf
87
+ ),
88
+ )
89
+ or 1
90
+ )
91
+ for u, v, k, e in edge_list:
92
+ r = min(e.get(capacity, inf), inf)
93
+ w = e.get(weight, 0)
94
+ # Add both (u, v) and (v, u) into the residual network marked with the
95
+ # original key. (key[1] == True) indicates the (u, v) is in the
96
+ # original network.
97
+ R.add_edge(u, v, key=(k, True), capacity=r, weight=w, flow=0)
98
+ R.add_edge(v, u, key=(k, False), capacity=0, weight=-w, flow=0)
99
+
100
+ # Record the value simulating infinity.
101
+ R.graph["inf"] = inf
102
+
103
+ _detect_unboundedness(R)
104
+
105
+ return R
106
+
107
+
108
+ def _build_flow_dict(G, R, capacity, weight):
109
+ """Build a flow dictionary from a residual network."""
110
+ inf = float("inf")
111
+ flow_dict = {}
112
+ if G.is_multigraph():
113
+ for u in G:
114
+ flow_dict[u] = {}
115
+ for v, es in G[u].items():
116
+ flow_dict[u][v] = {
117
+ # Always saturate negative selfloops.
118
+ k: (
119
+ 0
120
+ if (
121
+ u != v or e.get(capacity, inf) <= 0 or e.get(weight, 0) >= 0
122
+ )
123
+ else e[capacity]
124
+ )
125
+ for k, e in es.items()
126
+ }
127
+ for v, es in R[u].items():
128
+ if v in flow_dict[u]:
129
+ flow_dict[u][v].update(
130
+ (k[0], e["flow"]) for k, e in es.items() if e["flow"] > 0
131
+ )
132
+ else:
133
+ for u in G:
134
+ flow_dict[u] = {
135
+ # Always saturate negative selfloops.
136
+ v: (
137
+ 0
138
+ if (u != v or e.get(capacity, inf) <= 0 or e.get(weight, 0) >= 0)
139
+ else e[capacity]
140
+ )
141
+ for v, e in G[u].items()
142
+ }
143
+ flow_dict[u].update(
144
+ (v, e["flow"])
145
+ for v, es in R[u].items()
146
+ for e in es.values()
147
+ if e["flow"] > 0
148
+ )
149
+ return flow_dict
150
+
151
+
152
+ @nx._dispatchable(
153
+ node_attrs="demand", edge_attrs={"capacity": float("inf"), "weight": 0}
154
+ )
155
+ def capacity_scaling(
156
+ G, demand="demand", capacity="capacity", weight="weight", heap=BinaryHeap
157
+ ):
158
+ r"""Find a minimum cost flow satisfying all demands in digraph G.
159
+
160
+ This is a capacity scaling successive shortest augmenting path algorithm.
161
+
162
+ G is a digraph with edge costs and capacities and in which nodes
163
+ have demand, i.e., they want to send or receive some amount of
164
+ flow. A negative demand means that the node wants to send flow, a
165
+ positive demand means that the node want to receive flow. A flow on
166
+ the digraph G satisfies all demand if the net flow into each node
167
+ is equal to the demand of that node.
168
+
169
+ Parameters
170
+ ----------
171
+ G : NetworkX graph
172
+ DiGraph or MultiDiGraph on which a minimum cost flow satisfying all
173
+ demands is to be found.
174
+
175
+ demand : string
176
+ Nodes of the graph G are expected to have an attribute demand
177
+ that indicates how much flow a node wants to send (negative
178
+ demand) or receive (positive demand). Note that the sum of the
179
+ demands should be 0 otherwise the problem in not feasible. If
180
+ this attribute is not present, a node is considered to have 0
181
+ demand. Default value: 'demand'.
182
+
183
+ capacity : string
184
+ Edges of the graph G are expected to have an attribute capacity
185
+ that indicates how much flow the edge can support. If this
186
+ attribute is not present, the edge is considered to have
187
+ infinite capacity. Default value: 'capacity'.
188
+
189
+ weight : string
190
+ Edges of the graph G are expected to have an attribute weight
191
+ that indicates the cost incurred by sending one unit of flow on
192
+ that edge. If not present, the weight is considered to be 0.
193
+ Default value: 'weight'.
194
+
195
+ heap : class
196
+ Type of heap to be used in the algorithm. It should be a subclass of
197
+ :class:`MinHeap` or implement a compatible interface.
198
+
199
+ If a stock heap implementation is to be used, :class:`BinaryHeap` is
200
+ recommended over :class:`PairingHeap` for Python implementations without
201
+ optimized attribute accesses (e.g., CPython) despite a slower
202
+ asymptotic running time. For Python implementations with optimized
203
+ attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better
204
+ performance. Default value: :class:`BinaryHeap`.
205
+
206
+ Returns
207
+ -------
208
+ flowCost : integer
209
+ Cost of a minimum cost flow satisfying all demands.
210
+
211
+ flowDict : dictionary
212
+ If G is a digraph, a dict-of-dicts keyed by nodes such that
213
+ flowDict[u][v] is the flow on edge (u, v).
214
+ If G is a MultiDiGraph, a dict-of-dicts-of-dicts keyed by nodes
215
+ so that flowDict[u][v][key] is the flow on edge (u, v, key).
216
+
217
+ Raises
218
+ ------
219
+ NetworkXError
220
+ This exception is raised if the input graph is not directed,
221
+ not connected.
222
+
223
+ NetworkXUnfeasible
224
+ This exception is raised in the following situations:
225
+
226
+ * The sum of the demands is not zero. Then, there is no
227
+ flow satisfying all demands.
228
+ * There is no flow satisfying all demand.
229
+
230
+ NetworkXUnbounded
231
+ This exception is raised if the digraph G has a cycle of
232
+ negative cost and infinite capacity. Then, the cost of a flow
233
+ satisfying all demands is unbounded below.
234
+
235
+ Notes
236
+ -----
237
+ This algorithm does not work if edge weights are floating-point numbers.
238
+
239
+ See also
240
+ --------
241
+ :meth:`network_simplex`
242
+
243
+ Examples
244
+ --------
245
+ A simple example of a min cost flow problem.
246
+
247
+ >>> G = nx.DiGraph()
248
+ >>> G.add_node("a", demand=-5)
249
+ >>> G.add_node("d", demand=5)
250
+ >>> G.add_edge("a", "b", weight=3, capacity=4)
251
+ >>> G.add_edge("a", "c", weight=6, capacity=10)
252
+ >>> G.add_edge("b", "d", weight=1, capacity=9)
253
+ >>> G.add_edge("c", "d", weight=2, capacity=5)
254
+ >>> flowCost, flowDict = nx.capacity_scaling(G)
255
+ >>> flowCost
256
+ 24
257
+ >>> flowDict
258
+ {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}
259
+
260
+ It is possible to change the name of the attributes used for the
261
+ algorithm.
262
+
263
+ >>> G = nx.DiGraph()
264
+ >>> G.add_node("p", spam=-4)
265
+ >>> G.add_node("q", spam=2)
266
+ >>> G.add_node("a", spam=-2)
267
+ >>> G.add_node("d", spam=-1)
268
+ >>> G.add_node("t", spam=2)
269
+ >>> G.add_node("w", spam=3)
270
+ >>> G.add_edge("p", "q", cost=7, vacancies=5)
271
+ >>> G.add_edge("p", "a", cost=1, vacancies=4)
272
+ >>> G.add_edge("q", "d", cost=2, vacancies=3)
273
+ >>> G.add_edge("t", "q", cost=1, vacancies=2)
274
+ >>> G.add_edge("a", "t", cost=2, vacancies=4)
275
+ >>> G.add_edge("d", "w", cost=3, vacancies=4)
276
+ >>> G.add_edge("t", "w", cost=4, vacancies=1)
277
+ >>> flowCost, flowDict = nx.capacity_scaling(
278
+ ... G, demand="spam", capacity="vacancies", weight="cost"
279
+ ... )
280
+ >>> flowCost
281
+ 37
282
+ >>> flowDict
283
+ {'p': {'q': 2, 'a': 2}, 'q': {'d': 1}, 'a': {'t': 4}, 'd': {'w': 2}, 't': {'q': 1, 'w': 1}, 'w': {}}
284
+ """
285
+ R = _build_residual_network(G, demand, capacity, weight)
286
+
287
+ inf = float("inf")
288
+ # Account cost of negative selfloops.
289
+ flow_cost = sum(
290
+ 0
291
+ if e.get(capacity, inf) <= 0 or e.get(weight, 0) >= 0
292
+ else e[capacity] * e[weight]
293
+ for u, v, e in nx.selfloop_edges(G, data=True)
294
+ )
295
+
296
+ # Determine the maximum edge capacity.
297
+ wmax = max(chain([-inf], (e["capacity"] for u, v, e in R.edges(data=True))))
298
+ if wmax == -inf:
299
+ # Residual network has no edges.
300
+ return flow_cost, _build_flow_dict(G, R, capacity, weight)
301
+
302
+ R_nodes = R.nodes
303
+ R_succ = R.succ
304
+
305
+ delta = 2 ** int(log(wmax, 2))
306
+ while delta >= 1:
307
+ # Saturate Δ-residual edges with negative reduced costs to achieve
308
+ # Δ-optimality.
309
+ for u in R:
310
+ p_u = R_nodes[u]["potential"]
311
+ for v, es in R_succ[u].items():
312
+ for k, e in es.items():
313
+ flow = e["capacity"] - e["flow"]
314
+ if e["weight"] - p_u + R_nodes[v]["potential"] < 0:
315
+ flow = e["capacity"] - e["flow"]
316
+ if flow >= delta:
317
+ e["flow"] += flow
318
+ R_succ[v][u][(k[0], not k[1])]["flow"] -= flow
319
+ R_nodes[u]["excess"] -= flow
320
+ R_nodes[v]["excess"] += flow
321
+ # Determine the Δ-active nodes.
322
+ S = set()
323
+ T = set()
324
+ S_add = S.add
325
+ S_remove = S.remove
326
+ T_add = T.add
327
+ T_remove = T.remove
328
+ for u in R:
329
+ excess = R_nodes[u]["excess"]
330
+ if excess >= delta:
331
+ S_add(u)
332
+ elif excess <= -delta:
333
+ T_add(u)
334
+ # Repeatedly augment flow from S to T along shortest paths until
335
+ # Δ-feasibility is achieved.
336
+ while S and T:
337
+ s = arbitrary_element(S)
338
+ t = None
339
+ # Search for a shortest path in terms of reduce costs from s to
340
+ # any t in T in the Δ-residual network.
341
+ d = {}
342
+ pred = {s: None}
343
+ h = heap()
344
+ h_insert = h.insert
345
+ h_get = h.get
346
+ h_insert(s, 0)
347
+ while h:
348
+ u, d_u = h.pop()
349
+ d[u] = d_u
350
+ if u in T:
351
+ # Path found.
352
+ t = u
353
+ break
354
+ p_u = R_nodes[u]["potential"]
355
+ for v, es in R_succ[u].items():
356
+ if v in d:
357
+ continue
358
+ wmin = inf
359
+ # Find the minimum-weighted (u, v) Δ-residual edge.
360
+ for k, e in es.items():
361
+ if e["capacity"] - e["flow"] >= delta:
362
+ w = e["weight"]
363
+ if w < wmin:
364
+ wmin = w
365
+ kmin = k
366
+ emin = e
367
+ if wmin == inf:
368
+ continue
369
+ # Update the distance label of v.
370
+ d_v = d_u + wmin - p_u + R_nodes[v]["potential"]
371
+ if h_insert(v, d_v):
372
+ pred[v] = (u, kmin, emin)
373
+ if t is not None:
374
+ # Augment Δ units of flow from s to t.
375
+ while u != s:
376
+ v = u
377
+ u, k, e = pred[v]
378
+ e["flow"] += delta
379
+ R_succ[v][u][(k[0], not k[1])]["flow"] -= delta
380
+ # Account node excess and deficit.
381
+ R_nodes[s]["excess"] -= delta
382
+ R_nodes[t]["excess"] += delta
383
+ if R_nodes[s]["excess"] < delta:
384
+ S_remove(s)
385
+ if R_nodes[t]["excess"] > -delta:
386
+ T_remove(t)
387
+ # Update node potentials.
388
+ d_t = d[t]
389
+ for u, d_u in d.items():
390
+ R_nodes[u]["potential"] -= d_u - d_t
391
+ else:
392
+ # Path not found.
393
+ S_remove(s)
394
+ delta //= 2
395
+
396
+ if any(R.nodes[u]["excess"] != 0 for u in R):
397
+ raise nx.NetworkXUnfeasible("No flow satisfying all demands.")
398
+
399
+ # Calculate the flow cost.
400
+ for u in R:
401
+ for v, es in R_succ[u].items():
402
+ for e in es.values():
403
+ flow = e["flow"]
404
+ if flow > 0:
405
+ flow_cost += flow * e["weight"]
406
+
407
+ return flow_cost, _build_flow_dict(G, R, capacity, weight)
janus/lib/python3.10/site-packages/networkx/algorithms/flow/dinitz_alg.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dinitz' algorithm for maximum flow problems.
3
+ """
4
+
5
+ from collections import deque
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.flow.utils import build_residual_network
9
+ from networkx.utils import pairwise
10
+
11
+ __all__ = ["dinitz"]
12
+
13
+
14
+ @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
15
+ def dinitz(G, s, t, capacity="capacity", residual=None, value_only=False, cutoff=None):
16
+ """Find a maximum single-commodity flow using Dinitz' algorithm.
17
+
18
+ This function returns the residual network resulting after computing
19
+ the maximum flow. See below for details about the conventions
20
+ NetworkX uses for defining residual networks.
21
+
22
+ This algorithm has a running time of $O(n^2 m)$ for $n$ nodes and $m$
23
+ edges [1]_.
24
+
25
+
26
+ Parameters
27
+ ----------
28
+ G : NetworkX graph
29
+ Edges of the graph are expected to have an attribute called
30
+ 'capacity'. If this attribute is not present, the edge is
31
+ considered to have infinite capacity.
32
+
33
+ s : node
34
+ Source node for the flow.
35
+
36
+ t : node
37
+ Sink node for the flow.
38
+
39
+ capacity : string
40
+ Edges of the graph G are expected to have an attribute capacity
41
+ that indicates how much flow the edge can support. If this
42
+ attribute is not present, the edge is considered to have
43
+ infinite capacity. Default value: 'capacity'.
44
+
45
+ residual : NetworkX graph
46
+ Residual network on which the algorithm is to be executed. If None, a
47
+ new residual network is created. Default value: None.
48
+
49
+ value_only : bool
50
+ If True compute only the value of the maximum flow. This parameter
51
+ will be ignored by this algorithm because it is not applicable.
52
+
53
+ cutoff : integer, float
54
+ If specified, the algorithm will terminate when the flow value reaches
55
+ or exceeds the cutoff. In this case, it may be unable to immediately
56
+ determine a minimum cut. Default value: None.
57
+
58
+ Returns
59
+ -------
60
+ R : NetworkX DiGraph
61
+ Residual network after computing the maximum flow.
62
+
63
+ Raises
64
+ ------
65
+ NetworkXError
66
+ The algorithm does not support MultiGraph and MultiDiGraph. If
67
+ the input graph is an instance of one of these two classes, a
68
+ NetworkXError is raised.
69
+
70
+ NetworkXUnbounded
71
+ If the graph has a path of infinite capacity, the value of a
72
+ feasible flow on the graph is unbounded above and the function
73
+ raises a NetworkXUnbounded.
74
+
75
+ See also
76
+ --------
77
+ :meth:`maximum_flow`
78
+ :meth:`minimum_cut`
79
+ :meth:`preflow_push`
80
+ :meth:`shortest_augmenting_path`
81
+
82
+ Notes
83
+ -----
84
+ The residual network :samp:`R` from an input graph :samp:`G` has the
85
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
86
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
87
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
88
+ in :samp:`G`.
89
+
90
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
91
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
92
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
93
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
94
+ that does not affect the solution of the problem. This value is stored in
95
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
96
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
97
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
98
+
99
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
100
+ stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
101
+ specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
102
+ that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
103
+ :samp:`s`-:samp:`t` cut.
104
+
105
+ Examples
106
+ --------
107
+ >>> from networkx.algorithms.flow import dinitz
108
+
109
+ The functions that implement flow algorithms and output a residual
110
+ network, such as this one, are not imported to the base NetworkX
111
+ namespace, so you have to explicitly import them from the flow package.
112
+
113
+ >>> G = nx.DiGraph()
114
+ >>> G.add_edge("x", "a", capacity=3.0)
115
+ >>> G.add_edge("x", "b", capacity=1.0)
116
+ >>> G.add_edge("a", "c", capacity=3.0)
117
+ >>> G.add_edge("b", "c", capacity=5.0)
118
+ >>> G.add_edge("b", "d", capacity=4.0)
119
+ >>> G.add_edge("d", "e", capacity=2.0)
120
+ >>> G.add_edge("c", "y", capacity=2.0)
121
+ >>> G.add_edge("e", "y", capacity=3.0)
122
+ >>> R = dinitz(G, "x", "y")
123
+ >>> flow_value = nx.maximum_flow_value(G, "x", "y")
124
+ >>> flow_value
125
+ 3.0
126
+ >>> flow_value == R.graph["flow_value"]
127
+ True
128
+
129
+ References
130
+ ----------
131
+ .. [1] Dinitz' Algorithm: The Original Version and Even's Version.
132
+ 2006. Yefim Dinitz. In Theoretical Computer Science. Lecture
133
+ Notes in Computer Science. Volume 3895. pp 218-240.
134
+ https://doi.org/10.1007/11685654_10
135
+
136
+ """
137
+ R = dinitz_impl(G, s, t, capacity, residual, cutoff)
138
+ R.graph["algorithm"] = "dinitz"
139
+ nx._clear_cache(R)
140
+ return R
141
+
142
+
143
+ def dinitz_impl(G, s, t, capacity, residual, cutoff):
144
+ if s not in G:
145
+ raise nx.NetworkXError(f"node {str(s)} not in graph")
146
+ if t not in G:
147
+ raise nx.NetworkXError(f"node {str(t)} not in graph")
148
+ if s == t:
149
+ raise nx.NetworkXError("source and sink are the same node")
150
+
151
+ if residual is None:
152
+ R = build_residual_network(G, capacity)
153
+ else:
154
+ R = residual
155
+
156
+ # Initialize/reset the residual network.
157
+ for u in R:
158
+ for e in R[u].values():
159
+ e["flow"] = 0
160
+
161
+ # Use an arbitrary high value as infinite. It is computed
162
+ # when building the residual network.
163
+ INF = R.graph["inf"]
164
+
165
+ if cutoff is None:
166
+ cutoff = INF
167
+
168
+ R_succ = R.succ
169
+ R_pred = R.pred
170
+
171
+ def breath_first_search():
172
+ parents = {}
173
+ vertex_dist = {s: 0}
174
+ queue = deque([(s, 0)])
175
+ # Record all the potential edges of shortest augmenting paths
176
+ while queue:
177
+ if t in parents:
178
+ break
179
+ u, dist = queue.popleft()
180
+ for v, attr in R_succ[u].items():
181
+ if attr["capacity"] - attr["flow"] > 0:
182
+ if v in parents:
183
+ if vertex_dist[v] == dist + 1:
184
+ parents[v].append(u)
185
+ else:
186
+ parents[v] = deque([u])
187
+ vertex_dist[v] = dist + 1
188
+ queue.append((v, dist + 1))
189
+ return parents
190
+
191
+ def depth_first_search(parents):
192
+ # DFS to find all the shortest augmenting paths
193
+ """Build a path using DFS starting from the sink"""
194
+ total_flow = 0
195
+ u = t
196
+ # path also functions as a stack
197
+ path = [u]
198
+ # The loop ends with no augmenting path left in the layered graph
199
+ while True:
200
+ if len(parents[u]) > 0:
201
+ v = parents[u][0]
202
+ path.append(v)
203
+ else:
204
+ path.pop()
205
+ if len(path) == 0:
206
+ break
207
+ v = path[-1]
208
+ parents[v].popleft()
209
+ # Augment the flow along the path found
210
+ if v == s:
211
+ flow = INF
212
+ for u, v in pairwise(path):
213
+ flow = min(flow, R_pred[u][v]["capacity"] - R_pred[u][v]["flow"])
214
+ for u, v in pairwise(reversed(path)):
215
+ R_pred[v][u]["flow"] += flow
216
+ R_pred[u][v]["flow"] -= flow
217
+ # Find the proper node to continue the search
218
+ if R_pred[v][u]["capacity"] - R_pred[v][u]["flow"] == 0:
219
+ parents[v].popleft()
220
+ while path[-1] != v:
221
+ path.pop()
222
+ total_flow += flow
223
+ v = path[-1]
224
+ u = v
225
+ return total_flow
226
+
227
+ flow_value = 0
228
+ while flow_value < cutoff:
229
+ parents = breath_first_search()
230
+ if t not in parents:
231
+ break
232
+ this_flow = depth_first_search(parents)
233
+ if this_flow * 2 > INF:
234
+ raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
235
+ flow_value += this_flow
236
+
237
+ R.graph["flow_value"] = flow_value
238
+ return R
janus/lib/python3.10/site-packages/networkx/algorithms/flow/edmondskarp.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Edmonds-Karp algorithm for maximum flow problems.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.flow.utils import build_residual_network
7
+
8
+ __all__ = ["edmonds_karp"]
9
+
10
+
11
+ def edmonds_karp_core(R, s, t, cutoff):
12
+ """Implementation of the Edmonds-Karp algorithm."""
13
+ R_nodes = R.nodes
14
+ R_pred = R.pred
15
+ R_succ = R.succ
16
+
17
+ inf = R.graph["inf"]
18
+
19
+ def augment(path):
20
+ """Augment flow along a path from s to t."""
21
+ # Determine the path residual capacity.
22
+ flow = inf
23
+ it = iter(path)
24
+ u = next(it)
25
+ for v in it:
26
+ attr = R_succ[u][v]
27
+ flow = min(flow, attr["capacity"] - attr["flow"])
28
+ u = v
29
+ if flow * 2 > inf:
30
+ raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
31
+ # Augment flow along the path.
32
+ it = iter(path)
33
+ u = next(it)
34
+ for v in it:
35
+ R_succ[u][v]["flow"] += flow
36
+ R_succ[v][u]["flow"] -= flow
37
+ u = v
38
+ return flow
39
+
40
+ def bidirectional_bfs():
41
+ """Bidirectional breadth-first search for an augmenting path."""
42
+ pred = {s: None}
43
+ q_s = [s]
44
+ succ = {t: None}
45
+ q_t = [t]
46
+ while True:
47
+ q = []
48
+ if len(q_s) <= len(q_t):
49
+ for u in q_s:
50
+ for v, attr in R_succ[u].items():
51
+ if v not in pred and attr["flow"] < attr["capacity"]:
52
+ pred[v] = u
53
+ if v in succ:
54
+ return v, pred, succ
55
+ q.append(v)
56
+ if not q:
57
+ return None, None, None
58
+ q_s = q
59
+ else:
60
+ for u in q_t:
61
+ for v, attr in R_pred[u].items():
62
+ if v not in succ and attr["flow"] < attr["capacity"]:
63
+ succ[v] = u
64
+ if v in pred:
65
+ return v, pred, succ
66
+ q.append(v)
67
+ if not q:
68
+ return None, None, None
69
+ q_t = q
70
+
71
+ # Look for shortest augmenting paths using breadth-first search.
72
+ flow_value = 0
73
+ while flow_value < cutoff:
74
+ v, pred, succ = bidirectional_bfs()
75
+ if pred is None:
76
+ break
77
+ path = [v]
78
+ # Trace a path from s to v.
79
+ u = v
80
+ while u != s:
81
+ u = pred[u]
82
+ path.append(u)
83
+ path.reverse()
84
+ # Trace a path from v to t.
85
+ u = v
86
+ while u != t:
87
+ u = succ[u]
88
+ path.append(u)
89
+ flow_value += augment(path)
90
+
91
+ return flow_value
92
+
93
+
94
+ def edmonds_karp_impl(G, s, t, capacity, residual, cutoff):
95
+ """Implementation of the Edmonds-Karp algorithm."""
96
+ if s not in G:
97
+ raise nx.NetworkXError(f"node {str(s)} not in graph")
98
+ if t not in G:
99
+ raise nx.NetworkXError(f"node {str(t)} not in graph")
100
+ if s == t:
101
+ raise nx.NetworkXError("source and sink are the same node")
102
+
103
+ if residual is None:
104
+ R = build_residual_network(G, capacity)
105
+ else:
106
+ R = residual
107
+
108
+ # Initialize/reset the residual network.
109
+ for u in R:
110
+ for e in R[u].values():
111
+ e["flow"] = 0
112
+
113
+ if cutoff is None:
114
+ cutoff = float("inf")
115
+ R.graph["flow_value"] = edmonds_karp_core(R, s, t, cutoff)
116
+
117
+ return R
118
+
119
+
120
+ @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
121
+ def edmonds_karp(
122
+ G, s, t, capacity="capacity", residual=None, value_only=False, cutoff=None
123
+ ):
124
+ """Find a maximum single-commodity flow using the Edmonds-Karp algorithm.
125
+
126
+ This function returns the residual network resulting after computing
127
+ the maximum flow. See below for details about the conventions
128
+ NetworkX uses for defining residual networks.
129
+
130
+ This algorithm has a running time of $O(n m^2)$ for $n$ nodes and $m$
131
+ edges.
132
+
133
+
134
+ Parameters
135
+ ----------
136
+ G : NetworkX graph
137
+ Edges of the graph are expected to have an attribute called
138
+ 'capacity'. If this attribute is not present, the edge is
139
+ considered to have infinite capacity.
140
+
141
+ s : node
142
+ Source node for the flow.
143
+
144
+ t : node
145
+ Sink node for the flow.
146
+
147
+ capacity : string
148
+ Edges of the graph G are expected to have an attribute capacity
149
+ that indicates how much flow the edge can support. If this
150
+ attribute is not present, the edge is considered to have
151
+ infinite capacity. Default value: 'capacity'.
152
+
153
+ residual : NetworkX graph
154
+ Residual network on which the algorithm is to be executed. If None, a
155
+ new residual network is created. Default value: None.
156
+
157
+ value_only : bool
158
+ If True compute only the value of the maximum flow. This parameter
159
+ will be ignored by this algorithm because it is not applicable.
160
+
161
+ cutoff : integer, float
162
+ If specified, the algorithm will terminate when the flow value reaches
163
+ or exceeds the cutoff. In this case, it may be unable to immediately
164
+ determine a minimum cut. Default value: None.
165
+
166
+ Returns
167
+ -------
168
+ R : NetworkX DiGraph
169
+ Residual network after computing the maximum flow.
170
+
171
+ Raises
172
+ ------
173
+ NetworkXError
174
+ The algorithm does not support MultiGraph and MultiDiGraph. If
175
+ the input graph is an instance of one of these two classes, a
176
+ NetworkXError is raised.
177
+
178
+ NetworkXUnbounded
179
+ If the graph has a path of infinite capacity, the value of a
180
+ feasible flow on the graph is unbounded above and the function
181
+ raises a NetworkXUnbounded.
182
+
183
+ See also
184
+ --------
185
+ :meth:`maximum_flow`
186
+ :meth:`minimum_cut`
187
+ :meth:`preflow_push`
188
+ :meth:`shortest_augmenting_path`
189
+
190
+ Notes
191
+ -----
192
+ The residual network :samp:`R` from an input graph :samp:`G` has the
193
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
194
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
195
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
196
+ in :samp:`G`.
197
+
198
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
199
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
200
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
201
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
202
+ that does not affect the solution of the problem. This value is stored in
203
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
204
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
205
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
206
+
207
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
208
+ stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
209
+ specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
210
+ that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
211
+ :samp:`s`-:samp:`t` cut.
212
+
213
+ Examples
214
+ --------
215
+ >>> from networkx.algorithms.flow import edmonds_karp
216
+
217
+ The functions that implement flow algorithms and output a residual
218
+ network, such as this one, are not imported to the base NetworkX
219
+ namespace, so you have to explicitly import them from the flow package.
220
+
221
+ >>> G = nx.DiGraph()
222
+ >>> G.add_edge("x", "a", capacity=3.0)
223
+ >>> G.add_edge("x", "b", capacity=1.0)
224
+ >>> G.add_edge("a", "c", capacity=3.0)
225
+ >>> G.add_edge("b", "c", capacity=5.0)
226
+ >>> G.add_edge("b", "d", capacity=4.0)
227
+ >>> G.add_edge("d", "e", capacity=2.0)
228
+ >>> G.add_edge("c", "y", capacity=2.0)
229
+ >>> G.add_edge("e", "y", capacity=3.0)
230
+ >>> R = edmonds_karp(G, "x", "y")
231
+ >>> flow_value = nx.maximum_flow_value(G, "x", "y")
232
+ >>> flow_value
233
+ 3.0
234
+ >>> flow_value == R.graph["flow_value"]
235
+ True
236
+
237
+ """
238
+ R = edmonds_karp_impl(G, s, t, capacity, residual, cutoff)
239
+ R.graph["algorithm"] = "edmonds_karp"
240
+ nx._clear_cache(R)
241
+ return R
janus/lib/python3.10/site-packages/networkx/algorithms/flow/gomory_hu.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gomory-Hu tree of undirected Graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ from .edmondskarp import edmonds_karp
9
+ from .utils import build_residual_network
10
+
11
+ default_flow_func = edmonds_karp
12
+
13
+ __all__ = ["gomory_hu_tree"]
14
+
15
+
16
+ @not_implemented_for("directed")
17
+ @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
18
+ def gomory_hu_tree(G, capacity="capacity", flow_func=None):
19
+ r"""Returns the Gomory-Hu tree of an undirected graph G.
20
+
21
+ A Gomory-Hu tree of an undirected graph with capacities is a
22
+ weighted tree that represents the minimum s-t cuts for all s-t
23
+ pairs in the graph.
24
+
25
+ It only requires `n-1` minimum cut computations instead of the
26
+ obvious `n(n-1)/2`. The tree represents all s-t cuts as the
27
+ minimum cut value among any pair of nodes is the minimum edge
28
+ weight in the shortest path between the two nodes in the
29
+ Gomory-Hu tree.
30
+
31
+ The Gomory-Hu tree also has the property that removing the
32
+ edge with the minimum weight in the shortest path between
33
+ any two nodes leaves two connected components that form
34
+ a partition of the nodes in G that defines the minimum s-t
35
+ cut.
36
+
37
+ See Examples section below for details.
38
+
39
+ Parameters
40
+ ----------
41
+ G : NetworkX graph
42
+ Undirected graph
43
+
44
+ capacity : string
45
+ Edges of the graph G are expected to have an attribute capacity
46
+ that indicates how much flow the edge can support. If this
47
+ attribute is not present, the edge is considered to have
48
+ infinite capacity. Default value: 'capacity'.
49
+
50
+ flow_func : function
51
+ Function to perform the underlying flow computations. Default value
52
+ :func:`edmonds_karp`. This function performs better in sparse graphs
53
+ with right tailed degree distributions.
54
+ :func:`shortest_augmenting_path` will perform better in denser
55
+ graphs.
56
+
57
+ Returns
58
+ -------
59
+ Tree : NetworkX graph
60
+ A NetworkX graph representing the Gomory-Hu tree of the input graph.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXNotImplemented
65
+ Raised if the input graph is directed.
66
+
67
+ NetworkXError
68
+ Raised if the input graph is an empty Graph.
69
+
70
+ Examples
71
+ --------
72
+ >>> G = nx.karate_club_graph()
73
+ >>> nx.set_edge_attributes(G, 1, "capacity")
74
+ >>> T = nx.gomory_hu_tree(G)
75
+ >>> # The value of the minimum cut between any pair
76
+ ... # of nodes in G is the minimum edge weight in the
77
+ ... # shortest path between the two nodes in the
78
+ ... # Gomory-Hu tree.
79
+ ... def minimum_edge_weight_in_shortest_path(T, u, v):
80
+ ... path = nx.shortest_path(T, u, v, weight="weight")
81
+ ... return min((T[u][v]["weight"], (u, v)) for (u, v) in zip(path, path[1:]))
82
+ >>> u, v = 0, 33
83
+ >>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
84
+ >>> cut_value
85
+ 10
86
+ >>> nx.minimum_cut_value(G, u, v)
87
+ 10
88
+ >>> # The Gomory-Hu tree also has the property that removing the
89
+ ... # edge with the minimum weight in the shortest path between
90
+ ... # any two nodes leaves two connected components that form
91
+ ... # a partition of the nodes in G that defines the minimum s-t
92
+ ... # cut.
93
+ ... cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
94
+ >>> T.remove_edge(*edge)
95
+ >>> U, V = list(nx.connected_components(T))
96
+ >>> # Thus U and V form a partition that defines a minimum cut
97
+ ... # between u and v in G. You can compute the edge cut set,
98
+ ... # that is, the set of edges that if removed from G will
99
+ ... # disconnect u from v in G, with this information:
100
+ ... cutset = set()
101
+ >>> for x, nbrs in ((n, G[n]) for n in U):
102
+ ... cutset.update((x, y) for y in nbrs if y in V)
103
+ >>> # Because we have set the capacities of all edges to 1
104
+ ... # the cutset contains ten edges
105
+ ... len(cutset)
106
+ 10
107
+ >>> # You can use any maximum flow algorithm for the underlying
108
+ ... # flow computations using the argument flow_func
109
+ ... from networkx.algorithms import flow
110
+ >>> T = nx.gomory_hu_tree(G, flow_func=flow.boykov_kolmogorov)
111
+ >>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
112
+ >>> cut_value
113
+ 10
114
+ >>> nx.minimum_cut_value(G, u, v, flow_func=flow.boykov_kolmogorov)
115
+ 10
116
+
117
+ Notes
118
+ -----
119
+ This implementation is based on Gusfield approach [1]_ to compute
120
+ Gomory-Hu trees, which does not require node contractions and has
121
+ the same computational complexity than the original method.
122
+
123
+ See also
124
+ --------
125
+ :func:`minimum_cut`
126
+ :func:`maximum_flow`
127
+
128
+ References
129
+ ----------
130
+ .. [1] Gusfield D: Very simple methods for all pairs network flow analysis.
131
+ SIAM J Comput 19(1):143-155, 1990.
132
+
133
+ """
134
+ if flow_func is None:
135
+ flow_func = default_flow_func
136
+
137
+ if len(G) == 0: # empty graph
138
+ msg = "Empty Graph does not have a Gomory-Hu tree representation"
139
+ raise nx.NetworkXError(msg)
140
+
141
+ # Start the tree as a star graph with an arbitrary node at the center
142
+ tree = {}
143
+ labels = {}
144
+ iter_nodes = iter(G)
145
+ root = next(iter_nodes)
146
+ for n in iter_nodes:
147
+ tree[n] = root
148
+
149
+ # Reuse residual network
150
+ R = build_residual_network(G, capacity)
151
+
152
+ # For all the leaves in the star graph tree (that is n-1 nodes).
153
+ for source in tree:
154
+ # Find neighbor in the tree
155
+ target = tree[source]
156
+ # compute minimum cut
157
+ cut_value, partition = nx.minimum_cut(
158
+ G, source, target, capacity=capacity, flow_func=flow_func, residual=R
159
+ )
160
+ labels[(source, target)] = cut_value
161
+ # Update the tree
162
+ # Source will always be in partition[0] and target in partition[1]
163
+ for node in partition[0]:
164
+ if node != source and node in tree and tree[node] == target:
165
+ tree[node] = source
166
+ labels[node, source] = labels.get((node, target), cut_value)
167
+ #
168
+ if target != root and tree[target] in partition[0]:
169
+ labels[source, tree[target]] = labels[target, tree[target]]
170
+ labels[target, source] = cut_value
171
+ tree[source] = tree[target]
172
+ tree[target] = source
173
+
174
+ # Build the tree
175
+ T = nx.Graph()
176
+ T.add_nodes_from(G)
177
+ T.add_weighted_edges_from(((u, v, labels[u, v]) for u, v in tree.items()))
178
+ return T
janus/lib/python3.10/site-packages/networkx/algorithms/flow/maxflow.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Maximum flow (and minimum cut) algorithms on capacitated graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ from .boykovkolmogorov import boykov_kolmogorov
8
+ from .dinitz_alg import dinitz
9
+ from .edmondskarp import edmonds_karp
10
+ from .preflowpush import preflow_push
11
+ from .shortestaugmentingpath import shortest_augmenting_path
12
+ from .utils import build_flow_dict
13
+
14
+ # Define the default flow function for computing maximum flow.
15
+ default_flow_func = preflow_push
16
+
17
+ __all__ = ["maximum_flow", "maximum_flow_value", "minimum_cut", "minimum_cut_value"]
18
+
19
+
20
+ @nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
21
+ def maximum_flow(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
22
+ """Find a maximum single-commodity flow.
23
+
24
+ Parameters
25
+ ----------
26
+ flowG : NetworkX graph
27
+ Edges of the graph are expected to have an attribute called
28
+ 'capacity'. If this attribute is not present, the edge is
29
+ considered to have infinite capacity.
30
+
31
+ _s : node
32
+ Source node for the flow.
33
+
34
+ _t : node
35
+ Sink node for the flow.
36
+
37
+ capacity : string
38
+ Edges of the graph G are expected to have an attribute capacity
39
+ that indicates how much flow the edge can support. If this
40
+ attribute is not present, the edge is considered to have
41
+ infinite capacity. Default value: 'capacity'.
42
+
43
+ flow_func : function
44
+ A function for computing the maximum flow among a pair of nodes
45
+ in a capacitated graph. The function has to accept at least three
46
+ parameters: a Graph or Digraph, a source node, and a target node.
47
+ And return a residual network that follows NetworkX conventions
48
+ (see Notes). If flow_func is None, the default maximum
49
+ flow function (:meth:`preflow_push`) is used. See below for
50
+ alternative algorithms. The choice of the default function may change
51
+ from version to version and should not be relied on. Default value:
52
+ None.
53
+
54
+ kwargs : Any other keyword parameter is passed to the function that
55
+ computes the maximum flow.
56
+
57
+ Returns
58
+ -------
59
+ flow_value : integer, float
60
+ Value of the maximum flow, i.e., net outflow from the source.
61
+
62
+ flow_dict : dict
63
+ A dictionary containing the value of the flow that went through
64
+ each edge.
65
+
66
+ Raises
67
+ ------
68
+ NetworkXError
69
+ The algorithm does not support MultiGraph and MultiDiGraph. If
70
+ the input graph is an instance of one of these two classes, a
71
+ NetworkXError is raised.
72
+
73
+ NetworkXUnbounded
74
+ If the graph has a path of infinite capacity, the value of a
75
+ feasible flow on the graph is unbounded above and the function
76
+ raises a NetworkXUnbounded.
77
+
78
+ See also
79
+ --------
80
+ :meth:`maximum_flow_value`
81
+ :meth:`minimum_cut`
82
+ :meth:`minimum_cut_value`
83
+ :meth:`edmonds_karp`
84
+ :meth:`preflow_push`
85
+ :meth:`shortest_augmenting_path`
86
+
87
+ Notes
88
+ -----
89
+ The function used in the flow_func parameter has to return a residual
90
+ network that follows NetworkX conventions:
91
+
92
+ The residual network :samp:`R` from an input graph :samp:`G` has the
93
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
94
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
95
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
96
+ in :samp:`G`.
97
+
98
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
99
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
100
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
101
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
102
+ that does not affect the solution of the problem. This value is stored in
103
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
104
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
105
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
106
+
107
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
108
+ stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
109
+ only edges :samp:`(u, v)` such that
110
+ :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
111
+ :samp:`s`-:samp:`t` cut.
112
+
113
+ Specific algorithms may store extra data in :samp:`R`.
114
+
115
+ The function should supports an optional boolean parameter value_only. When
116
+ True, it can optionally terminate the algorithm as soon as the maximum flow
117
+ value and the minimum cut can be determined.
118
+
119
+ Examples
120
+ --------
121
+ >>> G = nx.DiGraph()
122
+ >>> G.add_edge("x", "a", capacity=3.0)
123
+ >>> G.add_edge("x", "b", capacity=1.0)
124
+ >>> G.add_edge("a", "c", capacity=3.0)
125
+ >>> G.add_edge("b", "c", capacity=5.0)
126
+ >>> G.add_edge("b", "d", capacity=4.0)
127
+ >>> G.add_edge("d", "e", capacity=2.0)
128
+ >>> G.add_edge("c", "y", capacity=2.0)
129
+ >>> G.add_edge("e", "y", capacity=3.0)
130
+
131
+ maximum_flow returns both the value of the maximum flow and a
132
+ dictionary with all flows.
133
+
134
+ >>> flow_value, flow_dict = nx.maximum_flow(G, "x", "y")
135
+ >>> flow_value
136
+ 3.0
137
+ >>> print(flow_dict["x"]["b"])
138
+ 1.0
139
+
140
+ You can also use alternative algorithms for computing the
141
+ maximum flow by using the flow_func parameter.
142
+
143
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
144
+ >>> flow_value == nx.maximum_flow(G, "x", "y", flow_func=shortest_augmenting_path)[
145
+ ... 0
146
+ ... ]
147
+ True
148
+
149
+ """
150
+ if flow_func is None:
151
+ if kwargs:
152
+ raise nx.NetworkXError(
153
+ "You have to explicitly set a flow_func if"
154
+ " you need to pass parameters via kwargs."
155
+ )
156
+ flow_func = default_flow_func
157
+
158
+ if not callable(flow_func):
159
+ raise nx.NetworkXError("flow_func has to be callable.")
160
+
161
+ R = flow_func(flowG, _s, _t, capacity=capacity, value_only=False, **kwargs)
162
+ flow_dict = build_flow_dict(flowG, R)
163
+
164
+ return (R.graph["flow_value"], flow_dict)
165
+
166
+
167
+ @nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
168
+ def maximum_flow_value(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
169
+ """Find the value of maximum single-commodity flow.
170
+
171
+ Parameters
172
+ ----------
173
+ flowG : NetworkX graph
174
+ Edges of the graph are expected to have an attribute called
175
+ 'capacity'. If this attribute is not present, the edge is
176
+ considered to have infinite capacity.
177
+
178
+ _s : node
179
+ Source node for the flow.
180
+
181
+ _t : node
182
+ Sink node for the flow.
183
+
184
+ capacity : string
185
+ Edges of the graph G are expected to have an attribute capacity
186
+ that indicates how much flow the edge can support. If this
187
+ attribute is not present, the edge is considered to have
188
+ infinite capacity. Default value: 'capacity'.
189
+
190
+ flow_func : function
191
+ A function for computing the maximum flow among a pair of nodes
192
+ in a capacitated graph. The function has to accept at least three
193
+ parameters: a Graph or Digraph, a source node, and a target node.
194
+ And return a residual network that follows NetworkX conventions
195
+ (see Notes). If flow_func is None, the default maximum
196
+ flow function (:meth:`preflow_push`) is used. See below for
197
+ alternative algorithms. The choice of the default function may change
198
+ from version to version and should not be relied on. Default value:
199
+ None.
200
+
201
+ kwargs : Any other keyword parameter is passed to the function that
202
+ computes the maximum flow.
203
+
204
+ Returns
205
+ -------
206
+ flow_value : integer, float
207
+ Value of the maximum flow, i.e., net outflow from the source.
208
+
209
+ Raises
210
+ ------
211
+ NetworkXError
212
+ The algorithm does not support MultiGraph and MultiDiGraph. If
213
+ the input graph is an instance of one of these two classes, a
214
+ NetworkXError is raised.
215
+
216
+ NetworkXUnbounded
217
+ If the graph has a path of infinite capacity, the value of a
218
+ feasible flow on the graph is unbounded above and the function
219
+ raises a NetworkXUnbounded.
220
+
221
+ See also
222
+ --------
223
+ :meth:`maximum_flow`
224
+ :meth:`minimum_cut`
225
+ :meth:`minimum_cut_value`
226
+ :meth:`edmonds_karp`
227
+ :meth:`preflow_push`
228
+ :meth:`shortest_augmenting_path`
229
+
230
+ Notes
231
+ -----
232
+ The function used in the flow_func parameter has to return a residual
233
+ network that follows NetworkX conventions:
234
+
235
+ The residual network :samp:`R` from an input graph :samp:`G` has the
236
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
237
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
238
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
239
+ in :samp:`G`.
240
+
241
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
242
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
243
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
244
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
245
+ that does not affect the solution of the problem. This value is stored in
246
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
247
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
248
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
249
+
250
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
251
+ stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
252
+ only edges :samp:`(u, v)` such that
253
+ :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
254
+ :samp:`s`-:samp:`t` cut.
255
+
256
+ Specific algorithms may store extra data in :samp:`R`.
257
+
258
+ The function should supports an optional boolean parameter value_only. When
259
+ True, it can optionally terminate the algorithm as soon as the maximum flow
260
+ value and the minimum cut can be determined.
261
+
262
+ Examples
263
+ --------
264
+ >>> G = nx.DiGraph()
265
+ >>> G.add_edge("x", "a", capacity=3.0)
266
+ >>> G.add_edge("x", "b", capacity=1.0)
267
+ >>> G.add_edge("a", "c", capacity=3.0)
268
+ >>> G.add_edge("b", "c", capacity=5.0)
269
+ >>> G.add_edge("b", "d", capacity=4.0)
270
+ >>> G.add_edge("d", "e", capacity=2.0)
271
+ >>> G.add_edge("c", "y", capacity=2.0)
272
+ >>> G.add_edge("e", "y", capacity=3.0)
273
+
274
+ maximum_flow_value computes only the value of the
275
+ maximum flow:
276
+
277
+ >>> flow_value = nx.maximum_flow_value(G, "x", "y")
278
+ >>> flow_value
279
+ 3.0
280
+
281
+ You can also use alternative algorithms for computing the
282
+ maximum flow by using the flow_func parameter.
283
+
284
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
285
+ >>> flow_value == nx.maximum_flow_value(
286
+ ... G, "x", "y", flow_func=shortest_augmenting_path
287
+ ... )
288
+ True
289
+
290
+ """
291
+ if flow_func is None:
292
+ if kwargs:
293
+ raise nx.NetworkXError(
294
+ "You have to explicitly set a flow_func if"
295
+ " you need to pass parameters via kwargs."
296
+ )
297
+ flow_func = default_flow_func
298
+
299
+ if not callable(flow_func):
300
+ raise nx.NetworkXError("flow_func has to be callable.")
301
+
302
+ R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
303
+
304
+ return R.graph["flow_value"]
305
+
306
+
307
+ @nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
308
+ def minimum_cut(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
309
+ """Compute the value and the node partition of a minimum (s, t)-cut.
310
+
311
+ Use the max-flow min-cut theorem, i.e., the capacity of a minimum
312
+ capacity cut is equal to the flow value of a maximum flow.
313
+
314
+ Parameters
315
+ ----------
316
+ flowG : NetworkX graph
317
+ Edges of the graph are expected to have an attribute called
318
+ 'capacity'. If this attribute is not present, the edge is
319
+ considered to have infinite capacity.
320
+
321
+ _s : node
322
+ Source node for the flow.
323
+
324
+ _t : node
325
+ Sink node for the flow.
326
+
327
+ capacity : string
328
+ Edges of the graph G are expected to have an attribute capacity
329
+ that indicates how much flow the edge can support. If this
330
+ attribute is not present, the edge is considered to have
331
+ infinite capacity. Default value: 'capacity'.
332
+
333
+ flow_func : function
334
+ A function for computing the maximum flow among a pair of nodes
335
+ in a capacitated graph. The function has to accept at least three
336
+ parameters: a Graph or Digraph, a source node, and a target node.
337
+ And return a residual network that follows NetworkX conventions
338
+ (see Notes). If flow_func is None, the default maximum
339
+ flow function (:meth:`preflow_push`) is used. See below for
340
+ alternative algorithms. The choice of the default function may change
341
+ from version to version and should not be relied on. Default value:
342
+ None.
343
+
344
+ kwargs : Any other keyword parameter is passed to the function that
345
+ computes the maximum flow.
346
+
347
+ Returns
348
+ -------
349
+ cut_value : integer, float
350
+ Value of the minimum cut.
351
+
352
+ partition : pair of node sets
353
+ A partitioning of the nodes that defines a minimum cut.
354
+
355
+ Raises
356
+ ------
357
+ NetworkXUnbounded
358
+ If the graph has a path of infinite capacity, all cuts have
359
+ infinite capacity and the function raises a NetworkXError.
360
+
361
+ See also
362
+ --------
363
+ :meth:`maximum_flow`
364
+ :meth:`maximum_flow_value`
365
+ :meth:`minimum_cut_value`
366
+ :meth:`edmonds_karp`
367
+ :meth:`preflow_push`
368
+ :meth:`shortest_augmenting_path`
369
+
370
+ Notes
371
+ -----
372
+ The function used in the flow_func parameter has to return a residual
373
+ network that follows NetworkX conventions:
374
+
375
+ The residual network :samp:`R` from an input graph :samp:`G` has the
376
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
377
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
378
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
379
+ in :samp:`G`.
380
+
381
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
382
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
383
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
384
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
385
+ that does not affect the solution of the problem. This value is stored in
386
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
387
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
388
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
389
+
390
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
391
+ stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
392
+ only edges :samp:`(u, v)` such that
393
+ :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
394
+ :samp:`s`-:samp:`t` cut.
395
+
396
+ Specific algorithms may store extra data in :samp:`R`.
397
+
398
+ The function should supports an optional boolean parameter value_only. When
399
+ True, it can optionally terminate the algorithm as soon as the maximum flow
400
+ value and the minimum cut can be determined.
401
+
402
+ Examples
403
+ --------
404
+ >>> G = nx.DiGraph()
405
+ >>> G.add_edge("x", "a", capacity=3.0)
406
+ >>> G.add_edge("x", "b", capacity=1.0)
407
+ >>> G.add_edge("a", "c", capacity=3.0)
408
+ >>> G.add_edge("b", "c", capacity=5.0)
409
+ >>> G.add_edge("b", "d", capacity=4.0)
410
+ >>> G.add_edge("d", "e", capacity=2.0)
411
+ >>> G.add_edge("c", "y", capacity=2.0)
412
+ >>> G.add_edge("e", "y", capacity=3.0)
413
+
414
+ minimum_cut computes both the value of the
415
+ minimum cut and the node partition:
416
+
417
+ >>> cut_value, partition = nx.minimum_cut(G, "x", "y")
418
+ >>> reachable, non_reachable = partition
419
+
420
+ 'partition' here is a tuple with the two sets of nodes that define
421
+ the minimum cut. You can compute the cut set of edges that induce
422
+ the minimum cut as follows:
423
+
424
+ >>> cutset = set()
425
+ >>> for u, nbrs in ((n, G[n]) for n in reachable):
426
+ ... cutset.update((u, v) for v in nbrs if v in non_reachable)
427
+ >>> print(sorted(cutset))
428
+ [('c', 'y'), ('x', 'b')]
429
+ >>> cut_value == sum(G.edges[u, v]["capacity"] for (u, v) in cutset)
430
+ True
431
+
432
+ You can also use alternative algorithms for computing the
433
+ minimum cut by using the flow_func parameter.
434
+
435
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
436
+ >>> cut_value == nx.minimum_cut(G, "x", "y", flow_func=shortest_augmenting_path)[0]
437
+ True
438
+
439
+ """
440
+ if flow_func is None:
441
+ if kwargs:
442
+ raise nx.NetworkXError(
443
+ "You have to explicitly set a flow_func if"
444
+ " you need to pass parameters via kwargs."
445
+ )
446
+ flow_func = default_flow_func
447
+
448
+ if not callable(flow_func):
449
+ raise nx.NetworkXError("flow_func has to be callable.")
450
+
451
+ if kwargs.get("cutoff") is not None and flow_func is preflow_push:
452
+ raise nx.NetworkXError("cutoff should not be specified.")
453
+
454
+ R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
455
+ # Remove saturated edges from the residual network
456
+ cutset = [(u, v, d) for u, v, d in R.edges(data=True) if d["flow"] == d["capacity"]]
457
+ R.remove_edges_from(cutset)
458
+
459
+ # Then, reachable and non reachable nodes from source in the
460
+ # residual network form the node partition that defines
461
+ # the minimum cut.
462
+ non_reachable = set(dict(nx.shortest_path_length(R, target=_t)))
463
+ partition = (set(flowG) - non_reachable, non_reachable)
464
+ # Finally add again cutset edges to the residual network to make
465
+ # sure that it is reusable.
466
+ R.add_edges_from(cutset)
467
+ return (R.graph["flow_value"], partition)
468
+
469
+
470
+ @nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
471
+ def minimum_cut_value(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
472
+ """Compute the value of a minimum (s, t)-cut.
473
+
474
+ Use the max-flow min-cut theorem, i.e., the capacity of a minimum
475
+ capacity cut is equal to the flow value of a maximum flow.
476
+
477
+ Parameters
478
+ ----------
479
+ flowG : NetworkX graph
480
+ Edges of the graph are expected to have an attribute called
481
+ 'capacity'. If this attribute is not present, the edge is
482
+ considered to have infinite capacity.
483
+
484
+ _s : node
485
+ Source node for the flow.
486
+
487
+ _t : node
488
+ Sink node for the flow.
489
+
490
+ capacity : string
491
+ Edges of the graph G are expected to have an attribute capacity
492
+ that indicates how much flow the edge can support. If this
493
+ attribute is not present, the edge is considered to have
494
+ infinite capacity. Default value: 'capacity'.
495
+
496
+ flow_func : function
497
+ A function for computing the maximum flow among a pair of nodes
498
+ in a capacitated graph. The function has to accept at least three
499
+ parameters: a Graph or Digraph, a source node, and a target node.
500
+ And return a residual network that follows NetworkX conventions
501
+ (see Notes). If flow_func is None, the default maximum
502
+ flow function (:meth:`preflow_push`) is used. See below for
503
+ alternative algorithms. The choice of the default function may change
504
+ from version to version and should not be relied on. Default value:
505
+ None.
506
+
507
+ kwargs : Any other keyword parameter is passed to the function that
508
+ computes the maximum flow.
509
+
510
+ Returns
511
+ -------
512
+ cut_value : integer, float
513
+ Value of the minimum cut.
514
+
515
+ Raises
516
+ ------
517
+ NetworkXUnbounded
518
+ If the graph has a path of infinite capacity, all cuts have
519
+ infinite capacity and the function raises a NetworkXError.
520
+
521
+ See also
522
+ --------
523
+ :meth:`maximum_flow`
524
+ :meth:`maximum_flow_value`
525
+ :meth:`minimum_cut`
526
+ :meth:`edmonds_karp`
527
+ :meth:`preflow_push`
528
+ :meth:`shortest_augmenting_path`
529
+
530
+ Notes
531
+ -----
532
+ The function used in the flow_func parameter has to return a residual
533
+ network that follows NetworkX conventions:
534
+
535
+ The residual network :samp:`R` from an input graph :samp:`G` has the
536
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
537
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
538
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
539
+ in :samp:`G`.
540
+
541
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
542
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
543
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
544
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
545
+ that does not affect the solution of the problem. This value is stored in
546
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
547
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
548
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
549
+
550
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
551
+ stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
552
+ only edges :samp:`(u, v)` such that
553
+ :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
554
+ :samp:`s`-:samp:`t` cut.
555
+
556
+ Specific algorithms may store extra data in :samp:`R`.
557
+
558
+ The function should supports an optional boolean parameter value_only. When
559
+ True, it can optionally terminate the algorithm as soon as the maximum flow
560
+ value and the minimum cut can be determined.
561
+
562
+ Examples
563
+ --------
564
+ >>> G = nx.DiGraph()
565
+ >>> G.add_edge("x", "a", capacity=3.0)
566
+ >>> G.add_edge("x", "b", capacity=1.0)
567
+ >>> G.add_edge("a", "c", capacity=3.0)
568
+ >>> G.add_edge("b", "c", capacity=5.0)
569
+ >>> G.add_edge("b", "d", capacity=4.0)
570
+ >>> G.add_edge("d", "e", capacity=2.0)
571
+ >>> G.add_edge("c", "y", capacity=2.0)
572
+ >>> G.add_edge("e", "y", capacity=3.0)
573
+
574
+ minimum_cut_value computes only the value of the
575
+ minimum cut:
576
+
577
+ >>> cut_value = nx.minimum_cut_value(G, "x", "y")
578
+ >>> cut_value
579
+ 3.0
580
+
581
+ You can also use alternative algorithms for computing the
582
+ minimum cut by using the flow_func parameter.
583
+
584
+ >>> from networkx.algorithms.flow import shortest_augmenting_path
585
+ >>> cut_value == nx.minimum_cut_value(
586
+ ... G, "x", "y", flow_func=shortest_augmenting_path
587
+ ... )
588
+ True
589
+
590
+ """
591
+ if flow_func is None:
592
+ if kwargs:
593
+ raise nx.NetworkXError(
594
+ "You have to explicitly set a flow_func if"
595
+ " you need to pass parameters via kwargs."
596
+ )
597
+ flow_func = default_flow_func
598
+
599
+ if not callable(flow_func):
600
+ raise nx.NetworkXError("flow_func has to be callable.")
601
+
602
+ if kwargs.get("cutoff") is not None and flow_func is preflow_push:
603
+ raise nx.NetworkXError("cutoff should not be specified.")
604
+
605
+ R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
606
+
607
+ return R.graph["flow_value"]
janus/lib/python3.10/site-packages/networkx/algorithms/flow/mincost.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Minimum cost flow algorithms on directed connected graphs.
3
+ """
4
+
5
+ __all__ = ["min_cost_flow_cost", "min_cost_flow", "cost_of_flow", "max_flow_min_cost"]
6
+
7
+ import networkx as nx
8
+
9
+
10
+ @nx._dispatchable(
11
+ node_attrs="demand", edge_attrs={"capacity": float("inf"), "weight": 0}
12
+ )
13
+ def min_cost_flow_cost(G, demand="demand", capacity="capacity", weight="weight"):
14
+ r"""Find the cost of a minimum cost flow satisfying all demands in digraph G.
15
+
16
+ G is a digraph with edge costs and capacities and in which nodes
17
+ have demand, i.e., they want to send or receive some amount of
18
+ flow. A negative demand means that the node wants to send flow, a
19
+ positive demand means that the node want to receive flow. A flow on
20
+ the digraph G satisfies all demand if the net flow into each node
21
+ is equal to the demand of that node.
22
+
23
+ Parameters
24
+ ----------
25
+ G : NetworkX graph
26
+ DiGraph on which a minimum cost flow satisfying all demands is
27
+ to be found.
28
+
29
+ demand : string
30
+ Nodes of the graph G are expected to have an attribute demand
31
+ that indicates how much flow a node wants to send (negative
32
+ demand) or receive (positive demand). Note that the sum of the
33
+ demands should be 0 otherwise the problem in not feasible. If
34
+ this attribute is not present, a node is considered to have 0
35
+ demand. Default value: 'demand'.
36
+
37
+ capacity : string
38
+ Edges of the graph G are expected to have an attribute capacity
39
+ that indicates how much flow the edge can support. If this
40
+ attribute is not present, the edge is considered to have
41
+ infinite capacity. Default value: 'capacity'.
42
+
43
+ weight : string
44
+ Edges of the graph G are expected to have an attribute weight
45
+ that indicates the cost incurred by sending one unit of flow on
46
+ that edge. If not present, the weight is considered to be 0.
47
+ Default value: 'weight'.
48
+
49
+ Returns
50
+ -------
51
+ flowCost : integer, float
52
+ Cost of a minimum cost flow satisfying all demands.
53
+
54
+ Raises
55
+ ------
56
+ NetworkXError
57
+ This exception is raised if the input graph is not directed or
58
+ not connected.
59
+
60
+ NetworkXUnfeasible
61
+ This exception is raised in the following situations:
62
+
63
+ * The sum of the demands is not zero. Then, there is no
64
+ flow satisfying all demands.
65
+ * There is no flow satisfying all demand.
66
+
67
+ NetworkXUnbounded
68
+ This exception is raised if the digraph G has a cycle of
69
+ negative cost and infinite capacity. Then, the cost of a flow
70
+ satisfying all demands is unbounded below.
71
+
72
+ See also
73
+ --------
74
+ cost_of_flow, max_flow_min_cost, min_cost_flow, network_simplex
75
+
76
+ Notes
77
+ -----
78
+ This algorithm is not guaranteed to work if edge weights or demands
79
+ are floating point numbers (overflows and roundoff errors can
80
+ cause problems). As a workaround you can use integer numbers by
81
+ multiplying the relevant edge attributes by a convenient
82
+ constant factor (eg 100).
83
+
84
+ Examples
85
+ --------
86
+ A simple example of a min cost flow problem.
87
+
88
+ >>> G = nx.DiGraph()
89
+ >>> G.add_node("a", demand=-5)
90
+ >>> G.add_node("d", demand=5)
91
+ >>> G.add_edge("a", "b", weight=3, capacity=4)
92
+ >>> G.add_edge("a", "c", weight=6, capacity=10)
93
+ >>> G.add_edge("b", "d", weight=1, capacity=9)
94
+ >>> G.add_edge("c", "d", weight=2, capacity=5)
95
+ >>> flowCost = nx.min_cost_flow_cost(G)
96
+ >>> flowCost
97
+ 24
98
+ """
99
+ return nx.network_simplex(G, demand=demand, capacity=capacity, weight=weight)[0]
100
+
101
+
102
+ @nx._dispatchable(
103
+ node_attrs="demand", edge_attrs={"capacity": float("inf"), "weight": 0}
104
+ )
105
+ def min_cost_flow(G, demand="demand", capacity="capacity", weight="weight"):
106
+ r"""Returns a minimum cost flow satisfying all demands in digraph G.
107
+
108
+ G is a digraph with edge costs and capacities and in which nodes
109
+ have demand, i.e., they want to send or receive some amount of
110
+ flow. A negative demand means that the node wants to send flow, a
111
+ positive demand means that the node want to receive flow. A flow on
112
+ the digraph G satisfies all demand if the net flow into each node
113
+ is equal to the demand of that node.
114
+
115
+ Parameters
116
+ ----------
117
+ G : NetworkX graph
118
+ DiGraph on which a minimum cost flow satisfying all demands is
119
+ to be found.
120
+
121
+ demand : string
122
+ Nodes of the graph G are expected to have an attribute demand
123
+ that indicates how much flow a node wants to send (negative
124
+ demand) or receive (positive demand). Note that the sum of the
125
+ demands should be 0 otherwise the problem in not feasible. If
126
+ this attribute is not present, a node is considered to have 0
127
+ demand. Default value: 'demand'.
128
+
129
+ capacity : string
130
+ Edges of the graph G are expected to have an attribute capacity
131
+ that indicates how much flow the edge can support. If this
132
+ attribute is not present, the edge is considered to have
133
+ infinite capacity. Default value: 'capacity'.
134
+
135
+ weight : string
136
+ Edges of the graph G are expected to have an attribute weight
137
+ that indicates the cost incurred by sending one unit of flow on
138
+ that edge. If not present, the weight is considered to be 0.
139
+ Default value: 'weight'.
140
+
141
+ Returns
142
+ -------
143
+ flowDict : dictionary
144
+ Dictionary of dictionaries keyed by nodes such that
145
+ flowDict[u][v] is the flow edge (u, v).
146
+
147
+ Raises
148
+ ------
149
+ NetworkXError
150
+ This exception is raised if the input graph is not directed or
151
+ not connected.
152
+
153
+ NetworkXUnfeasible
154
+ This exception is raised in the following situations:
155
+
156
+ * The sum of the demands is not zero. Then, there is no
157
+ flow satisfying all demands.
158
+ * There is no flow satisfying all demand.
159
+
160
+ NetworkXUnbounded
161
+ This exception is raised if the digraph G has a cycle of
162
+ negative cost and infinite capacity. Then, the cost of a flow
163
+ satisfying all demands is unbounded below.
164
+
165
+ See also
166
+ --------
167
+ cost_of_flow, max_flow_min_cost, min_cost_flow_cost, network_simplex
168
+
169
+ Notes
170
+ -----
171
+ This algorithm is not guaranteed to work if edge weights or demands
172
+ are floating point numbers (overflows and roundoff errors can
173
+ cause problems). As a workaround you can use integer numbers by
174
+ multiplying the relevant edge attributes by a convenient
175
+ constant factor (eg 100).
176
+
177
+ Examples
178
+ --------
179
+ A simple example of a min cost flow problem.
180
+
181
+ >>> G = nx.DiGraph()
182
+ >>> G.add_node("a", demand=-5)
183
+ >>> G.add_node("d", demand=5)
184
+ >>> G.add_edge("a", "b", weight=3, capacity=4)
185
+ >>> G.add_edge("a", "c", weight=6, capacity=10)
186
+ >>> G.add_edge("b", "d", weight=1, capacity=9)
187
+ >>> G.add_edge("c", "d", weight=2, capacity=5)
188
+ >>> flowDict = nx.min_cost_flow(G)
189
+ >>> flowDict
190
+ {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}
191
+ """
192
+ return nx.network_simplex(G, demand=demand, capacity=capacity, weight=weight)[1]
193
+
194
+
195
+ @nx._dispatchable(edge_attrs={"weight": 0})
196
+ def cost_of_flow(G, flowDict, weight="weight"):
197
+ """Compute the cost of the flow given by flowDict on graph G.
198
+
199
+ Note that this function does not check for the validity of the
200
+ flow flowDict. This function will fail if the graph G and the
201
+ flow don't have the same edge set.
202
+
203
+ Parameters
204
+ ----------
205
+ G : NetworkX graph
206
+ DiGraph on which a minimum cost flow satisfying all demands is
207
+ to be found.
208
+
209
+ weight : string
210
+ Edges of the graph G are expected to have an attribute weight
211
+ that indicates the cost incurred by sending one unit of flow on
212
+ that edge. If not present, the weight is considered to be 0.
213
+ Default value: 'weight'.
214
+
215
+ flowDict : dictionary
216
+ Dictionary of dictionaries keyed by nodes such that
217
+ flowDict[u][v] is the flow edge (u, v).
218
+
219
+ Returns
220
+ -------
221
+ cost : Integer, float
222
+ The total cost of the flow. This is given by the sum over all
223
+ edges of the product of the edge's flow and the edge's weight.
224
+
225
+ See also
226
+ --------
227
+ max_flow_min_cost, min_cost_flow, min_cost_flow_cost, network_simplex
228
+
229
+ Notes
230
+ -----
231
+ This algorithm is not guaranteed to work if edge weights or demands
232
+ are floating point numbers (overflows and roundoff errors can
233
+ cause problems). As a workaround you can use integer numbers by
234
+ multiplying the relevant edge attributes by a convenient
235
+ constant factor (eg 100).
236
+
237
+ Examples
238
+ --------
239
+ >>> G = nx.DiGraph()
240
+ >>> G.add_node("a", demand=-5)
241
+ >>> G.add_node("d", demand=5)
242
+ >>> G.add_edge("a", "b", weight=3, capacity=4)
243
+ >>> G.add_edge("a", "c", weight=6, capacity=10)
244
+ >>> G.add_edge("b", "d", weight=1, capacity=9)
245
+ >>> G.add_edge("c", "d", weight=2, capacity=5)
246
+ >>> flowDict = nx.min_cost_flow(G)
247
+ >>> flowDict
248
+ {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}
249
+ >>> nx.cost_of_flow(G, flowDict)
250
+ 24
251
+ """
252
+ return sum((flowDict[u][v] * d.get(weight, 0) for u, v, d in G.edges(data=True)))
253
+
254
+
255
+ @nx._dispatchable(edge_attrs={"capacity": float("inf"), "weight": 0})
256
+ def max_flow_min_cost(G, s, t, capacity="capacity", weight="weight"):
257
+ """Returns a maximum (s, t)-flow of minimum cost.
258
+
259
+ G is a digraph with edge costs and capacities. There is a source
260
+ node s and a sink node t. This function finds a maximum flow from
261
+ s to t whose total cost is minimized.
262
+
263
+ Parameters
264
+ ----------
265
+ G : NetworkX graph
266
+ DiGraph on which a minimum cost flow satisfying all demands is
267
+ to be found.
268
+
269
+ s: node label
270
+ Source of the flow.
271
+
272
+ t: node label
273
+ Destination of the flow.
274
+
275
+ capacity: string
276
+ Edges of the graph G are expected to have an attribute capacity
277
+ that indicates how much flow the edge can support. If this
278
+ attribute is not present, the edge is considered to have
279
+ infinite capacity. Default value: 'capacity'.
280
+
281
+ weight: string
282
+ Edges of the graph G are expected to have an attribute weight
283
+ that indicates the cost incurred by sending one unit of flow on
284
+ that edge. If not present, the weight is considered to be 0.
285
+ Default value: 'weight'.
286
+
287
+ Returns
288
+ -------
289
+ flowDict: dictionary
290
+ Dictionary of dictionaries keyed by nodes such that
291
+ flowDict[u][v] is the flow edge (u, v).
292
+
293
+ Raises
294
+ ------
295
+ NetworkXError
296
+ This exception is raised if the input graph is not directed or
297
+ not connected.
298
+
299
+ NetworkXUnbounded
300
+ This exception is raised if there is an infinite capacity path
301
+ from s to t in G. In this case there is no maximum flow. This
302
+ exception is also raised if the digraph G has a cycle of
303
+ negative cost and infinite capacity. Then, the cost of a flow
304
+ is unbounded below.
305
+
306
+ See also
307
+ --------
308
+ cost_of_flow, min_cost_flow, min_cost_flow_cost, network_simplex
309
+
310
+ Notes
311
+ -----
312
+ This algorithm is not guaranteed to work if edge weights or demands
313
+ are floating point numbers (overflows and roundoff errors can
314
+ cause problems). As a workaround you can use integer numbers by
315
+ multiplying the relevant edge attributes by a convenient
316
+ constant factor (eg 100).
317
+
318
+ Examples
319
+ --------
320
+ >>> G = nx.DiGraph()
321
+ >>> G.add_edges_from(
322
+ ... [
323
+ ... (1, 2, {"capacity": 12, "weight": 4}),
324
+ ... (1, 3, {"capacity": 20, "weight": 6}),
325
+ ... (2, 3, {"capacity": 6, "weight": -3}),
326
+ ... (2, 6, {"capacity": 14, "weight": 1}),
327
+ ... (3, 4, {"weight": 9}),
328
+ ... (3, 5, {"capacity": 10, "weight": 5}),
329
+ ... (4, 2, {"capacity": 19, "weight": 13}),
330
+ ... (4, 5, {"capacity": 4, "weight": 0}),
331
+ ... (5, 7, {"capacity": 28, "weight": 2}),
332
+ ... (6, 5, {"capacity": 11, "weight": 1}),
333
+ ... (6, 7, {"weight": 8}),
334
+ ... (7, 4, {"capacity": 6, "weight": 6}),
335
+ ... ]
336
+ ... )
337
+ >>> mincostFlow = nx.max_flow_min_cost(G, 1, 7)
338
+ >>> mincost = nx.cost_of_flow(G, mincostFlow)
339
+ >>> mincost
340
+ 373
341
+ >>> from networkx.algorithms.flow import maximum_flow
342
+ >>> maxFlow = maximum_flow(G, 1, 7)[1]
343
+ >>> nx.cost_of_flow(G, maxFlow) >= mincost
344
+ True
345
+ >>> mincostFlowValue = sum((mincostFlow[u][7] for u in G.predecessors(7))) - sum(
346
+ ... (mincostFlow[7][v] for v in G.successors(7))
347
+ ... )
348
+ >>> mincostFlowValue == nx.maximum_flow_value(G, 1, 7)
349
+ True
350
+
351
+ """
352
+ maxFlow = nx.maximum_flow_value(G, s, t, capacity=capacity)
353
+ H = nx.DiGraph(G)
354
+ H.add_node(s, demand=-maxFlow)
355
+ H.add_node(t, demand=maxFlow)
356
+ return min_cost_flow(H, capacity=capacity, weight=weight)
janus/lib/python3.10/site-packages/networkx/algorithms/flow/networksimplex.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Minimum cost flow algorithms on directed connected graphs.
3
+ """
4
+
5
+ __all__ = ["network_simplex"]
6
+
7
+ from itertools import chain, islice, repeat
8
+ from math import ceil, sqrt
9
+
10
+ import networkx as nx
11
+ from networkx.utils import not_implemented_for
12
+
13
+
14
+ class _DataEssentialsAndFunctions:
15
+ def __init__(
16
+ self, G, multigraph, demand="demand", capacity="capacity", weight="weight"
17
+ ):
18
+ # Number all nodes and edges and hereafter reference them using ONLY their numbers
19
+ self.node_list = list(G) # nodes
20
+ self.node_indices = {u: i for i, u in enumerate(self.node_list)} # node indices
21
+ self.node_demands = [
22
+ G.nodes[u].get(demand, 0) for u in self.node_list
23
+ ] # node demands
24
+
25
+ self.edge_sources = [] # edge sources
26
+ self.edge_targets = [] # edge targets
27
+ if multigraph:
28
+ self.edge_keys = [] # edge keys
29
+ self.edge_indices = {} # edge indices
30
+ self.edge_capacities = [] # edge capacities
31
+ self.edge_weights = [] # edge weights
32
+
33
+ if not multigraph:
34
+ edges = G.edges(data=True)
35
+ else:
36
+ edges = G.edges(data=True, keys=True)
37
+
38
+ inf = float("inf")
39
+ edges = (e for e in edges if e[0] != e[1] and e[-1].get(capacity, inf) != 0)
40
+ for i, e in enumerate(edges):
41
+ self.edge_sources.append(self.node_indices[e[0]])
42
+ self.edge_targets.append(self.node_indices[e[1]])
43
+ if multigraph:
44
+ self.edge_keys.append(e[2])
45
+ self.edge_indices[e[:-1]] = i
46
+ self.edge_capacities.append(e[-1].get(capacity, inf))
47
+ self.edge_weights.append(e[-1].get(weight, 0))
48
+
49
+ # spanning tree specific data to be initialized
50
+
51
+ self.edge_count = None # number of edges
52
+ self.edge_flow = None # edge flows
53
+ self.node_potentials = None # node potentials
54
+ self.parent = None # parent nodes
55
+ self.parent_edge = None # edges to parents
56
+ self.subtree_size = None # subtree sizes
57
+ self.next_node_dft = None # next nodes in depth-first thread
58
+ self.prev_node_dft = None # previous nodes in depth-first thread
59
+ self.last_descendent_dft = None # last descendants in depth-first thread
60
+ self._spanning_tree_initialized = (
61
+ False # False until initialize_spanning_tree() is called
62
+ )
63
+
64
+ def initialize_spanning_tree(self, n, faux_inf):
65
+ self.edge_count = len(self.edge_indices) # number of edges
66
+ self.edge_flow = list(
67
+ chain(repeat(0, self.edge_count), (abs(d) for d in self.node_demands))
68
+ ) # edge flows
69
+ self.node_potentials = [
70
+ faux_inf if d <= 0 else -faux_inf for d in self.node_demands
71
+ ] # node potentials
72
+ self.parent = list(chain(repeat(-1, n), [None])) # parent nodes
73
+ self.parent_edge = list(
74
+ range(self.edge_count, self.edge_count + n)
75
+ ) # edges to parents
76
+ self.subtree_size = list(chain(repeat(1, n), [n + 1])) # subtree sizes
77
+ self.next_node_dft = list(
78
+ chain(range(1, n), [-1, 0])
79
+ ) # next nodes in depth-first thread
80
+ self.prev_node_dft = list(range(-1, n)) # previous nodes in depth-first thread
81
+ self.last_descendent_dft = list(
82
+ chain(range(n), [n - 1])
83
+ ) # last descendants in depth-first thread
84
+ self._spanning_tree_initialized = True # True only if all the assignments pass
85
+
86
+ def find_apex(self, p, q):
87
+ """
88
+ Find the lowest common ancestor of nodes p and q in the spanning tree.
89
+ """
90
+ size_p = self.subtree_size[p]
91
+ size_q = self.subtree_size[q]
92
+ while True:
93
+ while size_p < size_q:
94
+ p = self.parent[p]
95
+ size_p = self.subtree_size[p]
96
+ while size_p > size_q:
97
+ q = self.parent[q]
98
+ size_q = self.subtree_size[q]
99
+ if size_p == size_q:
100
+ if p != q:
101
+ p = self.parent[p]
102
+ size_p = self.subtree_size[p]
103
+ q = self.parent[q]
104
+ size_q = self.subtree_size[q]
105
+ else:
106
+ return p
107
+
108
+ def trace_path(self, p, w):
109
+ """
110
+ Returns the nodes and edges on the path from node p to its ancestor w.
111
+ """
112
+ Wn = [p]
113
+ We = []
114
+ while p != w:
115
+ We.append(self.parent_edge[p])
116
+ p = self.parent[p]
117
+ Wn.append(p)
118
+ return Wn, We
119
+
120
+ def find_cycle(self, i, p, q):
121
+ """
122
+ Returns the nodes and edges on the cycle containing edge i == (p, q)
123
+ when the latter is added to the spanning tree.
124
+
125
+ The cycle is oriented in the direction from p to q.
126
+ """
127
+ w = self.find_apex(p, q)
128
+ Wn, We = self.trace_path(p, w)
129
+ Wn.reverse()
130
+ We.reverse()
131
+ if We != [i]:
132
+ We.append(i)
133
+ WnR, WeR = self.trace_path(q, w)
134
+ del WnR[-1]
135
+ Wn += WnR
136
+ We += WeR
137
+ return Wn, We
138
+
139
+ def augment_flow(self, Wn, We, f):
140
+ """
141
+ Augment f units of flow along a cycle represented by Wn and We.
142
+ """
143
+ for i, p in zip(We, Wn):
144
+ if self.edge_sources[i] == p:
145
+ self.edge_flow[i] += f
146
+ else:
147
+ self.edge_flow[i] -= f
148
+
149
+ def trace_subtree(self, p):
150
+ """
151
+ Yield the nodes in the subtree rooted at a node p.
152
+ """
153
+ yield p
154
+ l = self.last_descendent_dft[p]
155
+ while p != l:
156
+ p = self.next_node_dft[p]
157
+ yield p
158
+
159
+ def remove_edge(self, s, t):
160
+ """
161
+ Remove an edge (s, t) where parent[t] == s from the spanning tree.
162
+ """
163
+ size_t = self.subtree_size[t]
164
+ prev_t = self.prev_node_dft[t]
165
+ last_t = self.last_descendent_dft[t]
166
+ next_last_t = self.next_node_dft[last_t]
167
+ # Remove (s, t).
168
+ self.parent[t] = None
169
+ self.parent_edge[t] = None
170
+ # Remove the subtree rooted at t from the depth-first thread.
171
+ self.next_node_dft[prev_t] = next_last_t
172
+ self.prev_node_dft[next_last_t] = prev_t
173
+ self.next_node_dft[last_t] = t
174
+ self.prev_node_dft[t] = last_t
175
+ # Update the subtree sizes and last descendants of the (old) ancestors
176
+ # of t.
177
+ while s is not None:
178
+ self.subtree_size[s] -= size_t
179
+ if self.last_descendent_dft[s] == last_t:
180
+ self.last_descendent_dft[s] = prev_t
181
+ s = self.parent[s]
182
+
183
+ def make_root(self, q):
184
+ """
185
+ Make a node q the root of its containing subtree.
186
+ """
187
+ ancestors = []
188
+ while q is not None:
189
+ ancestors.append(q)
190
+ q = self.parent[q]
191
+ ancestors.reverse()
192
+ for p, q in zip(ancestors, islice(ancestors, 1, None)):
193
+ size_p = self.subtree_size[p]
194
+ last_p = self.last_descendent_dft[p]
195
+ prev_q = self.prev_node_dft[q]
196
+ last_q = self.last_descendent_dft[q]
197
+ next_last_q = self.next_node_dft[last_q]
198
+ # Make p a child of q.
199
+ self.parent[p] = q
200
+ self.parent[q] = None
201
+ self.parent_edge[p] = self.parent_edge[q]
202
+ self.parent_edge[q] = None
203
+ self.subtree_size[p] = size_p - self.subtree_size[q]
204
+ self.subtree_size[q] = size_p
205
+ # Remove the subtree rooted at q from the depth-first thread.
206
+ self.next_node_dft[prev_q] = next_last_q
207
+ self.prev_node_dft[next_last_q] = prev_q
208
+ self.next_node_dft[last_q] = q
209
+ self.prev_node_dft[q] = last_q
210
+ if last_p == last_q:
211
+ self.last_descendent_dft[p] = prev_q
212
+ last_p = prev_q
213
+ # Add the remaining parts of the subtree rooted at p as a subtree
214
+ # of q in the depth-first thread.
215
+ self.prev_node_dft[p] = last_q
216
+ self.next_node_dft[last_q] = p
217
+ self.next_node_dft[last_p] = q
218
+ self.prev_node_dft[q] = last_p
219
+ self.last_descendent_dft[q] = last_p
220
+
221
+ def add_edge(self, i, p, q):
222
+ """
223
+ Add an edge (p, q) to the spanning tree where q is the root of a subtree.
224
+ """
225
+ last_p = self.last_descendent_dft[p]
226
+ next_last_p = self.next_node_dft[last_p]
227
+ size_q = self.subtree_size[q]
228
+ last_q = self.last_descendent_dft[q]
229
+ # Make q a child of p.
230
+ self.parent[q] = p
231
+ self.parent_edge[q] = i
232
+ # Insert the subtree rooted at q into the depth-first thread.
233
+ self.next_node_dft[last_p] = q
234
+ self.prev_node_dft[q] = last_p
235
+ self.prev_node_dft[next_last_p] = last_q
236
+ self.next_node_dft[last_q] = next_last_p
237
+ # Update the subtree sizes and last descendants of the (new) ancestors
238
+ # of q.
239
+ while p is not None:
240
+ self.subtree_size[p] += size_q
241
+ if self.last_descendent_dft[p] == last_p:
242
+ self.last_descendent_dft[p] = last_q
243
+ p = self.parent[p]
244
+
245
+ def update_potentials(self, i, p, q):
246
+ """
247
+ Update the potentials of the nodes in the subtree rooted at a node
248
+ q connected to its parent p by an edge i.
249
+ """
250
+ if q == self.edge_targets[i]:
251
+ d = self.node_potentials[p] - self.edge_weights[i] - self.node_potentials[q]
252
+ else:
253
+ d = self.node_potentials[p] + self.edge_weights[i] - self.node_potentials[q]
254
+ for q in self.trace_subtree(q):
255
+ self.node_potentials[q] += d
256
+
257
+ def reduced_cost(self, i):
258
+ """Returns the reduced cost of an edge i."""
259
+ c = (
260
+ self.edge_weights[i]
261
+ - self.node_potentials[self.edge_sources[i]]
262
+ + self.node_potentials[self.edge_targets[i]]
263
+ )
264
+ return c if self.edge_flow[i] == 0 else -c
265
+
266
+ def find_entering_edges(self):
267
+ """Yield entering edges until none can be found."""
268
+ if self.edge_count == 0:
269
+ return
270
+
271
+ # Entering edges are found by combining Dantzig's rule and Bland's
272
+ # rule. The edges are cyclically grouped into blocks of size B. Within
273
+ # each block, Dantzig's rule is applied to find an entering edge. The
274
+ # blocks to search is determined following Bland's rule.
275
+ B = int(ceil(sqrt(self.edge_count))) # pivot block size
276
+ M = (self.edge_count + B - 1) // B # number of blocks needed to cover all edges
277
+ m = 0 # number of consecutive blocks without eligible
278
+ # entering edges
279
+ f = 0 # first edge in block
280
+ while m < M:
281
+ # Determine the next block of edges.
282
+ l = f + B
283
+ if l <= self.edge_count:
284
+ edges = range(f, l)
285
+ else:
286
+ l -= self.edge_count
287
+ edges = chain(range(f, self.edge_count), range(l))
288
+ f = l
289
+ # Find the first edge with the lowest reduced cost.
290
+ i = min(edges, key=self.reduced_cost)
291
+ c = self.reduced_cost(i)
292
+ if c >= 0:
293
+ # No entering edge found in the current block.
294
+ m += 1
295
+ else:
296
+ # Entering edge found.
297
+ if self.edge_flow[i] == 0:
298
+ p = self.edge_sources[i]
299
+ q = self.edge_targets[i]
300
+ else:
301
+ p = self.edge_targets[i]
302
+ q = self.edge_sources[i]
303
+ yield i, p, q
304
+ m = 0
305
+ # All edges have nonnegative reduced costs. The current flow is
306
+ # optimal.
307
+
308
+ def residual_capacity(self, i, p):
309
+ """Returns the residual capacity of an edge i in the direction away
310
+ from its endpoint p.
311
+ """
312
+ return (
313
+ self.edge_capacities[i] - self.edge_flow[i]
314
+ if self.edge_sources[i] == p
315
+ else self.edge_flow[i]
316
+ )
317
+
318
+ def find_leaving_edge(self, Wn, We):
319
+ """Returns the leaving edge in a cycle represented by Wn and We."""
320
+ j, s = min(
321
+ zip(reversed(We), reversed(Wn)),
322
+ key=lambda i_p: self.residual_capacity(*i_p),
323
+ )
324
+ t = self.edge_targets[j] if self.edge_sources[j] == s else self.edge_sources[j]
325
+ return j, s, t
326
+
327
+
328
+ @not_implemented_for("undirected")
329
+ @nx._dispatchable(
330
+ node_attrs="demand", edge_attrs={"capacity": float("inf"), "weight": 0}
331
+ )
332
+ def network_simplex(G, demand="demand", capacity="capacity", weight="weight"):
333
+ r"""Find a minimum cost flow satisfying all demands in digraph G.
334
+
335
+ This is a primal network simplex algorithm that uses the leaving
336
+ arc rule to prevent cycling.
337
+
338
+ G is a digraph with edge costs and capacities and in which nodes
339
+ have demand, i.e., they want to send or receive some amount of
340
+ flow. A negative demand means that the node wants to send flow, a
341
+ positive demand means that the node want to receive flow. A flow on
342
+ the digraph G satisfies all demand if the net flow into each node
343
+ is equal to the demand of that node.
344
+
345
+ Parameters
346
+ ----------
347
+ G : NetworkX graph
348
+ DiGraph on which a minimum cost flow satisfying all demands is
349
+ to be found.
350
+
351
+ demand : string
352
+ Nodes of the graph G are expected to have an attribute demand
353
+ that indicates how much flow a node wants to send (negative
354
+ demand) or receive (positive demand). Note that the sum of the
355
+ demands should be 0 otherwise the problem in not feasible. If
356
+ this attribute is not present, a node is considered to have 0
357
+ demand. Default value: 'demand'.
358
+
359
+ capacity : string
360
+ Edges of the graph G are expected to have an attribute capacity
361
+ that indicates how much flow the edge can support. If this
362
+ attribute is not present, the edge is considered to have
363
+ infinite capacity. Default value: 'capacity'.
364
+
365
+ weight : string
366
+ Edges of the graph G are expected to have an attribute weight
367
+ that indicates the cost incurred by sending one unit of flow on
368
+ that edge. If not present, the weight is considered to be 0.
369
+ Default value: 'weight'.
370
+
371
+ Returns
372
+ -------
373
+ flowCost : integer, float
374
+ Cost of a minimum cost flow satisfying all demands.
375
+
376
+ flowDict : dictionary
377
+ Dictionary of dictionaries keyed by nodes such that
378
+ flowDict[u][v] is the flow edge (u, v).
379
+
380
+ Raises
381
+ ------
382
+ NetworkXError
383
+ This exception is raised if the input graph is not directed or
384
+ not connected.
385
+
386
+ NetworkXUnfeasible
387
+ This exception is raised in the following situations:
388
+
389
+ * The sum of the demands is not zero. Then, there is no
390
+ flow satisfying all demands.
391
+ * There is no flow satisfying all demand.
392
+
393
+ NetworkXUnbounded
394
+ This exception is raised if the digraph G has a cycle of
395
+ negative cost and infinite capacity. Then, the cost of a flow
396
+ satisfying all demands is unbounded below.
397
+
398
+ Notes
399
+ -----
400
+ This algorithm is not guaranteed to work if edge weights or demands
401
+ are floating point numbers (overflows and roundoff errors can
402
+ cause problems). As a workaround you can use integer numbers by
403
+ multiplying the relevant edge attributes by a convenient
404
+ constant factor (eg 100).
405
+
406
+ See also
407
+ --------
408
+ cost_of_flow, max_flow_min_cost, min_cost_flow, min_cost_flow_cost
409
+
410
+ Examples
411
+ --------
412
+ A simple example of a min cost flow problem.
413
+
414
+ >>> G = nx.DiGraph()
415
+ >>> G.add_node("a", demand=-5)
416
+ >>> G.add_node("d", demand=5)
417
+ >>> G.add_edge("a", "b", weight=3, capacity=4)
418
+ >>> G.add_edge("a", "c", weight=6, capacity=10)
419
+ >>> G.add_edge("b", "d", weight=1, capacity=9)
420
+ >>> G.add_edge("c", "d", weight=2, capacity=5)
421
+ >>> flowCost, flowDict = nx.network_simplex(G)
422
+ >>> flowCost
423
+ 24
424
+ >>> flowDict
425
+ {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}
426
+
427
+ The mincost flow algorithm can also be used to solve shortest path
428
+ problems. To find the shortest path between two nodes u and v,
429
+ give all edges an infinite capacity, give node u a demand of -1 and
430
+ node v a demand a 1. Then run the network simplex. The value of a
431
+ min cost flow will be the distance between u and v and edges
432
+ carrying positive flow will indicate the path.
433
+
434
+ >>> G = nx.DiGraph()
435
+ >>> G.add_weighted_edges_from(
436
+ ... [
437
+ ... ("s", "u", 10),
438
+ ... ("s", "x", 5),
439
+ ... ("u", "v", 1),
440
+ ... ("u", "x", 2),
441
+ ... ("v", "y", 1),
442
+ ... ("x", "u", 3),
443
+ ... ("x", "v", 5),
444
+ ... ("x", "y", 2),
445
+ ... ("y", "s", 7),
446
+ ... ("y", "v", 6),
447
+ ... ]
448
+ ... )
449
+ >>> G.add_node("s", demand=-1)
450
+ >>> G.add_node("v", demand=1)
451
+ >>> flowCost, flowDict = nx.network_simplex(G)
452
+ >>> flowCost == nx.shortest_path_length(G, "s", "v", weight="weight")
453
+ True
454
+ >>> sorted([(u, v) for u in flowDict for v in flowDict[u] if flowDict[u][v] > 0])
455
+ [('s', 'x'), ('u', 'v'), ('x', 'u')]
456
+ >>> nx.shortest_path(G, "s", "v", weight="weight")
457
+ ['s', 'x', 'u', 'v']
458
+
459
+ It is possible to change the name of the attributes used for the
460
+ algorithm.
461
+
462
+ >>> G = nx.DiGraph()
463
+ >>> G.add_node("p", spam=-4)
464
+ >>> G.add_node("q", spam=2)
465
+ >>> G.add_node("a", spam=-2)
466
+ >>> G.add_node("d", spam=-1)
467
+ >>> G.add_node("t", spam=2)
468
+ >>> G.add_node("w", spam=3)
469
+ >>> G.add_edge("p", "q", cost=7, vacancies=5)
470
+ >>> G.add_edge("p", "a", cost=1, vacancies=4)
471
+ >>> G.add_edge("q", "d", cost=2, vacancies=3)
472
+ >>> G.add_edge("t", "q", cost=1, vacancies=2)
473
+ >>> G.add_edge("a", "t", cost=2, vacancies=4)
474
+ >>> G.add_edge("d", "w", cost=3, vacancies=4)
475
+ >>> G.add_edge("t", "w", cost=4, vacancies=1)
476
+ >>> flowCost, flowDict = nx.network_simplex(
477
+ ... G, demand="spam", capacity="vacancies", weight="cost"
478
+ ... )
479
+ >>> flowCost
480
+ 37
481
+ >>> flowDict
482
+ {'p': {'q': 2, 'a': 2}, 'q': {'d': 1}, 'a': {'t': 4}, 'd': {'w': 2}, 't': {'q': 1, 'w': 1}, 'w': {}}
483
+
484
+ References
485
+ ----------
486
+ .. [1] Z. Kiraly, P. Kovacs.
487
+ Efficient implementation of minimum-cost flow algorithms.
488
+ Acta Universitatis Sapientiae, Informatica 4(1):67--118. 2012.
489
+ .. [2] R. Barr, F. Glover, D. Klingman.
490
+ Enhancement of spanning tree labeling procedures for network
491
+ optimization.
492
+ INFOR 17(1):16--34. 1979.
493
+ """
494
+ ###########################################################################
495
+ # Problem essentials extraction and sanity check
496
+ ###########################################################################
497
+
498
+ if len(G) == 0:
499
+ raise nx.NetworkXError("graph has no nodes")
500
+
501
+ multigraph = G.is_multigraph()
502
+
503
+ # extracting data essential to problem
504
+ DEAF = _DataEssentialsAndFunctions(
505
+ G, multigraph, demand=demand, capacity=capacity, weight=weight
506
+ )
507
+
508
+ ###########################################################################
509
+ # Quick Error Detection
510
+ ###########################################################################
511
+
512
+ inf = float("inf")
513
+ for u, d in zip(DEAF.node_list, DEAF.node_demands):
514
+ if abs(d) == inf:
515
+ raise nx.NetworkXError(f"node {u!r} has infinite demand")
516
+ for e, w in zip(DEAF.edge_indices, DEAF.edge_weights):
517
+ if abs(w) == inf:
518
+ raise nx.NetworkXError(f"edge {e!r} has infinite weight")
519
+ if not multigraph:
520
+ edges = nx.selfloop_edges(G, data=True)
521
+ else:
522
+ edges = nx.selfloop_edges(G, data=True, keys=True)
523
+ for e in edges:
524
+ if abs(e[-1].get(weight, 0)) == inf:
525
+ raise nx.NetworkXError(f"edge {e[:-1]!r} has infinite weight")
526
+
527
+ ###########################################################################
528
+ # Quick Infeasibility Detection
529
+ ###########################################################################
530
+
531
+ if sum(DEAF.node_demands) != 0:
532
+ raise nx.NetworkXUnfeasible("total node demand is not zero")
533
+ for e, c in zip(DEAF.edge_indices, DEAF.edge_capacities):
534
+ if c < 0:
535
+ raise nx.NetworkXUnfeasible(f"edge {e!r} has negative capacity")
536
+ if not multigraph:
537
+ edges = nx.selfloop_edges(G, data=True)
538
+ else:
539
+ edges = nx.selfloop_edges(G, data=True, keys=True)
540
+ for e in edges:
541
+ if e[-1].get(capacity, inf) < 0:
542
+ raise nx.NetworkXUnfeasible(f"edge {e[:-1]!r} has negative capacity")
543
+
544
+ ###########################################################################
545
+ # Initialization
546
+ ###########################################################################
547
+
548
+ # Add a dummy node -1 and connect all existing nodes to it with infinite-
549
+ # capacity dummy edges. Node -1 will serve as the root of the
550
+ # spanning tree of the network simplex method. The new edges will used to
551
+ # trivially satisfy the node demands and create an initial strongly
552
+ # feasible spanning tree.
553
+ for i, d in enumerate(DEAF.node_demands):
554
+ # Must be greater-than here. Zero-demand nodes must have
555
+ # edges pointing towards the root to ensure strong feasibility.
556
+ if d > 0:
557
+ DEAF.edge_sources.append(-1)
558
+ DEAF.edge_targets.append(i)
559
+ else:
560
+ DEAF.edge_sources.append(i)
561
+ DEAF.edge_targets.append(-1)
562
+ faux_inf = (
563
+ 3
564
+ * max(
565
+ chain(
566
+ [
567
+ sum(c for c in DEAF.edge_capacities if c < inf),
568
+ sum(abs(w) for w in DEAF.edge_weights),
569
+ ],
570
+ (abs(d) for d in DEAF.node_demands),
571
+ )
572
+ )
573
+ or 1
574
+ )
575
+
576
+ n = len(DEAF.node_list) # number of nodes
577
+ DEAF.edge_weights.extend(repeat(faux_inf, n))
578
+ DEAF.edge_capacities.extend(repeat(faux_inf, n))
579
+
580
+ # Construct the initial spanning tree.
581
+ DEAF.initialize_spanning_tree(n, faux_inf)
582
+
583
+ ###########################################################################
584
+ # Pivot loop
585
+ ###########################################################################
586
+
587
+ for i, p, q in DEAF.find_entering_edges():
588
+ Wn, We = DEAF.find_cycle(i, p, q)
589
+ j, s, t = DEAF.find_leaving_edge(Wn, We)
590
+ DEAF.augment_flow(Wn, We, DEAF.residual_capacity(j, s))
591
+ # Do nothing more if the entering edge is the same as the leaving edge.
592
+ if i != j:
593
+ if DEAF.parent[t] != s:
594
+ # Ensure that s is the parent of t.
595
+ s, t = t, s
596
+ if We.index(i) > We.index(j):
597
+ # Ensure that q is in the subtree rooted at t.
598
+ p, q = q, p
599
+ DEAF.remove_edge(s, t)
600
+ DEAF.make_root(q)
601
+ DEAF.add_edge(i, p, q)
602
+ DEAF.update_potentials(i, p, q)
603
+
604
+ ###########################################################################
605
+ # Infeasibility and unboundedness detection
606
+ ###########################################################################
607
+
608
+ if any(DEAF.edge_flow[i] != 0 for i in range(-n, 0)):
609
+ raise nx.NetworkXUnfeasible("no flow satisfies all node demands")
610
+
611
+ if any(DEAF.edge_flow[i] * 2 >= faux_inf for i in range(DEAF.edge_count)) or any(
612
+ e[-1].get(capacity, inf) == inf and e[-1].get(weight, 0) < 0
613
+ for e in nx.selfloop_edges(G, data=True)
614
+ ):
615
+ raise nx.NetworkXUnbounded("negative cycle with infinite capacity found")
616
+
617
+ ###########################################################################
618
+ # Flow cost calculation and flow dict construction
619
+ ###########################################################################
620
+
621
+ del DEAF.edge_flow[DEAF.edge_count :]
622
+ flow_cost = sum(w * x for w, x in zip(DEAF.edge_weights, DEAF.edge_flow))
623
+ flow_dict = {n: {} for n in DEAF.node_list}
624
+
625
+ def add_entry(e):
626
+ """Add a flow dict entry."""
627
+ d = flow_dict[e[0]]
628
+ for k in e[1:-2]:
629
+ try:
630
+ d = d[k]
631
+ except KeyError:
632
+ t = {}
633
+ d[k] = t
634
+ d = t
635
+ d[e[-2]] = e[-1]
636
+
637
+ DEAF.edge_sources = (
638
+ DEAF.node_list[s] for s in DEAF.edge_sources
639
+ ) # Use original nodes.
640
+ DEAF.edge_targets = (
641
+ DEAF.node_list[t] for t in DEAF.edge_targets
642
+ ) # Use original nodes.
643
+ if not multigraph:
644
+ for e in zip(DEAF.edge_sources, DEAF.edge_targets, DEAF.edge_flow):
645
+ add_entry(e)
646
+ edges = G.edges(data=True)
647
+ else:
648
+ for e in zip(
649
+ DEAF.edge_sources, DEAF.edge_targets, DEAF.edge_keys, DEAF.edge_flow
650
+ ):
651
+ add_entry(e)
652
+ edges = G.edges(data=True, keys=True)
653
+ for e in edges:
654
+ if e[0] != e[1]:
655
+ if e[-1].get(capacity, inf) == 0:
656
+ add_entry(e[:-1] + (0,))
657
+ else:
658
+ w = e[-1].get(weight, 0)
659
+ if w >= 0:
660
+ add_entry(e[:-1] + (0,))
661
+ else:
662
+ c = e[-1][capacity]
663
+ flow_cost += w * c
664
+ add_entry(e[:-1] + (c,))
665
+
666
+ return flow_cost, flow_dict
janus/lib/python3.10/site-packages/networkx/algorithms/flow/preflowpush.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Highest-label preflow-push algorithm for maximum flow problems.
3
+ """
4
+
5
+ from collections import deque
6
+ from itertools import islice
7
+
8
+ import networkx as nx
9
+
10
+ from ...utils import arbitrary_element
11
+ from .utils import (
12
+ CurrentEdge,
13
+ GlobalRelabelThreshold,
14
+ Level,
15
+ build_residual_network,
16
+ detect_unboundedness,
17
+ )
18
+
19
+ __all__ = ["preflow_push"]
20
+
21
+
22
+ def preflow_push_impl(G, s, t, capacity, residual, global_relabel_freq, value_only):
23
+ """Implementation of the highest-label preflow-push algorithm."""
24
+ if s not in G:
25
+ raise nx.NetworkXError(f"node {str(s)} not in graph")
26
+ if t not in G:
27
+ raise nx.NetworkXError(f"node {str(t)} not in graph")
28
+ if s == t:
29
+ raise nx.NetworkXError("source and sink are the same node")
30
+
31
+ if global_relabel_freq is None:
32
+ global_relabel_freq = 0
33
+ if global_relabel_freq < 0:
34
+ raise nx.NetworkXError("global_relabel_freq must be nonnegative.")
35
+
36
+ if residual is None:
37
+ R = build_residual_network(G, capacity)
38
+ else:
39
+ R = residual
40
+
41
+ detect_unboundedness(R, s, t)
42
+
43
+ R_nodes = R.nodes
44
+ R_pred = R.pred
45
+ R_succ = R.succ
46
+
47
+ # Initialize/reset the residual network.
48
+ for u in R:
49
+ R_nodes[u]["excess"] = 0
50
+ for e in R_succ[u].values():
51
+ e["flow"] = 0
52
+
53
+ def reverse_bfs(src):
54
+ """Perform a reverse breadth-first search from src in the residual
55
+ network.
56
+ """
57
+ heights = {src: 0}
58
+ q = deque([(src, 0)])
59
+ while q:
60
+ u, height = q.popleft()
61
+ height += 1
62
+ for v, attr in R_pred[u].items():
63
+ if v not in heights and attr["flow"] < attr["capacity"]:
64
+ heights[v] = height
65
+ q.append((v, height))
66
+ return heights
67
+
68
+ # Initialize heights of the nodes.
69
+ heights = reverse_bfs(t)
70
+
71
+ if s not in heights:
72
+ # t is not reachable from s in the residual network. The maximum flow
73
+ # must be zero.
74
+ R.graph["flow_value"] = 0
75
+ return R
76
+
77
+ n = len(R)
78
+ # max_height represents the height of the highest level below level n with
79
+ # at least one active node.
80
+ max_height = max(heights[u] for u in heights if u != s)
81
+ heights[s] = n
82
+
83
+ grt = GlobalRelabelThreshold(n, R.size(), global_relabel_freq)
84
+
85
+ # Initialize heights and 'current edge' data structures of the nodes.
86
+ for u in R:
87
+ R_nodes[u]["height"] = heights[u] if u in heights else n + 1
88
+ R_nodes[u]["curr_edge"] = CurrentEdge(R_succ[u])
89
+
90
+ def push(u, v, flow):
91
+ """Push flow units of flow from u to v."""
92
+ R_succ[u][v]["flow"] += flow
93
+ R_succ[v][u]["flow"] -= flow
94
+ R_nodes[u]["excess"] -= flow
95
+ R_nodes[v]["excess"] += flow
96
+
97
+ # The maximum flow must be nonzero now. Initialize the preflow by
98
+ # saturating all edges emanating from s.
99
+ for u, attr in R_succ[s].items():
100
+ flow = attr["capacity"]
101
+ if flow > 0:
102
+ push(s, u, flow)
103
+
104
+ # Partition nodes into levels.
105
+ levels = [Level() for i in range(2 * n)]
106
+ for u in R:
107
+ if u != s and u != t:
108
+ level = levels[R_nodes[u]["height"]]
109
+ if R_nodes[u]["excess"] > 0:
110
+ level.active.add(u)
111
+ else:
112
+ level.inactive.add(u)
113
+
114
+ def activate(v):
115
+ """Move a node from the inactive set to the active set of its level."""
116
+ if v != s and v != t:
117
+ level = levels[R_nodes[v]["height"]]
118
+ if v in level.inactive:
119
+ level.inactive.remove(v)
120
+ level.active.add(v)
121
+
122
+ def relabel(u):
123
+ """Relabel a node to create an admissible edge."""
124
+ grt.add_work(len(R_succ[u]))
125
+ return (
126
+ min(
127
+ R_nodes[v]["height"]
128
+ for v, attr in R_succ[u].items()
129
+ if attr["flow"] < attr["capacity"]
130
+ )
131
+ + 1
132
+ )
133
+
134
+ def discharge(u, is_phase1):
135
+ """Discharge a node until it becomes inactive or, during phase 1 (see
136
+ below), its height reaches at least n. The node is known to have the
137
+ largest height among active nodes.
138
+ """
139
+ height = R_nodes[u]["height"]
140
+ curr_edge = R_nodes[u]["curr_edge"]
141
+ # next_height represents the next height to examine after discharging
142
+ # the current node. During phase 1, it is capped to below n.
143
+ next_height = height
144
+ levels[height].active.remove(u)
145
+ while True:
146
+ v, attr = curr_edge.get()
147
+ if height == R_nodes[v]["height"] + 1 and attr["flow"] < attr["capacity"]:
148
+ flow = min(R_nodes[u]["excess"], attr["capacity"] - attr["flow"])
149
+ push(u, v, flow)
150
+ activate(v)
151
+ if R_nodes[u]["excess"] == 0:
152
+ # The node has become inactive.
153
+ levels[height].inactive.add(u)
154
+ break
155
+ try:
156
+ curr_edge.move_to_next()
157
+ except StopIteration:
158
+ # We have run off the end of the adjacency list, and there can
159
+ # be no more admissible edges. Relabel the node to create one.
160
+ height = relabel(u)
161
+ if is_phase1 and height >= n - 1:
162
+ # Although the node is still active, with a height at least
163
+ # n - 1, it is now known to be on the s side of the minimum
164
+ # s-t cut. Stop processing it until phase 2.
165
+ levels[height].active.add(u)
166
+ break
167
+ # The first relabel operation after global relabeling may not
168
+ # increase the height of the node since the 'current edge' data
169
+ # structure is not rewound. Use height instead of (height - 1)
170
+ # in case other active nodes at the same level are missed.
171
+ next_height = height
172
+ R_nodes[u]["height"] = height
173
+ return next_height
174
+
175
+ def gap_heuristic(height):
176
+ """Apply the gap heuristic."""
177
+ # Move all nodes at levels (height + 1) to max_height to level n + 1.
178
+ for level in islice(levels, height + 1, max_height + 1):
179
+ for u in level.active:
180
+ R_nodes[u]["height"] = n + 1
181
+ for u in level.inactive:
182
+ R_nodes[u]["height"] = n + 1
183
+ levels[n + 1].active.update(level.active)
184
+ level.active.clear()
185
+ levels[n + 1].inactive.update(level.inactive)
186
+ level.inactive.clear()
187
+
188
+ def global_relabel(from_sink):
189
+ """Apply the global relabeling heuristic."""
190
+ src = t if from_sink else s
191
+ heights = reverse_bfs(src)
192
+ if not from_sink:
193
+ # s must be reachable from t. Remove t explicitly.
194
+ del heights[t]
195
+ max_height = max(heights.values())
196
+ if from_sink:
197
+ # Also mark nodes from which t is unreachable for relabeling. This
198
+ # serves the same purpose as the gap heuristic.
199
+ for u in R:
200
+ if u not in heights and R_nodes[u]["height"] < n:
201
+ heights[u] = n + 1
202
+ else:
203
+ # Shift the computed heights because the height of s is n.
204
+ for u in heights:
205
+ heights[u] += n
206
+ max_height += n
207
+ del heights[src]
208
+ for u, new_height in heights.items():
209
+ old_height = R_nodes[u]["height"]
210
+ if new_height != old_height:
211
+ if u in levels[old_height].active:
212
+ levels[old_height].active.remove(u)
213
+ levels[new_height].active.add(u)
214
+ else:
215
+ levels[old_height].inactive.remove(u)
216
+ levels[new_height].inactive.add(u)
217
+ R_nodes[u]["height"] = new_height
218
+ return max_height
219
+
220
+ # Phase 1: Find the maximum preflow by pushing as much flow as possible to
221
+ # t.
222
+
223
+ height = max_height
224
+ while height > 0:
225
+ # Discharge active nodes in the current level.
226
+ while True:
227
+ level = levels[height]
228
+ if not level.active:
229
+ # All active nodes in the current level have been discharged.
230
+ # Move to the next lower level.
231
+ height -= 1
232
+ break
233
+ # Record the old height and level for the gap heuristic.
234
+ old_height = height
235
+ old_level = level
236
+ u = arbitrary_element(level.active)
237
+ height = discharge(u, True)
238
+ if grt.is_reached():
239
+ # Global relabeling heuristic: Recompute the exact heights of
240
+ # all nodes.
241
+ height = global_relabel(True)
242
+ max_height = height
243
+ grt.clear_work()
244
+ elif not old_level.active and not old_level.inactive:
245
+ # Gap heuristic: If the level at old_height is empty (a 'gap'),
246
+ # a minimum cut has been identified. All nodes with heights
247
+ # above old_height can have their heights set to n + 1 and not
248
+ # be further processed before a maximum preflow is found.
249
+ gap_heuristic(old_height)
250
+ height = old_height - 1
251
+ max_height = height
252
+ else:
253
+ # Update the height of the highest level with at least one
254
+ # active node.
255
+ max_height = max(max_height, height)
256
+
257
+ # A maximum preflow has been found. The excess at t is the maximum flow
258
+ # value.
259
+ if value_only:
260
+ R.graph["flow_value"] = R_nodes[t]["excess"]
261
+ return R
262
+
263
+ # Phase 2: Convert the maximum preflow into a maximum flow by returning the
264
+ # excess to s.
265
+
266
+ # Relabel all nodes so that they have accurate heights.
267
+ height = global_relabel(False)
268
+ grt.clear_work()
269
+
270
+ # Continue to discharge the active nodes.
271
+ while height > n:
272
+ # Discharge active nodes in the current level.
273
+ while True:
274
+ level = levels[height]
275
+ if not level.active:
276
+ # All active nodes in the current level have been discharged.
277
+ # Move to the next lower level.
278
+ height -= 1
279
+ break
280
+ u = arbitrary_element(level.active)
281
+ height = discharge(u, False)
282
+ if grt.is_reached():
283
+ # Global relabeling heuristic.
284
+ height = global_relabel(False)
285
+ grt.clear_work()
286
+
287
+ R.graph["flow_value"] = R_nodes[t]["excess"]
288
+ return R
289
+
290
+
291
+ @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
292
+ def preflow_push(
293
+ G, s, t, capacity="capacity", residual=None, global_relabel_freq=1, value_only=False
294
+ ):
295
+ r"""Find a maximum single-commodity flow using the highest-label
296
+ preflow-push algorithm.
297
+
298
+ This function returns the residual network resulting after computing
299
+ the maximum flow. See below for details about the conventions
300
+ NetworkX uses for defining residual networks.
301
+
302
+ This algorithm has a running time of $O(n^2 \sqrt{m})$ for $n$ nodes and
303
+ $m$ edges.
304
+
305
+
306
+ Parameters
307
+ ----------
308
+ G : NetworkX graph
309
+ Edges of the graph are expected to have an attribute called
310
+ 'capacity'. If this attribute is not present, the edge is
311
+ considered to have infinite capacity.
312
+
313
+ s : node
314
+ Source node for the flow.
315
+
316
+ t : node
317
+ Sink node for the flow.
318
+
319
+ capacity : string
320
+ Edges of the graph G are expected to have an attribute capacity
321
+ that indicates how much flow the edge can support. If this
322
+ attribute is not present, the edge is considered to have
323
+ infinite capacity. Default value: 'capacity'.
324
+
325
+ residual : NetworkX graph
326
+ Residual network on which the algorithm is to be executed. If None, a
327
+ new residual network is created. Default value: None.
328
+
329
+ global_relabel_freq : integer, float
330
+ Relative frequency of applying the global relabeling heuristic to speed
331
+ up the algorithm. If it is None, the heuristic is disabled. Default
332
+ value: 1.
333
+
334
+ value_only : bool
335
+ If False, compute a maximum flow; otherwise, compute a maximum preflow
336
+ which is enough for computing the maximum flow value. Default value:
337
+ False.
338
+
339
+ Returns
340
+ -------
341
+ R : NetworkX DiGraph
342
+ Residual network after computing the maximum flow.
343
+
344
+ Raises
345
+ ------
346
+ NetworkXError
347
+ The algorithm does not support MultiGraph and MultiDiGraph. If
348
+ the input graph is an instance of one of these two classes, a
349
+ NetworkXError is raised.
350
+
351
+ NetworkXUnbounded
352
+ If the graph has a path of infinite capacity, the value of a
353
+ feasible flow on the graph is unbounded above and the function
354
+ raises a NetworkXUnbounded.
355
+
356
+ See also
357
+ --------
358
+ :meth:`maximum_flow`
359
+ :meth:`minimum_cut`
360
+ :meth:`edmonds_karp`
361
+ :meth:`shortest_augmenting_path`
362
+
363
+ Notes
364
+ -----
365
+ The residual network :samp:`R` from an input graph :samp:`G` has the
366
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
367
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
368
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
369
+ in :samp:`G`. For each node :samp:`u` in :samp:`R`,
370
+ :samp:`R.nodes[u]['excess']` represents the difference between flow into
371
+ :samp:`u` and flow out of :samp:`u`.
372
+
373
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
374
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
375
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
376
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
377
+ that does not affect the solution of the problem. This value is stored in
378
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
379
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
380
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
381
+
382
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
383
+ stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
384
+ only edges :samp:`(u, v)` such that
385
+ :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
386
+ :samp:`s`-:samp:`t` cut.
387
+
388
+ Examples
389
+ --------
390
+ >>> from networkx.algorithms.flow import preflow_push
391
+
392
+ The functions that implement flow algorithms and output a residual
393
+ network, such as this one, are not imported to the base NetworkX
394
+ namespace, so you have to explicitly import them from the flow package.
395
+
396
+ >>> G = nx.DiGraph()
397
+ >>> G.add_edge("x", "a", capacity=3.0)
398
+ >>> G.add_edge("x", "b", capacity=1.0)
399
+ >>> G.add_edge("a", "c", capacity=3.0)
400
+ >>> G.add_edge("b", "c", capacity=5.0)
401
+ >>> G.add_edge("b", "d", capacity=4.0)
402
+ >>> G.add_edge("d", "e", capacity=2.0)
403
+ >>> G.add_edge("c", "y", capacity=2.0)
404
+ >>> G.add_edge("e", "y", capacity=3.0)
405
+ >>> R = preflow_push(G, "x", "y")
406
+ >>> flow_value = nx.maximum_flow_value(G, "x", "y")
407
+ >>> flow_value == R.graph["flow_value"]
408
+ True
409
+ >>> # preflow_push also stores the maximum flow value
410
+ >>> # in the excess attribute of the sink node t
411
+ >>> flow_value == R.nodes["y"]["excess"]
412
+ True
413
+ >>> # For some problems, you might only want to compute a
414
+ >>> # maximum preflow.
415
+ >>> R = preflow_push(G, "x", "y", value_only=True)
416
+ >>> flow_value == R.graph["flow_value"]
417
+ True
418
+ >>> flow_value == R.nodes["y"]["excess"]
419
+ True
420
+
421
+ """
422
+ R = preflow_push_impl(G, s, t, capacity, residual, global_relabel_freq, value_only)
423
+ R.graph["algorithm"] = "preflow_push"
424
+ nx._clear_cache(R)
425
+ return R
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (181 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_maxflow.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_mincost.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_networksimplex.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_gomory_hu.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.flow import (
7
+ boykov_kolmogorov,
8
+ dinitz,
9
+ edmonds_karp,
10
+ preflow_push,
11
+ shortest_augmenting_path,
12
+ )
13
+
14
+ flow_funcs = [
15
+ boykov_kolmogorov,
16
+ dinitz,
17
+ edmonds_karp,
18
+ preflow_push,
19
+ shortest_augmenting_path,
20
+ ]
21
+
22
+
23
+ class TestGomoryHuTree:
24
+ def minimum_edge_weight(self, T, u, v):
25
+ path = nx.shortest_path(T, u, v, weight="weight")
26
+ return min((T[u][v]["weight"], (u, v)) for (u, v) in zip(path, path[1:]))
27
+
28
+ def compute_cutset(self, G, T_orig, edge):
29
+ T = T_orig.copy()
30
+ T.remove_edge(*edge)
31
+ U, V = list(nx.connected_components(T))
32
+ cutset = set()
33
+ for x, nbrs in ((n, G[n]) for n in U):
34
+ cutset.update((x, y) for y in nbrs if y in V)
35
+ return cutset
36
+
37
+ def test_default_flow_function_karate_club_graph(self):
38
+ G = nx.karate_club_graph()
39
+ nx.set_edge_attributes(G, 1, "capacity")
40
+ T = nx.gomory_hu_tree(G)
41
+ assert nx.is_tree(T)
42
+ for u, v in combinations(G, 2):
43
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
44
+ assert nx.minimum_cut_value(G, u, v) == cut_value
45
+
46
+ def test_karate_club_graph(self):
47
+ G = nx.karate_club_graph()
48
+ nx.set_edge_attributes(G, 1, "capacity")
49
+ for flow_func in flow_funcs:
50
+ T = nx.gomory_hu_tree(G, flow_func=flow_func)
51
+ assert nx.is_tree(T)
52
+ for u, v in combinations(G, 2):
53
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
54
+ assert nx.minimum_cut_value(G, u, v) == cut_value
55
+
56
+ def test_davis_southern_women_graph(self):
57
+ G = nx.davis_southern_women_graph()
58
+ nx.set_edge_attributes(G, 1, "capacity")
59
+ for flow_func in flow_funcs:
60
+ T = nx.gomory_hu_tree(G, flow_func=flow_func)
61
+ assert nx.is_tree(T)
62
+ for u, v in combinations(G, 2):
63
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
64
+ assert nx.minimum_cut_value(G, u, v) == cut_value
65
+
66
+ def test_florentine_families_graph(self):
67
+ G = nx.florentine_families_graph()
68
+ nx.set_edge_attributes(G, 1, "capacity")
69
+ for flow_func in flow_funcs:
70
+ T = nx.gomory_hu_tree(G, flow_func=flow_func)
71
+ assert nx.is_tree(T)
72
+ for u, v in combinations(G, 2):
73
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
74
+ assert nx.minimum_cut_value(G, u, v) == cut_value
75
+
76
+ @pytest.mark.slow
77
+ def test_les_miserables_graph_cutset(self):
78
+ G = nx.les_miserables_graph()
79
+ nx.set_edge_attributes(G, 1, "capacity")
80
+ for flow_func in flow_funcs:
81
+ T = nx.gomory_hu_tree(G, flow_func=flow_func)
82
+ assert nx.is_tree(T)
83
+ for u, v in combinations(G, 2):
84
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
85
+ assert nx.minimum_cut_value(G, u, v) == cut_value
86
+
87
+ def test_karate_club_graph_cutset(self):
88
+ G = nx.karate_club_graph()
89
+ nx.set_edge_attributes(G, 1, "capacity")
90
+ T = nx.gomory_hu_tree(G)
91
+ assert nx.is_tree(T)
92
+ u, v = 0, 33
93
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
94
+ cutset = self.compute_cutset(G, T, edge)
95
+ assert cut_value == len(cutset)
96
+
97
+ def test_wikipedia_example(self):
98
+ # Example from https://en.wikipedia.org/wiki/Gomory%E2%80%93Hu_tree
99
+ G = nx.Graph()
100
+ G.add_weighted_edges_from(
101
+ (
102
+ (0, 1, 1),
103
+ (0, 2, 7),
104
+ (1, 2, 1),
105
+ (1, 3, 3),
106
+ (1, 4, 2),
107
+ (2, 4, 4),
108
+ (3, 4, 1),
109
+ (3, 5, 6),
110
+ (4, 5, 2),
111
+ )
112
+ )
113
+ for flow_func in flow_funcs:
114
+ T = nx.gomory_hu_tree(G, capacity="weight", flow_func=flow_func)
115
+ assert nx.is_tree(T)
116
+ for u, v in combinations(G, 2):
117
+ cut_value, edge = self.minimum_edge_weight(T, u, v)
118
+ assert nx.minimum_cut_value(G, u, v, capacity="weight") == cut_value
119
+
120
+ def test_directed_raises(self):
121
+ with pytest.raises(nx.NetworkXNotImplemented):
122
+ G = nx.DiGraph()
123
+ T = nx.gomory_hu_tree(G)
124
+
125
+ def test_empty_raises(self):
126
+ with pytest.raises(nx.NetworkXError):
127
+ G = nx.empty_graph()
128
+ T = nx.gomory_hu_tree(G)
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_maxflow.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Maximum flow algorithms test suite."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.flow import (
7
+ boykov_kolmogorov,
8
+ build_flow_dict,
9
+ build_residual_network,
10
+ dinitz,
11
+ edmonds_karp,
12
+ preflow_push,
13
+ shortest_augmenting_path,
14
+ )
15
+
16
+ flow_funcs = {
17
+ boykov_kolmogorov,
18
+ dinitz,
19
+ edmonds_karp,
20
+ preflow_push,
21
+ shortest_augmenting_path,
22
+ }
23
+
24
+ max_min_funcs = {nx.maximum_flow, nx.minimum_cut}
25
+ flow_value_funcs = {nx.maximum_flow_value, nx.minimum_cut_value}
26
+ interface_funcs = max_min_funcs | flow_value_funcs
27
+ all_funcs = flow_funcs | interface_funcs
28
+
29
+
30
+ def compute_cutset(G, partition):
31
+ reachable, non_reachable = partition
32
+ cutset = set()
33
+ for u, nbrs in ((n, G[n]) for n in reachable):
34
+ cutset.update((u, v) for v in nbrs if v in non_reachable)
35
+ return cutset
36
+
37
+
38
+ def validate_flows(G, s, t, flowDict, solnValue, capacity, flow_func):
39
+ errmsg = f"Assertion failed in function: {flow_func.__name__}"
40
+ assert set(G) == set(flowDict), errmsg
41
+ for u in G:
42
+ assert set(G[u]) == set(flowDict[u]), errmsg
43
+ excess = {u: 0 for u in flowDict}
44
+ for u in flowDict:
45
+ for v, flow in flowDict[u].items():
46
+ if capacity in G[u][v]:
47
+ assert flow <= G[u][v][capacity]
48
+ assert flow >= 0, errmsg
49
+ excess[u] -= flow
50
+ excess[v] += flow
51
+ for u, exc in excess.items():
52
+ if u == s:
53
+ assert exc == -solnValue, errmsg
54
+ elif u == t:
55
+ assert exc == solnValue, errmsg
56
+ else:
57
+ assert exc == 0, errmsg
58
+
59
+
60
+ def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
61
+ errmsg = f"Assertion failed in function: {flow_func.__name__}"
62
+ assert all(n in G for n in partition[0]), errmsg
63
+ assert all(n in G for n in partition[1]), errmsg
64
+ cutset = compute_cutset(G, partition)
65
+ assert all(G.has_edge(u, v) for (u, v) in cutset), errmsg
66
+ assert solnValue == sum(G[u][v][capacity] for (u, v) in cutset), errmsg
67
+ H = G.copy()
68
+ H.remove_edges_from(cutset)
69
+ if not G.is_directed():
70
+ assert not nx.is_connected(H), errmsg
71
+ else:
72
+ assert not nx.is_strongly_connected(H), errmsg
73
+
74
+
75
+ def compare_flows_and_cuts(G, s, t, solnValue, capacity="capacity"):
76
+ for flow_func in flow_funcs:
77
+ errmsg = f"Assertion failed in function: {flow_func.__name__}"
78
+ R = flow_func(G, s, t, capacity)
79
+ # Test both legacy and new implementations.
80
+ flow_value = R.graph["flow_value"]
81
+ flow_dict = build_flow_dict(G, R)
82
+ assert flow_value == solnValue, errmsg
83
+ validate_flows(G, s, t, flow_dict, solnValue, capacity, flow_func)
84
+ # Minimum cut
85
+ cut_value, partition = nx.minimum_cut(
86
+ G, s, t, capacity=capacity, flow_func=flow_func
87
+ )
88
+ validate_cuts(G, s, t, solnValue, partition, capacity, flow_func)
89
+
90
+
91
+ class TestMaxflowMinCutCommon:
92
+ def test_graph1(self):
93
+ # Trivial undirected graph
94
+ G = nx.Graph()
95
+ G.add_edge(1, 2, capacity=1.0)
96
+
97
+ # solution flows
98
+ # {1: {2: 1.0}, 2: {1: 1.0}}
99
+
100
+ compare_flows_and_cuts(G, 1, 2, 1.0)
101
+
102
+ def test_graph2(self):
103
+ # A more complex undirected graph
104
+ # adapted from https://web.archive.org/web/20220815055650/https://www.topcoder.com/thrive/articles/Maximum%20Flow:%20Part%20One
105
+ G = nx.Graph()
106
+ G.add_edge("x", "a", capacity=3.0)
107
+ G.add_edge("x", "b", capacity=1.0)
108
+ G.add_edge("a", "c", capacity=3.0)
109
+ G.add_edge("b", "c", capacity=5.0)
110
+ G.add_edge("b", "d", capacity=4.0)
111
+ G.add_edge("d", "e", capacity=2.0)
112
+ G.add_edge("c", "y", capacity=2.0)
113
+ G.add_edge("e", "y", capacity=3.0)
114
+
115
+ # H
116
+ # {
117
+ # "x": {"a": 3, "b": 1},
118
+ # "a": {"c": 3, "x": 3},
119
+ # "b": {"c": 1, "d": 2, "x": 1},
120
+ # "c": {"a": 3, "b": 1, "y": 2},
121
+ # "d": {"b": 2, "e": 2},
122
+ # "e": {"d": 2, "y": 2},
123
+ # "y": {"c": 2, "e": 2},
124
+ # }
125
+
126
+ compare_flows_and_cuts(G, "x", "y", 4.0)
127
+
128
+ def test_digraph1(self):
129
+ # The classic directed graph example
130
+ G = nx.DiGraph()
131
+ G.add_edge("a", "b", capacity=1000.0)
132
+ G.add_edge("a", "c", capacity=1000.0)
133
+ G.add_edge("b", "c", capacity=1.0)
134
+ G.add_edge("b", "d", capacity=1000.0)
135
+ G.add_edge("c", "d", capacity=1000.0)
136
+
137
+ # H
138
+ # {
139
+ # "a": {"b": 1000.0, "c": 1000.0},
140
+ # "b": {"c": 0, "d": 1000.0},
141
+ # "c": {"d": 1000.0},
142
+ # "d": {},
143
+ # }
144
+
145
+ compare_flows_and_cuts(G, "a", "d", 2000.0)
146
+
147
+ def test_digraph2(self):
148
+ # An example in which some edges end up with zero flow.
149
+ G = nx.DiGraph()
150
+ G.add_edge("s", "b", capacity=2)
151
+ G.add_edge("s", "c", capacity=1)
152
+ G.add_edge("c", "d", capacity=1)
153
+ G.add_edge("d", "a", capacity=1)
154
+ G.add_edge("b", "a", capacity=2)
155
+ G.add_edge("a", "t", capacity=2)
156
+
157
+ # H
158
+ # {
159
+ # "s": {"b": 2, "c": 0},
160
+ # "c": {"d": 0},
161
+ # "d": {"a": 0},
162
+ # "b": {"a": 2},
163
+ # "a": {"t": 2},
164
+ # "t": {},
165
+ # }
166
+
167
+ compare_flows_and_cuts(G, "s", "t", 2)
168
+
169
+ def test_digraph3(self):
170
+ # A directed graph example from Cormen et al.
171
+ G = nx.DiGraph()
172
+ G.add_edge("s", "v1", capacity=16.0)
173
+ G.add_edge("s", "v2", capacity=13.0)
174
+ G.add_edge("v1", "v2", capacity=10.0)
175
+ G.add_edge("v2", "v1", capacity=4.0)
176
+ G.add_edge("v1", "v3", capacity=12.0)
177
+ G.add_edge("v3", "v2", capacity=9.0)
178
+ G.add_edge("v2", "v4", capacity=14.0)
179
+ G.add_edge("v4", "v3", capacity=7.0)
180
+ G.add_edge("v3", "t", capacity=20.0)
181
+ G.add_edge("v4", "t", capacity=4.0)
182
+
183
+ # H
184
+ # {
185
+ # "s": {"v1": 12.0, "v2": 11.0},
186
+ # "v2": {"v1": 0, "v4": 11.0},
187
+ # "v1": {"v2": 0, "v3": 12.0},
188
+ # "v3": {"v2": 0, "t": 19.0},
189
+ # "v4": {"v3": 7.0, "t": 4.0},
190
+ # "t": {},
191
+ # }
192
+
193
+ compare_flows_and_cuts(G, "s", "t", 23.0)
194
+
195
+ def test_digraph4(self):
196
+ # A more complex directed graph
197
+ # from https://web.archive.org/web/20220815055650/https://www.topcoder.com/thrive/articles/Maximum%20Flow:%20Part%20One
198
+ G = nx.DiGraph()
199
+ G.add_edge("x", "a", capacity=3.0)
200
+ G.add_edge("x", "b", capacity=1.0)
201
+ G.add_edge("a", "c", capacity=3.0)
202
+ G.add_edge("b", "c", capacity=5.0)
203
+ G.add_edge("b", "d", capacity=4.0)
204
+ G.add_edge("d", "e", capacity=2.0)
205
+ G.add_edge("c", "y", capacity=2.0)
206
+ G.add_edge("e", "y", capacity=3.0)
207
+
208
+ # H
209
+ # {
210
+ # "x": {"a": 2.0, "b": 1.0},
211
+ # "a": {"c": 2.0},
212
+ # "b": {"c": 0, "d": 1.0},
213
+ # "c": {"y": 2.0},
214
+ # "d": {"e": 1.0},
215
+ # "e": {"y": 1.0},
216
+ # "y": {},
217
+ # }
218
+
219
+ compare_flows_and_cuts(G, "x", "y", 3.0)
220
+
221
+ def test_wikipedia_dinitz_example(self):
222
+ # Nice example from https://en.wikipedia.org/wiki/Dinic's_algorithm
223
+ G = nx.DiGraph()
224
+ G.add_edge("s", 1, capacity=10)
225
+ G.add_edge("s", 2, capacity=10)
226
+ G.add_edge(1, 3, capacity=4)
227
+ G.add_edge(1, 4, capacity=8)
228
+ G.add_edge(1, 2, capacity=2)
229
+ G.add_edge(2, 4, capacity=9)
230
+ G.add_edge(3, "t", capacity=10)
231
+ G.add_edge(4, 3, capacity=6)
232
+ G.add_edge(4, "t", capacity=10)
233
+
234
+ # solution flows
235
+ # {
236
+ # 1: {2: 0, 3: 4, 4: 6},
237
+ # 2: {4: 9},
238
+ # 3: {"t": 9},
239
+ # 4: {3: 5, "t": 10},
240
+ # "s": {1: 10, 2: 9},
241
+ # "t": {},
242
+ # }
243
+
244
+ compare_flows_and_cuts(G, "s", "t", 19)
245
+
246
+ def test_optional_capacity(self):
247
+ # Test optional capacity parameter.
248
+ G = nx.DiGraph()
249
+ G.add_edge("x", "a", spam=3.0)
250
+ G.add_edge("x", "b", spam=1.0)
251
+ G.add_edge("a", "c", spam=3.0)
252
+ G.add_edge("b", "c", spam=5.0)
253
+ G.add_edge("b", "d", spam=4.0)
254
+ G.add_edge("d", "e", spam=2.0)
255
+ G.add_edge("c", "y", spam=2.0)
256
+ G.add_edge("e", "y", spam=3.0)
257
+
258
+ # solution flows
259
+ # {
260
+ # "x": {"a": 2.0, "b": 1.0},
261
+ # "a": {"c": 2.0},
262
+ # "b": {"c": 0, "d": 1.0},
263
+ # "c": {"y": 2.0},
264
+ # "d": {"e": 1.0},
265
+ # "e": {"y": 1.0},
266
+ # "y": {},
267
+ # }
268
+ solnValue = 3.0
269
+ s = "x"
270
+ t = "y"
271
+
272
+ compare_flows_and_cuts(G, s, t, solnValue, capacity="spam")
273
+
274
+ def test_digraph_infcap_edges(self):
275
+ # DiGraph with infinite capacity edges
276
+ G = nx.DiGraph()
277
+ G.add_edge("s", "a")
278
+ G.add_edge("s", "b", capacity=30)
279
+ G.add_edge("a", "c", capacity=25)
280
+ G.add_edge("b", "c", capacity=12)
281
+ G.add_edge("a", "t", capacity=60)
282
+ G.add_edge("c", "t")
283
+
284
+ # H
285
+ # {
286
+ # "s": {"a": 85, "b": 12},
287
+ # "a": {"c": 25, "t": 60},
288
+ # "b": {"c": 12},
289
+ # "c": {"t": 37},
290
+ # "t": {},
291
+ # }
292
+
293
+ compare_flows_and_cuts(G, "s", "t", 97)
294
+
295
+ # DiGraph with infinite capacity digon
296
+ G = nx.DiGraph()
297
+ G.add_edge("s", "a", capacity=85)
298
+ G.add_edge("s", "b", capacity=30)
299
+ G.add_edge("a", "c")
300
+ G.add_edge("c", "a")
301
+ G.add_edge("b", "c", capacity=12)
302
+ G.add_edge("a", "t", capacity=60)
303
+ G.add_edge("c", "t", capacity=37)
304
+
305
+ # H
306
+ # {
307
+ # "s": {"a": 85, "b": 12},
308
+ # "a": {"c": 25, "t": 60},
309
+ # "c": {"a": 0, "t": 37},
310
+ # "b": {"c": 12},
311
+ # "t": {},
312
+ # }
313
+
314
+ compare_flows_and_cuts(G, "s", "t", 97)
315
+
316
+ def test_digraph_infcap_path(self):
317
+ # Graph with infinite capacity (s, t)-path
318
+ G = nx.DiGraph()
319
+ G.add_edge("s", "a")
320
+ G.add_edge("s", "b", capacity=30)
321
+ G.add_edge("a", "c")
322
+ G.add_edge("b", "c", capacity=12)
323
+ G.add_edge("a", "t", capacity=60)
324
+ G.add_edge("c", "t")
325
+
326
+ for flow_func in all_funcs:
327
+ pytest.raises(nx.NetworkXUnbounded, flow_func, G, "s", "t")
328
+
329
+ def test_graph_infcap_edges(self):
330
+ # Undirected graph with infinite capacity edges
331
+ G = nx.Graph()
332
+ G.add_edge("s", "a")
333
+ G.add_edge("s", "b", capacity=30)
334
+ G.add_edge("a", "c", capacity=25)
335
+ G.add_edge("b", "c", capacity=12)
336
+ G.add_edge("a", "t", capacity=60)
337
+ G.add_edge("c", "t")
338
+
339
+ # H
340
+ # {
341
+ # "s": {"a": 85, "b": 12},
342
+ # "a": {"c": 25, "s": 85, "t": 60},
343
+ # "b": {"c": 12, "s": 12},
344
+ # "c": {"a": 25, "b": 12, "t": 37},
345
+ # "t": {"a": 60, "c": 37},
346
+ # }
347
+
348
+ compare_flows_and_cuts(G, "s", "t", 97)
349
+
350
+ def test_digraph5(self):
351
+ # From ticket #429 by mfrasca.
352
+ G = nx.DiGraph()
353
+ G.add_edge("s", "a", capacity=2)
354
+ G.add_edge("s", "b", capacity=2)
355
+ G.add_edge("a", "b", capacity=5)
356
+ G.add_edge("a", "t", capacity=1)
357
+ G.add_edge("b", "a", capacity=1)
358
+ G.add_edge("b", "t", capacity=3)
359
+ # flow solution
360
+ # {
361
+ # "a": {"b": 1, "t": 1},
362
+ # "b": {"a": 0, "t": 3},
363
+ # "s": {"a": 2, "b": 2},
364
+ # "t": {},
365
+ # }
366
+ compare_flows_and_cuts(G, "s", "t", 4)
367
+
368
+ def test_disconnected(self):
369
+ G = nx.Graph()
370
+ G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
371
+ G.remove_node(1)
372
+ assert nx.maximum_flow_value(G, 0, 3) == 0
373
+ # flow solution
374
+ # {0: {}, 2: {3: 0}, 3: {2: 0}}
375
+ compare_flows_and_cuts(G, 0, 3, 0)
376
+
377
+ def test_source_target_not_in_graph(self):
378
+ G = nx.Graph()
379
+ G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
380
+ G.remove_node(0)
381
+ for flow_func in all_funcs:
382
+ pytest.raises(nx.NetworkXError, flow_func, G, 0, 3)
383
+ G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
384
+ G.remove_node(3)
385
+ for flow_func in all_funcs:
386
+ pytest.raises(nx.NetworkXError, flow_func, G, 0, 3)
387
+
388
+ def test_source_target_coincide(self):
389
+ G = nx.Graph()
390
+ G.add_node(0)
391
+ for flow_func in all_funcs:
392
+ pytest.raises(nx.NetworkXError, flow_func, G, 0, 0)
393
+
394
+ def test_multigraphs_raise(self):
395
+ G = nx.MultiGraph()
396
+ M = nx.MultiDiGraph()
397
+ G.add_edges_from([(0, 1), (1, 0)], capacity=True)
398
+ for flow_func in all_funcs:
399
+ pytest.raises(nx.NetworkXError, flow_func, G, 0, 0)
400
+
401
+
402
+ class TestMaxFlowMinCutInterface:
403
+ def setup_method(self):
404
+ G = nx.DiGraph()
405
+ G.add_edge("x", "a", capacity=3.0)
406
+ G.add_edge("x", "b", capacity=1.0)
407
+ G.add_edge("a", "c", capacity=3.0)
408
+ G.add_edge("b", "c", capacity=5.0)
409
+ G.add_edge("b", "d", capacity=4.0)
410
+ G.add_edge("d", "e", capacity=2.0)
411
+ G.add_edge("c", "y", capacity=2.0)
412
+ G.add_edge("e", "y", capacity=3.0)
413
+ self.G = G
414
+ H = nx.DiGraph()
415
+ H.add_edge(0, 1, capacity=1.0)
416
+ H.add_edge(1, 2, capacity=1.0)
417
+ self.H = H
418
+
419
+ def test_flow_func_not_callable(self):
420
+ elements = ["this_should_be_callable", 10, {1, 2, 3}]
421
+ G = nx.Graph()
422
+ G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
423
+ for flow_func in interface_funcs:
424
+ for element in elements:
425
+ pytest.raises(nx.NetworkXError, flow_func, G, 0, 1, flow_func=element)
426
+ pytest.raises(nx.NetworkXError, flow_func, G, 0, 1, flow_func=element)
427
+
428
+ def test_flow_func_parameters(self):
429
+ G = self.G
430
+ fv = 3.0
431
+ for interface_func in interface_funcs:
432
+ for flow_func in flow_funcs:
433
+ errmsg = (
434
+ f"Assertion failed in function: {flow_func.__name__} "
435
+ f"in interface {interface_func.__name__}"
436
+ )
437
+ result = interface_func(G, "x", "y", flow_func=flow_func)
438
+ if interface_func in max_min_funcs:
439
+ result = result[0]
440
+ assert fv == result, errmsg
441
+
442
+ def test_minimum_cut_no_cutoff(self):
443
+ G = self.G
444
+ pytest.raises(
445
+ nx.NetworkXError,
446
+ nx.minimum_cut,
447
+ G,
448
+ "x",
449
+ "y",
450
+ flow_func=preflow_push,
451
+ cutoff=1.0,
452
+ )
453
+ pytest.raises(
454
+ nx.NetworkXError,
455
+ nx.minimum_cut_value,
456
+ G,
457
+ "x",
458
+ "y",
459
+ flow_func=preflow_push,
460
+ cutoff=1.0,
461
+ )
462
+
463
+ def test_kwargs(self):
464
+ G = self.H
465
+ fv = 1.0
466
+ to_test = (
467
+ (shortest_augmenting_path, {"two_phase": True}),
468
+ (preflow_push, {"global_relabel_freq": 5}),
469
+ )
470
+ for interface_func in interface_funcs:
471
+ for flow_func, kwargs in to_test:
472
+ errmsg = (
473
+ f"Assertion failed in function: {flow_func.__name__} "
474
+ f"in interface {interface_func.__name__}"
475
+ )
476
+ result = interface_func(G, 0, 2, flow_func=flow_func, **kwargs)
477
+ if interface_func in max_min_funcs:
478
+ result = result[0]
479
+ assert fv == result, errmsg
480
+
481
+ def test_kwargs_default_flow_func(self):
482
+ G = self.H
483
+ for interface_func in interface_funcs:
484
+ pytest.raises(
485
+ nx.NetworkXError, interface_func, G, 0, 1, global_relabel_freq=2
486
+ )
487
+
488
+ def test_reusing_residual(self):
489
+ G = self.G
490
+ fv = 3.0
491
+ s, t = "x", "y"
492
+ R = build_residual_network(G, "capacity")
493
+ for interface_func in interface_funcs:
494
+ for flow_func in flow_funcs:
495
+ errmsg = (
496
+ f"Assertion failed in function: {flow_func.__name__} "
497
+ f"in interface {interface_func.__name__}"
498
+ )
499
+ for i in range(3):
500
+ result = interface_func(
501
+ G, "x", "y", flow_func=flow_func, residual=R
502
+ )
503
+ if interface_func in max_min_funcs:
504
+ result = result[0]
505
+ assert fv == result, errmsg
506
+
507
+
508
+ # Tests specific to one algorithm
509
+ def test_preflow_push_global_relabel_freq():
510
+ G = nx.DiGraph()
511
+ G.add_edge(1, 2, capacity=1)
512
+ R = preflow_push(G, 1, 2, global_relabel_freq=None)
513
+ assert R.graph["flow_value"] == 1
514
+ pytest.raises(nx.NetworkXError, preflow_push, G, 1, 2, global_relabel_freq=-1)
515
+
516
+
517
+ def test_preflow_push_makes_enough_space():
518
+ # From ticket #1542
519
+ G = nx.DiGraph()
520
+ nx.add_path(G, [0, 1, 3], capacity=1)
521
+ nx.add_path(G, [1, 2, 3], capacity=1)
522
+ R = preflow_push(G, 0, 3, value_only=False)
523
+ assert R.graph["flow_value"] == 1
524
+
525
+
526
+ def test_shortest_augmenting_path_two_phase():
527
+ k = 5
528
+ p = 1000
529
+ G = nx.DiGraph()
530
+ for i in range(k):
531
+ G.add_edge("s", (i, 0), capacity=1)
532
+ nx.add_path(G, ((i, j) for j in range(p)), capacity=1)
533
+ G.add_edge((i, p - 1), "t", capacity=1)
534
+ R = shortest_augmenting_path(G, "s", "t", two_phase=True)
535
+ assert R.graph["flow_value"] == k
536
+ R = shortest_augmenting_path(G, "s", "t", two_phase=False)
537
+ assert R.graph["flow_value"] == k
538
+
539
+
540
+ class TestCutoff:
541
+ def test_cutoff(self):
542
+ k = 5
543
+ p = 1000
544
+ G = nx.DiGraph()
545
+ for i in range(k):
546
+ G.add_edge("s", (i, 0), capacity=2)
547
+ nx.add_path(G, ((i, j) for j in range(p)), capacity=2)
548
+ G.add_edge((i, p - 1), "t", capacity=2)
549
+ R = shortest_augmenting_path(G, "s", "t", two_phase=True, cutoff=k)
550
+ assert k <= R.graph["flow_value"] <= (2 * k)
551
+ R = shortest_augmenting_path(G, "s", "t", two_phase=False, cutoff=k)
552
+ assert k <= R.graph["flow_value"] <= (2 * k)
553
+ R = edmonds_karp(G, "s", "t", cutoff=k)
554
+ assert k <= R.graph["flow_value"] <= (2 * k)
555
+ R = dinitz(G, "s", "t", cutoff=k)
556
+ assert k <= R.graph["flow_value"] <= (2 * k)
557
+ R = boykov_kolmogorov(G, "s", "t", cutoff=k)
558
+ assert k <= R.graph["flow_value"] <= (2 * k)
559
+
560
+ def test_complete_graph_cutoff(self):
561
+ G = nx.complete_graph(5)
562
+ nx.set_edge_attributes(G, {(u, v): 1 for u, v in G.edges()}, "capacity")
563
+ for flow_func in [
564
+ shortest_augmenting_path,
565
+ edmonds_karp,
566
+ dinitz,
567
+ boykov_kolmogorov,
568
+ ]:
569
+ for cutoff in [3, 2, 1]:
570
+ result = nx.maximum_flow_value(
571
+ G, 0, 4, flow_func=flow_func, cutoff=cutoff
572
+ )
573
+ assert cutoff == result, f"cutoff error in {flow_func.__name__}"
janus/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_networksimplex.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bz2
2
+ import importlib.resources
3
+ import os
4
+ import pickle
5
+
6
+ import pytest
7
+
8
+ import networkx as nx
9
+
10
+
11
+ @pytest.fixture
12
+ def simple_flow_graph():
13
+ G = nx.DiGraph()
14
+ G.add_node("a", demand=0)
15
+ G.add_node("b", demand=-5)
16
+ G.add_node("c", demand=50000000)
17
+ G.add_node("d", demand=-49999995)
18
+ G.add_edge("a", "b", weight=3, capacity=4)
19
+ G.add_edge("a", "c", weight=6, capacity=10)
20
+ G.add_edge("b", "d", weight=1, capacity=9)
21
+ G.add_edge("c", "d", weight=2, capacity=5)
22
+ return G
23
+
24
+
25
+ @pytest.fixture
26
+ def simple_no_flow_graph():
27
+ G = nx.DiGraph()
28
+ G.add_node("s", demand=-5)
29
+ G.add_node("t", demand=5)
30
+ G.add_edge("s", "a", weight=1, capacity=3)
31
+ G.add_edge("a", "b", weight=3)
32
+ G.add_edge("a", "c", weight=-6)
33
+ G.add_edge("b", "d", weight=1)
34
+ G.add_edge("c", "d", weight=-2)
35
+ G.add_edge("d", "t", weight=1, capacity=3)
36
+ return G
37
+
38
+
39
+ def get_flowcost_from_flowdict(G, flowDict):
40
+ """Returns flow cost calculated from flow dictionary"""
41
+ flowCost = 0
42
+ for u in flowDict:
43
+ for v in flowDict[u]:
44
+ flowCost += flowDict[u][v] * G[u][v]["weight"]
45
+ return flowCost
46
+
47
+
48
+ def test_infinite_demand_raise(simple_flow_graph):
49
+ G = simple_flow_graph
50
+ inf = float("inf")
51
+ nx.set_node_attributes(G, {"a": {"demand": inf}})
52
+ pytest.raises(nx.NetworkXError, nx.network_simplex, G)
53
+
54
+
55
+ def test_neg_infinite_demand_raise(simple_flow_graph):
56
+ G = simple_flow_graph
57
+ inf = float("inf")
58
+ nx.set_node_attributes(G, {"a": {"demand": -inf}})
59
+ pytest.raises(nx.NetworkXError, nx.network_simplex, G)
60
+
61
+
62
+ def test_infinite_weight_raise(simple_flow_graph):
63
+ G = simple_flow_graph
64
+ inf = float("inf")
65
+ nx.set_edge_attributes(
66
+ G, {("a", "b"): {"weight": inf}, ("b", "d"): {"weight": inf}}
67
+ )
68
+ pytest.raises(nx.NetworkXError, nx.network_simplex, G)
69
+
70
+
71
+ def test_nonzero_net_demand_raise(simple_flow_graph):
72
+ G = simple_flow_graph
73
+ nx.set_node_attributes(G, {"b": {"demand": -4}})
74
+ pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
75
+
76
+
77
+ def test_negative_capacity_raise(simple_flow_graph):
78
+ G = simple_flow_graph
79
+ nx.set_edge_attributes(G, {("a", "b"): {"weight": 1}, ("b", "d"): {"capacity": -9}})
80
+ pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
81
+
82
+
83
+ def test_no_flow_satisfying_demands(simple_no_flow_graph):
84
+ G = simple_no_flow_graph
85
+ pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
86
+
87
+
88
+ def test_sum_demands_not_zero(simple_no_flow_graph):
89
+ G = simple_no_flow_graph
90
+ nx.set_node_attributes(G, {"t": {"demand": 4}})
91
+ pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
92
+
93
+
94
+ def test_google_or_tools_example():
95
+ """
96
+ https://developers.google.com/optimization/flow/mincostflow
97
+ """
98
+ G = nx.DiGraph()
99
+ start_nodes = [0, 0, 1, 1, 1, 2, 2, 3, 4]
100
+ end_nodes = [1, 2, 2, 3, 4, 3, 4, 4, 2]
101
+ capacities = [15, 8, 20, 4, 10, 15, 4, 20, 5]
102
+ unit_costs = [4, 4, 2, 2, 6, 1, 3, 2, 3]
103
+ supplies = [20, 0, 0, -5, -15]
104
+ answer = 150
105
+
106
+ for i in range(len(supplies)):
107
+ G.add_node(i, demand=(-1) * supplies[i]) # supplies are negative of demand
108
+
109
+ for i in range(len(start_nodes)):
110
+ G.add_edge(
111
+ start_nodes[i], end_nodes[i], weight=unit_costs[i], capacity=capacities[i]
112
+ )
113
+
114
+ flowCost, flowDict = nx.network_simplex(G)
115
+ assert flowCost == answer
116
+ assert flowCost == get_flowcost_from_flowdict(G, flowDict)
117
+
118
+
119
+ def test_google_or_tools_example2():
120
+ """
121
+ https://developers.google.com/optimization/flow/mincostflow
122
+ """
123
+ G = nx.DiGraph()
124
+ start_nodes = [0, 0, 1, 1, 1, 2, 2, 3, 4, 3]
125
+ end_nodes = [1, 2, 2, 3, 4, 3, 4, 4, 2, 5]
126
+ capacities = [15, 8, 20, 4, 10, 15, 4, 20, 5, 10]
127
+ unit_costs = [4, 4, 2, 2, 6, 1, 3, 2, 3, 4]
128
+ supplies = [23, 0, 0, -5, -15, -3]
129
+ answer = 183
130
+
131
+ for i in range(len(supplies)):
132
+ G.add_node(i, demand=(-1) * supplies[i]) # supplies are negative of demand
133
+
134
+ for i in range(len(start_nodes)):
135
+ G.add_edge(
136
+ start_nodes[i], end_nodes[i], weight=unit_costs[i], capacity=capacities[i]
137
+ )
138
+
139
+ flowCost, flowDict = nx.network_simplex(G)
140
+ assert flowCost == answer
141
+ assert flowCost == get_flowcost_from_flowdict(G, flowDict)
142
+
143
+
144
+ def test_large():
145
+ fname = (
146
+ importlib.resources.files("networkx.algorithms.flow.tests")
147
+ / "netgen-2.gpickle.bz2"
148
+ )
149
+
150
+ with bz2.BZ2File(fname, "rb") as f:
151
+ G = pickle.load(f)
152
+ flowCost, flowDict = nx.network_simplex(G)
153
+ assert 6749969302 == flowCost
154
+ assert 6749969302 == nx.cost_of_flow(G, flowDict)
155
+
156
+
157
+ def test_simple_digraph():
158
+ G = nx.DiGraph()
159
+ G.add_node("a", demand=-5)
160
+ G.add_node("d", demand=5)
161
+ G.add_edge("a", "b", weight=3, capacity=4)
162
+ G.add_edge("a", "c", weight=6, capacity=10)
163
+ G.add_edge("b", "d", weight=1, capacity=9)
164
+ G.add_edge("c", "d", weight=2, capacity=5)
165
+ flowCost, H = nx.network_simplex(G)
166
+ soln = {"a": {"b": 4, "c": 1}, "b": {"d": 4}, "c": {"d": 1}, "d": {}}
167
+ assert flowCost == 24
168
+ assert nx.min_cost_flow_cost(G) == 24
169
+ assert H == soln
170
+
171
+
172
+ def test_negcycle_infcap():
173
+ G = nx.DiGraph()
174
+ G.add_node("s", demand=-5)
175
+ G.add_node("t", demand=5)
176
+ G.add_edge("s", "a", weight=1, capacity=3)
177
+ G.add_edge("a", "b", weight=3)
178
+ G.add_edge("c", "a", weight=-6)
179
+ G.add_edge("b", "d", weight=1)
180
+ G.add_edge("d", "c", weight=-2)
181
+ G.add_edge("d", "t", weight=1, capacity=3)
182
+ pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
183
+
184
+
185
+ def test_transshipment():
186
+ G = nx.DiGraph()
187
+ G.add_node("a", demand=1)
188
+ G.add_node("b", demand=-2)
189
+ G.add_node("c", demand=-2)
190
+ G.add_node("d", demand=3)
191
+ G.add_node("e", demand=-4)
192
+ G.add_node("f", demand=-4)
193
+ G.add_node("g", demand=3)
194
+ G.add_node("h", demand=2)
195
+ G.add_node("r", demand=3)
196
+ G.add_edge("a", "c", weight=3)
197
+ G.add_edge("r", "a", weight=2)
198
+ G.add_edge("b", "a", weight=9)
199
+ G.add_edge("r", "c", weight=0)
200
+ G.add_edge("b", "r", weight=-6)
201
+ G.add_edge("c", "d", weight=5)
202
+ G.add_edge("e", "r", weight=4)
203
+ G.add_edge("e", "f", weight=3)
204
+ G.add_edge("h", "b", weight=4)
205
+ G.add_edge("f", "d", weight=7)
206
+ G.add_edge("f", "h", weight=12)
207
+ G.add_edge("g", "d", weight=12)
208
+ G.add_edge("f", "g", weight=-1)
209
+ G.add_edge("h", "g", weight=-10)
210
+ flowCost, H = nx.network_simplex(G)
211
+ soln = {
212
+ "a": {"c": 0},
213
+ "b": {"a": 0, "r": 2},
214
+ "c": {"d": 3},
215
+ "d": {},
216
+ "e": {"r": 3, "f": 1},
217
+ "f": {"d": 0, "g": 3, "h": 2},
218
+ "g": {"d": 0},
219
+ "h": {"b": 0, "g": 0},
220
+ "r": {"a": 1, "c": 1},
221
+ }
222
+ assert flowCost == 41
223
+ assert H == soln
224
+
225
+
226
+ def test_digraph1():
227
+ # From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied
228
+ # Mathematical Programming. Addison-Wesley, 1977.
229
+ G = nx.DiGraph()
230
+ G.add_node(1, demand=-20)
231
+ G.add_node(4, demand=5)
232
+ G.add_node(5, demand=15)
233
+ G.add_edges_from(
234
+ [
235
+ (1, 2, {"capacity": 15, "weight": 4}),
236
+ (1, 3, {"capacity": 8, "weight": 4}),
237
+ (2, 3, {"weight": 2}),
238
+ (2, 4, {"capacity": 4, "weight": 2}),
239
+ (2, 5, {"capacity": 10, "weight": 6}),
240
+ (3, 4, {"capacity": 15, "weight": 1}),
241
+ (3, 5, {"capacity": 5, "weight": 3}),
242
+ (4, 5, {"weight": 2}),
243
+ (5, 3, {"capacity": 4, "weight": 1}),
244
+ ]
245
+ )
246
+ flowCost, H = nx.network_simplex(G)
247
+ soln = {
248
+ 1: {2: 12, 3: 8},
249
+ 2: {3: 8, 4: 4, 5: 0},
250
+ 3: {4: 11, 5: 5},
251
+ 4: {5: 10},
252
+ 5: {3: 0},
253
+ }
254
+ assert flowCost == 150
255
+ assert nx.min_cost_flow_cost(G) == 150
256
+ assert H == soln
257
+
258
+
259
+ def test_zero_capacity_edges():
260
+ """Address issue raised in ticket #617 by arv."""
261
+ G = nx.DiGraph()
262
+ G.add_edges_from(
263
+ [
264
+ (1, 2, {"capacity": 1, "weight": 1}),
265
+ (1, 5, {"capacity": 1, "weight": 1}),
266
+ (2, 3, {"capacity": 0, "weight": 1}),
267
+ (2, 5, {"capacity": 1, "weight": 1}),
268
+ (5, 3, {"capacity": 2, "weight": 1}),
269
+ (5, 4, {"capacity": 0, "weight": 1}),
270
+ (3, 4, {"capacity": 2, "weight": 1}),
271
+ ]
272
+ )
273
+ G.nodes[1]["demand"] = -1
274
+ G.nodes[2]["demand"] = -1
275
+ G.nodes[4]["demand"] = 2
276
+
277
+ flowCost, H = nx.network_simplex(G)
278
+ soln = {1: {2: 0, 5: 1}, 2: {3: 0, 5: 1}, 3: {4: 2}, 4: {}, 5: {3: 2, 4: 0}}
279
+ assert flowCost == 6
280
+ assert nx.min_cost_flow_cost(G) == 6
281
+ assert H == soln
282
+
283
+
284
+ def test_digon():
285
+ """Check if digons are handled properly. Taken from ticket
286
+ #618 by arv."""
287
+ nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})]
288
+ edges = [
289
+ (1, 2, {"capacity": 3, "weight": 600000}),
290
+ (2, 1, {"capacity": 2, "weight": 0}),
291
+ (2, 3, {"capacity": 5, "weight": 714285}),
292
+ (3, 2, {"capacity": 2, "weight": 0}),
293
+ ]
294
+ G = nx.DiGraph(edges)
295
+ G.add_nodes_from(nodes)
296
+ flowCost, H = nx.network_simplex(G)
297
+ soln = {1: {2: 0}, 2: {1: 0, 3: 4}, 3: {2: 0}}
298
+ assert flowCost == 2857140
299
+
300
+
301
+ def test_deadend():
302
+ """Check if one-node cycles are handled properly. Taken from ticket
303
+ #2906 from @sshraven."""
304
+ G = nx.DiGraph()
305
+
306
+ G.add_nodes_from(range(5), demand=0)
307
+ G.nodes[4]["demand"] = -13
308
+ G.nodes[3]["demand"] = 13
309
+
310
+ G.add_edges_from([(0, 2), (0, 3), (2, 1)], capacity=20, weight=0.1)
311
+ pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
312
+
313
+
314
+ def test_infinite_capacity_neg_digon():
315
+ """An infinite capacity negative cost digon results in an unbounded
316
+ instance."""
317
+ nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})]
318
+ edges = [
319
+ (1, 2, {"weight": -600}),
320
+ (2, 1, {"weight": 0}),
321
+ (2, 3, {"capacity": 5, "weight": 714285}),
322
+ (3, 2, {"capacity": 2, "weight": 0}),
323
+ ]
324
+ G = nx.DiGraph(edges)
325
+ G.add_nodes_from(nodes)
326
+ pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G)
327
+
328
+
329
+ def test_multidigraph():
330
+ """Multidigraphs are acceptable."""
331
+ G = nx.MultiDiGraph()
332
+ G.add_weighted_edges_from([(1, 2, 1), (2, 3, 2)], weight="capacity")
333
+ flowCost, H = nx.network_simplex(G)
334
+ assert flowCost == 0
335
+ assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}}
336
+
337
+
338
+ def test_negative_selfloops():
339
+ """Negative selfloops should cause an exception if uncapacitated and
340
+ always be saturated otherwise.
341
+ """
342
+ G = nx.DiGraph()
343
+ G.add_edge(1, 1, weight=-1)
344
+ pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G)
345
+
346
+ G[1][1]["capacity"] = 2
347
+ flowCost, H = nx.network_simplex(G)
348
+ assert flowCost == -2
349
+ assert H == {1: {1: 2}}
350
+
351
+ G = nx.MultiDiGraph()
352
+ G.add_edge(1, 1, "x", weight=-1)
353
+ G.add_edge(1, 1, "y", weight=1)
354
+ pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G)
355
+
356
+ G[1][1]["x"]["capacity"] = 2
357
+ flowCost, H = nx.network_simplex(G)
358
+ assert flowCost == -2
359
+ assert H == {1: {1: {"x": 2, "y": 0}}}
360
+
361
+
362
+ def test_bone_shaped():
363
+ # From #1283
364
+ G = nx.DiGraph()
365
+ G.add_node(0, demand=-4)
366
+ G.add_node(1, demand=2)
367
+ G.add_node(2, demand=2)
368
+ G.add_node(3, demand=4)
369
+ G.add_node(4, demand=-2)
370
+ G.add_node(5, demand=-2)
371
+ G.add_edge(0, 1, capacity=4)
372
+ G.add_edge(0, 2, capacity=4)
373
+ G.add_edge(4, 3, capacity=4)
374
+ G.add_edge(5, 3, capacity=4)
375
+ G.add_edge(0, 3, capacity=0)
376
+ flowCost, H = nx.network_simplex(G)
377
+ assert flowCost == 0
378
+ assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}}
379
+
380
+
381
+ def test_graphs_type_exceptions():
382
+ G = nx.Graph()
383
+ pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G)
384
+ G = nx.MultiGraph()
385
+ pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G)
386
+ G = nx.DiGraph()
387
+ pytest.raises(nx.NetworkXError, nx.network_simplex, G)
janus/lib/python3.10/site-packages/networkx/algorithms/flow/utils.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility classes and functions for network flow algorithms.
3
+ """
4
+
5
+ from collections import deque
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = [
10
+ "CurrentEdge",
11
+ "Level",
12
+ "GlobalRelabelThreshold",
13
+ "build_residual_network",
14
+ "detect_unboundedness",
15
+ "build_flow_dict",
16
+ ]
17
+
18
+
19
+ class CurrentEdge:
20
+ """Mechanism for iterating over out-edges incident to a node in a circular
21
+ manner. StopIteration exception is raised when wraparound occurs.
22
+ """
23
+
24
+ __slots__ = ("_edges", "_it", "_curr")
25
+
26
+ def __init__(self, edges):
27
+ self._edges = edges
28
+ if self._edges:
29
+ self._rewind()
30
+
31
+ def get(self):
32
+ return self._curr
33
+
34
+ def move_to_next(self):
35
+ try:
36
+ self._curr = next(self._it)
37
+ except StopIteration:
38
+ self._rewind()
39
+ raise
40
+
41
+ def _rewind(self):
42
+ self._it = iter(self._edges.items())
43
+ self._curr = next(self._it)
44
+
45
+
46
+ class Level:
47
+ """Active and inactive nodes in a level."""
48
+
49
+ __slots__ = ("active", "inactive")
50
+
51
+ def __init__(self):
52
+ self.active = set()
53
+ self.inactive = set()
54
+
55
+
56
+ class GlobalRelabelThreshold:
57
+ """Measurement of work before the global relabeling heuristic should be
58
+ applied.
59
+ """
60
+
61
+ def __init__(self, n, m, freq):
62
+ self._threshold = (n + m) / freq if freq else float("inf")
63
+ self._work = 0
64
+
65
+ def add_work(self, work):
66
+ self._work += work
67
+
68
+ def is_reached(self):
69
+ return self._work >= self._threshold
70
+
71
+ def clear_work(self):
72
+ self._work = 0
73
+
74
+
75
+ @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
76
+ def build_residual_network(G, capacity):
77
+ """Build a residual network and initialize a zero flow.
78
+
79
+ The residual network :samp:`R` from an input graph :samp:`G` has the
80
+ same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
81
+ of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
82
+ self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
83
+ in :samp:`G`.
84
+
85
+ For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
86
+ is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
87
+ in :samp:`G` or zero otherwise. If the capacity is infinite,
88
+ :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
89
+ that does not affect the solution of the problem. This value is stored in
90
+ :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
91
+ :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
92
+ satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
93
+
94
+ The flow value, defined as the total flow into :samp:`t`, the sink, is
95
+ stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
96
+ specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
97
+ that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
98
+ :samp:`s`-:samp:`t` cut.
99
+
100
+ """
101
+ if G.is_multigraph():
102
+ raise nx.NetworkXError("MultiGraph and MultiDiGraph not supported (yet).")
103
+
104
+ R = nx.DiGraph()
105
+ R.__networkx_cache__ = None # Disable caching
106
+ R.add_nodes_from(G)
107
+
108
+ inf = float("inf")
109
+ # Extract edges with positive capacities. Self loops excluded.
110
+ edge_list = [
111
+ (u, v, attr)
112
+ for u, v, attr in G.edges(data=True)
113
+ if u != v and attr.get(capacity, inf) > 0
114
+ ]
115
+ # Simulate infinity with three times the sum of the finite edge capacities
116
+ # or any positive value if the sum is zero. This allows the
117
+ # infinite-capacity edges to be distinguished for unboundedness detection
118
+ # and directly participate in residual capacity calculation. If the maximum
119
+ # flow is finite, these edges cannot appear in the minimum cut and thus
120
+ # guarantee correctness. Since the residual capacity of an
121
+ # infinite-capacity edge is always at least 2/3 of inf, while that of an
122
+ # finite-capacity edge is at most 1/3 of inf, if an operation moves more
123
+ # than 1/3 of inf units of flow to t, there must be an infinite-capacity
124
+ # s-t path in G.
125
+ inf = (
126
+ 3
127
+ * sum(
128
+ attr[capacity]
129
+ for u, v, attr in edge_list
130
+ if capacity in attr and attr[capacity] != inf
131
+ )
132
+ or 1
133
+ )
134
+ if G.is_directed():
135
+ for u, v, attr in edge_list:
136
+ r = min(attr.get(capacity, inf), inf)
137
+ if not R.has_edge(u, v):
138
+ # Both (u, v) and (v, u) must be present in the residual
139
+ # network.
140
+ R.add_edge(u, v, capacity=r)
141
+ R.add_edge(v, u, capacity=0)
142
+ else:
143
+ # The edge (u, v) was added when (v, u) was visited.
144
+ R[u][v]["capacity"] = r
145
+ else:
146
+ for u, v, attr in edge_list:
147
+ # Add a pair of edges with equal residual capacities.
148
+ r = min(attr.get(capacity, inf), inf)
149
+ R.add_edge(u, v, capacity=r)
150
+ R.add_edge(v, u, capacity=r)
151
+
152
+ # Record the value simulating infinity.
153
+ R.graph["inf"] = inf
154
+
155
+ return R
156
+
157
+
158
+ @nx._dispatchable(
159
+ graphs="R",
160
+ preserve_edge_attrs={"R": {"capacity": float("inf")}},
161
+ preserve_graph_attrs=True,
162
+ )
163
+ def detect_unboundedness(R, s, t):
164
+ """Detect an infinite-capacity s-t path in R."""
165
+ q = deque([s])
166
+ seen = {s}
167
+ inf = R.graph["inf"]
168
+ while q:
169
+ u = q.popleft()
170
+ for v, attr in R[u].items():
171
+ if attr["capacity"] == inf and v not in seen:
172
+ if v == t:
173
+ raise nx.NetworkXUnbounded(
174
+ "Infinite capacity path, flow unbounded above."
175
+ )
176
+ seen.add(v)
177
+ q.append(v)
178
+
179
+
180
+ @nx._dispatchable(graphs={"G": 0, "R": 1}, preserve_edge_attrs={"R": {"flow": None}})
181
+ def build_flow_dict(G, R):
182
+ """Build a flow dictionary from a residual network."""
183
+ flow_dict = {}
184
+ for u in G:
185
+ flow_dict[u] = {v: 0 for v in G[u]}
186
+ flow_dict[u].update(
187
+ (v, attr["flow"]) for v, attr in R[u].items() if attr["flow"] > 0
188
+ )
189
+ return flow_dict
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_boundary.cpython-310.pyc ADDED
Binary file (7.14 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_broadcasting.cpython-310.pyc ADDED
Binary file (2.16 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_clique.cpython-310.pyc ADDED
Binary file (8.72 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_communicability.cpython-310.pyc ADDED
Binary file (2.16 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_cuts.cpython-310.pyc ADDED
Binary file (6.27 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_d_separation.cpython-310.pyc ADDED
Binary file (9.22 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_dag.cpython-310.pyc ADDED
Binary file (29.8 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_distance_measures.cpython-310.pyc ADDED
Binary file (29.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_graph_hashing.cpython-310.pyc ADDED
Binary file (21.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_hybrid.cpython-310.pyc ADDED
Binary file (826 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_non_randomness.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_smetric.cpython-310.pyc ADDED
Binary file (441 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_swap.cpython-310.pyc ADDED
Binary file (8.49 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_time_dependent.cpython-310.pyc ADDED
Binary file (9.28 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_tournament.cpython-310.pyc ADDED
Binary file (6.14 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (307 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/edgedfs.cpython-310.pyc ADDED
Binary file (5.48 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/traversal/beamsearch.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Basic algorithms for breadth-first searching the nodes of a graph."""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["bfs_beam_edges"]
6
+
7
+
8
+ @nx._dispatchable
9
+ def bfs_beam_edges(G, source, value, width=None):
10
+ """Iterates over edges in a beam search.
11
+
12
+ The beam search is a generalized breadth-first search in which only
13
+ the "best" *w* neighbors of the current node are enqueued, where *w*
14
+ is the beam width and "best" is an application-specific
15
+ heuristic. In general, a beam search with a small beam width might
16
+ not visit each node in the graph.
17
+
18
+ .. note::
19
+
20
+ With the default value of ``width=None`` or `width` greater than the
21
+ maximum degree of the graph, this function equates to a slower
22
+ version of `~networkx.algorithms.traversal.breadth_first_search.bfs_edges`.
23
+ All nodes will be visited, though the order of the reported edges may
24
+ vary. In such cases, `value` has no effect - consider using `bfs_edges`
25
+ directly instead.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : node
32
+ Starting node for the breadth-first search; this function
33
+ iterates over only those edges in the component reachable from
34
+ this node.
35
+
36
+ value : function
37
+ A function that takes a node of the graph as input and returns a
38
+ real number indicating how "good" it is. A higher value means it
39
+ is more likely to be visited sooner during the search. When
40
+ visiting a new node, only the `width` neighbors with the highest
41
+ `value` are enqueued (in decreasing order of `value`).
42
+
43
+ width : int (default = None)
44
+ The beam width for the search. This is the number of neighbors
45
+ (ordered by `value`) to enqueue when visiting each new node.
46
+
47
+ Yields
48
+ ------
49
+ edge
50
+ Edges in the beam search starting from `source`, given as a pair
51
+ of nodes.
52
+
53
+ Examples
54
+ --------
55
+ To give nodes with, for example, a higher centrality precedence
56
+ during the search, set the `value` function to return the centrality
57
+ value of the node:
58
+
59
+ >>> G = nx.karate_club_graph()
60
+ >>> centrality = nx.eigenvector_centrality(G)
61
+ >>> list(nx.bfs_beam_edges(G, source=0, value=centrality.get, width=3))
62
+ [(0, 2), (0, 1), (0, 8), (2, 32), (1, 13), (8, 33)]
63
+ """
64
+
65
+ if width is None:
66
+ width = len(G)
67
+
68
+ def successors(v):
69
+ """Returns a list of the best neighbors of a node.
70
+
71
+ `v` is a node in the graph `G`.
72
+
73
+ The "best" neighbors are chosen according to the `value`
74
+ function (higher is better). Only the `width` best neighbors of
75
+ `v` are returned.
76
+ """
77
+ # TODO The Python documentation states that for small values, it
78
+ # is better to use `heapq.nlargest`. We should determine the
79
+ # threshold at which its better to use `heapq.nlargest()`
80
+ # instead of `sorted()[:]` and apply that optimization here.
81
+ #
82
+ # If `width` is greater than the number of neighbors of `v`, all
83
+ # neighbors are returned by the semantics of slicing in
84
+ # Python. This occurs in the special case that the user did not
85
+ # specify a `width`: in this case all neighbors are always
86
+ # returned, so this is just a (slower) implementation of
87
+ # `bfs_edges(G, source)` but with a sorted enqueue step.
88
+ return iter(sorted(G.neighbors(v), key=value, reverse=True)[:width])
89
+
90
+ yield from nx.generic_bfs_edges(G, source, successors)
janus/lib/python3.10/site-packages/networkx/algorithms/traversal/breadth_first_search.py ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Basic algorithms for breadth-first searching the nodes of a graph."""
2
+
3
+ from collections import deque
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "bfs_edges",
9
+ "bfs_tree",
10
+ "bfs_predecessors",
11
+ "bfs_successors",
12
+ "descendants_at_distance",
13
+ "bfs_layers",
14
+ "bfs_labeled_edges",
15
+ "generic_bfs_edges",
16
+ ]
17
+
18
+
19
+ @nx._dispatchable
20
+ def generic_bfs_edges(G, source, neighbors=None, depth_limit=None):
21
+ """Iterate over edges in a breadth-first search.
22
+
23
+ The breadth-first search begins at `source` and enqueues the
24
+ neighbors of newly visited nodes specified by the `neighbors`
25
+ function.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : node
32
+ Starting node for the breadth-first search; this function
33
+ iterates over only those edges in the component reachable from
34
+ this node.
35
+
36
+ neighbors : function
37
+ A function that takes a newly visited node of the graph as input
38
+ and returns an *iterator* (not just a list) of nodes that are
39
+ neighbors of that node with custom ordering. If not specified, this is
40
+ just the ``G.neighbors`` method, but in general it can be any function
41
+ that returns an iterator over some or all of the neighbors of a
42
+ given node, in any order.
43
+
44
+ depth_limit : int, optional(default=len(G))
45
+ Specify the maximum search depth.
46
+
47
+ Yields
48
+ ------
49
+ edge
50
+ Edges in the breadth-first search starting from `source`.
51
+
52
+ Examples
53
+ --------
54
+ >>> G = nx.path_graph(7)
55
+ >>> list(nx.generic_bfs_edges(G, source=0))
56
+ [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
57
+ >>> list(nx.generic_bfs_edges(G, source=2))
58
+ [(2, 1), (2, 3), (1, 0), (3, 4), (4, 5), (5, 6)]
59
+ >>> list(nx.generic_bfs_edges(G, source=2, depth_limit=2))
60
+ [(2, 1), (2, 3), (1, 0), (3, 4)]
61
+
62
+ The `neighbors` param can be used to specify the visitation order of each
63
+ node's neighbors generically. In the following example, we modify the default
64
+ neighbor to return *odd* nodes first:
65
+
66
+ >>> def odd_first(n):
67
+ ... return sorted(G.neighbors(n), key=lambda x: x % 2, reverse=True)
68
+
69
+ >>> G = nx.star_graph(5)
70
+ >>> list(nx.generic_bfs_edges(G, source=0)) # Default neighbor ordering
71
+ [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
72
+ >>> list(nx.generic_bfs_edges(G, source=0, neighbors=odd_first))
73
+ [(0, 1), (0, 3), (0, 5), (0, 2), (0, 4)]
74
+
75
+ Notes
76
+ -----
77
+ This implementation is from `PADS`_, which was in the public domain
78
+ when it was first accessed in July, 2004. The modifications
79
+ to allow depth limits are based on the Wikipedia article
80
+ "`Depth-limited-search`_".
81
+
82
+ .. _PADS: http://www.ics.uci.edu/~eppstein/PADS/BFS.py
83
+ .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
84
+ """
85
+ if neighbors is None:
86
+ neighbors = G.neighbors
87
+ if depth_limit is None:
88
+ depth_limit = len(G)
89
+
90
+ seen = {source}
91
+ n = len(G)
92
+ depth = 0
93
+ next_parents_children = [(source, neighbors(source))]
94
+ while next_parents_children and depth < depth_limit:
95
+ this_parents_children = next_parents_children
96
+ next_parents_children = []
97
+ for parent, children in this_parents_children:
98
+ for child in children:
99
+ if child not in seen:
100
+ seen.add(child)
101
+ next_parents_children.append((child, neighbors(child)))
102
+ yield parent, child
103
+ if len(seen) == n:
104
+ return
105
+ depth += 1
106
+
107
+
108
+ @nx._dispatchable
109
+ def bfs_edges(G, source, reverse=False, depth_limit=None, sort_neighbors=None):
110
+ """Iterate over edges in a breadth-first-search starting at source.
111
+
112
+ Parameters
113
+ ----------
114
+ G : NetworkX graph
115
+
116
+ source : node
117
+ Specify starting node for breadth-first search; this function
118
+ iterates over only those edges in the component reachable from
119
+ this node.
120
+
121
+ reverse : bool, optional
122
+ If True traverse a directed graph in the reverse direction
123
+
124
+ depth_limit : int, optional(default=len(G))
125
+ Specify the maximum search depth
126
+
127
+ sort_neighbors : function (default=None)
128
+ A function that takes an iterator over nodes as the input, and
129
+ returns an iterable of the same nodes with a custom ordering.
130
+ For example, `sorted` will sort the nodes in increasing order.
131
+
132
+ Yields
133
+ ------
134
+ edge: 2-tuple of nodes
135
+ Yields edges resulting from the breadth-first search.
136
+
137
+ Examples
138
+ --------
139
+ To get the edges in a breadth-first search::
140
+
141
+ >>> G = nx.path_graph(3)
142
+ >>> list(nx.bfs_edges(G, 0))
143
+ [(0, 1), (1, 2)]
144
+ >>> list(nx.bfs_edges(G, source=0, depth_limit=1))
145
+ [(0, 1)]
146
+
147
+ To get the nodes in a breadth-first search order::
148
+
149
+ >>> G = nx.path_graph(3)
150
+ >>> root = 2
151
+ >>> edges = nx.bfs_edges(G, root)
152
+ >>> nodes = [root] + [v for u, v in edges]
153
+ >>> nodes
154
+ [2, 1, 0]
155
+
156
+ Notes
157
+ -----
158
+ The naming of this function is very similar to
159
+ :func:`~networkx.algorithms.traversal.edgebfs.edge_bfs`. The difference
160
+ is that ``edge_bfs`` yields edges even if they extend back to an already
161
+ explored node while this generator yields the edges of the tree that results
162
+ from a breadth-first-search (BFS) so no edges are reported if they extend
163
+ to already explored nodes. That means ``edge_bfs`` reports all edges while
164
+ ``bfs_edges`` only reports those traversed by a node-based BFS. Yet another
165
+ description is that ``bfs_edges`` reports the edges traversed during BFS
166
+ while ``edge_bfs`` reports all edges in the order they are explored.
167
+
168
+ Based on the breadth-first search implementation in PADS [1]_
169
+ by D. Eppstein, July 2004; with modifications to allow depth limits
170
+ as described in [2]_.
171
+
172
+ References
173
+ ----------
174
+ .. [1] http://www.ics.uci.edu/~eppstein/PADS/BFS.py.
175
+ .. [2] https://en.wikipedia.org/wiki/Depth-limited_search
176
+
177
+ See Also
178
+ --------
179
+ bfs_tree
180
+ :func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`
181
+ :func:`~networkx.algorithms.traversal.edgebfs.edge_bfs`
182
+
183
+ """
184
+ if reverse and G.is_directed():
185
+ successors = G.predecessors
186
+ else:
187
+ successors = G.neighbors
188
+
189
+ if sort_neighbors is not None:
190
+ yield from generic_bfs_edges(
191
+ G, source, lambda node: iter(sort_neighbors(successors(node))), depth_limit
192
+ )
193
+ else:
194
+ yield from generic_bfs_edges(G, source, successors, depth_limit)
195
+
196
+
197
+ @nx._dispatchable(returns_graph=True)
198
+ def bfs_tree(G, source, reverse=False, depth_limit=None, sort_neighbors=None):
199
+ """Returns an oriented tree constructed from of a breadth-first-search
200
+ starting at source.
201
+
202
+ Parameters
203
+ ----------
204
+ G : NetworkX graph
205
+
206
+ source : node
207
+ Specify starting node for breadth-first search
208
+
209
+ reverse : bool, optional
210
+ If True traverse a directed graph in the reverse direction
211
+
212
+ depth_limit : int, optional(default=len(G))
213
+ Specify the maximum search depth
214
+
215
+ sort_neighbors : function (default=None)
216
+ A function that takes an iterator over nodes as the input, and
217
+ returns an iterable of the same nodes with a custom ordering.
218
+ For example, `sorted` will sort the nodes in increasing order.
219
+
220
+ Returns
221
+ -------
222
+ T: NetworkX DiGraph
223
+ An oriented tree
224
+
225
+ Examples
226
+ --------
227
+ >>> G = nx.path_graph(3)
228
+ >>> list(nx.bfs_tree(G, 1).edges())
229
+ [(1, 0), (1, 2)]
230
+ >>> H = nx.Graph()
231
+ >>> nx.add_path(H, [0, 1, 2, 3, 4, 5, 6])
232
+ >>> nx.add_path(H, [2, 7, 8, 9, 10])
233
+ >>> sorted(list(nx.bfs_tree(H, source=3, depth_limit=3).edges()))
234
+ [(1, 0), (2, 1), (2, 7), (3, 2), (3, 4), (4, 5), (5, 6), (7, 8)]
235
+
236
+
237
+ Notes
238
+ -----
239
+ Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
240
+ by D. Eppstein, July 2004. The modifications
241
+ to allow depth limits based on the Wikipedia article
242
+ "`Depth-limited-search`_".
243
+
244
+ .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
245
+
246
+ See Also
247
+ --------
248
+ dfs_tree
249
+ bfs_edges
250
+ edge_bfs
251
+ """
252
+ T = nx.DiGraph()
253
+ T.add_node(source)
254
+ edges_gen = bfs_edges(
255
+ G,
256
+ source,
257
+ reverse=reverse,
258
+ depth_limit=depth_limit,
259
+ sort_neighbors=sort_neighbors,
260
+ )
261
+ T.add_edges_from(edges_gen)
262
+ return T
263
+
264
+
265
+ @nx._dispatchable
266
+ def bfs_predecessors(G, source, depth_limit=None, sort_neighbors=None):
267
+ """Returns an iterator of predecessors in breadth-first-search from source.
268
+
269
+ Parameters
270
+ ----------
271
+ G : NetworkX graph
272
+
273
+ source : node
274
+ Specify starting node for breadth-first search
275
+
276
+ depth_limit : int, optional(default=len(G))
277
+ Specify the maximum search depth
278
+
279
+ sort_neighbors : function (default=None)
280
+ A function that takes an iterator over nodes as the input, and
281
+ returns an iterable of the same nodes with a custom ordering.
282
+ For example, `sorted` will sort the nodes in increasing order.
283
+
284
+ Returns
285
+ -------
286
+ pred: iterator
287
+ (node, predecessor) iterator where `predecessor` is the predecessor of
288
+ `node` in a breadth first search starting from `source`.
289
+
290
+ Examples
291
+ --------
292
+ >>> G = nx.path_graph(3)
293
+ >>> dict(nx.bfs_predecessors(G, 0))
294
+ {1: 0, 2: 1}
295
+ >>> H = nx.Graph()
296
+ >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
297
+ >>> dict(nx.bfs_predecessors(H, 0))
298
+ {1: 0, 2: 0, 3: 1, 4: 1, 5: 2, 6: 2}
299
+ >>> M = nx.Graph()
300
+ >>> nx.add_path(M, [0, 1, 2, 3, 4, 5, 6])
301
+ >>> nx.add_path(M, [2, 7, 8, 9, 10])
302
+ >>> sorted(nx.bfs_predecessors(M, source=1, depth_limit=3))
303
+ [(0, 1), (2, 1), (3, 2), (4, 3), (7, 2), (8, 7)]
304
+ >>> N = nx.DiGraph()
305
+ >>> nx.add_path(N, [0, 1, 2, 3, 4, 7])
306
+ >>> nx.add_path(N, [3, 5, 6, 7])
307
+ >>> sorted(nx.bfs_predecessors(N, source=2))
308
+ [(3, 2), (4, 3), (5, 3), (6, 5), (7, 4)]
309
+
310
+ Notes
311
+ -----
312
+ Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
313
+ by D. Eppstein, July 2004. The modifications
314
+ to allow depth limits based on the Wikipedia article
315
+ "`Depth-limited-search`_".
316
+
317
+ .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
318
+
319
+ See Also
320
+ --------
321
+ bfs_tree
322
+ bfs_edges
323
+ edge_bfs
324
+ """
325
+ for s, t in bfs_edges(
326
+ G, source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
327
+ ):
328
+ yield (t, s)
329
+
330
+
331
+ @nx._dispatchable
332
+ def bfs_successors(G, source, depth_limit=None, sort_neighbors=None):
333
+ """Returns an iterator of successors in breadth-first-search from source.
334
+
335
+ Parameters
336
+ ----------
337
+ G : NetworkX graph
338
+
339
+ source : node
340
+ Specify starting node for breadth-first search
341
+
342
+ depth_limit : int, optional(default=len(G))
343
+ Specify the maximum search depth
344
+
345
+ sort_neighbors : function (default=None)
346
+ A function that takes an iterator over nodes as the input, and
347
+ returns an iterable of the same nodes with a custom ordering.
348
+ For example, `sorted` will sort the nodes in increasing order.
349
+
350
+ Returns
351
+ -------
352
+ succ: iterator
353
+ (node, successors) iterator where `successors` is the non-empty list of
354
+ successors of `node` in a breadth first search from `source`.
355
+ To appear in the iterator, `node` must have successors.
356
+
357
+ Examples
358
+ --------
359
+ >>> G = nx.path_graph(3)
360
+ >>> dict(nx.bfs_successors(G, 0))
361
+ {0: [1], 1: [2]}
362
+ >>> H = nx.Graph()
363
+ >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
364
+ >>> dict(nx.bfs_successors(H, 0))
365
+ {0: [1, 2], 1: [3, 4], 2: [5, 6]}
366
+ >>> G = nx.Graph()
367
+ >>> nx.add_path(G, [0, 1, 2, 3, 4, 5, 6])
368
+ >>> nx.add_path(G, [2, 7, 8, 9, 10])
369
+ >>> dict(nx.bfs_successors(G, source=1, depth_limit=3))
370
+ {1: [0, 2], 2: [3, 7], 3: [4], 7: [8]}
371
+ >>> G = nx.DiGraph()
372
+ >>> nx.add_path(G, [0, 1, 2, 3, 4, 5])
373
+ >>> dict(nx.bfs_successors(G, source=3))
374
+ {3: [4], 4: [5]}
375
+
376
+ Notes
377
+ -----
378
+ Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
379
+ by D. Eppstein, July 2004.The modifications
380
+ to allow depth limits based on the Wikipedia article
381
+ "`Depth-limited-search`_".
382
+
383
+ .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
384
+
385
+ See Also
386
+ --------
387
+ bfs_tree
388
+ bfs_edges
389
+ edge_bfs
390
+ """
391
+ parent = source
392
+ children = []
393
+ for p, c in bfs_edges(
394
+ G, source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
395
+ ):
396
+ if p == parent:
397
+ children.append(c)
398
+ continue
399
+ yield (parent, children)
400
+ children = [c]
401
+ parent = p
402
+ yield (parent, children)
403
+
404
+
405
+ @nx._dispatchable
406
+ def bfs_layers(G, sources):
407
+ """Returns an iterator of all the layers in breadth-first search traversal.
408
+
409
+ Parameters
410
+ ----------
411
+ G : NetworkX graph
412
+ A graph over which to find the layers using breadth-first search.
413
+
414
+ sources : node in `G` or list of nodes in `G`
415
+ Specify starting nodes for single source or multiple sources breadth-first search
416
+
417
+ Yields
418
+ ------
419
+ layer: list of nodes
420
+ Yields list of nodes at the same distance from sources
421
+
422
+ Examples
423
+ --------
424
+ >>> G = nx.path_graph(5)
425
+ >>> dict(enumerate(nx.bfs_layers(G, [0, 4])))
426
+ {0: [0, 4], 1: [1, 3], 2: [2]}
427
+ >>> H = nx.Graph()
428
+ >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
429
+ >>> dict(enumerate(nx.bfs_layers(H, [1])))
430
+ {0: [1], 1: [0, 3, 4], 2: [2], 3: [5, 6]}
431
+ >>> dict(enumerate(nx.bfs_layers(H, [1, 6])))
432
+ {0: [1, 6], 1: [0, 3, 4, 2], 2: [5]}
433
+ """
434
+ if sources in G:
435
+ sources = [sources]
436
+
437
+ current_layer = list(sources)
438
+ visited = set(sources)
439
+
440
+ for source in current_layer:
441
+ if source not in G:
442
+ raise nx.NetworkXError(f"The node {source} is not in the graph.")
443
+
444
+ # this is basically BFS, except that the current layer only stores the nodes at
445
+ # same distance from sources at each iteration
446
+ while current_layer:
447
+ yield current_layer
448
+ next_layer = []
449
+ for node in current_layer:
450
+ for child in G[node]:
451
+ if child not in visited:
452
+ visited.add(child)
453
+ next_layer.append(child)
454
+ current_layer = next_layer
455
+
456
+
457
+ REVERSE_EDGE = "reverse"
458
+ TREE_EDGE = "tree"
459
+ FORWARD_EDGE = "forward"
460
+ LEVEL_EDGE = "level"
461
+
462
+
463
+ @nx._dispatchable
464
+ def bfs_labeled_edges(G, sources):
465
+ """Iterate over edges in a breadth-first search (BFS) labeled by type.
466
+
467
+ We generate triple of the form (*u*, *v*, *d*), where (*u*, *v*) is the
468
+ edge being explored in the breadth-first search and *d* is one of the
469
+ strings 'tree', 'forward', 'level', or 'reverse'. A 'tree' edge is one in
470
+ which *v* is first discovered and placed into the layer below *u*. A
471
+ 'forward' edge is one in which *u* is on the layer above *v* and *v* has
472
+ already been discovered. A 'level' edge is one in which both *u* and *v*
473
+ occur on the same layer. A 'reverse' edge is one in which *u* is on a layer
474
+ below *v*.
475
+
476
+ We emit each edge exactly once. In an undirected graph, 'reverse' edges do
477
+ not occur, because each is discovered either as a 'tree' or 'forward' edge.
478
+
479
+ Parameters
480
+ ----------
481
+ G : NetworkX graph
482
+ A graph over which to find the layers using breadth-first search.
483
+
484
+ sources : node in `G` or list of nodes in `G`
485
+ Starting nodes for single source or multiple sources breadth-first search
486
+
487
+ Yields
488
+ ------
489
+ edges: generator
490
+ A generator of triples (*u*, *v*, *d*) where (*u*, *v*) is the edge being
491
+ explored and *d* is described above.
492
+
493
+ Examples
494
+ --------
495
+ >>> G = nx.cycle_graph(4, create_using=nx.DiGraph)
496
+ >>> list(nx.bfs_labeled_edges(G, 0))
497
+ [(0, 1, 'tree'), (1, 2, 'tree'), (2, 3, 'tree'), (3, 0, 'reverse')]
498
+ >>> G = nx.complete_graph(3)
499
+ >>> list(nx.bfs_labeled_edges(G, 0))
500
+ [(0, 1, 'tree'), (0, 2, 'tree'), (1, 2, 'level')]
501
+ >>> list(nx.bfs_labeled_edges(G, [0, 1]))
502
+ [(0, 1, 'level'), (0, 2, 'tree'), (1, 2, 'forward')]
503
+ """
504
+ if sources in G:
505
+ sources = [sources]
506
+
507
+ neighbors = G._adj
508
+ directed = G.is_directed()
509
+ visited = set()
510
+ visit = visited.discard if directed else visited.add
511
+ # We use visited in a negative sense, so the visited set stays empty for the
512
+ # directed case and level edges are reported on their first occurrence in
513
+ # the undirected case. Note our use of visited.discard -- this is built-in
514
+ # thus somewhat faster than a python-defined def nop(x): pass
515
+ depth = {s: 0 for s in sources}
516
+ queue = deque(depth.items())
517
+ push = queue.append
518
+ pop = queue.popleft
519
+ while queue:
520
+ u, du = pop()
521
+ for v in neighbors[u]:
522
+ if v not in depth:
523
+ depth[v] = dv = du + 1
524
+ push((v, dv))
525
+ yield u, v, TREE_EDGE
526
+ else:
527
+ dv = depth[v]
528
+ if du == dv:
529
+ if v not in visited:
530
+ yield u, v, LEVEL_EDGE
531
+ elif du < dv:
532
+ yield u, v, FORWARD_EDGE
533
+ elif directed:
534
+ yield u, v, REVERSE_EDGE
535
+ visit(u)
536
+
537
+
538
+ @nx._dispatchable
539
+ def descendants_at_distance(G, source, distance):
540
+ """Returns all nodes at a fixed `distance` from `source` in `G`.
541
+
542
+ Parameters
543
+ ----------
544
+ G : NetworkX graph
545
+ A graph
546
+ source : node in `G`
547
+ distance : the distance of the wanted nodes from `source`
548
+
549
+ Returns
550
+ -------
551
+ set()
552
+ The descendants of `source` in `G` at the given `distance` from `source`
553
+
554
+ Examples
555
+ --------
556
+ >>> G = nx.path_graph(5)
557
+ >>> nx.descendants_at_distance(G, 2, 2)
558
+ {0, 4}
559
+ >>> H = nx.DiGraph()
560
+ >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
561
+ >>> nx.descendants_at_distance(H, 0, 2)
562
+ {3, 4, 5, 6}
563
+ >>> nx.descendants_at_distance(H, 5, 0)
564
+ {5}
565
+ >>> nx.descendants_at_distance(H, 5, 1)
566
+ set()
567
+ """
568
+ if source not in G:
569
+ raise nx.NetworkXError(f"The node {source} is not in the graph.")
570
+
571
+ bfs_generator = nx.bfs_layers(G, source)
572
+ for i, layer in enumerate(bfs_generator):
573
+ if i == distance:
574
+ return set(layer)
575
+ return set()
janus/lib/python3.10/site-packages/networkx/algorithms/traversal/depth_first_search.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Basic algorithms for depth-first searching the nodes of a graph."""
2
+
3
+ from collections import defaultdict
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "dfs_edges",
9
+ "dfs_tree",
10
+ "dfs_predecessors",
11
+ "dfs_successors",
12
+ "dfs_preorder_nodes",
13
+ "dfs_postorder_nodes",
14
+ "dfs_labeled_edges",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable
19
+ def dfs_edges(G, source=None, depth_limit=None, *, sort_neighbors=None):
20
+ """Iterate over edges in a depth-first-search (DFS).
21
+
22
+ Perform a depth-first-search over the nodes of `G` and yield
23
+ the edges in order. This may not generate all edges in `G`
24
+ (see `~networkx.algorithms.traversal.edgedfs.edge_dfs`).
25
+
26
+ Parameters
27
+ ----------
28
+ G : NetworkX graph
29
+
30
+ source : node, optional
31
+ Specify starting node for depth-first search and yield edges in
32
+ the component reachable from source.
33
+
34
+ depth_limit : int, optional (default=len(G))
35
+ Specify the maximum search depth.
36
+
37
+ sort_neighbors : function (default=None)
38
+ A function that takes an iterator over nodes as the input, and
39
+ returns an iterable of the same nodes with a custom ordering.
40
+ For example, `sorted` will sort the nodes in increasing order.
41
+
42
+ Yields
43
+ ------
44
+ edge: 2-tuple of nodes
45
+ Yields edges resulting from the depth-first-search.
46
+
47
+ Examples
48
+ --------
49
+ >>> G = nx.path_graph(5)
50
+ >>> list(nx.dfs_edges(G, source=0))
51
+ [(0, 1), (1, 2), (2, 3), (3, 4)]
52
+ >>> list(nx.dfs_edges(G, source=0, depth_limit=2))
53
+ [(0, 1), (1, 2)]
54
+
55
+ Notes
56
+ -----
57
+ If a source is not specified then a source is chosen arbitrarily and
58
+ repeatedly until all components in the graph are searched.
59
+
60
+ The implementation of this function is adapted from David Eppstein's
61
+ depth-first search function in PADS [1]_, with modifications
62
+ to allow depth limits based on the Wikipedia article
63
+ "Depth-limited search" [2]_.
64
+
65
+ See Also
66
+ --------
67
+ dfs_preorder_nodes
68
+ dfs_postorder_nodes
69
+ dfs_labeled_edges
70
+ :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
71
+ :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_edges`
72
+
73
+ References
74
+ ----------
75
+ .. [1] http://www.ics.uci.edu/~eppstein/PADS
76
+ .. [2] https://en.wikipedia.org/wiki/Depth-limited_search
77
+ """
78
+ if source is None:
79
+ # edges for all components
80
+ nodes = G
81
+ else:
82
+ # edges for components with source
83
+ nodes = [source]
84
+ if depth_limit is None:
85
+ depth_limit = len(G)
86
+
87
+ get_children = (
88
+ G.neighbors
89
+ if sort_neighbors is None
90
+ else lambda n: iter(sort_neighbors(G.neighbors(n)))
91
+ )
92
+
93
+ visited = set()
94
+ for start in nodes:
95
+ if start in visited:
96
+ continue
97
+ visited.add(start)
98
+ stack = [(start, get_children(start))]
99
+ depth_now = 1
100
+ while stack:
101
+ parent, children = stack[-1]
102
+ for child in children:
103
+ if child not in visited:
104
+ yield parent, child
105
+ visited.add(child)
106
+ if depth_now < depth_limit:
107
+ stack.append((child, get_children(child)))
108
+ depth_now += 1
109
+ break
110
+ else:
111
+ stack.pop()
112
+ depth_now -= 1
113
+
114
+
115
+ @nx._dispatchable(returns_graph=True)
116
+ def dfs_tree(G, source=None, depth_limit=None, *, sort_neighbors=None):
117
+ """Returns oriented tree constructed from a depth-first-search from source.
118
+
119
+ Parameters
120
+ ----------
121
+ G : NetworkX graph
122
+
123
+ source : node, optional
124
+ Specify starting node for depth-first search.
125
+
126
+ depth_limit : int, optional (default=len(G))
127
+ Specify the maximum search depth.
128
+
129
+ sort_neighbors : function (default=None)
130
+ A function that takes an iterator over nodes as the input, and
131
+ returns an iterable of the same nodes with a custom ordering.
132
+ For example, `sorted` will sort the nodes in increasing order.
133
+
134
+ Returns
135
+ -------
136
+ T : NetworkX DiGraph
137
+ An oriented tree
138
+
139
+ Examples
140
+ --------
141
+ >>> G = nx.path_graph(5)
142
+ >>> T = nx.dfs_tree(G, source=0, depth_limit=2)
143
+ >>> list(T.edges())
144
+ [(0, 1), (1, 2)]
145
+ >>> T = nx.dfs_tree(G, source=0)
146
+ >>> list(T.edges())
147
+ [(0, 1), (1, 2), (2, 3), (3, 4)]
148
+
149
+ See Also
150
+ --------
151
+ dfs_preorder_nodes
152
+ dfs_postorder_nodes
153
+ dfs_labeled_edges
154
+ :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
155
+ :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
156
+ """
157
+ T = nx.DiGraph()
158
+ if source is None:
159
+ T.add_nodes_from(G)
160
+ else:
161
+ T.add_node(source)
162
+ T.add_edges_from(dfs_edges(G, source, depth_limit, sort_neighbors=sort_neighbors))
163
+ return T
164
+
165
+
166
+ @nx._dispatchable
167
+ def dfs_predecessors(G, source=None, depth_limit=None, *, sort_neighbors=None):
168
+ """Returns dictionary of predecessors in depth-first-search from source.
169
+
170
+ Parameters
171
+ ----------
172
+ G : NetworkX graph
173
+
174
+ source : node, optional
175
+ Specify starting node for depth-first search.
176
+ Note that you will get predecessors for all nodes in the
177
+ component containing `source`. This input only specifies
178
+ where the DFS starts.
179
+
180
+ depth_limit : int, optional (default=len(G))
181
+ Specify the maximum search depth.
182
+
183
+ sort_neighbors : function (default=None)
184
+ A function that takes an iterator over nodes as the input, and
185
+ returns an iterable of the same nodes with a custom ordering.
186
+ For example, `sorted` will sort the nodes in increasing order.
187
+
188
+ Returns
189
+ -------
190
+ pred: dict
191
+ A dictionary with nodes as keys and predecessor nodes as values.
192
+
193
+ Examples
194
+ --------
195
+ >>> G = nx.path_graph(4)
196
+ >>> nx.dfs_predecessors(G, source=0)
197
+ {1: 0, 2: 1, 3: 2}
198
+ >>> nx.dfs_predecessors(G, source=0, depth_limit=2)
199
+ {1: 0, 2: 1}
200
+
201
+ Notes
202
+ -----
203
+ If a source is not specified then a source is chosen arbitrarily and
204
+ repeatedly until all components in the graph are searched.
205
+
206
+ The implementation of this function is adapted from David Eppstein's
207
+ depth-first search function in `PADS`_, with modifications
208
+ to allow depth limits based on the Wikipedia article
209
+ "`Depth-limited search`_".
210
+
211
+ .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
212
+ .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
213
+
214
+ See Also
215
+ --------
216
+ dfs_preorder_nodes
217
+ dfs_postorder_nodes
218
+ dfs_labeled_edges
219
+ :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
220
+ :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
221
+ """
222
+ return {
223
+ t: s
224
+ for s, t in dfs_edges(G, source, depth_limit, sort_neighbors=sort_neighbors)
225
+ }
226
+
227
+
228
+ @nx._dispatchable
229
+ def dfs_successors(G, source=None, depth_limit=None, *, sort_neighbors=None):
230
+ """Returns dictionary of successors in depth-first-search from source.
231
+
232
+ Parameters
233
+ ----------
234
+ G : NetworkX graph
235
+
236
+ source : node, optional
237
+ Specify starting node for depth-first search.
238
+ Note that you will get successors for all nodes in the
239
+ component containing `source`. This input only specifies
240
+ where the DFS starts.
241
+
242
+ depth_limit : int, optional (default=len(G))
243
+ Specify the maximum search depth.
244
+
245
+ sort_neighbors : function (default=None)
246
+ A function that takes an iterator over nodes as the input, and
247
+ returns an iterable of the same nodes with a custom ordering.
248
+ For example, `sorted` will sort the nodes in increasing order.
249
+
250
+ Returns
251
+ -------
252
+ succ: dict
253
+ A dictionary with nodes as keys and list of successor nodes as values.
254
+
255
+ Examples
256
+ --------
257
+ >>> G = nx.path_graph(5)
258
+ >>> nx.dfs_successors(G, source=0)
259
+ {0: [1], 1: [2], 2: [3], 3: [4]}
260
+ >>> nx.dfs_successors(G, source=0, depth_limit=2)
261
+ {0: [1], 1: [2]}
262
+
263
+ Notes
264
+ -----
265
+ If a source is not specified then a source is chosen arbitrarily and
266
+ repeatedly until all components in the graph are searched.
267
+
268
+ The implementation of this function is adapted from David Eppstein's
269
+ depth-first search function in `PADS`_, with modifications
270
+ to allow depth limits based on the Wikipedia article
271
+ "`Depth-limited search`_".
272
+
273
+ .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
274
+ .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
275
+
276
+ See Also
277
+ --------
278
+ dfs_preorder_nodes
279
+ dfs_postorder_nodes
280
+ dfs_labeled_edges
281
+ :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
282
+ :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
283
+ """
284
+ d = defaultdict(list)
285
+ for s, t in dfs_edges(
286
+ G,
287
+ source=source,
288
+ depth_limit=depth_limit,
289
+ sort_neighbors=sort_neighbors,
290
+ ):
291
+ d[s].append(t)
292
+ return dict(d)
293
+
294
+
295
+ @nx._dispatchable
296
+ def dfs_postorder_nodes(G, source=None, depth_limit=None, *, sort_neighbors=None):
297
+ """Generate nodes in a depth-first-search post-ordering starting at source.
298
+
299
+ Parameters
300
+ ----------
301
+ G : NetworkX graph
302
+
303
+ source : node, optional
304
+ Specify starting node for depth-first search.
305
+
306
+ depth_limit : int, optional (default=len(G))
307
+ Specify the maximum search depth.
308
+
309
+ sort_neighbors : function (default=None)
310
+ A function that takes an iterator over nodes as the input, and
311
+ returns an iterable of the same nodes with a custom ordering.
312
+ For example, `sorted` will sort the nodes in increasing order.
313
+
314
+ Returns
315
+ -------
316
+ nodes: generator
317
+ A generator of nodes in a depth-first-search post-ordering.
318
+
319
+ Examples
320
+ --------
321
+ >>> G = nx.path_graph(5)
322
+ >>> list(nx.dfs_postorder_nodes(G, source=0))
323
+ [4, 3, 2, 1, 0]
324
+ >>> list(nx.dfs_postorder_nodes(G, source=0, depth_limit=2))
325
+ [1, 0]
326
+
327
+ Notes
328
+ -----
329
+ If a source is not specified then a source is chosen arbitrarily and
330
+ repeatedly until all components in the graph are searched.
331
+
332
+ The implementation of this function is adapted from David Eppstein's
333
+ depth-first search function in `PADS`_, with modifications
334
+ to allow depth limits based on the Wikipedia article
335
+ "`Depth-limited search`_".
336
+
337
+ .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
338
+ .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
339
+
340
+ See Also
341
+ --------
342
+ dfs_edges
343
+ dfs_preorder_nodes
344
+ dfs_labeled_edges
345
+ :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
346
+ :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
347
+ """
348
+ edges = nx.dfs_labeled_edges(
349
+ G, source=source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
350
+ )
351
+ return (v for u, v, d in edges if d == "reverse")
352
+
353
+
354
+ @nx._dispatchable
355
+ def dfs_preorder_nodes(G, source=None, depth_limit=None, *, sort_neighbors=None):
356
+ """Generate nodes in a depth-first-search pre-ordering starting at source.
357
+
358
+ Parameters
359
+ ----------
360
+ G : NetworkX graph
361
+
362
+ source : node, optional
363
+ Specify starting node for depth-first search and return nodes in
364
+ the component reachable from source.
365
+
366
+ depth_limit : int, optional (default=len(G))
367
+ Specify the maximum search depth.
368
+
369
+ sort_neighbors : function (default=None)
370
+ A function that takes an iterator over nodes as the input, and
371
+ returns an iterable of the same nodes with a custom ordering.
372
+ For example, `sorted` will sort the nodes in increasing order.
373
+
374
+ Returns
375
+ -------
376
+ nodes: generator
377
+ A generator of nodes in a depth-first-search pre-ordering.
378
+
379
+ Examples
380
+ --------
381
+ >>> G = nx.path_graph(5)
382
+ >>> list(nx.dfs_preorder_nodes(G, source=0))
383
+ [0, 1, 2, 3, 4]
384
+ >>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2))
385
+ [0, 1, 2]
386
+
387
+ Notes
388
+ -----
389
+ If a source is not specified then a source is chosen arbitrarily and
390
+ repeatedly until all components in the graph are searched.
391
+
392
+ The implementation of this function is adapted from David Eppstein's
393
+ depth-first search function in `PADS`_, with modifications
394
+ to allow depth limits based on the Wikipedia article
395
+ "`Depth-limited search`_".
396
+
397
+ .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
398
+ .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
399
+
400
+ See Also
401
+ --------
402
+ dfs_edges
403
+ dfs_postorder_nodes
404
+ dfs_labeled_edges
405
+ :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_edges`
406
+ """
407
+ edges = nx.dfs_labeled_edges(
408
+ G, source=source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
409
+ )
410
+ return (v for u, v, d in edges if d == "forward")
411
+
412
+
413
+ @nx._dispatchable
414
+ def dfs_labeled_edges(G, source=None, depth_limit=None, *, sort_neighbors=None):
415
+ """Iterate over edges in a depth-first-search (DFS) labeled by type.
416
+
417
+ Parameters
418
+ ----------
419
+ G : NetworkX graph
420
+
421
+ source : node, optional
422
+ Specify starting node for depth-first search and return edges in
423
+ the component reachable from source.
424
+
425
+ depth_limit : int, optional (default=len(G))
426
+ Specify the maximum search depth.
427
+
428
+ sort_neighbors : function (default=None)
429
+ A function that takes an iterator over nodes as the input, and
430
+ returns an iterable of the same nodes with a custom ordering.
431
+ For example, `sorted` will sort the nodes in increasing order.
432
+
433
+ Returns
434
+ -------
435
+ edges: generator
436
+ A generator of triples of the form (*u*, *v*, *d*), where (*u*,
437
+ *v*) is the edge being explored in the depth-first search and *d*
438
+ is one of the strings 'forward', 'nontree', 'reverse', or 'reverse-depth_limit'.
439
+ A 'forward' edge is one in which *u* has been visited but *v* has
440
+ not. A 'nontree' edge is one in which both *u* and *v* have been
441
+ visited but the edge is not in the DFS tree. A 'reverse' edge is
442
+ one in which both *u* and *v* have been visited and the edge is in
443
+ the DFS tree. When the `depth_limit` is reached via a 'forward' edge,
444
+ a 'reverse' edge is immediately generated rather than the subtree
445
+ being explored. To indicate this flavor of 'reverse' edge, the string
446
+ yielded is 'reverse-depth_limit'.
447
+
448
+ Examples
449
+ --------
450
+
451
+ The labels reveal the complete transcript of the depth-first search
452
+ algorithm in more detail than, for example, :func:`dfs_edges`::
453
+
454
+ >>> from pprint import pprint
455
+ >>>
456
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 1)])
457
+ >>> pprint(list(nx.dfs_labeled_edges(G, source=0)))
458
+ [(0, 0, 'forward'),
459
+ (0, 1, 'forward'),
460
+ (1, 2, 'forward'),
461
+ (2, 1, 'nontree'),
462
+ (1, 2, 'reverse'),
463
+ (0, 1, 'reverse'),
464
+ (0, 0, 'reverse')]
465
+
466
+ Notes
467
+ -----
468
+ If a source is not specified then a source is chosen arbitrarily and
469
+ repeatedly until all components in the graph are searched.
470
+
471
+ The implementation of this function is adapted from David Eppstein's
472
+ depth-first search function in `PADS`_, with modifications
473
+ to allow depth limits based on the Wikipedia article
474
+ "`Depth-limited search`_".
475
+
476
+ .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
477
+ .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
478
+
479
+ See Also
480
+ --------
481
+ dfs_edges
482
+ dfs_preorder_nodes
483
+ dfs_postorder_nodes
484
+ """
485
+ # Based on http://www.ics.uci.edu/~eppstein/PADS/DFS.py
486
+ # by D. Eppstein, July 2004.
487
+ if source is None:
488
+ # edges for all components
489
+ nodes = G
490
+ else:
491
+ # edges for components with source
492
+ nodes = [source]
493
+ if depth_limit is None:
494
+ depth_limit = len(G)
495
+
496
+ get_children = (
497
+ G.neighbors
498
+ if sort_neighbors is None
499
+ else lambda n: iter(sort_neighbors(G.neighbors(n)))
500
+ )
501
+
502
+ visited = set()
503
+ for start in nodes:
504
+ if start in visited:
505
+ continue
506
+ yield start, start, "forward"
507
+ visited.add(start)
508
+ stack = [(start, get_children(start))]
509
+ depth_now = 1
510
+ while stack:
511
+ parent, children = stack[-1]
512
+ for child in children:
513
+ if child in visited:
514
+ yield parent, child, "nontree"
515
+ else:
516
+ yield parent, child, "forward"
517
+ visited.add(child)
518
+ if depth_now < depth_limit:
519
+ stack.append((child, iter(get_children(child))))
520
+ depth_now += 1
521
+ break
522
+ else:
523
+ yield parent, child, "reverse-depth_limit"
524
+ else:
525
+ stack.pop()
526
+ depth_now -= 1
527
+ if stack:
528
+ yield stack[-1][0], parent, "reverse"
529
+ yield start, start, "reverse"
janus/lib/python3.10/site-packages/networkx/algorithms/traversal/edgebfs.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =============================
3
+ Breadth First Search on Edges
4
+ =============================
5
+
6
+ Algorithms for a breadth-first traversal of edges in a graph.
7
+
8
+ """
9
+
10
+ from collections import deque
11
+
12
+ import networkx as nx
13
+
14
+ FORWARD = "forward"
15
+ REVERSE = "reverse"
16
+
17
+ __all__ = ["edge_bfs"]
18
+
19
+
20
+ @nx._dispatchable
21
+ def edge_bfs(G, source=None, orientation=None):
22
+ """A directed, breadth-first-search of edges in `G`, beginning at `source`.
23
+
24
+ Yield the edges of G in a breadth-first-search order continuing until
25
+ all edges are generated.
26
+
27
+ Parameters
28
+ ----------
29
+ G : graph
30
+ A directed/undirected graph/multigraph.
31
+
32
+ source : node, list of nodes
33
+ The node from which the traversal begins. If None, then a source
34
+ is chosen arbitrarily and repeatedly until all edges from each node in
35
+ the graph are searched.
36
+
37
+ orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
38
+ For directed graphs and directed multigraphs, edge traversals need not
39
+ respect the original orientation of the edges.
40
+ When set to 'reverse' every edge is traversed in the reverse direction.
41
+ When set to 'ignore', every edge is treated as undirected.
42
+ When set to 'original', every edge is treated as directed.
43
+ In all three cases, the yielded edge tuples add a last entry to
44
+ indicate the direction in which that edge was traversed.
45
+ If orientation is None, the yielded edge has no direction indicated.
46
+ The direction is respected, but not reported.
47
+
48
+ Yields
49
+ ------
50
+ edge : directed edge
51
+ A directed edge indicating the path taken by the breadth-first-search.
52
+ For graphs, `edge` is of the form `(u, v)` where `u` and `v`
53
+ are the tail and head of the edge as determined by the traversal.
54
+ For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
55
+ the key of the edge. When the graph is directed, then `u` and `v`
56
+ are always in the order of the actual directed edge.
57
+ If orientation is not None then the edge tuple is extended to include
58
+ the direction of traversal ('forward' or 'reverse') on that edge.
59
+
60
+ Examples
61
+ --------
62
+ >>> nodes = [0, 1, 2, 3]
63
+ >>> edges = [(0, 1), (1, 0), (1, 0), (2, 0), (2, 1), (3, 1)]
64
+
65
+ >>> list(nx.edge_bfs(nx.Graph(edges), nodes))
66
+ [(0, 1), (0, 2), (1, 2), (1, 3)]
67
+
68
+ >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes))
69
+ [(0, 1), (1, 0), (2, 0), (2, 1), (3, 1)]
70
+
71
+ >>> list(nx.edge_bfs(nx.MultiGraph(edges), nodes))
72
+ [(0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (1, 2, 0), (1, 3, 0)]
73
+
74
+ >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes))
75
+ [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 0, 0), (2, 1, 0), (3, 1, 0)]
76
+
77
+ >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes, orientation="ignore"))
78
+ [(0, 1, 'forward'), (1, 0, 'reverse'), (2, 0, 'reverse'), (2, 1, 'reverse'), (3, 1, 'reverse')]
79
+
80
+ >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
81
+ [(0, 1, 0, 'forward'), (1, 0, 0, 'reverse'), (1, 0, 1, 'reverse'), (2, 0, 0, 'reverse'), (2, 1, 0, 'reverse'), (3, 1, 0, 'reverse')]
82
+
83
+ Notes
84
+ -----
85
+ The goal of this function is to visit edges. It differs from the more
86
+ familiar breadth-first-search of nodes, as provided by
87
+ :func:`networkx.algorithms.traversal.breadth_first_search.bfs_edges`, in
88
+ that it does not stop once every node has been visited. In a directed graph
89
+ with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
90
+ if not for the functionality provided by this function.
91
+
92
+ The naming of this function is very similar to bfs_edges. The difference
93
+ is that 'edge_bfs' yields edges even if they extend back to an already
94
+ explored node while 'bfs_edges' yields the edges of the tree that results
95
+ from a breadth-first-search (BFS) so no edges are reported if they extend
96
+ to already explored nodes. That means 'edge_bfs' reports all edges while
97
+ 'bfs_edges' only report those traversed by a node-based BFS. Yet another
98
+ description is that 'bfs_edges' reports the edges traversed during BFS
99
+ while 'edge_bfs' reports all edges in the order they are explored.
100
+
101
+ See Also
102
+ --------
103
+ bfs_edges
104
+ bfs_tree
105
+ edge_dfs
106
+
107
+ """
108
+ nodes = list(G.nbunch_iter(source))
109
+ if not nodes:
110
+ return
111
+
112
+ directed = G.is_directed()
113
+ kwds = {"data": False}
114
+ if G.is_multigraph() is True:
115
+ kwds["keys"] = True
116
+
117
+ # set up edge lookup
118
+ if orientation is None:
119
+
120
+ def edges_from(node):
121
+ return iter(G.edges(node, **kwds))
122
+
123
+ elif not directed or orientation == "original":
124
+
125
+ def edges_from(node):
126
+ for e in G.edges(node, **kwds):
127
+ yield e + (FORWARD,)
128
+
129
+ elif orientation == "reverse":
130
+
131
+ def edges_from(node):
132
+ for e in G.in_edges(node, **kwds):
133
+ yield e + (REVERSE,)
134
+
135
+ elif orientation == "ignore":
136
+
137
+ def edges_from(node):
138
+ for e in G.edges(node, **kwds):
139
+ yield e + (FORWARD,)
140
+ for e in G.in_edges(node, **kwds):
141
+ yield e + (REVERSE,)
142
+
143
+ else:
144
+ raise nx.NetworkXError("invalid orientation argument.")
145
+
146
+ if directed:
147
+ neighbors = G.successors
148
+
149
+ def edge_id(edge):
150
+ # remove direction indicator
151
+ return edge[:-1] if orientation is not None else edge
152
+
153
+ else:
154
+ neighbors = G.neighbors
155
+
156
+ def edge_id(edge):
157
+ return (frozenset(edge[:2]),) + edge[2:]
158
+
159
+ check_reverse = directed and orientation in ("reverse", "ignore")
160
+
161
+ # start BFS
162
+ visited_nodes = set(nodes)
163
+ visited_edges = set()
164
+ queue = deque([(n, edges_from(n)) for n in nodes])
165
+ while queue:
166
+ parent, children_edges = queue.popleft()
167
+ for edge in children_edges:
168
+ if check_reverse and edge[-1] == REVERSE:
169
+ child = edge[0]
170
+ else:
171
+ child = edge[1]
172
+ if child not in visited_nodes:
173
+ visited_nodes.add(child)
174
+ queue.append((child, edges_from(child)))
175
+ edgeid = edge_id(edge)
176
+ if edgeid not in visited_edges:
177
+ visited_edges.add(edgeid)
178
+ yield edge