Skip to content

Fixing nx.diameter inconsistent results with usebounds=True - #7954

Merged
MridulS merged 4 commits into
networkx:mainfrom
amcandio:issue-7948
Apr 8, 2025
Merged

MridulS merged 4 commits into
networkx:mainfrom
amcandio:issue-7948

Conversation

@amcandio

@amcandio amcandio commented Apr 2, 2025 •

Copy link
Copy Markdown
Contributor

Did a random sample comparison of the output of nx.diameter function when passing usebounds=True and I ended up finding instances where both algorithms don't match when they are expected to compute the same result (See #7948)

    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

Root cause

Old code was initializing upper bounds based on the unweighted case where N is always higher than any shortest path in the network.

    # 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

We can easily fix this replacing N by math.inf.

    # status variables
    ecc_lower = dict.fromkeys(G, 0)
    ecc_upper = dict.fromkeys(G, math.inf)
    candidates = set(G)

    # (re)set bound extremes
    minlower = math.inf
    maxlower = 0
    minupper = math.inf
    maxupper = 0

Testing

We formalize method used to find bug in the first place:

    def test_use_bounds_on_off_consistency(self):
        """Test for consistency of distance metrics when using usebounds=True.

        We validate consistency for `networkx.diameter`, `networkx.radius`, `networkx.periphery`
        and `networkx.center` when passing `usebounds=True`. Expectation is that method
        returns the same result whether we pass usebounds=True or not.

        For this we generate random connected graphs and validate method returns the same.
        """
        seeds = list(range(10))
        ns = list(range(10, 20))
        probs = [x / 10 for x in range(0, 10, 2)]
        methods = [nx.diameter, nx.radius, nx.periphery, nx.center]
        max_weight = [5, 10, 1000]
        for seed, n, prob in itertools.product(seeds, ns, probs):
            rng = np.random.RandomState(seed=seed)
            # we compose it with a random tree to ensure graph is connected
            G = nx.compose(
                nx.random_labeled_tree(n, seed=seed),
                nx.erdos_renyi_graph(n, prob, seed=seed),
            )
            for f in methods:
                # checking unweighted case
                assert f(G) == f(G, usebounds=True)
                for w in max_weight:
                    for u, v in G.edges():
                        G[u][v]["w"] = rng.randint(0, w)
                    # checking weighted case
                    assert f(G, weight="w") == f(G, weight="w", usebounds=True)

@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.

Just some minor comments.
Thanks for this!!

Comment on lines +19 to +20
def test_use_bounds_on_off_consistency(self):
"""Test for consistency of distance metrics when using usebounds=True.

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.

Can we keep the setup_method first in the class so it is easy to find?

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.

For sure, good catch

@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.

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.

4 participants