|
| 1 | +import importlib |
| 2 | +import os |
| 3 | + |
| 4 | +import sparse |
| 5 | + |
| 6 | +import networkx as nx |
| 7 | +from utils import benchmark |
| 8 | + |
| 9 | +import numpy as np |
| 10 | + |
| 11 | +ITERS = 3 |
| 12 | + |
| 13 | + |
| 14 | +if __name__ == "__main__": |
| 15 | + print("Counting Triangles Example:\n") |
| 16 | + |
| 17 | + G = nx.gnp_random_graph(n=200, p=0.2) |
| 18 | + |
| 19 | + # ======= Finch ======= |
| 20 | + os.environ[sparse._ENV_VAR_NAME] = "Finch" |
| 21 | + importlib.reload(sparse) |
| 22 | + |
| 23 | + a_sps = nx.to_scipy_sparse_array(G) |
| 24 | + a = sparse.asarray(a_sps) |
| 25 | + |
| 26 | + # @sparse.compiled NOTE: blocked by https://github.com/willow-ahrens/Finch.jl/issues/615 |
| 27 | + def count_triangles_finch(a): |
| 28 | + return sparse.sum(a @ a * a) / 6 |
| 29 | + |
| 30 | + # Compile & Benchmark |
| 31 | + result_finch = benchmark(count_triangles_finch, args=[a], info="Finch", iters=ITERS) |
| 32 | + |
| 33 | + # ======= SciPy ======= |
| 34 | + def count_triangles_scipy(a): |
| 35 | + return (a @ a * a).sum() / 6 |
| 36 | + |
| 37 | + a = nx.to_scipy_sparse_array(G) |
| 38 | + |
| 39 | + # Compile & Benchmark |
| 40 | + result_scipy = benchmark(count_triangles_scipy, args=[a], info="SciPy", iters=ITERS) |
| 41 | + |
| 42 | + # ======= NetworkX ======= |
| 43 | + def count_triangles_networkx(a): |
| 44 | + return sum(nx.triangles(a).values()) / 3 |
| 45 | + |
| 46 | + a = G |
| 47 | + |
| 48 | + # Compile & Benchmark |
| 49 | + result_networkx = benchmark(count_triangles_networkx, args=[a], info="NetworkX", iters=ITERS) |
| 50 | + |
| 51 | + np.testing.assert_equal(result_finch.todense(), result_scipy) |
| 52 | + np.testing.assert_equal(result_finch.todense(), result_networkx) |
| 53 | + assert result_networkx == result_scipy |
0 commit comments