From 95310fe83e251cefdf3a2729ae0153b8403efa4d Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 23:14:21 -0600 Subject: [PATCH] Add the unweighted shortest path names and predecessor single_source_shortest_path, single_target_shortest_path, all_pairs_shortest_path, shortest_path without a weight, and predecessor walk the graph a level at a time, each node taking as its parent its neighbor on the level above that is first in node order, and build NetworkX's dicts and lists from the levels. Where there are several shortest paths the one given may not be NetworkX's, which follows the order the edges were added; predecessor gives every predecessor, as NetworkX does. Errors, cutoffs and when the all-pairs generator raises are NetworkX's. A path between two nodes of a NetworkX graph is left to NetworkX, whose search from both ends costs less than converting the graph. --- README.md | 7 +- _nx_graphblas/__init__.py | 10 + _nx_graphblas/core.py | 24 + .../algorithms/shortest_paths/unweighted.py | 252 +++++++++- graphblas_algorithms/interface.py | 5 + .../nxapi/shortest_paths/generic.py | 59 ++- .../nxapi/shortest_paths/unweighted.py | 80 +++ .../nxapi/tests/test_unweighted_paths.py | 471 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 6 + 9 files changed, 909 insertions(+), 5 deletions(-) create mode 100644 graphblas_algorithms/nxapi/tests/test_unweighted_paths.py diff --git a/README.md b/README.md index 1bc06b5..988e70d 100644 --- a/README.md +++ b/README.md @@ -272,10 +272,15 @@ graphblas_algorithms.nxapi │ │ └── floyd_warshall_predecessor_and_distance │ ├── generic │ │ ├── average_shortest_path_length -│ │ └── has_path +│ │ ├── has_path +│ │ └── shortest_path │ ├── unweighted +│ │ ├── all_pairs_shortest_path │ │ ├── all_pairs_shortest_path_length +│ │ ├── predecessor +│ │ ├── single_source_shortest_path │ │ ├── single_source_shortest_path_length +│ │ ├── single_target_shortest_path │ │ └── single_target_shortest_path_length │ └── weighted │ ├── all_pairs_bellman_ford_path_length diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index f5d7b47..ff2579b 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_shortest_path", "all_pairs_shortest_path_length", "ancestors", "average_clustering", @@ -139,6 +140,7 @@ def get_info(): "pagerank", "partition_quality", "periphery", + "predecessor", "preferential_attachment", "radius", "reciprocity", @@ -147,8 +149,11 @@ def get_info(): "s_metric", "schultz_index", "score_sequence", + "shortest_path", "single_source_bellman_ford_path_length", + "single_source_shortest_path", "single_source_shortest_path_length", + "single_target_shortest_path", "single_target_shortest_path_length", "square_clustering", "symmetric_difference", @@ -191,6 +196,7 @@ def get_info(): _additional_docs = { # BEGIN: additional_docs "all_pairs_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "all_pairs_shortest_path": "Each path is a shortest path, but where there are several it may not be NetworkX's. Beside\neach node a path holds that node's neighbor one step nearer the path's fixed end (the\nsource, or the target) that is first in node order; NetworkX's holds the one its walk came\nfrom first. The nodes come by level from the fixed end, each level in node order.", "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".', "bellman_ford_path": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", "bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", @@ -225,10 +231,14 @@ def get_info(): "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', + "predecessor": "Each node's predecessors are NetworkX's, all of its neighbors one step nearer the\nsource, but in node order rather than in the order NetworkX's walk reaches them. The\nnodes come by level, each level in node order.", "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', + "shortest_path": "Unweighted: a call with `weight` is left to NetworkX, as is a path between two nodes of\na NetworkX graph, since NetworkX's search from both ends costs less than a conversion.\nEach path is a shortest path, but where there are several it may not be NetworkX's. Beside\neach node a path holds that node's neighbor one step nearer the path's fixed end (the\nsource, or the target) that is first in node order; NetworkX's holds the one its walk came\nfrom first. The nodes come by level from the fixed end, each level in node order.\nOn a graph of this backend's own, the path between two nodes joins a walk out of\neach end where they first meet, which may be at another node than NetworkX's.", "single_source_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "single_source_shortest_path": "Each path is a shortest path, but where there are several it may not be NetworkX's. Beside\neach node a path holds that node's neighbor one step nearer the path's fixed end (the\nsource, or the target) that is first in node order; NetworkX's holds the one its walk came\nfrom first. The nodes come by level from the fixed end, each level in node order.", + "single_target_shortest_path": "Each path is a shortest path, but where there are several it may not be NetworkX's. Beside\neach node a path holds that node's neighbor one step nearer the path's fixed end (the\nsource, or the target) that is first in node order; NetworkX's holds the one its walk came\nfrom first. The nodes come by level from the fixed end, each level in node order.", "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "volume": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more, or to 2**63 over the most times `S` names one node.", "wiener_index": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index 77a08ea..d059444 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -97,10 +97,20 @@ "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX." ) +# A graph can have several shortest paths between two nodes. NetworkX's choice follows the order +# each node's edges were added, which a matrix does not keep. +_ONE_SHORTEST_PATH = ( + "Each path is a shortest path, but where there are several it may not be NetworkX's. Beside\n" + "each node a path holds that node's neighbor one step nearer the path's fixed end (the\n" + "source, or the target) that is first in node order; NetworkX's holds the one its walk came\n" + "from first. The nodes come by level from the fixed end, each level in node order." +) + # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. _ADDITIONAL_DOCS = { "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, + "all_pairs_shortest_path": _ONE_SHORTEST_PATH, "average_shortest_path_length": ( 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n' 'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n' @@ -173,10 +183,24 @@ ), "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, + "predecessor": ( + "Each node's predecessors are NetworkX's, all of its neighbors one step nearer the\n" + "source, but in node order rather than in the order NetworkX's walk reaches them. The\n" + "nodes come by level, each level in node order." + ), "radius": _ECCENTRICITY_BOUNDS, "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, + "shortest_path": ( + "Unweighted: a call with `weight` is left to NetworkX, as is a path between two nodes of\n" + "a NetworkX graph, since NetworkX's search from both ends costs less than a conversion.\n" + + _ONE_SHORTEST_PATH + + "\nOn a graph of this backend's own, the path between two nodes joins a walk out of\n" + "each end where they first meet, which may be at another node than NetworkX's." + ), "single_source_bellman_ford_path_length": _PATH_OVERFLOW, + "single_source_shortest_path": _ONE_SHORTEST_PATH, + "single_target_shortest_path": _ONE_SHORTEST_PATH, "volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.", "wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW, } diff --git a/graphblas_algorithms/algorithms/shortest_paths/unweighted.py b/graphblas_algorithms/algorithms/shortest_paths/unweighted.py index 014f84a..5a2a92c 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/unweighted.py +++ b/graphblas_algorithms/algorithms/shortest_paths/unweighted.py @@ -1,15 +1,36 @@ -from graphblas import Matrix, Vector, replace +from itertools import chain + +import numpy as np +from graphblas import Matrix, Vector, binary, indexunary, replace, select, semiring from graphblas.semiring import any_pair -from .._bfs import _adjacency, _bfs_level, _bfs_levels, _visited +from .._bfs import ( + _adjacency, + _bfs_level, + _bfs_levels, + _bfs_parent_levels, + _get_cutoff, + _visited, +) from ..exceptions import NoPath __all__ = [ + "all_pairs_shortest_path", "all_pairs_shortest_path_length", + "bidirectional_shortest_path", + "predecessor", + "single_source_shortest_path", "single_source_shortest_path_length", + "single_target_shortest_path", "single_target_shortest_path_length", ] +# The ids a batch of walks in `all_pairs_shortest_path` may hold, about 16 bytes each. +_BATCH_ENTRIES = 2**20 +# The fewest nodes of a level whose paths `_paths` builds in an array (measured: a level of a +# few thousand nodes is where an array starts to cost less than a list per path). +_ARRAY_LEVEL = 4096 + def single_source_shortest_path_length(G, source, cutoff=None): return _bfs_level(G, source, cutoff=cutoff) @@ -63,3 +84,230 @@ def bidirectional_shortest_path_length(G, source, target): seen_src(q_src.S) << True raise NoPath(f"No path between {source} and {target}.") + + +def _keys_of(G): + """A function from an array of ids to an array of their nodes.""" + id_to_key = G.id_to_key + + def keys_of(ids): + # `fromiter`, so that a tuple node stays one entry. + return np.fromiter(map(id_to_key.__getitem__, ids.tolist()), dtype=object, count=len(ids)) + + return keys_of + + +def _paths(head, index, levels, keys_of, *, toward=False): + """Map each node a walk from `head` (id `index`) reaches to its path, a list of nodes. + + `levels` gives `(child_ids, parent_ids)` a level at a time, the children sorted. A child's + path is its parent's and then the child, or, with `toward` (a walk along edges backwards), + the child and then its parent's. A level of `_ARRAY_LEVEL` nodes or more is built at once + in an array, a row per path; a smaller one a path at a time, which costs less where the + levels are many and short, as in a grid. + """ + paths = {head: [head]} + prev_rows = [[head]] # the paths of the level above, as they are in `paths` + prev_array = None # the same in an array, if they were built in one + prev_ids = np.array([index]) + for child_ids, parent_ids in levels: + keys = keys_of(child_ids) + at = np.searchsorted(prev_ids, parent_ids) + if len(keys) < _ARRAY_LEVEL: + keys = keys.tolist() + pairs = zip(at.tolist(), keys, strict=True) + if toward: + rows = [[key, *prev_rows[i]] for i, key in pairs] + else: + rows = [[*prev_rows[i], key] for i, key in pairs] + array = None + else: + width = len(prev_rows[0]) + if prev_array is None: + # `fromiter`, so that a tuple node stays one entry. + prev_array = np.fromiter( + chain.from_iterable(prev_rows), dtype=object, count=len(prev_rows) * width + ).reshape(-1, width) + array = np.empty((len(keys), width + 1), dtype=object) + if toward: + array[:, 0] = keys + array[:, 1:] = prev_array[at] + else: + array[:, :width] = prev_array[at] + array[:, width] = keys + rows = array.tolist() + keys = keys.tolist() + paths.update(zip(keys, rows, strict=True)) + # The ids come unsigned and the parents signed; one type spares `searchsorted` a cast. + prev_rows, prev_array, prev_ids = rows, array, child_ids.view(np.int64) + return paths + + +def single_source_shortest_path(G, source, *, depth=None): + """A shortest path from `source` to each node at most `depth` levels away (None: any). + + A node's path is its parent's in `_bfs_parent_levels`'s tree, its neighbor on the level + above first in node order, and then the node. The nodes come by level, each level in node + order, and every path starts with `source` as given. + """ + levels = _bfs_parent_levels(G, source, cutoff=depth) + return _paths(source, G._key_to_id[source], levels, _keys_of(G)) + + +def single_target_shortest_path(G, target, *, depth=None): + """A shortest path to `target` from each node at most `depth` levels from it (None: any).""" + levels = _bfs_parent_levels(G, target, cutoff=depth, transpose=True) + return _paths(target, G._key_to_id[target], levels, _keys_of(G), toward=True) + + +def _batch_parent_levels(G, sources, depth): + """`_bfs_parent_levels` from each of `sources` at once, one row of a matrix per source. + + Gives `(bounds, child_ids, parent_ids)` per level: the children of the walk from + `sources[row]` are `child_ids[bounds[row]:bounds[row + 1]]`, sorted, with their parents. + """ + A = _adjacency(G) + n = A.nrows + k = len(sources) + rows = np.arange(k) + q = Matrix.from_coo(rows, sources, sources, dtype=int, nrows=k, ncols=n, name="q") + seen = _visited(Matrix.from_coo(rows, sources, True, nrows=k, ncols=n, name="seen")) + min_first = semiring.min_first[int] + own_index = indexunary.colindex[int] + every_row = np.arange(k + 1, dtype=np.uint64) + levels = [] + for _i in range(1, _get_cutoff(n, depth)): + q(~seen.S, replace) << min_first(q @ A) + if q.nvals == 0: + break + seen(q.S) << True + row_ids, child_ids, parent_ids = q.to_coo() + levels.append((np.searchsorted(row_ids, every_row), child_ids, parent_ids)) + q << own_index(q) + return levels + + +def _row_levels(levels, row): + for bounds, child_ids, parent_ids in levels: + start, stop = bounds[row], bounds[row + 1] + if start == stop: + return + yield child_ids[start:stop], parent_ids[start:stop] + + +def all_pairs_shortest_path(G, *, depth=None): + """Yield `(node, paths)` for each node in node order, as `single_source_shortest_path`. + + The walks are made a batch of sources at a time, so that a level is one product for the + batch; a batch holds about `_BATCH_ENTRIES` ids of the levels it reaches. A node's paths + are built when it is yielded. + """ + n = len(G) + id_to_key = G.id_to_key + names = np.fromiter(map(id_to_key.__getitem__, range(n)), dtype=object, count=n) + per_batch = max(1, _BATCH_ENTRIES // max(n, 1)) + for start in range(0, n, per_batch): + sources = np.arange(start, min(n, start + per_batch)) + levels = _batch_parent_levels(G, sources, depth) + for row, index in enumerate(sources.tolist()): + node = names[index] + yield node, _paths(node, index, _row_levels(levels, row), names.__getitem__) + + +def bidirectional_shortest_path(G, source, target): + """A shortest path from `source` to `target`, both as given, from a walk out of each. + + Each step widens the walk whose newest level is smaller. The first node one walk reaches + that the other has reached lies on a shortest path (no node was in both before the step), + which joins the two walks' trees there: its parent in each is its neighbor one level nearer + that walk's start, first in node order. Raises NoPath if either walk runs out first. + """ + src = G._key_to_id[source] + dst = G._key_to_id[target] + if src == dst: + return [source] + A = _adjacency(G) + AT = _adjacency(G, transpose=True) + n = A.nrows + parents = {} # by start: each node its walk reached, with its parent (the start, itself) + fronts = {} # by start: its walk's newest level, each node holding its own id + for start in (src, dst): + parents[start] = _visited(Vector(int, n, name="parents")) + parents[start][start] = start + fronts[start] = Vector(int, n, name="front") + fronts[start][start] = start + min_first = semiring.min_first[int] + own_index = indexunary.index[int] + while True: + start, other, M = ( + (src, dst, A) if fronts[src].nvals <= fronts[dst].nvals else (dst, src, AT) + ) + q, seen = fronts[start], parents[start] + q(~seen.S, replace) << min_first(q @ M) + if q.nvals == 0: + raise NoPath(f"No path between {source} and {target}.") + seen(q.S) << q + met = q.ewise_mult(parents[other], binary.pair).new(name="met") + if met.nvals: + [middle, *_] = met.to_coo(values=False)[0].tolist() + break + q << own_index(q) + ids = [] + node = middle + while node != src: + ids.append(node) + node = parents[src].get(node) + ids.reverse() + node = middle + while node != dst: + node = parents[dst].get(node) + ids.append(node) + # `ids` runs from the node after `src` to `dst`. + return [source, *map(G.id_to_key.__getitem__, ids[:-1]), target] + + +def predecessor(G, source, target=None, *, depth=None): + """Each node's neighbors on the level above in a walk from `source` of `depth` levels. + + On a directed graph a node's predecessors are its in-neighbors. Without `target`, gives + `(pred, seen)`: each node reached mapped to its predecessors and to its level, by level and + then in node order, each list in node order. With `target`, its predecessors and its level, + or `([], -1)` if the walk does not reach it; the walk stops at its level. `source` is given + as passed wherever it appears. + """ + index = G._key_to_id[source] + keys_of = _keys_of(G) + AT = _adjacency(G, transpose=True) + + def keys_with_source(ids): + keys = keys_of(ids) + for at in np.flatnonzero(ids == index).tolist(): + keys[at] = source # one at a time, so that a tuple stays one entry + return keys + + if target is not None: + dst = G._key_to_id[target] + reached = _bfs_level(G, source, target, cutoff=depth) + level = reached.get(dst) + if level is None: + return [], -1 + # The levels of its in-neighbors that the walk reached. + nbr_levels = reached.ewise_mult(AT[dst, :].new(name="row"), binary.first).new() + ids = select.valueeq(nbr_levels, level - 1).new().to_coo(values=False)[0] + return keys_with_source(ids).tolist(), level + reached = _bfs_level(G, source, cutoff=depth) + ids, level_of_id = reached.to_coo() + order = np.argsort(level_of_id, kind="stable") + ids, level_of_id = ids[order], level_of_id[order] + # Each node's in-neighbors, a row per node reached, kept where one level up. + rows, cols, _ = AT[ids, :].new(name="in_neighbors").to_coo(values=False) + level_of = np.full(AT.nrows, -2, dtype=level_of_id.dtype) # -2: not reached + level_of[ids] = level_of_id + above = level_of[cols] == level_of_id[rows] - 1 + bounds = np.searchsorted(rows[above], np.arange(len(ids) + 1, dtype=rows.dtype)).tolist() + keys = keys_with_source(ids).tolist() + preds = keys_with_source(cols[above]).tolist() + pred = { + key: preds[start:stop] for key, start, stop in zip(keys, bounds, bounds[1:], strict=False) + } + return pred, dict(zip(keys, level_of_id.tolist(), strict=True)) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..d4d157a 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -401,8 +401,13 @@ class Dispatcher: floyd_warshall_predecessor_and_distance = mod.dense.floyd_warshall_predecessor_and_distance average_shortest_path_length = mod.generic.average_shortest_path_length has_path = mod.generic.has_path + shortest_path = mod.generic.shortest_path + all_pairs_shortest_path = mod.unweighted.all_pairs_shortest_path all_pairs_shortest_path_length = mod.unweighted.all_pairs_shortest_path_length + predecessor = mod.unweighted.predecessor + single_source_shortest_path = mod.unweighted.single_source_shortest_path single_source_shortest_path_length = mod.unweighted.single_source_shortest_path_length + single_target_shortest_path = mod.unweighted.single_target_shortest_path 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 bellman_ford_path = mod.weighted.bellman_ford_path diff --git a/graphblas_algorithms/nxapi/shortest_paths/generic.py b/graphblas_algorithms/nxapi/shortest_paths/generic.py index cdcf0fe..a0a457a 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/generic.py +++ b/graphblas_algorithms/nxapi/shortest_paths/generic.py @@ -2,9 +2,15 @@ from graphblas_algorithms.classes.digraph import to_graph from .._utils import can_run -from ..exception import NetworkXError, NetworkXPointlessConcept, NetworkXUnbounded, NodeNotFound +from ..exception import ( + NetworkXError, + NetworkXNoPath, + NetworkXPointlessConcept, + NetworkXUnbounded, + NodeNotFound, +) -__all__ = ["average_shortest_path_length", "has_path"] +__all__ = ["average_shortest_path_length", "has_path", "shortest_path"] def has_path(G, source, target): @@ -44,3 +50,52 @@ def average_shortest_path_length(G, weight=None, method=None): raise NetworkXUnbounded("Negative cycle detected.") from e # What NetworkX's Dijkstra raises on a negative cycle. raise ValueError("Contradictory paths found:", "negative weights?") from e + + +def _served_form(bound): + # A walk by levels; NetworkX's Dijkstra and Bellman-Ford serve the weighted forms. + if bound.get("weight") is not None: + return "shortest_path is served without `weight`; networkx serves the weighted forms" + # NetworkX's search out of both ends of a pair reaches a few nodes, where a conversion costs + # every edge; on a cached conversion the walks here took longer too. A graph of this + # backend's own is served, having nothing to fall back on. + if ( + bound.get("source") is not None + and bound.get("target") is not None + and hasattr(bound.get("G"), "_adj") + ): + return ( + "networkx serves a path between two nodes of its own graph, as its search from " + "both ends costs less than a conversion" + ) + return None + + +@can_run(_served_form) +def shortest_path(G, source=None, target=None, weight=None, method="dijkstra"): + """The unweighted forms: paths that may differ from NetworkX's (see the notes).""" + if method not in ("dijkstra", "bellman-ford"): + raise ValueError(f"method not supported: {method}") + bound = {"G": G, "source": source, "target": target, "weight": weight} + if (reason := _served_form(bound)) is not None: + raise NotImplementedError(reason) + G = to_graph(G) + if source is None: + if target is None: + return algorithms.all_pairs_shortest_path(G) + # NetworkX walks out of the target on the reversed graph, so its message says "Source". + if target not in G: + raise NodeNotFound(f"Source {target} not in G") + return algorithms.single_target_shortest_path(G, target) + if target is None: + if source not in G: + raise NodeNotFound(f"Source {source} not in G") + return algorithms.single_source_shortest_path(G, source) + if source not in G: + raise NodeNotFound(f"Source {source} is not in G") + if target not in G: + raise NodeNotFound(f"Target {target} is not in G") + try: + return algorithms.bidirectional_shortest_path(G, source, target) + except algorithms.exceptions.NoPath as e: + raise NetworkXNoPath(*e.args) from e diff --git a/graphblas_algorithms/nxapi/shortest_paths/unweighted.py b/graphblas_algorithms/nxapi/shortest_paths/unweighted.py index c88baa5..2aa7a22 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/unweighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/unweighted.py @@ -1,3 +1,5 @@ +from math import ceil + from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph @@ -5,8 +7,12 @@ from ..exception import NodeNotFound __all__ = [ + "all_pairs_shortest_path", "all_pairs_shortest_path_length", + "predecessor", + "single_source_shortest_path", "single_source_shortest_path_length", + "single_target_shortest_path", "single_target_shortest_path_length", ] @@ -43,3 +49,77 @@ def all_pairs_shortest_path_length(G, cutoff=None, *, chunksize="10 MiB"): for i, source in enumerate(cur_nodes): d = D[i, :].new(name=f"all_pairs_shortest_path_length_{i}") yield (source, G.vector_to_nodemap(d)) + + +def _levels_below(cutoff, n): + """The levels NetworkX's walk takes below its start, which it widens while `cutoff > level`. + + None for every level. The first comparison is NetworkX's, so a cutoff it cannot compare + raises its TypeError. + """ + if cutoff is None: + return None + if not cutoff > 0: + return 0 + if cutoff >= n: + return None + return ceil(cutoff) + + +def _levels_through(cutoff, n): + """The levels `predecessor` walks: it stops after the first level `L` with `cutoff <= L`. + + A falsy cutoff sets no bound (None). NetworkX compares after its first level, so a cutoff it + cannot compare raises its TypeError here, and a cutoff below 1 still walks one level. + """ + if not cutoff: + return None + if cutoff <= 1: + return 1 + if not cutoff < n: # NaN never stops the walk + return None + return ceil(cutoff) + + +def single_source_shortest_path(G, source, cutoff=None): + """One shortest path to each node, which may differ from NetworkX's (see the notes).""" + G = to_graph(G) + if source not in G: + raise NodeNotFound(f"Source {source} not in G") + depth = _levels_below(cutoff, len(G)) + return algorithms.single_source_shortest_path(G, source, depth=depth) + + +def single_target_shortest_path(G, target, cutoff=None): + """One shortest path from each node, which may differ from NetworkX's (see the notes).""" + G = to_graph(G) + if target not in G: + raise NodeNotFound(f"Target {target} not in G") + depth = _levels_below(cutoff, len(G)) + return algorithms.single_target_shortest_path(G, target, depth=depth) + + +def all_pairs_shortest_path(G, cutoff=None): + """`single_source_shortest_path` from each node in turn, lazily, as NetworkX's generator.""" + G = to_graph(G) + if len(G) == 0: + return # NetworkX reads `cutoff` per source, so a graph with none never does + depth = _levels_below(cutoff, len(G)) + yield from algorithms.all_pairs_shortest_path(G, depth=depth) + + +def predecessor(G, source, target=None, cutoff=None, return_seen=None): + """All of each node's predecessors, as NetworkX's, which may list them in another order.""" + G = to_graph(G) + if source not in G: + raise NodeNotFound(f"Source {source} not in G") + depth = _levels_through(cutoff, len(G)) + if target is None: + pred, seen = algorithms.predecessor(G, source, depth=depth) + return (pred, seen) if return_seen else pred + # NetworkX looks `target` up in a dict, which raises TypeError for an unhashable one. + if target in G._key_to_id: + preds, level = algorithms.predecessor(G, source, target, depth=depth) + else: + preds, level = [], -1 + return (preds, level) if return_seen else preds diff --git a/graphblas_algorithms/nxapi/tests/test_unweighted_paths.py b/graphblas_algorithms/nxapi/tests/test_unweighted_paths.py new file mode 100644 index 0000000..a136abd --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_unweighted_paths.py @@ -0,0 +1,471 @@ +"""The unweighted shortest-path names and `predecessor` against NetworkX. + +A graph can have several shortest paths between two nodes, and NetworkX's choice follows the +order each node's edges were added, which a matrix does not keep. So these tests check that each +path is a shortest path in the graph, between the nodes NetworkX gives, with NetworkX's length, +and not which one it is; `predecessor`'s lists are compared as sets. Errors, cutoffs and when +`all_pairs_shortest_path` raises are NetworkX's exactly. +""" + +import math +from collections.abc import Iterator +from itertools import pairwise + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms.shortest_paths import unweighted +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +CUTOFFS = [None, 0, 1, 2, 3, 1.5, 2.5, -1, -0.5, math.nan, math.inf, True, False, 100] + + +def ours(name, *args, **kwargs): + return getattr(nx, name)(*args, **kwargs, backend="graphblas") + + +def theirs(name, *args, **kwargs): + return getattr(nx, name)(*args, **kwargs, backend="networkx") + + +def outcome(name, *args, backend, **kwargs): + """`("value", result)`, or `("raises", type, message)` for what the call raised.""" + try: + return "value", getattr(nx, name)(*args, **kwargs, backend=backend) + except Exception as exc: + return "raises", type(exc), str(exc) + + +def assert_path(G, path, first, last, length): + """`path` is a list of `length` edges of `G` from `first` to `last`.""" + assert type(path) is list + assert len(path) == length + 1 + assert path[0] == first + assert path[-1] == last + for u, v in pairwise(path): + assert G.has_edge(u, v), (path, u, v) + + +def assert_paths_from(G, got, want, source): + """`got` maps NetworkX's nodes to a shortest path from `source`, of NetworkX's length.""" + assert type(got) is dict + assert got.keys() == want.keys() + for node, path in got.items(): + assert_path(G, path, source, node, len(want[node]) - 1) + + +def assert_paths_to(G, got, want, target): + assert type(got) is dict + assert got.keys() == want.keys() + for node, path in got.items(): + assert_path(G, path, node, target, len(want[node]) - 1) + + +def assert_predecessors(got, want): + """Each node's predecessors: NetworkX's, each once, in any order.""" + assert type(got) is dict + assert got.keys() == want.keys() + for node, preds in got.items(): + assert type(preds) is list + assert len(preds) == len(set(preds)) + assert set(preds) == set(want[node]), node + + +def assert_levels(got, want): + assert type(got) is dict + assert got == want + assert all(type(level) is int for level in got.values()) + + +def random_graph(seed): + """A random graph: directed or not, in pieces, with self-loops, isolated nodes and labels. + + The nodes are added in a shuffled order, so that node order is not the order of the labels. + """ + rng = np.random.default_rng(seed) + n = int(rng.integers(1, 26)) + G = nx.DiGraph() if seed % 2 else nx.Graph() + labels = [ + list(range(n)), + [f"n{i}" for i in range(n)], + [(i, "t") for i in range(n)], + [i if i % 3 else f"s{i}" for i in range(n)], + ][seed // 2 % 4] + order = rng.permutation(n) + G.add_nodes_from(labels[i] for i in order) + p = float(rng.choice([0.03, 0.08, 0.15, 0.3])) + loops = rng.random() < 0.5 + for i in range(n): + for j in range(n): + if (i != j or loops) and rng.random() < p: + G.add_edge(labels[i], labels[j]) + nodes = list(G) + sources = [nodes[int(i)] for i in rng.integers(0, n, size=min(n, 3))] + cutoff = CUTOFFS[int(rng.integers(0, len(CUTOFFS)))] + return G, sources, cutoff + + +SEEDS = range(320) + + +@pytest.mark.parametrize("seed", SEEDS) +def test_random_graphs(seed): + G, sources, cutoff = random_graph(seed) + for source in sources: + for kw in [{}, {"cutoff": cutoff}]: + want = theirs("single_source_shortest_path", G, source, **kw) + assert_paths_from(G, ours("single_source_shortest_path", G, source, **kw), want, source) + want = theirs("single_target_shortest_path", G, source, **kw) + assert_paths_to(G, ours("single_target_shortest_path", G, source, **kw), want, source) + pred, seen = theirs("predecessor", G, source, return_seen=True, **kw) + got = ours("predecessor", G, source, return_seen=True, **kw) + assert type(got) is tuple + assert_predecessors(got[0], pred) + assert_levels(got[1], seen) + assert_predecessors(ours("predecessor", G, source, **kw), pred) + for target in [*sources, *list(G)[:4]]: + want = theirs("predecessor", G, source, target, return_seen=True, **kw) + got = ours("predecessor", G, source, target, return_seen=True, **kw) + assert type(got) is tuple + assert_predecessors({target: got[0]}, {target: want[0]}) + assert type(got[1]) is int + assert got[1] == want[1] + got = ours("predecessor", G, source, target, **kw) + assert_predecessors({target: got}, {target: want[0]}) + want = theirs("shortest_path", G, source=source) + assert_paths_from(G, ours("shortest_path", G, source=source), want, source) + want = theirs("shortest_path", G, target=source) + assert_paths_to(G, ours("shortest_path", G, target=source), want, source) + B = Dispatcher.convert_from_nx(G) # a pair of a NetworkX graph is left to NetworkX + for target in G: + want = outcome("shortest_path", G, source, target, backend="networkx") + got = outcome("shortest_path", B, source, target, backend=None) + if want[0] == "raises": + assert got == want # NetworkXNoPath + else: + assert got[0] == "value" + assert_path(G, got[1], source, target, len(want[1]) - 1) + want = dict(theirs("all_pairs_shortest_path", G, cutoff=cutoff)) + got = ours("all_pairs_shortest_path", G, cutoff=cutoff) + assert isinstance(got, Iterator) + got = list(got) + assert [node for node, _paths in got] == list(want) + for source, paths in got: + assert_paths_from(G, paths, want[source], source) + want = dict(theirs("shortest_path", G)) + got = ours("shortest_path", G) + assert isinstance(got, Iterator) + got = list(got) + assert [node for node, _paths in got] == list(want) + for source, paths in got: + assert_paths_from(G, paths, want[source], source) + + +def test_random_graphs_with_small_batches(monkeypatch): + """`all_pairs_shortest_path` in batches of a few sources gives the same paths.""" + for seed in range(40): + G, _, cutoff = random_graph(seed) + want = dict(theirs("all_pairs_shortest_path", G, cutoff=cutoff)) + for entries in [1, 7, 30]: + monkeypatch.setattr(unweighted, "_BATCH_ENTRIES", entries) + got = list(ours("all_pairs_shortest_path", G, cutoff=cutoff)) + assert [node for node, _paths in got] == list(want) + for source, paths in got: + assert_paths_from(G, paths, want[source], source) + + +@pytest.mark.parametrize("fewest", [1, 2, 5]) +def test_paths_built_in_arrays(monkeypatch, fewest): + """Levels of `fewest` nodes or more are built in arrays, the others a path at a time.""" + monkeypatch.setattr(unweighted, "_ARRAY_LEVEL", fewest) + for seed in range(0, 320, 3): + G, sources, cutoff = random_graph(seed) + for source in sources: + want = theirs("single_source_shortest_path", G, source, cutoff=cutoff) + got = ours("single_source_shortest_path", G, source, cutoff=cutoff) + assert_paths_from(G, got, want, source) + want = theirs("single_target_shortest_path", G, source, cutoff=cutoff) + got = ours("single_target_shortest_path", G, source, cutoff=cutoff) + assert_paths_to(G, got, want, source) + want = dict(theirs("all_pairs_shortest_path", G, cutoff=cutoff)) + got = list(ours("all_pairs_shortest_path", G, cutoff=cutoff)) + assert [node for node, _paths in got] == list(want) + for source, paths in got: + assert_paths_from(G, paths, want[source], source) + + +def two_routes(): + """0 reaches 3 through 1 and through 2; 4 hangs off 3, and 5 is apart.""" + G = nx.Graph([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)]) + G.add_node(5) + return G + + +def two_routes_directed(): + G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)]) + G.add_node(5) + return G + + +# Each name's call with `node` where a node goes: (name, args after the graph, kwargs). +ABSENT = { + "single_source_shortest_path": lambda node: ("single_source_shortest_path", (node,), {}), + "single_target_shortest_path": lambda node: ("single_target_shortest_path", (node,), {}), + "predecessor": lambda node: ("predecessor", (node,), {}), + "predecessor with a target": lambda node: ("predecessor", (node, 0), {}), + "predecessor of the node": lambda node: ("predecessor", (0, node), {"return_seen": True}), + "shortest_path from": lambda node: ("shortest_path", (), {"source": node}), + "shortest_path to": lambda node: ("shortest_path", (), {"target": node}), + "shortest_path pair from": lambda node: ("shortest_path", (node, 0), {}), + "shortest_path pair to": lambda node: ("shortest_path", (0, node), {}), + "shortest_path pair from and to": lambda node: ("shortest_path", (node, "absent"), {}), +} + + +@pytest.mark.parametrize("case", sorted(ABSENT)) +@pytest.mark.parametrize("node", [9, "absent", [1], None, (0,)], ids=repr) +@pytest.mark.parametrize("make", [two_routes, two_routes_directed]) +def test_absent_nodes_as_networkx(case, node, make): + """NetworkX's error and message, or its answer (`predecessor` of an absent target is []).""" + G = make() + name, args, kwargs = ABSENT[case](node) + if node is None and name == "shortest_path" and "absent" not in args: + return # None is no node to shortest_path, but "every node" (tested above) + want = outcome(name, G, *args, backend="networkx", **kwargs) + if "pair" in case: + # A pair of a NetworkX graph is left to NetworkX; the backend's own graph is served. + got = outcome(name, Dispatcher.convert_from_nx(G), *args, backend=None, **kwargs) + else: + got = outcome(name, G, *args, backend="graphblas", **kwargs) + if want[0] == "value" and want[1] != ([], -1): + # The whole of `predecessor`'s answer, its lists in any order. + assert got[0] == "value" + assert_predecessors(got[1][0], want[1][0]) + assert_levels(got[1][1], want[1][1]) + return + assert got == want + + +@pytest.mark.parametrize( + "name", ["single_source_shortest_path", "single_target_shortest_path", "predecessor"] +) +@pytest.mark.parametrize("cutoff", [*CUTOFFS, "a", [], [1], 7.0, -math.inf]) +@pytest.mark.parametrize("make", [two_routes, two_routes_directed]) +def test_cutoffs_as_networkx_reads_them(name, cutoff, make): + """Which levels a cutoff reaches, and the TypeError for one NetworkX cannot compare.""" + G = make() + want = outcome(name, G, 0, cutoff=cutoff, backend="networkx") + got = outcome(name, G, 0, cutoff=cutoff, backend="graphblas") + if want[0] == "raises": + assert got == want # TypeError + return + assert got[0] == "value" + got, want = got[1], want[1] + if name == "predecessor": + assert_predecessors(got, want) + elif name == "single_source_shortest_path": + assert_paths_from(G, got, want, 0) + else: + assert_paths_to(G, got, want, 0) + + +def test_an_absent_node_is_checked_before_the_cutoff(): + G = two_routes() + for name in ["single_source_shortest_path", "single_target_shortest_path", "predecessor"]: + with pytest.raises(nx.NodeNotFound): + ours(name, G, 9, cutoff="a") + + +def test_predecessor_reads_the_cutoff_before_the_target(): + G = two_routes() + with pytest.raises(TypeError, match="'<=' not supported"): + ours("predecessor", G, 0, [1], cutoff="a") + with pytest.raises(TypeError) as info: + ours("predecessor", G, 0, [1]) + with pytest.raises(TypeError) as want: + theirs("predecessor", G, 0, [1]) + assert str(info.value) == str(want.value) + + +@pytest.mark.parametrize("make", [two_routes, two_routes_directed]) +def test_all_pairs_raises_when_networkx_does(make): + """Nothing is read until the first pair is asked for, as in NetworkX's generator.""" + G = make() + got = ours("all_pairs_shortest_path", G, cutoff="a") + want = theirs("all_pairs_shortest_path", G, cutoff="a") + assert isinstance(got, Iterator) + with pytest.raises(TypeError) as exc: + next(want) + with pytest.raises(TypeError) as info: + next(got) + assert str(info.value) == str(exc.value) + # A graph without nodes has no source to read the cutoff for. + assert list(ours("all_pairs_shortest_path", nx.Graph(), cutoff="a")) == [] + assert list(ours("shortest_path", nx.Graph())) == [] + + +def test_all_pairs_holds_one_batch(monkeypatch): + """The walks are made a batch at a time, the next batch when its first node is asked for.""" + batches = [] + real = unweighted._batch_parent_levels + + def counted(G, sources, depth): + batches.append(sources.tolist()) + return real(G, sources, depth) + + monkeypatch.setattr(unweighted, "_batch_parent_levels", counted) + monkeypatch.setattr(unweighted, "_BATCH_ENTRIES", 12) + G = nx.path_graph(6) + got = ours("all_pairs_shortest_path", G) + assert batches == [] + next(got) + assert batches == [[0, 1]] + next(got) + assert batches == [[0, 1]] + next(got) + assert batches == [[0, 1], [2, 3]] + + +@pytest.mark.parametrize("name", ["single_source_shortest_path", "predecessor"]) +def test_the_source_is_kept_as_given(name): + """NetworkX's paths and keys hold the source object passed, such as 1.0 for node 1.""" + G = nx.path_graph(4) + got = ours(name, G, 1.0) + want = theirs(name, G, 1.0) + assert {(key, type(key)) for key in got} == {(key, type(key)) for key in want} + if name == "predecessor": + assert {type(node) for preds in got.values() for node in preds} == { + type(node) for preds in want.values() for node in preds + } + else: + assert all(type(path[0]) is float for path in got.values()) + B = Dispatcher.convert_from_nx(G) + assert type(nx.shortest_path(B, 1.0, 3)[0]) is float + assert type(nx.shortest_path(B, 1, 3.0)[-1]) is float + + +@pytest.mark.parametrize("make", [two_routes, two_routes_directed]) +def test_both_routes_count_as_predecessors(make): + G = make() + pred, seen = ours("predecessor", G, 0, return_seen=True) + assert_predecessors(pred, {0: [], 1: [0], 2: [0], 3: [1, 2], 4: [3]}) + assert_levels(seen, {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}) + assert sorted(ours("predecessor", G, 0, 3)) == [1, 2] + assert ours("predecessor", G, 0, 3, return_seen=True)[1] == 2 + assert ours("predecessor", G, 0, 5, return_seen=True) == ([], -1) + assert ours("predecessor", G, 0, 0, return_seen=True) == ([], 0) + assert ours("predecessor", G, 0, 4, cutoff=2, return_seen=True) == ([], -1) + assert ours("predecessor", G, 0, "absent", return_seen=True) == ([], -1) + assert nx.shortest_path(Dispatcher.convert_from_nx(G), 0, 4) in ([0, 1, 3, 4], [0, 2, 3, 4]) + + +def test_shortest_path_with_weight_is_left_to_networkx(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (0, 2, 5)]) + bound = {"G": G, "weight": "weight"} + assert isinstance(Dispatcher.can_run("shortest_path", (G,), {"weight": "weight"}), str) + assert nxapi.shortest_path._can_run(bound) is not None + with pytest.raises(NotImplementedError, match="without `weight`"): + nxapi.shortest_path(G, 0, weight="weight") + with nx.config.backend_priority(algos=["graphblas"]), nx.config(fallback_to_nx=False): + assert nx.shortest_path(G, 0, weight="weight")[2] == [0, 1, 2] + assert nx.shortest_path(G, 0)[2] == [0, 2] + assert Dispatcher.can_run("shortest_path", (G,), {}) is True + + +def test_a_pair_of_a_networkx_graph_is_left_to_networkx(): + """NetworkX's search from both ends costs less than a conversion; its answer is given.""" + G = two_routes() + B = Dispatcher.convert_from_nx(G) + assert isinstance(Dispatcher.can_run("shortest_path", (G, 0, 4), {}), str) + assert isinstance(Dispatcher.can_run("shortest_path", (G,), {"source": 0, "target": 4}), str) + assert Dispatcher.can_run("shortest_path", (B, 0, 4), {}) is True + assert Dispatcher.can_run("shortest_path", (G, 0), {}) is True + assert Dispatcher.can_run("shortest_path", (G,), {"target": 4}) is True + with pytest.raises(NotImplementedError, match="between two nodes"): + nxapi.shortest_path(G, 0, 4) + with nx.config.backend_priority(algos=["graphblas"]), nx.config(fallback_to_nx=False): + assert nx.shortest_path(G, 0, 4) == theirs("shortest_path", G, 0, 4) + assert_path(G, nxapi.shortest_path(B, 0, 4), 0, 4, 3) + + +@pytest.mark.parametrize("weight", [None, "weight"]) +@pytest.mark.parametrize("method", ["unweighted", "bad", "dijkstra", "bellman-ford"]) +@pytest.mark.parametrize("pair", [False, True]) +def test_shortest_path_methods(method, weight, pair): + """An unknown method raises NetworkX's ValueError; a weight is left to NetworkX.""" + G = two_routes() + ends = (0, 4) if pair else (0,) + kwargs = {"weight": weight, "method": method} + want = outcome("shortest_path", G, *ends, backend="networkx", **kwargs) + with nx.config.backend_priority(algos=["graphblas"]), nx.config(fallback_to_nx=False): + got = outcome("shortest_path", G, *ends, backend=None, **kwargs) + if want[0] == "raises": + assert got == want + if weight is None: + B = Dispatcher.convert_from_nx(G) + assert outcome("shortest_path", B, *ends, backend=None, **kwargs) == want + return + assert got[0] == "value" + if pair: + assert_path(G, got[1], 0, 4, len(want[1]) - 1) + else: + assert_paths_from(G, got[1], want[1], 0) + + +@pytest.mark.parametrize("make", [two_routes, two_routes_directed]) +def test_no_path_between_a_pair(make): + G = make() + B = Dispatcher.convert_from_nx(G) + want = outcome("shortest_path", G, 4, 5, backend="networkx") + assert want[:2] == ("raises", nx.NetworkXNoPath) + assert outcome("shortest_path", B, 4, 5, backend=None) == want + assert nx.shortest_path(B, 5, 5) == [5] + + +def test_backend_graph_input(): + """A converted graph is served for every name, with nothing to fall back on.""" + G = two_routes_directed() + B = Dispatcher.convert_from_nx(G) + assert_paths_from( + G, nx.single_source_shortest_path(B, 0), theirs("single_source_shortest_path", G, 0), 0 + ) + assert_paths_to( + G, nx.single_target_shortest_path(B, 4), theirs("single_target_shortest_path", G, 4), 4 + ) + assert_predecessors(nx.predecessor(B, 0), theirs("predecessor", G, 0)) + assert_path(G, nx.shortest_path(B, 0, 4), 0, 4, 3) + assert dict(nx.all_pairs_shortest_path(B)).keys() == set(G) + + +@pytest.mark.parametrize( + "make", + [ + lambda: nx.grid_2d_graph(6, 7), + lambda: nx.gnm_random_graph(300, 900, seed=3), + lambda: nx.gnm_random_graph(300, 700, seed=4, directed=True), + lambda: nx.barbell_graph(5, 6), + ], +) +def test_larger_graphs(make): + G = make() + B = Dispatcher.convert_from_nx(G) + nodes = list(G) + for source in nodes[::37]: + want = theirs("single_source_shortest_path", G, source) + assert_paths_from(G, ours("single_source_shortest_path", G, source), want, source) + want = theirs("single_target_shortest_path", G, source) + assert_paths_to(G, ours("single_target_shortest_path", G, source), want, source) + assert_predecessors(ours("predecessor", G, source), theirs("predecessor", G, source)) + for target in nodes[::53]: + want = outcome("shortest_path", G, source, target, backend="networkx") + got = outcome("shortest_path", B, source, target, backend=None) + if want[0] == "raises": + assert got == want + else: + assert got[0] == "value" + assert_path(G, got[1], source, target, len(want[1]) - 1) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..5799388 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_shortest_path": ("undirected", ()), "all_pairs_shortest_path_length": ("undirected", ()), "ancestors": ("dag", (3,)), "average_clustering": ("undirected", ()), @@ -186,6 +187,7 @@ def call_args(kind, args): "pagerank": ("undirected", ()), "partition_quality": ("undirected", ([{0, 1}, {2, 3, 4}],)), "periphery": ("tournament", ()), + "predecessor": ("undirected", (0,)), "preferential_attachment": ("undirected", ([(0, 1), (0, 4)],)), "radius": ("tournament", ()), "reciprocity": ("directed", ()), @@ -196,8 +198,12 @@ def call_args(kind, args): "s_metric": ("undirected", ()), "schultz_index": ("undirected", ()), "score_sequence": ("tournament", ()), + # A path between two nodes of a NetworkX graph is left to NetworkX (`can_run`). + "shortest_path": ("undirected", (0,)), "single_source_bellman_ford_path_length": ("undirected", (0,)), + "single_source_shortest_path": ("undirected", (0,)), "single_source_shortest_path_length": ("undirected", (0,)), + "single_target_shortest_path": ("undirected", (0,)), "single_target_shortest_path_length": ("undirected", (0,)), "square_clustering": ("undirected", ()), "symmetric_difference": ("plain", (SECOND,)),