Skip to content

Commit fbdd5c7

Browse files
authored
Merge pull request #781 from pydata/triangles-example
ENH: Add counting triangles example
2 parents a60f0ad + 733f44b commit fbdd5c7

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

examples/triangles_example.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ extras = [
4141
"sparse[finch]",
4242
"scipy",
4343
"scikit-learn",
44+
"networkx",
4445
]
4546
tests = [
4647
"sparse[extras]",

0 commit comments

Comments
 (0)