# Reference simulator¶

Nengo is designed so that models created with the Nengo modeling API work on a variety of different simulators. For example, simulators have been created to take advantage of GPUs and neuromorphic hardware.

Nengo comes with a simulator that is relatively fast, and works on general purpose computers. For most users, the only thing that you need to know about the reference simulator is how to create and close a nengo.Simulator instance.

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 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.Simulator(my_network) as sim:
sim.run(0.1)
print(sim.data[my_probe])


Note that the data attribute is still accessible even when a simulator has been closed. Running the simulator, however, will raise an error.

Parameters: network : Network or None A network object to be built and then simulated. If None, then a Model with the build model must be provided instead. dt : float, optional (Default: 0.001) The length of a simulator timestep, in seconds. seed : int, optional (Default: None) A seed for all stochastic operators used in this simulator. model : Model, optional (Default: None) A Model that contains build artifacts to be simulated. Usually the simulator will build this model for you; however, if you want to build the network manually, or you want to inject build artifacts in the model before building the network, then you can pass in a Model instance. progress_bar : bool or ProgressBar or ProgressUpdater, optional (Default: True) 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 or ProgressUpdater instance. optimize : bool, optional (Default: True) If True, the builder will run an additional optimization step that can speed up simulations signficantly at the cost of slower builds. If running models for very small amounts of time, pass False to disable the optimizer.

Attributes

 closed (bool) Whether the simulator has been closed. Once closed, it cannot be reopened. data (ProbeDict) The ProbeDict mapping from Nengo objects to the data associated with those objects. In particular, each Probe maps to the data probed while running the simulation. dg (dict) A dependency graph mapping from each Operator to the operators that depend on that operator. model (Model) The Model containing the signals and operators necessary to simulate the network. signals (SignalDict) The SignalDict mapping from Signal instances to NumPy arrays.
dt

(float) The time step of the simulator.

n_steps

(int) The current time step of the simulator.

time

(float) The current time of the simulator.

close()[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(seed=None)[source]

Reset the simulator state.

Parameters: seed : int, 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.

Parameters: time_in_seconds : float Amount of time to run the simulation for. progress_bar : bool or ProgressBar or ProgressUpdater, optional (Default: True) 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 or ProgressUpdater instance.
run_steps(steps, progress_bar=None)[source]

Simulate for the given number of dt steps.

Parameters: steps : int Number of steps to run the simulation for. progress_bar : bool or ProgressBar or ProgressUpdater, optional (Default: True) 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 or ProgressUpdater instance.
step()[source]

Advance the simulator by 1 step (dt seconds).

trange(dt=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: dt : float, optional (Default: None) The sampling period of the probe to create a range for. If None, the simulator’s dt will be used.

## 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 modeling 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.

class nengo.builder.Signal(initial_value, 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_value : array_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). name : str, optional (Default: None) Name of the signal. Primarily used for debugging. If None, the memory location of the Signal will be used. base : Signal, optional (Default: None) 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. readonly : bool, optional (Default: False) Whether this signal and its related live data should be marked as readonly. Writing to these arrays will raise an exception. offset : int, optional (Default: 0) 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).
base

(Signal or None) 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.

dtype

(numpy.dtype) Data type of the signal (e.g., float64).

elemoffset

(int) Offset of data from base in elements.

elemstrides

(int) Strides of data in elements.

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

is_view

(bool) True if this Signal is a view on another Signal.

itemsize

(int) Size of an array element in bytes.

name

(str) Name of the signal. Primarily used for debugging.

nbytes

(int) Number of bytes consumed by the signal.

ndim

(int) Number of array dimensions.

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

readonly

(bool) Whether associated live data can be changed.

shape

(tuple) Tuple of array dimensions.

size

(int) Total number of elements.

strides

(tuple) Strides of data in bytes.

column()[source]

Return a view on this signal with column vector shape.

may_share_memory(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: other : Signal 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. See numpy.reshape for more details.

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

row()[source]

Return a view on this signal with row vector shape.

class nengo.builder.Operator(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
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 default values for the reads, sets, incs, and updates properties to ensure that subclasses explicitly set these values.

Parameters: tag : str, optional (Default: None) A label associated with the operator, for debugging purposes.

Attributes

 tag (str or None) A label associated with the operator, for debugging purposes.
incs

Signals incremented by this operator.

Increments will be applied after sets (if it is set), and before reads.

reads

Signals that are read and not modified by this operator.

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.

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: signals : SignalDict 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: signals : SignalDict A mapping from signals to their associated live ndarrays. dt : float Length of each simulation timestep, in seconds. Random number generator for stochastic operators.

### Operators¶

class nengo.builder.operator.Reset(dst, value=0, tag=None)[source]

Assign a constant value to a Signal.

Implements dst[...] = value.

Parameters: dst : Signal The Signal to reset. value : float, optional (Default: 0) The constant value to which dst is set. tag : str, optional (Default: None) A label associated with the operator, for debugging purposes.

Notes

1. sets [dst]
2. incs []
3. reads []
4. updates []

Attributes

 dst (Signal) The Signal to reset. tag (str or None) A label associated with the operator, for debugging purposes. value (float) The constant value to which dst is set.
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] (when dst_slice or src_slice is not None)
• dst[dst_slice] += src[src_slice] (when inc=True)
Parameters: dst : Signal The signal that will be assigned to (set). src : Signal The signal that will be copied (read). dst_slice : slice or list, optional (Default: None) Slice or list of indices associated with dst. src_slice : slice or list, optional (Default: None) Slice or list of indices associated with src inc : bool, optional (Default: False) Whether this should be an increment rather than a copy. tag : str, optional (Default: None) 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

 dst (Signal) The signal that will be assigned to (set). dst_slice (list or None) Indices associated with dst. src (Signal) The signal that will be copied (read). src_slice (list or None) Indices associated with src. tag (str or None) A label associated with the operator, for debugging purposes.
class nengo.builder.operator.ElementwiseInc(A, X, Y, tag=None)[source]

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

Implements Y[...] += A * X.

Parameters: A : Signal The first signal to be multiplied. X : Signal The second signal to be multiplied. Y : Signal The signal to be incremented. tag : str, optional (Default: None) A label associated with the operator, for debugging purposes.

Notes

1. sets []
2. incs [Y]
3. reads [A, X]
4. updates []

Attributes

 A (Signal) The first signal to be multiplied. tag (str or None) A label associated with the operator, for debugging purposes. X (Signal) The second signal to be multiplied. Y (Signal) The signal to be incremented.
class nengo.builder.operator.DotInc(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: A : Signal The first signal to be multiplied (a matrix). X : Signal The second signal to be multiplied (a vector). Y : Signal The signal to be incremented. tag : str, optional (Default: None) A label associated with the operator, for debugging purposes.

Notes

1. sets []
2. incs [Y]
3. reads [A, X]
4. updates []

Attributes

 A (Signal) The first signal to be multiplied. tag (str or None) A label associated with the operator, for debugging purposes. X (Signal) The second signal to be multiplied. Y (Signal) The signal to be incremented.
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), 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. indices : ndarray Column indices, see scipy.sparse.bsr_matrix for details. indptr : ndarray Column index pointers, see scipy.sparse.bsr_matrix for details. reshape : bool Whether to reshape the result. tag : str, optional (Default: None) 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. indices (ndarray) Column indices, see scipy.sparse.bsr_matrix for details. indptr (ndarray) Column index pointers, see scipy.sparse.bsr_matrix for details. reshape (bool) Whether to reshape the result. tag (str 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.
class nengo.builder.operator.TimeUpdate(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: step : Signal The signal associated with the integer step counter. time : Signal The signal associated with the time (a float, in seconds). tag : str, optional (Default: None) A label associated with the operator, for debugging purposes.

Notes

1. sets [step, time]
2. incs []
3. reads []
4. updates []

Attributes

 step (Signal) The signal associated with the integer step counter. tag (str or None) A label associated with the operator, for debugging purposes. time (Signal) The signal associated with the time (a float, in seconds).
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) 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: output : Signal or None The signal to be set. If None, the function is still called. fn : callable The function to call. t : Signal or None The signal associated with the time (a float, in seconds). If None, the time will not be passed to fn. x : Signal or None An input signal to pass to fn. If None, an input signal will not be passed to fn. tag : str, optional (Default: None) 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

 fn (callable) The function to call. output (Signal or None) The signal to be set. If None, the function is still called. t (Signal or None) The signal associated with the time (a float, in seconds). If None, the time will not be passed to fn. tag (str or None) A label associated with the operator, for debugging purposes. x (Signal or None) An input signal to pass to fn. If None, an input signal will not be passed to fn.
class nengo.builder.neurons.SimNeurons(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: neurons : NeuronType The NeuronType, which defines a step_math function. J : Signal The input current. output : Signal The neuron output signal that will be set. states : list, optional (Default: None) A list of additional neuron state signals set by step_math. tag : str, optional (Default: None) A label associated with the operator, for debugging purposes.

Notes

1. sets [output] + states
2. incs []
3. reads [J]
4. updates []

Attributes

 J (Signal) The input current. neurons (NeuronType) The NeuronType, which defines a step_math function. output (Signal) The neuron output signal that will be set. states (list) A list of additional neuron state signals set by step_math. tag (str or None) A label associated with the operator, for debugging purposes.
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_filtered : Signal The presynaptic activity, $$a_i$$. post_filtered : Signal The postsynaptic activity, $$a_j$$. theta : Signal The modification threshold, $$\theta_j$$. delta : Signal The synaptic weight change to be applied, $$\Delta \omega_{ij}$$. learning_rate : float The scalar learning rate, $$\kappa$$. tag : str, optional (Default: None) 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

 delta (Signal) The synaptic weight change to be applied, $$\Delta \omega_{ij}$$. learning_rate (float) The scalar learning rate, $$\kappa$$. post_filtered (Signal) The postsynaptic activity, $$a_j$$. pre_filtered (Signal) The presynaptic activity, $$a_i$$. tag (str or None) A label associated with the operator, for debugging purposes. theta (Signal) The modification threshold, $$\theta_j$$.
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_filtered : Signal The presynaptic activity, $$a_i$$. post_filtered : Signal The postsynaptic activity, $$a_j$$. weights : Signal The connection weight matrix, $$\omega_{ij}$$. delta : Signal The synaptic weight change to be applied, $$\Delta \omega_{ij}$$. learning_rate : float The scalar learning rate, $$\kappa$$. beta : float The scalar forgetting rate, $$\beta$$. tag : str, optional (Default: None) 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

 beta (float) The scalar forgetting rate, $$\beta$$. delta (Signal) The synaptic weight change to be applied, $$\Delta \omega_{ij}$$. learning_rate (float) The scalar learning rate, $$\kappa$$. post_filtered (Signal) The postsynaptic activity, $$a_j$$. pre_filtered (Signal) The presynaptic activity, $$a_i$$. tag (str or None) A label associated with the operator, for debugging purposes. weights (Signal) The connection weight matrix, $$\omega_{ij}$$.
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 Associative Memory learning example for details.

Parameters: pre_decoded : Signal Decoded activity from presynaptic ensemble, $$a_i$$. post_filtered : Signal Filtered postsynaptic activity signal. scaled_encoders : Signal 2d array of encoders, multiplied by scale. delta : Signal The synaptic weight change to be applied, $$\Delta \omega_{ij}$$. scale : ndarray The length of each encoder. learning_signal : Signal Scalar signal to be multiplied by learning_rate. Expected to be either 0 or 1 to turn learning off or on, respectively. learning_rate : float The scalar learning rate. tag : str, optional (Default: None) 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

 delta (Signal) The synaptic weight change to be applied, $$\Delta \omega_{ij}$$. learning_rate (float) The scalar learning rate. learning_signal (Signal) Scalar signal to be multiplied by learning_rate. Expected to be either 0 or 1 to turn learning off or on, respectively. post_filtered (Signal) Filtered postsynaptic activity signal. pre_decoded (Signal) Decoded activity from presynaptic ensemble, $$a_i$$. scale (ndarray) The length of each encoder. scaled_encoders (Signal) 2d array of encoders, multiplied by scale. tag (str or None) A label associated with the operator, for debugging purposes.
class nengo.builder.processes.SimProcess(process, input, output, t, mode='set', tag=None)[source]

Simulate a process.

Parameters: process : Process The Process to simulate. input : Signal or None Input to the process, or None if no input. output : Signal or None Output from the process, or None if no output. t : Signal The signal associated with the time (a float, in seconds). mode : str, optional (Default: 'set') Denotes what type of update this operator performs. Must be one of 'update', 'inc' or 'set'. tag : str, optional (Default: None) 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

 input (Signal or None) Input to the process, or None if no input. mode (str) Denotes what type of update this operator performs. output (Signal or None) Output from the process, or None if no output. process (Process) The Process to simulate. t (Signal) The signal associated with the time (a float, in seconds). tag (str or None) A label associated with the operator, for debugging purposes.

### Build functions¶

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:

@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:

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

 builders (dict) 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: model : Model The Model instance in which to store build artifacts. obj : object 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_class : Class The type associated with the build function being decorated.
class nengo.builder.Model(dt=0.001, label=None, decoder_cache=<nengo.cache.NoDecoderCache object>)[source]

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

Parameters: dt : float, optional (Default: 0.001) The length of a simulator timestep, in seconds. label : str, optional (Default: None) A name or description to differentiate models. decoder_cache : DecoderCache, optional (Default: NoDecoderCache()) Interface to a cache for expensive parts of the build process.

Attributes

 config (Config or None) Build functions can set a config object here to affect sub-builders. decoder_cache (DecoderCache) Interface to a cache for expensive parts of the build process. dt (float) The length of each timestep, in seconds. label (str or None) A name or description to differentiate models. operators (list) List of all operators created in the build process. All operators must be added to this list, as it is used by Simulator. params (dict) Mapping from objects to namedtuples containing parameters generated in the build process. probes (list) List of all probes. Probes must be added to this list in the build process, as this list is used by Simulator. seeded (dict) 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. seeds (dict) Mapping from objects to the integer seed assigned to that object. sig (dict) 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. step (Signal) The current step (i.e., how many timesteps have occurred thus far). time (Signal) The current point in time. toplevel (Network) 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. 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(obj, *args, **kwargs)[source]

Build an object into this model.

See Builder.build for more details.

Parameters: obj : object 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 to model.params if they cannot be built multiple times.

Parameters: obj : object The object to query.
nengo.builder.network.build_network(model, network, progress_bar=False)[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: model : Model The model to build into. network : Network The network to build. progress_bar : bool or ProgressBar or ProgressUpdater, optional (Default: False) Progress bar for displaying build 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 or ProgressUpdater instance. Note that this will only affect top-level networks. Subnetworks cannot have progress bars displayed.

Notes

Sets model.params[network] to None.

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: model : Model The model to build into. ens : Ensemble The ensemble to build.

Notes

Sets model.params[ens] to a BuiltEnsemble instance.

class nengo.builder.ensemble.BuiltEnsemble[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_points : ndarray Evaluation points. encoders : ndarray Normalized encoders. intercepts : ndarray X-intercept of each neuron. max_rates : ndarray Maximum firing rates for each neuron. scaled_encoders : ndarray Normalized encoders scaled by the gain and radius. This quantity is used in the actual simulation, unlike encoders. gain : ndarray Gain of each neuron. bias : ndarray Bias current injected into each neuron.
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: model : Model The model to build into. node : Node The node to build.

Notes

Sets model.params[node] to None.

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: model : Model The model to build into. conn : Connection The connection to build.

Notes

Sets model.params[conn] to a BuiltConnection instance.

class nengo.builder.connection.BuiltConnection[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.

Note

The decoders attribute is obsolete as of Nengo 2.1.0. Use the weights attribute instead.

Parameters: eval_points : ndarray Evaluation points. solver_info : dict Information dictionary returned by the Solver. weights : ndarray 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. transform : ndarray The transform matrix.
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: model : Model The model to build into. probe : Probe The connection to build.

Notes

Sets model.params[probe] to a list. Simulator appends to that list when running a simulation.

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: model : Model The model to build into. neurontype : NeuronType Neuron type to build. neuron : Neurons 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_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: model : Model The model to build into. lif : LIF Neuron type to build. neuron : Neurons 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: model : Model The model to build into. alifrate : AdaptiveLIFRate Neuron type to build. neuron : Neurons 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: model : Model The model to build into. alif : AdaptiveLIF Neuron type to build. neuron : Neurons 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: model : Model The model to build into. izhikevich : Izhikevich Neuron type to build. neuron : Neurons 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.

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: model : Model The model to build into. rule : LearningRule 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: model : Model The model to build into. bcm : BCM Learning rule type to build. rule : LearningRule 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: model : Model The model to build into. oja : Oja Learning rule type to build. rule : LearningRule 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: model : Model The model to build into. voja : Voja Learning rule type to build. rule : LearningRule 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 several operators to implement the PES learning rule. Unlike other learning rules, there is no corresponding Operator subclass for the PES rule. Instead, the rule is implemented with generic operators like ElementwiseInc and DotInc. Generic operators are used because they are more likely to be implemented on other backends like Nengo OCL.

Parameters: model : Model The model to build into. pes : PES Learning rule type to build. rule : LearningRule 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.

nengo.builder.processes.build_process(model, process, sig_in=None, sig_out=None, inc=False)[source]

Builds a Process object into a model.

Parameters: model : Model The model to build into. process : Process Process to build. sig_in : Signal, optional (Default: None) The input signal, or None if no input signal. sig_out : Signal, optional (Default: None) The output signal, or None if no output signal. inc : bool, optional (Default: False) Whether SimProcess should be made with mode='inc' (True) or mode='set' (False).

Notes

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

nengo.builder.processes.build_synapse(model, synapse, sig_in, sig_out=None)[source]

Builds a Synapse object into a model.

Parameters: model : Model The model to build into. synapse : Synapse Synapse to build. sig_in : Signal The input signal. sig_out : Signal, optional (Default: None) The output signal. If None, a new output signal will be created and returned.

Notes

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

### Decoder cache¶

class nengo.cache.NoDecoderCache[source]

Provides the same interface as DecoderCache without caching.

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: readonly : bool 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_dir : str 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()[source]

Returns all of the files in the cache.

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

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

Returns: str
get_size_in_bytes()[source]

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

Returns: int
invalidate()[source]

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

shrink(limit=None)[source]

Reduces the size of the cache to meet a limit.

Parameters: limit : int, optional Maximum size of the cache in bytes.
remove_file(path)[source]

Removes the file at path from the cache.

wrap_solver(solver_fn)[source]

Takes a decoder solver and wraps it to use caching.

Parameters: solver : func Decoder solver to wrap for caching. func Wrapped decoder solver.
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: obj : object 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

 fingerprint (hash) 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(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_dir : str 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. Previously, these two objects were stored separately, with the version tuple stored in a legacy.txt file. These two objects were consolidated in the pickle file in Nengo 2.3.0.

Examples

>>> cache_dir = "./my_cache"
>>> to_cache = ("gotta cache 'em all", 151)
>>> with CacheIndex(cache_dir) as index:
...     filename, start, end = index[hash(to_cache)]


Attributes

 cache_dir (str) Path where the cache is stored. index_path (str) Path to the cache index file. legacy_path (str) Path to a potentially existing legacy file. This file was previously used to track version information, but is now obsolete. It will still be used to retrieve version information in case of an old cache index that does not store version information itself. version (tuple) 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.

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_dir : str Path where the cache is stored.

Examples

>>> cache_dir = "./my_cache"
>>> 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(filename)[source]

Remove entries mapping to filename.

sync()[source]

Write changes to the cache index back to disk.

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

### Optimizer¶

nengo.builder.optimizer.optimize(model, dg, max_passes=None)[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: Builder output to optimize. dg : dict Dict of the form {a: {b, c}} where b and c depend on a`, specifying the operator dependency graph of the model.