Skip to content

Floyd Warshall: Adding support for weight parameter as a callable - #8386

Merged
MridulS merged 14 commits into
networkx:mainfrom
gulshan-123:floydW/weight_as_func
Dec 23, 2025
Merged

MridulS merged 14 commits into
networkx:mainfrom
gulshan-123:floydW/weight_as_func

Conversation

@gulshan-123

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

Copy link
Copy Markdown
Contributor

Most of the distance algorithms under shortest path accept weight to be as either a string or a callable:

def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight="weight")

     """weight : string or function, optional (default = 'weight')
        If this is a string, then edge weights will be accessed via the
        edge attribute with this key (that is, the weight of the edge
        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
        such edge attribute exists, the weight of the edge is assumed to
        be one.

        If this is a function, the weight of an edge is the value
        returned by the function. The function must accept exactly three
        positional arguments: the two endpoints of an edge and the
        dictionary of edge attributes for that edge. The function must
        return a number or None to indicate a hidden edge."""

While implementing floyd_warshall_tree, we noticed to add this feature to Floyd Warshall algorithms too, which currently takes weight only as a string.

Currently, I have made this available for floyd_warshall_tree and floyd_warshall_predecessor_and_distance.

There is one another function: floyd_warshall_numpy. But for it to support callable weight, we need to change the more general function nx.to_numpy_array, which floyd_warshall_numpy calls internally.

    A = nx.to_numpy_array(
        G, nodelist, multigraph_weight=min, weight=weight, nonedge=np.inf
    )

CC: @amcandio , @dschult


Idea and tests taken from algorithms/shortest_paths/weighted.py

tested against older tree version;
since older tree version and older fw_pred_dist were giving the same
result, testing ensures nothing has been changed in behaviour..
1. regarding weight parameter: copied from other distance func
2. in fw_pred_dist: return value needed more specification, so, taken
   from tree version
@gulshan-123

Copy link
Copy Markdown
Contributor Author

Note: earlier in some part of the docstring, there were 3 chars indentation, so I have added 4 chars indentation there along with modifying the content of docstring.

@rossbar

rossbar commented Dec 16, 2025

Copy link
Copy Markdown
Contributor

Note: earlier in some part of the docstring, there were 3 chars indentation, so I have added 4 chars indentation there along with modifying the content of docstring.

Generally it's a good idea to leave doc indentation levels as-is, at least in PRs where other things are changing. The reason being that adding a space everywhere makes it look like every single line in the docstring has changed, making review more difficult. If it's possible to back out that change (e.g. revert a specific commit) it would make the review easier!

Note also that 3 spaces are fine for docstrings: the 4-spaces indentation from PEP 8 applies only to source code (there are reasons why 3 spaces can look better with rst).

@gulshan-123

Copy link
Copy Markdown
Contributor Author

I have reverted the docs update. Will update the docs once after the review.
Now, changes are only due to test addition and source code changes.

cost = weight(u, v, e_attr)
if cost is not None: # for hidden edge, weight() returns None
dist[u][v] = cost
pred[u][v] = u

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 doesn't look like the code it is replacing.
Can you explain how this is equivalent?
The old way loops over the edges, while this loops over the neighbors.

BTW, an even cleaner way of doing that is

    for u, unbrs in G._adj.items():
        for v, e_attr in unbrs.items():

So we trade one items lookup for N dict lookups of G_succ[u].

But then I don't understand how the rest is the same. we don't compare cost with previously found costs. But if it is different, why aren't the tests catching this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

we don't compare cost with previously found costs

we need to compare cost with previously found cost in case of Multigraphs, but _weight_function already do that internally:

def _weight_function(G, weight):
    if callable(weight):
        return weight
    # If the weight keyword argument is not callable, we assume it is a
    # string representing the edge attribute containing the weight of
    # the edge.
    if G.is_multigraph():
        return lambda u, v, d: min(attr.get(weight, 1) for attr in d.values())
    return lambda u, v, data: data.get(weight, 1)

So we trade one items lookup for N dict lookups of G_succ[u]

