Skip to content

fix bug of _sparse_fruchterman_reingold and remove try/except idiom - #8041

Merged
dschult merged 4 commits into
networkx:mainfrom
HirokiHamaguchi:bugfix-of-_sparse_fruchterman_reingold
May 19, 2025
Merged

dschult merged 4 commits into
networkx:mainfrom
HirokiHamaguchi:bugfix-of-_sparse_fruchterman_reingold

Conversation

@HirokiHamaguchi

@HirokiHamaguchi HirokiHamaguchi commented May 12, 2025 •

Copy link
Copy Markdown
Contributor

Fix bug in _sparse_fruchterman_reingold

Dear NetworkX maintainers,

I am Hiroki Hamaguchi, a contributor to NetworkX and the author of this previous pull request.

I sincerely apologize, but I have discovered a bug introduced in that PR. Specifically, when method="auto" is specified, the nx.spring_layout function does not use the new _energy_fruchterman_reingold function as intended.

The fix is trivial, and I would appreciate it if you could kindly review and merge the proposed correction.

Thank you very much for your time and consideration.


Added based on discussion (details in comments below)
I believe the try/except block [using ValueError as a signal to try a different branch of code] is unnecessary.
A ValueError can occur in the following situations:

pos is a NumPy array and if pos == None is evaluated
(Raises: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all())

fixed is a NumPy array and if fixed == None is evaluated
(Same error as above)

dim is set to -1, leading to calls like np.random.random((nnodes, dim)) or np.zeros(dim)
(Raises: ValueError: negative dimensions are not allowed)

However, the first two issues are already addressed in the current code using if pos is None and if fixed is None, so the try/except block is redundant.
For the third case, this ValueError is raised in the current version of NetworkX, so it is not related to the try/except block.


Based on this, I fixed the bug [about "method" keyword] and cleaned up the code as suggested in the current PR.

I also tested the code with the following configurations and confirmed it works successfully:

(Please refer to here for the results)

  1. Different method values:

    • "auto" (len(G)=499 and 500)
    • "energy"
    • "force"
  2. Providing an initial layout via the pos argument

  3. Fixing certain nodes using the fixed argument

  4. Changing layout dimensionality with the dim argument:

    • A 3D layout using dim=3
    • An invalid layout with dim=-1 to confirm error handling

Comment thread networkx/drawing/layout.py Outdated
k = np.sqrt(1.0 / nnodes)

if method == "energy":
if method != "force":

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.

I think this bug is just a symptom of code being hard to maintain. This line could break if we add extra methods in the future.

I think it will be easier if we replace method=auto by its resolved value right at the start of the call. Is that something we could do?

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.

How about we use: if method in ("energy", "auto"):
We could also put it at the start of the public function for this suite of calls. But that separates the processing from the use by quite a bit. Might be easier to maintain with it all handled within a few lines of each other.

