Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Feat: add k random sampling for betweeness approximation
Browse files Browse the repository at this point in the history
NYYCS committed Dec 11, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent cab6daa commit 9a8d366
Showing 2 changed files with 25 additions and 1 deletion.
20 changes: 19 additions & 1 deletion easygraph/functions/centrality/betweenness.py
Original file line number Diff line number Diff line change
@@ -18,7 +18,13 @@ def betweenness_centrality_parallel(nodes, G, path_length, accumulate):
@not_implemented_for("multigraph")
@hybrid("cpp_betweenness_centrality")
def betweenness_centrality(
G, weight=None, sources=None, normalized=True, endpoints=False, n_workers=None
G,
k=None,
weight=None,
sources=None,
normalized=True,
endpoints=False,
n_workers=None,
):
r"""Compute the shortest-basic betweenness centrality for nodes.
@@ -56,6 +62,11 @@ def betweenness_centrality(
If None, all nodes are considered.
Otherwise,the set of source vertices to consider when calculating shortest paths.
k : None or int, optional (default=None)
If None, all nodes are considered.
Otherwise, the set of vertices uniqued sampled k times from source vertices
when calculating shortest paths.
normalized : bool, optional
If True the betweenness values are normalized by `2/((n-1)(n-2))`
for graphs, and `1/((n-1)(n-2))` for directed graphs where `n`
@@ -89,6 +100,13 @@ def betweenness_centrality(
nodes = sources
else:
nodes = G.nodes

if k is not None:
import random

nodes = list(nodes)
nodes = random.sample(nodes, k=min(k, len(nodes)))

betweenness = dict.fromkeys(G, 0.0)

if n_workers is not None:
6 changes: 6 additions & 0 deletions easygraph/functions/centrality/tests/test_betweenness.py
Original file line number Diff line number Diff line change
@@ -21,6 +21,12 @@ def test_betweenness(self):
for i in self.test_graphs:
print(eg.functions.betweenness_centrality(i))

def test_k_sample_betweenness(self):
for i in self.test_graphs:
approx = eg.functions.betweenness_centrality(i, k=len(i))
actual = eg.functions.betweenness_centrality(i)
assert approx == actual


if __name__ == "__main__":
unittest.main()

0 comments on commit 9a8d366

Please sign in to comment.