Search code examples
pythongraphigraphadjacency-matrix

How to make adjacency matrix for sub-graphs detected by leidenalg


I need to make adjacency matrix for each community(sub-graph) detected by leidenalg; but the problem is the output of find_partition() is just showing the nodes in each sub-graph. Is there any way to convert the output to something like np.array with edge information of each sub-graph??

import leidenalg
import igraph as ig

G = ig.Graph.Erdos_Renyi(10, 0.1);
partitions = leidenalg.find_partition(G, leidenalg.ModularityVertexPartition)
print(partitions)

output:

Clustering with 10 elements and 3 clusters
[0] 2, 5, 8, 9
[1] 3, 4, 6
[2] 0, 1, 7


Solution

  • You can do this by simply constructing the subgraph and the computing the adjacency matrix. Your example is not quite reproducible because ig.Graph.Erdos_Renyi uses the random number generator. Therefore, I added a little code to set the random seed and generate a graph like yours, except reproducible. I simply get the adjacency matrix for the first partition, but of course, you can just loop through the partitions and get all of the matrices.

    import igraph as ig
    import leidenalg
    import random
    
    random.seed(a=321)
    G = ig.Graph.Erdos_Renyi(10, 0.28);
    partitions = leidenalg.find_partition(G, leidenalg.ModularityVertexPartition)
    print(partitions)
    
    P0 = G.subgraph(partitions[0])
    P0.get_adjacency()
    
    Out[15]: Matrix([[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]])