Skip to content

73 edge bfs - #171

Open
eriknw wants to merge 1 commit into
python-graphblas:46-bfs-own-orderfrom
eriknw:73-bfs-riders
Open

eriknw wants to merge 1 commit into
python-graphblas:46-bfs-own-orderfrom
eriknw:73-bfs-riders

Conversation

@eriknw

@eriknw eriknw commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Add edge_bfs, with every orientation: None, "original", "reverse" and "ignore". It yields each edge that a breadth-first walk from source reaches, once each. The walk goes a level at a time with any_pair products: over the out-edges; over the in-edges for "reverse"; over both for "ignore". Each node reached then gives its row of the adjacency, or of its transpose, and those rows are gathered in NumPy and deduplicated there. NetworkX walks each node's edges in Python, and on an undirected graph it builds a frozenset for every edge to yield it once.

  • What is exact. The edges are NetworkX's, each once, and so are their orientations wherever the walk fixes them.

    • A directed edge is yielded along itself, as "forward", or against itself for "reverse".
    • An undirected edge comes from the end the walk meets first, so it is oriented from the shallower end.
    • With "ignore", a directed edge is labelled "forward" when the walk meets it at its tail and "reverse" when it meets it at its head.
    • Between two nodes at the same depth, the direction or the label depends on which one the walk takes first, so it may differ from NetworkX's.
  • The order is breadth-first but this backend's own: first the nodes of source, as given, then each level in node order. Each node's edges come in the node order of their other ends, out-edges before in-edges. Any breadth-first order is a valid answer. NetworkX's order follows the order in which each node's edges were added, which a matrix does not keep.

  • As NetworkX reads its arguments:

    • source is read as an nbunch: None is every node in node order, a node is itself, and any other iterable gives its members that are in the graph. A repeated member counts once, and a string that is not a node is read by its characters.
    • A non-iterable that is not a node raises NetworkXError "Node 5 is not in the graph."; an unhashable member raises "Node [1] in sequence nbunch is not a valid node."
    • An orientation other than the four raises NetworkXError "invalid orientation argument." only where NetworkX raises it: on a directed graph, once source names one of its nodes. On an undirected graph every edge is "forward", whatever the orientation.
    • Errors come when the first edge is asked for, as from NetworkX's generator.
  • Left to NetworkX: multigraphs, as everywhere in this backend.

  • Speed. Indicative: dev, best of 2 interleaved in one process, conversion on every call unless cached, load 8.3 to 12.6. The loop column is NetworkX's 5 calls from random sources against one conversion and 5 calls.

    graph edges orientation NetworkX with conversion cached loop of 5 sources
    random, undirected, 6e5 nodes 3.0e6 None 11.7 s 2.29x 16.9x 8.85x
    random, directed, 6e5 nodes 3.0e6 None 5.31 s 2.03x 12.5x 7.32x
    random, directed, 6e5 nodes 3.0e6 "ignore" 6.95 s 2.14x 13.1x 6.91x
    random, directed, 6e5 nodes 3.0e6 "reverse" 2.80 s 1.22x 6.9x 4.14x
    power law, undirected, 3e5 nodes 3.0e6 "original" 7.85 s 2.78x 24.8x 10.6x
    grid, 1000 x 1000 2.0e6 None 3.80 s 2.70x 13.4x 8.42x
    dense, 2e4 nodes 3.0e6 None 6.41 s 3.09x 30.7x 11.5x
    • On small graphs, with conversion: 0.11x at 30 edges (0.03 ms against 0.30 ms), 0.51x at 300, 1.45x at 3000, 2.37x at 3e4 and 3.86x at 3e5.
    • NetworkX's transitive_closure of a graph with cycles calls edge_bfs from every node. With graphblas first in the priority, those calls are served from one conversion: 2.30x on 1000 nodes (5.53 s against 2.40 s) and 2.48x on 2000 nodes (17.8 s against 7.16 s). The rest of that time is NetworkX building the closure.
  • Memory. Peak RSS of one process on the undirected random graph of 3e6 edges is 2280 MB after edge_bfs with conversion and its edges listed, up from 1594 MB after building the graph. With "ignore" on the directed one it is 2123 MB, up from 1535 MB.

  • Also added: bfs_tree, bfs_predecessors and bfs_labeled_edges. They walk as bfs_edges does, a level at a time: each node's parent is its neighbor on the level above that comes first in node order (a min_first product). So the tree may differ from NetworkX's, which follows the order each node's edges were added.

    • bfs_tree gives a DiGraph with an edge from each parent to its child and no edge data. Its nodes are the source, as given, then each level's nodes in node order, which is the order bfs_edges yields them. reverse and depth_limit are NetworkX's.
    • For this backend's graph it is this backend's DiGraph. For a NetworkX graph served by name, it is NetworkX's own DiGraph, built as NetworkX's bfs_tree builds it: an empty DiGraph, the source added, then the edges. (On the automatic path NetworkX builds it itself, below.) NetworkX hands a returned graph to the caller as it is (only its test mode converts one back), and this backend's DiGraph lacks much of NetworkX's graph interface (edges, nodes, successors, degree and more), so a NetworkX caller gets the graph it would have had. Making this backend's graph classes complete is left to its own change.
    • To tell the two apart, each conversion now records, weakly, the NetworkX graph it was made from: remember_source and source_of in classes/_utils.py and two lines of convert_from_nx, carried identically from 50 spanning trees #151. A graph built with from_networkx has no record, so it is this backend's own.
    • Not taken: a conversion that is a snapshot (of a graph whose adjacency is virtual, as NetworkX's _AntiGraph's is) is not recorded, as in 50 spanning trees #151, so its tree is this backend's DiGraph; and a conversion made by calling convert_from_nx by hand is recorded, so its tree is NetworkX's. A conversion copied along with its NetworkX graph (copy.deepcopy or pickle, which copy the graph's cache) has no record either, so bfs_tree(G, s, backend="graphblas") on such a copy returns this backend's DiGraph; the automatic path is unaffected, since it leaves a NetworkX graph's bfs_tree to NetworkX.
    • bfs_predecessors yields (child, parent) for that tree, in bfs_edges's order, with the source as given. Where NetworkX deprecates it (3.7 and later), it gives NetworkX's DeprecationWarning, with its message, when the first pair is asked for; in 3.6.1 it gives none. An earlier decision not to register bfs_predecessors, as serving it would lose that warning, is superseded: the warning is now NetworkX's.
    • bfs_labeled_edges yields NetworkX's edges with NetworkX's labels. "level" and "reverse" are fixed by the depths of the two ends, so they are exact; which edges are "tree" and which "forward" follows the tree. An undirected graph gives no reverse edges and each level edge once, from the end reached first. A self-loop is a level edge.
    • Its order: the sources first, as given, then each level in node order, each node's edges by the other end's node order. A node one step from several sources is the child of the first given, so the first edge into each node is its tree edge, as NetworkX's labels say ("forward" means its head was already reached). The walk goes only as far as the edges read need, as NetworkX's generator does: it labels whole levels at a time, each part about twice as many nodes as the one before.
    • The labels are NetworkX's own string objects, which NetworkX's girth compares by identity.
  • Their errors, as NetworkX raises them.

    • A source that is not a node raises NetworkXError for bfs_tree and bfs_predecessors. None raises ValueError "None cannot be a node" for bfs_tree, and an unhashable source raises TypeError.
    • bfs_labeled_edges reads sources as NetworkX does: a node, or else an iterable of nodes, each counted once. A non-iterable that is not a node raises TypeError. A source that is not a node raises KeyError, after the edges of the sources before it have been yielded.
    • The generators raise when first read. sort_neighbors is declined, as in bfs_edges: a NetworkX graph on the automatic path goes to NetworkX, and this backend's graph, or a call with backend="graphblas", raises NotImplementedError.
    • A depth_limit of 0 or less walks no level, and so do -inf and NaN, as in NetworkX: bfs_tree gives the source alone and bfs_predecessors nothing. Before, -inf raised OverflowError and NaN TypeError in bfs_edges and bfs_successors too, which share the walk.
  • Which calls are served.

    • A graph of this backend's: every call, with no conversion. A test counts convert_from_nx calls through each name, and through a call on the tree bfs_tree returned, and finds none. A declined argument raises NotImplementedError there, as NetworkX falls back only for its own graphs.
    • backend="graphblas": every call.
    • A NetworkX graph on the automatic path, by should_run. The rival is NetworkX, and the measure is end to end, the conversion included, for each name.
      • bfs_predecessors is served where the graph is converted either way: a conversion of it is cached, or this backend is in bfs_edges's priority. NetworkX's own version calls bfs_edges, which would convert the graph and be served here. Served then, it is 0.96x to 1.18x as fast as NetworkX's own walk on the bfs_edges served here, about the same. Elsewhere it is left to NetworkX.
      • bfs_tree is left to NetworkX, even with a conversion cached or this backend in bfs_edges's priority. NetworkX's own bfs_tree then walks with the bfs_edges its priority names, this backend's included, and builds the same DiGraph. Serving it here would be 0.85x to 1.12x as fast as that, about the same.
      • Not taken, until the cost per level is fixed: serving bfs_tree where the graph is converted either way, as bfs_predecessors is. Building NetworkX's DiGraph costs here what it costs NetworkX, so from a cached conversion bfs_tree is 0.95x to 2.07x of NetworkX alone, against 0.04x on a path, whose walk pays this backend's cost per level once a node. (NetworkX would ask a backend for bfs_tree, which returns a graph, by backend_priority.generators or bfs_tree's own priority, not by algos.)
      • bfs_labeled_edges is left to NetworkX, even with a conversion cached. With the conversion it is 0.64x at best. Cached it is 1.4x to 5.0x on graphs of 1e5 nodes or more that are not a path or a grid, but NetworkX's girth, the one caller of it in NetworkX, reads a few edges from every node. Served from a cached conversion, girth is 0.012x to 0.019x of NetworkX's on graphs of 1600 to 20000 nodes: each call takes 157 to 206 microseconds here, against 2.1 to 3.8 in NetworkX.
    • Not taken: a size and degree threshold. Converting costs about the same per stored entry wherever the walk goes. NetworkX's walk costs per node and edge it reaches, and this backend's adds a cost per level.
      • With the conversion, bfs_tree is at best 1.12x: 0.60x to 1.12x on graphs of 1e5 nodes or more with at most 10 entries per node, other than a path, since it builds NetworkX's DiGraph as NetworkX does.
      • On graphs of that size and degree it is also 0.04x on a path (a level per node) and 0.00x from a source with no edges, where NetworkX takes 0.006 ms and this backend 52 ms with the conversion.
      • How deep the walk goes and how much of the graph it reaches are not known before it runs. Where such a threshold misses, the loss is 23x to 8600x; where it hits, the gain is at most 1.12x.
  • Their speed. Indicative: dev (NetworkX 3.7.1rc0.dev0, Python 3.14), JIT on and warmed, one process per graph. Each time is the mean over at least 0.2 s, and three interleaved rounds give the median. Load 3.1 to 4.6. The results are consumed: the generators are listed, and bfs_tree's graph is taken as returned.

    • For bfs_predecessors and bfs_labeled_edges, "cached" is within 5% of this backend's own graph, except from the source with no edges, where a call takes 0.03 to 0.22 ms.
    • bfs_tree's columns come from a later run, at load 3.1 to 3.8, of code whose calls by name are this change's, where a NetworkX graph's tree is NetworkX's DiGraph. Building it costs what it costs NetworkX, so cached is 0.95x to 2.07x, except on a path (0.04x) and from the source with no edges (0.13x). On this backend's own graph, whose tree is this backend's DiGraph, it is 2.6x to 68x, again except on a path (0.04x to 0.05x) and from the source with no edges (0.09x).
    graph entries per node bfs_tree: NetworkX, with conversion, cached bfs_predecessors bfs_labeled_edges
    random, 1e3 nodes 4 0.91 ms, 0.45x, 0.95x 0.24 ms, 0.18x, 0.74x 0.30 ms, 0.18x, 0.56x
    path, 1e6 nodes 2 1.12 s, 0.04x, 0.04x 202 ms, 0.01x, 0.01x 152 ms, 0.01x, 0.01x
    random tree, 1e6 nodes 2 2.41 s, 0.67x, 1.03x 820 ms, 0.53x, 3.54x 759 ms, 0.45x, 2.08x
    grid, 1000 x 1000 4 1.38 s, 0.70x, 1.30x 297 ms, 0.28x, 1.61x 329 ms, 0.28x, 1.01x
    random, 1e5 nodes 4 315 ms, 1.12x, 1.97x 134 ms, 0.88x, 14x 89 ms, 0.47x, 3.39x
    random, 1e5 nodes 64 474 ms, 0.23x, 1.43x 171 ms, 0.10x, 20x 1.44 s, 0.63x, 4.96x
    random, 1e6 nodes 10 5.28 s, 0.79x, 2.07x 3.52 s, 0.74x, 30x 3.51 s, 0.64x, 4.02x
    random directed, 1e6 nodes 5 4.22 s, 0.74x, 1.50x 2.35 s, 0.77x, 18x 2.19 s, 0.59x, 2.82x
    power law, 3e5 nodes 20 986 ms, 0.47x, 2.03x 504 ms, 0.31x, 16x 705 ms, 0.37x, 2.30x
    dense, 2e4 nodes 298 59 ms, 0.04x, 1.76x 18 ms, 0.01x, 7.83x 1.07 s, 0.62x, 4.29x
    a source with no edges, 1e5 nodes 0.8 0.006 ms, 0.00x, 0.13x 0.004 ms, 0.00x, 0.10x 0.001 ms, 0.00x, 0.01x
    • On a path the walk costs about 25 microseconds a level, on this backend's own graph too, and bfs_edges and bfs_successors share that walk. Taking narrow levels another way would help all of them.
    • NetworkX's own bfs_tree and bfs_predecessors with this backend in bfs_edges's priority, the conversion counted, are at best 1.13x and 0.74x of NetworkX alone.
    • Peak RSS of one process, with NetworkX's graph and its conversion, is 3.9 GB at most (5e6 edges).
  • Dispatcher.should_run, with a hook per wrapper (nxapi._utils.should_run, as can_run has), carried identically from 50 spanning trees #151.

  • A fix to edge_bfs. It cached the node keys under the name the components and core names use for a pair of arrays. So on one graph, k_core then edge_bfs raised TypeError, and edge_bfs then k_core raised ValueError. It now reads that pair. A test calls them in both orders, and with connected_components.

  • Tests. 320 seeded graphs, directed and undirected. Their node order is not their label order, their edges were added in a random order, a quarter have self-loops, and some have isolated nodes or string labels. Each is run with every orientation and with source as None, one node, a list with an absent node and a repeat, or an empty list. The tests check:

    • the edges are NetworkX's as a multiset, with NetworkX's labels where the walk fixes them;
    • each edge is met from a node no deeper than its other end;
    • the nodes edges are met from come in order of depth, each node's edges together, in the order the notes give;
    • every error and non-error above, three ways (NetworkX, graphblas by name, graphblas first in the priority with the fallback off), and that errors wait for the first edge;
    • generators and strings as source, a multigraph left to NetworkX, graphs of this backend (one whose ids are not in node order), and a walk 3000 nodes deep.

    27 mutants of the kernel and wrapper each fail them, in dev, 3.7 and 3.6.1.

  • Tests of the three added names. 80 random graphs, directed and undirected, with self-loops, isolated nodes and nodes added out of order; tuple nodes; a graph of this backend's whose ids are not in node order; a path 1500 deep. The tests check:

    • bfs_tree: NetworkX's nodes, each but the source the child of one parent a level up joined to it in the walk's direction, with every reverse and depth_limit; bfs_edges's order and edges; for a NetworkX graph, NetworkX's DiGraph, equal node for node and edge for edge to the one NetworkX builds from those edges, by name and from the wrapper itself; for this backend's graph, this backend's DiGraph. On the automatic path a NetworkX graph's tree is not served (a counter on the served calls), with this backend in bfs_tree's priority, in generators, in bfs_edges's, and with a conversion cached, and NetworkX's own tree walks with the bfs_edges served here. Each conversion's record of its NetworkX graph, and that it goes with the graph.
    • Depth limits of -inf, NaN, -1, -0.5 and 0 walk no level in bfs_tree, bfs_predecessors, bfs_edges and bfs_successors, and 0.5 walks one, as NetworkX's do.
    • bfs_predecessors: bfs_edges's tree as pairs, NetworkX's children, fractional depth limits, and the source as given, its type included.
    • bfs_labeled_edges: NetworkX's edges and labels as multisets, from one source, several (not in node order too), and a repeated one; each level edge within a level, each reverse edge back up, each tree and forward edge one level down, one tree edge into each node reached; the walk replayed edge by edge, so that an edge into a node not yet reached is its tree edge and no other edge is, before a KeyError too; the sources walked in the order given; the walk's order; the edges written out for two small graphs; that the walk goes only as far as the edges read; and the labels being NetworkX's objects, through girth.
    • Every error above, against NetworkX's type and message (the type alone for an unhashable source, whose message names the container Python hashed it in), and the edges yielded before a KeyError; that the generators raise when first read; NetworkX's DeprecationWarning as NetworkX gives it.
    • No conversion on this backend's graphs (a counter on convert_from_nx); each routing rule, with and without a cached conversion, with this backend in bfs_edges's priority, and with NetworkX's cache turned off; that NetworkX's own versions convert the graph for bfs_edges there; that a cached value that is not this backend's graph counts as no conversion.
    • The node keys shared by edge_bfs, these names, k_core and connected_components, called in both orders.

    47 mutants of the kernel, the wrappers, the routing, the hook, the conversion's record and the shared keys each fail them. 45 fail them in dev, 3.7 and 3.6.1 alike. The other two change only whether the DeprecationWarning is given, and fail them where that differs: always giving it in 3.6.1, never giving it in dev and 3.7. The repo's tests pass in dev, 3.7 and 3.6.1.

  • NetworkX's tests. algorithms/traversal/tests/test_edgebfs.py, the doctests of algorithms/traversal/edgebfs.py, and algorithms/tests/test_dag.py, whose transitive_closure calls edge_bfs, were run through the backend in dev, 3.7 and 3.6.1. The same tests pass before and after (94, 94 and 84).

    • After the change, the backend serves 75 calls in each environment (59 on directed graphs, 16 on undirected ones). The 31 left to NetworkX are its multigraph tests.
    • None needed an xfail. NetworkX's exact sequences in test_edgebfs.py come out in this order on its graphs.
  • NetworkX's tests of the three added names. algorithms/traversal/tests/test_bfs.py and the doctests of breadth_first_search.py, with test_cycles.py and the doctests of cycles.py (whose girth calls bfs_labeled_edges), test_edgebfs.py, the doctests of edgebfs.py, and test_dag.py, through the backend in dev, 3.7 and 3.6.1. The same tests pass before and after (189, 189 and 179).

    • One fails before and after in each: the bfs_layers doctest, which prints each layer in the order NetworkX met its nodes.
    • After the change the backend serves 250 calls of bfs_labeled_edges, 7 of bfs_predecessors and 5 of bfs_tree in each environment. NetworkX's test mode does not ask should_run, so it serves girth's calls and bfs_tree's too.
    • The calls of bfs_edges fall from 18 to 11, as bfs_tree and bfs_predecessors no longer call it.
    • Test mode compares a returned graph with NetworkX's exactly, and the 5 trees match. NetworkX's tests of the DeprecationWarning pass.

Stacked on #146.

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.
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.89909% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 93.45%. Comparing base (9f5e7dc) to head (94558a9).

Additional details and impacted files
@@                 Coverage Diff                  @@
##           46-bfs-own-order     #171      +/-   ##
====================================================
+ Coverage             92.89%   93.45%   +0.56%     
====================================================
  Files                   182      186       +4     
  Lines                 11305    12290     +985     
  Branches               1290     1393     +103     
====================================================
+ Hits                  10502    11486     +984     
- Misses                  548      549       +1     
  Partials                255      255              
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant