• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python compat.iteritems函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: compress

 def compress(cls, operators):
     sets = OrderedDict()
     incs = OrderedDict()
     rval = []
     for op in operators:
         if isinstance(op, cls):
             if op.as_update:
                 rval.append(op)
             else:
                 assert op.sets or op.incs
                 if op.sets:
                     sets.setdefault(op.sets[0], []).append(op)
                 if op.incs:
                     incs.setdefault(op.incs[0], []).append(op)
         else:
             rval.append(op)
     done = set()
     for view, set_ops in iteritems(sets):
         set_op, = set_ops
         done.add(set_op)
         for inc_op in incs.get(view, []):
             set_op.As.extend(inc_op.As)
             set_op.Xs.extend(inc_op.Xs)
             done.add(inc_op)
         rval.append(set_op)
     for view, inc_ops in iteritems(incs):
         for inc_op in inc_ops:
             if inc_op not in done:
                 rval.append(inc_op)
     return rval
开发者ID:MarcoSaku,项目名称:Spiking-C3D,代码行数:30,代码来源:sim_npy.py


示例2: compress

    def compress(cls, operators):
        sets = OrderedDict()
        incs = OrderedDict()
        rval = []
        for op in operators:
            if isinstance(op, cls):
                if op.sets:
                    assert len(op.sets) == 1 and len(op.incs) == 0
                    sets.setdefault(op.sets[0], []).append(op)
                else:
                    assert len(op.incs) == 1 and len(op.sets) == 0
                    incs.setdefault(op.incs[0], []).append(op)
            else:
                rval.append(op)

        # combine incs into sets if on same view
        for view, set_ops in iteritems(sets):
            set_op, = set_ops
            inc_ops = incs.get(view, [])
            for inc_op in inc_ops[:]:
                set_op.As.extend(inc_op.As)
                set_op.Xs.extend(inc_op.Xs)
                inc_ops.remove(inc_op)
            rval.append(set_op)

        # combine remaining incs if on same view
        for view, inc_ops in iteritems(incs):
            if len(inc_ops) > 0:
                inc_op0 = inc_ops[0]
                for inc_op in inc_ops[1:]:
                    inc_op0.As.extend(inc_op.As)
                    inc_op0.Xs.extend(inc_op.Xs)
                rval.append(inc_op0)

        return rval
开发者ID:nengo,项目名称:nengo_ocl,代码行数:35,代码来源:operators.py


示例3: __setattr__

    def __setattr__(self, key, value):
        """A setattr that handles Modules being added specially.

        This is so that we can use the variable name for the Module as
        the name that all of the SPA system will use to access that module.
        """
        if hasattr(self, key) and isinstance(getattr(self, key), Module):
            raise SpaModuleError("Cannot re-assign module-attribute %s to %s. "
                                 "SPA module-attributes can only be assigned "
                                 "once." % (key, value))
        super(SPA, self).__setattr__(key, value)
        if isinstance(value, Module):
            if value.label is None:
                value.label = key
            self._modules[key] = value
            for k, (obj, v) in iteritems(value.inputs):
                if type(v) == int:
                    value.inputs[k] = (obj, self.get_default_vocab(v))
                self.config[obj].vocab = value.inputs[k][1]
            for k, (obj, v) in iteritems(value.outputs):
                if type(v) == int:
                    value.outputs[k] = (obj, self.get_default_vocab(v))
                self.config[obj].vocab = value.outputs[k][1]

            value.on_add(self)
开发者ID:JolyZhang,项目名称:nengo,代码行数:25,代码来源:spa.py


示例4: parse_ges

def parse_ges(ges_path, speaker=None, ignore_f0=True):
    bridge = VTL(speaker)

    xml = etree.parse(ges_path)
    labels = bridge.gesture_labels()
    if ignore_f0:
        labels.remove('f0')
    gs = GestureScore(labels)
    for element in xml.iter():
        attr = element.attrib
        if element.tag == "gesture_sequence":
            seq = GestureSequence(**attr)
            if ignore_f0 and seq.type.startswith('f0'):
                continue
            gs.sequences.append(seq)
        elif element.tag == "gesture":
            gest_attr = {}
            gest_attr['neutral'] = bool(int(attr.pop('neutral')))
            gest_attr['value'] = attr.pop('value')
            if seq.numerical:
                gest_attr['value'] = float(gest_attr['value'])
            gest_attr.update({key: float(val) for key, val in iteritems(attr)})
            gest = Gesture(**gest_attr)
            seq.gestures.append(gest)
    return gs
