Nengo backend API¶
Nengo is designed so that models created with the Nengo frontend API work on a variety of different simulators, or “backends.” For example, backends have been created to take advantage of GPUs and neuromorphic hardware.
Reference backend¶
Reference simulator for Nengo models. |
|
Data structure used to access simulation data from the model. |
-
class
nengo.
Simulator
(network, dt=0.001, seed=None, model=None, progress_bar=True, optimize=True)[source]¶ 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 therun
method, and access probed data through thedata
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 thewith
syntax:with nengo.Network() as net: ensemble = nengo.Ensemble(10, 1) with nengo.Simulator(net, progress_bar=False) as sim: sim.run(0.1)
Note that the
data
attribute is still accessible even when a simulator has been closed. Running the simulator, however, will raise an error.When debugging or comparing models, it can be helpful to see the full ordered list of operators that the simulator will execute on each timestep.
with nengo.Simulator(nengo.Network(), progress_bar=False) as sim: print('\n'.join(f"* {op}" for op in sim.step_order))
* TimeUpdate{}
The diff of two simulators’ sorted ops tells us how two built models differ. We can use
difflib
in the Python standard library to see the differences.# Original model with nengo.Network() as net: ensemble = nengo.Ensemble(10, 1, label="Ensemble") sim1 = nengo.Simulator(net, progress_bar=False) # Add a node with net: node = nengo.Node(output=0, label="Node") nengo.Connection(node, ensemble) sim2 = nengo.Simulator(net, progress_bar=False) import difflib print("".join(difflib.unified_diff( sorted(f"{type(op).__name__}: {op.tag}\n" for op in sim1.step_order), sorted(f"{type(op).__name__}: {op.tag}\n" for op in sim2.step_order), fromfile="sim1", tofile="sim2", n=0, )).strip()) sim1.close() sim2.close()
--- sim1 +++ sim2 @@ -0,0 +1 @@ +Copy: <Connection from <Node 'Node'> to <Ensemble 'Ensemble'>> @@ -4,0 +6 @@ +SimProcess: Lowpass(tau=0.005)
- Parameters
- networkNetwork or None
A network object to be built and then simulated. If None, then a
Model
with the build model must be provided instead.- dtfloat, optional
The length of a simulator timestep, in seconds.
- seedint, optional
A seed for all stochastic operators used in this simulator. Will be set to
network.seed + 1
if not given.- modelModel, optional
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 aModel
instance.- progress_barbool or ProgressBar, optional
Progress bar for displaying build and simulation progress.
If
True
, the default progress bar will be used. IfFalse
, the progress bar will be disabled. For more control over the progress bar, pass in aProgressBar
instance.- optimizebool, optional
If
True
, the builder will run an additional optimization step that can speed up simulations significantly at the cost of slower builds. If running models for very small amounts of time, passFalse
to disable the optimizer.
- Attributes
- closedbool
Whether the simulator has been closed. Once closed, it cannot be reopened.
- dataSimulationData
The
SimulationData
mapping from Nengo objects to the data associated with those objects. In particular, eachProbe
maps to the data probed while running the simulation.- dgdict
A dependency graph mapping from each
Operator
to the operators that depend on that operator.- modelModel
The
Model
containing the signals and operators necessary to simulate the network.- signalsSignalDict
The
SignalDict
mapping fromSignal
instances to NumPy arrays.
-
property
dt
¶ (float) The time step of the simulator.
-
property
n_steps
¶ (int) The current time step of the simulator.
-
property
step_order
¶ (list) The ordered list of step functions run by this simulator.
-
property
time
¶ (float) The current time of the simulator.
-
close
()[source]¶ Closes the simulator.
Any call to
Simulator.run
,Simulator.run_steps
,Simulator.step
, andSimulator.reset
on a closed simulator raises aSimulatorClosed
exception.
-
reset
(seed=None)[source]¶ Reset the simulator state.
- Parameters
- seedint, optional
A seed for all stochastic operators used in the simulator. This will change the random sequences generated for noise or inputs (e.g. from processes), but not the built objects (e.g. ensembles, connections).
-
run
(time_in_seconds, progress_bar=None)[source]¶ Simulate for the given length of time.
If the given length of time is not a multiple of
dt
, it will be rounded to the nearestdt
. For example, ifdt
is 0.001 andrun
is called withtime_in_seconds=0.0006
, the simulator will advance one timestep, resulting in the actual simulator time being 0.001.The given length of time must be positive. The simulator cannot be run backwards.
- Parameters
- time_in_secondsfloat
Amount of time to run the simulation for. Must be positive.
- progress_barbool or ProgressBar, optional
Progress bar for displaying the progress of the simulation run.
If True, the default progress bar will be used. If False, the progress bar will be disabled. For more control over the progress bar, pass in a
ProgressBar
instance.
-
run_steps
(steps, progress_bar=None)[source]¶ Simulate for the given number of
dt
steps.- Parameters
- stepsint
Number of steps to run the simulation for.
- progress_barbool or ProgressBar, optional
Progress bar for displaying the progress of the simulation run.
If True, the default progress bar will be used. If False, the progress bar will be disabled. For more control over the progress bar, pass in a
ProgressBar
instance.
-
trange
(dt=None, sample_every=None)[source]¶ Create a vector of times matching probed data.
Note that the range does not start at 0 as one might expect, but at the first timestep (i.e.,
dt
).- Parameters
- sample_everyfloat, optional
The sampling period of the probe to create a range for. If None, a time value for every
dt
will be produced.Changed in version 3.0.0: Renamed from dt to sample_every
-
class
nengo.simulator.
SimulationData
(raw)[source]¶ Data structure used to access simulation data from the model.
The main use case for this is to access Probe data; for example,
probe_data = sim.data[my_probe]
. However, it is also used to access the parameters of objects in the model; for example, encoder values for an ensemble can be accessed viaencoders = sim.data[my_ens].encoders
.This is like a view on the raw simulation data manipulated by the Simulator, which allows the raw simulation data to be optimized for speed while this provides a more user-friendly interface.
Changed in version 3.0.0: Renamed from ProbeDict to SimulationData
The build process¶
The build process translates a Nengo model
to a set of data buffers (Signal
instances)
and computational operations (Operator
instances)
which implement the Nengo model
defined with the frontend API.
The build process is central to
how the reference simulator works,
and details how Nengo can be extended to include
new neuron types, learning rules, and other components.
Bekolay et al., 2014 provides a high-level description of the build process. For lower-level details and reference documentation, read on.
Stores artifacts from the build process, which are used by |
|
Manages the build functions known to the Nengo build process. |
-
class
nengo.builder.
Model
(dt=0.001, label=None, decoder_cache=None, builder=None)[source]¶ Stores artifacts from the build process, which are used by
Simulator
.- Parameters
- dtfloat, optional
The length of a simulator timestep, in seconds.
- labelstr, optional
A name or description to differentiate models.
- decoder_cacheDecoderCache, optional
Interface to a cache for expensive parts of the build process.
- builder
nengo.builder.Builder
, optional A
Builder
instance to use for building. Defaults to a newBuilder()
.
- Attributes
- configConfig or None
Build functions can set a config object here to affect sub-builders.
- decoder_cacheDecoderCache
Interface to a cache for expensive parts of the build process.
- dtfloat
The length of each timestep, in seconds.
- labelstr or None
A name or description to differentiate models.
- operatorslist
List of all operators created in the build process. All operators must be added to this list, as it is used by Simulator.
- paramsdict
Mapping from objects to namedtuples containing parameters generated in the build process.
- probeslist
List of all probes. Probes must be added to this list in the build process, as this list is used by Simulator.
- seededdict
All objects are assigned a seed, whether the user defined the seed or it was automatically generated. ‘seeded’ keeps track of whether the seed is user-defined. We consider the seed to be user-defined if it was set directly on the object, or if a seed was set on the network in which the object resides, or if a seed was set on any ancestor network of the network in which the object resides.
- seedsdict
Mapping from objects to the integer seed assigned to that object.
- sigdict
A dictionary of dictionaries that organizes all of the signals created in the build process, as build functions often need to access signals created by other build functions.
- stepSignal
The current step (i.e., how many timesteps have occurred thus far).
- timeSignal
The current point in time.
- toplevelNetwork
The top-level network being built. This is sometimes useful for accessing network elements after build, or for the network builder to determine if it is the top-level network.
-
add_op
(op)[source]¶ Add an operator to the model.
In addition to adding the operator, this method performs additional error checking by calling the operator’s
make_step
function. Callingmake_step
catches errors early, such as when signals are not properly initialized, which aids debugging. For that reason, we recommend calling this method over directly accessing theoperators
attribute.
-
build
(obj, *args, **kwargs)[source]¶ Build an object into this model.
See
Builder.build
for more details.- Parameters
- objobject
The object to build into this model.
-
has_built
(obj)[source]¶ Returns true if the object has already been built in this model.
Note
Some objects (e.g. synapses) can be built multiple times, and therefore will always result in this method returning
False
even though they have been built.This check is implemented by checking if the object is in the
params
dictionary. Build function should therefore add themselves tomodel.params
if they cannot be built multiple times.- Parameters
- objobject
The object to query.
-
class
nengo.builder.
Builder
[source]¶ Manages the build functions known to the Nengo build process.
Consists of two class methods to encapsulate the build function registry. All build functions should use the
Builder.register
method as a decorator. For example:class MyRule(nengo.learning_rules.LearningRuleType): modifies = "decoders" ... @nengo.builder.Builder.register(MyRule) def build_my_rule(model, my_rule, rule): ...
registers a build function for
MyRule
objects.Build functions should not be called directly, but instead called through the
Model.build
method.Model.build
uses theBuilder.build
method to ensure that the correct build function is called based on the type of the object passed to it. For example, to build the learning rule typemy_rule
from above, do:with nengo.Network() as net: ens_a = nengo.Ensemble(10, 1) ens_b = nengo.Ensemble(10, 1) my_rule = MyRule() connection = nengo.Connection(ens_a, ens_b, learning_rule_type=my_rule) model = nengo.builder.Model() model.build(my_rule, connection.learning_rule)
This will call the
build_my_rule
function from above with the argumentsmodel, my_rule, connection.learning_rule
.- Attributes
- buildersdict
Mapping from types to the build function associated with that type.
-
classmethod
build
(model, obj, *args, **kwargs)[source]¶ Build
obj
intomodel
.This method looks up the appropriate build function for
obj
and calls it with the model and other arguments provided.Note that if a build function is not specified for a particular type (e.g.,
EnsembleArray
), the type’s method resolution order will be examined to look for superclasses with defined build functions (e.g.,Network
in the case ofEnsembleArray
).This indirection (calling
Builder.build
instead of the build function directly) enables users to augment the build process in their own models, rather than having to modify Nengo itself.In addition to the parameters listed below, further positional and keyword arguments will be passed unchanged into the build function.
- Parameters
- modelModel
The
Model
instance in which to store build artifacts.- objobject
The object to build into the model.
Basic operators¶
Operators represent calculations that will occur in the simulation.
This code adapted from sigops/operator.py and sigops/operators.py (https://github.com/jaberg/sigops). This modified code is included under the terms of their license:
Copyright (c) 2014, James Bergstra All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Base class for operator instances understood by Nengo. |
|
Updates the simulation step and time. |
|
Assign a constant value to a Signal. |
|
Assign the value of one signal to another, with optional slicing. |
|
Increment signal |
|
Checks if the dot product needs to be reshaped. |
|
Increment signal |
|
Like |
|
Increment signal Y by dot(A, X) using block sparse row format. |
|
Apply a Python function to a signal, with optional arguments. |
-
class
nengo.builder.
Operator
(tag=None)[source]¶ Base class for operator instances understood by Nengo.
During one simulator timestep, a
Signal
can experienceat most one set operator (optional)
any number of increments
any number of reads
at most one update
in this specific order.
A
set
defines the state of the signal at time \(t\), the start of the simulation timestep. That state can then be modified byincrement
operations. A signal’s state will only beread
after all increments are complete. The state is then finalized by anupdate
, which denotes the state that the signal should be at time \(t + dt\).Each operator must keep track of the signals that it manipulates, and which of these four types of manipulations is done to each signal so that the simulator can order all of the operators properly.
Note
There are intentionally no valid default values for the
reads
,sets
,incs
, andupdates
properties to ensure that subclasses explicitly set these values.- Parameters
- tagstr, optional
A label associated with the operator, for debugging purposes.
- Attributes
- tagstr or None
A label associated with the operator, for debugging purposes.
-
property
incs
¶ Signals incremented by this operator.
Increments will be applied after sets (if it is set), and before reads.
-
property
reads
¶ Signals that are read and not modified by this operator.
Reads occur after increments, and before updates.
-
property
sets
¶ Signals set by this operator.
Sets occur first, before increments. A signal that is set here cannot be set or updated by any other operator.
-
property
updates
¶ Signals updated by this operator.
Updates are the last operation to occur to a signal.
-
init_signals
(signals)[source]¶ Initialize the signals associated with this operator.
The signals will be initialized into
signals
. Operator subclasses that use extra buffers should create them here.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.operator.
TimeUpdate
(step, time, tag=None)[source]¶ Updates the simulation step and time.
Implements
step[...] += 1
andtime[...] = step * dt
.A separate operator is used (rather than a combination of
Copy
andDotInc
) so that other backends can manage these important parts of the simulation state separately from other signals.- Parameters
- stepSignal
The signal associated with the integer step counter.
- timeSignal
The signal associated with the time (a float, in seconds).
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[step, time]
incs
[]
reads
[]
updates
[]
- Attributes
- stepSignal
The signal associated with the integer step counter.
- tagstr or None
A label associated with the operator, for debugging purposes.
- timeSignal
The signal associated with the time (a float, in seconds).
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.operator.
Reset
(dst, value=0, tag=None)[source]¶ Assign a constant value to a Signal.
Implements
dst[...] = value
.- Parameters
- dstSignal
The Signal to reset.
- valuefloat, optional
The constant value to which
dst
is set.- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[dst]
incs
[]
reads
[]
updates
[]
- Attributes
- dstSignal
The Signal to reset.
- tagstr or None
A label associated with the operator, for debugging purposes.
- valuefloat
The constant value to which
dst
is set.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.operator.
Copy
(src, dst, src_slice=None, dst_slice=None, inc=False, tag=None)[source]¶ Assign the value of one signal to another, with optional slicing.
Implements:
dst[:] = src
dst[dst_slice] = src[src_slice]
(whendst_slice
orsrc_slice
is not None)dst[dst_slice] += src[src_slice]
(wheninc=True
)
- Parameters
- dstSignal
The signal that will be assigned to (set).
- srcSignal
The signal that will be copied (read).
- dst_sliceslice or list, optional
Slice or list of indices associated with
dst
.- src_sliceslice or list, optional
Slice or list of indices associated with
src
- incbool, optional
Whether this should be an increment rather than a copy.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[] if inc else [dst]
incs
[dst] if inc else []
reads
[src]
updates
[]
- Attributes
- dstSignal
The signal that will be assigned to (set).
- dst_slicelist or None
Indices associated with
dst
.- srcSignal
The signal that will be copied (read).
- src_slicelist or None
Indices associated with
src
.- tagstr or None
A label associated with the operator, for debugging purposes.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.operator.
ElementwiseInc
(A, X, Y, tag=None)[source]¶ Increment signal
Y
byA * X
(with broadcasting).Implements
Y[...] += A * X
.- Parameters
- ASignal
The first signal to be multiplied.
- XSignal
The second signal to be multiplied.
- YSignal
The signal to be incremented.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[Y]
reads
[A, X]
updates
[]
- Attributes
- ASignal
The first signal to be multiplied.
- tagstr or None
A label associated with the operator, for debugging purposes.
- XSignal
The second signal to be multiplied.
- YSignal
The signal to be incremented.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
nengo.builder.operator.
reshape_dot
(A, X, Y, tag=None)[source]¶ Checks if the dot product needs to be reshaped.
Also does a bunch of error checking based on the shapes of A and X.
-
class
nengo.builder.operator.
DotInc
(A, X, Y, reshape=None, tag=None)[source]¶ Increment signal
Y
bydot(A, X)
.Implements
Y[...] += np.dot(A, X)
.Note
Currently, this only supports matrix-vector multiplies for compatibility with NengoOCL.
- Parameters
- ASignal
The first signal to be multiplied (a matrix).
- XSignal
The second signal to be multiplied (a vector).
- YSignal
The signal to be incremented.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[Y]
reads
[A, X]
updates
[]
- Attributes
- ASignal
The first signal to be multiplied.
- tagstr or None
A label associated with the operator, for debugging purposes.
- XSignal
The second signal to be multiplied.
- YSignal
The signal to be incremented.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.operator.
SparseDotInc
(A, X, Y, tag=None)[source]¶ Like
DotInc
butA
is a sparse matrix.New in version 3.0.0.
-
class
nengo.builder.operator.
BsrDotInc
(A, X, Y, indices, indptr, reshape=None, tag=None)[source]¶ Increment signal Y by dot(A, X) using block sparse row format.
Implements
Y[...] += np.dot(A, X)
, whereA
is an instance ofscipy.sparse.bsr_matrix
.Note
Requires SciPy.
Note
Currently, this only supports matrix-vector multiplies for compatibility with NengoOCL.
- Parameters
- A(k, r, c) Signal
The signal providing the k data blocks with r rows and c columns.
- X(k * c) Signal
The signal providing the k column vectors to multiply with.
- Y(k * r) Signal
The signal providing the k column vectors to update.
- indicesndarray
Column indices, see
scipy.sparse.bsr_matrix
for details.- indptrndarray
Column index pointers, see
scipy.sparse.bsr_matrix
for details.- reshapebool
Whether to reshape the result.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[Y]
reads
[A, X]
updates
[]
- Attributes
- A(k, r, c) Signal
The signal providing the k data blocks with r rows and c columns.
- indicesndarray
Column indices, see
scipy.sparse.bsr_matrix
for details.- indptrndarray
Column index pointers, see
scipy.sparse.bsr_matrix
for details.- reshapebool
Whether to reshape the result.
- tagstr or None
A label associated with the operator, for debugging purposes.
- X(k * c) Signal
The signal providing the k column vectors to multiply with.
- Y(k * r) Signal
The signal providing the k column vectors to update.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.operator.
SimPyFunc
(output, fn, t, x, tag=None)[source]¶ Apply a Python function to a signal, with optional arguments.
Implements
output[...] = fn(*args)
whereargs
can include the current simulation timet
and an input signalx
.Note that
output
may also be None, in which case the function is called but no output is captured.- Parameters
- outputSignal or None
The signal to be set. If None, the function is still called.
- fncallable
The function to call.
- tSignal or None
The signal associated with the time (a float, in seconds). If None, the time will not be passed to
fn
.- xSignal or None
An input signal to pass to
fn
. If None, an input signal will not be passed tofn
.- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[] if output is None else [output]
incs
[]
reads
([] if t is None else [t]) + ([] if x is None else [x])
updates
[]
- Attributes
- fncallable
The function to call.
- outputSignal or None
The signal to be set. If None, the function is still called.
- tSignal or None
The signal associated with the time (a float, in seconds). If None, the time will not be passed to
fn
.- tagstr or None
A label associated with the operator, for debugging purposes.
- xSignal or None
An input signal to pass to
fn
. If None, an input signal will not be passed tofn
.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
Signals¶
Check if |
|
Represents data or views onto data within a Nengo simulation. |
|
Map from Signal -> ndarray. |
-
class
nengo.builder.
Signal
(initial_value=None, shape=None, name=None, base=None, readonly=False, offset=0)[source]¶ Represents data or views onto data within a Nengo simulation.
Signals are tightly coupled to NumPy arrays, which is how live data is represented in a Nengo simulation. Signals provide a view onto the important metadata of the live NumPy array, and maintain the original value of the array in order to reset the simulation to the initial state.
- Parameters
- initial_valuearray_like
The initial value of the signal. Much of the metadata tracked by the Signal is based on this array as well (e.g., dtype).
- namestr, optional
Name of the signal. Primarily used for debugging. If None, the memory location of the Signal will be used.
- baseSignal, optional
The base signal, if this signal is a view on another signal. Linking the two signals with the
base
argument is necessary to ensure that their live data is also linked.- readonlybool, optional
Whether this signal and its related live data should be marked as readonly. Writing to these arrays will raise an exception.
- offsetint, optional
For a signal view this gives the offset of the view from the base
initial_value
in bytes. This might differ from the offset of the NumPy array view provided asinitial_value
if the base is a view already (in which case the signal base offset will be 0 because it starts where the view starts. That NumPy view can have an offset of itself).
-
property
base
¶ (Signal) The base signal, if this signal is a view.
Linking the two signals with the
base
argument is necessary to ensure that their live data is also linked.
-
property
dtype
¶ (numpy.dtype) Data type of the signal (e.g., float64).
-
property
elemoffset
¶ (int) Offset of data from base in elements.
-
property
elemstrides
¶ (int) Strides of data in elements.
-
property
initial_value
¶ (numpy.ndarray) Initial value of the signal.
Much of the metadata tracked by the Signal is based on this array as well (e.g., dtype).
-
property
is_view
¶ (bool) True if this Signal is a view on another Signal.
-
property
itemsize
¶ (int) Size of an array element in bytes.
-
property
name
¶ (str) Name of the signal. Primarily used for debugging.
-
property
nbytes
¶ (int) Number of bytes consumed by the signal.
-
property
ndim
¶ (int) Number of array dimensions.
-
property
offset
¶ (int) Offset of data from base in bytes.
For a signal view this gives the offset of the view from the base
initial_value
in bytes. This might differ from the offset of the NumPy array view provided asinitial_value
if the base is a view already (in which case the signal base offset will be 0 because it starts where the view starts. That NumPy view can have an offset of itself).
-
property
readonly
¶ (bool) Whether associated live data can be changed.
-
property
shape
¶ (tuple) Tuple of array dimensions.
-
property
size
¶ (int) Total number of elements.
-
property
strides
¶ (tuple) Strides of data in bytes.
-
property
sparse
¶ (bool) Whether the signal is sparse.
Determine if two signals might overlap in memory.
This comparison is not exact and errs on the side of false positives. See
numpy.may_share_memory
for more details.- Parameters
- otherSignal
The other signal we are investigating.
-
reshape
(*shape)[source]¶ Return a view on this signal with a different shape.
Note that
reshape
cannot change the overall size of the signal. Seenumpy.reshape
for more details.Any number of integers can be passed to this method, describing the desired shape of the returned signal.
-
class
nengo.builder.signal.
SignalDict
[source]¶ Map from Signal -> ndarray.
This dict subclass ensures that the ndarray values aren’t overwritten, and instead data are written into them, which ensures that these arrays never get copied, which wastes time and space.
Use
init
to set the ndarray initially.
Network builder¶
Builds a |
|
Populate seeding dictionaries for all objects in a network. |
-
nengo.builder.network.
build_network
(model, network, progress=None)[source]¶ Builds a
Network
object into a model.The network builder does this by mapping each high-level object to its associated signals and operators one-by-one, in the following order:
Ensembles, nodes, neurons
Subnetworks (recursively)
Connections, learning rules
Probes
Before calling any of the individual objects’ build functions, random number seeds are assigned to objects that did not have a seed explicitly set by the user. Whether the seed was assigned manually or automatically is tracked, and the decoder cache is only used when the seed is assigned manually.
- Parameters
- modelModel
The model to build into.
- networkNetwork
The network to build.
- progressProgress, optional
Object used to track the build progress.
Note that this will only affect top-level networks.
Notes
Sets
model.params[network]
toNone
.
-
nengo.builder.network.
seed_network
(network, seeds, seeded, base_rng=numpy.random)[source]¶ Populate seeding dictionaries for all objects in a network.
This includes all subnetworks.
New in version 3.0.0.
- Parameters
- networkNetwork
The network containing all objects to set seeds for.
- seeds{object: int}
Pre-existing map from objects to seeds for those objects. Will be modified in-place, but entries will not be overwritten if already set.
- seeded{object: bool}
Pre-existing map from objects to a boolean indicating whether they have a fixed seed either themselves or from a parent network (True), or whether the seed is randomly generated (False). Will be modified in-place, but entries will not be overwritten if already set.
- base_rngnp.random.RandomState
Random number generator to use to set the seeds.
Connection builder¶
Collects the parameters generated in |
|
Get evaluation points for connection. |
|
Get target points for connection with given evaluation points. |
|
Get all arrays needed to compute decoders. |
|
Compute decoders for connection. |
|
Solver for decoders. |
|
Apply a slice operation to given signal. |
|
Apply decoder solver to connection. |
|
Special builder for NoSolver to skip unnecessary steps. |
|
Builds a |
-
class
nengo.builder.connection.
BuiltConnection
(eval_points, solver_info, weights, transform)[source]¶ Collects the parameters generated in
build_connection
.These are stored here because in the majority of cases the equivalent attribute in the original connection is a
Distribution
. The attributes of a BuiltConnection are the full NumPy arrays used in the simulation.See the
Connection
documentation for more details on each parameter.- Parameters
- eval_pointsndarray
Evaluation points.
- solver_infodict
Information dictionary returned by the
Solver
.- weightsndarray
Connection weights. May be synaptic connection weights defined in the connection’s transform, or a combination of the decoders automatically solved for and the specified transform.
- transformndarray
The transform matrix.
Create new instance of BuiltConnection(eval_points, solver_info, weights, transform)
-
nengo.builder.connection.
get_eval_points
(model, conn, rng)[source]¶ Get evaluation points for connection.
-
nengo.builder.connection.
get_targets
(conn, eval_points, dtype=None)[source]¶ Get target points for connection with given evaluation points.
-
nengo.builder.connection.
build_linear_system
(model, conn, rng)[source]¶ Get all arrays needed to compute decoders.
-
nengo.builder.connection.
solve_for_decoders
(conn, gain, bias, x, targets, rng)[source]¶ Solver for decoders.
Factored out from
build_decoders
for use with the cache system.
-
nengo.builder.connection.
slice_signal
(model, signal, sl)[source]¶ Apply a slice operation to given signal.
-
nengo.builder.connection.
build_solver
(model, solver, conn, rng)[source]¶ Apply decoder solver to connection.
-
nengo.builder.connection.
build_no_solver
(model, solver, conn, rng)[source]¶ Special builder for NoSolver to skip unnecessary steps.
-
nengo.builder.connection.
build_connection
(model, conn)[source]¶ Builds a
Connection
object into a model.A brief summary of what happens in the connection build process, in order:
Solve for decoders.
Combine transform matrix with decoders to get weights.
Add operators for computing the function or multiplying neural activity by weights.
Call build function for the synapse.
Call build function for the learning rule.
Add operator for applying learning rule delta to weights.
Some of these steps may be altered or omitted depending on the parameters of the connection, in particular the pre and post types.
- Parameters
- modelModel
The model to build into.
- connConnection
The connection to build.
Notes
Sets
model.params[conn]
to aBuiltConnection
instance.
Ensemble builder¶
Collects the parameters generated in |
|
Generate evaluation points for ensemble. |
|
Get output of ensemble neurons for given evaluation points. |
|
Compute concrete gain and bias for ensemble. |
|
Builds an |
-
class
nengo.builder.ensemble.
BuiltEnsemble
(eval_points, encoders, intercepts, max_rates, scaled_encoders, gain, bias)[source]¶ Collects the parameters generated in
build_ensemble
.These are stored here because in the majority of cases the equivalent attribute in the original ensemble is a
Distribution
. The attributes of a BuiltEnsemble are the full NumPy arrays used in the simulation.See the
Ensemble
documentation for more details on each parameter.- Parameters
- eval_pointsndarray
Evaluation points.
- encodersndarray
Normalized encoders.
- interceptsndarray
X-intercept of each neuron.
- max_ratesndarray
Maximum firing rates for each neuron.
- scaled_encodersndarray
Normalized encoders scaled by the gain and radius. This quantity is used in the actual simulation, unlike
encoders
.- gainndarray
Gain of each neuron.
- biasndarray
Bias current injected into each neuron.
Create new instance of BuiltEnsemble(eval_points, encoders, intercepts, max_rates, scaled_encoders, gain, bias)
-
nengo.builder.ensemble.
gen_eval_points
(ens, eval_points, rng, scale_eval_points=True, dtype=None)[source]¶ Generate evaluation points for ensemble.
-
nengo.builder.ensemble.
get_activities
(built_ens, ens, eval_points)[source]¶ Get output of ensemble neurons for given evaluation points.
-
nengo.builder.ensemble.
get_gain_bias
(ens, rng=numpy.random, dtype=None)[source]¶ Compute concrete gain and bias for ensemble.
-
nengo.builder.ensemble.
build_ensemble
(model, ens)[source]¶ Builds an
Ensemble
object into a model.A brief summary of what happens in the ensemble build process, in order:
Generate evaluation points and encoders.
Normalize encoders to unit length.
Determine bias and gain.
Create neuron input signal
Add operator for injecting bias.
Call build function for neuron type.
Scale encoders by gain and radius.
Add operators for multiplying decoded input signal by encoders and incrementing the result in the neuron input signal.
Call build function for injected noise.
Some of these steps may be altered or omitted depending on the parameters of the ensemble, in particular the neuron type. For example, most steps are omitted for the
Direct
neuron type.- Parameters
- modelModel
The model to build into.
- ensEnsemble
The ensemble to build.
Notes
Sets
model.params[ens]
to aBuiltEnsemble
instance.
Learning rule builders¶
Calculate connection weight change according to the PES rule. |
|
Calculate connection weight change according to the BCM rule. |
|
Calculate connection weight change according to the Oja rule. |
|
Simulates a simplified version of Oja’s rule in the vector space. |
|
Calculate connection weight change according to the RLS rule. |
|
Get the input |
|
Get the output |
|
Builds the obj on signal, or returns the signal if obj is None. |
|
Builds a |
|
Builds a |
|
Builds a |
|
Builds a |
|
Builds a |
|
Builds an |
-
class
nengo.builder.learning_rules.
SimPES
(pre_filtered, error, delta, learning_rate, tag=None)[source]¶ Calculate connection weight change according to the PES rule.
Implements the PES learning rule of the form
\[\Delta \omega_{ij} = \frac{\kappa}{n} e_j a_i\]where
\(\kappa\) is a scalar learning rate,
\(n\) is the number of presynaptic neurons
\(e_j\) is the error for the jth output dimension, and
\(a_i\) is the activity of a presynaptic neuron.
New in version 3.0.0.
- Parameters
- pre_filteredSignal
The presynaptic activity, \(a_i\).
- errorSignal
The error signal, \(e_j\).
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate, \(\kappa\).
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[]
reads
[pre_filtered, error]
updates
[delta]
- Attributes
- pre_filteredSignal
The presynaptic activity, \(a_i\).
- errorSignal
The error signal, \(e_j\).
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate, \(\kappa\).
- tagstr, optional
A label associated with the operator, for debugging purposes.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.learning_rules.
SimBCM
(pre_filtered, post_filtered, theta, delta, learning_rate, tag=None)[source]¶ Calculate connection weight change according to the BCM rule.
Implements the Bienenstock-Cooper-Munroe learning rule of the form
\[\Delta \omega_{ij} = \kappa a_j (a_j - \theta_j) a_i\]where
\(\kappa\) is a scalar learning rate,
\(a_j\) is the activity of a postsynaptic neuron,
\(\theta_j\) is an estimate of the average \(a_j\), and
\(a_i\) is the activity of a presynaptic neuron.
- Parameters
- pre_filteredSignal
The presynaptic activity, \(a_i\).
- post_filteredSignal
The postsynaptic activity, \(a_j\).
- thetaSignal
The modification threshold, \(\theta_j\).
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate, \(\kappa\).
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[]
reads
[pre_filtered, post_filtered, theta]
updates
[delta]
- Attributes
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate, \(\kappa\).
- post_filteredSignal
The postsynaptic activity, \(a_j\).
- pre_filteredSignal
The presynaptic activity, \(a_i\).
- tagstr or None
A label associated with the operator, for debugging purposes.
- thetaSignal
The modification threshold, \(\theta_j\).
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.learning_rules.
SimOja
(pre_filtered, post_filtered, weights, delta, learning_rate, beta, tag=None)[source]¶ Calculate connection weight change according to the Oja rule.
Implements the Oja learning rule of the form
\[\Delta \omega_{ij} = \kappa (a_i a_j - \beta a_j^2 \omega_{ij})\]where
\(\kappa\) is a scalar learning rate,
\(a_i\) is the activity of a presynaptic neuron,
\(a_j\) is the activity of a postsynaptic neuron,
\(\beta\) is a scalar forgetting rate, and
\(\omega_{ij}\) is the connection weight between the two neurons.
- Parameters
- pre_filteredSignal
The presynaptic activity, \(a_i\).
- post_filteredSignal
The postsynaptic activity, \(a_j\).
- weightsSignal
The connection weight matrix, \(\omega_{ij}\).
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate, \(\kappa\).
- betafloat
The scalar forgetting rate, \(\beta\).
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[]
reads
[pre_filtered, post_filtered, weights]
updates
[delta]
- Attributes
- betafloat
The scalar forgetting rate, \(\beta\).
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate, \(\kappa\).
- post_filteredSignal
The postsynaptic activity, \(a_j\).
- pre_filteredSignal
The presynaptic activity, \(a_i\).
- tagstr or None
A label associated with the operator, for debugging purposes.
- weightsSignal
The connection weight matrix, \(\omega_{ij}\).
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.learning_rules.
SimVoja
(pre_decoded, post_filtered, scaled_encoders, delta, scale, learning_signal, learning_rate, tag=None)[source]¶ Simulates a simplified version of Oja’s rule in the vector space.
See Learning new associations for details.
- Parameters
- pre_decodedSignal
Decoded activity from presynaptic ensemble, \(a_i\).
- post_filteredSignal
Filtered postsynaptic activity signal.
- scaled_encodersSignal
2d array of encoders, multiplied by
scale
.- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- scalendarray
The length of each encoder.
- learning_signalSignal
Scalar signal to be multiplied by
learning_rate
. Expected to be either 0 or 1 to turn learning off or on, respectively.- learning_ratefloat
The scalar learning rate.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[]
reads
[pre_decoded, post_filtered, scaled_encoders, learning_signal]
updates
[delta]
- Attributes
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ij}\).
- learning_ratefloat
The scalar learning rate.
- learning_signalSignal
Scalar signal to be multiplied by
learning_rate
. Expected to be either 0 or 1 to turn learning off or on, respectively.- post_filteredSignal
Filtered postsynaptic activity signal.
- pre_decodedSignal
Decoded activity from presynaptic ensemble, \(a_i\).
- scalendarray
The length of each encoder.
- scaled_encodersSignal
2d array of encoders, multiplied by
scale
.- tagstr or None
A label associated with the operator, for debugging purposes.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.learning_rules.
SimRLS
(pre_filtered, error, delta, inv_gamma, tag=None)[source]¶ Calculate connection weight change according to the RLS rule.
Implements the Recursive Least Squares (RLS) learning rule of the form
\[\begin{split}g_i &= \sum_j P_{ij}(n-1) r_i \\ P_{ij}(n) &= P_{ij}(n-1) - g_i g_j / \left( 1 + \sum_{ij} r_i P_{ij}(n-1) r_j \right) \\ \Delta \omega_{ji} &= \frac{\kappa \delta_t}{n} e_j \sum_{k} P_{ik}(n) r_k\end{split}\]where \(r_i\) are the filtered presynaptic activities, \(e_j\) are the errors, \(\kappa\) is the learning rate, \(\delta_t\) is the simulator timestep, and \(n\) is the number of presynaptic neurons.
- Parameters
- pre_filteredSignal
The filtered presynaptic activity, \(r_i\).
- errorSignal
The error signal, \(e_j\).
- deltaSignal
The synaptic weight change to be applied, \(\Delta \omega_{ji}\).
- inv_gammandarray
The inverse activity matrix \(P_{ij}\).
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[]
reads
[pre_filtered, error]
updates
[delta, inv_gamma]
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
nengo.builder.learning_rules.
build_or_passthrough
(model, obj, signal)[source]¶ Builds the obj on signal, or returns the signal if obj is None.
-
nengo.builder.learning_rules.
build_learning_rule
(model, rule)[source]¶ Builds a
LearningRule
object into a model.A brief summary of what happens in the learning rule build process, in order:
Create a delta signal for the weight change.
Add an operator to increment the weights by delta.
Call build function for the learning rule type.
The learning rule system is designed to work with multiple learning rules on the same connection. If only one learning rule was to be applied to the connection, then we could directly modify the weights, rather than calculating the delta here and applying it in
build_connection
. However, with multiple learning rules, we must isolate each delta signal in case calculating the delta depends on the weights themselves, making the calculation depend on the order of the learning rule evaluations.- Parameters
- modelModel
The model to build into.
- ruleLearningRule
The learning rule to build.
Notes
Sets
model.params[rule]
toNone
.
-
nengo.builder.learning_rules.
build_bcm
(model, bcm, rule)[source]¶ Builds a
BCM
object into a model.Calls synapse build functions to filter the pre and post activities, and adds a
SimBCM
operator to the model to calculate the delta.- Parameters
- modelModel
The model to build into.
- bcmBCM
Learning rule type to build.
- ruleLearningRule
The learning rule object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameBCM
instance.
-
nengo.builder.learning_rules.
build_oja
(model, oja, rule)[source]¶ Builds a
BCM
object into a model.Calls synapse build functions to filter the pre and post activities, and adds a
SimOja
operator to the model to calculate the delta.- Parameters
- modelModel
The model to build into.
- ojaOja
Learning rule type to build.
- ruleLearningRule
The learning rule object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameOja
instance.
-
nengo.builder.learning_rules.
build_voja
(model, voja, rule)[source]¶ Builds a
Voja
object into a model.Calls synapse build functions to filter the post activities, and adds a
SimVoja
operator to the model to calculate the delta.- Parameters
- modelModel
The model to build into.
- vojaVoja
Learning rule type to build.
- ruleLearningRule
The learning rule object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameVoja
instance.
-
nengo.builder.learning_rules.
build_pes
(model, pes, rule)[source]¶ Builds a
PES
object into a model.Calls synapse build functions to filter the pre activities, and adds a
SimPES
operator to the model to calculate the delta.- Parameters
- modelModel
The model to build into.
- pesPES
Learning rule type to build.
- ruleLearningRule
The learning rule object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the samePES
instance.
-
nengo.builder.learning_rules.
build_rls
(model, rls, rule)[source]¶ Builds an
RLS
(Recursive Least Squares) object into a model.Calls synapse build functions to filter the pre activities, and adds a
SimRLS
operator to the model to calculate the delta.- Parameters
- modelModel
The model to build into.
- rlsRLS
Learning rule type to build.
- ruleLearningRule
The learning rule object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameRLS
instance.
Neuron builders¶
Set a neuron model output for the given input current. |
|
Builds a |
|
Builds a |
-
class
nengo.builder.neurons.
SimNeurons
(neurons, J, output, state=None, tag=None)[source]¶ Set a neuron model output for the given input current.
Implements
neurons.step(dt, J, **state)
.- Parameters
- neuronsNeuronType
The
NeuronType
, which defines astep
function.- JSignal
The input current.
- outputSignal
The neuron output signal that will be set
- statelist, optional
A list of additional neuron state signals set by
step
.- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[output] + state
incs
[]
reads
[J]
updates
[]
- Attributes
- JSignal
The input current.
- neuronsNeuronType
The
NeuronType
, which defines astep
function.- outputSignal
The neuron output signal that will be set.
- statelist
A list of additional neuron state signals set by
step
.- tagstr or None
A label associated with the operator, for debugging purposes.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
nengo.builder.neurons.
build_neurons
(model, neurontype, neurons, input_sig=None, output_sig=None)[source]¶ Builds a
NeuronType
object into a model.This function adds a
SimNeurons
operator connecting the input current to the neural output signals, and handles any additional state variables defined within the neuron type.- Parameters
- modelModel
The model to build into.
- neurontypeNeuronType
Neuron type to build.
- neuronNeurons
The neuron population object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameNeuronType
instance.
-
nengo.builder.neurons.
build_rates_to_spikes
(model, neurontype, neurons)[source]¶ Builds a
RatesToSpikesNeuronType
object into a model.This function adds two
SimNeurons
operators. The first one handles simulating the base_type, converting input signals into rates. The second one takes those rates as input and emits spikes.- Parameters
- modelModel
The model to build into.
- neurontypeRatesToSpikesNeuronType
Neuron type to build.
- neuronNeurons
The neuron population object corresponding to the neuron type.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameNeuronType
instance.
Node builder¶
Builds a |
-
nengo.builder.node.
build_node
(model, node)[source]¶ Builds a
Node
object into a model.The node build function is relatively simple. It involves creating input and output signals, and connecting them with an
Operator
that depends on the type ofnode.output
.- Parameters
- modelModel
The model to build into.
- nodeNode
The node to build.
Notes
Sets
model.params[node]
toNone
.
Probe builder¶
Mark a signal as being probed. |
|
Build a “connection” probe type. |
|
Build a “signal” probe type. |
|
Builds a |
-
class
nengo.builder.probe.
SimProbe
(signal, tag=None)[source]¶ Mark a signal as being probed.
This performs no computations, but marks
signal
as being read. This is necessary for the rare case in which a node with constant output is probed directly without that signal being otherwise used.- Parameters
- signalSignal
The probed signal.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[]
reads
[signal]
updates
[]
-
property
signal
¶ The probed signal
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
nengo.builder.probe.
conn_probe
(model, probe)[source]¶ Build a “connection” probe type.
Connection probes create a connection from the target, and probe the resulting signal (used when you want to probe the default output of an object, which may not have a predefined signal).
-
nengo.builder.probe.
signal_probe
(model, key, probe)[source]¶ Build a “signal” probe type.
Signal probes directly probe a target signal.
-
nengo.builder.probe.
build_probe
(model, probe)[source]¶ Builds a
Probe
object into a model.Under the hood, there are two types of probes: connection probes and signal probes.
Connection probes are those that are built by creating a new
Connection
object from the probe’s target to the probe, and calling that connection’s build function. Creating and building a connection ensure that the result of probing the target’s attribute is the same as would result from that target being connected to another object.Signal probes are those that are built by finding the correct
Signal
in the model and calling the build function corresponding to the probe’s synapse.- Parameters
- modelModel
The model to build into.
- probeProbe
The connection to build.
Notes
Sets
model.params[probe]
to a list.Simulator
appends to that list when running a simulation.
Process builder¶
Simulate a process. |
|
Builds a |
-
class
nengo.builder.processes.
SimProcess
(process, input, output, t, mode='set', state=None, tag=None)[source]¶ Simulate a process.
- Parameters
- processProcess
The
Process
to simulate.- inputSignal or None
Input to the process, or None if no input.
- outputSignal or None
Output from the process, or None if no output.
- tSignal
The signal associated with the time (a float, in seconds).
- modestr, optional
Denotes what type of update this operator performs. Must be one of
'update'
,'inc'
or'set'
.- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[output] if output is not None and mode=='set' else []
incs
[output] if output is not None and mode=='inc' else []
reads
[t, input] if input is not None else [t]
updates
[output] if output is not None and mode=='update' else []
- Attributes
- inputSignal or None
Input to the process, or None if no input.
- modestr
Denotes what type of update this operator performs.
- outputSignal or None
Output from the process, or None if no output.
- processProcess
The
Process
to simulate.- tSignal
The signal associated with the time (a float, in seconds).
- tagstr or None
A label associated with the operator, for debugging purposes.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
nengo.builder.processes.
build_process
(model, process, sig_in=None, sig_out=None, mode='set')[source]¶ Builds a
Process
object into a model.- Parameters
- modelModel
The model to build into.
- processProcess
Process to build.
- sig_inSignal, optional
The input signal, or None if no input signal.
- sig_outSignal, optional
The output signal, or None if no output signal.
- mode“set” or “inc” or “update”, optional
The
mode
of the builtSimProcess
.
Notes
Does not modify
model.params[]
and can therefore be called more than once with the sameProcess
instance.
Transform builders¶
Matrix-matrix multiply, interpreting vectors as diagonal matrices. |
|
Build a |
|
Build a |
|
Build a |
|
Apply convolutional weights to input signal. |
|
Apply convolutional weights to input signal. |
|
Apply transposed convolutional weights to input signal. |
|
Build a |
-
nengo.builder.transforms.
multiply
(x, y)[source]¶ Matrix-matrix multiply, interpreting vectors as diagonal matrices.
-
nengo.builder.transforms.
build_dense
(model, transform, sig_in, decoders=None, encoders=None, rng=numpy.random)[source]¶ Build a
Dense
transform object.
-
nengo.builder.transforms.
build_sparse
(model, transform, sig_in, decoders=None, encoders=None, rng=numpy.random)[source]¶ Build a
Sparse
transform object.
-
nengo.builder.transforms.
build_convolution
(model, transform, sig_in, decoders=None, encoders=None, rng=numpy.random)[source]¶ Build a
Convolution
transform object.
-
class
nengo.builder.transforms.
GeneralConvInc
(W, X, Y, conv, tag=None)[source]¶ Apply convolutional weights to input signal.
New in version 3.2.0.
- Parameters
- WSignal
The convolutional weights (a.k.a. the kernel).
- XSignal
The input signal.
- YSignal
Output signal to be incremented.
- conv
Convolution
orConvolutionTranspose
The Convolution or ConvolutionTranspose transform being applied.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[Y]
reads
[W, X]
updates
[]
- Attributes
- WSignal
The convolutional weights.
- XSignal
The input signal.
- YSignal
Output signal to be incremented.
- conv
Convolution
orConvolutionTranspose
The Convolution or ConvolutionTranspose transform being applied.
- tagstr, optional
A label associated with the operator, for debugging purposes.
-
make_step
(signals, dt, rng)[source]¶ Returns a callable that performs the desired computation.
This method must be implemented by subclasses. To fully understand what an operator does, look at its implementation of
make_step
.- Parameters
- signalsSignalDict
A mapping from signals to their associated live ndarrays.
- dtfloat
Length of each simulation timestep, in seconds.
- rng
numpy.random.RandomState
Random number generator for stochastic operators.
-
class
nengo.builder.transforms.
ConvInc
(W, X, Y, conv, tag=None)[source]¶ Apply convolutional weights to input signal.
New in version 3.0.0.
- Parameters
- WSignal
The convolutional weights (a.k.a. the kernel).
- XSignal
The input signal.
- YSignal
Output signal to be incremented.
- conv
Convolution
The Convolution transform being applied.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[Y]
reads
[W, X]
updates
[]
- Attributes
- WSignal
The convolutional weights.
- XSignal
The input signal.
- YSignal
Output signal to be incremented.
- conv
Convolution
The Convolution transform being applied.
- tagstr, optional
A label associated with the operator, for debugging purposes.
-
class
nengo.builder.transforms.
ConvTransposeInc
(W, X, Y, conv, tag=None)[source]¶ Apply transposed convolutional weights to input signal.
New in version 3.2.0.
- Parameters
- WSignal
The convolutional weights (a.k.a. the kernel).
- XSignal
The input signal.
- YSignal
Output signal to be incremented.
- conv
ConvolutionTranspose
The ConvolutionTranspose transform being applied.
- tagstr, optional
A label associated with the operator, for debugging purposes.
Notes
sets
[]
incs
[Y]
reads
[W, X]
updates
[]
- Attributes
- WSignal
The convolutional weights.
- XSignal
The input signal.
- YSignal
Output signal to be incremented.
- conv
ConvolutionTranspose
The ConvolutionTranspose transform being applied.
- tagstr, optional
A label associated with the operator, for debugging purposes.
-
nengo.builder.transforms.
build_no_transform
(model, transform, sig_in, decoders=None, encoders=None, rng=numpy.random)[source]¶ Build a
NoTransform
transform object.
Decoder cache¶
Caching capabilities for a faster build process.
Get fragment size in cross-compatible way. |
|
Gets file stat, but fails gracefully in case of an OSError. |
|
Removes file, but fails gracefully in case of an OSError. |
|
Try to make directories, but continue on error. |
|
Check that array is a standard dtype. |
|
Check that all objects in list are fingerprintable. |
|
Check that all values in dict are fingerprintable. |
|
Check that all attributes of |
|
Fingerprint of an object instance. |
|
Cache index mapping keys to (filename, start, end) tuples. |
|
Writable cache index mapping keys to files. |
|
Cache for decoders. |
|
Provides the same interface as |
|
Get default decoder implementation based on config settings. |
-
class
nengo.cache.
Fingerprint
(obj)[source]¶ Fingerprint of an object instance.
A finger print is equal for two instances if and only if they are of the same type and have the same attributes.
The fingerprint will be used as identification for caching.
- Parameters
- objobject
Object to fingerprint.
Notes
Not all objects can be fingerprinted. In particular, custom classes are tricky to fingerprint as their implementation can change without changing its fingerprint, as the type and attributes may be the same.
In order to ensure that only safe object are fingerprinted, this class maintains class attribute
WHITELIST
that contains all types that can be safely fingerprinted.If you want your custom class to be fingerprinted, call the
whitelist
class method and pass in your class.- Attributes
- fingerprinthash
A unique fingerprint for the object instance.
-
class
nengo.cache.
CacheIndex
(cache_dir)[source]¶ Cache index mapping keys to (filename, start, end) tuples.
Once instantiated the cache index has to be used in a
with
block to allow access. The index will not be loaded before thewith
block is entered.This class only provides read access to the cache index. For write access use
WriteableCacheIndex
.- Parameters
- cache_dirstr
Path where the cache is stored.
Notes
Under the hood, the cache index is stored as a pickle file. The pickle file contains two objects which are read sequentially: the
version
tuple, and theindex
dictionary mapping keys to (filename, start, end) tuples.Examples
from nengo.cache import CacheIndex, WriteableCacheIndex to_cache = ("gotta cache 'em all", 151) # create index file with WriteableCacheIndex(cache_dir) as index: index[hash(to_cache)] = ("file1", 0, 1) # set an item # read from index with CacheIndex(cache_dir) as index: filename, start, end = index[hash(to_cache)]
- Attributes
- cache_dirstr
Path where the cache is stored.
- index_pathstr
Path to the cache index file.
- versiontuple
Version code of the loaded cache index. The first element gives the format of the cache and the second element gives the pickle protocol used to store the index. Note that a cache index will always be written in the newest version with the highest pickle protocol.
- VERSION (class attribute)int
Highest supported version, and version used to store the cache index.
-
class
nengo.cache.
WriteableCacheIndex
(cache_dir)[source]¶ Writable cache index mapping keys to files.
This class allows write access to the cache index.
The updated cache file will be written when the
with
block is exited. The initial read and the write on exit of thewith
block are locked against concurrent access with a file lock. The lock will be released within thewith
block.- Parameters
- cache_dirstr
Path where the cache is stored.
Examples
from nengo.cache import WriteableCacheIndex to_cache = ("gotta cache 'em all", 151) key = hash(to_cache) with WriteableCacheIndex(cache_dir) as index: index[key] = ("file1", 0, 1) # set an item del index[key] # remove an item by key index.remove_file_entry("file1") # remove an item by filename
-
class
nengo.cache.
DecoderCache
(readonly=False, cache_dir=None)[source]¶ Cache for decoders.
Hashes the arguments to the decoder solver and stores the result in a file which will be reused in later calls with the same arguments.
Be aware that decoders should not use any global state, but only values passed and attributes of the object instance. Otherwise the wrong solver results might get loaded from the cache.
- Parameters
- readonlybool
Indicates that already existing items in the cache will be used, but no new items will be written to the disk in case of a cache miss.
- cache_dirstr or None
Path to the directory in which the cache will be stored. It will be created if it does not exists. Will use the value returned by
get_default_dir
, ifNone
.
-
class
nengo.cache.
NoDecoderCache
[source]¶ Provides the same interface as
DecoderCache
without caching.
Optimizer¶
Operator graph optimizers.
Optimizes the operator graph by merging operators. |
|
Manages a single optimization pass. |
|
Analyze and store extra information about operators. |
|
Analyze and store extra information about a list of ops to be merged. |
|
Manages the op merge classes known to the optimizer. |
|
Base class for all op merge classes. |
|
Merge |
|
Merge |
|
Merge |
|
Merge |
|
Merge |
|
Merge signals. |
|
Groups the given list by the value returned by |
-
nengo.builder.optimizer.
optimize
(model, dg)[source]¶ Optimizes the operator graph by merging operators.
This reduces the number of iterators to iterate over in slow Python code (as opposed to fast C code). The resulting merged operators will also operate on larger chunks of sequential memory, making better use of CPU caching and prefetching.
The optimization algorithm has worst case complexity \(O(n^2 + e)\), where \(n\) is the number of operators and \(e\) is the number of edges in the dependency graph. In practice the run time will be much better because not all \(n^2\) pairwise combinations of operators will be evaluated. A grouping depending on the operator type and view bases is done with dictionaries. This grouping can be done in amortized linear time and reduces the actual worst-case runtime of the optimization algorithm to \(O(gm^2 + e)\), where \(g\) is the number of groups and \(m\) is the number of elements in a group. Moreover, information about memory alignment will be used to cut the inner loop short in many cases and gives a runtime much closer to linear in most cases.
Note that this function modifies both
model
anddg
.- Parameters
- model
nengo.builder.Model
Builder output to optimize.
- dgdict
Dict of the form
{a: {b, c}}
whereb
andc
depend ona
, specifying the operator dependency graph of the model.
- model
-
class
nengo.builder.optimizer.
OpMergePass
(dg)[source]¶ Manages a single optimization pass.
-
perform_merges
()[source]¶ Go through all operators and merge them where possible.
- Parameters
- only_merge_ops_with_viewbool
Limit merges to operators with views.
-
perform_merges_for_subset
(subset)[source]¶ Performs operator merges for a subset of operators.
- Parameters
- subsetlist
Subset of operators.
-
-
class
nengo.builder.optimizer.
OpsToMerge
(initial_op, merged, merged_dependents, dependents)[source]¶ Analyze and store extra information about a list of ops to be merged.
-
class
nengo.builder.optimizer.
OpMerger
[source]¶ Manages the op merge classes known to the optimizer.
-
class
nengo.builder.optimizer.
ElementwiseIncMerger
[source]¶ Merge
ElementwiseInc
ops.
-
class
nengo.builder.optimizer.
SimNeuronsMerger
[source]¶ Merge
SimNeurons
ops.
-
class
nengo.builder.optimizer.
SigMerger
[source]¶ Merge signals.
-
static
check
(signals, axis=0)[source]¶ Checks that all signals can be concatenated along a given axis.
For views, this includes also a check that the signals have a common base and agree on the strides.
In comparison to the
check_*
functions, this function does not throw exceptions and allows for either signals or signal views.
-
static
check_signals
(signals, axis=0)[source]¶ Checks that all signals can be merged along a given axis.
If this is not possible, or any signals are views, a
ValueError
will be raised.
-
static
check_views
(signals, axis=0)[source]¶ Checks that all signal views can be merged along a given axis.
If this is not possible, or any signals are not views, a
ValueError
will be raised.signals
must be ordered by the offset into the base signal.
-
static
merge
(signals, axis=0)[source]¶ Merges multiple signals or signal views into one contiguous signal.
Note that if any of the signals are linked to another signal (by being the base of a view), the merged signal will not reflect those links anymore.
- Parameters
- signalssequence
Signals to merge. Must not contain views.
- axisint, optional
Axis along which to concatenate the signals.
- Returns
- merged_signalSignal
The merged signal.
- replacementsdict
Dictionary mapping from the old signals to new signals that are a view into the merged signal. Used to replace old signals.
-
static
merge_signals
(signals, axis=0)[source]¶ Merges multiple signal into one contiguous signal.
Note that if any of the signals are linked to another signal (by being the base of a view), the merged signal will not reflect those links anymore.
- Parameters
- signalssequence
Signals to merge. Must not contain views.
- axisint, optional
Axis along which to concatenate the signals.
- Returns
- merged_signalSignal
The merged signal.
- replacementsdict
Dictionary mapping from the old signals to new signals that are a view into the merged signal. Used to replace old signals.
-
static
merge_views
(signals, axis=0)[source]¶ Merges multiple signal views into one contiguous signal view.
- Parameters
- signalssequence
Signals to merge. Must only contain views.
- axisint, optional
Axis along which to concatenate the signals.
- Returns
- merged_signalSignal
The merged signal.
- replacementsdict
Dictionary mapping from the old signals to new signals that are a view into the merged signal. Used to replace old signals.
-
static
Exceptions¶
Base class for Nengo exceptions. |
|
Base class for Nengo warnings. |
|
A ValueError encountered during validation of a parameter. |
|
A RuntimeError raised when an algorithm does not converge. |
|
A ValidationError occurring because a parameter is read-only. |
|
A ValueError encountered during the build process. |
|
A feature that has been removed in a backwards-incompatible way. |
|
A feature that has been moved elsewhere. |
|
A ValueError encountered in the config system. |
|
An error in how SPA keeps track of modules. |
|
An error encountered while parsing a SPA expression. |
|
Raised when attempting to run a closed simulator. |
|
An error encountered during simulation of the model. |
|
An error dealing with Signals in the builder. |
|
An error in fingerprinting an object for cache identification. |
|
An error with the Network context stack. |
|
Raised a requested network conversion cannot be done. |
|
An IO error in reading from or writing to the decoder cache. |
|
A timeout occurred while waiting for a resource. |
|
A NengoObject has not been added to a network. |
|
A non-critical issue in accessing files in the cache. |
-
exception
nengo.exceptions.
NengoException
[source]¶ Base class for Nengo exceptions.
NengoException instances should not be created; this base class exists so that all exceptions raised by Nengo can be caught in a try / except block.
-
exception
nengo.exceptions.
ValidationError
(msg, attr, obj=None)[source]¶ A ValueError encountered during validation of a parameter.
-
exception
nengo.exceptions.
ConvergenceError
[source]¶ A RuntimeError raised when an algorithm does not converge.
-
exception
nengo.exceptions.
ReadonlyError
(attr, obj=None, msg=None)[source]¶ A ValidationError occurring because a parameter is read-only.
-
exception
nengo.exceptions.
ObsoleteError
(msg, since=None, url=None)[source]¶ A feature that has been removed in a backwards-incompatible way.
-
exception
nengo.exceptions.
MovedError
(location=None)[source]¶ A feature that has been moved elsewhere.
New in version 3.0.0.
-
exception
nengo.exceptions.
SpaParseError
[source]¶ An error encountered while parsing a SPA expression.
-
exception
nengo.exceptions.
SimulatorClosed
[source]¶ Raised when attempting to run a closed simulator.
-
exception
nengo.exceptions.
SimulationError
[source]¶ An error encountered during simulation of the model.
-
exception
nengo.exceptions.
FingerprintError
[source]¶ An error in fingerprinting an object for cache identification.
-
exception
nengo.exceptions.
Unconvertible
[source]¶ Raised a requested network conversion cannot be done.
-
exception
nengo.exceptions.
CacheIOError
[source]¶ An IO error in reading from or writing to the decoder cache.