From b6fc318de1c8fd5c243de820da247cec7d35a883 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 20:37:34 -0600 Subject: [PATCH] Add robins_alexander_clustering and butterflies Robins and Alexander's clustering is four times the four-cycles over the paths of three edges whose ends differ. With the nodes ranked by degree, a four-cycle has one node above its other three and one node opposite it, and the k paths of two edges from the top node down to the opposite one close C(k, 2) of its cycles, each counted once. A masked plus_pair product counts those paths, taking the rows in blocks of a bounded number of paths so that a dense graph's products stay small, and a node's own count, for butterflies, adds what it closes as top, opposite or middle node. The three-paths are a sum over the edges of (d_u - 1)(d_v - 1), less three for each triangle. Neither needs the bipartition, as in NetworkX, so a graph that is not bipartite gets NetworkX's numbers. The counts are added in int64 and divided once, as NetworkX divides, so the value is NetworkX's to the bit, and the integer 0 where NetworkX returns that. Where a bound on the counts, half the sum of the squares of each node's walks of two steps, reaches 2**62, the call raises OverflowError after the conversion. Graphs with self-loops, which NetworkX's loops read as neighbors, and directed graphs, which NetworkX 3.6.1 counts by successors and 3.7 refuses, are left to NetworkX. butterflies is NetworkX 3.7's, and its nodes follow NetworkX's nbunch rules. --- README.md | 4 + _nx_graphblas/__init__.py | 4 + _nx_graphblas/core.py | 10 + graphblas_algorithms/algorithms/__init__.py | 1 + .../algorithms/bipartite/__init__.py | 6 + .../algorithms/bipartite/cluster.py | 147 +++++++ graphblas_algorithms/interface.py | 5 + graphblas_algorithms/nxapi/__init__.py | 2 + .../nxapi/bipartite/__init__.py | 4 + .../nxapi/bipartite/cluster.py | 42 ++ .../nxapi/tests/test_bipartite_four_cycles.py | 362 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 2 + pyproject.toml | 2 + 13 files changed, 591 insertions(+) create mode 100644 graphblas_algorithms/algorithms/bipartite/__init__.py create mode 100644 graphblas_algorithms/algorithms/bipartite/cluster.py create mode 100644 graphblas_algorithms/nxapi/bipartite/__init__.py create mode 100644 graphblas_algorithms/nxapi/bipartite/cluster.py create mode 100644 graphblas_algorithms/nxapi/tests/test_bipartite_four_cycles.py diff --git a/README.md b/README.md index 1bc06b5..f00a2c1 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,10 @@ dispatch pattern shown above. ``` graphblas_algorithms.nxapi +├── bipartite +│ └── cluster +│ ├── butterflies +│ └── robins_alexander_clustering ├── boundary │ ├── edge_boundary │ └── node_boundary diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..3d83b6f 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -45,6 +45,7 @@ def get_info(): "bfs_layers", "bfs_successors", "boundary_expansion", + "butterflies", "center", "closeness_centrality", "clustering", @@ -144,6 +145,7 @@ def get_info(): "reciprocity", "resource_allocation_index", "reverse", + "robins_alexander_clustering", "s_metric", "schultz_index", "score_sequence", @@ -198,6 +200,7 @@ def get_info(): "betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.", "bfs_edges": "A breadth-first tree that may differ from NetworkX's, as may the order: a node's parent\nis its neighbor on the level above first in node order, and each level comes by parent,\nthen child, in node order. `sort_neighbors` is left to NetworkX.", "bfs_successors": "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n`sort_neighbors` is left to NetworkX.", + "butterflies": "A graph with self-loops is left to NetworkX.\nRaises OverflowError rather than count four-cycles and paths of three edges in 64-bit\nintegers where a bound on them, half the sum of the squares of each node's walks of two\nsteps, reaches 2**62.", "center": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", @@ -227,6 +230,7 @@ def get_info(): "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "robins_alexander_clustering": "A directed graph or a graph with self-loops is left to NetworkX.\nRaises OverflowError rather than count four-cycles and paths of three edges in 64-bit\nintegers where a bound on them, half the sum of the squares of each node's walks of two\nsteps, reaches 2**62.", "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', "single_source_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..ac1d41f 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -23,6 +23,7 @@ # The generated files list them on every version, so they do not depend on which NetworkX ran # the generators; an older NetworkX never asks this backend for a name it does not have. _ADDED_IN = { + "butterflies": "3.7", "is_cover": "3.7", "overlapping_modularity": "3.7", } @@ -69,6 +70,11 @@ "Raises OverflowError rather than add integer weights where the number of nodes times the\n" "heaviest absolute weight reaches 2**62, as a length could then pass 2**63." ) +_COUNT_OVERFLOW = ( + "Raises OverflowError rather than count four-cycles and paths of three edges in 64-bit\n" + "integers where a bound on them, half the sum of the squares of each node's walks of two\n" + "steps, reaches 2**62." +) _SUM_OVERFLOW = ( "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\n" "or more" @@ -122,6 +128,7 @@ "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n" "`sort_neighbors` is left to NetworkX." ), + "butterflies": "A graph with self-loops is left to NetworkX.\n" + _COUNT_OVERFLOW, "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, "common_neighbor_centrality": ( @@ -173,6 +180,9 @@ "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, + "robins_alexander_clustering": ( + "A directed graph or a graph with self-loops is left to NetworkX.\n" + _COUNT_OVERFLOW + ), "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, "single_source_bellman_ford_path_length": _PATH_OVERFLOW, diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..596def1 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -1,4 +1,5 @@ from . import exceptions +from .bipartite import * from .boundary import * from .centrality import * from .cluster import * diff --git a/graphblas_algorithms/algorithms/bipartite/__init__.py b/graphblas_algorithms/algorithms/bipartite/__init__.py new file mode 100644 index 0000000..ca68c1b --- /dev/null +++ b/graphblas_algorithms/algorithms/bipartite/__init__.py @@ -0,0 +1,6 @@ +from . import cluster +from .cluster import * + +# Only the functions: a bare star import would also hand `cluster`, this package's module, to +# `algorithms`, in place of `algorithms.cluster`. +__all__ = cluster.__all__ diff --git a/graphblas_algorithms/algorithms/bipartite/cluster.py b/graphblas_algorithms/algorithms/bipartite/cluster.py new file mode 100644 index 0000000..ec5858e --- /dev/null +++ b/graphblas_algorithms/algorithms/bipartite/cluster.py @@ -0,0 +1,147 @@ +"""Four-cycles ("butterflies") and three-paths, for Robins and Alexander's clustering. + +Neither needs the bipartition: NetworkX counts every four-cycle and every path of three edges +whose ends differ, so these do too, and a graph that is not bipartite gets NetworkX's numbers. +The graph must have no self-loops, which NetworkX's loops read as neighbors. +""" + +import numpy as np +from graphblas import Matrix, Vector, monoid, select +from graphblas.dtypes import INT64 +from graphblas.semiring import plus_pair, plus_second, plus_times + +from ..cluster import total_triangles + +__all__ = ["butterflies", "robins_alexander_clustering"] + +# Counts are added in int64. A node's four-cycles number at most half the square of its walks +# of two steps (`_walks`), so while those halves sum to less than this, no count overflows. +_COUNT_LIMIT = 2**62 + +# The wedges that one block of rows may walk (`_wedge_blocks`), which bounds the entries of +# its products: a dense graph's would otherwise hold a row for every node at once. +_BLOCK_WEDGES = 2**23 + + +def _degrees(G): + return G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64) + + +def _walks(G, degrees): + """Each node's walks of two steps that end at another node. + + That is the sum of its neighbors' degrees, less one each. + """ + less_one = Vector.from_dense(degrees - 1) + return plus_second[INT64](G._A @ less_one).new().to_dense(fill_value=0, dtype=np.int64) + + +def _check_counts(degrees, walks): + """Raise OverflowError unless every count fits in int64, as NetworkX's Python ints do.""" + cycles = float(np.dot(walks.astype(np.float64), walks)) / 2 + paths = float(np.dot((degrees - 1).astype(np.float64), walks)) + if cycles >= _COUNT_LIMIT or paths >= _COUNT_LIMIT: + raise OverflowError( + "the four-cycles or three-paths here could number 2**62 (a bound from each node's " + "walks of two steps), too near 2**63 for the 64-bit integers they are added in; " + "NetworkX counts with Python integers. Call with backend='networkx'." + ) + + +def _ranked(G, degrees): + """The adjacency with the nodes numbered by degree, lowest first. + + Returns `(ids, B, L)`: `ids` holds the id of each new number, `B` is the adjacency so + numbered, and `L` its edges `u - v` with `v` below `u`. + """ + n = len(G) + ids = np.argsort(degrees, kind="stable") + rank = np.empty(n, np.int64) + rank[ids] = np.arange(n) + rows, cols, _ = G._A.to_coo(values=False) + B = Matrix.from_coo(rank[rows], rank[cols], True, nrows=n, ncols=n) + return ids, B, select.tril(B, -1).new() + + +def _wedge_blocks(B, L, ranked_degrees): + """Yield `(start, Lb, W)` over blocks of rows from `start`, with `Lb` those rows of `L`. + + `W[i, w]`, for `w` below `u = start + i`, counts the wedges `u - v - w` with `v` below `u`. + A four-cycle has one node `u` above its other three and one node `w` opposite `u`, and its + other two nodes are middles of such wedges, so the `k` wedges from `u` to `w` close C(k, 2) + cycles, each counted once. A hub is never the middle of a wedge from a node of lower degree, + so its neighbors are not walked once for each of them: NetworkX's ordering too. A block + walks about `_BLOCK_WEDGES` wedges, or one row, so a dense graph's products stay small. + """ + n = B.nrows + walked = plus_second[INT64](L @ Vector.from_dense(ranked_degrees)).new() + reach = np.cumsum(walked.to_dense(fill_value=0, dtype=np.int64)) + start = 0 + while start < n: + before = reach[start - 1] if start else 0 + end = int(np.searchsorted(reach, before + _BLOCK_WEDGES, side="right")) + end = min(max(end, start + 1), n) + Lb = L[start:end, :].new() + W = select.tril(plus_pair[INT64](Lb @ B).new(), start - 1).new() + yield start, Lb, W + start = end + + +def _sums(reduction): + return reduction.new().to_dense(fill_value=0, dtype=np.int64) + + +def butterflies(G): + """The four-cycles through each node, an int64 array by node id.""" + n = len(G) + degrees = _degrees(G) + if G._A.nvals == 0: + return np.zeros(n, np.int64) + _check_counts(degrees, _walks(G, degrees)) + ids, B, L = _ranked(G, degrees) + by_rank = np.zeros(n, np.int64) + for start, Lb, W in _wedge_blocks(B, L, degrees[ids]): + size = W.nrows + rows, cols, counts = W.to_coo() + pairs = Matrix.from_coo( + rows, cols, counts * (counts - 1) // 2, dtype=INT64, nrows=size, ncols=n + ) + # A middle of one of the `k` wedges from `u` to `w` is in `k - 1` of their cycles, one + # with each other middle: `X[u, v]` adds those over the `w` that `v` reaches from `u`. + more = counts > 1 + less_one = Matrix.from_coo( + rows[more], cols[more], counts[more] - 1, dtype=INT64, nrows=size, ncols=n + ) + X = plus_times[INT64](less_one @ B).new(mask=Lb.S) + by_rank[start : start + size] += _sums(pairs.reduce_rowwise(monoid.plus)) + by_rank += _sums(pairs.reduce_columnwise(monoid.plus)) + by_rank += _sums(X.reduce_columnwise(monoid.plus)) + result = np.empty(n, np.int64) + result[ids] = by_rank + return result + + +def robins_alexander_clustering(G): + """Four times the four-cycles over the paths of three edges whose ends differ. + + Divided as NetworkX divides, so its float to the bit; the integer 0 below four nodes or three + edges, or without such paths, as NetworkX returns it. + """ + if len(G) < 4 or G._A.nvals < 6: # each edge is held both ways + return 0 + degrees = _degrees(G) + walks = _walks(G, degrees) + _check_counts(degrees, walks) + # Over each edge `u - w` as the middle, taken both ways as NetworkX takes it: a neighbor of + # `u` but `w` times a neighbor of `w` but `u`, less the pairs that are one node, which make + # a triangle; each triangle is met at its three edges, both ways. + paths = int(np.dot(degrees - 1, walks)) - 6 * int(total_triangles(G)) + L_3 = paths / 2 + if L_3 == 0: + return 0 + ids, B, L = _ranked(G, degrees) + four_cycles = 0 + for _, _, W in _wedge_blocks(B, L, degrees[ids]): + counts = W.to_coo(rows=False, columns=False)[2] + four_cycles += int((counts * (counts - 1) // 2).sum()) + return 4 * four_cycles / L_3 diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..d1a5f64 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -233,6 +233,11 @@ def _materialize_virtual_adjacency(graph): class Dispatcher: # Begin auto-generated code: dispatch + mod = nxapi.bipartite + # =================== + butterflies = mod.cluster.butterflies + robins_alexander_clustering = mod.cluster.robins_alexander_clustering + mod = nxapi.boundary # ================== edge_boundary = mod.edge_boundary diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..902b313 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -1,3 +1,4 @@ +from .bipartite import * from .boundary import * from .centrality import * from .cluster import * @@ -29,6 +30,7 @@ from .tournament import is_tournament from .wiener import * +from . import bipartite from . import centrality from . import cluster from . import community diff --git a/graphblas_algorithms/nxapi/bipartite/__init__.py b/graphblas_algorithms/nxapi/bipartite/__init__.py new file mode 100644 index 0000000..d461000 --- /dev/null +++ b/graphblas_algorithms/nxapi/bipartite/__init__.py @@ -0,0 +1,4 @@ +from .cluster import * + +# NetworkX keeps these in `nx.bipartite`, out of its top level. +__all__ = [] diff --git a/graphblas_algorithms/nxapi/bipartite/cluster.py b/graphblas_algorithms/nxapi/bipartite/cluster.py new file mode 100644 index 0000000..0edbbcc --- /dev/null +++ b/graphblas_algorithms/nxapi/bipartite/cluster.py @@ -0,0 +1,42 @@ +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.graph import to_undirected_graph +from graphblas_algorithms.utils import not_implemented_for + +from .._utils import can_run, nbunch_keys + +__all__ = ["butterflies", "robins_alexander_clustering"] + + +def _undirected(bound): + # NetworkX answers a directed graph from its successors in 3.6.1 and raises from + # `butterflies` in 3.7, after early returns of 0: its answer to give. + if bound["G"].is_directed(): + return "robins_alexander_clustering of a directed graph is left to networkx" + return None + + +def _refuse_self_loops(G, name): + # NetworkX's loops read a self-loop as a neighbor, so its counts with one are its own. + # Raised after the conversion, NetworkX's dispatcher still hands the call to NetworkX. + if G.get_property("has_self_edges"): + raise NotImplementedError(f"{name} of a graph with self-loops is left to networkx") + + +@can_run(_undirected) +def robins_alexander_clustering(G): + if G.is_directed(): + raise NotImplementedError(_undirected({"G": G})) + G = to_undirected_graph(G) + _refuse_self_loops(G, "robins_alexander_clustering") + return algorithms.robins_alexander_clustering(G) # OverflowError where counts could pass int64 + + +@not_implemented_for("directed") +def butterflies(G, nodes=None): + G = to_undirected_graph(G) + _refuse_self_loops(G, "butterflies") + counts = algorithms.butterflies(G).tolist() + key_to_id = G._key_to_id + if nodes is None: + return {key: counts[i] for key, i in key_to_id.items()} + return {key: counts[key_to_id[key]] for key in nbunch_keys(G, nodes)} diff --git a/graphblas_algorithms/nxapi/tests/test_bipartite_four_cycles.py b/graphblas_algorithms/nxapi/tests/test_bipartite_four_cycles.py new file mode 100644 index 0000000..74edf9e --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_bipartite_four_cycles.py @@ -0,0 +1,362 @@ +"""robins_alexander_clustering and butterflies against NetworkX and against plain counts. + +The clustering is NetworkX's to the bit, and of its type: the integer 0 where NetworkX returns +that early, else a float. `butterflies` is NetworkX 3.7's; NetworkX 3.6.1 has no `butterflies`, +so there it is checked against a count made here, as everywhere. +""" + +import itertools +import math + +import networkx as nx +import numpy as np +import pytest +from networkx.algorithms import bipartite + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +HAS_BUTTERFLIES = hasattr(bipartite, "butterflies") + + +def reference(G): + """Per-node four-cycles and NetworkX's three-path count, from neighbor sets, in ints. + + A node's four-cycles are C(c, 2) over each other node sharing `c` neighbors with it; the + paths of three edges whose ends differ, counted from both ends, as NetworkX counts them. + """ + nbrs = {v: set(G[v]) for v in G} + cycles = {v: sum(math.comb(len(nbrs[v] & nbrs[w]), 2) for w in G if w != v) for v in G} + paths = sum( + (len(nbrs[u]) - 1) * (len(nbrs[w]) - 1) - len(nbrs[u] & nbrs[w]) for u in G for w in nbrs[u] + ) + return cycles, paths + + +def expected_clustering(G): + """NetworkX's arithmetic, on the counts made here.""" + if G.order() < 4 or G.size() < 3: + return 0 + cycles, paths = reference(G) + L_3 = paths / 2 + if L_3 == 0: + return 0 + return sum(cycles.values()) / L_3 + + +def _shuffled(G, rng, prefix=None): + nodes = list(G) + name = (lambda u: f"{prefix}{u}") if prefix else (lambda u: u) + H = nx.Graph() + H.add_nodes_from(name(nodes[i]) for i in rng.permutation(len(nodes))) + edges = list(G.edges) + H.add_edges_from((name(edges[i][0]), name(edges[i][1])) for i in rng.permutation(len(edges))) + return H + + +def _random_graphs(): + """Seeded graphs: bipartite and not, dense and sparse, with hubs, labels, isolates.""" + rng = np.random.default_rng(62) + + def randint(a, b): + return int(rng.integers(a, b + 1)) + + graphs = [] + for i in range(80): + a, b = randint(1, 14), randint(1, 14) + p = [0.1, 0.25, 0.5, 0.8, 1.0][i % 5] + graphs.append((f"bipartite{i}", bipartite.random_graph(a, b, p, seed=i))) + for i in range(30): + a, b = randint(2, 30), randint(2, 30) + k = randint(0, a * b) + graphs.append((f"gnmk{i}", bipartite.gnmk_random_graph(a, b, k, seed=100 + i))) + for i in range(20): + G = nx.Graph(bipartite.preferential_attachment_graph([randint(1, 4)] * 25, 0.4, seed=i)) + graphs.append((f"hubs{i}", G)) + graphs.extend( + (f"complete{a}x{b}", nx.complete_bipartite_graph(a, b)) + for a in range(1, 6) + for b in range(a, 6) + ) + for i in range(60): + n = randint(0, 25) + G = nx.gnp_random_graph(n, [0.05, 0.15, 0.3, 0.6][i % 4], seed=200 + i) + graphs.append((f"gnp{i}", G)) # mostly not bipartite: triangles and odd cycles + graphs.extend( + (f"grid{a}x{b}", nx.grid_2d_graph(a, b)) for a in range(1, 6) for b in range(a, 7) + ) + graphs.extend((f"hypercube{d}", nx.hypercube_graph(d)) for d in range(1, 6)) + graphs.extend((f"cycle{n}", nx.cycle_graph(n)) for n in range(3, 11)) + graphs.extend((f"tree{i}", nx.random_labeled_tree(randint(1, 30), seed=i)) for i in range(15)) + graphs.extend((f"star{n}", nx.star_graph(n)) for n in range(8)) + graphs.extend((f"complete{n}", nx.complete_graph(n)) for n in range(8)) + for i in range(40): + G = bipartite.random_graph(randint(2, 12), randint(2, 12), 0.4, seed=300 + i) + G.add_nodes_from(range(len(G), len(G) + randint(0, 3))) # isolated nodes + graphs.append((f"labels{i}", _shuffled(G, rng, prefix=["n", "", "v "][i % 3] or None))) + return graphs + + +GRAPHS = _random_graphs() + + +def test_there_are_enough_graphs(): + assert len(GRAPHS) >= 300 + + +@pytest.mark.parametrize(("name", "G"), GRAPHS, ids=[name for name, _ in GRAPHS]) +def test_clustering_is_networkx_s_to_the_bit(name, G): + want = bipartite.robins_alexander_clustering(G) + got = bipartite.robins_alexander_clustering(G, backend="graphblas") + assert type(got) is type(want) + assert got == want + assert got == expected_clustering(G) + + +@pytest.mark.parametrize(("name", "G"), GRAPHS, ids=[name for name, _ in GRAPHS]) +def test_butterflies_count_each_node_s_four_cycles(name, G): + cycles, _ = reference(G) + got = nxapi.bipartite.butterflies(G) + assert got == cycles + assert list(got) == list(G) + assert all(type(count) is int for count in got.values()) + if HAS_BUTTERFLIES: + want = bipartite.butterflies(G) + got = bipartite.butterflies(G, backend="graphblas") + assert got == want + assert list(got) == list(want) + + +def test_the_early_zeros_are_ints(): + for G in [nx.Graph(), nx.path_graph(3), nx.Graph([(0, 1), (2, 3)]), nx.star_graph(6)]: + got = bipartite.robins_alexander_clustering(G, backend="graphblas") + assert got == 0 + assert type(got) is int + # Three-paths but no four-cycles: a float. + got = bipartite.robins_alexander_clustering(nx.path_graph(4), backend="graphblas") + assert got == 0.0 + assert type(got) is float + + +def test_known_values(): + assert bipartite.robins_alexander_clustering(nx.cycle_graph(4), backend="graphblas") == 1.0 + assert ( + bipartite.robins_alexander_clustering( + nx.complete_bipartite_graph(3, 3), backend="graphblas" + ) + == 1.0 + ) + # K4 is not bipartite: 3 four-cycles over 12 three-paths whose ends differ. + assert bipartite.robins_alexander_clustering(nx.complete_graph(4), backend="graphblas") == 1.0 + G = nx.complete_bipartite_graph(4, 5) + counts = nxapi.bipartite.butterflies(G) + assert counts == {v: math.comb(5 if v < 4 else 4, 2) * (3 if v < 4 else 4) for v in G} + + +def test_a_larger_graph(): + G = bipartite.gnmk_random_graph(300, 400, 3000, seed=62) + assert bipartite.robins_alexander_clustering( + G, backend="graphblas" + ) == bipartite.robins_alexander_clustering(G) + cycles, _ = reference(G) + assert nxapi.bipartite.butterflies(G) == cycles + + +def test_hubs(): + """A hub is a middle only of wedges from nodes of higher degree.""" + G = nx.star_graph(200) + G.add_edges_from((i, 300 + i % 7) for i in range(1, 201)) + cycles, _ = reference(G) + assert nxapi.bipartite.butterflies(G) == cycles + assert bipartite.robins_alexander_clustering(G, backend="graphblas") == expected_clustering(G) + + +def test_a_graph_whose_ids_do_not_follow_its_node_order(): + """The `union` here lists the second graph's nodes first but numbers them last.""" + U = nx.union(nx.cycle_graph(4), nx.relabel_nodes(nx.path_graph(3), str), backend="graphblas") + assert list(U) == ["0", "1", "2", 0, 1, 2, 3] + got = nxapi.bipartite.butterflies(U) + assert list(got) == list(U) + assert got == {"0": 0, "1": 0, "2": 0, 0: 1, 1: 1, 2: 1, 3: 1} + + +@pytest.mark.parametrize("budget", [1, 7, 60]) +def test_rows_in_blocks(monkeypatch, budget): + """Blocks of a row or a few, as a dense graph's rows come: the same counts.""" + from graphblas_algorithms.algorithms.bipartite import cluster + + monkeypatch.setattr(cluster, "_BLOCK_WEDGES", budget) + chosen = GRAPHS[::7] + [(name, G) for name, G in GRAPHS if name.startswith("hubs")] + for _, G in chosen: + cycles, _ = reference(G) + assert nxapi.bipartite.butterflies(G) == cycles + got = nxapi.bipartite.robins_alexander_clustering(G) + want = expected_clustering(G) + assert type(got) is type(want) + assert got == want + + +def test_the_kernels_module_cluster_is_not_hidden(): + from graphblas_algorithms import algorithms + + assert algorithms.cluster.__name__ == "graphblas_algorithms.algorithms.cluster" + assert ( + algorithms.bipartite.cluster.__name__ == "graphblas_algorithms.algorithms.bipartite.cluster" + ) + + +# What is left to NetworkX, and the errors + + +def _outcome(f): + try: + return f() + except Exception as exc: + return type(exc), str(exc) + + +def _self_loop_graphs(): + G = nx.complete_bipartite_graph(3, 3) + G.add_edge(0, 0) + H = nx.Graph([(0, 0), (1, 1), (2, 2), (3, 3), (0, 1)]) # NetworkX 3.6.1 gives 2.0, 3.7 0.0 + return [G, H] + + +@pytest.mark.parametrize("which", [0, 1]) +def test_self_loops_are_left_to_networkx(which): + G = _self_loop_graphs()[which] + with pytest.raises(NotImplementedError): + bipartite.robins_alexander_clustering(G, backend="graphblas") + with nx.config.backend_priority(algos=["graphblas"]): + assert _outcome(lambda: bipartite.robins_alexander_clustering(G)) == _outcome( + lambda: bipartite.robins_alexander_clustering(G, backend="networkx") + ) + for func in [nxapi.bipartite.robins_alexander_clustering, nxapi.bipartite.butterflies]: + with pytest.raises(NotImplementedError, match="self-loops"): + func(G) + with pytest.raises(NotImplementedError, match="self-loops"): + func(ga.Graph.from_networkx(G)) + if HAS_BUTTERFLIES: + with nx.config.backend_priority(algos=["graphblas"]): + assert bipartite.butterflies(G) == bipartite.butterflies(G, backend="networkx") + + +@pytest.mark.parametrize( + "G", [nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0)]), nx.DiGraph([(0, 1)])], ids=["C4", "edge"] +) +def test_a_directed_graph_is_left_to_networkx(G): + """NetworkX 3.6.1 counts successors, 3.7 raises from `butterflies` past its early zeros.""" + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + bipartite.robins_alexander_clustering(G, backend="graphblas") + with nx.config.backend_priority(algos=["graphblas"]): + assert _outcome(lambda: bipartite.robins_alexander_clustering(G)) == _outcome( + lambda: bipartite.robins_alexander_clustering(G, backend="networkx") + ) + with pytest.raises(NotImplementedError, match="directed"): + nxapi.bipartite.robins_alexander_clustering(G) + # `butterflies` is not for directed graphs, as NetworkX's. + for H in [G, ga.DiGraph.from_networkx(G)]: + with pytest.raises(nx.NetworkXNotImplemented): + nxapi.bipartite.butterflies(H) + if HAS_BUTTERFLIES: + with pytest.raises(nx.NetworkXNotImplemented): + bipartite.butterflies(G, backend="graphblas") + + +def test_a_multigraph_is_left_to_networkx(): + G = nx.MultiGraph([(0, 1), (1, 2), (2, 3), (3, 0), (0, 1)]) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + bipartite.robins_alexander_clustering(G, backend="graphblas") + with nx.config.backend_priority(algos=["graphblas"]): + assert bipartite.robins_alexander_clustering(G) == bipartite.robins_alexander_clustering( + G, backend="networkx" + ) + + +NBUNCHES = { + "one node": 0, + "list with absent and repeated": [5, 9, 0, 5], + "tuple": (1, 2), + "unhashable member": [0, [1]], + "non-iterable": 3.5, + "string": "ab", + "empty": [], + "set": {4, 3}, +} + + +@pytest.mark.parametrize("case", sorted(NBUNCHES)) +def test_butterflies_nodes_as_nbunch_iter(case): + G = nx.complete_bipartite_graph(3, 3) + nodes = NBUNCHES[case] + cycles, _ = reference(G) + + def by_nbunch_iter(): + return {v: cycles[v] for v in G.nbunch_iter(nodes)} + + want = _outcome(by_nbunch_iter) + got = _outcome(lambda: nxapi.bipartite.butterflies(G, nodes=nodes)) + assert got == want + if not isinstance(want, tuple): + assert list(got) == list(want) + if HAS_BUTTERFLIES: + assert _outcome(lambda: bipartite.butterflies(G, nodes=nodes, backend="graphblas")) == want + + +def test_butterflies_of_a_graph_without_edges(): + G = nx.empty_graph(4) + assert nxapi.bipartite.butterflies(G) == {0: 0, 1: 0, 2: 0, 3: 0} + assert nxapi.bipartite.butterflies(G, nodes=[3, 1]) == {3: 0, 1: 0} + assert nxapi.bipartite.butterflies(nx.Graph()) == {} + + +@pytest.mark.parametrize("limit", [10, 100]) +def test_counts_that_could_pass_int64_raise_overflow_error(monkeypatch, limit): + """On K(3, 3) the cycles' bound is 108 and the three-paths 72: either may pass the limit. + + The bound is seen after the conversion, so the call raises there, with NetworkX's fallback + on too: an OverflowError is not a decline. + """ + from graphblas_algorithms.algorithms.bipartite import cluster + + monkeypatch.setattr(cluster, "_COUNT_LIMIT", limit) + for func in [nxapi.bipartite.robins_alexander_clustering, nxapi.bipartite.butterflies]: + with pytest.raises(OverflowError, match="backend='networkx'"): + func(nx.complete_bipartite_graph(3, 3)) + names = ["robins_alexander_clustering", *(["butterflies"] if HAS_BUTTERFLIES else [])] + for name in names: + G = nx.complete_bipartite_graph(3, 3) + with ( + nx.config.backend_priority(algos=["graphblas"]), + nx.config(fallback_to_nx=True), + pytest.raises(OverflowError, match="2\\*\\*62"), + ): + getattr(bipartite, name)(G) + assert "graphblas" in G.__networkx_cache__["backends"] # converted, then raised + with pytest.raises(OverflowError): + getattr(bipartite, name)(G, backend="graphblas") + assert getattr(bipartite, name)(G, backend="networkx") == ( + 1.0 if name == "robins_alexander_clustering" else dict.fromkeys(G, 6) + ) + + +def test_the_count_limit_bounds_every_sum(): + """A node's four-cycles are at most half the square of its two-step walks.""" + for G in [nx.complete_bipartite_graph(4, 7), nx.hypercube_graph(4), nx.complete_graph(6)]: + cycles, _ = reference(G) + walks = {v: sum(len(G[x]) - 1 for x in G[v]) for v in G} + assert all(cycles[v] <= walks[v] ** 2 / 2 for v in G) + assert sum(cycles.values()) <= sum(w * w for w in walks.values()) / 2 + + +def test_reference_counts_match_brute_force(): + """The count made here, against every four-cycle listed.""" + for G in [nx.complete_graph(5), nx.complete_bipartite_graph(3, 4), nx.hypercube_graph(3)]: + found = set() + for a, b, c, d in itertools.permutations(G, 4): + if G.has_edge(a, b) and G.has_edge(b, c) and G.has_edge(c, d) and G.has_edge(d, a): + found.add(frozenset([frozenset([a, c]), frozenset([b, d])])) + cycles, _ = reference(G) + assert sum(cycles.values()) == 4 * len(found) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..f58b8e2 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -87,6 +87,7 @@ def call_args(kind, args): "bfs_layers": ("undirected", ([0],)), "bfs_successors": ("undirected", (0,)), "boundary_expansion": ("undirected", ([0, 1],)), + "butterflies": ("undirected", ()), # The tournament is the kind without an isolated node: eccentricity, and the names read # off it, raise on a graph in pieces. "center": ("tournament", ()), @@ -193,6 +194,7 @@ def call_args(kind, args): # Unweighted: NetworkX 3.6.1 does not ask for `reverse`'s edge data, so a weighted graph # is declined there and answered on 3.7; the version is not what these tests are about. "reverse": ("plain directed", ()), + "robins_alexander_clustering": ("undirected", ()), "s_metric": ("undirected", ()), "schultz_index": ("undirected", ()), "score_sequence": ("tournament", ()), diff --git a/pyproject.toml b/pyproject.toml index e353a3d..b428f12 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -94,6 +94,7 @@ packages = [ "_nx_graphblas", "graphblas_algorithms", "graphblas_algorithms.algorithms", + "graphblas_algorithms.algorithms.bipartite", "graphblas_algorithms.algorithms.centrality", "graphblas_algorithms.algorithms.community", "graphblas_algorithms.algorithms.components", @@ -108,6 +109,7 @@ packages = [ "graphblas_algorithms.generators", "graphblas_algorithms.linalg", "graphblas_algorithms.nxapi", + "graphblas_algorithms.nxapi.bipartite", "graphblas_algorithms.nxapi.centrality", "graphblas_algorithms.nxapi.community", "graphblas_algorithms.nxapi.components",