Skip to content

Refactor flow package. - #1102

Merged
hagberg merged 40 commits into
networkx:masterfrom
jtorrents:refactor-flow
Apr 28, 2014
Merged

hagberg merged 40 commits into
networkx:masterfrom
jtorrents:refactor-flow

Conversation

@jtorrents

Copy link
Copy Markdown
Member

This refactoring follows from the discussion at #1096 and #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 Add shortest augmenting path maximum flow algorithm #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.
  5. 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.
  6. 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.
  7. 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.

Comment thread networkx/algorithms/__init__.py Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it would be okay to remove the backwards compatibility imports. It's a very simple change for people to make in their code, should they choose to upgrade to the latest NetworkX---which I'm guessing could be 2.0.

@ysitu

ysitu commented Apr 13, 2014

Copy link
Copy Markdown
Contributor

@jtorrents I am thinking that perhaps I will not make a separate PR for my edmonds_karp branch. You can merge it into this Issue directly.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The compute_flow parameter of preflow_push_impl should be exposed. Some problems (e.g., the closure problem) need only maximum preflows.

Docstring for compute_flow:

compute_flow : bool
    If True, compute a maximum flow; otherwise, compute a maximum preflow. Default
    value: True.

@jtorrents

Copy link
Copy Markdown
Member Author

A loop does make the code cleaner, but if the assertion fails, you cannot tell which function produced the wrong result. This applies to all other loops below.

@ysitu, that's true. I'm thinking that maybe we can use the msg parameter of assert_* to deal with that. I'll give it a try. I think that I've addressed all your other comments. Thanks for looking at this, and for the nice implementation of edmonds_karp!

@jtorrents

Copy link
Copy Markdown
Member Author

I wonder if it would be okay to remove the backwards compatibility imports. It's a very simple change for people to make in their code, should they choose to upgrade to the latest NetworkX---which I'm guessing could be 2.0.

