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)
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
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"))
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"
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
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])
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))
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))
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")
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"
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
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
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))
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]
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)
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")
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)
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
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]
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
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")
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))
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")
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")
def validate(self, instance, distorarray): if isinstance(distorarray, Distribution): Parameter.validate(self, instance, distorarray) return distorarray return super(DistOrArrayParam, self).validate(instance, distorarray)
class MyClass(SupportDefaultsMixin): p = Parameter("p", default="baba", readonly=True) def __init__(self, p=Default): self.p = p
def coerce(self, instance, distorarray): if isinstance(distorarray, Distribution): return Parameter.coerce(self, instance, distorarray) return super().coerce(instance, distorarray)
def coerce(self, instance, distorarray): # pylint: disable=arguments-renamed if isinstance(distorarray, Distribution): return Parameter.coerce(self, instance, distorarray) return super().coerce(instance, distorarray)
class MyParent(SupportDefaultsMixin): p = Parameter("p", default="baba") def __init__(self, p=Default): self.p = p
class A: thing = Parameter("thing", default="hey")
class A(object): thing = Parameter(default='hey')
def validate(self, instance, distorarray): if isinstance(distorarray, Distribution): Parameter.validate(self, instance, distorarray) return distorarray else: return NdarrayParam.validate(self, instance, distorarray)