Repository navigation
Improve _sparse_fruchterman_reingold with L-BFGS - #7889
Conversation
|
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 I hope to be able to dive into the code changes soon. In the meantime, here are some questions:
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!! |
Reply1Thank you very much for your thoughtful and encouraging feedback! Regarding your questions, we address them below. TestingWe 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 MeaningL-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 Reference: SciPy Documentation Method NamingWe 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 Adding a "Notes" SectionAdding 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 VersionOne of the features we used has been available since SciPy 0.11.0. Additionally, the another feature is already used in If we understand correctly, the proposed test should confirm compatibility with the required SciPy version, reducing concerns on that front. Layout GalleryThe idea of contributing to the layout gallery is interesting. 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! |
|
Dear @dschult, I apologize for the inconvenience, but just in case something was overlooked, I wanted to mention this. |
|
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 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:
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:
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
left a comment
There was a problem hiding this comment.
Very cool! Commented on improvements on code structure. Will need more time for validating implementation logic matches intended
Reply2.1Dear @dschult, Thank you for your valuable feedback! Below are our responses to your comments. Scope of This PRAs 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 CompatibilityFollowing your suggestion, we modified the code so that the old Now, the old version results can be reproduced by using
(The code is available at here.) Method NamingBased 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:
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 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) About Other Your QuestionsQ1Q1. 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. Q2Q2. 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. (Still, in most cases, the default value Once again, thank you for your insightful feedback! |
Reply2.2Dear @amcandio, Thank you very much for the review! It was my first time to hear that In the latest commit, we have addressed all of your comments. If you have any further suggestions, please let us know. Thank you! |
dschult
left a comment
There was a problem hiding this comment.
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.
rossbar
left a comment
There was a problem hiding this comment.
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!
|
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! |





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_reingoldfunction, 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.drawuses this model and simulates this force system to perform graph drawing.Here,
_sparse_fruchterman_reingoldis 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
FRmeans the currentnx.spring_layout, and the orangeFR (L-BFGS)means the our proposed method.)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_layoutin 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.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.
Algorithm
In this section, we describe our proposed algorithm.
We wrote this content in our research paper 2, Section 8.3.
Implementation
Please refer to the diff in the pull request for the implementation details.
Here are a few additional notes:
method="auto"as the default innx.spring_layoutbecause energy-based approaches like ours are relatively rare for the FR force model. We don't want to confuse users.distance2andAidimprove computational speed. Although this may make the code look a bit redundant, it was a deliberate trade-off to enhance performance.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_layoutdoes not allow specifying the number of iterations.)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-BFGSmethod 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. Sincenx.spring_layoutwill 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_layoutandnx.forceatlas2_layout.Although these methods do not directly use the FR force model, we think that
FR (L-BFGS)provides better visualization.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:

For comparision, we listed some of the optimal layouts as follows.
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
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.
(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.deltain the_sparse_fruchterman_reingoldisdim=2.delta's data type isnp.float64, which requires 8 bytes.3D Graphs
We confirmed that the method works correctly for graphs with
dim=3.fixedParameterOur method also works correctly when the
fixedandposparameters are specified. The following figure shows the output for a cycle graph with four vertices specified asfixed.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
Hosobe, Hiroshi. "Numerical optimization-based graph drawing revisited." In 2012 IEEE Pacific Visualization Symposium, pp. 81-88. IEEE, 2012. ↩
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
Fruchterman, Thomas MJ, and Edward M. Reingold. "Graph drawing by force-directed placement." Software: Practice and experience 21, no. 11 (1991): 1129-1164. ↩