本文整理汇总了Python中igraph.Graph.add_edges方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_edges方法的具体用法?Python Graph.add_edges怎么用?Python Graph.add_edges使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类igraph.Graph
的用法示例。
在下文中一共展示了Graph.add_edges方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Physic
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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_edges [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: convert_to_igraph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [as 别名]
def convert_to_igraph(road_map):
# First, re-index nodes from 0 to N-1
shuffle(road_map.nodes)
n = len(road_map.nodes)
new_node_ids = {}
for i in xrange(n):
new_node_ids[road_map.nodes[i].node_id] = i
# Now, create a Graph object with the correct number of nodes
graph = Graph(n, directed=False)
"""
# Add the correct links
for i in xrange(n):
if(i%1000==0):
print i
for link in road_map.nodes[i].forward_links:
j = new_node_ids[link.connecting_node.node_id]
graph.add_edge(i,j)
"""
edge_set = set()
for i in xrange(n):
for link in road_map.nodes[i].forward_links:
j = new_node_ids[link.connecting_node.node_id]
x = min(i,j)
y = max(i,j)
edge_set.add((x,y))
graph.add_edges(list(edge_set))
return graph
示例4: merge
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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: create_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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
示例6: file2igraph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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
示例7: test_shouldReturnCommunityLevelWithMaximumCommunities
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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)
示例8: Ring
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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"]
示例9: xg_to_ig
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [as 别名]
def xg_to_ig(xg):
print "-----------xg_to_ig------------"
ig = Graph()
weights = [float(xg[edge[0]][edge[1]]['weight']) for edge in xg.edges()]
for node in xg.nodes():
ig.add_vertex(str(node))
#print ig.vs["name"]
edges = [(str(edge[0]), str(edge[1])) for edge in xg.edges()]
ig.add_edges(edges)
ig.es["capacity"] = weights
return ig
示例10: Football
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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]) )
示例11: build_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [as 别名]
def build_graph(amplicons, relations):
"""
Convert pairwise relations into a graph structure.
"""
# Create vertices (= number of unique amplicons)
g = Graph(len(amplicons))
g.add_edges(relations)
amplicon_ids = [amplicon[0] for amplicon in amplicons]
abundances = [int(amplicon[1]) for amplicon in amplicons]
minimum, maximum = min(abundances), max(abundances)
# Determine canvas size
if len(abundances) < 500:
bbox = (1920, 1080)
elif len(abundances) > 4000:
bbox = (5760, 3240)
else:
bbox = (3840, 2160)
# Compute node attributes
node_colors = list()
node_sizes = list()
node_labels = list()
print("Building graph", file=sys.stdout)
for abundance in abundances:
# Color is coded by a 3-tuple of float values (0.0 to 1.0)
# Start from a max color in rgb(red, green, blue)
max_color = (176, 196, 222) # light steel blue
color = [1.0 * (c + (255 - c) / abundance) / 255 for c in max_color]
node_colors.append(color)
node_size = 30 + (abundance * 70 / maximum)
node_sizes.append(node_size)
# Label nodes with an abundance greater than 10
if abundance >= 10 or abundance == maximum:
node_labels.append(str(abundance))
else:
node_labels.append("") # Doesn't work with "None"
g.vs["name"] = amplicon_ids
g.vs["abundance"] = abundances
g.vs["label"] = node_labels
g.vs["color"] = node_colors
g.vs["vertex_size"] = node_sizes
return g, bbox
示例12: readFromFile
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [as 别名]
def readFromFile(file):
"""
Function which forms igraph graph object by reading
edgelsit from the input file
:param file:
:return:the graph g, number of vertices of g
"""
with open(file, mode="r") as f:
vertices, edges = f.readline().split()
edgeList = list()
for line in f:
#add each line to edgelist as (a,b) where a and b are vertex ids
edgeList.append((int(line.split()[0]), int(line.split()[1])))
g = Graph(int(vertices))
g.add_edges(edgeList)
#makes sure that edges are equal to nubmer specified in file
assert (int(edges) == len(edgeList))
return g, int(vertices)
示例13: LFR
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [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_edges [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: grid
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edges [as 别名]
def grid(p, q):
g = Graph(p * q)
g.vs["label"] = [str(x) for x in range(1, p*q+1)]
def v2i(i, j):
return i * q + j
def i2v(i):
return (i / q, i % q)
for i in range(p - 1):
for j in range(q):
# vertical
edge = (v2i(i, j), v2i(i + 1, j))
g.add_edges(edge)
for i in range(p):
for j in range(q - 1):
# horizontal
for i_ in range(i, p):
edge = (v2i(i, j), v2i(i_, j + 1))
g.add_edges(edge)
return g