diff --git a/README.md b/README.md index 3694763..780660c 100644 --- a/README.md +++ b/README.md @@ -282,8 +282,11 @@ graphblas_algorithms.nxapi │ ├── all_pairs_dijkstra_path_length │ ├── bellman_ford_path │ ├── bellman_ford_path_length +│ ├── dijkstra_path_length +│ ├── multi_source_dijkstra_path_length │ ├── negative_edge_cycle -│ └── single_source_bellman_ford_path_length +│ ├── single_source_bellman_ford_path_length +│ └── single_source_dijkstra_path_length ├── simple_paths │ └── is_simple_path ├── smetric diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index bd2b130..3828083 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -61,6 +61,7 @@ def get_info(): "descendants_at_distance", "diameter", "difference", + "dijkstra_path_length", "directed_modularity_matrix", "disjoint_union", "eccentricity", @@ -123,6 +124,7 @@ def get_info(): "mixing_expansion", "modularity", "modularity_matrix", + "multi_source_dijkstra_path_length", "mutual_weight", "negative_edge_cycle", "node_boundary", @@ -149,6 +151,7 @@ def get_info(): "schultz_index", "score_sequence", "single_source_bellman_ford_path_length", + "single_source_dijkstra_path_length", "single_source_shortest_path_length", "single_target_shortest_path_length", "square_clustering", diff --git a/graphblas_algorithms/algorithms/shortest_paths/weighted.py b/graphblas_algorithms/algorithms/shortest_paths/weighted.py index fdbda9c..b0a404f 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/weighted.py +++ b/graphblas_algorithms/algorithms/shortest_paths/weighted.py @@ -14,7 +14,9 @@ "bellman_ford_path", "bellman_ford_path_length", "bellman_ford_path_lengths", + "dijkstra_path_length", "dijkstra_path_lengths", + "multi_source_dijkstra_path_length", "negative_edge_cycle", "single_source_bellman_ford_path_length", ] @@ -458,3 +460,53 @@ def dijkstra_path_lengths(G, nodes=None, *, cutoff=None): lengths = vals[lo:hi] lengths[0] = 0 # NetworkX's integer 0 for the source yield src, cols[lo:hi], lengths + + +def _dijkstra_vector(G, ids, *, cutoff=None, dst_id=None): + """The least length from any node in `ids` to each node it reaches within `cutoff`. + + A walk is relaxed one edge a round from the nodes whose length improved in the last one, + as in `bellman_ford_path_lengths`, but from all of `ids` at once. With `dst_id`, a walk + longer than the length found to it is dropped, so only its length is then the least. + """ + A = G.get_property("offdiag") + dtype = _length_dtype(G, A) + cutoff = _dijkstra_cutoff(cutoff, lookup_dtype(dtype).np_type) + n = A.nrows + d = Vector.from_coo(np.unique(ids), 0, dtype, size=n, name="dijkstra_path_length") + cur = d.dup(name="cur") + mask = Vector(bool, n, name="mask") + one = unary.one[bool] + for _i in range(n - 1): + cur << min_plus[dtype](cur @ A) + if cutoff is not None: + cur << select.valuele(cur, cutoff) + mask << one(cur) + mask(binary.second) << binary.lt(cur & d) + cur(mask.V, replace) << cur + if cur.nvals == 0: + break + d(cur.S) << cur + if dst_id is not None: + # Weights are not negative, so no walk past this length makes a shorter one. + cutoff = cur.get(dst_id, cutoff) + return d + + +def multi_source_dijkstra_path_length(G, sources, *, cutoff=None): + """A Vector of the least length from any of `sources` to each node within `cutoff`. + + Each source is at 0, whatever `cutoff` is. Where no weight is negative or NaN these are the + lengths NetworkX's Dijkstra gives; elsewhere its lengths follow the order of its walk. + """ + return _dijkstra_vector(G, G.list_to_ids(sources), cutoff=cutoff) + + +def dijkstra_path_length(G, source, target): + """The least length from `source` to `target`, as `multi_source_dijkstra_path_length`.""" + src_id = G._key_to_id[source] + dst_id = G._key_to_id[target] + d = _dijkstra_vector(G, [src_id], dst_id=dst_id).get(dst_id) + if d is None: + raise NoPath(f"node {target} not reachable from {source}") + return d diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 81b7ee9..5579cca 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -408,8 +408,11 @@ class Dispatcher: all_pairs_dijkstra_path_length = mod.weighted.all_pairs_dijkstra_path_length bellman_ford_path = mod.weighted.bellman_ford_path bellman_ford_path_length = mod.weighted.bellman_ford_path_length + dijkstra_path_length = mod.weighted.dijkstra_path_length + multi_source_dijkstra_path_length = mod.weighted.multi_source_dijkstra_path_length negative_edge_cycle = mod.weighted.negative_edge_cycle single_source_bellman_ford_path_length = mod.weighted.single_source_bellman_ford_path_length + single_source_dijkstra_path_length = mod.weighted.single_source_dijkstra_path_length mod = nxapi.simple_paths # ====================== @@ -592,6 +595,22 @@ def can_run(name, args, kwargs): return reason return True + @staticmethod + def should_run(name, args, kwargs): + """True if serving `name` here should be faster than NetworkX, else the reason not. + + NetworkX asks only where it would convert a graph to call this backend, after `can_run` + said yes. A wrapper's own rule is its `_should_run` attribute, set with + `nxapi._utils.should_run`. + """ + hook = getattr(getattr(Dispatcher, name, None), "_should_run", None) + if hook is None: + return True + bound = _bound_args(name, args, kwargs) + if bound is None or (reason := hook(bound)) is None: + return True + return reason + @staticmethod def on_start_tests(items): """Mark the tests in NetworkX's suite that this backend cannot pass; the table is empty. diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 72f728b..b3fe7a9 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -147,6 +147,20 @@ def decorator(func): return decorator +def should_run(hook): + """Give the decorated wrapper `hook` as its rule in `Dispatcher.should_run`. + + `hook(bound)` gets the arguments as `can_run`'s hook does, and returns the reason NetworkX + should serve the call itself, as the faster of the two, or None to serve it here. + """ + + def decorator(func): + func._should_run = hook + return func + + return decorator + + def check_nodelist(G, nodelist, *, null_graph=True): """Refuse what NetworkX's `to_scipy_sparse_array` refuses, in the order it checks. diff --git a/graphblas_algorithms/nxapi/shortest_paths/weighted.py b/graphblas_algorithms/nxapi/shortest_paths/weighted.py index dd90698..7861d48 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/weighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/weighted.py @@ -1,10 +1,11 @@ import numpy as np from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.components._labels import _keys_by_id from graphblas_algorithms.algorithms.shortest_paths.weighted import _length_dtype from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run, normalize_chunksize, partition +from .._utils import can_run, normalize_chunksize, partition, should_run from ..exception import NetworkXNoPath, NetworkXUnbounded, NodeNotFound __all__ = [ @@ -12,8 +13,11 @@ "all_pairs_dijkstra_path_length", "bellman_ford_path", "bellman_ford_path_length", + "dijkstra_path_length", + "multi_source_dijkstra_path_length", "negative_edge_cycle", "single_source_bellman_ford_path_length", + "single_source_dijkstra_path_length", ] @@ -112,44 +116,68 @@ def negative_edge_cycle(G, weight="weight", heuristic=True): return algorithms.negative_edge_cycle(G) -_NAME = "all_pairs_dijkstra_path_length" _CUTOFF_TYPES = (int, float, np.integer, np.float64) -def _dijkstra_can_run(bound): - G = bound["G"] - cutoff = bound["cutoff"] - if cutoff is not None and ( - not isinstance(cutoff, _CUTOFF_TYPES) - or (isinstance(cutoff, (int, np.integer)) and abs(int(cutoff)) >= 2**53) - ): - # NetworkX compares each length with `cutoff` as Python does, which for other types, - # or integers beyond float precision, need not be as a matrix of lengths compares. - return f"{_NAME} compares lengths with a cutoff of {type(cutoff).__name__} as networkx does" - if not hasattr(G, "_adj"): - return None # this backend's graph - import networkx as nx - - if getattr(type(G), "adjacency", None) is not nx.Graph.adjacency: - # NetworkX's Dijkstra walks `G._adj`, and a conversion reads the adjacency this class - # reports instead, as `_AntiGraph`'s complement. - return f"{_NAME} walks `G._adj`, which this graph does not report as its adjacency" - return None - - -@can_run(_dijkstra_can_run) -def all_pairs_dijkstra_path_length(G, cutoff=None, weight="weight"): - G = to_graph(G, weight=weight) +def _dijkstra_rule(name): + """The `can_run` rule of the Dijkstra length name `name`.""" + + def rule(bound): + G = bound["G"] + cutoff = bound.get("cutoff") + if cutoff is not None and ( + not isinstance(cutoff, _CUTOFF_TYPES) + or (isinstance(cutoff, (int, np.integer)) and abs(int(cutoff)) >= 2**53) + ): + # NetworkX compares each length with `cutoff` as Python does, which for other + # types, or integers beyond float precision, need not be as a matrix compares. + kind = type(cutoff).__name__ + return f"{name} compares lengths with a cutoff of {kind} as networkx does" + if "target" in bound: + try: + hash(bound["target"]) + except TypeError: + # NetworkX compares each node it reaches with the target, and then looks it up. + return f"{name} meets a target that is not hashable as networkx does" + if not hasattr(G, "_adj"): + return None # this backend's graph + import networkx as nx + + if getattr(type(G), "adjacency", None) is not nx.Graph.adjacency: + # NetworkX's Dijkstra walks `G._adj`, and a conversion reads the adjacency this + # class reports instead, as `_AntiGraph`'s complement. + return f"{name} walks `G._adj`, which this graph does not report as its adjacency" + return None + + return rule + + +def _negative_or_nan(G): A = G._A - if G.get_property("has_negative_edges+") or ( + return bool(G.get_property("has_negative_edges+")) or bool( A.dtype.np_type.kind == "f" and np.isnan(A.to_coo(rows=False, columns=False)[2]).any() - ): - # NetworkX's Dijkstra gives what its walk meets: which nodes a NaN length hides, which - # lengths a negative weight changes, and the item that raises "Contradictory paths". - raise NotImplementedError(f"{_NAME} with a negative or NaN weight is left to networkx") - # Bound integer sums now, when called, rather than at the first item: an error raised - # then reaches the caller after NetworkX's dispatcher has returned. + ) + + +def _check_walk(G, name): + """Raise where NetworkX's Dijkstra on `G` gives what its walk meets, not the least lengths. + + That is which nodes a NaN length hides, which lengths a negative weight changes, and where + it raises "Contradictory paths"; NetworkX answers these. Integer weights whose sums could + reach 2**63 raise OverflowError. The check is kept with `G`, since NetworkX's own loops, + such as its `all_pairs_dijkstra_path_length`, ask for one source at a time. + """ + if G._cacheit("negative_or_nan", _negative_or_nan, G): + raise NotImplementedError(f"{name} with a negative or NaN weight is left to networkx") _length_dtype(G, G.get_property("offdiag")) + + +@can_run(_dijkstra_rule("all_pairs_dijkstra_path_length")) +def all_pairs_dijkstra_path_length(G, cutoff=None, weight="weight"): + G = to_graph(G, weight=weight) + # Checked now, when called, rather than at the first item: an error raised then reaches + # the caller after NetworkX's dispatcher has returned. + _check_walk(G, "all_pairs_dijkstra_path_length") return _all_pairs_dijkstra_path_length(G, cutoff) @@ -162,3 +190,74 @@ def _all_pairs_dijkstra_path_length(G, cutoff): if not identity: ids = map(keys.__getitem__, ids) yield keys[src], dict(zip(ids, lengths, strict=True)) + + +def _lengths_from(G, sources, d): + """`d`, the lengths from `sources`, as a dict of NetworkX's keys and order up to ties. + + Each source comes first, as given, at the integer 0, and then the other nodes by increasing + length, equal lengths in id order. + """ + ids, lengths = d.to_coo() + is_source = np.zeros(len(G), bool) + is_source[G.list_to_ids(sources)] = True + others = ~is_source[ids] + order = np.argsort(lengths[others], kind="stable") + keys, _ = G._cacheit("keys_by_id", _keys_by_id, G) + rv = dict.fromkeys(sources, 0) + rv.update(zip(keys[ids[others][order]].tolist(), lengths[others][order].tolist(), strict=True)) + return rv + + +def _one_walk(bound): + # NetworkX's Dijkstra from one source, or from several at once, reads each edge about once, + # as converting the graph does. Measured with the conversion counted, NetworkX was the + # faster on graphs of 1e5 edges, and of 1e6 but for random float weights on a random graph. + # With the conversion cached the backend was faster on random graphs and slower on grids, + # where it takes a round per edge of the longest path. + return "networkx walks from a few sources sooner than this backend converts the graph" + + +def _multi_source(G, sources, cutoff, name): + # NetworkX's checks, in its order; a generator is spent by the second and gives {}. + if not sources: + raise ValueError("sources must not be empty") + for s in sources: + if s not in G: + raise NodeNotFound(f"Node {s} not found in graph") + _check_walk(G, name) + sources = list(sources) + d = algorithms.multi_source_dijkstra_path_length(G, sources, cutoff=cutoff) + return _lengths_from(G, sources, d) + + +@can_run(_dijkstra_rule("multi_source_dijkstra_path_length")) +@should_run(_one_walk) +def multi_source_dijkstra_path_length(G, sources, cutoff=None, weight="weight"): + G = to_graph(G, weight=weight) + return _multi_source(G, sources, cutoff, "multi_source_dijkstra_path_length") + + +@can_run(_dijkstra_rule("single_source_dijkstra_path_length")) +@should_run(_one_walk) +def single_source_dijkstra_path_length(G, source, cutoff=None, weight="weight"): + G = to_graph(G, weight=weight) + # NetworkX passes `{source}`, whose TypeError an unhashable source raises here too. + return _multi_source(G, {source}, cutoff, "single_source_dijkstra_path_length") + + +@can_run(_dijkstra_rule("dijkstra_path_length")) +@should_run(_one_walk) +def dijkstra_path_length(G, source, target, weight="weight"): + G = to_graph(G, weight=weight) + if source not in G: + raise NodeNotFound(f"Node {source} not found in graph") + if source == target: + return 0 + _check_walk(G, "dijkstra_path_length") + if target not in G: + raise NetworkXNoPath(f"Node {target} not reachable from {source}") + try: + return algorithms.dijkstra_path_length(G, source, target) + except algorithms.exceptions.NoPath as e: + raise NetworkXNoPath(f"Node {target} not reachable from {source}") from e diff --git a/graphblas_algorithms/nxapi/tests/test_dijkstra.py b/graphblas_algorithms/nxapi/tests/test_dijkstra.py index ca2ec1b..cb4b385 100644 --- a/graphblas_algorithms/nxapi/tests/test_dijkstra.py +++ b/graphblas_algorithms/nxapi/tests/test_dijkstra.py @@ -1,12 +1,13 @@ -"""all_pairs_dijkstra_path_length: NetworkX's targets and lengths for each source, or a decline. +"""The Dijkstra length names: NetworkX's targets and lengths for each source, or a decline. Lengths are compared exactly where they are integers and within rounding where they are -floats. Each dict's order is the backend's own: the source, then by increasing length. +floats. Each dict's order is the backend's own: the sources, then by increasing length. """ import math from decimal import Decimal from fractions import Fraction +from functools import partial from itertools import pairwise import networkx as nx @@ -17,6 +18,8 @@ from graphblas_algorithms.algorithms.shortest_paths import weighted from graphblas_algorithms.interface import Dispatcher +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + NAME = "all_pairs_dijkstra_path_length" @@ -280,3 +283,386 @@ def test_any_cutoff_keeps_what_networkx_keeps(weights, cutoff): } assert got.keys() == want.keys() assert all(got[s] == near(want[s]) for s in want) + + +# single_source_dijkstra_path_length, multi_source_dijkstra_path_length, dijkstra_path_length + +SS = nx.single_source_dijkstra_path_length +MS = nx.multi_source_dijkstra_path_length +PAIR = nx.dijkstra_path_length +SOURCE_NAMES = [ + "single_source_dijkstra_path_length", + "multi_source_dijkstra_path_length", + "dijkstra_path_length", +] + + +def outcome(f): + """What `f()` gives: its value, or its exception's type and args.""" + try: + return ("value", f()) + except Exception as exc: + return ("raises", type(exc), exc.args) + + +def assert_from_sources(got, want, sources, rel=1e-12): + """NetworkX's keys exactly and its lengths within `rel`, the sources first, as given, at 0.""" + assert got.keys() == want.keys() + assert got == near(want, rel) + firsts = list(dict.fromkeys(sources)) + keys = list(got) + assert keys[: len(firsts)] == firsts + assert [type(key) for key in keys[: len(firsts)]] == [type(key) for key in firsts] + assert all(type(got[key]) is int and got[key] == 0 for key in firsts) + assert all(a <= b for a, b in pairwise(list(got.values())[len(firsts) :])) + + +def pick(rng, values): + return values[int(rng.integers(len(values)))] + + +def sample(rng, values, k): + return [values[i] for i in rng.choice(len(values), min(k, len(values)), replace=False)] + + +def draw_weight(rng, kind): + if kind == "ints": + return int(rng.integers(10)) + if kind == "big ints": + return int(rng.integers(2**40)) + if kind == "floats": + return float(rng.random()) * 10 + if kind == "tenths": + return pick(rng, [0.1, 0.2, 0.3, 0.7]) + if kind == "float32": + return np.float32(pick(rng, [0.1, 0.2, 0.3, 1.5])) + if kind == "zero or one": + return pick(rng, [0, 1]) + if kind == "with inf": + return pick(rng, [0.5, 1.0, 2.5, math.inf]) + if kind == "mixed": + return pick(rng, [1, 2, 0.5, 1.25]) + return pick(rng, [None, 1, 3]) # "some missing": NetworkX reads a missing weight as 1 + + +WEIGHT_KINDS = ["ints", "big ints", "floats", "tenths", "float32", "zero or one", "with inf"] +WEIGHT_KINDS += ["mixed", "some missing"] + + +def random_graph(seed): + """A small graph, directed or not, its nodes ints or strings in a shuffled order.""" + rng = np.random.default_rng(seed) + n = int(rng.integers(1, 26)) + directed = rng.random() < 0.5 + kind = WEIGHT_KINDS[seed % len(WEIGHT_KINDS)] + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(rng.permutation(n).tolist()) + for _ in range(int(rng.integers(3 * n + 1))): + u, v = rng.integers(n, size=2).tolist() + w = draw_weight(rng, kind) + if u == v and not directed and w == math.inf: + continue # NetworkX's matrix holds NaN there: declined (see below) + if w is None: + G.add_edge(u, v) + else: + G.add_edge(u, v, weight=w) + if seed % 3 == 0: + G = nx.relabel_nodes(G, {i: f"n{i}" for i in range(n)}) + return G, kind, rng + + +def assert_pair_as_networkx(G, H, source, target, rel=1e-12): + """`dijkstra_path_length` on `G` as NetworkX's on `H`: ints exactly, floats within `rel`.""" + want = outcome(partial(PAIR, H, source, target)) + got = outcome(partial(PAIR, G, source, target, backend="graphblas")) + if want[0] == "value" and type(want[1]) is not int: + assert got[0] == "value" + assert got[1] == pytest.approx(want[1], rel) + else: + assert got == want + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs_from_sources_as_networkx(seed): + G, kind, rng = random_graph(seed) + rel = 1e-6 if kind == "float32" else 1e-12 + nodes = list(G) + cutoff = pick(rng, [None, None, 0, 1, 2.5, 7, 0.65, -1, math.nan, math.inf, np.float64(3.5)]) + for source in sample(rng, nodes, 3): + want = SS(G, source, cutoff=cutoff) + got = SS(G, source, cutoff=cutoff, backend="graphblas") + assert_from_sources(got, want, [source], rel) + if cutoff is None: + assert_shortest(G, source, got, 1e-6) + for target in sample(rng, nodes, 4): + assert_pair_as_networkx(G, G, source, target, rel) + for _ in range(2): + sources = [pick(rng, nodes) for _ in range(int(rng.integers(1, 5)))] + want = MS(G, sources, cutoff=cutoff) + got = MS(G, sources, cutoff=cutoff, backend="graphblas") + assert_from_sources(got, want, sources, rel) + + +def errors_graph(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 2), (1, 2, 3), (0, 3, 1)]) + G.add_node(9) + return G + + +ERRORS = { + "single source missing": (SS, (7,)), + "single source unhashable": (SS, ([0],)), + "a missing source among sources": (MS, ([0, 7, 8],)), + "an unhashable source among sources": (MS, ([[0]],)), + "sources empty": (MS, ([],)), + "sources an empty set": (MS, (set(),)), + "sources a falsy int": (MS, (0,)), + "sources an int": (MS, (5,)), + "sources a generator": (MS, "generator"), + "sources a generator with a missing node": (MS, "generator with 7"), + "sources repeated": (MS, ([2, 0, 2],)), + "a source equal to a node": (MS, ([1.0, True],)), + "pair source missing": (PAIR, (7, 0)), + "pair both missing and equal": (PAIR, (7, 7)), + "pair source is target": (PAIR, (0, 0)), + "pair source equals target": (PAIR, (1, 1.0)), + "pair target missing": (PAIR, (0, 7)), + "pair target unreachable": (PAIR, (0, 9)), + "pair target reachable": (PAIR, (0, 2)), +} + + +@pytest.mark.parametrize("case", sorted(ERRORS)) +def test_errors_and_edge_cases_as_networkx(case): + f, args = ERRORS[case] + G = errors_graph() + + def call(**kwargs): + if args == "generator": + return f(G, (s for s in [0, 2]), **kwargs) + if args == "generator with 7": + return f(G, (s for s in [0, 7]), **kwargs) + return f(G, *args, **kwargs) + + want = outcome(call) + got = outcome(lambda: call(backend="graphblas")) + assert got == want + assert repr(got) == repr(want) # keys of the same types, as `1.0` and `True` + + +def test_an_unhashable_target_is_left_to_networkx(): + """NetworkX compares it with each node it reaches before it looks it up.""" + G = errors_graph() + reason = Dispatcher.can_run("dijkstra_path_length", (G, 0, [7]), {}) + assert isinstance(reason, str) + assert "hashable" in reason + want = outcome(lambda: PAIR(G, 0, [7])) + with nx.config(backend_priority=["graphblas"]): + assert outcome(lambda: PAIR(G, 0, [7])) == want + + +@pytest.mark.parametrize("graph", sorted(NEGATIVE_OR_NAN)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", SOURCE_NAMES) +def test_negative_and_nan_weights_from_sources_are_left_to_networkx(graph, directed, name): + """NetworkX's answer, ValueError included, follows its walk; it answers them itself.""" + G = in_node_order(NEGATIVE_OR_NAN[graph], 4, directed) + f = getattr(nx, name) + args = {"dijkstra_path_length": (0, 3), "multi_source_dijkstra_path_length": ([0, 3],)} + args = args.get(name, (0,)) + with pytest.raises(NotImplementedError) as info: + f(G, *args, backend="graphblas") + assert "negative or NaN" in f"{info.value} {info.value.__cause__}" + want = outcome(lambda: f(G, *args, backend="networkx")) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + got = outcome(lambda: f(G, *args)) + assert repr(got) == repr(want) + + +@pytest.mark.parametrize("graph", sorted(NEGATIVE_OR_NAN)) +def test_a_source_that_is_its_target_is_at_zero_whatever_the_weights(graph): + """NetworkX answers 0 before it walks, so nothing is left to it.""" + G = in_node_order(NEGATIVE_OR_NAN[graph], 4) + assert outcome(partial(PAIR, G, 1, 1.0, backend="graphblas")) == ("value", 0) + assert PAIR(G, 1, 1.0) == 0 + + +@pytest.mark.parametrize("weights", [None, (1, 2), (0.1, 0.7), (0, 3)]) +@pytest.mark.parametrize("directed", [False, True]) +def test_a_path_from_end_to_end_takes_a_round_per_edge(weights, directed): + """The longest walk a least length needs has an edge fewer than the graph has nodes.""" + n = 9 + edges = [(i, i + 1, None if weights is None else weights[i % 2]) for i in range(n - 1)] + G = in_node_order(edges, n, directed) + for source in [0, n - 1]: + assert_from_sources(SS(G, source, backend="graphblas"), SS(G, source), [source]) + assert_pair_as_networkx(G, G, source, n - 1 - source) + assert_from_sources(MS(G, [0, 4], backend="graphblas"), MS(G, [0, 4]), [0, 4]) + + +@pytest.mark.parametrize("weights", [None, (1, 2), (0.5, 0.25)]) +def test_the_walk_to_a_target_goes_no_farther_than_its_length(weights): + """Weights are not negative, so a walk past the target's length cannot shorten it.""" + edges = [(i, i + 1, None if weights is None else weights[i % 2]) for i in range(8)] + G = Graph.from_networkx(in_node_order(edges, 9), weight="weight") + d = weighted._dijkstra_vector(G, [0], dst_id=3) + assert d.to_coo()[0].tolist() == [0, 1, 2, 3] + assert d.get(3) == nx.dijkstra_path_length(in_node_order(edges, 9), 0, 3) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_an_inf_self_loop_is_served_where_its_matrix_holds_inf(directed): + """An undirected one is NaN in NetworkX's matrix, so declined; NetworkX's answer is the same.""" + G = in_node_order([(0, 0, math.inf), (0, 1, 1.5), (1, 2, math.inf)], 3, directed) + want = SS(G, 0) + if directed: + assert_from_sources(SS(G, 0, backend="graphblas"), want, [0]) + else: + with pytest.raises(NotImplementedError): + SS(G, 0, backend="graphblas") + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + assert_from_sources(SS(G, 0), want, [0]) + + +CUTOFFS = [None, -math.inf, -1, -0.5, 0, 1, 2.5, 3, 5, math.nan, math.inf, True] +CUTOFFS += [np.int64(3), np.float64(2.5)] + + +@pytest.mark.parametrize("weights", ["int", "float"]) +@pytest.mark.parametrize("cutoff", CUTOFFS) +def test_a_cutoff_from_sources_keeps_what_networkx_keeps(weights, cutoff): + edges = [(0, 1, 2), (1, 2, 3), (0, 3, 1), (3, 4, 2), (4, 2, 0)] + if weights == "float": + edges = [(u, v, w / 2) for u, v, w in edges] + G = in_node_order(edges, 6) + assert Dispatcher.can_run(SOURCE_NAMES[0], (G, 0), {"cutoff": cutoff}) is True + for source in G: + want = SS(G, source, cutoff=cutoff) + assert_from_sources(SS(G, source, cutoff=cutoff, backend="graphblas"), want, [source]) + for sources in [[0], [5, 2], [4, 0, 4], {1, 3}]: + want = MS(G, sources, cutoff=cutoff) + assert_from_sources(MS(G, sources, cutoff=cutoff, backend="graphblas"), want, sources) + + +@pytest.mark.parametrize( + "cutoff", + [Decimal(1), Fraction(1, 3), np.float32(0.5), 2**53, -(2**60), np.int64(2**60), "1"], +) +@pytest.mark.parametrize("name", SOURCE_NAMES[:2]) +def test_a_cutoff_from_sources_that_compares_unlike_a_matrix_is_declined(name, cutoff): + G = in_node_order(GRAPHS["unit grid"][0], 16) + args = (G, [0]) if name.startswith("multi") else (G, 0) + assert isinstance(Dispatcher.can_run(name, args, {"cutoff": cutoff}), str) + + +@pytest.mark.parametrize("name", SOURCE_NAMES) +def test_a_weight_function_or_another_adjacency_from_sources_is_declined(name): + class Reported(nx.Graph): + def adjacency(self): + return iter([]) + + args = {"dijkstra_path_length": (0, 3), "multi_source_dijkstra_path_length": ([0],)} + args = args.get(name, (0,)) + G = nx.path_graph(4) + assert Dispatcher.can_run(name, (G, *args), {}) is True + assert isinstance(Dispatcher.can_run(name, (G, *args), {"weight": lambda u, v, d: 1}), str) + assert isinstance(Dispatcher.can_run(name, (Reported(G), *args), {}), str) + + +@pytest.mark.parametrize("graph", ["ties", "directed integers", "tenths grid", "inf weights"]) +def test_a_backend_graph_from_sources_is_answered(graph): + edges, n, directed = GRAPHS[graph] + H = in_node_order(edges, n, directed) + G = (DiGraph if directed else Graph).from_networkx(H, weight="weight") + for source in H: + assert_from_sources(SS(G, source), SS(H, source), [source]) + for target in H: + assert_pair_as_networkx(G, H, source, target) + assert_from_sources(MS(G, [3, 1]), MS(H, [3, 1]), [3, 1]) + + +def test_float32_lengths_from_sources(): + edges = [(u, v, np.float32(w)) for u, v, w in GRAPHS["tenths grid"][0]] + G = in_node_order(edges, 16) + assert_from_sources(SS(G, 0, backend="graphblas"), SS(G, 0), [0], rel=1e-6) + assert PAIR(G, 0, 15, backend="graphblas") == pytest.approx(PAIR(G, 0, 15), rel=1e-6) + + +@pytest.mark.parametrize("name", SOURCE_NAMES) +def test_integer_sums_that_could_overflow_raise_from_sources(name): + G = nx.path_graph(4) + nx.set_edge_attributes(G, 2**61, "weight") + args = {"dijkstra_path_length": (0, 3), "multi_source_dijkstra_path_length": ([0],)} + with pytest.raises(OverflowError): + getattr(nxapi, name)(G, *args.get(name, (0,))) + + +def test_the_walk_is_checked_once_per_graph(monkeypatch): + """NetworkX's own loops, as in its all_pairs_dijkstra_path_length, ask one source at a time.""" + from graphblas_algorithms.nxapi.shortest_paths import weighted as api + + calls = [] + check = api._negative_or_nan + monkeypatch.setattr(api, "_negative_or_nan", lambda G: calls.append(G) or check(G)) + G = Graph.from_networkx(in_node_order(GRAPHS["integer grid"][0], 16), weight="weight") + for source in G: + nxapi.single_source_dijkstra_path_length(G, source) + assert len(calls) == 1 + + +@pytest.mark.parametrize("name", SOURCE_NAMES) +def test_should_run_leaves_a_walk_from_sources_to_networkx(name): + """Converting the graph costs about what NetworkX's walk does (see `_one_walk`).""" + G = nx.path_graph(4) + args = {"dijkstra_path_length": (0, 3), "multi_source_dijkstra_path_length": ([0],)} + reason = Dispatcher.should_run(name, (G, *args.get(name, (0,))), {}) + assert isinstance(reason, str) + assert "networkx" in reason + assert Dispatcher.should_run(NAME, (G,), {}) is True + + +SHORTEST_PATH_LENGTH = { + "source": ((1,), {}), + "target": ((), {"target": 1}), + "pair": ((1, 7), {}), +} + + +@pytest.mark.parametrize("gated", [True, False]) +@pytest.mark.parametrize("directed", [False, True]) +def test_shortest_path_length_dispatches_through_these_names(directed, gated, monkeypatch): + """NetworkX's shortest_path_length calls them by name, so it is served where they are. + + That is with this backend first and `should_run` set aside; with it, NetworkX answers. + """ + G = in_node_order(GRAPHS["directed integers"][0], 12, directed) + want = { + key: nx.shortest_path_length(G, *args, weight="weight", **kwargs) + for key, (args, kwargs) in SHORTEST_PATH_LENGTH.items() + } + served = [] + for name in SOURCE_NAMES: + original = getattr(Dispatcher, name) + + def spy(*args, _original=original, _name=name, **kwargs): + served.append(_name) + return _original(*args, **kwargs) + + spy._can_run = original._can_run + spy._should_run = original._should_run + monkeypatch.setattr(Dispatcher, name, staticmethod(spy)) + if not gated: + monkeypatch.setattr(Dispatcher, "should_run", staticmethod(lambda name, args, kwargs: True)) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + got = { + key: nx.shortest_path_length(G, *args, weight="weight", **kwargs) + for key, (args, kwargs) in SHORTEST_PATH_LENGTH.items() + } + assert served == ([] if gated else [SOURCE_NAMES[0], SOURCE_NAMES[0], SOURCE_NAMES[2]]) + if gated: + assert got == want + else: + assert_from_sources(got["source"], want["source"], [1]) + assert_from_sources(got["target"], want["target"], [1]) + assert got["pair"] == want["pair"] diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 2885aaf..19f5cfe 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -106,6 +106,7 @@ def call_args(kind, args): "descendants_at_distance": ("dag", (0, 1)), "diameter": ("tournament", ()), "difference": ("plain", (SECOND,)), + "dijkstra_path_length": ("undirected", (0, 2)), "directed_modularity_matrix": ("directed", ()), "disjoint_union": ("undirected", (SECOND_DISJOINT,)), "eccentricity": ("tournament", ()), @@ -170,6 +171,7 @@ def call_args(kind, args): "mixing_expansion": ("undirected", ([0, 1], [2, 3])), "modularity": ("undirected", ([{0, 1}, {2, 3, 4}],)), "modularity_matrix": ("undirected", ()), + "multi_source_dijkstra_path_length": ("undirected", ([0, 2],)), "mutual_weight": ("directed", (0, 1)), "negative_edge_cycle": ("undirected", ()), "node_boundary": ("undirected", ([0, 1], [2, 3])), @@ -198,6 +200,7 @@ def call_args(kind, args): "schultz_index": ("undirected", ()), "score_sequence": ("tournament", ()), "single_source_bellman_ford_path_length": ("undirected", (0,)), + "single_source_dijkstra_path_length": ("undirected", (0,)), "single_source_shortest_path_length": ("undirected", (0,)), "single_target_shortest_path_length": ("undirected", (0,)), "square_clustering": ("undirected", ()),