Skip to content

Improve _sparse_fruchterman_reingold with L-BFGS - #7889

Merged
rossbar merged 7 commits into
networkx:mainfrom
HirokiHamaguchi:improve-sparse-fruchterman-reingold
Apr 15, 2025
Merged

rossbar merged 7 commits into
networkx:mainfrom
HirokiHamaguchi:improve-sparse-fruchterman-reingold

Conversation

@HirokiHamaguchi

Copy link
Copy Markdown
Contributor

Pull Request

Hello, NetworkX developers.

I'm Hiroki Hamaguchi from the University of Tokyo, Japan. We want to contribute to NetworkX by improving the _sparse_fruchterman_reingold function, a.k.a. spring_layout.

We know that this function is one of NetworkX's core features, so we are very careful about the changes and willing to receive any feedback to refine our approach. We hope that our proposal will benefit the NetworkX community.

Abstract

The Fruchterman--Reingold (FR) model is a framework that assumes both attractive and repulsive forces act between vertices. nx.draw uses this model and simulates this force system to perform graph drawing.
Here, _sparse_fruchterman_reingold is one of the key internal functions called when the number of vertices exceeds 500.

To generate faster and better layouts using the FR force model, we aim to modify this function by adopting a different approach from the traditional force-directed method. Specifically, we utilize SciPy's L-BFGS method to optimize the layout, similar to nx.kamada_kawai_layout.

We can broadly classify our proposed method as an energy-based algorithm, but it may be more intuitive to interpret the approach as introducing a kind of momentum into the motion simulation and thus achieving a better layout. Please note that our proposal does not introduce a new model; the conventional interpretation of the FR model works for most cases.

This method is based on the research by Hosobe, H. 1 and our research paper 2.
Our paper mainly discusses the initial placement with this L-BFGS approach, but this L-BFGS's approach itself is also discussed in detail.
We can update our paper to explain our proposal more clearly if necessary.

Key Contribution

Our proposed method can usually achieve better visualization with faster computation. The visualization result is shown in the figure.
(The blue FR means the current nx.spring_layout, and the orange FR (L-BFGS) means the our proposed method.)

$n \approx 500$ and 50 iterations:
graphs_500_50

$n \approx 600$ and 200 iterations:
graphs_600_200

Other Improvements (or Side Effects of Our Proposal?)

The output of our proposed method is theoretically equivalent to the output of the existing method when the graph $G$ is connected and has positive weights. However, the output differs when the graph is not connected or has negative weights due to the current implementation's ill-defined extension of the FR algorithm in 3.

By ill-defined, we mean that the corresponding optimization problem can be unbounded, leading to arbitrary results. This is why our proposed method cannot perfectly reproduce the existing method.

We used the current nx.spring_layout in the figure below. The three graphs on the left show the results with the number of iterations set to 50, 500, and 5000, respectively. The rightmost graph contains negative edges.

unconnected_and_negative_FR

As the number of iterations increases, the graphs blow away and become unreadable. The same issue arises in the rightmost graph. This is because the optimization problem behind the FR model is ill-defined in these cases, and thus we cannot reproduce the results by the optimization method.

Our proposed method introduces additional forces for each connected component and uses the absolute values of edge weights, preventing such problems. This approach often produces better results, which may not completely match the existing method. This is a side effect of our proposed method, which can be seen as either an advantage or a disadvantage.

unconnected_and_negative_L-BFGS

Algorithm

In this section, we describe our proposed algorithm.
We wrote this content in our research paper 2, Section 8.3.

algorithm

Implementation

Please refer to the diff in the pull request for the implementation details.
Here are a few additional notes:

  • We used batch processing to improve computational efficiency. The batch size is 500. As far as we tested, even if we increase the batch size more, the efficiency does not improve or sometimes decreases.
  • We set method="auto" as the default in nx.spring_layout because energy-based approaches like ours are relatively rare for the FR force model. We don't want to confuse users.
  • Temporary variables such as distance2 and Aid improve computational speed. Although this may make the code look a bit redundant, it was a deliberate trade-off to enhance performance.
  • As discussed later, defining the additional force is one of the most challenging problems, not due to mathematical difficulty but rather the philosophical challenges of keeping the implementation concise and what aesthetic principles to base the design on. After various trials, errors, and considerations, we reached the current implementation.

Evaluation

We evaluated our proposed method. The code is available at here.

NetworkX Graphs

We evaluated our method on various graphs generated by NetworkX with different numbers of vertices: 10, 50, 500, and 600.
We set the number of iterations to 50 or 200. (Note that nx.kamada_kawai_layout does not allow specifying the number of iterations.)

