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


Python DiGraph.has_node方法代码示例

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


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

示例1: make_dependency_graph

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_node [as 别名]
def make_dependency_graph(tasks):
    dep_graph = DiGraph()

    #build the dependency graph in two steps. First add the nodes
    for task in tasks:
        assert not dep_graph.has_node(task), "Cannot add duplicate task: %s" % task
        dep_graph.add_node(task)

    #then add the edges.
    taskdeps = [(name, task.__pub_dependencies__)
                 for name, task in tasks.iteritems()
                 if hasattr(task, "__pub_dependencies__")]
    for task, deps in taskdeps:
        for dep in deps:
            dep_graph.add_edge(task, dep)

    cycles = list(simple_cycles(dep_graph))
    if cycles:
        raise DependencyCycle("Cycle in the dependency graph: %s %s" % (dep_graph, cycles))

    return dep_graph
开发者ID:llimllib,项目名称:pub,代码行数:23,代码来源:pub.py

示例2: VariableDictionary

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_node [as 别名]

#.........这里部分代码省略.........
                graph.remove_edge(*edge)
            self.addDependencies(graph, dependencies, name) # add all new dependencies
            var.value = result
            var.strvalue = strvalue
            self.dependencyGraph = graph
            var.strerror = None
        except KeyError as e:
            var.strerror = str(e)
        except Exception as e:
            errstr = "Unable to evaluate the expression '{0}' for variable '{1}'.".format(strvalue,name)
            logging.getLogger(__name__).warning( errstr )
            var.strerror = errstr
        return self.recalculateDependent(name)

    def setParentStrValue(self, name, strvalue):
        var = self[name]
        try:
            result, dependencies = self.expression.evaluate(strvalue, self.valueView, listDependencies=True )
            graph = self.dependencyGraph.copy()            # make a copy of the graph. In case of cyclic dependencies we do not want o leave any changes
            for edge in list(graph.in_edges([name])):      # remove all the inedges, dependencies from other variables might be gone
                graph.remove_edge(*edge)
            self.addDependencies(graph, dependencies, name) # add all new dependencies
            var.parentValue = result
            var.parentStrvalue = strvalue
            self.dependencyGraph = graph
            var.strerror = None
        except KeyError as e:
            var.strerror = str(e)
        except Exception as e:
            errstr = 'Unable to evaluate the expression \'{0}\' for variable \'{1}\'.'.format(strvalue,name)
            logging.getLogger(__name__).warning( errstr )
            var.strerror = errstr
        return self.recalculateDependent(name)

    def setValue(self, name, value):
        """update the variable value with value and recalculate as necessary.
        This is done using existing dependencies."""
        var = self[name]
        try:
            var.value = value
            var.strvalue = ""
            var.strerror = None
        except KeyError as e:
            var.strerror = str(e)
        return self.recalculateDependent(name, returnResult=True)
        
    def setParentValue(self, name, value):
        """update the variable value with value and recalculate as necessary.
        This is done using existing dependencies."""
        var = self[name]
        try:
            var.parentValue = value
            var.parentStrvalue = ""
            var.strerror = None
        except KeyError as e:
            var.strerror = str(e)
        return self.recalculateDependent(name, returnResult=True)

    def setEncodingIndex(self, index, encoding):
        self.at(index).encoding = None if encoding == 'None' else str(encoding)
    
    def setEnabledIndex(self, index, enabled):
        self.at(index).enabled = enabled
       
    def recalculateDependent(self, node, returnResult=False):
        if self.dependencyGraph.has_node(node):
            generator = dfs_preorder_nodes(self.dependencyGraph, node)
            next(generator )   # skip the first, that is us
            nodelist = list(generator)  # make a list, we need it twice 
            result = [ self.recalculateNode(node) for node in nodelist ]                
            return (nodelist, result) if returnResult else nodelist     # return which ones were re-calculated, so gui can be updated 
        return (list(), list()) if returnResult else list()

    def recalculateNode(self, node):
        if node in self:
            var = self[node]
            if hasattr(var, 'strvalue'):
                try:
                    var.value = self.expression.evaluate(var.strvalue, self.valueView)
                    var.strerror = None
                except (KeyError, ValueError) as e:
                    var.strerror = str(e)
                except Exception as e:
                    errstr = 'Unable to evaluate the expression \'{0}\'.'.format(var.strvalue)
                    logging.getLogger(__name__).warning( errstr )
                    var.strerror = errstr
            else:
                logging.getLogger(__name__).warning("variable {0} does not have strvalue. Value is {1}".format(var, var.value))
            return var.value
        return None
            
    def recalculateAll(self):
        g = self.dependencyGraph.reverse()
        for node, indegree in g.in_degree_iter():
            if indegree==0:
                for calcnode in dfs_postorder_nodes(g, node):
                    self.recalculateNode(calcnode)
                    
    def bareDictionaryCopy(self):
        return SequenceDict( self )
开发者ID:pyIonControl,项目名称:IonControl,代码行数:104,代码来源:VariableDictionary.py

