Skip to content

Add shortest augmenting path maximum flow algorithm - #1099

Merged
hagberg merged 6 commits into
networkx:masterfrom
ysitu:sap
Apr 9, 2014
Merged

hagberg merged 6 commits into
networkx:masterfrom
ysitu:sap

Conversation

@ysitu

@ysitu ysitu commented Apr 8, 2014

Copy link
Copy Markdown
Contributor

This is Ahuja & Orlin's shortest augmenting path algorithm briefly touched on in #1095. See [1] for detailed description. The two-phase method tailored for unit-capacity networks in [1] is also provided through an optional parameter.

Timing tests
Cases from #1082

For general problems, SAP is no doubt an improvement over Edmonds–Karp, but highest-label preflow-push is a better idea.

Case ford_fulkerson shortest_augmenting_path preflow_push
GL1 1.36 s 0.68 s 0.12 s
GL2 4.05 s 1.27 s 0.20 s
GL3 17.50 s 5.30 s 0.80 s
GL4 65.67 s 11.74 s 1.25 s
GL5 308.97 s 39.69 s 2.88 s
GL6 1508.11 s 170.58 s 6.65 s
GW1 0.52 s 0.49 s 0.33 s
GW2 2.50 s 1.68 s 0.70 s
GW3 7.80 s 4.22 s 1.79 s
GW4 34.07 s 12.46 s 4.05 s
GW5 165.34 s 40.50 s 10.94 s
GW6 844.14 s 117.70 s 28.95 s
WLM1 0.09 s 0.04 s 0.02 s
WLM2 0.42 s 0.10 s 0.06 s
WLM3 1.38 s 0.24 s 0.12 s
WLM4 7.80 s 0.83 s 0.32 s
WLM5 42.75 s 2.56 s 1.06 s
WLM6 188.53 s 6.06 s 3.01 s
3000 vs 3000 random bipartite matching

Edmonds–Karp is good when the graph is very dense (m/_n_² > 0.1) or very sparse (m/_n_² < 0.00001). In the more sensible range, SAP is the king.

The two-phase method seems to make a difference only when the gap heuristic is disabled. When enabled, the heuristic always terminates the algorithm before the criterion for switching to phase 2 is met. So there is no reason to disable it.

#edges ford_fulkerson shortest_augmenting_path preflow_push
9000000 52.570 s 96.890 s 189.640 s
901033 8.100 s 9.930 s 11.290 s
89714 3.290 s 1.250 s 1.610 s
8832 3.750 s 0.700 s 0.750 s
882 1.380 s 0.150 s 0.260 s
90 0.250 s 0.120 s 0.210 s
11 0.070 s 0.110 s 0.210 s
  • 6000 extra edges needed for reducing bipartite matching to maximum flow are not counted.
Reference
  1. Ahuja, R. K.; Orlin, J. B. (1991). "Distance-directed augmenting path algorithms for maximum flow and parametric maximum flow problems". Naval Research Logistics, 38 (3): 413–430.

@ysitu

ysitu commented Apr 8, 2014

Copy link
Copy Markdown
Contributor Author

I need help with refactoring. There are several auxiliary classes and functions in prefixed with underscores in preflow_push.py imported into shortest_augmenting_path.py. I want to move them to a separate file, but however I do it, I get an ImportError when I do import networkx as nx from the interactive prompt. Neither does nosetests run.

@hagberg

hagberg commented Apr 8, 2014

Copy link
Copy Markdown
Member

That is a very interesting table. Thanks for this!

As for refactoring - I can't quite tell what your error is. Can you post the whole message?

@ysitu

ysitu commented Apr 8, 2014

Copy link
Copy Markdown
Contributor Author
>>> import networkx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/homes/ysitu/work/github/networkx/networkx/__init__.py", line 87, in <module>
    import networkx.drawing
  File "/homes/ysitu/work/github/networkx/networkx/drawing/__init__.py", line 8, in <module>
    from networkx.drawing.nx_agraph import *
  File "/homes/ysitu/work/github/networkx/networkx/drawing/nx_agraph.py", line 276, in <module>
    @nx.utils.open_file(5, 'w')
AttributeError: 'module' object has no attribute 'open_file'

