Search code examples
pythonconditional-statementsigraphedges

How to add edges that are conditional to object attribute using igraph and python


The nodes of my graphs are instances that have some methods. I have correctly added the nodes, but now I want to check, for those nodes if they have the same group_id, add_edges. I am using igraph

import igraph as ig

def making_graph(researchers):
    g = ig.Graph()
    for each in researchers:
        for i in range(len(each)):
            g.add_vertex(each[i])
            g.vs[i]['researcher_id'] = each[i].get_researcher_id()
            g.vs[i]['name'] = each[i].get_name()
            g.vs[i]['sex'] = each[i].get_sex()

    g.add_edges() # if researchers have the same group_id, add edge
    return g

The class for researcher is

class Researcher:

    def __init__(self, group_id, research_id, name, tit, sex,
             tot_nac_2011, tot_nac_2014, tot_int_2011, tot_int_2014, tot_bbl_2011, tot_bbl_2014):

        self.group_id = group_id
        self.research_id = research_id
        self.name = name
        self.tit = tit
        self.sex = sex
        self.producao = [tot_nac_2011, tot_nac_2014, tot_int_2011, tot_int_2014, tot_bbl_2011, tot_bbl_2014]

    def get_group_id(self):
        return self.group_id

    def get_researcher_id(self):
        return self.research_id

    def get_sex(self):
        return self.sex

and when I call making_graph I pass a list with a list of researchers

EDITED. This also does not work. Why?

def making_graph(researchers):
    g = ig.Graph()
    for each in researchers:
        for i in range(len(each)):
            g.add_vertex(each[i])
            g.vs[i]['researcher_id'] = each[i].get_researcher_id()
            g.vs[i]['name'] = each[i].get_name()
            g.vs[i]['sex'] = each[i].get_sex()
            for other in researchers:
                for j in range(len(other)):
                    if each[i].get_group_id() == other[j].get_group_id():
                        g.add_edge([(g.vs[i], g.vs[j])])
return g

Solution

  • Now, it seems this does work:

    def making_graph(researchers):
        g = ig.Graph()
        for each in researchers:
            for i in range(len(each)):
                g.add_vertex(each[i])
                g.vs[i]['group_id'] = each[i].get_group_id()
                g.vs[i]['researcher_id'] = each[i].get_researcher_id()
                g.vs[i]['name'] = each[i].get_name()
                g.vs[i]['sex'] = each[i].get_sex()
        for v in g.vs:
            for w in g.vs:
                if v['group_id'] == w['group_id'] and v != w and g.are_connected(v, w) is False:
                    g.add_edge(v, w)
        return g