Repository navigation
Avoid O(E) lookup in nx.display -issue8639 - #8663
Conversation
Avoid O(E) lookup store known node-edge attr-keys update known node attr pos avoid O(E) lookup Avoid O(E) lookup and error networkx#8639
6356c3f to
cf7b5f4
Compare
There was a problem hiding this comment.
Great idea to keep it simple and just address the O(|E|^2) timing problem.
That makes it so much easier to review...
It will also make it easy to merge with the ongoing work not only in main but also in our review and merging with gh-8255.
Thank you!
I reran the timing comparison from #8639:
In [1]: G = nx.barabasi_albert_graph(400, m=3, seed=19320)
...: pos = nx.spring_layout(G, iterations=100, seed=5040)
...: nx.set_node_attributes(G, pos, name="pos")
...: %timeit -n1 -r1 nx.draw(G, pos=pos, with_labels=True);
...: %timeit -n1 -r1 nx.display(G);
185 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
382 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
So this reduces the time difference to 2x slower for display (from ~12x). This is good!
This PR sets up pre-processing the kwargs and stores any kwarg_value that appears in the graph as an attribute name in a dict known_node_attr with bool value True. It might seem better to use a set instead of a dict. And maybe it would be. But we may want to hang other info off of this kwarg info later -- so I'm good with leaving it as is.
Optional code idiom suggestions:
- the checking code is arguably more readable as
and attr not in known_edge_attrinstead ofand known_edge_attr.get(attr, False). But that choice is subjective... You can choose... - Similarly
not known_node_attr.get(attr, False)could beattr not in known_node_attr.
I approve this PR with or without these suggestions.
amcandio
left a comment
There was a problem hiding this comment.
LGTM. I approve this PR.
Fixes #8639
This PR is linked to issue #8639, in which a performance problem with the function
nx.displaywas revealed. The concern origins in callingnx.get_[node/edge]_attributesinside afor. This was solved doing a pre-procesing over the parameterskwargs, introduced when the function is called, and considering the following cases for the values, as @dschult suggested:display#8255The proposed solution is to create two dicts:
knwon_node_attrandknown_edge_attr. Which stores weather if kwarg_value is a graph-attribute-name of any node/edge of the graph respectively. This dict are updated when we set new node attributes to avoid future errors (so far only happens with position). Then we can change an O(E) lookup for a O(1) lookup:Note that we can't do this change in line 849 because
posmight not be a kwarg_value and be defined in some node.Examples run in my machine:
Performance:
An error of calling the function with the default value has been solved:
Examples with different attributes
Example defining specific position: