From 5943fa6b972b39a925715d8873e2b07044913d83 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 22:51:34 -0600 Subject: [PATCH] Add closeness_vitality The closeness vitality of a node is the Wiener index of the graph less that of the graph without the node. Rather than find every length again for each node, one pass over all sources finds, for each source, the nodes that are the one strictly nearer parent of some node on its shortest paths. Without any other node, every length from that source is kept: each node keeps a parent other than the one removed, and the parent order is well founded, so this holds for float lengths too. A row is searched again without a node only for those pairs, and only when the rest stays connected (strongly, on a digraph); each node's index then follows from the sums of the first pass. Without a weight, or when every edge holds one finite value, rows are breadth-first searches in hops, and those searched again add up their lengths a level at a time. Otherwise they are Bellman-Ford over lengths that changed. A zero or infinite weight can leave a node with no strictly nearer parent; that source's row is then searched again for every node it reaches. Values and types are NetworkX's: inf where the graph is not connected, -inf for a node whose removal disconnects the rest, nan where both are infinite, an int on a directed graph of integer lengths and a float otherwise, and a given wiener_index used as it is. Weights are served when they are Python ints or floats, at least 0 and not NaN between two nodes; inf is added as NetworkX adds it. Ints raise OverflowError where the number of nodes cubed times the largest could reach 2**63. Graphs of fewer than two nodes and an unhashable node are left to NetworkX. Batches of rows are sized to 1 GiB at the bytes a row takes per node and per edge, measured, and a first-pass batch's rows are dropped before rows are searched again. --- README.md | 2 + _nx_graphblas/__init__.py | 2 + _nx_graphblas/core.py | 10 + graphblas_algorithms/algorithms/__init__.py | 1 + graphblas_algorithms/algorithms/vitality.py | 338 ++++++++++++++++++ graphblas_algorithms/interface.py | 4 + graphblas_algorithms/nxapi/__init__.py | 1 + .../nxapi/tests/test_vitality.py | 315 ++++++++++++++++ graphblas_algorithms/nxapi/vitality.py | 54 +++ graphblas_algorithms/tests/_dispatched.py | 1 + 10 files changed, 728 insertions(+) create mode 100644 graphblas_algorithms/algorithms/vitality.py create mode 100644 graphblas_algorithms/nxapi/tests/test_vitality.py create mode 100644 graphblas_algorithms/nxapi/vitality.py diff --git a/README.md b/README.md index 1bc06b5..db49e6d 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,8 @@ graphblas_algorithms.nxapi │ └── is_tree ├── triads │ └── is_triad +├── vitality +│ └── closeness_vitality └── wiener ├── gutman_index ├── hyper_wiener_index diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..28b43a5 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -47,6 +47,7 @@ def get_info(): "boundary_expansion", "center", "closeness_centrality", + "closeness_vitality", "clustering", "common_neighbor_centrality", "complement", @@ -200,6 +201,7 @@ def get_info(): "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.", "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".', + "closeness_vitality": "A Wiener index is infinite unless every node reaches every node, so a node whose\nremoval disconnects the rest gets -inf, and on a disconnected graph inf or nan, as in\nNetworkX. Weights are served when Python ints or floats, at least 0, and not NaN on an\nedge between two nodes; inf is added as NetworkX adds it, and other weights are left\nto NetworkX. Integer weights raise OverflowError where the number of nodes cubed\ntimes the largest could reach 2**63. With ints mixed with floats a value is a float\nwhere NetworkX's can be an int (3.0 for 3). A graph of fewer than two nodes is left to\nNetworkX.", "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", "compose": "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.", "cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..f74c570 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -124,6 +124,16 @@ ), "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, + "closeness_vitality": ( + "A Wiener index is infinite unless every node reaches every node, so a node whose\n" + "removal disconnects the rest gets -inf, and on a disconnected graph inf or nan, as in\n" + "NetworkX. Weights are served when Python ints or floats, at least 0, and not NaN on an\n" + "edge between two nodes; inf is added as NetworkX adds it, and other weights are left\n" + "to NetworkX. Integer weights raise OverflowError where the number of nodes cubed\n" + "times the largest could reach 2**63. With ints mixed with floats a value is a float\n" + "where NetworkX's can be an int (3.0 for 3). A graph of fewer than two nodes is left to\n" + "NetworkX." + ), "common_neighbor_centrality": ( "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX." ), diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..b63e306 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -26,4 +26,5 @@ from .traversal import * from .tree import * from .triads import * +from .vitality import * from .wiener import * diff --git a/graphblas_algorithms/algorithms/vitality.py b/graphblas_algorithms/algorithms/vitality.py new file mode 100644 index 0000000..cf94c28 --- /dev/null +++ b/graphblas_algorithms/algorithms/vitality.py @@ -0,0 +1,338 @@ +"""Closeness vitality: the Wiener index less that of the graph without each node in turn.""" + +import math + +import numpy as np +from graphblas import Matrix, agg, binary, monoid, replace, select, unary +from graphblas.semiring import any_pair, min_plus + +from ._bfs import _visited +from ._helpers import _ADVICE + +__all__ = ["closeness_vitality"] + +# The memory a batch of rows may take. A row is a search from one source, with at most one node +# taken out, and peaks at about `_ROW_NODE_BYTES` per node of the graph; a row of the first pass +# also counts the parents of every edge, at about `_ROW_EDGE_BYTES` per edge. +_BATCH_BUDGET = 2**30 +_ROW_NODE_BYTES = 64 +_ROW_EDGE_BYTES = 48 + + +def _rows_per_batch(n, m=0): + return max(1, _BATCH_BUDGET // (_ROW_NODE_BYTES * n + _ROW_EDGE_BYTES * m)) + + +def closeness_vitality(G, node=None, wiener_index=None): + """`wiener_index` less the Wiener index of `G` without `node`, or a dict over every node. + + `wiener_index` defaults to that of `G`. The Wiener index of a graph is infinite unless every + node reaches every node, so a node whose removal disconnects the rest gets `-inf`, and on a + disconnected graph `inf` or `nan`. The subtraction is Python's, with the Wiener indices as + NetworkX gives them: an int on a directed graph of integer lengths, else a float. + """ + lengths = _Lengths(G) + if node is not None: + whole = None + if wiener_index is None: + wiener_index = whole = lengths.wiener(*lengths.totals()) + if node in G: + after = lengths.wiener(*lengths.totals(G._key_to_id[node])) + else: + after = whole if whole is not None else lengths.wiener(*lengths.totals()) + return wiener_index - after + whole, afters = lengths.every_removal() + if wiener_index is None: + wiener_index = whole + return {key: wiener_index - afters[index] for key, index in G._key_to_id.items()} + + +class _Lengths: + """Lengths between nodes: hops times the one value every edge holds, or Bellman-Ford's. + + Hops are exact and give each node its parents in one breadth-first level; Bellman-Ford rows + are used only when the values differ or are infinite. + """ + + def __init__(self, G): + A = G.get_property("offdiag") + self.A = A + self.n = n = A.nrows + self.directed = G.is_directed() + self.scale = _one_value(A) + self.rows = _hop_rows if self.scale is not None else _length_rows + if A.dtype.np_type.kind in "iu" and A.nvals > 0: + heaviest = 1 if self.scale is not None else A.reduce_scalar(monoid.max).get() + # A per-node total adds up to `n` row sums of up to `n` lengths of up to `n - 1` edges. + if n * n * (n - 1) * max(heaviest, 1) >= 2**63: + raise OverflowError( + f"integer weights up to {heaviest} between {n} nodes could make a sum of " + f"lengths reach 2**63, {_ADVICE}" + ) + + def wiener(self, total, infinite, connected): + """The Wiener index from the sum of finite lengths over ordered pairs, as NetworkX's.""" + if not connected or infinite: + return math.inf + if self.scale is not None: + total *= self.scale + return total if self.directed else total / 2 + + def totals(self, removed=None): + """`(sum of finite lengths, number infinite, every pair reached)` over ordered pairs. + + Without node id `removed`, when given. + """ + n = self.n + sources = np.arange(n, dtype=np.uint64) + if removed is not None: + sources = sources[sources != removed] + total, infinite, reached = 0, 0, 0 + size = _rows_per_batch(n) + for start in range(0, len(sources), size): + batch = sources[start : start + size] + gone = None if removed is None else np.full(len(batch), removed, np.uint64) + sums, infs, counts = self.stats(batch, gone) + total += _python_sum(sums) + infinite += int(infs.sum()) + reached += int(counts.sum()) + return total, infinite, reached == len(sources) ** 2 + + def every_removal(self): + """The Wiener index of the graph, and a list of it without each node by node id. + + Removing `v` changes the lengths from a source `s` only where `v` is the one parent of + a node in the shortest paths from `s`: otherwise, by induction on the length, every + other node keeps a shortest path that avoids `v`. So one pass over all sources gives + each source's sum of lengths and the nodes that matter to it, and a row is searched + again without `v` only for those pairs, and only when the graph stays connected + without `v`. + """ + n = self.n + connected_without = self._connected_without() + integer = self.A.dtype.np_type.kind in "iu" or self.scale is not None + acc = np.int64 if integer else np.float64 + row_sums = np.zeros(n, acc) + row_infs = np.zeros(n, np.int64) + column_sums = np.zeros(n, acc) + column_infs = np.zeros(n, np.int64) + changed_sums = np.zeros(n, acc) + changed_infs = np.zeros(n, np.int64) + reached = 0 + p, c, w = self.A.to_coo() + if self.scale is not None: + w = np.ones_like(p, dtype=np.int64) + size = _rows_per_batch(n, len(p)) + for start in range(0, n, size): + sources = np.arange(start, min(start + size, n), dtype=np.uint64) + D = self.rows(self.A, sources) + sums, infs, counts = _row_stats(D) + row_sums[sources] = sums + row_infs[sources] = infs + reached += int(counts.sum()) + lengths, finite, infinite = _dense(D) + finite_lengths = np.where(finite, lengths, 0) + column_sums += finite_lengths.sum(axis=0) + column_infs += infinite.sum(axis=0) + matters = _sole_parents(lengths, finite | infinite, sources, p, c, w) + matters &= connected_without + rows, removed = np.nonzero(matters) + # What each such row adds to the total without `v` if no length changed. + kept_sums = sums[rows] - finite_lengths[rows, removed] + kept_infs = infs[rows] - infinite[rows, removed] + again = sources[rows] + removed = removed.astype(np.uint64) + # The batch's rows are no longer needed while rows are searched again. + del D, lengths, finite, infinite, finite_lengths, matters, rows + step = _rows_per_batch(n) + for at in range(0, len(again), step): + part = slice(at, at + step) + new_sums, new_infs, _ = self.stats(again[part], removed[part]) + np.add.at(changed_sums, removed[part], new_sums - kept_sums[part]) + np.add.at(changed_infs, removed[part], new_infs - kept_infs[part]) + total = _python_sum(row_sums) + infinite = int(row_infs.sum()) + whole = self.wiener(total, infinite, reached == n * n) + afters = [] + for v, (own, column, changed, own_inf, column_inf, changed_inf) in enumerate( + zip( + *map(np.ndarray.tolist, (row_sums, column_sums, changed_sums)), + *map(np.ndarray.tolist, (row_infs, column_infs, changed_infs)), + strict=True, + ) + ): + if not connected_without[v]: + afters.append(math.inf) + continue + after = total - own - column + changed + afters.append(self.wiener(after, infinite - own_inf - column_inf + changed_inf, True)) + return whole, afters + + def stats(self, sources, removed=None): + """`_row_stats` of the rows from `sources`, row `i` without node `removed[i]`.""" + if self.scale is not None: + return _hop_stats(self.A, sources, removed) + return _row_stats(_length_rows(self.A, sources, removed)) + + def _connected_without(self): + """For each node id, whether every other node reaches every other without it.""" + n = self.n + ids = np.arange(n, dtype=np.uint64) + sources = np.where(ids == 0, 1, 0).astype(np.uint64) + connected = np.empty(n, bool) + size = _rows_per_batch(n) + for start in range(0, n, size): + part = slice(start, start + size) + ok = _hop_stats(self.A, sources[part], ids[part])[2] == n - 1 + if self.directed: + ok &= _hop_stats(self.A.T, sources[part], ids[part])[2] == n - 1 + connected[part] = ok + return connected + + +def _one_value(A): + """The value every edge holds, as a Python number, when there is one and it is finite.""" + if A.nvals == 0: + return 1 + least = A.reduce_scalar(monoid.min).get() + if least == A.reduce_scalar(monoid.max).get() and math.isfinite(least): + return least + return None + + +def _start(sources, ncols, value, dtype): + rows = np.arange(len(sources), dtype=np.uint64) + return Matrix.from_coo(rows, sources, value, dtype, nrows=len(sources), ncols=ncols) + + +def _hop_rows(A, sources, removed=None): + """Hops from each source, a row each; row `i` never enters node `removed[i]`.""" + n = A.nrows + D = _visited(_start(sources, n, 0, np.int64)) + seen = _visited(_start(sources, n, True, bool)) + if removed is not None: + seen(binary.lor) << _start(removed, n, True, bool) + F = _start(sources, n, True, bool) + depth = 0 + while F.nvals > 0: + depth += 1 + F(~seen.S, replace) << any_pair[bool](F @ A) + seen(F.S) << True + D(F.S) << depth + return D + + +def _hop_stats(A, sources, removed=None): + """`_row_stats` of `_hop_rows`, added up a level at a time without holding the lengths.""" + n = A.nrows + seen = _visited(_start(sources, n, True, bool)) + if removed is not None: + seen(binary.lor) << _start(removed, n, True, bool) + F = _start(sources, n, True, bool) + sums = np.zeros(len(sources), np.int64) + counts = np.ones(len(sources), np.int64) + depth = 0 + while F.nvals > 0: + depth += 1 + F(~seen.S, replace) << any_pair[bool](F @ A) + seen(F.S) << True + level = F.reduce_rowwise(agg.count).new().to_dense(fill_value=0) + sums += depth * level + counts += level + return sums, np.zeros(len(sources), np.int64), counts + + +def _length_rows(A, sources, removed=None): + """Least sums of values from each source, a row each, as `_hop_rows`; values at least 0. + + Bellman-Ford that walks on only from lengths that changed; an infinite length is stored. + """ + n = A.nrows + dtype = A.dtype + D = _visited(_start(sources, n, 0, dtype)) + F = D.dup() + gone = None if removed is None else _start(removed, n, True, bool) + Mask = _visited(Matrix(bool, len(sources), n)) + one = unary.one[bool] + while F.nvals > 0: + F << min_plus[dtype](F @ A) + if gone is not None: + F(~gone.S, replace) << F + Mask << one(F) + Mask(binary.second) << binary.lt(F & D) + F(Mask.V, replace) << F + D(F.S) << F + return D + + +def _row_stats(D): + """Per row: the sum of finite lengths, the number of infinite ones, the number reached.""" + counts = D.reduce_rowwise(agg.count).new().to_dense(fill_value=0) + if D.dtype.np_type.kind != "f" or D.reduce_scalar(monoid.max).get(0) < math.inf: + return _row_sums(D), np.zeros(D.nrows, np.int64), counts + infinite = select.valueeq(D, math.inf).new() + infs = infinite.reduce_rowwise(agg.count).new().to_dense(fill_value=0) + del infinite + return _row_sums(select.valuene(D, math.inf).new()), infs, counts + + +def _row_sums(M): + return M.reduce_rowwise(monoid.plus).new().to_dense(fill_value=0) + + +def _dense(D): + """`D` as a dense array, with where it holds a finite and an infinite length.""" + rows, columns, values = D.to_coo() + lengths = np.zeros(D.shape, values.dtype) + lengths[rows, columns] = values + finite = np.zeros(D.shape, bool) + infinite = np.zeros(D.shape, bool) + if values.dtype.kind == "f": + is_inf = np.isinf(values) + finite[rows[~is_inf], columns[~is_inf]] = True + infinite[rows[is_inf], columns[is_inf]] = True + else: + finite[rows, columns] = True + return lengths, finite, infinite + + +def _sole_parents(lengths, reached, sources, p, c, w): + """Per row, the nodes that are the one parent of a node, or every node a row reaches. + + `p -> c` with value `w` is a parent edge where `length(p) + w == length(c)` and + `length(p) < length(c)`; strictness makes the parent order well founded, so a node with a + parent other than `v` keeps a path of its length without `v` (an infinite length stays + infinite). A reached node other than the source with no strict parent, as a zero or + infinite weight can make, leaves the row's lengths unexplained, and the row then counts + every node it reaches. + """ + b = len(sources) + rows = np.arange(b) + tail = lengths[:, p] + head = lengths[:, c] + strict = reached[:, p] & reached[:, c] & (tail + w == head) & (tail < head) + del tail, head + order = np.argsort(c, kind="stable") + heads = c[order] + if len(heads) > 0: + starts = np.flatnonzero(np.r_[True, heads[1:] != heads[:-1]]) + counts = np.zeros(reached.shape, np.int32) + counts[:, heads[starts]] = np.add.reduceat(strict[:, order], starts, axis=1, dtype=np.int32) + else: + counts = np.zeros(reached.shape, np.int32) + sole = strict & (counts[:, c] == 1) + del strict + matters = np.zeros(reached.shape, bool) + r, e = np.nonzero(sole) + matters[r, p[e]] = True + unexplained = reached & (counts == 0) + unexplained[rows, sources] = False + whole = unexplained.any(axis=1) + matters[whole] = reached[whole] + matters[rows, sources] = False + return matters + + +def _python_sum(values): + """The exact sum, as a Python int for integers.""" + return sum(values.tolist()) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..954bea4 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -446,6 +446,10 @@ class Dispatcher: # ================ is_triad = mod.is_triad + mod = nxapi.vitality + # ================== + closeness_vitality = mod.closeness_vitality + mod = nxapi.wiener # ================ gutman_index = mod.gutman_index diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..47ecbc0 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -26,6 +26,7 @@ from .traversal import * from .tree import * from .triads import * +from .vitality import * from .tournament import is_tournament from .wiener import * diff --git a/graphblas_algorithms/nxapi/tests/test_vitality.py b/graphblas_algorithms/nxapi/tests/test_vitality.py new file mode 100644 index 0000000..294a0b2 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_vitality.py @@ -0,0 +1,315 @@ +"""closeness_vitality against NetworkX: the same values, of the same types, in node order.""" + +import math +from contextlib import contextmanager +from decimal import Decimal + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms import vitality +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + + +@contextmanager +def graphblas_first(fallback=True): + """NetworkX's dispatcher with this backend first, as a user who installs it meets it.""" + config = nx.config + saved = list(config.backend_priority.algos), config.fallback_to_nx + config.backend_priority.algos = ["graphblas"] + config.fallback_to_nx = fallback + try: + yield + finally: + config.backend_priority.algos, config.fallback_to_nx = saved + + +def answer(**kwargs): + """`closeness_vitality`, or the exception's exact type and message.""" + try: + return nx.closeness_vitality(**kwargs) + except Exception as exc: + return type(exc), str(exc) + + +def assert_same(got, want, wiener=1.0): + """The same keys in the same order, each value of NetworkX's type. + + Ints are exact. Floats are within 1e-9 of the Wiener index: each is the difference of two + sums over every pair of nodes, added in another order here. + """ + if isinstance(want, dict): + assert list(got) == list(want) + for key in want: + assert_same(got[key], want[key], wiener) + return + assert type(got) is type(want) + if isinstance(want, float) and math.isnan(want): + assert math.isnan(got) + elif isinstance(want, float) and math.isfinite(want): + assert got == pytest.approx(want, abs=1e-9 * max(abs(wiener), 1.0)) + else: + assert got == want + + +def compare(G, **kwargs): + want = nx.closeness_vitality(G, **kwargs, backend="networkx") + got = nx.closeness_vitality(G, **kwargs, backend="graphblas") + whole = nx.wiener_index(G, weight=kwargs.get("weight"), backend="networkx") + assert_same(got, want, whole if math.isfinite(whole) else 1.0) + return got + + +def weigh(G, kind, seed): + rng = np.random.default_rng(seed) + for u, v in G.edges: + if kind == "int": + G[u][v]["weight"] = int(rng.integers(1, 7)) + elif kind == "int with 0": + G[u][v]["weight"] = int(rng.integers(0, 4)) + elif kind == "float": + G[u][v]["weight"] = float(rng.choice([0.1, 0.25, 0.7, 1.5, 3.3])) + elif kind == "inf": + G[u][v]["weight"] = math.inf if rng.random() < 0.3 else 1.0 + elif kind == "some missing" and rng.random() < 0.6: + G[u][v]["weight"] = int(rng.choice([2, 3])) + elif kind == "all 2": + G[u][v]["weight"] = 2 + elif kind == "all 0.1": + G[u][v]["weight"] = 0.1 + return G + + +def graphs(seed): + rng = np.random.default_rng(seed) + n = int(rng.integers(2, 22)) + s = int(rng.integers(0, 2**31)) + return { + "gnp sparse": nx.gnp_random_graph(n, 1.5 / n, seed=s), + "gnp dense": nx.gnp_random_graph(n, 0.4, seed=s), + "tree": ( + nx.from_prufer_sequence(rng.integers(0, n, n - 2).tolist()) + if n > 2 + else nx.path_graph(n) + ), + "barbell": nx.barbell_graph(int(rng.integers(2, 6)), int(rng.integers(0, 4))), + "cut vertices": nx.connected_watts_strogatz_graph(max(n, 5), 2, 0.3, seed=s), + "directed sparse": nx.gnp_random_graph(n, 2.0 / n, seed=s, directed=True), + "directed dense": nx.gnp_random_graph(n, 0.35, seed=s, directed=True), + "directed cycle": nx.cycle_graph(max(n, 3), create_using=nx.DiGraph), + } + + +FAMILIES = list(graphs(0)) +KINDS = ["none", "int", "int with 0", "float", "inf", "some missing", "all 2", "all 0.1"] + + +@pytest.mark.parametrize("kind", KINDS) +@pytest.mark.parametrize("family", FAMILIES) +@pytest.mark.parametrize("seed", range(3)) +def test_random_graphs_match_networkx(seed, family, kind): + G = weigh(graphs(seed)[family], kind, seed) + weight = None if kind == "none" else "weight" + compare(G, weight=weight) + nodes = list(G) + compare(G, weight=weight, node=nodes[seed % len(nodes)]) + compare(G, weight=weight, node="not a node") + compare(G, weight=weight, wiener_index=[5, 2.5, math.inf][seed]) + + +def test_a_node_whose_removal_disconnects_gets_minus_inf(): + got = compare(nx.path_graph(3)) + assert got == {0: 3.0, 1: -math.inf, 2: 3.0} + + +def test_a_disconnected_graph_gives_inf_for_an_isolated_node_and_nan_elsewhere(): + G = nx.path_graph(3) + G.add_node(9) + got = compare(G) + assert math.isnan(got[0]) + assert got[9] == math.inf + + +def test_an_infinite_weight_makes_a_connected_remainder_infinite(): + """Infinite lengths count however the graph is connected: inf - inf is nan.""" + G = nx.cycle_graph(4) + G[0][1]["weight"] = math.inf + assert compare(G, weight="weight") == {0: 6.0, 1: 6.0, 2: -math.inf, 3: -math.inf} + nx.set_edge_attributes(G, math.inf, "weight") + assert all(math.isnan(value) for value in compare(G, weight="weight").values()) + # Without either node of an infinite edge the one left has an index of 0. + assert compare(nx.Graph([(0, 1, {"weight": math.inf})]), weight="weight") == { + 0: math.inf, + 1: math.inf, + } + + +def test_an_infinite_length_to_a_node_whose_row_is_searched_again(): + """Every row is searched again, as `z` has no strictly nearer parent from any source. + + Only the lengths to and from `p` are infinite, so without `p` the index is finite. + """ + G = nx.cycle_graph(4) + nx.set_edge_attributes(G, 1, "weight") + G.add_edge(0, "p", weight=math.inf) + G.add_edge(1, "z", weight=0) + assert compare(G, weight="weight")["p"] == math.inf + + +def test_ints_mixed_with_floats_give_floats_of_networkx_s_value(): + """One matrix holds one type; NetworkX's sum is an int where no float is on any path.""" + G = nx.DiGraph(nx.cycle_graph(4)) + nx.set_edge_attributes(G, 2, "weight") + G.add_edge(0, 2, weight=9.5) # on no shortest path + want = nx.closeness_vitality(G, weight="weight", backend="networkx") + got = nx.closeness_vitality(G, weight="weight", backend="graphblas") + assert want == got + assert {type(value) for value in want.values()} == {int} + assert {type(value) for value in got.values()} == {float} + + +@pytest.mark.parametrize("weight", [None, "weight"]) +def test_a_directed_graph_of_integer_lengths_gives_ints(weight): + G = nx.DiGraph(nx.cycle_graph(4)) + nx.set_edge_attributes(G, 3, "weight") + got = compare(G, weight=weight) + assert all(type(value) is int for value in got.values()) + + +def test_two_nodes(): + assert compare(nx.path_graph(2)) == {0: 1.0, 1: 1.0} + assert compare(nx.DiGraph([(0, 1), (1, 0)])) == {0: 2, 1: 2} + assert compare(nx.empty_graph(2)) == {0: math.inf, 1: math.inf} + + +def test_a_given_wiener_index_is_used_as_it_is(): + G = nx.cycle_graph(4) + assert type(compare(G, wiener_index=np.int64(100))[0]) is np.float64 + assert compare(nx.DiGraph(G), wiener_index=Decimal(1))[0] == Decimal(-7) + assert compare(G, node="not a node", wiener_index=5) == 5 - nx.wiener_index(G) + want = answer(G=G, wiener_index=Decimal(1), backend="networkx") + assert answer(G=G, wiener_index=Decimal(1), backend="graphblas") == want + assert want[0] is TypeError + + +def test_zero_weights_whose_nodes_hang_off_one_node(): + """Without `s`'s neighbor `v`, `a` and `b` are reached the long way. + + Before `v` is removed, `a` and `b` are each other's parent over a weight of 0 as well as + `v`'s, so neither has `v` as its one parent; only a parent strictly nearer counts. + """ + G = nx.Graph() + G.add_weighted_edges_from( + [("s", "v", 1), ("v", "a", 0), ("v", "b", 0), ("a", "b", 0), ("s", "x", 5), ("x", "a", 5)] + ) + got = compare(G, weight="weight") + assert got["v"] < 0 + + +@pytest.mark.parametrize("rows", [1, 2, 3]) +def test_batches_of_any_size_give_the_same_answer(monkeypatch, rows): + G = nx.connected_watts_strogatz_graph(17, 4, 0.3, seed=3) + weigh(G, "int", 3) + monkeypatch.setattr(vitality, "_rows_per_batch", lambda n, m=0: rows) + compare(G) + compare(G, weight="weight") + compare(nx.DiGraph(G), weight="weight") + + +@pytest.mark.parametrize("weight", [None, "weight"]) +def test_a_row_is_searched_again_only_where_the_node_is_a_sole_parent(monkeypatch, weight): + """No node of a complete graph is any node's one parent, so no row is searched again.""" + removed_rows = [] + stats = vitality._Lengths.stats + + def counting(self, sources, removed=None): + if removed is not None: + removed_rows.append(len(sources)) + return stats(self, sources, removed) + + monkeypatch.setattr(vitality._Lengths, "stats", counting) + G = nx.complete_graph(12) + nx.set_edge_attributes(G, {edge: 1 + i % 2 for i, edge in enumerate(G.edges)}, "weight") + if weight is None: + compare(G) + assert removed_rows == [] + removed_rows.clear() + G = nx.cycle_graph(12) + nx.set_edge_attributes(G, 1.5, "weight") + G[0][1]["weight"] = 1.25 # values that differ: lengths, not hops + compare(G, weight=weight) + if weight is None: + # From each source a node is the one parent of the next node round, but for the two + # next to the far node, which has both as parents: 8 of the 11 other nodes. + assert sum(removed_rows) == 12 * 8 + else: + assert 0 < sum(removed_rows) < 12 * 11 + + +def test_a_graph_of_fewer_than_two_nodes_is_left_to_networkx(): + for G in [nx.empty_graph(0), nx.empty_graph(1)]: + assert isinstance(Dispatcher.can_run("closeness_vitality", (G,), {}), str) + with graphblas_first(): + assert answer(G=G) == answer(G=G, backend="networkx") + with graphblas_first(): + assert nx.closeness_vitality(nx.empty_graph(0), wiener_index=5) == {} + + +def test_an_unhashable_node_is_left_to_networkx(): + G = nx.cycle_graph(4) + assert isinstance(Dispatcher.can_run("closeness_vitality", (G,), {"node": [1]}), str) + with graphblas_first(fallback=False): + assert answer(G=G, node=[1]) == answer(G=G, node=[1], backend="networkx") + + +@pytest.mark.parametrize(("G", "node"), [(nx.empty_graph(1), None), (nx.cycle_graph(4), [1])]) +def test_a_direct_call_refuses_what_networkx_is_left(G, node): + with pytest.raises(NotImplementedError): + nxapi.closeness_vitality(G, node=node) + + +@pytest.mark.parametrize("value", [-1, -1.5, -math.inf, math.nan, np.float32(1.5), True], ids=repr) +def test_weights_dijkstra_cannot_take_or_another_type_are_left_to_networkx(value): + G = nx.cycle_graph(5) + nx.set_edge_attributes(G, 1, "weight") + G[1][2]["weight"] = value + if isinstance(value, np.float32) or value is True: + nx.set_edge_attributes(G, value, "weight") + with pytest.raises(NotImplementedError): + nx.closeness_vitality(G, weight="weight", backend="graphblas") + with graphblas_first(): + # NetworkX's own closeness_vitality, which asks the dispatcher for each Wiener index. + want = answer(G=G, weight="weight", backend="networkx") + got = answer(G=G, weight="weight") + if isinstance(want, dict): + assert_same(got, want) + else: + assert got == want + + +@pytest.mark.parametrize("loop", [math.nan, math.inf]) +def test_a_nan_or_infinite_self_loop_is_served(loop): + """NetworkX's own conversion holds an undirected self-loop of inf as NaN.""" + G = nx.cycle_graph(5) + nx.set_edge_attributes(G, 1.5, "weight") + G.add_edge(2, 2, weight=loop) + compare(G, weight="weight") + + +def test_a_negative_self_loop_is_left_to_networkx(): + G = nx.cycle_graph(5) + G.add_edge(2, 2, weight=-1) + with graphblas_first(): + assert answer(G=G, weight="weight") == answer(G=G, weight="weight", backend="networkx") + + +def test_integer_weights_whose_sums_could_pass_64_bits_raise_overflow_error(): + G = nx.cycle_graph(5) + nx.set_edge_attributes(G, 1, "weight") + G[0][1]["weight"] = 2**60 + with pytest.raises(OverflowError): + nx.closeness_vitality(G, weight="weight", backend="graphblas") diff --git a/graphblas_algorithms/nxapi/vitality.py b/graphblas_algorithms/nxapi/vitality.py new file mode 100644 index 0000000..7b443b6 --- /dev/null +++ b/graphblas_algorithms/nxapi/vitality.py @@ -0,0 +1,54 @@ +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__ = ["closeness_vitality"] + + +def _served(bound): + """Why NetworkX is left the call before conversion, or None.""" + if len(bound["G"]) < 2: + # NetworkX raises NetworkXPointlessConcept for the Wiener index of the graph left + # without the one node, or answers `{}` for the null graph with a `wiener_index`. + return "closeness_vitality on fewer than two nodes is left to networkx" + if (node := bound["node"]) is not None: + try: + hash(node) + except TypeError: + return "closeness_vitality of an unhashable `node` raises TypeError in networkx" + return None + + +def _unserved_weights(G): + """Why the lengths over `G`'s weights are left to NetworkX, or None. + + NetworkX's Dijkstra raises or can stop early on a negative weight, a self-loop's too, and + NaN compares false, so weights are served when at least 0 and not NaN; `inf` is added as + NetworkX adds it. A self-loop changes no length, and a NaN one is served: NetworkX's own + conversion gives an undirected self-loop of `inf` that value. Other dtypes, such as NumPy's + narrow floats or bools, are added in other types by NetworkX. + """ + A = G._A + if A.dtype not in {dtypes.INT64, dtypes.FP64}: + return f"closeness_vitality over {A.dtype} weights is not implemented here" + if (A.to_coo(rows=False, columns=False)[2] < 0).any(): + return "closeness_vitality over negative weights is not implemented here" + offdiag = G.get_property("offdiag") + if A.dtype == dtypes.FP64 and np.isnan(offdiag.to_coo(rows=False, columns=False)[2]).any(): + return "closeness_vitality over NaN weights is not implemented here" + return None + + +@can_run(_served) +def closeness_vitality(G, node=None, weight=None, wiener_index=None): + # Again here: a direct call does not pass through `can_run`. + if (reason := _served({"G": G, "node": node})) is not None: + raise NotImplementedError(reason) + G = to_graph(G, weight=weight) + if weight is not None and (reason := _unserved_weights(G)) is not None: + raise NotImplementedError(f"{reason}; networkx serves it") + return algorithms.closeness_vitality(G, node=node, wiener_index=wiener_index) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..87be331 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -91,6 +91,7 @@ def call_args(kind, args): # off it, raise on a graph in pieces. "center": ("tournament", ()), "closeness_centrality": ("undirected", ()), + "closeness_vitality": ("tournament", ()), "clustering": ("undirected", ()), "common_neighbor_centrality": ("undirected", ([(0, 1), (0, 4)],)), # Unweighted: the complement's new edges would have no weight to carry.