Skip to content

Add all_triangles generator yielding all unique triangles in a graph - #8135

Merged
dschult merged 24 commits into
networkx:mainfrom
georakom:fast-triangle-count
Jul 25, 2025
Merged

dschult merged 24 commits into
networkx:mainfrom
georakom:fast-triangle-count

Conversation

@georakom

@georakom georakom commented Jul 7, 2025 •

Copy link
Copy Markdown
Contributor

Implemented an all_triangles function 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!

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

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))

@georakom

georakom commented Jul 7, 2025 •

Copy link
Copy Markdown
Contributor Author

Thanks again for the reponse @rossbar !
I took a closer look at nx.simple_cycles, and while it definitely works in practice, it's not an ideal tool for triangle enumeration in practice. The function is built for general purpose cycle enumeration, which can bring in quite a bit of overhead, especially for large or undirected graphs. Also, it explores components and paths far beyond what's needed for triangle detection. In my use case, I found that a dedicated triangle generator is an order of magnitude faster, and more memory efficient.
I'd be happy to modify the PR to implement a unique_triangles(G) generator instead of a counting function, if that would better align with NetworkX’s design.

@rossbar

rossbar commented Jul 7, 2025

Copy link
Copy Markdown
Contributor

I'd be happy to modify the PR to implement a unique_triangles(G) generator instead of a counting function, if that would better align with NetworkX’s design.

It would be more compelling to me at least! Re: naming, I'd propose all_triangles which matches a naming pattern used elsewhere, see e.g. all_triads. In fact, that's another bit of existing functionality that meets this need: nx.all_triads(G.to_directed()).

@georakom

georakom commented Jul 7, 2025

Copy link
Copy Markdown
Contributor Author

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

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?

Comment thread networkx/algorithms/cluster.py Resolved
@georakom
georakom force-pushed the fast-triangle-count branch from 331f7a6 to ee07f41 Compare July 8, 2025 09:10
@georakom
georakom force-pushed the fast-triangle-count branch from ee07f41 to 1e14192 Compare July 8, 2025 16:09
@georakom

georakom commented Jul 8, 2025

Copy link
Copy Markdown
Contributor Author

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.
As for motivation, I am currently doing a thesis on triangle counting in undirected graphs (in Python), and during my research, I explored various enumeration techniques. This led me to try implementing one directly in NetworkX, adapted to follow the library’s design principles.
I'm happy to further adjust the code or design if needed.

@rossbar rossbar changed the title Add triangle_count function that returns total triangle count Add all_triangles generator yielding all unique triangles in a graph Jul 11, 2025

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

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):
        pass

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

@georakom

Copy link
Copy Markdown
Contributor Author

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.

@amcandio

amcandio commented Jul 12, 2025 •

Copy link
Copy Markdown
Contributor

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

@georakom
georakom force-pushed the fast-triangle-count branch from aa65be3 to 1dd99cc Compare July 12, 2025 21:59
@georakom

Copy link
Copy Markdown
Contributor Author

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!

Comment thread networkx/algorithms/cluster.py Outdated
[(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())}

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.

You can just iterate G

Suggested change
node_to_id = {node: i for i, node in enumerate(G.nodes())}
node_to_id = {node: i for i, node in enumerate(G)}

Comment thread networkx/algorithms/cluster.py Outdated
Comment on lines +280 to +288
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

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 is consuming n^2 extra memory. You don't need to cache the nodes, for you could do:

Suggested change
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)

@georakom georakom Jul 13, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@amcandio amcandio Jul 13, 2025 •

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.

Yes, it could even be faster due to less memory allocations. My bad on the &, we will have to use neighbors method

@georakom georakom Jul 13, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the suggestion, I went on and applied it!

Comment thread networkx/algorithms/cluster.py Resolved
Comment thread networkx/algorithms/cluster.py Resolved
Comment thread networkx/algorithms/cluster.py Resolved
@amcandio

Copy link
Copy Markdown
Contributor

Btw, let's update the description before shipping this

@georakom

Copy link
Copy Markdown
Contributor Author

@amcandio You mean we should make the description more in detail? Or sharpen it?

@amcandio

Copy link
Copy Markdown
Contributor

I think the description is for a previous approach?

@georakom

georakom commented Jul 15, 2025 •

Copy link
Copy Markdown
Contributor Author

@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 :)

@amcandio

Copy link
Copy Markdown
Contributor

I'm confused. I don't see any triangle count method?

@georakom

Copy link
Copy Markdown
Contributor Author

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

Comment thread networkx/algorithms/cluster.py Outdated
>>> list(all_triangles(G))
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
"""
nodes_set = dict.fromkeys(G.nbunch_iter(nodes))

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.

Last optimization: you don't need to create this new dict if nodes is None. You can use G for that

@georakom georakom Jul 16, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. Fixed it now.

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

Comment thread networkx/algorithms/cluster.py Outdated
@nx._dispatchable
def all_triangles(G, nodes=None):
"""
Yields all unique triangles in an undirected graph using a node ordering strategy.

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.

