Skip to content

FilterAdjacency: __len__ is recalculated unnecessarily #7377 - #7378

Merged
rossbar merged 21 commits into
networkx:mainfrom
lejansenGitHub:bugfix-for-issue-7377
Apr 14, 2024
Merged

rossbar merged 21 commits into
networkx:mainfrom
lejansenGitHub:bugfix-for-issue-7377

Conversation

@lejansenGitHub

@lejansenGitHub lejansenGitHub commented Mar 27, 2024 •

Copy link
Copy Markdown
Contributor

len result is being stored for FilterAdjacency and FilterAtlas

Fixes #7377

Impacts of dynamic computation of len

The class FilterAdjacency is only used in views and therefore only works on frozen sets of edges and nodes. Despite that its len function is recalculated each time it is called instead of it being calculated and stored once upon its first call.

Current Behavior

len of FilterAdjacency is recalculated unnecessarily upon each call using up 80% of runtime for my application.

Expected Behavior

len of FilterAdjacency should calculated and stored once upon its first call. For all other calls the stored value is returned.

Steps to Reproduce

Any use of nx.subgraph_view shows this behaviour. Very poor performance shows in my case for number of nodes > 100.000.

Environment

Should be completely independent of env.

Python version: 3.11.8
NetworkX version: 3.2.1

@dschult

dschult commented Mar 27, 2024 •

Copy link
Copy Markdown
Member

Can you describe what impact this has on your projects or how this helps you? Storing information in two places is potentially problematic if one source changes. By caching the length value we need to ensure that the iter process remains the same, or that the cached value gets updated.

so… what’s the problem you are running into that this will solve?
[Edited: I added a link to Issue #7377 that describes the problem and how this fix might help that problem.]

@dschult

dschult commented Mar 27, 2024

Copy link
Copy Markdown
Member

I've edited my previous comment and the OP to show the link to the issue where a good description of the problem is contained.
Thank you for this bug report and potential fix.

I will need to check for ways that this cached value might be out of sync with the underlying data.
Could we e.g. use len(self.NODE_OK.nodes) when that exists? When NODE_OK is a function we might need to fall back on the current iterator based approach.

Another approach:
I suspect you will get better response time if you copy the subgraph as soon as you create it using G.subgraph(...).copy(). If you have to look at edges more than once this will usually be faster.

@lejansenGitHub

Copy link
Copy Markdown
Contributor Author

Hi,
thank you very much for the very fast response.

I would like to avoid the copy approach. I deal with large graphs and apply multiple different views and dont want to worry about memory consumption. Also i optimized my filter functions a lot and their runtime is sufficient fast, also faster than copying.

In my case NODE_OK is a function.

@dschult

dschult commented Mar 27, 2024

Copy link
Copy Markdown
Member

Do you have any suggestions for how to make sure that an arbitrary user's functions are not resulting in a change in the length of the view? I don't see that we can guarantee that. And so caching the length may not be correct.

As for copying the subgraph -- remember that it is only copying the subgraph, not the full graph. In terms of time, it should be faster if you end up looking at the edges more than once. In terms of memory, it will require an extra size of the subgraph -- not the size of the full graph. You might want to try it and see what the impact is.

As another workaround, maybe you can store the length in a cache that you create (assuming that you know that your lengths will not change).

SG = G.subgraph(node_ok_func)
SG.length = len(SG)

If you don't want to store it on the subgraph object, could you store it somewhere else?

@lejansenGitHub

lejansenGitHub commented Mar 27, 2024 •

Copy link
Copy Markdown
Contributor Author

For my case it would be enough to give the subgraph_view something like a cache_len: bool = False option.
For the case that you know that the length does not change you can set it to True chache the length and enjoy your performance improvement.

SG = G.subgraph(node_ok_func)
SG.length = len(SG)

this is also fine

@rossbar

rossbar commented Mar 27, 2024

Copy link
Copy Markdown
Contributor

Is this a candidate for functools.cached_property? I'd lean against custom caching machinery, but if this is a case where functools might work it'd be worth exploring.

@dschult

dschult commented Mar 28, 2024

Copy link
Copy Markdown
Member

Here's another approach that might work. Since NODE_OK is either a bunch of nodes or callable, we could compute the length based on len(NODE_OK.nodes) when NODE_OK has a nodes attribute, on NODE_OK.length when NODE_OK has a length attribute. And when NODE_OK has neither attributes, we iterate to find the length.

Users who define the length attribute are responsible for updating it when the set is a dynamic quantity. The length is stored on the object that defines the set of nodes (i.e., close to the data it describes).

Thoughts?

@lejansenGitHub

lejansenGitHub commented Mar 28, 2024 •

Copy link
Copy Markdown
Contributor Author

Here's another approach that might work. Since NODE_OK is either a bunch of nodes or callable, we could compute the length based on len(NODE_OK.nodes) when NODE_OK has a nodes attribute, on NODE_OK.length when NODE_OK has a length attribute. And when NODE_OK has neither attributes, we iterate to find the length.

works for me!

i am really impressed about the speed and the level of quality of your responses. Thank you again for that!

@dschult

dschult commented Mar 28, 2024

Copy link
Copy Markdown
Member

Thanks!
Also, based on the test-failure that's showing up: we don't include type annotations in the NetworkX source code. People are working on type stubs elsewhere. But for this PR please take out the annotations.
:)

