Repository navigation
Add all_triangles generator yielding all unique triangles in a graph - #8135
Conversation
…ient node ordering
rossbar
left a comment
There was a problem hiding this comment.
You raise a good point that the existing triangles functionality does not (AFAIK) have a way to pull out unique triangles, and I could see how that could be of interest in some applications. Personally, I would find a generator over unique triangles to be more compelling than a counting function (you can get the count by simply iterating over that generator).
I'm not sure whether this needs a new function though - here's how I'd do it with existing functionality:
sum(1 for _ in nx.simple_cycles(G, length_bound=3))|
Thanks again for the reponse @rossbar ! |
It would be more compelling to me at least! Re: naming, I'd propose |
|
Thank you for the feedback @rossbar ! I’ve gone ahead and implemented the generator version as all_triangles, following the naming pattern you mentioned. |
rossbar
left a comment
There was a problem hiding this comment.
Make sure to remove the extraneous changes to the other files that have nothing to do with this PR, which would be required before this gets any in-depth review.
Also - you will likely garner more traction from the community if you can provide stronger motivation for the addition. For example, what problem were you trying to solve where this functionality was necessary? Similarly, why not just use one of the other proposed methods - do we really need a new function for this?
331f7a6 to
ee07f41
Compare
ee07f41 to
1e14192
Compare
|
Thanks again for the feedback @rossbar . I have now removed all unrelated file changes from the PR to keep it clean. I have also addressed the issue regarding node comparability. Specifically, the implementation now uses str(node)-based ordering to ensure consistent and safe behavior regardless of node type, which avoids assumptions about comparability or orderability. |
all_triangles generator yielding all unique triangles in a graph
rossbar
left a comment
There was a problem hiding this comment.
I went ahead and took the liberty of changing the title of the PR to reflect the new direction!
I have the same comment as previously - I think an implementation that depends on ordering nodes is not a good fit for networkx. The workaround with str, while clever, still isn't general enough. The only requirement for NetworkX nodes is that they are hashable (and not None`). So users can do something like:
class MyNode:
def __init__(self):
passIf they don't specify a __str__ method, then by default they'll get a string with an arbitrary memory location in it:
>>> n = my_node()
>>> str(n)
'<__main__.my_node object at 0xfffeca82f4d0>'Obviously, sorting nodes based on arbitrary memory location is probably not what you want.
I encourage you to think about an algorithm that doesn't rely on ordering. As a hint, recall that the Graph adjacency structure is based on nested dictionaries, and dictionary keys support set operations.
|
Thank you @rossbar, I implemented now a generator that doesn't rely on any node ordering. Now the implementation yields the unique triangles by using purely the adjacency structure and set intersections. However, the current implementation might suffer a bit for larger graphs, and I will work on refining it to incorperate some form of visited ordering to avoid redundant checks. |
|
This implementation is storing all triangles, which means memory consumption is cubical on the amount of nodes in the worst case. I know in NetworkX you cannot depend on ordering the nodes but you can do a linear memory solution. You assign an incremental id to each node as you see them for the first time. Then you only yield the ones with form (u, v, w) where id(u) < id(v) < id(w). |
aa65be3 to
1dd99cc
Compare
|
You are right, the implementation did need an improvement. I was thinking of some sort of "visited" ordering, but your idea is simpler to execute, and so I implemented it. The function now assigns an ID to the nodes needed and then computes intersections while avoiding redundant checks. Thank you for the suggestion, @amcandio! |
| [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)] | ||
| """ | ||
| if nodes is None: | ||
| node_to_id = {node: i for i, node in enumerate(G.nodes())} |
There was a problem hiding this comment.
You can just iterate G
| node_to_id = {node: i for i, node in enumerate(G.nodes())} | |
| node_to_id = {node: i for i, node in enumerate(G)} |
| neighbor_sets = { | ||
| node: {nbr for nbr in G[node] if node_to_id[nbr] > node_to_id[node]} | ||
| for node in G.nodes() | ||
| } | ||
| for u in G.nodes(): | ||
| for v in neighbor_sets[u]: | ||
| common = neighbor_sets[u] & neighbor_sets[v] | ||
| for w in common: | ||
| yield u, v, w |
There was a problem hiding this comment.
This is consuming n^2 extra memory. You don't need to cache the nodes, for you could do:
| neighbor_sets = { | |
| node: {nbr for nbr in G[node] if node_to_id[nbr] > node_to_id[node]} | |
| for node in G.nodes() | |
| } | |
| for u in G.nodes(): | |
| for v in neighbor_sets[u]: | |
| common = neighbor_sets[u] & neighbor_sets[v] | |
| for w in common: | |
| yield u, v, w | |
| for u in G: | |
| for v in G[u]: | |
| if node_to_id[v] <= node_to_id[u]: | |
| continue | |
| for w in G[u] & G[v]: | |
| if node_to_id[w] <= node_to_id[v]: | |
| continue | |
| yield (u, v, w) |
There was a problem hiding this comment.
Yeah you are right, but for a large graph will they have similar performance? Also " G[u] & G[v] " is not supported for Atlas view
There was a problem hiding this comment.
Yes, it could even be faster due to less memory allocations. My bad on the &, we will have to use neighbors method
There was a problem hiding this comment.
But from my understanding, NetworkX has G[nodes] that we can't operate intersections with the neighbors of nodes, so I think building the neighbor_sets is needed either way. Edit: We can only intersect if we convert the node's neighbors into a set()
There was a problem hiding this comment.
Thank you for the suggestion, I went on and applied it!
|
Btw, let's update the description before shipping this |
|
@amcandio You mean we should make the description more in detail? Or sharpen it? |
|
I think the description is for a previous approach? |
|
@amcandio it was yes but I checked it and I thought it could fit to the new changes as well. However, I have changed it and I hope it's better now :) |
|
I'm confused. I don't see any triangle count method? |
|
@amcandio oh excuse me I thought you were referring to the doc string in the function. Yes I will change the description of the PR. Thank you! |
| >>> list(all_triangles(G)) | ||
| [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)] | ||
| """ | ||
| nodes_set = dict.fromkeys(G.nbunch_iter(nodes)) |
There was a problem hiding this comment.
Last optimization: you don't need to create this new dict if nodes is None. You can use G for that
There was a problem hiding this comment.
But we have to iterate in nodes_set either way since we have every option to operate in the same for loop. You mean I should put nodes_set = set(G) instead of the dict if nodes is None?
There was a problem hiding this comment.
I think the suggestion is to have node_set = G. Which also reminds us that node_set is not a set anymore and should probably be renamed. How about something like:
if nodes is None:
nodes = relevant_nodes = G
else:
nodes = dict.fromkeys(G.nbunch_iter(nodes))
relevant_nodes = chain(...
)
node_to_id = {node: i for i, node in enumerate(relevant_nodes)}
for u in nodes:
...And we should probably rename the input parameter from nodes to nbunch to make it clear that we are using the standard networkx handling of a collection of nodes (nbunch is described in the NetworkX glossary).
There was a problem hiding this comment.
Thank you. Fixed it now.
Peiffap
left a comment
There was a problem hiding this comment.
This is nice! Some comments below, but feel free to push back if you disagree :).
Can this be used to speed up nx.simple_cycles for the undirected, length_bound = 3 case? It would be nice to benchmark that... It might also be interesting to add it to the See Also section for that function in that case. This should probably all be done in a separate PR, though, if we decide it's worthwhile.
| @nx._dispatchable | ||
| def all_triangles(G, nodes=None): | ||
| """ | ||
| Yields all unique triangles in an undirected graph using a node ordering strategy. |
There was a problem hiding this comment.
The implementation details should be in a Notes section imo, where it can be used to justify an asymptotic run time complexity.
| Yields all unique triangles in an undirected graph using a node ordering strategy. | |
| Yields all unique triangles in an undirected graph. |
|
|
||
| nodes : node, iterable of nodes, or None (default=None) | ||
| If a node or iterable of nodes is given, only triangles involving those nodes are yielded. | ||
| If None, yields all unique triangles in the graph. |
There was a problem hiding this comment.
| If None, yields all unique triangles in the graph. | |
| If ``None``, yields all unique triangles in the graph. |
| if node_to_id.get(w, -1) <= v_id: | ||
| continue | ||
| yield u, v, w |
There was a problem hiding this comment.
| if node_to_id.get(w, -1) <= v_id: | |
| continue | |
| yield u, v, w | |
| if node_to_id.get(w, -1) > v_id: | |
| yield u, v, w |
| >>> list(all_triangles(G)) | ||
| [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)] |
There was a problem hiding this comment.
Should this (and the tests which use lists too) use sets instead? There isn't any guarantee in the function description about the order in which tuples are returned, so if the implementation changes at any point, it'd be nice to not have that be a breaking change.
There was a problem hiding this comment.
I completely agree. If I am not mistaken, the node_to_id ordering is based on how the graph is inserted, right? If I build manually a graph and I do G.add_nodes_from([2, 0, 5]), I think the triangle (0,2,5) will be yielded like (2,0,5). I am not 100% sure so let me know!
There was a problem hiding this comment.
That's actually a separate point I believe—there are two levels at which ordering can matter:
- This note is about the order in which the tuples are returned, e.g.
all_triangles(G)could yield(0, 1, 2)then(0, 1, 3)etc., but yielding them in a different order would still be correct—making the examples and tests use lists means this order is somehow "checked", when I don't believe it should be. - The order of nodes inside a tuple is also relevant, and another comment I made addresses that question. A tuple
(u, v, w)can also be given as(v, w, u), etc. Since technically for an undirected triangle, all 6 node orderings are valid (unlike for a cycle of length 4, where the order matters), this could also be a set, but I think by analogy withnx.simple_cycles, an argument can be made that it's perhaps more consistent to return a tuple. I'd be curious to hear other opinions on this.
There was a problem hiding this comment.
The tests and the example have a specific ordering on how the graph is built, and yes I agree that this can give the impression that the triangles are always yielded in a specific order that the human eye sees, which might not be the case. So I think I do need to remove the mention of u < v < w from the docstring and make the tests order-independent (using sets or frozensets).
There was a problem hiding this comment.
What I could also do is to apply tests where the graphs are built with unorthodox ordering, and use there sets.
There was a problem hiding this comment.
Maybe returning a tuple (u, v, w) but running the tests with set (something like assert {set(t) for t in nx.all_triangles(G)} == {{u1, v1, w1}, {u2, v2, w2}, ...} makes the most sense then!
There was a problem hiding this comment.
Okay perfect, will apply it now as well then!
| Yields | ||
| ------- | ||
| tuple | ||
| A tuple of three nodes forming a triangle (u, v, w), with u < v < w based on internal ordering. |
There was a problem hiding this comment.
Iiuc, someone calling the function won't know anything about this ordering (nor is it certain to stay the same in the future), so I'm not sure it's good to specify.
| A tuple of three nodes forming a triangle (u, v, w), with u < v < w based on internal ordering. | |
| A tuple of three nodes forming a triangle ``(u, v, w)``. |
| An undirected graph. Self-loops and multiple edges are ignored. | ||
|
|
||
| nodes : node, iterable of nodes, or None (default=None) | ||
| If a node or iterable of nodes is given, only triangles involving those nodes are yielded. |
There was a problem hiding this comment.
Wording nit: it's unclear from this sentence whether only triangles that have all of their nodes in nodes are considered, or only triangles that have at least one of their nodes in nodes (or only triangles that have all of the nodes in nodes—although that would be an unlikely interpretation...).
| If a node or iterable of nodes is given, only triangles involving those nodes are yielded. | |
| If a node or iterable of nodes is given, only triangles with all their nodes in `nodes` are yielded. |
There was a problem hiding this comment.
I wasn't very specific with it, I will describe it more concisely now, thank you! However your suggestion doesn't completely apply to what the nbunch is actually for. If an iterable of nodes is given, the triangles that are actually yielded are the ones that contain atleast one of the nodes from nbunch.
There was a problem hiding this comment.
Welp... That illustrates my point I suppose!
| Parameters | ||
| ---------- | ||
| G : NetworkX graph | ||
| An undirected graph. Self-loops and multiple edges are ignored. |
There was a problem hiding this comment.
Minor nit: I believe this doesn't matter (self-loops and multiedges shouldn't affect the result), and it might just end up confusing users ("will this function work for multigraphs?").
| An undirected graph. Self-loops and multiple edges are ignored. | |
| An undirected graph. |
| from ..cluster import all_triangles | ||
|
|
There was a problem hiding this comment.
I think this won't be necessary anymore once the new function is properly exposed in the top-level namespace. You'll be able to just call nx.all_triangles then.
| def test_all_triangles_no_duplicates(): | ||
| G = nx.complete_graph(4) # 4 nodes, 4-choose-3 = 4 triangles | ||
| triangles = list(all_triangles(G)) | ||
| assert len(triangles) == 4 |
There was a problem hiding this comment.
This is redundant if test_all_triangles_complete_graph_exact is kept.
|
I was reviewing this before you made the latest changes—let's make sure my suggestions don't undo some of the other changes you've made! |
72566f6 to
3da6717
Compare
|
Thank you for all the suggestions @Peiffap ! I went ahead and applied every single one of them.
|
Peiffap
left a comment
There was a problem hiding this comment.
Nice! Some more minor comments. We should also make sure the function gets added to __all__ on L9–L16! That'll enable using it as nx.all_triangles in tests without having to import anything.
| An undirected graph. | ||
|
|
||
| nbunch : node, iterable of nodes, or None (default=None) | ||
| If a node or iterable of nodes, only triangles involving at least one node in nbunch are yielded. |
There was a problem hiding this comment.
| If a node or iterable of nodes, only triangles involving at least one node in nbunch are yielded. | |
| If a node or iterable of nodes, only triangles involving at least one node in `nbunch` are yielded. |
| Yields | ||
| ------- | ||
| tuple | ||
| A tuple of three nodes forming a triangle ``(u, v, w)``. |
There was a problem hiding this comment.
| A tuple of three nodes forming a triangle ``(u, v, w)``. | |
| A tuple of three nodes forming a triangle ``(u, v, w)``. |
There was a problem hiding this comment.
I need to be more careful with such details, thank you!
| Notes | ||
| ----- | ||
| This algorithm ensures each triangle is yielded once using an internal node ordering. | ||
| It runs in O(m * d) time in the worst case, where m is the number of edges and d is the maximum degree. |
There was a problem hiding this comment.
Where did you get this complexity? Shouldn't it be O(m * d**2) because you compute a set intersection in the loop on L309?
| It runs in O(m * d) time in the worst case, where m is the number of edges and d is the maximum degree. | |
| It runs in ``O(m * d)`` time in the worst case, where ``m`` is the number of edges and ``d`` is the maximum degree. |
There was a problem hiding this comment.
A set intersection of two sets of size at most d costs O(d) and not O(d**2). I am not doing an inner nested scan over both neighbor lists since python’s set intersection does the efficient hashed lookup approach.
There was a problem hiding this comment.
Ah so is it because we have the continue statement that we only end looping over the intersection of neighbors once? Because from my understanding, we are looping over all nodes, then all neighbors of that node, then all nodes in the intersection of the neighbors of both.
|
Thank you @Peiffap. I have now added the |
rossbar
left a comment
There was a problem hiding this comment.
Generally LGTM, thanks @georakom . The one major thing that I still think needs to be hammered out is the semantics for multigraphs; i.e. what happens when there are multiple edges between two nodes.
For example:
>>> G = nx.MultiGraph()
>>> G.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 2)])
>>> list(nx.all_triangles(G))I can see three possible outputs here:
[(0, 1, 2)]- you get only one collection of nodes corresponding to the triangle[(0, 1, 2), (0, 1, 2)]- you get one collection of nodes for each edge-unique triangleNetworkXNotImplemented- we can punt on the decision and just raise.
My preference is option 1.. Since the triangles are represented by a collection of nodes (rather than edges), I think it makes sense to treat that collection as the unique unit and leave it to the user to reconstruct the edges of triangles (if they want them) themselves. This is consistent with the treatment of e.g. paths and cycles in the library. Assuming others are okay with these semantics, I think the only things we'd need to do is:
- Document this behavior for multigraphs, and
- Add a test.
I see the test for MultiGraph at the bottom of the test file, but it doesn't actually have multiedges. It should be easy to expand that test to add multi-edges and verify that the behavior is correct!
| triangles = list(nx.all_triangles(G)) | ||
| assert set(map(frozenset, triangles)) == {frozenset({"a", "b", "c"})} |
There was a problem hiding this comment.
Just a nit, but I prefer set comprehension:
| triangles = list(nx.all_triangles(G)) | |
| assert set(map(frozenset, triangles)) == {frozenset({"a", "b", "c"})} | |
| expected = {frozenset({"a", "b", "c"})} | |
| assert {frozenset(t) for t in nx.all_triangles)} == expected |
| import pytest | ||
|
|
||
| import networkx as nx | ||
| from networkx.exception import NetworkXNotImplemented |
There was a problem hiding this comment.
| from networkx.exception import NetworkXNotImplemented |
| def test_all_triangles_directed_graph(): | ||
| G = nx.DiGraph() | ||
| G.add_edges_from([(0, 1), (1, 2), (2, 0)]) | ||
| with pytest.raises(NetworkXNotImplemented): |
There was a problem hiding this comment.
| with pytest.raises(NetworkXNotImplemented): | |
| with pytest.raises(nx.NetworkXNotImplemented): |
|
Thanks @rossbar . Yes the function's behavior on multigraphs is indeed the option 1, since I am certain that |
Implemented an
all_trianglesfunction that efficiently yields all unique triangles in an undirected graph.The algorithm follows a "Forward" principle by enforcing a node ordering to avoid redundant comparisons and double-counting. For each node u, it examines neighbors v > u and yields triangles formed by the intersection of u's and v's neighbors that are greater than v.
The function optionally supports a nodes parameter, restricting enumeration to triangles where all three nodes are in the specified set.
This is my first pull request here and I would gladly appreciate any comments and improvements!