当前位置: 首页>>代码示例>>Python>>正文


Python Graph.vertices方法代码示例

本文整理汇总了Python中graph_tool.Graph.vertices方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.vertices方法的具体用法?Python Graph.vertices怎么用?Python Graph.vertices使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在graph_tool.Graph的用法示例。


在下文中一共展示了Graph.vertices方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _filter_short_branch

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import vertices [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())])
开发者ID:bo-wu,项目名称:skel_corres,代码行数:61,代码来源:skeleton_data.py

示例2: SkeletonData

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import vertices [as 别名]
class SkeletonData(object):
    """
    class to store and process skeleton data, like generated from starlab mean curvature skeleton
    """
    def __init__(self, fname=None, mesh_name=None, filter_sb=False):
        """
        @param filter_sb: if filter out Short Branch
        """
        if fname != None:
            self.skel_name = fname
            self.read_skel_file(fname)
            self._filter_short_branch(filter=filter_sb, short=10)
            self._parse_data()
            self.mesh_name = mesh_name
            self.vert_radius = None

    def calc_skel_properties(self):
        """
        calc all properties needed for matching
        """
        self.calc_node_centricity()
        self.calc_skel_radius()
        self.calc_path_length_ratio()
        self.calc_path_radius_ratio()
        self.normalize_skeleton()


    def read_skel_file(self, fname, dim=3):
        if fname == None:
            print 'please input skeleton file name'
            sys.exit(0)
        elif os.path.isfile(fname):
            self.verts_init = []
            self.edges_init = []
            with open(fname) as sf:
                for line in sf:
                    line = line.strip('\n')
                    line = line.split(' ')
                    if line[0] == '#':
                        continue
                    elif line[0] == 'v':
                        self.verts_init.append([x for x in line[1:(dim+1)]])
                    #### attention!! verts of edge start from 1 in files ####
                    elif line[0] == 'e':
                        self.edges_init.append([int(x)-1 for x in line[1:3]])
                    else:
                        print 'not support this format'
                        sys.exit(0)
        else:
            print 'no such flie', fname
            sys.exit(0)


    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,
#.........这里部分代码省略.........
开发者ID:bo-wu,项目名称:skel_corres,代码行数:103,代码来源:skeleton_data.py

示例3: BoardGraphGraphtool

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import vertices [as 别名]
class BoardGraphGraphtool(BoardGraphBase):

    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")

    def __getitem__(self, position):
        return self._graph.vp.cell[self._graph.vertex(position)]

    def __setitem__(self, position, board_cell):
        self._graph.vp.cell[self._graph.vertex(position)] = board_cell

    def __contains__(self, position):
        return position in range(0, self.vertices_count())

    def vertices_count(self):
        return self._graph.num_vertices()

    def edges_count(self):
        return self._graph.num_edges()

    def has_edge(self, source_vertice, target_vertice, direction):
        for e in self._graph.vertex(source_vertice).out_edges():
            if (
                int(e.target()) == target_vertice and
                self._graph.ep.direction[e] == direction
            ):
                return True
        return False

    def out_edges_count(self, source_vertice, target_vertice):
        return len([
            1 for e in self._graph.vertex(source_vertice).out_edges()
            if int(e.target()) == target_vertice
        ])

    def reconfigure_edges(self, width, height, tessellation):
        """
        Uses tessellation object to create all edges in graph.
        """
        self._graph.clear_edges()
        for source_vertice in self._graph.vertices():
            for direction in tessellation.legal_directions:
                neighbor_vertice = tessellation.neighbor_position(
                    int(source_vertice),
                    direction,
                    board_width=width,
                    board_height=height
                )
                if neighbor_vertice is not None:
                    e = self._graph.add_edge(
                        source_vertice, neighbor_vertice, add_missing=False
                    )
                    self._graph.ep.direction[e] = direction

    # TODO: Faster version?
    # def reconfigure_edges(self, width, height, tessellation):
    #     """
    #     Uses tessellation object to create all edges in graph.
    #     """
    #     self._graph.clear_edges()
    #     edges_to_add = []
    #     directions_to_add = dict()
    #     for source_vertice in self._graph.vertices():
    #         for direction in tessellation.legal_directions:
    #             neighbor_vertice = tessellation.neighbor_position(
    #                 int(source_vertice), direction,
    #                 board_width=width, board_height=height
    #             )
    #             if neighbor_vertice is not None:
    #                 edge = (int(source_vertice), neighbor_vertice,)

    #                 edges_to_add.append(edge)

    #                 if edge not in directions_to_add:
    #                     directions_to_add[edge] = deque()

    #                 directions_to_add[edge].append(direction)

    #     self._graph.add_edge_list(edges_to_add) if edges_to_add else None

    #     for e in edges_to_add:
    #         e_descriptors = self._graph.edge(
    #             s = self._graph.vertex(e[0]),
    #             t = self._graph.vertex(e[1]),
    #             all_edges = True
    #         )

    #         for e_descriptor in e_descriptors:
    #             if len(directions_to_add[e]) > 0:
    #                 self._graph.ep.direction[e_descriptor] = directions_to_add[e][0]
#.........这里部分代码省略.........
开发者ID:tadamic,项目名称:sokoenginepy,代码行数:103,代码来源:board_graph_graphtool.py

示例4: SkeletonMatch

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import vertices [as 别名]