示例3: CollectNodes

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_node [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

示例4: __init__

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_node [as 别名]
class Codebase:
    def __init__(self):
        self.counter = 0
        self._revisions = []
        with open(path.join(path.dirname(__file__), '..', 'App.java')) as java_file:
            parser = Parser()
            tree = parser.parse_file(java_file)
            initial_classes = tree.type_declarations
        self._inheritance_graph = DiGraph()
        self._method_call_graph = DiGraph()

        for c in initial_classes:
            self._inheritance_graph.add_node(c.name, {'class': c})
            for m in c.body:
                if isinstance(m, MethodDeclaration):
                    self._method_call_graph.add_node(m.name,
                                                  {'method': m,
                                                   'class_name': c.name,
                                                   'fitness': random()
                                                   })

    def get_class_name(self, method_name):
        return self._method_call_graph.node[method_name]['class_name']

    def size_of(self, method_name):
        return len(self._method_call_graph.node[method_name]['method'].body)

    def number_of_methods(self):
        return len(self._method_call_graph)

    def number_of_classes(self):
        return len(self._inheritance_graph)

    def has_method(self, method_name):
        return self._method_call_graph.has_node(method_name)

    def choose_random_method(self):
        """
        Choose a random method, weighted by its size
        :return: the method name
        """
        return sample([(method_name, len(data['method'].body) + 1)
                       for method_name, data in self._method_call_graph.nodes_iter(True)])

    def choose_random_class(self):
        """
        Choose a random class, weighted by its size
        :return: the class name
        """
        return sample([(class_name, len(data['class'].body) + 1)
                       for class_name, data in self._inheritance_graph.nodes_iter(data=True)])

    def least_fit_methods(self, n=1):
        """
        :return: the name of the method with smallest fitness value
        """
        return nsmallest(n, self._method_call_graph,
                         key=lambda method_name: self._method_call_graph.node[method_name]['fitness'])

    def choose_random_neighbor(self, method_name):
        neighbors = self._method_call_graph.neighbors(method_name)
        num_neighbors = len(neighbors)
        if num_neighbors > 0:
            return neighbors[floor(random() * num_neighbors)]
        else:
            return None

    def caller_names(self, method_name):
        """
        :param method_name:
        :return: caller method names iterator
        """
        return self._method_call_graph.predecessors_iter(method_name)

    def method_invocations(self, method_name):
        """
        Generator for MethodInvocation instances of method_name
        :param method_name:
        :return:
        """
        for caller_name in self._method_call_graph.predecessors_iter(method_name):
            caller = self._method_call_graph.node[caller_name]['method']
            for stmt in caller.body:
                if Codebase.is_invocation(stmt, method_name):
                    yield stmt.expression

    def create_method(self, class_name):
        """
        The created methods are static methods for now
        """
        klass = self._inheritance_graph.node[class_name]['class']
        method = MethodDeclaration(
            'method' + str(self.counter),
            body=[], modifiers=['static'])
        self.counter += 1
        klass.body.append(method)
        method_info = {'method': method, 'class_name': class_name, 'fitness': random()}
        self._method_call_graph.add_node(method.name, method_info)
        return 1, method.name

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

示例5: GroupGraph

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import has_node [as 别名]

#.........这里部分代码省略.........
                    if g not in audited_group_nodes:
                        audited_group_nodes.add(g)
                        for nhbr in self._graph.neighbors(g):  # Members of g.
                            if nhbr[0] == "Group":
                                queue.append(nhbr)
                groups = sorted(
                    [self._groups[group[1]] for group in audited_group_nodes], key=lambda g: g.name
                )
        return groups

    def get_group_details(self, groupname, show_permission=None, expose_aliases=True):
        # type: (str, Optional[str], bool) -> Dict[str, Any]
        """ Get users and permissions that belong to a group. Raise NoSuchGroup
        for missing groups. """

        with self.lock:
            data = {
                "group": {"name": groupname},
                "users": {},
                "groups": {},
                "subgroups": {},
                "permissions": [],
            }  # type: Dict[str, Any]
            if groupname in self._group_service_accounts:
                data["service_accounts"] = self._group_service_accounts[groupname]
            if groupname in self._groups and self._groups[groupname].email_address:
                data["group"]["contacts"] = {"email": self._groups[groupname].email_address}

            # This is calculated based on all the permissions that apply to this group. Since this
            # is a graph walk, we calculate it here when we're getting this data.
            group_audited = False

            group = ("Group", groupname)
            if not self._graph.has_node(group):
                raise NoSuchGroup("Group %s is either missing or disabled." % groupname)
            paths = single_source_shortest_path(self._graph, group)
            rpaths = single_source_shortest_path(self._rgraph, group)

            for member, path in iteritems(paths):
                if member == group:
                    continue
                member_type, member_name = member
                role = self._graph[group][path[1]]["role"]
                data[MEMBER_TYPE_MAP[member_type]][member_name] = {
                    "name": member_name,
                    "path": [elem[1] for elem in path],
                    "distance": len(path) - 1,
                    "role": role,
                    "rolename": GROUP_EDGE_ROLES[role],
                }

            for parent, path in iteritems(rpaths):
                if parent == group:
                    continue
                parent_type, parent_name = parent
                role = self._rgraph[path[-2]][parent]["role"]
                data["groups"][parent_name] = {
                    "name": parent_name,
                    "path": [elem[1] for elem in path],
                    "distance": len(path) - 1,
                    "role": role,
                    "rolename": GROUP_EDGE_ROLES[role],
                }
                for grant in self._group_grants.get(parent_name, []):
                    if show_permission is not None and grant.permission != show_permission:
                        continue
开发者ID:dropbox,项目名称:grouper,代码行数:70,代码来源:graph.py


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