From 8f200a005335db1868a272e7f912cd3d4d9cbd6e Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 19:42:54 -0600 Subject: [PATCH] Add global_reaching_centrality and local_reaching_centrality On a directed graph a node's local reaching centrality is the share of the other nodes it reaches; on an undirected one each node at length d counts 1/d. The global value needs it for every node, so the nodes are walked in blocks, one breadth-first search from every source of a block at once. A directed value is a ratio of counts, and the global value sums the shortfalls in node order with Python's sum, as NetworkX does, so both are NetworkX's to the bit. An undirected local value sums NetworkX's terms in its order, so it matches to the bit too. The undirected global value adds each level's count over its length, so it can differ from NetworkX's in the last bits. A weight is left to NetworkX: it averages the weights along the path its Dijkstra picks, and paths of equal length can average differently. Given paths are left to it as well, and so is a v of None, which NetworkX reads as every source before raising on the result. Errors are NetworkX's, in its order. --- README.md | 7 +- _nx_graphblas/__init__.py | 4 + _nx_graphblas/core.py | 9 + .../algorithms/centrality/__init__.py | 1 + .../algorithms/centrality/reaching.py | 72 +++++++ graphblas_algorithms/interface.py | 2 + .../nxapi/centrality/__init__.py | 1 + .../nxapi/centrality/reaching.py | 50 +++++ .../nxapi/tests/test_reaching.py | 197 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 2 + 10 files changed, 343 insertions(+), 2 deletions(-) create mode 100644 graphblas_algorithms/algorithms/centrality/reaching.py create mode 100644 graphblas_algorithms/nxapi/centrality/reaching.py create mode 100644 graphblas_algorithms/nxapi/tests/test_reaching.py diff --git a/README.md b/README.md index 1bc06b5..45c31c3 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 +│ └── reaching +│ ├── global_reaching_centrality +│ └── local_reaching_centrality ├── cluster │ ├── average_clustering │ ├── clustering diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..5d6b339 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -78,6 +78,7 @@ def get_info(): "full_join", "generalized_degree", "global_efficiency", + "global_reaching_centrality", "google_matrix", "group_closeness_centrality", "group_degree_centrality", @@ -118,6 +119,7 @@ def get_info(): "katz_centrality", "laplacian_matrix", "local_efficiency", + "local_reaching_centrality", "lowest_common_ancestor", "mixing_expansion", "modularity", @@ -211,6 +213,7 @@ def get_info(): "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.", + "global_reaching_centrality": "Unweighted: a call with `weight` is left to NetworkX, which averages the weights along\nthe path its Dijkstra picks among paths of equal length.", "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", "gutman_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.', "harmonic_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', @@ -223,6 +226,7 @@ def get_info(): "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.", "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.", + "local_reaching_centrality": "Unweighted: a call with `weight` is left to NetworkX, which averages the weights along\nthe path its Dijkstra picks among paths of equal length. So are given `paths`.", "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.", "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.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..0b72509 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -99,6 +99,13 @@ # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. +# NetworkX averages the weights along the path its Dijkstra picks, and paths of equal length +# can average differently. +_REACHING_WEIGHTED = ( + "Unweighted: a call with `weight` is left to NetworkX, which averages the weights along\n" + "the path its Dijkstra picks among paths of equal length." +) + _ADDITIONAL_DOCS = { "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, "average_shortest_path_length": ( @@ -151,6 +158,7 @@ ), "floyd_warshall": _PATH_OVERFLOW, "floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW, + "global_reaching_centrality": _REACHING_WEIGHTED, "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, @@ -170,6 +178,7 @@ "neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n" "memory stays bounded." ), + "local_reaching_centrality": _REACHING_WEIGHTED + " So are given `paths`.", "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, diff --git a/graphblas_algorithms/algorithms/centrality/__init__.py b/graphblas_algorithms/algorithms/centrality/__init__.py index 7713385..913a3cd 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 .reaching import * diff --git a/graphblas_algorithms/algorithms/centrality/reaching.py b/graphblas_algorithms/algorithms/centrality/reaching.py new file mode 100644 index 0000000..d321e35 --- /dev/null +++ b/graphblas_algorithms/algorithms/centrality/reaching.py @@ -0,0 +1,72 @@ +import itertools + +import numpy as np +from graphblas import Matrix, agg, replace +from graphblas.semiring import any_pair + +from .._bfs import _adjacency, _bfs_level, _bfs_plain, _visited + +__all__ = ["global_reaching_centrality", "local_reaching_centrality"] + +# The most (source, node) slots one block of walks holds; its bitmap is this many bytes. A +# graph of up to 8192 nodes is walked in one block. +_BLOCK_SLOTS = 2**26 + + +def _reaching(G, ids): + """The local reaching centrality of each node of `ids`, by one walk from all of them at once. + + A breadth-first search from every source of the block, one product per level. On a + directed graph a node's value is the share of the other nodes it reaches. On an undirected + one it is the sum of `1 / d` over the nodes at length `d`, as a share of the other nodes: + each level adds its count over its length, so the sum depends only on how many nodes each + level holds. + """ + A = _adjacency(G) + n = A.nrows + frontier = Matrix.from_coo(np.arange(len(ids)), ids, True, nrows=len(ids), ncols=n) + seen = _visited(frontier.dup(name="seen")) + sums = np.zeros(len(ids)) + any_pair_bool = any_pair[bool] + for length in itertools.count(1): + frontier(~seen.S, replace) << any_pair_bool(frontier @ A) + if frontier.nvals == 0: + break + seen(frontier.S) << True + if not G.is_directed(): + rows, counts = frontier.reduce_rowwise(agg.count).new().to_coo() + sums[rows] += counts / length + if G.is_directed(): + rows, counts = seen.reduce_rowwise(agg.count).new().to_coo() + sums[rows] = counts - 1 + return sums / (n - 1) + + +def global_reaching_centrality(G): + """The mean, over the nodes, of how far each falls short of the most any node reaches. + + NetworkX's local values in id order, which is node order for a converted graph, summed by + Python's `sum` as NetworkX sums them. + """ + n = len(G) + size = max(1, _BLOCK_SLOTS // n) + local = np.empty(n) + for start in range(0, n, size): + ids = np.arange(start, min(start + size, n), dtype=np.uint64) + local[ids] = _reaching(G, ids) + return sum((local.max() - local).tolist()) / (n - 1) + + +def local_reaching_centrality(G, v): + """The share of the other nodes `v` reaches; undirected, each counts `1 / d` at length `d`. + + The undirected terms are NetworkX's, nearest first, summed by Python's `sum` as NetworkX + sums them. + """ + n = len(G) + if G.is_directed(): + return (_bfs_plain(G, v).nvals - 1) / (n - 1) + _, levels = _bfs_level(G, v).to_coo() + per_level = np.bincount(levels)[1:] + terms = np.repeat(1 / np.arange(1, len(per_level) + 1), per_level) + return sum(terms.tolist()) / (n - 1) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..1695364 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 + global_reaching_centrality = mod.reaching.global_reaching_centrality + local_reaching_centrality = mod.reaching.local_reaching_centrality mod = nxapi.cluster # ================= diff --git a/graphblas_algorithms/nxapi/centrality/__init__.py b/graphblas_algorithms/nxapi/centrality/__init__.py index 7713385..913a3cd 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 .reaching import * diff --git a/graphblas_algorithms/nxapi/centrality/reaching.py b/graphblas_algorithms/nxapi/centrality/reaching.py new file mode 100644 index 0000000..8b81ded --- /dev/null +++ b/graphblas_algorithms/nxapi/centrality/reaching.py @@ -0,0 +1,50 @@ +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.digraph import to_graph + +from .._utils import can_run +from ..exception import NetworkXError, NodeNotFound + +__all__ = ["global_reaching_centrality", "local_reaching_centrality"] + + +def _unweighted_without_paths(bound): + # With a weight NetworkX averages the weights along the path its Dijkstra picks among + # paths of equal length, so the answer turns on its tie-breaks. + if bound["weight"] is not None: + return "a weighted reaching centrality is left to networkx, as its ties pick the answer" + if bound.get("paths") is not None: + return "given `paths` are read by networkx" + # NetworkX's `shortest_path` reads a `v` of None as every source, and the lengths it then + # takes of the generator raise TypeError (directed) or AttributeError: its errors to give. + if "v" in bound and bound["v"] is None: + return "a `v` of None is left to networkx" + return None + + +def _check(G, name, bound): + # A direct call does not pass through `can_run`. + if (reason := _unweighted_without_paths(bound)) is not None: + raise NotImplementedError(f"{name}: {reason}") + # NetworkX's checks, in its order; `G.size()` counts a self-loop. + if G._A.nvals > 0 and len(G) == 1: + raise NetworkXError( + "local_reaching_centrality of a single node with self-loop not well-defined" + ) + if G._A.nvals == 0: + raise NetworkXError("Size of G must be positive") + + +@can_run(_unweighted_without_paths) +def global_reaching_centrality(G, weight=None, normalized=True): + G = to_graph(G) + _check(G, "global_reaching_centrality", {"weight": weight}) + return algorithms.global_reaching_centrality(G) + + +@can_run(_unweighted_without_paths) +def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True): + G = to_graph(G) + _check(G, "local_reaching_centrality", {"weight": weight, "paths": paths, "v": v}) + if v not in G: + raise NodeNotFound(f"Source {v} not in G") + return algorithms.local_reaching_centrality(G, v) diff --git a/graphblas_algorithms/nxapi/tests/test_reaching.py b/graphblas_algorithms/nxapi/tests/test_reaching.py new file mode 100644 index 0000000..b3b9044 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_reaching.py @@ -0,0 +1,197 @@ +"""Reaching centrality against NetworkX, through the backend. + +On a directed graph a node's local value is the share of the other nodes it reaches, a ratio of +counts, so every value is NetworkX's to the bit. On an undirected one it adds `1 / d` for each +node at length `d`: the local value sums NetworkX's terms in its order, so it is NetworkX's to the +bit too, while the global one sums each level's count over its length, within 1e-12 of NetworkX's. +""" + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms.centrality import reaching + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + + +def random_graph(seed): + """A random graph, directed for an even seed. + + Some have self-loops, isolated nodes, or labels whose order is not the order of their + numbers; each has an edge. + """ + rng = np.random.default_rng(seed) + n = int(rng.choice([2, 3, 5, 8, 13, 30, 60])) + p = float(rng.choice([0.02, 0.05, 0.1, 0.3, 0.7])) + G = nx.gnp_random_graph(n, p, seed=int(rng.integers(2**32)), directed=seed % 2 == 0) + for _ in range(int(rng.choice([0, 0, 1, 3]))): + u = int(rng.integers(n)) + G.add_edge(u, u) + G.add_nodes_from(range(n, n + int(rng.choice([0, 0, 1, 3])))) + if rng.random() < 0.3: + nodes = [f"v{node}" for node in G] + H = G.__class__() + H.add_nodes_from(nodes[i] for i in rng.permutation(len(nodes))) + H.add_edges_from((f"v{u}", f"v{v}") for u, v in G.edges) + G = H + if G.size() == 0: + G.add_edge(*list(G)[:2]) + return G + + +def outcome(func, *args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as exc: + return type(exc), str(exc) + + +@pytest.mark.parametrize("seed", range(320)) +def test_random_graphs_as_networkx(seed): + G = random_graph(seed) + expected = nx.global_reaching_centrality(G) + got = nx.global_reaching_centrality(G, backend="graphblas") + if G.is_directed(): + assert got == expected + else: + assert got == pytest.approx(expected, rel=1e-12) + for v in list(G)[:12]: + assert nx.local_reaching_centrality(G, v, backend="graphblas") == ( + nx.local_reaching_centrality(G, v) + ) + + +@pytest.mark.parametrize("slots", [40, 100, 2**26]) +@pytest.mark.parametrize("directed", [False, True]) +def test_any_block_size(monkeypatch, slots, directed): + """40 slots over 30 nodes walk one source per block, 100 three.""" + G = nx.gnp_random_graph(30, 0.08, seed=7, directed=directed) + expected = nx.global_reaching_centrality(G) + monkeypatch.setattr(reaching, "_BLOCK_SLOTS", slots) + assert nx.global_reaching_centrality(G, backend="graphblas") == pytest.approx( + expected, rel=1e-12 + ) + + +def self_loop_only(cls): + G = cls() + G.add_edge(0, 0) + return G + + +def isolated_pair(cls): + G = cls() + G.add_nodes_from([0, 1]) + return G + + +ERRORS = { + "no nodes": (lambda cls: cls(), 0), + "no edges": (isolated_pair, 0), + "one node with a self-loop": (self_loop_only, 0), + "an absent node": (lambda cls: cls([(0, 1)]), 5), + "an unhashable node": (lambda cls: cls([(0, 1)]), [0]), + "an absent node, no edges": (isolated_pair, 5), + "an absent node, one node with a self-loop": (self_loop_only, 5), +} + + +@pytest.mark.parametrize("case", sorted(ERRORS)) +@pytest.mark.parametrize("cls", [nx.Graph, nx.DiGraph]) +@pytest.mark.parametrize("name", ["global", "local"]) +def test_errors_as_networkx(case, cls, name): + make, v = ERRORS[case] + if name == "global": + expected = outcome(nx.global_reaching_centrality, make(cls)) + got = outcome(nx.global_reaching_centrality, make(cls), backend="graphblas") + else: + expected = outcome(nx.local_reaching_centrality, make(cls), v) + got = outcome(nx.local_reaching_centrality, make(cls), v, backend="graphblas") + assert got == expected + + +def test_the_errors_are_networkx_s(): + assert outcome(nx.local_reaching_centrality, nx.DiGraph([(0, 1)]), 5, backend="graphblas") == ( + nx.NodeNotFound, + "Source 5 not in G", + ) + assert outcome(nx.global_reaching_centrality, nx.Graph(), backend="graphblas") == ( + nx.NetworkXError, + "Size of G must be positive", + ) + + +def test_a_self_loop_beside_other_nodes_is_served(): + G = nx.Graph([(0, 1)]) + G.add_edge(2, 2) + assert nx.global_reaching_centrality(G, backend="graphblas") == 0.25 + + +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", ["global", "local"]) +def test_a_weight_is_left_to_networkx(directed, name): + G = nx.gnp_random_graph(12, 0.3, seed=3, directed=directed) + for u, v in G.edges: + G[u][v]["weight"] = 1 + (u * v) % 3 + func = nx.global_reaching_centrality if name == "global" else nx.local_reaching_centrality + args = (G,) if name == "global" else (G, 0) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + func(*args, weight="weight", backend="graphblas") + with nx.config.backend_priority(algos=["graphblas"]): + assert func(*args, weight="weight") == func(*args, weight="weight", backend="networkx") + + +def test_given_paths_are_left_to_networkx(): + G = nx.DiGraph([(0, 1), (1, 2)]) + paths = nx.shortest_path(G, source=0) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + nx.local_reaching_centrality(G, 0, paths=paths, backend="graphblas") + + +@pytest.mark.parametrize( + ("func", "args"), + [ + (nxapi.global_reaching_centrality, ()), + (nxapi.local_reaching_centrality, (0,)), + ], +) +def test_a_direct_call_refuses_what_can_run_declines(func, args): + with pytest.raises(NotImplementedError, match="weighted reaching centrality"): + func(nx.DiGraph([(0, 1)]), *args, weight="weight") + + +def test_a_direct_call_refuses_given_paths(): + with pytest.raises(NotImplementedError, match="paths"): + nxapi.local_reaching_centrality(nx.DiGraph([(0, 1)]), 0, paths={0: [0]}) + + +@pytest.mark.parametrize( + "make", [lambda cls: cls([(0, 1), (1, 2)]), isolated_pair, self_loop_only, lambda cls: cls()] +) +@pytest.mark.parametrize("cls", [nx.Graph, nx.DiGraph]) +def test_a_v_of_none_is_left_to_networkx(cls, make): + """NetworkX reads None as every source and raises on what it gets back, after its checks.""" + expected = outcome(nx.local_reaching_centrality, make(cls), None) + assert isinstance(expected, tuple) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + nx.local_reaching_centrality(make(cls), None, backend="graphblas") + with nx.config.backend_priority(algos=["graphblas"]): + assert outcome(nx.local_reaching_centrality, make(cls), None) == expected + with pytest.raises(NotImplementedError, match="`v` of None"): + nxapi.local_reaching_centrality(make(cls), None) + # Any other `v` NetworkX's `G` does not hold, hashable or not, is its NodeNotFound. + for v in [[1], {}, (1,), "1", float("nan")]: + G = make(cls) + assert outcome(nx.local_reaching_centrality, G, v, backend="graphblas") == outcome( + nx.local_reaching_centrality, G, v + ) + + +@pytest.mark.parametrize("normalized", [True, False]) +def test_normalized_does_not_matter_unweighted(normalized): + G = nx.gnp_random_graph(20, 0.15, seed=5) + expected = nx.global_reaching_centrality(G, normalized=normalized) + got = nx.global_reaching_centrality(G, normalized=normalized, backend="graphblas") + assert got == pytest.approx(expected, rel=1e-12) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..10f5904 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -124,6 +124,7 @@ def call_args(kind, args): "full_join": ("plain", (SECOND_DISJOINT,)), "generalized_degree": ("undirected", ()), "global_efficiency": ("undirected", ()), + "global_reaching_centrality": ("directed", ()), "google_matrix": ("undirected", ()), "group_closeness_centrality": ("undirected", ([0, 1],)), "group_degree_centrality": ("undirected", ([0, 1],)), @@ -165,6 +166,7 @@ def call_args(kind, args): "katz_centrality": ("undirected", ()), "laplacian_matrix": ("undirected", ()), "local_efficiency": ("undirected", ()), + "local_reaching_centrality": ("directed", (0,)), "lowest_common_ancestor": ("dag", (1, 2)), "mixing_expansion": ("undirected", ([0, 1], [2, 3])), "modularity": ("undirected", ([{0, 1}, {2, 3, 4}],)),