コード例 #1
0
ファイル: convnet.py プロジェクト: fmirus/nengo_extras
 def __set__(self, instance, value):
     try:
         value = tuple(int(v) for v in value)
     except TypeError:
         raise ValidationError("Value must be castable to a tuple of ints",
                               attr=self.name, obj=instance)
     Parameter.__set__(self, instance, value)
コード例 #2
0
 def __set__(self, instance, value):
     try:
         value = tuple(int(v) for v in value)
     except TypeError:
         raise ValidationError("Value must be castable to a tuple of ints",
                               attr=self.name,
                               obj=instance)
     Parameter.__set__(self, instance, value)
コード例 #3
0
def test_config_basic():
    model = nengo.Network()
    model.config[nengo.Ensemble].set_param("something",
                                           Parameter("something", None))
    model.config[nengo.Ensemble].set_param("other",
                                           Parameter("other", default=0))
    model.config[nengo.Connection].set_param("something_else",
                                             Parameter("something_else", None))

    with pytest.raises(ConfigError, match="'fails' is not a parameter"):
        model.config[nengo.Ensemble].set_param("fails", 1.0)

    with pytest.raises(ConfigError, match="'bias' is already a parameter in"):
        model.config[nengo.Ensemble].set_param("bias", Parameter("bias", None))

    with model:
        a = nengo.Ensemble(50, dimensions=1)
        b = nengo.Ensemble(90, dimensions=1)
        a2b = nengo.Connection(a, b, synapse=0.01)

    with pytest.raises(ConfigError,
                       match="Cannot set parameters on an instance"):
        model.config[a].set_param("thing", Parameter("thing", None))

    with pytest.raises(ConfigError,
                       match="Cannot get parameters on an instance"):
        model.config[a].get_param("bias")

    assert model.config[a].something is None
    assert model.config[b].something is None
    assert model.config[a].other == 0
    assert model.config[b].other == 0
    assert model.config[a2b].something_else is None

    model.config[a].something = "hello"
    assert model.config[a].something == "hello"
    model.config[a].something = "world"
    assert model.config[a].something == "world"
    del model.config[a].something
    assert model.config[a].something is None

    with pytest.raises(AttributeError):
        model.config[a].something_else
    with pytest.raises(AttributeError):
        model.config[a2b].something
    with pytest.raises(AttributeError):
        model.config[a].something_else = 1
    with pytest.raises(AttributeError):
        model.config[a2b].something = 1

    with pytest.raises(ConfigError,
                       match="'str' is not set up for configuration"):
        model.config["a"].something
    with pytest.raises(ConfigError,
                       match="'NoneType' is not set up for configuration"):
        model.config[None].something
コード例 #4
0
def test_reuse_parameters_configerror(request):
    """test that exception is raised when
    reusing parameters"""
    def finalizer():
        del nengo.Ensemble.same

    request.addfinalizer(finalizer)

    model = nengo.Network()
    nengo.Ensemble.same = Parameter("param_a")
    with pytest.raises(ConfigError, match="'same' is already a parameter in"):
        model.config[nengo.Ensemble].set_param("same", Parameter("param_b"))
コード例 #5
0
def test_unconfigurable_configerror():
    """Tests exception when using settattr on something that is not configurable"""
    model = nengo.Network()
    model.config[nengo.Ensemble].set_param("prm", Parameter("prm", Unconfigurable))

    with pytest.raises(ConfigError, match="'prm' is not configurable"):
        model.config[nengo.Ensemble].prm = "other"
コード例 #6
0
def test_instance_fallthrough():
    """If the class default is set, instances should use that."""
    class A:
        pass

    inst1 = A()
    inst2 = A()
    config = nengo.Config(A)
    config[A].set_param("amount", Parameter("amount", default=1))
    assert config[A].amount == 1
    assert config[inst1].amount == 1
    assert config[inst2].amount == 1
    # Value can change for instance
    config[inst1].amount = 2
    assert config[A].amount == 1
    assert config[inst1].amount == 2
    assert config[inst2].amount == 1
    # If value to A is changed, unset instances should also change
    config[A].amount = 3
    assert config[A].amount == 3
    assert config[inst1].amount == 2
    assert config[inst2].amount == 3
    # If class default is deleted, unset instances go back
    del config[A].amount
    assert config[A].amount == 1
    assert config[inst1].amount == 2
    assert config[inst2].amount == 1