graphs_10_50
graphs_50_50
graphs_500_50
graphs_600_200

From these experiments, we can see that our proposed method (orange, FR (L-BFGS)) can, in most cases, achieve better visualization with faster computation compared to the existing method (blue, FR).

For small graphs with around 10 vertices, the overhead of the L-BFGS method can make it slightly slower, but as the number of vertices increases, this overhead becomes negligible, or our method can even outperform the existing one due to the implementation technique. Since nx.spring_layout will use our approach only when the number of vertices exceeds 500 by default, we believe this trade-off is acceptable.

NetworkX Layouts with Different Methods

We also compared our method with nx.arf_layout and nx.forceatlas2_layout.
Although these methods do not directly use the FR force model, we think that FR (L-BFGS) provides better visualization.

$n \approx 50$ and 100 iterations:
arf_forceatlas_50_100

Graphs from SuiteSparse Matrix Collection

We tested our method on large-scale, real-world graphs from the SuiteSparse Matrix Collection.
The superior performance of our method is evident in these cases as well.

200 iterations:
ssgetpy_17758_200

For comparision, we listed some of the optimal layouts as follows.

jagmesh1 1138_bus dwt_1005 dwt_2680 3elt USPowerGrid
optimal layout jagmesh1 1138_bus dwt_1005 dwt_2680 3elt USPowerGrid

Since the problem is a nonconvex optimization problem, it is easy to fall into the local optimum solutions, especially in cases such as dwt_1005, but depending on the seed, L-BFGS can obtain results close to those of optimal layout.

Special Cases

We confirmed that our method works correctly in special cases.

Unconnected Graphs

separated_100

Very Large Graphs

Although we do not provide specific output results here, we confirmed that our method successfully executed on a cycle graph with 100,000 vertices without causing kernel crashes.

We estimate the necessary memory size for the optimization as follows.

  1. If we compute layout for a graph with 100'000 vertices for 100 iterations, it will takes about 55.5 hours with our laptop. ((dim*|V|^2*iterations)/(computational speed per second) = (2*1e5^2*100)/1e7 = 200'000 seconds = 55.5 hours. This method of estimation is broadly correct for smaller graphs.) Approximately this size would be the maximum size users would want to calculate.
  2. We used batch processing with a batch size of 500, i,e., the size of delta in the _sparse_fruchterman_reingold is $500 \times 100000 \times 2$ when the number of vertices is 100,000 and dim=2.
  3. delta's data type is np.float64, which requires 8 bytes.
  4. The memory size is $500 \times 100000 \times 2 \times 8 \approx 0.74$ GB.
  5. In most modern laptops or runtime environments, this memory size is not a problem.

3D Graphs

We confirmed that the method works correctly for graphs with dim=3.

3d

fixed Parameter

Our method also works correctly when the fixed and pos parameters are specified. The following figure shows the output for a cycle graph with four vertices specified as fixed.

fixed

Discussion

We have demonstrated that our proposed method can, in most cases, achieve better visualization with faster computation compared to the existing method.

As far as we anticipate, there are few major inconveniences that users will experience due to this change. If we must point out one, when increasing the number of nodes stepwise from 100 to 1000 and drawing a graph that includes negative edge weights, discontinuities may occur at 500 with method="auto". How to balance such corner cases against improvements in most situations is a matter of values. We personally think it's not a problem, while we would like to follow the community's intentions.

In general, the most well-known algorithm of the FR force model for large-scale graphs is the multi-level approach, such as Graphviz's sfdp. Instead of our approach, we could have implemented this in NetworkX.

However, a complex implementation is not necessarily the best choice for a lightweight library like NetworkX. Furthermore, it is implemented in Python, a language known for its relatively slow execution time.

We believe leveraging SciPy's powerful scientific computing capabilities is a good choice in this situation, and it aligns well with NetworkX's Mission and Values.

We hope our proposal will benefit the NetworkX community.

Thank you for your attention.

Footnotes

  1. Hosobe, Hiroshi. "Numerical optimization-based graph drawing revisited." In 2012 IEEE Pacific Visualization Symposium, pp. 81-88. IEEE, 2012. ↩

  2. Hamaguchi, Hiroki, Naoki Marumo, and Akiko Takeda. "Initial Placement for Fruchterman--Reingold Force Model With Coordinate Newton Direction." arXiv preprint arXiv:2412.20317 (2024). ↩ ↩2

  3. Fruchterman, Thomas MJ, and Edward M. Reingold. "Graph drawing by force-directed placement." Software: Practice and experience 21, no. 11 (1991): 1129-1164. ↩

