本文整理汇总了Python中nengo.builder.signal.SignalDict类的典型用法代码示例。如果您正苦于以下问题:Python SignalDict类的具体用法?Python SignalDict怎么用?Python SignalDict使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SignalDict类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_signaldict
def test_signaldict():
"""Tests SignalDict's dict overrides."""
signaldict = SignalDict()
scalar = Signal(1.)
# Both __getitem__ and __setitem__ raise KeyError
with pytest.raises(KeyError):
signaldict[scalar]
with pytest.raises(KeyError):
signaldict[scalar] = np.array(1.)
signaldict.init(scalar)
assert np.allclose(signaldict[scalar], np.array(1.))
# __getitem__ handles scalars
assert signaldict[scalar].shape == ()
one_d = Signal([1.])
signaldict.init(one_d)
assert np.allclose(signaldict[one_d], np.array([1.]))
assert signaldict[one_d].shape == (1,)
two_d = Signal([[1.], [1.]])
signaldict.init(two_d)
assert np.allclose(signaldict[two_d], np.array([[1.], [1.]]))
assert signaldict[two_d].shape == (2, 1)
# __getitem__ handles views
two_d_view = two_d[0, :]
signaldict.init(two_d_view)
assert np.allclose(signaldict[two_d_view], np.array([1.]))
assert signaldict[two_d_view].shape == (1,)
# __setitem__ ensures memory location stays the same
memloc = signaldict[scalar].__array_interface__['data'][0]
signaldict[scalar] = np.array(0.)
assert np.allclose(signaldict[scalar], np.array(0.))
assert signaldict[scalar].__array_interface__['data'][0] == memloc
memloc = signaldict[one_d].__array_interface__['data'][0]
signaldict[one_d] = np.array([0.])
assert np.allclose(signaldict[one_d], np.array([0.]))
assert signaldict[one_d].__array_interface__['data'][0] == memloc
memloc = signaldict[two_d].__array_interface__['data'][0]
signaldict[two_d] = np.array([[0.], [0.]])
assert np.allclose(signaldict[two_d], np.array([[0.], [0.]]))
assert signaldict[two_d].__array_interface__['data'][0] == memloc
# __str__ pretty-prints signals and current values
# Order not guaranteed for dicts, so we have to loop
for k in signaldict:
assert "%s %s" % (repr(k), repr(signaldict[k])) in str(signaldict)
示例2: __init__
def __init__(self, network, dt=0.001, seed=None, model=None):
self.closed = False
if model is None:
dt = float(dt) # make sure it's a float (for division purposes)
self.model = Model(dt=dt,
label="%s, dt=%f" % (network, dt),
decoder_cache=get_default_decoder_cache())
else:
self.model = model
if network is not None:
# Build the network into the model
self.model.build(network)
self.model.decoder_cache.shrink()
# -- map from Signal.base -> ndarray
self.signals = SignalDict()
for op in self.model.operators:
op.init_signals(self.signals)
# Order the steps (they are made in `Simulator.reset`)
self.dg = operator_depencency_graph(self.model.operators)
self._step_order = [op for op in toposort(self.dg)
if hasattr(op, 'make_step')]
# Add built states to the probe dictionary
self._probe_outputs = self.model.params
# Provide a nicer interface to probe outputs
self.data = ProbeDict(self._probe_outputs)
seed = np.random.randint(npext.maxint) if seed is None else seed
self.reset(seed=seed)
示例3: test_signal_reshape
def test_signal_reshape():
"""Tests Signal.reshape"""
# check proper shape after reshape
three_d = Signal(np.ones((2, 2, 2)))
assert three_d.reshape((8,)).shape == (8,)
assert three_d.reshape((4, 2)).shape == (4, 2)
assert three_d.reshape((2, 4)).shape == (2, 4)
assert three_d.reshape(-1).shape == (8,)
assert three_d.reshape((4, -1)).shape == (4, 2)
assert three_d.reshape((-1, 4)).shape == (2, 4)
assert three_d.reshape((2, -1, 2)).shape == (2, 2, 2)
assert three_d.reshape((1, 2, 1, 2, 2, 1)).shape == (1, 2, 1, 2, 2, 1)
# check with non-contiguous arrays (and with offset)
value = np.arange(20).reshape(5, 4)
s = Signal(np.array(value), name='s')
s0slice = slice(0, 3), slice(None, None, 2)
s0shape = 2, 3
s0 = s[s0slice].reshape(*s0shape)
assert s.offset == 0
assert np.array_equal(s0.initial_value, value[s0slice].reshape(*s0shape))
s1slice = slice(1, None), slice(None, None, 2)
s1shape = 2, 4
s1 = s[s1slice].reshape(s1shape)
assert s1.offset == 4 * s1.dtype.itemsize
assert np.array_equal(s1.initial_value, value[s1slice].reshape(s1shape))
# check error if non-contiguous array cannot be reshaped without copy
s2slice = slice(None, None, 2), slice(None, None, 2)
s2shape = 2, 3
s2 = s[s2slice]
with pytest.raises(SignalError):
s2.reshape(s2shape)
# check that views are working properly (incrementing `s` effects views)
values = SignalDict()
values.init(s)
values.init(s0)
values.init(s1)
values[s] += 1
assert np.array_equal(values[s0], value[s0slice].reshape(s0shape) + 1)
assert np.array_equal(values[s1], value[s1slice].reshape(s1shape) + 1)
示例4: test_signaldict_reset
def test_signaldict_reset():
"""Tests SignalDict's reset function."""
signaldict = SignalDict()
two_d = Signal([[1.], [1.]])
signaldict.init(two_d)
two_d_view = two_d[0, :]
signaldict.init(two_d_view)
signaldict[two_d_view] = -0.5
assert np.allclose(signaldict[two_d], np.array([[-0.5], [1]]))
signaldict[two_d] = np.array([[-1], [-1]])
assert np.allclose(signaldict[two_d], np.array([[-1], [-1]]))
assert np.allclose(signaldict[two_d_view], np.array([-1]))
signaldict.reset(two_d_view)
assert np.allclose(signaldict[two_d_view], np.array([1]))
assert np.allclose(signaldict[two_d], np.array([[1], [-1]]))
signaldict.reset(two_d)
assert np.allclose(signaldict[two_d], np.array([[1], [1]]))
示例5: __init__
def __init__(self, network, dt=0.001, seed=None, model=None):
"""Initialize the simulator with a network and (optionally) a model.
Most of the time, you will pass in a network and sometimes a dt::
sim1 = nengo.Simulator(my_network) # Uses default 0.001s dt
sim2 = nengo.Simulator(my_network, dt=0.01) # Uses 0.01s dt
For more advanced use cases, you can initialize the model yourself,
and also pass in a network that will be built into the same model
that you pass in::
sim = nengo.Simulator(my_network, model=my_model)
If you want full control over the build process, then you can build
your network into the model manually. If you do this, then you must
explicitly pass in ``None`` for the network::
sim = nengo.Simulator(None, model=my_model)
Parameters
----------
network : nengo.Network instance or None
A network object to the built and then simulated.
If a fully built ``model`` is passed in, then you can skip
building the network by passing in network=None.
dt : float, optional
The length of a simulator timestep, in seconds.
seed : int, optional
A seed for all stochastic operators used in this simulator.
model : nengo.builder.Model instance or None, optional
A model object that contains build artifacts to be simulated.
Usually the simulator will build this model for you; however,
if you want to build the network manually, or to inject some
build artifacts in the Model before building the network,
then you can pass in a ``nengo.builder.Model`` instance.
"""
if model is None:
dt = float(dt) # make sure it's a float (for division purposes)
self.model = Model(dt=dt,
label="%s, dt=%f" % (network, dt),
decoder_cache=get_default_decoder_cache())
else:
self.model = model
if network is not None:
# Build the network into the model
self.model.build(network)
self.model.decoder_cache.shrink()
# -- map from Signal.base -> ndarray
self.signals = SignalDict(__time__=np.asarray(0.0, dtype=np.float64))
for op in self.model.operators:
op.init_signals(self.signals)
# Order the steps (they are made in `Simulator.reset`)
self.dg = operator_depencency_graph(self.model.operators)
self._step_order = [op for op in toposort(self.dg)
if hasattr(op, 'make_step')]
# Add built states to the probe dictionary
self._probe_outputs = self.model.params
# Provide a nicer interface to probe outputs
self.data = ProbeDict(self._probe_outputs)
seed = np.random.randint(npext.maxint) if seed is None else seed
self.reset(seed=seed)
示例6: Simulator
class Simulator(object):
"""Reference simulator for Nengo models."""
def __init__(self, network, dt=0.001, seed=None, model=None):
"""Initialize the simulator with a network and (optionally) a model.
Most of the time, you will pass in a network and sometimes a dt::
sim1 = nengo.Simulator(my_network) # Uses default 0.001s dt
sim2 = nengo.Simulator(my_network, dt=0.01) # Uses 0.01s dt
For more advanced use cases, you can initialize the model yourself,
and also pass in a network that will be built into the same model
that you pass in::
sim = nengo.Simulator(my_network, model=my_model)
If you want full control over the build process, then you can build
your network into the model manually. If you do this, then you must
explicitly pass in ``None`` for the network::
sim = nengo.Simulator(None, model=my_model)
Parameters
----------
network : nengo.Network instance or None
A network object to the built and then simulated.
If a fully built ``model`` is passed in, then you can skip
building the network by passing in network=None.
dt : float, optional
The length of a simulator timestep, in seconds.
seed : int, optional
A seed for all stochastic operators used in this simulator.
model : nengo.builder.Model instance or None, optional
A model object that contains build artifacts to be simulated.
Usually the simulator will build this model for you; however,
if you want to build the network manually, or to inject some
build artifacts in the Model before building the network,
then you can pass in a ``nengo.builder.Model`` instance.
"""
if model is None:
dt = float(dt) # make sure it's a float (for division purposes)
self.model = Model(dt=dt,
label="%s, dt=%f" % (network, dt),
decoder_cache=get_default_decoder_cache())
else:
self.model = model
if network is not None:
# Build the network into the model
self.model.build(network)
self.model.decoder_cache.shrink()
# -- map from Signal.base -> ndarray
self.signals = SignalDict(__time__=np.asarray(0.0, dtype=np.float64))
for op in self.model.operators:
op.init_signals(self.signals)
# Order the steps (they are made in `Simulator.reset`)
self.dg = operator_depencency_graph(self.model.operators)
self._step_order = [op for op in toposort(self.dg)
if hasattr(op, 'make_step')]
# Add built states to the probe dictionary
self._probe_outputs = self.model.params
# Provide a nicer interface to probe outputs
self.data = ProbeDict(self._probe_outputs)
seed = np.random.randint(npext.maxint) if seed is None else seed
self.reset(seed=seed)
@property
def dt(self):
"""The time step of the simulator"""
return self.model.dt
@dt.setter
def dt(self, dummy):
raise AttributeError("Cannot change simulator 'dt'. Please file "
"an issue at http://github.com/nengo/nengo"
"/issues and describe your use case.")
@property
def time(self):
"""The current time of the simulator"""
return self.signals['__time__'].copy()
def trange(self, dt=None):
"""Create a range of times matching probe data.
Note that the range does not start at 0 as one might expect, but at
the first timestep (i.e., dt).
Parameters
----------
dt : float (optional)
The sampling period of the probe to create a range for. If empty,
will use the default probe sampling period.
#.........这里部分代码省略.........
示例7: Simulator
class Simulator(object):
"""Reference simulator for Nengo models.
The simulator takes a `.Network` and builds internal data structures to
run the model defined by that network. Run the simulator with the
`~.Simulator.run` method, and access probed data through the
``data`` attribute.
Building and running the simulation may allocate resources like files
and sockets. To properly free these resources, call the `.Simulator.close`
method. Alternatively, `.Simulator.close` will automatically be called
if you use the ``with`` syntax::
with nengo.Simulator(my_network) as sim:
sim.run(0.1)
print(sim.data[my_probe])
Note that the ``data`` attribute is still accessible even when a simulator
has been closed. Running the simulator, however, will raise an error.
Parameters
----------
network : Network or None
A network object to be built and then simulated. If None,
then a `.Model` with the build model must be provided instead.
dt : float, optional (Default: 0.001)
The length of a simulator timestep, in seconds.
seed : int, optional (Default: None)
A seed for all stochastic operators used in this simulator.
model : Model, optional (Default: None)
A `.Model` that contains build artifacts to be simulated.
Usually the simulator will build this model for you; however, if you
want to build the network manually, or you want to inject build
artifacts in the model before building the network, then you can
pass in a `.Model` instance.
Attributes
----------
closed : bool
Whether the simulator has been closed.
Once closed, it cannot be reopened.
data : ProbeDict
The `.ProbeDict` mapping from Nengo objects to the data associated
with those objects. In particular, each `.Probe` maps to the data
probed while running the simulation.
dg : dict
A dependency graph mapping from each `.Operator` to the operators
that depend on that operator.
model : Model
The `.Model` containing the signals and operators necessary to
simulate the network.
signals : SignalDict
The `.SignalDict` mapping from `.Signal` instances to NumPy arrays.
"""
# 'unsupported' defines features unsupported by a simulator.
# The format is a list of tuples of the form `(test, reason)` with `test`
# being a string with wildcards (*, ?, [abc], [!abc]) matched against Nengo
# test paths and names, and `reason` is a string describing why the feature
# is not supported by the backend. For example:
# unsupported = [('test_pes*', 'PES rule not implemented')]
# would skip all test whose names start with 'test_pes'.
unsupported = []
def __init__(self, network, dt=0.001, seed=None, model=None):
self.closed = False
if model is None:
dt = float(dt) # make sure it's a float (for division purposes)
self.model = Model(dt=dt,
label="%s, dt=%f" % (network, dt),
decoder_cache=get_default_decoder_cache())
else:
self.model = model
if network is not None:
# Build the network into the model
self.model.build(network)
self.model.decoder_cache.shrink()
# -- map from Signal.base -> ndarray
self.signals = SignalDict()
for op in self.model.operators:
op.init_signals(self.signals)
# Order the steps (they are made in `Simulator.reset`)
self.dg = operator_depencency_graph(self.model.operators)
self._step_order = [op for op in toposort(self.dg)
if hasattr(op, 'make_step')]
# Add built states to the probe dictionary
self._probe_outputs = self.model.params
# Provide a nicer interface to probe outputs
self.data = ProbeDict(self._probe_outputs)
seed = np.random.randint(npext.maxint) if seed is None else seed
self.reset(seed=seed)
#.........这里部分代码省略.........
示例8: Simulator
class Simulator(object):
"""Reference simulator for Nengo models."""
def __init__(self, network, dt=0.001, seed=None, model=None):
"""Initialize the simulator with a network and (optionally) a model.
Most of the time, you will pass in a network and sometimes a dt::
sim1 = nengo.Simulator(my_network) # Uses default 0.001s dt
sim2 = nengo.Simulator(my_network, dt=0.01) # Uses 0.01s dt
For more advanced use cases, you can initialize the model yourself,
and also pass in a network that will be built into the same model
that you pass in::
sim = nengo.Simulator(my_network, model=my_model)
If you want full control over the build process, then you can build
your network into the model manually. If you do this, then you must
explicitly pass in ``None`` for the network::
sim = nengo.Simulator(None, model=my_model)
Parameters
----------
network : nengo.Network instance or None
A network object to the built and then simulated.
If a fully built ``model`` is passed in, then you can skip
building the network by passing in network=None.
dt : float
The length of a simulator timestep, in seconds.
seed : int
A seed for all stochastic operators used in this simulator.
Note that there are not stochastic operators implemented
currently, so this parameters does nothing.
model : nengo.builder.Model instance or None
A model object that contains build artifacts to be simulated.
Usually the simulator will build this model for you; however,
if you want to build the network manually, or to inject some
build artifacts in the Model before building the network,
then you can pass in a ``nengo.builder.Model`` instance.
"""
dt = float(dt) # make sure it's a float (for division purposes)
if model is None:
self.model = Model(dt=dt,
label="%s, dt=%f" % (network, dt),
decoder_cache=get_default_decoder_cache())
else:
self.model = model
if network is not None:
# Build the network into the model
self.model.build(network)
self.model.decoder_cache.shrink()
self.seed = np.random.randint(npext.maxint) if seed is None else seed
self.rng = np.random.RandomState(self.seed)
# -- map from Signal.base -> ndarray
self.signals = SignalDict(__time__=np.asarray(0.0, dtype=np.float64))
for op in self.model.operators:
op.init_signals(self.signals)
self.dg = operator_depencency_graph(self.model.operators)
self._step_order = [node for node in toposort(self.dg)
if hasattr(node, 'make_step')]
self._steps = [node.make_step(self.signals, dt, self.rng)
for node in self._step_order]
# Add built states to the probe dictionary
self._probe_outputs = self.model.params
# Provide a nicer interface to probe outputs
self.data = ProbeDict(self._probe_outputs)
self.reset()
@property
def dt(self):
"""The time step of the simulator"""
return self.model.dt
@dt.setter
def dt(self, dummy):
raise AttributeError("Cannot change simulator 'dt'. Please file "
"an issue at http://github.com/ctn-waterloo/nengo"
"/issues and describe your use case.")
@property
def time(self):
"""The current time of the simulator"""
return self.signals['__time__'].copy()
def trange(self, dt=None):
"""Create a range of times matching probe data.
Parameters
----------
#.........这里部分代码省略.........
示例9: Simulator
class Simulator(object):
"""Reference simulator for Nengo models."""
# 'unsupported' defines features unsupported by a simulator.
# The format is a list of tuples of the form `(test, reason)` with `test`
# being a string with wildcards (*, ?, [abc], [!abc]) matched against Nengo
# test paths and names, and `reason` is a string describing why the feature
# is not supported by the backend. For example:
# unsupported = [('test_pes*', 'PES rule not implemented')]
# would skip all test whose names start with 'test_pes'.
unsupported = []
def __init__(self, network, dt=0.001, seed=None, model=None):
"""Initialize the simulator with a network and (optionally) a model.
Most of the time, you will pass in a network and sometimes a dt::
sim1 = nengo.Simulator(my_network) # Uses default 0.001s dt
sim2 = nengo.Simulator(my_network, dt=0.01) # Uses 0.01s dt
For more advanced use cases, you can initialize the model yourself,
and also pass in a network that will be built into the same model
that you pass in::
sim = nengo.Simulator(my_network, model=my_model)
If you want full control over the build process, then you can build
your network into the model manually. If you do this, then you must
explicitly pass in ``None`` for the network::
sim = nengo.Simulator(None, model=my_model)
Parameters
----------
network : nengo.Network instance or None
A network object to the built and then simulated.
If a fully built ``model`` is passed in, then you can skip
building the network by passing in network=None.
dt : float, optional
The length of a simulator timestep, in seconds.
seed : int, optional
A seed for all stochastic operators used in this simulator.
model : nengo.builder.Model instance or None, optional
A model object that contains build artifacts to be simulated.
Usually the simulator will build this model for you; however,
if you want to build the network manually, or to inject some
build artifacts in the Model before building the network,
then you can pass in a ``nengo.builder.Model`` instance.
"""
self.closed = False
if model is None:
dt = float(dt) # make sure it's a float (for division purposes)
self.model = Model(dt=dt,
label="%s, dt=%f" % (network, dt),
decoder_cache=get_default_decoder_cache())
else:
self.model = model
if network is not None:
# Build the network into the model
self.model.build(network)
self.model.decoder_cache.shrink()
# -- map from Signal.base -> ndarray
self.signals = SignalDict()
for op in self.model.operators:
op.init_signals(self.signals)
# Order the steps (they are made in `Simulator.reset`)
self.dg = operator_depencency_graph(self.model.operators)
self._step_order = [op for op in toposort(self.dg)
if hasattr(op, 'make_step')]
# Add built states to the probe dictionary
self._probe_outputs = self.model.params
# Provide a nicer interface to probe outputs
self.data = ProbeDict(self._probe_outputs)
seed = np.random.randint(npext.maxint) if seed is None else seed
self.reset(seed=seed)
def __del__(self):
"""Raise a ResourceWarning if we are deallocated while open."""
if not self.closed:
warnings.warn(
"Simulator with model=%s was deallocated while open. Please "
"close simulators manually to ensure resources are properly "
"freed." % self.model, ResourceWarning)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def dt(self):
#.........这里部分代码省略.........