FrankenNetworkX

Guide/Start here

Cookbook

2 min readFrom the README

On this page 6
Large-graph PageRankCommunity detectionMixing fnx + nx graph types at the boundaryFormat conversion in one lineDrawing (delegated to matplotlib via NetworkX)Inspecting CGSE policy + witness types from Python

Large-graph PageRank

import franken_networkx as fnx

# Build (or load) a 1M-node BA graph.
G = fnx.barabasi_albert_graph(1_000_000, 4, seed=42)

# fnx.pagerank releases the GIL, so this is fine to run from a thread pool.
pr = fnx.pagerank(G, alpha=0.85, max_iter=100, tol=1e-6)

top10 = sorted(pr.items(), key=lambda kv: kv[1], reverse=True)[:10]

Community detection

import franken_networkx as fnx

G = fnx.karate_club_graph()
comms = list(fnx.community.louvain_communities(G, seed=42))
print("#communities:", len(comms))
print("modularity:", fnx.community.modularity(G, comms))

Mixing fnx + nx graph types at the boundary

Every fnx function accepts an nx.Graph (or fnx graph) interchangeably; the boundary coerces:

import networkx as nx, franken_networkx as fnx

G_nx  = nx.path_graph(10)
G_fnx = fnx.path_graph(10)

# all four combinations work and return the same answer
fnx.shortest_path(G_nx,  0, 9)
fnx.shortest_path(G_fnx, 0, 9)
nx.shortest_path(G_nx,  0, 9, backend="franken_networkx")
nx.shortest_path(G_fnx, 0, 9, backend="franken_networkx")

Format conversion in one line

import tempfile, pathlib
import franken_networkx as fnx

# Self-contained so the snippet actually runs: it makes its own input and writes
# into a temp dir rather than reading an "input.gml" that has to exist and
# littering four files into the working directory.
with tempfile.TemporaryDirectory() as tmp:
    out = pathlib.Path(tmp)
    seed = fnx.Graph()
    seed.add_edge("a", "b", weight=1.0)
    fnx.write_gml(seed, str(out / "input.gml"))

    converted = fnx.read_gml(str(out / "input.gml"))
    fnx.write_graphml(converted, str(out / "output.xml"))
    fnx.write_edgelist(converted, str(out / "output.edgelist"))
    fnx.write_gexf(converted, str(out / "output.gexf"))

Drawing (delegated to matplotlib via NetworkX)

import franken_networkx as fnx
import matplotlib.pyplot as plt

G = fnx.karate_club_graph()
pos = fnx.spring_layout(G, seed=7)
fnx.draw(G, pos, with_labels=True, node_size=200)
plt.savefig("karate.png", dpi=160)

Inspecting CGSE policy + witness types from Python

import franken_networkx as fnx
from franken_networkx._fnx import cgse

# The 13 tie-break policies are reachable as named constructors:
p = cgse.TieBreakPolicy.weight_then_lex()
print(p.id())                       # "weight_then_lex"

# Per-algorithm canonical policy. Only the 12 reference algorithms have
# entries; unknown algorithms return None.
print(cgse.algorithm_policy("dijkstra"))             # → TieBreakPolicy.weight_then_insertion_order
print(cgse.algorithm_policy("max_weight_matching")) # → TieBreakPolicy.weight_then_lex
print(cgse.algorithm_policy("pagerank"))             # → None (not in the V1 reference set)

# Full V1 registry: { "<algorithm>": {"family": ..., "policy": ..., "dominant_complexity": ...} }
registry = cgse.policy_registry()
print(len(registry), "registered algorithms")        # → 12
print(sorted(registry.keys())[:5])                   # → ['bellman_ford', 'bfs', 'connected_components', 'dfs', 'dijkstra']

# All reference-algorithm identifiers:
print(cgse.reference_algorithms())
# → ['dijkstra', 'bellman_ford', 'bfs', 'dfs', 'max_weight_matching', 'min_weight_matching',
#    'connected_components', 'strongly_connected_components', 'kruskal', 'prim',
#    'eulerian_circuit', 'topological_sort']