@lejansenGitHub

lejansenGitHub commented Apr 3, 2024 •

Copy link
Copy Markdown
Contributor Author

@dschult ready for re-review

i dont think it is ok to use:

        if hasattr(self.NODE_OK, "nodes"):
            return len(self.NODE_OK.nodes)

otherwise the __iter__ function doesnt rly make sense, since it checks for hasattr(self.NODE_OK, "nodes") but then still iterates and checks if nodes are in atlas.

if this is not needed i also would update the __iter__ function

@dschult

dschult commented Apr 3, 2024

Copy link
Copy Markdown
Member

I think the __iter__ function works fine in that case, though perhaps slower than necessary.
If NODE_OK has the attribute nodes then that attribute is a set of nodes so we can compute it's length. and the len computation is done. If nodes doesn't exist then we iterate, calling __iter__ which checks if nodes exists, which it doesn't, so it calls the NODE_OK function for each node to determine whether that node is in the _atlas being considered.

So, in the case with a nodes attribute, we are fast, and in the case without nodes we are accurate, but we check for the nodes attribute twice. Does this make sense?

To speed it up, change the last line of your change to do the iteration directly instead of having self do it. We've added enough to these __len__ methods that I feel iterating directly makes sense. So could you replace the last line of each of the two sections with something like?:

    return sum(1 for n in self._atlas if self.NODE_OK(n))

Thanks!

@lejansenGitHub

lejansenGitHub commented Apr 3, 2024 •

Copy link
Copy Markdown
Contributor Author

At the moment in main the length would be:
length of (n for n in self.NODE_OK.nodes if n in self._atlas) if self.NODE_OK has the nodes attr.

but in the new version if would be
len(self.NODE_OK.nodes) if self.NODE_OK has the nodes attr and does not have the length attr

so if self.NODE_OK has the nodes attr and at least one node of self.NODE_OK.nodes is not in self._atlas, we would change the functionality with this update. IMO functionality should not be change by this branch

@lejansenGitHub

Copy link
Copy Markdown
Contributor Author

@dschult review pls :)

@lejansenGitHub

Copy link
Copy Markdown
Contributor Author

@dschult pls i could rly need this change

@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 agree that we should not change functionality with this update.

Let's find a way to get the same answer as before -- but still check for a length attribute.

Comment thread networkx/classes/coreviews.py Resolved
@lejansenGitHub

lejansenGitHub commented Apr 12, 2024 •

Copy link
Copy Markdown
Contributor Author

@dschult
there is bug in panther_similarity. the way it is implemented depends on the order of the nodes in the nodeview of G

G = G.subgraph([node for node in G.nodes if node not in isolates]).copy()

this is why:
 and 2 * len(self.NODE_OK.nodes) < len(
        self._atlas
    )

cant be removed even so it is unnecessary

otherwise i think this is the final solution

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

Right -- we don't want to change the __iter__ order.

So leave the __iter__ methods unchanged. Forming the intersection self.NODE_OK.nodes & self._atlas.keys() inside the iter method creates a whole new object with all values anyway and we want to avoid that if all we are doing is iterating.

We do want the intersection for the len computation because we know we will be looking at all values, so it's better than summing over the iterations in this case.

There is also a new blank line at line 5. If that just slipped in during other changes let's take it out. If linting checks are asking for it, leave it in. :)

Thanks!

@dschult

dschult commented Apr 12, 2024

Copy link
Copy Markdown
Member

Why are we changing the first part of the __iter__ methods? It's not clear to me that they are the same. And without a check of the performance difference I'd be more comfortable leaving them as they were.

@lejansenGitHub

lejansenGitHub commented Apr 12, 2024 •

Copy link
Copy Markdown
Contributor Author

only __len__ is now changed

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

This change looks good to me. It'd be great to have more tests for views and filters, but I think that is a bigger issue than this PR.

I approve this PR

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

This seems fine to me, but let's add a comment to the changes for future readers - I find the changes confusing even with the context of the discussion on GH!

@dschult

dschult commented Apr 14, 2024

Copy link
Copy Markdown
Member

I added some comments and also expanded t he docstring of the show_nodes filter.
I'm sure it is not sufficient for easy understanding -- this code is pretty poorly documented.
But I hope it helps explain the optional nodes and length attributes on node filters

@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 @lejansenGitHub and @dschult !

@rossbar
rossbar merged commit e3507d6 into networkx:main Apr 14, 2024
@jarrodmillman jarrodmillman added this to the 3.4 milestone Apr 14, 2024
cvanelteren pushed a commit to cvanelteren/networkx that referenced this pull request Apr 22, 2024
…etworkx#7378)

Optimize FilterAdjacency.__len__ with cached length

Co-authored-by: Dan Schult <[email protected]>
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.

FilterAdjacency: __len__ is recalculated unnecessarily

5 participants