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

nengo.Simulator

Reference simulator for Nengo models.

nengo.simulator.SimulationData

Data structure used to access simulation data from the model.

class nengo.Simulator(self, 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 the 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.Network() as my_network:
    my_ensemble = nengo.Ensemble(10, 1)
    my_probe = nengo.Probe(my_ensemble)

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
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 a Model instance.

progress_barbool or ProgressBar, optional

Progress bar for displaying build and simulation progress.

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.

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, pass False 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, each Probe 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 from Signal 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 time

(float) The current time of the simulator.

clear_probes(self)[source]

Clear all probe histories.

New in version 3.0.0.

close(self)[source]

Closes the simulator.

Any call to Simulator.run, Simulator.run_steps, Simulator.step, and Simulator.reset on a closed simulator raises a SimulatorClosed exception.

reset(self, 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(self, 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 nearest dt. For example, if dt is 0.001 and run is called with time_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(self, 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.

step(self)[source]

Advance the simulator by 1 step (dt seconds).

trange(self, 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(self, 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 via encoders = 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.

nengo.builder.Model

Stores artifacts from the build process, which are used by Simulator.

nengo.builder.Builder

Manages the build functions known to the Nengo build process.

class nengo.builder.Model(self, 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.

buildernengo.builder.Builder, optional

A Builder instance to use for building. Defaults to a new Builder().

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(self, 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. Calling make_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 the operators attribute.

build(self, 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(self, 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 to model.params if they cannot be built multiple times.

Parameters
objobject

The object to query.

class nengo.builder.Builder(self, *args, **kwargs)[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 the Builder.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 type my_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 arguments model, 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 into model.

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 of EnsembleArray).

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.

classmethod register(nengo_class)[source]

A decorator for adding a class to the build function registry.

Raises a warning if a build function already exists for the class.

Parameters
nengo_classClass

The type associated with the build function being decorated.

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:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. 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.

nengo.builder.Operator

Base class for operator instances understood by Nengo.

nengo.builder.operator.TimeUpdate

Updates the simulation step and time.

nengo.builder.operator.Reset

Assign a constant value to a Signal.

nengo.builder.operator.Copy

Assign the value of one signal to another, with optional slicing.

nengo.builder.operator.ElementwiseInc

Increment signal Y by A * X (with broadcasting).

nengo.builder.operator.reshape_dot

Checks if the dot product needs to be reshaped.

nengo.builder.operator.DotInc

Increment signal Y by dot(A, X).

nengo.builder.operator.SparseDotInc

Like DotInc but A is a sparse matrix.

nengo.builder.operator.BsrDotInc

Increment signal Y by dot(A, X) using block sparse row format.

nengo.builder.operator.SimPyFunc

Apply a Python function to a signal, with optional arguments.

class nengo.builder.Operator(self, tag=None)[source]

Base class for operator instances understood by Nengo.

During one simulator timestep, a Signal can experience

  1. at most one set operator (optional)

  2. any number of increments

  3. any number of reads

  4. 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 by increment operations. A signal’s state will only be read after all increments are complete. The state is then finalized by an update, 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, and updates 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(self, 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.operator.TimeUpdate(self, step, time, tag=None)[source]

Updates the simulation step and time.

Implements step[...] += 1 and time[...] = step * dt.

A separate operator is used (rather than a combination of Copy and DotInc) 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

  1. sets [step, time]

  2. incs []

  3. reads []

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.operator.Reset(self, 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

  1. sets [dst]

  2. incs []

  3. reads []

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.operator.Copy(self, 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] (when dst_slice or src_slice is not None)

  • dst[dst_slice] += src[src_slice] (when inc=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

  1. sets [] if inc else [dst]

  2. incs [dst] if inc else []

  3. reads [src]

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.operator.ElementwiseInc(self, A, X, Y, tag=None)[source]

Increment signal Y by A * 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

  1. sets []

  2. incs [Y]

  3. reads [A, X]

  4. 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(self, 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.

rngnumpy.random.mtrand.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(self, A, X, Y, reshape=None, tag=None)[source]

Increment signal Y by dot(A, X).

Implements Y[...] += np.dot(A, X).

Note

Currently, this only supports matrix-vector multiplies for compatibility with Nengo OCL.

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

  1. sets []

  2. incs [Y]

  3. reads [A, X]

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.operator.SparseDotInc(self, A, X, Y, tag=None)[source]

Like DotInc but A is a sparse matrix.

New in version 3.0.0.

class nengo.builder.operator.BsrDotInc(self, 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), where A is an instance of scipy.sparse.bsr_matrix.

Note

Requires SciPy.

Note

Currently, this only supports matrix-vector multiplies for compatibility with Nengo OCL.

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

  1. sets []

  2. incs [Y]

  3. reads [A, X]

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.operator.SimPyFunc(self, output, fn, t, x, tag=None)[source]

Apply a Python function to a signal, with optional arguments.

Implements output[...] = fn(*args) where args can include the current simulation time t and an input signal x.

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 to fn.

tagstr, optional

A label associated with the operator, for debugging purposes.

Notes

  1. sets [] if output is None else [output]

  2. incs []

  3. reads ([] if t is None else [t]) + ([] if x is None else [x])

  4. 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 to fn.

make_step(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

Signals

nengo.builder.Signal

Represents data or views onto data within a Nengo simulation.

nengo.builder.signal.is_sparse

Check if obj is a sparse matrix.

nengo.builder.signal.SignalDict

Map from Signal -> ndarray.

class nengo.builder.Signal(self, 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 as initial_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 as initial_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.

may_share_memory(self, other)[source]

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(self, *shape)[source]

Return a view on this signal with a different shape.

Note that reshape cannot change the overall size of the signal. See numpy.reshape for more details.

Any number of integers can be passed to this method, describing the desired shape of the returned signal.

nengo.builder.signal.is_sparse(obj)[source]

Check if obj is a sparse matrix.

class nengo.builder.signal.SignalDict(self, *args, **kwargs)[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.

init(self, signal)[source]

Set up a permanent mapping from signal -> data.

reset(self, signal)[source]

Reset ndarray to the base value of the signal that maps to it.

Network builder

nengo.builder.network.build_network

Builds a Network object into a model.

nengo.builder.network.seed_network

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:

  1. Ensembles, nodes, neurons

  2. Subnetworks (recursively)

  3. Connections, learning rules

  4. 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] to None.

nengo.builder.network.seed_network(network, seeds, seeded, base_rng=<module 'numpy.random' from '/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/numpy/random/__init__.py'>)[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

nengo.builder.connection.BuiltConnection

Collects the parameters generated in build_connection.

nengo.builder.connection.get_eval_points

Get evaluation points for connection.

nengo.builder.connection.get_targets

Get target points for connection with given evaluation points.

nengo.builder.connection.build_linear_system

Get all arrays needed to compute decoders.

nengo.builder.connection.build_decoders

Compute decoders for connection.

nengo.builder.connection.solve_for_decoders

Solver for decoders.

nengo.builder.connection.slice_signal

Apply a slice operation to given signal.

nengo.builder.connection.build_solver

Apply decoder solver to connection.

nengo.builder.connection.build_no_solver

Special builder for NoSolver to skip unnecessary steps.

nengo.builder.connection.build_connection

Builds a Connection object into a model.

class nengo.builder.connection.BuiltConnection(self, *args, **kwargs)[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.build_decoders(model, conn, rng)[source]

Compute decoders for connection.

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:

  1. Solve for decoders.

  2. Combine transform matrix with decoders to get weights.

  3. Add operators for computing the function or multiplying neural activity by weights.

  4. Call build function for the synapse.

  5. Call build function for the learning rule.

  6. 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 a BuiltConnection instance.

Ensemble builder

nengo.builder.ensemble.BuiltEnsemble

Collects the parameters generated in build_ensemble.

nengo.builder.ensemble.gen_eval_points

Generate evaluation points for ensemble.

nengo.builder.ensemble.get_activities

Get output of ensemble neurons for given evaluation points.

nengo.builder.ensemble.get_gain_bias

Compute concrete gain and bias for ensemble.

nengo.builder.ensemble.build_ensemble

Builds an Ensemble object into a model.

class nengo.builder.ensemble.BuiltEnsemble(self, *args, **kwargs)[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=<module 'numpy.random' from '/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/numpy/random/__init__.py'>, 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:

  1. Generate evaluation points and encoders.

  2. Normalize encoders to unit length.

  3. Determine bias and gain.

  4. Create neuron input signal

  5. Add operator for injecting bias.

  6. Call build function for neuron type.

  7. Scale encoders by gain and radius.

  8. Add operators for multiplying decoded input signal by encoders and incrementing the result in the neuron input signal.

  9. 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 a BuiltEnsemble instance.

Learning rule builders

nengo.builder.learning_rules.SimPES

Calculate connection weight change according to the PES rule.

nengo.builder.learning_rules.SimBCM

Calculate connection weight change according to the BCM rule.

nengo.builder.learning_rules.SimOja

Calculate connection weight change according to the Oja rule.

nengo.builder.learning_rules.SimVoja

Simulates a simplified version of Oja’s rule in the vector space.

nengo.builder.learning_rules.get_pre_ens

Get the input Ensemble for connection.

nengo.builder.learning_rules.get_post_ens

Get the output Ensemble for connection.

nengo.builder.learning_rules.build_or_passthrough

Builds the obj on signal, or returns the signal if obj is None.

nengo.builder.learning_rules.build_learning_rule

Builds a LearningRule object into a model.

nengo.builder.learning_rules.build_bcm

Builds a BCM object into a model.

nengo.builder.learning_rules.build_oja

Builds a BCM object into a model.

nengo.builder.learning_rules.build_voja

Builds a Voja object into a model.

nengo.builder.learning_rules.build_pes

Builds a PES object into a model.

class nengo.builder.learning_rules.SimPES(self, pre_filtered, error, delta, learning_rate, encoders=None, 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\).

encodersSignal, optional

If not None, multiply the error signal by these post-synaptic encoders (in the case that we want to learn a neuron-to-neuron weight matrix instead of decoder weights).

tagstr, optional

A label associated with the operator, for debugging purposes.

Notes

  1. sets []

  2. incs []

  3. reads [pre_filtered, error, encoders]

  4. 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\).

encodersSignal, optional

If not None, multiply the error signal by these post-synaptic encoders (in the case that we want to learn a neuron-to-neuron weight matrix instead of decoder weights).

tagstr, optional

A label associated with the operator, for debugging purposes.

make_step(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.learning_rules.SimBCM(self, 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

  1. sets []

  2. incs []

  3. reads [pre_filtered, post_filtered, theta]

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.learning_rules.SimOja(self, 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

  1. sets []

  2. incs []

  3. reads [pre_filtered, post_filtered, weights]

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

class nengo.builder.learning_rules.SimVoja(self, 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

  1. sets []

  2. incs []

  3. reads [pre_decoded, post_filtered, scaled_encoders, learning_signal]

  4. 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(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

nengo.builder.learning_rules.get_pre_ens(conn)[source]

Get the input Ensemble for connection.

nengo.builder.learning_rules.get_post_ens(conn)[source]

Get the output Ensemble for connection.

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:

  1. Create a delta signal for the weight change.

  2. Add an operator to increment the weights by delta.

  3. 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] to None.

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 same BCM 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 same Oja 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 same Voja 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 same PES instance.

Neuron builders

nengo.builder.neurons.SimNeurons

Set a neuron model output for the given input current.

nengo.builder.neurons.build_neurons

Builds a NeuronType object into a model.

nengo.builder.neurons.build_spikingrectifiedlinear

Builds a SpikingRectifiedLinear object into a model.

nengo.builder.neurons.build_lif

Builds a LIF object into a model.

nengo.builder.neurons.build_alifrate

Builds an AdaptiveLIFRate object into a model.

nengo.builder.neurons.build_alif

Builds an AdaptiveLIF object into a model.

nengo.builder.neurons.build_izhikevich

Builds an Izhikevich object into a model.

class nengo.builder.neurons.SimNeurons(self, neurons, J, output, states=None, tag=None)[source]

Set a neuron model output for the given input current.

Implements neurons.step_math(dt, J, output, *states).

Parameters
neuronsNeuronType

The NeuronType, which defines a step_math function.

JSignal

The input current.

outputSignal

The neuron output signal that will be set.

stateslist, optional

A list of additional neuron state signals set by step_math.

tagstr, optional

A label associated with the operator, for debugging purposes.

Notes

  1. sets [output] + states

  2. incs []

  3. reads [J]

  4. updates []

Attributes
JSignal

The input current.

neuronsNeuronType

The NeuronType, which defines a step_math function.

outputSignal

The neuron output signal that will be set.

stateslist

A list of additional neuron state signals set by step_math.

tagstr or None

A label associated with the operator, for debugging purposes.

make_step(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

nengo.builder.neurons.build_neurons(model, neurontype, neurons)[source]

Builds a NeuronType object into a model.

This build function works with any NeuronType that does not require extra state, like RectifiedLinear and LIFRate. This function adds a SimNeurons operator connecting the input current to the neural output signals.

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 same NeuronType instance.

nengo.builder.neurons.build_spikingrectifiedlinear(model, spikingrectifiedlinear, neurons)[source]

Builds a SpikingRectifiedLinear object into a model.

In addition to adding a SimNeurons operator, this build function sets up signals to track the voltage for each neuron.

Parameters
modelModel

The model to build into.

spikingrectifiedlinear: SpikingRectifiedLinear

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 same SpikingRectifiedLinear instance.

nengo.builder.neurons.build_lif(model, lif, neurons)[source]

Builds a LIF object into a model.

In addition to adding a SimNeurons operator, this build function sets up signals to track the voltage and refractory times for each neuron.

Parameters
modelModel

The model to build into.

lifLIF

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 same LIF instance.

nengo.builder.neurons.build_alifrate(model, alifrate, neurons)[source]

Builds an AdaptiveLIFRate object into a model.

In addition to adding a SimNeurons operator, this build function sets up signals to track the adaptation term for each neuron.

Parameters
modelModel

The model to build into.

alifrateAdaptiveLIFRate

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 same AdaptiveLIFRate instance.

nengo.builder.neurons.build_alif(model, alif, neurons)[source]

Builds an AdaptiveLIF object into a model.

In addition to adding a SimNeurons operator, this build function sets up signals to track the voltage, refractory time, and adaptation term for each neuron.

Parameters
modelModel

The model to build into.

alifAdaptiveLIF

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 same AdaptiveLIF instance.

nengo.builder.neurons.build_izhikevich(model, izhikevich, neurons)[source]

Builds an Izhikevich object into a model.

In addition to adding a SimNeurons operator, this build function sets up signals to track the voltage and recovery terms for each neuron.

Parameters
modelModel

The model to build into.

izhikevichIzhikevich

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 same Izhikevich instance.

Node builder

nengo.builder.node.build_node

Builds a Node object into a model.

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 of node.output.

Parameters
modelModel

The model to build into.

nodeNode

The node to build.

Notes

Sets model.params[node] to None.

Probe builder

nengo.builder.probe.conn_probe

Build a “connection” probe type.

nengo.builder.probe.signal_probe

Build a “signal” probe type.

nengo.builder.probe.build_probe

Builds a Probe object into a model.

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

nengo.builder.processes.SimProcess

Simulate a process.

nengo.builder.processes.build_process

Builds a Process object into a model.

class nengo.builder.processes.SimProcess(self, 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

  1. sets [output] if output is not None and mode=='set' else []

  2. incs [output] if output is not None and mode=='inc' else []

  3. reads [t, input] if input is not None else [t]

  4. 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(self, 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.

rngnumpy.random.mtrand.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 built SimProcess.

Notes

Does not modify model.params[] and can therefore be called more than once with the same Process instance.

Transform builders

nengo.builder.transforms.multiply

Matrix-matrix multiply, interpreting vectors as diagonal matrices.

nengo.builder.transforms.build_dense

Build a Dense transform object.

nengo.builder.transforms.build_sparse

Build a Sparse transform object.

nengo.builder.transforms.build_convolution

Build a Convolution transform object.

nengo.builder.transforms.ConvInc

Apply convolutional weights to input signal.

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=<module 'numpy.random' from '/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/numpy/random/__init__.py'>)[source]

Build a Dense transform object.

nengo.builder.transforms.build_sparse(model, transform, sig_in, decoders=None, encoders=None, rng=<module 'numpy.random' from '/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/numpy/random/__init__.py'>)[source]

Build a Sparse transform object.

nengo.builder.transforms.build_convolution(model, transform, sig_in, decoders=None, encoders=None, rng=<module 'numpy.random' from '/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/numpy/random/__init__.py'>)[source]

Build a Convolution transform object.

class nengo.builder.transforms.ConvInc(self, 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.

convConvolution

The Convolution object being applied.

tagstr, optional

A label associated with the operator, for debugging purposes.

Notes

  1. sets []

  2. incs [Y]

  3. reads [W, X]

  4. updates []

Attributes
WSignal

The convolutional weights.

XSignal

The input signal.

YSignal

Output signal to be incremented.

convConvolution

The Convolution object being applied.

tagstr, optional

A label associated with the operator, for debugging purposes.

make_step(self, 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.

rngnumpy.random.mtrand.RandomState

Random number generator for stochastic operators.

Decoder cache

Caching capabilities for a faster build process.

nengo.cache.get_fragment_size

Get fragment size in cross-compatible way.

nengo.cache.safe_stat

Does os.stat, but fails gracefully in case of an OSError.

nengo.cache.safe_remove

Does os.remove, but fails gracefully in case of an OSError.

nengo.cache.safe_makedirs

Try to make directories, but continue on error.

nengo.cache.check_dtype

Check that array is a standard dtype.

nengo.cache.check_seq

Check that all objects in list are fingerprintable.

nengo.cache.check_attrs

Check that all attributes of obj are fingerprintable.

nengo.cache.Fingerprint

Fingerprint of an object instance.

nengo.cache.CacheIndex

Cache index mapping keys to (filename, start, end) tuples.

nengo.cache.WriteableCacheIndex

Writable cache index mapping keys to files.

nengo.cache.DecoderCache

Cache for decoders.

nengo.cache.NoDecoderCache

Provides the same interface as DecoderCache without caching.

nengo.cache.get_default_decoder_cache

Get default decoder implementation based on config settings.

nengo.cache.get_fragment_size(path)[source]

Get fragment size in cross-compatible way.

nengo.cache.safe_stat(path)[source]

Does os.stat, but fails gracefully in case of an OSError.

nengo.cache.safe_remove(path)[source]

Does os.remove, but fails gracefully in case of an OSError.

nengo.cache.safe_makedirs(path)[source]

Try to make directories, but continue on error.

nengo.cache.check_dtype(ndarray)[source]

Check that array is a standard dtype.

nengo.cache.check_seq(tpl)[source]

Check that all objects in list are fingerprintable.

nengo.cache.check_attrs(obj)[source]

Check that all attributes of obj are fingerprintable.

class nengo.cache.Fingerprint(self, 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.

classmethod supports(obj)[source]

Determines whether obj can be fingerprinted.

Uses the whitelist method and runs the check function associated with the type of obj.

classmethod whitelist(typ, fn=None)[source]

Whitelist the type given in typ.

Will run the check function fn on objects if provided.

class nengo.cache.CacheIndex(self, 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 the with 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 the index 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(self, 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 the with block are locked against concurrent access with a file lock. The lock will be released within the with 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
remove_file_entry(self, filename)[source]

Remove entries mapping to filename.

sync(self)[source]

Write changes to the cache index back to disk.

The call to this function will be locked by a file lock.

class nengo.cache.DecoderCache(self, 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, if None.

static get_default_dir()[source]

Returns the default location of the cache.

Returns
str
get_files(self)[source]

Returns all of the files in the cache.

Returns
list of (str, int) tuples
get_size(self)[source]

Returns the size of the cache with units as a string.

Returns
str
get_size_in_bytes(self)[source]

Returns the size of the cache in bytes as an int.

Returns
int
invalidate(self)[source]

Invalidates the cache (i.e. removes all cache files).

shrink(self, limit=None)[source]

Reduces the size of the cache to meet a limit.

Parameters
limitint, optional

Maximum size of the cache in bytes.

remove_file(self, path)[source]

Removes the file at path from the cache.

wrap_solver(self, solver_fn)[source]

Takes a decoder solver and wraps it to use caching.

Parameters
solverfunc

Decoder solver to wrap for caching.

Returns
func

Wrapped decoder solver.

class nengo.cache.NoDecoderCache(self, *args, **kwargs)[source]

Provides the same interface as DecoderCache without caching.

nengo.cache.get_default_decoder_cache()[source]

Get default decoder implementation based on config settings.

Optimizer

Operator graph optimizers.

nengo.builder.optimizer.optimize

Optimizes the operator graph by merging operators.

nengo.builder.optimizer.OpMergePass

Manages a single optimization pass.

nengo.builder.optimizer.OpInfo

Analyze and store extra information about operators.

nengo.builder.optimizer.OpsToMerge

Analyze and store extra information about a list of ops to be merged.

nengo.builder.optimizer.OpMerger

Manages the op merge classes known to the optimizer.

nengo.builder.optimizer.Merger

Base class for all op merge classes.

nengo.builder.optimizer.ResetMerger

Merge Reset ops.

nengo.builder.optimizer.CopyMerger

Merge Copy ops.

nengo.builder.optimizer.ElementwiseIncMerger

Merge ElementwiseInc ops.

nengo.builder.optimizer.DotIncMerger

Merge DotInc ops.

nengo.builder.optimizer.SimNeuronsMerger

Merge SimNeurons ops.

nengo.builder.optimizer.SigMerger

Merge signals.

nengo.builder.optimizer.groupby

Groups the given list by the value returned by keyfunc.

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 and dg.

Parameters
modelnengo.builder.Model

Builder output to optimize.

dgdict

Dict of the form {a: {b, c}} where b and c depend on a, specifying the operator dependency graph of the model.

class nengo.builder.optimizer.OpMergePass(self, dg)[source]

Manages a single optimization pass.

perform_merges(self)[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(self, subset)[source]

Performs operator merges for a subset of operators.

Parameters
subsetlist

Subset of operators.

perform_merges_for_view_subset(self, subset)[source]

Perform merges for a subset of operators with the same view base.

Parameters
subsetlist

Subset of operators. These need to have the same view base (can be None if it is None for all) for their first signal in all_signals.

merge(self, tomerge)[source]

Merges the given operators.

This method will also update op_replacements, sig_replacements, and the internal list of merged operators to prevent further merges on the same operators before all required operators and signals have been replaced.

class nengo.builder.optimizer.OpInfo(self)[source]

Analyze and store extra information about operators.

class nengo.builder.optimizer.OpsToMerge(self, 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(self, *args, **kwargs)[source]

Manages the op merge classes known to the optimizer.

class nengo.builder.optimizer.Merger(self, *args, **kwargs)[source]

Base class for all op merge classes.

static merge_dicts(*dicts)[source]

Merges the given dictionaries into a single dictionary.

This function assumes and enforces that no keys overlap.

class nengo.builder.optimizer.ResetMerger(self, *args, **kwargs)[source]

Merge Reset ops.

class nengo.builder.optimizer.CopyMerger(self, *args, **kwargs)[source]

Merge Copy ops.

class nengo.builder.optimizer.ElementwiseIncMerger(self, *args, **kwargs)[source]

Merge ElementwiseInc ops.

class nengo.builder.optimizer.DotIncMerger(self, *args, **kwargs)[source]

Merge DotInc ops.

class nengo.builder.optimizer.SimNeuronsMerger(self, *args, **kwargs)[source]

Merge SimNeurons ops.

class nengo.builder.optimizer.SigMerger(self, *args, **kwargs)[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.

nengo.builder.optimizer.groupby(lst, keyfunc=<function <lambda> at 0x7f8daeecdbf8>)[source]

Groups the given list by the value returned by keyfunc.

Similar to itertools.groupby, but returns a dict, and does not depend on the order of the input list.

Exceptions

nengo.exceptions.NengoException

Base class for Nengo exceptions.

nengo.exceptions.NengoWarning

Base class for Nengo warnings.

nengo.exceptions.ValidationError

A ValueError encountered during validation of a parameter.

nengo.exceptions.ReadonlyError

A ValidationError occurring because a parameter is read-only.

nengo.exceptions.BuildError

A ValueError encountered during the build process.

nengo.exceptions.ObsoleteError

A feature that has been removed in a backwards-incompatible way.

nengo.exceptions.MovedError

A feature that has been moved elsewhere.

nengo.exceptions.ConfigError

A ValueError encountered in the config system.

nengo.exceptions.SpaModuleError

An error in how SPA keeps track of modules.

nengo.exceptions.SpaParseError

An error encountered while parsing a SPA expression.

nengo.exceptions.SimulatorClosed

Raised when attempting to run a closed simulator.

nengo.exceptions.SimulationError

An error encountered during simulation of the model.

nengo.exceptions.SignalError

An error dealing with Signals in the builder.

nengo.exceptions.FingerprintError

An error in fingerprinting an object for cache identification.

nengo.exceptions.NetworkContextError

An error with the Network context stack.

nengo.exceptions.Unconvertible

Raised a requested network conversion cannot be done.

nengo.exceptions.CacheIOError

An IO error in reading from or writing to the decoder cache.

nengo.exceptions.TimeoutError

A timeout occurred while waiting for a resource.

nengo.exceptions.NotAddedToNetworkWarning

A NengoObject has not been added to a network.

nengo.exceptions.CacheIOWarning

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.NengoWarning[source]

Base class for Nengo warnings.

exception nengo.exceptions.ValidationError(msg, attr, obj=None)[source]

A ValueError encountered during validation of a parameter.

exception nengo.exceptions.ReadonlyError(attr, obj=None, msg=None)[source]

A ValidationError occurring because a parameter is read-only.

exception nengo.exceptions.BuildError[source]

A ValueError encountered during the build process.

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.ConfigError[source]

A ValueError encountered in the config system.

exception nengo.exceptions.SpaModuleError[source]

An error in how SPA keeps track of modules.

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.SignalError[source]

An error dealing with Signals in the builder.

exception nengo.exceptions.FingerprintError[source]

An error in fingerprinting an object for cache identification.

exception nengo.exceptions.NetworkContextError[source]

An error with the Network context stack.

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.

exception nengo.exceptions.TimeoutError[source]

A timeout occurred while waiting for a resource.

exception nengo.exceptions.NotAddedToNetworkWarning(obj)[source]

A NengoObject has not been added to a network.

exception nengo.exceptions.CacheIOWarning[source]

A non-critical issue in accessing files in the cache.