@chebee7i I also think that we could be a bit flexible with backwards compatibility here. Perhaps we can remove definitively ford_fulkerson_flow_and_auxiliary (it was added in 1.7 along with the connectivity package, that's about ~1.5 years ago), I think that it's not widely used but of course we might be breaking someone's else code. However, there will not be better moment than this refactoring for getting rid of ford_fulkerson_flow_and_auxiliary before 2.0. We could also not import ford_fulkerson_flow to NetworkX base namespace, this is not a big change. However I would keep max_flow and min_cut. What do you think guys?

@ysitu

ysitu commented Apr 13, 2014

Copy link
Copy Markdown
Contributor

Thanks for bringing in my commits. I have pushed two more follow-up commits. Please also bring them in.

I think that the public API can be made more compact. maximum_flow/minimum_cut should be the unified entry points to all the different algorithms. The _value and _flow functions are not needed. Only the _residual functions are used. In fact, the _residual suffix can be dropped if the _value and _flow simply functions are removed. The user specifies the maxflow function as an argument to maximum_flow, then maximum_flow calls it to get a residual network from which the return valued is extracted.

maximum_flow/minimum_cut should have the ability to return the actual maximum flow/minimum cut in addition to the maximum flow value. Because some algorithms (e.g., preflow-push, pseudoflow) can terminate early if a maximum flow is not needed, maximum_flow/minimum_cut should inform them of the choice. The algorithms may have other options which should also be forwarded. I suggest standardizing compute_flow from preflow_push (maybe choose more explanatory name) and cutoff (to be implemented), which all maxflow algorithms should recognize, and adding **kwargs to maximum_flow/minimum_cut to forward the algorithm-specific options.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"(default 'capacity')" is not needed.

@jtorrents

Copy link
Copy Markdown
Member Author

Thanks for bringing in my commits. I have pushed two more follow-up commits. Please also bring them in.

Done! I hope that the history of this PR is not too messy for merging it. What do you think @chebee7i?

I think that the public API can be made more compact. maximum_flow/minimum_cut should be the unified entry points to all the different algorithms. The _value and _flow functions are not needed. Only the _residual functions are used. In fact, the _residual suffix can be dropped if the _value and _flow simply functions are removed. The user specifies the maxflow function as an argument to maximum_flow, then maximum_flow calls it to get a residual network from which the return valued is extracted.

maximum_flow/minimum_cut should have the ability to return the actual maximum flow/minimum cut in addition to the maximum flow value. Because some algorithms (e.g., preflow-push, pseudoflow) can terminate early if a maximum flow is not needed, maximum_flow/minimum_cut should inform them of the choice. The algorithms may have other options which should also be forwarded. I suggest standardizing compute_flow from preflow_push (maybe choose more explanatory name) and cutoff (to be implemented), which all maxflow algorithms should recognize, and adding **kwargs to maximum_flow/minimum_cut to forward the algorithm-specific options.

That's interesting. I also have the feeling that having separated {residual|flow|value} functions is a bit too much redundancy. And I like the idea of only using residual networks internally. However, this will not be backwards compatible; until now ford_fulkerson returned a tuple (flow_value, flow_dict), and according to your proposal it should return the residual network. However I think your proposal is more compact and easier to understand and explain.

Regarding of what should maximum_flow/minimum_cut return. I agree that we should not restrict it only to the flow value. Note that, with the code in this PR (without your proposed changes), it is already possible to pass any flow functions to maximum_flow, thus the functions that you pass to it defines what it returns:

In [24]: import networkx as nx
In [25]: from networkx.algorithms import flow
In [26]: G = nx.Graph()
In [27]: G.add_path([1,2,3,4], capacity=1)
In [28]: nx.maximum_flow(G, 1, 4)
Out[28]: 1
In [29]: nx.maximum_flow(G, 1, 4, flow_func=flow.shortest_augmenting_path_flow)
Out[29]: {1: {2: 1}, 2: {1: 0, 3: 1}, 3: {2: 0, 4: 1}, 4: {3: 0}}
In [30]: nx.maximum_flow(G, 1, 4, flow_func=nx.ford_fulkerson)
Out[30]: (1, {1: {2: 1}, 2: {1: 1, 3: 1}, 3: {2: 1, 4: 1}, 4: {3: 1}})

This is not documented, and the docstrings refer only to the flow_value. Moreover, it might be a bit confusing for the users, especially if they use minimum_cut and one of the flow functions imported in the base NetworkX namespace. They will get the value of the cut and the flow dict, which I guess is not what they would expect.

Regarding the options, I think that is better to change the name to compute_flows, but not sure which one would be better, what about preflow_only or just preflow? Finally, regarding **kwargs, if all algorithms should tolerate and ignore all options that do not apply to them, I think that is necessary to add **kwargs all the way down from maximum_flow to algo_name_impl, is that right?

The more I think about it, the more I like your proposal, but it might have to wait until 2.0 if we are to maintain backwards compatibility with how ford_fulkerson and friends worked until now. Let's see what others think.

@jtorrents

Copy link
Copy Markdown
Member Author

Regarding the use of for loops in maximum flow tests, the last commit adds a custom message to assert_* for keeping track of which flow function failed. However, this does not work for assert_raises (as far as I can tell, there is no msg parameter) and thus in this case we are not able to see which function failed in the traceback.

@ysitu

ysitu commented Apr 14, 2014

Copy link
Copy Markdown
Contributor

Can ford_fulkerson be special-cased out right in maximum_flow? Something like

if flow_func is nx.ford_fulkerson:
    return ford_fulkerson_specific_code()

This is will make removing it very easy in 2.0.

@ysitu

ysitu commented Apr 14, 2014

Copy link
Copy Markdown
Contributor

On second thought, maybe it is better that the old max_flow and min_cut are left untouched with the old behavior and uses only ford_fulkerson. If the user wants to use the other algorithms, he/she needs to use the new maximum_flow and minimum_cut. The old-new separation avoids the backward compatibility problem as what has been working continues to work. Then max_flow, min_cut and ford_fulkerson can be declared deprecated in 1.9, which paves the way for removal in 2.0, when ford_fulkerson can perhaps be aliased to edmonds_karp.

@ysitu

ysitu commented Apr 14, 2014

Copy link
Copy Markdown
Contributor

Regarding a better name from compute_flow, how about min_cut_only? Preflows only make sense in the context of preflow-push algorithms, but minimum cuts also apply to augmenting path algorithms. Conceptually, each maximum flow algorithm can be divided into two phases. Phase 1 computes a minimum cut (or whatever equivalent, such as a maximum preflow). Phase 2 computes a maximum flow. In augmenting path algorithms, phase 1 just happens to do enough that phase 2 is a no-op.

The precise semantics of min_cut_only also needs to be defined. I think that when min_cut_only == True, maximum_flow/minimum_cut should assume nothing beyond that the returned residual network R induces a minimum cut by reachability from s and to t and that R.node[t]['excess'] gives the maximum flow/minimum cut value.

I believe that implementations of the algorithms do not need the **kwargs parameter themselves. All algorithms should recognize the standardized min_cut_only (or whatever name that is) and cutoff. If flow_func is None, maximum_flow/minimum_cut should enforce that kwargs be empty and raise an exception if not. This forces the user to explicitly specify the algorithm to use when he/she wants to pass in algorithm-specific options. It allows the call to the algorithm to be syntax-checked by the language. It also allows the default algorithm to be freely changed without breaking user code.

Regarding returning the flow/cut value vs the flow/cut itself from maximum_flow and minimum_cut, although I am not opposed to it, I can imagine that some will feel uncomfortable that the same function returns stuff of different types depending on the input. Does changing maximum_flow and minimum_cut to return the contents of a maximum flow/minimum cut and adding maximum_flow_value and minimum_cut_value to return its value sound like a better idea?

@chebee7i

Copy link
Copy Markdown
Member

To the issue of messiness: design is hard, and redesign is very rarely a pretty process. So the messiness of the PR isn't an issue to me. There have been far simpler pull requests (some by me) which have been hard to follow as well. :)

I think the main focus here should be on good design, with backwards compatibility issues being an after-thought. That's not to say that backwards compatibility isn't important...it just tends to influence the design. Once a happy design is found, we can always create a separate pull request which adds a compatibility layer back in.

jtorrents added a commit to jtorrents/networkx that referenced this pull request Apr 18, 2014
This implements most of ysitu's proposal (see networkx#1102) on the inetrfaces of flow algorithms. It is still backwards compatible. The main changes are:

1. Removed all {residual|value|flow} functions for the new algorithms. Each algorithm exposes only a function named `algorithm_name` that returns the residual network after computing the maximum flow. Internally we use residual networks everywhere. This simplifies code and tests.

2. Added a new parameter `legacy` to `ford_fulkerson` (default True). If it's True it returns a tuple (flow_value, flow_dict) as it used to do. If `legacy` is False then it returns the residual network, with the flow_value and the flow_dict as graph attributes. Thus we can use it internally (tests, other functions) in more or less the same way that we use the new algorithms. Expanded docstrings explaining all this. The functions `ford_fulkerson_value` and `ford_fulkerson_residual` introduced in the first refactoring are removed. The functions `ford_fulkerson_flow` and `ford_fulkerson_flow_and_auxiliary` are kept here for backwards compatibility, but I'll remove them in a separated commit.

3. I named the parameter `value_only` (ysitu proposed `min_cut_only`) and changed a bit the semantics. It defines what the functions `maximum_flow` and `minimum_cut` return. If True they return the maximum flow value, otherwise they return the actual flow or the set of edges that form the minimum cut. All algorithms recognize this parameter, for the ones in which it's not applicable they just ignore it.

4. The `maximum_flow` and `minimum_cut` functions deal now with `ford_fulkerson` as especial case. They also accept `**kwargs` and pass them to the function implementing the computation. This still needs work and do some checks on the sanity of the arguments passed to flow algorothms.

5. We import everything again from the flow package, without the {residual|value|flow} functions there is no need to keep stuff only to the flow package.

6. I've just adapted the old tests, more tests needed for testing the interface and new features of maximum_flow and minimum_cut. Now tests take less time because we are not testing redundant {residual|value|flow} functions.

7. `max_flow` and `min_cut` are alias for `maximum_flow` and `minimum_cut`. I think it's not a good idea to have them behave different, it could be a source of confusion.
@jtorrents

Copy link
Copy Markdown
Member Author

Sorry for being slow on this, I'm quite busy this days. After playing a bit with ysitu proposal, I think that it is quite nice and the way to go for the interfaces of flow algorithms. The commit above implements most of ysitu's proposal with some changes. It is still backwards compatible. The main changes are:

  1. Removed all {residual|value|flow} functions for the new algorithms. Each algorithm exposes only a function named algorithm_name that returns the residual network after computing the maximum flow. Internally we use residual networks everywhere. This simplifies code and tests.
  2. Added a new parameter legacy to ford_fulkerson (default True). If it's True it returns a tuple (flow_value, flow_dict) as it used to do. If legacy is False then it returns the residual network, with the flow_value and the flow_dict as graph attributes. Thus we can use it internally (tests, other functions) in more or less the same way that we use the new algorithms. Expanded docstrings explaining all this. The functions ford_fulkerson_value and ford_fulkerson_residual introduced in the first refactoring are removed. The functions ford_fulkerson_flow and ford_fulkerson_flow_and_auxiliary are kept here for backwards compatibility, but I'll remove them in a separated commit.
  3. I named the parameter value_only (ysitu proposed min_cut_only) and changed a bit the semantics. It defines what the functions maximum_flow and minimum_cut return. If True they return the maximum flow value, otherwise they return the actual flow or the set of edges that form the minimum cut. All algorithms recognize this parameter, for the ones in which it's not applicable they just ignore it.
  4. The maximum_flow and minimum_cut functions deal now with ford_fulkerson as especial case. They also accept **kwargs and pass them to the function implementing the computation. This still needs work and do some checks on the sanity of the arguments passed to flow algorothms.
  5. We import everything again from the flow package, without the {residual|value|flow} functions there is no need to keep stuff only to the flow package.
  6. I've just adapted the old tests, more tests needed for testing the interface and new features of maximum_flow and minimum_cut. Now tests take less time because we are not testing redundant {residual|value|flow} functions.
  7. max_flow and min_cut are alias for maximum_flow and minimum_cut. I think it's not a good idea to have them behave different, it could be a source of confusion.

@ysitu

ysitu commented Apr 18, 2014

Copy link
Copy Markdown
Contributor

If you use functools.partial, please ensure that the documentation does not contain the same problem as #1110.

@jtorrents

Copy link
Copy Markdown
Member Author

2014-04-18 17:24 GMT+02:00 ysitu [email protected]:

If you use functools.partial, please ensure that the documentation does
not contain the same problem as #1110#1110

I think functools.partial is only used in tests here, thus it does not
affect documentation.

@ysitu

ysitu commented Apr 18, 2014

Copy link
Copy Markdown
Contributor

I think that minimum_cut should return a node partition rather than a cut set. The argument is same as in #1094—it is much easier to produce a cut set from a node partition than the other way round.

@jtorrents

Copy link
Copy Markdown
Member Author

I think that minimum_cut should return a node partition rather than a cut set. The argument is same as in #1094—it is much easier to produce a cut set from a node partition than the other way round.

Ok, sounds good. Besides, we already have functions in the connectivity package that return the cut set (minimum_edge_cut and friends). I'll put in the documentation, as an example, how to get the cut set from the node partition.

I'm working on refactoring a bit the tests and removing flord_fulkerson_flow_and_auxiliary.

@jtorrents

Copy link
Copy Markdown
Member Author

Regarding removing the functions ford_fulkerson_flow and ford_fulkerson_flow_and_auxiliary, I've tested it, and it certainly breaks my code (not in NetworkX, where it also breaks the connectivity package, but it's easy to fix and needs refactoring anyway). So I'm a bit hesitant to remove them at this point. In any case, more work is needed after this is merged (adding a cutoff parameter, ...), so we can keep improving the interface, the documentation and the tests; and decide if we keep or remove them when we are done.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"is not aplicable"

Add option to reuse residual networks in maxflow algorithms
@jtorrents

Copy link
Copy Markdown
Member Author

Done. I am not adding new tests to networkx.algorithms.flow. I suppose that the tests in networkx.algorithms.connectivity will cover the scenario.

Great! I'll write some more tests for the flow package, (maxflow.py still needs to improve coverage of the _value functions) and will also test reuse of the residual network. In the connectivity package this will also be covered.

Since only flow and excess needs to be reset, inlining it looks more concise.

preflow_push still checks for unboundedness up front, shortest_augmenting_path and edmonds_karp bake the check into flow augmentation. That required a small change in how inf is defined.

Looking at the change in inf I think that this will also be faster.

I thought about this when implementing preflow_push. The reason against it is that float('inf') - 10 ** 1000 throws, and I do not want to check for infinity every time I calculate the residual capacity of an edge.

Oh I see. Checking every time is quite ugly.

I want to remove edmonds_karp. This thing is popular only because 1) it is simplest; 2) the CLRS book covers it.

No please! in my benchmarks with connectivity algorithms (still without using cutoff and without your last changes) edmonds_karp is faster than SAP, very close to the legacy ford_fulkerson even building the residual network for each pair of nodes. I'll update the connectivity algorithms to use your last changes, I'll post benchmarks shortly.

