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


Python toposort.toposort_flatten函数代码示例

本文整理汇总了Python中toposort.toposort_flatten函数的典型用法代码示例。如果您正苦于以下问题:Python toposort_flatten函数的具体用法?Python toposort_flatten怎么用?Python toposort_flatten使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: testAlreadyPrioritized

 def testAlreadyPrioritized(self):
     graph = {1: set([2]),
              2: set()}
     expected = deepcopy(graph)
     topo_prioritize(2, graph)
     self.assertEquals(graph, expected)
     sorted = toposort_flatten(graph)
     self.assertEqual(toposort_flatten(graph), [2, 1])
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:8,代码来源:testTopoPrioritize.py

示例2: testAvoidCircularReference

 def testAvoidCircularReference(self):
     graph = {1: set(),
              2: set([1])}
     expected = deepcopy(graph)
     topo_prioritize(2, graph)
     self.assertEquals(graph, expected)
     sorted = toposort_flatten(graph)
     self.assertEqual(toposort_flatten(graph), [1, 2])
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:8,代码来源:testTopoPrioritize.py

示例3: testSimple

 def testSimple(self):
     graph = {1: set(),
              2: set()}
     expected = deepcopy(graph)
     expected[1].add(2)
     topo_prioritize(2, graph)
     self.assertEquals(graph, expected)
     sorted = toposort_flatten(graph)
     self.assertEqual(toposort_flatten(graph), [2, 1])
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:9,代码来源:testTopoPrioritize.py

示例4: order_modules

 def order_modules(self):
     runorder = None
     try:
         dependencies = self.collect_dependencies()
         runorder = toposort_flatten(dependencies)
         self.compute_reachability(dependencies)
     except ValueError: # cycle, try to break it then
         # if there's still a cycle, we cannot run the first cycle
         logger.info('Cycle in module dependencies, trying to drop optional fields')
         dependencies = self.collect_dependencies(only_required=True)
         runorder = toposort_flatten(dependencies)
         self.compute_reachability(dependencies)
     return runorder
开发者ID:jdfekete,项目名称:progressivis,代码行数:13,代码来源:scheduler.py

示例5: expand

    def expand(self, states):
        seen = set()
        depends = defaultdict(list)
        queue = deque()
        for state in states:
            queue.append(state)
            seen.add(state)
        while len(queue):
            state = queue.popleft()
            for arc in self.get_arcs(state, EPSILON):
                depends[arc[1]].append((arc[0], arc[3]))
                if arc[1] in seen:
                    continue
                queue.append(arc[1])
                seen.add(arc[1])

        depends_for_toposort = {key: {state for state, weight in value}
                                for key, value in depends.items()}
        order = toposort_flatten(depends_for_toposort)

        next_states = states
        for next_state in order:
            next_states[next_state] = self.combine_weights(
                *([next_states.get(next_state)] +
                  [next_states[prev_state] + weight
                   for prev_state, weight in depends[next_state]]))

        return next_states
开发者ID:ZhangAustin,项目名称:attention-lvcsr,代码行数:28,代码来源:ops.py

示例6: get_dependency_map

def get_dependency_map(
  depman: 'DependencyManager', mods: LilacMods,
) -> Dict[str, Set['Dependency']]:
  map: Dict[str, Set['Dependency']] = defaultdict(set)
  shallow_map: Dict[str, Set[str]] = defaultdict(set)
  rmap: Dict[str, Set[str]] = defaultdict(set)

  for name, mod in mods.items():
    depends = getattr(mod, 'repo_depends', ())

    ds = [depman.get(d) for d in depends]
    if ds:
      for d in ds:
        shallow_map[name].add(d.pkgname)
        rmap[d.pkgname].add(name)
      map[name].update(ds)

  dep_order = toposort_flatten(shallow_map)
  for name in dep_order:
    if name in rmap:
      deps = map[name]
      dependers = rmap[name]
      for dd in dependers:
        map[dd].update(deps)

  return map
开发者ID:archlinuxcn,项目名称:lilac,代码行数:26,代码来源:packages.py

