Example #1
0
def makeSignal(t, f, dt=0.001, value=1.0, seed=0):
    stim = nengo.processes.WhiteSignal(period=t / 2,
                                       high=0.5,
                                       rms=0.5,
                                       seed=seed)
    stim2 = nengo.processes.WhiteSignal(period=t / 2,
                                        high=0.5,
                                        rms=0.5,
                                        seed=100 + seed)
    with nengo.Network() as model:
        u = nengo.Node(stim)
        u2 = nengo.Node(stim2)
        both = nengo.Ensemble(1, 2, neuron_type=nengo.Direct())
        tar = nengo.Ensemble(1, 2, neuron_type=nengo.Direct())
        tar2 = nengo.Ensemble(1, 1, neuron_type=nengo.Direct())
        nengo.Connection(u, both[0], synapse=None)
        nengo.Connection(u2, both[1], synapse=None)
        nengo.Connection(both, tar, synapse=f)
        nengo.Connection(tar, tar2, synapse=f, function=multiply)
        pBoth = nengo.Probe(both, synapse=None)
        pTar = nengo.Probe(tar, synapse=None)
        pTar2 = nengo.Probe(tar2, synapse=None)
    with nengo.Simulator(model, progress_bar=False, dt=dt) as sim:
        sim.run(t / 2, progress_bar=False)
    tar2 = f.filt(sim.data[pTar2], dt=dt)
    norm = value / np.max(np.abs(tar2))
    positive = np.sqrt(norm) * np.vstack(
        (sim.data[pBoth][:, 0], sim.data[pBoth][:, 1])).T
    negative = np.sqrt(norm) * np.vstack(
        (sim.data[pBoth][:, 0], -sim.data[pBoth][:, 1])).T
    mirrored = np.concatenate(([[0, 0]], positive, negative))
    return lambda t: mirrored[int(t / dt)]
Example #2
0
    def __init__(self,
                 target_func,
                 cid=None,
                 decoder_solver=None,
                 noise_std=None):

        gain_matrix, adaptive_filter, task_to_rotor = gain_sets.get_gain_matrices(
            gain_set='hybrid_fast')

        self.model = nengo.Network(label='V-REP Adaptive Quadcopter', seed=13)
        with self.model:

            # Sensors and Actuators
            self.copter_node = Quadcopter(target_func=target_func,
                                          cid=cid,
                                          noise_std=noise_std)
            copter = nengo.Node(self.copter_node, size_in=4, size_out=12)

            # State Error Population
            state = nengo.Ensemble(n_neurons=1,
                                   dimensions=12,
                                   neuron_type=nengo.Direct())

            # Contains the rotor speeds
            motor = nengo.Ensemble(n_neurons=1,
                                   dimensions=4,
                                   neuron_type=nengo.Direct())

            # Command in 'task' space (up/down, forward/back, left/right, rotate)
            task = nengo.Ensemble(n_neurons=1,
                                  dimensions=4,
                                  neuron_type=nengo.Direct())

            adaptation = nengo.Ensemble(n_neurons=1000, dimensions=12)

            nengo.Connection(state, adaptation, synapse=None)

            if decoder_solver is None:
                self.a_conn = nengo.Connection(
                    adaptation,
                    task,
                    function=lambda x: [0, 0, 0, 0],
                    learning_rule_type=nengo.PES(learning_rate=1e-4))
            else:
                self.a_conn = nengo.Connection(
                    adaptation,
                    task,
                    function=lambda x: [0, 0, 0, 0],
                    solver=decoder_solver[0],
                    learning_rule_type=nengo.PES(learning_rate=1e-4))

            # Sign of the error changed in newer versions of Nengo since this work
            error_conn = nengo.Connection(state,
                                          self.a_conn.learning_rule,
                                          transform=-1 * gain_matrix)

            nengo.Connection(state, task, transform=gain_matrix)
            nengo.Connection(task, motor, transform=task_to_rotor)
            nengo.Connection(copter, state, synapse=None)
            nengo.Connection(motor, copter, synapse=0.001)
def test_merged_simpyfunc(Simulator):
    with nengo.Network() as net:
        # nodes get time + x
        node0 = nengo.Node(lambda t, x: x + t, size_in=1)
        node1 = nengo.Node(lambda t, x: x + 2 * t, size_in=1)

        # direct ensembles won't get time as input
        ens0 = nengo.Ensemble(10, 1, neuron_type=nengo.Direct())
        nengo.Connection(ens0, node0, function=lambda x: x + 1)
        ens1 = nengo.Ensemble(10, 1, neuron_type=nengo.Direct())
        nengo.Connection(ens1, node1, function=lambda x: x + 2)

        p0 = nengo.Probe(node0)
        p1 = nengo.Probe(node1)

    with nengo.Simulator(net) as canonical:
        canonical.run_steps(10)

    with Simulator(net) as sim:
        assert (len([
            ops for ops in sim.tensor_graph.plan
            if isinstance(ops[0], operator.SimPyFunc)
        ]) == 2)

        sim.run_steps(10)

    assert np.allclose(canonical.data[p0], sim.data[p0])
    assert np.allclose(canonical.data[p1], sim.data[p1])
