From 13130697f23551bdbc61c178228beb81f900f738 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Tue, 1 Dec 2026 22:14:36 -0600 Subject: [PATCH] Add all_pairs_dijkstra_path_length Serve it with the batched Bellman-Ford kernel, which now takes a cutoff. With no negative or NaN weight, the length NetworkX's Dijkstra gives a node is the least sum over the walks to it, which is what min-plus finds, here in the weights' own type, float32 included. Each source's dict holds the source, at the integer 0, and then the other nodes by increasing length, equal lengths in id order. NetworkX orders equal lengths by its heap, which is arbitrary. Negative and NaN weights are left to NetworkX, since its lengths and its "Contradictory paths" error there follow its walk. A weight function, a graph class that reports another adjacency, and a cutoff that does not compare as a float does are declined. Integer weights whose sums could overflow raise when called, not at the first item. The tests compare targets and integer lengths exactly and float lengths within rounding, and check that every length is a shortest path's: no edge shortens one, and a tight edge leads into each. --- README.md | 1 + _nx_graphblas/__init__.py | 1 + .../algorithms/shortest_paths/weighted.py | 103 ++++++- graphblas_algorithms/interface.py | 1 + .../nxapi/shortest_paths/weighted.py | 58 +++- .../nxapi/tests/test_dijkstra.py | 282 ++++++++++++++++++ .../nxapi/tests/test_shortest_paths.py | 25 ++ graphblas_algorithms/tests/_dispatched.py | 1 + 8 files changed, 466 insertions(+), 6 deletions(-) create mode 100644 graphblas_algorithms/nxapi/tests/test_dijkstra.py diff --git a/README.md b/README.md index 1bc06b5..3694763 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,7 @@ graphblas_algorithms.nxapi │ │ └── single_target_shortest_path_length │ └── weighted │ ├── all_pairs_bellman_ford_path_length +│ ├── all_pairs_dijkstra_path_length │ ├── bellman_ford_path │ ├── bellman_ford_path_length │ ├── negative_edge_cycle diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..bd2b130 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -32,6 +32,7 @@ def get_info(): "adamic_adar_index", "adjacency_matrix", "all_pairs_bellman_ford_path_length", + "all_pairs_dijkstra_path_length", "all_pairs_shortest_path_length", "ancestors", "average_clustering", diff --git a/graphblas_algorithms/algorithms/shortest_paths/weighted.py b/graphblas_algorithms/algorithms/shortest_paths/weighted.py index 1fd9bf8..fdbda9c 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/weighted.py +++ b/graphblas_algorithms/algorithms/shortest_paths/weighted.py @@ -1,5 +1,9 @@ +import math +from itertools import pairwise + import numpy as np from graphblas import Matrix, Vector, binary, indexunary, monoid, replace, select, unary +from graphblas.dtypes import lookup_dtype from graphblas.semiring import any_pair, min_plus from .._bfs import _bfs_level, _bfs_levels, _bfs_parent @@ -10,6 +14,7 @@ "bellman_ford_path", "bellman_ford_path_length", "bellman_ford_path_lengths", + "dijkstra_path_lengths", "negative_edge_cycle", "single_source_bellman_ford_path_length", ] @@ -53,6 +58,17 @@ def _levels_to_lengths(levels, weight): return levels +def _iso_walks(G, weight, cutoff): + """`(weight, levels)`: what each edge of an iso-valued `G` weighs, and its level cutoff. + + Where no edge joins two nodes no walk leaves a source, whose length is NetworkX's integer + 0 whatever a self-loop weighs, inf included, which integer lengths do not hold. + """ + if G.get_property("offdiag").nvals == 0: + return 1, None + return weight, _level_cutoff(weight, G._A.nrows, cutoff) + + def _bellman_ford_path_length(G, source, target=None, *, cutoff=None, name): # No need for `is_weighted=` keyword, b/c this is assumed to be weighted (I think) src_id = G._key_to_id[source] @@ -66,9 +82,9 @@ def _bellman_ford_path_length(G, source, target=None, *, cutoff=None, name): is_negative, iso_value = G.get_properties("has_negative_edges+ iso_value") if not is_negative: dtype = _length_dtype(G, G.get_property("offdiag")) - cutoff = _level_cutoff(iso_value.get(), G._A.nrows, cutoff) + weight, cutoff = _iso_walks(G, iso_value.get(), cutoff) d = _bfs_level(G, source, target, cutoff=cutoff, dtype=dtype) - d = _levels_to_lengths(d, iso_value.get()) + d = _levels_to_lengths(d, weight) if dst_id is not None: d = d.get(dst_id) if d is None: @@ -150,8 +166,8 @@ def bellman_ford_path_length(G, source, target): return _bellman_ford_path_length(G, source, target, name="bellman_ford_path_length") -def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None): - """Extra parameters: expand_output, dtype +def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None, cutoff=None): + """Extra parameters: expand_output, dtype, cutoff Parameters ---------- @@ -162,6 +178,9 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None) The lengths' dtype. By default the values' own, or INT64 for integers, which raises OverflowError where a length could reach 2**63; a caller whose answer is a float can pass a floating-point type instead. + cutoff : number, optional + Only lengths at most `cutoff` are kept, as a value of the lengths' dtype; a source's + own 0 always is. """ # Same algorithms as in `single_source_bellman_ford_path_length`, but with # `Cur` as a Matrix with each row corresponding to a source node. @@ -169,7 +188,9 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None) is_negative, iso_value = G.get_properties("has_negative_edges+ iso_value") if not is_negative: dtype = _length_dtype(G, G.get_property("offdiag"), dtype) - D = _levels_to_lengths(_bfs_levels(G, nodes, dtype=dtype), iso_value.get()) + weight, levels = _iso_walks(G, iso_value.get(), cutoff) + D = _bfs_levels(G, nodes, cutoff=levels, dtype=dtype) + D = _levels_to_lengths(D, weight) if nodes is not None and expand_output and D.ncols != D.nrows: ids = G.list_to_ids(nodes) rv = Matrix(D.dtype, D.ncols, D.ncols, name=D.name) @@ -209,6 +230,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None) 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 @@ -217,6 +240,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None) D(Cur.S) << Cur else: Cur << min_plus[dtype](Cur @ A) + if cutoff is not None: + Cur << select.valuele(Cur, cutoff) Mask << binary.lt(Cur & D) if Mask.reduce_scalar(monoid.lor): raise Unbounded("Negative cycle detected.") @@ -365,3 +390,71 @@ def negative_edge_cycle(G): if mask.reduce(monoid.lor): return True return False + + +# Dijkstra +# +# With no negative or NaN weight, adding an edge never shortens a walk, so the length NetworkX's +# Dijkstra gives a node is the least sum over the walks to it: what min-plus finds. + +# Rows of lengths found at a time, so that a batch holds about 2**22 entries. +_BATCH_ENTRIES = 2**22 + + +def _dijkstra_cutoff(cutoff, np_type): + """`cutoff` as a value of the lengths' type that keeps what NetworkX keeps, or None for all. + + NetworkX drops a length `x` where `x > cutoff`, so a NaN cutoff drops none. Lengths here + are never negative, so a negative cutoff keeps only the sources. + """ + if cutoff is None or (isinstance(cutoff, float) and math.isnan(cutoff)): + return None + if np_type.kind == "f": + if cutoff == math.inf: + return None + if cutoff == -math.inf: + return -1.0 + value = float(cutoff) + if value > cutoff: # an integer that rounds up: the float below it keeps the same + value = math.nextafter(value, -math.inf) + return value + if cutoff < 0: + return -1 + if cutoff >= 2**63 - 1: + return None + return int(cutoff) # its floor, as it is not negative + + +def dijkstra_path_lengths(G, nodes=None, *, cutoff=None): + """Yield `(source id, ids, lengths)` per source in `nodes`, every node if None. + + `ids` lists the nodes the source reaches within `cutoff`: the source, its length the + integer 0, and then the others by increasing length, equal lengths in id order. A + negative or NaN weight is not read as NetworkX's Dijkstra reads it, which follows the + order of its walk; the lengths are then Bellman-Ford's. + """ + if nodes is None: + nodes = list(G) + dtype = _length_dtype(G, G.get_property("offdiag")) + cutoff = _dijkstra_cutoff(cutoff, lookup_dtype(dtype).np_type) + batch = max(1, min(len(nodes), _BATCH_ENTRIES // max(len(G), 1))) + for start in range(0, len(nodes), batch): + keys = nodes[start : start + batch] + ids = G.list_to_ids(keys).astype(np.int64) + D = bellman_ford_path_lengths(G, keys, dtype=dtype, cutoff=cutoff) + rows, cols, vals = D.to_coo() # by row, then by id + rows = rows.astype(np.int64) + rowptr = np.zeros(D.nrows + 1, np.int64) + np.cumsum(np.bincount(rows, minlength=D.nrows), out=rowptr[1:]) + # Lengths are not negative, so -1 puts the source first, ahead of any other at 0. + key = np.where(cols == ids[rows], -1, vals) + order = np.empty(rows.size, np.int64) + for lo, hi in pairwise(rowptr.tolist()): + order[lo:hi] = lo + np.argsort(key[lo:hi], kind="stable") + cols = cols[order].tolist() + vals = vals[order].tolist() + for i, src in enumerate(ids.tolist()): + lo, hi = rowptr[i], rowptr[i + 1] + lengths = vals[lo:hi] + lengths[0] = 0 # NetworkX's integer 0 for the source + yield src, cols[lo:hi], lengths diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..81b7ee9 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -405,6 +405,7 @@ class Dispatcher: single_source_shortest_path_length = mod.unweighted.single_source_shortest_path_length single_target_shortest_path_length = mod.unweighted.single_target_shortest_path_length all_pairs_bellman_ford_path_length = mod.weighted.all_pairs_bellman_ford_path_length + 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 negative_edge_cycle = mod.weighted.negative_edge_cycle diff --git a/graphblas_algorithms/nxapi/shortest_paths/weighted.py b/graphblas_algorithms/nxapi/shortest_paths/weighted.py index 2f2a016..dd90698 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/weighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/weighted.py @@ -1,11 +1,15 @@ +import numpy as np + from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.shortest_paths.weighted import _length_dtype from graphblas_algorithms.classes.digraph import to_graph -from .._utils import normalize_chunksize, partition +from .._utils import can_run, normalize_chunksize, partition from ..exception import NetworkXNoPath, NetworkXUnbounded, NodeNotFound __all__ = [ "all_pairs_bellman_ford_path_length", + "all_pairs_dijkstra_path_length", "bellman_ford_path", "bellman_ford_path_length", "negative_edge_cycle", @@ -106,3 +110,55 @@ def negative_edge_cycle(G, weight="weight", heuristic=True): # TODO: use a heuristic to try to stop early G = to_graph(G, weight=weight) 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) + A = G._A + if G.get_property("has_negative_edges+") or ( + 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. + _length_dtype(G, G.get_property("offdiag")) + return _all_pairs_dijkstra_path_length(G, cutoff) + + +def _all_pairs_dijkstra_path_length(G, cutoff): + nodes = list(G) + id_to_key = G.id_to_key + keys = [id_to_key[i] for i in range(len(G))] + identity = all(key == i and type(key) is int for i, key in enumerate(keys)) + for src, ids, lengths in algorithms.dijkstra_path_lengths(G, nodes, cutoff=cutoff): + if not identity: + ids = map(keys.__getitem__, ids) + yield keys[src], dict(zip(ids, lengths, strict=True)) diff --git a/graphblas_algorithms/nxapi/tests/test_dijkstra.py b/graphblas_algorithms/nxapi/tests/test_dijkstra.py new file mode 100644 index 0000000..ca2ec1b --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_dijkstra.py @@ -0,0 +1,282 @@ +"""all_pairs_dijkstra_path_length: 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. +""" + +import math +from decimal import Decimal +from fractions import Fraction +from itertools import pairwise + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms import DiGraph, Graph, nxapi +from graphblas_algorithms.algorithms.shortest_paths import weighted +from graphblas_algorithms.interface import Dispatcher + +NAME = "all_pairs_dijkstra_path_length" + + +def in_node_order(edges, n, directed=False): + """A graph over nodes 0..n-1 whose successors follow node order.""" + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(n)) + key = (lambda e: e[:2]) if directed else (lambda e: (min(e[:2]), max(e[:2]))) + for u, v, w in sorted(edges, key=key): + if w is None: + G.add_edge(u, v) + else: + G.add_edge(u, v, weight=w) + return G + + +def near(want, rel=1e-12): + """`want`, a source's lengths, exactly where they are integers, else within `rel`.""" + if all(type(x) is int for x in want.values()): + return want + return pytest.approx(want, rel=rel) + + +def assert_shortest(G, source, lengths, rel): + """No edge shortens a length, and each but the source's is a path's: an edge in is tight.""" + pred = G.pred if G.is_directed() else G.adj + for u, du in lengths.items(): + for v, data in G.adj[u].items(): + assert lengths[v] <= du + data.get("weight", 1) or math.isclose( + lengths[v], du + data.get("weight", 1), rel_tol=rel + ) + for v, dv in lengths.items(): + if v != source: + assert any( + u in lengths and math.isclose(lengths[u] + data.get("weight", 1), dv, rel_tol=rel) + for u, data in pred[v].items() + ), (source, v) + + +def assert_as_networkx(G, rel=1e-12, **kwargs): + want = dict(nx.all_pairs_dijkstra_path_length(G, **kwargs)) + got = list(nx.all_pairs_dijkstra_path_length(G, backend="graphblas", **kwargs)) + assert dict(got).keys() == want.keys() + for source, lengths in got: + assert lengths == near(want[source], rel) + # The source first, at the integer 0, and then by increasing length. + values = list(lengths.values()) + assert next(iter(lengths)) == source + assert type(values[0]) is int + assert values[0] == 0 + assert all(a <= b for a, b in pairwise(values)) + if kwargs.get("cutoff") is None: + assert_shortest(G, source, lengths, rel) + + +GRID = [(u, v, 1) for u, v in nx.convert_node_labels_to_integers(nx.grid_2d_graph(4, 4)).edges] +TREE = [(u, v, 1) for u, v in nx.balanced_tree(2, 3).edges] +GRAPHS = { + "ties": ([(0, 5, 1), (0, 3, 2), (5, 1, 1), (3, 2, 1)], 6, False), + "unit grid": (GRID, 16, False), + "unweighted grid": ([(u, v, None) for u, v, _ in GRID], 16, False), + "integer grid": ([(u, v, 1 + (u * v) % 3) for u, v, _ in GRID], 16, False), + "tenths grid": ([(u, v, (0.1, 0.2, 0.3)[(u + v) % 3]) for u, v, _ in GRID], 16, False), + "zero weights": ([(u, v, (u + v) % 2) for u, v, _ in GRID], 16, False), + "unit tree": (TREE, 15, False), + "directed integers": ( + [(u, (u * 7 + k) % 12, k) for u in range(12) for k in (1, 2, 3)], + 12, + True, + ), + "inf weights": ([(0, 1, math.inf), (1, 2, 1.0), (0, 3, 1.0), (3, 2, math.inf)], 5, False), + "a self-loop": ([(0, 0, 1), (0, 1, 1), (1, 2, 1), (0, 2, 2)], 3, False), + "a longer edge from earlier": ( + [(0, 1, 1), (0, 2, 2), (1, 4, 5), (2, 3, 1), (2, 4, 1)], + 5, + False, + ), + "a longer directed edge from earlier": ( + [(0, 1, 1), (0, 2, 2), (1, 4, 5), (2, 3, 1), (2, 4, 1)], + 5, + True, + ), + # From 4, 0 is also at length 0: the source still comes first. + "a zero weight out of a source": ([(4, 0, 0), (0, 1, 1), (1, 2, 1), (4, 3, 2)], 5, True), + "edgeless": ([], 3, False), +} + + +@pytest.mark.parametrize("graph", sorted(GRAPHS)) +@pytest.mark.parametrize("cutoff", [None, 0, 1, 2, 2.5, -1, math.nan, math.inf]) +def test_every_length_as_networkx(graph, cutoff): + edges, n, directed = GRAPHS[graph] + assert_as_networkx(in_node_order(edges, n, directed), cutoff=cutoff) + + +NEGATIVE_OR_NAN = { + "negative, unseen": [(0, 1, 1), (1, 2, -1), (0, 2, 3)], + "negative, contradictory": [(0, 1, 2), (1, 2, -3), (0, 2, 1), (2, 3, 1)], + "negative self-loop": [(0, 0, -1), (0, 1, 1)], + "-inf": [(0, 1, 1.0), (1, 2, -math.inf)], + "nan": [(0, 1, 1.0), (1, 2, math.nan), (0, 2, 3.0), (2, 3, 1.0)], + "nan self-loop": [(0, 0, math.nan), (0, 1, 1.0)], +} + + +def items(f): + """Every item, or the items before an exception and its type and args.""" + seen = [] + try: + for s, d in f(): + seen.append((s, list(d.items()))) + except Exception as exc: + return seen, type(exc), exc.args + return seen, None, None + + +@pytest.mark.parametrize("graph", sorted(NEGATIVE_OR_NAN)) +@pytest.mark.parametrize("directed", [False, True]) +def test_negative_and_nan_weights_are_left_to_networkx(graph, directed): + """NetworkX's answer, ValueError included, follows its walk; it answers them itself.""" + G = in_node_order(NEGATIVE_OR_NAN[graph], 4, directed) + with pytest.raises(NotImplementedError) as info: + nx.all_pairs_dijkstra_path_length(G, backend="graphblas") + assert "negative or NaN" in f"{info.value} {info.value.__cause__}" + want = items(lambda: nx.all_pairs_dijkstra_path_length(G, backend="networkx")) + with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}): + got = items(lambda: nx.all_pairs_dijkstra_path_length(G)) + assert repr(got) == repr(want) + + +@pytest.mark.parametrize("cutoff", [None, 0.65, np.float64(0.65)]) +def test_float32_weights_are_served(cutoff): + """Added in float32 as NetworkX adds them, though not in its order.""" + edges = [(u, v, np.float32(w)) for u, v, w in GRAPHS["tenths grid"][0]] + assert_as_networkx(in_node_order(edges, 16), rel=1e-6, cutoff=cutoff) + + +def test_a_backend_graph_is_answered(): + for edges, n, directed in [GRAPHS["ties"], GRAPHS["directed integers"]]: + H = in_node_order(edges, n, directed) + G = (DiGraph if directed else Graph).from_networkx(H, weight="weight") + want = dict(nx.all_pairs_dijkstra_path_length(H)) + assert dict(nx.all_pairs_dijkstra_path_length(G)) == want + + +def test_string_nodes_are_answered_with_their_keys(): + G = nx.relabel_nodes(in_node_order(GRAPHS["unit grid"][0], 16), {i: f"n{i}" for i in range(16)}) + assert_as_networkx(G) + + +@pytest.mark.parametrize("entries", [1, 40, 50]) +def test_small_batches_give_the_same_lengths(monkeypatch, entries): + monkeypatch.setattr(weighted, "_BATCH_ENTRIES", entries) + for graph in ["unit grid", "integer grid", "zero weights", "directed integers"]: + edges, n, directed = GRAPHS[graph] + assert_as_networkx(in_node_order(edges, n, directed)) + + +def edges_after_nodes(edges, directed=False): + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(3)) + G.add_edges_from(edges, weight=1) + return G + + +# Graphs whose successors do not follow node order. +OUT_OF_ORDER = { + "undirected": lambda: edges_after_nodes([(0, 2), (0, 1)]), + "directed": lambda: edges_after_nodes([(0, 2), (0, 1)], directed=True), + "cycle_graph": lambda: nx.cycle_graph(9), + "grid_2d_graph": lambda: nx.grid_2d_graph(4, 3), + "karate_club_graph": nx.karate_club_graph, + "gnm_random_graph": lambda: nx.gnm_random_graph(30, 60, seed=1), + "directed gnm_random_graph": lambda: nx.gnm_random_graph(30, 90, seed=1, directed=True), + "hypercube_graph": lambda: nx.hypercube_graph(3), +} + + +@pytest.mark.parametrize("graph", sorted(OUT_OF_ORDER)) +@pytest.mark.parametrize("weights", [None, (1, 2, 3), (0, 1, 2), (0.1, 0.2, 0.3)]) +def test_graphs_built_from_edges(graph, weights): + G = OUT_OF_ORDER[graph]() + if weights is not None: + for i, (_u, _v, data) in enumerate(G.edges(data=True)): + data["weight"] = weights[i % len(weights)] + assert_as_networkx(G) + + +def test_integer_sums_that_could_overflow_raise_when_called(): + """Not at the first item, which is read after NetworkX's dispatcher has returned.""" + G = nx.path_graph(4) + nx.set_edge_attributes(G, 2**61, "weight") + with pytest.raises(OverflowError): + nxapi.all_pairs_dijkstra_path_length(G) + + +def test_a_graph_reporting_another_adjacency_is_declined(): + class Reported(nx.Graph): + def adjacency(self): + return iter([]) + + G = Reported(nx.path_graph(4)) + assert isinstance(Dispatcher.can_run(NAME, (G,), {}), str) + + +@pytest.mark.parametrize( + "cutoff", + [Decimal(1), Fraction(1, 3), np.float32(0.5), 2**53, -(2**60), np.int64(2**60), "1"], +) +def test_a_cutoff_that_compares_unlike_a_matrix_is_declined(cutoff): + G = in_node_order(GRAPHS["unit grid"][0], 16) + assert isinstance(Dispatcher.can_run(NAME, (G,), {"cutoff": cutoff}), str) + + +@pytest.mark.parametrize("cutoff", [None, 1, 2.5, True, np.int64(3), np.float64(2.5), math.inf]) +def test_a_plain_cutoff_is_served(cutoff): + G = in_node_order(GRAPHS["unit grid"][0], 16) + assert Dispatcher.can_run(NAME, (G,), {"cutoff": cutoff}) is True + assert_as_networkx(G, cutoff=cutoff) + + +def test_a_weight_function_is_declined(): + G = in_node_order(GRAPHS["unit grid"][0], 16) + assert isinstance(Dispatcher.can_run(NAME, (G,), {"weight": lambda u, v, d: 1}), str) + + +@pytest.mark.parametrize("weights", ["int", "float", "inf self-loops"]) +@pytest.mark.parametrize( + "cutoff", + [ + -math.inf, + -1, + -0.5, + 0, + 2.5, + 2**53 + 1, + 2**53 + 3, + 2**62, + 2**63, + 2**70, + 1e300, + math.inf, + math.nan, + ], +) +def test_any_cutoff_keeps_what_networkx_keeps(weights, cutoff): + """Directly, past what `can_run` serves: an integer cutoff with float lengths, and back.""" + if weights == "inf self-loops": + # No edge joins two nodes, so each length is a source's 0, which inf does not bound. + H = in_node_order([(0, 0, math.inf), (2, 2, math.inf)], 3, directed=True) + else: + big = 2**52 if weights == "int" else 2.0**52 + one = 1 if weights == "int" else 1.0 + # Lengths 2**53 + 1, which a float does not hold, and 2**53 + 4, past 2**53 + 3. + H = in_node_order([(0, 1, big), (1, 2, big), (2, 3, one), (2, 5, 4 * one), (0, 4, 2)], 6) + G = (DiGraph if H.is_directed() else Graph).from_networkx(H, weight="weight") + want = dict(nx.all_pairs_dijkstra_path_length(H, cutoff=cutoff)) + got = { + s: dict(zip(ids, lengths, strict=True)) + for s, ids, lengths in weighted.dijkstra_path_lengths(G, cutoff=cutoff) + } + assert got.keys() == want.keys() + assert all(got[s] == near(want[s]) for s in want) diff --git a/graphblas_algorithms/nxapi/tests/test_shortest_paths.py b/graphblas_algorithms/nxapi/tests/test_shortest_paths.py index 93aa012..a14a8ec 100644 --- a/graphblas_algorithms/nxapi/tests/test_shortest_paths.py +++ b/graphblas_algorithms/nxapi/tests/test_shortest_paths.py @@ -500,3 +500,28 @@ def test_a_nan_or_inf_weight_keeps_the_source_at_zero(weight, cutoff): assert got.keys() == want.keys() assert got[0] == want[0] == 0 assert all(got[k] == want[k] or math.isnan(got[k]) and math.isnan(want[k]) for k in want) + + +@pytest.mark.parametrize("value", [math.inf, 2.0, 3]) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("cutoff", [-1, 0, 0.7, 2, None]) +def test_self_loops_alone_take_no_walk_past_the_source(value, directed, cutoff): + """No edge joins two nodes, so each length is a source's 0 whatever a self-loop weighs.""" + from graphblas_algorithms import algorithms + + H = nx.DiGraph() if directed else nx.Graph() + H.add_nodes_from(range(3)) + H.add_weighted_edges_from([(0, 0, value), (2, 2, value)]) + # One stored value, so the iso route, which a conversion need not give: NetworkX's matrix + # of an undirected inf self-loop holds NaN. + A = Matrix.from_coo([0, 2], [0, 2], value, nrows=3, ncols=3) + G = (DiGraph if directed else Graph)(A, weight="weight") + assert G.get_property("is_iso") + want = nx.single_source_dijkstra_path_length(H, 0, cutoff=cutoff) + got = algorithms.single_source_bellman_ford_path_length(G, 0, cutoff=cutoff) + assert G.vector_to_nodemap(got) == want + D = algorithms.bellman_ford_path_lengths(G, cutoff=cutoff) + assert [x.tolist() for x in D.to_coo()] == [[0, 1, 2], [0, 1, 2], [0, 0, 0]] + if cutoff is not None: + R = nx.ego_graph(H, 0, radius=cutoff, distance="weight", backend="graphblas") + assert list(R) == list(nx.ego_graph(H, 0, radius=cutoff, distance="weight")) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..2885aaf 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -72,6 +72,7 @@ def call_args(kind, args): "adamic_adar_index": ("undirected", ([(0, 1), (0, 4)],)), "adjacency_matrix": ("undirected", ()), "all_pairs_bellman_ford_path_length": ("undirected", ()), + "all_pairs_dijkstra_path_length": ("undirected", ()), "all_pairs_shortest_path_length": ("undirected", ()), "ancestors": ("dag", (3,)), "average_clustering": ("undirected", ()),