after applying the following diff:

diff --git a/networkx/algorithms/flow/preflow_push.py b/networkx/algorithms/flow/preflow_push.py
index 20169f2..f4b0daf 100644
--- a/networkx/algorithms/flow/preflow_push.py
+++ b/networkx/algorithms/flow/preflow_push.py
@@ -11,129 +11,13 @@ __author__ = """ysitu <[email protected]>"""
 from collections import deque
 from itertools import islice
 import networkx as nx
+from networkx.algorithms.flow.utils import *

 __all__ = ['preflow_push',
            'preflow_push_value',
            'preflow_push_flow']


-class _CurrentEdge(object):
-    """Mechanism for iterating over out-edges incident to a node in a circular
-    manner. StopIteration exception is raised when wraparound occurs.
-    """
-
-    def __init__(self, edges):
-        self._edges = edges
-        if self._edges:
-            self._rewind()
-
-    def get(self):
-        return self._curr
-
-    def move_to_next(self):
-        try:
-            self._curr = next(self._it)
-        except StopIteration:
-            self._rewind()
-            raise
-
-    def _rewind(self):
-        self._it = iter(self._edges.items())
-        self._curr = next(self._it)
-
-
-class _Level(object):
-    """Active and inactive nodes in a level.
-    """
-
-    def __init__(self):
-        self.active = set()
-        self.inactive = set()
-
-
-class _GlobalRelabelThreshold(object):
-    """Measurement of work before the global relabeling heuristic should be
-    applied.
-    """
-
-    def __init__(self, n, m, freq):
-        self._threshold = (n + m) / freq if freq else float('inf')
-        self._work = 0
-
-    def add_work(self, work):
-        self._work += work
-
-    def is_reached(self):
-        return self._work >= self._threshold
-
-    def clear_work(self):
-        self._work = 0
-
-
-def _build_residual_network(G, s, t, capacity):
-    """Build the residual network. Initialize the edge capacities so that they
-    correspond to a zero flow.
-    """
-    if G.is_multigraph():
-        raise nx.NetworkXError(
-                'MultiGraph and MultiDiGraph not supported (yet).')
-
-    if s not in G:
-        raise nx.NetworkXError('node %s not in graph' % str(s))
-    if t not in G:
-        raise nx.NetworkXError('node %s not in graph' % str(t))
-    if s == t:
-        raise nx.NetworkXError('source and sink are the same node')
-
-    R = nx.DiGraph()
-    R.add_nodes_from(G, excess=0)
-
-    # Extract edges with positive capacities. Self loops excluded.
-    edge_list = [(u, v, attr) for u, v, attr in G.edges_iter(data=True)
-                 if u != v and (capacity not in attr or attr[capacity] > 0)]
-    # Simulate infinity with twice the sum of the finite edge capacities or any
-    # positive value if the sum is zero. This allows the infinite-capacity
-    # edges to be distinguished for detecting unboundedness. If the maximum
-    # flow is finite, these edge still cannot appear in the minimum cut and
-    # thus guarantee correctness.
-    inf = float('inf')
-    inf = 2 * sum(attr[capacity] for u, v, attr in edge_list
-                  if capacity in attr and attr[capacity] != inf) or 1
-    if G.is_directed():
-        for u, v, attr in edge_list:
-            r = attr[capacity] if capacity in attr else inf
-            if not R.has_edge(u, v):
-                # Both (u, v) and (v, u) must be present in the residual
-                # network.
-                R.add_edge(u, v, capacity=r, flow=0)
-                R.add_edge(v, u, capacity=0, flow=0)
-            else:
-                # The edge (u, v) was added when (v, u) was visited.
-                R[u][v]['capacity'] = r
-    else:
-        for u, v, attr in edge_list:
-            # Add a pair of edges with equal residual capacities.
-            r = attr[capacity] if capacity in attr else inf
-            R.add_edge(u, v, capacity=r, flow=0)
-            R.add_edge(v, u, capacity=r, flow=0)
-
-    # Detect unboundedness by determining reachability of t from s using only
-    # infinite-capacity edges.
-    q = deque([s])
-    seen = set([s])
-    while q:
-        u = q.popleft()
-        for v, attr in R[u].items():
-            if attr['capacity'] == inf and v not in seen:
-                if v == t:
-                    raise nx.NetworkXUnbounded(
-                            'Infinite capacity path, flow unbounded above.')
-                seen.add(v)
-                q.append(v)
-
-    return R
-
-
 def preflow_push_impl(G, s, t, capacity, global_relabel_freq, compute_flow):
     """Implementation of the highest-label preflow-push algorithm.
     """
