2016-04-23 72 views
1

我的圖形的節點是具有某些方法的實例。 我已經正確地添加了節點,但是現在我想檢查這些節點是否具有相同的group_id,add_edges。我使用的igraph如何使用igraph和python添加條件對象屬性的邊緣

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 

的類研究者

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 

,當我打電話making_graph我傳遞一個清單,研究人員

編着的清單。這也是行不通的。爲什麼?現在

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 
+0

你的意思是,如果研究人員_all_有相同'group_id'? –

+0

對於這個特定的情況,是的。但是當我收集更多圖表(106,000)時,我將需要訪問節點方法researcher.get_group_id(),並且如果它與另一個節點相同,那麼add_edge(researcher1,researcher2) –

+0

一步一個腳印。你可能想看看[這個問題](http://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical)。 –

回答

0

,看來這確實工作:

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