pythonigraphsubgraphvertex-attributes

Using subgraph() and preserving vertex attributes with igraph python


I want partition my disconnected graph into blocks (to use community_spinglass). However once I get the subgraph and use community_spinglass() the labels of the vertex in the original graph are lost. I am dealing with 40+ vertices so it is not easy to track them down. Here is a "toy example" of my problem:

import igraph
from igraph import Graph
g4_matrix = [ [0,0,-1,0,0,0,0], [0,0,0,0.8,0.2,0,0], [-1,0,0,0,0,0,0], [0,0.8,0,0,1,0,0.1], [0,0.2,0,1,0,-0.3,-.7], [0,0,0,0,-0.3,0,1], [0,0,0,0.1,-0.7,1,0] ]
v_name = ["1", "2", "3", "4", "5", "6", "7"]
g4 = Graph.Weighted_Adjacency(g4_matrix, mode = 'undirected',attr = 'weight' )
igraph.plot(g4,bbox = (300, 300),vertex_label = v_name)

Original graph with labels

After I obtain blocks and communities:

g4_blocks = g4.blocks()
g4_block = g4.vs.select(g4_blocks[1])
Block1 = g4.subgraph(g4_block)
igraph.plot(Block1, bbox = (200, 200), vertex_label = v_name)

Subgraph, as observed the vertices follow v_name list in order and don't preserve past label

But we see the vertices follow v_name list in order, not their previous label.Furthermore when we obtain communities:

comm = Block1.community_spinglass()
for c in comm:
    print c

[2, 3, 4]
[0, 1]

we get the index of the subgraph, but it is difficult to relate to the index of original graph.

Is there a way to obtain communities referring to the index or label of the original graph?

Thanks in advance.


Solution

  • Use Block1.vs[c]["name"] to get the names of the nodes in community c within Block1. Explanation:

    1. Block1.vs is the vertex sequence of the entire Block1 graph.

    2. Block1.vs[c] subsets this vertex sequence to only the nodes whose indices are in the iterable named c, which is the case in your for loop.

    3. Block1.vs[c]["name"] retrieves the name vertex attribute of the vertices that you have selected in the previous step. Since names are kept in the subgraphs, this should allow you to relate the nodes of Block1 back to your original graph.