Skip to content

Add butterflies() to bipartite cluster module - #8591

Merged
rossbar merged 11 commits into
networkx:mainfrom
mmujtaba0085:add-butterfly-counting
May 22, 2026
Merged

rossbar merged 11 commits into
networkx:mainfrom
mmujtaba0085:add-butterfly-counting

Conversation

@mmujtaba0085

Copy link
Copy Markdown
Contributor

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

  • Returns {node: count} — number of butterflies each node participates in
  • nodes=None computes for all nodes; nodes=[...] filters returned keys
  • Total butterfly count can be obtained via:
  total = sum(butterflies(G).values()) // 4

Placement

Added to networkx.algorithms.bipartite.cluster as it directly relates to
robins_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 — add butterflies() and update __all__
  • networkx/algorithms/bipartite/__init__.py — export butterflies
  • networkx/algorithms/bipartite/tests/test_cluster.py — add TestButterflies (20 tests)
  • doc/reference/algorithms/bipartite.rst — register in docs

Tests

Adds TestButterflies with 20 cases covering:

  • Complete bipartite graphs (K₂,₂, K₃,₃, K₄,₄, K₅,₅) verified against brute-force ground truth
  • Disconnected graphs (no AmbiguousSolution)
  • Edge cases (empty graph, single edge, star, isolated nodes)
  • nodes= parameter behaviour matching nx.triangles
  • Non-bipartite input raises NetworkXError

@mmujtaba0085

Copy link
Copy Markdown
Contributor Author

Hi! It looks like the CI is waiting for a type: label.
Could a maintainer please add the appropriate label (likely type: feature)?

Thanks!

Copilot AI review requested due to automatic review settings April 5, 2026 19:05

This comment was marked as spam.

@jtorrents

Copy link
Copy Markdown
Member

Thanks @mmujtaba0085 . The algorithm choice, API design, and implementation reflect the discussion at #8589 well. Here are some review notes:

AI tools disclosure

Could 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 paper

The 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 wedge_cnt dict per start node and accumulates C(k,2) into a running total. The paper's Theorem 4 proves O(m) space precisely because it only stores this integer-valued dict.

The PR extends BFC-VP with per-node attribution; distributing butterfly credits to start, end, and middle nodes. This extension requires the wedge_mid data structure (a list of middle nodes per end node), which is not in the paper and is the reason the O(m) space claim doesn't hold.

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 _four_cycles

The priority-based wedge enumeration from BFC-VP is an improvement over what we currently have in _four_cycles(). Since _four_cycles is a private helper with a single call place in robins_alexander_clustering, I think we should remove it entirely and use butterflies() directly:

return sum(butterflies(G).values()) / L_3

This removes 17 lines of slower duplicate counting logic and makes the relationship between the two functions explicit. Note that butterflies() includes a bipartite check that _four_cycles lacks. This is actually an improvement since BFC-VP requires bipartite structure and robins_alexander_clustering currently silently gives wrong results on non-bipartite graphs. The O(n+m) cost of the check is negligible compared to the counting itself.

Docstring

The definition, parameters, examples, and cross-references are good. However, the Notes section needs work:

1. The algorithm description is too detailed. The 4-step numbered description with "start-vertex", "middle-vertices", "end-vertices" reads like a condensed version of the paper. A reader who wants that level of detail can go to the reference. The Notes section should briefly name the algorithm, cite the reference, and describe the complexity in plain terms. Compare with robins_alexander_clustering's docstring in the same file, which is much more concise.

2. Reference to private function. The Notes mention _four_cycles which is a private helper and shouldn't appear in a public docstring. If we go ahead with removing _four_cycles (see above), this reference becomes stale anyway.

3. Use "node" not "vertex". NetworkX convention is always using "node". The docstring uses "vertex" in several places. Please use "node" consistently.

Code comments

