Guide/How it works
Algorithm Implementation Notes
7 min readFrom the README
On this page 12
The native algorithm implementations in fnx-algorithms favor textbook complexity bounds. CGSE registers policies and optional witness collection for twelve reference algorithms; instrumentation does not yet cover every public route. The notes below cover the most-used families.
Shortest path
- Dijkstra. Standard binary-heap Dijkstra. Internally uses a
DijkstraState { dist: f64, seq: u64, node }struct whoseOrdimpl reverses the dist comparison (so a max-heap acts as a min-heap, with no per-pushReverse(_)wrapper) and tie-breaks equal-distance entries by insertion-counterseqto match NetworkX'sheapq-with-counter behavior exactly. Single-source / multi-source / bidirectional all share the same kernel. The+∞and negative-weight gates are short-circuit native scans before the algorithm enters its main loop; invalid input fails fast or delegates tonxper the documented contract. - Bellman-Ford. O(VE) relaxation with predecessor reconstruction. Negative-cycle detection scans the last-pass relaxation; the canonical error wording matches NetworkX's exact string (regression-locked in
test_bellman_ford_negative_cycle_message_parity.py). - A.* Standard heuristic-guided Dijkstra. The heuristic callable contract was tightened in commit
b7d9e785(franken_networkx-74xw) to honor NetworkX's exact signature. - Johnson all-pairs. Edge re-weighting via Bellman-Ford + Dijkstra from every source. The inner-dict ordering of
johnsonwas specifically locked to NetworkX's order inbr-r37-c1-9l73c.
Connectivity
- Connected components. Index-based BFS with a packed visited bitset. Emits
PySetper component directly through PyO3, skipping a Vec → set conversion pass. - Strongly connected components. Tarjan's iterative variant (avoids Rust stack overflow on deep DAGs). Kosaraju is available as
kosaraju_strongly_connected_componentsfor parity tests where NetworkX uses it specifically. - Articulation points / bridges. Single DFS, parent-tracking, low-link propagation. The DFS visit order is the documented
BfsLevelLex/DfsPreordervariant from CGSE. - Node / edge connectivity, min cuts. Built on max-flow over a residual graph; custom
flow_funccallables are explicitly rejected bycan_runso nx's slower-but-flexible path takes over when needed.
Centrality
- PageRank. The public
pagerankbuilds the adjacency as CSR arrays natively in Rust, then runs the damped power iteration as a scipy sparse matvec mirroring nx's_pagerank_scipyfloat for float (br-r37-c1-y5y7i, 2026-05-24); the nonfinite-weight scan and dangling handling stay native. A Rust power-iteration kernel exists as_fnx.pagerankbut is not on the public route, sopagerankrequires scipy, exactly as it does in NetworkX. - Betweenness. Brandes' algorithm. Subset variants (
betweenness_centrality_subset,edge_betweenness_subset) share the same accumulator infrastructure. - HITS. Power iteration on the adjacency operator and its transpose.
numpyvariants offload eigensolvers to SciPy with sign/basis tolerance baked into the test layer. - Katz / eigenvector / closeness / harmonic. Standard formulas.
harmonic_centralityspecifically matches NetworkX's set-based dict iteration order (locked inbr-r37-c1-rsom6). - Voterank. Iterative selection with explicit
LexMintie-break.
Matching
- Maximum-weight matching. The public
max_weight_matchingrunsnetworkx_max_weight_matching_mate, a step-for-step Rust port of networkx's blossom algorithm (br-r37-c1-epic-native-algorithms-1g0lj.1): it makes every order-dependent choice in networkx's order and returns networkx'smateinsertion order, so on graphs with several optimal matchings it picks networkx's, with networkx's(u, v)direction for each pair (an earlier native kernel did neither,br-r37-c1-kpnc8). Weights other than ints within ±2⁴⁸ and finite floats keep networkx's own code.min_weight_matchingis networkx's body over it (the inverted graph built as networkx builds it). Both raiseNetworkXNotImplementedon directed and multigraph input, as networkx does. - Maximal matching. Greedy with canonical edge enumeration; suitable as a lower-bound approximation.
- Bipartite matching helpers (
hopcroft_karp_matching,eppstein_matching,minimum_weight_full_matching). Live underfnx.bipartite.*and currently delegate to the upstreamnetworkx.algorithms.bipartitereference. Tracked indocs/delegation_ledger.md.
Flow
- Maximum flow and minimum cut. Public
maximum_flow,maximum_flow_value,minimum_cut, andminimum_cut_valuedefault to nativepreflow_push(crates/fnx-algorithms/src/preflow_push.rs,br-r37-c1-uh5ua), matching NetworkX's default preflow-push flow dictionary and minimum-cut partition byte-for-byte. Edmonds-Karp on the residual graph remains available viaedmonds_karpand for internal connectivity callers (edmonds_karp=True). - Stoer-Wagner. Native O(V·E + V²·log V) global min-cut.
- Gomory-Hu tree. Native; rejects MultiGraph input with a typed
NetworkXErrormatching nx. - Min-cost flow. Successive-shortest-path + Bellman-Ford for negative-edge support; delegates to nx for undirected input (
NetworkXNotImplemented). - Exact-integer network simplex (
fnx_algorithms::network_simplex_int). The exact-integer primal network-simplex kernel is a first-class Rust API, re-exported from thefnx-algorithmscrate root, so sibling Rust consumers can reach the exact min-cost-flow path directly without taking a PyO3 dependency. It is specialised toi64demands/capacities/weights — the only byte-exact-integer case — with nof64anywhere on the path, so results are exact and reproducible. Originally this pivot logic lived inside thefnx-pythonbinding; it was hoisted intofnx-algorithmsin commit6de8937d, and the Pythonnetwork_simplexbinding now delegates to this shared kernel, so the Rust API and the Python binding run identical pivot code and produce byte-identical numeric results. The block/Dantzig+Bland entering-edge search and the first-minimiser leaving-edge tie-break (matching Python'smin) are deterministic and covered by unit tests (determinism_across_repeated_runs,known_integer_optimum).
Trees and arborescences
- MST. Kruskal's with union-find;
partition_spanning_tree/random_spanning_tree/number_of_spanning_treesare exposed. - Edmonds' branching. Native rewrite (commit
9edb5819) using explicitEdmondsMultiDiGraph+UnionFindstructures; deterministic edge sort. - SpanningTreeIterator / ArborescenceIterator. Janssens-Sörensen partition scheme for lazy enumeration of all minimum spanning trees / arborescences; the partition logic is module-level and reusable.
Community
The fnx.community submodule mirrors nx.algorithms.community. Most algorithms currently route through nx after parity-converting the graph (the _networkx_graph_for_parity adapter); the native rewrites are landing one by one.
- Louvain (
louvain_communities). A native Rust kernel (_raw_louvain_communities) handles a plain unweightedfnx.Graphwithout self-loops. Every other shape (weights, self-loops, directed, multigraph, nx input) converts and routes throughnx.algorithms.community.louvain_communities, pinned to the networkx backend so a globalbackend_prioritycannot recurse (br-r37-c1-egjfn); nx's multi-level Louvain produces wrong partitions against a raw fnx graph, hence the conversion. - Label propagation (
label_propagation_communities). A Python implementation over nativegreedy_colorand adjacency forfnx.Graph; multigraph, view and non-fnx inputs route through nx (br-r37-c1-cy2me). - Greedy modularity (
greedy_modularity_communities). Runsnetworkx_greedy_modularity_merges, a step-for-step Rust port of networkx 3.6's Clauset-Newman-Moore loop (br-r37-c1-epic-native-algorithms-1g0lj.3): itsMappedQueueheaps with equal gains broken by node label, as networkx's_HeapElementcompares them, and the same float arithmetic from the same setup values. The merges are replayed into networkx'scommunitiesdict, so the result is networkx's: the same communities in the same order, each frozenset built the same way. Measured 12.3–13.4× faster than networkx on 2,000–5,000-node graphs (weighted and unweighted) with identical results; same-process interleaved probe, 3 rounds, A/A null 0.96–1.03, loaded host (load 39), 2026-09-24. Graphs whose node labels are not allintor allstr, weights other than ints within 2⁵³ and floats, and NaN gains keep networkx's own code, which is also the backend-mode fallback, pinned so it cannot recurse. An earlier native route was retired for picking different equal-gain merges (br-r37-c1-z4rnj). - K-clique communities, Girvan-Newman, asyn_fluidc, Kernighan-Lin bisection. Mixed: some native, some delegated. Check
docs/delegation_ledger.mdfor the canonical state of each. community.modularity. Computed natively against fnx adjacency.
Isomorphism
- VF2 / VF2++. Native no-label VF2++ implementation. With node/edge label callbacks, the algorithm falls back to NetworkX's reference matcher to honor the user-provided callable contract.
could_be_isomorphic/fast_could_be_isomorphic/faster_could_be_isomorphic. Quick degree/clustering invariant checks before invoking the full matcher.
Planarity
is_planar/check_planarity.is_planarruns Euler and degree bounds and then the native left-right planarity kernel (is_planar_lr), so K5, K3,3 and Petersen are decided in Rust.check_planaritybuilds nativePlanarEmbeddingclockwise rotation orders (Boyer-Myrvold edge-addition) and extracts native Kuratowski subgraph counterexamples without NetworkX.
DAG
- Topological sort. Kahn's algorithm with zero-in-degree nodes queued in insertion order (the registry's
InsertionOrderpolicy); matches nx's order exactly, including ties. - Transitive closure. O(V·(V+E)) DFS-based, preserves node + edge attributes on the DAG fast path (regression
br-r37-c1-gtkxs). - Dominators. Cooper-Harvey-Kennedy iterative algorithm: reverse-postorder DFS followed by intersect-by-walking-up until fixpoint.
immediate_dominators+dominance_frontiers.
Polynomial / spectral
- Tutte polynomial / chromatic polynomial. Native straight-line deletion-contraction recursion (exponential time, no memoization; intentional, matching NetworkX's reference behavior on small graphs).
- Spectral helpers.
laplacian_spectrum,adjacency_spectrum,modularity_spectrum,fiedler_vector,algebraic_connectivity; built onscipy.linalg.eigh/scipy.sparse.linalg.eigsh. Solver-method validation (fiedler_method) is enforced (br-r37-c1-pvge4).
Generators
- Random generators (BA, WS, GNP, GNM, fast_GNP). Deterministic seeded RNG; edge enumeration order matches NetworkX byte-for-byte where contracted (
waxman_graphis locked byte-for-byte;erdos_renyi_graphseed parity is locked). - Stochastic block model. Native; preserves user-supplied
nodelistorder. - Random tree (Prüfer). Native O(n) Prüfer-sequence sampling.
- Navigable small world. Native Kleinberg implementation.
- Lattice generators. Native Rust
hypercube_graph; pure-Pythongrid_graph,hexagonal_lattice_graph,triangular_lattice_graph(compose into native primitives but stay at the Python layer since the cost is dominated by the construction loop, not by per-edge insertion).