diff --git a/graphblas_algorithms/algorithms/_bfs.py b/graphblas_algorithms/algorithms/_bfs.py index b8c2a3a..d991ab0 100644 --- a/graphblas_algorithms/algorithms/_bfs.py +++ b/graphblas_algorithms/algorithms/_bfs.py @@ -1,14 +1,25 @@ """BFS routines used by other algorithms""" +import math + import numpy as np from graphblas import Matrix, Vector, binary, indexunary, replace, semiring, unary from graphblas.semiring import any_pair def _get_cutoff(n, cutoff): + """One more than the steps a walk takes from its first level, for `range(1, ...)`. + + NetworkX steps on while `cutoff > level`: a float such as 2.5 takes ceil(cutoff) steps, and + NaN, 0 or a negative cutoff takes none. A walk never needs more than `n - 1`. + """ + if isinstance(cutoff, np.generic): + cutoff = cutoff.item() # a Python number: numpy warns on casting `n` to a narrow float if cutoff is None or cutoff >= n: return n # Everything - return cutoff + 1 # Inclusive + if not cutoff > 0: + return 1 # The first level alone + return math.ceil(cutoff) + 1 def _adjacency(G, transpose=False): diff --git a/graphblas_algorithms/algorithms/traversal/breadth_first_search.py b/graphblas_algorithms/algorithms/traversal/breadth_first_search.py index b1cc9eb..da906b2 100644 --- a/graphblas_algorithms/algorithms/traversal/breadth_first_search.py +++ b/graphblas_algorithms/algorithms/traversal/breadth_first_search.py @@ -1,4 +1,4 @@ -from math import ceil +import itertools import numpy as np from graphblas import Vector, replace @@ -21,8 +21,7 @@ def bfs_edges(G, source, *, reverse=False, depth_limit=None): edges are sorted by parent and then by child, in node order. """ id_to_key = G.id_to_key - if depth_limit is not None and depth_limit < len(G): - depth_limit = ceil(depth_limit) # NetworkX walks on while `depth < depth_limit` + # NetworkX walks on while `depth < depth_limit`, the rule `_get_cutoff` reads. for child_ids, parent_ids in _bfs_parent_levels( G, source, cutoff=depth_limit, transpose=reverse ): @@ -73,13 +72,14 @@ def descendants_at_distance(G, source, distance): n = A.nrows q = Vector(bool, size=n, name=f"descendants_at_distance_{distance}") q[index] = True + # NetworkX gives the layer `i` for which `i == distance`, so none for 2.5, NaN, inf or -1: + # those walk until the layers run out, as NetworkX's do. if distance == 0: return q v = _visited(Vector(bool, size=n, name="bfs_seen")) any_pair_bool = any_pair[bool] - for _i in range(1, distance + 1): + for i in itertools.count(1): v(q.S) << True q(~v.S, replace) << any_pair_bool(q @ A) - if q.nvals == 0: - break - return q + if q.nvals == 0 or i == distance: + return q diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index fd84fbd..c880654 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -135,6 +135,30 @@ def split_evenly(k, L): yield L[stop:] +# A bound on a walk's levels read here as NetworkX reads it: an int (a bool too), a float no +# wider than a double, or a numpy integer. Others, such as a str, Decimal, Fraction or long +# double, compare by rules of their own, so NetworkX reads them. +_LEVEL_BOUND_TYPES = (int, float, np.integer, np.float16, np.float32) + + +def level_bound(param): + """A `can_run` hook that leaves to NetworkX a `param` of a type it reads by other rules.""" + + def hook(bound): + value = bound.get(param) + if value is None or isinstance(value, _LEVEL_BOUND_TYPES): + return None + return f"a {param} of type {type(value).__name__} is left to networkx" + + return hook + + +def check_level_bound(param, value): + """Raise what `level_bound(param)` declines; a direct call does not pass through `can_run`.""" + if (reason := level_bound(param)({param: value})) is not None: + raise NotImplementedError(reason) + + def can_run(hook): """Give the decorated wrapper `hook` as its rule in `Dispatcher.can_run`. diff --git a/graphblas_algorithms/nxapi/generators/ego.py b/graphblas_algorithms/nxapi/generators/ego.py index c1c904e..1f4de99 100644 --- a/graphblas_algorithms/nxapi/generators/ego.py +++ b/graphblas_algorithms/nxapi/generators/ego.py @@ -1,16 +1,42 @@ +import math +import sys + +import numpy as np + from graphblas_algorithms import generators from graphblas_algorithms.classes._utils import PRESERVE from graphblas_algorithms.classes.digraph import to_graph -from .._utils import check_dijkstra_weights +from .._utils import can_run, check_dijkstra_weights, check_level_bound, level_bound from ..exception import NodeNotFound __all__ = ["ego_graph"] +def _radius(radius, distance, is_weighted): + """`radius` as the walks here read it: a length, a count of edges, or None for no bound. + + Without `distance` NetworkX walks while `radius > level`, which the breadth-first walk + reads too. With it, Dijkstra drops a length `> radius`, which keeps every length when + `radius` is NaN; where the edges lack `distance`, each is 1 long, so floor(radius) edges. + """ + if distance is None or radius is None: + return radius + if isinstance(radius, np.generic): + radius = radius.item() # a Python number: numpy warns on casting to a narrow float + # NaN, inf, or an int past every float, which a float conversion would refuse + if (isinstance(radius, float) and math.isnan(radius)) or radius > sys.float_info.max: + return None + if radius < 0: + return -1 # the center alone + return radius if is_weighted else math.floor(radius) + + +@can_run(level_bound("radius")) def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None): # A subgraph keeps the input's edge data whatever `distance` names. NetworkX reads a # `distance` the edges do not carry as 1, so the radius is then a hop count. + check_level_bound("radius", radius) G = to_graph(G, weight=PRESERVE) if n not in G: # NetworkX's shortest-path helpers raise these, by whether `distance` is given. @@ -22,5 +48,10 @@ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None): # NetworkX walks `distance` with Dijkstra. check_dijkstra_weights(G, "ego_graph") return generators.ego_graph( - G, n, radius=radius, center=center, undirected=undirected, is_weighted=is_weighted + G, + n, + radius=_radius(radius, distance, is_weighted), + center=center, + undirected=undirected, + is_weighted=is_weighted, ) diff --git a/graphblas_algorithms/nxapi/shortest_paths/unweighted.py b/graphblas_algorithms/nxapi/shortest_paths/unweighted.py index c88baa5..417b3ad 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/unweighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/unweighted.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import normalize_chunksize, partition +from .._utils import can_run, check_level_bound, level_bound, normalize_chunksize, partition from ..exception import NodeNotFound __all__ = [ @@ -11,7 +11,9 @@ ] +@can_run(level_bound("cutoff")) def single_source_shortest_path_length(G, source, cutoff=None): + check_level_bound("cutoff", cutoff) G = to_graph(G) if source not in G: raise NodeNotFound(f"Source {source} is not in G") @@ -19,7 +21,9 @@ def single_source_shortest_path_length(G, source, cutoff=None): return G.vector_to_nodemap(v) +@can_run(level_bound("cutoff")) def single_target_shortest_path_length(G, target, cutoff=None): + check_level_bound("cutoff", cutoff) G = to_graph(G) if target not in G: raise NodeNotFound(f"Target {target} is not in G") @@ -27,7 +31,9 @@ def single_target_shortest_path_length(G, target, cutoff=None): return G.vector_to_nodemap(v) +@can_run(level_bound("cutoff")) def all_pairs_shortest_path_length(G, cutoff=None, *, chunksize="10 MiB"): + check_level_bound("cutoff", cutoff) G = to_graph(G) chunksize = normalize_chunksize(chunksize, len(G) * G._A.dtype.np_type.itemsize, len(G)) if chunksize is None: diff --git a/graphblas_algorithms/nxapi/tests/test_ego.py b/graphblas_algorithms/nxapi/tests/test_ego.py index f7897af..b1a519c 100644 --- a/graphblas_algorithms/nxapi/tests/test_ego.py +++ b/graphblas_algorithms/nxapi/tests/test_ego.py @@ -4,7 +4,10 @@ without it, so naming one the graph does not carry makes the radius a hop count. """ +import math + import networkx as nx +import numpy as np import pytest from graphblas_algorithms import DiGraph, Graph, nxapi @@ -92,3 +95,75 @@ def test_a_negative_cycle_is_left_to_networkx(cls, edges, radius): nx.ego_graph(G, 0, radius=radius, distance="weight") with pytest.raises(NotImplementedError): nx.ego_graph(G, 0, radius=radius, distance="weight", backend="graphblas") + + +def branched(directed, costs): + """A graph whose edges carry "cost" as `costs` says, with graph data and an isolated node. + + A rebuilt graph cannot keep node data, so the backend declines a graph that has any. + """ + G = nx.DiGraph() if directed else nx.Graph() + G.graph["name"] = "branched" + pairs = [(0, 1), (1, 2), (2, 3), (3, 4), (1, 5), (5, 0)] + values = {"varied": [1.0, 0.5, 2.0, 1.0, 1.5, 1.0], "equal": [1.0] * 6}.get(costs) + for i, (u, v) in enumerate(pairs): + G.add_edge(u, v, **({} if values is None else {"cost": values[i]})) + G.add_node(6) # reached by nothing + return G + + +def everything(H): + """A result's class, graph data, nodes and edges with their data; or its exception.""" + if isinstance(H, Exception): + return type(H).__name__, str(H) + H = Dispatcher.convert_to_nx(H) + return ( + H.is_directed(), + dict(H.graph), + sorted(H.nodes(data=True)), + sorted((u, v, sorted(d.items())) for u, v, d in H.edges(data=True)), + ) + + +def ego(G, **kwargs): + try: + return nx.ego_graph(G, 0, **kwargs) + except Exception as exc: + return exc + + +@pytest.mark.parametrize( + "radius", + [2.5, 2.0, 1.5, 0.5, 0.0, -0.5, -1.0, 2, math.inf, -math.inf, math.nan, np.float32(math.nan)], + ids=repr, +) +@DISTANCES +@pytest.mark.parametrize("directed", [False, True], ids=["undirected", "directed"]) +@pytest.mark.parametrize("costs", ["varied", "equal", "none"]) +@pytest.mark.parametrize("center", [True, False]) +@pytest.mark.parametrize("undirected", [False, True], ids=["", "undirected=True"]) +def test_a_float_radius_as_networkx(radius, distance, directed, costs, center, undirected): + """Each answer is NetworkX's: its nodes, edges, their data and the graph data. + + Without `distance` NetworkX steps while `radius > level`, so 2.5 reaches 3 edges out and + NaN none. With it, Dijkstra drops a length `> radius`, so 2.5 reaches 2 edges out where + each is 1 long, and NaN reaches every node. + """ + kwargs = {"radius": radius, "center": center, "undirected": undirected} + if distance is not None: + kwargs["distance"] = distance + expected = everything(ego(branched(directed, costs), **kwargs)) + assert everything(ego(branched(directed, costs), backend="graphblas", **kwargs)) == expected + + +@DISTANCES +@pytest.mark.parametrize("costs", ["varied", "none"]) +@pytest.mark.parametrize(("radius", "reached"), [(10**400, 6), (-(10**400), 1)], ids=["+", "-"]) +def test_an_int_radius_past_every_float(distance, costs, radius, reached): + """No float holds it, so a conversion to one would raise OverflowError.""" + kwargs = {"radius": radius} + if distance is not None: + kwargs["distance"] = distance + expected = everything(ego(branched(False, costs), **kwargs)) + assert len(expected[2]) == reached # every node but the isolated one, or the center alone + assert everything(ego(branched(False, costs), backend="graphblas", **kwargs)) == expected diff --git a/graphblas_algorithms/nxapi/tests/test_level_bounds.py b/graphblas_algorithms/nxapi/tests/test_level_bounds.py new file mode 100644 index 0000000..11c234c --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_level_bounds.py @@ -0,0 +1,185 @@ +"""A bound on the levels of a breadth-first walk, read as NetworkX reads it. + +NetworkX steps on while `cutoff > level` (`depth_limit > depth` for the bfs names), so a +float cutoff of 2.5 reaches nodes 3 edges out, and NaN, 0 or a negative cutoff only the +source. `descendants_at_distance` gives the layer whose index equals `distance`, so none for +2.5, NaN, inf or a negative distance. Each answer here is NetworkX's, through the backend. +""" + +import math +import warnings +from decimal import Decimal +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms import nxapi + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +BOUNDS = { + "2.5": 2.5, + "2.0": 2.0, + "1.5": 1.5, + "0.5": 0.5, + "0.0": 0.0, + "-0.5": -0.5, + "-1.0": -1.0, + "-1": -1, + "2": 2, + "inf": math.inf, + "-inf": -math.inf, + "nan": math.nan, + "10**400": 10**400, + "-10**400": -(10**400), + "float32 1.5": np.float32(1.5), + "float32 nan": np.float32(math.nan), +} + + +def branched(directed): + """Nodes added first, so a breadth-first tree is NetworkX's; node 7 is isolated.""" + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(8)) + G.add_edges_from([(0, 1), (0, 5), (1, 2), (1, 5), (2, 3), (3, 4), (4, 6)]) + return G + + +CALLS = { + "single_source_shortest_path_length": lambda G, b, **kw: dict( + nx.single_source_shortest_path_length(G, 0, cutoff=b, **kw) + ), + "single_target_shortest_path_length": lambda G, b, **kw: dict( + nx.single_target_shortest_path_length(G, 4, cutoff=b, **kw) + ), + "all_pairs_shortest_path_length": lambda G, b, **kw: { + source: dict(row) for source, row in nx.all_pairs_shortest_path_length(G, cutoff=b, **kw) + }, + "bfs_edges": lambda G, b, **kw: list(nx.bfs_edges(G, 0, depth_limit=b, **kw)), + "bfs_edges reverse": lambda G, b, **kw: list( + nx.bfs_edges(G, 6, reverse=True, depth_limit=b, **kw) + ), + "bfs_successors": lambda G, b, **kw: list(nx.bfs_successors(G, 0, depth_limit=b, **kw)), + "descendants_at_distance": lambda G, b, **kw: set(nx.descendants_at_distance(G, 0, b, **kw)), +} + + +@pytest.mark.parametrize("bound", BOUNDS.values(), ids=BOUNDS.keys()) +@pytest.mark.parametrize("name", sorted(CALLS)) +@pytest.mark.parametrize("directed", [False, True], ids=["undirected", "directed"]) +def test_a_bound_as_networkx_reads_it(name, bound, directed): + expected = CALLS[name](branched(directed), bound) + assert CALLS[name](branched(directed), bound, backend="graphblas") == expected + + +@pytest.mark.parametrize("bound", BOUNDS.values(), ids=BOUNDS.keys()) +@pytest.mark.parametrize("chunksize", [1, 3, None]) +def test_all_pairs_in_any_batch_width(bound, chunksize): + G = branched(False) + expected = CALLS["all_pairs_shortest_path_length"](G, bound) + got = { + s: dict(row) + for s, row in nxapi.all_pairs_shortest_path_length(G, bound, chunksize=chunksize) + } + assert got == expected + + +@pytest.mark.parametrize( + ("cutoff", "reached"), [(2.5, [0, 1, 2, 3, 5]), (2.0, [0, 1, 2, 5]), (math.nan, [0])] +) +def test_a_float_cutoff_written_out(cutoff, reached): + got = nx.single_source_shortest_path_length( + branched(False), 0, cutoff=cutoff, backend="graphblas" + ) + assert sorted(got) == reached + + +@pytest.mark.parametrize(("distance", "layer"), [(2, {2}), (2.0, {2}), (2.5, set()), (-1, set())]) +def test_descendants_at_a_distance_that_is_no_layer(distance, layer): + G = nx.path_graph(5) + assert nx.descendants_at_distance(G, 0, distance, backend="graphblas") == layer + + +def outcome(func, *args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as exc: + return type(exc), str(exc) + + +# Types NetworkX compares by rules of their own: left to it, which answers or raises as it does. +OTHER_TYPES = { + "str": "2", + "Decimal 1.5": Decimal("1.5"), + "Decimal NaN": Decimal("NaN"), + "Fraction 3/2": Fraction(3, 2), + "numpy bool": np.True_, +} +EGO = { + f"ego_graph distance={distance}": lambda G, b, distance=distance, **kw: sorted( + nx.ego_graph(G, 0, radius=b, **({} if distance is None else {"distance": distance}), **kw) + ) + for distance in [None, "weight", "missing"] +} + + +def weighted(directed): + G = branched(directed) + for u, v in G.edges: + G[u][v]["weight"] = 0.5 + (u + v) % 3 + return G + + +@pytest.mark.parametrize("bound", OTHER_TYPES.values(), ids=OTHER_TYPES.keys()) +@pytest.mark.parametrize("name", sorted(CALLS | EGO)) +def test_a_bound_of_another_type_is_left_to_networkx(name, bound): + call = (CALLS | EGO)[name] + expected = outcome(call, weighted(True), bound) + if name != "descendants_at_distance": # its `i == distance` is NetworkX's for any type + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + call(weighted(True), bound, backend="graphblas") + with nx.config.backend_priority(algos=["graphblas"]): + assert outcome(call, weighted(True), bound) == expected + + +@pytest.mark.parametrize( + ("func", "args", "kwargs"), + [ + (nxapi.single_source_shortest_path_length, (0,), {"cutoff": "2"}), + (nxapi.single_target_shortest_path_length, (0,), {"cutoff": Fraction(3, 2)}), + (lambda *a, **k: list(nxapi.all_pairs_shortest_path_length(*a, **k)), (), {"cutoff": "2"}), + (lambda *a, **k: list(nxapi.bfs_edges(*a, **k)), (0,), {"depth_limit": Decimal(2)}), + (lambda *a, **k: list(nxapi.bfs_successors(*a, **k)), (0,), {"depth_limit": "2"}), + (nxapi.ego_graph, (0,), {"radius": Decimal("NaN"), "distance": "weight"}), + ], +) +def test_a_direct_call_refuses_another_type(func, args, kwargs): + with pytest.raises(NotImplementedError, match="is left to networkx"): + func(weighted(True), *args, **kwargs) + + +@pytest.mark.parametrize("bound", [np.float16(2.5), np.float32(2.5), np.float16(math.nan)]) +@pytest.mark.parametrize("name", sorted(CALLS | EGO)) +def test_a_narrow_numpy_float_casts_nothing(name, bound): + """No comparison casts a large node count or the largest float to its type. + + numpy warns of such a cast, and NetworkX's comparisons with small levels make none. + """ + call = (CALLS | EGO)[name] + expected = call(weighted(True), bound) + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert call(weighted(True), bound, backend="graphblas") == expected + + +def test_a_narrow_numpy_float_beside_many_nodes_casts_nothing(): + G = nx.path_graph(70_000) # more nodes than float16 holds + expected = nx.single_source_shortest_path_length(G, 0, cutoff=np.float16(2.5)) + with warnings.catch_warnings(): + warnings.simplefilter("error") + got = nx.single_source_shortest_path_length( + G, 0, cutoff=np.float16(2.5), backend="graphblas" + ) + assert got == expected == {0: 0, 1: 1, 2: 2, 3: 3} diff --git a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py index 1c4afc2..dcb236e 100644 --- a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py +++ b/graphblas_algorithms/nxapi/traversal/breadth_first_search.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 can_run, level_bound from ..exception import NetworkXError __all__ = [ @@ -21,6 +21,10 @@ def _without_sort_neighbors(bound): return None +def _without_sort_neighbors_or_odd_depth(bound): + return _without_sort_neighbors(bound) or level_bound("depth_limit")(bound) + + def _check_source(G, source): # The mapping, not `G`, so that an unhashable source raises TypeError, as in NetworkX. if source not in G._key_to_id: @@ -29,20 +33,22 @@ def _check_source(G, source): raise NetworkXError(f"The node {source} is not in the {kind}.") -@can_run(_without_sort_neighbors) +@can_run(_without_sort_neighbors_or_odd_depth) def bfs_edges(G, source, reverse=False, depth_limit=None, sort_neighbors=None): """A breadth-first tree that may differ from NetworkX's (see the backend's notes).""" - if (reason := _without_sort_neighbors({"sort_neighbors": sort_neighbors})) is not None: + bound = {"sort_neighbors": sort_neighbors, "depth_limit": depth_limit} + if (reason := _without_sort_neighbors_or_odd_depth(bound)) is not None: raise NotImplementedError(reason) G = to_graph(G) _check_source(G, source) yield from algorithms.bfs_edges(G, source, reverse=reverse, depth_limit=depth_limit) -@can_run(_without_sort_neighbors) +@can_run(_without_sort_neighbors_or_odd_depth) def bfs_successors(G, source, depth_limit=None, sort_neighbors=None): """The children in `bfs_edges`'s tree, which may differ from NetworkX's.""" - if (reason := _without_sort_neighbors({"sort_neighbors": sort_neighbors})) is not None: + bound = {"sort_neighbors": sort_neighbors, "depth_limit": depth_limit} + if (reason := _without_sort_neighbors_or_odd_depth(bound)) is not None: raise NotImplementedError(reason) G = to_graph(G) _check_source(G, source)