开发者ID:tbekolay,项目名称:phd,代码行数:25,代码来源:__init__.py


示例5: on_add

    def on_add(self, spa):
        Module.on_add(self, spa)
        self.spa = spa

        with spa:
            # connect basal ganglia to thalamus
            nengo.Connection(self.bg.output, self.actions.input,
                             synapse=self.synapse_bg)

        # implement the various effects
        for i, action in enumerate(self.bg.actions.actions):
            for name, effects in iteritems(action.effect.effect):
                for effect in effects.expression.items:
                    if isinstance(effect, (int, float)):
                        effect = Symbol('%g' % effect)
                    if isinstance(effect, Symbol):
                        self.add_direct_effect(i, name, effect.symbol)
                    elif isinstance(effect, Source):
                        self.add_route_effect(i, name, effect.name,
                                              effect.transform.symbol,
                                              effect.inverted)
                    elif isinstance(effect, Convolution):
                        self.add_conv_effect(i, name, effect)
                    else:
                        raise NotImplementedError(
                            "Subexpression '%s' from action '%s' is not "
                            "supported by the Thalamus." % (effect, action))
开发者ID:goaaron,项目名称:blouw-etal-2015,代码行数:27,代码来源:thalamus.py


示例6: add_derivative

 def add_derivative(self, klass="IntermediateDeriv", **kwargs):
     deriv = globals()["%sParams" % klass]()
     for k, v in iteritems(kwargs):
         setattr(deriv, k, v)
     self.derivatives.append(deriv)
     self.mfcc.n_derivatives += 1
     return deriv
开发者ID:tbekolay,项目名称:phd,代码行数:7,代码来源:sermo.py


示例7: get_module_inputs

 def get_module_inputs(self):
     for name, module in iteritems(self._modules):
         for input in module.inputs:
             if input == 'default':
                 yield name
             else:
                 yield '%s_%s' % (name, input)
开发者ID:SampsonKwan,项目名称:nengo,代码行数:7,代码来源:spa.py


示例8: on_add

    def on_add(self, spa):
        Module.on_add(self, spa)
        self.spa = spa

        # parse the provided class and match it up with the spa model
        self.actions.process(spa)
        for action in self.actions.actions:
            if action.condition is not None:
                raise NotImplementedError("Cortical actions do not support "
                                          "conditional expressions: %s." %
                                          action.condition)
            for name, effects in iteritems(action.effect.effect):
                for effect in effects.expression.items:
                    if isinstance(effect, Symbol):
                        self.add_direct_effect(name, effect.symbol)
                    elif isinstance(effect, Source):
                        self.add_route_effect(name, effect.name,
                                              effect.transform.symbol,
                                              effect.inverted)
                    elif isinstance(effect, Convolution):
                        self.add_conv_effect(name, effect)
                    else:
                        raise NotImplementedError(
                            "Subexpression '%s' from action '%s' is not "
                            "supported by the cortex." % (effect, action))
开发者ID:4n6strider,项目名称:nengo,代码行数:25,代码来源:cortical.py


示例9: probe_helper

    def probe_helper(net, recursive, probe_options):
        with net:
            for obj_type, obj_list in iteritems(net.objects):

                # recursively probe subnetworks if required
                if obj_type is Network and recursive:
                    for subnet in obj_list:
                        probe_helper(subnet, recursive=recursive,
                                     probe_options=probe_options)

                # probe all probeable objects
                elif probe_options is None:
                    for obj in obj_list:
                        if hasattr(obj, 'probeable') and len(
                                obj.probeable) > 0:
                            probes[obj] = {}
                            for probeable in obj.probeable:
                                probes[obj][probeable] = Probe(
                                    obj, probeable, **probe_args)

                # probe specified objects only
                elif obj_type in probe_options:
                    for obj in obj_list:
                        if not (hasattr(obj, 'probeable')
                                and len(obj.probeable) > 0):
                            raise ValueError("'%s' is not probeable" % obj)
                        probes[obj] = {}
                        for attr in probe_options[obj_type]:
                            if attr not in obj.probeable:
                                raise ValueError(
                                    "'%s' is not probeable for '%s'" %
                                    (obj, attr))
                            probes[obj][
                                attr] = Probe(obj, attr, **probe_args)
开发者ID:Ocode,项目名称:nengo,代码行数:34,代码来源:probe.py


示例10: get_module_outputs

 def get_module_outputs(self):
     for name, module in iteritems(self._modules):
         for output in module.outputs:
             if output == 'default':
                 yield name
             else:
                 yield '%s_%s' % (name, output)
