Skip to content

nx.diameter inconsistent results with usebounds=True #7948

Closed

Description

@amcandio

Did a random sample comparison of the output of nx.diameter function when passing usebounds=True.

I ended up finding instances where both algorithms don't match when they are expected to compute the same result.

    def test_ale(self):
        import numpy as np
        seed = 1
        rng = np.random.RandomState(seed=seed)
        G = nx.erdos_renyi_graph(10, 0.25, seed=seed)
        for u, v in G.edges():
            G[u][v]['w'] = rng.randint(0, 1000)
        assert nx.diameter(G, weight='w') == nx.diameter(G, usebounds=True, weight='w')

Besides this issue, we should incorporate these types of randomized tests for certain algorithms/optimizations where they apply.

Current Behavior

    def test_ale(self):
        import numpy as np
        seed = 1
        rng = np.random.RandomState(seed=seed)
        G = nx.erdos_renyi_graph(10, 0.25, seed=seed)
        for u, v in G.edges():
            G[u][v]['w'] = rng.randint(0, 1000)
>       assert nx.diameter(G, weight='w') == nx.diameter(G, usebounds=True, weight='w')
E       AssertionError: assert 1972 == 1257
E        +  where 1972 = <function diameter at 0x103aa1a80>(<networkx.classes.graph.Graph object at 0x128636350>, weight='w')
E        +    where <function diameter at 0x103aa1a80> = nx.diameter
E        +  and   1257 = <function diameter at 0x103aa1a80>(<networkx.classes.graph.Graph object at 0x128636350>, usebounds=True, weight='w')
E        +    where <function diameter at 0x103aa1a80> = nx.diameter

Expected Behavior

Test should pass as output should be the same.

Steps to Reproduce

Add test and run pytest -k test_ale

Python version: Python 3.12.7
NetworkX version: I'm at commit 1af2820e3710526248c64d981488f83c3c32e056

Activity

  1. dschult commented on Mar 31, 2025

    @dschult
    Member

    Yikes! Thanks for this!

    I can't get it to fail when calling it on an unweighted graph.
    And the weighted feature was added well after the original function was written.
    Perhaps we are breaking some assumption in the usebounds alg by computing with weights?

    For example, there are expressions like ecc_upper[i] + 1 <= 2 * minlower which I could believe don't work the same for weighted and unweighted graphs. But I haven't dived into the algorithm to check that.

    Perhaps we should just jettison the usebounds functionality.
    For a long time, it has been untested and hidden (in the sense that the docs didn't describe the usebounds parameter at all) until this year...

  2. amcandio commented on Mar 31, 2025

    @amcandio
    ContributorAuthor

    For example, there are expressions like ecc_upper[i] + 1 <= 2 * minlower which I could believe don't work the same for weighted and unweighted graphs. But I haven't dived into the algorithm to check that.

    That totally makes sense! I will try to dive deep over next weekend but algo doesn't seem trivial. Maybe @franktakes can help us here?

    Perhaps we should just jettison the usebounds functionality.

    Or at least disable it till there is a fix (like throwing a warning if usebounds=True is passed and fallback to default algo).

  3. amcandio commented on Apr 1, 2025

    @amcandio
    ContributorAuthor

    Found it, will send a PR later in the week.

        # status variables
        ecc_lower = dict.fromkeys(G, 0)
        ecc_upper = dict.fromkeys(G, N)
        candidates = set(G)
    
        # (re)set bound extremes
        minlower = N
        maxlower = 0
        minupper = N
        maxupper = 0

    All the upper bounds are set for the undirected case. Replacing them by math.inf should do the trick :)

  4. franktakes commented on Apr 1, 2025

    @franktakes

    Thanks for tagging me.
    I was only involved when the original unweighted algorithm was implemented; back then it was ported from my C++ implementation into python networkx. I remember we had an assert in there that made sure it was an unweighted graph; otherwise the user should simply not make use of useBounds=true. For the unweighted version we also had some well-thought-through testcases, if I remember correctly.

    It is nice to see that there is now also a weighted version. I was not the person who implemented the weighted variant, nor can I say whether that algorithm is correct at this point.
    Quickly judging the code, indeed setting the initial values to N is not enough, because there can be just one numeric edge weight greater than the number of nodes, and the whole thing does not work any more.
    So, the suggested fix seems logical, and should not affect he unweighted case.
    Does this help?

  5. amcandio commented on Apr 1, 2025

    @amcandio
    ContributorAuthor

    Great, thanks for the confirmation! From quick randomized tests I did seems to be working fine after that change

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions