Пример #1
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)
Пример #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
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
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
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
    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
    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
 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
 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
 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
 def validate(self, instance, distorarray):
     if isinstance(distorarray, Distribution):
         Parameter.validate(self, instance, distorarray)
         return distorarray
     else:
         return NdarrayParam.validate(self, instance, distorarray)