コード例 #7
0
def test_config_pickle(tmp_path):
    # --- test ClassParams
    clsconfig = ClassParams(nengo.Ensemble)
    clsconfig.max_rates = nengo.dists.Choice([0])

    picklefile = str(tmp_path / "config0.pkl")
    with open(picklefile, "wb") as fh:
        pickle.dump(clsconfig, fh)

    del fh

    with open(picklefile, "rb") as fh:
        clsconfig2 = pickle.load(fh)

    assert clsconfig2.max_rates == nengo.dists.Choice([0])

    # --- test InstanceParams
    clsconfig.set_param("dummy", Parameter("dummy",
                                           default=None,
                                           optional=True))

    ens = nengo.Ensemble(10, 1, add_to_container=False)
    insconfig = InstanceParams(ens, clsconfig)
    insconfig.dummy = nengo.dists.Choice([3])

    picklefile = str(tmp_path / "config1.pkl")
    with open(picklefile, "wb") as fh:
        pickle.dump(insconfig, fh)

    del fh

    with open(picklefile, "rb") as fh:
        insconfig2 = pickle.load(fh)

    assert insconfig2.dummy == nengo.dists.Choice([3])
コード例 #8
0
ファイル: config.py プロジェクト: trigrass2/nengo-loihi
def add_params(network):
    """Add nengo_loihi config option to *network*.

    The following options will be added:

    `nengo.Ensemble`
      * ``on_chip``: Whether the ensemble should be simulated
        on a Loihi chip. Marking specific ensembles for simulation
        off of a Loihi chip can help with debugging.

    Examples
    --------

    >>> with nengo.Network() as model:
    ...     ens = nengo.Ensemble(10, dimensions=1)
    ...     # By default, ens will be placed on a Loihi chip
    ...     nengo_loihi.add_params(model)
    ...     model.config[ens].on_chip = False
    ...     # Now it will be simulated with Nengo

    """
    config = network.config

    ens_cfg = config[nengo.Ensemble]
    if 'on_chip' not in ens_cfg._extra_params:
        ens_cfg.set_param("on_chip",
                          Parameter('on_chip', default=None, optional=True))
コード例 #9
0
def add_params(network):
    """Add nengo_loihi config option to *network*.

    The following options will be added:

    `nengo.Ensemble`
      * ``on_chip``: Whether the ensemble should be simulated
        on a Loihi chip. Marking specific ensembles for simulation
        off of a Loihi chip can help with debugging.
      * ``block_shape``: Specifies how this ensemble should be split across
        Loihi neuron cores. See `.BlockShape` for more details.
    `nengo.Connection`
      * ``pop_type``: The axon format when using population spikes, which are only
        used for convolutional connections. Must be either the integer 16 or 32.
        By default, we use ``pop_type`` 32. Using 16 reduces the number of axons
        required by a factor of two, but has more constraints, including on the
        number of channels allowed per block. When using ``pop_type`` 16, we
        recommend to use ``channels_last=True`` and have ``n_filters`` (as well as
        the number of channels per block) be a multiple of 4 on your
        convolutional connections; this will reduce the required synapse memory.

    Examples
    --------

    >>> with nengo.Network() as model:
    ...     ens = nengo.Ensemble(10, dimensions=1)
    ...     # By default, ens will be placed on a Loihi chip
    ...     nengo_loihi.add_params(model)
    ...     model.config[ens].on_chip = False
    ...     # Now it will be simulated with Nengo

    """
    config = network.config

    ens_cfg = config[nengo.Ensemble]
    if "on_chip" not in ens_cfg._extra_params:
        ens_cfg.set_param("on_chip",
                          Parameter("on_chip", default=None, optional=True))
    if "block_shape" not in ens_cfg._extra_params:
        ens_cfg.set_param(
            "block_shape",
            BlockShapeParam("block_shape", default=None, optional=True))

    conn_cfg = config[nengo.Connection]
    if "pop_type" not in conn_cfg._extra_params:
        conn_cfg.set_param("pop_type",
                           Parameter("pop_type", default=32, optional=True))
