示例#1
0
def test_tuning_curves_lif():
    """This tests that the neuron model on SpiNNaker doesn't diverge too far
    from the reference LIF model.
    """
    with nengo.Network() as model:
        a = nengo.Ensemble(100, 1)
        a.bias = np.linspace(0.0, 40.0, a.n_neurons)
        a.gain = np.ones(a.n_neurons)
        p = nengo.Probe(a.neurons)

    # Run with Nengo neurons
    nsim = nengo.Simulator(model)
    nsim.run(1.0)

    # Run on SpiNNaker
    ssim = nengo_spinnaker.Simulator(model)
    with ssim:
        ssim.run(1.0)

    # Calculate the rates
    n_rates = np.sum(nsim.data[p] != 0, axis=0)
    s_rates = np.sum(ssim.data[p] != 0, axis=0)

    # Calculate the RMSE
    rmse = np.sqrt(np.mean(np.square(n_rates - s_rates)))
    assert rmse < 5.0  # Nothing special about 5.0
def test_probe_ensemble_voltages():
    with nengo.Network("Test Network") as network:
        # Create an Ensemble with 2 neurons that have known gain and bias. The
        # result is that we know how the membrane voltage should change over
        # time even with no external stimulus.
        ens = nengo.Ensemble(2, 1)
        ens.bias = [0.5, 1.0]
        ens.gain = [0.0, 0.0]

        # Add the voltage probe
        probe = nengo.Probe(ens.neurons, "voltage")

    # Compute the rise time to 95%
    max_t = -ens.neuron_type.tau_rc * np.log(0.05)

    # Run the simulation for this period of time
    sim = nengo_spinnaker.Simulator(network)
    with sim:
        sim.run(max_t)

    # Compute the ideal voltage curves
    c = 1.0 - np.exp(-sim.trange() / ens.neuron_type.tau_rc)
    ideal = np.dot(ens.bias[:, np.newaxis], c[np.newaxis, :]).T

    # Assert that the ideal curves match the retrieved curves well
    assert np.allclose(ideal, sim.data[probe], atol=1e-3)
示例#3
0
def test_probe_ensemble_spikes():
    with nengo.Network("Test Network") as network:
        a = nengo.Node(lambda t: -1.0 if t > 1.0 else 1.0)

        # Create a 2 neuron ensemble with opposing encoders
        b = nengo.Ensemble(2, 1)
        b.encoders = [[-1.0], [1.0]]
        b.max_rates = [100, 100]
        b.intercepts = [0.1, -0.1]

        nengo.Connection(a, b, synapse=None)

        # Probe the spikes
        p_n0 = nengo.Probe(b.neurons[0])
        p_n1 = nengo.Probe(b.neurons[1], sample_every=0.002)
        p_spikes = nengo.Probe(b.neurons)

    # Mark the input Node as a function of time
    nengo_spinnaker.add_spinnaker_params(network.config)
    network.config[a].function_of_time = True

    # Create the simulator and run for 2 s
    sim = nengo_spinnaker.Simulator(network)
    with sim:
        sim.run(2.0)

    # Check that the neurons spiked as expected
    assert not np.any(sim.data[p_n0][:1.0 / sim.dt])  # Neuron 0
    assert np.any(sim.data[p_n1][:1.0 / p_n1.sample_every])  # Neuron 1
    assert np.any(sim.data[p_n0][1.0 / sim.dt:])
    assert not np.any(sim.data[p_n1][1.0 / p_n1.sample_every:])
def test_time_scaling(timescale, f_of_t):
    """Test that for various time-scales the model results in the same
    behaviour but takes different times to compute.
    """
    # Create a model to test
    with nengo.Network() as model:
        inp = nengo.Node(lambda t: -0.75 if t < 1.0 else .25)
        ens = nengo.Ensemble(100, 1)
        nengo.Connection(inp, ens)
        p = nengo.Probe(ens, synapse=0.01)

    # Mark function of time Node if necessary
    if f_of_t:
        nengo_spinnaker.add_spinnaker_params(model.config)
        model.config[inp].function_of_time = True

    # Perform the simulation
    runtime = 2.0
    sim = nengo_spinnaker.Simulator(model, timescale=timescale)
    with sim:
        start = time.time()
        sim.run(runtime)
        duration = time.time() - start

    # Assert that the output is reasonable
    assert np.allclose(sim.data[p][100:900], -0.75, atol=1e-1)
    assert np.allclose(sim.data[p][1500:1900], +0.25, atol=1e-1)

    # Assert that the simulation took a reasonable amount of time
    assert 0.8 <= (timescale * duration) / runtime <= 1.2
