diff --git a/README.md b/README.md index 1bc06b5..7ec26d0 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,8 @@ graphblas_algorithms.nxapi │ └── is_tree ├── triads │ └── is_triad +├── walks +│ └── number_of_walks └── wiener ├── gutman_index ├── hyper_wiener_index diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..7ec5ed9 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -131,6 +131,7 @@ def get_info(): "normalized_laplacian_matrix", "number_connected_components", "number_of_isolates", + "number_of_walks", "number_weakly_connected_components", "onion_layers", "out_degree_centrality", @@ -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.", + "number_of_walks": "Counts from 2**63, where NetworkX's int64 wraps (to negative counts), are exact here up\nto 2**64; OverflowError is raised where a count could reach 2**64. A `walk_length` that\nis not an int is left to NetworkX.", "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..021872b 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -171,6 +171,11 @@ "memory stays bounded." ), "negative_edge_cycle": _PATH_OVERFLOW, + "number_of_walks": ( + "Counts from 2**63, where NetworkX's int64 wraps (to negative counts), are exact here up\n" + "to 2**64; OverflowError is raised where a count could reach 2**64. A `walk_length` that\n" + "is not an int is left to NetworkX." + ), "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..7794a57 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 .walks import * from .wiener import * diff --git a/graphblas_algorithms/algorithms/walks.py b/graphblas_algorithms/algorithms/walks.py new file mode 100644 index 0000000..6d69094 --- /dev/null +++ b/graphblas_algorithms/algorithms/walks.py @@ -0,0 +1,102 @@ +import math + +import numpy as np +from graphblas import Matrix, agg, dtypes, monoid, semiring, unary + +__all__ = ["number_of_walks"] + +# Integers below this, and sums of them that stay below it, are exact in FP64. +_EXACT = 2**53 +_UNIT_ROUNDOFF = 2.0**-53 + + +def number_of_walks(G, walk_length, *, method=None): + """The number of walks of `walk_length` edges from each node to each, as a dense array. + + Rows and columns are in node id order. Each edge counts once whatever its value, and so + does a self-loop. The counts are exact integers, in int64 below 2**53 and in uint64 above, + and OverflowError is raised where one could reach 2**64. On a graph with no edges they are + floats, as NetworkX's adjacency matrix of such a graph is float64. + """ + A = G._A + n = A.nrows + if A.nvals == 0: + return np.eye(n) if walk_length == 0 else np.zeros((n, n)) + X, exact = _power(A, walk_length, dtypes.FP64, method) + if exact: + return X.to_dense(fill_value=0).astype(np.int64) + # A count passed 2**53, so these are estimates. + largest = X.reduce_scalar(monoid.max).get(0) + if not _largest_count_bound(largest, n, walk_length) < 2**64: + raise OverflowError( + f"the number of walks of length {walk_length} could reach 2**64 (the largest is " + f"about {largest:.4g}), which 64-bit integers cannot hold" + ) + # uint64 arithmetic wraps modulo 2**64 even where a product on the way does not fit, so + # every count below 2**64 comes out exact. + X, _ = _power(A, walk_length, dtypes.UINT64, method) + return X.to_dense(fill_value=0) + + +def _largest_count_bound(largest, n, walk_length): + """An upper bound on the largest count, from the largest float estimate of the counts. + + Every term is positive, so each dot product of at most n terms is within a factor + 1 + gamma of its exact value, and a count made of `walk_length` products in a row within + (1 + gamma)**walk_length. That error is clipped at e - 1, which says nothing anyway, so a + huge length cannot overflow it. Past 1/3 the bound is inf: below, it is within a factor + of 2, so a count below 2**63 (which NetworkX's int64 holds) is never taken for 2**64. + """ + gamma = n * _UNIT_ROUNDOFF / (1 - n * _UNIT_ROUNDOFF) + error = math.expm1(min(1.0, min(walk_length, 2**53) * math.log1p(gamma))) + return largest / (1 - error) if error < 1 / 3 else math.inf + + +def _power(A, k, dtype, method=None): + """`A**k` in `dtype`, each of `A`'s entries taken as 1, and whether it is exact in FP64. + + Exact means no entry of any product on the way reached 2**53. The power is built up + through the leading bits of `k`: from `A**j` to `A**(k >> s)`, by one squaring (and a + step) or by single-edge steps, whichever needs fewer multiplications. A squaring costs + the sum over nodes of (entries in its column) times (entries in its row), a step the + same with A's row instead: squaring wins on a cycle or a path, where the counts stay + sparse, and steps win once the counts fill in. `method` forces "squares" or "edges". + """ + n = A.nrows + if k == 0: + ids = np.arange(n) + return Matrix.from_coo(ids, ids, 1, dtype=dtype, nrows=n, ncols=n), True + X = unary.one[dtype](A).new() + times_A = semiring.plus_first[dtype] # A's values are not read + square = semiring.plus_times[dtype] + rows_A = _entries(A, rows=True) + exact = True + j = 1 + for shift in range(k.bit_length() - 2, -1, -1): + target = k >> shift + if X.nvals == 0: + break # no walk of this length, so none longer + # Capped: no squaring costs as much as 2**53 steps, and a huge length is past floats. + steps = min(target - j, 2**53) + if method == "squares" or ( + method is None + and (cols := _entries(X, rows=False)) @ _entries(X, rows=True) + <= steps * (cols @ rows_A) + ): + X = X.mxm(X, square).new() + j *= 2 + exact = exact and _below_exact(X, dtype) + while j < target and X.nvals: + X = X.mxm(A, times_A).new() + j += 1 + exact = exact and _below_exact(X, dtype) + return X, exact + + +def _entries(X, *, rows): + counts = X.reduce_rowwise(agg.count) if rows else X.reduce_columnwise(agg.count) + return counts.new().to_dense(fill_value=0).astype(np.float64) + + +def _below_exact(X, dtype): + return dtype != dtypes.FP64 or X.reduce_scalar(monoid.max).get(0) < _EXACT diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..50b77b4 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -446,6 +446,10 @@ class Dispatcher: # ================ is_triad = mod.is_triad + mod = nxapi.walks + # =============== + number_of_walks = mod.number_of_walks + mod = nxapi.wiener # ================ gutman_index = mod.gutman_index diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..1e6afef 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -27,6 +27,7 @@ from .tree import * from .triads import * from .tournament import is_tournament +from .walks import * from .wiener import * from . import centrality diff --git a/graphblas_algorithms/nxapi/tests/test_walks.py b/graphblas_algorithms/nxapi/tests/test_walks.py new file mode 100644 index 0000000..8042747 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_walks.py @@ -0,0 +1,442 @@ +"""number_of_walks against NetworkX and against exact counts. + +Where NetworkX's int64 holds the counts (below 2**63), they must be NetworkX's exactly: the +same values, the same types (ints, or floats on a graph without edges) and the same order. +From 2**63 NetworkX's counts wrap, so there they are checked against exact counts: the +backend's are exact below 2**64 and raise OverflowError from it. Each call is made with +``backend="graphblas"`` and with this backend first in NetworkX's priority, where a decline +must reach NetworkX's own answer. +""" + +import fractions +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 algorithms, nxapi + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +CAP = 2**64 + + +@contextmanager +def graphblas_first(): + """Put this backend first for algorithms; a decline goes to NetworkX.""" + 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 call(G, walk_length, backend=None): + """The answer of one call: ("value", counts) or ("error", type, message).""" + kwargs = {} if backend is None else {"backend": backend} + try: + return ("value", nx.number_of_walks(G, walk_length, **kwargs)) + except Exception as e: + return ("error", type(e), str(e)) + + +def exact_counts(G, k): + """The counts as Python ints, each capped at 2**64, from powers of an object matrix. + + Every term is at least 0, so a capped product is exact below the cap and the cap above. + """ + nodes = list(G) + index = {u: i for i, u in enumerate(nodes)} + n = len(nodes) + A = np.zeros((n, n), dtype=object) + for u, v in G.edges(): + A[index[u], index[v]] = 1 + if not G.is_directed(): + A[index[v], index[u]] = 1 + P = np.zeros((n, n), dtype=object) + P[range(n), range(n)] = 1 + cap = np.vectorize(lambda x: min(x, CAP), otypes=[object]) + while k: + if k & 1: + P = cap(P.dot(A)) if n else P + k >>= 1 + if k: + A = cap(A.dot(A)) if n else A + return {u: dict(zip(nodes, row, strict=True)) for u, row in zip(nodes, P.tolist(), strict=True)} + + +def largest(counts): + return max((max(row.values()) for row in counts.values() if row), default=0) + + +def assert_counts(got, expected): + """Equal, with the same types and keys in the same order.""" + assert got == expected + assert list(got) == list(expected) + for u, row in got.items(): + assert list(row) == list(expected[u]) + assert [type(x) for x in row.values()] == [type(x) for x in expected[u].values()] + + +def check(G, k): + """Served: NetworkX's counts below 2**63, the exact ones below 2**64, else OverflowError. + + Returns the largest exact count, capped at 2**64. + """ + exact = exact_counts(G, k) + top = largest(exact) + got = call(G, k, "graphblas") + if top >= CAP: + assert got[:2] == ("error", OverflowError), got + assert "could reach 2**64" in got[2] + elif top >= 2**63: + # NetworkX's int64 wraps these to negative counts. + assert got[0] == "value", got + assert got[1] == exact + assert all(type(x) is int for row in got[1].values() for x in row.values()) + assert min(min(row.values()) for row in call(G, k, "networkx")[1].values()) < 0 + else: + expected = call(G, k, "networkx") + assert got[0] == expected[0] == "value", (got, expected) + assert_counts(got[1], expected[1]) + assert got[1] == exact + G.__networkx_cache__.clear() + with graphblas_first(): + again = call(G, k) + assert again[0] == got[0] + if got[0] == "value": + assert_counts(again[1], got[1]) + else: + assert again == got + return top + + +def random_graph(seed): + """A random graph with self-loops, isolated nodes, ignored weights and mixed labels.""" + rng = np.random.default_rng(seed) + G = nx.DiGraph() if seed % 2 else nx.Graph() + n = int(rng.integers(1, 25)) + labels = [ + list(range(n)), + [f"n{i}" for i in range(n)], + [(i, "x") for i in range(n)], + rng.permutation(100)[:n].tolist(), + ][seed // 2 % 4] + G.add_nodes_from(labels) + density = [0.5, 1, 2, 4][seed // 8 % 4] + for _ in range(int(rng.poisson(density * n))): + u, v = rng.integers(0, n, size=2) + weight = [1, -2, 0.5, "w", None][int(rng.integers(0, 5))] + G.add_edge(labels[u], labels[v], weight=weight, other=3) + return G + + +WALK_LENGTHS = [0, 1, 2, 3, 4, 5, 7, 10, 16, 25, 40, 64, 2**40] + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs(seed): + G = random_graph(seed) + k = WALK_LENGTHS[seed % len(WALK_LENGTHS)] + check(G, k) + if k < 100: # both ways of building the power, which the choice may not take + H = ga.DiGraph.from_networkx(G) if G.is_directed() else ga.Graph.from_networkx(G) + exact = exact_counts(G, k) + for method in ["edges", "squares"]: + try: + counts = algorithms.number_of_walks(H, k, method=method) + except OverflowError: + assert largest(exact) >= 2**63 + else: + assert counts.tolist() == [list(row.values()) for row in exact.values()] + + +def test_networkx_examples(): + walks = check(nx.Graph([(0, 1), (1, 2)]), 2) + assert walks == 2 + assert nxapi.number_of_walks(nx.Graph([(0, 1), (1, 2)]), 2) == { + 0: {0: 1, 1: 0, 2: 1}, + 1: {0: 0, 1: 2, 2: 0}, + 2: {0: 1, 1: 0, 2: 1}, + } + assert nxapi.number_of_walks(nx.DiGraph([(0, 1), (1, 2), (2, 0)]), 3) == { + 0: {0: 1, 1: 0, 2: 0}, + 1: {0: 0, 1: 1, 2: 0}, + 2: {0: 0, 1: 0, 2: 1}, + } + G = nx.cycle_graph(3) + G.add_edge(1, 2, weight=5) + assert nxapi.number_of_walks(G, 3) == { + 0: {0: 2, 1: 3, 2: 3}, + 1: {0: 3, 1: 2, 2: 3}, + 2: {0: 3, 1: 3, 2: 2}, + } + for G in [nx.DiGraph([("A", "B"), ("B", "C"), ("C", "A")]), nx.cycle_graph(3)]: + for k in [0, 1, 2, 3]: + check(G, k) + + +def test_self_loops(): + # An undirected self-loop is one walk of length 1, as in NetworkX's adjacency matrix. + assert nxapi.number_of_walks(nx.Graph([(0, 0), (0, 1)]), 2) == { + 0: {0: 2, 1: 1}, + 1: {0: 1, 1: 1}, + } + for G in [nx.Graph([(0, 0), (0, 1), (1, 2)]), nx.DiGraph([(0, 0), (0, 1), (1, 1)])]: + for k in [1, 2, 5]: + check(G, k) + + +def test_past_int64(): + """K10: from length 21 a count passes 2**63, from 22 2**64.""" + G = nx.complete_graph(10) + diagonal, off = ((9**21 - 9) // 10, (9**21 + 1) // 10) + assert 2**63 < diagonal < off < CAP + counts = nxapi.number_of_walks(G, 21) + assert counts[0][0] == diagonal + assert counts[0][1] == off + assert nx.number_of_walks(G, 21, backend="networkx")[0][0] == diagonal - CAP + assert check(G, 20) < 2**63 + assert check(G, 21) < CAP + assert check(G, 22) == CAP + with pytest.raises(OverflowError, match="walks of length 22 could reach 2"): + nxapi.number_of_walks(G, 22) + + +@pytest.mark.parametrize( + ("n", "k", "count"), + [ + (128, 8, 128**7), # below 2**53: exact in floats + (255, 8, 255**7), # past 2**53, below 2**63: NetworkX's + (255, 9, 255**8), # past 2**63, below 2**64: NetworkX's wraps + (256, 9, 2**64), # 2**64 itself + ], +) +def test_complete_with_self_loops(n, k, count): + """Every count is n**(k - 1), so the bound is tested at its edges.""" + G = nx.complete_graph(n) + G.add_edges_from((u, u) for u in G) + if count >= CAP: + with pytest.raises(OverflowError): + nxapi.number_of_walks(G, k) + return + counts = nxapi.number_of_walks(G, k) + assert {x for row in counts.values() for x in row.values()} == {count} + assert all(type(x) is int for row in counts.values() for x in row.values()) + if count < 2**63: + assert counts == nx.number_of_walks(G, k, backend="networkx") + + +@pytest.mark.parametrize("method", ["edges", "squares", None]) +def test_large_counts_on_the_way(method): + """Counts past 2**53 at some length on the way, and few at the length asked for. + + Layers of 64 nodes, each joined to all of the next: 64**(k - 1) walks of length `k` join + two nodes `k` layers apart, so 64**9 = 2**54 cross 11 layers, and none is longer. A + directed cycle of 5 beside them keeps one walk of every length. + """ + width, layers = 64, 11 + G = nx.DiGraph() + for i in range(layers - 1): + G.add_edges_from( + (i * width + a, (i + 1) * width + b) for a in range(width) for b in range(width) + ) + nx.add_cycle(G, [("c", i) for i in range(5)]) + H = ga.DiGraph.from_networkx(G) + nodes = H.list_to_keys(range(len(H))) + for k in [10, 11, 12, 13]: + counts = algorithms.number_of_walks(H, k, method=method) + expected = np.zeros((len(G), len(G)), dtype=object) + for i, u in enumerate(nodes): + for j, v in enumerate(nodes): + if isinstance(u, tuple) and isinstance(v, tuple): + expected[i, j] = int((u[1] + k) % 5 == v[1]) + elif not isinstance(u, tuple) and not isinstance(v, tuple): + expected[i, j] = 64 ** (k - 1) if v // width - u // width == k else 0 + assert counts.tolist() == expected.tolist() + expected = nx.number_of_walks(G, 13, backend="networkx") + assert_counts(nx.number_of_walks(G, 13, backend="graphblas"), expected) + + +def test_no_edges(): + """NetworkX's adjacency matrix of a graph without edges is float64, so are its counts.""" + for G in [nx.empty_graph(3), nx.empty_graph(3, create_using=nx.DiGraph)]: + for k in [0, 1, 2, 2**70]: + check(G, k) + assert nxapi.number_of_walks(G, 0)[0] == {0: 1.0, 1: 0.0, 2: 0.0} + assert type(nxapi.number_of_walks(G, 5)[2][1]) is float + + +def test_huge_walk_lengths(): + cycle = nx.cycle_graph(7, create_using=nx.DiGraph) + assert check(cycle, 2**70 + 3) == 1 + # A DAG has no walk longer than its longest path. + assert check(nx.DiGraph([(0, 1), (1, 2), (0, 2)]), 2**70) == 0 + assert check(nx.path_graph(4), 2**70) == CAP + assert check(nx.path_graph(4), 10**400) == CAP # past the largest float + + +def test_bound_too_loose(): + """A count that grows with the walk length only polynomially, at a huge length. + + A walk from 0 to 1 here stays at 0 for some steps, crosses, and stays at 1, so there are + `k` of them, 2**60 here, which NetworkX's int64 holds. Past 2**53 the floats only bound + the counts, here within a factor no better than (1 + 2**-52)**k, which says nothing, so + the backend raises OverflowError: the count could reach 2**64 as far as it can tell. + """ + G = nx.DiGraph([(0, 0), (0, 1), (1, 1)]) + assert nx.number_of_walks(G, 2**60, backend="networkx")[0][1] == 2**60 + with pytest.raises(OverflowError): + nxapi.number_of_walks(G, 2**60) + assert check(G, 2**40) == 2**40 # here the bound is close + + +@pytest.mark.parametrize( + "walk_length", + [True, False, np.int64(3), np.uint8(2), np.int8(-1), -1, -7, 10**30], +) +def test_int_walk_lengths(walk_length): + """Ints of any kind are served; a negative one raises NetworkX's ValueError.""" + G = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 2)]) + expected = call(G, walk_length, "networkx") + got = call(G, walk_length, "graphblas") + if expected[0] == "error": + assert got == expected + elif walk_length < 2**63: + assert_counts(got[1], expected[1]) + G.__networkx_cache__.clear() + with graphblas_first(): + again = call(G, walk_length) + assert again[0] == got[0] + if got[0] == "error": + assert again == got + else: + assert_counts(again[1], got[1]) + + +@pytest.mark.parametrize( + "walk_length", + [ + 2.0, + 2.5, + np.float64(2.0), + -0.5, + -1.0, + "2", + None, + complex(2), + fractions.Fraction(2, 1), + np.array(2), + np.array([2]), + [2], + ], +) +@pytest.mark.parametrize("nodes", [3, 0]) +def test_other_walk_lengths_left_to_networkx(walk_length, nodes): + """Not an int: NetworkX's comparison with 0 or SciPy's matrix power answers it.""" + from graphblas_algorithms.interface import Dispatcher + + G = nx.cycle_graph(nodes, create_using=nx.DiGraph) + expected = call(G, walk_length, "networkx") + assert "not an int" in Dispatcher.can_run("number_of_walks", (G, walk_length), {}) + with graphblas_first(): + got = call(G, walk_length) + if expected[0] == "error": + assert got == expected + else: + assert_counts(got[1], expected[1]) + # Called directly, the comparison with 0 is NetworkX's; past it the backend declines. + try: + nxapi.number_of_walks(G, walk_length) + except NotImplementedError: + return + except Exception as e: + direct = ("error", type(e), str(e)) + else: + direct = ("value",) + assert direct == expected + + +def test_null_graph(): + for G in [nx.Graph(), nx.DiGraph()]: + for k in [0, 1, -1, 2**70]: + expected = call(G, k, "networkx") + assert expected[0] == "error" + assert call(G, k, "graphblas") == expected + with graphblas_first(): + assert call(G, k) == expected + with pytest.raises(expected[1], match=expected[2]): + nxapi.number_of_walks(ga.Graph.from_networkx(G), k) + + +def test_attribute_named_none_not_read(): + """An edge counts once, even with an attribute named None. + + NetworkX builds its matrix with ``G.edges(data=None, default=1)``, which reads such an + attribute as the edge's value. This backend's `adjacency_matrix` does not read it either, + and NetworkX's `number_of_walks` calls it, so with this backend first NetworkX's answer + counts the edge once too. + """ + G = nx.Graph([(0, 1), (1, 2)]) + G[0][1][None] = 5 + assert nx.number_of_walks(G, 2, backend="networkx")[0][0] == 25 + expected = nx.number_of_walks(nx.Graph([(0, 1), (1, 2)]), 2, backend="networkx") + assert_counts(nx.number_of_walks(G, 2, backend="graphblas"), expected) + G.__networkx_cache__.clear() + with graphblas_first(): + assert_counts(nx.number_of_walks(G, 2), expected) + assert_counts(nx.number_of_walks(G, 2, backend="networkx"), expected) + + +def test_multigraphs_left_to_networkx(): + """Parallel edges are walks of their own in NetworkX; multigraphs are not served here.""" + from graphblas_algorithms.interface import Dispatcher + + G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 0)]) + assert "multigraphs" in Dispatcher.can_run("number_of_walks", (G, 2), {}) + with graphblas_first(): + assert nx.number_of_walks(G, 2) == {0: {0: 2, 1: 0}, 1: {0: 0, 1: 2}} + + +def test_backend_graphs(): + """A backend graph's values are not read, whatever the matrix holds.""" + G = nx.gnm_random_graph(30, 70, seed=4, directed=True) + for u, v, data in G.edges(data=True): + data["weight"] = (u * 7 + v) % 5 - 2.5 + expected = nx.number_of_walks(G, 6, backend="networkx") + for H in [ga.DiGraph.from_networkx(G), ga.DiGraph.from_networkx(G, weight="weight")]: + assert_counts(nxapi.number_of_walks(H, 6), expected) + assert_counts(nx.number_of_walks(H, 6), expected) + for k in [1, 2, 5]: + assert_counts(nxapi.number_of_walks(H, k), nx.number_of_walks(G, k, backend="networkx")) + assert_counts(nxapi.number_of_walks(G, 6), expected) + # The wrapper reads the structure only; the kernel does not read the values either. + H = ga.DiGraph.from_networkx(G, weight="weight") + assert H._A.dtype == float + for k in [1, 2, 6]: + for method in ["edges", "squares"]: + counts = algorithms.number_of_walks(H, k, method=method) + expected = nx.number_of_walks(G, k, backend="networkx") + assert counts.tolist() == [list(row.values()) for row in expected.values()] + + +def test_largest_count_bound(): + """The floats' relative error after k products of at most n terms is about k * n * 2**-53.""" + from graphblas_algorithms.algorithms.walks import _largest_count_bound + + bound = _largest_count_bound(2.0**62, 1000, 50) + assert bound / 2**62 - 1 == pytest.approx(50 * 1000 * 2.0**-53, rel=1e-6) + # Within that error of 2**64, a count could reach it. + assert not _largest_count_bound(2.0**64 * (1 - 1e-12), 1000, 10) < 2**64 + assert _largest_count_bound(2.0**64 * (1 - 1e-11), 1000, 10) < 2**64 + # An error past 1/3 bounds nothing; below, a count below 2**63 stays below 2**64. + assert _largest_count_bound(2.0**62, 2**40, 2**11) < 2**63 + assert _largest_count_bound(1.0, 2**40, 2**12) == math.inf + assert _largest_count_bound(1.0, 2, 2**60) == math.inf + assert _largest_count_bound(1.0, 2, 10**400) == math.inf diff --git a/graphblas_algorithms/nxapi/walks.py b/graphblas_algorithms/nxapi/walks.py new file mode 100644 index 0000000..19e3b40 --- /dev/null +++ b/graphblas_algorithms/nxapi/walks.py @@ -0,0 +1,30 @@ +import numpy as np + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.digraph import to_graph + +from ._utils import can_run +from .exception import NetworkXError + +__all__ = ["number_of_walks"] + + +def _int_walk_length(bound): + if not isinstance(bound.get("walk_length"), int | np.integer): + # NetworkX compares it with 0, then SciPy's matrix power raises its own errors. + return "a `walk_length` that is not an int is left to networkx; networkx serves it" + return None + + +@can_run(_int_walk_length) +def number_of_walks(G, walk_length): + if walk_length < 0: + raise ValueError(f"`walk_length` cannot be negative: {walk_length}") + G = to_graph(G) + if len(G) == 0: + raise NetworkXError("Graph has no nodes or edges") + if (reason := _int_walk_length({"walk_length": walk_length})) is not None: + raise NotImplementedError(reason) + counts = algorithms.number_of_walks(G, int(walk_length)).tolist() + nodes = G.list_to_keys(range(len(G))) + return {u: dict(zip(nodes, row, strict=True)) for u, row in zip(nodes, counts, strict=True)} diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..e23217c 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -178,6 +178,7 @@ def call_args(kind, args): "normalized_laplacian_matrix": ("undirected", ()), "number_connected_components": ("undirected", ()), "number_of_isolates": ("undirected", ()), + "number_of_walks": ("directed", (3,)), "number_weakly_connected_components": ("directed", ()), "onion_layers": ("undirected", ()), "out_degree_centrality": ("directed", ()),