diff --git a/graphblas_algorithms/algorithms/shortest_paths/weighted.py b/graphblas_algorithms/algorithms/shortest_paths/weighted.py index c0e5913..1fd9bf8 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/weighted.py +++ b/graphblas_algorithms/algorithms/shortest_paths/weighted.py @@ -27,6 +27,32 @@ def _length_dtype(G, A, dtype=None): return int if A.nvals == 0 else checked_sum_type(G, "path") +def _level_cutoff(weight, count, cutoff): + """The most edges weighing `weight` a walk within `cutoff` has, or None for no bound. + + NetworkX drops a length `x` where `x > cutoff`, so a NaN weight or cutoff drops nothing, + and the source is always reached. A walk of `count - 1` edges is the longest there is. + """ + if cutoff is None or not (count - 1) * weight > cutoff: + return None + if cutoff < weight: + return 0 # the source alone, as for a zero weight and a negative cutoff + edges = int(cutoff // weight) + # `//` floors the exact quotient; the lengths are products rounded to nearest + return edges + 1 if (edges + 1) * weight <= cutoff else edges + + +def _levels_to_lengths(levels, weight): + """`levels`, a Vector or Matrix of walks' edge counts, as lengths of edges weighing `weight`. + + A source keeps its length 0 when `weight` is NaN or inf, as it does in NetworkX. + """ + if weight != 1: + # A Python number: a UINT64 Scalar would multiply in FP64 + levels(levels.V) << levels.apply(binary.times, right=weight) + return levels + + 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] @@ -39,12 +65,10 @@ def _bellman_ford_path_length(G, source, target=None, *, cutoff=None, name): # If the edges are iso-valued (and positive), then we can simply do level BFS is_negative, iso_value = G.get_properties("has_negative_edges+ iso_value") if not is_negative: - if cutoff is not None: - cutoff = int(cutoff // iso_value.get()) dtype = _length_dtype(G, G.get_property("offdiag")) + cutoff = _level_cutoff(iso_value.get(), G._A.nrows, cutoff) d = _bfs_level(G, source, target, cutoff=cutoff, dtype=dtype) - if iso_value != 1: - d *= iso_value.get() # a Python number: a UINT64 Scalar would multiply in FP64 + d = _levels_to_lengths(d, iso_value.get()) if dst_id is not None: d = d.get(dst_id) if d is None: @@ -144,9 +168,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None) if G.get_property("is_iso"): is_negative, iso_value = G.get_properties("has_negative_edges+ iso_value") if not is_negative: - D = _bfs_levels(G, nodes, dtype=_length_dtype(G, G.get_property("offdiag"), dtype)) - if iso_value != 1: - D *= iso_value.get() # as in `_bellman_ford_path_length` + dtype = _length_dtype(G, G.get_property("offdiag"), dtype) + D = _levels_to_lengths(_bfs_levels(G, nodes, dtype=dtype), iso_value.get()) 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) diff --git a/graphblas_algorithms/nxapi/tests/test_shortest_paths.py b/graphblas_algorithms/nxapi/tests/test_shortest_paths.py index 71fc7a5..93aa012 100644 --- a/graphblas_algorithms/nxapi/tests/test_shortest_paths.py +++ b/graphblas_algorithms/nxapi/tests/test_shortest_paths.py @@ -1,9 +1,11 @@ """Negative cycles and unreachable nodes in the floyd_warshall and bellman_ford names.""" +import math + import networkx as nx import numpy as np import pytest -from graphblas import Matrix +from graphblas import Matrix, select from graphblas_algorithms import DiGraph, Graph, nxapi from graphblas_algorithms.nxapi.exception import NetworkXUnbounded @@ -414,3 +416,87 @@ def test_floyd_warshall_without_a_negative_cycle_processes_every_node(name, oute got = getattr(nxapi, name)(convert(G)) assert distances(got) == pytest.approx(distances(want)) assert len(outer_products) == 98 + + +# Each answers with lengths, of a graph whose edges all weigh the same, so that a backend +# graph walks breadth-first and multiplies a walk's edge count by the weight. NetworkX adds +# the weights one edge at a time, which for floats can differ in the last bits. +EQUAL_WEIGHTS = { + "single_source_bellman_ford_path_length": lambda G, **kw: dict( + nx.single_source_bellman_ford_path_length(G, 0, **kw) + ), + "bellman_ford_path_length": lambda G, **kw: {13: nx.bellman_ford_path_length(G, 0, 13, **kw)}, + "all_pairs_bellman_ford_path_length": lambda G, **kw: { + (u, v): x + for u, lengths in nx.all_pairs_bellman_ford_path_length(G, **kw) + for v, x in lengths.items() + }, + "eccentricity": lambda G, **kw: nx.eccentricity(G, weight="weight", **kw), +} + + +def near(value, want): + """`want` exactly for integers, else within float64's or float32's rounding.""" + if isinstance(value, int): + return want + return pytest.approx(want, rel=1e-5 if isinstance(value, np.float32) else 1e-12) + + +@pytest.mark.parametrize("name", sorted(EQUAL_WEIGHTS)) +@pytest.mark.parametrize("value", [0.1, 0.7, 1 / 3, 3, 1e-17, np.float32(0.1), np.float32(1 / 3)]) +@pytest.mark.parametrize("directed", [False, True]) +def test_equal_weights_give_networkx_lengths(name, value, directed): + """The same nodes as NetworkX's; float lengths within rounding, integer ones exact.""" + # A directed cycle, so that every node reaches every other, as eccentricity asks. + G, H = iso(directed, value, [(i, (i + 1) % 14) for i in range(13 + directed)], 14) + want = EQUAL_WEIGHTS[name](H) + assert EQUAL_WEIGHTS[name](G) == near(value, want) + assert EQUAL_WEIGHTS[name](H, backend="graphblas") == near(value, want) + + +# No cutoff here is within rounding of a length, where NetworkX's sums and the backend's +# products could fall on either side of it. +@pytest.mark.parametrize("value", [0.1, 1 / 3, 0.0, 2, 0, np.float32(0.1)]) +@pytest.mark.parametrize("cutoff", [-1, 0, 0.35, 2.55, 7.05, 101, math.inf, None]) +@pytest.mark.parametrize("n", [14, 200]) +def test_equal_weights_end_a_walk_at_the_cutoff(value, cutoff, n): + """A node is reached when its length is within `cutoff`; the source always is.""" + from graphblas_algorithms import algorithms + + G, H = iso(False, value, [(i, i + 1) for i in range(n - 1)], n) + got = algorithms.single_source_bellman_ford_path_length(G, 0, cutoff=cutoff) + want = nx.single_source_dijkstra_path_length(H, 0, cutoff=cutoff) + assert G.vector_to_nodemap(got) == near(value, want) + + +@pytest.mark.parametrize( + ("value", "cutoff"), + # Each cutoff is the weight times an edge count, and floor division of the cutoff by the + # weight gives one edge fewer. + [(0.3, 49 * 0.3), (0.7, 131 * 0.7), (0.001, 222 * 0.001), (0.1, 481 * 0.1)], +) +def test_a_length_equal_to_the_cutoff_is_kept(value, cutoff): + """The cutoff keeps exactly the lengths within it, as the backend computes them.""" + from graphblas_algorithms import algorithms + + G, _ = iso(True, value, [(i, i + 1) for i in range(499)], 500) + every = algorithms.single_source_bellman_ford_path_length(G, 0) + got = algorithms.single_source_bellman_ford_path_length(G, 0, cutoff=cutoff) + assert cutoff in every.to_coo()[1] + assert got.isequal(select.valuele(every, cutoff).new()) + + +@pytest.mark.parametrize("weight", [math.nan, math.inf]) +@pytest.mark.parametrize("cutoff", [-1, 0, 0.5, 100, math.inf, math.nan, None]) +def test_a_nan_or_inf_weight_keeps_the_source_at_zero(weight, cutoff): + """NetworkX drops a length past `cutoff`, and NaN is past nothing.""" + from graphblas_algorithms import algorithms + + G, H = iso(False, weight, [(i, i + 1) for i in range(4)], 5) + got = dict( + G.vector_to_nodemap(algorithms.single_source_bellman_ford_path_length(G, 0, cutoff=cutoff)) + ) + want = nx.single_source_dijkstra_path_length(H, 0, cutoff=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)