简体   繁体   中英

Extract a certain component from a graph using igraph python

Description of the problem:

The objective is to extract the component that a certain vertex belongs to in order to calculate its size.

Steps of the code:

  • Use the igraph method clusters() to get the list of all connected components (cc) in the graph.
  • Then, iterate over the c.c list while checking each time if that certain node belongs to it or not.
  • When it is found, I calculate its size.

The code is as follows:

def sizeofcomponent(clusters, vertex):
    for i in range(len(clusters)):
        if str(vertex) in clusters.subgraphs()[i].vs["name"]:
            return(len(clusters.subgraphs()[i].vs["name"]))

The Problem is that this code will be used with extremely large graphs, and this way of doing things slowed my code by a lot. Is there a way to improve it?


EDIT 01: Explanation of how the algorithm works

  1. Suppose that the following graph is the main graph :

    - 主图 -

  2. The Maximal Independent Set (MIS) is calculated and we get the following graph that I call components :

    - 组件 (MIS) -

  3. Randomly add a node from the main Graph in a way that that node belongs to the main graph but doesn't belong to components (isn't part of the MIS). Example: adding node 10 to components.

    将节点 10 添加到组件

  4. Calculate the size of the component it forms.

  5. The process is repeated with all nodes (ones that don't belong in components (MIS).

  6. In the end, the node that forms the smallest component (smallest size) is the one added permanently to components .

Your solution:

  • When the following code is executed (i being the vertex):
    cls = components.clusters()
    c = cls.membership[i]

The variable c value would be the following list: c=cls.membership[i]

Example: node (2) belongs to the component 1 (of id 1).

Why it wouldn't work for me:

The following line of code wouldn't give me the correct result:

    cls = components.clusters()
    c = cls.membership[i]

because the ids of the nodes in the list c don't match up with the name of the nodes. Example: cls.membership[i] would give an exception error: list out of range. Instead of the correct result which is: 4.

Also, from your code, the size, in your case, is calculated in the following way:

    c = components.membership[i]
    s = components.membership.count(c)

You can simply get the component vertex i belongs to by doing

components = G.clusters()
c = components.membership[i]

You can then get the size of component c using

s = components.size(c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM