import json
import platform
from pathlib import Path
import networkx as nx
import numpy as np
DAMPING = 0.85
NX_TOL = 1e-13
MAX_ITER = 1000
adj_unweighted = [
[0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0, 1.0, 0.0],
[1.0, 0.0, 0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], ]
adj_weighted = [
[0.0, 2.0, 0.5, 0.0, 0.0, 0.0],
[0.0, 0.0, 1.5, 0.0, 0.0, 3.0],
[1.0, 0.0, 0.0, 2.5, 0.0, 0.0],
[0.0, 0.8, 0.0, 0.0, 1.2, 0.0],
[0.6, 0.0, 0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], ]
n = len(adj_unweighted)
def pagerank_scores(matrix, weight):
a = np.array(matrix)
g = nx.from_numpy_array(a, create_using=nx.DiGraph)
pr = nx.pagerank(g, alpha=DAMPING, tol=NX_TOL, max_iter=MAX_ITER, weight=weight)
return [pr[i] for i in range(n)]
pagerank = pagerank_scores(adj_unweighted, weight=None)
pagerank_weighted = pagerank_scores(adj_weighted, weight="weight")
fixture = {
"provenance": {
"generator": "gen_graphops.py",
"library": "networkx",
"networkx_version": nx.__version__,
"numpy_version": np.__version__,
"python": platform.python_version(),
"note": "Both sides converged far tighter than the 1e-9 comparison.",
},
"params": {
"damping": DAMPING,
"graphops_tolerance": 1e-12,
"max_iterations": MAX_ITER,
},
"adj_unweighted": adj_unweighted,
"adj_weighted": adj_weighted,
"expected": {
"pagerank": pagerank,
"pagerank_weighted": pagerank_weighted,
},
}
out = Path(__file__).parent / "graphops_pagerank.json"
out.write_text(json.dumps(fixture, indent=2) + "\n")
print("pagerank ", [f"{v:.6f}" for v in pagerank])
print("pagerank_weighted", [f"{v:.6f}" for v in pagerank_weighted])
print(f"wrote {out}")