Since the residual network is the same for every pair of nodes, delegate
sanity checks on source and sink to algorithm implementations. This makes
build_residual_network easier to use in the connectivity package, and in
general.
This solution is not very nice but works.
@jtorrents

Copy link
Copy Markdown
Member Author

The commits above implement these changes:

  1. Do not require source and sink to build a residual network. Since the residual network is the same for every pair of nodes, delegate
    sanity checks on source and sink to algorithm implementations. This makes
    build_residual_network easier to use in the connectivity package, and in
    general.
  2. Added tests for all interface functions and a test for reusing the residual network. This pointed a problem with how minimum_cut computes the node partition: it removes the cutset and computes single target shortest path to target. In the fix I just re-added the cutset afterwards as a quick fix (I'm working in the connectivity stuff), but this solution is not nice. @ysitu, you said in Better shortest paths for Multigraphs... #1120 that you find unnatural to use shortest paths for reachability, what do you think it would be the best solution?
  3. I still have to work more on the connectivity algorithms and benchmarks, but now the new algorithms beat by far in speed the legacy implementation! Very good work @ysitu!

@ysitu

ysitu commented Apr 26, 2014

Copy link
Copy Markdown
Contributor

Your trouble with minimum_cut is yet another instance of #762 despite a different algorithmic context. The fundamental fact is that the same algorithm can have many different implementations, and in some situations, they just have to be different. When you try to hammer them into the same shape, you will have to bend and twist the code elsewhere. In your case, it is the edge juggling work, which saves you the need to write a floodfill yourself in return.

There are probably no good solutions. NetworkX is geared towards static graphs. When your graph is dynamic, even in the simple case where the dynamicity originates from with the graph itself (e.g., node/edge attribute-defined topology), pretty much you need to write special code.

@jtorrents

Copy link
Copy Markdown
Member Author

Good points. I guess that we will have to wait for a better/more elegant solution until we have a working implementation of a Graph view that can be used to filter nodes and edges in graph methods.

Regarding the last changes that we did for allowing reuse of the residual network, they make a huge difference in connectivity algorithms. The code is simpler by taking advantage of the new interface to flow functions, and it is a lot faster in some scenarios (sparse networks with degree distributions skewed to the right, the kind of networks in which I'm interested).

I did some benchmarks for node and edge connectivity comparing all new algorithms and the legacy implementation. In this benchmarks, edmonds_karp and shortest_augmenting_path do not use the cutoff parameter because the other algorithms do not support it (using it they are quite faster). The examples are small because the legacy implementation (and preflow_push in some scenarios) is really slow. edmonds_karp is the faster by far, specially in sparse power law like degree distribution graphs, where it is up to one order of magnitude faster than the legacy implementation, and several times faster than shortest_augmenting_path (where the parameter two_phase does not seem to make much difference). It must be said that, in denser networks, shortest_augmenting_path beats edmonds_karp in speed, but not by much.

This benchmarks use python 2.7 in a Linux 64-bit system. pypy cuts the time by half approximately:

jtorrents@saturn:~/projects/benchmark$ python benchmark_flow.py
Name: fast_gnp_random_graph(1000,0.02)
Type: Graph
Number of nodes: 1000
Number of edges: 10071
Average degree:  20.1420
Time computing node connectivity
    edmonds_karp:   7.41 seconds
    ford_fulkerson: 89.28 seconds
    preflow_push:   49.87 seconds
    shortest_ap:    38.58 seconds
    shortest_ap_tp: 38.78 seconds
Time computing edge connectivity
    edmonds_karp:   0.62 seconds
    ford_fulkerson: 10.00 seconds
    preflow_push:   3.08 seconds
    shortest_ap:    2.15 seconds
    shortest_ap_tp: 2.18 seconds

Name: fast_gnp_random_graph(200,0.2)
Type: Graph
Number of nodes: 200
Number of edges: 3980
Average degree:  39.8000
Time computing node connectivity
    edmonds_karp:   2.49 seconds
    ford_fulkerson: 11.17 seconds
    preflow_push:   4.45 seconds
    shortest_ap:    2.97 seconds
    shortest_ap_tp: 2.98 seconds
Time computing edge connectivity
    edmonds_karp:   0.08 seconds
    ford_fulkerson: 0.44 seconds
    preflow_push:   0.13 seconds
    shortest_ap:    0.12 seconds
    shortest_ap_tp: 0.11 seconds

Name: fast_gnp_random_graph(100,0.8)
Type: Graph
Number of nodes: 100
Number of edges: 3962
Average degree:  79.2400
Time computing node connectivity
    edmonds_karp:   4.45 seconds
    ford_fulkerson: 12.85 seconds
    preflow_push:   7.08 seconds
    shortest_ap:    4.97 seconds
    shortest_ap_tp: 5.10 seconds
Time computing edge connectivity
    edmonds_karp:   0.05 seconds
    ford_fulkerson: 0.09 seconds
    preflow_push:   0.06 seconds
    shortest_ap:    0.07 seconds
    shortest_ap_tp: 0.06 seconds

Name: Power law configuration model: 1000
Type: Graph
Number of nodes: 981
Number of edges: 2329
Average degree:   4.7482
Time computing node connectivity
    edmonds_karp:   1.64 seconds
    ford_fulkerson: 21.70 seconds
    preflow_push:   17.87 seconds
    shortest_ap:    11.00 seconds
    shortest_ap_tp: 10.97 seconds
Time computing edge connectivity
    edmonds_karp:   0.43 seconds
    ford_fulkerson: 9.65 seconds
    preflow_push:   4.20 seconds
    shortest_ap:    2.29 seconds
    shortest_ap_tp: 2.27 seconds

Name: Power law configuration model: 2000
Type: Graph
Number of nodes: 1978
Number of edges: 5515
Average degree:   5.5763
Time computing node connectivity
    edmonds_karp:   9.79 seconds
    ford_fulkerson: 124.36 seconds
    preflow_push:   106.75 seconds
    shortest_ap:    74.92 seconds
    shortest_ap_tp: 76.22 seconds
Time computing edge connectivity
    edmonds_karp:   2.29 seconds
    ford_fulkerson: 51.29 seconds
    preflow_push:   24.04 seconds
    shortest_ap:    15.49 seconds
    shortest_ap_tp: 15.59 seconds

Name: Power law configuration model: 3000
Type: Graph
Number of nodes: 2951
Number of edges: 8605
Average degree:   5.8319
Time computing node connectivity
    edmonds_karp:   24.78 seconds
    ford_fulkerson: 341.65 seconds
    preflow_push:   303.78 seconds
    shortest_ap:    216.74 seconds
    shortest_ap_tp: 216.32 seconds
Time computing edge connectivity
    edmonds_karp:   6.15 seconds
    ford_fulkerson: 127.86 seconds
    preflow_push:   70.43 seconds
    shortest_ap:    46.65 seconds
    shortest_ap_tp: 46.80 seconds

jtorrents added a commit to jtorrents/networkx that referenced this pull request Apr 27, 2014
This is still work in progress. Tests updated only for connectivity and all
docstrings are the old ones. As a starting point, I've kept the flow_func
parameter (is very nice for tests) and set edmonds_karp by default. However
shortest_augmenting_path is faster in denser networks (this is a reason
for keeping the flow_func parameter in connectivity functions). We can discuss
more about the inetrface to connectivity algorithms when networkx#1102 is merged and I
can do a proper PR.

I've post some benchmarks in networkx#1102, and for some problems that I care about
I'm seeing one order of magnitude faster runtimes. Great work @ysitu!
The test for cutoff was not picking it. I've added another.
@jtorrents

Copy link
Copy Markdown
Member Author

In 6fa58b9 I've made edmonds_karp_core obey the cutoff parameter. The test for cutoff did not detect that, however I'm not sure I understand it. So I've added another (simpler) test.

With this I think this PR is almost ready for merging (do you agree @ysitu?). In ec56e7d I started the refactoring of the connectivity package using the new maximum flow interfaces and algorithms. I think that the code is clearer, and it is for sure a lot faster than the legacy implementation. For some networks that I care about, I'm seeing one order of magnitude difference in speed. Thanks a lot @ysitu for your work on this! When this is merged I'll do a proper PR from ec56e7d and we can discuss the interface to connectivity algorithms. I'd like to keep the flow_func parameter, and maybe we can keep some functions (eg local_* in connectivity and st cuts) out of the base NetworkX namespace.

@ysitu

ysitu commented Apr 27, 2014

Copy link
Copy Markdown
Contributor

It was a blunder of mine that I forgot to use cutoff in edmonds_karp. Thanks for fixing it. I have one final comment above. After that is also dealt with, this PR is good to go.

@jtorrents

Copy link
Copy Markdown
Member Author

Hmm, it seems that github ate a comment that I did last night. Anyway it was not important, I was just saying that I did the change in handling cutoff in edmonds_karp_core that @ysitu proposed.

I keep working on the refactoring of the connectivity package to use the new flow interfaces and algorithms. I'm working on a branch of my fork refactor-conn . So far I have code and tests in good shape, still working on the documentation. However I have some doubts about the interface, about how much to document (eg reuse of residual network and auxiliary digraph, ...) and would like to discuss them in a proper PR, but I'm not sure which is the best course of action:

  1. Wait until this is merged. The problem is that, given that there are a lot of changes here, we might need to give people time to take a look. And I'd like to start the discussion in parallel, if possible, because I have a quite busy May and I'd like to get as much work done as possible these last few days of April (or the few first of May).
  2. Make a PR now (that branch is a fork of this branch, so all commits related to the refactoring of flow package will appear also in that branch). Maybe we can use this for discussing, and when this is merged, then do another PR.
  3. Just push the changes of refactoring the connectivity package to this PR. I'm not sure this is wise, we already have a quite messy PR here.

Which do you think is the best approach?

@hagberg

hagberg commented Apr 28, 2014

Copy link
Copy Markdown
Member

I think this PR should be merged before it grows so large that it eats all of the other PRs...

@ysitu

ysitu commented Apr 28, 2014

Copy link
Copy Markdown
Contributor

This should be merged ASAP.

@chebee7i

Copy link
Copy Markdown
Member

The most likely situation, in my mind, is that this won't get many more eyes on it...certainly not at the level of detail that has already been put in. Are you guys (@jtorrents and @ysitu) at the point where this is ready? If so, you have my vote to merge it.

[If it passes a smell test and all the unit tests continue to pass, I lean for "merge". :) ]

hagberg added a commit that referenced this pull request Apr 28, 2014
@hagberg
hagberg merged commit ccd4dc2 into networkx:master Apr 28, 2014
@chebee7i

Copy link
Copy Markdown
Member

So ends the most-involved PR evaarrrrr....

@jtorrents

Copy link
Copy Markdown
Member Author

Yay! This has been a lot of fun! I guess that we'll see some complains for breaking backwards compatibility, but I'm sure that people will understand when they play a bit with the new interface, and we can also show them how fast are the new algorithms in some scenarios. I'll try to put together another PR with module level documentation showing the performance of flow algorithms in different contexts (we can use the benchmarks provided by @ysitu at #1099), so users can pick the one that fits their problem.

I'm preparing the pull request for the refactor of connectivity, but I'm having some problems with git. By the way, @hagberg when do you think the 1.9 release can be ready? I'd like to also include the connectivity improvements.

jtorrents added a commit to jtorrents/networkx that referenced this pull request Apr 29, 2014
Use the new algorithms and the new interfaces provided by the flow package.
The code is quite clearer, and the new algorithms and interface provide
a significant speed up in running time. For some problems, this code is one order
of magnitude faster (see networkx#1102 for bechmarks). So far the code is still
backwards compatible, but we should discuss some possible non backward
compatible improvements.
@jtorrents
jtorrents deleted the refactor-flow branch April 30, 2014 17:12
@ysitu ysitu added the 1.9 label May 13, 2014
yangpeng366 added a commit to yangpeng366/networkx that referenced this pull request Oct 30, 2026
minimum_cut has documented the partition as the set of nodes reachable from
the source in the residual network, but has computed the other side instead:
the nodes that can reach the sink, and then the complement. The two agree only
when the sink side is exactly the sink-reachable set, and they disagree
whenever a minimum cut is not adjacent to the sink. On the digraph

    35->36->37->39->40->41->46->47, capacities 2,2,2,2,1,1,1

the bottleneck is (40, 41), yet minimum_cut returns

    (1, ({35, 36, 37, 39, 40, 41, 46}, {47}))

which is a valid minimum cut -- cutting the saturated edge (46, 47) also
costs 1 -- but reports a partition unrelated to the cut. Randomized testing
over small capacitated digraphs and graphs puts the rate at which that
trivial partition is returned at around 44%.

This is the behaviour reported in networkx#5239, open since 2021.
The sink-side formulation dates back to networkx#1102; networkx#8756 reimplemented it as a
reverse breadth-first search and left the Notes describing the search
direction as running "to t", so the code and its documentation disagreed
throughout. The cut *value* has always been correct, which is why no test
caught this: what is wrong is the partition, so callers asking which nodes or
edges form the bottleneck get an answer unrelated to it.

Search forward from the source instead, over the same flow < capacity
predicate, which is what the residual network Notes describe ("Reachability
from s ... induces a minimum s-t cut"). That needs a residual network holding
a maximum *flow*: a maximum *preflow* (value_only=True) may still leave excess
on intermediate nodes, and the spare-capacity edges leaving such a node would
report a cut that is not minimum. minimum_cut therefore lets the flow
computation run to completion. On random capacitated graphs that measured
between neutral and roughly 1.25x slower for a single minimum_cut call, and
within noise for gomory_hu_tree, which makes n-1 such calls against a reused
residual.

The five residual-network Notes that described the search direction as running
"to t" -- four in maxflow.py, one in preflow_push -- are corrected to match.
They cannot be corrected on their own: at the parent commit the code, its
inline comment and the Notes all describe the sink-side search consistently,
so the wording only becomes true once the search runs from the source.
yangpeng366 added a commit to yangpeng366/networkx that referenced this pull request Nov 10, 2026
minimum_cut has documented the partition as the set of nodes reachable from
the source in the residual network, but has computed the other side instead:
the nodes that can reach the sink, and then the complement. The two agree only
when the sink side is exactly the sink-reachable set, and they disagree
whenever a minimum cut is not adjacent to the sink. On the digraph

    35->36->37->39->40->41->46->47, capacities 2,2,2,2,1,1,1

the bottleneck is (40, 41), yet minimum_cut returns

    (1, ({35, 36, 37, 39, 40, 41, 46}, {47}))

which is a valid minimum cut -- cutting the saturated edge (46, 47) also
costs 1 -- but reports a partition unrelated to the cut. Randomized testing
over small capacitated digraphs and graphs puts the rate at which that
trivial partition is returned at around 44%.

This is the behaviour reported in networkx#5239, open since 2021.
The sink-side formulation dates back to networkx#1102; networkx#8756 reimplemented it as a
reverse breadth-first search and left the Notes describing the search
direction as running "to t", so the code and its documentation disagreed
throughout. The cut *value* has always been correct, which is why no test
caught this: what is wrong is the partition, so callers asking which nodes or
edges form the bottleneck get an answer unrelated to it.

Search forward from the source instead, over the same flow < capacity
predicate, which is what the residual network Notes describe ("Reachability
from s ... induces a minimum s-t cut"). That needs a residual network holding
a maximum *flow*: a maximum *preflow* (value_only=True) may still leave excess
on intermediate nodes, and the spare-capacity edges leaving such a node would
report a cut that is not minimum. minimum_cut therefore lets the flow
computation run to completion. On random capacitated graphs that measured
between neutral and roughly 1.25x slower for a single minimum_cut call, and
within noise for gomory_hu_tree, which makes n-1 such calls against a reused
residual.

The five residual-network Notes that described the search direction as running
"to t" -- four in maxflow.py, one in preflow_push -- are corrected to match.
They cannot be corrected on their own: at the parent commit the code, its
inline comment and the Notes all describe the sink-side search consistently,
so the wording only becomes true once the search runs from the source.
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