def test_global_inhibition(source):
    with nengo.Network("Test Network") as network:
        # Create a 2-d ensemble representing a constant value
        input_value = nengo.Node([0.25, -0.3])
        ens = nengo.Ensemble(200, 2)
        nengo.Connection(input_value, ens)
        p_ens = nengo.Probe(ens, synapse=0.05)

        # The gate should be open initially and then closed after 1s
        gate_control = nengo.Node(lambda t: 0.0 if t < 1.0 else 1.0)

        if source == "ensemble":
            # Create another ensemble which will act to gate `ens`
            gate_driver = nengo.Ensemble(100, 1)
            gate_driver.intercepts = [0.3] * gate_driver.n_neurons
            gate_driver.encoders = [[1.0]] * gate_driver.n_neurons
            nengo.Connection(gate_control, gate_driver)
            nengo.Connection(gate_driver,
                             ens.neurons,
                             transform=[[-10.0]] * ens.n_neurons)
        elif source == "node" or source == "f_of_t_node":
            nengo.Connection(gate_control,
                             ens.neurons,
                             transform=[[-10.0]] * ens.n_neurons)

    # Mark appropriate Nodes as functions of time if desired
    if source != "node":
        nengo_spinnaker.add_spinnaker_params(network.config)
        network.config[gate_control].function_of_time = True

    # Create the simulate and simulate
    sim = nengo_spinnaker.Simulator(network)

    # Run the simulation for long enough to ensure that the decoded value is
    # with +/-20% of the input value.
    with sim:
        sim.run(2.0)

    # Check that the values are decoded as expected
    index10 = int(p_ens.synapse.tau * 4 / sim.dt)
    index11 = 1.0 / sim.dt
    index20 = index11 + int(p_ens.synapse.tau * 4 / sim.dt)
    data = sim.data[p_ens]

    assert (np.all(+0.20 <= data[index10:index11, 0])
            and np.all(+0.30 >= data[index10:index11, 0])
            and np.all(+0.05 >= data[index20:, 0])
            and np.all(-0.05 <= data[index20:, 0]))
    assert (np.all(-0.36 <= data[index10:index11, 1])
            and np.all(-0.24 >= data[index10:index11, 1])
            and np.all(+0.05 >= data[index20:, 1])
            and np.all(-0.05 <= data[index20:, 1]))
示例#6
0
def test_lowpass_filter(tau):
    with nengo.Network() as network:
        inp = nengo.Node([1.0, -0.4])
        probe = nengo.Probe(inp, synapse=tau)

    # Simulate the network
    sim = nengo_spinnaker.Simulator(network)
    with sim:
        sim.run(tau * 3)

    # Check that the probed value is near the expected value
    assert np.allclose(sim.data[probe],
                       (np.array([inp.output]).T *
                        (1.0 - np.exp(-sim.trange() / tau))).T,
                       atol=0.10)
示例#7
0
def test_none_filter():
    with nengo.Network() as network:
        inp = nengo.Node([1.0, 0.5])
        probe = nengo.Probe(inp, synapse=None)

    # Simulate the network
    sim = nengo_spinnaker.Simulator(network)
    with sim:
        sim.run(0.1)

    # Check that the probed value is as expected, calculate the mean of the
    # received data and ensure this is close to the given input (this accounts
    # for dropped packets).
    mean = np.mean(sim.data[probe], axis=0)
    assert np.all(0.9 * inp.output <= mean)
    assert np.all(1.1 * inp.output >= mean)
示例#8
0
def test_constant_node():
    with nengo.Network("Test Network") as model:
        in_val = nengo.Node([0.5])
        pn = nengo.Node(size_in=1)
        ens = nengo.Ensemble(100, 1)

        nengo.Connection(in_val, pn)
        nengo.Connection(pn, ens)

        probe = nengo.Probe(ens, synapse=0.05)

    sim = nengo_spinnaker.Simulator(model)
    with sim:
        sim.run(0.5)

    assert 0.45 < sim.data[probe][-1] < 0.55
def test_nodes_sliced(f_of_t):
    # Create a model with a single function of time node which returns a 4D
    # vector, apply preslicing on some connections from it and ensure that this
    # slicing plays nicely with the functions attached to the connections.
    def out_fun_1(val):
        assert val.size == 2
        return val * 2

    with nengo.Network() as model:
        # Create the input node and an ensemble
        in_node = nengo.Node(lambda t: [0.1, 1.0, 0.2, -1.0], size_out=4)
        in_node_2 = nengo.Node(0.25)

        ens = nengo.Ensemble(400, 4)
        ens2 = nengo.Ensemble(200, 2)

        # Create the connections
        nengo.Connection(in_node[::2],
                         ens[[1, 3]],
                         transform=.5,
                         function=out_fun_1)
        nengo.Connection(in_node_2[[0, 0]], ens2)

        # Probe the ensemble to ensure that the values are correct
        p = nengo.Probe(ens, synapse=0.05)
        p2 = nengo.Probe(ens2, synapse=0.05)

    # Mark the input as being a function of time if desired
    if f_of_t:
        nengo_spinnaker.add_spinnaker_params(model.config)
        model.config[in_node].function_of_time = True

    # Run the simulator for 1.0 s and check that the last probed values are in
    # range
    sim = nengo_spinnaker.Simulator(model)
    with sim:
        sim.run(1.0)

    # Check the final values
    assert -0.05 < sim.data[p][-1, 0] < 0.05
    assert 0.05 < sim.data[p][-1, 1] < 0.15
    assert -0.05 < sim.data[p][-1, 2] < 0.05
    assert 0.15 < sim.data[p][-1, 3] < 0.25

    assert 0.20 < sim.data[p2][-1, 0] < 0.30
    assert 0.20 < sim.data[p2][-1, 1] < 0.30
