diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..7d5b7fc 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -211,6 +211,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.", + "google_matrix": "Keys of `personalization` and `dangling` that are not nodes are left out, as NetworkX\nleaves them. NetworkX divides each by its sum: where `personalization` sums to 0, inf\nor NaN, or `dangling` does and a node dangles, the call is left to NetworkX.", "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".', @@ -224,6 +225,7 @@ def get_info(): "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "pagerank": "Keys of `nstart`, `personalization` and `dangling` that are not nodes are left out, as\nNetworkX leaves them. NetworkX divides each by its sum, `dangling` even where no node\ndangles: where one sums to 0, inf or NaN, the call is left to NetworkX.\nWhere values of both signs nearly cancel, so that dividing by their sum magnifies its\nrounding, rounding may decide whether NetworkX's iteration stops, and its ranks: such a\ncall is left to NetworkX. The sums are each node's out-weights and those of `nstart`,\n`personalization` and `dangling`; the magnifications, the sum of the values' sizes over\nthe size of their sum, are multiplied, and the call is left to NetworkX past\n`sqrt(tol / 2**-52) / 100` (671 for the default `tol`). A node with three or more\nout-weights of both signs is left to NetworkX in any case.", "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..15e2f74 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -151,6 +151,11 @@ ), "floyd_warshall": _PATH_OVERFLOW, "floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW, + "google_matrix": ( + "Keys of `personalization` and `dangling` that are not nodes are left out, as NetworkX\n" + "leaves them. NetworkX divides each by its sum: where `personalization` sums to 0, inf\n" + "or NaN, or `dangling` does and a node dangles, the call is left to NetworkX." + ), "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, @@ -171,6 +176,18 @@ "memory stays bounded." ), "negative_edge_cycle": _PATH_OVERFLOW, + "pagerank": ( + "Keys of `nstart`, `personalization` and `dangling` that are not nodes are left out, as\n" + "NetworkX leaves them. NetworkX divides each by its sum, `dangling` even where no node\n" + "dangles: where one sums to 0, inf or NaN, the call is left to NetworkX.\n" + "Where values of both signs nearly cancel, so that dividing by their sum magnifies its\n" + "rounding, rounding may decide whether NetworkX's iteration stops, and its ranks: such a\n" + "call is left to NetworkX. The sums are each node's out-weights and those of `nstart`,\n" + "`personalization` and `dangling`; the magnifications, the sum of the values' sizes over\n" + "the size of their sum, are multiplied, and the call is left to NetworkX past\n" + "`sqrt(tol / 2**-52) / 100` (671 for the default `tol`). A node with three or more\n" + "out-weights of both signs is left to NetworkX in any case." + ), "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' diff --git a/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py b/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py index 6cd1f2d..814f220 100644 --- a/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py +++ b/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py @@ -2,7 +2,7 @@ import numpy as np from graphblas import Matrix, Vector, binary, monoid -from graphblas.semiring import plus_first, plus_times +from graphblas.semiring import any_rdiv, plus_first, plus_times from graphblas_algorithms import Graph @@ -65,7 +65,10 @@ def pagerank( # Fold alpha constant into S if row_degrees is None: row_degrees = nonzero_out_weight_sums(A) - S = (alpha / row_degrees).new(name="S") + # 1 / sum first, as NetworkX takes it: below about 5.6e-309 it passes the largest float, + # where alpha / sum may not, and NetworkX's ranks turn inf or NaN. + S = (1.0 / row_degrees).new(name="S") + S *= alpha if (iso_value := G.get_property("iso_value")) is not None: # Fold iso-value of A into S @@ -82,9 +85,12 @@ def pagerank( dangling_mask(mask=~S.S) << 1.0 # Fold alpha constant into dangling_weights (or dangling_mask) if dangling is not None: - dangling_weights = (alpha / dangling.reduce().get(0) * dangling).new( - name="dangling_weights" - ) + denom = dangling.reduce().get(0) + if denom == 0: + raise ZeroDivisionError("dangling sums to 0") + # Divided first, as in NetworkX: alpha over a tiny sum can pass the largest float + dangling_weights = (dangling / denom).new(name="dangling_weights") + dangling_weights *= alpha elif personalization is None: # Fast case (and common case); is iso-valued dangling_mask(mask=dangling_mask.S) << alpha * p @@ -156,19 +162,23 @@ def google_matrix( if dangling is not None: if ids is not None: dangling = dangling[ids].new(name="dangling") - dangling_weights = (1.0 / dangling.reduce().get(0) * dangling).new( - mask=dangling.V, name="dangling_weights" - ) + denom = dangling.reduce().get(0) + if denom == 0: + raise ZeroDivisionError("dangling sums to 0") + # Divided, as in NetworkX: 1 over a tiny sum can pass the largest float + dangling_weights = (dangling / denom).new(mask=dangling.V, name="dangling_weights") A << binary.first(empty_rows.outer(dangling_weights) | A) elif personalization is None: A << binary.first((p * empty_rows) | A) else: A << binary.first(empty_rows.outer(p) | A) + # Each row divided by its sum, as in NetworkX: 1 or alpha over a tiny sum can pass the + # largest float, and the row would turn inf scale = A.reduce_rowwise(monoid.plus).new(float) rows, sums = scale.to_coo() - scale << alpha / scale - A << scale * A + A << any_rdiv(scale.diag() @ A) + A *= alpha p *= 1 - alpha if personalization is None: # Add a scalar everywhere, which makes A dense diff --git a/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py b/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py index cf2e63f..0b012ef 100644 --- a/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py +++ b/graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py @@ -1,7 +1,8 @@ +import math from math import inf import numpy as np -from graphblas import agg, binary +from graphblas import Vector, agg, binary, monoid, unary from graphblas_algorithms import algorithms from graphblas_algorithms.algorithms.link_analysis.pagerank_alg import nonzero_out_weight_sums @@ -44,12 +45,20 @@ def pagerank( "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 row_sums.nvals < N: - dangling_weights = G.dict_to_vector(dangling, dtype=float, name="dangling") - else: - dangling_weights = None + x = _values_at_nodes(G, nstart, "nstart") + p = _values_at_nodes(G, personalization, "personalization") + d = _values_at_nodes(G, dangling, "dangling") + # NetworkX divides the dangling values by their sum even where no node dangles, and then + # fails to converge where that sum is 0, inf or NaN: 0 times NaN is NaN + _check_sums("pagerank", nstart=x, personalization=p, dangling=d) + dangling_weights = d if d is not None and row_sums.nvals < N else None + # Dividing by a sum magnifies its rounding where its values cancel, which NetworkX's own + # rounding then decides: whether it stops, and with which ranks. + magnified = _magnification(G._A, x, p, dangling_weights) + if magnified > 1 and magnified > _magnification_allowed(tol): + raise NotImplementedError( + "pagerank where values of both signs nearly cancel is left to networkx" + ) try: result = algorithms.pagerank( G, @@ -85,6 +94,77 @@ def find(): return G._cacheit("out_weights_cancel_by_order", find) +def _values_at_nodes(G, values, name): + """A dict's values at `G`'s nodes, as a vector; other keys are left out, as NetworkX does.""" + if values is None: + return None + key_to_id = G._key_to_id + pairs = [(key_to_id[key], value) for key, value in values.items() if key in key_to_id] + ids, at_nodes = zip(*pairs, strict=True) if pairs else ((), ()) + return Vector.from_coo(ids, at_nodes, size=len(G), dtype=float, name=name) + + +def _check_sums(name, **vectors): + """Leave to NetworkX a call where one of `vectors` sums to 0, or to inf or NaN. + + NetworkX divides each by its sum: 0 makes NaN, so its iteration fails to converge (for + `personalization` it raises ZeroDivisionError), and so does a value of inf or NaN, which + makes NaN in `google_matrix`. Finite values whose sum only overflows give zeros there; + such a call goes to NetworkX as well. + """ + for key, v in vectors.items(): + if v is not None: + total = v.reduce().get(0) + if total == 0 or not math.isfinite(total): + raise NotImplementedError(f"{name} where {key} sums to {total} is left to networkx") + + +def _magnification_allowed(tol): + """The most rounding may be magnified, for NetworkX's answer to stay the same here. + + Rounding to within `eps` (2**-52), magnified `m` times in the ranks and `m` times again in + the change between rounds, which stops the iteration at `N * tol`: this keeps `eps * m**2` + at least 10**4 times below `tol`. NetworkX first gave another answer at 7 to 9 times + `sqrt(N * tol / eps)`, 1100 to 1600 times this, on a node whose out-weights nearly cancel and + whose two heads lead back to it, where their huge ranks cancel again. + """ + if not tol > 0: # NetworkX never stops: its change between rounds is never below 0 + return 0.0 + return math.sqrt(tol / np.finfo(float).eps) / 100 + + +def _magnification(A, *vectors): + """How much dividing by sums that cancel may magnify their rounding, at most. + + For values of both signs, the sum of their sizes over the size of their sum: in each node's + out-weights, and in each of `vectors` given. The product of these, as a path in the graph + may pass through every such node. 1 where nothing cancels. A row that sums to 0 dangles, + and is not counted: the caller has left out-weights of both signs, three or more of them, + to NetworkX (`_out_weights_cancel_by_order`), and two add to 0 in either order. It has also + left a vector that sums to 0 to NetworkX (`_check_sums`). + """ + + def product(logs): + return math.exp(logs) if logs < 700 else math.inf + + logs = 0.0 + for v in vectors: + if v is not None and v.reduce(monoid.min).get(0) < 0 < v.reduce(monoid.max).get(0): + total = v.reduce().get(0) + logs += math.log(unary.abs(v).reduce().get(0) / abs(total)) + if A.nvals == 0 or A.reduce_scalar(monoid.min).get(0) >= 0: + return product(logs) + low = A.reduce_rowwise(monoid.min).new().select("<", 0).new() + high = A.reduce_rowwise(monoid.max).new().select(">", 0).new() + mixed = binary.pair(low & high).new() + if mixed.nvals == 0: + return product(logs) + sums = A.reduce_rowwise().new(mask=mixed.S) + sizes = unary.abs(A).reduce_rowwise().new(mask=sums.select("!=", 0).new().S) + _, ratios = binary.truediv(sizes & unary.abs(sums)).new().to_coo() + return product(logs + float(np.log(ratios).sum())) + + def google_matrix( G, alpha=0.85, personalization=None, nodelist=None, weight="weight", dangling=None ): @@ -92,11 +172,12 @@ def google_matrix( 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") + p = _values_at_nodes(G, personalization, "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") + dangling_weights = _values_at_nodes(G, dangling, "dangling") else: dangling_weights = None + _check_sums("google_matrix", personalization=p, dangling=dangling_weights) rv = algorithms.google_matrix( G, alpha=alpha, diff --git a/graphblas_algorithms/nxapi/tests/test_link_analysis.py b/graphblas_algorithms/nxapi/tests/test_link_analysis.py index 9bd75ee..edef824 100644 --- a/graphblas_algorithms/nxapi/tests/test_link_analysis.py +++ b/graphblas_algorithms/nxapi/tests/test_link_analysis.py @@ -263,3 +263,329 @@ def test_pagerank_reads_the_weights_this_call_asked_for(make, weight, warm): nx.pagerank(G, weight="weight", backend="graphblas") got = nx.pagerank(G, weight=weight, backend="graphblas") assert got == pytest.approx(nx.pagerank(make(), weight=weight)) + + +def _cancelling(k, a=1.0): + """0 sends its rank to 1 and 2 by out-weights summing to `a / k`, and both send it back. + + Dividing by that sum magnifies its rounding `2 * k - 1` times in the ranks of 1 and 2, + which cancel again at 0. + """ + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, a), (0, 2, -a + a / k), (1, 0, 1.0), (2, 0, 1.0)]) + return G + + +def _cancelling_twice(k): + """`_cancelling` with 1 and 2 each sending their rank on as 0 does: magnified k**2 at 3 to 6.""" + b = -1.0 + 1.0 / k + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, 1.0), (0, 2, b), (1, 3, 1.0), (1, 4, b), (2, 5, 1.0)]) + G.add_weighted_edges_from([(2, 6, b), (3, 7, 1.0), (4, 7, 1.0), (5, 8, 1.0), (6, 8, 1.0)]) + G.add_weighted_edges_from([(7, 0, 1.0), (8, 0, 1.0)]) + return G + + +def _pagerank_outcome(G, backend, **kwargs): + """("value", ranks), ("raised", its type), or ("declined",) where graphblas declines.""" + try: + if backend == "automatic": + with nx.config.backend_priority(algos=["graphblas"]): + return "value", nx.pagerank(G, **kwargs) + return "value", nx.pagerank(G, backend=backend, **kwargs) + except NotImplementedError: + if backend == "graphblas": + return ("declined",) + raise + except nx.NetworkXException as exc: + return "raised", type(exc) + + +def _assert_pagerank_as_networkx(G, **kwargs): + """NetworkX's outcome, called with graphblas first; whether graphblas itself answered.""" + expected = _pagerank_outcome(G, "networkx", **kwargs) + got = _pagerank_outcome(G, "automatic", **kwargs) + assert got[0] == expected[0] + if expected[0] == "value": + assert got[1] == pytest.approx(expected[1], rel=1e-9) + else: + assert got == expected + return _pagerank_outcome(G, "graphblas", **kwargs) != ("declined",) + + +def test_pagerank_leaves_out_weights_that_nearly_cancel_to_networkx(): + """Out-weights 1 and -1 + 2**-51: NetworkX fails to converge, where this gave huge ranks.""" + G = _cancelling(2.0**51 / (1 - 2.0**-51)) + assert sum(w for _, _, w in G.out_edges(0, data="weight")) == 2.0**-51 + with pytest.raises(NotImplementedError, match="nearly cancel"): + nxapi.pagerank(G) + assert not _assert_pagerank_as_networkx(G) + with pytest.raises(nx.PowerIterationFailedConvergence): + nx.pagerank(G) + + +@pytest.mark.parametrize("e", range(53)) +def test_pagerank_on_out_weights_that_cancel_as_networkx(e): + """Served where cancelling magnifies rounding at most 671 times (2 * k - 1 here).""" + k = 2.0**e + served = _assert_pagerank_as_networkx(_cancelling(k, a=0.7)) + assert served == (2 * k - 1 <= 671) + + +@pytest.mark.parametrize("k", [1.5, 2, 4, 8, 9, 100, 2.0**26]) +def test_pagerank_on_out_weights_that_cancel_twice_as_networkx(k): + """Three nodes' out-weights cancel: magnified (2 * k - 1)**3 times, served to 671.""" + served = _assert_pagerank_as_networkx(_cancelling_twice(k)) + assert served == ((2 * k - 1) ** 3 <= 671) + + +@pytest.mark.parametrize( + ("tol", "served"), + [(1e-4, True), (1e-6, True), (1e-7, True), (1e-8, False), (1e-12, False), (0, False)], +) +def test_pagerank_allows_less_cancelling_for_a_smaller_tol(tol, served): + """Magnified 199 times: rounding to 2**-52, magnified twice, stays 10**4 below `tol`.""" + G = _cancelling(100) + assert _assert_pagerank_as_networkx(G, tol=tol) == served + + +@pytest.mark.parametrize("tol", [-1.0, float("nan")]) +def test_pagerank_reads_a_tol_that_never_stops_as_networkx(tol): + """Nothing cancels in the second graph, which is served as NetworkX fails to converge.""" + _assert_pagerank_as_networkx(_cancelling(100), tol=tol) + assert _assert_pagerank_as_networkx(_weighted_directed(), tol=tol) + + +@pytest.mark.parametrize("kwarg", ["personalization", "nstart", "dangling"]) +@pytest.mark.parametrize("k", [2, 100, 400, 1e4, 2.0**52]) +def test_pagerank_on_values_that_cancel_as_networkx(kwarg, k): + """`personalization`, `nstart` and `dangling` values summing to `1 / k`: 2 * k - 1 again.""" + G = _weighted_with_a_dangling_node() + values = {1: 1.0, 2: 0.5, 3: -1.5 + 1 / k} + served = _assert_pagerank_as_networkx(G, **{kwarg: values}) + sizes = sum(map(abs, values.values())) + assert served == (sizes / abs(sum(values.values())) <= 671) + + +def test_pagerank_leaves_three_out_weights_that_add_to_zero_to_networkx(): + """1 + 2 - 3 is 0 here; another order of adding three or more values may not give 0.""" + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, 1.0), (0, 2, 2.0), (0, 3, -3.0), (1, 0, 1.0)]) + G.add_weighted_edges_from([(2, 0, 1.0), (3, 0, 1.0)]) + assert not _assert_pagerank_as_networkx(G) + with pytest.raises(NotImplementedError, match="both signs, three or more"): + nxapi.pagerank(G) + + +@pytest.mark.parametrize("zeros", [1, 2]) +def test_pagerank_serves_two_out_weights_that_add_to_zero_beside_zeros(zeros): + """1 - 1 and any zeros add to 0 in every order, so the node dangles, as in NetworkX.""" + G = _out_weights_sum_to_zero() + G.add_weighted_edges_from([(0, 3 + i, 0.0) for i in range(zeros)]) + assert _assert_pagerank_as_networkx(G) + assert _assert_pagerank_as_networkx(G, personalization={0: 1, 1: 2}, dangling={2: 1}) + + +def test_pagerank_serves_out_weights_of_one_sign(): + """Negative out-weights alone do not cancel: each share of the rank is positive.""" + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, -1.0), (0, 2, -3.0), (1, 0, 1.0), (2, 0, 2.0), (2, 1, 0.5)]) + assert _assert_pagerank_as_networkx(G) + assert _assert_pagerank_as_networkx(G, personalization={0: -1.0, 1: -2.0}) + + +def test_pagerank_magnification(): + from graphblas_algorithms.nxapi.link_analysis.pagerank_alg import _magnification + + def of(G, *vectors): + B = DiGraph.from_networkx(G, weight="weight") + return _magnification(B._A, *(None if v is None else B.dict_to_vector(v) for v in vectors)) + + assert of(_weighted_directed()) == 1 + assert of(_cancelling(4)) == pytest.approx(7) + assert of(_cancelling(4, a=-1.0)) == pytest.approx(7) # a sum of -1/4 + assert of(_cancelling_twice(4)) == pytest.approx(7**3) + assert of(_cancelling(4), {1: 1.0, 2: -0.5}, None) == pytest.approx(7 * 3) + assert of(_weighted_directed(), {1: -1.0, 2: 0.5}) == pytest.approx(3) + assert of(_out_weights_sum_to_zero()) == 1 # two values give 0 in either order + G = _out_weights_sum_to_zero() + G.add_weighted_edges_from([(0, 3, 0.0), (0, 4, 0.0)]) + assert of(G) == 1 # and so do they beside zeros + G = nx.DiGraph() + for u in range(0, 400, 4): # 100 nodes whose out-weights cancel to 1 part in 1000 + G.add_weighted_edges_from([(u, u + 1, 1.0), (u, u + 2, -0.999), (u + 1, u, 1.0)]) + assert of(G) == float("inf") + + +def _outcome(func, G, backend, **kwargs): + """As `_pagerank_outcome` for `func`, with any exception's type and message.""" + try: + if backend == "automatic": + with nx.config.backend_priority(algos=["graphblas"]): + return "value", func(G, **kwargs) + return "value", func(G, backend=backend, **kwargs) + except NotImplementedError: + if backend == "graphblas": + return ("declined",) + raise + except Exception as exc: + return "raised", type(exc), str(exc) + + +def _as_networkx(func, G, **kwargs): + """NetworkX's outcome, called with graphblas first; whether graphblas itself answered.""" + expected = _outcome(func, G, "networkx", **kwargs) + got = _outcome(func, G, "automatic", **kwargs) + assert got[0] == expected[0] + if expected[0] != "value": + assert got == expected + elif func is nx.pagerank: + assert got[1] == pytest.approx(expected[1], rel=1e-9) + else: + np.testing.assert_allclose(got[1], expected[1], rtol=1e-9) + return _outcome(func, G, "graphblas", **kwargs) != ("declined",) + + +def _nothing_dangles(): + return _weighted_directed() + + +# NetworkX's own division by these sums warns +NX_DIVIDES_BY_ZERO = pytest.mark.filterwarnings("ignore:.*encountered in:RuntimeWarning") +SUMS_TO_ZERO = pytest.mark.parametrize( + "values", + [{}, "zeros", {1: 0.0}, {1: 1.0, 2: -1.0}, {1: 1.0, 2: 1.0, 3: -2.0}, {99: 1.0}], + ids=["empty", "zeros", "one-zero", "cancel", "cancel-three", "not-a-node"], +) + + +@NX_DIVIDES_BY_ZERO +@pytest.mark.parametrize("make", [_weighted_with_a_dangling_node, _nothing_dangles]) +@pytest.mark.parametrize("kwarg", ["nstart", "personalization", "dangling"]) +@SUMS_TO_ZERO +def test_pagerank_leaves_values_that_sum_to_zero_to_networkx(make, kwarg, values): + """NetworkX divides by the sum, the dangling values' too where no node dangles: NaN.""" + G = make() + values = dict.fromkeys(G, 0.0) if values == "zeros" else values + assert not _as_networkx(nx.pagerank, G, **{kwarg: values}) + with pytest.raises(NotImplementedError, match=f"where {kwarg} sums to 0"): + nxapi.pagerank(G, **{kwarg: values}) + + +@NX_DIVIDES_BY_ZERO +@pytest.mark.parametrize("make", [_weighted_with_a_dangling_node, _nothing_dangles]) +@pytest.mark.parametrize("kwarg", ["nstart", "personalization", "dangling"]) +@pytest.mark.parametrize( + "values", + [{1: float("nan"), 2: 1.0}, {1: float("inf"), 2: 1.0}, {1: -float("inf"), 2: 1.0}], + ids=["nan", "inf", "-inf"], +) +def test_pagerank_leaves_values_that_sum_to_inf_or_nan_to_networkx(make, kwarg, values): + """Where no node dangles, NetworkX still reads the dangling values, times 0: NaN.""" + assert not _as_networkx(nx.pagerank, make(), **{kwarg: values}) + + +@pytest.mark.parametrize("make", [_weighted_with_a_dangling_node, _nothing_dangles]) +@pytest.mark.parametrize("kwarg", ["nstart", "personalization", "dangling"]) +@pytest.mark.parametrize( + "values", [{1: 1.0, 99: 5.0}, {1: 1.0, 2: 3.0, 99: -1.0}], ids=["positive", "negative"] +) +def test_pagerank_leaves_out_keys_that_are_not_nodes(make, kwarg, values): + """As NetworkX does, which reads the dict at each node.""" + assert _as_networkx(nx.pagerank, make(), **{kwarg: values}) + + +@NX_DIVIDES_BY_ZERO +@pytest.mark.parametrize("make", [_weighted_with_a_dangling_node, _nothing_dangles]) +@SUMS_TO_ZERO +def test_google_matrix_leaves_a_personalization_that_sums_to_zero_to_networkx(make, values): + """NetworkX raises ZeroDivisionError, with no message.""" + G = make() + values = dict.fromkeys(G, 0.0) if values == "zeros" else values + assert not _as_networkx(nx.google_matrix, G, personalization=values) + + +@NX_DIVIDES_BY_ZERO +@SUMS_TO_ZERO +def test_google_matrix_leaves_dangling_values_that_sum_to_zero_to_networkx(values): + """NetworkX's dangling row is NaN, where a node dangles; elsewhere it reads no such row.""" + G = _weighted_with_a_dangling_node() + values = dict.fromkeys(G, 0.0) if values == "zeros" else values + assert not _as_networkx(nx.google_matrix, G, dangling=values) + assert _as_networkx(nx.google_matrix, _nothing_dangles(), dangling=values) + + +@NX_DIVIDES_BY_ZERO +@pytest.mark.parametrize("kwarg", ["personalization", "dangling"]) +@pytest.mark.parametrize( + "values", + [{1: float("nan"), 2: 1.0}, {1: float("inf"), 2: 1.0}, {1: -float("inf"), 2: 1.0}], + ids=["nan", "inf", "-inf"], +) +def test_google_matrix_leaves_values_that_sum_to_inf_or_nan_to_networkx(kwarg, values): + """NetworkX's matrix has NaN where these values are divided by their sum.""" + assert not _as_networkx(nx.google_matrix, _weighted_with_a_dangling_node(), **{kwarg: values}) + + +@pytest.mark.parametrize("make", [_weighted_with_a_dangling_node, _nothing_dangles]) +@pytest.mark.parametrize("kwarg", ["personalization", "dangling"]) +@pytest.mark.parametrize( + "values", [{1: 1.0, 99: 5.0}, {1: 1.0, 2: 3.0, 99: -1.0}], ids=["positive", "negative"] +) +def test_google_matrix_leaves_out_keys_that_are_not_nodes(make, kwarg, values): + assert _as_networkx(nx.google_matrix, make(), **{kwarg: values}) + + +def _tiny_out_weights(w): + """Out-weights of `w` on a cycle, and 0 with two of them; 3 dangles.""" + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, w), (1, 2, w), (2, 0, w), (0, 3, w)]) + return G + + +def _one_tiny_out_weight(w): + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, 1.0), (1, 2, w), (2, 0, 1.0)]) + return G + + +TINY = pytest.mark.parametrize("w", [1e-320, 5e-309, 5.5e-309, 6e-309, 1e-300]) + + +@TINY +@pytest.mark.parametrize("make", [_tiny_out_weights, _one_tiny_out_weight]) +def test_pagerank_divides_by_tiny_out_weight_sums_as_networkx(make, w): + """1 / sum passes the largest float below about 5.56e-309, and 0.85 / sum below 4.72e-309. + + NetworkX takes 1 / sum, so between the two its ranks turn inf and it fails to converge. + """ + assert _as_networkx(nx.pagerank, make(w)) + + +@TINY +@pytest.mark.parametrize("make", [_tiny_out_weights, _one_tiny_out_weight]) +def test_google_matrix_divides_by_tiny_out_weight_sums_as_networkx(make, w): + """NetworkX divides each row by its sum, where 0.85 / sum times an entry would be inf.""" + assert _as_networkx(nx.google_matrix, make(w)) + + +@pytest.mark.parametrize("func", [nx.pagerank, nx.google_matrix]) +@pytest.mark.parametrize( + "values", [{1: 1e-320}, {1: 5e-309}, {1: 1e-320, 2: 1e-320}], ids=["1e-320", "5e-309", "two"] +) +def test_dangling_values_with_a_tiny_sum_are_divided_as_networkx(func, values): + """Each value over their sum is at most 1, where 0.85 over the sum passes the largest float.""" + assert _as_networkx(func, _weighted_with_a_dangling_node(), dangling=values) + + +@pytest.mark.parametrize("kwarg", ["nstart", "personalization", "dangling"]) +def test_pagerank_kernel_raises_where_a_vector_sums_to_zero(kwarg): + from graphblas_algorithms import algorithms + + G = DiGraph.from_networkx(_weighted_with_a_dangling_node(), weight="weight") + v = G.dict_to_vector({1: 1.0, 2: -1.0}, dtype=float) + with pytest.raises(ZeroDivisionError, match=f"{kwarg} sums to 0"): + algorithms.pagerank(G, **{kwarg: v}) + if kwarg != "nstart": + with pytest.raises(ZeroDivisionError, match=f"{kwarg} sums to 0"): + algorithms.google_matrix(G, **{kwarg: v})