コード例 #10
0
def test_get_param_on_instance_configerror():
    """test that exception is raised when getting params on instance"""
    model = nengo.Network()
    model.config[nengo.Ensemble].set_param("something", Parameter("something", None))
    with model:
        a = nengo.Ensemble(50, dimensions=1)

    with pytest.raises(ConfigError, match="Cannot get parameters on an instance"):
        model.config[a].get_param("something")
コード例 #11
0
def test_classparams_str_repr():
    """tests the repr function in classparams class"""
    clsparams = nengo.Network().config[nengo.Ensemble]
    clsparams.set_param("test", Parameter("test", None))
    assert repr(clsparams) == "<ClassParams[Ensemble]{test: None}>"
    assert str(clsparams) == "No parameters configured for Ensemble."

    clsparams.test = "val"
    assert str(clsparams) == "Parameters configured for Ensemble:\n  test: val"
コード例 #12
0
def test_config_basic():
    model = nengo.Network()
    model.config[nengo.Ensemble].set_param('something',
                                           Parameter('something', None))
    model.config[nengo.Ensemble].set_param('other',
                                           Parameter('other', default=0))
    model.config[nengo.Connection].set_param('something_else',
                                             Parameter('something_else', None))

    with pytest.raises(ConfigError):
        model.config[nengo.Ensemble].set_param('fails', 1.0)

    with model:
        a = nengo.Ensemble(50, dimensions=1)
        b = nengo.Ensemble(90, dimensions=1)
        a2b = nengo.Connection(a, b, synapse=0.01)

    with pytest.raises(ConfigError):
        model.config[a].set_param('thing', Parameter('thing', None))

    assert model.config[a].something is None
    assert model.config[b].something is None
    assert model.config[a].other == 0
    assert model.config[b].other == 0
    assert model.config[a2b].something_else is None

    model.config[a].something = 'hello'
    assert model.config[a].something == 'hello'
    model.config[a].something = 'world'
    assert model.config[a].something == 'world'
    del model.config[a].something
    assert model.config[a].something is None

    with pytest.raises(AttributeError):
        model.config[a].something_else
        model.config[a2b].something
    with pytest.raises(AttributeError):
        model.config[a].something_else = 1
        model.config[a2b].something = 1

    with pytest.raises(ConfigError):
        model.config['a'].something
    with pytest.raises(ConfigError):
        model.config[None].something
コード例 #13
0
ファイル: test_config.py プロジェクト: xlong0513/nengo
def test_config_basic():
    model = nengo.Network()
    model.config[nengo.Ensemble].set_param("something", Parameter("something", None))
    model.config[nengo.Ensemble].set_param("other", Parameter("other", default=0))
    model.config[nengo.Connection].set_param(
        "something_else", Parameter("something_else", None)
    )

    with pytest.raises(ConfigError):
        model.config[nengo.Ensemble].set_param("fails", 1.0)

    with model:
        a = nengo.Ensemble(50, dimensions=1)
        b = nengo.Ensemble(90, dimensions=1)
        a2b = nengo.Connection(a, b, synapse=0.01)

    with pytest.raises(ConfigError):
        model.config[a].set_param("thing", Parameter("thing", None))

    assert model.config[a].something is None
    assert model.config[b].something is None
    assert model.config[a].other == 0
    assert model.config[b].other == 0
    assert model.config[a2b].something_else is None

    model.config[a].something = "hello"
    assert model.config[a].something == "hello"
    model.config[a].something = "world"
    assert model.config[a].something == "world"
    del model.config[a].something
    assert model.config[a].something is None

    with pytest.raises(AttributeError):
        model.config[a].something_else
        model.config[a2b].something
    with pytest.raises(AttributeError):
        model.config[a].something_else = 1
        model.config[a2b].something = 1

    with pytest.raises(ConfigError):
        model.config["a"].something
    with pytest.raises(ConfigError):
        model.config[None].something