开发者ID:SampsonKwan,项目名称:nengo,代码行数:7,代码来源:spa.py


示例11: reset

    def reset(self, seed=None):
        if self.closed:
            raise SimulatorClosed("Cannot reset closed Simulator.")

        if seed is not None:
            raise NotImplementedError("Seed changing not implemented")

        # reset signals
        for base in self.all_bases:
            # TODO: copy all data on at once
            if not base.readonly:
                self.all_data[self.sidx[base]] = base.initial_value

        for clra, ra in iteritems(self._raggedarrays_to_reset):
            # TODO: copy all data on at once
            for i in range(len(clra)):
                clra[i] = ra[i]

        # clear probe data
        if self._cl_probe_plan is not None:
            self._cl_probe_plan.cl_bufpositions.fill(0)

            for probe in self.model.probes:
                del self._probe_outputs[probe][:]

        self._reset_rng()
        self._reset_cl_rngs()
        self._probe_step_time()
开发者ID:shaunren,项目名称:nengo_ocl,代码行数:28,代码来源:simulator.py


示例12: save_network

 def save_network(self):
     state = []
     for obj, layout in iteritems(self.pos):
         state.append({
             'uid': self.net_graph.page.get_uid(obj),
             'pos': self.net_graph.page.config[obj].pos,
             'size': self.net_graph.page.config[obj].size,
             'obj': obj,
         })
     return state
开发者ID:jasusc,项目名称:nengo_gui,代码行数:10,代码来源:action.py


示例13: process

    def process(self, spa):
        """Parse the actions and generate the list of Action objects."""
        self.actions = []

        sources = list(spa.get_module_outputs())
        sinks = list(spa.get_module_inputs())

        for action in self.args:
            self.actions.append(Action(sources, sinks, action, name=None))
        for name, action in iteritems(self.kwargs):
            self.actions.append(Action(sources, sinks, action, name=name))
开发者ID:LittileBee,项目名称:nengo,代码行数:11,代码来源:actions.py


示例14: __setattr__

    def __setattr__(self, key, value):
        """A setattr that handles Modules being added specially.

        This is so that we can use the variable name for the Module as
        the name that all of the SPA system will use to access that module.
        """
        super(SPA, self).__setattr__(key, value)
        if isinstance(value, Module):
            value.label = key
            self._modules[value.label] = value
            for k, (obj, v) in iteritems(value.inputs):
                if type(v) == int:
                    value.inputs[k] = (obj, self.get_default_vocab(v))
                obj.vocab = value.inputs[k][1]
            for k, (obj, v) in iteritems(value.outputs):
                if type(v) == int:
                    value.outputs[k] = (obj, self.get_default_vocab(v))
                obj.vocab = value.outputs[k][1]

            value.on_add(self)
开发者ID:bopo,项目名称:nengo,代码行数:20,代码来源:spa.py


示例15: save_network

 def save_network(self):
     state = []
     for obj, layout in iteritems(self.pos):
         state.append(
             {
                 "uid": self.net_graph.page.get_uid(obj),
                 "pos": self.net_graph.page.config[obj].pos,
                 "size": self.net_graph.page.config[obj].size,
                 "obj": obj,
             }
         )
     return state
开发者ID:rsimmons1,项目名称:nengo_gui,代码行数:12,代码来源:user_action.py


示例16: act_feedforward_layout

    def act_feedforward_layout(self):
        for obj, layout in iteritems(self.pos):
            obj_cfg = self.net_graph.page.config[obj]
            obj_cfg.pos = (layout["y"] / self.scale - self.x, layout["x"] / self.scale - self.y)
            obj_cfg.size = (layout["h"] / 2 / self.scale, layout["w"] / 2 / self.scale)

            obj_uid = self.net_graph.page.get_uid(obj)

            self.send("pos_size", uid=obj_uid, pos=obj_cfg.pos, size=obj_cfg.size)

        self.net_graph.page.config[self.network].has_layout = True
        self.net_graph.modified_config()
开发者ID:rsimmons1,项目名称:nengo_gui,代码行数:12,代码来源:user_action.py


示例17: learning_rule

 def learning_rule(self):
     if self.learning_rule_type is not None and self._learning_rule is None:
         types = self.learning_rule_type
         if isinstance(types, dict):
             self._learning_rule = types.__class__()  # dict of same type
             for k, v in iteritems(types):
                 self._learning_rule[k] = LearningRule(self, v)
         elif is_iterable(types):
             self._learning_rule = [LearningRule(self, v) for v in types]
         elif isinstance(types, LearningRuleType):
             self._learning_rule = LearningRule(self, types)
         else:
             raise ValueError("Invalid type for `learning_rule_type`: %s"
                              % (types.__class__.__name__))
     return self._learning_rule
