本文整理汇总了Python中igraph.Graph类的典型用法代码示例。如果您正苦于以下问题:Python Graph类的具体用法?Python Graph怎么用?Python Graph使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: convert_to_igraph
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
示例2: disp_tree
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
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: testBug128
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())
示例5: growInstanceGraph
def growInstanceGraph(g, pattern, parentPattern, parentIg):
''' Create the instance graph for pattern @pattern from its parent pattern @parentPattern whose
instance graph is given by @parentIg '''
childEdges = set([x.index for x in pattern.getEdgeList()])
parentEdges = set([x.index for x in parentPattern.getEdgeList()])
newEdgeIndex = childEdges.difference(parentEdges)
dfsCode = str(pattern.getDFSCode())
parentDfsCode = str(parentPattern.getDFSCode())
print pattern.getDFSCode()
if dfsCode not in PATTERNS:
PATTERNS[dfsCode] = set()
if not newEdgeIndex:
return None
if len(newEdgeIndex) != 1:
raise Exception("Cannot grow instance graph beucase has child pattern has %d edges more than the parent pattern"%len(newEdgeIndex))
newEdge = g.es[newEdgeIndex.pop()]
[v0, v1] = getVertices(g, newEdge) #V0 and V1 are the vertices of the new edge that is present in the child pattern
newIg = Graph()
for p in PATTERNS[parentDfsCode]:
newPatternList = []
pEdgeIndices = set([x.index for x in p.getEdgeList()])
for gv in p.getVertices():
if gv["nl"] != v0["nl"]:
continue
for gu in gv.neighbors():
if gu["nl"] != v1["nl"]:
continue
e = getEdge(g, gv, gu)
if e.index in pEdgeIndices:
continue
newPatternEdges = list(p.getEdgeList()) #TODO: Fix this.
newPatternEdges.append(e)
newPattern = Pattern(g, newPatternEdges)
if newPattern in PATTERNS[dfsCode]:
continue
PATTERNS[dfsCode].add(newPattern)
print newPattern
print
newPatternList.append(newPattern)
newIg.add_vertex()
vid = newIg.vs[-1:].indices[0]
INSTANCE_GRAPH_NODES[newPattern] = vid
#Create edges between vertices of newIg
createInstanceGraphEdges(newIg, dfsCode)
return newIg
示例6: create_graph
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
示例7: read_graph
def read_graph(file_name):
# Input edge list file name and output igraph representation
df = pd.read_csv(file_name, sep=" ", names=["Edge1", "Edge2"])
n_vertex, n_edge = df.irow(0)
df = df.drop(0)
graph = Graph(edges=[(x[1]["Edge1"], x[1]["Edge2"])
for x in df.iterrows()], directed=False)
assert(graph.vcount() == n_vertex)
assert(graph.ecount() == n_edge)
return preprocess_graph(graph)
示例8: merge
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
示例9: load_adjlist
def load_adjlist(filename, directed=True):
edgelist = []
names = UniqueIdGenerator()
for line in open(filename):
parts = line.strip().split()
u = names[parts.pop(0)]
edgelist.extend([(u, names[v]) for v in parts])
logging.debug("Edgelist for line %s : %s" % (parts, edgelist))
g = Graph(edgelist, directed=directed)
g.vs["name"] = names.values()
return g
示例10: file2igraph
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
示例11: graph_from_sparse
def graph_from_sparse(data, directed=None):
from igraph import Graph
sources, targets = data.nonzero()
if directed==None:
from numpy import all
directed = not all(data[sources, targets]==data[targets, sources])
from numpy import array
g = Graph(zip(sources, targets), directed=directed, edge_attrs={'weight': array(data[sources, targets])[0]})
if g.is_directed():
return g
else:
return g.simplify(combine_edges="first")
示例12: generate_seed_graph
def generate_seed_graph(g, k):
vcounts = g.vcount()
init_seed = random.randint(0, vcounts)
seed_graph = Graph(directed=False)
seed_graph.add_vertex(g.vs[init_seed]['name'], degree=g.degree(init_seed))
while seed_graph.vcount() != k:
choiced_vertex = random.choice(seed_graph.vs)
choiced_vertex_index = g.vs.find(name=choiced_vertex['name'])
choiced_neighor = g.vs[random.choice(g.neighbors(choiced_vertex_index))]
if choiced_neighor['name'] in seed_graph.vs['name']:
continue
seed_graph.add_vertex(choiced_neighor['name'], degree=g.degree(choiced_neighor['name']))
choiced_neighor_neighor = g.neighbors(choiced_neighor.index)
choiced_neighor_neighor_name = [g.vs[i]['name'] for i in choiced_neighor_neighor]
existed_nodes = set(choiced_neighor_neighor_name) & set(seed_graph.vs['name'])
for node in existed_nodes:
choiced_neighor_id = seed_graph.vs.find(name=choiced_neighor['name']).index
node_id = seed_graph.vs.find(name=node).index
seed_graph.add_edge(choiced_neighor_id, node_id)
return seed_graph
示例13: buildGraph
def buildGraph(taskList, tsize, eList):
G = Graph(tsize + len(eList), directed=False)
G.vs['name'] = taskList.keys() + eList
G.vs['type'] = 0
G.vs[tsize:]['type'] = 1
for task, entityList in taskList.iteritems():
for entity, score in entityList.iteritems():
#a dict -- entity: score
#print task, entity
G[task, entity] = score
#print G
#print G.is_bipartite()
return G
示例14: Physic
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"]) )
示例15: __findNegativeCut
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