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


Python DiGraph.has_edge方法代码示例

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


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

示例1: load

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_edge [as 别名]
    def load(self,fname, verbose=True, **kwargs):
        """
        Load a data file. The expected data format is three columns 
        (comma seperated by default) with source, target, flux.
        No header should be included and the node IDs have to run contuously 
        from 0 to Number_of_nodes-1.

        Parameters
        ----------
            fname : str
                Path to the file
            
            verbose : bool
                Print information about the data. True by Default
                
            kwargs : dict
                Default parameters can be changed here. Supported key words are
                    dtype     : float (default)
                    delimiter : ","   (default)
        
            return_graph : bool
                If True, the graph is returned (False by default).
                
        Returns:
        --------
            The graph is saved internally in self.graph.
                
        """
        delimiter = kwargs["delimiter"]      if "delimiter"      in kwargs.keys() else " "
        
        data = np.genfromtxt(fname, delimiter=delimiter, dtype=int, unpack=False)
        source, target = data[:,0], data[:,1]
        if data.shape[1] > 2:
            flux = data[:,2]
        else:
            flux = np.ones_like(source)
        nodes  = set(source) | set(target)
        self.nodes = len(nodes)
        lines  = len(flux)
        if set(range(self.nodes)) != nodes:
            new_node_ID = {old:new for new,old in enumerate(nodes)}
            map_new_node_ID = np.vectorize(new_node_ID.__getitem__)
            source = map_new_node_ID(source)
            target = map_new_node_ID(target)
            if verbose:
                print "\nThe node IDs have to run continuously from 0 to Number_of_nodes-1."
                print "Node IDs have been changed according to the requirement.\n-----------------------------------\n"
                
        
            print 'Lines: ',lines , ', Nodes: ', self.nodes
            print '-----------------------------------\nData Structure:\n\nsource,    target,    weight \n'
            for ii in range(7):            
                print "%i,       %i,       %1.2e" %(source[ii], target[ii], flux[ii])
            print '-----------------------------------\n'
        
        
        G = DiGraph()         # Empty, directed Graph
        G.add_nodes_from(range(self.nodes))
        for ii in xrange(lines):
            u, v, w = int(source[ii]), int(target[ii]), float(flux[ii])
            if u != v: # ignore self loops
                assert not G.has_edge(u,v), "Edge appeared twice - not supported"                    
                G.add_edge(u,v,weight=w)
            else:
                if verbose:
                    print "ignore self loop at node", u
        
        symmetric = True
        for s,t,w in G.edges(data=True):
            w1 = G[s][t]["weight"]
            try:
                w2 = G[t][s]["weight"]
            except KeyError:
                symmetric = False
                G.add_edge(t,s,weight=w1)
                w2 = w1
            if w1 != w2:
                symmetric = False
                G[s][t]["weight"] += G[t][s]["weight"]
                G[s][t]["weight"] /= 2
                G[t][s]["weight"]  = G[s][t]["weight"]
        if verbose:
            if not symmetric:
                print "The network has been symmetricised."
        
        
        ccs = strongly_connected_component_subgraphs(G)
        ccs = sorted(ccs, key=len, reverse=True)
        
        G_GSCC = ccs[0]
        if G_GSCC.number_of_nodes() != G.number_of_nodes():
            G = G_GSCC
            if verbose:
                print "\n--------------------------------------------------------------------------"
                print "The network has been restricted to the giant strongly connected component."
        self.nodes = G.number_of_nodes()
        
        
        
        
#.........这里部分代码省略.........
开发者ID:andreaskoher,项目名称:effective_distance,代码行数:103,代码来源:effective_distance.py