Certainly testing whether method != "force" is dangerous -- if someone misspells the word for example.
That shows that we also need an elif clause on this if structure. Maybe like:

    if method in ("energy", "auto"):
        return ......
    elif method != "force":
        raise NetworkXError(fmethod parameter {method} should be "energy", "force" or "auto"')  

...

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.

Thank you for the comment. I really appreciate your help.

I think this bug is just a symptom of code being hard to maintain. This line could break if we add extra methods in the future.

Yes, you're absolutely right. I should have fixed it in a different way.

Regarding the misspelling, we have already checked it here.

if method not in ("auto", "force", "energy"):
raise ValueError("the method must be either auto, force, or energy.")

I think using if method in ("energy", "auto"): is one of the most reasonable choices, but I am wondering if there might be an even better solution.

The logic for method='auto' is also complicated here.

try:
# Sparse matrix
if method in ["auto", "force"] and len(G) < 500:
raise ValueError
A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
if k is None and fixed is not None:
# We must adjust k by domain size for layouts not near 1x1
nnodes, _ = A.shape
k = dom_size / np.sqrt(nnodes)
pos = _sparse_fruchterman_reingold(
A, k, pos_arr, fixed, iterations, threshold, dim, seed, method, gravity
)
except ValueError:
A = nx.to_numpy_array(G, weight=weight)
if k is None and fixed is not None:
# We must adjust k by domain size for layouts not near 1x1
nnodes, _ = A.shape
k = dom_size / np.sqrt(nnodes)
pos = _fruchterman_reingold(
A, k, pos_arr, fixed, iterations, threshold, dim, seed
)

Therefore, adding the following lines after if method not in ("auto", "force", "energy"): might be one option:

if method == "auto":
    method = "force" if len(G) < 500 else "energy"

(Maybe replacing the raise ValueError part with a simple if statement would simplify the code, but I'm not sure why this code uses try and except. It already existed before my first commit.)

I would appreciate hearing your thoughts on how best to handle method="auto".

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.

I think we should resolve method at the start (replacing auto) and clean up all the auto checks. This includes removing the try catch for method selection

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.

Thank you for your reply. I mostly agree with you, but my only concern is that removing the try block might cause some unintended behavior. As I mentioned earlier, I'm not sure why this code uses try and except. Do you happen to know any specific reason why it was written this way?

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.

I don't have the historical context but you should be able to find it with git blame. I'm okay with doing that clean up in a separate PR to not block the fix.

What about this interim structure:

if can we do sparse?
    try:
        return sparse_method(...)
    catch ValueError:
        pass # we fallback to non-sparse

# non sparse method

@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

Thanks for your reply.

I thought doing the PR in a separate PR and inheriting the structure you suggested would be a good idea, but I realized that it would be better to do it in the same PR. So I’ve made the changes in this PR.

First, I found that the try/except block was introduced in the following commit:

0723fcd

Here is the corresponding file from that commit:

https://github.com/networkx/networkx/blob/0723fcdd9193ebc9e7ddd61e5b37e4aee0448947/networkx/drawing/layout.py

I believe the try/except block is unnecessary.
A ValueError can occur in the following situations:

  • pos is a NumPy array and if pos == None is evaluated
    (Raises: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all())

  • fixed is a NumPy array and if fixed == None is evaluated
    (Same error as above)

  • dim is set to -1, leading to calls like np.random.random((nnodes, dim)) or np.zeros(dim)
    (Raises: ValueError: negative dimensions are not allowed)

However, the first two issues are already addressed in the current code using if pos is None and if fixed is None, so the try/except block is redundant.
For the third case, this ValueError is raised in the current version of NetworkX, so it is not related to the try/except block.


Based on this, I fixed the bug and cleaned up the code as suggested in the current PR.

I also tested the code with the following configurations and confirmed it works successfully:

(Please refer to here for the results)

  1. Different method values:

    • "auto" (len(G)=499 and 500)
    • "energy"
    • "force"
  2. Providing an initial layout via the pos argument

  3. Fixing certain nodes using the fixed argument

  4. Changing layout dimensionality with the dim argument:

    • A 3D layout using dim=3
    • An invalid layout with dim=-1 to confirm error handling

I would appreciate it if you could review the current PR.

@amcandio

Copy link
Copy Markdown
Contributor

Great job, thanks for the deep dive! I checked the code and what you are saying makes sense to me. We have some 20 years old code here 😅

Can you update the PR description with all your analysis so it's easier to track in the future? Code-wise I don't have any other comment

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

Thank you for this!
I approve these changes.

@amcandio, Did you mean that @HirokiHamaguchi should edit the initial post of the PR? Or that they should add a comment with more details? And what details/analysis are you referring to? The link to the jupyter notebook webpage seemed good -- did you want some of that in this PR?

@dschult dschult added this to the 3.5 milestone May 17, 2025
@amcandio

Copy link
Copy Markdown
Contributor

Thanks for your reply.

I thought doing the PR in a separate PR and inheriting the structure you suggested would be a good idea, but I realized that it would be better to do it in the same PR. So I’ve made the changes in this PR.

First, I found that the try/except block was introduced in the following commit:

0723fcd

Here is the corresponding file from that commit:

https://github.com/networkx/networkx/blob/0723fcdd9193ebc9e7ddd61e5b37e4aee0448947/networkx/drawing/layout.py

I believe the try/except block is unnecessary.
A ValueError can occur in the following situations:

  • pos is a NumPy array and if pos == None is evaluated
    (Raises: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all())

  • fixed is a NumPy array and if fixed == None is evaluated
    (Same error as above)

  • dim is set to -1, leading to calls like np.random.random((nnodes, dim)) or np.zeros(dim)
    (Raises: ValueError: negative dimensions are not allowed)

However, the first two issues are already addressed in the current code using if pos is None and if fixed is None, so the try/except block is redundant.
For the third case, this ValueError is raised in the current version of NetworkX, so it is not related to the try/except block.


Based on this, I fixed the bug and cleaned up the code as suggested in the current PR.

I also tested the code with the following configurations and confirmed it works successfully:

(Please refer to here for the results)

  1. Different method values:

    • "auto" (len(G)=499 and 500)
    • "energy"
    • "force"
  2. Providing an initial layout via the pos argument

  3. Fixing certain nodes using the fixed argument

  4. Changing layout dimensionality with the dim argument:

    • A 3D layout using dim=3
    • An invalid layout with dim=-1 to confirm error handling

I would appreciate it if you could review the current PR.

@dschult I meant including part of this context on why it is safe to remove try except. Would be nice to see that directly in description

@dschult dschult changed the title fix bug of _sparse_fruchterman_reingold fix bug of _sparse_fruchterman_reingold and remove try/except idiom May 17, 2025
@dschult

dschult commented May 17, 2025

Copy link
Copy Markdown
Member

I added some of the text from the recent comment to the top post (the PR description).
@HirokiHamaguchi can you check that the top comment/post on this PR summarizes the changes in this PR and why they are made -- and why they are justified?
@amcandio is this the kind of thing you are aiming for?

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

Yes, that's what I had in mind!

@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 the quick fix @HirokiHamaguchi !

Since this slipped through review the first time, I thought it was worth adding an explicit unit test for the method selection logic1 based on the number-of-nodes heuristic. I took the liberty of pushing such a test up... essentially, it works by computing the seeded spring_layout twice: once with method="auto" and once with the method set explicitly based on the expected method given the number of nodes (see the first parametrization). It's not an inexpensive test, but I can't think of another way to probe the number-of-nodes heuristic other than generating inputs that are greater than the limit!

Anyways: +1 from me for the code improvements, so I approve. @dschult @amcandio could you take a look and make sure you're okay with the test? The second parametrization could be removed but was inspired by the types of tests @HirokiHamaguchi had set up in the linked notebook. I'm also happy to pytest.mark it slow. LMK!

Footnotes

  1. FWIW the test fails on main but passes here, so it checks the intended behavior! ↩

@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

I added some of the text from the recent comment to the top post (the PR description). @HirokiHamaguchi can you check that the top comment/post on this PR summarizes the changes in this PR and why they are made -- and why they are justified? @amcandio is this the kind of thing you are aiming for?

@dschult Thank you for the edition! It seems the post you edited well summarizes the content. Thank you very much.

@amcandio

Copy link
Copy Markdown
Contributor

Thanks for the quick fix @HirokiHamaguchi !

Since this slipped through review the first time, I thought it was worth adding an explicit unit test for the method selection logic1 based on the number-of-nodes heuristic. I took the liberty of pushing such a test up... essentially, it works by computing the seeded spring_layout twice: once with method="auto" and once with the method set explicitly based on the expected method given the number of nodes (see the first parametrization). It's not an inexpensive test, but I can't think of another way to probe the number-of-nodes heuristic other than generating inputs that are greater than the limit!

Anyways: +1 from me for the code improvements, so I approve. @dschult @amcandio could you take a look and make sure you're okay with the test? The second parametrization could be removed but was inspired by the types of tests @HirokiHamaguchi had set up in the linked notebook. I'm also happy to pytest.mark it slow. LMK!

Good call actually. Test looks good to me!

Footnotes

  1. FWIW the test fails on main but passes here, so it checks the intended behavior! ↩

@Peiffap Peiffap 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 :)

Comment thread networkx/drawing/tests/test_layout.py Resolved


@pytest.mark.parametrize(
("num_nodes", "expected_method"), [(100, "force"), (501, "energy")]

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.

What's the reason for using 501 instead of 500?

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.

Probably the same reason as the typo you commented above. Would be cool to test both ends of the edge 499 and 500

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 3 parametrizations of the 501 tests take about 1 sec each -- and they are 3 of the top 10 tests in terms of time. Bumping up the "force" case to 499 adds ~2.5 secs more, while the case with 100 adds about 0.03 secs.

Maybe we should split out the test of "auto" from the tests of "3d" and "fixed node positions". We should still run those with both "energy" and "force", but could use the smaller n100 size when testing the other kwargs.

I'm going to merge this to get it in before the release. We can tweak the tests in a separate PR.

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.

Thank you very much for checking the test performance🙇

@dschult
dschult merged commit dc8de3b into networkx:main May 19, 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