@@ -384,17 +268,6 @@ def preflow_push_impl(G, s, t, capacity, global_relabel_freq, compute_flow):
     return R


-def _build_flow_dict(G, R):
-    """Build a flow dictionary from a residual network.
-    """
-    flow_dict = {}
-    for u in G:
-        flow_dict[u] = dict((v, 0) for v in G[u])
-        flow_dict[u].update((v, R[u][v]['flow']) for v in R[u]
-                            if R[u][v]['flow'] > 0)
-    return flow_dict
-
-
 def preflow_push(G, s, t, capacity='capacity', global_relabel_freq=1):
     """Find a maximum single-commodity flow using the highest-label
     preflow-push algorithm.
diff --git a/networkx/algorithms/flow/shortest_augmenting_path.py b/networkx/algorithms/flow/shortest_augmenting_path.py
index 152486a..35366ca 100644
--- a/networkx/algorithms/flow/shortest_augmenting_path.py
+++ b/networkx/algorithms/flow/shortest_augmenting_path.py
@@ -10,9 +10,7 @@ __author__ = """ysitu <[email protected]>"""

 from collections import deque
 import networkx as nx
-from networkx.algorithms.flow.preflow_push import _CurrentEdge
-from networkx.algorithms.flow.preflow_push import _build_flow_dict
-from networkx.algorithms.flow.preflow_push import _build_residual_network
+from networkx.algorithms.flow.utils import *

 __all__ = ['shortest_augmenting_path', 'shortest_augmenting_path_value',
            'shortest_augmenting_path_flow']
diff --git a/networkx/algorithms/flow/utils.py b/networkx/algorithms/flow/utils.py
new file mode 100644
index 0000000..8b1a4cd
--- /dev/null
+++ b/networkx/algorithms/flow/utils.py
@@ -0,0 +1,128 @@
+import networkx as nx
+
+class _CurrentEdge(object):
+    """Mechanism for iterating over out-edges incident to a node in a circular
+    manner. StopIteration exception is raised when wraparound occurs.
+    """
+
+    def __init__(self, edges):
+        self._edges = edges
+        if self._edges:
+            self._rewind()
+
+    def get(self):
+        return self._curr
+
+    def move_to_next(self):
+        try:
+            self._curr = next(self._it)
+        except StopIteration:
+            self._rewind()
+            raise
+
+    def _rewind(self):
+        self._it = iter(self._edges.items())
+        self._curr = next(self._it)
+
+
+class _Level(object):
+    """Active and inactive nodes in a level.
+    """
+
+    def __init__(self):
+        self.active = set()
+        self.inactive = set()
+
+
+class _GlobalRelabelThreshold(object):
+    """Measurement of work before the global relabeling heuristic should be
+    applied.
+    """
+
+    def __init__(self, n, m, freq):
+        self._threshold = (n + m) / freq if freq else float('inf')
+        self._work = 0
+
+    def add_work(self, work):
+        self._work += work
+
+    def is_reached(self):
+        return self._work >= self._threshold
+
+    def clear_work(self):
+        self._work = 0
+
+
+def _build_residual_network(G, s, t, capacity):
+    """Build the residual network. Initialize the edge capacities so that they
+    correspond to a zero flow.
+    """
+    if G.is_multigraph():
+        raise nx.NetworkXError(
+                'MultiGraph and MultiDiGraph not supported (yet).')
+
+    if s not in G:
+        raise nx.NetworkXError('node %s not in graph' % str(s))
+    if t not in G:
+        raise nx.NetworkXError('node %s not in graph' % str(t))
+    if s == t:
+        raise nx.NetworkXError('source and sink are the same node')
+
+    R = nx.DiGraph()
+    R.add_nodes_from(G, excess=0)
+
+    # Extract edges with positive capacities. Self loops excluded.
+    edge_list = [(u, v, attr) for u, v, attr in G.edges_iter(data=True)
+                 if u != v and (capacity not in attr or attr[capacity] > 0)]
+    # Simulate infinity with twice the sum of the finite edge capacities or any
+    # positive value if the sum is zero. This allows the infinite-capacity
+    # edges to be distinguished for detecting unboundedness. If the maximum
+    # flow is finite, these edge still cannot appear in the minimum cut and
+    # thus guarantee correctness.
+    inf = float('inf')
+    inf = 2 * sum(attr[capacity] for u, v, attr in edge_list
+                  if capacity in attr and attr[capacity] != inf) or 1
+    if G.is_directed():
+        for u, v, attr in edge_list:
+            r = attr[capacity] if capacity in attr else inf
+            if not R.has_edge(u, v):
+                # Both (u, v) and (v, u) must be present in the residual
+                # network.
+                R.add_edge(u, v, capacity=r, flow=0)
+                R.add_edge(v, u, capacity=0, flow=0)
+            else:
+                # The edge (u, v) was added when (v, u) was visited.
+                R[u][v]['capacity'] = r
+    else:
+        for u, v, attr in edge_list:
+            # Add a pair of edges with equal residual capacities.
+            r = attr[capacity] if capacity in attr else inf
+            R.add_edge(u, v, capacity=r, flow=0)
+            R.add_edge(v, u, capacity=r, flow=0)
+
+    # Detect unboundedness by determining reachability of t from s using only
+    # infinite-capacity edges.
+    q = deque([s])
+    seen = set([s])
+    while q:
+        u = q.popleft()
+        for v, attr in R[u].items():
+            if attr['capacity'] == inf and v not in seen:
+                if v == t:
+                    raise nx.NetworkXUnbounded(
+                            'Infinite capacity path, flow unbounded above.')
+                seen.add(v)
+                q.append(v)
+
+    return R
+
+
+def _build_flow_dict(G, R):
+    """Build a flow dictionary from a residual network.
+    """
+    flow_dict = {}
+    for u in G:
+        flow_dict[u] = dict((v, 0) for v in G[u])
+        flow_dict[u].update((v, R[u][v]['flow']) for v in R[u]
+                            if R[u][v]['flow'] > 0)
+    return flow_dict

@jtorrents

Copy link
Copy Markdown
Member

This is brilliant @ysitu! I'll look at it more closely and benchmark your very nice implementation of the two-phase method in connectivity and cut functions (I might not have time until the weekend). In general, I think that this is the correct approach to provide an interface to flow algorithms, but as discussed in #1096 we still have to figure out all the details. However I think this can be merged as soon as we figure out the refactoring error. It will be easier to play with different interfaces to max_flow and friends with this in master. Tanks for this PR, and for your work @ysitu, in a matter of days you've contributed a ton of high quality code. Keep up the good work!

Regarding the error that you get refactoring, I think that you need to form utils import * instead of the full from networkx.algorithms.flow.utils import *.

Salut!

@ysitu

ysitu commented Apr 8, 2014

Copy link
Copy Markdown
Contributor Author

@jtorrents With from utils import * it says ImportError: No module named 'utils'. from .utils import * produces the same error as before.

@jtorrents

Copy link
Copy Markdown
Member

Mmmm, you are right. I said that without actually testing it. I just tested It and it is indeed quite strange, maybe @chebee7i or @dschult can take a look and help us figure out what is going on here.

@jtorrents

Copy link
Copy Markdown
Member

Ok, I think I've got it. The problem seems to be with naming the new file utils.py, if you change its name to flow_utils.py or whatever, it works (I've also had to add __all__ to flow_utils.py). I didn't know that we could have this kind of name collision.

@ysitu

ysitu commented Apr 8, 2014

Copy link
Copy Markdown
Contributor Author

You are right. It is leaked from nx.algorithms.flow and conflicts with nx.utils. Another possible fix is to do del utils in __init__.py.

@chebee7i

chebee7i commented Apr 9, 2014

Copy link
Copy Markdown
Member

The other common fix is to use an __all__ inside networkx/algorithms/flow/__init__.py. One problem with deleting utils is that everything in utils.py is no longer accessible (manually importing it again doesn't work either). Presumably, no one will need those functions, but who knows.

It's quite a bit more boilerplate though: http://codepad.org/7oTfU82b
Note that there is a possible function/module name conflict with preflow_push.

@jtorrents

Copy link
Copy Markdown
Member

Thanks for looking at this Chris. @ysitu solution looks good to me. I think this is ready for merging. Chris, do you agree?

@chebee7i

chebee7i commented Apr 9, 2014

Copy link
Copy Markdown
Member

Let's do it!

@hagberg hagberg added this to the networkx-1.9 milestone Apr 9, 2014
@hagberg hagberg self-assigned this Apr 9, 2014
hagberg added a commit that referenced this pull request Apr 9, 2014
Add shortest augmenting path maximum flow algorithm
@hagberg
hagberg merged commit 88cbed6 into networkx:master Apr 9, 2014
@ysitu
ysitu deleted the sap branch April 9, 2014 20:31
jtorrents added a commit to jtorrents/networkx that referenced this pull request Apr 12, 2014
This refactoring follows from the discussion at networkx#1096 and networkx#1095. It is fully backwards compatible. The main changes are:

1. Rename max_flow and min_cut to maximum_flow and minimum_cut to be consistent with NetworkX naming convention. The short names can still be used (eg nx.max_flow(...)) but are not in the documentation.

2. maximum_flow and minimum_cut accept a new parameter flow_func for the function that will perform the computation. A default_flow_func is set, which is preflow_push_value, based on the benckmarks by @ysitu at networkx#1099.

3. The legacy implementation of ford_fulkerson and firends is separated in its own file and refactored for it to follow the new conventions in the function names, the implementation is the same.

4. Added a new function that return the residual network for each algorithm implementation. Also added docstrings explaining the conventions used in the residual network.

4. Refactored tests. Now it is easy to add a new maximum flow algorithm for testing. They take maybe a bit too long, but now we test all flow related functions.

5. The functions <algo_name>_{value|flow|residual} are not imported to NetworkX base namespace, it is necessary now to explicitly import them from networkx.algorithms.flow, the exception is ford_fulkerson_flow for backwards compatibility.

6. The maximum flow related functions imported in networkx namespace are: maximum_flow, minimum_cut, ford_fulkerson, preflow_push, shortest_augmenting_path. For convenience max_flow and min_cut are also imported. And for backwards compatibility: ford_fulkerson_flow and ford_fulkerson_flow_and_auxiliary.
jtorrents added a commit to jtorrents/networkx that referenced this pull request Apr 18, 2014
This refactoring follows from the discussion at networkx#1096 and networkx#1095. It is fully backwards compatible. The main changes are:

1. Rename max_flow and min_cut to maximum_flow and minimum_cut to be consistent with NetworkX naming convention. The short names can still be used (eg nx.max_flow(...)) but are not in the documentation.

2. maximum_flow and minimum_cut accept a new parameter flow_func for the function that will perform the computation. A default_flow_func is set, which is preflow_push_value, based on the benckmarks by @ysitu at networkx#1099.

3. The legacy implementation of ford_fulkerson and firends is separated in its own file and refactored for it to follow the new conventions in the function names, the implementation is the same.

4. Added a new function that return the residual network for each algorithm implementation. Also added docstrings explaining the conventions used in the residual network.

4. Refactored tests. Now it is easy to add a new maximum flow algorithm for testing. They take maybe a bit too long, but now we test all flow related functions.

5. The functions <algo_name>_{value|flow|residual} are not imported to NetworkX base namespace, it is necessary now to explicitly import them from networkx.algorithms.flow, the exception is ford_fulkerson_flow for backwards compatibility.

6. The maximum flow related functions imported in networkx namespace are: maximum_flow, minimum_cut, ford_fulkerson, preflow_push, shortest_augmenting_path. For convenience max_flow and min_cut are also imported. And for backwards compatibility: ford_fulkerson_flow and ford_fulkerson_flow_and_auxiliary.
@ysitu ysitu added the 1.9 label May 13, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

4 participants