Repository navigation
Add butterflies() to bipartite cluster module - #8591
Conversation
|
Hi! It looks like the CI is waiting for a Thanks! |
|
Thanks @mmujtaba0085 . The algorithm choice, API design, and implementation reflect the discussion at #8589 well. Here are some review notes: AI tools disclosureCould you clarify whether AI tools were used in preparing this PR? See Automated Contributions Policy. Reading the code and the comments, my impression is that they are mostly (completely?) LLM generated. I'd like the input of core maintainers here. I think that the algorithm is a nice addition to NetworkX and would like do my best reviewing it carefully to make sure that its accurate and sound. I assume you already reviewed if LLMs were indeed used. Algorithm: clarify relationship to the paperThe docstring and Notes say this implements "BFC-VP from Wang et al. [2]", but that's not quite accurate. The paper's Algorithm 2 (BFC-VP) computes only a global butterfly count (a single integer X_G). It uses a simple The PR extends BFC-VP with per-node attribution; distributing butterfly credits to start, end, and middle nodes. This extension requires the I've verified it gives correct results against brute-force enumeration on several graphs, but the docstring should be honest about what comes from the paper (the priority-based wedge enumeration) and what is a custom extension (the per-node attribution). Refactoring
|
|
On AI tool usage: yes, I used AI assistance during this contribution — primarily for drafting the docstring and structuring the benchmark script. I reviewed the implementation carefully, validated it against brute-force enumeration on multiple graph types, and read the Wang et al. (2023) paper directly to understand the algorithm. The C++ parallel butterfly counter at github.com/mmujtaba0085/parallel-butterfly-counter is my own prior work, which informed this Python port. Design decisions and benchmark analysis were done independently. Happy to discuss any part of the implementation in detail. |
774eb95 to
4934134
Compare
|
Thanks for the quick turnaround @mmujtaba0085 . A few follow-up points: In
|
- Implement vertex-priority wedge enumeration (Wang et al., 2023) - Add per-node attribution (extension of BFC-VP) - Improve docstring and terminology clarity - Fix nodes= handling and tests Closes networkx#8589
4934134 to
00c912b
Compare
|
@jtorrents Thanks for the detailed review — I’ve addressed all the points (docstring clarification, nodes handling, cleanup, tests, and |
|
Thanks @mmujtaba0085 , all things addressed. I think it's a good addition to NetworkX. I'll leave it for core maintainers to take a final look. |
dschult
left a comment
There was a problem hiding this comment.
This looks pretty good ... I have a bunch of minor comments below. push back if it isn't reasonable, and ask if it isn't clear.
- Add alternate names (square, four-cycle) to robins_alexander docstring - Add (default: all nodes) to nodes parameter description - Simplify empty-graph early return to match end-of-function style - Simplify priority construction using enumerate(G.degree()) - Use priority.__getitem__ instead of lambda in sorted_nbrs - Use dict.fromkeys(G, 0) and for u in G: instead of G.nodes() - Move inline comments above their lines per style feedback
|
I’ve pushed updates addressing the suggestions, including stylistic changes, and ensuring deterministic behaviour across environments. Please let me know if anything still needs adjustment. P.S. I have responded on above feedback review by @dschult. Please have a look at that as well. |
2154cc7 to
564a728
Compare
- Remove unused itertools import (caused ruff/CI failure) - Simplify priority using enumerate(G.degree()) - Use defaultdict for wedge_count and wedge_mid
564a728 to
409d15a
Compare
dschult
left a comment
There was a problem hiding this comment.
This is looking pretty good.
I'm diving into the algorithm code on this review.
I wonder why none of the functions in this module seems to rule out directed graphs. But just to keep myself sane -- does this algorithm work with directed graphs? Should we have the decorator @nx.not_implemented_for("directed")? Or is there something I am missing.
| if priority[v] >= pu: | ||
| break | ||
| for w in sorted_nbrs[v]: | ||
| if priority[w] >= pu: |
There was a problem hiding this comment.
Can you easily explain why this compares priority with pu and not with pv?
Why would it be right to keep both v and w >=u but not keep w>= v?
There was a problem hiding this comment.
The condition priority[w] >= pu (not >= pv) is correct because the goal is to count each butterfly exactly once, assigned to its highest-priority node u. For a butterfly with four nodes, there is exactly one node with the highest priority. By requiring both v (middle) and w (end) to have lower priority than u, we guarantee that u is that unique highest-priority node, so the butterfly is counted exactly once in u's iteration. We don't additionally require priority[w] < priority[v] because that would exclude butterflies where w > v but both are below u — those butterflies are still counted correctly under u.
There was a problem hiding this comment.
Nice.... working through the 4-cycle graph (below) helped me see how the counting works.
It's a little strange because pairs of wedges give one butterfly.
Thanks!!
But I have another question: Can we track wedge_mid and just get k from len(wedge_mid)? It definitely saves space -- and I think it would save time... fewer dict lookups and only one place to assign to.
for w, mids in wedge_mids.items():
k = len(mids)
... # same stuff here as now
for v in mids: # instead of for v in wedge_mids[w]
...Example (TL;DR): cycle_graph(4). there is one butterfly. node "u=0" has lowest priority value. So it finds no wedges. "u=1" also finds no wedges. "u=2" finds (2, 1, 0). So the wedge_count is {0: 1} and the wedge_mid is {0: [1]}. This results in zero change for _bt. Finally for "u=3" we get wedges (3, 2, 1) and (3, 0, 1) so wedge_count is {1: 2} and wedge_mid` is {1: [0, 2]}. So we get _bt = {0: 1, 1: 1, 2: 1, 3: 1} in the end.
- Import not_implemented_for from networkx.utils.decorators - Add @not_implemented_for(directed) to butterflies() - Remove explicit is_bipartite() check (per bipartite subpackage convention) - Remove Raises section from docstring
dschult
left a comment
There was a problem hiding this comment.
I have some minor comments about the tests and docs.
And one optimization suggestion. Its up to you on all these.
I approve this PR with or without these suggestions.
Thanks @mmujtaba0085 !!
| if priority[v] >= pu: | ||
| break | ||
| for w in sorted_nbrs[v]: | ||
| if priority[w] >= pu: |
There was a problem hiding this comment.
Nice.... working through the 4-cycle graph (below) helped me see how the counting works.
It's a little strange because pairs of wedges give one butterfly.
Thanks!!
But I have another question: Can we track wedge_mid and just get k from len(wedge_mid)? It definitely saves space -- and I think it would save time... fewer dict lookups and only one place to assign to.
for w, mids in wedge_mids.items():
k = len(mids)
... # same stuff here as now
for v in mids: # instead of for v in wedge_mids[w]
...Example (TL;DR): cycle_graph(4). there is one butterfly. node "u=0" has lowest priority value. So it finds no wedges. "u=1" also finds no wedges. "u=2" finds (2, 1, 0). So the wedge_count is {0: 1} and the wedge_mid is {0: [1]}. This results in zero change for _bt. Finally for "u=3" we get wedges (3, 2, 1) and (3, 0, 1) so wedge_count is {1: 2} and wedge_mid` is {1: [0, 2]}. So we get _bt = {0: 1, 1: 1, 2: 1, 3: 1} in the end.
| def test_k22_total(self): | ||
| G = self.make([0, 1], [2, 3], [(0, 2), (0, 3), (1, 2), (1, 3)]) | ||
| assert sum(bipartite.butterflies(G).values()) // 4 == 1 | ||
|
|
||
| def test_k33_total(self): | ||
| G = nx.complete_bipartite_graph(3, 3) | ||
| assert sum(bipartite.butterflies(G).values()) // 4 == 9 | ||
|
|
||
| def test_k44_total(self): | ||
| G = nx.complete_bipartite_graph(4, 4) | ||
| assert sum(bipartite.butterflies(G).values()) // 4 == 36 | ||
|
|
||
| def test_k55_total(self): | ||
| G = nx.complete_bipartite_graph(5, 5) | ||
| assert sum(bipartite.butterflies(G).values()) // 4 == 100 | ||
|
|
||
| def test_empty_graph(self): | ||
| G = self.make([0, 1], [2, 3], []) | ||
| assert all(v == 0 for v in bipartite.butterflies(G).values()) | ||
|
|
||
| def test_single_edge(self): | ||
| G = self.make([0], [1], [(0, 1)]) | ||
| assert sum(bipartite.butterflies(G).values()) == 0 | ||
|
|
||
| def test_path_no_butterfly(self): | ||
| G = self.make([0, 1], [2, 3], [(0, 2), (1, 2), (1, 3)]) | ||
| assert sum(bipartite.butterflies(G).values()) // 4 == 0 | ||
|
|
||
| def test_star_no_butterfly(self): | ||
| G = self.make([0], [1, 2, 3, 4], [(0, 1), (0, 2), (0, 3), (0, 4)]) | ||
| assert sum(bipartite.butterflies(G).values()) // 4 == 0 |
There was a problem hiding this comment.
These tests are good candidates for pytest parametrization. Something like:
def make(...): # move this outside the class.
# can still have the class (or not)
class TestButterflies:
@pytest.mark.parametrize("G,total", [
(make([0, 1], [2, 3], [(0, 2), ...]), 1),
(nx.complete_bipartite_graph(3, 3), 9
.... many lines of (G, total) pairings
]
def test_total(self, G, total):
assert sum(bipartitie.butterflies(G) // 4 == totalBut that's not necessary for this PR. can be done in a followup
Co-authored-by: Dan Schult <[email protected]>
rossbar
left a comment
There was a problem hiding this comment.
Generally LGTM, a few comments remaining to address and a merge conflict to resolve (just an import) but this is nearly there!
|
This one is close @mmujtaba0085 - one more round of addressing review comments should do it! |
|
@dschult and @rossbar Thank you for the assistance and patience throughout this PR. This was actually my first open-source PR overall, and I learned a lot from the review process. Apologies for the delay in making the final changes and responses over the past couple of weeks — I’m currently a final-year CS student and was occupied with my FYP and semester projects. @dschult I also haven’t forgotten the suggestions you mentioned earlier, and I plan to revisit and work on those improvements in the future as well. Really enjoyed contributing and interacting with everyone here — I’d love to stay connected with the community and continue contributing going forward. |
Co-authored-by: Dan Schult <[email protected]>
rossbar
left a comment
There was a problem hiding this comment.
I took the liberty of pushing up the remaining review comments that fell through the cracks. Thanks everyone!
Closes #8589
Summary
Adds
butterflies(G, nodes=None)for per-node butterfly counting in bipartite graphs.A butterfly is a complete bipartite subgraph K_{2,2} — the bipartite analogue of a
triangle in unipartite graphs.
API
Matches
nx.triangles():{node: count}— number of butterflies each node participates innodes=Nonecomputes for all nodes;nodes=[...]filters returned keysPlacement
Added to
networkx.algorithms.bipartite.clusteras it directly relates torobins_alexander_clustering, which uses the butterfly count as its numerator.Algorithm
Wedge-based counting with degree ranking (Sanei-Mehri et al., KDD 2018).
Time complexity: O(Σ_v d(v)²), Space: O(E).
Changes
networkx/algorithms/bipartite/cluster.py— addbutterflies()and update__all__networkx/algorithms/bipartite/__init__.py— exportbutterfliesnetworkx/algorithms/bipartite/tests/test_cluster.py— addTestButterflies(20 tests)doc/reference/algorithms/bipartite.rst— register in docsTests
Adds
TestButterflieswith 20 cases covering:AmbiguousSolution)nodes=parameter behaviour matchingnx.trianglesNetworkXError