4. Reduce code comments significantly. The banner separators (# ------) and the multi-line text blocks below them should all go. They narrate the code rather than explaining anything non-obvious, and the variable names (priority, sorted_nbrs, wedge_count, wedge_mid) are descriptive enough on their own. If someone needs to understand the algorithm, the docstring and the paper reference are there.

Same for most inline comments: # all remaining neighbours have higher priority restates the if condition, # early termination adds nothing, # start-vertex / # end-vertex are obvious from context. Keep only # C(k, 2) butterflies for pair (u, w) and # each middle node pairs with k-1 others; I feel those explain non-obvious logic.

Bugs and tests

5. nodes= with missing nodes will KeyError

return {v: _bt[v] for v in nodes}

If nodes contains a node not in G, this raises KeyError. To match nx.triangles() you can use:

return {v: _bt[v] for v in G.nbunch_iter(nodes)}

6. Tautological test

test_sum_equals_four_times_total only checks that sum(bt.values()) == 4 * (sum(bt.values()) // 4). That is divisibility by 4.

7. Missing test for nodes= with absent node

Add a test for butterflies(G, nodes=[0, 99]) where 99 not in G to lock in the expected behavior (skip silently, matching nx.triangles).

Other

8. Unrelated whitespace changes

The PR touches several files with EOF newline fixes only. Please drop these from this PR: they add noise to the review and git blame.

9. Unrelated entry in See Also

latapy_clustering is listed in See Also but it measures a different quantity (per-node bipartite clustering based on neighbor overlap). It's not related to butterfly/square counting. Keep only robins_alexander_clustering and square_clustering, which have a direct relationship.

@mmujtaba0085

mmujtaba0085 commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@mmujtaba0085
mmujtaba0085 force-pushed the add-butterfly-counting branch from 774eb95 to 4934134 Compare April 12, 2026 16:55
@jtorrents

Copy link
Copy Markdown
Member

Thanks for the quick turnaround @mmujtaba0085 . A few follow-up points:

In robins_alexander_clustering

C_4 = sum(butterflies(G).values()) / 4
return (4.0 * C_4) / L_3

This divides by 4 and then multiplies by 4. Since each butterfly contributes to exactly 4 nodes, sum(butterflies(G).values()) is already 4 * C_4, so the whole thing simplifies to:

return sum(butterflies(G).values()) / L_3

Unrelated changes to other functions

A few useful comments in functions outside the scope of this PR have been removed:

latapy_clustering — # len(nbrs2)>0 was removed:

if cc > 0.0:  # len(nbrs2)>0
    cc /= len(nbrs2)

This comment explains why cc > 0.0 is equivalent to len(nbrs2) > 0 (cc stays at its initial 0.0 when nbrs2 is empty, so the check serves double duty). Without it, the reader wonders why we don't just check len(nbrs2) directly. Please restore it.

_threepaths — these lines were removed:

# Divide by two because we count each three path twice
# one for each possible starting point
return paths / 2

The / 2 is non-obvious without the explanation. This is exactly the kind of "why" comment that should stay. Please restore it.

My feedback about excessive comments was specifically about the new butterflies() function. Other functions in the file were not in scope for this PR and should be left alone.

Unrelated whitespace changes

The 5 unrelated files with EOF newline fixes are still present in the first commit. Please drop them from this PR.

- 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
@mmujtaba0085
mmujtaba0085 force-pushed the add-butterfly-counting branch from 4934134 to 00c912b Compare April 16, 2026 04:44
@mmujtaba0085

Copy link
Copy Markdown
Contributor Author

@jtorrents Thanks for the detailed review — I’ve addressed all the points (docstring clarification, nodes handling, cleanup, tests, and _four_cycles refactor) and pushed an updated commit. Please let me know if I missed anything or if further changes are needed.

@jtorrents

Copy link
Copy Markdown
Member

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

Copy link
Copy Markdown
Contributor Author

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.

@mmujtaba0085
mmujtaba0085 force-pushed the add-butterfly-counting branch 2 times, most recently from 2154cc7 to 564a728 Compare April 20, 2026 20:24
@mmujtaba0085
mmujtaba0085 requested a review from dschult April 20, 2026 20:39
- Remove unused itertools import (caused ruff/CI failure)
- Simplify priority using enumerate(G.degree())
- Use defaultdict for wedge_count and wedge_mid
@mmujtaba0085
mmujtaba0085 force-pushed the add-butterfly-counting branch from 564a728 to 409d15a Compare April 20, 2026 20:42

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

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.

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?

@mmujtaba0085 mmujtaba0085 Apr 27, 2026 •

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

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.... 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
@mmujtaba0085
mmujtaba0085 requested a review from dschult April 27, 2026 15:23

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

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

Comment on lines +104 to +134
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

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.

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 == total

But that's not necessary for this PR. can be done in a followup

@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, a few comments remaining to address and a merge conflict to resolve (just an import) but this is nearly there!

@rossbar

rossbar commented May 7, 2026

Copy link
Copy Markdown
Contributor

This one is close @mmujtaba0085 - one more round of addressing review comments should do it!

@mmujtaba0085

Copy link
Copy Markdown
Contributor Author

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

@mmujtaba0085
mmujtaba0085 requested review from dschult and rossbar May 16, 2026 10:31
Co-authored-by: Dan Schult <[email protected]>

@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 the remaining review comments that fell through the cracks. Thanks everyone!

@rossbar
rossbar merged commit c7d0f4b into networkx:main May 22, 2026
44 checks passed
@dschult dschult added this to the 3.7 milestone May 22, 2026
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.

[ENH] Add butterfly counting to bipartite module

5 participants