本文整理汇总了Python中igraph.Graph.add_edge方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_edge方法的具体用法?Python Graph.add_edge怎么用?Python Graph.add_edge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类igraph.Graph
的用法示例。
在下文中一共展示了Graph.add_edge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: translate_cfg
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def translate_cfg(neo4j_db, function_node):
cfg_edges = get_cfg_edges(neo4j_db, function_node)
#create igraph cfg
g = Graph(directed = True)
#add edge and edge properties
for edge in cfg_edges :
start_node = edge.start_node
end_node = edge.end_node
if start_node is None or end_node is None:
print "edge has no start or end node"
try:
g.vs.find(name=str(start_node._id))
except:
g.add_vertex(name=str(start_node._id), **get_node_properties(start_node.properties))
try:
g.vs.find(name=str(end_node._id))
except:
g.add_vertex(name=str(end_node._id), **get_node_properties(end_node.properties))
g.add_edge(str(start_node._id), str(end_node._id),**get_cfg_edge_properties(edge.properties))
return g
示例2: generate_seed_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
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
示例3: __findNegativeCut
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [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
示例4: plotTreeFromString
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def plotTreeFromString(treeString, colordict, plotFile):
"""
Plots a tree from the 'brackets tree' format
:param treeString:
:param colordict: defines the colors of the nodes by label (e.g. 1 to 5)
:param plotFile: output file (.png)
:return:
"""
g = Graph()
splitted = treeString.split("(")
level = -1
parents = dict()
parentIds = dict()
levelCount = dict()
for part in splitted:
if len(part)<1:
continue
else: #label follows
level+=1
count = levelCount.get(level,0)
levelCount[level] = count+1
#print "level %d" % level
label = part[0]
#print part.split()
if len(part.split())>1: #leaf node
label, wordPlusEnding = part.split()
#print part, "at leaf"
endings = wordPlusEnding.count(")")
word = wordPlusEnding.strip(")")
g.add_vertex(label=word, color=colordict[int(label)])
#print "added node %d" % (len(g.vs)-1)
currentNode = len(g.vs)-1
p = parents[level-1]
g.add_edge(currentNode,p)#add edge to parent
#print "added edge %d-%d" % (len(g.vs)-1, parentIds[level-1])
level-=endings
#print "word", word
else:
g.add_vertex(label=label, color=colordict[int(label)])
currentNode = g.vs[len(g.vs)-1]
#print "added node %d" % (len(g.vs)-1)
if level != 0:
p = parents[level-1]
g.add_edge(currentNode,p)#add edge to parent
#print "added edge %d-%d" % (len(g.vs)-1, parentIds[level-1])
parent = currentNode
parentId = len(g.vs)-1
parents[level] = parent
parentIds[level] = parentId
print parentIds
print g.summary()
layout = g.layout_reingold_tilford(mode="in", root=0)
plot(g, plotFile, layout=layout, bbox = (2000, 1000), margin = 100)
示例5: parse_seed_response
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def parse_seed_response(data):
g = Graph(directed=False)
lines = data.splitlines()
#query_count = lines[1]
node_attr, edge_attr = [int(i) for i in lines[2].split(' ')]
node_count = int(lines[3])
for i in lines[4: node_count+4]:
attr_dict = parse_node_attribute(i, node_attr)
if not attr_dict:
continue
g.add_vertex(**attr_dict)
for i in lines[node_count+5:]:
attr_dict = parse_edge_attribute(i, edge_attr)
if not attr_dict:
continue
g.add_edge(**attr_dict)
return g, node_attr, edge_attr
示例6: translatePDGById
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def translatePDGById(db, func_id):
ddgEdges = getDDGEdges(db, func_id) # prop:var
cdgEdges = getCDGEdges(db, func_id) # no prop
Edges = ddgEdges + cdgEdges
g = Graph(directed=True)
for edge in Edges:
startNode = str(edge.start_node._id)
if isNodeExist(g, startNode) == False:
node_prop = {"code": edge.start_node.properties["code"], "type": edge.start_node.properties["type"]}
g.add_vertex(startNode, **node_prop)
endNode = str(edge.end_node._id)
if isNodeExist(g, endNode) == False:
node_prop = {"code": edge.end_node.properties["code"], "type": edge.end_node.properties["type"]}
g.add_vertex(endNode, **node_prop)
edge_prop = {"var": edge.properties["var"]}
g.add_edge(startNode, endNode, **edge_prop)
return g
示例7: getSimMSTs
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def getSimMSTs(self, inverse=True, plotGraph=True, root="UNK"):
rootId1 = self.emb1.d[root]
rootId2 = self.emb2.d[root]
if inverse == True:
d = -1
else:
d = 1
g1 = minimum_spanning_tree(csr_matrix(d*self.s1))
g2 = minimum_spanning_tree(csr_matrix(d*self.s2))
a1 = g1.toarray()
a2 = g2.toarray()
if plotGraph==True:
t1 = Graph()
t2 = Graph()
t3 = Graph()
t1.add_vertices(self.emb1.vocab_size)
t2.add_vertices(self.emb2.vocab_size)
t3.add_vertices(self.emb1.vocab_size)
t1.vs["color"] = "white"
t2.vs["color"] = "white"
t3.vs["color"] = "white"
t1.vs["label"] = [w for w,i in sorted(self.emb1.d.items(), key=itemgetter(1))]
t2.vs["label"] = [w for w,i in sorted(self.emb2.d.items(), key=itemgetter(1))]
t3.vs["label"] = t1.vs["label"]
for i in xrange(a1.shape[0]):
for j in xrange(a1.shape[1]):
if a1[i,j] != 0:
t1.add_edge(i,j, weight=a1[i,j], color="blue")
t3.add_edge(i,j, weight=a1[i,j], color="blue")
for i in xrange(a2.shape[0]):
for j in xrange(a2.shape[1]):
if a2[i,j] != 0:
t2.add_edge(i,j, weight=a2[i,j], color="red")
if t3.are_connected(i,j): #edge in both MSTs
t3.es[i,j]["color"] = "black"
else:
t3.add_edge(i,j, weight=a1[i,j], color="red")
layout1 = t1.layout_reingold_tilford(mode="in", root=rootId1)
layout2 = t2.layout_reingold_tilford(mode="in", root=rootId2)
layout3 = t3.layout_reingold_tilford(mode="in", root=rootId1)
graphs = [Graph.GRG(10, 0.4) for _ in xrange(5)]
figure = Plot(bbox=(0,0,2000,1000))
figure.add(t1, layout=layout1, margin=100, bbox=(0,0,1000,1000))
figure.add(t2, layout=layout2, margin=100, bbox=(1000,0,2000,1000))
plotname1 = "plots/"+NAME+".mst_trees.png"
figure.save(plotname1)
plotname3 = "plots/"+NAME+".merged_mst.png"
plot(t3, plotname3 , layout=layout3, bbox=(1000,1000), margin=100)
print("\tSaved MST plots in '%s', '%s'" % (plotname1, plotname3))
return t1,t2,t3
示例8: createInstanceGraphForPattern
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def createInstanceGraphForPattern(pattern):
instanceGraph = Graph()
if pattern not in PATTERN_INSTANCES:
raise Exception('Pattern %s not found'%str(pattern))
patternInstances = list(PATTERN_INSTANCES[pattern])
for instance in patternInstances:
instanceGraph.add_vertex()
vertex = instanceGraph.vs[len(instanceGraph.vs) - 1]
vertex["instance"] = instance
for i in range(0, len(patternInstances) - 1):
for j in range(i+1, len(patternInstances)):
instance1 = patternInstances[i]
instance2 = patternInstances[j]
if instance1.overlaps(instance2):
instanceGraph.add_edge(i,j)
return instanceGraph
示例9: translate_target_cfg
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def translate_target_cfg(neo4j_db, function_node):
cfg_edges = get_cfg_edges(neo4j_db, function_node)
#create igraph cfg
g = Graph(directed = True)
#add edge and edge properties
for edge in cfg_edges :
start_node = edge.start_node
end_node = edge.end_node
if start_node is None or end_node is None:
print "edge has no start or end node"
add_edge = True
try:
g.vs.find(name=str(start_node._id))
except:
if start_node.properties['type'] == u'CFGEntryNode':
add_edge = False
else:
g.add_vertex(name=str(start_node._id), **get_node_properties(start_node.properties))
try:
g.vs.find(name=str(end_node._id))
except:
if start_node.properties['type'] == u'CFGExitNode':
add_edge = False
else:
g.add_vertex(name=str(end_node._id), **get_node_properties(end_node.properties))
if add_edge:
g.add_edge(str(start_node._id), str(end_node._id),**get_cfg_edge_properties(edge.properties))
return g
示例10: to_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def to_graph(tree, g=None, serial=None, is_unrooted=True):
is_root = False
if g is None:
is_root = True
g = Graph()
if serial is None:
serial = it.count(-1, -1)
c = tree.content if tree.content is not None else str(serial.next())
if is_root and is_unrooted and len(tree.children()) == 2:
left, right = [to_graph(child, g, serial) for child in tree.children()]
length = sum(tree.lengths())
g.add_edge(left, right, length=length)
else:
g.add_vertex(name = c)
for child, length in zip(tree.children(), tree.lengths()):
child_content = to_graph(child, g, serial)
g.add_edge(c, child_content, length=length)
if is_root:
return g
return c
示例11: schools_network
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def schools_network(cls, schools):
# generate a network graph for people, places, and journals
# associated with a set of schools (e.g., all schools categorized
# by a particular person)
# igraph requires numerical id; zurnatikl uses network id to
# differentiate content types & database ids
# prefetch related people and locations for efficiency
schools = schools.prefetch_related('person_set', 'locations')
graph_start = time.time()
graph = Graph()
for s in schools:
# add the school itself to the graph
graph.add_vertex(s.network_id, label=unicode(s),
type=s.network_type)
# add people, places, & journals associated with each school
start = time.time()
# a school may have one or more locations
for loc in s.locations.all():
# only add location if it is not already in the graph
if loc.network_id not in graph.vs['name']:
graph.add_vertex(loc.network_id, label=loc.short_label,
type=loc.network_type)
graph.add_edge(s.network_id, loc.network_id)
# people can be associated with one or more schools
for p in s.person_set.all():
# only add person if not already in the graph
if p.network_id not in graph.vs['name']:
graph.add_vertex(p.network_id, label=p.firstname_lastname,
type=p.network_type)
graph.add_edge(s.network_id, p.network_id)
# journals can also be associated with a school
for j in s.journal_set.all():
if j.network_id not in graph.vs['name']:
graph.add_vertex(j.network_id, label=unicode(j),
type=j.network_type)
graph.add_edge(s.network_id, j.network_id)
logger.debug('Added %d locations, %s people, and %d journals for %s in %.2f sec',
s.locations.all().count(), s.person_set.all().count(),
s.journal_set.all().count(), s, time.time() - start)
logger.debug('schools network graph generated in %.2f sec',
time.time() - graph_start)
return graph
示例12: test_should
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def test_should(self):
graph = Graph()
graph.add_vertices(["1", "2"])
graph.add_edge("1", "2",weight=9)
self.assertFalse(graph.is_directed())
示例13: get_activity_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def get_activity_graph(self, episodes):
"""Generates the qstag for a set of input episode QSRs.
:param episodes: list of QSR Epiosdes generated using `compute_episodes(world_qsr)``
:type episodes: list
:return: igraph.Graph: An igraph graph object containing all the object, spatial and temporal nodes.
:rtype: igraph.Graph
"""
temporal_map = {'after': 'before',
'metby' : 'meets',
'overlapped_by': 'overlaps',
'started_by': 'starts',
'contains':'during',
'finished_by': 'finishes'
}
spatial_nodes_edges = {"rcc2": 2, "rcc3": 2, "rcc8": 2, "cardir": 2,
"qtcbs": 2, "qtccs": 2, "qtcbcs": 2, "argd": 2, "argprobd": 2, "mos": 1}
objects = {}
spatial_data = []
vertex_count = 0
graph = Graph(directed=True)
#print("Looping through the episodes...")
for (objs, relations, (intv_start, intv_end)) in episodes:
#print(objs, relations, (intv_start, intv_end))
#############################################
# Object Nodes: #
#############################################
number_of_edges = set([])
for rel in relations.keys():
number_of_edges.add(spatial_nodes_edges[rel])
if len(number_of_edges) != 1:
raise ValueError("QSRs with different spatial node edges selected.")
else:
spatial_edges = number_of_edges.pop()
for o in objs:
if o in objects: continue
graph.add_vertex(o)
objects[o] = vertex_count
if o in self.__object_types:
graph.vs()[vertex_count]['obj_type'] = self.__object_types[o]
graph.vs()[vertex_count]['node_type'] = 'object'
vertex_count += 1
object_ids = []
for o in objs:
object_ids.append(objects[o])
#print(" OBJECT IDS ", object_ids)
#############################################
# Spatial Nodes: #
#############################################
graph.add_vertex(relations)
graph.vs()[vertex_count]['node_type'] = 'spatial_relation'
# Add edges from spatial node to objects
edge_from_object = objects[objs[0]]
#print("adding edge: : ", edge_from_object, vertex_count)
graph.add_edge(edge_from_object, vertex_count)
self.__spatial_obj_edges.append( (edge_from_object, vertex_count) )
if spatial_edges is 2:
#print("TWO OBJECTS -- ")
edge_to_object = objects[objs[1]]
graph.add_edge(vertex_count, edge_to_object)
self.__spatial_obj_edges.append( (vertex_count, edge_to_object) )
elif spatial_edges is 3:
#print("THREE OBJECTS -- ")
edge_from_object_2 = objects[objs[1]]
edge_from_object_3 = objects[objs[2]]
graph.add_edge(edge_from_object_2, vertex_count)
graph.add_edge(edge_from_object_3, vertex_count)
self.__spatial_obj_edges.append( (edge_from_object_2, vertex_count) )
self.__spatial_obj_edges.append( (edge_from_object_3, vertex_count) )
spatial_data.append( (object_ids, vertex_count, (intv_start, intv_end)) )
vertex_count += 1
#############################################
# Temporal Nodes: #
#############################################
#print("data: \n", spatial_data)
#print("objects \n", objects)
(E_s, E_f) = self.get_E_set(objects, spatial_data)
#print("E_s: ", E_s)
#print("E_f: ", E_f)
temporal_vertices = {}
#.........这里部分代码省略.........
示例14: parse_full_arnetminer_dataset
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def parse_full_arnetminer_dataset(should_profile, use_igraph):
"""
Parse the full arnetminer dataset in plaintext format. Vertex types in the graph are:
1: Authors
2: Papers
3: Conferences
4: Terms
"""
print "Parsing nodes for graph..."
input_file = open(os.path.join(project_root, 'data', 'Arnetminer-Full.txt'))
beginning = input_file.tell()
# Use either igraph or networkx
if use_igraph:
graph = Graph(directed=True)
else:
graph = MultiDiGraph()
# Counts for statistics
VALID_PAPERS = 8579222 # Most recent count of valid papers from Arnetminer
papers_processed = 0
# Caches for vertices & edges to add (batch adds together when using igraph)
vertices_to_add = []
edges_to_add = []
types_of_vertices_to_add = []
FLUSH_FREQUENCY = 100000 # 'Flush' cached vertices and edges this often
# Add each paper to graph (adding missing associated terms, authors, and conferences)
for title, authors, conference, terms, paper_index in __papers_from_file(input_file, should_profile):
# Output any test paper indices found
if title in test_papers:
print "Found test paper '%s' by %s, index: %d" % (title, ','.join(authors), paper_index)
if use_igraph:
# Use string, because otherwise integer overflow in igraph
paper_index = str(paper_index)
# Collect vertices and edges to add
vertices_to_add += [paper_index, conference] + authors + terms
types_of_vertices_to_add += [2, 3] + ([1] * len(authors)) + ([4] * len(terms))
for author in authors:
edges_to_add += [(author, paper_index), (paper_index, author)]
edges_to_add += [(conference, paper_index), (paper_index, conference)]
for term in terms:
edges_to_add += [(term, paper_index), (paper_index, term)]
# Every so often, actually mutate the graph
if papers_processed % FLUSH_FREQUENCY == 0:
for vertex, vertex_type in zip(vertices_to_add, types_of_vertices_to_add):
graph.add_vertex(vertex, type=vertex_type)
graph.add_edges(edges_to_add)
vertices_to_add = []
edges_to_add = []
types_of_vertices_to_add = []
else:
# Add symmetric edges & nodes (if they don't already exist in the network)
for author in authors:
graph.add_edges_from([(author, paper_index), (paper_index, author)])
graph.add_edges_from([(conference, paper_index), (paper_index, conference)])
for term in terms:
graph.add_edges_from([(term, paper_index), (paper_index, term)])
# Output progress
papers_processed += 1
if papers_processed % 10 == 0:
sys.stdout.write("\r Processed %d / %d papers..." % (papers_processed, VALID_PAPERS))
sys.stdout.flush()
# Basic statistics about cleanliness of data
count_and_percent_of_papers = lambda a: (a, total_papers, 100 * float(a) / total_papers)
print "\n\nTotal Papers: %d" % total_papers
print " Added (Successful): %d / %d (%2.2f%%)" % count_and_percent_of_papers(successful_papers)
print " Ignored (Bad Title): %d / %d (%2.2f%%)" % count_and_percent_of_papers(skipped_bad_title)
print " Skipped (Missing Conference): %d / %d (%2.2f%%)" % count_and_percent_of_papers(skipped_missing_conference)
print " Invalid (Unknown): %d / %d (%2.2f%%)\n\n" % count_and_percent_of_papers(invalid_papers)
# Rewind file
input_file.seek(beginning)
print "Parsing citations for graph..."
# Counts for statistics
papers_processed = 0
successful_citations = 0
omitted_paper_citations = 0
invalid_paper_citations = 0
invalid_citations = 0
# Cache for citations to add (batch graph actions for igraph)
citations_to_add = []
# Add citations to the graph
for citing_id, citations in __citations_from_file(input_file, should_profile):
#.........这里部分代码省略.........
示例15: generate_network_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_edge [as 别名]
def generate_network_graph(use_ascii=False):
'''Generate a :class:`networkx.MultiGraph` from the connections among
schools, people, locations, journals, issues, and items.
Optionally convert unicode to ascii, if needed by the export tool.
'''
start = time.time()
# generate a graph for serialization
# TODO: probably need to add caching on this graph
graph = Graph()
# igraph requires numerical id; zurnatikl uses network id to
# differentiate content types & database ids
# helper method to convert attributes to ascii or unicode as requested
def attr(attributes):
# force content to ascii if requested
if use_ascii:
return to_ascii(attributes)
else:
# explicitly encode unicode, as a workaround for
# igraph/ascii errors
# see https://github.com/igraph/python-igraph/issues/5
return encode_unicode(attributes)
schools = School.objects.all()
edges = []
for school in schools:
graph.add_vertex(school.network_id,
**attr(school.network_attributes))
# edges can't be added until both source and target nodes exist
if school.has_network_edges:
edges.extend(school.network_edges)
people = Person.objects.all().prefetch_related('schools', 'dwellings')
for person in people:
graph.add_vertex(person.network_id,
**attr(person.network_attributes))
if person.has_network_edges:
edges.extend(person.network_edges)
locations = Location.objects.all().prefetch_related('placename_set')
for loc in locations:
graph.add_vertex(loc.network_id,
**attr(loc.network_attributes))
if loc.has_network_edges:
edges.extend(loc.network_edges)
journals = Journal.objects.all()
for journal in journals:
graph.add_vertex(journal.network_id,
**attr(journal.network_attributes))
if journal.has_network_edges:
edges.extend(journal.network_edges)
issues = Issue.objects.all().prefetch_related('editors',
'contributing_editors', 'publication_address', 'print_address',
'mailing_addresses')
for issue in issues:
graph.add_vertex(issue.network_id,
**attr(issue.network_attributes))
if issue.has_network_edges:
edges.extend(issue.network_edges)
items = Item.objects.all().prefetch_related('issue', 'creators',
'translators', 'persons_mentioned', 'addresses', 'genre')
for item in items:
graph.add_vertex(item.network_id,
**attr(item.network_attributes))
if item.has_network_edges:
edges.extend(item.network_edges)
# some edges have edge attributes, others do not
# edges without attributes can be added en masse
simple_edges = [edge for edge in edges if len(edge) == 2]
graph.add_edges(simple_edges)
edge_attrs = [edge for edge in edges if len(edge) > 2]
for source, target, attributes in edge_attrs:
graph.add_edge(source, target, **attributes)
logger.debug('Generated full graph in %.2f sec' % (time.time() - start))
return graph