Is there a networkx functiuon to calculate number of edges between communities?

Viewed 754

I have used Louvain algorithm for community detection. Then position the communities with respect to each other: create a new, weighted graph, where each node corresponds to a community, and the weights correspond to the number of edges between communities.

My problem is how to efficiently calculate "the number of edges between communities". I know I can do I massive for loop for every single two nodes from each community.

Is there a function in Networkx that implements this?

1 Answers

There is! The induced_graph function seems to be what you are looking for.

This function allows you to:

  1. Obtain the induced graph of communities as nodes.
  2. The WEIGHT between nodes in the induced graph equals the number of edges between nodes in the original graph.

Like so:

induced_graph = community.induced_graph(p1, giant_component, weight='WEIGHT')
for u,v,a in induced_graph.edges(data=True):
    print(u,v,a)

This will print Community_a Community_b {'WEIGHT': NumberOfLinks}

Here is an example for a partitioning with 7 communities:

0 1 {'WEIGHT': 8782}
0 0 {'WEIGHT': 15336}
0 3 {'WEIGHT': 9858}
0 4 {'WEIGHT': 4306}
0 2 {'WEIGHT': 1216}
0 7 {'WEIGHT': 1}
0 6 {'WEIGHT': 2}
0 5 {'WEIGHT': 5}
1 1 {'WEIGHT': 10116}
1 3 {'WEIGHT': 6728}
1 4 {'WEIGHT': 4030}
1 2 {'WEIGHT': 667}
1 5 {'WEIGHT': 38}
1 7 {'WEIGHT': 1}
1 6 {'WEIGHT': 1}
2 3 {'WEIGHT': 605}
2 4 {'WEIGHT': 348}
2 2 {'WEIGHT': 470}
3 3 {'WEIGHT': 13921}
3 4 {'WEIGHT': 2805}
3 5 {'WEIGHT': 45}
3 6 {'WEIGHT': 2}
3 7 {'WEIGHT': 1}
4 4 {'WEIGHT': 3273}
4 5 {'WEIGHT': 5}
5 5 {'WEIGHT': 37}
6 6 {'WEIGHT': 1}
7 7 {'WEIGHT': 1}

The docs for the induced_graph function

Related