Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/chains.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/graph_hashing.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/link_prediction.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/planar_drawing.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/similarity.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/threshold.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/tournament.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__init__.py +11 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/__init__.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/boykovkolmogorov.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/capacityscaling.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/dinitz_alg.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/edmondskarp.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/gomory_hu.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/maxflow.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/mincost.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/networksimplex.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/preflowpush.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/shortestaugmentingpath.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/utils.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/boykovkolmogorov.py +369 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/capacityscaling.py +407 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/dinitz_alg.py +237 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/edmondskarp.py +241 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/gomory_hu.py +177 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/maxflow.py +601 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/mincost.py +356 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/networksimplex.py +666 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/preflowpush.py +425 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/shortestaugmentingpath.py +300 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__init__.py +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_gomory_hu.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_maxflow.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_maxflow_large_graph.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_mincost.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_networksimplex.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2 +3 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2 +3 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 +3 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_gomory_hu.py +128 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_maxflow.py +560 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_maxflow_large_graph.py +157 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_mincost.py +476 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_networksimplex.py +387 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 +3 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/flow/utils.py +189 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/traversal/__init__.py +5 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/__init__.cpython-310.pyc +0 -0
- valley/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/beamsearch.cpython-310.pyc +0 -0
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/chains.cpython-310.pyc
ADDED
|
Binary file (5.14 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/graph_hashing.cpython-310.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/link_prediction.cpython-310.pyc
ADDED
|
Binary file (23 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/planar_drawing.cpython-310.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/similarity.cpython-310.pyc
ADDED
|
Binary file (53.9 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/threshold.cpython-310.pyc
ADDED
|
Binary file (24.7 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/__pycache__/tournament.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
valley/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
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (501 Bytes). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/boykovkolmogorov.cpython-310.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/capacityscaling.cpython-310.pyc
ADDED
|
Binary file (11.7 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/dinitz_alg.cpython-310.pyc
ADDED
|
Binary file (7.26 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/edmondskarp.cpython-310.pyc
ADDED
|
Binary file (7.16 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/gomory_hu.cpython-310.pyc
ADDED
|
Binary file (5.87 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/maxflow.cpython-310.pyc
ADDED
|
Binary file (21.4 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/mincost.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/networksimplex.cpython-310.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/preflowpush.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/shortestaugmentingpath.cpython-310.pyc
ADDED
|
Binary file (7.99 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (6.39 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/boykovkolmogorov.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Boykov-Kolmogorov algorithm for maximum flow problems.
|
| 3 |
+
"""
|
| 4 |
+
from collections import deque
|
| 5 |
+
from operator import itemgetter
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.algorithms.flow.utils import build_residual_network
|
| 9 |
+
|
| 10 |
+
__all__ = ["boykov_kolmogorov"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
|
| 14 |
+
def boykov_kolmogorov(
|
| 15 |
+
G, s, t, capacity="capacity", residual=None, value_only=False, cutoff=None
|
| 16 |
+
):
|
| 17 |
+
r"""Find a maximum single-commodity flow using Boykov-Kolmogorov algorithm.
|
| 18 |
+
|
| 19 |
+
This function returns the residual network resulting after computing
|
| 20 |
+
the maximum flow. See below for details about the conventions
|
| 21 |
+
NetworkX uses for defining residual networks.
|
| 22 |
+
|
| 23 |
+
This algorithm has worse case complexity $O(n^2 m |C|)$ for $n$ nodes, $m$
|
| 24 |
+
edges, and $|C|$ the cost of the minimum cut [1]_. This implementation
|
| 25 |
+
uses the marking heuristic defined in [2]_ which improves its running
|
| 26 |
+
time in many practical problems.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
----------
|
| 30 |
+
G : NetworkX graph
|
| 31 |
+
Edges of the graph are expected to have an attribute called
|
| 32 |
+
'capacity'. If this attribute is not present, the edge is
|
| 33 |
+
considered to have infinite capacity.
|
| 34 |
+
|
| 35 |
+
s : node
|
| 36 |
+
Source node for the flow.
|
| 37 |
+
|
| 38 |
+
t : node
|
| 39 |
+
Sink node for the flow.
|
| 40 |
+
|
| 41 |
+
capacity : string
|
| 42 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 43 |
+
that indicates how much flow the edge can support. If this
|
| 44 |
+
attribute is not present, the edge is considered to have
|
| 45 |
+
infinite capacity. Default value: 'capacity'.
|
| 46 |
+
|
| 47 |
+
residual : NetworkX graph
|
| 48 |
+
Residual network on which the algorithm is to be executed. If None, a
|
| 49 |
+
new residual network is created. Default value: None.
|
| 50 |
+
|
| 51 |
+
value_only : bool
|
| 52 |
+
If True compute only the value of the maximum flow. This parameter
|
| 53 |
+
will be ignored by this algorithm because it is not applicable.
|
| 54 |
+
|
| 55 |
+
cutoff : integer, float
|
| 56 |
+
If specified, the algorithm will terminate when the flow value reaches
|
| 57 |
+
or exceeds the cutoff. In this case, it may be unable to immediately
|
| 58 |
+
determine a minimum cut. Default value: None.
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
R : NetworkX DiGraph
|
| 63 |
+
Residual network after computing the maximum flow.
|
| 64 |
+
|
| 65 |
+
Raises
|
| 66 |
+
------
|
| 67 |
+
NetworkXError
|
| 68 |
+
The algorithm does not support MultiGraph and MultiDiGraph. If
|
| 69 |
+
the input graph is an instance of one of these two classes, a
|
| 70 |
+
NetworkXError is raised.
|
| 71 |
+
|
| 72 |
+
NetworkXUnbounded
|
| 73 |
+
If the graph has a path of infinite capacity, the value of a
|
| 74 |
+
feasible flow on the graph is unbounded above and the function
|
| 75 |
+
raises a NetworkXUnbounded.
|
| 76 |
+
|
| 77 |
+
See also
|
| 78 |
+
--------
|
| 79 |
+
:meth:`maximum_flow`
|
| 80 |
+
:meth:`minimum_cut`
|
| 81 |
+
:meth:`preflow_push`
|
| 82 |
+
:meth:`shortest_augmenting_path`
|
| 83 |
+
|
| 84 |
+
Notes
|
| 85 |
+
-----
|
| 86 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 87 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 88 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 89 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 90 |
+
in :samp:`G`.
|
| 91 |
+
|
| 92 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 93 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 94 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 95 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 96 |
+
that does not affect the solution of the problem. This value is stored in
|
| 97 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 98 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 99 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 100 |
+
|
| 101 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 102 |
+
stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
|
| 103 |
+
specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
|
| 104 |
+
that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 105 |
+
:samp:`s`-:samp:`t` cut.
|
| 106 |
+
|
| 107 |
+
Examples
|
| 108 |
+
--------
|
| 109 |
+
>>> from networkx.algorithms.flow import boykov_kolmogorov
|
| 110 |
+
|
| 111 |
+
The functions that implement flow algorithms and output a residual
|
| 112 |
+
network, such as this one, are not imported to the base NetworkX
|
| 113 |
+
namespace, so you have to explicitly import them from the flow package.
|
| 114 |
+
|
| 115 |
+
>>> G = nx.DiGraph()
|
| 116 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 117 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 118 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 119 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 120 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 121 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 122 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 123 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 124 |
+
>>> R = boykov_kolmogorov(G, "x", "y")
|
| 125 |
+
>>> flow_value = nx.maximum_flow_value(G, "x", "y")
|
| 126 |
+
>>> flow_value
|
| 127 |
+
3.0
|
| 128 |
+
>>> flow_value == R.graph["flow_value"]
|
| 129 |
+
True
|
| 130 |
+
|
| 131 |
+
A nice feature of the Boykov-Kolmogorov algorithm is that a partition
|
| 132 |
+
of the nodes that defines a minimum cut can be easily computed based
|
| 133 |
+
on the search trees used during the algorithm. These trees are stored
|
| 134 |
+
in the graph attribute `trees` of the residual network.
|
| 135 |
+
|
| 136 |
+
>>> source_tree, target_tree = R.graph["trees"]
|
| 137 |
+
>>> partition = (set(source_tree), set(G) - set(source_tree))
|
| 138 |
+
|
| 139 |
+
Or equivalently:
|
| 140 |
+
|
| 141 |
+
>>> partition = (set(G) - set(target_tree), set(target_tree))
|
| 142 |
+
|
| 143 |
+
References
|
| 144 |
+
----------
|
| 145 |
+
.. [1] Boykov, Y., & Kolmogorov, V. (2004). An experimental comparison
|
| 146 |
+
of min-cut/max-flow algorithms for energy minimization in vision.
|
| 147 |
+
Pattern Analysis and Machine Intelligence, IEEE Transactions on,
|
| 148 |
+
26(9), 1124-1137.
|
| 149 |
+
https://doi.org/10.1109/TPAMI.2004.60
|
| 150 |
+
|
| 151 |
+
.. [2] Vladimir Kolmogorov. Graph-based Algorithms for Multi-camera
|
| 152 |
+
Reconstruction Problem. PhD thesis, Cornell University, CS Department,
|
| 153 |
+
2003. pp. 109-114.
|
| 154 |
+
https://web.archive.org/web/20170809091249/https://pub.ist.ac.at/~vnk/papers/thesis.pdf
|
| 155 |
+
|
| 156 |
+
"""
|
| 157 |
+
R = boykov_kolmogorov_impl(G, s, t, capacity, residual, cutoff)
|
| 158 |
+
R.graph["algorithm"] = "boykov_kolmogorov"
|
| 159 |
+
nx._clear_cache(R)
|
| 160 |
+
return R
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def boykov_kolmogorov_impl(G, s, t, capacity, residual, cutoff):
|
| 164 |
+
if s not in G:
|
| 165 |
+
raise nx.NetworkXError(f"node {str(s)} not in graph")
|
| 166 |
+
if t not in G:
|
| 167 |
+
raise nx.NetworkXError(f"node {str(t)} not in graph")
|
| 168 |
+
if s == t:
|
| 169 |
+
raise nx.NetworkXError("source and sink are the same node")
|
| 170 |
+
|
| 171 |
+
if residual is None:
|
| 172 |
+
R = build_residual_network(G, capacity)
|
| 173 |
+
else:
|
| 174 |
+
R = residual
|
| 175 |
+
|
| 176 |
+
# Initialize/reset the residual network.
|
| 177 |
+
# This is way too slow
|
| 178 |
+
# nx.set_edge_attributes(R, 0, 'flow')
|
| 179 |
+
for u in R:
|
| 180 |
+
for e in R[u].values():
|
| 181 |
+
e["flow"] = 0
|
| 182 |
+
|
| 183 |
+
# Use an arbitrary high value as infinite. It is computed
|
| 184 |
+
# when building the residual network.
|
| 185 |
+
INF = R.graph["inf"]
|
| 186 |
+
|
| 187 |
+
if cutoff is None:
|
| 188 |
+
cutoff = INF
|
| 189 |
+
|
| 190 |
+
R_succ = R.succ
|
| 191 |
+
R_pred = R.pred
|
| 192 |
+
|
| 193 |
+
def grow():
|
| 194 |
+
"""Bidirectional breadth-first search for the growth stage.
|
| 195 |
+
|
| 196 |
+
Returns a connecting edge, that is and edge that connects
|
| 197 |
+
a node from the source search tree with a node from the
|
| 198 |
+
target search tree.
|
| 199 |
+
The first node in the connecting edge is always from the
|
| 200 |
+
source tree and the last node from the target tree.
|
| 201 |
+
"""
|
| 202 |
+
while active:
|
| 203 |
+
u = active[0]
|
| 204 |
+
if u in source_tree:
|
| 205 |
+
this_tree = source_tree
|
| 206 |
+
other_tree = target_tree
|
| 207 |
+
neighbors = R_succ
|
| 208 |
+
else:
|
| 209 |
+
this_tree = target_tree
|
| 210 |
+
other_tree = source_tree
|
| 211 |
+
neighbors = R_pred
|
| 212 |
+
for v, attr in neighbors[u].items():
|
| 213 |
+
if attr["capacity"] - attr["flow"] > 0:
|
| 214 |
+
if v not in this_tree:
|
| 215 |
+
if v in other_tree:
|
| 216 |
+
return (u, v) if this_tree is source_tree else (v, u)
|
| 217 |
+
this_tree[v] = u
|
| 218 |
+
dist[v] = dist[u] + 1
|
| 219 |
+
timestamp[v] = timestamp[u]
|
| 220 |
+
active.append(v)
|
| 221 |
+
elif v in this_tree and _is_closer(u, v):
|
| 222 |
+
this_tree[v] = u
|
| 223 |
+
dist[v] = dist[u] + 1
|
| 224 |
+
timestamp[v] = timestamp[u]
|
| 225 |
+
_ = active.popleft()
|
| 226 |
+
return None, None
|
| 227 |
+
|
| 228 |
+
def augment(u, v):
|
| 229 |
+
"""Augmentation stage.
|
| 230 |
+
|
| 231 |
+
Reconstruct path and determine its residual capacity.
|
| 232 |
+
We start from a connecting edge, which links a node
|
| 233 |
+
from the source tree to a node from the target tree.
|
| 234 |
+
The connecting edge is the output of the grow function
|
| 235 |
+
and the input of this function.
|
| 236 |
+
"""
|
| 237 |
+
attr = R_succ[u][v]
|
| 238 |
+
flow = min(INF, attr["capacity"] - attr["flow"])
|
| 239 |
+
path = [u]
|
| 240 |
+
# Trace a path from u to s in source_tree.
|
| 241 |
+
w = u
|
| 242 |
+
while w != s:
|
| 243 |
+
n = w
|
| 244 |
+
w = source_tree[n]
|
| 245 |
+
attr = R_pred[n][w]
|
| 246 |
+
flow = min(flow, attr["capacity"] - attr["flow"])
|
| 247 |
+
path.append(w)
|
| 248 |
+
path.reverse()
|
| 249 |
+
# Trace a path from v to t in target_tree.
|
| 250 |
+
path.append(v)
|
| 251 |
+
w = v
|
| 252 |
+
while w != t:
|
| 253 |
+
n = w
|
| 254 |
+
w = target_tree[n]
|
| 255 |
+
attr = R_succ[n][w]
|
| 256 |
+
flow = min(flow, attr["capacity"] - attr["flow"])
|
| 257 |
+
path.append(w)
|
| 258 |
+
# Augment flow along the path and check for saturated edges.
|
| 259 |
+
it = iter(path)
|
| 260 |
+
u = next(it)
|
| 261 |
+
these_orphans = []
|
| 262 |
+
for v in it:
|
| 263 |
+
R_succ[u][v]["flow"] += flow
|
| 264 |
+
R_succ[v][u]["flow"] -= flow
|
| 265 |
+
if R_succ[u][v]["flow"] == R_succ[u][v]["capacity"]:
|
| 266 |
+
if v in source_tree:
|
| 267 |
+
source_tree[v] = None
|
| 268 |
+
these_orphans.append(v)
|
| 269 |
+
if u in target_tree:
|
| 270 |
+
target_tree[u] = None
|
| 271 |
+
these_orphans.append(u)
|
| 272 |
+
u = v
|
| 273 |
+
orphans.extend(sorted(these_orphans, key=dist.get))
|
| 274 |
+
return flow
|
| 275 |
+
|
| 276 |
+
def adopt():
|
| 277 |
+
"""Adoption stage.
|
| 278 |
+
|
| 279 |
+
Reconstruct search trees by adopting or discarding orphans.
|
| 280 |
+
During augmentation stage some edges got saturated and thus
|
| 281 |
+
the source and target search trees broke down to forests, with
|
| 282 |
+
orphans as roots of some of its trees. We have to reconstruct
|
| 283 |
+
the search trees rooted to source and target before we can grow
|
| 284 |
+
them again.
|
| 285 |
+
"""
|
| 286 |
+
while orphans:
|
| 287 |
+
u = orphans.popleft()
|
| 288 |
+
if u in source_tree:
|
| 289 |
+
tree = source_tree
|
| 290 |
+
neighbors = R_pred
|
| 291 |
+
else:
|
| 292 |
+
tree = target_tree
|
| 293 |
+
neighbors = R_succ
|
| 294 |
+
nbrs = ((n, attr, dist[n]) for n, attr in neighbors[u].items() if n in tree)
|
| 295 |
+
for v, attr, d in sorted(nbrs, key=itemgetter(2)):
|
| 296 |
+
if attr["capacity"] - attr["flow"] > 0:
|
| 297 |
+
if _has_valid_root(v, tree):
|
| 298 |
+
tree[u] = v
|
| 299 |
+
dist[u] = dist[v] + 1
|
| 300 |
+
timestamp[u] = time
|
| 301 |
+
break
|
| 302 |
+
else:
|
| 303 |
+
nbrs = (
|
| 304 |
+
(n, attr, dist[n]) for n, attr in neighbors[u].items() if n in tree
|
| 305 |
+
)
|
| 306 |
+
for v, attr, d in sorted(nbrs, key=itemgetter(2)):
|
| 307 |
+
if attr["capacity"] - attr["flow"] > 0:
|
| 308 |
+
if v not in active:
|
| 309 |
+
active.append(v)
|
| 310 |
+
if tree[v] == u:
|
| 311 |
+
tree[v] = None
|
| 312 |
+
orphans.appendleft(v)
|
| 313 |
+
if u in active:
|
| 314 |
+
active.remove(u)
|
| 315 |
+
del tree[u]
|
| 316 |
+
|
| 317 |
+
def _has_valid_root(n, tree):
|
| 318 |
+
path = []
|
| 319 |
+
v = n
|
| 320 |
+
while v is not None:
|
| 321 |
+
path.append(v)
|
| 322 |
+
if v in (s, t):
|
| 323 |
+
base_dist = 0
|
| 324 |
+
break
|
| 325 |
+
elif timestamp[v] == time:
|
| 326 |
+
base_dist = dist[v]
|
| 327 |
+
break
|
| 328 |
+
v = tree[v]
|
| 329 |
+
else:
|
| 330 |
+
return False
|
| 331 |
+
length = len(path)
|
| 332 |
+
for i, u in enumerate(path, 1):
|
| 333 |
+
dist[u] = base_dist + length - i
|
| 334 |
+
timestamp[u] = time
|
| 335 |
+
return True
|
| 336 |
+
|
| 337 |
+
def _is_closer(u, v):
|
| 338 |
+
return timestamp[v] <= timestamp[u] and dist[v] > dist[u] + 1
|
| 339 |
+
|
| 340 |
+
source_tree = {s: None}
|
| 341 |
+
target_tree = {t: None}
|
| 342 |
+
active = deque([s, t])
|
| 343 |
+
orphans = deque()
|
| 344 |
+
flow_value = 0
|
| 345 |
+
# data structures for the marking heuristic
|
| 346 |
+
time = 1
|
| 347 |
+
timestamp = {s: time, t: time}
|
| 348 |
+
dist = {s: 0, t: 0}
|
| 349 |
+
while flow_value < cutoff:
|
| 350 |
+
# Growth stage
|
| 351 |
+
u, v = grow()
|
| 352 |
+
if u is None:
|
| 353 |
+
break
|
| 354 |
+
time += 1
|
| 355 |
+
# Augmentation stage
|
| 356 |
+
flow_value += augment(u, v)
|
| 357 |
+
# Adoption stage
|
| 358 |
+
adopt()
|
| 359 |
+
|
| 360 |
+
if flow_value * 2 > INF:
|
| 361 |
+
raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
|
| 362 |
+
|
| 363 |
+
# Add source and target tree in a graph attribute.
|
| 364 |
+
# A partition that defines a minimum cut can be directly
|
| 365 |
+
# computed from the search trees as explained in the docstrings.
|
| 366 |
+
R.graph["trees"] = (source_tree, target_tree)
|
| 367 |
+
# Add the standard flow_value graph attribute.
|
| 368 |
+
R.graph["flow_value"] = flow_value
|
| 369 |
+
return R
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/capacityscaling.py
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/dinitz_alg.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dinitz' algorithm for maximum flow problems.
|
| 3 |
+
"""
|
| 4 |
+
from collections import deque
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.algorithms.flow.utils import build_residual_network
|
| 8 |
+
from networkx.utils import pairwise
|
| 9 |
+
|
| 10 |
+
__all__ = ["dinitz"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
|
| 14 |
+
def dinitz(G, s, t, capacity="capacity", residual=None, value_only=False, cutoff=None):
|
| 15 |
+
"""Find a maximum single-commodity flow using Dinitz' algorithm.
|
| 16 |
+
|
| 17 |
+
This function returns the residual network resulting after computing
|
| 18 |
+
the maximum flow. See below for details about the conventions
|
| 19 |
+
NetworkX uses for defining residual networks.
|
| 20 |
+
|
| 21 |
+
This algorithm has a running time of $O(n^2 m)$ for $n$ nodes and $m$
|
| 22 |
+
edges [1]_.
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : NetworkX graph
|
| 28 |
+
Edges of the graph are expected to have an attribute called
|
| 29 |
+
'capacity'. If this attribute is not present, the edge is
|
| 30 |
+
considered to have infinite capacity.
|
| 31 |
+
|
| 32 |
+
s : node
|
| 33 |
+
Source node for the flow.
|
| 34 |
+
|
| 35 |
+
t : node
|
| 36 |
+
Sink node for the flow.
|
| 37 |
+
|
| 38 |
+
capacity : string
|
| 39 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 40 |
+
that indicates how much flow the edge can support. If this
|
| 41 |
+
attribute is not present, the edge is considered to have
|
| 42 |
+
infinite capacity. Default value: 'capacity'.
|
| 43 |
+
|
| 44 |
+
residual : NetworkX graph
|
| 45 |
+
Residual network on which the algorithm is to be executed. If None, a
|
| 46 |
+
new residual network is created. Default value: None.
|
| 47 |
+
|
| 48 |
+
value_only : bool
|
| 49 |
+
If True compute only the value of the maximum flow. This parameter
|
| 50 |
+
will be ignored by this algorithm because it is not applicable.
|
| 51 |
+
|
| 52 |
+
cutoff : integer, float
|
| 53 |
+
If specified, the algorithm will terminate when the flow value reaches
|
| 54 |
+
or exceeds the cutoff. In this case, it may be unable to immediately
|
| 55 |
+
determine a minimum cut. Default value: None.
|
| 56 |
+
|
| 57 |
+
Returns
|
| 58 |
+
-------
|
| 59 |
+
R : NetworkX DiGraph
|
| 60 |
+
Residual network after computing the maximum flow.
|
| 61 |
+
|
| 62 |
+
Raises
|
| 63 |
+
------
|
| 64 |
+
NetworkXError
|
| 65 |
+
The algorithm does not support MultiGraph and MultiDiGraph. If
|
| 66 |
+
the input graph is an instance of one of these two classes, a
|
| 67 |
+
NetworkXError is raised.
|
| 68 |
+
|
| 69 |
+
NetworkXUnbounded
|
| 70 |
+
If the graph has a path of infinite capacity, the value of a
|
| 71 |
+
feasible flow on the graph is unbounded above and the function
|
| 72 |
+
raises a NetworkXUnbounded.
|
| 73 |
+
|
| 74 |
+
See also
|
| 75 |
+
--------
|
| 76 |
+
:meth:`maximum_flow`
|
| 77 |
+
:meth:`minimum_cut`
|
| 78 |
+
:meth:`preflow_push`
|
| 79 |
+
:meth:`shortest_augmenting_path`
|
| 80 |
+
|
| 81 |
+
Notes
|
| 82 |
+
-----
|
| 83 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 84 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 85 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 86 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 87 |
+
in :samp:`G`.
|
| 88 |
+
|
| 89 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 90 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 91 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 92 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 93 |
+
that does not affect the solution of the problem. This value is stored in
|
| 94 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 95 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 96 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 97 |
+
|
| 98 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 99 |
+
stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
|
| 100 |
+
specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
|
| 101 |
+
that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 102 |
+
:samp:`s`-:samp:`t` cut.
|
| 103 |
+
|
| 104 |
+
Examples
|
| 105 |
+
--------
|
| 106 |
+
>>> from networkx.algorithms.flow import dinitz
|
| 107 |
+
|
| 108 |
+
The functions that implement flow algorithms and output a residual
|
| 109 |
+
network, such as this one, are not imported to the base NetworkX
|
| 110 |
+
namespace, so you have to explicitly import them from the flow package.
|
| 111 |
+
|
| 112 |
+
>>> G = nx.DiGraph()
|
| 113 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 114 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 115 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 116 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 117 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 118 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 119 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 120 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 121 |
+
>>> R = dinitz(G, "x", "y")
|
| 122 |
+
>>> flow_value = nx.maximum_flow_value(G, "x", "y")
|
| 123 |
+
>>> flow_value
|
| 124 |
+
3.0
|
| 125 |
+
>>> flow_value == R.graph["flow_value"]
|
| 126 |
+
True
|
| 127 |
+
|
| 128 |
+
References
|
| 129 |
+
----------
|
| 130 |
+
.. [1] Dinitz' Algorithm: The Original Version and Even's Version.
|
| 131 |
+
2006. Yefim Dinitz. In Theoretical Computer Science. Lecture
|
| 132 |
+
Notes in Computer Science. Volume 3895. pp 218-240.
|
| 133 |
+
https://doi.org/10.1007/11685654_10
|
| 134 |
+
|
| 135 |
+
"""
|
| 136 |
+
R = dinitz_impl(G, s, t, capacity, residual, cutoff)
|
| 137 |
+
R.graph["algorithm"] = "dinitz"
|
| 138 |
+
nx._clear_cache(R)
|
| 139 |
+
return R
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def dinitz_impl(G, s, t, capacity, residual, cutoff):
|
| 143 |
+
if s not in G:
|
| 144 |
+
raise nx.NetworkXError(f"node {str(s)} not in graph")
|
| 145 |
+
if t not in G:
|
| 146 |
+
raise nx.NetworkXError(f"node {str(t)} not in graph")
|
| 147 |
+
if s == t:
|
| 148 |
+
raise nx.NetworkXError("source and sink are the same node")
|
| 149 |
+
|
| 150 |
+
if residual is None:
|
| 151 |
+
R = build_residual_network(G, capacity)
|
| 152 |
+
else:
|
| 153 |
+
R = residual
|
| 154 |
+
|
| 155 |
+
# Initialize/reset the residual network.
|
| 156 |
+
for u in R:
|
| 157 |
+
for e in R[u].values():
|
| 158 |
+
e["flow"] = 0
|
| 159 |
+
|
| 160 |
+
# Use an arbitrary high value as infinite. It is computed
|
| 161 |
+
# when building the residual network.
|
| 162 |
+
INF = R.graph["inf"]
|
| 163 |
+
|
| 164 |
+
if cutoff is None:
|
| 165 |
+
cutoff = INF
|
| 166 |
+
|
| 167 |
+
R_succ = R.succ
|
| 168 |
+
R_pred = R.pred
|
| 169 |
+
|
| 170 |
+
def breath_first_search():
|
| 171 |
+
parents = {}
|
| 172 |
+
vertex_dist = {s: 0}
|
| 173 |
+
queue = deque([(s, 0)])
|
| 174 |
+
# Record all the potential edges of shortest augmenting paths
|
| 175 |
+
while queue:
|
| 176 |
+
if t in parents:
|
| 177 |
+
break
|
| 178 |
+
u, dist = queue.popleft()
|
| 179 |
+
for v, attr in R_succ[u].items():
|
| 180 |
+
if attr["capacity"] - attr["flow"] > 0:
|
| 181 |
+
if v in parents:
|
| 182 |
+
if vertex_dist[v] == dist + 1:
|
| 183 |
+
parents[v].append(u)
|
| 184 |
+
else:
|
| 185 |
+
parents[v] = deque([u])
|
| 186 |
+
vertex_dist[v] = dist + 1
|
| 187 |
+
queue.append((v, dist + 1))
|
| 188 |
+
return parents
|
| 189 |
+
|
| 190 |
+
def depth_first_search(parents):
|
| 191 |
+
# DFS to find all the shortest augmenting paths
|
| 192 |
+
"""Build a path using DFS starting from the sink"""
|
| 193 |
+
total_flow = 0
|
| 194 |
+
u = t
|
| 195 |
+
# path also functions as a stack
|
| 196 |
+
path = [u]
|
| 197 |
+
# The loop ends with no augmenting path left in the layered graph
|
| 198 |
+
while True:
|
| 199 |
+
if len(parents[u]) > 0:
|
| 200 |
+
v = parents[u][0]
|
| 201 |
+
path.append(v)
|
| 202 |
+
else:
|
| 203 |
+
path.pop()
|
| 204 |
+
if len(path) == 0:
|
| 205 |
+
break
|
| 206 |
+
v = path[-1]
|
| 207 |
+
parents[v].popleft()
|
| 208 |
+
# Augment the flow along the path found
|
| 209 |
+
if v == s:
|
| 210 |
+
flow = INF
|
| 211 |
+
for u, v in pairwise(path):
|
| 212 |
+
flow = min(flow, R_pred[u][v]["capacity"] - R_pred[u][v]["flow"])
|
| 213 |
+
for u, v in pairwise(reversed(path)):
|
| 214 |
+
R_pred[v][u]["flow"] += flow
|
| 215 |
+
R_pred[u][v]["flow"] -= flow
|
| 216 |
+
# Find the proper node to continue the search
|
| 217 |
+
if R_pred[v][u]["capacity"] - R_pred[v][u]["flow"] == 0:
|
| 218 |
+
parents[v].popleft()
|
| 219 |
+
while path[-1] != v:
|
| 220 |
+
path.pop()
|
| 221 |
+
total_flow += flow
|
| 222 |
+
v = path[-1]
|
| 223 |
+
u = v
|
| 224 |
+
return total_flow
|
| 225 |
+
|
| 226 |
+
flow_value = 0
|
| 227 |
+
while flow_value < cutoff:
|
| 228 |
+
parents = breath_first_search()
|
| 229 |
+
if t not in parents:
|
| 230 |
+
break
|
| 231 |
+
this_flow = depth_first_search(parents)
|
| 232 |
+
if this_flow * 2 > INF:
|
| 233 |
+
raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
|
| 234 |
+
flow_value += this_flow
|
| 235 |
+
|
| 236 |
+
R.graph["flow_value"] = flow_value
|
| 237 |
+
return R
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/edmondskarp.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/gomory_hu.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gomory-Hu tree of undirected Graphs.
|
| 3 |
+
"""
|
| 4 |
+
import networkx as nx
|
| 5 |
+
from networkx.utils import not_implemented_for
|
| 6 |
+
|
| 7 |
+
from .edmondskarp import edmonds_karp
|
| 8 |
+
from .utils import build_residual_network
|
| 9 |
+
|
| 10 |
+
default_flow_func = edmonds_karp
|
| 11 |
+
|
| 12 |
+
__all__ = ["gomory_hu_tree"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@not_implemented_for("directed")
|
| 16 |
+
@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
|
| 17 |
+
def gomory_hu_tree(G, capacity="capacity", flow_func=None):
|
| 18 |
+
r"""Returns the Gomory-Hu tree of an undirected graph G.
|
| 19 |
+
|
| 20 |
+
A Gomory-Hu tree of an undirected graph with capacities is a
|
| 21 |
+
weighted tree that represents the minimum s-t cuts for all s-t
|
| 22 |
+
pairs in the graph.
|
| 23 |
+
|
| 24 |
+
It only requires `n-1` minimum cut computations instead of the
|
| 25 |
+
obvious `n(n-1)/2`. The tree represents all s-t cuts as the
|
| 26 |
+
minimum cut value among any pair of nodes is the minimum edge
|
| 27 |
+
weight in the shortest path between the two nodes in the
|
| 28 |
+
Gomory-Hu tree.
|
| 29 |
+
|
| 30 |
+
The Gomory-Hu tree also has the property that removing the
|
| 31 |
+
edge with the minimum weight in the shortest path between
|
| 32 |
+
any two nodes leaves two connected components that form
|
| 33 |
+
a partition of the nodes in G that defines the minimum s-t
|
| 34 |
+
cut.
|
| 35 |
+
|
| 36 |
+
See Examples section below for details.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
G : NetworkX graph
|
| 41 |
+
Undirected graph
|
| 42 |
+
|
| 43 |
+
capacity : string
|
| 44 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 45 |
+
that indicates how much flow the edge can support. If this
|
| 46 |
+
attribute is not present, the edge is considered to have
|
| 47 |
+
infinite capacity. Default value: 'capacity'.
|
| 48 |
+
|
| 49 |
+
flow_func : function
|
| 50 |
+
Function to perform the underlying flow computations. Default value
|
| 51 |
+
:func:`edmonds_karp`. This function performs better in sparse graphs
|
| 52 |
+
with right tailed degree distributions.
|
| 53 |
+
:func:`shortest_augmenting_path` will perform better in denser
|
| 54 |
+
graphs.
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
Tree : NetworkX graph
|
| 59 |
+
A NetworkX graph representing the Gomory-Hu tree of the input graph.
|
| 60 |
+
|
| 61 |
+
Raises
|
| 62 |
+
------
|
| 63 |
+
NetworkXNotImplemented
|
| 64 |
+
Raised if the input graph is directed.
|
| 65 |
+
|
| 66 |
+
NetworkXError
|
| 67 |
+
Raised if the input graph is an empty Graph.
|
| 68 |
+
|
| 69 |
+
Examples
|
| 70 |
+
--------
|
| 71 |
+
>>> G = nx.karate_club_graph()
|
| 72 |
+
>>> nx.set_edge_attributes(G, 1, "capacity")
|
| 73 |
+
>>> T = nx.gomory_hu_tree(G)
|
| 74 |
+
>>> # The value of the minimum cut between any pair
|
| 75 |
+
... # of nodes in G is the minimum edge weight in the
|
| 76 |
+
... # shortest path between the two nodes in the
|
| 77 |
+
... # Gomory-Hu tree.
|
| 78 |
+
... def minimum_edge_weight_in_shortest_path(T, u, v):
|
| 79 |
+
... path = nx.shortest_path(T, u, v, weight="weight")
|
| 80 |
+
... return min((T[u][v]["weight"], (u, v)) for (u, v) in zip(path, path[1:]))
|
| 81 |
+
>>> u, v = 0, 33
|
| 82 |
+
>>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
|
| 83 |
+
>>> cut_value
|
| 84 |
+
10
|
| 85 |
+
>>> nx.minimum_cut_value(G, u, v)
|
| 86 |
+
10
|
| 87 |
+
>>> # The Gomory-Hu tree also has the property that removing the
|
| 88 |
+
... # edge with the minimum weight in the shortest path between
|
| 89 |
+
... # any two nodes leaves two connected components that form
|
| 90 |
+
... # a partition of the nodes in G that defines the minimum s-t
|
| 91 |
+
... # cut.
|
| 92 |
+
... cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
|
| 93 |
+
>>> T.remove_edge(*edge)
|
| 94 |
+
>>> U, V = list(nx.connected_components(T))
|
| 95 |
+
>>> # Thus U and V form a partition that defines a minimum cut
|
| 96 |
+
... # between u and v in G. You can compute the edge cut set,
|
| 97 |
+
... # that is, the set of edges that if removed from G will
|
| 98 |
+
... # disconnect u from v in G, with this information:
|
| 99 |
+
... cutset = set()
|
| 100 |
+
>>> for x, nbrs in ((n, G[n]) for n in U):
|
| 101 |
+
... cutset.update((x, y) for y in nbrs if y in V)
|
| 102 |
+
>>> # Because we have set the capacities of all edges to 1
|
| 103 |
+
... # the cutset contains ten edges
|
| 104 |
+
... len(cutset)
|
| 105 |
+
10
|
| 106 |
+
>>> # You can use any maximum flow algorithm for the underlying
|
| 107 |
+
... # flow computations using the argument flow_func
|
| 108 |
+
... from networkx.algorithms import flow
|
| 109 |
+
>>> T = nx.gomory_hu_tree(G, flow_func=flow.boykov_kolmogorov)
|
| 110 |
+
>>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
|
| 111 |
+
>>> cut_value
|
| 112 |
+
10
|
| 113 |
+
>>> nx.minimum_cut_value(G, u, v, flow_func=flow.boykov_kolmogorov)
|
| 114 |
+
10
|
| 115 |
+
|
| 116 |
+
Notes
|
| 117 |
+
-----
|
| 118 |
+
This implementation is based on Gusfield approach [1]_ to compute
|
| 119 |
+
Gomory-Hu trees, which does not require node contractions and has
|
| 120 |
+
the same computational complexity than the original method.
|
| 121 |
+
|
| 122 |
+
See also
|
| 123 |
+
--------
|
| 124 |
+
:func:`minimum_cut`
|
| 125 |
+
:func:`maximum_flow`
|
| 126 |
+
|
| 127 |
+
References
|
| 128 |
+
----------
|
| 129 |
+
.. [1] Gusfield D: Very simple methods for all pairs network flow analysis.
|
| 130 |
+
SIAM J Comput 19(1):143-155, 1990.
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
if flow_func is None:
|
| 134 |
+
flow_func = default_flow_func
|
| 135 |
+
|
| 136 |
+
if len(G) == 0: # empty graph
|
| 137 |
+
msg = "Empty Graph does not have a Gomory-Hu tree representation"
|
| 138 |
+
raise nx.NetworkXError(msg)
|
| 139 |
+
|
| 140 |
+
# Start the tree as a star graph with an arbitrary node at the center
|
| 141 |
+
tree = {}
|
| 142 |
+
labels = {}
|
| 143 |
+
iter_nodes = iter(G)
|
| 144 |
+
root = next(iter_nodes)
|
| 145 |
+
for n in iter_nodes:
|
| 146 |
+
tree[n] = root
|
| 147 |
+
|
| 148 |
+
# Reuse residual network
|
| 149 |
+
R = build_residual_network(G, capacity)
|
| 150 |
+
|
| 151 |
+
# For all the leaves in the star graph tree (that is n-1 nodes).
|
| 152 |
+
for source in tree:
|
| 153 |
+
# Find neighbor in the tree
|
| 154 |
+
target = tree[source]
|
| 155 |
+
# compute minimum cut
|
| 156 |
+
cut_value, partition = nx.minimum_cut(
|
| 157 |
+
G, source, target, capacity=capacity, flow_func=flow_func, residual=R
|
| 158 |
+
)
|
| 159 |
+
labels[(source, target)] = cut_value
|
| 160 |
+
# Update the tree
|
| 161 |
+
# Source will always be in partition[0] and target in partition[1]
|
| 162 |
+
for node in partition[0]:
|
| 163 |
+
if node != source and node in tree and tree[node] == target:
|
| 164 |
+
tree[node] = source
|
| 165 |
+
labels[node, source] = labels.get((node, target), cut_value)
|
| 166 |
+
#
|
| 167 |
+
if target != root and tree[target] in partition[0]:
|
| 168 |
+
labels[source, tree[target]] = labels[target, tree[target]]
|
| 169 |
+
labels[target, source] = cut_value
|
| 170 |
+
tree[source] = tree[target]
|
| 171 |
+
tree[target] = source
|
| 172 |
+
|
| 173 |
+
# Build the tree
|
| 174 |
+
T = nx.Graph()
|
| 175 |
+
T.add_nodes_from(G)
|
| 176 |
+
T.add_weighted_edges_from(((u, v, labels[u, v]) for u, v in tree.items()))
|
| 177 |
+
return T
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/maxflow.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Maximum flow (and minimum cut) algorithms on capacitated graphs.
|
| 3 |
+
"""
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
from .boykovkolmogorov import boykov_kolmogorov
|
| 7 |
+
from .dinitz_alg import dinitz
|
| 8 |
+
from .edmondskarp import edmonds_karp
|
| 9 |
+
from .preflowpush import preflow_push
|
| 10 |
+
from .shortestaugmentingpath import shortest_augmenting_path
|
| 11 |
+
from .utils import build_flow_dict
|
| 12 |
+
|
| 13 |
+
# Define the default flow function for computing maximum flow.
|
| 14 |
+
default_flow_func = preflow_push
|
| 15 |
+
|
| 16 |
+
__all__ = ["maximum_flow", "maximum_flow_value", "minimum_cut", "minimum_cut_value"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
|
| 20 |
+
def maximum_flow(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
|
| 21 |
+
"""Find a maximum single-commodity flow.
|
| 22 |
+
|
| 23 |
+
Parameters
|
| 24 |
+
----------
|
| 25 |
+
flowG : NetworkX graph
|
| 26 |
+
Edges of the graph are expected to have an attribute called
|
| 27 |
+
'capacity'. If this attribute is not present, the edge is
|
| 28 |
+
considered to have infinite capacity.
|
| 29 |
+
|
| 30 |
+
_s : node
|
| 31 |
+
Source node for the flow.
|
| 32 |
+
|
| 33 |
+
_t : node
|
| 34 |
+
Sink node for the flow.
|
| 35 |
+
|
| 36 |
+
capacity : string
|
| 37 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 38 |
+
that indicates how much flow the edge can support. If this
|
| 39 |
+
attribute is not present, the edge is considered to have
|
| 40 |
+
infinite capacity. Default value: 'capacity'.
|
| 41 |
+
|
| 42 |
+
flow_func : function
|
| 43 |
+
A function for computing the maximum flow among a pair of nodes
|
| 44 |
+
in a capacitated graph. The function has to accept at least three
|
| 45 |
+
parameters: a Graph or Digraph, a source node, and a target node.
|
| 46 |
+
And return a residual network that follows NetworkX conventions
|
| 47 |
+
(see Notes). If flow_func is None, the default maximum
|
| 48 |
+
flow function (:meth:`preflow_push`) is used. See below for
|
| 49 |
+
alternative algorithms. The choice of the default function may change
|
| 50 |
+
from version to version and should not be relied on. Default value:
|
| 51 |
+
None.
|
| 52 |
+
|
| 53 |
+
kwargs : Any other keyword parameter is passed to the function that
|
| 54 |
+
computes the maximum flow.
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
flow_value : integer, float
|
| 59 |
+
Value of the maximum flow, i.e., net outflow from the source.
|
| 60 |
+
|
| 61 |
+
flow_dict : dict
|
| 62 |
+
A dictionary containing the value of the flow that went through
|
| 63 |
+
each edge.
|
| 64 |
+
|
| 65 |
+
Raises
|
| 66 |
+
------
|
| 67 |
+
NetworkXError
|
| 68 |
+
The algorithm does not support MultiGraph and MultiDiGraph. If
|
| 69 |
+
the input graph is an instance of one of these two classes, a
|
| 70 |
+
NetworkXError is raised.
|
| 71 |
+
|
| 72 |
+
NetworkXUnbounded
|
| 73 |
+
If the graph has a path of infinite capacity, the value of a
|
| 74 |
+
feasible flow on the graph is unbounded above and the function
|
| 75 |
+
raises a NetworkXUnbounded.
|
| 76 |
+
|
| 77 |
+
See also
|
| 78 |
+
--------
|
| 79 |
+
:meth:`maximum_flow_value`
|
| 80 |
+
:meth:`minimum_cut`
|
| 81 |
+
:meth:`minimum_cut_value`
|
| 82 |
+
:meth:`edmonds_karp`
|
| 83 |
+
:meth:`preflow_push`
|
| 84 |
+
:meth:`shortest_augmenting_path`
|
| 85 |
+
|
| 86 |
+
Notes
|
| 87 |
+
-----
|
| 88 |
+
The function used in the flow_func parameter has to return a residual
|
| 89 |
+
network that follows NetworkX conventions:
|
| 90 |
+
|
| 91 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 92 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 93 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 94 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 95 |
+
in :samp:`G`.
|
| 96 |
+
|
| 97 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 98 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 99 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 100 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 101 |
+
that does not affect the solution of the problem. This value is stored in
|
| 102 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 103 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 104 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 105 |
+
|
| 106 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 107 |
+
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
|
| 108 |
+
only edges :samp:`(u, v)` such that
|
| 109 |
+
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 110 |
+
:samp:`s`-:samp:`t` cut.
|
| 111 |
+
|
| 112 |
+
Specific algorithms may store extra data in :samp:`R`.
|
| 113 |
+
|
| 114 |
+
The function should supports an optional boolean parameter value_only. When
|
| 115 |
+
True, it can optionally terminate the algorithm as soon as the maximum flow
|
| 116 |
+
value and the minimum cut can be determined.
|
| 117 |
+
|
| 118 |
+
Examples
|
| 119 |
+
--------
|
| 120 |
+
>>> G = nx.DiGraph()
|
| 121 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 122 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 123 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 124 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 125 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 126 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 127 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 128 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 129 |
+
|
| 130 |
+
maximum_flow returns both the value of the maximum flow and a
|
| 131 |
+
dictionary with all flows.
|
| 132 |
+
|
| 133 |
+
>>> flow_value, flow_dict = nx.maximum_flow(G, "x", "y")
|
| 134 |
+
>>> flow_value
|
| 135 |
+
3.0
|
| 136 |
+
>>> print(flow_dict["x"]["b"])
|
| 137 |
+
1.0
|
| 138 |
+
|
| 139 |
+
You can also use alternative algorithms for computing the
|
| 140 |
+
maximum flow by using the flow_func parameter.
|
| 141 |
+
|
| 142 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
| 143 |
+
>>> flow_value == nx.maximum_flow(G, "x", "y", flow_func=shortest_augmenting_path)[0]
|
| 144 |
+
True
|
| 145 |
+
|
| 146 |
+
"""
|
| 147 |
+
if flow_func is None:
|
| 148 |
+
if kwargs:
|
| 149 |
+
raise nx.NetworkXError(
|
| 150 |
+
"You have to explicitly set a flow_func if"
|
| 151 |
+
" you need to pass parameters via kwargs."
|
| 152 |
+
)
|
| 153 |
+
flow_func = default_flow_func
|
| 154 |
+
|
| 155 |
+
if not callable(flow_func):
|
| 156 |
+
raise nx.NetworkXError("flow_func has to be callable.")
|
| 157 |
+
|
| 158 |
+
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=False, **kwargs)
|
| 159 |
+
flow_dict = build_flow_dict(flowG, R)
|
| 160 |
+
|
| 161 |
+
return (R.graph["flow_value"], flow_dict)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
|
| 165 |
+
def maximum_flow_value(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
|
| 166 |
+
"""Find the value of maximum single-commodity flow.
|
| 167 |
+
|
| 168 |
+
Parameters
|
| 169 |
+
----------
|
| 170 |
+
flowG : NetworkX graph
|
| 171 |
+
Edges of the graph are expected to have an attribute called
|
| 172 |
+
'capacity'. If this attribute is not present, the edge is
|
| 173 |
+
considered to have infinite capacity.
|
| 174 |
+
|
| 175 |
+
_s : node
|
| 176 |
+
Source node for the flow.
|
| 177 |
+
|
| 178 |
+
_t : node
|
| 179 |
+
Sink node for the flow.
|
| 180 |
+
|
| 181 |
+
capacity : string
|
| 182 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 183 |
+
that indicates how much flow the edge can support. If this
|
| 184 |
+
attribute is not present, the edge is considered to have
|
| 185 |
+
infinite capacity. Default value: 'capacity'.
|
| 186 |
+
|
| 187 |
+
flow_func : function
|
| 188 |
+
A function for computing the maximum flow among a pair of nodes
|
| 189 |
+
in a capacitated graph. The function has to accept at least three
|
| 190 |
+
parameters: a Graph or Digraph, a source node, and a target node.
|
| 191 |
+
And return a residual network that follows NetworkX conventions
|
| 192 |
+
(see Notes). If flow_func is None, the default maximum
|
| 193 |
+
flow function (:meth:`preflow_push`) is used. See below for
|
| 194 |
+
alternative algorithms. The choice of the default function may change
|
| 195 |
+
from version to version and should not be relied on. Default value:
|
| 196 |
+
None.
|
| 197 |
+
|
| 198 |
+
kwargs : Any other keyword parameter is passed to the function that
|
| 199 |
+
computes the maximum flow.
|
| 200 |
+
|
| 201 |
+
Returns
|
| 202 |
+
-------
|
| 203 |
+
flow_value : integer, float
|
| 204 |
+
Value of the maximum flow, i.e., net outflow from the source.
|
| 205 |
+
|
| 206 |
+
Raises
|
| 207 |
+
------
|
| 208 |
+
NetworkXError
|
| 209 |
+
The algorithm does not support MultiGraph and MultiDiGraph. If
|
| 210 |
+
the input graph is an instance of one of these two classes, a
|
| 211 |
+
NetworkXError is raised.
|
| 212 |
+
|
| 213 |
+
NetworkXUnbounded
|
| 214 |
+
If the graph has a path of infinite capacity, the value of a
|
| 215 |
+
feasible flow on the graph is unbounded above and the function
|
| 216 |
+
raises a NetworkXUnbounded.
|
| 217 |
+
|
| 218 |
+
See also
|
| 219 |
+
--------
|
| 220 |
+
:meth:`maximum_flow`
|
| 221 |
+
:meth:`minimum_cut`
|
| 222 |
+
:meth:`minimum_cut_value`
|
| 223 |
+
:meth:`edmonds_karp`
|
| 224 |
+
:meth:`preflow_push`
|
| 225 |
+
:meth:`shortest_augmenting_path`
|
| 226 |
+
|
| 227 |
+
Notes
|
| 228 |
+
-----
|
| 229 |
+
The function used in the flow_func parameter has to return a residual
|
| 230 |
+
network that follows NetworkX conventions:
|
| 231 |
+
|
| 232 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 233 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 234 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 235 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 236 |
+
in :samp:`G`.
|
| 237 |
+
|
| 238 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 239 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 240 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 241 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 242 |
+
that does not affect the solution of the problem. This value is stored in
|
| 243 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 244 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 245 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 246 |
+
|
| 247 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 248 |
+
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
|
| 249 |
+
only edges :samp:`(u, v)` such that
|
| 250 |
+
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 251 |
+
:samp:`s`-:samp:`t` cut.
|
| 252 |
+
|
| 253 |
+
Specific algorithms may store extra data in :samp:`R`.
|
| 254 |
+
|
| 255 |
+
The function should supports an optional boolean parameter value_only. When
|
| 256 |
+
True, it can optionally terminate the algorithm as soon as the maximum flow
|
| 257 |
+
value and the minimum cut can be determined.
|
| 258 |
+
|
| 259 |
+
Examples
|
| 260 |
+
--------
|
| 261 |
+
>>> G = nx.DiGraph()
|
| 262 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 263 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 264 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 265 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 266 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 267 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 268 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 269 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 270 |
+
|
| 271 |
+
maximum_flow_value computes only the value of the
|
| 272 |
+
maximum flow:
|
| 273 |
+
|
| 274 |
+
>>> flow_value = nx.maximum_flow_value(G, "x", "y")
|
| 275 |
+
>>> flow_value
|
| 276 |
+
3.0
|
| 277 |
+
|
| 278 |
+
You can also use alternative algorithms for computing the
|
| 279 |
+
maximum flow by using the flow_func parameter.
|
| 280 |
+
|
| 281 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
| 282 |
+
>>> flow_value == nx.maximum_flow_value(G, "x", "y", flow_func=shortest_augmenting_path)
|
| 283 |
+
True
|
| 284 |
+
|
| 285 |
+
"""
|
| 286 |
+
if flow_func is None:
|
| 287 |
+
if kwargs:
|
| 288 |
+
raise nx.NetworkXError(
|
| 289 |
+
"You have to explicitly set a flow_func if"
|
| 290 |
+
" you need to pass parameters via kwargs."
|
| 291 |
+
)
|
| 292 |
+
flow_func = default_flow_func
|
| 293 |
+
|
| 294 |
+
if not callable(flow_func):
|
| 295 |
+
raise nx.NetworkXError("flow_func has to be callable.")
|
| 296 |
+
|
| 297 |
+
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
|
| 298 |
+
|
| 299 |
+
return R.graph["flow_value"]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
|
| 303 |
+
def minimum_cut(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
|
| 304 |
+
"""Compute the value and the node partition of a minimum (s, t)-cut.
|
| 305 |
+
|
| 306 |
+
Use the max-flow min-cut theorem, i.e., the capacity of a minimum
|
| 307 |
+
capacity cut is equal to the flow value of a maximum flow.
|
| 308 |
+
|
| 309 |
+
Parameters
|
| 310 |
+
----------
|
| 311 |
+
flowG : NetworkX graph
|
| 312 |
+
Edges of the graph are expected to have an attribute called
|
| 313 |
+
'capacity'. If this attribute is not present, the edge is
|
| 314 |
+
considered to have infinite capacity.
|
| 315 |
+
|
| 316 |
+
_s : node
|
| 317 |
+
Source node for the flow.
|
| 318 |
+
|
| 319 |
+
_t : node
|
| 320 |
+
Sink node for the flow.
|
| 321 |
+
|
| 322 |
+
capacity : string
|
| 323 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 324 |
+
that indicates how much flow the edge can support. If this
|
| 325 |
+
attribute is not present, the edge is considered to have
|
| 326 |
+
infinite capacity. Default value: 'capacity'.
|
| 327 |
+
|
| 328 |
+
flow_func : function
|
| 329 |
+
A function for computing the maximum flow among a pair of nodes
|
| 330 |
+
in a capacitated graph. The function has to accept at least three
|
| 331 |
+
parameters: a Graph or Digraph, a source node, and a target node.
|
| 332 |
+
And return a residual network that follows NetworkX conventions
|
| 333 |
+
(see Notes). If flow_func is None, the default maximum
|
| 334 |
+
flow function (:meth:`preflow_push`) is used. See below for
|
| 335 |
+
alternative algorithms. The choice of the default function may change
|
| 336 |
+
from version to version and should not be relied on. Default value:
|
| 337 |
+
None.
|
| 338 |
+
|
| 339 |
+
kwargs : Any other keyword parameter is passed to the function that
|
| 340 |
+
computes the maximum flow.
|
| 341 |
+
|
| 342 |
+
Returns
|
| 343 |
+
-------
|
| 344 |
+
cut_value : integer, float
|
| 345 |
+
Value of the minimum cut.
|
| 346 |
+
|
| 347 |
+
partition : pair of node sets
|
| 348 |
+
A partitioning of the nodes that defines a minimum cut.
|
| 349 |
+
|
| 350 |
+
Raises
|
| 351 |
+
------
|
| 352 |
+
NetworkXUnbounded
|
| 353 |
+
If the graph has a path of infinite capacity, all cuts have
|
| 354 |
+
infinite capacity and the function raises a NetworkXError.
|
| 355 |
+
|
| 356 |
+
See also
|
| 357 |
+
--------
|
| 358 |
+
:meth:`maximum_flow`
|
| 359 |
+
:meth:`maximum_flow_value`
|
| 360 |
+
:meth:`minimum_cut_value`
|
| 361 |
+
:meth:`edmonds_karp`
|
| 362 |
+
:meth:`preflow_push`
|
| 363 |
+
:meth:`shortest_augmenting_path`
|
| 364 |
+
|
| 365 |
+
Notes
|
| 366 |
+
-----
|
| 367 |
+
The function used in the flow_func parameter has to return a residual
|
| 368 |
+
network that follows NetworkX conventions:
|
| 369 |
+
|
| 370 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 371 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 372 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 373 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 374 |
+
in :samp:`G`.
|
| 375 |
+
|
| 376 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 377 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 378 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 379 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 380 |
+
that does not affect the solution of the problem. This value is stored in
|
| 381 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 382 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 383 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 384 |
+
|
| 385 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 386 |
+
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
|
| 387 |
+
only edges :samp:`(u, v)` such that
|
| 388 |
+
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 389 |
+
:samp:`s`-:samp:`t` cut.
|
| 390 |
+
|
| 391 |
+
Specific algorithms may store extra data in :samp:`R`.
|
| 392 |
+
|
| 393 |
+
The function should supports an optional boolean parameter value_only. When
|
| 394 |
+
True, it can optionally terminate the algorithm as soon as the maximum flow
|
| 395 |
+
value and the minimum cut can be determined.
|
| 396 |
+
|
| 397 |
+
Examples
|
| 398 |
+
--------
|
| 399 |
+
>>> G = nx.DiGraph()
|
| 400 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 401 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 402 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 403 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 404 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 405 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 406 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 407 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 408 |
+
|
| 409 |
+
minimum_cut computes both the value of the
|
| 410 |
+
minimum cut and the node partition:
|
| 411 |
+
|
| 412 |
+
>>> cut_value, partition = nx.minimum_cut(G, "x", "y")
|
| 413 |
+
>>> reachable, non_reachable = partition
|
| 414 |
+
|
| 415 |
+
'partition' here is a tuple with the two sets of nodes that define
|
| 416 |
+
the minimum cut. You can compute the cut set of edges that induce
|
| 417 |
+
the minimum cut as follows:
|
| 418 |
+
|
| 419 |
+
>>> cutset = set()
|
| 420 |
+
>>> for u, nbrs in ((n, G[n]) for n in reachable):
|
| 421 |
+
... cutset.update((u, v) for v in nbrs if v in non_reachable)
|
| 422 |
+
>>> print(sorted(cutset))
|
| 423 |
+
[('c', 'y'), ('x', 'b')]
|
| 424 |
+
>>> cut_value == sum(G.edges[u, v]["capacity"] for (u, v) in cutset)
|
| 425 |
+
True
|
| 426 |
+
|
| 427 |
+
You can also use alternative algorithms for computing the
|
| 428 |
+
minimum cut by using the flow_func parameter.
|
| 429 |
+
|
| 430 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
| 431 |
+
>>> cut_value == nx.minimum_cut(G, "x", "y", flow_func=shortest_augmenting_path)[0]
|
| 432 |
+
True
|
| 433 |
+
|
| 434 |
+
"""
|
| 435 |
+
if flow_func is None:
|
| 436 |
+
if kwargs:
|
| 437 |
+
raise nx.NetworkXError(
|
| 438 |
+
"You have to explicitly set a flow_func if"
|
| 439 |
+
" you need to pass parameters via kwargs."
|
| 440 |
+
)
|
| 441 |
+
flow_func = default_flow_func
|
| 442 |
+
|
| 443 |
+
if not callable(flow_func):
|
| 444 |
+
raise nx.NetworkXError("flow_func has to be callable.")
|
| 445 |
+
|
| 446 |
+
if kwargs.get("cutoff") is not None and flow_func is preflow_push:
|
| 447 |
+
raise nx.NetworkXError("cutoff should not be specified.")
|
| 448 |
+
|
| 449 |
+
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
|
| 450 |
+
# Remove saturated edges from the residual network
|
| 451 |
+
cutset = [(u, v, d) for u, v, d in R.edges(data=True) if d["flow"] == d["capacity"]]
|
| 452 |
+
R.remove_edges_from(cutset)
|
| 453 |
+
|
| 454 |
+
# Then, reachable and non reachable nodes from source in the
|
| 455 |
+
# residual network form the node partition that defines
|
| 456 |
+
# the minimum cut.
|
| 457 |
+
non_reachable = set(dict(nx.shortest_path_length(R, target=_t)))
|
| 458 |
+
partition = (set(flowG) - non_reachable, non_reachable)
|
| 459 |
+
# Finally add again cutset edges to the residual network to make
|
| 460 |
+
# sure that it is reusable.
|
| 461 |
+
if cutset is not None:
|
| 462 |
+
R.add_edges_from(cutset)
|
| 463 |
+
return (R.graph["flow_value"], partition)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
@nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
|
| 467 |
+
def minimum_cut_value(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
|
| 468 |
+
"""Compute the value of a minimum (s, t)-cut.
|
| 469 |
+
|
| 470 |
+
Use the max-flow min-cut theorem, i.e., the capacity of a minimum
|
| 471 |
+
capacity cut is equal to the flow value of a maximum flow.
|
| 472 |
+
|
| 473 |
+
Parameters
|
| 474 |
+
----------
|
| 475 |
+
flowG : NetworkX graph
|
| 476 |
+
Edges of the graph are expected to have an attribute called
|
| 477 |
+
'capacity'. If this attribute is not present, the edge is
|
| 478 |
+
considered to have infinite capacity.
|
| 479 |
+
|
| 480 |
+
_s : node
|
| 481 |
+
Source node for the flow.
|
| 482 |
+
|
| 483 |
+
_t : node
|
| 484 |
+
Sink node for the flow.
|
| 485 |
+
|
| 486 |
+
capacity : string
|
| 487 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 488 |
+
that indicates how much flow the edge can support. If this
|
| 489 |
+
attribute is not present, the edge is considered to have
|
| 490 |
+
infinite capacity. Default value: 'capacity'.
|
| 491 |
+
|
| 492 |
+
flow_func : function
|
| 493 |
+
A function for computing the maximum flow among a pair of nodes
|
| 494 |
+
in a capacitated graph. The function has to accept at least three
|
| 495 |
+
parameters: a Graph or Digraph, a source node, and a target node.
|
| 496 |
+
And return a residual network that follows NetworkX conventions
|
| 497 |
+
(see Notes). If flow_func is None, the default maximum
|
| 498 |
+
flow function (:meth:`preflow_push`) is used. See below for
|
| 499 |
+
alternative algorithms. The choice of the default function may change
|
| 500 |
+
from version to version and should not be relied on. Default value:
|
| 501 |
+
None.
|
| 502 |
+
|
| 503 |
+
kwargs : Any other keyword parameter is passed to the function that
|
| 504 |
+
computes the maximum flow.
|
| 505 |
+
|
| 506 |
+
Returns
|
| 507 |
+
-------
|
| 508 |
+
cut_value : integer, float
|
| 509 |
+
Value of the minimum cut.
|
| 510 |
+
|
| 511 |
+
Raises
|
| 512 |
+
------
|
| 513 |
+
NetworkXUnbounded
|
| 514 |
+
If the graph has a path of infinite capacity, all cuts have
|
| 515 |
+
infinite capacity and the function raises a NetworkXError.
|
| 516 |
+
|
| 517 |
+
See also
|
| 518 |
+
--------
|
| 519 |
+
:meth:`maximum_flow`
|
| 520 |
+
:meth:`maximum_flow_value`
|
| 521 |
+
:meth:`minimum_cut`
|
| 522 |
+
:meth:`edmonds_karp`
|
| 523 |
+
:meth:`preflow_push`
|
| 524 |
+
:meth:`shortest_augmenting_path`
|
| 525 |
+
|
| 526 |
+
Notes
|
| 527 |
+
-----
|
| 528 |
+
The function used in the flow_func parameter has to return a residual
|
| 529 |
+
network that follows NetworkX conventions:
|
| 530 |
+
|
| 531 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 532 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 533 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 534 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 535 |
+
in :samp:`G`.
|
| 536 |
+
|
| 537 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 538 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 539 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 540 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 541 |
+
that does not affect the solution of the problem. This value is stored in
|
| 542 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 543 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 544 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 545 |
+
|
| 546 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 547 |
+
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
|
| 548 |
+
only edges :samp:`(u, v)` such that
|
| 549 |
+
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 550 |
+
:samp:`s`-:samp:`t` cut.
|
| 551 |
+
|
| 552 |
+
Specific algorithms may store extra data in :samp:`R`.
|
| 553 |
+
|
| 554 |
+
The function should supports an optional boolean parameter value_only. When
|
| 555 |
+
True, it can optionally terminate the algorithm as soon as the maximum flow
|
| 556 |
+
value and the minimum cut can be determined.
|
| 557 |
+
|
| 558 |
+
Examples
|
| 559 |
+
--------
|
| 560 |
+
>>> G = nx.DiGraph()
|
| 561 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 562 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 563 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 564 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 565 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 566 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 567 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 568 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 569 |
+
|
| 570 |
+
minimum_cut_value computes only the value of the
|
| 571 |
+
minimum cut:
|
| 572 |
+
|
| 573 |
+
>>> cut_value = nx.minimum_cut_value(G, "x", "y")
|
| 574 |
+
>>> cut_value
|
| 575 |
+
3.0
|
| 576 |
+
|
| 577 |
+
You can also use alternative algorithms for computing the
|
| 578 |
+
minimum cut by using the flow_func parameter.
|
| 579 |
+
|
| 580 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
| 581 |
+
>>> cut_value == nx.minimum_cut_value(G, "x", "y", flow_func=shortest_augmenting_path)
|
| 582 |
+
True
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
if flow_func is None:
|
| 586 |
+
if kwargs:
|
| 587 |
+
raise nx.NetworkXError(
|
| 588 |
+
"You have to explicitly set a flow_func if"
|
| 589 |
+
" you need to pass parameters via kwargs."
|
| 590 |
+
)
|
| 591 |
+
flow_func = default_flow_func
|
| 592 |
+
|
| 593 |
+
if not callable(flow_func):
|
| 594 |
+
raise nx.NetworkXError("flow_func has to be callable.")
|
| 595 |
+
|
| 596 |
+
if kwargs.get("cutoff") is not None and flow_func is preflow_push:
|
| 597 |
+
raise nx.NetworkXError("cutoff should not be specified.")
|
| 598 |
+
|
| 599 |
+
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
|
| 600 |
+
|
| 601 |
+
return R.graph["flow_value"]
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/mincost.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/networksimplex.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/preflowpush.py
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/shortestaugmentingpath.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shortest augmenting path algorithm for maximum flow problems.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections import deque
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
from .edmondskarp import edmonds_karp_core
|
| 10 |
+
from .utils import CurrentEdge, build_residual_network
|
| 11 |
+
|
| 12 |
+
__all__ = ["shortest_augmenting_path"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def shortest_augmenting_path_impl(G, s, t, capacity, residual, two_phase, cutoff):
|
| 16 |
+
"""Implementation of the shortest augmenting path algorithm."""
|
| 17 |
+
if s not in G:
|
| 18 |
+
raise nx.NetworkXError(f"node {str(s)} not in graph")
|
| 19 |
+
if t not in G:
|
| 20 |
+
raise nx.NetworkXError(f"node {str(t)} not in graph")
|
| 21 |
+
if s == t:
|
| 22 |
+
raise nx.NetworkXError("source and sink are the same node")
|
| 23 |
+
|
| 24 |
+
if residual is None:
|
| 25 |
+
R = build_residual_network(G, capacity)
|
| 26 |
+
else:
|
| 27 |
+
R = residual
|
| 28 |
+
|
| 29 |
+
R_nodes = R.nodes
|
| 30 |
+
R_pred = R.pred
|
| 31 |
+
R_succ = R.succ
|
| 32 |
+
|
| 33 |
+
# Initialize/reset the residual network.
|
| 34 |
+
for u in R:
|
| 35 |
+
for e in R_succ[u].values():
|
| 36 |
+
e["flow"] = 0
|
| 37 |
+
|
| 38 |
+
# Initialize heights of the nodes.
|
| 39 |
+
heights = {t: 0}
|
| 40 |
+
q = deque([(t, 0)])
|
| 41 |
+
while q:
|
| 42 |
+
u, height = q.popleft()
|
| 43 |
+
height += 1
|
| 44 |
+
for v, attr in R_pred[u].items():
|
| 45 |
+
if v not in heights and attr["flow"] < attr["capacity"]:
|
| 46 |
+
heights[v] = height
|
| 47 |
+
q.append((v, height))
|
| 48 |
+
|
| 49 |
+
if s not in heights:
|
| 50 |
+
# t is not reachable from s in the residual network. The maximum flow
|
| 51 |
+
# must be zero.
|
| 52 |
+
R.graph["flow_value"] = 0
|
| 53 |
+
return R
|
| 54 |
+
|
| 55 |
+
n = len(G)
|
| 56 |
+
m = R.size() / 2
|
| 57 |
+
|
| 58 |
+
# Initialize heights and 'current edge' data structures of the nodes.
|
| 59 |
+
for u in R:
|
| 60 |
+
R_nodes[u]["height"] = heights[u] if u in heights else n
|
| 61 |
+
R_nodes[u]["curr_edge"] = CurrentEdge(R_succ[u])
|
| 62 |
+
|
| 63 |
+
# Initialize counts of nodes in each level.
|
| 64 |
+
counts = [0] * (2 * n - 1)
|
| 65 |
+
for u in R:
|
| 66 |
+
counts[R_nodes[u]["height"]] += 1
|
| 67 |
+
|
| 68 |
+
inf = R.graph["inf"]
|
| 69 |
+
|
| 70 |
+
def augment(path):
|
| 71 |
+
"""Augment flow along a path from s to t."""
|
| 72 |
+
# Determine the path residual capacity.
|
| 73 |
+
flow = inf
|
| 74 |
+
it = iter(path)
|
| 75 |
+
u = next(it)
|
| 76 |
+
for v in it:
|
| 77 |
+
attr = R_succ[u][v]
|
| 78 |
+
flow = min(flow, attr["capacity"] - attr["flow"])
|
| 79 |
+
u = v
|
| 80 |
+
if flow * 2 > inf:
|
| 81 |
+
raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
|
| 82 |
+
# Augment flow along the path.
|
| 83 |
+
it = iter(path)
|
| 84 |
+
u = next(it)
|
| 85 |
+
for v in it:
|
| 86 |
+
R_succ[u][v]["flow"] += flow
|
| 87 |
+
R_succ[v][u]["flow"] -= flow
|
| 88 |
+
u = v
|
| 89 |
+
return flow
|
| 90 |
+
|
| 91 |
+
def relabel(u):
|
| 92 |
+
"""Relabel a node to create an admissible edge."""
|
| 93 |
+
height = n - 1
|
| 94 |
+
for v, attr in R_succ[u].items():
|
| 95 |
+
if attr["flow"] < attr["capacity"]:
|
| 96 |
+
height = min(height, R_nodes[v]["height"])
|
| 97 |
+
return height + 1
|
| 98 |
+
|
| 99 |
+
if cutoff is None:
|
| 100 |
+
cutoff = float("inf")
|
| 101 |
+
|
| 102 |
+
# Phase 1: Look for shortest augmenting paths using depth-first search.
|
| 103 |
+
|
| 104 |
+
flow_value = 0
|
| 105 |
+
path = [s]
|
| 106 |
+
u = s
|
| 107 |
+
d = n if not two_phase else int(min(m**0.5, 2 * n ** (2.0 / 3)))
|
| 108 |
+
done = R_nodes[s]["height"] >= d
|
| 109 |
+
while not done:
|
| 110 |
+
height = R_nodes[u]["height"]
|
| 111 |
+
curr_edge = R_nodes[u]["curr_edge"]
|
| 112 |
+
# Depth-first search for the next node on the path to t.
|
| 113 |
+
while True:
|
| 114 |
+
v, attr = curr_edge.get()
|
| 115 |
+
if height == R_nodes[v]["height"] + 1 and attr["flow"] < attr["capacity"]:
|
| 116 |
+
# Advance to the next node following an admissible edge.
|
| 117 |
+
path.append(v)
|
| 118 |
+
u = v
|
| 119 |
+
break
|
| 120 |
+
try:
|
| 121 |
+
curr_edge.move_to_next()
|
| 122 |
+
except StopIteration:
|
| 123 |
+
counts[height] -= 1
|
| 124 |
+
if counts[height] == 0:
|
| 125 |
+
# Gap heuristic: If relabeling causes a level to become
|
| 126 |
+
# empty, a minimum cut has been identified. The algorithm
|
| 127 |
+
# can now be terminated.
|
| 128 |
+
R.graph["flow_value"] = flow_value
|
| 129 |
+
return R
|
| 130 |
+
height = relabel(u)
|
| 131 |
+
if u == s and height >= d:
|
| 132 |
+
if not two_phase:
|
| 133 |
+
# t is disconnected from s in the residual network. No
|
| 134 |
+
# more augmenting paths exist.
|
| 135 |
+
R.graph["flow_value"] = flow_value
|
| 136 |
+
return R
|
| 137 |
+
else:
|
| 138 |
+
# t is at least d steps away from s. End of phase 1.
|
| 139 |
+
done = True
|
| 140 |
+
break
|
| 141 |
+
counts[height] += 1
|
| 142 |
+
R_nodes[u]["height"] = height
|
| 143 |
+
if u != s:
|
| 144 |
+
# After relabeling, the last edge on the path is no longer
|
| 145 |
+
# admissible. Retreat one step to look for an alternative.
|
| 146 |
+
path.pop()
|
| 147 |
+
u = path[-1]
|
| 148 |
+
break
|
| 149 |
+
if u == t:
|
| 150 |
+
# t is reached. Augment flow along the path and reset it for a new
|
| 151 |
+
# depth-first search.
|
| 152 |
+
flow_value += augment(path)
|
| 153 |
+
if flow_value >= cutoff:
|
| 154 |
+
R.graph["flow_value"] = flow_value
|
| 155 |
+
return R
|
| 156 |
+
path = [s]
|
| 157 |
+
u = s
|
| 158 |
+
|
| 159 |
+
# Phase 2: Look for shortest augmenting paths using breadth-first search.
|
| 160 |
+
flow_value += edmonds_karp_core(R, s, t, cutoff - flow_value)
|
| 161 |
+
|
| 162 |
+
R.graph["flow_value"] = flow_value
|
| 163 |
+
return R
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)
|
| 167 |
+
def shortest_augmenting_path(
|
| 168 |
+
G,
|
| 169 |
+
s,
|
| 170 |
+
t,
|
| 171 |
+
capacity="capacity",
|
| 172 |
+
residual=None,
|
| 173 |
+
value_only=False,
|
| 174 |
+
two_phase=False,
|
| 175 |
+
cutoff=None,
|
| 176 |
+
):
|
| 177 |
+
r"""Find a maximum single-commodity flow using the shortest augmenting path
|
| 178 |
+
algorithm.
|
| 179 |
+
|
| 180 |
+
This function returns the residual network resulting after computing
|
| 181 |
+
the maximum flow. See below for details about the conventions
|
| 182 |
+
NetworkX uses for defining residual networks.
|
| 183 |
+
|
| 184 |
+
This algorithm has a running time of $O(n^2 m)$ for $n$ nodes and $m$
|
| 185 |
+
edges.
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
Parameters
|
| 189 |
+
----------
|
| 190 |
+
G : NetworkX graph
|
| 191 |
+
Edges of the graph are expected to have an attribute called
|
| 192 |
+
'capacity'. If this attribute is not present, the edge is
|
| 193 |
+
considered to have infinite capacity.
|
| 194 |
+
|
| 195 |
+
s : node
|
| 196 |
+
Source node for the flow.
|
| 197 |
+
|
| 198 |
+
t : node
|
| 199 |
+
Sink node for the flow.
|
| 200 |
+
|
| 201 |
+
capacity : string
|
| 202 |
+
Edges of the graph G are expected to have an attribute capacity
|
| 203 |
+
that indicates how much flow the edge can support. If this
|
| 204 |
+
attribute is not present, the edge is considered to have
|
| 205 |
+
infinite capacity. Default value: 'capacity'.
|
| 206 |
+
|
| 207 |
+
residual : NetworkX graph
|
| 208 |
+
Residual network on which the algorithm is to be executed. If None, a
|
| 209 |
+
new residual network is created. Default value: None.
|
| 210 |
+
|
| 211 |
+
value_only : bool
|
| 212 |
+
If True compute only the value of the maximum flow. This parameter
|
| 213 |
+
will be ignored by this algorithm because it is not applicable.
|
| 214 |
+
|
| 215 |
+
two_phase : bool
|
| 216 |
+
If True, a two-phase variant is used. The two-phase variant improves
|
| 217 |
+
the running time on unit-capacity networks from $O(nm)$ to
|
| 218 |
+
$O(\min(n^{2/3}, m^{1/2}) m)$. Default value: False.
|
| 219 |
+
|
| 220 |
+
cutoff : integer, float
|
| 221 |
+
If specified, the algorithm will terminate when the flow value reaches
|
| 222 |
+
or exceeds the cutoff. In this case, it may be unable to immediately
|
| 223 |
+
determine a minimum cut. Default value: None.
|
| 224 |
+
|
| 225 |
+
Returns
|
| 226 |
+
-------
|
| 227 |
+
R : NetworkX DiGraph
|
| 228 |
+
Residual network after computing the maximum flow.
|
| 229 |
+
|
| 230 |
+
Raises
|
| 231 |
+
------
|
| 232 |
+
NetworkXError
|
| 233 |
+
The algorithm does not support MultiGraph and MultiDiGraph. If
|
| 234 |
+
the input graph is an instance of one of these two classes, a
|
| 235 |
+
NetworkXError is raised.
|
| 236 |
+
|
| 237 |
+
NetworkXUnbounded
|
| 238 |
+
If the graph has a path of infinite capacity, the value of a
|
| 239 |
+
feasible flow on the graph is unbounded above and the function
|
| 240 |
+
raises a NetworkXUnbounded.
|
| 241 |
+
|
| 242 |
+
See also
|
| 243 |
+
--------
|
| 244 |
+
:meth:`maximum_flow`
|
| 245 |
+
:meth:`minimum_cut`
|
| 246 |
+
:meth:`edmonds_karp`
|
| 247 |
+
:meth:`preflow_push`
|
| 248 |
+
|
| 249 |
+
Notes
|
| 250 |
+
-----
|
| 251 |
+
The residual network :samp:`R` from an input graph :samp:`G` has the
|
| 252 |
+
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
|
| 253 |
+
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
|
| 254 |
+
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
|
| 255 |
+
in :samp:`G`.
|
| 256 |
+
|
| 257 |
+
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
|
| 258 |
+
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
|
| 259 |
+
in :samp:`G` or zero otherwise. If the capacity is infinite,
|
| 260 |
+
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
|
| 261 |
+
that does not affect the solution of the problem. This value is stored in
|
| 262 |
+
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
|
| 263 |
+
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
|
| 264 |
+
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
|
| 265 |
+
|
| 266 |
+
The flow value, defined as the total flow into :samp:`t`, the sink, is
|
| 267 |
+
stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
|
| 268 |
+
specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
|
| 269 |
+
that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
|
| 270 |
+
:samp:`s`-:samp:`t` cut.
|
| 271 |
+
|
| 272 |
+
Examples
|
| 273 |
+
--------
|
| 274 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
| 275 |
+
|
| 276 |
+
The functions that implement flow algorithms and output a residual
|
| 277 |
+
network, such as this one, are not imported to the base NetworkX
|
| 278 |
+
namespace, so you have to explicitly import them from the flow package.
|
| 279 |
+
|
| 280 |
+
>>> G = nx.DiGraph()
|
| 281 |
+
>>> G.add_edge("x", "a", capacity=3.0)
|
| 282 |
+
>>> G.add_edge("x", "b", capacity=1.0)
|
| 283 |
+
>>> G.add_edge("a", "c", capacity=3.0)
|
| 284 |
+
>>> G.add_edge("b", "c", capacity=5.0)
|
| 285 |
+
>>> G.add_edge("b", "d", capacity=4.0)
|
| 286 |
+
>>> G.add_edge("d", "e", capacity=2.0)
|
| 287 |
+
>>> G.add_edge("c", "y", capacity=2.0)
|
| 288 |
+
>>> G.add_edge("e", "y", capacity=3.0)
|
| 289 |
+
>>> R = shortest_augmenting_path(G, "x", "y")
|
| 290 |
+
>>> flow_value = nx.maximum_flow_value(G, "x", "y")
|
| 291 |
+
>>> flow_value
|
| 292 |
+
3.0
|
| 293 |
+
>>> flow_value == R.graph["flow_value"]
|
| 294 |
+
True
|
| 295 |
+
|
| 296 |
+
"""
|
| 297 |
+
R = shortest_augmenting_path_impl(G, s, t, capacity, residual, two_phase, cutoff)
|
| 298 |
+
R.graph["algorithm"] = "shortest_augmenting_path"
|
| 299 |
+
nx._clear_cache(R)
|
| 300 |
+
return R
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__init__.py
ADDED
|
File without changes
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_gomory_hu.cpython-310.pyc
ADDED
|
Binary file (4.75 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_maxflow.cpython-310.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_maxflow_large_graph.cpython-310.pyc
ADDED
|
Binary file (4.2 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_mincost.cpython-310.pyc
ADDED
|
Binary file (13.4 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/__pycache__/test_networksimplex.cpython-310.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf8f81ceb5eaaee1621aa60b892d83e596a6173f6f6517359b679ff3daa1b0f8
|
| 3 |
+
size 44623
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6f79f0e90fa4c51ec79165f15963e1ed89477576e06bcaa67ae622c260411931
|
| 3 |
+
size 42248
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3b17e66cdeda8edb8d1dec72626c77f1f65dd4675e3f76dc2fc4fd84aa038e30
|
| 3 |
+
size 18972
|
valley/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)
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_maxflow.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, solnFlows, 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 |
+
solnFlows = {1: {2: 1.0}, 2: {1: 1.0}}
|
| 98 |
+
|
| 99 |
+
compare_flows_and_cuts(G, 1, 2, solnFlows, 1.0)
|
| 100 |
+
|
| 101 |
+
def test_graph2(self):
|
| 102 |
+
# A more complex undirected graph
|
| 103 |
+
# adapted from https://web.archive.org/web/20220815055650/https://www.topcoder.com/thrive/articles/Maximum%20Flow:%20Part%20One
|
| 104 |
+
G = nx.Graph()
|
| 105 |
+
G.add_edge("x", "a", capacity=3.0)
|
| 106 |
+
G.add_edge("x", "b", capacity=1.0)
|
| 107 |
+
G.add_edge("a", "c", capacity=3.0)
|
| 108 |
+
G.add_edge("b", "c", capacity=5.0)
|
| 109 |
+
G.add_edge("b", "d", capacity=4.0)
|
| 110 |
+
G.add_edge("d", "e", capacity=2.0)
|
| 111 |
+
G.add_edge("c", "y", capacity=2.0)
|
| 112 |
+
G.add_edge("e", "y", capacity=3.0)
|
| 113 |
+
|
| 114 |
+
H = {
|
| 115 |
+
"x": {"a": 3, "b": 1},
|
| 116 |
+
"a": {"c": 3, "x": 3},
|
| 117 |
+
"b": {"c": 1, "d": 2, "x": 1},
|
| 118 |
+
"c": {"a": 3, "b": 1, "y": 2},
|
| 119 |
+
"d": {"b": 2, "e": 2},
|
| 120 |
+
"e": {"d": 2, "y": 2},
|
| 121 |
+
"y": {"c": 2, "e": 2},
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
compare_flows_and_cuts(G, "x", "y", H, 4.0)
|
| 125 |
+
|
| 126 |
+
def test_digraph1(self):
|
| 127 |
+
# The classic directed graph example
|
| 128 |
+
G = nx.DiGraph()
|
| 129 |
+
G.add_edge("a", "b", capacity=1000.0)
|
| 130 |
+
G.add_edge("a", "c", capacity=1000.0)
|
| 131 |
+
G.add_edge("b", "c", capacity=1.0)
|
| 132 |
+
G.add_edge("b", "d", capacity=1000.0)
|
| 133 |
+
G.add_edge("c", "d", capacity=1000.0)
|
| 134 |
+
|
| 135 |
+
H = {
|
| 136 |
+
"a": {"b": 1000.0, "c": 1000.0},
|
| 137 |
+
"b": {"c": 0, "d": 1000.0},
|
| 138 |
+
"c": {"d": 1000.0},
|
| 139 |
+
"d": {},
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
compare_flows_and_cuts(G, "a", "d", H, 2000.0)
|
| 143 |
+
|
| 144 |
+
def test_digraph2(self):
|
| 145 |
+
# An example in which some edges end up with zero flow.
|
| 146 |
+
G = nx.DiGraph()
|
| 147 |
+
G.add_edge("s", "b", capacity=2)
|
| 148 |
+
G.add_edge("s", "c", capacity=1)
|
| 149 |
+
G.add_edge("c", "d", capacity=1)
|
| 150 |
+
G.add_edge("d", "a", capacity=1)
|
| 151 |
+
G.add_edge("b", "a", capacity=2)
|
| 152 |
+
G.add_edge("a", "t", capacity=2)
|
| 153 |
+
|
| 154 |
+
H = {
|
| 155 |
+
"s": {"b": 2, "c": 0},
|
| 156 |
+
"c": {"d": 0},
|
| 157 |
+
"d": {"a": 0},
|
| 158 |
+
"b": {"a": 2},
|
| 159 |
+
"a": {"t": 2},
|
| 160 |
+
"t": {},
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
compare_flows_and_cuts(G, "s", "t", H, 2)
|
| 164 |
+
|
| 165 |
+
def test_digraph3(self):
|
| 166 |
+
# A directed graph example from Cormen et al.
|
| 167 |
+
G = nx.DiGraph()
|
| 168 |
+
G.add_edge("s", "v1", capacity=16.0)
|
| 169 |
+
G.add_edge("s", "v2", capacity=13.0)
|
| 170 |
+
G.add_edge("v1", "v2", capacity=10.0)
|
| 171 |
+
G.add_edge("v2", "v1", capacity=4.0)
|
| 172 |
+
G.add_edge("v1", "v3", capacity=12.0)
|
| 173 |
+
G.add_edge("v3", "v2", capacity=9.0)
|
| 174 |
+
G.add_edge("v2", "v4", capacity=14.0)
|
| 175 |
+
G.add_edge("v4", "v3", capacity=7.0)
|
| 176 |
+
G.add_edge("v3", "t", capacity=20.0)
|
| 177 |
+
G.add_edge("v4", "t", capacity=4.0)
|
| 178 |
+
|
| 179 |
+
H = {
|
| 180 |
+
"s": {"v1": 12.0, "v2": 11.0},
|
| 181 |
+
"v2": {"v1": 0, "v4": 11.0},
|
| 182 |
+
"v1": {"v2": 0, "v3": 12.0},
|
| 183 |
+
"v3": {"v2": 0, "t": 19.0},
|
| 184 |
+
"v4": {"v3": 7.0, "t": 4.0},
|
| 185 |
+
"t": {},
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
compare_flows_and_cuts(G, "s", "t", H, 23.0)
|
| 189 |
+
|
| 190 |
+
def test_digraph4(self):
|
| 191 |
+
# A more complex directed graph
|
| 192 |
+
# from https://web.archive.org/web/20220815055650/https://www.topcoder.com/thrive/articles/Maximum%20Flow:%20Part%20One
|
| 193 |
+
G = nx.DiGraph()
|
| 194 |
+
G.add_edge("x", "a", capacity=3.0)
|
| 195 |
+
G.add_edge("x", "b", capacity=1.0)
|
| 196 |
+
G.add_edge("a", "c", capacity=3.0)
|
| 197 |
+
G.add_edge("b", "c", capacity=5.0)
|
| 198 |
+
G.add_edge("b", "d", capacity=4.0)
|
| 199 |
+
G.add_edge("d", "e", capacity=2.0)
|
| 200 |
+
G.add_edge("c", "y", capacity=2.0)
|
| 201 |
+
G.add_edge("e", "y", capacity=3.0)
|
| 202 |
+
|
| 203 |
+
H = {
|
| 204 |
+
"x": {"a": 2.0, "b": 1.0},
|
| 205 |
+
"a": {"c": 2.0},
|
| 206 |
+
"b": {"c": 0, "d": 1.0},
|
| 207 |
+
"c": {"y": 2.0},
|
| 208 |
+
"d": {"e": 1.0},
|
| 209 |
+
"e": {"y": 1.0},
|
| 210 |
+
"y": {},
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
compare_flows_and_cuts(G, "x", "y", H, 3.0)
|
| 214 |
+
|
| 215 |
+
def test_wikipedia_dinitz_example(self):
|
| 216 |
+
# Nice example from https://en.wikipedia.org/wiki/Dinic's_algorithm
|
| 217 |
+
G = nx.DiGraph()
|
| 218 |
+
G.add_edge("s", 1, capacity=10)
|
| 219 |
+
G.add_edge("s", 2, capacity=10)
|
| 220 |
+
G.add_edge(1, 3, capacity=4)
|
| 221 |
+
G.add_edge(1, 4, capacity=8)
|
| 222 |
+
G.add_edge(1, 2, capacity=2)
|
| 223 |
+
G.add_edge(2, 4, capacity=9)
|
| 224 |
+
G.add_edge(3, "t", capacity=10)
|
| 225 |
+
G.add_edge(4, 3, capacity=6)
|
| 226 |
+
G.add_edge(4, "t", capacity=10)
|
| 227 |
+
|
| 228 |
+
solnFlows = {
|
| 229 |
+
1: {2: 0, 3: 4, 4: 6},
|
| 230 |
+
2: {4: 9},
|
| 231 |
+
3: {"t": 9},
|
| 232 |
+
4: {3: 5, "t": 10},
|
| 233 |
+
"s": {1: 10, 2: 9},
|
| 234 |
+
"t": {},
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
compare_flows_and_cuts(G, "s", "t", solnFlows, 19)
|
| 238 |
+
|
| 239 |
+
def test_optional_capacity(self):
|
| 240 |
+
# Test optional capacity parameter.
|
| 241 |
+
G = nx.DiGraph()
|
| 242 |
+
G.add_edge("x", "a", spam=3.0)
|
| 243 |
+
G.add_edge("x", "b", spam=1.0)
|
| 244 |
+
G.add_edge("a", "c", spam=3.0)
|
| 245 |
+
G.add_edge("b", "c", spam=5.0)
|
| 246 |
+
G.add_edge("b", "d", spam=4.0)
|
| 247 |
+
G.add_edge("d", "e", spam=2.0)
|
| 248 |
+
G.add_edge("c", "y", spam=2.0)
|
| 249 |
+
G.add_edge("e", "y", spam=3.0)
|
| 250 |
+
|
| 251 |
+
solnFlows = {
|
| 252 |
+
"x": {"a": 2.0, "b": 1.0},
|
| 253 |
+
"a": {"c": 2.0},
|
| 254 |
+
"b": {"c": 0, "d": 1.0},
|
| 255 |
+
"c": {"y": 2.0},
|
| 256 |
+
"d": {"e": 1.0},
|
| 257 |
+
"e": {"y": 1.0},
|
| 258 |
+
"y": {},
|
| 259 |
+
}
|
| 260 |
+
solnValue = 3.0
|
| 261 |
+
s = "x"
|
| 262 |
+
t = "y"
|
| 263 |
+
|
| 264 |
+
compare_flows_and_cuts(G, s, t, solnFlows, solnValue, capacity="spam")
|
| 265 |
+
|
| 266 |
+
def test_digraph_infcap_edges(self):
|
| 267 |
+
# DiGraph with infinite capacity edges
|
| 268 |
+
G = nx.DiGraph()
|
| 269 |
+
G.add_edge("s", "a")
|
| 270 |
+
G.add_edge("s", "b", capacity=30)
|
| 271 |
+
G.add_edge("a", "c", capacity=25)
|
| 272 |
+
G.add_edge("b", "c", capacity=12)
|
| 273 |
+
G.add_edge("a", "t", capacity=60)
|
| 274 |
+
G.add_edge("c", "t")
|
| 275 |
+
|
| 276 |
+
H = {
|
| 277 |
+
"s": {"a": 85, "b": 12},
|
| 278 |
+
"a": {"c": 25, "t": 60},
|
| 279 |
+
"b": {"c": 12},
|
| 280 |
+
"c": {"t": 37},
|
| 281 |
+
"t": {},
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
compare_flows_and_cuts(G, "s", "t", H, 97)
|
| 285 |
+
|
| 286 |
+
# DiGraph with infinite capacity digon
|
| 287 |
+
G = nx.DiGraph()
|
| 288 |
+
G.add_edge("s", "a", capacity=85)
|
| 289 |
+
G.add_edge("s", "b", capacity=30)
|
| 290 |
+
G.add_edge("a", "c")
|
| 291 |
+
G.add_edge("c", "a")
|
| 292 |
+
G.add_edge("b", "c", capacity=12)
|
| 293 |
+
G.add_edge("a", "t", capacity=60)
|
| 294 |
+
G.add_edge("c", "t", capacity=37)
|
| 295 |
+
|
| 296 |
+
H = {
|
| 297 |
+
"s": {"a": 85, "b": 12},
|
| 298 |
+
"a": {"c": 25, "t": 60},
|
| 299 |
+
"c": {"a": 0, "t": 37},
|
| 300 |
+
"b": {"c": 12},
|
| 301 |
+
"t": {},
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
compare_flows_and_cuts(G, "s", "t", H, 97)
|
| 305 |
+
|
| 306 |
+
def test_digraph_infcap_path(self):
|
| 307 |
+
# Graph with infinite capacity (s, t)-path
|
| 308 |
+
G = nx.DiGraph()
|
| 309 |
+
G.add_edge("s", "a")
|
| 310 |
+
G.add_edge("s", "b", capacity=30)
|
| 311 |
+
G.add_edge("a", "c")
|
| 312 |
+
G.add_edge("b", "c", capacity=12)
|
| 313 |
+
G.add_edge("a", "t", capacity=60)
|
| 314 |
+
G.add_edge("c", "t")
|
| 315 |
+
|
| 316 |
+
for flow_func in all_funcs:
|
| 317 |
+
pytest.raises(nx.NetworkXUnbounded, flow_func, G, "s", "t")
|
| 318 |
+
|
| 319 |
+
def test_graph_infcap_edges(self):
|
| 320 |
+
# Undirected graph with infinite capacity edges
|
| 321 |
+
G = nx.Graph()
|
| 322 |
+
G.add_edge("s", "a")
|
| 323 |
+
G.add_edge("s", "b", capacity=30)
|
| 324 |
+
G.add_edge("a", "c", capacity=25)
|
| 325 |
+
G.add_edge("b", "c", capacity=12)
|
| 326 |
+
G.add_edge("a", "t", capacity=60)
|
| 327 |
+
G.add_edge("c", "t")
|
| 328 |
+
|
| 329 |
+
H = {
|
| 330 |
+
"s": {"a": 85, "b": 12},
|
| 331 |
+
"a": {"c": 25, "s": 85, "t": 60},
|
| 332 |
+
"b": {"c": 12, "s": 12},
|
| 333 |
+
"c": {"a": 25, "b": 12, "t": 37},
|
| 334 |
+
"t": {"a": 60, "c": 37},
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
compare_flows_and_cuts(G, "s", "t", H, 97)
|
| 338 |
+
|
| 339 |
+
def test_digraph5(self):
|
| 340 |
+
# From ticket #429 by mfrasca.
|
| 341 |
+
G = nx.DiGraph()
|
| 342 |
+
G.add_edge("s", "a", capacity=2)
|
| 343 |
+
G.add_edge("s", "b", capacity=2)
|
| 344 |
+
G.add_edge("a", "b", capacity=5)
|
| 345 |
+
G.add_edge("a", "t", capacity=1)
|
| 346 |
+
G.add_edge("b", "a", capacity=1)
|
| 347 |
+
G.add_edge("b", "t", capacity=3)
|
| 348 |
+
flowSoln = {
|
| 349 |
+
"a": {"b": 1, "t": 1},
|
| 350 |
+
"b": {"a": 0, "t": 3},
|
| 351 |
+
"s": {"a": 2, "b": 2},
|
| 352 |
+
"t": {},
|
| 353 |
+
}
|
| 354 |
+
compare_flows_and_cuts(G, "s", "t", flowSoln, 4)
|
| 355 |
+
|
| 356 |
+
def test_disconnected(self):
|
| 357 |
+
G = nx.Graph()
|
| 358 |
+
G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
|
| 359 |
+
G.remove_node(1)
|
| 360 |
+
assert nx.maximum_flow_value(G, 0, 3) == 0
|
| 361 |
+
flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}
|
| 362 |
+
compare_flows_and_cuts(G, 0, 3, flowSoln, 0)
|
| 363 |
+
|
| 364 |
+
def test_source_target_not_in_graph(self):
|
| 365 |
+
G = nx.Graph()
|
| 366 |
+
G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
|
| 367 |
+
G.remove_node(0)
|
| 368 |
+
for flow_func in all_funcs:
|
| 369 |
+
pytest.raises(nx.NetworkXError, flow_func, G, 0, 3)
|
| 370 |
+
G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
|
| 371 |
+
G.remove_node(3)
|
| 372 |
+
for flow_func in all_funcs:
|
| 373 |
+
pytest.raises(nx.NetworkXError, flow_func, G, 0, 3)
|
| 374 |
+
|
| 375 |
+
def test_source_target_coincide(self):
|
| 376 |
+
G = nx.Graph()
|
| 377 |
+
G.add_node(0)
|
| 378 |
+
for flow_func in all_funcs:
|
| 379 |
+
pytest.raises(nx.NetworkXError, flow_func, G, 0, 0)
|
| 380 |
+
|
| 381 |
+
def test_multigraphs_raise(self):
|
| 382 |
+
G = nx.MultiGraph()
|
| 383 |
+
M = nx.MultiDiGraph()
|
| 384 |
+
G.add_edges_from([(0, 1), (1, 0)], capacity=True)
|
| 385 |
+
for flow_func in all_funcs:
|
| 386 |
+
pytest.raises(nx.NetworkXError, flow_func, G, 0, 0)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class TestMaxFlowMinCutInterface:
|
| 390 |
+
def setup_method(self):
|
| 391 |
+
G = nx.DiGraph()
|
| 392 |
+
G.add_edge("x", "a", capacity=3.0)
|
| 393 |
+
G.add_edge("x", "b", capacity=1.0)
|
| 394 |
+
G.add_edge("a", "c", capacity=3.0)
|
| 395 |
+
G.add_edge("b", "c", capacity=5.0)
|
| 396 |
+
G.add_edge("b", "d", capacity=4.0)
|
| 397 |
+
G.add_edge("d", "e", capacity=2.0)
|
| 398 |
+
G.add_edge("c", "y", capacity=2.0)
|
| 399 |
+
G.add_edge("e", "y", capacity=3.0)
|
| 400 |
+
self.G = G
|
| 401 |
+
H = nx.DiGraph()
|
| 402 |
+
H.add_edge(0, 1, capacity=1.0)
|
| 403 |
+
H.add_edge(1, 2, capacity=1.0)
|
| 404 |
+
self.H = H
|
| 405 |
+
|
| 406 |
+
def test_flow_func_not_callable(self):
|
| 407 |
+
elements = ["this_should_be_callable", 10, {1, 2, 3}]
|
| 408 |
+
G = nx.Graph()
|
| 409 |
+
G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight="capacity")
|
| 410 |
+
for flow_func in interface_funcs:
|
| 411 |
+
for element in elements:
|
| 412 |
+
pytest.raises(nx.NetworkXError, flow_func, G, 0, 1, flow_func=element)
|
| 413 |
+
pytest.raises(nx.NetworkXError, flow_func, G, 0, 1, flow_func=element)
|
| 414 |
+
|
| 415 |
+
def test_flow_func_parameters(self):
|
| 416 |
+
G = self.G
|
| 417 |
+
fv = 3.0
|
| 418 |
+
for interface_func in interface_funcs:
|
| 419 |
+
for flow_func in flow_funcs:
|
| 420 |
+
errmsg = (
|
| 421 |
+
f"Assertion failed in function: {flow_func.__name__} "
|
| 422 |
+
f"in interface {interface_func.__name__}"
|
| 423 |
+
)
|
| 424 |
+
result = interface_func(G, "x", "y", flow_func=flow_func)
|
| 425 |
+
if interface_func in max_min_funcs:
|
| 426 |
+
result = result[0]
|
| 427 |
+
assert fv == result, errmsg
|
| 428 |
+
|
| 429 |
+
def test_minimum_cut_no_cutoff(self):
|
| 430 |
+
G = self.G
|
| 431 |
+
pytest.raises(
|
| 432 |
+
nx.NetworkXError,
|
| 433 |
+
nx.minimum_cut,
|
| 434 |
+
G,
|
| 435 |
+
"x",
|
| 436 |
+
"y",
|
| 437 |
+
flow_func=preflow_push,
|
| 438 |
+
cutoff=1.0,
|
| 439 |
+
)
|
| 440 |
+
pytest.raises(
|
| 441 |
+
nx.NetworkXError,
|
| 442 |
+
nx.minimum_cut_value,
|
| 443 |
+
G,
|
| 444 |
+
"x",
|
| 445 |
+
"y",
|
| 446 |
+
flow_func=preflow_push,
|
| 447 |
+
cutoff=1.0,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
def test_kwargs(self):
|
| 451 |
+
G = self.H
|
| 452 |
+
fv = 1.0
|
| 453 |
+
to_test = (
|
| 454 |
+
(shortest_augmenting_path, {"two_phase": True}),
|
| 455 |
+
(preflow_push, {"global_relabel_freq": 5}),
|
| 456 |
+
)
|
| 457 |
+
for interface_func in interface_funcs:
|
| 458 |
+
for flow_func, kwargs in to_test:
|
| 459 |
+
errmsg = (
|
| 460 |
+
f"Assertion failed in function: {flow_func.__name__} "
|
| 461 |
+
f"in interface {interface_func.__name__}"
|
| 462 |
+
)
|
| 463 |
+
result = interface_func(G, 0, 2, flow_func=flow_func, **kwargs)
|
| 464 |
+
if interface_func in max_min_funcs:
|
| 465 |
+
result = result[0]
|
| 466 |
+
assert fv == result, errmsg
|
| 467 |
+
|
| 468 |
+
def test_kwargs_default_flow_func(self):
|
| 469 |
+
G = self.H
|
| 470 |
+
for interface_func in interface_funcs:
|
| 471 |
+
pytest.raises(
|
| 472 |
+
nx.NetworkXError, interface_func, G, 0, 1, global_relabel_freq=2
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
def test_reusing_residual(self):
|
| 476 |
+
G = self.G
|
| 477 |
+
fv = 3.0
|
| 478 |
+
s, t = "x", "y"
|
| 479 |
+
R = build_residual_network(G, "capacity")
|
| 480 |
+
for interface_func in interface_funcs:
|
| 481 |
+
for flow_func in flow_funcs:
|
| 482 |
+
errmsg = (
|
| 483 |
+
f"Assertion failed in function: {flow_func.__name__} "
|
| 484 |
+
f"in interface {interface_func.__name__}"
|
| 485 |
+
)
|
| 486 |
+
for i in range(3):
|
| 487 |
+
result = interface_func(
|
| 488 |
+
G, "x", "y", flow_func=flow_func, residual=R
|
| 489 |
+
)
|
| 490 |
+
if interface_func in max_min_funcs:
|
| 491 |
+
result = result[0]
|
| 492 |
+
assert fv == result, errmsg
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
# Tests specific to one algorithm
|
| 496 |
+
def test_preflow_push_global_relabel_freq():
|
| 497 |
+
G = nx.DiGraph()
|
| 498 |
+
G.add_edge(1, 2, capacity=1)
|
| 499 |
+
R = preflow_push(G, 1, 2, global_relabel_freq=None)
|
| 500 |
+
assert R.graph["flow_value"] == 1
|
| 501 |
+
pytest.raises(nx.NetworkXError, preflow_push, G, 1, 2, global_relabel_freq=-1)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def test_preflow_push_makes_enough_space():
|
| 505 |
+
# From ticket #1542
|
| 506 |
+
G = nx.DiGraph()
|
| 507 |
+
nx.add_path(G, [0, 1, 3], capacity=1)
|
| 508 |
+
nx.add_path(G, [1, 2, 3], capacity=1)
|
| 509 |
+
R = preflow_push(G, 0, 3, value_only=False)
|
| 510 |
+
assert R.graph["flow_value"] == 1
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def test_shortest_augmenting_path_two_phase():
|
| 514 |
+
k = 5
|
| 515 |
+
p = 1000
|
| 516 |
+
G = nx.DiGraph()
|
| 517 |
+
for i in range(k):
|
| 518 |
+
G.add_edge("s", (i, 0), capacity=1)
|
| 519 |
+
nx.add_path(G, ((i, j) for j in range(p)), capacity=1)
|
| 520 |
+
G.add_edge((i, p - 1), "t", capacity=1)
|
| 521 |
+
R = shortest_augmenting_path(G, "s", "t", two_phase=True)
|
| 522 |
+
assert R.graph["flow_value"] == k
|
| 523 |
+
R = shortest_augmenting_path(G, "s", "t", two_phase=False)
|
| 524 |
+
assert R.graph["flow_value"] == k
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TestCutoff:
|
| 528 |
+
def test_cutoff(self):
|
| 529 |
+
k = 5
|
| 530 |
+
p = 1000
|
| 531 |
+
G = nx.DiGraph()
|
| 532 |
+
for i in range(k):
|
| 533 |
+
G.add_edge("s", (i, 0), capacity=2)
|
| 534 |
+
nx.add_path(G, ((i, j) for j in range(p)), capacity=2)
|
| 535 |
+
G.add_edge((i, p - 1), "t", capacity=2)
|
| 536 |
+
R = shortest_augmenting_path(G, "s", "t", two_phase=True, cutoff=k)
|
| 537 |
+
assert k <= R.graph["flow_value"] <= (2 * k)
|
| 538 |
+
R = shortest_augmenting_path(G, "s", "t", two_phase=False, cutoff=k)
|
| 539 |
+
assert k <= R.graph["flow_value"] <= (2 * k)
|
| 540 |
+
R = edmonds_karp(G, "s", "t", cutoff=k)
|
| 541 |
+
assert k <= R.graph["flow_value"] <= (2 * k)
|
| 542 |
+
R = dinitz(G, "s", "t", cutoff=k)
|
| 543 |
+
assert k <= R.graph["flow_value"] <= (2 * k)
|
| 544 |
+
R = boykov_kolmogorov(G, "s", "t", cutoff=k)
|
| 545 |
+
assert k <= R.graph["flow_value"] <= (2 * k)
|
| 546 |
+
|
| 547 |
+
def test_complete_graph_cutoff(self):
|
| 548 |
+
G = nx.complete_graph(5)
|
| 549 |
+
nx.set_edge_attributes(G, {(u, v): 1 for u, v in G.edges()}, "capacity")
|
| 550 |
+
for flow_func in [
|
| 551 |
+
shortest_augmenting_path,
|
| 552 |
+
edmonds_karp,
|
| 553 |
+
dinitz,
|
| 554 |
+
boykov_kolmogorov,
|
| 555 |
+
]:
|
| 556 |
+
for cutoff in [3, 2, 1]:
|
| 557 |
+
result = nx.maximum_flow_value(
|
| 558 |
+
G, 0, 4, flow_func=flow_func, cutoff=cutoff
|
| 559 |
+
)
|
| 560 |
+
assert cutoff == result, f"cutoff error in {flow_func.__name__}"
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_maxflow_large_graph.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Maximum flow algorithms test suite on large graphs.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import bz2
|
| 5 |
+
import importlib.resources
|
| 6 |
+
import os
|
| 7 |
+
import pickle
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
from networkx.algorithms.flow import (
|
| 13 |
+
boykov_kolmogorov,
|
| 14 |
+
build_flow_dict,
|
| 15 |
+
build_residual_network,
|
| 16 |
+
dinitz,
|
| 17 |
+
edmonds_karp,
|
| 18 |
+
preflow_push,
|
| 19 |
+
shortest_augmenting_path,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
flow_funcs = [
|
| 23 |
+
boykov_kolmogorov,
|
| 24 |
+
dinitz,
|
| 25 |
+
edmonds_karp,
|
| 26 |
+
preflow_push,
|
| 27 |
+
shortest_augmenting_path,
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def gen_pyramid(N):
|
| 32 |
+
# This graph admits a flow of value 1 for which every arc is at
|
| 33 |
+
# capacity (except the arcs incident to the sink which have
|
| 34 |
+
# infinite capacity).
|
| 35 |
+
G = nx.DiGraph()
|
| 36 |
+
|
| 37 |
+
for i in range(N - 1):
|
| 38 |
+
cap = 1.0 / (i + 2)
|
| 39 |
+
for j in range(i + 1):
|
| 40 |
+
G.add_edge((i, j), (i + 1, j), capacity=cap)
|
| 41 |
+
cap = 1.0 / (i + 1) - cap
|
| 42 |
+
G.add_edge((i, j), (i + 1, j + 1), capacity=cap)
|
| 43 |
+
cap = 1.0 / (i + 2) - cap
|
| 44 |
+
|
| 45 |
+
for j in range(N):
|
| 46 |
+
G.add_edge((N - 1, j), "t")
|
| 47 |
+
|
| 48 |
+
return G
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def read_graph(name):
|
| 52 |
+
fname = (
|
| 53 |
+
importlib.resources.files("networkx.algorithms.flow.tests")
|
| 54 |
+
/ f"{name}.gpickle.bz2"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
with bz2.BZ2File(fname, "rb") as f:
|
| 58 |
+
G = pickle.load(f)
|
| 59 |
+
return G
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def validate_flows(G, s, t, soln_value, R, flow_func):
|
| 63 |
+
flow_value = R.graph["flow_value"]
|
| 64 |
+
flow_dict = build_flow_dict(G, R)
|
| 65 |
+
errmsg = f"Assertion failed in function: {flow_func.__name__}"
|
| 66 |
+
assert soln_value == flow_value, errmsg
|
| 67 |
+
assert set(G) == set(flow_dict), errmsg
|
| 68 |
+
for u in G:
|
| 69 |
+
assert set(G[u]) == set(flow_dict[u]), errmsg
|
| 70 |
+
excess = {u: 0 for u in flow_dict}
|
| 71 |
+
for u in flow_dict:
|
| 72 |
+
for v, flow in flow_dict[u].items():
|
| 73 |
+
assert flow <= G[u][v].get("capacity", float("inf")), errmsg
|
| 74 |
+
assert flow >= 0, errmsg
|
| 75 |
+
excess[u] -= flow
|
| 76 |
+
excess[v] += flow
|
| 77 |
+
for u, exc in excess.items():
|
| 78 |
+
if u == s:
|
| 79 |
+
assert exc == -soln_value, errmsg
|
| 80 |
+
elif u == t:
|
| 81 |
+
assert exc == soln_value, errmsg
|
| 82 |
+
else:
|
| 83 |
+
assert exc == 0, errmsg
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class TestMaxflowLargeGraph:
|
| 87 |
+
def test_complete_graph(self):
|
| 88 |
+
N = 50
|
| 89 |
+
G = nx.complete_graph(N)
|
| 90 |
+
nx.set_edge_attributes(G, 5, "capacity")
|
| 91 |
+
R = build_residual_network(G, "capacity")
|
| 92 |
+
kwargs = {"residual": R}
|
| 93 |
+
|
| 94 |
+
for flow_func in flow_funcs:
|
| 95 |
+
kwargs["flow_func"] = flow_func
|
| 96 |
+
errmsg = f"Assertion failed in function: {flow_func.__name__}"
|
| 97 |
+
flow_value = nx.maximum_flow_value(G, 1, 2, **kwargs)
|
| 98 |
+
assert flow_value == 5 * (N - 1), errmsg
|
| 99 |
+
|
| 100 |
+
def test_pyramid(self):
|
| 101 |
+
N = 10
|
| 102 |
+
# N = 100 # this gives a graph with 5051 nodes
|
| 103 |
+
G = gen_pyramid(N)
|
| 104 |
+
R = build_residual_network(G, "capacity")
|
| 105 |
+
kwargs = {"residual": R}
|
| 106 |
+
|
| 107 |
+
for flow_func in flow_funcs:
|
| 108 |
+
kwargs["flow_func"] = flow_func
|
| 109 |
+
errmsg = f"Assertion failed in function: {flow_func.__name__}"
|
| 110 |
+
flow_value = nx.maximum_flow_value(G, (0, 0), "t", **kwargs)
|
| 111 |
+
assert flow_value == pytest.approx(1.0, abs=1e-7)
|
| 112 |
+
|
| 113 |
+
def test_gl1(self):
|
| 114 |
+
G = read_graph("gl1")
|
| 115 |
+
s = 1
|
| 116 |
+
t = len(G)
|
| 117 |
+
R = build_residual_network(G, "capacity")
|
| 118 |
+
kwargs = {"residual": R}
|
| 119 |
+
|
| 120 |
+
# do one flow_func to save time
|
| 121 |
+
flow_func = flow_funcs[0]
|
| 122 |
+
validate_flows(G, s, t, 156545, flow_func(G, s, t, **kwargs), flow_func)
|
| 123 |
+
|
| 124 |
+
# for flow_func in flow_funcs:
|
| 125 |
+
# validate_flows(G, s, t, 156545, flow_func(G, s, t, **kwargs),
|
| 126 |
+
# flow_func)
|
| 127 |
+
|
| 128 |
+
@pytest.mark.slow
|
| 129 |
+
def test_gw1(self):
|
| 130 |
+
G = read_graph("gw1")
|
| 131 |
+
s = 1
|
| 132 |
+
t = len(G)
|
| 133 |
+
R = build_residual_network(G, "capacity")
|
| 134 |
+
kwargs = {"residual": R}
|
| 135 |
+
|
| 136 |
+
for flow_func in flow_funcs:
|
| 137 |
+
validate_flows(G, s, t, 1202018, flow_func(G, s, t, **kwargs), flow_func)
|
| 138 |
+
|
| 139 |
+
def test_wlm3(self):
|
| 140 |
+
G = read_graph("wlm3")
|
| 141 |
+
s = 1
|
| 142 |
+
t = len(G)
|
| 143 |
+
R = build_residual_network(G, "capacity")
|
| 144 |
+
kwargs = {"residual": R}
|
| 145 |
+
|
| 146 |
+
# do one flow_func to save time
|
| 147 |
+
flow_func = flow_funcs[0]
|
| 148 |
+
validate_flows(G, s, t, 11875108, flow_func(G, s, t, **kwargs), flow_func)
|
| 149 |
+
|
| 150 |
+
# for flow_func in flow_funcs:
|
| 151 |
+
# validate_flows(G, s, t, 11875108, flow_func(G, s, t, **kwargs),
|
| 152 |
+
# flow_func)
|
| 153 |
+
|
| 154 |
+
def test_preflow_push_global_relabel(self):
|
| 155 |
+
G = read_graph("gw1")
|
| 156 |
+
R = preflow_push(G, 1, len(G), global_relabel_freq=50)
|
| 157 |
+
assert R.graph["flow_value"] == 1202018
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_mincost.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
| 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 |
+
class TestMinCostFlow:
|
| 12 |
+
def test_simple_digraph(self):
|
| 13 |
+
G = nx.DiGraph()
|
| 14 |
+
G.add_node("a", demand=-5)
|
| 15 |
+
G.add_node("d", demand=5)
|
| 16 |
+
G.add_edge("a", "b", weight=3, capacity=4)
|
| 17 |
+
G.add_edge("a", "c", weight=6, capacity=10)
|
| 18 |
+
G.add_edge("b", "d", weight=1, capacity=9)
|
| 19 |
+
G.add_edge("c", "d", weight=2, capacity=5)
|
| 20 |
+
flowCost, H = nx.network_simplex(G)
|
| 21 |
+
soln = {"a": {"b": 4, "c": 1}, "b": {"d": 4}, "c": {"d": 1}, "d": {}}
|
| 22 |
+
assert flowCost == 24
|
| 23 |
+
assert nx.min_cost_flow_cost(G) == 24
|
| 24 |
+
assert H == soln
|
| 25 |
+
assert nx.min_cost_flow(G) == soln
|
| 26 |
+
assert nx.cost_of_flow(G, H) == 24
|
| 27 |
+
|
| 28 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 29 |
+
assert flowCost == 24
|
| 30 |
+
assert nx.cost_of_flow(G, H) == 24
|
| 31 |
+
assert H == soln
|
| 32 |
+
|
| 33 |
+
def test_negcycle_infcap(self):
|
| 34 |
+
G = nx.DiGraph()
|
| 35 |
+
G.add_node("s", demand=-5)
|
| 36 |
+
G.add_node("t", demand=5)
|
| 37 |
+
G.add_edge("s", "a", weight=1, capacity=3)
|
| 38 |
+
G.add_edge("a", "b", weight=3)
|
| 39 |
+
G.add_edge("c", "a", weight=-6)
|
| 40 |
+
G.add_edge("b", "d", weight=1)
|
| 41 |
+
G.add_edge("d", "c", weight=-2)
|
| 42 |
+
G.add_edge("d", "t", weight=1, capacity=3)
|
| 43 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
|
| 44 |
+
pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G)
|
| 45 |
+
|
| 46 |
+
def test_sum_demands_not_zero(self):
|
| 47 |
+
G = nx.DiGraph()
|
| 48 |
+
G.add_node("s", demand=-5)
|
| 49 |
+
G.add_node("t", demand=4)
|
| 50 |
+
G.add_edge("s", "a", weight=1, capacity=3)
|
| 51 |
+
G.add_edge("a", "b", weight=3)
|
| 52 |
+
G.add_edge("a", "c", weight=-6)
|
| 53 |
+
G.add_edge("b", "d", weight=1)
|
| 54 |
+
G.add_edge("c", "d", weight=-2)
|
| 55 |
+
G.add_edge("d", "t", weight=1, capacity=3)
|
| 56 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
|
| 57 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G)
|
| 58 |
+
|
| 59 |
+
def test_no_flow_satisfying_demands(self):
|
| 60 |
+
G = nx.DiGraph()
|
| 61 |
+
G.add_node("s", demand=-5)
|
| 62 |
+
G.add_node("t", demand=5)
|
| 63 |
+
G.add_edge("s", "a", weight=1, capacity=3)
|
| 64 |
+
G.add_edge("a", "b", weight=3)
|
| 65 |
+
G.add_edge("a", "c", weight=-6)
|
| 66 |
+
G.add_edge("b", "d", weight=1)
|
| 67 |
+
G.add_edge("c", "d", weight=-2)
|
| 68 |
+
G.add_edge("d", "t", weight=1, capacity=3)
|
| 69 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
|
| 70 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G)
|
| 71 |
+
|
| 72 |
+
def test_transshipment(self):
|
| 73 |
+
G = nx.DiGraph()
|
| 74 |
+
G.add_node("a", demand=1)
|
| 75 |
+
G.add_node("b", demand=-2)
|
| 76 |
+
G.add_node("c", demand=-2)
|
| 77 |
+
G.add_node("d", demand=3)
|
| 78 |
+
G.add_node("e", demand=-4)
|
| 79 |
+
G.add_node("f", demand=-4)
|
| 80 |
+
G.add_node("g", demand=3)
|
| 81 |
+
G.add_node("h", demand=2)
|
| 82 |
+
G.add_node("r", demand=3)
|
| 83 |
+
G.add_edge("a", "c", weight=3)
|
| 84 |
+
G.add_edge("r", "a", weight=2)
|
| 85 |
+
G.add_edge("b", "a", weight=9)
|
| 86 |
+
G.add_edge("r", "c", weight=0)
|
| 87 |
+
G.add_edge("b", "r", weight=-6)
|
| 88 |
+
G.add_edge("c", "d", weight=5)
|
| 89 |
+
G.add_edge("e", "r", weight=4)
|
| 90 |
+
G.add_edge("e", "f", weight=3)
|
| 91 |
+
G.add_edge("h", "b", weight=4)
|
| 92 |
+
G.add_edge("f", "d", weight=7)
|
| 93 |
+
G.add_edge("f", "h", weight=12)
|
| 94 |
+
G.add_edge("g", "d", weight=12)
|
| 95 |
+
G.add_edge("f", "g", weight=-1)
|
| 96 |
+
G.add_edge("h", "g", weight=-10)
|
| 97 |
+
flowCost, H = nx.network_simplex(G)
|
| 98 |
+
soln = {
|
| 99 |
+
"a": {"c": 0},
|
| 100 |
+
"b": {"a": 0, "r": 2},
|
| 101 |
+
"c": {"d": 3},
|
| 102 |
+
"d": {},
|
| 103 |
+
"e": {"r": 3, "f": 1},
|
| 104 |
+
"f": {"d": 0, "g": 3, "h": 2},
|
| 105 |
+
"g": {"d": 0},
|
| 106 |
+
"h": {"b": 0, "g": 0},
|
| 107 |
+
"r": {"a": 1, "c": 1},
|
| 108 |
+
}
|
| 109 |
+
assert flowCost == 41
|
| 110 |
+
assert nx.min_cost_flow_cost(G) == 41
|
| 111 |
+
assert H == soln
|
| 112 |
+
assert nx.min_cost_flow(G) == soln
|
| 113 |
+
assert nx.cost_of_flow(G, H) == 41
|
| 114 |
+
|
| 115 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 116 |
+
assert flowCost == 41
|
| 117 |
+
assert nx.cost_of_flow(G, H) == 41
|
| 118 |
+
assert H == soln
|
| 119 |
+
|
| 120 |
+
def test_max_flow_min_cost(self):
|
| 121 |
+
G = nx.DiGraph()
|
| 122 |
+
G.add_edge("s", "a", bandwidth=6)
|
| 123 |
+
G.add_edge("s", "c", bandwidth=10, cost=10)
|
| 124 |
+
G.add_edge("a", "b", cost=6)
|
| 125 |
+
G.add_edge("b", "d", bandwidth=8, cost=7)
|
| 126 |
+
G.add_edge("c", "d", cost=10)
|
| 127 |
+
G.add_edge("d", "t", bandwidth=5, cost=5)
|
| 128 |
+
soln = {
|
| 129 |
+
"s": {"a": 5, "c": 0},
|
| 130 |
+
"a": {"b": 5},
|
| 131 |
+
"b": {"d": 5},
|
| 132 |
+
"c": {"d": 0},
|
| 133 |
+
"d": {"t": 5},
|
| 134 |
+
"t": {},
|
| 135 |
+
}
|
| 136 |
+
flow = nx.max_flow_min_cost(G, "s", "t", capacity="bandwidth", weight="cost")
|
| 137 |
+
assert flow == soln
|
| 138 |
+
assert nx.cost_of_flow(G, flow, weight="cost") == 90
|
| 139 |
+
|
| 140 |
+
G.add_edge("t", "s", cost=-100)
|
| 141 |
+
flowCost, flow = nx.capacity_scaling(G, capacity="bandwidth", weight="cost")
|
| 142 |
+
G.remove_edge("t", "s")
|
| 143 |
+
assert flowCost == -410
|
| 144 |
+
assert flow["t"]["s"] == 5
|
| 145 |
+
del flow["t"]["s"]
|
| 146 |
+
assert flow == soln
|
| 147 |
+
assert nx.cost_of_flow(G, flow, weight="cost") == 90
|
| 148 |
+
|
| 149 |
+
def test_digraph1(self):
|
| 150 |
+
# From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied
|
| 151 |
+
# Mathematical Programming. Addison-Wesley, 1977.
|
| 152 |
+
G = nx.DiGraph()
|
| 153 |
+
G.add_node(1, demand=-20)
|
| 154 |
+
G.add_node(4, demand=5)
|
| 155 |
+
G.add_node(5, demand=15)
|
| 156 |
+
G.add_edges_from(
|
| 157 |
+
[
|
| 158 |
+
(1, 2, {"capacity": 15, "weight": 4}),
|
| 159 |
+
(1, 3, {"capacity": 8, "weight": 4}),
|
| 160 |
+
(2, 3, {"weight": 2}),
|
| 161 |
+
(2, 4, {"capacity": 4, "weight": 2}),
|
| 162 |
+
(2, 5, {"capacity": 10, "weight": 6}),
|
| 163 |
+
(3, 4, {"capacity": 15, "weight": 1}),
|
| 164 |
+
(3, 5, {"capacity": 5, "weight": 3}),
|
| 165 |
+
(4, 5, {"weight": 2}),
|
| 166 |
+
(5, 3, {"capacity": 4, "weight": 1}),
|
| 167 |
+
]
|
| 168 |
+
)
|
| 169 |
+
flowCost, H = nx.network_simplex(G)
|
| 170 |
+
soln = {
|
| 171 |
+
1: {2: 12, 3: 8},
|
| 172 |
+
2: {3: 8, 4: 4, 5: 0},
|
| 173 |
+
3: {4: 11, 5: 5},
|
| 174 |
+
4: {5: 10},
|
| 175 |
+
5: {3: 0},
|
| 176 |
+
}
|
| 177 |
+
assert flowCost == 150
|
| 178 |
+
assert nx.min_cost_flow_cost(G) == 150
|
| 179 |
+
assert H == soln
|
| 180 |
+
assert nx.min_cost_flow(G) == soln
|
| 181 |
+
assert nx.cost_of_flow(G, H) == 150
|
| 182 |
+
|
| 183 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 184 |
+
assert flowCost == 150
|
| 185 |
+
assert H == soln
|
| 186 |
+
assert nx.cost_of_flow(G, H) == 150
|
| 187 |
+
|
| 188 |
+
def test_digraph2(self):
|
| 189 |
+
# Example from ticket #430 from mfrasca. Original source:
|
| 190 |
+
# http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
|
| 191 |
+
G = nx.DiGraph()
|
| 192 |
+
G.add_edge("s", 1, capacity=12)
|
| 193 |
+
G.add_edge("s", 2, capacity=6)
|
| 194 |
+
G.add_edge("s", 3, capacity=14)
|
| 195 |
+
G.add_edge(1, 2, capacity=11, weight=4)
|
| 196 |
+
G.add_edge(2, 3, capacity=9, weight=6)
|
| 197 |
+
G.add_edge(1, 4, capacity=5, weight=5)
|
| 198 |
+
G.add_edge(1, 5, capacity=2, weight=12)
|
| 199 |
+
G.add_edge(2, 5, capacity=4, weight=4)
|
| 200 |
+
G.add_edge(2, 6, capacity=2, weight=6)
|
| 201 |
+
G.add_edge(3, 6, capacity=31, weight=3)
|
| 202 |
+
G.add_edge(4, 5, capacity=18, weight=4)
|
| 203 |
+
G.add_edge(5, 6, capacity=9, weight=5)
|
| 204 |
+
G.add_edge(4, "t", capacity=3)
|
| 205 |
+
G.add_edge(5, "t", capacity=7)
|
| 206 |
+
G.add_edge(6, "t", capacity=22)
|
| 207 |
+
flow = nx.max_flow_min_cost(G, "s", "t")
|
| 208 |
+
soln = {
|
| 209 |
+
1: {2: 6, 4: 5, 5: 1},
|
| 210 |
+
2: {3: 6, 5: 4, 6: 2},
|
| 211 |
+
3: {6: 20},
|
| 212 |
+
4: {5: 2, "t": 3},
|
| 213 |
+
5: {6: 0, "t": 7},
|
| 214 |
+
6: {"t": 22},
|
| 215 |
+
"s": {1: 12, 2: 6, 3: 14},
|
| 216 |
+
"t": {},
|
| 217 |
+
}
|
| 218 |
+
assert flow == soln
|
| 219 |
+
|
| 220 |
+
G.add_edge("t", "s", weight=-100)
|
| 221 |
+
flowCost, flow = nx.capacity_scaling(G)
|
| 222 |
+
G.remove_edge("t", "s")
|
| 223 |
+
assert flow["t"]["s"] == 32
|
| 224 |
+
assert flowCost == -3007
|
| 225 |
+
del flow["t"]["s"]
|
| 226 |
+
assert flow == soln
|
| 227 |
+
assert nx.cost_of_flow(G, flow) == 193
|
| 228 |
+
|
| 229 |
+
def test_digraph3(self):
|
| 230 |
+
"""Combinatorial Optimization: Algorithms and Complexity,
|
| 231 |
+
Papadimitriou Steiglitz at page 140 has an example, 7.1, but that
|
| 232 |
+
admits multiple solutions, so I alter it a bit. From ticket #430
|
| 233 |
+
by mfrasca."""
|
| 234 |
+
|
| 235 |
+
G = nx.DiGraph()
|
| 236 |
+
G.add_edge("s", "a")
|
| 237 |
+
G["s"]["a"].update({0: 2, 1: 4})
|
| 238 |
+
G.add_edge("s", "b")
|
| 239 |
+
G["s"]["b"].update({0: 2, 1: 1})
|
| 240 |
+
G.add_edge("a", "b")
|
| 241 |
+
G["a"]["b"].update({0: 5, 1: 2})
|
| 242 |
+
G.add_edge("a", "t")
|
| 243 |
+
G["a"]["t"].update({0: 1, 1: 5})
|
| 244 |
+
G.add_edge("b", "a")
|
| 245 |
+
G["b"]["a"].update({0: 1, 1: 3})
|
| 246 |
+
G.add_edge("b", "t")
|
| 247 |
+
G["b"]["t"].update({0: 3, 1: 2})
|
| 248 |
+
|
| 249 |
+
"PS.ex.7.1: testing main function"
|
| 250 |
+
sol = nx.max_flow_min_cost(G, "s", "t", capacity=0, weight=1)
|
| 251 |
+
flow = sum(v for v in sol["s"].values())
|
| 252 |
+
assert 4 == flow
|
| 253 |
+
assert 23 == nx.cost_of_flow(G, sol, weight=1)
|
| 254 |
+
assert sol["s"] == {"a": 2, "b": 2}
|
| 255 |
+
assert sol["a"] == {"b": 1, "t": 1}
|
| 256 |
+
assert sol["b"] == {"a": 0, "t": 3}
|
| 257 |
+
assert sol["t"] == {}
|
| 258 |
+
|
| 259 |
+
G.add_edge("t", "s")
|
| 260 |
+
G["t"]["s"].update({1: -100})
|
| 261 |
+
flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1)
|
| 262 |
+
G.remove_edge("t", "s")
|
| 263 |
+
flow = sum(v for v in sol["s"].values())
|
| 264 |
+
assert 4 == flow
|
| 265 |
+
assert sol["t"]["s"] == 4
|
| 266 |
+
assert flowCost == -377
|
| 267 |
+
del sol["t"]["s"]
|
| 268 |
+
assert sol["s"] == {"a": 2, "b": 2}
|
| 269 |
+
assert sol["a"] == {"b": 1, "t": 1}
|
| 270 |
+
assert sol["b"] == {"a": 0, "t": 3}
|
| 271 |
+
assert sol["t"] == {}
|
| 272 |
+
assert nx.cost_of_flow(G, sol, weight=1) == 23
|
| 273 |
+
|
| 274 |
+
def test_zero_capacity_edges(self):
|
| 275 |
+
"""Address issue raised in ticket #617 by arv."""
|
| 276 |
+
G = nx.DiGraph()
|
| 277 |
+
G.add_edges_from(
|
| 278 |
+
[
|
| 279 |
+
(1, 2, {"capacity": 1, "weight": 1}),
|
| 280 |
+
(1, 5, {"capacity": 1, "weight": 1}),
|
| 281 |
+
(2, 3, {"capacity": 0, "weight": 1}),
|
| 282 |
+
(2, 5, {"capacity": 1, "weight": 1}),
|
| 283 |
+
(5, 3, {"capacity": 2, "weight": 1}),
|
| 284 |
+
(5, 4, {"capacity": 0, "weight": 1}),
|
| 285 |
+
(3, 4, {"capacity": 2, "weight": 1}),
|
| 286 |
+
]
|
| 287 |
+
)
|
| 288 |
+
G.nodes[1]["demand"] = -1
|
| 289 |
+
G.nodes[2]["demand"] = -1
|
| 290 |
+
G.nodes[4]["demand"] = 2
|
| 291 |
+
|
| 292 |
+
flowCost, H = nx.network_simplex(G)
|
| 293 |
+
soln = {1: {2: 0, 5: 1}, 2: {3: 0, 5: 1}, 3: {4: 2}, 4: {}, 5: {3: 2, 4: 0}}
|
| 294 |
+
assert flowCost == 6
|
| 295 |
+
assert nx.min_cost_flow_cost(G) == 6
|
| 296 |
+
assert H == soln
|
| 297 |
+
assert nx.min_cost_flow(G) == soln
|
| 298 |
+
assert nx.cost_of_flow(G, H) == 6
|
| 299 |
+
|
| 300 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 301 |
+
assert flowCost == 6
|
| 302 |
+
assert H == soln
|
| 303 |
+
assert nx.cost_of_flow(G, H) == 6
|
| 304 |
+
|
| 305 |
+
def test_digon(self):
|
| 306 |
+
"""Check if digons are handled properly. Taken from ticket
|
| 307 |
+
#618 by arv."""
|
| 308 |
+
nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})]
|
| 309 |
+
edges = [
|
| 310 |
+
(1, 2, {"capacity": 3, "weight": 600000}),
|
| 311 |
+
(2, 1, {"capacity": 2, "weight": 0}),
|
| 312 |
+
(2, 3, {"capacity": 5, "weight": 714285}),
|
| 313 |
+
(3, 2, {"capacity": 2, "weight": 0}),
|
| 314 |
+
]
|
| 315 |
+
G = nx.DiGraph(edges)
|
| 316 |
+
G.add_nodes_from(nodes)
|
| 317 |
+
flowCost, H = nx.network_simplex(G)
|
| 318 |
+
soln = {1: {2: 0}, 2: {1: 0, 3: 4}, 3: {2: 0}}
|
| 319 |
+
assert flowCost == 2857140
|
| 320 |
+
assert nx.min_cost_flow_cost(G) == 2857140
|
| 321 |
+
assert H == soln
|
| 322 |
+
assert nx.min_cost_flow(G) == soln
|
| 323 |
+
assert nx.cost_of_flow(G, H) == 2857140
|
| 324 |
+
|
| 325 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 326 |
+
assert flowCost == 2857140
|
| 327 |
+
assert H == soln
|
| 328 |
+
assert nx.cost_of_flow(G, H) == 2857140
|
| 329 |
+
|
| 330 |
+
def test_deadend(self):
|
| 331 |
+
"""Check if one-node cycles are handled properly. Taken from ticket
|
| 332 |
+
#2906 from @sshraven."""
|
| 333 |
+
G = nx.DiGraph()
|
| 334 |
+
|
| 335 |
+
G.add_nodes_from(range(5), demand=0)
|
| 336 |
+
G.nodes[4]["demand"] = -13
|
| 337 |
+
G.nodes[3]["demand"] = 13
|
| 338 |
+
|
| 339 |
+
G.add_edges_from([(0, 2), (0, 3), (2, 1)], capacity=20, weight=0.1)
|
| 340 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.min_cost_flow, G)
|
| 341 |
+
|
| 342 |
+
def test_infinite_capacity_neg_digon(self):
|
| 343 |
+
"""An infinite capacity negative cost digon results in an unbounded
|
| 344 |
+
instance."""
|
| 345 |
+
nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})]
|
| 346 |
+
edges = [
|
| 347 |
+
(1, 2, {"weight": -600}),
|
| 348 |
+
(2, 1, {"weight": 0}),
|
| 349 |
+
(2, 3, {"capacity": 5, "weight": 714285}),
|
| 350 |
+
(3, 2, {"capacity": 2, "weight": 0}),
|
| 351 |
+
]
|
| 352 |
+
G = nx.DiGraph(edges)
|
| 353 |
+
G.add_nodes_from(nodes)
|
| 354 |
+
pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G)
|
| 355 |
+
pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G)
|
| 356 |
+
|
| 357 |
+
def test_finite_capacity_neg_digon(self):
|
| 358 |
+
"""The digon should receive the maximum amount of flow it can handle.
|
| 359 |
+
Taken from ticket #749 by @chuongdo."""
|
| 360 |
+
G = nx.DiGraph()
|
| 361 |
+
G.add_edge("a", "b", capacity=1, weight=-1)
|
| 362 |
+
G.add_edge("b", "a", capacity=1, weight=-1)
|
| 363 |
+
min_cost = -2
|
| 364 |
+
assert nx.min_cost_flow_cost(G) == min_cost
|
| 365 |
+
|
| 366 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 367 |
+
assert flowCost == -2
|
| 368 |
+
assert H == {"a": {"b": 1}, "b": {"a": 1}}
|
| 369 |
+
assert nx.cost_of_flow(G, H) == -2
|
| 370 |
+
|
| 371 |
+
def test_multidigraph(self):
|
| 372 |
+
"""Multidigraphs are acceptable."""
|
| 373 |
+
G = nx.MultiDiGraph()
|
| 374 |
+
G.add_weighted_edges_from([(1, 2, 1), (2, 3, 2)], weight="capacity")
|
| 375 |
+
flowCost, H = nx.network_simplex(G)
|
| 376 |
+
assert flowCost == 0
|
| 377 |
+
assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}}
|
| 378 |
+
|
| 379 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 380 |
+
assert flowCost == 0
|
| 381 |
+
assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}}
|
| 382 |
+
|
| 383 |
+
def test_negative_selfloops(self):
|
| 384 |
+
"""Negative selfloops should cause an exception if uncapacitated and
|
| 385 |
+
always be saturated otherwise.
|
| 386 |
+
"""
|
| 387 |
+
G = nx.DiGraph()
|
| 388 |
+
G.add_edge(1, 1, weight=-1)
|
| 389 |
+
pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G)
|
| 390 |
+
pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G)
|
| 391 |
+
G[1][1]["capacity"] = 2
|
| 392 |
+
flowCost, H = nx.network_simplex(G)
|
| 393 |
+
assert flowCost == -2
|
| 394 |
+
assert H == {1: {1: 2}}
|
| 395 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 396 |
+
assert flowCost == -2
|
| 397 |
+
assert H == {1: {1: 2}}
|
| 398 |
+
|
| 399 |
+
G = nx.MultiDiGraph()
|
| 400 |
+
G.add_edge(1, 1, "x", weight=-1)
|
| 401 |
+
G.add_edge(1, 1, "y", weight=1)
|
| 402 |
+
pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G)
|
| 403 |
+
pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G)
|
| 404 |
+
G[1][1]["x"]["capacity"] = 2
|
| 405 |
+
flowCost, H = nx.network_simplex(G)
|
| 406 |
+
assert flowCost == -2
|
| 407 |
+
assert H == {1: {1: {"x": 2, "y": 0}}}
|
| 408 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 409 |
+
assert flowCost == -2
|
| 410 |
+
assert H == {1: {1: {"x": 2, "y": 0}}}
|
| 411 |
+
|
| 412 |
+
def test_bone_shaped(self):
|
| 413 |
+
# From #1283
|
| 414 |
+
G = nx.DiGraph()
|
| 415 |
+
G.add_node(0, demand=-4)
|
| 416 |
+
G.add_node(1, demand=2)
|
| 417 |
+
G.add_node(2, demand=2)
|
| 418 |
+
G.add_node(3, demand=4)
|
| 419 |
+
G.add_node(4, demand=-2)
|
| 420 |
+
G.add_node(5, demand=-2)
|
| 421 |
+
G.add_edge(0, 1, capacity=4)
|
| 422 |
+
G.add_edge(0, 2, capacity=4)
|
| 423 |
+
G.add_edge(4, 3, capacity=4)
|
| 424 |
+
G.add_edge(5, 3, capacity=4)
|
| 425 |
+
G.add_edge(0, 3, capacity=0)
|
| 426 |
+
flowCost, H = nx.network_simplex(G)
|
| 427 |
+
assert flowCost == 0
|
| 428 |
+
assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}}
|
| 429 |
+
flowCost, H = nx.capacity_scaling(G)
|
| 430 |
+
assert flowCost == 0
|
| 431 |
+
assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}}
|
| 432 |
+
|
| 433 |
+
def test_exceptions(self):
|
| 434 |
+
G = nx.Graph()
|
| 435 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G)
|
| 436 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.capacity_scaling, G)
|
| 437 |
+
G = nx.MultiGraph()
|
| 438 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G)
|
| 439 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.capacity_scaling, G)
|
| 440 |
+
G = nx.DiGraph()
|
| 441 |
+
pytest.raises(nx.NetworkXError, nx.network_simplex, G)
|
| 442 |
+
# pytest.raises(nx.NetworkXError, nx.capacity_scaling, G)
|
| 443 |
+
G.add_node(0, demand=float("inf"))
|
| 444 |
+
pytest.raises(nx.NetworkXError, nx.network_simplex, G)
|
| 445 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G)
|
| 446 |
+
G.nodes[0]["demand"] = 0
|
| 447 |
+
G.add_node(1, demand=0)
|
| 448 |
+
G.add_edge(0, 1, weight=-float("inf"))
|
| 449 |
+
pytest.raises(nx.NetworkXError, nx.network_simplex, G)
|
| 450 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G)
|
| 451 |
+
G[0][1]["weight"] = 0
|
| 452 |
+
G.add_edge(0, 0, weight=float("inf"))
|
| 453 |
+
pytest.raises(nx.NetworkXError, nx.network_simplex, G)
|
| 454 |
+
# pytest.raises(nx.NetworkXError, nx.capacity_scaling, G)
|
| 455 |
+
G[0][0]["weight"] = 0
|
| 456 |
+
G[0][1]["capacity"] = -1
|
| 457 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
|
| 458 |
+
# pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G)
|
| 459 |
+
G[0][1]["capacity"] = 0
|
| 460 |
+
G[0][0]["capacity"] = -1
|
| 461 |
+
pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G)
|
| 462 |
+
# pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G)
|
| 463 |
+
|
| 464 |
+
def test_large(self):
|
| 465 |
+
fname = (
|
| 466 |
+
importlib.resources.files("networkx.algorithms.flow.tests")
|
| 467 |
+
/ "netgen-2.gpickle.bz2"
|
| 468 |
+
)
|
| 469 |
+
with bz2.BZ2File(fname, "rb") as f:
|
| 470 |
+
G = pickle.load(f)
|
| 471 |
+
flowCost, flowDict = nx.network_simplex(G)
|
| 472 |
+
assert 6749969302 == flowCost
|
| 473 |
+
assert 6749969302 == nx.cost_of_flow(G, flowDict)
|
| 474 |
+
flowCost, flowDict = nx.capacity_scaling(G)
|
| 475 |
+
assert 6749969302 == flowCost
|
| 476 |
+
assert 6749969302 == nx.cost_of_flow(G, flowDict)
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/test_networksimplex.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 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)
|
valley/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ccacba1e0fbfb30bec361f0e48ec88c999d3474fcda5ddf93bd444ace17cfa0e
|
| 3 |
+
size 88132
|
valley/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
|
valley/lib/python3.10/site-packages/networkx/algorithms/traversal/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .beamsearch import *
|
| 2 |
+
from .breadth_first_search import *
|
| 3 |
+
from .depth_first_search import *
|
| 4 |
+
from .edgedfs import *
|
| 5 |
+
from .edgebfs import *
|
valley/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (308 Bytes). View file
|
|
|
valley/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/beamsearch.cpython-310.pyc
ADDED
|
Binary file (3.12 kB). View file
|
|
|