#.........这里部分代码省略.........
            print 'none in matched_pairs'
            return False


    def test_spatial_configuration(self, n1, n2, matched_pairs):
        """
        match spatial configuration
        """
        threhold = self.distorted_threhold
        #need test if can be inverse
        skel1_vectors = self.skel1.normalized_feature_verts[matched_pairs[-3:,0]] - self.skel1.normalized_feature_verts[n1]
        skel2_vectors = self.skel2.normalized_feature_verts[matched_pairs[-3:,1]] - self.skel2.normalized_feature_verts[n2]
        #skel1_vectors = self.skel1.feature_node[matched_pairs[-3:,0]] - self.skel1.feature_node[n1]
        #skel2_vectors = self.skel2.feature_node[matched_pairs[-3:,1]] - self.skel2.feature_node[n2]
        """
        for i in xrange(3):
            skel1_vectors[i] *= ( 1. / np.linalg.norm(skel1_vectors[i]) )
            skel2_vectors[i] *= ( 1. / np.linalg.norm(skel2_vectors[i]) )
        """

        a = np.dot(skel2_vectors, np.linalg.inv(skel1_vectors))
        u, s, v = np.linalg.svd(a)
        r = np.dot(u, v)
        if np.linalg.det(r) < 0:
            r *= -1.0

        res1 = np.linalg.norm(a-r)
        #print 'res1', res1,
        if res1 > threhold:
            return False
        else:
            a = np.dot(skel1_vectors, np.linalg.inv(skel2_vectors))
            u, s, v = np.linalg.svd(a)
            r = np.dot(u, v)
            if np.linalg.det(r) < 0:
                r *= -1.0

            res2 = np.linalg.norm(a-r)
            if res2 > threhold:
                return False
            #print 'res2', res2

        #return max(res1, res2) <= threhold
        return True


    def elector_vote(self):
        """
        use elector vote to find better correspondence
        """
        vote_matrix = np.zeros((len(self.skel1.feature_node_index), len(self.skel2.feature_node_index)), dtype=int)
        for v in self.vote_tree.vertices():
            if v.out_degree() < 2:
                pairs = self.node_pair[v]
                if len(pairs) >= 8:
                    temp_pairs = pairs.a.reshape(-1,2)
                    for pair in temp_pairs:
                        vote_matrix[pair[0], pair[1]] += 1

        node_num_skel1 = len(self.skel1.feature_node_index)
        node_num_skel2 = len(self.skel2.feature_node_index)
        self.vote_matrix = vote_matrix.copy()

        
        #print 'original vote_matrix\n', vote_matrix
        if np.max(vote_matrix) == 0:
            final_corres = np.array([])
        else:
            node_pair = np.unravel_index(vote_matrix.argmax(), vote_matrix.shape)
            vote_matrix[node_pair[0], :] = vote_matrix[:, node_pair[1]] = 0
            final_corres = np.array(node_pair)
            final_corres.shape = (-1,2)
            #print 'correspondence\n', final_corres
            #print 'vote_matrix\n', vote_matrix
            while len(final_corres) < min(node_num_skel1, node_num_skel2):
                junct1 = final_corres[final_corres[:,0] < len(self.skel1.junction_index), 0]
                junct2 = final_corres[final_corres[:,1] < len(self.skel2.junction_index), 1]
                node_pair = np.unravel_index(vote_matrix.argmax(), vote_matrix.shape)
                if node_pair[0] not in final_corres[:,0] and node_pair[1] not in final_corres[:,1]:
                    if len(junct1) < 3 or len(junct2) < 3:
                        print 'less than 3 junction matched'
                        final_corres = np.vstack((final_corres, node_pair))
                        vote_matrix[node_pair[0], :] = vote_matrix[:, node_pair[1]] = 0
                    else:
                        idx1 = np.argmin(self.skel1.path_to_junction[node_pair[0], junct1])
                        idx2 = np.argmin(self.skel2.path_to_junction[node_pair[1], junct2])
                        if [junct1[idx1], junct2[idx2]] in final_corres.tolist():
                            final_corres = np.vstack((final_corres, node_pair))
                            vote_matrix[node_pair[0], :] = vote_matrix[:, node_pair[1]] = 0
                            #print 'added correspondence\n', final_corres
                            #print 'vote_matrix\n', vote_matrix
                        else:
                            vote_matrix[node_pair[0], node_pair[1]] = 0
                else:
                    vote_matrix[node_pair[0], node_pair[1]] = 0

                if np.all(vote_matrix == 0):
                    break

        self.final_corres = final_corres
开发者ID:bo-wu,项目名称:skel_corres,代码行数:104,代码来源:skeleton_match.py

示例5: range

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import vertices [as 别名]
    # Flags to see which channels are currently in use
    for i in range(number_frequency_bands):
        flags_of_edges.append(1)
    # Flags to keep record of the extent of the usage of a particular channel in a link
    for i in range(number_frequency_bands):
        flags_of_edges.append(0)
    # Flags to fulfil the single point failure protection between those who share their primary paths
    for i in range(number_frequency_bands):
        flags_of_edges.append(1)
    edges_logger[str(e.source()) + " --> " + str(e.target())] = flags_of_edges
    edges_logger[str(e.target()) + " --> " + str(e.source())] = flags_of_edges
##### End of defining of the flags of edges #####

##### Generating the fixed paths #####
## Begin generation of fixed primary and backup paths ##
for src in g.vertices():
    for tgt in g.vertices():
        if not(src == tgt):
            rev_path = []
            tracer = tgt
            dist, pred = gt.dijkstra_search(g, src, g.ep.weight)
            g.vp.pred_tree = pred
            #print pred.a
            #print g.vp.pred_tree.a

            while g.vertex(tracer) != src:
                rev_path.append(tracer)
                #print(tracer)
                temp = tracer
                tracer = g.vp.pred_tree[g.vertex(tracer)]
                if temp == tracer:
开发者ID:sanjaythakur,项目名称:RoutingNWavelengthAssignment,代码行数:33,代码来源:RWA_Fixed_Static_Routing.py


注:本文中的graph_tool.Graph.vertices方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。