Example #4
0
    def get_network_TR(self, label):
        net = nengo.Network(label=label)
        with net:
            net.input = nengo.Node(size_in=2)
            net.perception_proprioception = nengo.Ensemble(
                n_neurons=600,
                dimensions=2,
                radius=10,
                neuron_type=nengo.Direct())
            net.u = nengo.Ensemble(n_neurons=200,
                                   dimensions=1,
                                   neuron_type=nengo.Direct())
            net.output = nengo.Node(size_in=len(self._joints),
                                    size_out=len(self._joints))
            nengo.Connection(net.input[0], net.perception_proprioception[0])
            nengo.Connection(net.input[1], net.perception_proprioception[1]
                             )  #, transform = 10 / self.neuron_number)

            nengo.Connection(net.perception_proprioception,
                             net.u,
                             function=self.get_u_TR)  #, transform= 1.2)
            #net.debug = nengo.Node(size_in = 1)
            #nengo.Connection(net.perception_proprioception, net.debug , function = self.get_u_TR)

            nengo.Connection(net.u, net.output, function=self.map_voluntary)
            #if len(self._joints) > 1:
            #    nengo.Connection(net.u, net.output[1], synapse=0.01, function=self.map_voluntary)
        return net
    def get_network_effort(self, label):
        def get_feedback_effort(t):
            if self.arm is None:
                return 0
            else:
                #Orginal: return self.arm.effort[self.sensor_joints]
                res = []
                for i in self.sensor_joints:
                    res.append(self.arm.effort[i])
                return res

        def get_threshold(x):
            for i in range(len(self.sensor_joints)):
                if x[i] > self.threshold_mapping[0][self.sensor_joints[
                        i]] or x[i] < self.threshold_mapping[1][
                            self.sensor_joints[i]]:
                    return 10
            return 0

        def get_avg(x):
            self.avg.append(x)
            if (len(self.avg) > 500):
                self.avg.pop(0)
            res = sum(self.avg) / float(len(self.avg))
            return x

        def get_threshi(x):
            if abs(x) > 50:
                return 1
            else:
                return 0

        sub = rospy.Subscriber(self.joint_states_topic,
                               JointState,
                               self.callback,
                               queue_size=1)
        net = nengo.Network(label=label)
        with net:
            net.input = nengo.Node(get_feedback_effort)
            # net.ens = nengo.Ensemble(n_neurons=200, dimensions=1, radius=10) #' RADIUS "200
            #net.ens = nengo.Ensemble(n_neurons=150, dimensions=1)
            net.output = nengo.Node(size_in=1)

            #TRYOUT
            net.ens = nengo.Ensemble(n_neurons=150,
                                     dimensions=len(self.sensor_joints),
                                     neuron_type=nengo.Direct())
            net.ens_2 = nengo.Ensemble(n_neurons=150,
                                       dimensions=len(self.sensor_joints),
                                       neuron_type=nengo.Direct())
            nengo.Connection(net.input, net.ens)
            for i in range(len(self.sensor_joints)):
                nengo.Connection(net.ens[i], net.ens_2[i], function=get_avg)
            #nengo.Connection(net.ens_2, net.output, function = get_threshi)
            nengo.Connection(net.ens_2, net.output, function=get_threshold)
            #nengo.Connection(net.input, net.ens, function=get_threshold)
            #nengo.Connection(net.ens, net.output)
        return net
Example #6
0
def test_direct_connection(OclOnlySimulator, synapse):
    """Test a direct-mode connection"""

    model = nengo.Network("test_connection", seed=124)
    with model:
        a = nengo.Ensemble(1, dimensions=1, neuron_type=nengo.Direct())
        b = nengo.Ensemble(1, dimensions=1, neuron_type=nengo.Direct())
        nengo.Connection(a, b, function=lambda x: x**2, synapse=synapse)

    OclOnlySimulator(model)
Example #7
0
def test_direct_connection(Simulator):
    """Test a direct-mode connection"""

    model = nengo.Network('test_connection', seed=124)
    with model:
        a = nengo.Ensemble(1, dimensions=1, neuron_type=nengo.Direct())
        b = nengo.Ensemble(1, dimensions=1, neuron_type=nengo.Direct())
        nengo.Connection(a, b, function=lambda x: x**2)

    Simulator(model)
Example #8
0
    def model(self, p):
        vocab = spa.Vocabulary(p.D)
        for i in range(p.M):
            vocab.parse('M%d' % i)

        order = np.arange(p.n_tests)
        np.random.shuffle(order)

        model = spa.SPA()
        with model:
            model.cue = spa.State(p.D, vocab=vocab)
            for ens in model.cue.all_ensembles:
                ens.neuron_type = nengo.Direct()

            model.accum = spa.State(p.D, vocab=vocab, feedback=p.feedback)

            model.recall = spa.AssociativeMemory(vocab,
                                                 wta_output=True,
                                                 threshold_output=True)

            model.recalled = spa.State(p.D, vocab=vocab)
            for ens in model.recalled.all_ensembles:
                ens.neuron_type = nengo.Direct()

            nengo.Connection(model.cue.output,
                             model.accum.input,
                             transform=p.accum)
            nengo.Connection(model.recall.output, model.recalled.input)
            nengo.Connection(model.accum.output, model.recall.input)

            model.same = nengo.Ensemble(n_neurons=100,
                                        dimensions=1,
                                        encoders=nengo.dists.Choice([[1]]),
                                        intercepts=nengo.dists.Uniform(0.3, 1))

            model.dot = nengo.networks.Product(n_neurons=200, dimensions=p.D)
            nengo.Connection(model.cue.output, model.dot.A)
            nengo.Connection(model.recalled.output, model.dot.B)
            nengo.Connection(model.dot.output,
                             model.same,
                             transform=[[1] * p.D])

            def stim(t):
                index = int(t / p.T_test)
                index2 = order[index % len(order)]
                if index % 2 == 0:
                    return 'X%d' % (index2 % p.M)
                else:
                    return 'M%d' % (index2 % p.M)

            model.input = spa.Input(cue=stim)

            self.p_same = nengo.Probe(model.same, synapse=0.01)
        return model
Example #9
0
    def get_network_learn(self, label):
        net = nengo.Network(label=label)

        with net:
            net.input = nengo.Node(size_in=1)
            net.ens = nengo.Ensemble(n_neurons=200,
                                     dimensions=1,
                                     neuron_type=nengo.Direct(),
                                     label='u')
            net.u_global = nengo.Ensemble(n_neurons=200,
                                          dimensions=1,
                                          label='f(u) global')

            net.u_local = nengo.Ensemble(
                n_neurons=400, dimensions=2,
                label='f(u) local')  # first shoulder, second elbow
            #net.u_shoulder = nengo.Ensemble(n_neurons=200, dimensions = 1)#, neuron_type=nengo.Direct())
            # net.u_elbow = nengo.Ensemble(n_neurons=200, dimensions = 1)#, neuron_type=nengo.Direct())

            net.output = nengo.Node(size_in=len(self._joints))

            nengo.Connection(net.input, net.ens)
            nengo.Connection(net.ens, net.u_global, function=self.get_u)

            nengo.Connection(net.u_local[0],
                             net.output[0],
                             function=self.map_voluntary_1)
            nengo.Connection(net.u_local[1],
                             net.output[1],
                             function=self.map_voluntary_2)
        return net
        '''
Example #10
0
    def model(self, p):
        random.seed(p.exp_seed)

        data_dir = os.path.join(
            os.path.dirname(__file__), os.pardir, os.pardir, 'data')
        sp_path = os.path.join(data_dir, 'associationmatrices')
        assoc, i2w, _ = load_assoc_mat(sp_path, p.assocmat)

        sp_path = os.path.join(data_dir, 'semanticpointers')
        pointers, _, _ = load_pointers(sp_path, p.sp_file)

        rat_path = os.path.join(data_dir, 'rat', p.ratfile)
        self.rat_items = list(filter_valid(load_rat_items(rat_path), i2w))

        with spa.SPA(seed=p.model_seed) as model:
            self.model = model
            # set up vocab
            self.vocab = model.get_default_vocab(p.d)
            for i, pointer in enumerate(pointers):
                sanitized = i2w[i].upper().replace(' ', '_').replace(
                    '+', '_').replace('-', '_').replace('&', '_').replace(
                        "'", '_')
                self.vocab.add(sanitized, pointer)

            # set up model
            self.stimulus = Stimulus(self.rat_items)
            model.stimulus = StimulusModule(
                self.stimulus, self.vocab, p.neurons_per_dimension)
            model.rat_model = FfwdConnectionsRat(
                assoc, self.vocab,
                neurons_per_dimension=p.neurons_per_dimension)
            nengo.Connection(model.stimulus.cue1.output, model.rat_model.cue1)
            nengo.Connection(model.stimulus.cue2.output, model.rat_model.cue2)
            nengo.Connection(model.stimulus.cue3.output, model.rat_model.cue3)
            self.p_output = nengo.Probe(
                model.rat_model.rat_state.output, synapse=0.003)
            self.p_cue1 = nengo.Probe(
                model.stimulus.cue1.output, synapse=0.003)
            self.p_cue2 = nengo.Probe(
                model.stimulus.cue2.output, synapse=0.003)
            self.p_cue3 = nengo.Probe(
                model.stimulus.cue3.output, synapse=0.003)
            self.p_spikes = nengo.Probe(
                model.rat_model.rat_state.state_ensembles.ensembles[0].neurons,
                'spikes')

            tr = np.dot(
                self.vocab.vectors.T,
                np.dot(assoc.T, self.vocab.vectors)) / 3.
            direct_result = nengo.Ensemble(
                n_neurons=1, dimensions=p.d, neuron_type=nengo.Direct())
            nengo.Connection(
                model.stimulus.cue1.output, direct_result, transform=tr)
            nengo.Connection(
                model.stimulus.cue2.output, direct_result, transform=tr)
            nengo.Connection(
                model.stimulus.cue3.output, direct_result, transform=tr)
            self.p_direct = nengo.Probe(direct_result, synapse=0.003)

        return model
Example #11
0
def test_place_ensembles():
    with nengo.Network() as net:
        add_params(net)
        offchip = nengo.Ensemble(10, 1, label="offchip")
        net.config[offchip].on_chip = False
        direct = nengo.Ensemble(1,
                                1,
                                neuron_type=nengo.Direct(),
                                label="direct")
        with nengo.Network():
            onchip = nengo.Ensemble(20, 1, label="onchip")
        pre = nengo.Ensemble(10, 1, label="pre")
        post = nengo.Ensemble(10, 1, label="post")
        error = nengo.Ensemble(10, 1, label="error")
        conn = nengo.Connection(pre, post, learning_rule_type=nengo.PES())
        nengo.Connection(error, conn.learning_rule)

    networks = SplitNetworks(net, node_neurons=default_node_neurons)
    place_ensembles(networks)
    assert networks.moves[offchip] == "host"
    assert networks.moves[direct] == "host"
    assert networks.moves[onchip] == "chip"
    assert networks.moves[pre] == "chip"
    assert networks.moves[post] == "host"
    assert networks.moves[error] == "host"
Example #12
0
    def get_network(self):
        net = nengo.Network()
        with net:
            #Nodes
            net.stim = nengo.Node(self._stim, label='Stimulus')
            net.input = nengo.Node(size_in=1)
            net.output = nengo.Node(size_in=self._num_joints)
            net.ros_out = nengo.Node(self.publish_topic,
                                     size_in=self._num_joints)

            #Ensembles
            net.u = nengo.Ensemble(n_neurons=200, dimensions=1, label='u')
            net.fu = nengo.Ensemble(n_neurons=200,
                                    dimensions=self._num_joints,
                                    radius=2,
                                    label='f(u)')
            net.gfu = nengo.Ensemble(n_neurons=100,
                                     dimensions=self._num_joints,
                                     radius=2,
                                     neuron_type=nengo.Direct(),
                                     label='g(f(u))')
            #Connections
            nengo.Connection(net.stim[0], net.input)
            nengo.Connection(net.input, net.u)
            nengo.Connection(net.u, net.fu, function=self.map_trajectory)
            nengo.Connection(net.fu, net.output, function=self.map)

            for i in range(self._num_joints):
                nengo.Connection(net.output[i], net.gfu[i])
            nengo.Connection(net.gfu, net.ros_out)

        return net
Example #13
0
def create_control_none_nengo(sim_dt=0.005, syn_tau=0.005):
    """Create a nengo network to foward receiver data to command data

    Parameters
    ----------
    sim_dt: float
        desired timestep of simulation (seconds)
    syn_tau: float
        synaptic time constant (seconds)
    """
    rdb = redis_util.DBRedis()
    net = nengo.Network()
    with net:
        stim = RedisNodeGetRx(rdb)
        ens = nengo.Ensemble(n_neurons=50,
                             dimensions=6,
                             neuron_type=nengo.Direct())
        preout = nengo.Node(lambda t, x: x, size_in=6, size_out=6)
        out = RedisNodeSetCmd(rdb)
        nengo.Connection(stim, ens, synapse=None)
        nengo.Connection(ens, preout, synapse=syn_tau)
        nengo.Connection(preout, out, synapse=None)
        # print signals
        print_node = PrintNode(print_wrapper, size_in=12)
        nengo.Connection(stim, print_node[:6], synapse=None)
        nengo.Connection(preout, print_node[6:], synapse=None)

    sim = nengo.Simulator(net, sim_dt, progress_bar=False)
    return sim
Example #14
0
    def __init__(self,
                 dimensions,
                 vocab=None,
                 neurons_per_multiply=200,
                 output_scaling=1.0,
                 radius=1.0,
                 direct=False):
        super(Compare, self).__init__()

        with self:
            if vocab is None:
                # use the default vocab for this number of dimensions
                vocab = dimensions

            self.output_scaling = output_scaling

            self.compare = Product(
                neurons_per_multiply,
                dimensions,
                radius=radius,
                neuron_type=nengo.Direct() if direct else nengo.LIF(),
                label='compare')

            self.inputA = nengo.Node(size_in=dimensions, label='inputA')
            self.inputB = nengo.Node(size_in=dimensions, label='inputB')
            self.output = nengo.Node(size_in=dimensions, label='output')

            self.inputs = dict(A=(self.inputA, vocab), B=(self.inputB, vocab))
            self.outputs = dict(default=(self.output, vocab))

            nengo.Connection(self.inputA, self.compare.A, synapse=None)
            nengo.Connection(self.inputB, self.compare.B, synapse=None)
def test_direct_window(legendre, Simulator, seed, plt):
    theta = 1.0
    T = theta

    assert np.allclose(t_default, np.linspace(0, 1, 1000))

    with Network() as model:
        stim = nengo.Node(output=lambda t: t)
        rw = RollingWindow(theta, n_neurons=1, dimensions=12,
                           neuron_type=nengo.Direct(), process=None,
                           legendre=legendre)
        assert rw.theta == theta
        assert rw.dt == 0.001
        assert rw.process is None
        assert rw.synapse == nengo.Lowpass(0.1)
        assert rw.input_synapse == nengo.Lowpass(0.1)

        nengo.Connection(stim, rw.input, synapse=None)
        output = rw.add_output(function=lambda w: np.sum(w**3)**2)
        p_output = nengo.Probe(output, synapse=None)

    with Simulator(model) as sim:
        sim.run(T)

    actual = sim.data[p_output].squeeze()
    t = sim.trange()
    ideal = shift(np.cumsum(t**3)**2)

    plt.figure()
    plt.plot(t, actual, label="Output")
    plt.plot(t, ideal, label="Ideal", linestyle='--')
    plt.legend()

    assert nrmse(actual, ideal) < 0.005
Example #16
0
def go(N=2000, d=None, f=None, t=100, l=False, neuron_type=LIF(),
       m=Uniform(30, 30), i=Uniform(-1, 1), r=30, IC=np.array([0,0,0]),
       seed=0, dt=0.001, dtSample=0.001):

    with nengo.Network(seed=seed) as model:
        inpt = nengo.Node(lambda t: IC*(t<=1.0))
        tar = nengo.Ensemble(1, 3, neuron_type=nengo.Direct())
        ens = nengo.Ensemble(N, 3, max_rates=m, intercepts=i, neuron_type=neuron_type, seed=seed, radius=r)
        dss = nengo.Node(DownsampleNode(size_in=N, size_out=N, dt=dt, dtSample=dtSample), size_in=N, size_out=N)
        nengo.Connection(inpt, tar, synapse=None)
        nengo.Connection(tar, tar, function=feedback, synapse=~s)
        if l:
            nengo.Connection(tar, ens, synapse=None, seed=seed)
        else:
            nengo.Connection(inpt, ens, synapse=None, seed=seed)
            nengo.Connection(ens, ens, synapse=f, solver=NoSolver(d), seed=seed)
        nengo.Connection(ens.neurons, dss, synapse=None)
        pTar = nengo.Probe(tar, synapse=None, sample_every=dtSample)
        pEns = nengo.Probe(dss, synapse=None, sample_every=dtSample)

    with nengo.Simulator(model, seed=seed, dt=dt, progress_bar=False) as sim:
        sim.run(t+dt, progress_bar=True)

    return dict(
        times=sim.trange(),
        tar=sim.data[pTar],
        ens=sim.data[pEns])
Example #17
0
def test_direct_mode_with_single_neuron(Simulator, plt, seed):
    radius = 2
    dim = 5

    config = nengo.Config(nengo.Ensemble)
    config[nengo.Ensemble].neuron_type = nengo.Direct()
    with config:
        product = nengo_extras.networks.Product(
            1, dim, radius, net=nengo.Network(seed=seed))

    func_A = lambda t: np.sqrt(radius)*np.sin(np.arange(1, dim+1)*2*np.pi*t)
    func_B = lambda t: np.sqrt(radius)*np.sin(np.arange(dim, 0, -1)*2*np.pi*t)
    with product:
        input_A = nengo.Node(func_A)
        input_B = nengo.Node(func_B)
        nengo.Connection(input_A, product.A)
        nengo.Connection(input_B, product.B)
        p = nengo.Probe(product.output, synapse=0.005)

    with Simulator(product) as sim:
        sim.run(1.0)

    t = sim.trange()
    AB = np.asarray(list(map(func_A, t))) * np.asarray(list(map(func_B, t)))
    delay = 0.013
    offset = np.where(t >= delay)[0]

    for i in range(dim):
        plt.subplot(dim+1, 1, i+1)
        plt.plot(t + delay, AB[:, i])
        plt.plot(t, sim.data[p][:, i])
        plt.xlim(right=t[-1])
        plt.yticks((-2, 0, 2))

    assert rmse(AB[:len(offset), :], sim.data[p][offset, :]) < 0.2
Example #18
0
    def __init__(self, task_grab, task_hold, grabbed):
        super(TaskGrabAndHold, self).__init__()
        if b_direct:
            self.config[nengo.Ensemble].neuron_type = nengo.Direct()

        with self:
            self.activation = nengo.Node(None, size_in=1)

            self.choice = nengo.Ensemble(n_neurons=300,
                                         dimensions=2,
                                         radius=1.5)
            nengo.Connection(self.activation, self.choice[0])
        nengo.Connection(grabbed.has_grabbed, self.choice[1])

        def choose_grab(x):
            if x[1] < 0.5 and x[0] > 0.5:
                return 1
            else:
                return 0

        nengo.Connection(self.choice,
                         task_grab.activation,
                         function=choose_grab)

        def choose_hold(x):
            if x[1] > 0.5 and x[0] > 0.5:
                return 1
            else:
                return 0

        nengo.Connection(self.choice,
                         task_hold.activation,
                         function=choose_hold)
def makeCarrier(t, fPre, fNMDA, dt=0.001, seed=0):
    stimWhite = nengo.processes.WhiteSignal(period=t / 4,
                                            high=10,
                                            rms=2,
                                            seed=seed)
    stimSin = lambda x: 2 * np.sin(4 * 2 * np.pi * x * 4 / t)
    if seed % 2 == 0:
        stimRamp = lambda x: 4 / t if (t / 4) < x < (3 * t / 4) else -4 / t
    else:
        stimRamp = lambda x: -4 / t if (t / 4) < x < (3 * t / 4) else 4 / t
    with nengo.Network() as model:
        uSignal = nengo.Node(stimWhite)
        # uSignal = nengo.Node(stimSin)
        uCarrier = nengo.Node(stimRamp)
        u = nengo.Ensemble(1, 1, neuron_type=nengo.Direct())
        nengo.Connection(uSignal, u, synapse=None)
        nengo.Connection(uCarrier, u, synapse=None)
        pU = nengo.Probe(u, synapse=None)
        pX = nengo.Probe(u, synapse=1 / s)
    with nengo.Simulator(model, progress_bar=False, dt=dt) as sim:
        sim.run(t + dt, progress_bar=False)
    plt.plot(fNMDA.filt(sim.data[pX]))
    plt.savefig('plots/testCarrier.pdf')
    funcU = lambda t: sim.data[pU][int(t / dt)]
    funcX = lambda t: sim.data[pX][int(t / dt)]
    return funcU, funcX
Example #20
0
    def __init__(self, target, botnet):
        super(Parallel, self).__init__()
        self.config[nengo.Ensemble].neuron_type = nengo.Direct()

        with self:
            self.all_diff = nengo.networks.EnsembleArray(
                n_neurons=200, n_ensembles=len(freqs), ens_dimensions=2)

            self.all_diff.add_output('product', lambda x: x[0] * x[1])
            self.slide = nengo.Ensemble(n_neurons=200, dimensions=2)
            nengo.Connection(self.all_diff.product,
                             self.slide[0],
                             transform=np.ones((1, len(freqs))))
            self.activation = nengo.Node(None, size_in=1)
            nengo.Connection(self.activation, self.slide[1], synapse=None)

        for i, ens in enumerate(self.all_diff.ensembles):
            nengo.Connection(botnet.tracker[12 * i + 0], ens[1], transform=0.5)
            nengo.Connection(botnet.tracker[12 * i + 4], ens[1], transform=0.5)

            nengo.Connection(botnet.tracker[12 * i + 0], ens[0], transform=1)
            nengo.Connection(botnet.tracker[12 * i + 4], ens[0], transform=-1)
            nengo.Connection(target.info[[0]], ens[0], transform=-1)
            nengo.Connection(target.info[[4]], ens[0], transform=1)

        nengo.Connection(
            self.slide,
            botnet.base_pos[1],
            function=lambda x: x[0] * x[1],
            transform=1,  # change this to -1 to swap direction
            # increase value to slide faster
        )
Example #21
0
def activate_direct_mode(network):
    """Activates direct mode for a network.

    This sets the neuron type of all ensembles to a `nengo.Direct`
    instance unless:

    - there is a connection to or from the ensemble's neurons
    - there is a probe on an ensemble's neurons
    - the ensemble has a connection with a learning rule attached.

    Parameters
    ----------
    network : Network
        Network to activate direct mode for.
    """
    requires_neurons = set()

    for c in network.all_connections:
        if isinstance(c.pre_obj, nengo.ensemble.Neurons):
            requires_neurons.add(c.pre_obj.ensemble)
        if isinstance(c.post_obj, nengo.ensemble.Neurons):
            requires_neurons.add(c.post_obj.ensemble)
        if c.learning_rule_type is not None:
            requires_neurons.add(c.pre_obj)
            requires_neurons.add(c.post_obj)

    for p in network.all_probes:
        if isinstance(p.obj, nengo.ensemble.Neurons):
            requires_neurons.add(p.obj.ensemble)

    for e in network.all_ensembles:
        if e not in requires_neurons:
            e.neuron_type = nengo.Direct()
Example #22
0
def go(d_ens, f_ens, n_neurons=3000, t=100, L=False, neuron_type=LIF(),
       m=Uniform(30, 40), i=Uniform(-1, 1), r=40, IC=np.array([1,1,1]),
       seed=0, dt=0.001, dt_sample=0.001, f=DoubleExp(1e-3, 1e-1)):

    with nengo.Network(seed=seed) as model:
        # Ensembles
        u = nengo.Node(lambda t: IC*(t<=1.0))
        x = nengo.Ensemble(1, 3, neuron_type=nengo.Direct())
        ens = nengo.Ensemble(n_neurons, 3, max_rates=m, intercepts=i, neuron_type=neuron_type, seed=seed, radius=r)
        dss = nengo.Node(DownsampleNode(size_in=n_neurons, size_out=n_neurons, dt=dt, dt_sample=dt_sample), size_in=n_neurons, size_out=n_neurons)

        # Connections
        nengo.Connection(u, x, synapse=None)
        nengo.Connection(x, x, function=feedback, synapse=~s)
        if L:
            supv = nengo.Ensemble(n_neurons, 3, neuron_type=SpikingRectifiedLinear(), radius=r, seed=seed)
            nengo.Connection(x, supv, synapse=None)
            nengo.Connection(supv, ens, synapse=f, seed=seed)
        else:
            nengo.Connection(ens, ens, synapse=f_ens, solver=NoSolver(d_ens), seed=seed)

        # Probes
        nengo.Connection(ens.neurons, dss, synapse=None)
        p_x = nengo.Probe(x, synapse=None, sample_every=dt_sample)
        p_ens = nengo.Probe(dss, synapse=None, sample_every=dt_sample)

    with nengo.Simulator(model, seed=seed, dt=dt) as sim:
        sim.run(t)

    return dict(
        times=sim.trange(),
        x=sim.data[p_x],
        ens=sim.data[p_ens])
Example #23
0
    def run_trial():
        model = nengo.Network(seed=rng.randint(maxint))
        with model:
            model.config[nengo.Ensemble].n_eval_points = n_eval_points

            stimulus = nengo.Node(
                output=lambda t: stimulus_fn(max(0., t - wait_duration)),
                size_out=2)

            product_net = nengo.networks.Product(n_neurons, 1)
            nengo.Connection(stimulus[0], product_net.input_a)
            nengo.Connection(stimulus[1], product_net.input_b)
            probe_test = nengo.Probe(product_net.output)

            ens_direct = nengo.Ensemble(1,
                                        dimensions=2,
                                        neuron_type=nengo.Direct())
            result_direct = nengo.Node(size_in=1)
            nengo.Connection(stimulus, ens_direct)
            nengo.Connection(ens_direct,
                             result_direct,
                             function=lambda x: x[0] * x[1],
                             synapse=None)
            probe_direct = nengo.Probe(result_direct)

        with Simulator(model) as sim:
            sim.run(duration + wait_duration, progress_bar=False)

        selection = sim.trange() > wait_duration
        test = sim.data[probe_test][selection]
        direct = sim.data[probe_direct][selection]
        return rmse(test, direct)
Example #24
0
def test_place_ensembles():
    # builder will move the learning stuff onto the host

    with nengo.Network() as net:
        add_params(net)
        offchip = nengo.Ensemble(10, 1, label="offchip")
        net.config[offchip].on_chip = False
        direct = nengo.Ensemble(
            1, 1, neuron_type=nengo.Direct(), label="direct")
        with nengo.Network():
            onchip = nengo.Ensemble(20, 1, label="onchip")
        pre = nengo.Ensemble(10, 1, label="pre")
        post = nengo.Ensemble(10, 1, label="post")
        error = nengo.Ensemble(10, 1, label="error")
        conn = nengo.Connection(pre, post, learning_rule_type=nengo.PES())
        nengo.Connection(error, conn.learning_rule)

    split = Split(net)
    assert not split.on_chip(offchip)
    assert not split.on_chip(direct)
    assert split.on_chip(onchip)
    assert split.on_chip(pre)
    assert not split.on_chip(post)
    assert not split.on_chip(error)

    for obj in net.all_ensembles + net.all_nodes:
        assert not split.is_precomputable(obj)

    with pytest.raises(BuildError, match="Locations are only established"):
        split.on_chip(conn)
Example #25
0
    def __init__(self, dimensions, subdimensions=16, neurons_per_dimension=50,
                 vocab=None, direct=False, label=None, seed=None,
                 add_to_container=None):
        warnings.warn("Buffer is deprecated in favour of spa.State",
                      DeprecationWarning)
        super(Buffer, self).__init__(label, seed, add_to_container)

        if vocab is None:
            # use the default one for this dimensionality
            vocab = dimensions
        elif vocab.dimensions != dimensions:
            raise ValueError('Dimensionality of given vocabulary (%d) does not'
                             'match dimensionality of buffer (%d)' %
                             (vocab.dimensions, dimensions))

        # Subdimensions should be at most the number of dimensions
        subdimensions = min(dimensions, subdimensions)

        if dimensions % subdimensions != 0:
            raise ValueError('Number of dimensions(%d) must be divisible by '
                             'subdimensions(%d)' % (dimensions, subdimensions))

        with self:
            self.state = nengo.networks.EnsembleArray(
                neurons_per_dimension * subdimensions,
                dimensions // subdimensions,
                ens_dimensions=subdimensions,
                neuron_type=nengo.Direct() if direct else nengo.LIF(),
                radius=np.sqrt(float(subdimensions) / dimensions),
                label='state')

        self.inputs = dict(default=(self.state.input, vocab))
        self.outputs = dict(default=(self.state.output, vocab))
Example #26
0
    def __init__(self, target, botnet):
        super(OrientLR, self).__init__()
        if b_direct:
            self.config[nengo.Ensemble].neuron_type = nengo.Direct()
        with self:
            self.x_data = nengo.Ensemble(n_neurons=500, dimensions=6, radius=3)
        nengo.Connection(target.info[[0,3,4,7,8,11]], self.x_data)

        with self:
            self.x_pos = nengo.Ensemble(n_neurons=200, dimensions=2)
            def compute_pos(x):
                lx, lc, rx, rc, ax, ac = x

                c = (lc + rc + ac)
                if c <= 0.1:
                    return 0
                return (lx*lc+rx*rc+ax*ac) / c

            nengo.Connection(self.x_data, self.x_pos[0], function=compute_pos)

            self.activation = nengo.Node(None, size_in=1)
            nengo.Connection(self.activation, self.x_pos[1], synapse=None)

        nengo.Connection(self.x_pos, botnet.base_pos[2],
                         function=lambda x: x[0]*x[1],
                         transform=-1)
Example #27
0
    def __init__(self, target, botnet, strength=1):
        super(ArmOrientLR, self).__init__()
        if b_direct:
            self.config[nengo.Ensemble].neuron_type = nengo.Direct()
        with self:
            self.x_data = nengo.Ensemble(n_neurons=500, dimensions=2, radius=3)
        nengo.Connection(target.info[[8,11]], self.x_data)

        with self:
            self.x_pos = nengo.Ensemble(n_neurons=200, dimensions=2)
            def compute_pos(x):
                x, c = x

                if c <= 0.1:
                    return 0
                return -x

            nengo.Connection(self.x_data, self.x_pos[0], function=compute_pos)

            self.activation = nengo.Node(None, size_in=1)
            nengo.Connection(self.activation, self.x_pos[1], synapse=None)

        nengo.Connection(self.x_pos, botnet.base_pos[2],
                         function=lambda x: x[0]*x[1],
                         transform=strength)
Example #28
0
    def __init__(self, target, botnet):
        super(OrientFB, self).__init__()
        if b_direct:
            self.config[nengo.Ensemble].neuron_type = nengo.Direct()

        with self:
            self.data = nengo.Ensemble(n_neurons=500, dimensions=2, radius=1.5)
        nengo.Connection(target.info[[0, 4]], self.data)

        with self:
            self.spd = nengo.Ensemble(n_neurons=500, dimensions=2, radius=1.5)
            def dist_func(x):
                mid = x[0]+x[1]
                diff = x[0] - x[1]

                target_separation = 0.8
                if -0.5<mid<0.5:
                    return (target_separation - diff)*10
                else:
                    return 0
            nengo.Connection(self.data, self.spd[0], function=dist_func)


            self.activation = nengo.Node(None, size_in=1)
            nengo.Connection(self.activation, self.spd[1], synapse=None)

        nengo.Connection(self.spd, botnet.base_pos[0],
                         function=lambda x: x[0]*x[1], transform=5.0)
Example #29
0
    def get_network_slider(self, label, inverted_reflex=False, factor=1):
        net = nengo.Network(label=label)
        with net:

            net.input = nengo.Node(size_in=1)
            net.ens = nengo.Ensemble(n_neurons=200,
                                     dimensions=1,
                                     neuron_type=nengo.Direct(),
                                     label='u')
            nengo.Connection(net.input, net.ens)
            net.output = nengo.Node(size_in=len(self._joints))
            if inverted_reflex:

                def reflex(x):
                    if x[1] < 0.1: return self.map_voluntary(x[0])
                    else: return self.map_voluntary(0.2)

                net.u = nengo.Ensemble(n_neurons=200,
                                       dimensions=2,
                                       neuron_type=nengo.Direct(),
                                       label='f(u)')
                nengo.Connection(net.ens, net.u[0], function=self.get_u)
                #nengo.Connection(net.u, net.output, function=self.map_voluntary)
                nengo.Connection(net.u, net.output, function=reflex)
                '''
                def invert(x):
                    return (-(self.get_u(x)-0.5) +0.5) * factor

                def map_inv_u(x):
                    if x[2] < 0.5: return self.map_voluntary(x[0])
                    else: return self.map_voluntary(x[1])

                net.u = nengo.Ensemble(n_neurons=400, dimensions = 3, neuron_type=nengo.Direct(), label = 'f(u)')
                nengo.Connection(net.ens, net.u[0], function = self.get_u)
                nengo.Connection(net.ens, net.u[1], function = invert)
                nengo.Connection(net.u, net.output, function=map_inv_u)
                '''
            else:
                net.u = nengo.Ensemble(n_neurons=200,
                                       dimensions=1,
                                       neuron_type=nengo.Direct(),
                                       label='f(u)')
                nengo.Connection(net.ens, net.u, function=self.get_u)
                nengo.Connection(net.u,
                                 net.output,
                                 function=self.map_voluntary)
        return net
Example #30
0
def test_node_to_ensemble(Simulator, nl_nodirect, plt, seed, allclose):
    N = 50

    m = nengo.Network(seed=seed)
    with m:
        m.config[nengo.Ensemble].neuron_type = nl_nodirect()
        input_node = nengo.Node(
            output=lambda t: [np.sin(t * 3), np.cos(t * 3)])
        a = nengo.Ensemble(N * 1, dimensions=1)
        b = nengo.Ensemble(N * 1, dimensions=1)
        c = nengo.Ensemble(N * 2, dimensions=2)
        d = nengo.Ensemble(N, neuron_type=nengo.Direct(), dimensions=3)

        nengo.Connection(input_node, a, function=lambda x: -x[0])
        nengo.Connection(input_node[:1], b, function=lambda x: -x)
        nengo.Connection(input_node, c, function=lambda x: -(x**2))
        nengo.Connection(input_node,
                         d,
                         function=lambda x: [-x[0], -(x[0]**2), -(x[1]**2)])

        a_p = nengo.Probe(a, "decoded_output", synapse=0.01)
        b_p = nengo.Probe(b, "decoded_output", synapse=0.01)
        c_p = nengo.Probe(c, "decoded_output", synapse=0.01)
        d_p = nengo.Probe(d, "decoded_output", synapse=0.01)

    with Simulator(m) as sim:
        sim.run(2.0)
    t = sim.trange()

    plt.plot(t, sim.data[a_p])
    plt.plot(t, sim.data[b_p])
    plt.plot(t, sim.data[c_p])
    plt.plot(t, sim.data[d_p])
    plt.legend(
        [
            "-sin",
            "-sin",
            "-(sin ** 2)",
            "-(cos ** 2)",
            "-sin",
            "-(sin ** 2)",
            "-(cos ** 2)",
        ],
        loc="best",
        fontsize="small",
    )

    assert allclose(sim.data[a_p][-10:],
                    sim.data[d_p][-10:][:, 0],
                    atol=0.1,
                    rtol=0.01)
    assert allclose(sim.data[b_p][-10:],
                    sim.data[d_p][-10:][:, 0],
                    atol=0.1,
                    rtol=0.01)
    assert allclose(sim.data[c_p][-10:],
                    sim.data[d_p][-10:][:, 1:3],
                    atol=0.1,
                    rtol=0.01)