本文整理汇总了Python中graph_tool.Graph.add_vertex方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_vertex方法的具体用法?Python Graph.add_vertex怎么用?Python Graph.add_vertex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graph_tool.Graph
的用法示例。
在下文中一共展示了Graph.add_vertex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen_cascade
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def gen_cascade(g, p, source=None, stop_fraction=0.5):
if source is None:
source = random.choice(np.arange(g.num_vertices()))
infected = {source}
infection_times = np.ones(g.num_vertices()) * -1
infection_times[source] = 0
time = 0
edges = []
while np.count_nonzero(infection_times != -1) / g.num_vertices() <= stop_fraction:
infected_nodes_until_t = copy(infected)
time += 1
for i in infected_nodes_until_t:
for j in g.vertex(i).all_neighbours():
j = int(j)
if j not in infected and random.random() <= p:
infected.add(j)
infection_times[j] = time
edges.append((i, j))
tree = Graph(directed=True)
for _ in range(g.num_vertices()):
tree.add_vertex()
for u, v in edges:
tree.add_edge(u, v)
return source, infection_times, tree
示例2: build_minimum_tree
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def build_minimum_tree(g, root, terminals, edges, directed=True):
"""remove redundant edges from `edges` so that root can reach each node in terminals
"""
# build the tree
t = Graph(directed=directed)
for _ in range(g.num_vertices()):
t.add_vertex()
for (u, v) in edges:
t.add_edge(u, v)
# mask out redundant edges
vis = init_visitor(t, root)
pbfs_search(t, source=root, terminals=list(terminals), visitor=vis)
minimum_edges = {e
for u in terminals
for e in extract_edges_from_pred(t, root, u, vis.pred)}
# print(minimum_edges)
efilt = t.new_edge_property('bool')
efilt.a = False
for u, v in minimum_edges:
efilt[u, v] = True
t.set_edge_filter(efilt)
return filter_nodes_by_edges(t, minimum_edges)
示例3: _filter_short_branch
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def _filter_short_branch(self, filter=False, short=30):
"""
filter out very short branches: do this maybe not right for some models, for models with flat part, it is right
I will test how this effect the final matching results
need to delete nodes, switch with the last one then delete last
"""
if filter == False:
self.verts = self.verts_init
self.edges = self.edges_init
else:
init_graph = Graph(directed=False)
init_graph.add_vertex(len(self.verts_init))
for edge in self.edges_init:
init_graph.add_edge(init_graph.vertex(edge[0]), init_graph.vertex(edge[1]))
terminal_node = []
for v in init_graph.vertices():
if v.out_degree() == 1:
terminal_node.append(v)
visitor = DepthVisitor()
short_nodes = []
for tn in terminal_node:
search.dfs_search(init_graph, tn, visitor)
tmp_node = visitor.get_short_branch(min_length=short)
visitor.reset()
for n in tmp_node:
short_nodes.append(n)
## get edges on the short paths
short_nodes = list(set(short_nodes))
short_edges = []
temp_verts = self.verts_init[:]
v_num = len(self.verts_init)
if len(short_nodes):
for v in reversed(sorted(short_nodes)):
for ve in init_graph.vertex(v).out_edges():
short_edges.append(ve)
## delete edges first, then vertex
short_edges = list(set(short_edges))
for e in short_edges:
init_graph.remove_edge(e)
print 'deleting vertex',
for v in reversed(sorted(short_nodes)):
print v,
temp_verts[int(v)] = temp_verts[v_num-1]
init_graph.remove_vertex(v, fast=True)
v_num -= 1
print '\ndeleting related edges' # already done above, just info user
else:
print 'no short branches'
######## new vertices and edges ########
self.verts = temp_verts[:v_num]
self.edges = []
for e in init_graph.edges():
self.edges.append([int(e.source()), int(e.target())])
示例4: edges2graph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def edges2graph(g, edges):
tree = Graph(directed=True)
for _ in range(g.num_vertices()):
tree.add_vertex()
for u, v in edges:
tree.add_edge(int(u), int(v))
return filter_nodes_by_edges(tree, edges)
示例5: steiner_tree_greedy
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def steiner_tree_greedy(
g, root, infection_times, source, obs_nodes,
debug=False,
verbose=True):
# root = min(obs_nodes, key=infection_times.__getitem__)
sorted_obs = list(sorted(obs_nodes, key=infection_times.__getitem__))[1:]
tree_nodes = {root}
tree_edges = set()
for u in sorted_obs:
# connect u to the tree
vis = init_visitor(g, u)
if debug:
print('connect {} to tree'.format(u))
print('nodes connectable: {}'.format(tree_nodes))
forbidden_nodes = list(set(obs_nodes) - tree_nodes)
cpbfs_search(g, u, visitor=vis,
terminals=list(tree_nodes),
forbidden_nodes=forbidden_nodes,
count_threshold=1)
# add edge
reachable_nodes = set(np.nonzero(vis.dist > 0)[0]).intersection(tree_nodes)
if debug:
print('reachable_nodes: {}'.format(reachable_nodes))
assert len(reachable_nodes) > 0
sorted_ancestors = sorted(reachable_nodes, key=vis.dist.__getitem__)
ancestor = sorted_ancestors[0]
if debug:
print('ancestor: {}'.format(ancestor))
print('dist to reachable: {}'.format(vis.dist[sorted_ancestors]))
new_edges = extract_edges_from_pred(g, u, ancestor, vis.pred)
new_edges = {(v, u) for u, v in new_edges} # needs to reverse the order
if debug:
print('new_edges: {}'.format(new_edges))
tree_edges |= set(new_edges)
tree_nodes |= {v for e in new_edges for v in e}
t = Graph(directed=True)
for _ in range(g.num_vertices()):
t.add_vertex()
vfilt = t.new_vertex_property('bool')
vfilt.a = False
for v in tree_nodes:
vfilt[t.vertex(v)] = True
for u, v in tree_edges:
t.add_edge(t.vertex(u), t.vertex(v))
t.set_vertex_filter(vfilt)
return t
示例6: gen_er
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def gen_er(dicProperties):
np.random.seed()
# initialize graph
graphER = Graph()
nNodes = 0
nEdges = 0
rDens = 0.0
if "Nodes" in dicProperties.keys():
nNodes = dicProperties["Nodes"]
graphER.add_vertex(nNodes)
if "Edges" in dicProperties.keys():
nEdges = dicProperties["Edges"]
rDens = nEdges / float(nNodes**2)
dicProperties["Density"] = rDens
else:
rDens = dicProperties["Density"]
nEdges = int(np.floor(rDens*nNodes**2))
dicProperties["Edges"] = nEdges
else:
nEdges = dicProperties["Edges"]
rDens = dicProperties["Density"]
nNodes = int(np.floor(np.sqrt(nEdges/rDens)))
graphER.add_vertex(nNodes)
dicProperties["Nodes"] = nNodes
# generate edges
numTest,numCurrentEdges = 0,0
while numCurrentEdges != nEdges and numTest < n_MAXTESTS:
lstEdges = np.random.randint(0,nNodes,(nEdges-numCurrentEdges,2))
graphER.add_edge_list(lstEdges)
# remove loops and duplicate edges
remove_self_loops(graphER)
remove_parallel_edges(graphER)
numCurrentEdges = graphER.num_edges()
numTest += 1
graphER.reindex_edges()
nEdges = graphER.num_edges()
rDens = nEdges / float(nNodes**2)
# generate types
rInhibFrac = dicProperties["InhibFrac"]
lstTypesGen = np.random.uniform(0,1,nEdges)
lstTypeLimit = np.full(nEdges,rInhibFrac)
lstIsExcitatory = np.greater(lstTypesGen,lstTypeLimit)
nExc = np.count_nonzero(lstIsExcitatory)
epropType = graphER.new_edge_property("int",np.multiply(2,lstIsExcitatory)-np.repeat(1,nEdges)) # excitatory (True) or inhibitory (False)
graphER.edge_properties["type"] = epropType
# and weights
if dicProperties["Weighted"]:
lstWeights = dicGenWeights[dicProperties["Distribution"]](graphER,dicProperties,nEdges,nExc) # generate the weights
epropW = graphER.new_edge_property("double",lstWeights) # crée la propriété pour stocker les poids
graphER.edge_properties["weight"] = epropW
return graphER
示例7: to_directed
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def to_directed(g, t, root):
new_t = Graph(directed=True)
all_edges = set()
leaves = [v for v in t.vertices()
if (v.out_degree() + v.in_degree()) == 1 and t != root]
for target in leaves:
path = shortest_path(t, source=root, target=target)[0]
edges = set(zip(path[:-1], path[1:]))
all_edges |= edges
for _ in range(g.num_vertices()):
new_t.add_vertex()
for u, v in all_edges:
new_t.add_edge(int(u), int(v))
return new_t
示例8: ring
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def ring(num_vtx=100, k=2, p=0.0):
g = Graph(directed=False)
vtx = list(g.add_vertex(num_vtx))
# connect neighbors
for i in vtx:
for j in xrange(1, k + 1):
dest = g.vertex((g.vertex_index[i] - j) % num_vtx)
if g.edge(i, dest) is None:
g.add_edge(i, dest)
# redirect edges
# old_edges = list(g.edges())
old_edges = [(x.source(), x.target()) for x in g.edges()]
for i in old_edges:
n = random.random()
if n < p: # redirect edge; choose random vertex as new destination
vtx_tmp = vtx[:]
vtx_tmp.remove(i[1])
if i[0] in vtx_tmp:
vtx_tmp.remove(i[0])
dest = random.choice(vtx_tmp)
while g.edge(i[0], dest) is not None:
vtx_tmp.remove(dest)
dest = random.choice(vtx_tmp)
g.remove_edge(g.edge(i[0], i[1]))
g.add_edge(i[0], dest)
return g
示例9: RoadMap
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
class RoadMap(object):
def __init__(self, mapfile):
self._mapfile = mapfile
self.DIRECTION_index = 6
self.PATHCLASS_index = 20
self.g = Graph()
self.g.edge_properties["length"] = self.g.new_edge_property("double")
self.g.edge_properties["level"] = self.g.new_edge_property("int")
self.g.vertex_properties["pos"] = self.g.new_vertex_property("vector<double>")
self.cross_pos_index = {}
def load(self):
if self._mapfile[-3:] != 'shp':
self.g = load_graph(self._mapfile)
return
try:
sf = shapefile.Reader(self._mapfile)
except Exception as e:
print(str(e))
return False
roads_records = sf.shapeRecords() # 获取路段信息'
for road_record in roads_records:
cross_s_index = self.add_cross(road_record.shape.points[0])
cross_e_index = self.add_cross(road_record.shape.points[-1])
self.add_road_edge(cross_s_index, cross_e_index, road_record)
if int(road_record.record[self.DIRECTION_index]) == 0: # 若路段是双向车道
self.add_road_edge(cross_e_index, cross_s_index, road_record)
return True
def has_edge(self, s_vertex, e_vertex):
if self.g.num_vertices() >= max(s_vertex, e_vertex):
return self.g.edge(s_vertex, e_vertex)
else:
return None
def add_cross(self, cross_pos):
if cross_pos in self.cross_pos_index:
return self.cross_pos_index.get(cross_pos)
else:
cross_index = self.g.add_vertex()
self.g.vp.pos[cross_index] = cross_pos
self.cross_pos_index[cross_pos] = cross_index
return cross_index
def add_road_edge(self, s_vertex, e_vertex, road):
if self.has_edge(s_vertex, e_vertex):
return self.g.edge(s_vertex, e_vertex)
else:
edge = self.g.add_edge(s_vertex, e_vertex)
self.g.ep.level[edge] = int(road.record[self.PATHCLASS_index])
self.g.ep.length[edge] = self.road_length(road)
return edge
@staticmethod
def road_length(road):
length = 0
for sub_road in zip(road.shape.points[:-1], road.shape.points[1:]):
length += distance.euclidean(sub_road[0], sub_road[1])
return length
示例10: test_sredni_wspolczynnik_klasteryzacji_na_sztywno_graf_pelny
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def test_sredni_wspolczynnik_klasteryzacji_na_sztywno_graf_pelny(self):
# self.assertEqual(7. / 15, self.stat.sredni_wspolczynnik_klasteryzacji_moj())
# print self.stat.sredni_wspolczynnik_klasteryzacji_moj()
g = Graph(directed=False)
v0 = g.add_vertex()
v1 = g.add_vertex()
v2 = g.add_vertex()
v3 = g.add_vertex()
g.add_edge(v0, v1)
g.add_edge(v0, v2)
g.add_edge(v0, v3)
g.add_edge(v1, v2)
g.add_edge(v1, v3)
g.add_edge(v2, v3)
lc = local_clustering(g, undirected=True)
self.assertEqual(1.0, vertex_average(g, lc)[0])
示例11: edges_to_directed_tree
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def edges_to_directed_tree(g, root, edges):
t = Graph(directed=False)
for _ in range(g.num_vertices()):
t.add_vertex()
for u, v in edges:
t.add_edge(u, v)
vis = EdgeCollectorVisitor()
bfs_search(t, source=root, visitor=vis)
t.clear_edges()
t.set_directed(True)
for u, v in vis.edges:
t.add_edge(u, v)
return filter_nodes_by_edges(t, edges)
示例12: compose_graph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def compose_graph(uid_pid_pairs):
# set up graph
g = Graph()
g.vp['pid'] = v_pid_p = g.new_vertex_property('string')
g.vp['count'] = v_count_p = g.new_vertex_property('int')
g.ep['count'] = e_count_p = g.new_edge_property('int')
pid_v_map = {}
uid_last_v_map = {}
vv_e_map = {}
for uid, pid in uid_pid_pairs:
# vertex
v = pid_v_map.get(pid)
if v is None:
v = g.add_vertex()
v_pid_p[v] = pid
v_count_p[v] = 0
pid_v_map[pid] = v
v_count_p[v] += 1
# edge
last_v = uid_last_v_map.get(uid)
uid_last_v_map[uid] = v
if last_v is None:
continue
vv = (last_v, v)
e = vv_e_map.get(vv)
if e is None:
e = g.add_edge(*vv)
e_count_p[e] = 0
vv_e_map[vv] = e
e_count_p[e] += 1
# calculate closeness
g.vp['closeness'] = v_closeness_p = g.new_vertex_property('float')
e_inverse_count_p = g.new_edge_property('int')
e_inverse_count_p.a = e_count_p.a.max()-e_count_p.a
debug('e_inverse_count_p.a: {}', e_inverse_count_p.a)
closeness(g, weight=e_inverse_count_p, vprop=v_closeness_p)
debug('v_closeness_p.a : {}', v_closeness_p.a)
v_closeness_p.a = nan_to_num(v_closeness_p.a)
debug('v_closeness_p.a : {}', v_closeness_p.a)
# fillter
g.vp['picked'] = v_picked_p = g.new_vertex_property('bool')
debug('v_count_p.a.mean() : {}', v_count_p.a.mean())
v_picked_p.a = v_count_p.a > v_count_p.a.mean()
debug('v_picked_p.a : {}', v_picked_p.a)
g.set_vertex_filter(v_picked_p)
g.set_vertex_filter(None)
return g
示例13: graph_from_dataframes
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def graph_from_dataframes(vertex_df, edge_df):
'''Re-creates a Graph object with PropertyMaps taken
from the vertex_df and edge_df DataFrames
Paramters:
==========
verex_df: a DataFrame with an index named 'vertex_index'
edge_df: a DataFrame with a multi-index named ('source', 'target')
Returns:
========
graph: a grah-tool Graph with PropertyMaps copied
from the columns of the input DataFrames
'''
graph = Graph(directed=True)
vertex_index = vertex_df.index.get_level_values(level='vertex_index')
vertices = graph.add_vertex(n=vertex_index.shape[0])
for col in vertex_df.columns:
in_type = vertex_df[col].dtype.name
try:
dtype = ALIASES[in_type]
except KeyError:
log.info('Data type {} not supported'.format(in_type))
continue
prop = graph.new_vertex_property(dtype)
prop.fa = vertex_df[col]
graph.vertex_properties[col] = prop
src = edge_df.index.names.index('source')
trgt = edge_df.index.names.index('target')
### TODO: use the list edge creation
for tup in edge_df.index:
source, target = tup[src], tup[trgt]
try:
edge = graph.add_edge(source, target)
except ValueError:
log.info('Invalid vertex in (source: {}, target: {})'.format(source, target))
for col in edge_df.columns:
in_type = edge_df[col].dtype.name
try:
dtype = ALIASES[in_type]
except KeyError:
log.info('Data type {} not supported'.format(in_type))
continue
prop = graph.new_edge_property(dtype)
prop.fa = edge_df[col]
graph.edge_properties[col] = prop
return graph
示例14: components_graphtool
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def components_graphtool():
"""
Find connected components using graphtool
"""
g = GTGraph()
# make sure all the nodes are in the graph
g.add_vertex(node_count)
# add the edge list
g.add_edge_list(edges)
labels = np.array(label_components(g, directed=False)[0].a,
dtype=np.int64)[:node_count]
# we have to remove results that contain nodes outside
# of the specified node set and reindex
contained = np.zeros(node_count, dtype=np.bool)
contained[nodes] = True
index = np.arange(node_count, dtype=np.int64)[contained]
components = grouping.group(labels[contained], min_len=min_len)
components = np.array([index[c] for c in components])
return components
示例15: build_closure
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_vertex [as 别名]
def build_closure(g, terminals,
debug=False,
verbose=False):
terminals = list(terminals)
# build closure
gc = Graph(directed=False)
for _ in range(g.num_vertices()):
gc.add_vertex()
edges_with_weight = set()
r2pred = {}
for r in terminals:
if debug:
print('root {}'.format(r))
vis = init_visitor(g, r)
pbfs_search(g, source=r, terminals=terminals, visitor=vis)
new_edges = set(get_edges(vis.dist, r, terminals))
if debug:
print('new edges {}'.format(new_edges))
edges_with_weight |= new_edges
r2pred[r] = vis.pred
for u, v, c in edges_with_weight:
gc.add_edge(u, v)
eweight = gc.new_edge_property('int')
weights = np.array([c for _, _, c in edges_with_weight])
eweight.set_2d_array(weights)
vfilt = gc.new_vertex_property('bool')
vfilt.a = False
for v in terminals:
vfilt[v] = True
gc.set_vertex_filter(vfilt)
return gc, eweight, r2pred