The implementation details should be in a Notes section imo, where it can be used to justify an asymptotic run time complexity.

Suggested change
Yields all unique triangles in an undirected graph using a node ordering strategy.
Yields all unique triangles in an undirected graph.

Comment thread networkx/algorithms/cluster.py Outdated

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.

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.

Suggested change
If None, yields all unique triangles in the graph.
If ``None``, yields all unique triangles in the graph.

Comment thread networkx/algorithms/cluster.py Outdated
Comment on lines +309 to +311
if node_to_id.get(w, -1) <= v_id:
continue
yield u, v, w

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.

Suggested change
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

Comment thread networkx/algorithms/cluster.py Outdated
Comment on lines +282 to +283
>>> list(all_triangles(G))
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]

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.

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.

@georakom georakom Jul 16, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

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.

That's actually a separate point I believe—there are two levels at which ordering can matter:

  1. 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.
  2. 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 with nx.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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I could also do is to apply tests where the graphs are built with unorthodox ordering, and use there sets.

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.

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!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay perfect, will apply it now as well then!

Comment thread networkx/algorithms/cluster.py Outdated
Yields
-------
tuple
A tuple of three nodes forming a triangle (u, v, w), with u < v < w based on internal ordering.

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.

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.

Suggested change
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)``.

Comment thread networkx/algorithms/cluster.py Outdated
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.

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.

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

Suggested change
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.

@georakom georakom Jul 16, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

Welp... That illustrates my point I suppose!

Comment thread networkx/algorithms/cluster.py Outdated
Parameters
----------
G : NetworkX graph
An undirected graph. Self-loops and multiple edges are ignored.

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.

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?").

Suggested change
An undirected graph. Self-loops and multiple edges are ignored.
An undirected graph.

Comment on lines +5 to +6
from ..cluster import all_triangles

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

Comment on lines +127 to +130
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

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 is redundant if test_all_triangles_complete_graph_exact is kept.

@Peiffap

Peiffap commented Jul 16, 2025

Copy link
Copy Markdown
Member

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!

@georakom
georakom force-pushed the fast-triangle-count branch from 72566f6 to 3da6717 Compare July 16, 2025 22:17
@georakom

Copy link
Copy Markdown
Contributor Author

Thank you for all the suggestions @Peiffap ! I went ahead and applied every single one of them.

  • Changed the comments and put notes for implementation description and complexity
  • Applied set-based comparisons in the tests
  • Added the tests you recommended!
    I am not very experienced so I added every single suggestion you gave manually just in case it doesn't undo other changes, I hope that's fine :) !

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

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.

Comment thread networkx/algorithms/cluster.py Outdated
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.

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.

Suggested change
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.

Comment thread networkx/algorithms/cluster.py Outdated
Yields
-------
tuple
A tuple of three nodes forming a triangle ``(u, v, w)``.

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.

Suggested change
A tuple of three nodes forming a triangle ``(u, v, w)``.
A tuple of three nodes forming a triangle ``(u, v, w)``.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to be more careful with such details, thank you!

Comment thread networkx/algorithms/cluster.py Outdated
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.

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.

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?

Suggested change
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.

@georakom georakom Jul 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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.

@georakom

georakom commented Jul 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Thank you @Peiffap. I have now added the all_triangles function to __all__ and also fixed the issues in the comments!

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

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:

  1. [(0, 1, 2)] - you get only one collection of nodes corresponding to the triangle
  2. [(0, 1, 2), (0, 1, 2)] - you get one collection of nodes for each edge-unique triangle
  3. NetworkXNotImplemented - 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:

  1. Document this behavior for multigraphs, and
  2. 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!

Comment on lines +90 to +91
triangles = list(nx.all_triangles(G))
assert set(map(frozenset, triangles)) == {frozenset({"a", "b", "c"})}

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.

Just a nit, but I prefer set comprehension:

Suggested change
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

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.

Suggested change
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):

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.

Suggested change
with pytest.raises(NetworkXNotImplemented):
with pytest.raises(nx.NetworkXNotImplemented):

@georakom

Copy link
Copy Markdown
Contributor Author

Thanks @rossbar . Yes the function's behavior on multigraphs is indeed the option 1, since I am certain that G._adj[u].keys() returns only unique neighbors (even in a MultiGraph), ignoring multiple edges, and also, as you have mentioned, the intersection is a set of nodes and not edges. For that reason, I just documented the behavior for multigraphs, and have also updated the tests accordingly!

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

I took the liberty of pushing up a few minor changes related to formatting etc. but this LGTM! Thanks @georakom and @amcandio + @Peiffap for the detailed review!

@dschult
dschult merged commit eea6802 into networkx:main Jul 25, 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.

6 participants