Skip to content

50 spanning trees - #151

Open
eriknw wants to merge 1 commit into
python-graphblas:20-wiener-efficiencyfrom
eriknw:50-spanning-trees
Open

eriknw wants to merge 1 commit into
python-graphblas:20-wiener-efficiencyfrom
eriknw:50-spanning-trees

Conversation

@eriknw

@eriknw eriknw commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Add minimum_spanning_tree, maximum_spanning_tree, minimum_spanning_edges and maximum_spanning_edges. The forest is Boruvka's over edges ranked by weight: each round every component takes the lightest edge leaving it (a scatter-min over the edges that still join two components) and the components merge by pointer jumping. The answer is a valid spanning forest, one tree per component, with NetworkX's total weight; where weights tie it may be a different forest from NetworkX's, whichever algorithm is named. Equal weights are taken by their ends in node order, the same on every platform. NetworkX's Kruskal takes them in G.edges() order, which is that order where each node's neighbors were added in node order, and there the forest is Kruskal's. Where the weights are distinct the forest is unique, and the edges are NetworkX's.

  • The graph's own data. Each conversion now records, weakly, the NetworkX graph it was made from. The edges names yield that graph's own dicts, as NetworkX's do, and the trees are built as NetworkX builds them: the graph's class, then copies of its graph, node and edge dicts. The matrix gives only the weights, so a tree is never rebuilt from it, and the trees serve graphs with node data (they are not "rebuild" names, so the node-data refusal does not apply to them; a rebuild name that later meets their cached conversion is still declined in can_run).
  • Declined, so NetworkX answers: a conversion that was copied or unpickled (no graph recorded); a view whose graph has since lost an edge (NetworkX keeps the view's cached conversion); complex weights; ints past 2**53 held as floats that tie with another weight; an infinite weight with algorithm="boruvka", since NetworkX's Boruvka never takes an edge that is not lighter than infinity and so leaves it out; a NaN self-loop with algorithm="prim", which NetworkX reads only at a node it starts a tree from; an unhashable weight; a graph where some edges carry weight and some do not, which the conversion declines (NetworkX takes a missing weight as 1).
  • Not served, by the existing conversion rule: with data=True (the default) and for the trees, a graph whose edges carry more than one attribute, or the weight on some edges only. NetworkX's cache gives one conversion that carries the edge data to every name that asks for one, and edge_boundary(data=True) reads its values back as the edge data, so this change keeps such a conversion as it is. data=False converts only the weight and serves any graph.
  • NaN weights. ignore_nan=True leaves those edges out. Otherwise ValueError, "NaN found as an edge weight. Edge (u, v, d)", where NetworkX's algorithm reads the weight: Kruskal every edge's (self-loops too), Boruvka and Prim each edge's between two nodes. The generators raise when first asked for an edge; NetworkX's Prim yields some edges first, and which NaN edge is named may differ. The conversion adds a self-loop's weight in twice and takes it out once, so a loop of weight inf or -inf is NaN on the matrix's diagonal too; a NaN there is checked against the graph's own weight, and only a real NaN raises. On 4000 random graphs with self-loops of NaN, inf, -inf and 1e308 through each name, algorithm and ignore_nan, the answers match NetworkX's in dev, 3.7 and 3.6.1, where before this check 208 of those calls raised ValueError under Kruskal where NetworkX answers, and 187 more were left to NetworkX.
  • Errors as in NetworkX: a directed graph raises NetworkXNotImplemented; an unknown algorithm raises its ValueError when called (an unhashable one, TypeError). Multigraphs are declined, as everywhere in this backend.
  • Order. The edges come lightest first (heaviest first for the maximum), as Kruskal's do, equal weights by their ends in node order; the orientation of each edge is this backend's own.
  • Speed (Indicative, interleaved with NetworkX's Kruskal, best of 3, one process, conversion included; load 9 to 11). At 1e6 edges (1e5 nodes): the trees 1.21x and 1.06x, the edges with data 1.23x, without data 1.56x; on a cached conversion 4x to 6x. At 1e5 edges NetworkX is faster (0.50x to 0.99x), since the conversion costs about as much as Kruskal. So should_run leaves graphs of fewer than 800000 edges to NetworkX, or 200000 when only the weights are converted (data=False). An earlier run at load 4 to 5 gave the same picture. The conversion that carries the edge data spends 0.39 s of its 0.87 s at 1e6 edges checking the values in Python; a faster check would help these names and every name that rebuilds its input.
  • Also added: Dispatcher.should_run with a per-wrapper hook (nxapi._utils.should_run), as can_run has.
  • Tests. Every name, algorithm and weight kind (distinct and tied floats, tied ints, big ints) on random graphs with several components, isolated nodes and self-loops: a spanning forest with NetworkX's total weight (exact for ints; for floats approx(rel=1e-12), the largest difference seen over 600 calls being 0), NetworkX's edges where the weights are distinct, the data carried (dict identity for the edges, copies whose values are the graph's objects for the trees), every decline and error above, and self-loops of NaN, inf, -inf and +-1e308 under each algorithm and ignore_nan. 33 mutants of the kernel, the wrapper, the conversion record and the dispatcher each fail them, in NetworkX dev, 3.7 and 3.6.1. Equal weights are checked against Kruskal's forest where neighbors were added in node order, on random tied graphs and on a grid of one weight, as are NetworkX's Steiner test graphs; 5 mutants of the tie order each fail them, in NetworkX dev, 3.7 on Python 3.14 and 3.13, and 3.6.1.
  • NetworkX's tests of these names and of the algorithms that call them (test_mst, test_decomposition, test_cycles, the Steiner tree, traveling salesman and edge augmentation tests), through the backend in dev, 3.7 and 3.6.1: the same tests pass before and after (235, 235 and 234), with 170 spanning-tree calls served in each. None needed an xfail, though some pin a tie choice. test_steiner_tree[mehlhorn] lists the trees it accepts, and NetworkX's test mode compares a returned tree with NetworkX's exactly, which four traveling salesman tests reach through Christofides. With the ties in a random order (a test plugin), those fail for most orders, while the forests keep NetworkX's weight and the Steiner trees the listed trees' weight (14 on the test's third graph). The kernel first sorted with NumPy's default argsort, which orders equal values differently on different CPUs, and the Steiner test failed in CI on Linux x86 alone. The sort is now stable; its order is Kruskal's on these graphs, and they pass on every platform. The whole NetworkX suite through the backend on Python 3.13 passes in 3.6.1 and 3.7.

Stacked on #121.

The forest is Boruvka's, over edges ranked by weight: each round every
component takes the lightest edge leaving it, found with a scatter-min
over the edges that still join two components, and the components
merge by pointer jumping. Ranks break ties, from a stable sort, so
equal weights go by their ends in node order on every platform.
NetworkX's Kruskal takes them in G.edges() order, the same order where
each node's neighbors were added in node order, and there the forest
is Kruskal's. Elsewhere, where weights tie, it may differ from
NetworkX's, whichever algorithm is named, with the same total weight.

The answer carries the graph's own data, as NetworkX's does: each
conversion records the NetworkX graph it was made from, held weakly,
and the edges yield that graph's dicts, while the trees are built as
NetworkX builds them, from its graph, nodes and edge dicts. A matrix
gives only the weights, so the trees take graphs with node data. A
conversion that was copied or unpickled has no graph recorded and is
declined, as is a view's whose graph has since lost an edge.

A NaN raises ValueError where NetworkX's algorithm reads it: Kruskal
any edge's, Boruvka and Prim an edge's between two nodes, the edges
when first asked for. The conversion adds a self-loop's weight in twice
and takes it out once, so a loop of inf or -inf is NaN on the diagonal
too, and there the graph's own weight decides. Left to NetworkX: a NaN
self-loop with Prim, which reads it only where it starts a tree; an
infinite weight with Boruvka, which leaves such an edge out; complex
weights; and ints past 2**53 held as floats that tie. Converting the
graph costs more than Kruskal on small graphs, so should_run leaves
graphs of under 800000 edges to NetworkX, or 200000 where only the
weights are converted.
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.64865% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.20%. Comparing base (5b54ace) to head (0604cc2).

Additional details and impacted files
@@                   Coverage Diff                    @@
##           20-wiener-efficiency     #151      +/-   ##
========================================================
+ Coverage                 92.88%   93.20%   +0.32%     
========================================================
  Files                       182      185       +3     
  Lines                     11227    11885     +658     
  Branches                   1274     1336      +62     
========================================================
+ Hits                      10428    11078     +650     
- Misses                      546      551       +5     
- Partials                    253      256       +3     
🚀 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