Skip to content

Fix handling of faux_infinite values in network_simplex - #7796

Merged
dschult merged 5 commits into
networkx:mainfrom
Schwarf:bugfix/issue7562
Feb 16, 2025
Merged

dschult merged 5 commits into
networkx:mainfrom
Schwarf:bugfix/issue7562

Conversation

@Schwarf

@Schwarf Schwarf commented Jan 16, 2025 •

Copy link
Copy Markdown
Contributor

I've looked into the issue and implemented a potential fix. While I have a general understanding of the high-level idea, I have not studied the network-simplex algorithm in full detail.

From my understanding, the purpose of the faux_inf value is to create dummy edges and assign them a "practical infinity" value, rather than using actual infinity. This "practical infinity" is intended to be sufficiently large compared to all other "real" weights and capacities.

Change made:

  1. Implemented a new calculation for faux_inf:
    faux_inf = (sum(c for c in DEAF.edge_capacities if c < inf) + sum(abs(w) for w in DEAF.edge_weights) + sum(abs(d) for d in DEAF.node_demands)) * 10 or 1

  2. Added the three sample cases discussed in the issue as tests (for illustration):

    • Verified that these tests fail without the fix.
    • Confirmed that they pass with the fix applied.

I believe not all three test cases are necessary for permanent inclusion in the codebase. Please feel free to provide feedback or suggest changes.

Fixes #7562

@dschult dschult changed the title Proposal to to fix issue 7562. Fix handling of faux_infinite values in network_simplex Jan 16, 2025

@rossbar rossbar left a comment

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.

@Schwarf did you try @boothby 's original suggestion? The proposed computation will certainly always yield a number larger than the current bound, but I think there's value in trying to keep this value as low as reasonably achievable in order to avoid potential overflow/precision issues.

@Schwarf

Schwarf commented Jan 25, 2025 •

Copy link
Copy Markdown
Contributor Author

@Schwarf did you try @boothby 's original suggestion? The proposed computation will certainly always yield a number larger than the current bound, but I think there's value in trying to keep this value as low as reasonably achievable in order to avoid potential overflow/precision issues.

Hi @rossbar,
Good point! I checked the proposed solution:
faux_inf = sum(abs(d) for d in DEAF.node_demands)
However, 5 out of 25 tests (including the 3 I added) failed, including the minimal example mentioned here: #7562 (comment).

@dschult

dschult commented Jan 26, 2025

Copy link
Copy Markdown
Member

That suggestion is to change one line on the file..... and that line is only one part of a fairly long multi-line assignment statement. The full statement will now be:

faux_inf = (
        3
        * max(
            chain(
                [
                    sum(c for c in DEAF.edge_capacities if c < inf),
                    sum(abs(w) for w in DEAF.edge_weights),
                ],
                sum(abs(d) for d in DEAF.node_demands),
            )
        )
        or 1
    )

Notice the addition of 3 characters "sum" to the line handling demands.

@Schwarf

Schwarf commented Jan 26, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @dschult,

Thank you for pointing this out! After revisiting the comment, I realized my mistake when testing @boothby's suggestion.
If I use your suggestion as shown above (#7796 (comment))
18 out of 25 network-simplex-tests fail. The line
sum(abs(d) for d in DEAF.node_demands), needs to be provided in the list within the chain function.
The full statement, according to @boothby's suggestion, should be:

faux_inf = (
    3
    * max(
        chain(
            [
                sum(c for c in DEAF.edge_capacities if c < inf),
                sum(abs(w) for w in DEAF.edge_weights),
                sum(abs(d) for d in DEAF.node_demands),
            ]
        )
    )
    or 1
)

With this value for faux_inf all tests pass.

@dschult

dschult commented Jan 27, 2025

Copy link
Copy Markdown
Member

Hmmm.... It looks like you could even get rid of the chain now... and the list too..... it's the max of 3 values now.
It just keeps getting better. :)

pytest.fail(f"network_simplex(G2) failed with error: {e}")


def test_case3_issue7562():

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.

Re: tests, my personal vote would be to keep test_case3 and ditch the other two, which IIUC probe the same behavior.

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

I think this looks reasonable. We can use the final test -- but we should tweak the tests by moving the calls outside of the try/except so the actual Errors are shown (pytest reports those as failures). See below.

Comment on lines +554 to +564
try:
G1 = create_graph(False)
flow_value, flow_dict = nx.network_simplex(G1) # fails
except Exception as e:
pytest.fail(f"network_simplex(G1) failed with error: {e}")

try:
G2 = create_graph(True)
flow_value, flow_dict = nx.network_simplex(G2)
except Exception as e:
pytest.fail(f"network_simplex(G2) failed with error: {e}")

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.

We should probably take the create_graph part of this out of the try/except so that if it raises an exception that isn't interpreted as an expected failure. Also we should use the pytest.raises context manager to test for the failure and in the case of expected passing, we can just run the function without a try/except.

Something like this:

    G1 = create_graph(False)
    with pytest.raises(NetworkXUnbounded, message="negative cycle"):
        flow_value, flow_dict = nx.network_simplex(G1)

    G2 = create_graph(True)
    flow_value, flow_dict = nx.network_simplex(G2)

But now that I look at that, we should be passing both, right?
So I guess the test should just run the two cases without any try/except or pytest.raises.

Other thoughts:

  • we should change the error message to say that the flow is exceeding the theoretical limit of the circuit. But there'sprobably a better word ing of that.
  • we should create a test where we DO get higher than faux_infinity to make sure that check is working. But I don't see how to get it to break. Maybe add a negative cycle?

I agree that the first two tests are not needed once we get the third one (keep the third because it is small and understandable).

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.

I have adapted the tests—please have a look. So far, I have added one failing test using a negative cycle, as suggested by @dschult.
I believe it is valuable to test each of these conditions separately:

    if any(DEAF.edge_flow[i] != 0 for i in range(-n, 0)):
        raise nx.NetworkXUnfeasible("no flow satisfies all node demands")

    if any(DEAF.edge_flow[i] * 2 >= faux_inf for i in range(DEAF.edge_count)) or any(
        e[-1].get(capacity, inf) == inf and e[-1].get(weight, 0) < 0
        for e in nx.selfloop_edges(G, data=True)
    ):
        raise nx.NetworkXUnbounded("negative cycle with infinite capacity found")

To do so, I plan to take a deeper look into the algorithm. Additionally, the error message should likely be refined as discussed earlier

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 like those adapted tests... And the new test for infinite capacity negative cycle looks good!
We already test for negative infinite capacity self-loops. So I think we only need to test the "no flow" case. And maybe we actually already do. There are tests for a few "no flow" cases.

I think the wording no flow satisfies all node demands is confusing: does it mean "flows values of zero satisfy all node demands"? Or does it mean "no flow exists which can satisfy all node demands"? The code makes me think it is the first. Better wording would be helpful.

@Schwarf Schwarf Feb 8, 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.

I took the liberty of rephrasing all exception messages to provide clearer feedback to the user. Hopefully, this improves clarity. I’ve also updated the tests accordingly to reflect these changes. If I have overshot the mark, please let me know.

@rossbar rossbar left a comment

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.

Thanks @Schwarf ! It seems some of the changes have expanded beyond the original scope. My general thoughts:

  • IMO making the exception messages more verbose is not necessarily an improvement, especially since the added wording is often redundant with the exception type.
  • +1 for adding match to the exception tests, this is a nice improvement!
  • +1 for the updated faux_infinity computation!
  • +1 for the new tests to probe faux_infinity and negative cycles. IMO the test_network_simplex_large_capacities has quite a bit of indirection that make it difficult to understand, but that can be fixed in a follow-up PR.

Ultimately I don't think there are any blockers. I'd personally be more strongly in favor if the changes to the exception messages were backed out, but it's not a major sticking point for me.

@Schwarf

Schwarf commented Feb 16, 2025

Copy link
Copy Markdown
Contributor Author

Hi @rossbar,
I have undone the changes regarding the exception messages and applied your suggestions.
Thank you for your feedback.

@Schwarf
Schwarf requested a review from rossbar February 16, 2025 09:17

@rossbar rossbar left a comment

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.

Thanks for that @Schwarf ! My approval stands

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

Nice!
Thanks @Schwarf !!

@dschult
dschult merged commit 7768b92 into networkx:main Feb 16, 2025
@jarrodmillman jarrodmillman added this to the 3.5 milestone May 29, 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.

network_simplex falsely reports negative cycle with infinite capacity

4 participants