Skip to content

[ENH] Flow algorithms: Add support for callable capacity parameter - #8406

Merged
dschult merged 14 commits into
networkx:mainfrom
gulshan-123:flow/callable_capacity
Jan 2, 2026
Merged

dschult merged 14 commits into
networkx:mainfrom
gulshan-123:flow/callable_capacity

Conversation

@gulshan-123

@gulshan-123 gulshan-123 commented Dec 19, 2025 •

Copy link
Copy Markdown
Contributor

Fix: #8390

Similar to shortest path algorithms, flow algorithms can now accept a callable capacity function.

_capacity_function is similar to _weight_function of shortest path algorithms, except: Since build_residual_network is not supported for Multigraphs, I have removed that portion.


will update docs and add test after the initial reviews.

@dschult dschult left a comment

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.

The doc_strings of the function need to change the description of the capacity argument. Take a look at how the doc_strings for e.g. shortest_path word it for the weight argument. Do something similar here.

Also where the function processor is defined can be more clear (see below).
Finally, I think there are a couple of typos like eedge and capcity

Thanks for this!

Comment thread networkx/algorithms/flow/utils.py Resolved
@gulshan-123

gulshan-123 commented Dec 20, 2025 •

Copy link
Copy Markdown
Contributor Author

Thank you for the review.

I have now updated the docstrings related to capacity in all maxflow algorithms. These are aligned with the weight docstrings used in the shortest path algorithms. I have also added tests for callable capacity functions.


doctest
However, the dispatch tests are currently failing. In CI, the following error is observed:

u = 0, v = 1
e_attr = {<function TestMaxflowMinCutCommon.test_capacity_func.<locals>.my_cap at 0x7fef0810f240>: inf}

    def my_cap(u, v, e_attr):
>       return 1 / e_attr["capacity"]
                   ^^^^^^^^^^^^^^^^^^
E       KeyError: 'capacity'

Here, the function my_cap is being inserted into the edge attribute dictionary. This appears to be because the backend is assuming the callable is a string key, and therefore default constructing the attribute value as inf. This likely originates from the decorator:

@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True)

used in build_residual_network().

I was able to reproduce this locally using the same command as in CI:

NETWORKX_TEST_BACKEND=nx_loopback pytest networkx/algorithms/flow/tests/test_maxflow.py

I then did this inside the core algorithm: capacity=_capacity_function(G, capacity) in boykov_kolmogorov, (from some motivation from shortest path algorithms ) so that the backend can clearly distinguish that capacity is not a string.

With this change, a different error occurs:

Details
networkx/utils/decorators.py:784: in func
    return argmap._lazy_compile(__wrapper)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<class 'networkx.utils.decorators.argmap'> compilation 8:3: in argmap_boykov_kolmogorov_5
    ???
networkx/utils/backends.py:633: in _call_if_any_backends_installed
    return self._convert_and_call_for_tests(
networkx/utils/backends.py:1878: in _convert_and_call_for_tests
    G = self.orig_func(*args_nx, **kwargs_nx)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
networkx/algorithms/flow/boykovkolmogorov.py:166: in boykov_kolmogorov
    R = boykov_kolmogorov_impl(G, s, t, capacity, residual, cutoff)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
networkx/algorithms/flow/boykovkolmogorov.py:181: in boykov_kolmogorov_impl
    R = build_residual_network(G, capacity)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<class 'networkx.utils.decorators.argmap'> compilation 12:3: in argmap_build_residual_network_9
    ???
networkx/utils/backends.py:633: in _call_if_any_backends_installed
    return self._convert_and_call_for_tests(
networkx/utils/backends.py:1879: in _convert_and_call_for_tests
    assert_graphs_equal(G, converted_result)
    
  def assert_graphs_equal(G1, G2, strict=True):
        assert G1.number_of_nodes() == G2.number_of_nodes()
        assert G1.number_of_edges() == G2.number_of_edges()
        assert G1.is_directed() is G2.is_directed()
        assert G1.is_multigraph() is G2.is_multigraph()
        print("G1:",G1._adj)
        print("G2:",G2._adj)
        if strict:
>           assert G1.graph == G2.graph
                   ^^^^^^^^^^^^^^^^^^^^
E           AssertionError
This results in an assertion failure: assert G1.graph == G2.graph
G1 = <networkx.classes.digraph.DiGraph object at 0x7560505b4510>
G2 = <networkx.classes.digraph.DiGraph object at 0x75604ff34050>
----------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------
G1: {1: {2: {'capacity': 1.0}}, 2: {1: {'capacity': 1.0}}}
G2: {1: {2: {'capacity': 1}},   2: {1: {'capacity': 1}}}

G1.graph: {'inf': 3.0}
G2.graph: {'inf': 1}
    `G2 = backend.convert_to_nx(G1)`

The graph attributes are not being copied and thus default value is being constructed for 'inf'. This originates from the default behavior described in backends.rst:

- edge_attrs : dict, optional
  Dictionary mapping edge attributes to default values if missing in G.
  If None, then no edge attributes will be converted and default may be 1.

I don't know if I am in right direction to solve the test failure.. But I did enjoy debugging..

@dschult dschult added the floating-point Issues that ultimate stem from numerical precision label Dec 20, 2025

@dschult dschult left a comment

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.

The dispatch CI test shows that dispatching is not treating this well.
It looks like your first step in fixing it ended up changing the original graph's data attributes. That is the second error you found -- the backend testing machinery found that the graph itself had been changed.

I haven't chased that down completely. Changing the attr dict will update the original graph. But I don't see where that might be happening.

But I have a suggestion below for one section of the code to keep it in a list comprehension. Not sure if that will help with these errors. I'll come back to this later.
:/

Comment thread networkx/algorithms/flow/utils.py Resolved
@gulshan-123

gulshan-123 commented Dec 21, 2025 •

Copy link
Copy Markdown
Contributor Author

I have looked more into this, and I could find the fix!

It looks like @nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True): edge_attrs corresponds to the function parameter which must be present in the modified graph, but when passing capacity as a callable, it looks if that attribute (which is callable) is present inside the original graph or not, it could not find it, and thus construct it by default as inf. This corresponds to above (e_attr containing mapping of my_cap to inf).

u = 0, v = 1
e_attr = {<function TestMaxflowMinCutCommon.test_capacity_func.<locals>.my_cap at 0x7fef0810f240>: inf}

The fix is to preserve all the edge attribute by adding preserve_edge_attribute=True in
@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True, preserve_edge_attrs=True).
This is required in all the modified function in this PR. I have tested it locally by adding and it passed the pytest as well dispatch.

But in shortest path algorithms, preserve_edge_attrs=True is not required. Is it because those functions dont have return_graph=True ?

@dschult, is the above fix reasonable and correct? If yes, I will push the new changes.

EDIT: I have pushed the changes. The circleci test looks unrelated to this PR.

@gulshan-123

Copy link
Copy Markdown
Contributor Author

I have given some more time on why preserve_edge_attr=True is not needed in shortest_path_algorithms, and now could spot an issue in networkx/utils/backends.py

See line 1202-1236 in it:

if edge_attrs is None:
# May have been set to None above b/c all attributes are preserved
pass
elif isinstance(edge_attrs, str):
if edge_attrs[0] == "[":
# e.g. `edge_attrs="[edge_attributes]"` (argument of list of attributes)
# e.g. `func(edge_attributes=["foo", "bar"])`
edge_attrs = {
edge_attr: 1 for edge_attr in bound.arguments[edge_attrs[1:-1]]
}
elif callable(bound.arguments[edge_attrs]):
# e.g. `edge_attrs="weight"` and `func(weight=myfunc)`
preserve_edge_attrs = True
edge_attrs = None
elif bound.arguments[edge_attrs] is not None:
# e.g. `edge_attrs="weight"` and `func(weight="foo")` (default of 1)
edge_attrs = {bound.arguments[edge_attrs]: 1}
elif self.name == "to_numpy_array" and hasattr(
bound.arguments["dtype"], "names"
):
# Custom handling: attributes may be obtained from `dtype`
edge_attrs = {
edge_attr: 1 for edge_attr in bound.arguments["dtype"].names
}
else:
# e.g. `edge_attrs="weight"` and `func(weight=None)`
edge_attrs = None
else:
# e.g. `edge_attrs={"attr": "default"}` and `func(attr="foo", default=7)`
# e.g. `edge_attrs={"attr": 0}` and `func(attr="foo")`
edge_attrs = {
edge_attr: bound.arguments.get(val, 1) if isinstance(val, str) else val
for key, val in edge_attrs.items()
if (edge_attr := bound.arguments[key]) is not None
}

In shortest path algos, we dispatch like:

@nx._dispatchable(edge_attrs="weight")
def dijkstra_path(G, source, target, weight="weight"):
"""Returns the shortest weighted path from source to target in G.

Here edge_attr="weight", it will go inside L1205 condition. Within this block there are separate handling of callable (see L-1212) whereas string (L-1216). We may notice that if weight is callable, the backend itself set preserve_edge_attrs=True, thus there is no need to do it inside dispatchable decorator.

But in our flow algorithms, we are dispatching like:

@nx._dispatchable(graphs="flowG", edge_attrs={"capacity": float("inf")})
def maximum_flow(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
"""Find a maximum single-commodity flow.
.
Here edge_attr is a dictionary, with key as parameter name and mapping as default.
Thus, it will go inside else condition of L-1229. But here we are not taking care of whether parameter will be callable or string, etc.

I have verified that if I set edge_attr="capacity", instead of current dictionary, all the dispatch test passes, without preserve_edge_attr=True.


Thus, there are two directions:

  • We may also make the else case (L-1229) to handle separately for callable, string, etc
  • We may manually pass preserve_edge_attr=True

@dschult

dschult commented Dec 22, 2025

Copy link
Copy Markdown
Member

Thanks for tracking this down!!

I'll ask @eriknw to comment if he has time. My guess is to keep the default specification and use preserve_edge_attr, but I haven't thought carefully about the implications.

Comment thread networkx/algorithms/flow/utils.py Resolved
Comment thread networkx/algorithms/flow/utils.py Resolved
Comment thread networkx/algorithms/flow/utils.py Resolved

@dschult dschult left a comment

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.

This looks good to me!
Thanks @gulshan-123 !!
:)

@dschult
dschult merged commit 0080011 into networkx:main Jan 2, 2026
@dschult dschult added this to the 3.7 milestone Jan 2, 2026
@dschult

dschult commented Jan 8, 2026

Copy link
Copy Markdown
Member

It looks like we will need a more thorough pass through the flow folder to ensure that all uses of an edge attribute "capacity" will actually use the function.. For example, in "utils.py" the bounded calculations look up capacity values by assuming they are attributes in the edge datadict. We need to update these -- and look for more occurences of edge capacity lookup broadly.

@gulshan-123

gulshan-123 commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor Author

I’ve done a pass of the flow directory. It appears that most capacity lookups are performed on the residual graph R, rather than G.

As in _build_residual_graph, we explicitly construct R and assign the "capacity" attribute ourselves:

R = nx.DiGraph()
# ...
R[u][v]["capacity"] = r

in the detect_unboundedness function in utils.py:

def detect_unboundedness(R, s, t):
...
    for v, attr in R[u].items():
        if attr["capacity"] == inf and v not in seen:
...

Since detect_unboundedness operates on the residual graph R, I believe it doesn't need to use the capacity function.

I will perform one more scan of the flow directory to ensure no direct lookups are happening on the original input graph G.

@dschult

dschult commented Jan 8, 2026

Copy link
Copy Markdown
Member

I should have made a link to the follow-up PR and discussion that seems to be causing troubles.

Maybe the Residual Graph is being built somehow such that it doesn't use the capacity function. The symptom reported is that an UnBoundedError is occuring when it shouldn't. I jumped to the conclusion that the capacities were not being built into the bound correctly. But maybe something more is going on.

@rossbar

rossbar commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Going through these issues - I'm wondering if this shouldn't be a target for reverting before release? #8402 ended up being closed but AFAICT that was a real regression? WDYT @dschult @amcandio ?

@amcandio

Copy link
Copy Markdown
Contributor

Not sure I follow. The ticket you mention as a regression is a documentation PR. Did you mean another issue?

@dschult

dschult commented Jul 14, 2026

Copy link
Copy Markdown
Member

I'm not sure it is a regression. After #8406 we can use a function in place of an attribute name in the capacity kwarg of maximum_flow. The PR #8402 was created to show people how to use that feature to solve floating point troubles.

Certainly it was unfortunate that #8402 was closed by the author. I think it will be straight-forward to accomplish the same goal. I put that together in #8761 We can move this discussion there I guess.

@rossbar

rossbar commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

My mistake - too many open tabs 🙃 . So no issues here: +1 for reviving the docs over in #8761 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

floating-point Issues that ultimate stem from numerical precision type: Enhancements

Development

Successfully merging this pull request may close these issues.

ENH: Add support for callables to capacity attributes in flow algorithms

4 participants