本文整理汇总了Python中igraph.Graph.add_vertices方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_vertices方法的具体用法?Python Graph.add_vertices怎么用?Python Graph.add_vertices使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类igraph.Graph
的用法示例。
在下文中一共展示了Graph.add_vertices方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Physic
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
class Physic (BaseInputGraph):
def __init__(self):
'''
@return: Arxiv ASTRO-PH (Astro Physics) collaboration network as iGraph graph instance
'''
edges = []
weights = []
f = open("./physic/compact-physic.txt", "r")
for line in f:
if line and line[0]!='#':
seg = line.split()
edges.append( (int(seg[0]), int(seg[1])) )
weights.append( 1 )
maxid = max( edges, key=itemgetter(1) )[1]
maxid = max( maxid, max(edges,key=itemgetter(0))[0] )
self.g = Graph()
self.g.add_vertices(maxid + 1)
self.g.add_edges(edges)
self.g.to_undirected()
self.g.simplify()
self.g.vs["myID"] = [ str(int(i)) for i in range(maxid+1)]
print "#nodes=", maxid + 1
print "#edges=", len(self.g.es)
def run(self):
C = BaseInputGraph.unsupervised_logexpand(self)
BaseInputGraph.run(self, C, p0=np.array([0.04, 0.04]))
with open("./physic/Physic_weights.pairs", "w+") as txt:
for e in self.g.es:
txt.write("%d %d %f\n" %(e.tuple[0], e.tuple[1], e["weight"]) )
示例2: disp_tree
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def disp_tree(tree):
from igraph import Graph, plot
g = Graph(directed=True)
g.add_vertices(len(tree))
g.vs['label'] = [node.name for node in tree]
nodes_to_add = set([0])
while len(nodes_to_add) != 0:
i_node = nodes_to_add.pop()
node = tree[i_node]
g.vs['label'][i_node] = node.name
left_node = node.left_child
right_node = node.right_child
if left_node != None:
i_left = tree.index(left_node)
g.add_edges((i_node, i_left))
nodes_to_add.add(i_left)
if right_node != None:
i_right = tree.index(right_node)
g.add_edges((i_node, i_right))
nodes_to_add.add(i_right)
layout = g.layout_reingold_tilford(root=0)
plot(g, layout=layout, bbox=(0, 0, 3000, 1000))
示例3: _gen_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def _gen_graph(self):
# make it lazy to support optional addslaves command
from igraph import Graph
g = Graph().as_directed()
g.add_vertices(self.vertex_count)
g.es['weight'] = 1 # enable weight
return g
示例4: merge
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def merge(g1,g2):
""" merges graph g1 and graph g2 into the output graph"""
g3nslst = list(set(g1.vs['name'][:]) | set(g2.vs['name'][:]))
g3 = Graph(0,directed=True)
g3.add_vertices(g3nslst)
g3elst = []
for e in g1.get_edgelist():
g3elst.append((g1.vs['name'][e[0]],g1.vs['name'][e[1]]))
for e in g2.get_edgelist():
g3elst.append((g2.vs['name'][e[0]],g2.vs['name'][e[1]]))
g3.add_edges(g3elst)
g3.simplify()
#add attributes
g1primlst = [vn for i,vn in enumerate(g1.vs['name'][:]) if int(g1.vs['inprim'][i]) == 1]
g2primlst = [vn for i,vn in enumerate(g2.vs['name'][:]) if int(g2.vs['inprim'][i]) == 1]
g3prim = [1 if vn in g1primlst or vn in g2primlst else 0 for vn in g3.vs['name'][:]]
g3pnamelst = [[] for i in range(len(g3.vs['name'][:]))]
for i,vn1 in enumerate(g3.vs['name'][:]):
for j,vn2 in enumerate(g1.vs['name'][:]):
if vn1 == vn2:
g3pnamelst[i].extend(g1.vs['pnamelst'][j].strip().split('|'))
for j,vn2 in enumerate(g2.vs['name'][:]):
if vn1 == vn2:
g3pnamelst[i].extend(g2.vs['pnamelst'][j].strip().split('|'))
g3.vs['pnamelst'] = ['|'.join(map(str,list(set(inp)))) if inp != [] else '' for inp in g3pnamelst]
#print g1.vs['pnamelst'][:]
#print g3.vs['name'][:]
g3.vs['inprim'] = g3prim
return g3
示例5: __findNegativeCut
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def __findNegativeCut(self,debug=False):
"""Best negative cut heuristic.
Heuristic to find the best cut value to construct the Gamma Model (RMgamma).
Args:
debug (bool,optional): Show debug information.
Returns:
A Heuristic object that contains all the relevant info about the heuristic.
"""
time_total = time.time()
# Graph and unique set construction
time_graph_construction = time.time()
graph_negative = Graph()
graph_negative.add_vertices(self.__n)
unique_negative_weights = set()
for i in range(self.__n):
for j in range (i+1,self.__n):
if self.__S[i][j] <= 0:
graph_negative.add_edge(i,j,weight=self.__S[i][j])
unique_negative_weights.add(self.__S[i][j])
time_graph_construction = time.time() - time_graph_construction
# Sort unique weights and start heuristic to find the best cut value
time_find_best_cut = time.time()
unique_negative_weights = sorted(unique_negative_weights)
# Test different cuts and check connected
best_negative_cut = 0
for newCut in unique_negative_weights:
edges_to_delete = graph_negative.es.select(weight_lt=newCut)
graph_negative.delete_edges(edges_to_delete)
if graph_negative.is_connected():
best_negative_cut = newCut
else:
break
time_find_best_cut = time.time() - time_find_best_cut
time_total = time.time() - time_total
if debug==True:
print ("Time Graph Construction: %f" %(time_graph_construction))
print ("Time Heuristic to find best cut: %f" %(time_find_best_cut))
print ("Total Time: %f" %(time_total))
print ("NEW (Best cut-): %d" %(best_negative_cut))
heuristic={}
heuristic['cut'] = best_negative_cut
heuristic['time_total']=time_total
heuristic['time_graph_construction']=time_graph_construction
heuristic['time_find_best_cut']=time_find_best_cut
return heuristic
示例6: testBug128
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def testBug128(self):
y = [1, 4, 9]
g = Graph(n=len(y), directed=True, vertex_attrs={'y': y})
self.assertEquals(3, g.vcount())
g.add_vertices(1)
# Bug #128 would prevent us from reaching the next statement
# because an exception would have been thrown here
self.assertEquals(4, g.vcount())
示例7: create_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def create_graph(vertice,edges=[]):
"""Create a graph using igraph
:add_vertices() method of the Graph class adds the given number of vertices to the graph.
:add_edges() method of the Graph class adds edges, they are specified by pairs of integers,
so [(0,1), (1,2)] denotes a list of two edge. igraph uses integer vertex IDs starting from zero
"""
graph = Graph(directed=True)
graph.add_vertices(vertice)
graph.add_edges(edges)
return graph
示例8: gen_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def gen_graph():
masters = sum(ms, [])
slaves = sum(ss, [])
frees = sum(fs, [])
ct = machine_count
g = Graph().as_directed()
g.add_vertices(2 * ct + 2)
g.es['weight'] = 1
assert g.is_weighted()
lin = map(len, fs)
# lin = map(operator.add, map(len, ss), map(len, fs))
rout = map(len, ms)
s = 2 * ct
t = s + 1
for i, m in enumerate(lin):
g[s, i] = m
for i, m in enumerate(rout):
g[i + ct, t] = m
cap = defaultdict(dict)
for i, m in enumerate(lin):
for j, n in enumerate(rout):
if i == j:
continue
cap[i][j] = m
assert len(ss) == ct
# for i in range(ct):
# for slave in ss[i]:
# cap[i][slave.master.machine_tag] -= 1
# assert cap[i][slave.master.machine_tag] >= 0
print cap
for i in range(ct):
for j in range(ct):
if i == j:
continue
masters_in_j = set(slave.master.tag for slave in ss[i] if slave.master.machine_tag == j) # to fight existing distribution error
limit = len(ms[j]) - len(masters_in_j)
cap[i][j] = min(limit, map(len, fs)[i])
for i, m in enumerate(lin):
if m == 0:
continue
for j, n in enumerate(rout):
if i == j:
continue
g[i, ct + j] = cap[i][j]
print g
start = datetime.utcnow()
mf = g.maxflow(s, t, g.es['weight'])
end = datetime.utcnow()
print 'result:', end - start
print mf.value, sum(rout)
print mf.flow
print map(float, g.es['weight']), len(g.es['weight'])
示例9: file2igraph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def file2igraph(file):
"""
Converts graph file into iGraph object, adds artifacts
"""
with open(file, 'r') as fi:
v,e = fi.next().split()
e_list = [(int(i.split()[0]), int(i.split()[1])) for i in list(fi)]
assert (int(e) == len(e_list)),\
"#edges mentioned and # of edges in file differ"
g = Graph()
g.add_vertices(int(v))
g.add_edges(e_list)
return g
示例10: test_shouldReturnCommunityLevelWithMaximumCommunities
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def test_shouldReturnCommunityLevelWithMaximumCommunities(self):
graph_1 = Graph()
graph_1.add_vertices(["1","2","3","4"])
graph_1.add_edges([("1","2"),("2","4"),("1","4"),("2","3")])
graph_2 = Graph()
graph_2.add_vertices(["1","3","4"])
graph_2.add_edges([("3","4"),("1","4"),("1","3")])
vertex_clustering_1 = VertexClustering(graph_1)
vertex_clustering_2 = VertexClustering(graph_2)
community_levels = [vertex_clustering_1, vertex_clustering_2]
expected_communities = vertex_clustering_1
actual_communities = SentenceGraph().find_best_community_level(community_levels)
self.assertEquals(actual_communities, expected_communities)
示例11: Ring
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
class Ring ( BaseInputGraph ):
wvalue = 1
g = Graph() # the iGraph graph instance
def __init__(self, v):
'''
@param v: the weight of edge connecting two cliques
@return: the produced ring network as iGraph graph instance
'''
self.wvalue = v
edges = []
ws = []
clique_num = 30
clique_size = 5
for c in range(0, clique_num):
for i in range(clique_size*c, clique_size*(c+1)):
for j in range(i+1, clique_size*(c+1)):
edges.append((i,j))
ws.append(1)
for c in range(0, clique_num):
edges.append((clique_size*c, clique_size*( (c+1) % clique_num)))
ws.append(self.wvalue)
maxid = max( edges, key=itemgetter(1))[1]
maxid = max( maxid, max(edges,key=itemgetter(0))[0] )
self.g = Graph()
self.g.add_vertices(maxid + 1)
self.g.add_edges(edges)
self.g.es["weight"] = ws
self.g.vs["comm"] = [str( int(_ / clique_size) ) for _ in range(len(self.g.vs))]
print "#nodes=", maxid + 1
print "#edges=", len(self.g.es)
def run(self):
'''
run the algorithm
'''
#supervised
group = [0,1,2,3,4]
C = BaseInputGraph.get_C(self, group)
#unsupervised
#C = BaseInputGraph.unsupervised_logexpand(self)
print C
BaseInputGraph.run(self, C)
for e in self.g.es:
print "(",e.tuple[0]," ,",
print e.tuple[1],")=",
print e["weight"]
示例12: Football
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
class Football ( BaseInputGraph ):
def __init__(self):
'''
@return: American Colleage Football Network as iGraph graph instance
'''
edges = []
weights = []
f = open("./football/footballTSEinputEL.dat", "r")
for line in f:
seg = line.split()
edges.append( (int(seg[0]), int(seg[1])) )
weights.append( 1 )
maxid = max( edges, key=itemgetter(1))[1]
maxid = max( maxid, max(edges,key=itemgetter(0))[0] )
self.g = Graph()
self.g.add_vertices(maxid + 1)
self.g.add_edges(edges)
self.g.to_undirected()
conf = []
with open("./football/footballTSEinputConference.clu", "r") as fconf:
conf = (fconf.read()).split()
self.g.vs["comm"] = [x for x in conf]
self.g.vs["myID"] = [ str(int(i)) for i in range(maxid+1)]
print "#nodes=", maxid + 1
print "#edges=", len(self.g.es)
def run(self):
AMI_increase = [[], [], [], [], [], []]
for igroup in range(10):
#semi-supervised
#group = [i for i, conf in enumerate(self.g.vs["comm"]) if conf == str(igroup)]
#if len(group) < 3: continue
#C = BaseInputGraph.get_C(self, group)
#unsupervised
C = BaseInputGraph.unsupervised_logexpand(self)
BaseInputGraph.run(self, C)
AMI_increase[0] += BaseInputGraph.results(self, Graph.community_fastgreedy, hasgnc = True)
AMI_increase[1] += BaseInputGraph.results(self, Graph.community_label_propagation, hasgnc = True)
AMI_increase[2] += BaseInputGraph.results(self, Graph.community_leading_eigenvector, hasgnc = True)
AMI_increase[3] += BaseInputGraph.results(self, Graph.community_walktrap, hasgnc = True)
AMI_increase[4] += BaseInputGraph.results(self, Graph.community_edge_betweenness, hasgnc = True)
AMI_increase[5] += BaseInputGraph.results(self, Graph.community_multilevel, hasgnc = True)
for i in range(6):
print "& %.5f" % ( 1.0 * sum(AMI_increase[i]) / len(AMI_increase[i]) )
示例13: LFR
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
class LFR ( BaseInputGraph ):
def __init__(self, trialval=1):
ws = []
edges = []
self.trial = trialval
with open("./binary_networks/mu0.5/network%d.dat" % self.trial, "r") as txt:
for line in txt:
seg = line.split()
edges.append((int(seg[0]), int(seg[1])))
ws.append(1)
maxid = max( edges, key=itemgetter(1))[1]
maxid = max( maxid, max(edges,key=itemgetter(0))[0] )
self.g = Graph()
print maxid
self.g.add_vertices(maxid + 1)
with open("./binary_networks/mu0.5/community%d.dat" % self.trial, "r") as txt:
for line in txt:
seg = line.split()
#print seg[0]
self.g.vs[int(seg[0])]["comm"] = seg[1] #note: string is returned
self.g.add_edges(edges)
self.g.to_undirected()
self.g.simplify()
self.g.delete_vertices(0)
self.g.es["weight"] = ws
BaseInputGraph.write_ground_truth(self, "./ground_truth_community%d.groups" % self.trial)
print "#nodes=", maxid + 1
print "#edges=", len(self.g.es)
def run(self):
#supervised
C = []
for i in range(6):
commval = str(random.randint(0,100))
group = [i for i, comm in enumerate(self.g.vs["comm"]) if comm == commval]
C += BaseInputGraph.get_C(self, group)
#unsupervised
C = BaseInputGraph.unsupervised_logexpand(self)
BaseInputGraph.run(self, C, p0=np.array([1 , 1]))
BaseInputGraph.results(self, Graph.community_fastgreedy, hasgnc = False,\
filename="%d" %self.trial)
示例14: get_igraph_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
def get_igraph_graph(network):
print 'load %s users into igraph' % len(network)
g = Graph(directed=True)
keys_set = set(network.keys())
g.add_vertices(network.keys())
print 'iterative load into igraph'
edges = []
for source in network:
for target in network[source].intersection(keys_set):
edges.append((source, target))
g.add_edges(edges)
g = g.simplify()
print 'make sure graph is connected'
connected_clusters = g.clusters()
connected_cluster_lengths = [len(x) for x in connected_clusters]
connected_cluster_max_idx = connected_cluster_lengths.index(max(connected_cluster_lengths))
g = connected_clusters.subgraph(connected_cluster_max_idx)
if g.is_connected():
print 'graph is connected'
else:
print 'graph is not connected'
return g
示例15: Enron
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertices [as 别名]
class Enron (BaseInputGraph):
def __init__(self):
'''
@return: Enron email communication network as iGraph graph instance
'''
edges = []
weights = []
f = open("./enron/email-Enron.txt", "r")
for line in f:
if line and line[0]!='#':
seg = line.split()
edges.append( (int(seg[0]), int(seg[1])) )
weights.append( 1 )
maxid = max( edges, key=itemgetter(1) )[1]
maxid = max( maxid, max(edges,key=itemgetter(0))[0] )
self.g = Graph()
self.g.add_vertices(maxid + 1)
self.g.add_edges(edges)
self.g.to_undirected()
self.g.simplify()
self.g.vs["myID"] = [ str(int(i)) for i in range(maxid+1)]
print "#nodes=", maxid + 1
print "#edges=", len(self.g.es)
def run(self):
C = BaseInputGraph.unsupervised_logexpand(self)
BaseInputGraph.run(self, C, p0=np.array([0.04, 0.04]))
with open("./enron/email-Enron_weights.pairs", "w+") as txt:
for e in self.g.es:
txt.write("%d %d %f\n" %(e.tuple[0], e.tuple[1], e["weight"]) )
with open("./enron/email-Enron_unweights.pairs", "w+") as txt:
count = 0
for e in self.g.es:
txt.write("%d %d\n" %(e.tuple[0], e.tuple[1]) )
count += 1
print count , "edges written."