Witnesses can also be drained from Python. cgse.collect_witnesses(func) runs func() with the calling thread's ledger armed and returns (result, witnesses):

G = fnx.karate_club_graph()
components, witnesses = cgse.collect_witnesses(lambda: list(fnx.connected_components(G)))
w = witnesses[0]
print(w.policy.id(), w.dominant_term, w.n, w.m, w.observed_count)   # lex_min n_plus_m 34 78 34
print(len(w.decision_path_hash))                                     # 64 (Blake3, hex)

# Same graph, same policy → same decision-path hash. Any drift is a regression.
_, again = cgse.collect_witnesses(lambda: list(fnx.connected_components(G)))
assert again[0].decision_path_hash == w.decision_path_hash

# Replay a serialized receipt and apply the same bound checker as Rust.
# This checks its operation count, not the authenticity of its execution.
restored = cgse.ComplexityWitness.from_json(w.to_json())
assert restored.verify_complexity_bound()["within_bounds"]

# A kernel outside the reference set emits nothing rather than a fabricated receipt.
assert cgse.collect_witnesses(lambda: fnx.degree_centrality(G))[1] == []

From the public Python surface, all 12 reference algorithms in v1_policy_registry() have instrumented public routes (br-r37-c1-rc0923-epic-crown-jewels-csmqh.1): connected components, BFS/DFS edges and trees, unweighted bidirectional_shortest_path (including shortest_path with both endpoints) on all four graph classes, Kruskal's minimum_spanning_tree, indexed Prim's minimum/maximum spanning edges and trees on simple graphs, Bellman-Ford, SCC enumeration/count on DiGraph/MultiDiGraph, topological sort, max_weight_matching and min_weight_matching on simple undirected graphs, finite numeric simple-graph dijkstra_path and bidirectional Dijkstra, exact-domain undirected MultiGraph bidirectional Dijkstra (including weighted single-pair shortest_path), and simple undirected and directed eulerian_circuit. The MultiGraph bidirectional route accepts exact built-in string/integer labels and nonnegative finite built-in weights within the exact-integer sum envelope; custom numerics, hash-equal mixed display objects, subclasses and attribute-key collisions retain Python traversal. Its receipt counts heap pops and neighbor decisions, not every parallel-weight inspection, and reports the original parallel-edge count without projecting the graph or changing FIFO ties.

Concrete Graph/DiGraph/MultiGraph/MultiDiGraph dijkstra_path(weight=None) also emits a Dijkstra witness when the effective weights are one, preserving single-source FIFO ties and endpoint/discovery objects. Unlike shortest_path(weight=None), Dijkstra looks up the actual attribute key None: non-string attribute keys (including custom keys equal to None) and empty live multigraph keydicts retain Python weight evaluation. Private-root rows are queried before view coercion; subclasses and the source-wide target=None sentinel also retain Python traversal. The unit-weight receipt counts dequeues and neighbor examinations, not the admission scan or result marshaling. Public Prim counts heap pushes/pops, including stale entries; its string-root trace can legitimately vary with PYTHONHASHSEED to preserve NetworkX's set(G).pop() behavior.

While all 12 reference algorithms emit witnesses on their primary public routes, the public Prim FIFO policy (WeightThenInsertionOrder) intentionally differs from the reference registry's lexical policy (WeightThenLex), and multigraph Euler, callable-weight fallbacks, and several shortest-path sibling variants remain uninstrumented. Restored witness JSON can be checked with verify_complexity_bound(); unknown complexity terms raise ValueError, and an inflated count returns within_bounds=False. Neither a restored receipt nor a passing bound authenticates the execution or replaces differential conformance. The Rust level also exposes fnx_cgse::collect_witnesses and the WitnessLedger JSONL serializer.