From 3538d1250b78ccd8e96555f9068f84c32805b65d Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 21:23:16 -0600 Subject: [PATCH] Add latapy_clustering, its average, and node_redundancy Latapy's bipartite clustering averages, over the nodes two steps from a node, the neighbors each shares with it over the size of the union of their neighborhoods, the smaller degree or the larger. A masked plus_pair product counts the shared neighbors, taking the rows asked for in blocks of a bounded number of paths of two steps, and each term is one division of two integers, as in NetworkX. NetworkX adds a node's terms in the order of a Python set, which is not followed here, so a value can differ from NetworkX's in its last bits. A graph that is not bipartite raises NetworkXError, as in NetworkX: it is one where some node shares a component with its twin in the double cover. Node redundancy, the share of a node's pairs of neighbors that meet at another node too, counts from the same product the pairs that share two neighbors or more, and divides as NetworkX does, so it is NetworkX's to the bit. It does not ask for a bipartite graph. The nodes, the mode and the errors are NetworkX's, in its order. A directed graph is left to NetworkX, and for node_redundancy so is a graph with self-loops. The bipartite average_clustering is registered as bipartite_average_clustering, so the dispatch table's generator, and the tests that follow it, now know a function by where it lives before its name, which here also names nx.average_clustering. --- README.md | 10 +- _nx_graphblas/__init__.py | 6 + _nx_graphblas/core.py | 10 + .../algorithms/bipartite/__init__.py | 11 +- .../algorithms/bipartite/basic.py | 51 +++ .../algorithms/bipartite/latapy.py | 42 ++ .../algorithms/bipartite/redundancy.py | 36 ++ graphblas_algorithms/interface.py | 3 + .../nxapi/bipartite/__init__.py | 4 +- .../nxapi/bipartite/cluster.py | 69 +++- .../nxapi/bipartite/redundancy.py | 33 ++ .../nxapi/tests/test_bipartite_latapy.py | 369 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 7 + .../tests/test_cached_conversion.py | 15 +- graphblas_algorithms/tests/test_match_nx.py | 13 +- scripts/maketree.py | 31 +- 16 files changed, 693 insertions(+), 17 deletions(-) create mode 100644 graphblas_algorithms/algorithms/bipartite/basic.py create mode 100644 graphblas_algorithms/algorithms/bipartite/latapy.py create mode 100644 graphblas_algorithms/algorithms/bipartite/redundancy.py create mode 100644 graphblas_algorithms/nxapi/bipartite/redundancy.py create mode 100644 graphblas_algorithms/nxapi/tests/test_bipartite_latapy.py diff --git a/README.md b/README.md index f00a2c1..85ace31 100644 --- a/README.md +++ b/README.md @@ -125,9 +125,13 @@ dispatch pattern shown above. ``` graphblas_algorithms.nxapi ├── bipartite -│ └── cluster -│ ├── butterflies -│ └── robins_alexander_clustering +│ ├── cluster +│ │ ├── average_clustering (bipartite_average_clustering) +│ │ ├── butterflies +│ │ ├── latapy_clustering +│ │ └── robins_alexander_clustering +│ └── redundancy +│ └── node_redundancy ├── boundary │ ├── edge_boundary │ └── node_boundary diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3d83b6f..498b347 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -44,6 +44,7 @@ def get_info(): "bfs_edges", "bfs_layers", "bfs_successors", + "bipartite_average_clustering", "boundary_expansion", "butterflies", "center", @@ -118,6 +119,7 @@ def get_info(): "k_truss", "katz_centrality", "laplacian_matrix", + "latapy_clustering", "local_efficiency", "lowest_common_ancestor", "mixing_expansion", @@ -128,6 +130,7 @@ def get_info(): "node_boundary", "node_connected_component", "node_expansion", + "node_redundancy", "normalized_cut_size", "normalized_laplacian_matrix", "number_connected_components", @@ -200,6 +203,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.", + "bipartite_average_clustering": "A directed graph is left to NetworkX. The average is NetworkX's sum over the nodes, of\nvalues within a relative 1e-12 of NetworkX's (see `latapy_clustering`).", "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".', @@ -225,8 +229,10 @@ def get_info(): "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge 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.", "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge 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.", "k_truss": "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.", + "latapy_clustering": "A directed graph is left to NetworkX. A node's terms are added in the order of the\nnodes' ids, not in NetworkX's set order, so a value can differ from NetworkX's in its\nlast bits.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "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.", + "node_redundancy": "A directed graph, or a graph with self-loops, is left to NetworkX.", "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.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index ac1d41f..a18334e 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -128,6 +128,10 @@ "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n" "`sort_neighbors` is left to NetworkX." ), + "bipartite_average_clustering": ( + "A directed graph is left to NetworkX. The average is NetworkX's sum over the nodes, of\n" + "values within a relative 1e-12 of NetworkX's (see `latapy_clustering`)." + ), "butterflies": "A graph with self-loops is left to NetworkX.\n" + _COUNT_OVERFLOW, "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, @@ -172,12 +176,18 @@ "k_corona": _CORE_SUBGRAPH, "k_crust": _CORE_SUBGRAPH, "k_shell": _CORE_SUBGRAPH, + "latapy_clustering": ( + "A directed graph is left to NetworkX. A node's terms are added in the order of the\n" + "nodes' ids, not in NetworkX's set order, so a value can differ from NetworkX's in its\n" + "last bits." + ), "local_efficiency": ( "The cost is the breadth-first levels times the chunks of walks, so a node whose\n" "neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n" "memory stays bounded." ), "negative_edge_cycle": _PATH_OVERFLOW, + "node_redundancy": "A directed graph, or a graph with self-loops, is left to NetworkX.", "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, "robins_alexander_clustering": ( diff --git a/graphblas_algorithms/algorithms/bipartite/__init__.py b/graphblas_algorithms/algorithms/bipartite/__init__.py index ca68c1b..c426b4c 100644 --- a/graphblas_algorithms/algorithms/bipartite/__init__.py +++ b/graphblas_algorithms/algorithms/bipartite/__init__.py @@ -1,6 +1,9 @@ -from . import cluster +from . import basic, cluster, latapy, redundancy +from .basic import * from .cluster import * +from .latapy import * +from .redundancy 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__ +# Only the functions: a bare star import would also hand this package's modules to +# `algorithms`, among them `cluster` in place of `algorithms.cluster`. +__all__ = basic.__all__ + cluster.__all__ + latapy.__all__ + redundancy.__all__ diff --git a/graphblas_algorithms/algorithms/bipartite/basic.py b/graphblas_algorithms/algorithms/bipartite/basic.py new file mode 100644 index 0000000..023052d --- /dev/null +++ b/graphblas_algorithms/algorithms/bipartite/basic.py @@ -0,0 +1,51 @@ +"""Whether a graph is bipartite, and the blocks of rows the bipartite kernels walk.""" + +import numpy as np +from graphblas import Matrix, Vector +from graphblas.dtypes import INT64 +from graphblas.semiring import plus_second + +from ..components._labels import component_labels + +__all__ = ["is_bipartite"] + +# The paths of two steps that one block of rows may walk, which bounds the entries of its +# products: a dense graph's would otherwise hold a row for every node at once. +_BLOCK_WALKS = 2**22 + + +def is_bipartite(G): + """Whether `G` has no cycle of odd length, a self-loop being one, as NetworkX answers. + + In the double cover each node `v` is two, `v` and `v'`, and each edge `u - v` joins `u` to + `v'` and `u'` to `v`. A walk there from `v` to `v'` is a walk of odd length from `v` back to + `v` in `G`, so `G` is bipartite exactly when no `v` shares a component with its `v'`. + """ + n = len(G) + rows, cols, _ = G._A.to_coo(values=False) + cover = Matrix.from_coo( + np.concatenate([rows, rows + n]), + np.concatenate([cols + n, cols]), + True, + nrows=2 * n, + ncols=2 * n, + ) + labels = component_labels(cover) + return not np.any(labels[:n] == labels[n:]) + + +def row_blocks(G, ids, degrees): + """Split `ids` into runs, in order, that walk about `_BLOCK_WALKS` paths of two steps each. + + A node's paths of two steps number its neighbors' degrees added up; a run holds one node + at least. + """ + walks = plus_second[INT64](G._A @ Vector.from_dense(degrees)).new() + reach = np.cumsum(walks.to_dense(fill_value=0, dtype=np.int64)[ids]) + start = 0 + while start < len(ids): + before = reach[start - 1] if start else 0 + end = int(np.searchsorted(reach, before + _BLOCK_WALKS, side="right")) + end = min(max(end, start + 1), len(ids)) + yield ids[start:end] + start = end diff --git a/graphblas_algorithms/algorithms/bipartite/latapy.py b/graphblas_algorithms/algorithms/bipartite/latapy.py new file mode 100644 index 0000000..e590a13 --- /dev/null +++ b/graphblas_algorithms/algorithms/bipartite/latapy.py @@ -0,0 +1,42 @@ +"""Latapy's bipartite clustering: each node's overlaps with the nodes two steps away.""" + +import numpy as np +from graphblas.dtypes import INT64 +from graphblas.semiring import plus_pair + +from .basic import row_blocks + +__all__ = ["latapy_clustering"] + + +def latapy_clustering(G, ids, mode): + """The clustering of each node in `ids`, which holds no node twice, as a float64 array. + + `G` must be bipartite, so the nodes two steps from `v` are the nodes other than `v` that + share a neighbor with it. Each such `u` adds the neighbors they share over the size of the + union of their neighbors ("dot"), the smaller of their degrees ("min") or the larger + ("max"): one division each, as NetworkX's. The terms are added in the order of `u`'s id, + and their sum is divided by their number. + """ + A = G._A + degrees = G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64) + result = np.zeros(len(ids), np.float64) + done = 0 + for block in row_blocks(G, ids, degrees): + size = len(block) + shared = plus_pair[INT64](A[block, :].new() @ A).new() + rows, cols, common = shared.to_coo() + others = cols != block[rows] # each node shares its whole neighborhood with itself + rows, cols, common = rows[others], cols[others], common[others] + mine, theirs = degrees[block[rows]], degrees[cols] + if mode == "dot": + sizes = mine + theirs - common + elif mode == "min": + sizes = np.minimum(mine, theirs) + else: + sizes = np.maximum(mine, theirs) + sums = np.bincount(rows, weights=common / sizes, minlength=size) + counts = np.bincount(rows, minlength=size) + np.divide(sums, counts, out=result[done : done + size], where=counts > 0) + done += size + return result diff --git a/graphblas_algorithms/algorithms/bipartite/redundancy.py b/graphblas_algorithms/algorithms/bipartite/redundancy.py new file mode 100644 index 0000000..61366d8 --- /dev/null +++ b/graphblas_algorithms/algorithms/bipartite/redundancy.py @@ -0,0 +1,36 @@ +"""Latapy's node redundancy: the share of a node's pairs of neighbors that meet elsewhere too.""" + +import numpy as np +from graphblas import Matrix, monoid +from graphblas.dtypes import INT64 +from graphblas.semiring import plus_pair + +from .basic import row_blocks + +__all__ = ["node_redundancy"] + + +def node_redundancy(G, ids): + """The redundancy of each node in `ids`, which holds no node twice, as a float64 array. + + Each node in `ids` needs two neighbors at least, and `G` no self-loops. Two neighbors `u` + and `w` of `v` meet at a node other than `v` when they share two neighbors or more, so + `M[u, w]` marks the pairs of nodes that share two, and `P[u, v]` counts, for a neighbor + `u` of `v`, the other neighbors of `v` that `u` meets so. Its column sums count each pair + of `v`'s neighbors twice, and they are divided by `d (d - 1)`, as NetworkX divides. + """ + A = G._A + n = len(G) + degrees = G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64) + asked = A[:, ids].new() + neighbors = np.unique(asked.to_coo(values=False)[0]) + twice = np.zeros(len(ids), np.int64) + for block in row_blocks(G, neighbors, degrees): + shared = plus_pair[INT64](A[block, :].new() @ A).new() + rows, cols, common = shared.to_coo() + meet = (common >= 2) & (cols != block[rows]) + M = Matrix.from_coo(rows[meet], cols[meet], True, nrows=len(block), ncols=n) + P = plus_pair[INT64](M @ asked).new(mask=asked[block, :].new().S) + twice += P.reduce_columnwise(monoid.plus).new().to_dense(fill_value=0, dtype=np.int64) + pairs = degrees[ids] * (degrees[ids] - 1) + return twice / pairs diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index d1a5f64..4e3af76 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -235,8 +235,11 @@ class Dispatcher: # Begin auto-generated code: dispatch mod = nxapi.bipartite # =================== + bipartite_average_clustering = mod.cluster.average_clustering butterflies = mod.cluster.butterflies + latapy_clustering = mod.cluster.latapy_clustering robins_alexander_clustering = mod.cluster.robins_alexander_clustering + node_redundancy = mod.redundancy.node_redundancy mod = nxapi.boundary # ================== diff --git a/graphblas_algorithms/nxapi/bipartite/__init__.py b/graphblas_algorithms/nxapi/bipartite/__init__.py index d461000..4f92e38 100644 --- a/graphblas_algorithms/nxapi/bipartite/__init__.py +++ b/graphblas_algorithms/nxapi/bipartite/__init__.py @@ -1,4 +1,6 @@ from .cluster import * +from .redundancy import * -# NetworkX keeps these in `nx.bipartite`, out of its top level. +# NetworkX keeps these in `nx.bipartite`, out of its top level, where `clustering` and +# `average_clustering` name other functions. __all__ = [] diff --git a/graphblas_algorithms/nxapi/bipartite/cluster.py b/graphblas_algorithms/nxapi/bipartite/cluster.py index 0edbbcc..1439793 100644 --- a/graphblas_algorithms/nxapi/bipartite/cluster.py +++ b/graphblas_algorithms/nxapi/bipartite/cluster.py @@ -1,10 +1,21 @@ +import numpy as np +from networkx import NetworkXError + 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"] +# Where two names are one function, the later is the one listed: `latapy_clustering`, after +# its alias `clustering`, as in NetworkX. +__all__ = [ + "average_clustering", + "butterflies", + "clustering", + "latapy_clustering", + "robins_alexander_clustering", +] def _undirected(bound): @@ -40,3 +51,59 @@ def butterflies(G, nodes=None): 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)} + + +# NetworkX's `modes`, looked up the same way, so a bad mode raises what NetworkX raises. +_MODES = {"dot": "dot", "min": "min", "max": "max"} + + +def _left_if_directed(bound): + # NetworkX reads a directed graph's successors as its neighbors: its answer to give. + if bound["G"].is_directed(): + return "a directed graph is left to networkx" + return None + + +def _refuse_directed(G): + if G.is_directed(): + raise NotImplementedError(_left_if_directed({"G": G})) + + +def _clustering(G, nodes, mode): + """NetworkX's checks in NetworkX's order, then a dict of the nodes in `nodes`'s order.""" + if not G._cacheit("is_bipartite", algorithms.is_bipartite, G): + raise NetworkXError("Graph is not bipartite") + try: + mode = _MODES[mode] + except KeyError as err: + raise NetworkXError("Mode for bipartite clustering must be: dot, min or max") from err + if nodes is None: + nodes = G + key_to_id = G._key_to_id + # Each lookup as NetworkX's `G[v]`: KeyError for a node not in the graph, TypeError for + # one that cannot be. + ids = {} + for v in nodes: + ids.setdefault(v, key_to_id[v]) + values = algorithms.latapy_clustering(G, np.fromiter(ids.values(), np.int64), mode) + return dict(zip(ids, values.tolist(), strict=True)) + + +@can_run(_left_if_directed) +def latapy_clustering(G, nodes=None, mode="dot"): + _refuse_directed(G) + G = to_undirected_graph(G) + return _clustering(G, nodes, mode) + + +clustering = latapy_clustering + + +@can_run(_left_if_directed) +def average_clustering(G, nodes=None, mode="dot"): + _refuse_directed(G) + G = to_undirected_graph(G) + if nodes is None: + nodes = G + ccs = _clustering(G, nodes, mode) + return sum(ccs[v] for v in nodes) / len(nodes) diff --git a/graphblas_algorithms/nxapi/bipartite/redundancy.py b/graphblas_algorithms/nxapi/bipartite/redundancy.py new file mode 100644 index 0000000..060f2bd --- /dev/null +++ b/graphblas_algorithms/nxapi/bipartite/redundancy.py @@ -0,0 +1,33 @@ +import numpy as np +from networkx import NetworkXError + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.graph import to_undirected_graph + +from .._utils import can_run +from .cluster import _left_if_directed, _refuse_directed, _refuse_self_loops + +__all__ = ["node_redundancy"] + + +@can_run(_left_if_directed) +def node_redundancy(G, nodes=None): + _refuse_directed(G) + G = to_undirected_graph(G) + # NetworkX counts a self-loop as a neighbor, and a node as a neighbor two of its neighbors + # meet at. Raised before `nodes` is read, NetworkX's dispatcher hands it the call intact. + _refuse_self_loops(G, "node_redundancy") + if nodes is None: + nodes = G + key_to_id = G._key_to_id + degrees = G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64) + # As NetworkX: `nodes` is read once for the check and again for the answer. + if any(degrees[key_to_id[v]] < 2 for v in nodes): + raise NetworkXError( + "Cannot compute redundancy coefficient for a node that has fewer than two neighbors." + ) + ids = {} + for v in nodes: + ids.setdefault(v, key_to_id[v]) + values = algorithms.node_redundancy(G, np.fromiter(ids.values(), np.int64)) + return dict(zip(ids, values.tolist(), strict=True)) diff --git a/graphblas_algorithms/nxapi/tests/test_bipartite_latapy.py b/graphblas_algorithms/nxapi/tests/test_bipartite_latapy.py new file mode 100644 index 0000000..617e492 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_bipartite_latapy.py @@ -0,0 +1,369 @@ +"""Latapy's bipartite clustering, its average, and node redundancy against NetworkX. + +The clustering adds a float term per node two steps away in the order of NetworkX's set of +those nodes, which this backend does not follow, so its values are NetworkX's within a +relative 1e-12, and checked against exact sums of fractions too. Redundancy is one division of +two integers, as NetworkX's, so it is NetworkX's to the bit. +""" + +from fractions import Fraction + +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") + +MODES = ["dot", "min", "max"] + + +def _close(got, want): + return got == want or abs(got - want) <= 1e-12 * max(abs(got), abs(want)) + + +def reference_clustering(G, nodes=None, mode="dot"): + """Each node's clustering as an exact fraction, from neighbor sets.""" + nbrs = {v: set(G[v]) for v in G} + measure = { + "dot": lambda u, v: len(nbrs[u] | nbrs[v]), + "min": lambda u, v: min(len(nbrs[u]), len(nbrs[v])), + "max": lambda u, v: max(len(nbrs[u]), len(nbrs[v])), + }[mode] + out = {} + for v in G if nodes is None else nodes: + far = {u for x in nbrs[v] for u in nbrs[x]} - {v} + total = sum((Fraction(len(nbrs[u] & nbrs[v]), measure(u, v)) for u in far), Fraction(0)) + out[v] = total / len(far) if far else Fraction(0) + return out + + +def reference_redundancy(G, nodes=None): + """Each node's redundancy, as NetworkX divides it, from neighbor sets.""" + nbrs = {v: set(G[v]) for v in G} + out = {} + for v in G if nodes is None else nodes: + near = sorted(nbrs[v], key=list(G).index) + overlap = sum( + 1 for i, u in enumerate(near) for w in near[i + 1 :] if (nbrs[u] & nbrs[w]) - {v} + ) + out[v] = (2 * overlap) / (len(near) * (len(near) - 1)) + return out + + +def _relabeled(G, rng, prefix): + nodes = list(G) + H = nx.Graph() + H.add_nodes_from(f"{prefix}{nodes[i]}" for i in rng.permutation(len(nodes))) + edges = list(G.edges) + H.add_edges_from( + (f"{prefix}{edges[i][0]}", f"{prefix}{edges[i][1]}") for i in rng.permutation(len(edges)) + ) + return H + + +def _graphs(): + """Seeded bipartite graphs: random, sparse and dense, with hubs, labels and isolates.""" + rng = np.random.default_rng(66) + + def randint(a, b): + return int(rng.integers(a, b + 1)) + + graphs = [] + for i in range(110): + a, b = randint(1, 15), randint(1, 15) + p = [0.08, 0.2, 0.4, 0.7, 1.0][i % 5] + graphs.append((f"bipartite{i}", bipartite.random_graph(a, b, p, seed=i))) + for i in range(40): + a, b = randint(2, 30), randint(2, 30) + graphs.append( + (f"gnmk{i}", bipartite.gnmk_random_graph(a, b, randint(0, a * b // 2), seed=100 + i)) + ) + for i in range(25): + 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) + ) + 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(4, 21, 2)) + graphs.extend((f"path{n}", nx.path_graph(n)) for n in range(9)) + graphs.extend((f"tree{i}", nx.random_labeled_tree(randint(1, 30), seed=i)) for i in range(20)) + graphs.extend((f"star{n}", nx.star_graph(n)) for n in range(7)) + for i in range(45): + G = bipartite.random_graph(randint(2, 12), randint(2, 12), 0.35, seed=300 + i) + G.add_nodes_from(range(len(G), len(G) + randint(0, 3))) # isolated nodes + graphs.append((f"labels{i}", _relabeled(G, rng, ["n", "v ", "x"][i % 3]))) + return graphs + + +GRAPHS = _graphs() +IDS = [name for name, _ in GRAPHS] + + +def _not_bipartite(): + out = [(f"odd cycle{n}", nx.cycle_graph(n)) for n in (3, 5, 7)] + out += [(f"complete{n}", nx.complete_graph(n)) for n in (3, 4, 6)] + out += [(f"gnp{i}", nx.gnp_random_graph(14, 0.3, seed=i)) for i in range(20)] + G = nx.path_graph(6) + G.add_edge(5, 5) # a self-loop is a cycle of odd length + out.append(("path with a self-loop", G)) + H = nx.complete_bipartite_graph(3, 3) + H.add_edges_from([(10, 11), (11, 12), (12, 10)]) # bipartite but for one far component + out.append(("one odd component", H)) + return out + + +NOT_BIPARTITE = _not_bipartite() + + +def test_there_are_enough_graphs(): + assert len(GRAPHS) >= 300 + assert all(nx.is_bipartite(G) for _, G in GRAPHS) + assert not any(nx.is_bipartite(G) for _, G in NOT_BIPARTITE) + + +@pytest.mark.parametrize(("name", "G"), GRAPHS, ids=IDS) +def test_latapy_clustering(name, G): + for mode in MODES: + want = bipartite.latapy_clustering(G, mode=mode) + got = bipartite.latapy_clustering(G, mode=mode, backend="graphblas") + exact = reference_clustering(G, mode=mode) + assert list(got) == list(want) + assert all(type(value) is float for value in got.values()) + assert all(_close(got[v], want[v]) for v in want), mode + assert all(_close(got[v], float(exact[v])) for v in want), mode + + +@pytest.mark.parametrize(("name", "G"), GRAPHS, ids=IDS) +def test_average_clustering(name, G): + for mode in MODES: + want = bipartite.average_clustering(G, mode=mode) if len(G) else None + if want is None: + with pytest.raises(ZeroDivisionError): + bipartite.average_clustering(G, mode=mode, backend="graphblas") + continue + got = bipartite.average_clustering(G, mode=mode, backend="graphblas") + assert type(got) is float + assert _close(got, want) + + +@pytest.mark.parametrize( + ("name", "G"), GRAPHS + NOT_BIPARTITE, ids=IDS + [n for n, _ in NOT_BIPARTITE] +) +def test_node_redundancy_is_networkx_s_to_the_bit(name, G): + if nx.number_of_selfloops(G): + pytest.skip("left to NetworkX; tested below") + nodes = [v for v in G if G.degree(v) >= 2] + want = bipartite.node_redundancy(G, nodes) + got = bipartite.node_redundancy(G, nodes, backend="graphblas") + assert list(got) == list(want) + assert all(type(value) is float for value in got.values()) + assert got == want + assert got == reference_redundancy(G, nodes) + + +@pytest.mark.parametrize(("name", "G"), NOT_BIPARTITE, ids=[n for n, _ in NOT_BIPARTITE]) +def test_a_graph_that_is_not_bipartite_raises_as_networkx(name, G): + for func in [bipartite.latapy_clustering, bipartite.clustering, bipartite.average_clustering]: + for kwargs in [{}, {"mode": "bad"}, {"nodes": [999]}]: + with pytest.raises(nx.NetworkXError, match=r"^Graph is not bipartite$"): + func(G, backend="graphblas", **kwargs) + assert ga.algorithms.is_bipartite(ga.Graph.from_networkx(G)) is False + + +def test_is_bipartite(): + from graphblas_algorithms import algorithms + + rng = np.random.default_rng(6) + for i in range(200): + G = nx.gnp_random_graph( + int(rng.integers(0, 16)), float(rng.choice([0.05, 0.12, 0.25])), seed=i + ) + if i % 4 == 0 and len(G): + v = int(rng.integers(0, len(G))) + G.add_edge(v, v) + assert algorithms.is_bipartite(ga.Graph.from_networkx(G)) == nx.is_bipartite(G) + + +# What the arguments do, three ways: NetworkX, this backend by name, and this backend first +# in NetworkX's priority (which hands a declined call to NetworkX). + + +def _outcome(f): + try: + out = f() + except Exception as exc: + return type(exc), str(exc) + if isinstance(out, dict): + return [(key, type(key), value) for key, value in out.items()] + return out + + +def _three_ways(func, G, **kwargs): + want = _outcome(lambda: func(G, backend="networkx", **kwargs)) + got = _outcome(lambda: func(G, backend="graphblas", **kwargs)) + with nx.config.backend_priority(algos=["graphblas"]): + priority = _outcome(lambda: func(G, **kwargs)) + return want, got, priority + + +P = nx.path_graph(5) +K = nx.complete_bipartite_graph(2, 3) +ARGUMENTS = { + "subset": (P, {"nodes": [3, 0]}), + "repeated": (P, {"nodes": [3, 0, 3]}), + "absent": (P, {"nodes": [3, 9, 0]}), + "absent, bad mode": (P, {"nodes": [9], "mode": "bad"}), + "one node, not a list": (P, {"nodes": 3}), + "unhashable member": (K, {"nodes": [0, [1]]}), + "empty": (P, {"nodes": []}), + "set": (P, {"nodes": {4, 1}}), + "string": (nx.relabel_nodes(P, str), {"nodes": "31"}), + "1.0 for 1": (K, {"nodes": [1.0, 1, 2]}), + "bad mode": (K, {"mode": "bad"}), + "unhashable mode": (K, {"mode": ["dot"]}), + "min": (P, {"mode": "min"}), + "max": (P, {"mode": "max"}), + "empty graph": (nx.Graph(), {}), + "isolated nodes": (nx.empty_graph(3), {}), + "isolated node asked": (nx.empty_graph(3), {"nodes": [1]}), + "a leaf asked": (P, {"nodes": [0]}), +} + + +@pytest.mark.parametrize("case", sorted(ARGUMENTS)) +@pytest.mark.parametrize("name", ["latapy_clustering", "average_clustering", "node_redundancy"]) +def test_arguments_as_networkx(name, case): + G, kwargs = ARGUMENTS[case] + if name == "node_redundancy" and "mode" in kwargs: + kwargs = {k: v for k, v in kwargs.items() if k != "mode"} + want, got, priority = _three_ways(getattr(bipartite, name), G, **kwargs) + if isinstance(want, list): + assert len(got) == len(want) + assert all(g[:2] == w[:2] and _close(g[2], w[2]) for g, w in zip(got, want, strict=True)) + assert priority == got + elif isinstance(want, float): + assert _close(got, want) + assert priority == got + else: + assert got == want + assert priority == want + + +@pytest.mark.parametrize("name", ["latapy_clustering", "average_clustering", "node_redundancy"]) +def test_nodes_as_a_generator(name): + """Read as NetworkX reads it: the average and redundancy read `nodes` twice.""" + func = getattr(bipartite, name) + G = K if name == "node_redundancy" else P + want = _outcome(lambda: func(G, nodes=(v for v in [3, 1]), backend="networkx")) + got = _outcome(lambda: func(G, nodes=(v for v in [3, 1]), backend="graphblas")) + assert got == want + + +def _with_self_loop(far): + G = nx.complete_bipartite_graph(2, 3) + G.add_edge(9 if far else 0, 9 if far else 0) + G.add_node(9) + return G + + +@pytest.mark.parametrize("far", [False, True]) +def test_redundancy_with_a_self_loop_is_left_to_networkx(far): + G = _with_self_loop(far) + nodes = [0, 1] + want, got, priority = _three_ways(bipartite.node_redundancy, G, nodes=nodes) + assert got[0] is NotImplementedError + assert priority == want + with pytest.raises(NotImplementedError, match="self-loops"): + nxapi.bipartite.node_redundancy(G, nodes) + + # Declined before `nodes` is read, so NetworkX still gets all of a generator: here it + # meets the self-loop's node, of one neighbor, and raises, where an emptied generator + # would give {}. + def fresh(): + return (v for v in [0, 9]) + + want = _outcome(lambda: bipartite.node_redundancy(G, nodes=fresh(), backend="networkx")) + assert want[0] is nx.NetworkXError + with nx.config.backend_priority(algos=["graphblas"]): + assert _outcome(lambda: bipartite.node_redundancy(G, nodes=fresh())) == want + + +@pytest.mark.parametrize("name", ["latapy_clustering", "average_clustering", "node_redundancy"]) +@pytest.mark.parametrize( + "G", + [ + nx.DiGraph([(0, 1), (1, 2), (2, 3)]), + nx.DiGraph(nx.complete_bipartite_graph(2, 3)), + nx.MultiGraph(K), + ], + ids=["directed path", "directed K2,3", "multigraph"], +) +def test_directed_graphs_and_multigraphs_are_left_to_networkx(name, G): + func = getattr(bipartite, name) + want, got, priority = _three_ways(func, G) + assert got[0] is NotImplementedError + assert "is not implemented by 'graphblas' backend for the given arguments" in got[1] + assert priority == want + if G.is_directed(): + with pytest.raises(NotImplementedError, match="directed"): + getattr(nxapi.bipartite, name)(G) + + +@pytest.mark.parametrize("budget", [1, 9, 100]) +def test_rows_in_blocks(monkeypatch, budget): + """Blocks of a row or a few, as a large graph's rows come: the same values.""" + from graphblas_algorithms.algorithms.bipartite import basic + + monkeypatch.setattr(basic, "_BLOCK_WALKS", budget) + for _, G in GRAPHS[::9] + [(n, G) for n, G in GRAPHS if n.startswith("hubs")]: + for mode in MODES: + got = nxapi.bipartite.latapy_clustering(G, mode=mode) + exact = reference_clustering(G, mode=mode) + assert all(_close(got[v], float(exact[v])) for v in G) + nodes = [v for v in G if G.degree(v) >= 2] + assert nxapi.bipartite.node_redundancy(G, nodes) == reference_redundancy(G, nodes) + + +def test_known_values(): + G = nx.path_graph(5) + assert nxapi.bipartite.latapy_clustering(G) == {0: 0.5, 1: 1 / 3, 2: 0.5, 3: 1 / 3, 4: 0.5} + assert nxapi.bipartite.average_clustering(G, nodes=[0, 2, 4]) == 0.5 + assert nxapi.bipartite.node_redundancy(nx.cycle_graph(4)) == dict.fromkeys(range(4), 1.0) + # Not bipartite: redundancy does not ask. In K4 every pair of a node's neighbors meets at + # the third. + assert nxapi.bipartite.node_redundancy(nx.complete_graph(4)) == dict.fromkeys(range(4), 1.0) + + +def test_names_do_not_collide_with_the_unipartite_ones(): + """`clustering` and `average_clustering` stay NetworkX's top-level functions here.""" + from graphblas_algorithms import algorithms + from graphblas_algorithms.interface import Dispatcher + + assert nxapi.clustering is nxapi.cluster.clustering + assert nxapi.average_clustering is nxapi.cluster.average_clustering + assert nxapi.bipartite.clustering is nxapi.bipartite.latapy_clustering + assert Dispatcher.average_clustering is nxapi.cluster.average_clustering + assert Dispatcher.bipartite_average_clustering is nxapi.bipartite.cluster.average_clustering + assert Dispatcher.latapy_clustering is nxapi.bipartite.latapy_clustering + assert algorithms.cluster.__name__ == "graphblas_algorithms.algorithms.cluster" + assert not hasattr(algorithms, "latapy") + + +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.latapy_clustering(U) + assert list(got) == list(U) + assert got == {"0": 1.0, "1": 0.0, "2": 1.0, 0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0} + assert nxapi.bipartite.node_redundancy(U, [0, 1, "1"]) == {0: 1.0, 1: 1.0, "1": 0.0} diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index f58b8e2..be0f334 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -17,6 +17,7 @@ def dispatcher_functions(): # The graphs the calls below are made on. Each carries graph attributes, and each but the # tournament an isolated node: neither is visible in a graph that is only its edges. _SQUARE = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (1, 3)] +_CYCLE = _SQUARE[:4] # the square without its diagonals: bipartite _DAG = [(0, 1), (0, 2), (1, 3), (2, 3)] _DIRECTED_KINDS = {"directed", "plain directed", "tournament", "dag"} _UNWEIGHTED_KINDS = {"plain", "plain directed"} @@ -36,6 +37,8 @@ def make_graph(kind, *, shift=0, drop=0, label="first"): edges = _DAG elif kind in _DIRECTED_KINDS: edges = _SQUARE + [(v, u) for u, v in _SQUARE] + elif kind == "bipartite": + edges = _CYCLE else: edges = _SQUARE edges = [(u + shift, v + shift) for u, v in edges] @@ -86,6 +89,7 @@ def call_args(kind, args): "bfs_edges": ("undirected", (0,)), "bfs_layers": ("undirected", ([0],)), "bfs_successors": ("undirected", (0,)), + "bipartite_average_clustering": ("bipartite", ()), "boundary_expansion": ("undirected", ([0, 1],)), "butterflies": ("undirected", ()), # The tournament is the kind without an isolated node: eccentricity, and the names read @@ -165,6 +169,7 @@ def call_args(kind, args): "k_truss": ("undirected", (3,)), "katz_centrality": ("undirected", ()), "laplacian_matrix": ("undirected", ()), + "latapy_clustering": ("bipartite", ()), "local_efficiency": ("undirected", ()), "lowest_common_ancestor": ("dag", (1, 2)), "mixing_expansion": ("undirected", ([0, 1], [2, 3])), @@ -175,6 +180,8 @@ def call_args(kind, args): "node_boundary": ("undirected", ([0, 1], [2, 3])), "node_connected_component": ("undirected", (0,)), "node_expansion": ("undirected", ([0, 1],)), + # Its isolated node has no two neighbors, which raises. + "node_redundancy": ("bipartite", ([0, 1, 2, 3],)), "normalized_cut_size": ("undirected", ([0, 1], [2, 3])), "normalized_laplacian_matrix": ("undirected", ()), "number_connected_components": ("undirected", ()), diff --git a/graphblas_algorithms/tests/test_cached_conversion.py b/graphblas_algorithms/tests/test_cached_conversion.py index cf4c99a..838dbec 100644 --- a/graphblas_algorithms/tests/test_cached_conversion.py +++ b/graphblas_algorithms/tests/test_cached_conversion.py @@ -282,7 +282,8 @@ def _helper_calls(): """Every `nxapi` function: the conversion helpers it calls, and which pass `PRESERVE`. Read from the source, since a runtime probe would have to guess each wrapper's arguments. - A local bound to the sentinel counts as the sentinel. + A local bound to the sentinel counts as the sentinel. The calls are keyed by the function's + full name, since two modules may each define one name (`average_clustering`). """ import ast import pathlib @@ -291,9 +292,11 @@ def _helper_calls(): helpers = {"to_graph", "to_undirected_graph", "to_directed_graph"} calls, preserving = {}, set() - for path in sorted(pathlib.Path(nxapi_pkg.__file__).parent.rglob("*.py")): + root = pathlib.Path(nxapi_pkg.__file__).parent + for path in sorted(root.rglob("*.py")): if "tests" in path.parts: continue + module = ".".join((nxapi_pkg.__name__, *path.relative_to(root).with_suffix("").parts)) for node in ast.walk(ast.parse(path.read_text(), str(path))): if not isinstance(node, ast.FunctionDef) or node.name.startswith("_"): continue @@ -307,7 +310,7 @@ def _helper_calls(): for call in ast.walk(node): if not isinstance(call, ast.Call) or getattr(call.func, "id", None) not in helpers: continue - calls.setdefault(node.name, set()).add(call.func.id) + calls.setdefault(f"{module}.{node.name}", set()).add(call.func.id) for keyword in call.keywords: if keyword.arg == "weight" and any( isinstance(inner, ast.Name) and inner.id in sentinel @@ -320,7 +323,11 @@ def _helper_calls(): def test_every_dispatched_wrapper_converts_through_one_of_the_three_helpers(): """The invariant binds at the helpers, so a wrapper that skips them escapes it.""" calls, _ = _helper_calls() - escapes = sorted(name for name in dispatcher_functions() if not calls.get(name)) + escapes = sorted( + name + for name, func in dispatcher_functions().items() + if not calls.get(f"{func.__module__}.{func.__name__}") + ) assert not escapes, f"dispatched wrappers that convert without a helper: {escapes}" diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py index 4bf5d09..449a8ff 100644 --- a/graphblas_algorithms/tests/test_match_nx.py +++ b/graphblas_algorithms/tests/test_match_nx.py @@ -84,16 +84,25 @@ def gb_info(): from graphblas_algorithms import nxapi # noqa: F401 (populates sys.modules) + # A function is known by where it lives, as maketree knows it: the bipartite + # `average_clustering` is registered as `bipartite_average_clustering`. + by_path = { + nx_to_gb_info((name, fullname(func), ""))[1]: name + for name, func in _registered_algorithms.items() + if func.__module__.startswith("networkx.") + } rv = {} # {modulepath: {dispatchname: NameInfo}} for modname, module in sys.modules.items(): cur = {} if not modname.startswith("graphblas_algorithms.nxapi") or "tests" in modname: continue for key, val in vars(module).items(): - if key.startswith("_") or key not in _registered_algorithms or not callable(val): + if key.startswith("_") or not callable(val): continue if getattr(val, "__module__", "").startswith("graphblas_algorithms.nxapi."): - cur[key] = NameInfo(key, fullname(val), f"{modname}.{key}") + name = by_path.get(fullname(val), key) + if name in _registered_algorithms: + cur[name] = NameInfo(name, fullname(val), f"{modname}.{key}") if cur: rv[modname] = cur return rv diff --git a/scripts/maketree.py b/scripts/maketree.py index b9b91f7..817718d 100755 --- a/scripts/maketree.py +++ b/scripts/maketree.py @@ -5,6 +5,7 @@ """ +import functools import inspect import sys from io import StringIO @@ -45,6 +46,30 @@ def public_names(modname, module): ] +@functools.cache +def _names_by_path(): + """Each registered name by its NetworkX path, as `nxapi` mirrors it: `cluster.clustering`.""" + from networkx.utils.backends import _registered_algorithms + + return { + trim(f"{func.__module__}.{func.__name__}"): name + for name, func in _registered_algorithms.items() + if func.__module__.startswith("networkx.") + } + + +def registered_name(key, func): + """The name NetworkX registers `func`, an `nxapi` function found as `key`, under. + + Found by where the function lives: `nxapi.bipartite.cluster.average_clustering` mirrors + NetworkX's `bipartite.cluster.average_clustering`, registered as + `bipartite_average_clustering`, while `average_clustering` names `cluster.average_clustering`. + A function whose module does not mirror NetworkX's is known by `key`. + """ + path = f"{func.__module__}.{func.__name__}".removeprefix("graphblas_algorithms.nxapi.") + return _names_by_path().get(path, key) + + def get_names(): """Names we implement: the `nxapi` functions that NetworkX's registry knows. @@ -71,10 +96,12 @@ def get_names(): if missing: unregistered[modname] = sorted(missing) for key, val in vars(module).items(): - if key.startswith("_") or key not in known or not callable(val): + if key.startswith("_") or not callable(val): continue if getattr(val, "__module__", "").startswith("graphblas_algorithms.nxapi."): - implemented[key] = val + name = registered_name(key, val) + if name in known: + implemented[name] = val if unregistered: import networkx