def test_global_inhibition_from_optimised_out_passthrough_node():
    with nengo.Network("Test Network") as network:
        # Create a 2-d ensemble representing a constant value
        input_value = nengo.Node([0.25, -0.3])
        ens = nengo.Ensemble(200, 2)
        nengo.Connection(input_value, ens)
        p_ens = nengo.Probe(ens, synapse=0.05)

        # The gate should be open initially and then closed after 1s
        gate_control = nengo.Node(lambda t: 0.0 if t < 1.0 else 1.0)

        # Add the passthrough Node
        gate_ptn = nengo.Node(size_in=ens.n_neurons)
        nengo.Connection(gate_ptn, ens.neurons)

        # Create the control and
        nengo.Connection(gate_control,
                         gate_ptn,
                         transform=[[-10.0]] * ens.n_neurons)

    # Mark appropriate Nodes as functions of time
    nengo_spinnaker.add_spinnaker_params(network.config)
    network.config[gate_control].function_of_time = True

    # Create the simulate and simulate
    sim = nengo_spinnaker.Simulator(network)

    # Run the simulation for long enough to ensure that the decoded value is
    # with +/-20% of the input value.
    with sim:
        sim.run(2.0)

    # Check that the values are decoded as expected
    index10 = int(p_ens.synapse.tau * 4 / sim.dt)
    index11 = 1.0 / sim.dt
    index20 = index11 + int(p_ens.synapse.tau * 4 / sim.dt)
    data = sim.data[p_ens]

    assert (np.all(+0.20 <= data[index10:index11, 0])
            and np.all(+0.30 >= data[index10:index11, 0])
            and np.all(+0.05 >= data[index20:, 0])
            and np.all(-0.05 <= data[index20:, 0]))
    assert (np.all(-0.36 <= data[index10:index11, 1])
            and np.all(-0.24 >= data[index10:index11, 1])
            and np.all(+0.05 >= data[index20:, 1])
            and np.all(-0.05 <= data[index20:, 1]))
示例#11
0
def test_node_input_received_from_board():
    """Test that Nodes do receive data from a running simulation.
    """

    # Node just maintains a list of received values
    class NodeCallable(object):
        def __init__(self):
            self.received_values = []

        def __call__(self, t, x):
            self.received_values.append(x)

    nc = NodeCallable()

    with nengo.Network("Test Network") as network:
        # Ensemble representing a constant 0.5
        a = nengo.Node(0.5)
        b = nengo.Ensemble(100, 1)
        nengo.Connection(a, b)

        # Feeds into the target Node with some transforms.  The transforms
        # could be combined in a single connection but we use two here to check
        # that this works!
        node = nengo.Node(nc, size_in=2, size_out=0)
        nengo.Connection(b, node[0], transform=0.5, synapse=0.05)
        nengo.Connection(b, node[1], transform=-1.0, synapse=0.05)

    # Create the simulate and simulate
    sim = nengo_spinnaker.Simulator(network)

    # Run the simulation for long enough to ensure that the decoded value is
    # with +/-20% of the input value.
    with sim:
        sim.run(2.0)

    # All we can really check is that the received values aren't all zero, that
    # the last few are within the expected range.
    vals = np.array(nc.received_values)
    offset = int(0.05 * 3 / sim.dt)
    print(vals[offset:])
    assert np.any(vals != np.zeros(vals.shape))
    assert (np.all(+0.20 <= vals[offset:, 0])
            and np.all(+0.30 >= vals[offset:, 0])
            and np.all(-0.40 >= vals[offset:, 1])
            and np.all(-0.60 <= vals[offset:, 1]))
示例#12
0
def test_white_signal():
    model = nengo.Network()
    with model:
        inp = nengo.Node(WhiteSignal(60, high=5), size_out=2)
        inp_p = nengo.Probe(inp)

    nengo_spinnaker.add_spinnaker_params(model.config)
    model.config[inp].function_of_time = True

    sim = nengo_spinnaker.Simulator(model)
    with sim:
        sim.run(0.2)

    # Read data
    in_data = sim.data[inp_p]

    # Check that the input value actually changes
    assert np.any(in_data[5] != in_data[6:])
