本文整理汇总了Python中graph_tool.Graph类的典型用法代码示例。如果您正苦于以下问题:Python Graph类的具体用法?Python Graph怎么用?Python Graph使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: split_gt
def split_gt():
g = GTGraph()
g.add_edge_list(adjacency)
component_labels = label_components(g, directed=False)[0].a
components = group(component_labels)
result = mesh.submesh(components, only_watertight=only_watertight)
return result
示例2: gen_cascade
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
示例3: is_planar
def is_planar(self):
"""
See the following library:
https://graph-tool.skewed.de/static/doc/topology.html
"""
edges = self.obtain_edge_list()
graph = Graph().add_vertex(len(self.adj_matrix)).add_edge_list(edges)
return graph.is_planar()
示例4: edges2graph
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: RoadMap
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
示例6: build_minimum_tree
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)
示例7: to_directed
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: _parse_data
def _parse_data(self):
"""
extract interal points(degree>2) and endpoints(degree=1)
extract segments
"""
if self.verts == None or self.edges == None:
print 'please first call read_skel_file function'
else:
self.verts = np.array(self.verts, dtype=np.float)
self.edges = np.array(self.edges, dtype=np.int)
terminal_index = []
junction_index = []
self.skel_graph = Graph(directed=False)
self.skel_graph.add_vertex(len(self.verts))
for edge in self.edges :
self.skel_graph.add_edge(self.skel_graph.vertex(edge[0]), self.skel_graph.vertex(edge[1]))
for v in self.skel_graph.vertices():
if v.out_degree() == 2 :
continue
elif v.out_degree() == 1 :
terminal_index.append(int(v))
elif v.out_degree() > 2 :
junction_index.append(int(v))
self.terminal = self.verts[terminal_index]
self.junction = self.verts[junction_index]
self.terminal_index = terminal_index
self.junction_index = junction_index
self.feature_node_index = junction_index + terminal_index
self.feature_node = self.verts[self.feature_node_index]
"""
示例9: facets_gt
def facets_gt(mesh):
'''
Returns lists of facets of a mesh.
Facets are defined as groups of faces which are both adjacent and parallel
facets returned reference indices in mesh.faces
If return_area is True, both the list of facets and their area are returned.
'''
face_idx = mesh.face_adjacency()
normal_pairs = mesh.face_normals[[face_idx]]
parallel = np.abs(np.sum(normal_pairs[:,0,:] * normal_pairs[:,1,:], axis=1) - 1) < TOL_PLANAR
graph_parallel = GTGraph()
graph_parallel.add_edge_list(face_idx[parallel])
connected = label_components(graph_parallel, directed=False)[0].a
facets_idx = group(connected, min_length=2)
return facets_idx
示例10: load_graph
def load_graph(infile):
inmatrix = np.loadtxt(infile, dtype=np.dtype('uint32'), delimiter=" ")
numv = np.amax(inmatrix[:,0:2])
#print numv, inmatrix[:,0:2]
g = Graph(directed=False)
edge_weights = g.new_edge_property("double")
g.edge_properties["weights"] = edge_weights
vlist = list(g.add_vertex(numv))
for i in inmatrix:
edge = g.add_edge(vlist[i[0]-1], vlist[i[1]-1]) # need to convert from 1-based index in file to 0-based
edge_weights[edge] = i[2]
remove_parallel_edges(g)
return g
示例11: __init__
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 = {}
示例12: test_sredni_wspolczynnik_klasteryzacji_na_sztywno_graf_pelny
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])
示例13: split_gt
def split_gt(mesh, check_watertight=True, only_count=False):
g = GTGraph()
g.add_edge_list(mesh.face_adjacency())
component_labels = label_components(g, directed=False)[0].a
if check_watertight:
degree = g.degree_property_map('total').a
meshes = deque()
components = group(component_labels)
if only_count: return len(components)
for i, current in enumerate(components):
fill_holes = False
if check_watertight:
degree_3 = degree[current] == 3
degree_2 = degree[current] == 2
if not degree_3.all():
if np.logical_or(degree_3, degree_2).all():
fill_holes = True
else:
continue
# these faces have the original vertex indices
faces_original = mesh.faces[current]
face_normals = mesh.face_normals[current]
# we find the unique vertex indices, so we can reindex from zero
unique_vert = np.unique(faces_original)
vertices = mesh.vertices[unique_vert]
replacement = np.zeros(unique_vert.max()+1, dtype=np.int)
replacement[unique_vert] = np.arange(len(unique_vert))
faces = replacement[faces_original]
new_mesh = mesh.__class__(faces = faces,
face_normals = face_normals,
vertices = vertices)
new_meta = deepcopy(mesh.metadata)
if 'name' in new_meta:
new_meta['name'] = new_meta['name'] + '_' + str(i)
new_mesh.metadata.update(new_meta)
if fill_holes:
try: new_mesh.fill_holes(raise_watertight=True)
except MeshError: continue
meshes.append(new_mesh)
return list(meshes)
示例14: __init__
def __init__(self, number_of_vertices, graph_type):
super().__init__(number_of_vertices, graph_type)
# Graph tool creates directed multigraph by default.
self._graph = Graph()
self._graph.add_vertex(number_of_vertices)
self._graph.vertex_properties["cell"] = self._graph.new_vertex_property(
"object", number_of_vertices * [BoardCell()]
)
self._graph.edge_properties["direction"
] = self._graph.new_edge_property("object")
self._graph.edge_properties["weight"
] = self._graph.new_edge_property("int")
示例15: components_graphtool
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