@dschult

dschult commented Mar 10, 2025

Copy link
Copy Markdown
Member

Wow -- this is quite a nice description of the impact of this PR. And you've taken care in exploring the many possible impacts too. It is really nice work!! :)

The change to the code is fairly isolated to one main section of code. I have not dived into that yet.

The changes to the docs look good.

Other code changes are mostly about setting up this function with a method= keyword argument instead of our automatic switching between NumPy (dense) and SciPy (sparse) treatments. Our current implementation switches for graphs larger/smaller than 500 nodes. With the two options now specified as FR and L-BFGS, we have the method name auto which performs the current switching between methods. This is a nice way to use the current setup by default and still allow users to specifically choose dense or sparse approaches no matter how many nodes there are.

I hope to be able to dive into the code changes soon. In the meantime, here are some questions:

  • Does it make any sense to have tests for these changes? I can't think of any way to do that. But maybe there is something.
  • What does L-BFGS stand for?
  • Is there a friendlier way to abbreviate the two method names? I believe most users of spring_layout will not know what FR and L-BFGS stand for. Can we add a "Notes" section in the docs that in a few sentences describes the difference between the methods? I think perhaps wording can be taken from this PR.
  • We should make sure the code works with all supported versions of SciPy. I think it does based on the tests.

Thanks very much for this code and for the beautiful presentation of results. I am trying to figure out if there is a way to include some of this -- or something like it in our docs. Maybe in a gallery section on layouts. But I'm not sure how to make that work with the sphinx gallery system. If nothing else, we could add it to the nx-guides repository.

Thanks!!

@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

Reply1

Thank you very much for your thoughtful and encouraging feedback!
I truly appreciate your time and effort in reviewing our proposal.

Regarding your questions, we address them below.
We will commit the changes to the PR once the keywords for method are finalized.

Testing

We have also considered testing and agree that adding tests would be beneficial.

One possible approach is to extend the existing test at this location.

If necessary, we could add the following:

    def test_adjacency_interface_numpy(self):
        A = nx.to_numpy_array(self.Gs)
        pos = nx.drawing.layout._fruchterman_reingold(A)
        assert pos.shape == (6, 2)
        pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
        assert pos.shape == (6, 3)
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
        assert pos.shape == (6, 2)
+       pos = nx.drawing.layout._sparse_fruchterman_reingold(A, method="L-BFGS")
+       assert pos.shape == (6, 2)

    def test_adjacency_interface_scipy(self):
        A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
        assert pos.shape == (6, 2)
        pos = nx.drawing.layout._sparse_spectral(A)
        assert pos.shape == (6, 2)
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
        assert pos.shape == (6, 3)
+       pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3, method="L-BFGS")
+       assert pos.shape == (6, 3)

Besides, although the main concern will be whether SciPy’s L-BFGS runs without errors, since SciPy already thoroughly tests this, we believe additional safeguards are unnecessary on our end.

L-BFGS Meaning

L-BFGS stands for Limited-memory Broyden-Fletcher-Goldfarb-Shanno, a well-known optimization algorithm.

We chose this name for consistency with SciPy's terminology, as it is already used in the method parameter of scipy.optimize.minimize ("L-BFGS-B", where "B" stands for Box-constrained, which is not relevant).

Reference: SciPy Documentation

Method Naming

We considered using "force" for the existing method (FR) and "energy" for our proposal (L-BFGS) as potential alternatives.

However, these terms might be misleading in a strict technical sense. Since "L-BFGS" is already used in scipy.optimize.minimize, it may be somewhat familiar to users -- though admittedly, it is not the most intuitive name.

Adding a "Notes" Section

Adding a "Notes" section sounds like a great idea! Would something like the following work?

    method : str, optional (default='auto')
        The method used to compute the layout.
        If 'FR', the force-directed Fruchterman--Reingold algorithm [1] is used.
-       If 'L-BFGS', the energy-based optimization algorithm [2] is used
-       with absolute values of edge weights and additional forces per connected component.
+       If 'L-BFGS', the energy-based optimization algorithm [2] is used.
        If 'auto', we use 'FR' when len(G) < 500 and 'L-BFGS' otherwise.

    Returns
    -------
    pos : dict
        A dictionary of positions keyed by node

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.spring_layout(G)
    >>> # suppress the returned dict and store on the graph directly
    >>> _ = nx.spring_layout(G, seed=123, store_pos_as="pos")
    >>> nx.get_node_attributes(G, "pos")
    {0: array([-0.61520994, -1.        ]), 1: array([-0.21840965, -0.35501755]), 2: array([0.21841264, 0.35502078]), 3: array([0.61520696, 0.99999677])}

    # The same using longer but equivalent function name
    >>> pos = nx.fruchterman_reingold_layout(G)

