From 18bb9e4306b669027bdf57e5c6b57571bca3ed77 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 19:23:15 -0600 Subject: [PATCH] Add load centrality for nodes and for edges Serve load_centrality (newman_betweenness_centrality) and edge_load_centrality, which NetworkX computes with a Python walk from each source. Load splits what a node passes up equally among its predecessors rather than by their path counts, so the batched walk of betweenness carries each node's count of predecessors, and one multiply per level passes the shares back up. The cutoffs are NetworkX's: a count of levels as nx.predecessor stops, and the lengths Dijkstra keeps when weighted. A weighted call is served only where every edge weighs one positive value of one type, so that Dijkstra's predecessors are the levels', ties included. Other weights, nodes that may not compare when NetworkX sorts them, and a cutoff that is not a number are left to NetworkX. The name generator and the nxapi name check now accept a second name for a function, as NetworkX exports load_centrality. --- README.md | 7 +- _nx_graphblas/__init__.py | 4 + _nx_graphblas/core.py | 14 + .../algorithms/centrality/__init__.py | 1 + .../algorithms/centrality/load.py | 94 +++++ graphblas_algorithms/interface.py | 2 + .../nxapi/centrality/__init__.py | 1 + graphblas_algorithms/nxapi/centrality/load.py | 206 +++++++++++ graphblas_algorithms/nxapi/tests/test_load.py | 344 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 2 + graphblas_algorithms/tests/test_match_nx.py | 9 +- scripts/maketree.py | 14 +- 12 files changed, 693 insertions(+), 5 deletions(-) create mode 100644 graphblas_algorithms/algorithms/centrality/load.py create mode 100644 graphblas_algorithms/nxapi/centrality/load.py create mode 100644 graphblas_algorithms/nxapi/tests/test_load.py diff --git a/README.md b/README.md index 1bc06b5..a8f27b2 100644 --- a/README.md +++ b/README.md @@ -149,8 +149,11 @@ graphblas_algorithms.nxapi │ │ └── group_out_degree_centrality │ ├── harmonic │ │ └── harmonic_centrality -│ └── katz -│ └── katz_centrality +│ ├── katz +│ │ └── katz_centrality +│ └── load +│ ├── edge_load_centrality +│ └── newman_betweenness_centrality ├── cluster │ ├── average_clustering │ ├── clustering diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 90bcdcf..fbc3274 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -67,6 +67,7 @@ def get_info(): "edge_betweenness_centrality_subset", "edge_boundary", "edge_expansion", + "edge_load_centrality", "efficiency", "ego_graph", "eigenvector_centrality", @@ -124,6 +125,7 @@ def get_info(): "modularity_matrix", "mutual_weight", "negative_edge_cycle", + "newman_betweenness_centrality", "node_boundary", "node_connected_component", "node_expansion", @@ -208,6 +210,7 @@ def get_info(): "eccentricity": 'A precomputed `sp`, and the null graph, are 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.', "edge_betweenness_centrality": "Unweighted: a call with `weight` is left to NetworkX. With `k`, the sources are drawn\nfrom `seed` as NetworkX draws them, `seed.sample(list(G), k)`, and the scores are\nscaled as NetworkX scales them. The edges come by their first ends in node order, then\nby their second ends in node order, which may differ from the order of `G.edges()`.", "edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.", + "edge_load_centrality": "The pairs come by their first ends in node order, then by their second ends in node\norder, which may differ from NetworkX's order. A `cutoff` that is not an int or float\nis left to NetworkX.", "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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.', "floyd_warshall": "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.", "floyd_warshall_predecessor_and_distance": "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.", @@ -224,6 +227,7 @@ def get_info(): "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.", "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.", + "newman_betweenness_centrality": "With `weight`, served where every edge between two nodes weighs one positive, finite\nvalue, all of one type (int, float or float32), with each self-loop at least as heavy\nand lengths that keep rising to `cutoff`; NetworkX's Dijkstra then finds each level's\npredecessors, ties included. Other weights are left to NetworkX. Int weights add as\nPython ints, which do not wrap past 2**63 where NetworkX's sums of NumPy int64s do.\nNodes that may not compare with `<`, which NetworkX sorts, and a `cutoff` that is not\nan int or float are 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 35bed9e..d3bdf27 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -146,6 +146,11 @@ "in node order, then by their second ends in node order, which may differ from the order\n" "of `G.edges()`." ), + "edge_load_centrality": ( + "The pairs come by their first ends in node order, then by their second ends in node\n" + "order, which may differ from NetworkX's order. A `cutoff` that is not an int or float\n" + "is left to NetworkX." + ), "ego_graph": ( "With `distance`, lengths are Bellman-Ford's, so a negative edge without a negative\n" 'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\n' @@ -174,6 +179,15 @@ "memory stays bounded." ), "negative_edge_cycle": _PATH_OVERFLOW, + "newman_betweenness_centrality": ( + "With `weight`, served where every edge between two nodes weighs one positive, finite\n" + "value, all of one type (int, float or float32), with each self-loop at least as heavy\n" + "and lengths that keep rising to `cutoff`; NetworkX's Dijkstra then finds each level's\n" + "predecessors, ties included. Other weights are left to NetworkX. Int weights add as\n" + "Python ints, which do not wrap past 2**63 where NetworkX's sums of NumPy int64s do.\n" + "Nodes that may not compare with `<`, which NetworkX sorts, and a `cutoff` that is not\n" + "an int or float are left to NetworkX." + ), "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' diff --git a/graphblas_algorithms/algorithms/centrality/__init__.py b/graphblas_algorithms/algorithms/centrality/__init__.py index 7713385..b7a61af 100644 --- a/graphblas_algorithms/algorithms/centrality/__init__.py +++ b/graphblas_algorithms/algorithms/centrality/__init__.py @@ -6,3 +6,4 @@ from .group import * from .harmonic import * from .katz import * +from .load import * diff --git a/graphblas_algorithms/algorithms/centrality/load.py b/graphblas_algorithms/algorithms/centrality/load.py new file mode 100644 index 0000000..25ea681 --- /dev/null +++ b/graphblas_algorithms/algorithms/centrality/load.py @@ -0,0 +1,94 @@ +"""Load centrality over a batch of sources at a time, as NetworkX's load_centrality computes it. + +Load is betweenness with each unit a node passes up split equally among its predecessors, the +nodes a level above with an edge to it, rather than by their counts of shortest paths. The walk +is betweenness's, a row per source, with each level holding its nodes' predecessor counts. +""" + +from graphblas import Matrix, Vector, binary, monoid, unary +from graphblas.semiring import plus_first, plus_pair + +from .betweenness import ( + _BYTES_PER_PAIR, + _EDGE_BYTES_PER_PAIR, + _add_edge_credit, + _batches, + _sources, + _walk_matrices, +) + +__all__ = ["edge_load_centrality", "load_centrality"] + + +def load_centrality(G, *, levels=None, chunksize=None): + """Unnormalized load of each node, summed over every source. + + From a source `s`, a node `v` on level `d` passes `1 + L(v)` up, split equally among its + predecessors, where `L(v)` is what `v` got from below; a node on level 1 passes nothing, as + its one predecessor is `s`. `levels` is the most levels walked below each source, None for + all. `chunksize` is the number of sources per batch, None for a batch of about 256 MiB. + """ + A, AT = _walk_matrices(G) + result = Vector(float, A.nrows, name="load_centrality") + for batch in _batches(G, None, chunksize, _BYTES_PER_PAIR): + below = _forward(A, batch, levels) + L = None + for d in range(len(below) - 1, 0, -1): + passed = unary.one[float](below[d]).new() + if L is not None: + passed(binary.plus) << L + share = binary.truediv(passed & below[d]).new() + L = plus_first[float](share @ AT).new(mask=below[d - 1].S) + result(binary.plus) << L.reduce_columnwise(monoid.plus) + return result + + +def edge_load_centrality(G, *, levels=None, chunksize=None): + """Load of each ordered pair of nodes an edge joins, either way, summed over every source. + + From a source, an edge from a node to one of its successors a level below carries + `g(w) = 1 + U(w) / p(w)` at its lower end `w`, where `p(w)` counts `w`'s predecessors and + `U(w)` sums `g` over the edges below `w`; every other edge carries 1. A pair `(u, v)` with + an edge either way gets what both edges carry, so the Matrix is symmetric, a self-loop at + the number of nodes. `levels` and `chunksize` are as for `load_centrality`. + """ + A, AT = _walk_matrices(G) + n = A.nrows + credit = Matrix(float, n, n, name="edge_load_credit") + for batch in _batches(G, None, chunksize, _EDGE_BYTES_PER_PAIR): + below = _forward(A, batch, levels) + # `g(w) - 1` by level, the credit of each edge into a node on that level. + Y = [None] * len(below) + U = None + for d in range(len(below) - 1, -1, -1): + g = unary.one[float](below[d]).new() + if U is None: + Y[d] = Matrix(float, *below[d].shape) + else: + Y[d] = binary.truediv(U & below[d]).new() + g(binary.plus) << Y[d] + if d > 0: + U = plus_first[float](g @ AT).new(mask=below[d - 1].S) + above = [_sources(batch, n), *(unary.one[float](level).new() for level in below[:-1])] + _add_edge_credit(credit, A, above, Y) + pairs = G._A.dup(float, name="edge_load_centrality") + pairs << binary.any(pairs | pairs.T) + pairs(pairs.S) << float(n) + pairs(binary.plus) << credit + pairs(binary.plus) << credit.T + return pairs + + +def _forward(A, batch, levels): + """Each level below the sources, at most `levels`, with each node's count of predecessors.""" + level = _sources(batch, A.ncols) + seen = level.dup(name="seen") + seen.ss.config["bitmap_switch"] = 0.01 # as betweenness's `sigma` + below = [] + while levels is None or len(below) < levels: + level = plus_pair[float](level @ A).new(mask=~seen.S) + if level.nvals == 0: + break + below.append(level) + seen(binary.plus) << level + return below diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..585f567 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -255,6 +255,8 @@ class Dispatcher: group_out_degree_centrality = mod.group.group_out_degree_centrality harmonic_centrality = mod.harmonic.harmonic_centrality katz_centrality = mod.katz.katz_centrality + edge_load_centrality = mod.load.edge_load_centrality + newman_betweenness_centrality = mod.load.newman_betweenness_centrality mod = nxapi.cluster # ================= diff --git a/graphblas_algorithms/nxapi/centrality/__init__.py b/graphblas_algorithms/nxapi/centrality/__init__.py index 7713385..b7a61af 100644 --- a/graphblas_algorithms/nxapi/centrality/__init__.py +++ b/graphblas_algorithms/nxapi/centrality/__init__.py @@ -6,3 +6,4 @@ from .group import * from .harmonic import * from .katz import * +from .load import * diff --git a/graphblas_algorithms/nxapi/centrality/load.py b/graphblas_algorithms/nxapi/centrality/load.py new file mode 100644 index 0000000..b6f2ac3 --- /dev/null +++ b/graphblas_algorithms/nxapi/centrality/load.py @@ -0,0 +1,206 @@ +import math +from collections.abc import Hashable + +import numpy as np +from graphblas import dtypes + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.digraph import to_graph + +from .._utils import can_run + +__all__ = ["edge_load_centrality", "load_centrality"] + +_NAME = "newman_betweenness_centrality" +_EDGE_NAME = "edge_load_centrality" +_NUMBERS = (int, float, np.integer, np.floating) # bool is an int +# Weights whose sums NetworkX's Dijkstra makes in one arithmetic: an int and a NumPy int64 add +# as integers, a float and a NumPy float64 as doubles. +_KINDS = {int: int, np.int64: int, float: float, np.float64: float, np.float32: np.float32} +# The arithmetic of a conversion's weights, by its dtype. +_ARITHMETIC = {dtypes.INT64: int, dtypes.FP64: float, dtypes.FP32: np.float32} + + +def _cutoff_reason(name, cutoff): + if cutoff is not None and not isinstance(cutoff, _NUMBERS): + # NetworkX compares it with each level, or each length, as Python does. + return f"{name} compares a cutoff of {type(cutoff).__name__} as networkx does" + return None + + +def _weights_reason(G, weight): + """Why NetworkX's Dijkstra may not walk `G`'s levels exactly, from the graph's own weights. + + Its lengths are sums of the weights as Python adds them, so they must be one kind of number + for every walk of `d` edges to have one length; their values are checked once converted. + """ + if not isinstance(weight, Hashable) or callable(weight): + return f"{_NAME} with a weight of {type(weight).__name__} is left to networkx" + if not hasattr(G, "_adj"): + return None # this backend's own graph: its matrix is its data + import networkx as nx + + if getattr(type(G), "adjacency", None) is not nx.Graph.adjacency: + # NetworkX's Dijkstra walks `G._adj`, and a conversion reads the adjacency this class + # reports instead, as `_AntiGraph`'s complement. + return f"{_NAME} walks `G._adj` when weighted, which this graph does not report" + kinds = set() + for *_, value in G.edges(data=weight, default=1): + kind = _KINDS.get(type(value)) + if kind is None or kind is int and not -(2**63) <= value < 2**63: + return f"{_NAME} with a weight of {type(value).__name__} is left to networkx" + kinds.add(kind) + if len(kinds) > 1: + return f"{_NAME} with weights of several types is left to networkx" + return None + + +def _node_rule(bound): + if (reason := _cutoff_reason(_NAME, bound.get("cutoff"))) is not None: + return reason + if (weight := bound.get("weight")) is not None: + return _weights_reason(bound["G"], weight) + return None + + +def _edge_rule(bound): + return _cutoff_reason(_EDGE_NAME, bound.get("cutoff")) + + +def _bfs_levels(cutoff): + """The most levels NetworkX's `predecessor` walks below a source, None for all. + + It stops after the first level `cutoff` is at most, so a cutoff of 2.5 walks 3 levels and + any cutoff of 1 or less one; a false cutoff, 0 included, and NaN or inf walk them all. + """ + if not cutoff: + return None + if cutoff <= 1: + return 1 + if isinstance(cutoff, (int, np.integer)): + return int(cutoff) + if math.isnan(cutoff) or cutoff == math.inf: + return None + return math.ceil(cutoff) + + +def _one_weight(G): + """What every edge between two nodes weighs, in the arithmetic NetworkX adds it in. + + NetworkX's Dijkstra then finds a level-by-level walk's predecessors, ties exactly, if that + weight is positive and finite. A self-loop at least that heavy changes nothing; a lighter + one may tie with a node's own length, and NetworkX then lists the node among its own + predecessors (or raises "Contradictory paths" if negative). + """ + A = G._A + if (arithmetic := _ARITHMETIC.get(A.dtype)) is None: + raise NotImplementedError(f"{_NAME} with {A.dtype} weights is left to networkx") + values = G.get_property("offdiag").to_coo(rows=False, columns=False)[2] + if values.size == 0: + return 1 # no walk leaves a source + weight = values[0] + if not (values == weight).all() or not 0 < weight < math.inf: + # NetworkX's predecessors then follow its sums and the order of its walk. + raise NotImplementedError( + f"{_NAME} is served weighted only where every edge weighs one positive value" + ) + loops = G.get_property("diag").to_coo(indices=False)[1] + if not (loops >= weight).all(): # NaN too + raise NotImplementedError( + f"{_NAME} with a self-loop lighter than its edges is left to networkx" + ) + return weight.item() if arithmetic is not np.float32 else weight + + +def _dijkstra_levels(weight, cutoff, n): + """The most levels whose lengths NetworkX's Dijkstra keeps, None for all. + + A node `d` levels below a source is at `weight` added `d` times to the integer 0, as + NetworkX adds it, and a length past `cutoff` is not kept: None and NaN keep all, and False + keeps the source alone. Lengths must rise at every level below `n` that is kept, or two + levels would tie. + """ + length = 0 + for d in range(n - 1): + below = length + weight + if cutoff is not None and below > cutoff: + return d + if not length < below < math.inf: + raise NotImplementedError(f"{_NAME} with lengths that stop rising is left to networkx") + length = below + return None + + +def _keys_compare(G): + """True if any two of `G`'s nodes compare with `<`, as NetworkX's sort may compare them. + + It sorts `(length, node)` pairs, so two nodes at one length are compared. Numbers compare + with numbers and strings with strings, and tuples of them where each position holds one kind. + """ + kinds = set() + positions = {} + for key in G._key_to_id: + if isinstance(key, _NUMBERS): + kinds.add("number") + elif isinstance(key, str): + kinds.add("str") + elif isinstance(key, tuple): + kinds.add("tuple") + for i, item in enumerate(key): + if isinstance(item, _NUMBERS): + positions.setdefault(i, set()).add("number") + elif isinstance(item, str): + positions.setdefault(i, set()).add("str") + else: + return False + else: + return False + if len(kinds) > 1: + return False + return all(len(kind) == 1 for kind in positions.values()) + + +@can_run(_node_rule) +def newman_betweenness_centrality(G, v=None, cutoff=None, normalized=True, weight=None): + bound = {"G": G, "v": v, "cutoff": cutoff, "normalized": normalized, "weight": weight} + if (reason := _node_rule(bound)) is not None: + raise NotImplementedError(reason) + G = to_graph(G, weight=weight) + n = len(G) + # Below three nodes no source reaches two nodes at one length. + if n > 2 and not G._cacheit("keys_compare", _keys_compare, G): + raise NotImplementedError( + f"{_NAME} sorts nodes at one length, and these may not compare; networkx serves it" + ) + if weight is None: + levels = _bfs_levels(cutoff) + else: + levels = _dijkstra_levels(_one_weight(G), cutoff, n) + result = algorithms.load_centrality(G, levels=levels) + scale = 1.0 / ((n - 1) * (n - 2)) if normalized and n > 2 else None + if v is not None: + # NetworkX looks `v` up in each source's dict, so an unhashable one raises there. + betweenness = 0.0 + if n and v in G._key_to_id: + betweenness += result.get(G._key_to_id[v], 0.0) + return betweenness if scale is None else betweenness * scale + if scale is not None: + result << result * scale + return G.vector_to_nodemap(result, fill_value=0.0) + + +load_centrality = newman_betweenness_centrality # as NetworkX names it + + +@can_run(_edge_rule) +def edge_load_centrality(G, cutoff=False): + if (reason := _edge_rule({"G": G, "cutoff": cutoff})) is not None: + raise NotImplementedError(reason) + G = to_graph(G) + E = algorithms.edge_load_centrality(G, levels=_bfs_levels(cutoff)) + rows, cols, values = E.to_coo() + id_to_key = G.id_to_key + return { + (id_to_key[row], id_to_key[col]): value + for row, col, value in zip(rows.tolist(), cols.tolist(), values.tolist(), strict=True) + } diff --git a/graphblas_algorithms/nxapi/tests/test_load.py b/graphblas_algorithms/nxapi/tests/test_load.py new file mode 100644 index 0000000..8cedac6 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_load.py @@ -0,0 +1,344 @@ +"""load_centrality (newman_betweenness_centrality) and edge_load_centrality against NetworkX. + +Keys are compared exactly and values within a relative 1e-12. Each value is a sum of positive +terms, which NetworkX adds source by source and node by node in its walk's order and this +backend in a batch's; NetworkX also adds 1 to each share a node passes up and takes it off at +the end, which rounds a small share. On these graphs the largest relative difference is 4e-16; +on a 70 by 70 grid, 3e-13. A zero is compared exactly. +""" + +import math +from decimal import Decimal +from fractions import Fraction +from functools import partial + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms import DiGraph, Graph, algorithms +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +NODE = "newman_betweenness_centrality" +EDGE_NAME = "edge_load_centrality" +LOAD = nx.load_centrality +EDGE = nx.edge_load_centrality +REL = 1e-12 + + +def outcome(f): + """What `f()` gives: its value, or its exception's type and args.""" + try: + return ("value", f()) + except Exception as exc: + return ("raises", type(exc), exc.args) + + +def assert_close(got, want): + """`want`'s keys exactly and its values within REL; a single node's load is a float.""" + if isinstance(want, dict): + got = dict(got) + assert got.keys() == want.keys() + assert got == pytest.approx(want, rel=REL, abs=0) + else: + assert type(got) is float + assert got == pytest.approx(want, rel=REL, abs=0) + + +# Every edge weighs one value, or no edge has the attribute: what is served weighted. +WEIGHTS = [None, None, "ints", "floats", "float32", "missing"] +VALUES = {"ints": 3, "floats": 0.7, "float32": np.float32(0.3)} +CUTOFFS = [None, None, 0, 1, 2, 2.5, 3, -1, 0.5, math.nan, math.inf, False, True, 10**30] + + +def random_graph(seed): + """A small graph, directed or not, often in pieces, with self-loops, some with str labels.""" + rng = np.random.default_rng(seed) + n = int(rng.integers(22)) + G = nx.DiGraph() if rng.random() < 0.5 else nx.Graph() + G.add_nodes_from(rng.permutation(n).tolist()) + kind = WEIGHTS[seed % len(WEIGHTS)] + value = VALUES.get(kind) + for _ in range(int(rng.integers(3 * n + 1))): + u, v = rng.integers(n, size=2).tolist() + if value is None: + G.add_edge(u, v) + else: + G.add_edge(u, v, weight=value) + if seed % 3 == 0: + G = nx.relabel_nodes(G, {i: f"n{i}" for i in range(n)}) + return G, None if kind is None else "weight", rng + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs_as_networkx(seed): + G, weight, rng = random_graph(seed) + cutoff = CUTOFFS[int(rng.integers(len(CUTOFFS)))] + kwargs = {"cutoff": cutoff, "normalized": bool(rng.integers(2)), "weight": weight} + assert_close(LOAD(G, backend="graphblas", **kwargs), LOAD(G, **kwargs)) + nodes = list(G) + some = [nodes[i] for i in rng.choice(len(nodes), min(2, len(nodes)), replace=False)] + for v in [*some, "absent"]: + assert_close(LOAD(G, v, backend="graphblas", **kwargs), LOAD(G, v, **kwargs)) + cutoff = CUTOFFS[int(rng.integers(len(CUTOFFS)))] + assert_close(EDGE(G, cutoff=cutoff, backend="graphblas"), EDGE(G, cutoff=cutoff)) + + +@pytest.mark.parametrize( + "graph", + [ + nx.path_graph(1), + nx.path_graph(2), + nx.path_graph(3), + nx.DiGraph([(0, 1)]), + nx.Graph(), + nx.DiGraph(), + nx.empty_graph(4), + ], + ids=[ + "one node", + "two nodes", + "three nodes", + "directed pair", + "null", + "null directed", + "no edges", + ], +) +@pytest.mark.parametrize("normalized", [True, False]) +def test_small_graphs_are_scaled_as_networkx_scales_them(graph, normalized): + """Two nodes or fewer are not scaled; NetworkX returns them as they are.""" + assert_close( + LOAD(graph, normalized=normalized, backend="graphblas"), LOAD(graph, normalized=normalized) + ) + for v in [*graph, "absent"]: + assert_close( + LOAD(graph, v, normalized=normalized, backend="graphblas"), + LOAD(graph, v, normalized=normalized), + ) + assert_close(EDGE(graph, backend="graphblas"), EDGE(graph)) + + +def test_a_node_that_is_not_hashable_raises_as_networkx(): + G = nx.path_graph(4) + want = outcome(partial(LOAD, G, [1])) + assert want[0] == "raises" + assert outcome(partial(LOAD, G, [1], backend="graphblas")) == want + # With no nodes NetworkX never looks it up. + assert LOAD(nx.Graph(), [1], backend="graphblas") == LOAD(nx.Graph(), [1]) == 0.0 + + +@pytest.mark.parametrize("cutoff", [Decimal(1), Fraction(1, 2), "1", [1]]) +@pytest.mark.parametrize("name", [NODE, EDGE_NAME]) +def test_a_cutoff_that_is_not_a_number_is_declined(name, cutoff): + G = nx.path_graph(4) + assert isinstance(Dispatcher.can_run(name, (G,), {"cutoff": cutoff}), str) + assert Dispatcher.can_run(name, (G,), {"cutoff": 2.5}) is True + + +@pytest.mark.parametrize("weight", [None, 2, 0.5, np.float32(0.5)]) +def test_a_cutoff_past_the_floats_compares_as_networkx_s(weight): + """10**400 is no float: NumPy raises comparing a float32 with it, Python compares exactly.""" + G = nx.path_graph(5) + attr = None if weight is None else "weight" + if attr: + nx.set_edge_attributes(G, weight, attr) + for cutoff in [10**400, np.int64(2)]: + want = outcome(partial(LOAD, G, cutoff=cutoff, weight=attr)) + got = outcome(partial(LOAD, G, cutoff=cutoff, weight=attr, backend="graphblas")) + if want[0] == "value": + assert got[0] == "value" + assert_close(got[1], want[1]) + else: + assert got == want + assert_close(EDGE(G, cutoff=10**400, backend="graphblas"), EDGE(G, cutoff=10**400)) + + +DECLINED_WEIGHTS = { + "two weights": [(0, 1, 1), (1, 2, 2), (0, 2, 3), (2, 3, 1)], + "ties of floats": [(0, 1, 0.1), (1, 2, 0.2), (0, 2, 0.3), (2, 3, 0.1)], + "zero": [(0, 1, 0), (1, 2, 0), (2, 3, 0)], + "negative": [(0, 1, -1), (1, 2, -1)], + "inf": [(0, 1, math.inf), (1, 2, math.inf)], + "a negative self-loop": [(0, 1, 1), (1, 2, 1), (1, 1, -1)], + "a zero self-loop": [(0, 1, 1), (1, 2, 1), (2, 3, 1), (2, 2, 0)], + "an infinite self-loop": [(0, 1, 1.0), (1, 2, 1.0), (1, 1, math.inf)], +} + + +@pytest.mark.parametrize("graph", sorted(DECLINED_WEIGHTS)) +@pytest.mark.parametrize("directed", [False, True]) +def test_weights_networkx_walks_by_its_own_order_are_left_to_it(graph, directed): + """NetworkX's Dijkstra predecessors follow its float sums and walk; it answers these.""" + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(5)) + G.add_weighted_edges_from(DECLINED_WEIGHTS[graph]) + if graph == "an infinite self-loop" and directed: + # Its matrix holds inf, heavier than the edges; an undirected one's holds NaN. + assert_close(LOAD(G, weight="weight", backend="graphblas"), LOAD(G, weight="weight")) + return + with pytest.raises(NotImplementedError): + LOAD(G, weight="weight", backend="graphblas") + want = outcome(partial(LOAD, G, weight="weight")) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + assert repr(outcome(partial(LOAD, G, weight="weight"))) == repr(want) + # Unweighted, the same graph is served. + assert_close(LOAD(G, backend="graphblas"), LOAD(G)) + + +def test_one_weight_on_every_edge_is_served_with_networkx_s_cutoff(): + """NetworkX's Dijkstra keeps a length within the cutoff: 0.7 added, not multiplied.""" + G = nx.path_graph(12) + nx.set_edge_attributes(G, 0.7, "weight") + # 0.7 added ten times is 6.999999999999999, kept by a cutoff of 7 with an eleventh edge. + for cutoff in [None, 0, False, -1, 0.7, 2.1, 6.999999999999999, 7, 7.7, math.nan, 10**30]: + want = LOAD(G, weight="weight", cutoff=cutoff, normalized=False) + assert_close( + LOAD(G, weight="weight", cutoff=cutoff, normalized=False, backend="graphblas"), want + ) + + +def test_float32_weights_add_and_compare_as_networkx_s_do(): + """NumPy adds float32 to float32, and compares a float cutoff in float32.""" + G = nx.path_graph(12) + nx.set_edge_attributes(G, np.float32(0.7), "weight") + # Three float32 0.7s make float32(2.1), and 2.1 compares as float32(2.1): not past it. + for cutoff in [2.1, 2.1000001, 2.0999999, np.float64(2.1), 4.9, 4.8999999, None]: + want = LOAD(G, weight="weight", cutoff=cutoff, normalized=False) + assert_close( + LOAD(G, weight="weight", cutoff=cutoff, normalized=False, backend="graphblas"), want + ) + + +def test_heavy_weights_are_served_until_lengths_stop_rising(): + """1e308 added twice is inf, and a third time inf again: NetworkX's levels would tie.""" + G = nx.path_graph(5) + nx.set_edge_attributes(G, 1e308, "weight") + with pytest.raises(NotImplementedError): + LOAD(G, weight="weight", backend="graphblas") + # A cutoff that keeps only finite lengths is served. + for cutoff in [1e308, 1.5e308]: + want = LOAD(G, weight="weight", cutoff=cutoff) + assert_close(LOAD(G, weight="weight", cutoff=cutoff, backend="graphblas"), want) + + +def test_a_self_loop_at_least_as_heavy_as_the_edges_is_served(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 2), (1, 2, 2), (2, 3, 2), (1, 1, 2), (2, 2, 5)]) + assert_close(LOAD(G, weight="weight", backend="graphblas"), LOAD(G, weight="weight")) + G.add_edge(3, 3, weight=1) + with pytest.raises(NotImplementedError): + LOAD(G, weight="weight", backend="graphblas") + + +WEIGHT_KINDS = { + "int and float": [1, 1.0, 1, 1], + "float32 and float": [np.float32(0.5), 0.5, 0.5, 0.5], + "int32": [np.int32(1)] * 4, + "float16": [np.float16(1)] * 4, + "bool": [True] * 4, + "past int64": [2**63] * 4, + "Fraction": [Fraction(1, 3)] * 4, +} + + +@pytest.mark.parametrize("kind", sorted(WEIGHT_KINDS)) +def test_weights_of_another_kind_are_left_to_networkx(kind): + """NetworkX adds a graph's weights as their own types; these are not added as one kind.""" + G = nx.path_graph(5) + for (u, v), w in zip(G.edges, WEIGHT_KINDS[kind], strict=True): + G[u][v]["weight"] = w + assert isinstance(Dispatcher.can_run(NODE, (G,), {"weight": "weight"}), str) + want = outcome(partial(LOAD, G, weight="weight")) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + assert repr(outcome(partial(LOAD, G, weight="weight"))) == repr(want) + + +@pytest.mark.parametrize("weight", [["weight"], lambda u, v, d: 1], ids=["unhashable", "callable"]) +@pytest.mark.parametrize("edges", [[(0, 1), (1, 2)], []], ids=["edges", "no edges"]) +def test_a_weight_that_is_no_key_is_left_to_networkx(weight, edges): + G = nx.Graph(edges) + G.add_node(5) + assert isinstance(Dispatcher.can_run(NODE, (G,), {"weight": weight}), str) + want = outcome(partial(LOAD, G, weight=weight)) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + assert repr(outcome(partial(LOAD, G, weight=weight))) == repr(want) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_nodes_that_may_not_compare_are_left_to_networkx(directed): + """NetworkX sorts each source's (level, node) pairs, so two nodes of one level meet.""" + G = nx.DiGraph() if directed else nx.Graph() + G.add_edges_from([(0, "a"), (0, "b"), ("a", 1), ("b", 1)]) + with pytest.raises(NotImplementedError): + LOAD(G, backend="graphblas") + want = outcome(partial(LOAD, G)) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + assert outcome(partial(LOAD, G)) == want + # The edges' version sorts by level alone. + assert_close(EDGE(G, backend="graphblas"), EDGE(G)) + + +def test_tuples_of_numbers_compare_and_are_served(): + G = nx.grid_2d_graph(4, 5) + assert_close(LOAD(G, backend="graphblas"), LOAD(G)) + H = nx.relabel_nodes(G, {(i, j): (i, str(j)) for i, j in G}) + assert_close(LOAD(H, backend="graphblas"), LOAD(H)) + K = nx.relabel_nodes(G, {(i, j): (i, str(j) if i else j) for i, j in G}) + with pytest.raises(NotImplementedError): + LOAD(K, backend="graphblas") + + +def test_a_weighted_graph_reporting_another_adjacency_is_declined(): + class Reported(nx.Graph): + def adjacency(self): + return iter([]) + + G = Reported(nx.path_graph(4)) + assert isinstance(Dispatcher.can_run(NODE, (G,), {"weight": "weight"}), str) + assert Dispatcher.can_run(NODE, (G,), {}) is True + + +def test_weights_are_read_only_when_asked_for(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 1), (1, 2, 5), (0, 2, 3), (2, 3, 2), (3, 4, 1)]) + assert_close(LOAD(G, backend="graphblas"), LOAD(G)) + assert_close(EDGE(G, backend="graphblas"), EDGE(G)) + + +@pytest.mark.parametrize("chunksize", [1, 2, 5]) +def test_small_batches_give_the_same_loads(chunksize): + H = nx.gnm_random_graph(30, 70, seed=4, directed=True) + G = DiGraph.from_networkx(H) + for levels in [None, 2]: + want = algorithms.load_centrality(G, levels=levels) + got = algorithms.load_centrality(G, levels=levels, chunksize=chunksize) + assert got.isclose(want, rel_tol=REL) + want = algorithms.edge_load_centrality(G, levels=levels) + got = algorithms.edge_load_centrality(G, levels=levels, chunksize=chunksize) + assert got.isclose(want, rel_tol=REL) + + +def test_a_direct_call_declines_what_dispatch_declines(): + from graphblas_algorithms import nxapi + + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1.0)]) + with pytest.raises(NotImplementedError, match="several types"): + nxapi.load_centrality(G, weight="weight") + # Converted directly, a function would weigh every edge 1. + with pytest.raises(NotImplementedError, match="weight of function"): + nxapi.load_centrality(G, weight=lambda u, v, d: d["weight"]) + with pytest.raises(NotImplementedError, match="cutoff of str"): + nxapi.edge_load_centrality(G, cutoff="1") + assert nxapi.load_centrality is nxapi.centrality.load.newman_betweenness_centrality + + +def test_a_backend_graph_is_answered(): + H = nx.karate_club_graph() + G = Graph.from_networkx(H) + assert_close(LOAD(G), LOAD(H)) + assert_close(LOAD(G, 0, normalized=False), LOAD(H, 0, normalized=False)) + assert_close(EDGE(G), EDGE(H)) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..54c52f6 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -112,6 +112,7 @@ def call_args(kind, args): "edge_betweenness_centrality_subset": ("undirected", ([0, 1], [2, 3])), "edge_boundary": ("undirected", ([0, 1], [2, 3], True)), "edge_expansion": ("undirected", ([0, 1], [2, 3])), + "edge_load_centrality": ("undirected", ()), "efficiency": ("undirected", (0, 2)), "ego_graph": ("undirected", (0,)), "eigenvector_centrality": ("undirected", ()), @@ -171,6 +172,7 @@ def call_args(kind, args): "modularity_matrix": ("undirected", ()), "mutual_weight": ("directed", (0, 1)), "negative_edge_cycle": ("undirected", ()), + "newman_betweenness_centrality": ("undirected", ()), "node_boundary": ("undirected", ([0, 1], [2, 3])), "node_connected_component": ("undirected", (0,)), "node_expansion": ("undirected", ([0, 1],)), diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py index 4bf5d09..263b104 100644 --- a/graphblas_algorithms/tests/test_match_nx.py +++ b/graphblas_algorithms/tests/test_match_nx.py @@ -90,10 +90,15 @@ def gb_info(): 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 + # A name for a function defined under another, as NetworkX's `load_centrality` is. + dname = key if key in _registered_algorithms else getattr(val, "__name__", None) + if dname not in _registered_algorithms: continue if getattr(val, "__module__", "").startswith("graphblas_algorithms.nxapi."): - cur[key] = NameInfo(key, fullname(val), f"{modname}.{key}") + # As `nx_info`, a module's later name for a function replaces its earlier one. + cur[dname] = NameInfo(dname, fullname(val), f"{modname}.{key}") if cur: rv[modname] = cur return rv diff --git a/scripts/maketree.py b/scripts/maketree.py index b9b91f7..a4b63ae 100755 --- a/scripts/maketree.py +++ b/scripts/maketree.py @@ -45,6 +45,14 @@ def public_names(modname, module): ] +def _alias_of(module, name): + """The name the function `module.name` was defined with; None if it is no function. + + NetworkX's `load_centrality`, for one, is its other name for `newman_betweenness_centrality`. + """ + return getattr(getattr(module, name, None), "__name__", None) + + def get_names(): """Names we implement: the `nxapi` functions that NetworkX's registry knows. @@ -67,7 +75,11 @@ def get_names(): continue if any(part.startswith("_") for part in modname.split(".")[1:]): continue - missing = [name for name in public_names(modname, module) if name not in known] + missing = [ + name + for name in public_names(modname, module) + if name not in known and _alias_of(module, name) not in known + ] if missing: unregistered[modname] = sorted(missing) for key, val in vars(module).items():