示例#13
0
def test_f_of_t_node_with_outgoing_function():
    with nengo.Network() as model:
        a = nengo.Node(0.0)
        b = nengo.Node(size_in=2)
        c = nengo.Ensemble(100, 2)

        output = nengo.Probe(c, synapse=0.01)

        nengo.Connection(a, b, function=lambda x: [np.sin(x), 1], synapse=None)
        nengo.Connection(b, c, synapse=None)

    # Simulate and ensure that the output is [0, 1] towards the end of the
    # simulation
    sim = nengo_spinnaker.Simulator(model)
    with sim:
        sim.run(0.5)

    assert -0.05 < sim.data[output][-1, 0] < 0.05
    assert 0.95 < sim.data[output][-1, 1] < 1.05
示例#14
0
def test_lti_filter(num, den, t, rmse, tolerance):
    """Test the LTI filter."""
    # Create the network
    with nengo.Network() as network:
        step = nengo.Node([1.0, -0.4])
        probe = nengo.Probe(step, synapse=nengo.LinearFilter(num, den))

    # Simulate with reference Nengo
    nsim = nengo.Simulator(network)
    nsim.run(t)

    # Simulate with SpiNNaker
    ssim = nengo_spinnaker.Simulator(network)
    with ssim:
        ssim.run(t)

    # Calculate the error
    error = nsim.data[probe] - ssim.data[probe]
    assert np.sqrt(np.mean(np.square(error))) <= rmse
    assert np.allclose(nsim.data[probe], ssim.data[probe], atol=tolerance)
示例#15
0
    def __init__(self, run_time=None, period=None, **simulation_parameters):
        """
        This object is an interface for controlling the Robot simulation.

        :param run_time: How long to run the simulation for in seconds
        :type run_time: int
        :param period:  Duration of one period of the simulator. This determines
            how much memory will be allocated to store
            precomputed and probed data.
        :type period: float or None
        :param simulation_parameters: Parameters of the Robot Network. See
            :class:`.Robot` for a list of the parameters and what
            they each represent.
        :type simulation_parameters: dict
        """
        self.robot = Robot()

        self.simulation_control = SimulationControl(
            nengo_spinnaker.Simulator(self.robot,
                                      period=period,
                                      **simulation_parameters), run_time)
def test_constant_node_ensemble_and_value_probe():
    with nengo.Network("Test Network") as network:
        a = nengo.Node(0.50)
        b = nengo.Ensemble(100, 2)
        nengo.Connection(a, b, transform=[[-1.0], [1.0]])
        p = nengo.Probe(b, synapse=0.05)

    # Create the simulate and simulate
    sim = nengo_spinnaker.Simulator(network)

    # Run the simulation for long enough to ensure that the decoded value is
    # with +/-20% of the input value.
    with sim:
        sim.run(2.0)

    # Check that the value was decoded as expected
    index = int(p.synapse.tau * 2.5 / sim.dt)
    data = sim.data[p]
    assert (np.all(+0.40 <= data[index:, 1])
            and np.all(+0.60 >= data[index:, 1])
            and np.all(-0.60 <= data[index:, 0])
            and np.all(-0.40 >= data[index:, 0]))
def test_radius_is_included_in_encoders():
    radius = 1000.0

    with nengo.Network() as model:
        stim = nengo.Node(0.5)
        ens1 = nengo.Ensemble(100, 1)
        ens2 = nengo.Ensemble(100, 1, radius=radius)
        ens3 = nengo.Ensemble(100, 1)

        nengo.Connection(stim, ens1)
        nengo.Connection(ens1, ens2, transform=radius)
        nengo.Connection(ens2, ens3, transform=1 / radius)

        p1 = nengo.Probe(ens1, synapse=0.05)
        p2 = nengo.Probe(ens2, synapse=0.05)
        p3 = nengo.Probe(ens3, synapse=0.05)

    sim = nengo_spinnaker.Simulator(model)
    with sim:
        sim.run(2.0)

    assert .4 * radius <= sim.data[p2][-1] <= .6 * radius
    assert .4 <= sim.data[p3][-1] <= .6