开发者ID:LittileBee,项目名称:nengo,代码行数:15,代码来源:connection.py


示例18: toposort

def toposort(edges):
    """Topological sort algorithm by Kahn[1]

    Complexity is O(nodes + vertices).

    Parameters
    ----------
    edges : dict
        Dict of the form {a: {b, c}} where b and c depend on a

    Returns
    -------
    An ordered list of nodes that satisfy the dependencies of ``edges``

    Example
    -------

    >>> toposort({1: {2, 3}, 2: (3,)})
    [1, 2, 3]

    Notes
    -----

    Closely follows the wikipedia page [2]

    [1] Kahn, Arthur B. (1962), "Topological sorting of large networks",
    Communications of the ACM
    [2] http://en.wikipedia.org/wiki/Toposort#Algorithms
    """
    incoming_edges = reverse_edges(edges)
    incoming_edges = dict((k, set(val))
                          for k, val in iteritems(incoming_edges))
    vertices = set((v for v in edges if v not in incoming_edges))
    ordered = []

    while vertices:
        n = vertices.pop()
        ordered.append(n)
        for m in edges.get(n, ()):
            assert n in incoming_edges[m]
            incoming_edges[m].remove(n)
            if not incoming_edges[m]:
                vertices.add(m)
    if any(incoming_edges.get(v, None) for v in edges):
        raise ValueError("Input graph has cycles. This usually occurs because "
                         "too many connections have no synapses. Try setting "
                         "more synapses to '0' instead of 'None'.")
    return ordered
开发者ID:Ocode,项目名称:nengo,代码行数:48,代码来源:graphs.py


示例19: groupby

def groupby(objects, key, hashable=None, force_list=True):
    """Group objects based on a key.

    Unlike `itertools.groupby`, this function does not require the input
    to be sorted.

    Parameters
    ----------
    objects : Iterable
        The objects to be grouped.
    key : callable
        The key function by which to group the objects. If
        `key(obj1) == key(obj2)` then `obj1` and `obj2` are in the same group,
        otherwise they are not.
    hashable : boolean (optional)
        Whether to use the key's hash to determine equality. By default, this
        will be determined by calling `key` on the first item in `objects`, and
        if it is hashable, the hash will be used. Using a hash is faster, but
        not possible for all keys.
    force_list : boolean (optional)
        Whether to force the returned `key_groups` iterator, as well as the
        `group` iterator in each `(key, group)` pair, to be lists.

    Returns
    -------
    keygroups : iterable
        An iterable of `(key, group)` pairs, where `key` is the key used for
        grouping, and `group` is an iterable of the items in the group. The
        nature of the iterables depends on the value of `force_list`.
    """
    if hashable is None:
        # get first item without advancing iterator, and see if key is hashable
        objects, objects2 = itertools.tee(iter(objects))
        item0 = next(objects2)
        hashable = isinstance(key(item0), collections.Hashable)

    if hashable:
        # use a dictionary to sort by hash (faster)
        groups = {}
        for obj in objects:
            groups.setdefault(key(obj), []).append(obj)
        return list(groups.items()) if force_list else iteritems(groups)
    else:
        keygroupers = itertools.groupby(sorted(objects, key=key), key=key)
        if force_list:
            return [(k, [v for v in g]) for k, g in keygroupers]
        else:
            return keygroupers
开发者ID:Ocode,项目名称:nengo,代码行数:48,代码来源:stdlib.py


示例20: plan_SimProcess

    def plan_SimProcess(self, all_ops):
        class_groups = groupby(all_ops, lambda op: op.process.__class__)
        plan_groups = defaultdict(list)

        for process_class, ops in class_groups:
            for cls in process_class.__mro__:
                attrname = '_plan_' + cls.__name__
                if hasattr(self, attrname):
                    plan_groups[attrname].extend(ops)
                    break
            else:
                raise NotImplementedError("Unsupported process type '%s'"
                                          % process_class.__name__)

        return [p for attr, ops in iteritems(plan_groups)
                for p in getattr(self, attr)(ops)]
开发者ID:shaunren,项目名称:nengo_ocl,代码行数:16,代码来源:simulator.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python compat.range函数代码示例发布时间:2022-05-27
下一篇:
Python compat.is_string函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap