本文整理汇总了Python中igraph.Graph.add_vertex方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_vertex方法的具体用法?Python Graph.add_vertex怎么用?Python Graph.add_vertex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类igraph.Graph
的用法示例。
在下文中一共展示了Graph.add_vertex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: translate_cfg
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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_vertex [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: growInstanceGraph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [as 别名]
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
示例4: plotTreeFromString
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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: xg_to_ig
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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
示例6: parse_seed_response
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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
示例7: translatePDGById
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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
示例8: createInstanceGraphForPattern
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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: schools_network
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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
示例10: to_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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: translate_target_cfg
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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
示例12: get_activity_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [as 别名]
def get_activity_graph(self, input_episodes, COLLAPSE_TEMPORAL_NODES):
# Generate activity graph from file with object interaction information
temporal_map = {'after': 'before',
'metby' : 'meets',
'overlapped_by': 'overlaps',
'started_by': 'starts',
'contains':'during',
'finished_by': 'finishes'
}
if type(input_episodes) != list:
# Episodes are given in a file
episodes = self._get_episodes_from_file(input_episodes)
else:
episodes = input_episodes
self.episodes = episodes
objects = {}
data = []
types = []
spatial_rels = {}
vertex_count = 0
graph = Graph(directed=True)
for (o1, o1t, o2, o2t, rel, intv_start, intv_end) in episodes:
# Add objects to the graph
if o1 not in objects:
graph.add_vertex(o1)
objects[o1] = vertex_count
graph.vs()[vertex_count]['obj_type'] = o1t
graph.vs()[vertex_count]['node_type'] = 'object'
vertex_count += 1
if o2 not in objects:
graph.add_vertex(o2)
objects[o2] = vertex_count
graph.vs()[vertex_count]['obj_type'] = o2t
graph.vs()[vertex_count]['node_type'] = 'object'
vertex_count += 1
# Add spatial node to the graph
graph.add_vertex(rel)
graph.vs()[vertex_count]['node_type'] = 'spatial_relation'
# Add edges from spatial node to objects
graph.add_edge(objects[o1], vertex_count)
graph.add_edge(vertex_count, objects[o2])
self.spatial_obj_edges.append((objects[o1], vertex_count))
self.spatial_obj_edges.append((vertex_count, objects[o2]))
data.append((objects[o1], objects[o2], vertex_count, intv_start, intv_end))
vertex_count += 1
(E_s, E_f) = self.get_E_set(objects, data)
temporal_vertices = {}
for ((o11, o12, rel1, s1, e1),(o21, o22, rel2, s2, e2)) in combinations(data,2):
#No temporal relation between two starting episodes or between two final episodes
if ((o11, o12, s1, e1) in E_s and (o21, o22, s2, e2) in E_s) or ((o11, o12, s1, e1) in E_f and (o21, o22, s2, e2) in E_f):
continue
temporal_rel = get_allen_relation(s1, e1, s2, e2)
# If temporal_rel is in temporal_map get its value otherwise keep it the same
# If the edges are directed, then we need to change the direction of the edges
# if we change change the temporal relation to its inverse
temporal_rel_new = temporal_map.get(temporal_rel, temporal_rel)
# Add temporal node to the graph
if COLLAPSE_TEMPORAL_NODES and temporal_rel_new in temporal_vertices:
temporal_rel_vertex_id = temporal_vertices[temporal_rel_new]
else:
graph.add_vertex(temporal_rel_new)
graph.vs()[vertex_count]['node_type'] = 'temporal_relation'
temporal_rel_vertex_id = vertex_count
temporal_vertices[temporal_rel_new] = vertex_count
vertex_count += 1
if temporal_rel_new == temporal_rel:
# Add edges from temporal node to the spatial nodes
graph.add_edge(rel1, temporal_rel_vertex_id)
graph.add_edge(temporal_rel_vertex_id, rel2)
self.temp_spatial_edges.append((rel1, temporal_rel_vertex_id))
self.temp_spatial_edges.append((temporal_rel_vertex_id, rel2))
else:
# PD: if an inverse temporal relation has been used, switch the edges around
graph.add_edge(temporal_rel_vertex_id, rel1)
graph.add_edge(rel2, temporal_rel_vertex_id)
self.temp_spatial_edges.append((temporal_rel_vertex_id, rel1))
self.temp_spatial_edges.append((rel2, temporal_rel_vertex_id))
return graph
示例13: BpmnSerializer
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [as 别名]
class BpmnSerializer(object):
def __init__(self, file_path, entrypoint=None):
entrypoint = entrypoint or 'main_process'
bpmn = ET.parse(file_path)
self.parser = BpmnParser()
self.parser.add_bpmn_xml(bpmn, filename=file_path)
self.spec = self.parser.get_spec(entrypoint)
self.workflow = BpmnWorkflow(self.spec)
self.graph = Graph(directed=True)
self.data = {}
self.data_watch = True
self.vertices = {}
self.vertice_id = 0
self.edges = {}
self.edge_id = 0
def set_data(self, data):
self.data = data
self.data_watch = True
def get_start_task(self, task=None):
task = task or self.workflow.task_tree
if isinstance(task.task_spec, StartEvent):
return task
for subtask in task.children:
subtask_child = self.get_start_task(subtask)
if subtask_child:
return subtask_child
return None
def get_tasks_node_ids(self, *tasks):
try:
return [self.vertices[task.task_spec.id] for task in tasks]
except:
pass
def link_tasks(self, task_source, task_target, **kwargs):
edge_ids = self.get_tasks_node_ids(task_source, task_target)
if edge_ids:
edge_signature = '{}-{}'.format(*edge_ids)
if edge_signature not in self.edges.keys():
self.graph.add_edge(edge_ids[0], edge_ids[1], **kwargs)
edge_conf = dict(kwargs)
edge_conf['source'] = edge_ids[0]
edge_conf['target'] = edge_ids[1]
self.edges[edge_signature] = edge_conf
return self.edges[edge_signature]
@staticmethod
def get_task_type(task):
if isinstance(task.task_spec, ParallelGateway):
return 'split'
if isinstance(task.task_spec, InclusiveGateway):
return 'join'
if isinstance(task.task_spec, StartEvent):
return 'virtual'
return 'task'
def map_graph(self, task=None):
task = task or self.get_start_task()
if isinstance(task.task_spec, EndEvent):
return
if task.task_spec.id not in self.vertices.keys():
task_data = self.data.get(task.get_name(), {})
self.graph.add_vertex(
task.get_name(),
type=self.get_task_type(task),
domain=task.task_spec.lane or 'default',
id=task.task_spec.description,
label=task.get_name(),
parameters=task_data.get('parameters', {})
)
self.vertices[task.task_spec.id] = self.vertice_id
self.vertice_id += 1
if not isinstance(task.task_spec, StartTask):
self.link_tasks(task.parent, task)
map(self.map_graph, task.children)
def get_graph(self, data=None):
if data:
self.set_data(data)
if self.data_watch:
self.map_graph()
self.data_watch = False
return self.graph
def dump_graph(self, vertex, indent=0):
print ' '*indent, vertex
[self.dump_graph(child, indent+1) for child in vertex.successors()]
def dump_workflow(self, task, indent=0):
#.........这里部分代码省略.........
示例14: Graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [as 别名]
# cant add an edge if one of the verices are not made
g = Graph()
# print g
g.es["weight"] = 1.0
gen = UniqueIdGenerator()
for e in adjList:
# print e[0], e[1]
if e[0] not in gen:
sourceVertex = {}
# sourceVertex["uid"] = gen[e[0]]
sourceVertex = e[0]
g.add_vertex(sourceVertex)
# print g
if e[1] not in gen:
targetVertex = {}
# targetVertex["uid"] = gen[e[1]]
targetVertex = e[1]
g.add_vertex(targetVertex)
# print adjList[e]
g[gen[e[0]], gen[e[1]]] = adjList[e] * 5
print "graph contains ", len(g.es), "edges"
print "graph contains ", len(g.vs), "vertices"
# filterOutNoise(edge)
示例15: generate_network_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import add_vertex [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