示例#18
0
def test_function_of_time_node():
    with nengo.Network("Test Network") as network:
        a = nengo.Node(lambda t: 0.6 if t < 1.0 else -0.4)

        b = nengo.Ensemble(200, 1)
        p_a = nengo.Probe(a, synapse=0.05)
        p_b = nengo.Probe(b, synapse=0.05)

        c = nengo.Ensemble(200, 1)
        p_c = nengo.Probe(c, synapse=0.05)

        nengo.Connection(a, b)
        nengo.Connection(a, c, function=lambda x: x**2)

    # Mark `a` as a function of time Node
    nengo_spinnaker.add_spinnaker_params(network.config)
    network.config[a].function_of_time = True

    # Create the simulate and simulate
    sim = nengo_spinnaker.Simulator(network, period=1.0)

    # Run the simulation for long enough to ensure that the decoded value is
    # with +/-20% of the input value.
    with sim:
        sim.run(2.0)

    # Check that the values are decoded as expected
    index10 = int(p_b.synapse.tau * 3 / sim.dt)
    index11 = 1.0 / sim.dt
    index20 = index11 + int(p_b.synapse.tau * 3 / sim.dt)
    data = sim.data[p_b]

    assert np.all(+0.44 <= data[index10:index11, 0])
    assert np.all(+0.72 >= data[index10:index11, 0])
    assert np.all(-0.32 >= data[index20:, 0])
    assert np.all(-0.48 <= data[index20:, 0])
示例#19
0
    def __init__(self,
                 n_input,
                 n_output,
                 n_neurons=1000,
                 seed=1,
                 pes_learning_rate=1e-6,
                 intercepts=(0.5, 1.0),
                 weights_file=None,
                 backend='nengo',
                 **kwargs):

        self.input_signal = np.zeros(n_input)
        self.training_signal = np.zeros(n_output)
        self.output = np.zeros(n_output)

        if weights_file is None:
            weights_file = ['']

        nengo_model = nengo.Network(seed=seed)
        with nengo_model:

            def input_signals_func(t):
                """ Get the input and -1 * training signal """
                return np.hstack([self.input_signal, -self.training_signal])

            input_signals = nengo.Node(input_signals_func,
                                       size_out=n_input + n_output)

            # make the adaptive population output accessible
            def output_func(t, x):
                """ stores the adaptive output for use in control() """
                self.output = np.copy(x)

            output = nengo.Node(output_func, size_in=n_output, size_out=0)

            # specify intercepts such that neurons are
            # active throughout the whole range specified
            intercepts = AreaIntercepts(dimensions=n_input,
                                        base=nengo.dists.Uniform(
                                            intercepts[0], intercepts[1]))

            adapt_ens = nengo.Ensemble(n_neurons=n_neurons,
                                       dimensions=n_input,
                                       intercepts=intercepts,
                                       **kwargs)

            try:
                # if the NengoLib is installed, use it
                # to optimize encoder placement
                import nengolib
                adapt_ens.encoders = (nengolib.stats.ScatteredHypersphere(
                    surface=True))
                print('NengoLib used to optimize encoders placement')
            except ImportError:
                print('Nengo lib not installed, encoder ' +
                      'placement will be sub-optimal.')

            # hook up input signal to adaptive population to provide context
            nengo.Connection(input_signals[:n_input], adapt_ens, synapse=0.005)

            # load weights from file if they exist, otherwise use zeros
            if os.path.isfile('%s' % weights_file):
                transform = np.load(weights_file)['weights'][-1][0]
                print('Loading weights: \n', transform)
                print('Loaded weights all zeros: ', np.allclose(transform, 0))
            else:
                print('No weights found, starting with zeros')
                transform = np.zeros((adapt_ens.n_neurons, n_output)).T

            # set up learning connections
            if backend == 'nengo_spinnaker':
                conn_learn = nengo.Connection(
                    adapt_ens,
                    output,
                    learning_rule_type=nengo.PES(pes_learning_rate),
                    solver=DummySolver(transform.T))
            else:
                conn_learn = nengo.Connection(
                    adapt_ens.neurons,
                    output,
                    learning_rule_type=nengo.PES(pes_learning_rate),
                    transform=transform)

            # hook up the training signal to the learning rule
            nengo.Connection(input_signals[n_input:],
                             conn_learn.learning_rule,
                             synapse=0.01)

        nengo.cache.DecoderCache().invalidate()
        if backend == 'nengo':
            self.sim = nengo.Simulator(nengo_model, dt=.001)
        elif backend == 'nengo_ocl':
            try:
                import nengo_ocl
            except ImportError:
                raise Exception('Nengo OCL not installed, ' +
                                'cannot use this backend.')
            import pyopencl as cl
            # Here, the context would be to use all devices from platform [0]
            ctx = cl.Context(cl.get_platforms()[0].get_devices())
            self.sim = nengo_ocl.Simulator(nengo_model, context=ctx, dt=.001)
        elif backend == 'nengo_spinnaker':
            try:
                import nengo_spinnaker
            except ImportError:
                raise Exception('Nengo SpiNNaker not installed, ' +
                                'cannot use this backend.')
            self.sim = nengo_spinnaker.Simulator(nengo_model)
            # start running the spinnaker model
            self.sim.async_run_forever()
        else:
            raise Exception('Invalid backend specified')
        self.backend = backend