示例7: ordered_task_instances_list

    def ordered_task_instances_list(self):
        """
        Start from a root task, and read task dependencies recursively.
        """
        # NOTE consider Luiti modifies Luigi, same task instances maybe not unique. TODO Fix it
        def func(dep_dict, _curr_task):
            """ Generate a a dependencies graph. """
            required_task_instances = _curr_task.requires()

            # 1. clean dep normal tasks as a list
            if not isinstance(required_task_instances, list):
                required_task_instances = [required_task_instances]
            dep_dict[_curr_task] = filter(lambda t1: bool(t1) and (not isinstance(t1, RootTask)), required_task_instances)

            # 2. selected undone tasks
            if self.check_output_recursive:
                dep_dict[_curr_task] = filter(lambda t1: not t1.output().exists(), dep_dict[_curr_task])
            dep_dict[_curr_task] = set(dep_dict[_curr_task])

            # 3. recursive
            for t1 in dep_dict[_curr_task]:
                func(dep_dict, t1)

            return dep_dict

        # 1. generate a dep dict
        task_instances_dep_dict = func(dict(), self.curr_task_intance)

        # 2. sort the DAG.
        from toposort import toposort_flatten
        ordered_task_instances_list = toposort_flatten(task_instances_dep_dict)

        return ordered_task_instances_list
开发者ID:Luiti,项目名称:luiti,代码行数:33,代码来源:sensor_schedule.py

示例8: render_schema

    def render_schema(self, **kwargs):
        "return full SQL schema built rendering indexed resources"

        # construct templating environment
        tplEnv = Environment(line_statement_prefix='--#')

        # build resource index
        rsrIdx = self.build_index()

        # iterates resource in 'topological' sorted order
        buf = []
        for rsr in toposort_flatten(rsrIdx):

            # process resource template if any
            if rsr.tplstr:

                # add source informations to tplstr
                tplstr = self._fileHead % (self.get_rpath(rsr), rsr.tplstr)

                # compile template
                tpl = tplEnv.from_string(tplstr)

                # prepare rendering context
                ctx = {}
                ctx.update(rsr.tpldefaults)
                ctx.update(kwargs)

                # render template
                buf.append(tpl.render(ctx))


        return u"\n".join(buf)
开发者ID:amvtek,项目名称:SqlMake,代码行数:32,代码来源:indexer.py

示例9: mount_lowerdirs

    def mount_lowerdirs(self):
        # First, build a dependency graph in order to avoid duplicate entries
        dependencies = {}

        def dependency_path(dep):
            if 'image' in dep:
                return Image.download(dep['image'], dep['version'])
            if ':' in dep['imageName']:  # It's an image
                return Image.download(dep['imageName'])
            else:  # It's a container
                container = self.__class__(dep['imageName'])
                path = dep.get('path', str((container.path / 'overlay.fs').resolve()))
                return os.path.join(dep['imageName'], path)

        pending_deps = set(map(dependency_path, self.dependencies))
        while len(pending_deps) > 0:
            path = pending_deps.pop()
            if isinstance(path, Image):
                path.extract()
                prev_layer = str(path.layers[-1].fs_path)
                dependencies[prev_layer] = set()
                for layer in reversed(path.layers[:-1]):
                    dependencies[prev_layer] = {str(layer.fs_path)}
                    prev_layer = str(layer.fs_path)
            else:
                name = path.split('/')[-2]
                if name not in dependencies:
                    dependencies[path] = set(map(dependency_path, self.__class__(name).dependencies))
                    pending_deps |= dependencies[path]

        # Then sort it topologically. The list is reversed, because overlayfs
        # will check the mounts in order they are given, so the base fs has to
        # be the last one.
        dependencies = reversed(list(toposort_flatten(dependencies)))
        return (os.path.join(self.metadata_dir, dep) for dep in dependencies)
开发者ID:pixers,项目名称:kostka,代码行数:35,代码来源:mount.py

示例10: refresh_provisioning_playbook

