From 94558a93130cf601a6dcdfaefb8f54767ae7b296 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Thu, 3 Dec 2026 01:30:29 -0600 Subject: [PATCH] Add edge_bfs, bfs_tree, bfs_predecessors and bfs_labeled_edges edge_bfs yields every edge that a breadth-first walk from the given nodes reaches, each once. The walk goes a level at a time with any_pair products over the out-edges, over the in-edges for orientation="reverse", or over both for "ignore". Each node reached then gives its row of the adjacency, or of its transpose, gathered in NumPy. NetworkX walks each node's edges in Python and, on an undirected graph, builds a frozenset for each edge to see it once. The edges are NetworkX's, and so are their orientations wherever the walk fixes them: an undirected edge, or with "ignore" a directed one, comes from the end the walk meets first, labelled "forward" from its tail and "reverse" from its head. The order is breadth-first but this backend's own: the nodes of source first, as given, then each level in node order, each node's edges in the node order of their other ends, out-edges before in-edges. So between two nodes at one depth the direction or label may differ from NetworkX's. source is read as NetworkX reads an nbunch, with its errors. An orientation other than None, "original", "reverse" or "ignore" raises NetworkXError where NetworkX raises it: on a directed graph, once source names a node. Errors come when the first edge is asked for, as from NetworkX's generator. All three walk as bfs_edges does: each node's parent is its neighbor on the level above that comes first in node order, so the tree may differ from NetworkX's. For this backend's graph, bfs_tree returns this backend's DiGraph, whose nodes are the source, as given, then each level in node order. For a NetworkX graph it returns NetworkX's DiGraph, built from those edges as NetworkX builds it, so a NetworkX caller gets the graph it would have had. bfs_predecessors yields the tree's parents, with NetworkX's DeprecationWarning where NetworkX gives one. bfs_labeled_edges labels each edge by the depths of its ends, and walks only as far as the edges read need, a part at a time, as NetworkX's generator does. Several sources are walked in the order given, so a node one step from two of them is the child of the first, and the first edge into each node is its tree edge. Each conversion now records, weakly, the NetworkX graph it was made from; bfs_tree reads that record to tell a conversion from this backend's own graph. A conversion copied along with its graph (deepcopy or pickle) has no record, so bfs_tree by name on such a copy returns this backend's DiGraph. A graph of this backend's is served without a conversion, as is a call by name. On the automatic path a NetworkX graph goes to NetworkX where converting it costs more than the walk. bfs_predecessors is served where the graph is converted either way: a conversion of it is cached, or this backend serves bfs_edges, which NetworkX's own version calls. bfs_tree is left to NetworkX, whose own version builds the same DiGraph from the bfs_edges its priority names; building it costs the same here, and a deep graph's walk costs more. bfs_labeled_edges is left to NetworkX too, whose girth reads a few edges from every node. Dispatcher.should_run takes each wrapper's rule, as can_run does. A depth limit of -inf or NaN now walks no level, as in NetworkX, where bfs_edges and bfs_successors raised OverflowError or TypeError. edge_bfs cached the node keys under the name the components and core names use for a pair of arrays, so calling one after the other on the same graph failed. It now reads that pair. --- README.md | 15 +- _nx_graphblas/__init__.py | 12 +- _nx_graphblas/core.py | 47 +- .../algorithms/traversal/__init__.py | 1 + .../traversal/breadth_first_search.py | 148 +++- .../algorithms/traversal/edgebfs.py | 106 +++ graphblas_algorithms/classes/_utils.py | 16 + graphblas_algorithms/interface.py | 25 + graphblas_algorithms/nxapi/_utils.py | 14 + .../nxapi/tests/test_bfs_riders.py | 757 ++++++++++++++++++ .../nxapi/tests/test_edge_bfs.py | 307 +++++++ .../nxapi/traversal/__init__.py | 1 + .../nxapi/traversal/breadth_first_search.py | 180 ++++- .../nxapi/traversal/edgebfs.py | 47 ++ graphblas_algorithms/tests/_dispatched.py | 4 + graphblas_algorithms/tests/test_dispatch.py | 5 +- graphblas_algorithms/tests/test_match_nx.py | 18 +- 17 files changed, 1686 insertions(+), 17 deletions(-) create mode 100644 graphblas_algorithms/algorithms/traversal/edgebfs.py create mode 100644 graphblas_algorithms/nxapi/tests/test_bfs_riders.py create mode 100644 graphblas_algorithms/nxapi/tests/test_edge_bfs.py create mode 100644 graphblas_algorithms/nxapi/traversal/edgebfs.py diff --git a/README.md b/README.md index 1bc06b5..6c04913 100644 --- a/README.md +++ b/README.md @@ -294,11 +294,16 @@ graphblas_algorithms.nxapi │ ├── score_sequence │ └── tournament_matrix ├── traversal -│ └── breadth_first_search -│ ├── bfs_edges -│ ├── bfs_layers -│ ├── bfs_successors -│ └── descendants_at_distance +│ ├── breadth_first_search +│ │ ├── bfs_edges +│ │ ├── bfs_labeled_edges +│ │ ├── bfs_layers +│ │ ├── bfs_predecessors +│ │ ├── bfs_successors +│ │ ├── bfs_tree +│ │ └── descendants_at_distance +│ └── edgebfs +│ └── edge_bfs ├── tree │ └── recognition │ ├── is_arborescence diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index f5d7b47..d604cf6 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -42,8 +42,11 @@ def get_info(): "betweenness_centrality", "betweenness_centrality_subset", "bfs_edges", + "bfs_labeled_edges", "bfs_layers", + "bfs_predecessors", "bfs_successors", + "bfs_tree", "boundary_expansion", "center", "closeness_centrality", @@ -65,6 +68,7 @@ def get_info(): "eccentricity", "edge_betweenness_centrality", "edge_betweenness_centrality_subset", + "edge_bfs", "edge_boundary", "edge_expansion", "efficiency", @@ -196,8 +200,11 @@ def get_info(): "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.", "betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.", "betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.", - "bfs_edges": "A breadth-first tree with NetworkX's nodes and depths, which may differ from NetworkX's\ntree, as may the order: a node's parent is its neighbor on the level above first in\nnode order, and the edges come level by level, each level by child in node order. A\nparent's children need not come together. `sort_neighbors` is left to NetworkX.", - "bfs_successors": "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order:\nlevel by level, each level's parents in node order. `sort_neighbors` is left to NetworkX.", + "bfs_edges": 'A breadth-first tree with NetworkX\'s nodes and depths, which may differ from NetworkX\'s\ntree, as may the order: a node\'s parent is its neighbor on the level above first in\nnode order, and the edges come level by level, each level by child in node order. A\nparent\'s children need not come together.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.', + "bfs_labeled_edges": "NetworkX's edges and labels, from `bfs_edges`'s tree, so which edges are tree edges and\nwhich forward edges may differ from NetworkX's, as may the direction of an undirected\nlevel edge and the order: the sources first, then each level in node order, each\nnode's edges by the other end's node order. Served for this backend's graphs; a\nNetworkX graph is left to NetworkX, which is faster than converting it, and faster too\nwhere a caller reads a few edges from many sources, as `girth` does.", + "bfs_predecessors": 'The parents in `bfs_edges`\'s tree, which may differ from NetworkX\'s, in its order, with\nNetworkX\'s DeprecationWarning where NetworkX gives one.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.\nA NetworkX graph is served where it is converted either way: where a conversion of it is\ncached, or where this backend serves `bfs_edges`, which NetworkX\'s own version calls.\nElsewhere it is left to NetworkX, which is faster than converting it.', + "bfs_successors": 'The children in `bfs_edges`\'s tree, which may differ from NetworkX\'s, as may the order:\nlevel by level, each level\'s parents in node order.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.', + "bfs_tree": '`bfs_edges`\'s tree, which may differ from NetworkX\'s: the source, then each level\'s\nnodes in node order. For this backend\'s graph it is this backend\'s DiGraph; for a\nNetworkX graph, NetworkX\'s DiGraph, built as NetworkX builds it.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.\nServed for this backend\'s graphs and with `backend="graphblas"`. On the automatic\npath a NetworkX graph is left to NetworkX, whose own `bfs_tree` walks with the\n`bfs_edges` its priority names, this backend\'s included: building NetworkX\'s DiGraph\ncosts the same either way, and a deep graph\'s walk costs more here.', "center": '`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.', "closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", @@ -208,6 +215,7 @@ def get_info(): "eccentricity": 'A precomputed `sp`, and the null graph, are 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.', "edge_betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\nThe edges come by their first ends in node order, then by their second ends in node\norder, which may differ from the order of `G.edges()`.", "edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.", + "edge_bfs": 'Each edge NetworkX yields, once, with NetworkX\'s orientation where it is fixed, in a\nbreadth-first order that may differ from NetworkX\'s: the nodes in `source` first, then\neach level by node order, each node\'s edges by the other end\'s node order, out-edges\nbefore in-edges. An undirected edge, or with `orientation="ignore"` a directed one,\ncomes from the end met first, so between two nodes at one depth its direction or label\nmay differ.', "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nEdge 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.', "floyd_warshall": "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.", "floyd_warshall_predecessor_and_distance": "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.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index 77a08ea..e590d20 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -97,6 +97,16 @@ "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX." ) +_CONVERTED_EITHER_WAY = ( + "A NetworkX graph is served where it is converted either way: where a conversion of it is\n" + "cached, or where this backend serves `bfs_edges`, which NetworkX's own version calls.\n" + "Elsewhere it is left to NetworkX, which is faster than converting it." +) +_SORT_NEIGHBORS = ( + "`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\n" + 'backend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.' +) + # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. _ADDITIONAL_DOCS = { @@ -117,11 +127,36 @@ "A breadth-first tree with NetworkX's nodes and depths, which may differ from NetworkX's\n" "tree, as may the order: a node's parent is its neighbor on the level above first in\n" "node order, and the edges come level by level, each level by child in node order. A\n" - "parent's children need not come together. `sort_neighbors` is left to NetworkX." + "parent's children need not come together.\n" + _SORT_NEIGHBORS + ), + "bfs_labeled_edges": ( + "NetworkX's edges and labels, from `bfs_edges`'s tree, so which edges are tree edges and\n" + "which forward edges may differ from NetworkX's, as may the direction of an undirected\n" + "level edge and the order: the sources first, then each level in node order, each\n" + "node's edges by the other end's node order. Served for this backend's graphs; a\n" + "NetworkX graph is left to NetworkX, which is faster than converting it, and faster too\n" + "where a caller reads a few edges from many sources, as `girth` does." + ), + "bfs_predecessors": ( + "The parents in `bfs_edges`'s tree, which may differ from NetworkX's, in its order, with\n" + "NetworkX's DeprecationWarning where NetworkX gives one.\n" + + _SORT_NEIGHBORS + + "\n" + + _CONVERTED_EITHER_WAY ), "bfs_successors": ( "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order:\n" - "level by level, each level's parents in node order. `sort_neighbors` is left to NetworkX." + "level by level, each level's parents in node order.\n" + _SORT_NEIGHBORS + ), + "bfs_tree": ( + "`bfs_edges`'s tree, which may differ from NetworkX's: the source, then each level's\n" + "nodes in node order. For this backend's graph it is this backend's DiGraph; for a\n" + "NetworkX graph, NetworkX's DiGraph, built as NetworkX builds it.\n" + + _SORT_NEIGHBORS + + '\nServed for this backend\'s graphs and with `backend="graphblas"`. On the automatic\n' + "path a NetworkX graph is left to NetworkX, whose own `bfs_tree` walks with the\n" + "`bfs_edges` its priority names, this backend's included: building NetworkX's DiGraph\n" + "costs the same either way, and a deep graph's walk costs more here." ), "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, @@ -144,6 +179,14 @@ "in node order, then by their second ends in node order, which may differ from the order\n" "of `G.edges()`." ), + "edge_bfs": ( + "Each edge NetworkX yields, once, with NetworkX's orientation where it is fixed, in a\n" + "breadth-first order that may differ from NetworkX's: the nodes in `source` first, then\n" + "each level by node order, each node's edges by the other end's node order, out-edges\n" + 'before in-edges. An undirected edge, or with `orientation="ignore"` a directed one,\n' + "comes from the end met first, so between two nodes at one depth its direction or label\n" + "may differ." + ), "ego_graph": ( "With `distance`, lengths are Bellman-Ford's, so a negative edge without a negative\n" 'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\n' diff --git a/graphblas_algorithms/algorithms/traversal/__init__.py b/graphblas_algorithms/algorithms/traversal/__init__.py index 7811162..055970d 100644 --- a/graphblas_algorithms/algorithms/traversal/__init__.py +++ b/graphblas_algorithms/algorithms/traversal/__init__.py @@ -1 +1,2 @@ from .breadth_first_search import * +from .edgebfs import * diff --git a/graphblas_algorithms/algorithms/traversal/breadth_first_search.py b/graphblas_algorithms/algorithms/traversal/breadth_first_search.py index 1740e32..7682ab6 100644 --- a/graphblas_algorithms/algorithms/traversal/breadth_first_search.py +++ b/graphblas_algorithms/algorithms/traversal/breadth_first_search.py @@ -1,20 +1,33 @@ from math import ceil import numpy as np -from graphblas import Vector, replace +from graphblas import Matrix, Vector, indexunary, replace, semiring from graphblas.semiring import any_pair -from .._bfs import _bfs_parent_levels, _visited +from graphblas_algorithms.classes.digraph import DiGraph + +from .._bfs import _adjacency, _bfs_parent_levels, _visited +from ..components._labels import _keys_by_id +from .edgebfs import _csr, _rows __all__ = [ "bfs_edges", + "bfs_labeled_edges", "bfs_layers", + "bfs_predecessors", "bfs_successors", + "bfs_tree", "descendants_at_distance", ] +# The kinds of edge `bfs_labeled_edges` gives, in the order of NetworkX's names for them. +TREE_EDGE, LEVEL_EDGE, FORWARD_EDGE, REVERSE_EDGE = range(4) + def _levels(G, source, depth_limit, reverse=False): + if depth_limit is not None and not depth_limit >= 0: + # NetworkX walks no level for a limit below 0, -inf or NaN alike. + return iter(()) if depth_limit is not None and depth_limit < len(G): depth_limit = ceil(depth_limit) # NetworkX walks on while `depth < depth_limit` return _bfs_parent_levels(G, source, cutoff=depth_limit, transpose=reverse) @@ -56,6 +69,137 @@ def bfs_successors(G, source, *, depth_limit=None): yield source, [] +def bfs_predecessors(G, source, *, depth_limit=None): + """Yield `(child, parent)` for each edge of `bfs_edges`'s tree, in its order. + + The source is yielded as given, as NetworkX does. + """ + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + first = True + for child_ids, parent_ids in _levels(G, source, depth_limit): + children = keys[child_ids].tolist() + if first: + # Every node of the first level is the source's child. + first = False + yield from zip(children, [source] * len(children), strict=True) + else: + yield from zip(children, keys[parent_ids].tolist(), strict=True) + + +def bfs_tree(G, source, *, reverse=False, depth_limit=None): + """`bfs_edges`'s tree as a DiGraph of this backend: an edge from each parent to its child. + + Its nodes are the source, as given, then each level's nodes in node order, as `bfs_edges` + yields them; its edges carry no values. + """ + index = G._key_to_id[source] + order = [np.array([index], np.int64)] + parents = [np.empty(0, np.int64)] + for child_ids, parent_ids in _levels(G, source, depth_limit, reverse): + order.append(child_ids.astype(np.int64)) + parents.append(parent_ids.astype(np.int64)) + order = np.concatenate(order) + k = len(order) + renumber = np.empty(len(G), np.int64) + renumber[order] = np.arange(k) + A = Matrix.from_coo( + renumber[np.concatenate(parents)], + renumber[order[1:]], + True, + dtype=bool, + nrows=k, + ncols=k, + name="bfs_tree", + ) + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + names = keys[order].tolist() + names[0] = source + return DiGraph(A, key_to_id=dict(zip(names, range(k), strict=True))) + + +def _parent_levels(G, source_ids): + """Yield `(child_ids, parent_ids)` for each level below the nodes `source_ids`, nearest first. + + `_bfs_parent_levels`'s walk from several sources, each node reached getting the neighbor on + the level above that the walk takes first: a source in the order given, then a node in node + order. So the first level's values are the sources' places in `source_ids`, mapped back. + """ + A = _adjacency(G) + n = A.nrows + seen = _visited(Vector(bool, n, name="seen")) + seen.build(source_ids, np.ones(len(source_ids), bool)) + q = Vector.from_coo(source_ids, np.arange(len(source_ids)), size=n, name="q") + min_first = semiring.min_first[int] + own_index = indexunary.index[int] + first = True + while True: + q(~seen.S, replace) << min_first(q @ A) + if q.nvals == 0: + return + seen(q.S) << True + child_ids, parent_ids = q.to_coo() + if first: + first, parent_ids = False, source_ids[parent_ids] + yield child_ids, parent_ids + q << own_index(q) + + +def bfs_labeled_edges(G, source_ids): + """Yield `(tails, heads, labels)`, as ids: the edges NetworkX's `bfs_labeled_edges` yields. + + `source_ids` are unique ids, in the order given. The walk is `_parent_levels`'s, so the + tree is `bfs_edges`'s for one source. Each node reached, the sources first, then each level + in node order, gives its edges by the node order of their heads: TREE_EDGE to a child, + LEVEL_EDGE within a level, FORWARD_EDGE to the level below otherwise, and REVERSE_EDGE + back up, which an undirected graph leaves out, as it gives a level edge once, from the end + reached first. A self-loop is a level edge. + + The walk goes as far as the edges asked for need, as NetworkX's does, so a caller that + stops early, as NetworkX's `girth` does, leaves the rest undone. The first part is the + sources' edges; each later part holds whole levels, about twice as many nodes as the one + before it, and is labelled once the level after it is known. + """ + n = len(G) + csr = _csr(G, False) + depth = np.full(n, -1, np.int64) + parent = np.full(n, -1, np.int64) + position = np.empty(n, np.int64) # in the walk's order, for an undirected level edge + depth[source_ids] = 0 + position[source_ids] = np.arange(len(source_ids)) + placed = len(source_ids) + + def labelled(levels): + tails, heads = _rows(*csr, np.concatenate(levels)) + tail_depth, head_depth = depth[tails], depth[heads] + labels = np.where( + tail_depth == head_depth, + LEVEL_EDGE, + np.where(tail_depth < head_depth, FORWARD_EDGE, REVERSE_EDGE), + ) + labels[parent[heads] == tails] = TREE_EDGE + if not G.is_directed(): + keep = (labels != REVERSE_EDGE) & ( + (labels != LEVEL_EDGE) | (position[tails] <= position[heads]) + ) + tails, heads, labels = tails[keep], heads[keep], labels[keep] + return tails, heads, labels + + pending, size, part = [source_ids], len(source_ids), 1 + for level, (child_ids, parent_ids) in enumerate(_parent_levels(G, source_ids), 1): + child_ids = child_ids.astype(np.int64) + depth[child_ids] = level + parent[child_ids] = parent_ids + position[child_ids] = np.arange(placed, placed + len(child_ids)) + placed += len(child_ids) + # The heads of the pending levels all have their depths now. + if size >= part: + yield labelled(pending) + pending, size, part = [], 0, 2 * size + pending.append(child_ids) + size += len(child_ids) + yield labelled(pending) + + def bfs_layers(G, sources): if sources in G: sources = [sources] diff --git a/graphblas_algorithms/algorithms/traversal/edgebfs.py b/graphblas_algorithms/algorithms/traversal/edgebfs.py new file mode 100644 index 0000000..bde8256 --- /dev/null +++ b/graphblas_algorithms/algorithms/traversal/edgebfs.py @@ -0,0 +1,106 @@ +"""Every edge a breadth-first walk from some nodes reaches, once each, node by node.""" + +import numpy as np +from graphblas import Vector, binary, replace +from graphblas.semiring import any_pair + +from .._bfs import _visited + +__all__ = ["edge_bfs"] + +# How an edge was reached: from its tail, along it, or from its head, against it. +FORWARD = 0 +REVERSE = 1 + + +def _csr(G, transpose): + """`(indptr, columns)` of the adjacency, or of its transpose, as int64 arrays.""" + A = G.get_property("AT") if transpose else G._A + indptr, columns, _values = A.to_csr() + return indptr.astype(np.int64), columns.astype(np.int64) + + +def _walk_order(G, source_ids, *, out, back): + """The nodes reached from `source_ids`, each once, in the order a walk takes them. + + The sources come first, as given, then each level of the walk by id. A level is the nodes + one step from the one before along out-edges if `out`, in-edges if `back`, or either. + """ + n = len(G) + seen = _visited(Vector(bool, n, name="seen")) + seen.build(source_ids, np.ones(len(source_ids), bool)) + frontier = seen.dup(name="frontier") + steps = [] + if out: + steps.append(G.get_property("offdiag")) + if back: + steps.append(G.get_property("AT")) + reached = Vector(bool, n, name="reached") + order = [source_ids] + any_pair_bool = any_pair[bool] + while True: + reached(~seen.S, replace) << any_pair_bool(frontier @ steps[0]) + for A in steps[1:]: + reached(binary.any, mask=~seen.S) << any_pair_bool(frontier @ A) + if reached.nvals == 0: + return np.concatenate(order) + seen(reached.S) << True + order.append(reached.to_coo(values=False)[0].astype(np.int64)) + frontier, reached = reached, frontier + + +def _rows(indptr, columns, nodes): + """The entries of the rows `nodes`, in that order: `(rows, columns)`.""" + counts = indptr[nodes + 1] - indptr[nodes] + starts = np.repeat(indptr[nodes] - (np.cumsum(counts) - counts), counts) + return np.repeat(nodes, counts), columns[np.arange(len(starts)) + starts] + + +def edge_bfs(G, source_ids, *, reverse=False, ignore=False): + """`(tails, heads, how)`: the edges NetworkX's `edge_bfs` yields, as ids, in a BFS order. + + `source_ids` are unique ids, in the order given; None for every node, in node order. Each + node reached gives its edges once each: a directed graph its out-edges, its in-edges if + `reverse`, or both if `ignore`, each edge where it is first met, and `how` says whether + from its tail (FORWARD) or its head (REVERSE); an undirected graph each edge from the end + met first. A node's edges come by the id of the other end, its out-edges before its + in-edges. + """ + directed = G.is_directed() + if source_ids is None: + order = np.fromiter(G._key_to_id.values(), np.int64, len(G)) + else: + order = _walk_order( + G, source_ids, out=not (directed and reverse), back=directed and (reverse or ignore) + ) + position = np.full(len(G), -1, np.int64) + position[order] = np.arange(len(order)) + if directed and reverse: + heads, tails = _rows(*_csr(G, True), order) + return tails, heads, np.full(len(tails), REVERSE, np.int8) + tails, heads = _rows(*_csr(G, False), order) + if not directed: + # Each edge is in the rows of both its ends: it is met first at the end first reached. + first = position[tails] <= position[heads] + tails, heads = tails[first], heads[first] + return tails, heads, np.full(len(tails), FORWARD, np.int8) + if not ignore: + return tails, heads, np.full(len(tails), FORWARD, np.int8) + # Each edge is met as an out-edge of its tail and an in-edge of its head; a node gives its + # out-edges first, so a self-loop is met along it. + in_heads, in_tails = _rows(*_csr(G, True), order) + along = position[tails] <= position[heads] + against = position[in_heads] < position[in_tails] + tails, heads = tails[along], heads[along] + in_tails, in_heads = in_tails[against], in_heads[against] + # Interleave by the node met, its out-edges first; each part is already in that order. + key = np.concatenate([2 * position[tails], 2 * position[in_heads] + 1]) + at = np.argsort(key, kind="stable") + how = np.concatenate( + [np.full(len(tails), FORWARD, np.int8), np.full(len(in_tails), REVERSE, np.int8)] + ) + return ( + np.concatenate([tails, in_tails])[at], + np.concatenate([heads, in_heads])[at], + how[at], + ) diff --git a/graphblas_algorithms/classes/_utils.py b/graphblas_algorithms/classes/_utils.py index fa821b1..6bb3993 100644 --- a/graphblas_algorithms/classes/_utils.py +++ b/graphblas_algorithms/classes/_utils.py @@ -1,3 +1,4 @@ +import weakref from collections.abc import Mapping from itertools import islice @@ -21,6 +22,21 @@ def __repr__(self): PRESERVE = _Preserve() +# The NetworkX graph each conversion was made from, held weakly: NetworkX's cache keeps a +# conversion as long as its graph, and a pickled or copied conversion is not the one made. +_SOURCES = weakref.WeakKeyDictionary() + + +def remember_source(G, graph): + """Record that backend graph `G` was converted from NetworkX graph `graph`.""" + _SOURCES[G] = weakref.ref(graph) + + +def source_of(G): + """The NetworkX graph `G` was converted from, or None if it is unknown or gone.""" + ref = _SOURCES.get(G) + return None if ref is None else ref() + def _structure_of(G): """`G` with its values replaced by integer ones, and a cache of its own. diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..6d1fb75 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -431,9 +431,13 @@ class Dispatcher: mod = nxapi.traversal # =================== bfs_edges = mod.breadth_first_search.bfs_edges + bfs_labeled_edges = mod.breadth_first_search.bfs_labeled_edges bfs_layers = mod.breadth_first_search.bfs_layers + bfs_predecessors = mod.breadth_first_search.bfs_predecessors bfs_successors = mod.breadth_first_search.bfs_successors + bfs_tree = mod.breadth_first_search.bfs_tree descendants_at_distance = mod.breadth_first_search.descendants_at_distance + edge_bfs = mod.edgebfs.edge_bfs mod = nxapi.tree # ============== @@ -468,6 +472,7 @@ def convert_from_nx( graph_name=None, ): from .classes import DiGraph, Graph + from .classes._utils import remember_source # Each refusal is a NotImplementedError, the one exception NetworkX falls back on here. if not hasattr(graph, "is_directed") or not hasattr(graph, "adj"): @@ -479,6 +484,7 @@ def convert_from_nx( "graphblas-algorithms does not support multigraphs: a GraphBLAS matrix " "holds one value per node pair, so parallel edges would be combined" ) + source = graph graph = _materialize_virtual_adjacency(graph) if node_attrs: @@ -524,6 +530,9 @@ def convert_from_nx( # ask for on `reverse` when its conversion cache is off. if preserve_graph_attrs or declared.rebuilds_input: G.graph.update(graph.graph) + if graph is source: + # A snapshot's data dicts are not the caller's, so only a graph read as it is counts. + remember_source(G, graph) return G @staticmethod @@ -591,6 +600,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/tests/test_bfs_riders.py b/graphblas_algorithms/nxapi/tests/test_bfs_riders.py new file mode 100644 index 0000000..7df60b8 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_bfs_riders.py @@ -0,0 +1,757 @@ +"""bfs_tree, bfs_predecessors and bfs_labeled_edges against NetworkX. + +A breadth-first tree is not unique, and NetworkX's follows the order each node's edges were +added, which a matrix does not keep. This backend's is `bfs_edges`'s: each node's parent is its +neighbor on the level above first in node order. So these tests check NetworkX's nodes, depths, +edges and labels, that the tree is a breadth-first tree, and this backend's own order; and that +a graph of this backend's is never converted. +""" + +import collections +import functools +import gc +import itertools +import math +import warnings +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest +from graphblas import Matrix + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings( + "ignore:Note. conversions to backend graphs", + "ignore:\\s*bfs_predecessors is deprecated:DeprecationWarning", +) + +RIDERS = ["bfs_tree", "bfs_predecessors", "bfs_labeled_edges"] + + +def _random_graph(seed, directed): + """A small random graph with self-loops, isolated nodes and nodes added out of order.""" + rng = np.random.default_rng(seed) + n = int(rng.integers(1, 16)) + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(rng.permutation(n).tolist()) + p = rng.choice([0.05, 0.15, 0.3, 0.6]) + for u in range(n): + for v in range(n): + if (directed or u <= v) and rng.random() < (p if u != v else 0.1): + G.add_edge(u, v) + return G + + +GRAPHS = { + f"{'directed' if d else 'undirected'} {seed}": (seed, d) + for d in [False, True] + for seed in range(40) +} + + +def graph(label): + return _random_graph(*GRAPHS[label]) + + +def depths(G, sources, *, reverse=False, depth_limit=None): + """Each node's depth in a breadth-first walk from `sources`, theirs 0.""" + step = G.predecessors if reverse and G.is_directed() else G.neighbors + depth = dict.fromkeys(sources, 0) + queue = collections.deque(depth) + while queue: + v = queue.popleft() + if depth_limit is not None and not depth[v] < depth_limit: # NaN too, as NetworkX + continue + for w in step(v): + if w not in depth: + depth[w] = depth[v] + 1 + queue.append(w) + return depth + + +def assert_tree(G, source, T, *, reverse=False, depth_limit=None, native=False): + """`T` is a breadth-first tree of `G` from `source`, as this backend gives it. + + NetworkX's nodes, each but the source the child of one parent a level up, joined to it in + the walk's direction; the nodes in `bfs_edges`'s order, and its edges. For a graph of this + backend's (`native`), this backend's DiGraph; for a NetworkX graph, NetworkX's DiGraph, + built as NetworkX builds it from those edges. + """ + want = nx.bfs_tree(G, source, reverse=reverse, depth_limit=depth_limit, backend="networkx") + edges = list( + nx.bfs_edges(G, source, reverse=reverse, depth_limit=depth_limit, backend="graphblas") + ) + if native: + assert type(T) is ga.DiGraph + H = T.to_networkx() + else: + assert type(T) is nx.DiGraph + H = T + built = nx.DiGraph() + built.add_node(source) + built.add_edges_from(edges) + assert [(u, list(nbrs)) for u, nbrs in T.adj.items()] == [ + (u, list(nbrs)) for u, nbrs in built.adj.items() + ] + assert [(type(u), data) for u, data in T.nodes(data=True)] == [ + (type(u), data) for u, data in built.nodes(data=True) + ] + assert T.graph == {} + assert set(H) == set(want) + depth = depths(G, [source], reverse=reverse, depth_limit=depth_limit) + assert H.in_degree(source) == 0 + for child in H: + if child != source: + assert H.in_degree(child) == 1 + (parent,) = H.predecessors(child) + assert depth[child] == depth[parent] + 1 + assert ( + (child, parent) in G.edges + if reverse and G.is_directed() + else (parent, child) in G.edges + ) + assert all(not data for *_, data in H.edges(data=True)) + assert list(H) == [source, *(child for _parent, child in edges)] + assert sorted(H.edges) == sorted(edges) + + +@pytest.mark.parametrize("depth_limit", [None, 0, 1, 2]) +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("label", sorted(GRAPHS)) +def test_bfs_tree_is_a_breadth_first_tree(label, reverse, depth_limit): + """Of a NetworkX graph through NetworkX, and of this backend's graph.""" + G = graph(label) + B = (ga.DiGraph if G.is_directed() else ga.Graph).from_networkx(G) + for source in list(G)[:3]: + T = nx.bfs_tree(G, source, reverse=reverse, depth_limit=depth_limit, backend="graphblas") + assert_tree(G, source, T, reverse=reverse, depth_limit=depth_limit) + T = nx.bfs_tree(B, source, reverse=reverse, depth_limit=depth_limit) + assert_tree(G, source, T, reverse=reverse, depth_limit=depth_limit, native=True) + + +@pytest.mark.parametrize("depth_limit", [None, 1, 2.5]) +@pytest.mark.parametrize("label", sorted(GRAPHS)) +def test_bfs_predecessors_are_the_tree_s_parents(label, depth_limit): + G = graph(label) + for source in list(G)[:3]: + got = list(nx.bfs_predecessors(G, source, depth_limit=depth_limit, backend="graphblas")) + edges = nx.bfs_edges(G, source, depth_limit=depth_limit, backend="graphblas") + assert got == [(child, parent) for parent, child in edges] + want = nx.bfs_predecessors(G, source, depth_limit=depth_limit, backend="networkx") + assert {child for child, _parent in got} == {child for child, _parent in want} + + +def assert_discovered_in_order(starts, edges): + """Replay the walk: an edge to a node not yet reached is a tree edge, and no other is. + + As NetworkX labels them: the sources are reached first, and every other node by its tree + edge, the first edge into it the walk yields. The sources are walked in the order given. + """ + reached = set(starts) + for u, v, label in edges: + assert u in reached + if label == "tree": + assert v not in reached, (u, v, label) + reached.add(v) + else: + assert v in reached, (u, v, label) + tails = list(dict.fromkeys(u for u, _v, _label in edges)) + given = set(starts) + assert [u for u in tails if u in given] == [u for u in starts if u in tails] + + +def assert_labeled(G, sources, got): + """`got` holds NetworkX's edges and labels, with a breadth-first tree of this backend's.""" + want = list(nx.bfs_labeled_edges(G, sources, backend="networkx")) + starts = [sources] if sources in G else list(dict.fromkeys(sources)) + depth = depths(G, starts) + if G.is_directed(): + assert collections.Counter((u, v) for u, v, _ in got) == collections.Counter( + (u, v) for u, v, _ in want + ) + else: + assert collections.Counter(frozenset((u, v)) for u, v, _ in got) == collections.Counter( + frozenset((u, v)) for u, v, _ in want + ) + assert collections.Counter(label for *_, label in got) == collections.Counter( + label for *_, label in want + ) + parents = collections.Counter() + for u, v, label in got: + if label == "level": + assert depth[u] == depth[v] + elif label == "reverse": + assert G.is_directed() + assert depth[v] < depth[u] + else: + assert depth[v] == depth[u] + 1 + if label == "tree": + parents[v] += 1 + assert set(parents) == set(depth) - set(starts) + assert set(parents.values()) <= {1} + # The walk's order: each node's edges together, from nodes in order of depth + tails = [u for u, _edges in itertools.groupby(got, key=lambda edge: edge[0])] + assert len(tails) == len(set(tails)) + assert [depth[u] for u in tails] == sorted(depth[u] for u in tails) + assert_discovered_in_order(starts, got) + + +@pytest.mark.parametrize("label", sorted(GRAPHS)) +def test_bfs_labeled_edges_as_networkx(label): + G = graph(label) + nodes = list(G) + for sources in [nodes[0], nodes[:2], nodes[::-1][:3], [nodes[0], nodes[0]]]: + got = list(nx.bfs_labeled_edges(G, sources, backend="graphblas")) + assert_labeled(G, sources, got) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_bfs_labeled_edges_tree_is_bfs_edges_tree(directed): + for seed in range(20): + G = _random_graph(seed, directed) + source = next(iter(G)) + tree = [ + (u, v) + for u, v, label in nx.bfs_labeled_edges(G, source, backend="graphblas") + if label == "tree" + ] + assert sorted(tree) == sorted(nx.bfs_edges(G, source, backend="graphblas")) + + +def test_the_labels_are_networkx_s_own_strings(conversions): + """NetworkX's `girth` compares them by identity.""" + from networkx.algorithms.traversal import breadth_first_search as theirs + + G = nx.DiGraph([(0, 1), (0, 2), (1, 2), (2, 0), (2, 2), (1, 3), (2, 3)]) + labels = {label for *_, label in nx.bfs_labeled_edges(G, 0, backend="graphblas")} + expected = {theirs.TREE_EDGE, theirs.LEVEL_EDGE, theirs.FORWARD_EDGE, theirs.REVERSE_EDGE} + assert labels == expected + assert all(any(label is constant for constant in expected) for label in labels) + H = nx.cycle_graph(7) + H.add_edge(0, 3) + assert nx.girth(H, backend="networkx") == 4 + before = conversions[0] + with _priority(bfs_labeled_edges=["graphblas"]), _served_anyway("bfs_labeled_edges"): + assert nx.girth(H) == 4 + assert conversions[0] == before + 1 # served from one conversion, from each node + + +@contextmanager +def _served_anyway(name): + """`name` served on the automatic path whatever its `should_run` says.""" + func = getattr(Dispatcher, name) + hook = func._should_run + func._should_run = lambda bound: None + try: + yield + finally: + func._should_run = hook + + +def test_sources_not_in_node_order_are_walked_in_the_order_given(): + """A node one step from several sources is the child of the first given. + + Not the first in node order: so its first edge is its tree edge. + """ + G = nx.Graph() + G.add_nodes_from([0, 1, 2]) + G.add_edges_from([(2, 0), (1, 0)]) + want = [(2, 0, "tree"), (1, 0, "forward")] + assert list(nx.bfs_labeled_edges(G, [2, 1], backend="networkx")) == want + assert list(nx.bfs_labeled_edges(G, [2, 1], backend="graphblas")) == want + got, error = _until_it_raises(nx.bfs_labeled_edges(G, [2, 99, 1], backend="graphblas")) + assert (got, error) == ([(2, 0, "tree")], (99,)) + + +def test_the_documented_labels_written_out(): + # 0 reaches 1 and 2; 1 and 2 reach 3; 2 also reaches 1 and back to 0; 3 has a loop. + G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3), (2, 1), (2, 0), (3, 3)]) + assert list(nx.bfs_labeled_edges(G, 0, backend="graphblas")) == [ + (0, 1, "tree"), + (0, 2, "tree"), + (1, 3, "tree"), + (2, 0, "reverse"), + (2, 1, "level"), + (2, 3, "forward"), + (3, 3, "level"), + ] + H = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 3)]) + assert list(nx.bfs_labeled_edges(H, 0, backend="graphblas")) == [ + (0, 1, "tree"), + (0, 2, "tree"), + (1, 2, "level"), + (1, 3, "tree"), + (2, 3, "forward"), + (3, 3, "level"), + ] + + +@pytest.mark.parametrize("depth_limit", [-math.inf, math.nan, -1, -0.5, 0, 0.5]) +@pytest.mark.parametrize("directed", [False, True]) +def test_a_depth_limit_of_0_or_less_walks_no_level(directed, depth_limit): + """NetworkX walks while `depth < depth_limit`, so -inf and NaN walk nothing too; 0.5, one.""" + G = _random_graph(5, directed) + source = next(iter(G)) + for B, backend in [ + (G, "graphblas"), + ((ga.DiGraph if directed else ga.Graph).from_networkx(G), None), + ]: + T = nx.bfs_tree(B, source, depth_limit=depth_limit, backend=backend) + assert_tree(G, source, T, depth_limit=depth_limit, native=backend is None) + assert (list(T) == [source]) == (depth_limit != 0.5) + for name in ["bfs_edges", "bfs_successors", "bfs_predecessors"]: + got = getattr(nx, name)(B, source, depth_limit=depth_limit, backend=backend) + want = getattr(nx, name)(G, source, depth_limit=depth_limit, backend="networkx") + if depth_limit == 0.5: + # One level, the source's neighbors, whose order may differ + as_edges = { + "bfs_edges": set, + "bfs_successors": lambda pairs: {(p, c) for p, cs in pairs for c in cs}, + "bfs_predecessors": lambda pairs: {(p, c) for c, p in pairs}, + }[name] + assert ( + as_edges(got) + == as_edges(want) + == {(source, c) for c in G[source] if c != source} + ) + else: + assert ( + list(got) == list(want) == ([(source, [])] if name == "bfs_successors" else []) + ) + + +def test_a_deep_walk(): + G = nx.path_graph(1500, create_using=nx.DiGraph) + T = nx.bfs_tree(G, 0, backend="graphblas") + assert list(T) == list(range(1500)) + assert list(nx.bfs_predecessors(G, 0, backend="graphblas")) == [(i + 1, i) for i in range(1499)] + assert [label for *_, label in nx.bfs_labeled_edges(G, 0, backend="graphblas")] == [ + "tree" + ] * 1499 + + +def test_the_walk_goes_only_as_far_as_the_edges_asked_for(monkeypatch): + """As NetworkX's generator does, which `girth` stops early.""" + from graphblas_algorithms.algorithms.traversal import breadth_first_search as kernel + + walked = [] + levels = kernel._parent_levels + + def counted(*args): + for level in levels(*args): + walked.append(len(level[0])) + yield level + + monkeypatch.setattr(kernel, "_parent_levels", counted) + G = nx.path_graph(1000) + edges = nx.bfs_labeled_edges(G, 0, backend="graphblas") + assert next(edges) == (0, 1, "tree") + assert len(walked) == 1 + for count in range(2, 200): + next(edges) + # Each part is about twice the last, and labelled once the level after it is known + assert len(walked) <= 2 * count + 1 + assert len(list(edges)) == 999 - 199 + assert len(walked) == 999 + + +def test_nodes_that_are_tuples(): + G = nx.grid_2d_graph(4, 3) + for sources in [(0, 0), [(0, 0), (3, 2)], [(1, 1), (0, 0), (3, 2)]]: + got = list(nx.bfs_labeled_edges(G, sources, backend="graphblas")) + assert_labeled(G, sources, got) + assert all(isinstance(u, tuple) and isinstance(v, tuple) for u, v, _label in got) + T = nx.bfs_tree(G, (1, 2), backend="graphblas") + assert_tree(G, (1, 2), T) + edges = nx.bfs_edges(G, (1, 2), backend="graphblas") + want = [(child, parent) for parent, child in edges] + assert list(nx.bfs_predecessors(G, (1, 2), backend="graphblas")) == want + + +def test_ids_out_of_node_order(): + """A graph of this backend's whose ids do not follow its node order.""" + A = Matrix.from_coo([0, 1, 2], [1, 2, 0], True, nrows=3, ncols=3) + G = ga.DiGraph(A, key_to_id={"c": 2, "a": 0, "b": 1}) + T = nx.bfs_tree(G, "a") + assert list(T._key_to_id) == ["a", "b", "c"] + assert sorted(T.to_networkx().edges) == [("a", "b"), ("b", "c")] + assert list(nx.bfs_predecessors(G, "a")) == [("b", "a"), ("c", "b")] + assert list(nx.bfs_labeled_edges(G, "c")) == [ + ("c", "a", "tree"), + ("a", "b", "tree"), + ("b", "c", "reverse"), + ] + + +def test_a_source_is_kept_as_given(): + """As NetworkX keeps it: 1.0 for the node 1, where the walk starts from it.""" + G = nx.Graph([(1, 2), (2, 3), (3, 1)]) + T = nx.bfs_tree(G, 1.0, backend="graphblas") + assert [type(node) for node in T] == [float, int, int] + T = nx.bfs_tree(ga.Graph.from_networkx(G), 1.0) + assert [type(node) for node in T._key_to_id] == [float, int, int] + got = list(nx.bfs_predecessors(G, 1.0, backend="graphblas")) + want = list(nx.bfs_predecessors(G, 1.0, backend="networkx")) + assert [(child, parent, type(parent)) for child, parent in got] == [ + (2, 1.0, float), + (3, 1.0, float), + ] + assert [tuple(map(type, edge)) for edge in got] == [tuple(map(type, edge)) for edge in want] + want = list(nx.bfs_labeled_edges(G, [1.0], backend="networkx")) + got = list(nx.bfs_labeled_edges(G, [1.0], backend="graphblas")) + assert [tuple(map(type, edge[:2])) for edge in got] == [ + tuple(map(type, edge[:2])) for edge in want + ] + + +def _error(call): + try: + list(call()) + except Exception as exc: + return type(exc), str(exc) + return None + + +ERRORS = { + "bfs_tree absent": lambda G, **kw: nx.bfs_tree(G, "absent", **kw), + "bfs_tree None": lambda G, **kw: nx.bfs_tree(G, None, **kw), + "bfs_tree unhashable": lambda G, **kw: nx.bfs_tree(G, [0], **kw), + "bfs_predecessors absent": lambda G, **kw: nx.bfs_predecessors(G, "absent", **kw), + "bfs_predecessors unhashable": lambda G, **kw: nx.bfs_predecessors(G, [0], **kw), + "bfs_labeled_edges absent": lambda G, **kw: nx.bfs_labeled_edges(G, [0, "absent"], **kw), + "bfs_labeled_edges not a node": lambda G, **kw: nx.bfs_labeled_edges(G, 7, **kw), + "bfs_labeled_edges unhashable": lambda G, **kw: nx.bfs_labeled_edges(G, [[0]], **kw), +} + + +@pytest.mark.parametrize("cls", [nx.Graph, nx.DiGraph]) +@pytest.mark.parametrize("case", sorted(ERRORS)) +def test_errors_as_networkx(case, cls): + G = cls([(0, 1), (1, 2)]) + want = _error(lambda: ERRORS[case](G, backend="networkx")) + got = _error(lambda: ERRORS[case](G, backend="graphblas")) + assert want is not None + if case.endswith("unhashable"): + # Python's message names the container it hashed for + want, got = want[0], got[0] + assert got == want + + +def _until_it_raises(edges): + """The edges yielded before a KeyError, and its args.""" + got = [] + edges = iter(edges) + while True: + try: + edge = next(edges) + except KeyError as exc: + return got, exc.args + got.append(edge) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_an_absent_source_raises_after_the_edges_of_those_before_it(directed): + """NetworkX walks the sources first, in order, and raises where it meets one not a node.""" + for seed in range(20): + G = _random_graph(seed, directed) + nodes = list(G) + for sources in [[*nodes[:1], "absent", *nodes[1:3]], [*nodes[:3], "absent", "gone"]]: + theirs, error = _until_it_raises(nx.bfs_labeled_edges(G, sources, backend="networkx")) + ours, our_error = _until_it_raises( + nx.bfs_labeled_edges(G, sources, backend="graphblas") + ) + assert our_error == error == ("absent",) + # The tree may differ, so which of these edges are tree edges and which forward + assert sorted((u, v, label == "level") for u, v, label in ours) == sorted( + (u, v, label == "level") for u, v, label in theirs + ) + assert_discovered_in_order([node for node in sources if node in G], ours) + + +@pytest.mark.parametrize("name", ["bfs_predecessors", "bfs_labeled_edges"]) +def test_errors_wait_for_the_first_edge(name): + G = nx.path_graph(3) + gen = getattr(nx, name)(G, "absent", backend="graphblas") + with pytest.raises((nx.NetworkXError, TypeError, KeyError)): + next(gen) + + +def test_no_sources_give_no_edges(): + G = nx.path_graph(3) + assert list(nx.bfs_labeled_edges(G, [], backend="graphblas")) == [] + assert list(nx.bfs_labeled_edges(G, iter([2]), backend="graphblas")) == [ + (2, 1, "tree"), + (1, 0, "tree"), + ] + + +def test_bfs_predecessors_warns_as_networkx_does(): + G = nx.path_graph(3) + with warnings.catch_warnings(record=True) as theirs: + warnings.simplefilter("always") + list(nx.bfs_predecessors(G, 0, backend="networkx")) + with warnings.catch_warnings(record=True) as ours: + warnings.simplefilter("always") + gen = nx.bfs_predecessors(G, 0, backend="graphblas") + assert not [w for w in ours if w.category is DeprecationWarning] # not before the walk + list(gen) + theirs = [(w.category, str(w.message)) for w in theirs if w.category is DeprecationWarning] + ours = [(w.category, str(w.message)) for w in ours if w.category is DeprecationWarning] + assert ours == theirs + + +@pytest.mark.parametrize("name", ["bfs_tree", "bfs_predecessors"]) +def test_sort_neighbors_is_declined(name): + G = nx.path_graph(4) + assert Dispatcher.can_run(name, (G, 0), {}) is True + reason = Dispatcher.can_run(name, (G, 0), {"sort_neighbors": sorted}) + assert isinstance(reason, str) + + def call(): + rv = getattr(nxapi, name)(G, 0, sort_neighbors=sorted) + return rv if name == "bfs_tree" else list(rv) + + with pytest.raises(NotImplementedError, match="sort_neighbors"): + call() + + +@pytest.fixture +def conversions(monkeypatch): + """The number of graphs converted from NetworkX since the test began.""" + count = [0] + convert = Dispatcher.convert_from_nx + + def counting(*args, **kwargs): + count[0] += 1 + return convert(*args, **kwargs) + + monkeypatch.setattr(Dispatcher, "convert_from_nx", staticmethod(counting)) + return count + + +@pytest.fixture +def served(monkeypatch): + """The calls of each of these names this backend has served since the test began.""" + count = collections.Counter() + for name in RIDERS: + func = getattr(Dispatcher, name) + + @functools.wraps(func) # keeps its `_can_run` and `_should_run` + def counting(*args, _name=name, _func=func, **kwargs): + count[_name] += 1 + return _func(*args, **kwargs) + + monkeypatch.setattr(Dispatcher, name, staticmethod(counting)) + return count + + +@pytest.mark.parametrize("directed", [False, True]) +def test_a_graph_of_this_backend_s_is_never_converted(directed, conversions): + G = _random_graph(3, directed) + B = (ga.DiGraph if directed else ga.Graph).from_networkx(G) + source = next(iter(G)) + T = nx.bfs_tree(B, source) + predecessors = list(nx.bfs_predecessors(B, source)) + edges = list(nx.bfs_edges(B, source)) + labeled = list(nx.bfs_labeled_edges(B, source)) + # The tree is this backend's too, so a call on it stays here + from_tree = list(nx.bfs_labeled_edges(T, source)) + assert conversions[0] == 0 + assert_tree(G, source, T, native=True) + assert predecessors == [(child, parent) for parent, child in edges] + assert_labeled(G, source, labeled) + assert [label for *_, label in from_tree] == ["tree"] * (len(T) - 1) + + +@contextmanager +def _priority(**names): + """NetworkX's priority for the names given (or `algos`), with fallback on, for the duration.""" + priority = nx.config.backend_priority + saved = {key: list(priority[key]) for key in priority} + try: + for key, value in names.items(): + priority[key] = value + yield + finally: + for key in list(priority): + if key not in saved: + del priority[key] + for key, value in saved.items(): + priority[key] = value + + +CALLS = { + "bfs_predecessors": lambda G: list(nx.bfs_predecessors(G, 0)), + "bfs_labeled_edges": lambda G: list(nx.bfs_labeled_edges(G, 0)), +} + + +def test_a_networkx_graph_goes_to_networkx_unless_it_is_converted_anyway(conversions, served): + """`bfs_predecessors`: served where the graph is converted either way, else left to NetworkX. + + Either way: its conversion is cached, or NetworkX's own walk would call `bfs_edges` here. + Elsewhere NetworkX's walk costs less than converting the graph. + """ + name = "bfs_predecessors" + G = nx.gnm_random_graph(30, 60, seed=1) + with _priority(**{name: ["graphblas"]}): + assert isinstance(Dispatcher.should_run(name, (G, 0), {}), str) + CALLS[name](G) + assert (conversions[0], served[name]) == (0, 0) + with _priority(**{name: ["graphblas"], "bfs_edges": ["graphblas"]}): + assert Dispatcher.should_run(name, (G, 0), {}) is True + # Another name's call converts the graph and caches the conversion + list(nx.bfs_edges(G, 0, backend="graphblas")) + assert conversions[0] == 1 + with _priority(**{name: ["graphblas"]}): + assert Dispatcher.should_run(name, (G, 0), {}) is True + CALLS[name](G) + assert (conversions[0], served[name]) == (1, 1) + nx.config.cache_converted_graphs = False + try: + assert isinstance(Dispatcher.should_run(name, (G, 0), {}), str) + finally: + nx.config.cache_converted_graphs = True + + +def test_labeled_edges_of_a_networkx_graph_are_left_to_networkx(conversions): + """Even with a conversion cached: NetworkX's `girth` reads a few edges from every node.""" + G = nx.gnm_random_graph(30, 60, seed=1) + with _priority(bfs_labeled_edges=["graphblas"], bfs_edges=["graphblas"]): + assert isinstance(Dispatcher.should_run("bfs_labeled_edges", (G, 0), {}), str) + CALLS["bfs_labeled_edges"](G) + assert conversions[0] == 0 + list(nx.bfs_edges(G, 0)) + assert conversions[0] == 1 + assert isinstance(Dispatcher.should_run("bfs_labeled_edges", (G, 0), {}), str) + served = list(nx.bfs_labeled_edges(G, 0, backend="graphblas")) + assert conversions[0] == 1 + assert_labeled(G, 0, served) + + +def test_networkx_s_own_walk_converts_where_bfs_edges_is_served_here(conversions): + """Why `bfs_predecessors` is served then: declining it would not spare the conversion.""" + G = nx.gnm_random_graph(30, 60, seed=1) + with _priority(bfs_edges=["graphblas"]): + CALLS["bfs_predecessors"](G) + assert conversions[0] == 1 + + +def test_a_tree_of_a_networkx_graph_is_left_to_networkx(conversions, served): + """On the automatic path, even with `bfs_edges` served here or a conversion cached. + + NetworkX's own `bfs_tree` builds the same DiGraph from the `bfs_edges` its priority names, + and building NetworkX's DiGraph costs here what it costs NetworkX, which is no gain against + this backend's cost per level on a deep graph. + """ + G = nx.gnm_random_graph(30, 60, seed=1) + want = nx.bfs_tree(G, 0, backend="networkx") + with _priority(bfs_tree=["graphblas"], generators=["graphblas"]): + assert isinstance(Dispatcher.should_run("bfs_tree", (G, 0), {}), str) + T = nx.bfs_tree(G, 0) + assert (conversions[0], served["bfs_tree"]) == (0, 0) + assert type(T) is nx.DiGraph + assert sorted(T.edges) == sorted(want.edges) # NetworkX's own walk and tree + with _priority(bfs_tree=["graphblas"], bfs_edges=["graphblas"]): + assert isinstance(Dispatcher.should_run("bfs_tree", (G, 0), {}), str) + # NetworkX's own walks with the bfs_edges served here, which converts the graph once + assert_tree(G, 0, nx.bfs_tree(G, 0)) + assert (conversions[0], served["bfs_tree"]) == (1, 0) + # The conversion is cached now + assert isinstance(Dispatcher.should_run("bfs_tree", (G, 0), {}), str) + assert_tree(G, 0, nx.bfs_tree(G, 0)) + assert (conversions[0], served["bfs_tree"]) == (1, 0) + # By name it is served, from the cached conversion + assert_tree(G, 0, nx.bfs_tree(G, 0, backend="graphblas")) + assert (conversions[0], served["bfs_tree"]) == (1, 1) + + +def test_an_explicit_backend_is_served_without_a_cached_conversion(conversions): + G = nx.path_graph(5) + assert_tree(G, 0, nx.bfs_tree(G, 0, backend="graphblas")) + assert conversions[0] == 1 + + +def test_a_networkx_caller_gets_networkx_s_digraph_on_every_path(conversions, served): + """Explicitly, from the wrapper itself, and on the automatic path, from NetworkX.""" + G = nx.gnm_random_graph(30, 60, seed=1) + T = nx.bfs_tree(G, 0, backend="graphblas") + assert_tree(G, 0, T) + assert T.number_of_edges() == len(T) - 1 + assert list(T.successors(0)) == [ + v for u, v in nx.bfs_edges(G, 0, backend="graphblas") if u == 0 + ] + assert next(iter(nx.topological_sort(T))) == 0 + assert served["bfs_tree"] == 1 + G = nx.gnm_random_graph(30, 60, seed=2) # no conversion cached + with _priority(generators=["graphblas"], algos=["graphblas"]): + # Left to NetworkX, whose own bfs_tree walks with the bfs_edges served here + assert isinstance(Dispatcher.should_run("bfs_tree", (G, 0), {}), str) + assert_tree(G, 0, nx.bfs_tree(G, 0)) + G = nx.gnm_random_graph(30, 60, seed=3) + with _priority(algos=["graphblas"]): + # bfs_tree is not asked for: `generators` gives its priority, not `algos` + assert_tree(G, 0, nx.bfs_tree(G, 0)) + assert served["bfs_tree"] == 1 + # A NetworkX graph handed to the wrapper itself + assert_tree(G, 0, nxapi.bfs_tree(G, 0)) + # This backend's own conversion of it, made outside NetworkX, is this backend's graph + B = ga.Graph.from_networkx(G) + assert_tree(G, 0, nxapi.bfs_tree(B, 0), native=True) + + +def test_a_conversion_records_its_networkx_graph(): + """Weakly: the conversion is NetworkX's to keep, in the graph's cache.""" + from graphblas_algorithms.classes._utils import source_of + + G = nx.path_graph(4) + B = Dispatcher.convert_from_nx(G) + assert source_of(B) is G + assert source_of(ga.Graph.from_networkx(G)) is None + del G + gc.collect() # in NetworkX 3.6.1 a reference cycle keeps the graph until collected + assert source_of(B) is None + + +def _k_core(G): + return len(nx.k_core(G, 2)) + + +def _components(G): + return sum(map(len, nx.connected_components(G))) + + +@pytest.mark.parametrize("other", [_k_core, _components], ids=["k_core", "components"]) +@pytest.mark.parametrize("other_first", [True, False]) +def test_the_node_keys_are_cached_as_the_components_and_core_names_cache_them(other, other_first): + """One cache entry, read by edge_bfs, these names, and the components and core names.""" + nxG = nx.gnm_random_graph(30, 60, seed=1) + G = ga.Graph.from_networkx(nxG) + if other_first: + expected = other(nxG) + assert other(G) == expected + assert len(list(nx.edge_bfs(G, 0))) == 60 + assert len(list(nx.bfs_labeled_edges(G, 0))) == 60 + assert len(nx.bfs_tree(G, 0)) == len(list(nx.bfs_predecessors(G, 0))) + 1 + assert other(G) == other(nxG) + + +def test_a_cached_value_that_is_not_a_graph_of_this_backend_s_is_no_conversion(): + """NetworkX marks a conversion that failed, and anything may be put there by hand.""" + G = nx.path_graph(5) + G.__networkx_cache__.setdefault("backends", {}).setdefault("graphblas", {})[ + (False, False) + ] = object() + for name in RIDERS: + assert isinstance(Dispatcher.should_run(name, (G, 0), {}), str) + + +def test_the_tree_s_difference_is_in_networkx_s_docs(): + from _nx_graphblas import get_info + + for name in RIDERS: + assert get_info()["functions"][name].get("additional_docs") diff --git a/graphblas_algorithms/nxapi/tests/test_edge_bfs.py b/graphblas_algorithms/nxapi/tests/test_edge_bfs.py new file mode 100644 index 0000000..0a740e3 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_edge_bfs.py @@ -0,0 +1,307 @@ +"""edge_bfs against NetworkX: its edges once each, in a breadth-first order of the backend's. + +The orientation is NetworkX's wherever the walk fixes it. NetworkX's order follows the order +each node's edges were added, which a matrix does not keep. So the edges are compared as a +multiset, and the order is checked to be breadth-first: each edge is met from a node no deeper +than its other end, the nodes edges are met from come in order of depth, and each node's edges +come together. +""" + +import collections +import itertools + +import networkx as nx +import numpy as np +import pytest +from graphblas import Matrix + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +ORIENTATIONS = [None, "original", "reverse", "ignore"] + + +def _outcome(call): + try: + return "answer", call() + except Exception as exc: + return type(exc), str(exc) + + +def _three_ways(G, source=None, orientation=None, *, fresh=None): + """NetworkX's outcome, graphblas's by name, and NetworkX's with graphblas first. + + `fresh`, if given, makes the source anew for each call (a generator is read once). + """ + + def call(**kw): + src = fresh() if fresh is not None else source + return list(nx.edge_bfs(G, src, orientation, **kw)) + + want = _outcome(lambda: call(backend="networkx")) + got = _outcome(lambda: call(backend="graphblas")) + config = nx.config.backend_priority + before, fallback = list(config.algos), nx.config.fallback_to_nx + config.algos, nx.config.fallback_to_nx = ["graphblas"], False + try: + first = _outcome(call) + finally: + config.algos, nx.config.fallback_to_nx = before, fallback + return want, got, first + + +def _sources(G, source): + """The nodes NetworkX starts from, each once, in order.""" + if source is None: + return list(G) + if source in G: + return [source] + return list(dict.fromkeys(v for v in source if v in G)) + + +def _depths(G, starts, orientation): + """Each node's depth in the walk edge_bfs makes, its sources' 0.""" + if G.is_directed() and orientation == "reverse": + step = G.predecessors + elif G.is_directed() and orientation == "ignore": + step = lambda v: itertools.chain(G.successors(v), G.predecessors(v)) # noqa: E731 + else: + step = G.neighbors + depth = dict.fromkeys(starts, 0) + queue = collections.deque(starts) + while queue: + v = queue.popleft() + for w in step(v): + if w not in depth: + depth[w] = depth[v] + 1 + queue.append(w) + return depth + + +def _assert_edge_bfs(G, got, want, source, orientation): + directed = G.is_directed() + labeled = orientation is not None + assert len(got) == len(want) + assert all(len(e) == (3 if labeled else 2) for e in got) + if directed and orientation == "ignore": + # Between two nodes at one depth, which end meets the edge first is the walk's own. + assert collections.Counter(e[:2] for e in got) == collections.Counter(e[:2] for e in want) + elif directed: + assert collections.Counter(got) == collections.Counter(want) + else: + + def norm(edges): + return collections.Counter((frozenset(e[:2]), e[2:]) for e in edges) + + assert norm(got) == norm(want) + depth = _depths(G, _sources(G, source), orientation) + met = [] # the node each edge is met from + for edge in got: + u, v = edge[:2] + x, y = (v, u) if labeled and edge[2] == "reverse" else (u, v) + if not directed or orientation == "ignore": + assert depth[x] <= depth[y] + met.append(x) + assert [depth[x] for x in met] == sorted(depth[x] for x in met) + blocks = [x for x, _ in itertools.groupby(met)] + assert len(blocks) == len(set(blocks)) # each node's edges together + + +def _assert_this_backend_s_order(G, got, source, orientation): + """The order the notes give: the sources as given, then each level in node order.""" + labeled = orientation is not None + starts = _sources(G, source) + depth = _depths(G, starts, orientation) + index = {v: i for i, v in enumerate(G)} + rank = {v: i for i, v in enumerate(starts)} + met = [e[1] if labeled and e[2] == "reverse" else e[0] for e in got] + met = [x for x, _ in itertools.groupby(met)] + keys = [(depth[x], rank[x] if x in rank else index[x]) for x in met] + assert keys == sorted(keys) + + +def _pick(rng, values): + return values[int(rng.integers(len(values)))] + + +def _graph(rng, i): + directed = i % 2 == 1 + n = _pick(rng, [0, 1, 2, 3, 5, 8, 13, 21, 40, 70]) + p = _pick(rng, [0.02, 0.06, 0.15, 0.4]) + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(rng.permutation(n).tolist()) # node order is not label order + pairs = [(int(a), int(b)) for a in range(n) for b in range(n) if a != b and rng.random() < p] + G.add_edges_from(pairs[k] for k in rng.permutation(len(pairs))) # nor is edge order + if n and i % 4 == 0: + G.add_edges_from((v, v) for v in rng.choice(n, 1 + n // 10, replace=False).tolist()) + if i % 7 == 0: + G.add_nodes_from([n, n + 1]) # isolated + if i % 5 == 0: + G = nx.relabel_nodes(G, {v: f"v{v}" for v in G}) + return G + + +def _random_source(rng, G, i): + nodes = list(G) + kind = i % 5 + if kind == 0 or not nodes: + return None + if kind == 1: + return _pick(rng, nodes) + if kind == 2: + picked = [_pick(rng, nodes) for _ in range(int(rng.integers(1, 4)))] + return [*picked, "absent", picked[0]] # an absent node is skipped, a repeat ignored + if kind == 3: + return [_pick(rng, nodes)] + return [] + + +GRAPHS = [_graph(np.random.default_rng(i), i) for i in range(320)] +CASES = [(i, orientation) for i in range(len(GRAPHS)) for orientation in ORIENTATIONS] + + +def test_there_are_enough_graphs(): + assert len(GRAPHS) >= 300 + + +@pytest.mark.parametrize(("i", "orientation"), CASES) +def test_the_edges_of_a_breadth_first_walk(i, orientation): + G = GRAPHS[i] + source = _random_source(np.random.default_rng(1000 + i), G, i) + want = list(nx.edge_bfs(G, source, orientation, backend="networkx")) + got = list(nx.edge_bfs(G, source, orientation, backend="graphblas")) + _assert_edge_bfs(G, got, want, source, orientation) + _assert_this_backend_s_order(G, got, source, orientation) + + +@pytest.mark.parametrize("orientation", ORIENTATIONS) +def test_a_generator_of_sources(orientation): + G = GRAPHS[3] + nodes = list(G)[:3] + want, got, first = _three_ways(G, orientation=orientation, fresh=lambda: (v for v in nodes)) + assert want[0] == got[0] == first[0] == "answer" + _assert_edge_bfs(G, got[1], want[1], nodes, orientation) + _assert_edge_bfs(G, first[1], want[1], nodes, orientation) + + +def test_a_string_is_read_by_its_characters(): + G = nx.DiGraph([("a", "b"), ("b", "c"), ("x", "a")]) + for source in ["ab", "bx", "zz"]: + want, got, first = _three_ways(G, source) + assert collections.Counter(got[1]) == collections.Counter(want[1]) + assert first == got + + +def test_a_node_that_is_a_string_is_one_node(): + G = nx.DiGraph([("ab", "c"), ("a", "b"), ("b", "d")]) + want, got, first = _three_ways(G, "ab") + assert got == want == first == ("answer", [("ab", "c")]) + + +ERRORS = { + "absent node": (nx.Graph([(0, 1)]), 5, None), + "absent node, directed": (nx.DiGraph([(0, 1)]), 5.5, None), + "unhashable member": (nx.Graph([(0, 1)]), [0, [1]], None), + "invalid orientation": (nx.DiGraph([(0, 1)]), 0, "hello"), + "invalid orientation, every node": (nx.DiGraph([(0, 1)]), None, "both"), + "unhashable orientation": (nx.DiGraph([(0, 1)]), [0], ["reverse"]), +} + + +@pytest.mark.parametrize("name", sorted(ERRORS)) +def test_errors_as_networkx_s(name): + G, source, orientation = ERRORS[name] + want, got, first = _three_ways(G, source, orientation) + assert want[0] is nx.NetworkXError + assert got == want == first + + +NOT_ERRORS = { + # NetworkX looks at `orientation` only after `source` names a node of a directed graph. + "invalid orientation, no node": (nx.DiGraph([(0, 1)]), [7], "hello"), + "invalid orientation, empty graph": (nx.DiGraph(), None, "hello"), + # An undirected graph's edges are all "forward", whatever the orientation. + "invalid orientation, undirected": (nx.Graph([(0, 1), (1, 2)]), 0, "hello"), + "reverse, undirected": (nx.Graph([(0, 1), (1, 2)]), 1, "reverse"), + "ignore, undirected": (nx.Graph([(0, 1), (1, 1)]), 0, "ignore"), + "empty graph": (nx.Graph(), None, None), + "empty source": (nx.Graph([(0, 1)]), [], "original"), +} + + +@pytest.mark.parametrize("name", sorted(NOT_ERRORS)) +def test_what_networkx_answers(name): + G, source, orientation = NOT_ERRORS[name] + want, got, first = _three_ways(G, source, orientation) + assert want[0] == "answer" + assert got == want == first + + +def test_errors_come_when_the_first_edge_is_asked_for(): + G = nx.DiGraph([(0, 1)]) + for source, orientation in [(5, None), (0, "hello"), ([0, [1]], None)]: + edges = nx.edge_bfs(G, source, orientation, backend="graphblas") + with pytest.raises(nx.NetworkXError): + next(edges) + + +def test_a_multigraph_is_left_to_networkx(): + G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 0)]) + want, got, first = _three_ways(G, 0, "ignore") + assert got[0] is NotImplementedError + assert first == want + + +@pytest.mark.parametrize("orientation", ORIENTATIONS) +def test_every_node_in_node_order(orientation): + """With no source every node starts, in node order, so each node's edges come in turn.""" + G = nx.DiGraph() + G.add_nodes_from([3, 1, 2, 0]) + G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 3), (2, 3)]) + got = list(nx.edge_bfs(G, None, orientation, backend="graphblas")) + want = list(nx.edge_bfs(G, None, orientation, backend="networkx")) + _assert_edge_bfs(G, got, want, None, orientation) + met = [e[1] if orientation == "reverse" or e[2:] == ("reverse",) else e[0] for e in got] + assert [x for x, _ in itertools.groupby(met)] == [v for v in G if v in met] + + +@pytest.mark.parametrize("orientation", ORIENTATIONS) +def test_both_ways_between_two_nodes(orientation): + G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 2)]) + want, got, first = _three_ways(G, 0, orientation) + _assert_edge_bfs(G, got[1], want[1], 0, orientation) + assert first == got + + +def test_a_backend_graph(): + G = nx.DiGraph([(0, 1), (1, 2), (3, 1)]) + H = ga.DiGraph.from_networkx(G) + for orientation in ORIENTATIONS: + for source in [None, 1, [3, 0]]: + got = list(nxapi.edge_bfs(H, source, orientation)) + want = list(nx.edge_bfs(G, source, orientation, backend="networkx")) + _assert_edge_bfs(G, got, want, source, orientation) + + +def test_a_backend_graph_whose_ids_are_not_in_node_order(): + A = Matrix.from_coo([0, 0, 2], [1, 2, 2], True, nrows=3, ncols=3) + H = ga.DiGraph(A, key_to_id={"b": 1, "c": 2, "a": 0}) # a -> b, a -> c, c -> c + G = nx.DiGraph([("a", "b"), ("a", "c"), ("c", "c")]) + for orientation in ORIENTATIONS: + for source in [None, "a", ["c", "b"]]: + got = list(nxapi.edge_bfs(H, source, orientation)) + want = list(nx.edge_bfs(G, source, orientation, backend="networkx")) + _assert_edge_bfs(G, got, want, source, orientation) + + +def test_a_deep_walk(): + G = nx.path_graph(3000, create_using=nx.DiGraph) + G.add_edge(2999, 0) + for orientation in ORIENTATIONS: + want = list(nx.edge_bfs(G, 1500, orientation, backend="networkx")) + got = list(nx.edge_bfs(G, 1500, orientation, backend="graphblas")) + _assert_edge_bfs(G, got, want, 1500, orientation) + if orientation != "ignore": + assert got == want # one way to walk a cycle diff --git a/graphblas_algorithms/nxapi/traversal/__init__.py b/graphblas_algorithms/nxapi/traversal/__init__.py index 7811162..055970d 100644 --- a/graphblas_algorithms/nxapi/traversal/__init__.py +++ b/graphblas_algorithms/nxapi/traversal/__init__.py @@ -1 +1,2 @@ from .breadth_first_search import * +from .edgebfs import * diff --git a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py index 1c4afc2..4b69291 100644 --- a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py +++ b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py @@ -1,16 +1,29 @@ +import warnings +from functools import cache + +import numpy as np + from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.components._labels import _keys_by_id +from graphblas_algorithms.classes._utils import source_of from graphblas_algorithms.classes.digraph import to_graph +from graphblas_algorithms.classes.graph import Graph -from .._utils import can_run +from .._utils import can_run, should_run from ..exception import NetworkXError __all__ = [ "bfs_edges", + "bfs_labeled_edges", "bfs_layers", + "bfs_predecessors", "bfs_successors", + "bfs_tree", "descendants_at_distance", ] +_LABELS = np.array(["tree", "level", "forward", "reverse"], dtype=object) # NetworkX's names + def _without_sort_neighbors(bound): # The order a node's neighbors are walked in picks the tree, and a matrix keeps none. @@ -49,6 +62,171 @@ def bfs_successors(G, source, depth_limit=None, sort_neighbors=None): yield from algorithms.bfs_successors(G, source, depth_limit=depth_limit) +def _converted(G): + """Whether NetworkX's cache holds a conversion of `G` to this backend. + + NetworkX reuses any conversion for a name that reads no attributes, as these do. + """ + import networkx as nx + + cache = getattr(G, "__networkx_cache__", None) + if not cache or not nx.config.cache_converted_graphs: + return False + converted = cache.get("backends", {}).get("graphblas", {}) + return any(isinstance(graph, Graph) for graph in list(converted.values())) + + +def _with_a_conversion(bound): + # Converting the graph costs more than NetworkX's walk on most graphs, and far more on a + # deep one or one the walk reaches little of, which nothing can see before the walk. + if _converted(bound["G"]): + return None + return "networkx is faster than converting this graph, of which no conversion is cached" + + +def _converted_either_way(bound): + """None where the graph is converted to this backend whether or not this call is served. + + NetworkX's own `bfs_predecessors` walks with the dispatched `bfs_edges`, which this backend + serves wherever it is in `bfs_edges`'s priority. Elsewhere NetworkX's walk costs less than + converting the graph, but for a conversion already cached. + """ + import networkx as nx + + priority = nx.config.backend_priority + if "graphblas" in priority.get("bfs_edges", priority.algos): + return None + return _with_a_conversion(bound) + + +@cache +def _networkx_deprecates_bfs_predecessors(): + import networkx as nx + + return tuple(int(part) for part in nx.__version__.split(".")[:2]) >= (3, 7) + + +@can_run(_without_sort_neighbors) +@should_run(_converted_either_way) +def bfs_predecessors(G, source, depth_limit=None, sort_neighbors=None): + """The parents in `bfs_edges`'s tree, which may differ from NetworkX's.""" + if _networkx_deprecates_bfs_predecessors(): + # NetworkX's own message, raised where its generator raises it. + warnings.warn( + ( + "\n\nbfs_predecessors is deprecated and will be removed in NetworkX 3.9\n" + "Use ``(t, s) for (s, t) in bfs_edges`` instead" + ), + category=DeprecationWarning, + stacklevel=2, + ) + if (reason := _without_sort_neighbors({"sort_neighbors": sort_neighbors})) is not None: + raise NotImplementedError(reason) + G = to_graph(G) + _check_source(G, source) + yield from algorithms.bfs_predecessors(G, source, depth_limit=depth_limit) + + +def _tree_left_to_networkx(bound): + # NetworkX's own `bfs_tree` builds the same DiGraph from the dispatched `bfs_edges`, which + # this backend serves wherever it is in that priority, so serving it here gains little; and + # with a conversion cached, building NetworkX's DiGraph costs what it costs NetworkX, so the + # gain is small against this backend's cost per level on a deep graph. + return ( + "networkx builds the same tree from the bfs_edges its priority names, and a deep " + "graph's walk costs more here" + ) + + +@can_run(_without_sort_neighbors) +@should_run(_tree_left_to_networkx) +def bfs_tree(G, source, reverse=False, depth_limit=None, sort_neighbors=None): + """`bfs_edges`'s tree, which may differ from NetworkX's. + + This backend's DiGraph for this backend's graph; for a NetworkX graph, NetworkX's DiGraph, + built as NetworkX builds it, so a NetworkX caller gets the graph it would have. + """ + if (reason := _without_sort_neighbors({"sort_neighbors": sort_neighbors})) is not None: + raise NotImplementedError(reason) + if source is None: + # NetworkX adds the source to the tree before it walks. + raise ValueError("None cannot be a node") + import networkx as nx + + # A NetworkX graph, or this backend's conversion of one + of_networkx = isinstance(G, nx.Graph) or source_of(G) is not None + G = to_graph(G) + _check_source(G, source) + if not of_networkx: + return algorithms.bfs_tree(G, source, reverse=reverse, depth_limit=depth_limit) + T = nx.DiGraph() + T.add_node(source) + T.add_edges_from(algorithms.bfs_edges(G, source, reverse=reverse, depth_limit=depth_limit)) + return T + + +def _has(key_to_id, node): + try: + return node in key_to_id + except TypeError: + return False + + +def _left_to_networkx(bound): + # Converting the graph costs more than NetworkX's whole walk, and with a conversion cached + # a caller that reads a few edges from each of many sources, as NetworkX's `girth` does, + # pays this backend's cost of starting a walk each time. + return ( + "networkx is faster: converting the graph costs more than its walk, and its girth " + "reads a few edges from every node" + ) + + +@should_run(_left_to_networkx) +def bfs_labeled_edges(G, sources): + """NetworkX's labeled edges, in a breadth-first order of this backend's own. + + The tree is `bfs_edges`'s, so which edges are "tree" and which "forward" may differ from + NetworkX's, as may the direction of an undirected "level" edge. Errors come where NetworkX + raises them: when the first edge is asked for, or for a source that is not a node, after + the edges of the sources before it. + """ + G = to_graph(G) + key_to_id = G._key_to_id + if _has(key_to_id, sources): + sources = [sources] + sources = list(dict.fromkeys(sources)) + absent = next((i for i, node in enumerate(sources) if node not in key_to_id), None) + if absent is not None: + # NetworkX walks the sources first, in order, and raises KeyError, from its adjacency, + # at the first that is not a node, having yielded the edges of those before it, which + # are the first of the walk's parts. + missing = sources[absent] + sources = [node for node in sources if node in key_to_id] + if sources and absent != 0: + source_ids = np.fromiter(map(key_to_id.__getitem__, sources), np.int64, len(sources)) + parts = algorithms.bfs_labeled_edges(G, source_ids) + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + # The sources' edges, NetworkX's tails as given + tails, heads, labels = next(parts) + if absent is not None: + parts, keep = (), np.isin(tails, source_ids[:absent]) + tails, heads, labels = tails[keep], heads[keep], labels[keep] + given = dict(zip(source_ids.tolist(), sources, strict=True)) + yield from zip( + map(given.__getitem__, tails.tolist()), + keys[heads].tolist(), + _LABELS[labels].tolist(), + strict=True, + ) + for tails, heads, labels in parts: + yield from zip( + keys[tails].tolist(), keys[heads].tolist(), _LABELS[labels].tolist(), strict=True + ) + if absent is not None: + raise KeyError(missing) + + def bfs_layers(G, sources): G = to_graph(G) try: diff --git a/graphblas_algorithms/nxapi/traversal/edgebfs.py b/graphblas_algorithms/nxapi/traversal/edgebfs.py new file mode 100644 index 0000000..2cf0a6f --- /dev/null +++ b/graphblas_algorithms/nxapi/traversal/edgebfs.py @@ -0,0 +1,47 @@ +import numpy as np + +from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.components._labels import _keys_by_id +from graphblas_algorithms.classes.digraph import to_graph + +from .._utils import nbunch_keys +from ..exception import NetworkXError + +__all__ = ["edge_bfs"] + +_HOW = np.array(["forward", "reverse"], dtype=object) # NetworkX's FORWARD and REVERSE + + +def edge_bfs(G, source=None, orientation=None): + """The edges NetworkX's `edge_bfs` yields, in a breadth-first order of this backend's own. + + Errors come as NetworkX raises them, when the first edge is asked for: those of `source` + as an nbunch, then, only if it names a node of `G` and `G` is directed, an orientation + other than None, "original", "reverse" or "ignore". + """ + G = to_graph(G) + keys = nbunch_keys(G, source, unique=True) + if keys is None: + source_ids = None + if len(G) == 0: + return + elif not keys: + return + else: + source_ids = G.list_to_ids(keys).astype(np.int64) + directed = G.is_directed() + if directed and orientation not in (None, "original", "reverse", "ignore"): + raise NetworkXError("invalid orientation argument.") + tails, heads, how = algorithms.edge_bfs( + G, + source_ids, + reverse=directed and orientation == "reverse", + ignore=directed and orientation == "ignore", + ) + # The cache's entry, which the components and core names read too. + id_to_keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + tails, heads = id_to_keys[tails].tolist(), id_to_keys[heads].tolist() + if orientation is None: + yield from zip(tails, heads, strict=True) + else: + yield from zip(tails, heads, _HOW[how].tolist(), strict=True) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..4e4aa0b 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -84,8 +84,11 @@ def call_args(kind, args): "betweenness_centrality": ("undirected", ()), "betweenness_centrality_subset": ("undirected", ([0, 1], [2, 3])), "bfs_edges": ("undirected", (0,)), + "bfs_labeled_edges": ("directed", ([0, 2],)), "bfs_layers": ("undirected", ([0],)), + "bfs_predecessors": ("undirected", (0,)), "bfs_successors": ("undirected", (0,)), + "bfs_tree": ("directed", (0, True)), "boundary_expansion": ("undirected", ([0, 1],)), # The tournament is the kind without an isolated node: eccentricity, and the names read # off it, raise on a graph in pieces. @@ -109,6 +112,7 @@ def call_args(kind, args): "disjoint_union": ("undirected", (SECOND_DISJOINT,)), "eccentricity": ("tournament", ()), "edge_betweenness_centrality": ("undirected", ()), + "edge_bfs": ("directed", (0, "ignore")), "edge_betweenness_centrality_subset": ("undirected", ([0, 1], [2, 3])), "edge_boundary": ("undirected", ([0, 1], [2, 3], True)), "edge_expansion": ("undirected", ([0, 1], [2, 3])), diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 1765e78..69f6388 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -480,7 +480,7 @@ def operands(name, build): return (G, H) if name in {"k_corona", "k_truss"}: return (G, 2) - if name == "ego_graph": + if name in {"bfs_tree", "ego_graph"}: return (G, 0) return (G,) @@ -548,7 +548,8 @@ def test_a_name_that_keeps_no_data_answers_any_graph_cold_and_warm(name): args = operands(name, every_kind_of_data) if warm: for graph in args: - nx.pagerank(graph, backend="graphblas") + if isinstance(graph, nx.Graph): + nx.pagerank(graph, backend="graphblas") got = Dispatcher.convert_to_nx(_registered_algorithms[name](*args, backend="graphblas")) assert nx.utils.graphs_equal(got, expected) diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py index 4bf5d09..293fc06 100644 --- a/graphblas_algorithms/tests/test_match_nx.py +++ b/graphblas_algorithms/tests/test_match_nx.py @@ -568,6 +568,7 @@ def test_signatures_match_nx(): # Every name whose answer is a graph, checked against NetworkX below. _RETURNS_GRAPH = [ + "bfs_tree", "complement", "compose", "difference", @@ -635,12 +636,23 @@ def _graph_call(name, weighted, backend): return _registered_algorithms[name](G, *built, backend=backend) +def _weight_of(result): + """The weight a result carries: a backend graph's own, or the key of a NetworkX graph's.""" + import networkx as nx + + if isinstance(result, nx.Graph): + # bfs_tree builds NetworkX's own DiGraph for a NetworkX graph, as NetworkX does + keys = {key for _u, _v, data in result.edges(data=True) for key in data} + return "weight" if "weight" in keys else None + return result._weight + + @pytest.mark.parametrize("name", _RETURNS_GRAPH) def test_an_unweighted_graph_returning_call_keeps_what_networkx_keeps(name): """Graph attributes are NetworkX's to decide: some of these names carry them, some not.""" expected = _graph_call(name, False, "networkx") result = _graph_call(name, False, "graphblas") - assert result._weight is None, f"{name} invented a weight for an unweighted graph" + assert _weight_of(result) is None, f"{name} invented a weight for an unweighted graph" back = _as_networkx(result) assert dict(back.graph) == dict(expected.graph) assert _edges(back) == _edges(expected) @@ -670,8 +682,8 @@ def test_a_weighted_graph_returning_call_carries_the_weight_or_says_it_cannot(na # so a weight there would be one this backend invented. belongs = "weight" if any(data for _u, _v, data in expected.edges(data=True)) else None assert ( - result._weight == belongs - ), f"{name} carries {result._weight!r} where networkx carries {belongs!r}" + _weight_of(result) == belongs + ), f"{name} carries {_weight_of(result)!r} where networkx carries {belongs!r}" result = _as_networkx(result) assert dict(result.graph) == dict(expected.graph) # Edge by edge: `full_join` adds edges that NetworkX leaves bare.