diff --git a/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py b/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py index b485489..6cd1f2d 100644 --- a/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py +++ b/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py @@ -1,3 +1,6 @@ +from math import nan + +import numpy as np from graphblas import Matrix, Vector, binary, monoid from graphblas.semiring import plus_first, plus_times @@ -163,6 +166,7 @@ def google_matrix( A << binary.first(empty_rows.outer(p) | A) scale = A.reduce_rowwise(monoid.plus).new(float) + rows, sums = scale.to_coo() scale << alpha / scale A << scale * A p *= 1 - alpha @@ -171,4 +175,8 @@ def google_matrix( A(binary.plus)[:, :] = p else: A << A + p + # NetworkX divides the whole dense row by its sum, so a NaN sum makes every entry NaN, + # where this scales only the row's entries. + if nan_rows := rows[np.isnan(sums)].tolist(): + A[nan_rows, :] = nan return A diff --git a/graphblas_algorithms/linalg/laplacianmatrix.py b/graphblas_algorithms/linalg/laplacianmatrix.py index a2fbe99..8cfd92f 100644 --- a/graphblas_algorithms/linalg/laplacianmatrix.py +++ b/graphblas_algorithms/linalg/laplacianmatrix.py @@ -1,4 +1,4 @@ -from graphblas import monoid, unary +from graphblas import binary, monoid, unary __all__ = [ "laplacian_matrix", @@ -36,9 +36,12 @@ def normalized_laplacian_matrix( ): d, A = _laplacian_helper(G, nodelist, is_weighted) # A node whose weights sum to zero is left out of the scaling, which zeroes its row and - # column; NetworkX takes its 1 / sqrt(0) as 0. + # column; NetworkX takes its 1 / sqrt(0) as 0. So is a node whose weights sum to +inf, + # whose 1 / sqrt(inf) is 0: NetworkX's sparse diagonal drops the zero, and with it the + # node's row and column. A sum that is NaN or below zero gives NaN, which stays. d_invsqrt = unary.sqrt(d.select("!=", 0).new()).new(name="d_invsqrt") d_invsqrt << unary.minv(d_invsqrt) + d_invsqrt = d_invsqrt.select("!=", 0).new(name="d_invsqrt") # Calculate: A_weighted = D_invsqrt @ A @ D_invsqrt A_weighted = d_invsqrt.outer(d_invsqrt).new(mask=A.S, name=name) @@ -48,7 +51,10 @@ def normalized_laplacian_matrix( # A_weighted = (D_invsqrt @ A).new(name=name) # A_weighted @= D_invsqrt - d_invsqrt << unary.one(d_invsqrt) + # NetworkX's diagonal is d_invsqrt * d * d_invsqrt, which is 1 here, or NaN with a NaN + # d_invsqrt even where the node has no self-loop. + d_invsqrt << binary.times(d_invsqrt, 0.0) + d_invsqrt << binary.plus(d_invsqrt, 1.0) D = d_invsqrt.diag(name="D") A_weighted << D - A_weighted return A_weighted diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 72f728b..8425781 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -1,6 +1,8 @@ from math import ceil from numbers import Number +import numpy as np + from .exception import NetworkXError try: @@ -208,3 +210,40 @@ def nbunch_keys(G, nbunch, *, unique=False): if present: keys.append(node) return list(dict.fromkeys(keys)) if unique else keys + + +def _read_apart(G): + """`(nan, posinf, neginf)`: whether some value of `G` is NaN, +inf or -inf; cached on `G`. + + NetworkX meets these values with arithmetic and comparisons that can differ from the + matrix operations here. + """ + + def find(): + A = G._A + if A.nvals == 0 or A.dtype.np_type.kind != "f": + return False, False, False + _, _, values = A.to_coo(rows=False, columns=False) + return ( + bool(np.isnan(values).any()), + bool(np.isposinf(values).any()), + bool(np.isneginf(values).any()), + ) + + return G._cacheit("read_apart", find) + + +def _signs(G): + """`(largest, negative)`: the largest value of `G`, and whether some value is below zero. + + NetworkX divides by the largest weight (clustering) and by sums of weights (the modularity + matrices, google_matrix, pagerank), and takes square roots of sums + (normalized_laplacian_matrix). So a largest weight of 0 can make it divide by zero, and a + negative weight can make a sum 0 or below 0, or make it cancel, so that its rounding follows + the order NetworkX adds in. Both are read off the minimum and maximum cached on `G`'s + conversion, which pass over NaN. A graph with no values gives None and False. + """ + if G._A.nvals == 0: + return None, False + smallest = G.get_property("min_element+").get() + return G.get_property("max_element+").get(), smallest is not None and smallest < 0 diff --git a/graphblas_algorithms/nxapi/cluster.py b/graphblas_algorithms/nxapi/cluster.py index 3b0b7f4..8f76d2a 100644 --- a/graphblas_algorithms/nxapi/cluster.py +++ b/graphblas_algorithms/nxapi/cluster.py @@ -6,7 +6,7 @@ from graphblas_algorithms.classes.nodemap import VectorMap from graphblas_algorithms.utils import not_implemented_for -from ._utils import can_run, nbunch_keys, normalize_chunksize, partition +from ._utils import _read_apart, _signs, can_run, nbunch_keys, normalize_chunksize, partition __all__ = [ "average_clustering", @@ -42,8 +42,30 @@ def transitivity(G): return G._cacheit("transitivity", func, G) +def _check_weights(G, weight, name): + """Raise NotImplementedError for a NaN weight, or a largest weight of 0. + + NetworkX scales the weights by `max(d.get(weight, 1) for u, v, d in G.edges(data=True))`. + Python's `max` keeps a NaN it starts with and passes over a NaN met later, so a NaN on the + first edge makes every scaled weight NaN, and one elsewhere only its own triangles. A + matrix keeps no edge order. An infinite weight gives the same maximum in any order. + + A largest weight of 0 (every weight 0 or less) makes NetworkX divide by zero: it raises + ZeroDivisionError for Python numbers and gives NaN or infinities for NumPy ones, and only + at the nodes it reaches. A largest weight below 0 scales every weight to a positive one, + as here. + """ + if weight is None: + return + if _read_apart(G)[0]: + raise NotImplementedError(f"{name} with a NaN weight is left to networkx") + if _signs(G)[0] == 0: + raise NotImplementedError(f"{name} with a largest weight of 0 is left to networkx") + + def clustering(G, nodes=None, weight=None): G = to_graph(G, weight=weight) # to directed or undirected + _check_weights(G, weight, "clustering") # before `nodes`, which may be read only once weighted = weight is not None if nodes in G: if G.is_directed(): @@ -62,6 +84,7 @@ def clustering(G, nodes=None, weight=None): def average_clustering(G, nodes=None, weight=None, count_zeros=True): G = to_graph(G, weight=weight) # to directed or undirected + _check_weights(G, weight, "average_clustering") keys = nbunch_keys(G, nodes) if len(G) == 0: raise ZeroDivisionError("division by zero") diff --git a/graphblas_algorithms/nxapi/linalg/laplacianmatrix.py b/graphblas_algorithms/nxapi/linalg/laplacianmatrix.py index 9730d50..1c65a3f 100644 --- a/graphblas_algorithms/nxapi/linalg/laplacianmatrix.py +++ b/graphblas_algorithms/nxapi/linalg/laplacianmatrix.py @@ -3,7 +3,7 @@ from graphblas_algorithms import linalg from graphblas_algorithms.classes.digraph import to_graph -from .._utils import check_nodelist +from .._utils import _read_apart, _signs, check_nodelist __all__ = ["laplacian_matrix", "normalized_laplacian_matrix"] @@ -18,5 +18,35 @@ def laplacian_matrix(G, nodelist=None, weight="weight"): def normalized_laplacian_matrix(G, nodelist=None, weight="weight"): G = to_graph(G, weight=weight) check_nodelist(G, nodelist) + if weight is not None and (_read_apart(G)[0] or _signs(G)[1]): + return _normalized_laplacian_as_networkx(G, nodelist) rv = linalg.normalized_laplacian_matrix(G, nodelist, is_weighted=weight is not None) return gb_io.to_scipy_sparse(rv) + + +def _normalized_laplacian_as_networkx(G, nodelist): + """NetworkX's own arithmetic on the same SciPy array, for a NaN or a negative weight. + + Such a weight can make a node's weight sum NaN or negative, so that 1 / sqrt(sum) is NaN, + and NetworkX's sparse products then put NaN only where `L = D - A` has an entry: SciPy + drops a zero there, as at an edge of weight 0, or at a node whose other weights sum to 0. + The sign of a sum that cancels follows the order of addition, which is SciPy's here too. + """ + import numpy as np + import scipy as sp + + if nodelist is None: + A = G._A + else: + ids = G.list_to_ids(nodelist) + A = G._A[ids, ids].new() + A = sp.sparse.csr_array(gb_io.to_scipy_sparse(A, format="csr")) + n, _ = A.shape + diags = A.sum(axis=1) + D = sp.sparse.dia_array((diags, 0), shape=(n, n)).tocsr() + L = D - A + with np.errstate(divide="ignore"): + diags_sqrt = 1.0 / np.sqrt(diags) + diags_sqrt[np.isinf(diags_sqrt)] = 0 + DH = sp.sparse.dia_array((diags_sqrt, 0), shape=(n, n)).tocsr() + return DH @ (L @ DH) diff --git a/graphblas_algorithms/nxapi/linalg/modularitymatrix.py b/graphblas_algorithms/nxapi/linalg/modularitymatrix.py index 89bb278..d94d171 100644 --- a/graphblas_algorithms/nxapi/linalg/modularitymatrix.py +++ b/graphblas_algorithms/nxapi/linalg/modularitymatrix.py @@ -1,11 +1,12 @@ import numpy as np +from graphblas import io as gb_io from graphblas_algorithms import linalg from graphblas_algorithms.classes.digraph import to_directed_graph from graphblas_algorithms.classes.graph import to_undirected_graph from graphblas_algorithms.utils import not_implemented_for -from .._utils import check_nodelist +from .._utils import _read_apart, _signs, check_nodelist __all__ = ["directed_modularity_matrix", "modularity_matrix"] @@ -23,6 +24,36 @@ def _all_nan_if_no_edges(G, nodelist): return np.full((n, n), np.nan) if nvals == 0 else None +def _for_networkx_arithmetic(G, nodelist, weight): + """The weights `nodelist` selects as NetworkX holds them, if NetworkX's arithmetic decides. + + A NaN or infinite value makes `m` NaN or infinite, and NetworkX's + `A - outer(k, k) / (2 * m)` then gives NaN in every row and column whose `k` is not finite, + and in a zero row or column beside one (0 times inf), where the sparse product here has no + entry. Every other entry is `A` less a zero, as a finite product over an infinite `m` is + zero. Weights that are all 0 make `m` 0, and NetworkX divides by it; weights of both signs + can make `m` cancel, to 0 or to a small number, by the order NetworkX adds in. So these are + computed with NetworkX's own arithmetic on the same SciPy array. Otherwise None. + """ + if weight is None: + return None + largest, negative = _signs(G) + positive = largest is not None and largest > 0 + if positive and nodelist is None and not negative and not any(_read_apart(G)): + return None + if nodelist is None: + A = G._A + else: + ids = G.list_to_ids(nodelist) + A = G._A[ids, ids].new() + import scipy as sp + + A = sp.sparse.csr_array(gb_io.to_scipy_sparse(A, format="csr")) + if np.isfinite(A.data).all() and (A.data >= 0).all() and (A.data > 0).any(): + return None + return A + + @not_implemented_for("directed") @not_implemented_for("multigraph") def modularity_matrix(G, nodelist=None, weight=None): @@ -30,6 +61,12 @@ def modularity_matrix(G, nodelist=None, weight=None): check_nodelist(G, nodelist) if (all_nan := _all_nan_if_no_edges(G, nodelist)) is not None: return all_nan + if (A := _for_networkx_arithmetic(G, nodelist, weight)) is not None: + k = A.sum(axis=1) + m = k.sum() * 0.5 + with np.errstate(invalid="ignore", divide="ignore"): + X = np.outer(k, k) / (2 * m) + return A - X rv = linalg.modularity_matrix(G, nodelist, is_weighted=weight is not None) return rv.to_dense(fill_value=0) @@ -41,5 +78,12 @@ def directed_modularity_matrix(G, nodelist=None, weight=None): check_nodelist(G, nodelist) if (all_nan := _all_nan_if_no_edges(G, nodelist)) is not None: return all_nan + if (A := _for_networkx_arithmetic(G, nodelist, weight)) is not None: + k_in = A.sum(axis=0) + k_out = A.sum(axis=1) + m = k_in.sum() + with np.errstate(invalid="ignore", divide="ignore"): + X = np.outer(k_out, k_in) / m + return A - X rv = linalg.directed_modularity_matrix(G, nodelist, is_weighted=weight is not None) return rv.to_dense(fill_value=0) diff --git a/graphblas_algorithms/nxapi/link_analysis/hits_alg.py b/graphblas_algorithms/nxapi/link_analysis/hits_alg.py index 7936df0..8786570 100644 --- a/graphblas_algorithms/nxapi/link_analysis/hits_alg.py +++ b/graphblas_algorithms/nxapi/link_analysis/hits_alg.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run +from .._utils import _read_apart, _signs, can_run from ..exception import NetworkXError, PowerIterationFailedConvergence __all__ = ["hits"] @@ -20,8 +20,23 @@ def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True, *, method="p if (reason := _power_iteration_only({"method": method})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight="weight", dtype=float) + if any(_read_apart(G)): + # NetworkX 3.6 computes hits with ARPACK, which raises its own error on these values; + # later versions fail to converge, as the power iteration here does. + raise NotImplementedError("hits with a NaN or infinite weight is left to networkx") if len(G) == 0: return {}, {} + largest, negative = _signs(G) + if negative or largest == 0: + # Each step divides the hub values by their largest. NetworkX takes it over every node, + # 0 for a node with no hub value, and this power iteration over the values it holds. + # With every weight 0 the largest is 0: NetworkX does not converge (in 3.6 its ARPACK + # raises), and here the division is skipped. With a negative weight, hub values can all + # be below 0, so that NetworkX divides by 0 and this iteration does not. A graph with + # no edges is answered here, as the backend's notes say. + raise NotImplementedError( + "hits with a negative weight, or with every weight 0, is left to networkx" + ) x = None if nstart is not None: if missing := G._key_to_id.keys() - nstart.keys(): diff --git a/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py b/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py index 4026dbd..cf2e63f 100644 --- a/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py +++ b/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py @@ -1,8 +1,13 @@ +from math import inf + +import numpy as np +from graphblas import agg, binary + from graphblas_algorithms import algorithms from graphblas_algorithms.algorithms.link_analysis.pagerank_alg import nonzero_out_weight_sums from graphblas_algorithms.classes.digraph import to_graph -from .._utils import check_dense_nodelist +from .._utils import _signs, check_dense_nodelist from ..exception import PowerIterationFailedConvergence _all = ["pagerank", "google_matrix"] @@ -22,10 +27,26 @@ def pagerank( N = len(G) if N == 0: return {} + row_sums = nonzero_out_weight_sums(G._A) + if row_sums.select("==", inf).new().nvals or row_sums.select("==", -inf).new().nvals: + # NetworkX scales a row by 1 / its sum, 0 here. NetworkX 3.6 then takes the node as + # dangling and passes its rank on; later versions take it as not dangling, and since + # their sparse diagonal keeps no 0, the node's rank is lost. Each answer is the other + # version's wrong one. + raise NotImplementedError( + "pagerank with out-weights that sum to +inf or -inf is left to networkx" + ) + if weight is not None and _signs(G)[1] and _out_weights_cancel_by_order(G): + # Such a row can sum to 0 or to a small number by the order NetworkX adds in, and + # NetworkX takes the node as dangling only where the sum is 0. + raise NotImplementedError( + "pagerank where a node's out-weights hold both signs, three or more of them, " + "is left to networkx" + ) # We'll normalize initial, personalization, and dangling vectors later x = G.dict_to_vector(nstart, dtype=float, name="nstart") p = G.dict_to_vector(personalization, dtype=float, name="personalization") - if dangling is not None and nonzero_out_weight_sums(G._A).nvals < N: + if dangling is not None and row_sums.nvals < N: dangling_weights = G.dict_to_vector(dangling, dtype=float, name="dangling") else: dangling_weights = None @@ -38,6 +59,7 @@ def pagerank( tol=tol, nstart=x, dangling=dangling_weights, + row_degrees=row_sums, ) except algorithms.exceptions.ConvergenceFailure as e: raise PowerIterationFailedConvergence(*e.args) from e @@ -45,11 +67,31 @@ def pagerank( return G.vector_to_nodemap(result, fill_value=0.0) +def _out_weights_cancel_by_order(G): + """Whether a node's out-weights hold both signs among three values or more. + + Only such a sum can cancel to another number in another order of addition: a sum of two + floats does not depend on their order, adding a zero changes nothing, and sums of values of + one sign differ by rounding only. Cached on the conversion. + """ + + def find(): + A = G._A + below = A.select("<", 0).new().reduce_rowwise(agg.count).new() + above = A.select(">", 0).new().reduce_rowwise(agg.count).new() + both = below.ewise_mult(above, binary.plus).new() + return both.select(">=", 3).new().nvals > 0 + + return G._cacheit("out_weights_cancel_by_order", find) + + def google_matrix( G, alpha=0.85, personalization=None, nodelist=None, weight="weight", dangling=None ): G = to_graph(G, weight=weight, dtype=float) check_dense_nodelist(G, nodelist) + if weight is not None and _signs(G)[1]: + return _google_matrix_as_networkx(G, alpha, personalization, nodelist, dangling) p = G.dict_to_vector(personalization, dtype=float, name="personalization") if dangling is not None and nonzero_out_weight_sums(G._A).nvals < len(G): dangling_weights = G.dict_to_vector(dangling, dtype=float, name="dangling") @@ -63,3 +105,33 @@ def google_matrix( dangling=dangling_weights, ) return rv.to_dense(fill_value=0) + + +def _google_matrix_as_networkx(G, alpha, personalization, nodelist, dangling): + """NetworkX's own arithmetic on the same dense array, for weights of both signs. + + A row whose weights cancel sums to 0, which NetworkX takes as dangling, or to a small + number that it divides by, as its NumPy sums round in their own order. So the row sums and + everything after them are NetworkX's, on the array `nx.to_numpy_array` gives. + """ + if nodelist is None: + nodelist = list(G) + ids = G.list_to_ids(nodelist) + A = G._A[ids, ids].new(float).to_dense(fill_value=0.0) + N = len(G) + if personalization is None: + p = np.repeat(1.0 / N, N) + else: + p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float) + if p.sum() == 0: + raise ZeroDivisionError + p /= p.sum() + if dangling is None: + dangling_weights = p + else: + dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float) + dangling_weights /= dangling_weights.sum() + dangling_nodes = np.where(A.sum(axis=1) == 0)[0] + A[dangling_nodes] = dangling_weights + A /= A.sum(axis=1)[:, np.newaxis] + return alpha * A + (1 - alpha) * p diff --git a/graphblas_algorithms/nxapi/tests/test_nonfinite_other_names.py b/graphblas_algorithms/nxapi/tests/test_nonfinite_other_names.py new file mode 100644 index 0000000..416ab4d --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_nonfinite_other_names.py @@ -0,0 +1,575 @@ +"""NaN and infinite weights in the names that read weights and are not shortest paths. + +Where NetworkX's own arithmetic decides the answer, the backend follows it: the modularity +matrices, `google_matrix` and `normalized_laplacian_matrix`. Where NetworkX's answer follows the +order of its edges or differs between its versions, the call is left to NetworkX: weighted +`clustering` and `average_clustering` with a NaN weight, `hits` with any such weight, and +`pagerank` where a node's out-weights sum to +inf or -inf. A declined call is checked under +`graphblas_first`, where NetworkX answers it. +""" + +import math +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi + +pytestmark = [ + # NetworkX's own arithmetic meets these values with NumPy and SciPy, which warn. + pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning"), + pytest.mark.filterwarnings("ignore:divide by zero encountered:RuntimeWarning"), + pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning"), + # A graph called both ways keeps its conversion, which NetworkX notes once. + pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs are saved:UserWarning"), +] + +NAN, INF = float("nan"), float("inf") +VALUES = {"nan": (NAN,), "+inf": (INF,), "-inf": (-INF,), "+inf and -inf": (INF, -INF)} + + +@contextmanager +def graphblas_first(): + """The graphblas backend first in the priority, and no fallback: NetworkX answers a decline.""" + config = nx.config + saved = list(config.backend_priority.algos), config.fallback_to_nx + config.backend_priority.algos = ["graphblas"] + config.fallback_to_nx = False + try: + yield + finally: + config.backend_priority.algos, config.fallback_to_nx = saved + + +def weighted(directed=False, values=(), seed=3, at=None): + """A random graph on 0..7 plus an isolated node 9, weights 2.0; `values` on node `at`'s edges. + + `at` defaults to the first node with two edges, so that "+inf and -inf" share a row. + """ + G = nx.gnp_random_graph(8, 0.5, seed=seed, directed=directed) + nx.set_edge_attributes(G, 2.0, "weight") + G.add_node(9) + if at is None: + at = next(n for n in G if len(G[n]) >= 2) + assert len(G[at]) >= len(values) + for value, v in zip(values, list(G[at]), strict=False): + G[at][v]["weight"] = value + return G + + +def outcome(f, *args, **kwargs): + """The answer, or the type of the exception raised; a decline by name is raised.""" + try: + result = f(*args, **kwargs) + except Exception as exc: + if isinstance(exc, NotImplementedError) and kwargs.get("backend") == "graphblas": + raise + return type(exc) + if hasattr(result, "toarray"): + return result.toarray() + if isinstance(result, np.ndarray): + return result + if isinstance(result, float | np.generic): + return {None: float(result)} + return dict(result) + + +def assert_same(got, want, *, exact=False): + """NaN and infinities where NetworkX has them; the rest within rounding. + + `exact` is a tighter tolerance for the finite entries (relative 1e-12, none absolute). + """ + if isinstance(want, type) or isinstance(got, type): + assert got == want + elif isinstance(want, np.ndarray): + assert type(got) is type(want) + assert got.shape == want.shape + assert np.array_equal(np.isnan(got), np.isnan(want)) + assert np.array_equal(np.isposinf(got), np.isposinf(want)) + assert np.array_equal(np.isneginf(got), np.isneginf(want)) + finite = np.isfinite(want) + if exact: + np.testing.assert_allclose(got[finite], want[finite], rtol=1e-12, atol=0) + else: + np.testing.assert_allclose(got[finite], want[finite], rtol=1e-12, atol=1e-15) + else: + assert got.keys() == want.keys() + np.testing.assert_allclose( + [got[k] for k in want], list(want.values()), rtol=0, atol=1e-7, equal_nan=True + ) + + +def declined_reason(f, G, *args, **kwargs): + with pytest.raises(NotImplementedError) as info: + f(G, *args, backend="graphblas", **kwargs) + return str(info.value.__cause__ or info.value) + + +def modularity(G, **kwargs): + return nx.modularity_matrix(G, weight="weight", **kwargs) + + +def directed_modularity(G, **kwargs): + return nx.directed_modularity_matrix(G, weight="weight", **kwargs) + + +# name: (call, graph is directed, finite entries compared at the tighter tolerance) +SERVED = { + "modularity_matrix": (modularity, False, True), + "directed_modularity_matrix": (directed_modularity, True, True), + "google_matrix": (nx.google_matrix, False, False), + "google_matrix directed": (nx.google_matrix, True, False), + "normalized_laplacian_matrix": (nx.normalized_laplacian_matrix, False, False), + "normalized_laplacian_matrix directed": (nx.normalized_laplacian_matrix, True, False), +} + + +@pytest.mark.parametrize("value", VALUES) +@pytest.mark.parametrize("name", SERVED) +def test_served_with_networkx_arithmetic(name, value): + f, directed, exact = SERVED[name] + for at in [None, 0]: + G = weighted(directed, VALUES[value], at=at) + want = outcome(f, G, backend="networkx") + assert_same(outcome(f, G, backend="graphblas"), want, exact=exact) + + +@pytest.mark.parametrize("seed", range(6)) +@pytest.mark.parametrize("name", ["modularity_matrix", "directed_modularity_matrix"]) +def test_modularity_with_random_weights(name, seed): + """Random weights, a self-loop and a shuffled nodelist; the rest agrees within rounding.""" + f, directed, _ = SERVED[name] + rng = np.random.default_rng(seed) + G = nx.gnp_random_graph(30, 0.3, seed=seed, directed=directed) + for u, v in G.edges: + G[u][v]["weight"] = rng.uniform(-1, 3) + G.add_edge(3, 3, weight=rng.random()) + G.add_node(99) + edges = list(G.edges) + u, v = edges[rng.integers(len(edges))] + G[u][v]["weight"] = [NAN, INF, -INF][seed % 3] + others = [n for n in G if n not in {u, v}] + nodelist = [u, v, *(others[i] for i in rng.choice(len(others), 18, replace=False))] + nodelist = [nodelist[i] for i in rng.permutation(len(nodelist))] + for kwargs in [{}, {"nodelist": nodelist}]: + want = outcome(f, G, backend="networkx", **kwargs) + assert_same(outcome(f, G, backend="graphblas", **kwargs), want, exact=True) + + +@pytest.mark.parametrize("name", ["modularity_matrix", "directed_modularity_matrix"]) +def test_modularity_with_a_nodelist(name): + """Only the weights the nodelist selects count: first without the NaN, then with it.""" + f, directed, _ = SERVED[name] + G = weighted(directed, (NAN,), at=0) + [v] = [v for v in G[0] if G[0][v]["weight"] != G[0][v]["weight"]] + without = [n for n in G if n != 0] + with_it = [v, 9, 0, *[n for n in G if n not in {0, v, 9}][:2]] + for nodelist in (without, with_it): + want = outcome(f, G, nodelist=nodelist, backend="networkx") + assert_same(outcome(f, G, nodelist=nodelist, backend="graphblas"), want, exact=True) + + +def test_google_matrix_nan_row_with_personalization_dangling_and_nodelist(): + G = weighted(True, (NAN,)) + G.add_edge(9, 9, weight=0.0) # a row that sums to zero is dangling + kwargs = { + "personalization": {n: n + 1 for n in G}, + "dangling": {n: 2 * n + 1 for n in G}, + "nodelist": sorted(G, reverse=True), + } + for keys in [(), ("personalization",), ("dangling",), ("nodelist",), tuple(kwargs)]: + kw = {k: kwargs[k] for k in keys} + want = outcome(nx.google_matrix, G, backend="networkx", **kw) + assert_same(outcome(nx.google_matrix, G, backend="graphblas", **kw), want) + + +@pytest.mark.parametrize( + "weights", + [(1e308, 1e308), (-3.0, 1.0)], + ids=["finite weights that sum to inf", "a negative sum"], +) +def test_normalized_laplacian_where_finite_weights_sum_to_inf_or_below_zero(weights): + """1 / sqrt(inf) is 0, which drops the node; 1 / sqrt(-2) is NaN, on its diagonal too.""" + G = weighted(False, weights) + want = outcome(nx.normalized_laplacian_matrix, G, backend="networkx") + assert_same(outcome(nx.normalized_laplacian_matrix, G, backend="graphblas"), want) + + +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_networkx_answers_weighted_clustering_with_a_nan_weight(name, directed): + """NetworkX scales by the first maximum it meets in edge order; a NaN first makes all NaN.""" + f = getattr(nx, name) + for at in [0, 5]: + G = weighted(directed, (NAN,), at=at) + want = outcome(f, G, weight="weight", backend="networkx") + assert "NaN weight" in declined_reason(f, G, weight="weight") + with graphblas_first(): + assert_same(outcome(f, G, weight="weight"), want) + # without `weight` the weights are not read + assert_same(outcome(f, G, backend="graphblas"), outcome(f, G, backend="networkx")) + + +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_unweighted_clustering_of_a_graph_holding_a_nan_weight(name, directed): + """Called directly, the backend graph keeps its weights, which `weight=None` does not read.""" + G = weighted(directed, (NAN,), at=0) + H = (ga.DiGraph if directed else ga.Graph).from_networkx(G, weight="weight") + got = outcome(getattr(nxapi, name), H) + assert_same(got, outcome(getattr(nx, name), G, backend="networkx")) + + +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_networkx_reads_the_nodes_it_is_given_once(name): + """The check comes before `nodes` is read, so NetworkX still has every node to read.""" + f = getattr(nx, name) + G = weighted(False, (NAN,), at=0) + want = outcome(f, G, [0, 1, 2, 5], weight="weight", backend="networkx") + with graphblas_first(): + assert_same(outcome(f, G, iter([0, 1, 2, 5]), weight="weight"), want) + + +@pytest.mark.parametrize("value", ["+inf", "-inf", "+inf and -inf"]) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_weighted_clustering_with_an_infinite_weight_is_served(name, directed, value): + """The maximum is the same whichever edge NetworkX meets first.""" + f = getattr(nx, name) + G = weighted(directed, VALUES[value], at=0) + want = outcome(f, G, weight="weight", backend="networkx") + assert_same(outcome(f, G, weight="weight", backend="graphblas"), want) + + +@pytest.mark.parametrize("value", VALUES) +def test_networkx_answers_hits_with_a_nonfinite_weight(value): + """NetworkX 3.6 raises ArpackError here, later versions PowerIterationFailedConvergence.""" + G = weighted(True, VALUES[value]) + want = outcome(nx.hits, G, backend="networkx") + assert "NaN or infinite weight" in declined_reason(nx.hits, G) + with graphblas_first(): + assert outcome(nx.hits, G) == want + + +def out_weights_of_both_signs(G): + """Whether a node's nonzero out-weights hold both signs, three or more of them.""" + for u in G: + weights = [w for w in (d["weight"] for d in G[u].values()) if w != 0] + if len(weights) >= 3 and min(weights) < 0 < max(weights): + return True + return False + + +def sums_to_an_infinity(G): + return any(math.isinf(sum(d["weight"] for d in G[u].values())) for u in G) + + +@pytest.mark.parametrize("value", ["+inf", "-inf", "+inf and -inf", "finite sum to inf"]) +@pytest.mark.parametrize("directed", [False, True]) +def test_networkx_answers_pagerank_where_out_weights_sum_to_an_infinity(directed, value): + """NetworkX 3.6 passes such a node's rank on, as a dangling node's; later versions lose it.""" + values = (1e308, 1e308) if value == "finite sum to inf" else VALUES[value] + G = weighted(directed, values) + want = outcome(nx.pagerank, G, backend="networkx") + if sums_to_an_infinity(G): + assert "sum to +inf or -inf" in declined_reason(nx.pagerank, G) + elif out_weights_of_both_signs(G): + assert value == "+inf and -inf" + assert "both signs, three or more" in declined_reason(nx.pagerank, G) + else: # one row sums to NaN: no rank converges, here or there + assert value == "+inf and -inf" + assert want is nx.PowerIterationFailedConvergence + assert outcome(nx.pagerank, G, backend="graphblas") is want + with graphblas_first(): + assert_same(outcome(nx.pagerank, G), want) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_pagerank_with_a_nan_weight_fails_to_converge_as_networkx_does(directed): + G = weighted(directed, (NAN,)) + assert outcome(nx.pagerank, G, backend="networkx") is nx.PowerIterationFailedConvergence + assert outcome(nx.pagerank, G, backend="graphblas") is nx.PowerIterationFailedConvergence + + +def test_finite_weights_are_served_as_before(): + G = weighted(False, (5.0, 0.5)) + D = weighted(True, (5.0, 0.5)) + for f, H in [ + (lambda G, **kw: nx.clustering(G, weight="weight", **kw), G), + (lambda G, **kw: nx.average_clustering(G, weight="weight", **kw), D), + (nx.pagerank, D), + (lambda G, **kw: nx.hits(G, **kw)[0], D), + ]: + assert_same(outcome(f, H, backend="graphblas"), outcome(f, H, backend="networkx")) + + +# Weights of 0 or below. NetworkX divides by the largest weight (clustering), by weight sums +# (the modularity matrices, google_matrix, pagerank) and takes their square roots +# (normalized_laplacian_matrix); a sum of weights of both signs can cancel, to 0 or to a small +# number, by the order it adds in. + + +def answer(f, *args, **kwargs): + """The answer, or the exception's type and message.""" + try: + result = f(*args, **kwargs) + except Exception as exc: + return type(exc), str(exc) + return outcome(lambda: result) + + +def assert_networkx_s(f, G, *args, **kwargs): + """Through the dispatcher, graphblas first: NetworkX's answer, or its exception and message.""" + want = answer(f, G, *args, backend="networkx", **kwargs) + with graphblas_first(): + got = answer(f, G, *args, **kwargs) + if isinstance(want, tuple) or isinstance(got, tuple): + assert got == want + else: + assert_same(got, want) + + +def signed(directed, values, seed=0, self_loop=False): + """A random graph on 0..7 plus an isolated node 9; each edge's weight one of `values`. + + The first edge takes `values[0]`, so a pattern whose first value is 0 holds a 0. + """ + rng = np.random.default_rng(seed) + G = nx.gnp_random_graph(8, 0.5, seed=seed, directed=directed) + if self_loop: + G.add_edge(2, 2) + for k, (u, v) in enumerate(G.edges): + G[u][v]["weight"] = values[0] if k == 0 else values[rng.integers(len(values))] + G.add_node(9) + return G + + +# The weights of the case that found these: ints, every one 0 or below, some of them 0. +BIG_NEGATIVE = [0, -(2**53) - 1, -(2**60) - 3, -(2**55) - 1, -(2**61) + 1, -3] +SIGNS = { + "0 or below": [0, -1, -2, -3], + "0 or below, floats": [0.0, -0.1, -0.2, -0.3], + "every weight 0": [0], + "below 0": [-1, -2.5, -3], + "both signs": [-3, -1, 1, 2, 4], + "both signs and 0": [-0.2, -0.1, 0.0, 0.1, 0.2], + "both signs, cancelling": [0.1, 0.2, -0.3, -0.1], +} + + +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_clustering_with_a_largest_weight_of_0_is_networkx_s(name, directed, seed): + """NetworkX divides by the largest weight, 0: ZeroDivisionError for Python numbers.""" + f = getattr(nx, name) + for values in [BIG_NEGATIVE, SIGNS["0 or below, floats"], SIGNS["every weight 0"]]: + G = signed(directed, values, seed) + assert "largest weight of 0" in declined_reason(f, G, weight="weight") + assert_networkx_s(f, G, weight="weight") + assert answer(f, G, weight="weight", backend="networkx")[0] is ZeroDivisionError + # unweighted, the weights are not read + assert_same(outcome(f, G, backend="graphblas"), outcome(f, G, backend="networkx")) + + +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_clustering_with_numpy_weights_and_a_largest_of_0_is_networkx_s(name): + """NumPy divides by 0 with a warning, so NetworkX gives NaN or infinities, not an error.""" + f = getattr(nx, name) + G = signed(False, [np.float64(x) for x in SIGNS["0 or below, floats"]]) + assert "largest weight of 0" in declined_reason(f, G, weight="weight") + assert_networkx_s(f, G, weight="weight") + + +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("values", ["below 0", "both signs", "both signs, cancelling"]) +@pytest.mark.parametrize("name", ["clustering", "average_clustering"]) +def test_clustering_with_a_largest_weight_not_0_is_served(name, values, directed, seed): + """Below 0, every weight scales to a positive one; with both signs, as NetworkX scales.""" + f = getattr(nx, name) + G = signed(directed, SIGNS[values], seed, self_loop=seed == 1) + want = outcome(f, G, weight="weight", backend="networkx") + assert_same(outcome(f, G, weight="weight", backend="graphblas"), want) + + +MATRICES = { + "normalized_laplacian_matrix": (nx.normalized_laplacian_matrix, "UD"), + "modularity_matrix": (modularity, "U"), + "directed_modularity_matrix": (directed_modularity, "D"), + "google_matrix": (nx.google_matrix, "UD"), +} + + +def nodelists(name, G): + """No nodelist; and a subset in another order, or for google_matrix every node reordered.""" + if name == "google_matrix": + return [None, sorted(G, reverse=True)] + return [None, [5, 3, 1, 0, 2]] + + +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("values", SIGNS) +@pytest.mark.parametrize("name", MATRICES) +def test_matrices_with_weights_of_0_or_below_are_networkx_s(name, values, seed): + """Served with NetworkX's arithmetic: NaN where NetworkX has it, and its rounding. + + NaN comes from a square root of a negative sum, or a division by a sum of 0; where sums + cancel, the rounding of NetworkX's order of addition decides the result. + """ + f, kinds = MATRICES[name] + for directed in [kind == "D" for kind in kinds]: + G = signed(directed, SIGNS[values], seed, self_loop=seed == 1) + for nodelist in nodelists(name, G): + want = outcome(f, G, nodelist=nodelist, backend="networkx") + got = outcome(f, G, nodelist=nodelist, backend="graphblas") + assert_same(got, want, exact=name != "google_matrix" or values != "every weight 0") + + +@pytest.mark.parametrize("value", [NAN, -INF], ids=["nan", "-inf"]) +@pytest.mark.parametrize("directed", [False, True]) +def test_normalized_laplacian_with_a_nan_or_minus_inf_beside_a_0_weight(directed, value): + """NetworkX's L = D - A holds no entry for an edge of weight 0, so no NaN lands there.""" + G = signed(directed, [value, 0.0, 0.0, 1.5, 2.5], seed=2) + want = outcome(nx.normalized_laplacian_matrix, G, backend="networkx") + assert_same(outcome(nx.normalized_laplacian_matrix, G, backend="graphblas"), want, exact=True) + + +@pytest.mark.parametrize("name", ["modularity_matrix", "directed_modularity_matrix"]) +def test_modularity_with_a_nodelist_selecting_only_weights_of_0(name): + """The graph's other weights are positive, but `m` of the weights selected is 0. + + NetworkX's `outer(k, k) / (2 * m)` is then NaN everywhere, also at node 9, which has no + weight selected. + """ + f, directed, _ = SERVED[name] + G = nx.path_graph(5, create_using=nx.DiGraph if directed else nx.Graph) + nx.set_edge_attributes(G, 1.0, "weight") + G[1][2]["weight"] = G[2][3]["weight"] = 0.0 + G.add_node(9) + for nodelist in [[3, 2, 1], [3, 2, 9, 1]]: + want = outcome(f, G, nodelist=nodelist, backend="networkx") + assert np.isnan(want).all() + assert_same(outcome(f, G, nodelist=nodelist, backend="graphblas"), want) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_google_matrix_where_a_row_cancels_to_a_rounding(directed): + """Node 0's weights sum to 2.8e-17 in NumPy's order and to 5.6e-17 left to right. + + NetworkX divides the row by the sum, so the order of addition decides its entries. + """ + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(9)) + G.add_weighted_edges_from([(0, 1, 0.1), (0, 2, 0.2), (0, 3, -0.3), (4, 5, 1.0)]) + want = outcome(nx.google_matrix, G, backend="networkx") + assert want[0, 1] > 1e15 + assert_same(outcome(nx.google_matrix, G, backend="graphblas"), want) + + +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("values", ["below 0", "both signs", "both signs, cancelling"]) +def test_pagerank_with_a_negative_weight_is_networkx_s(values, directed, seed): + """Declined only where a node's out-weights can cancel to another sum in another order.""" + G = signed(directed, SIGNS[values], seed) + if out_weights_of_both_signs(G): + assert "both signs, three or more" in declined_reason(nx.pagerank, G) + else: + assert values == "below 0" + assert_same( + outcome(nx.pagerank, G, backend="graphblas"), answer(nx.pagerank, G, backend="networkx") + ) + assert_networkx_s(nx.pagerank, G) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_pagerank_where_out_weights_cancel(directed): + """0.1 + 0.2 - 0.3 is 5.6e-17 from left to right and 2.8e-17 from right to left. + + Two out-weights sum to the same in either order, and a zero changes nothing, so a node + whose out-weights are 1, -1 and 0 sums to 0 here as in NetworkX, and is dangling. + """ + three = nx.DiGraph() if directed else nx.Graph() + three.add_weighted_edges_from([(0, 1, 0.1), (0, 2, 0.2), (0, 3, -0.3), (1, 2, 1.0)]) + assert "both signs, three or more" in declined_reason(nx.pagerank, three) + assert_networkx_s(nx.pagerank, three) + two = nx.DiGraph() if directed else nx.Graph() + two.add_weighted_edges_from([(0, 1, 1.0), (0, 2, -1.0), (0, 3, 0.0)]) + if directed: + two.add_edges_from([(1, 2), (2, 3), (3, 0)], weight=1.0) + else: + two.add_edges_from([(1, 3), (2, 3)], weight=1.0) + assert not out_weights_of_both_signs(two) + for kwargs in [{}, {"personalization": {0: 1, 1: 2}, "dangling": {2: 1}}]: + want = outcome(nx.pagerank, two, backend="networkx", **kwargs) + assert_same(outcome(nx.pagerank, two, backend="graphblas", **kwargs), want) + + +def hubs_and_authorities(G, **kwargs): + hubs, authorities = nx.hits(G, tol=1e-12, max_iter=1000, **kwargs) + return { + **{("hub", n): x for n, x in hubs.items()}, + **{("auth", n): x for n, x in authorities.items()}, + } + + +def networkx_repeats(f, G): + """Whether NetworkX gives `f`'s answer twice. + + NetworkX 3.6 computes hits with ARPACK from a random start, so where the largest singular + value is repeated, its vectors differ from run to run. + """ + first, second = (answer(f, G, backend="networkx") for _ in range(2)) + if isinstance(first, tuple) or isinstance(second, tuple): + return first == second + return all(math.isclose(first[k], second[k], abs_tol=1e-9) for k in first) + + +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("values", ["every weight 0", "0 or below", "below 0", "both signs"]) +def test_hits_with_a_negative_weight_or_every_weight_0_is_networkx_s(values, directed, seed): + """NetworkX divides by the largest hub value over every node, which can be 0 here.""" + G = signed(directed, SIGNS[values], seed) + assert "negative weight, or with every weight 0" in declined_reason(nx.hits, G) + if networkx_repeats(hubs_and_authorities, G): + assert_networkx_s(hubs_and_authorities, G) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_hits_with_no_edges_still_answers_0(directed): + """As the backend's notes say: NetworkX's power iteration does not converge here.""" + G = nx.empty_graph(4, create_using=nx.DiGraph if directed else nx.Graph) + h, a = nx.hits(G, backend="graphblas") + assert dict(h) == dict(a) == dict.fromkeys(G, 0.0) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_hits_of_the_null_graph_is_served(directed): + G = nx.DiGraph() if directed else nx.Graph() + assert nx.hits(G, backend="graphblas") == nx.hits(G, backend="networkx") == ({}, {}) + + +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("values", [[1, 2, 3], [0, 1.5, 2.5], [0.5, 0.0]], ids=str) +def test_positive_weights_are_served(values, directed, seed): + """With or without weights of 0, beside a positive one.""" + G = signed(directed, values, seed, self_loop=seed == 1) + calls = [ + lambda G, **kw: nx.clustering(G, weight="weight", **kw), + lambda G, **kw: nx.average_clustering(G, weight="weight", **kw), + nx.pagerank, + hubs_and_authorities, + nx.normalized_laplacian_matrix, + nx.google_matrix, + directed_modularity if directed else modularity, + ] + for f in calls: + if f is hubs_and_authorities and not networkx_repeats(f, G): + continue + assert_same(outcome(f, G, backend="graphblas"), outcome(f, G, backend="networkx"))