def refresh_provisioning_playbook(arg_vars, project_root):
  cluster_id = arg_vars['cluster_id']
  tpl = util.provisioning_template()
  path = util.machine_profiles_path(project_root, cluster_id)
  profile_files = [f for f in listdir(path) if isfile(join(path, f))]

  services = {}
  service_graph = {}
  profiles = []
  for f in profile_files:
    with open((path + "/"  + f), "r") as handle:
      content = yaml.load(handle)
      profiles.append(content['profile_id'])
      for s in content.get('machine_services', []):
        rets = services.get(s, [])
        rets.append(content['profile_id'])
        services[s] = rets

  for s in services.keys():
    with open((project_root + "/ansible/roles/" + s + "/defaults/main.yml"), "r") as text_file:
      content = yaml.load(text_file)
      service_graph[s] = set(content.get('service_dependencies', {}))

  service_seq = toposort_flatten(service_graph)
  with open(util.provisioning_file(project_root, cluster_id), "w") as text_file:
    text_file.write(tpl.render(cluster_id = cluster_id,
                               services = services,
                               profiles = profiles,
                               service_seq = service_seq,
                               service_graph = service_graph))
开发者ID:drewverlee,项目名称:engraver,代码行数:30,代码来源:ansible.py

示例11: find_joins_for_tables

def find_joins_for_tables(joins, base_table, required_tables):
    """
    Given a set of tables required for a slicer query, this function finds the joins required for the query and
    sorts them topologically.

    :return:
        A list of joins in the order that they must be joined to the query.
    :raises:
        MissingTableJoinException - If a table is required but there is no join for that table
        CircularJoinsException - If there is a circular dependency between two or more joins
    """
    dependencies = defaultdict(set)
    slicer_joins = {join.table: join
                    for join in joins}

    while required_tables:
        table = required_tables.pop()

        if table not in slicer_joins:
            raise MissingTableJoinException('Could not find a join for table {}'
                                            .format(str(table)))

        join = slicer_joins[table]
        tables_required_for_join = set(join.criterion.tables_) - {base_table, join.table}

        dependencies[join] |= {slicer_joins[table]
                               for table in tables_required_for_join}
        required_tables += tables_required_for_join - {d.table for d in dependencies}

    try:
        return toposort_flatten(dependencies, sort=True)
    except CircularDependencyError as e:
        raise CircularJoinsException(str(e))
开发者ID:kayak,项目名称:fireant,代码行数:33,代码来源:finders.py

示例12: toposort_flatten_checking

def toposort_flatten_checking(d, sort=False):
    '''Essentially just toposort_flatten, but with checking for
       self-referential dependencies and defaulting to sort=False
       to preserves order when possible'''
    for k, v in d.iteritems():
        assert k not in v, 'Self-referencing dependency: {}'.format(k)
    return toposort.toposort_flatten(d, sort=sort)
开发者ID:davidmashburn,项目名称:metrics_manager,代码行数:7,代码来源:argument_handling.py

示例13: step

 def step(self, name, deps, f, *args, **kwargs):
     """
     Function to add a step to the computational graph.
       deps [String]: a list of nodes in the graph that the function depends on
       f [Function]: node to execute
       args [List]: list of arguments to be passed into the function
     """
     # create a new stair for this function
     stair = Stair(name, deps, f,  *args, **kwargs)
     # update our computational graph with this stair
     self.stairs[name] = stair
     # check that we have the dependencies in the, and assume any
     # that aren't are inputs
     for dep in deps:
         # first check that the variable isn't already in the graph
         if dep in self.stairs: continue
         # create an input stair and enter it into our graph
         input_stair = Stair(dep, [], lambda v: v)
         self.stairs[dep] = input_stair
         self.graph[input_stair] = set([])
     # add our dependencie to the graph
     self.graph[stair] = set([self.stairs[dep] for dep in deps])
     # ensure that our new graph compiles
     self.slist = toposort_flatten(self.graph)
     # return self for chaining
     return self
开发者ID:jbarrow,项目名称:capstone,代码行数:26,代码来源:stairway.py

示例14: recreateSequence

def recreateSequence(darcs):
    from toposort import toposort_flatten
    
    dependFrom={}
    for u,v in darcs:
        dependFrom[v]=set([u])

    return toposort_flatten(dependFrom)
开发者ID:pizzonia,项目名称:sdn-ci,代码行数:8,代码来源:ver_2.py

示例15: resolveDependencies

 def resolveDependencies(self):
     import toposort
     #build dependancy graph
                 
     dg = self.dependancyGraph()
     
     #solve the dependency tree        
     return toposort.toposort_flatten(dg)
开发者ID:RuralCat,项目名称:CLipPYME,代码行数:8,代码来源:filters.py


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