FrankenNetworkX

Guide/How it works

Algorithm Implementation Notes

7 min readFrom the README

On this page 12
Shortest pathConnectivityCentralityMatchingFlowTrees and arborescencesCommunityIsomorphismPlanarityDAGPolynomial / spectralGenerators

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 whose Ord impl reverses the dist comparison (so a max-heap acts as a min-heap, with no per-push Reverse(_) wrapper) and tie-breaks equal-distance entries by insertion-counter seq to match NetworkX's heapq-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 to nx per 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 johnson was specifically locked to NetworkX's order in br-r37-c1-9l73c.

Connectivity

  • Connected components. Index-based BFS with a packed visited bitset. Emits PySet per 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_components for 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 / DfsPreorder variant from CGSE.
  • Node / edge connectivity, min cuts. Built on max-flow over a residual graph; custom flow_func callables are explicitly rejected by can_run so nx's slower-but-flexible path takes over when needed.

Centrality

  • PageRank. The public pagerank builds the adjacency as CSR arrays natively in Rust, then runs the damped power iteration as a scipy sparse matvec mirroring nx's _pagerank_scipy float 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.pagerank but is not on the public route, so pagerank requires 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. numpy variants offload eigensolvers to SciPy with sign/basis tolerance baked into the test layer.
  • Katz / eigenvector / closeness / harmonic. Standard formulas. harmonic_centrality specifically matches NetworkX's set-based dict iteration order (locked in br-r37-c1-rsom6).
  • Voterank. Iterative selection with explicit LexMin tie-break.

Matching

  • Maximum-weight matching. The public max_weight_matching runs networkx_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's mate insertion 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_matching is networkx's body over it (the inverted graph built as networkx builds it). Both raise NetworkXNotImplemented on 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 under fnx.bipartite.* and currently delegate to the upstream networkx.algorithms.bipartite reference. Tracked in docs/delegation_ledger.md.

Flow

  • Maximum flow and minimum cut. Public maximum_flow, maximum_flow_value, minimum_cut, and minimum_cut_value default to native preflow_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 via edmonds_karp and 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 NetworkXError matching 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 the fnx-algorithms crate root, so sibling Rust consumers can reach the exact min-cost-flow path directly without taking a PyO3 dependency. It is specialised to i64 demands/capacities/weights — the only byte-exact-integer case — with no f64 anywhere on the path, so results are exact and reproducible. Originally this pivot logic lived inside the fnx-python binding; it was hoisted into fnx-algorithms in commit 6de8937d, and the Python network_simplex binding 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's min) 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_trees are exposed.
  • Edmonds' branching. Native rewrite (commit 9edb5819) using explicit EdmondsMultiDiGraph + UnionFind structures; 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 unweighted fnx.Graph without self-loops. Every other shape (weights, self-loops, directed, multigraph, nx input) converts and routes through nx.algorithms.community.louvain_communities, pinned to the networkx backend so a global backend_priority cannot 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 native greedy_color and adjacency for fnx.Graph; multigraph, view and non-fnx inputs route through nx (br-r37-c1-cy2me).
  • Greedy modularity (greedy_modularity_communities). Runs networkx_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): its MappedQueue heaps with equal gains broken by node label, as networkx's _HeapElement compares them, and the same float arithmetic from the same setup values. The merges are replayed into networkx's communities dict, 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 all int or all str, 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.md for 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_planar runs 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_planarity builds native PlanarEmbedding clockwise 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 InsertionOrder policy); 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 on scipy.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_graph is locked byte-for-byte; erdos_renyi_graph seed parity is locked).
  • Stochastic block model. Native; preserves user-supplied nodelist order.
  • Random tree (Prüfer). Native O(n) Prüfer-sequence sampling.
  • Navigable small world. Native Kleinberg implementation.
  • Lattice generators. Native Rust hypercube_graph; pure-Python grid_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).