コード例 #14
0
ファイル: config.py プロジェクト: InspectorDidi/nengo-loihi
def add_params(network):
    """Add nengo_loihi config option to *network*.

    The following options will be added:

    `nengo.Ensemble`
      * ``on_chip``: Whether the ensemble should be simulated
        on a Loihi chip. Marking specific ensembles for simulation
        off of a Loihi chip can help with debugging.
      * ``block_shape``: Specifies how this ensemble should be split across
        Loihi neuron cores. See `.BlockShape` for more details.
    `nengo.Connection`
      * ``pop_type``: The axon format when using population spikes, which are only
        used for convolutional connections. Must be an int between 16 and 32.
        By default, we use ``pop_type`` 32.

    Examples
    --------

    >>> with nengo.Network() as model:
    ...     ens = nengo.Ensemble(10, dimensions=1)
    ...     # By default, ens will be placed on a Loihi chip
    ...     nengo_loihi.add_params(model)
    ...     model.config[ens].on_chip = False
    ...     # Now it will be simulated with Nengo

    """
    config = network.config

    ens_cfg = config[nengo.Ensemble]
    if "on_chip" not in ens_cfg._extra_params:
        ens_cfg.set_param("on_chip",
                          Parameter("on_chip", default=None, optional=True))
    if "block_shape" not in ens_cfg._extra_params:
        ens_cfg.set_param(
            "block_shape",
            BlockShapeParam("block_shape", default=None, optional=True))

    conn_cfg = config[nengo.Connection]
    if "pop_type" not in conn_cfg._extra_params:
        conn_cfg.set_param("pop_type",
                           Parameter("pop_type", default=32, optional=True))
コード例 #15
0
def test_instanceparams_contains():
    """tests the contains function in InstanceParams class"""
    model = nengo.Network()
    model.config[nengo.Ensemble].set_param("test", Parameter("test", None))
    with model:
        a = nengo.Ensemble(5, 1)
        b = nengo.Ensemble(5, 1)
        model.config[b].test = 3

    assert "test" not in model.config[a]
    assert "test" in model.config[b]
コード例 #16
0
ファイル: probe.py プロジェクト: nengo/nengo
    def coerce(self, probe, target):
        obj = target.obj if isinstance(target, ObjView) else target
        if not hasattr(obj, 'probeable'):
            raise ValidationError("Type %r is not probeable"
                                  % type(obj).__name__,
                                  attr=self.name, obj=probe)

        # do this after; better to know that type is not Probable first
        if isinstance(obj, LearningRule):
            # TODO: this special case should be able to be removed with #1310
            return Parameter.coerce(self, probe, target)
        else:
            return super().coerce(probe, target)
コード例 #17
0
def test_unconfigurable_default_configerror(request):
    """test exception when using `Config.default` with a unconfigurable parameter"""
    def finalizer():
        del nengo.Ensemble.something2

    request.addfinalizer(finalizer)

    model = nengo.Network()
    nengo.Ensemble.something2 = Parameter("something2", Unconfigurable)

    with pytest.raises(ConfigError,
                       match="Unconfigurable parameters have no defaults"):
        model.config.default(nengo.Ensemble, "something2")
コード例 #18
0
ファイル: probe.py プロジェクト: kpc-simone/nengo
    def coerce(self, probe, target):
        obj = target.obj if isinstance(target, ObjView) else target
        if not hasattr(obj, 'probeable'):
            raise ValidationError("Type %r is not probeable" %
                                  type(obj).__name__,
                                  attr=self.name,
                                  obj=probe)

        # do this after; better to know that type is not Probable first
        if isinstance(obj, LearningRule):
            # TODO: this special case should be able to be removed with #1310
            return Parameter.coerce(self, probe, target)
        else:
            return super().coerce(probe, target)
コード例 #19
0
    def coerce(self, probe, target):  # pylint: disable=arguments-renamed
        obj = target.obj if isinstance(target, ObjView) else target
        if not hasattr(obj, "probeable"):
            raise ValidationError(
                f"Type '{type(obj).__name__}' is not probeable",
                attr=self.name,
                obj=probe,
            )

        # do this after; better to know that type is not Probable first
        if isinstance(obj, LearningRule):
            # TODO: this special case should be able to be removed with #1310
            return Parameter.coerce(self, probe, target)
        else:
            return super().coerce(probe, target)