I was thinking like this: since for each node, we are looping over only its neighbours, thus overall it will be O(Number of Edges), (since sum of outdegrees = E)

@gulshan-123 gulshan-123 Dec 17, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Can you explain how this is equivalent?

This part of the code is responsible for assigning weights and pred according to the edge and edge weights.
Thus we need to iterate over all the edges in any method.

This was done in the previous version by just iterating on G.edges(data=True)

In the current version, for each node, we are checking its neighbours (which basically makes a edge). Thus, we are in fact iterating edges but in another way.

Please correct me if I'm wrong

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.

You are correct -- the G.edges object is actually doing exactly the double loop you use here. I was more confused about looking up the minimum -- and your explanation reminds we that with G.edges we also have loop of the key_dict. Here we handle that via the weight function as you correctly describe.

Thanks!!

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.

My suggestion of

    for u, unbrs in G._adj.items():
        for v, e_attr in unbrs.items():

doesn't change the complexity of the loops -- it just avoids the lookup cost of G_succ[u].
Your code is correct and works fine -- my experience is that using items() to get G_succ[u] while iterating is faster than actually looking it up. :)

@gulshan-123

gulshan-123 commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Thank you for the review!

  • using .items() to avoid extra dict loop
  • made a helper function _init_pred_dist(G, weight) to do the initialization steps which was common in the both floyd warshall algorithms. Thanks to @amcandio.
  • One more change: earlier, dist[u][u] = 0 was being set up in a separate loop, now I've merged within the same loop as where other dist are being initialized

TODO:
Update docstring for floyd_warshall(), floyd_warshall_predecessor_and_distance, floyd_warshall_tree.
Add docstring to _init_pred_dist

@dschult

dschult commented Dec 18, 2025

Copy link
Copy Markdown
Member

No need to add a doc_string to the private function _init_pred_dist. It's private and won't show up in any docs anyway. And it is short enough that reading it is probably just as good as a doc_string.

@dschult

dschult commented Dec 18, 2025

Copy link
Copy Markdown
Member

Did we lose the original changes that make this use the weight as a function? I'm not seeing them in the diff...

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Did we lose the original changes that make this use the weight as a function? I'm not seeing them in the diff...

You might be talking about this:

    weight = _weight_function(G, weight)
    for u, unbr in G._adj.items():
        dist[u][u] = 0
        for v, e_attr in unbr.items():
            cost = weight(u, v, e_attr)
            if cost is not None:  # for hidden edge, weight() returns None
                dist[u][v] = cost
                pred[u][v] = u
    return pred, dist

These are now moved to _init_pred_dist(G, weight). The initialisation of pred and dist was common to both the algorithms. Thus moved it here. diff-link

@dschult

dschult commented Dec 18, 2025

Copy link
Copy Markdown
Member

Right -- Thanks... got confused because the doc_string changes are not there anymore.

This looks good to me.

But is there a problem with the doc_strings? I think it should be the same text that the other shortest paths use for their weight function input. And I'm not sure if you mean waiting for the docs till after the review of the tests/code, or the merging of the tests/code.

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Right -- Thanks... got confused because the doc_string changes are not there anymore.

Oh, Sorry for the confusion. I was waiting for the code review to update the docstring. I had reverted doc change after some discussion about 3/4 char indentation

I think it should be the same text that the other shortest paths use for their weight function input.

Yes, will add the docstring along with your suggested change about importing defaultdict.

Thank you

@gulshan-123

gulshan-123 commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Now added the docstring, along with other suggestion to import defaultdict at top..
Docstring is just copy pasted from other shortest path functions.

Note that I have respected the earlier indentation rule whatever that was.
Eg: in floyd_warshall_tree, in docstring it was 4 char, in other two functions, it was 3 chars.

@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! Thanks @gulshan-123 !

@MridulS
MridulS merged commit dba6e0f into networkx:main Dec 23, 2025
@dschult dschult added this to the 3.7 milestone Dec 23, 2025
amcandio pushed a commit that referenced this pull request Dec 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

5 participants