Repository navigation
Add shortest augmenting path maximum flow algorithm - #1099
Conversation
|
I need help with refactoring. There are several auxiliary classes and functions in prefixed with underscores in |
|
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? |
>>> 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 |
|
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 Regarding the error that you get refactoring, I think that you need to Salut! |
|
@jtorrents With |
|
Ok, I think I've got it. The problem seems to be with naming the new file |
|
You are right. It is leaked from |
|
The other common fix is to use an It's quite a bit more boilerplate though: http://codepad.org/7oTfU82b |
|
Thanks for looking at this Chris. @ysitu solution looks good to me. I think this is ready for merging. Chris, do you agree? |
|
Let's do it! |
Add shortest augmenting path maximum flow algorithm
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.
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.
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.
ford_fulkersonshortest_augmenting_pathpreflow_push3000 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.
ford_fulkersonshortest_augmenting_pathpreflow_pushReference