+    Notes
+    -----
+    method="FR" supports negative edge weights and uses only attractive and repulsive forces.
+    method="L-BFGS" uses absolute edge weights and additional forces per connected component,
+    making graph drawing a well-defined optimization problem. This enables the use of the 
+    efficient optimization algorithm: Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS).
+    You can see the differences in the [Gallery](todo???).

 References
    ----------
    .. [1] Fruchterman, Thomas MJ, and Edward M. Reingold.
           "Graph drawing by force-directed placement."
           Software: Practice and experience 21, no. 11 (1991): 1129-1164.
           http://dx.doi.org/10.1002/spe.4380211102
    .. [2] Hamaguchi, Hiroki, Naoki Marumo, and Akiko Takeda.
           "Initial Placement for Fruchterman--Reingold Force Model With Coordinate Newton Direction."
           arXiv preprint arXiv:2412.20317 (2024).
           https://arxiv.org/abs/2412.20317
    """

SciPy Version

One of the features we used has been available since SciPy 0.11.0.

Additionally, the another feature is already used in nx.kamada_kawai_layout, compatibility should not be an issue.

If we understand correctly, the proposed test should confirm compatibility with the required SciPy version, reducing concerns on that front.

Layout Gallery

The idea of contributing to the layout gallery is interesting.
But we're unsure where to start. Are you referring to adding images to here?

If you have specific ideas or requests, please let us know -- we’d be happy to help!


Again, thank you so much for your review and kind words!
We look forward to hearing your thoughts on these points.

@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

Dear @dschult,

I apologize for the inconvenience, but just in case something was overlooked, I wanted to mention this.
Even a brief instruction would be greatly helpful to us!
Thank you in advance for your attention.

@dschult

dschult commented Mar 23, 2025

Copy link
Copy Markdown
Member

Sorry for the delay. And I still haven't dug through the code in detail.

The main change needed for this PR is to somehow make it possible for old code to be able to recreate what used to happen (for backward compatibility -- and assuming this isn't too difficult to do). Perhaps the easiest way to do this would be to make a "method" option for the old version of this code. The intent is to allow them to get the same results as before by adding this other method option keyword to their previous call to spring_layout.

My current understanding is that there are two fundamental changes made to the sparse algorithm by this PR. First the nodes in each components are given an additional force (based on the average position of nodes in each component) to reduce the separation between components (keep it finite). Second, we are minimizing energy rather than simulating a time-dependent (dynamic) newton's law force system to find its steady state. Theoretically the minimal energy state and the steady state in a dynamic setting should be the same (for a single component network).

Two questions:

  1. Why didn't you choose to update the small graph option to use the optimizing approach? (I don't want you to do that -- I'm just wondering whether you investigated it at all.)
  2. Would it be reasonable to scale the connected component force by a keyword arg parameter? That is, do you think it would be helpful to be able to increase or decrease the force between connected components?

Tests: I think we do not need to change the tests as you describe above. Yes, it could be done, but the existing tests are good enough. We might want to add a test checking the method names, but let's not do that now. We can do that in a separate PR if desired.

Method naming: Let's please add another method value to get the old version of the sparse results. As for the various names:

  • Is it possible that someone in the future would want to implement a different optimization routine than L-BFGS?
  • Is it important to indicate whether the method is good for large or small networks in the name?
  • Is it important to indicate whether it is simulating dynamic forces to a steady state vs minimizing energy?
  • And I guess we want to keep the abbreviations short -- with a Notes section to explain in more detail.

Perhaps: "auto"/"dense-ss"/"sparse-ss"/"sparse-me" with "ss" for steady-state and "me" for minimal-energy. But maybe "FR" and "L-BFGS" with good descriptions is better after all.

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

Very cool! Commented on improvements on code structure. Will need more time for validating implementation logic matches intended

Comment thread networkx/drawing/layout.py Resolved
Comment thread networkx/drawing/layout.py Resolved
Comment thread networkx/drawing/layout.py Resolved
@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

Reply2.1

Dear @dschult,

Thank you for your valuable feedback!

Below are our responses to your comments.

Scope of This PR

As you suggested, we agree that the test should be handled in a separate PR. Therefore, this PR will focus solely on adding the proposed method.

If necessary, we will create additional PRs to test or update the gallery for documentation.

Backward Compatibility

Following your suggestion, we modified the code so that the old _sparse_fruchterman_reingold method remains accessible, and we renamed our proposed method as _energy_fruchterman_reingold.

Now, the old version results can be reproduced by using method="force", which means the blue graphs and pink graphs are the same in the below.

$n \approx 10$ and 50 iterations:
graphs2_10_50

$n \approx 50$ and 50 iterations:
graphs2_50_50

$n \approx 500$ and 50 iterations:
graphs2_500_50

$n \approx 5000$ and 50 iterations:
graphs2_5000_50

(The code is available at here.)

Method Naming

Based on your feedback, we considered a lot, and we concluded that our previous statements were incorrect. While we initially expressed concerns that the terms might be misleading in a strictly technical sense, naming the old version "force" and the new version "energy" is actually the most intuitive, we think. Thank you for caring about the naming.

From a technical standpoint, we also think they are acceptable, as these terms can be understood as abbreviations:  

  • method="force" <- force-directed Fruchterman-Reingold algorithm.
  • method="energy" <- energy-based optimization algorithm.

And here is the answers to your questions:

Q1. Is it possible that someone in the future would want to implement a different optimization routine than L-BFGS?

A1. We don't deny the possibility, but we think it is unlikely. We know that L-BFGS algorithm is the de facto standard for unconstrained smooth optimization problems (Hiroki Hamaguchi major in optimization and other members are the experts of optimization).
We believe that the L-BFGS algorithm is the most suitable choice for this problem.

Q2 and Q3. Is it important to indicate whether the method is good for large or small networks in the name? Is it important to indicate whether it is simulating dynamic forces to a steady state vs minimizing energy?

A2 and A3. We think both are not so much important. Now we have backward compatibility, and thus the main difference between the two methods is (i) the quality and speed of the output and (ii) method="energy" uses absolute values of edge weights and gravitational forces per connected component. Given the shortness of the method names (force and energy), we think they are the most intuitive and suitable names.

About Other Your Questions

Q1

Q1. Why didn't you choose to update the small graph option to use the optimizing approach? (I don't want you to do that -- I'm just wondering whether you investigated it at all.)

A1. Because it would be the most beneficial for users.

The current implementation often struggles to properly render graphs with 500 or more vertices. For those cases, the advantages of speeding up by the proposed method outweigh the disadvantages caused by slight changes in output interpretation.

However, for graphs with fewer than 500 vertices, the current method generally performs well and the proposed method takes longer time for calculation due to the overhead of the sparse matrix operations and so on.
To maintain consistency and avoid altering existing behavior, we left the small graph version unchanged.

Q2

Q2. Would it be reasonable to scale the connected component force by a keyword arg parameter? That is, do you think it would be helpful to be able to increase or decrease the force between connected components?

A2: Yes, we believe this would be a great addition.

We truly appreciate this thoughtful suggestion.
We also struggled with this aspect and initially aimed for a parameter-free approach, but achieving the best results for all cases was quite challenging. By introducing gravity as an adjustable parameter, users can now more easily achieve their desired results.

(Still, in most cases, the default value gravity=1.0 is the best choice, the orange graphs.)

separated2_50


Once again, thank you for your insightful feedback!

@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

Reply2.2

Dear @amcandio,

Thank you very much for the review!
I really appreciate your feedback and suggestions.

It was my first time to hear that x**2 is slower than x*x in Python. Thank you for the information.

In the latest commit, we have addressed all of your comments. If you have any further suggestions, please let us know.

Thank you!

@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 approve these changes. I do make a suggestion below to make the new keyword args keyword-only so that people don't try specifying them by position order... The private functions don't need that. And it is a minor tweak really.

Thank you for this improvement/addition to an important part of our layout suite.

Comment thread networkx/drawing/layout.py Resolved

@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 @HirokiHamaguchi , I found this an especially thoughtful PR particularly in how you've structured things to fit within the existing framework without unrelated code churn. Bravo!

I took the liberty of pushing up some extremely minor docstring formatting tweaks, but this is good to go IMO. I will merge when CI from my last push is done. Thanks again for the detailed proposal and thoughtful discussion, and thanks @dschult and @amcandio for the excellent review!

@rossbar
rossbar merged commit 9d96e77 into networkx:main Apr 15, 2025
@HirokiHamaguchi

Copy link
Copy Markdown
Contributor Author

Sorry for the late reply, and I deeply appreciate everyone's tremendous support.

There are no issues with the changes made by both of you. My latest changes are just minor refactoring and are quite trivial.

Thank you very much once again!

@HirokiHamaguchi
HirokiHamaguchi deleted the improve-sparse-fruchterman-reingold branch April 24, 2025 11:12
@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.

5 participants