コード例 #20
0
def test_external_class():
    class A(object):
        thing = Parameter(default='hey')

    inst = A()
    config = nengo.Config(A)
    config[A].set_param('amount', Parameter(default=1))

    # Extra param
    assert config[inst].amount == 1

    # Default still works like Nengo object
    assert inst.thing == 'hey'
    with pytest.raises(AttributeError):
        config[inst].thing
コード例 #21
0
def test_contains():
    class A:
        pass

    cfg = nengo.Config(A)
    with pytest.raises(TypeError, match="Cannot check if .* is in a config"):
        A in cfg

    net = nengo.Network()

    net.config[nengo.Ensemble].set_param("test", Parameter("test", None))
    assert "test" not in net.config[nengo.Ensemble]

    net.config[nengo.Ensemble].test = "testval"
    assert "test" in net.config[nengo.Ensemble]
コード例 #22
0
def test_external_class():
    class A:
        thing = Parameter("thing", default="hey")

    inst = A()
    config = nengo.Config(A)
    config[A].set_param("amount", Parameter("amount", default=1))

    # Extra param
    assert config[inst].amount == 1

    # Default still works like Nengo object
    assert inst.thing == "hey"
    with pytest.raises(ConfigError):
        config[inst].thing
コード例 #23
0
def test_classparams_del():
    """tests ClassParams.__delattr__"""
    net = nengo.Network()
    clsparams = net.config[nengo.Ensemble]

    # test that normal instance param can be added/deleted
    clsparams.set_param("test", Parameter("test", None))
    clsparams.test = "val"
    assert "test" in clsparams
    del clsparams.test
    assert "test" not in clsparams

    # test that we can set/get/delete underscore attributes regularly
    clsparams._test = 3
    assert hasattr(clsparams, "_test") and clsparams._test == 3
    del clsparams._test
    assert not hasattr(clsparams, "_test")
コード例 #24
0
def add_spinnaker_params(config):
    """Add SpiNNaker specific parameters to a configuration object."""
    # Add simulator parameters
    config.configures(Simulator)

    config[Simulator].set_param("placer", CallableParameter(default=par.place))
    config[Simulator].set_param("placer_kwargs", DictParam(default={}))

    config[Simulator].set_param("allocater",
                                CallableParameter(default=par.allocate))
    config[Simulator].set_param("allocater_kwargs", DictParam(default={}))

    config[Simulator].set_param("router", CallableParameter(default=par.route))
    config[Simulator].set_param("router_kwargs", DictParam(default={}))

    config[Simulator].set_param("node_io", Parameter(default=Ethernet))
    config[Simulator].set_param("node_io_kwargs", DictParam(default={}))

    # Add function_of_time parameters to Nodes
    config[nengo.Node].set_param("function_of_time", BoolParam(default=False))
    config[nengo.Node].set_param("function_of_time_period",
                                 NumberParam(default=None, optional=True))

    # Add multiple-core options to Nodes
    config[nengo.Node].set_param(
        "n_cores_per_chip",
        IntParam(default=None, low=1, high=16, optional=True))
    config[nengo.Node].set_param("n_chips",
                                 IntParam(default=None, low=1, optional=True))
    # Add optimisation control parameters to (passthrough) Nodes. None means
    # that a heuristic will be used to determine if the passthrough Node should
    # be removed.
    config[nengo.Node].set_param("optimize_out",
                                 BoolParam(default=None, optional=True))

    # Add profiling parameters to Ensembles
    config[nengo.Ensemble].set_param("profile", BoolParam(default=False))
    config[nengo.Ensemble].set_param("profile_num_samples",
                                     NumberParam(default=None, optional=True))
コード例 #25
0
def test_instanceparams_del():
    """tests built in params on the delattr function in InstanceParams class"""
    model = nengo.Network()
    with model:
        a = nengo.Ensemble(5, dimensions=1)

    # test that normal instance param can be added/deleted
    model.config[nengo.Ensemble].set_param("test", Parameter("test", None))
    model.config[a].test = "val"
    assert "test" in model.config[a]
    del model.config[a].test
    assert "test" not in model.config[a]

    # test that built-in parameter cannot be deleted
    with pytest.raises(ConfigError, match="Cannot configure the built-in parameter"):
        del model.config[a].bias

    # test that we can set/get/delete underscore attributes regularly
    model.config[a]._test = 3
    assert hasattr(model.config[a], "_test") and model.config[a]._test == 3
    del model.config[a]._test
    assert not hasattr(model.config[a], "_test")
コード例 #26
0
def test_config_str():
    """Ensure that string representations are nice."""
    with nengo.Network() as net1:
        assert net1.config[nengo.Ensemble].params == list(
            nengo.Ensemble.param_list())

        net1.config[nengo.Ensemble].radius = 3.0
        net1.config[nengo.Ensemble].seed = 10
        assert str(
            net1.config[nengo.Ensemble]) == ("All parameters for Ensemble:\n"
                                             "  radius: 3.0\n"
                                             "  seed: 10")

        ens = nengo.Ensemble(10, 1, radius=2.0, label="A")
        assert str(net1.config[ens]) == ("Parameters set for Ensemble: A:")

        with nengo.Network() as net2:
            assert str(net2.config[nengo.Ensemble]) == (
                "All parameters for Ensemble:")
            net2.config[nengo.Ensemble].radius = 5.0
            assert str(net2.config[nengo.Ensemble]) == (
                "All parameters for Ensemble:\n"
                "  radius: 5.0")

            with nengo.Network() as net3:
                net3.config[nengo.Ensemble].set_param("extra",
                                                      Parameter(default="20"))
                net3.config[nengo.Ensemble].seed = 20
                assert str(net3.config[nengo.Ensemble]) == (
                    "All parameters for Ensemble:\n"
                    "  seed: 20\n"
                    "  extra: 20")
                net3.config[ens].extra = 50
                assert str(
                    net3.config[ens]) == ("Parameters set for Ensemble: A:\n"
                                          "  extra: 50")
コード例 #27
0
ファイル: dists.py プロジェクト: thingimon/nengo
 def validate(self, instance, distorarray):
     if isinstance(distorarray, Distribution):
         Parameter.validate(self, instance, distorarray)
         return distorarray
     return super(DistOrArrayParam, self).validate(instance, distorarray)
コード例 #28
0
    class MyClass(SupportDefaultsMixin):
        p = Parameter("p", default="baba", readonly=True)

        def __init__(self, p=Default):
            self.p = p
コード例 #29
0
ファイル: dists.py プロジェクト: nengo/nengo
 def coerce(self, instance, distorarray):
     if isinstance(distorarray, Distribution):
         return Parameter.coerce(self, instance, distorarray)
     return super().coerce(instance, distorarray)
コード例 #30
0
 def coerce(self, instance, distorarray):  # pylint: disable=arguments-renamed
     if isinstance(distorarray, Distribution):
         return Parameter.coerce(self, instance, distorarray)
     return super().coerce(instance, distorarray)
コード例 #31
0
    class MyParent(SupportDefaultsMixin):
        p = Parameter("p", default="baba")

        def __init__(self, p=Default):
            self.p = p
コード例 #32
0
ファイル: dists.py プロジェクト: jepetolee/nengo
 def coerce(self, instance, distorarray):
     if isinstance(distorarray, Distribution):
         return Parameter.coerce(self, instance, distorarray)
     return super().coerce(instance, distorarray)
コード例 #33
0
 class A:
     thing = Parameter("thing", default="hey")
コード例 #34
0
 class A(object):
     thing = Parameter(default='hey')
コード例 #35
0
ファイル: dists.py プロジェクト: MarcoSaku/Spiking-C3D
 def validate(self, instance, distorarray):
     if isinstance(distorarray, Distribution):
         Parameter.validate(self, instance, distorarray)
         return distorarray
     else:
         return NdarrayParam.validate(self, instance, distorarray)