diff --git a/graphblas_algorithms/algorithms/traversal/breadth_first_search.py b/graphblas_algorithms/algorithms/traversal/breadth_first_search.py index 7682ab6..4b2c9fc 100644 --- a/graphblas_algorithms/algorithms/traversal/breadth_first_search.py +++ b/graphblas_algorithms/algorithms/traversal/breadth_first_search.py @@ -1,3 +1,4 @@ +import numbers from math import ceil import numpy as np @@ -221,18 +222,34 @@ def bfs_layers(G, sources): def descendants_at_distance(G, source, distance): + """The nodes on the level `i` of a walk from `source` for which `i == distance`. + + NetworkX's test, level by level, so a float or a fraction equal to a level gives it, and a + distance no level equals gives no node: one below 0, between two levels, infinite, NaN, or + not a number. A real number stops the walk once the levels pass it. + """ index = G._key_to_id[source] A = G.get_property("offdiag") n = A.nrows - q = Vector(bool, size=n, name=f"descendants_at_distance_{distance}") + q = Vector(bool, size=n, name="descendants_at_distance") q[index] = True - if distance == 0: + ordered = isinstance(distance, numbers.Real) + if ordered and not distance >= 0: + # Below 0, -inf or NaN: no level equals it. + q.clear() return q v = _visited(Vector(bool, size=n, name="bfs_seen")) any_pair_bool = any_pair[bool] - for _i in range(1, distance + 1): + level = 0 + while True: + if level == distance: # NetworkX's test, which a NumPy array answers by its truth + return q + if ordered and level > distance: + break # between two levels v(q.S) << True q(~v.S, replace) << any_pair_bool(q @ A) if q.nvals == 0: - break + return q # past the last level + level += 1 + q.clear() return q diff --git a/graphblas_algorithms/nxapi/tests/test_descendants_at_distance.py b/graphblas_algorithms/nxapi/tests/test_descendants_at_distance.py new file mode 100644 index 0000000..2d3d38d --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_descendants_at_distance.py @@ -0,0 +1,140 @@ +"""descendants_at_distance against NetworkX. + +NetworkX's walk returns the level `i` for which `i == distance`, and no node where no level is +equal to it. +""" + +import functools +import math +from decimal import Decimal +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms.algorithms.traversal import breadth_first_search as kernel +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +# Each kind NetworkX's `i == distance` reads: ints, floats equal to a level or between two, below +# 0, infinite and NaN; NumPy scalars and arrays; other numbers; and what is not a number. +DISTANCES = [ + 0, 1, 2, 3, 6, -1, -2, True, False, 0.0, -0.0, 1.0, 2.0, 0.5, 1.5, -0.5, 1e-300, + math.inf, -math.inf, math.nan, np.int64(2), np.uint8(1), np.float64(2.0), np.float32(1.5), + np.float64("nan"), Fraction(4, 2), Fraction(1, 2), Decimal(2), Decimal("2.5"), + complex(2, 0), complex(2, 1), "1", None, (), 10**30, 1e300, np.array(2), np.array(2.5), + np.array([1]), +] # fmt: skip + + +def _random_graph(seed, directed): + rng = np.random.default_rng(seed) + n = int(rng.integers(1, 40)) + G = nx.DiGraph() if directed else nx.Graph() + nodes = rng.permutation(n).tolist() # node order is not label order + G.add_nodes_from(nodes) + m = int(rng.integers(0, 2 * n + 1)) + edges = rng.integers(0, n, size=(m, 2)).tolist() # self-loops too + G.add_edges_from(map(tuple, edges)) + return G + + +GRAPHS = [(seed, directed) for seed in range(30) for directed in (False, True)] + + +@pytest.fixture +def served(monkeypatch): + """How many calls this backend has served since the test began.""" + count = [0] + func = Dispatcher.descendants_at_distance + + @functools.wraps(func) + def counting(*args, **kwargs): + count[0] += 1 + return func(*args, **kwargs) + + monkeypatch.setattr(Dispatcher, "descendants_at_distance", staticmethod(counting)) + return count + + +def outcome(call): + try: + return "ok", call() + except Exception as exc: + return type(exc), str(exc) + + +def three_ways(G, source, distance, served): + """The answers for this backend's graph, by name, and with it first in the priority.""" + before = served[0] + B = (ga.DiGraph if G.is_directed() else ga.Graph).from_networkx(G) + ways = { + "native": outcome(lambda: nx.descendants_at_distance(B, source, distance)), + "explicit": outcome( + lambda: nx.descendants_at_distance(G, source, distance, backend="graphblas") + ), + } + with nx.config.backend_priority(algos=["graphblas"]): + ways["auto"] = outcome(lambda: nx.descendants_at_distance(G, source, distance)) + assert served[0] == before + 3 # each way reached this backend + return ways + + +@pytest.mark.parametrize(("seed", "directed"), GRAPHS) +def test_every_level_and_past_the_last(seed, directed, served): + G = _random_graph(seed, directed) + for source in list(G)[:3]: + for distance in range(len(G) + 2): + want = nx.descendants_at_distance(G, source, distance, backend="networkx") + for way, got in three_ways(G, source, distance, served).items(): + assert got == ("ok", want), (way, source, distance) + + +@pytest.mark.parametrize("distance", DISTANCES, ids=repr) +@pytest.mark.parametrize("directed", [False, True]) +def test_a_distance_of_each_kind_as_networkx_reads_it(directed, distance, served): + G = nx.balanced_tree(2, 3, create_using=nx.DiGraph if directed else nx.Graph) + G.add_edge(14, 0) # back to the source + want = outcome(lambda: nx.descendants_at_distance(G, 0, distance, backend="networkx")) + for way, got in three_ways(G, 0, distance, served).items(): + assert got == want, way + + +@pytest.mark.parametrize("distance", [-1, 1.5, math.inf, math.nan, "1", np.array([1, 2])], ids=repr) +@pytest.mark.parametrize("source", [[0], {}, 99, None], ids=repr) +def test_a_source_not_in_the_graph_raises_networkx_s_error_first(source, distance, served): + """NetworkX asks `source not in G` before the distance: False for an unhashable source.""" + G = nx.path_graph(4) + want = outcome(lambda: nx.descendants_at_distance(G, source, distance, backend="networkx")) + assert want[0] is nx.NetworkXError + for way, got in three_ways(G, source, distance, served).items(): + assert got == want, way + + +@pytest.mark.parametrize( + ("distance", "steps"), + [(-1, 0), (-math.inf, 0), (math.nan, 0), (0, 0), (0.5, 1), (1.5, 2), (3, 3), (3.0, 3), + (Fraction(7, 2), 4), (math.inf, 1000), ("1", 1000), (5000, 1000)], + ids=repr, +) # fmt: skip +def test_the_walk_stops_once_its_levels_pass_a_real_distance(distance, steps, monkeypatch): + """One step a level, and a step more finds the end. + + NetworkX's walk goes to the end, which only a distance past every level, or one that is not + a real number, needs here. + """ + taken = [0] + step = kernel.any_pair[bool] + + def counting(expr): + taken[0] += 1 + return step(expr) + + monkeypatch.setattr(kernel, "any_pair", {bool: counting}) + G = ga.Graph.from_networkx(nx.path_graph(1000)) + want = nx.descendants_at_distance(nx.path_graph(1000), 0, distance, backend="networkx") + assert nx.descendants_at_distance(G, 0, distance) == want + assert taken[0] == steps diff --git a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py index 4b69291..1a63226 100644 --- a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py +++ b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py @@ -238,8 +238,8 @@ def bfs_layers(G, sources): def descendants_at_distance(G, source, distance): G = to_graph(G) - try: - v = algorithms.descendants_at_distance(G, source, distance) - except KeyError as e: - raise NetworkXError(f"The node {e.args[0]} is not in the graph.") from e + if not _has(G._key_to_id, source): + # NetworkX's `source not in G`, which is False for an unhashable source too + raise NetworkXError(f"The node {source} is not in the graph.") + v = algorithms.descendants_at_distance(G, source, distance) return G.vector_to_nodeset(v)