示例#20
0
        dodge -= max(x[0] - 0.5, 0) * 1
        dodge += max(x[1] - 0.5, 0) * 1
        return dodge
    nengo.Connection(sensors_us, control.input[0], synapse=synapse,
                     function=avoid_dodge)


    avoid_inhibit = nengo.Ensemble(n_neurons=50, dimensions=1,
                                   intercepts=nengo.utils.distributions.Uniform(0.2, 0.9))
    nengo.Connection(joystick[5], avoid_inhibit, synapse=None)
    nengo.Connection(avoid_inhibit, sensors_ir.neurons, transform=[[-1]]*200,
                     synapse=0.1)
    nengo.Connection(avoid_inhibit, sensors_us.neurons, transform=[[-1]]*200,
                     synapse=0.1)
    '''

import nengo_spinnaker
sim = nengo_spinnaker.Simulator(model)
sim.run(1000)
'''
import nengo_viz
viz = nengo_viz.Viz(model)
viz.value(sensor_node)
viz.value(control.output)
viz.value(motor.output)
viz.start()
'''
#sim = nengo.Simulator(model)
#while True:
#    sim.run(1, progress_bar=None)
示例#21
0
import nengo_spinnaker_gfe.nengo_simulator as gfe_nengo
import nengo_spinnaker as mundy_nengo
USE_GFE = True


def create_model():
    D = 16

    model = spa.SPA(seed=1)
    with model:
        model.a = spa.State(dimensions=D)
        model.b = spa.State(dimensions=D)
        model.c = spa.State(dimensions=D)
        model.cortical = spa.Cortical(spa.Actions(
            'c = a+b',
            ))

        model.input = spa.Input(
            a='A',
            b=(lambda t: 'C*~A' if (t%0.1 < 0.05) else 'D*~A'),
            )
    return model, list(), dict()

if __name__ == '__main__':
    network, function_of_time, function_of_time_time_period = create_model()
    if USE_GFE:
        sim = gfe_nengo.NengoSimulator(network)
    else:
        sim = mundy_nengo.Simulator(network)
    sim.run(100)
示例#22
0
    def __init__(self,
                 n_input,
                 n_output,
                 n_neurons=1000,
                 n_ensembles=1,
                 seed=None,
                 pes_learning_rate=1e-6,
                 intercepts=(0.5, 1.0),
                 weights_file=None,
                 backend='nengo',
                 session=None,
                 run=None,
                 test_name='test',
                 autoload=False,
                 function=None,
                 send_redis_spikes=False,
                 encoders=None,
                 probe_weights=False,
                 debug_print=False,
                 **kwargs):

        self.input_signal = np.zeros(n_input)
        self.training_signal = np.zeros(n_output)
        self.output = np.zeros(n_output)

        # if a weights_file is not specified and auto_load is desired,
        # check the test_name directory for the most recent weights
        if weights_file is None and autoload:
            weights_file = self.load_weights(session=session,
                                             run=run,
                                             test_name=test_name)

        if weights_file is None:
            weights_file = ''

        self.nengo_model = nengo.Network(seed=seed)
        self.nengo_model.config[nengo.Connection].synapse = None

        # Set the nerual model to use
        if backend == 'nengo':
            self.nengo_model.config[nengo.Ensemble].neuron_type = nengo.LIF()
        elif backend == 'nengo_spinnaker':
            self.nengo_model.config[nengo.Ensemble].neuron_type = nengo.LIF()

        with self.nengo_model:

            def input_signals_func(t):
                """ Get the input and -1 * training signal """
                return self.input_signal

            input_signals = nengo.Node(input_signals_func, size_out=n_input)

            def training_signals_func(t):
                return -self.training_signal

            training_signals = nengo.Node(training_signals_func,
                                          size_out=n_output)

            # make the adaptive population output accessible
            def output_func(t, x):
                """ stores the adaptive output for use in control() """
                self.output = np.copy(x)

            output = nengo.Node(output_func, size_in=n_output, size_out=0)

            # specify intercepts such that neurons are
            # active throughout the whole range specified
            intercepts = AreaIntercepts(dimensions=n_input,
                                        base=Triangular(-0.9, -0.9, 0.0))

            self.adapt_ens = []
            self.conn_learn = []

            for ii in range(n_ensembles):
                self.adapt_ens.append(
                    nengo.Ensemble(n_neurons=n_neurons,
                                   dimensions=n_input,
                                   intercepts=intercepts,
                                   radius=np.sqrt(n_input),
                                   **kwargs))
                print('*** ENSEMBLE %i ***' % ii)

                try:
                    # if the NengoLib is installed, use it
                    # to optimize encoder placement
                    import nengolib
                    if encoders is None:
                        self.adapt_ens[ii].encoders = (
                            nengolib.stats.ScatteredHypersphere(surface=True))
                        print('NengoLib used to optimize encoders placement')
                    else:
                        self.adapt_ens[ii].encoders = encoders
                        print('Using user defined encoder values')
                except ImportError:
                    print('Nengo lib not installed, encoder ' +
                          'placement will be sub-optimal.')

                # hook up input signal to adaptive population for context
                nengo.Connection(input_signals, self.adapt_ens[ii])

                # load weights from file if they exist, otherwise use zeros
                if weights_file == '~':
                    weights_file = os.path.expanduser(weights_file)
                print('Backend: ', backend)
                print('Weights file: %s' % weights_file)
                if not os.path.isfile('%s' % weights_file):
                    print('No weights found, starting with zeros')
                    transform = np.zeros(
                        (n_output, self.adapt_ens[ii].n_neurons))

                # set up learning connections
                if function is not None and (weights_file is None
                                             or weights_file is ''):
                    print("Using provided function to bootstrap learning")
                    eval_points = Concatenate([
                        nengo.dists.Choice([0]),
                        nengo.dists.Choice([0]),
                        nengo.dists.Uniform(-1, 1),
                        nengo.dists.Uniform(-1, 1)
                    ])
                    self.conn_learn.append(
                        nengo.Connection(
                            self.adapt_ens[ii],
                            output,
                            learning_rule_type=nengo.PES(pes_learning_rate),
                            function=function,
                            eval_points=eval_points))
                else:
                    if backend == 'nengo_spinnaker':
                        if os.path.isfile('%s' % weights_file):
                            if n_ensembles == 1:
                                transform = np.squeeze(
                                    np.load(weights_file)['weights']).T
                            else:
                                transform = np.squeeze(
                                    np.load(weights_file)['weights'])[ii].T
                            print('Loading weights: \n', transform)
                            print('Loaded weights all zeros: ',
                                  np.allclose(transform, 0))

                        print(transform.T.shape)

                        self.conn_learn.append(
                            nengo.Connection(
                                self.adapt_ens[ii],
                                output,
                                function=lambda x: np.zeros(n_output),
                                learning_rule_type=nengo.PES(
                                    pes_learning_rate),
                                solver=DummySolver(transform.T)))
                    else:

                        if os.path.isfile('%s' % weights_file):
                            if n_ensembles == 1:
                                transform = np.load(weights_file)['weights']
                            else:
                                transform = (
                                    np.load(weights_file)['weights'][ii])
                            # remove third dimension if present
                            if len(transform.shape) > 2:
                                transform = np.squeeze(transform)
                            print('Loading weights: \n', transform)
                            print('Loaded weights all zeros: ',
                                  np.allclose(transform, 0))

                        self.conn_learn.append(
                            nengo.Connection(self.adapt_ens[ii].neurons,
                                             output,
                                             learning_rule_type=nengo.PES(
                                                 pes_learning_rate),
                                             transform=transform))

                # hook up the training signal to the learning rule
                nengo.Connection(training_signals,
                                 self.conn_learn[ii].learning_rule,
                                 synapse=None)

            if backend != 'nengo_spinnaker' and send_redis_spikes:
                # Send spikes via redis
                def send_spikes(t, x):
                    v = np.where(x != 0)[0]
                    if len(v) > 0:
                        msg = struct.pack('%dI' % len(v), *v)
                    else:
                        msg = ''
                    r.set('spikes', msg)
                    self.activity = x

                source_node = nengo.Node(send_spikes, size_in=n_neurons)
                nengo.Connection(self.adapt_ens[0].neurons[:n_neurons],
                                 source_node,
                                 synapse=None)

            def save_x(t, x):
                self.x = x

            x_node = nengo.Node(save_x, size_in=n_input)
            nengo.Connection(self.adapt_ens[0], x_node, synapse=None)

            if backend == 'nengo' and probe_weights:
                self.nengo_model.weights_probe = nengo.Probe(
                    self.conn_learn[0], 'weights', synapse=None)

        nengo.cache.DecoderCache().invalidate()
        if backend == 'nengo':
            self.sim = nengo.Simulator(self.nengo_model, dt=.001)
        elif backend == 'nengo_ocl':
            try:
                import nengo_ocl
            except ImportError:
                raise Exception('Nengo OCL not installed, ' +
                                'cannot use this backend.')
            import pyopencl as cl
            # Here, the context would be to use all devices from platform [0]
            ctx = cl.Context(cl.get_platforms()[0].get_devices())
            self.sim = nengo_ocl.Simulator(self.nengo_model,
                                           context=ctx,
                                           dt=.001)
        elif backend == 'nengo_spinnaker':
            try:
                import nengo_spinnaker
            except ImportError:
                raise Exception('Nengo SpiNNaker not installed, ' +
                                'cannot use this backend.')
            if debug_print:
                # turn on debug printing
                logging.basicConfig(level=logging.DEBUG)

            self.sim = nengo_spinnaker.Simulator(self.nengo_model)
            # start running the spinnaker model
            self.sim.async_run_forever()

        else:
            raise Exception('Invalid backend specified')
        self.backend = backend
示例#23
0
    bias = nengo.Node([1], label='bias')
    nengo.Connection(bias,
                     R.input,
                     transform=numpy.ones((num_inputs, 1)),
                     synapse=None)

    nengo.Connection(R.output,
                     R.input,
                     transform=(numpy.eye(num_inputs) - 1),
                     synapse=0.008)

    config = nengo_spinnaker.Config()
    config[input_node].f_of_t = True

    sim = nengo_spinnaker.Simulator(model, config=config)

    sim.run(0.5)

    fig, axis = plt.subplots(2,
                             sharex=True,
                             figsize=(plot_settings.column_width, 3.5),
                             frameon=False)

    axis[0].plot(sim.trange(), sim.data[q_probe])
    axis[0].set_ylabel("Input utility")

    lines = axis[1].plot(sim.trange(), sim.data[output_probe])
    axis[1].set_xlabel("Time / s")
    axis[1].set_ylabel("Basal ganglia output")
示例#24
0
def test_probe_passnodes():
    """Test that pass nodes are left on SpiNNaker and that they may be probed.
    """
    class ValueReceiver(object):
        def __init__(self):
            self.ts = list()
            self.values = list()

        def __call__(self, t, x):
            self.ts.append(t)
            self.values.append(x[:])

    with nengo.Network("Test Network") as net:
        # Create an input Node which is a function of time only
        input_node = nengo.Node(lambda t: -0.33 if t < 1.0 else 0.10,
                                label="my input")

        # 3D ensemble array to represent this value
        ens = nengo.networks.EnsembleArray(500, 3, label="reps")

        # Pipe the input to the array and probe the output of the array
        nengo.Connection(input_node,
                         ens.input,
                         transform=[[1.0], [0.0], [-1.0]])
        p_ens = nengo.Probe(ens.output, synapse=0.05)

        # Also add a node connected to the end of the ensemble array to ensure
        # that multiple things correctly receive values from the filter.
        receiver = ValueReceiver()
        n_receiver = nengo.Node(receiver, size_in=3)
        nengo.Connection(ens.output, n_receiver, synapse=0.05)

    # Mark the input Node as being a function of time
    nengo_spinnaker.add_spinnaker_params(net.config)
    net.config[input_node].function_of_time = True

    # Create the simulate and simulate
    sim = nengo_spinnaker.Simulator(net)

    # Run the simulation for long enough to ensure that the decoded value is
    # with +/-20% of the input value.
    with sim:
        sim.run(2.0)

    # Check that the values are decoded as expected
    index10 = int(p_ens.synapse.tau * 3 / sim.dt)
    index11 = 1.0 / sim.dt
    index20 = index11 + index10
    data = sim.data[p_ens]

    assert (np.all(-0.25 >= data[index10:index11, 0])
            and np.all(-0.40 <= data[index10:index11, 0])
            and np.all(+0.05 <= data[index20:, 0])
            and np.all(+0.15 >= data[index20:, 0]))
    assert np.all(-0.05 <= data[:, 1]) and np.all(+0.05 >= data[:, 1])
    assert (np.all(+0.25 <= data[index10:index11, 2])
            and np.all(+0.40 >= data[index10:index11, 2])
            and np.all(-0.05 >= data[index20:, 2])
            and np.all(-0.15 <= data[index20:, 2]))

    # Check that values came into the node correctly
    assert +0.05 <= receiver.values[-1][0] <= +0.15
    assert -0.05 >= receiver.values[-1][2] >= -0.15
示例#25
0
    pUtility = nengo.Probe(model.bg.input, synapse=None)

#Make a simulator and run it
if not spinnaker:
    track = profile("Building", datetime.datetime.now())
    sim = nengo.Simulator(model)
    profile("Building done", track)
else:
    import nengo_spinnaker

    config = nengo_spinnaker.Config()
    for n in model.input.input_nodes.values():
        config[n].f_of_t = True

    sim = nengo_spinnaker.Simulator(model,
                                    config=config,
                                    machine_name="192.168.1.1")

track = profile("Running", datetime.datetime.now())
sim.run(10.0)
profile("Running done", track)

from matplotlib import pyplot as plt
figure = plt.figure()

p1 = figure.add_subplot(2, 1, 1)
action_plot = p1.plot(sim.trange(), sim.data[pActions])
p1.set_ylabel('Action')
p1.set_ylim([-0.1, 1.1])
figure.legend(action_plot, model.action_names)