示例2: __init__

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_edge [as 别名]
class TransformTree:
    '''
    A feature complete if not particularly optimized implementation of a transform graph.
    
    Few allowances are made for thread safety, caching, or enforcing graph structure.
    '''

    def __init__(self, base_frame='world'):
        self._transforms = DiGraph()
        self._parents    = {}
        self._paths      = {}
        self._is_changed = False
        self.base_frame  = base_frame

    def update(self, 
               frame_to,
               frame_from = None,
               **kwargs):
        '''
        Update a transform in the tree.

        Arguments
        ---------
        frame_from: hashable object, usually a string (eg 'world').
                    If left as None it will be set to self.base_frame
        frame_to:   hashable object, usually a string (eg 'mesh_0')
        
        Additional kwargs (can be used in combinations)
        --------- 
        matrix:      (4,4) array 
        quaternion:  (4) quatenion
        axis:        (3) array
        angle:       float, radians
        translation: (3) array
        '''
        if frame_from is None:
            frame_from = self.base_frame

        matrix = np.eye(4)
        if 'matrix' in kwargs:
            # a matrix takes precedence over other options
            matrix = kwargs['matrix']
        elif 'quaternion' in kwargs:
            matrix = quaternion_matrix(kwargs['quaternion'])
        elif ('axis' in kwargs) and ('angle' in kwargs):
            matrix = rotation_matrix(kwargs['angle'],
                                     kwargs['axis'])
        else: 
            raise ValueError('Couldn\'t update transform!')

        if 'translation' in kwargs:
            # translation can be used in conjunction with any of the methods of 
            # specifying transforms. In the case a matrix and translation are passed,
            # we add the translations together rather than picking one. 
            matrix[0:3,3] += kwargs['translation']

        if self._transforms.has_edge(frame_from, frame_to):
            self._transforms.edge[frame_from][frame_to]['matrix'] = matrix
            self._transforms.edge[frame_from][frame_to]['time']   = time.time()
        else:
            # since the connectivity has changed, throw out previously computed
            # paths through the transform graph so queries compute new shortest paths
            # we could only throw out transforms that are connected to the new edge,
            # but this is less bookeeping at the expensive of being slower. 
            self._paths = {}
            self._transforms.add_edge(frame_from, 
                                      frame_to, 
                                      matrix = matrix, 
                                      time   = time.time())
        self._is_changed = True

    def get(self,
            frame_to,
            frame_from = None):
        '''
        Get the transform from one frame to another, assuming they are connected
        in the transform tree. 

        If the frames are not connected a NetworkXNoPath error will be raised.

        Arguments
        ---------
        frame_from: hashable object, usually a string (eg 'world').
                    If left as None it will be set to self.base_frame
        frame_to:   hashable object, usually a string (eg 'mesh_0')

        Returns
        ---------
        transform:  (4,4) homogenous transformation matrix
        '''
        if frame_from is None:
            frame_from = self.base_frame

        transform = np.eye(4)
        path, inverted = self._get_path(frame_from, frame_to)
        for i in range(len(path) - 1):
            matrix = self._transforms.get_edge_data(path[i], 
                                                    path[i+1])['matrix']
            transform = np.dot(transform, matrix)
        if inverted:
#.........这里部分代码省略.........
开发者ID:MiaoLi,项目名称:trimesh,代码行数:103,代码来源:transform_tree.py

示例3: CollectNodes

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_edge [as 别名]
class CollectNodes(Visitor):

    def __init__(self, call_deps=False):
        self.graph = DiGraph()
        self.modified = set()
        self.used = set()
        self.undefined = set()
        self.sources = set()
        self.targets = set()

        self.context_names = set()

        self.call_deps = call_deps

    visitDefault = collect_

    def visitName(self, node):
        if isinstance(node.ctx, _ast.Store):
            self.modified.add(node.id)

        elif isinstance(node.ctx, _ast.Load):
            self.used.update(node.id)

        if not self.graph.has_node(node.id):
            self.graph.add_node(node.id)
            if isinstance(node.ctx, _ast.Load):
                self.undefined.add(node.id)

        for ctx_var in self.context_names:
            if not self.graph.has_edge(node.id, ctx_var):
                self.graph.add_edge(node.id, ctx_var)

        return {node.id}

    def visitalias(self, node):
        name = node.asname if node.asname else node.name

        if '.' in name:
            name = name.split('.', 1)[0]

        if not self.graph.has_node(name):
            self.graph.add_node(name)

        return {name}

    def visitCall(self, node):
        left = self.visit(node.func)

        right = set()
        for attr in ('args', 'keywords'):
            for child in getattr(node, attr):
                if child:
                    right.update(self.visit(child))

        for attr in ('starargs', 'kwargs'):
            child = getattr(node, attr)
            if child:
                right.update(self.visit(child))

        for src in left | right:
            if not self.graph.has_node(src):
                self.undefined.add(src)

        if self.call_deps:
            add_edges(self.graph, left, right)
            add_edges(self.graph, right, left)

        right.update(left)
        return right

    def visitSubscript(self, node):
        if isinstance(node.ctx, _ast.Load):
            return collect_(self, node)
        else:
            sources = self.visit(node.slice)
            targets = self.visit(node.value)
            self.modified.update(targets)
            add_edges(self.graph, targets, sources)
            return targets
        
    def handle_generators(self, generators):
        defined = set()
        required = set()
        for generator in generators:
            get_symbols(generator, _ast.Load)
            required.update(get_symbols(generator, _ast.Load) - defined)
            defined.update(get_symbols(generator, _ast.Store))
            
        return defined, required
    
    def visitListComp(self, node):

        defined, required = self.handle_generators(node.generators)
        required.update(get_symbols(node.elt, _ast.Load) - defined)

        for symbol in required:
            if not self.graph.has_node(symbol):
                self.graph.add_node(symbol)
                self.undefined.add(symbol)

#.........这里部分代码省略.........
开发者ID:Bhushan1002,项目名称:SFrame,代码行数:103,代码来源:graph_visitor.py


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