Esempio n. 1
0
def test_inputgatedmemory(Simulator, plt, seed):
    to_memorize = 0.5
    start_memorizing = 0.4
    with nengo.Network(seed=seed) as net:
        test_input = nengo.Node(
            Piecewise({
                0.0: 0,
                0.1: to_memorize,
                start_memorizing + 0.1: 0
            }))
        gate_input = nengo.Node(Piecewise({0.0: 0, start_memorizing: 1}))
        reset_input = nengo.Node(0)

        mem = nengo.networks.InputGatedMemory(100, 1, difference_gain=5.0)
        nengo.Connection(test_input, mem.input)
        nengo.Connection(gate_input, mem.gate)
        nengo.Connection(reset_input, mem.reset)

        mem_p = nengo.Probe(mem.output, synapse=0.01)

    with Simulator(net) as sim:
        sim.run(0.5)

    data = sim.data[mem_p]
    t = sim.trange()

    plt.title("gating at %.1f s" % start_memorizing)
    plt.plot(t, data, label="value in memory")
    plt.axhline(to_memorize, c="k", lw=2, label="value to remember")
    plt.axvline(start_memorizing, c="k", ls=":", label="start gating")
    plt.legend(loc="best")

    assert abs(np.mean(data[t < 0.1])) < 0.01
    assert abs(np.mean(data[(t > 0.2) & (t <= 0.4)]) - 0.5) < 0.02
    assert abs(np.mean(data[t > 0.4]) - 0.5) < 0.02
Esempio n. 2
0
    def test_invalid_length(self):
        data = {0.05: [1, 0], 0.1: [1, 0, 0]}
        with pytest.raises(ValidationError):
            Piecewise(data)

        # check that scalars and length 1 arrays can be used interchangeably
        # (no validation error)
        Piecewise({0.05: [1], 0.1: 0})
Esempio n. 3
0
 def test_default_zero(self):
     process = Piecewise({0.05: 1, 0.1: 0})
     f = process.make_step(shape_in=(process.default_size_in, ),
                           shape_out=(process.default_size_out, ),
                           dt=process.default_dt,
                           rng=None)
     assert np.allclose(f(-10), [0.])
     assert np.allclose(f(0), [0.])
Esempio n. 4
0
 def test_default_zero(self):
     process = Piecewise({0.05: 1, 0.1: 0})
     f = process.make_step(shape_in=(process.default_size_in,),
                           shape_out=(process.default_size_out,),
                           dt=process.default_dt,
                           rng=None)
     assert np.allclose(f(-10), [0.])
     assert np.allclose(f(0), [0.])
Esempio n. 5
0
    def test_shape_out(self, value):
        process = Piecewise({1: value})
        f = process.make_step(shape_in=(process.default_size_in, ),
                              shape_out=(process.default_size_out, ),
                              dt=process.default_dt,
                              rng=None)

        assert np.array_equal(f(0), np.zeros(process.default_size_out))
        assert np.array_equal(f(2), np.ones(process.default_size_out))
Esempio n. 6
0
    def test_shape_out(self, value):
        process = Piecewise({1: value})
        f = process.make_step(shape_in=(process.default_size_in,),
                              shape_out=(process.default_size_out,),
                              dt=process.default_dt,
                              rng=None)

        assert np.array_equal(f(0), np.zeros(process.default_size_out))
        assert np.array_equal(f(2), np.ones(process.default_size_out))
Esempio n. 7
0
    def test_cubic_interpolation_warning(self):
        pytest.importorskip("scipy")

        # cubic interpolation with 0 not in times
        process = Piecewise({0.001: 0, 0.1: 0.1}, interpolation="cubic")
        with pytest.warns(UserWarning,
                          match="'cubic' interpolation.*for t=0.0"):
            try:
                process.run(0.001)
            except ValueError:
                pass  # scipy may raise a ValueError
Esempio n. 8
0
def test_ensemble_to_neurons(Simulator, nl_nodirect, plt, seed):
    N = 30

    m = nengo.Network(seed=seed)
    with m:
        m.config[nengo.Ensemble].neuron_type = nl_nodirect()
        a = nengo.Ensemble(N, dimensions=1)
        b = nengo.Ensemble(N, dimensions=1)
        inn = nengo.Node(output=np.sin)
        inh = nengo.Node(Piecewise({0: 0, 0.5: 1}))
        nengo.Connection(inn, a)
        nengo.Connection(inh, b)
        nengo.Connection(b, a.neurons, transform=[[-10]] * N)

        inn_p = nengo.Probe(inn, 'output')
        a_p = nengo.Probe(a, 'decoded_output', synapse=0.1)
        b_p = nengo.Probe(b, 'decoded_output', synapse=0.1)
        inh_p = nengo.Probe(inh, 'output')

    with Simulator(m) as sim:
        sim.run(1.0)
    t = sim.trange()
    ideal = np.sin(t)
    ideal[t >= 0.5] = 0

    plt.plot(t, sim.data[inn_p], label='Input')
    plt.plot(t, sim.data[a_p], label='Neuron approx, pstc=0.1')
    plt.plot(t, sim.data[b_p], label='Neuron approx of inhib sig, pstc=0.1')
    plt.plot(t, sim.data[inh_p], label='Inhib signal')
    plt.plot(t, ideal, label='Ideal output')
    plt.legend(loc=0, prop={'size': 10})

    assert np.allclose(sim.data[a_p][-10:], 0, atol=.1, rtol=.01)
    assert np.allclose(sim.data[b_p][-10:], 1, atol=.1, rtol=.01)
Esempio n. 9
0
def test_integrator(Simulator, plt, seed):
    model = nengo.Network(seed=seed)
    with model:
        inputs = {0: 0, 0.2: 1, 1: 0, 2: -2, 3: 0, 4: 1, 5: 0}
        input = nengo.Node(Piecewise(inputs))

        tau = 0.1
        T = nengo.networks.Integrator(tau, n_neurons=100, dimensions=1)
        nengo.Connection(input, T.input, synapse=tau)

        A = nengo.Ensemble(100, dimensions=1)
        nengo.Connection(A, A, synapse=tau)
        nengo.Connection(input, A, transform=tau, synapse=tau)

        input_p = nengo.Probe(input, sample_every=0.01)
        A_p = nengo.Probe(A, synapse=0.01, sample_every=0.01)
        T_p = nengo.Probe(T.ensemble, synapse=0.01, sample_every=0.01)

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

    t = sim.trange(sample_every=0.01)
    plt.plot(t, sim.data[A_p], label='Manual')
    plt.plot(t, sim.data[T_p], label='Template')
    plt.plot(t, sim.data[input_p], 'k', label='Input')
    plt.legend(loc='best')

    assert rmse(sim.data[A_p], sim.data[T_p]) < 0.1
Esempio n. 10
0
def test_node_to_neurons(Simulator, nl_nodirect, plt, seed, allclose):
    N = 50

    m = nengo.Network(seed=seed)
    with m:
        m.config[nengo.Ensemble].neuron_type = nl_nodirect()
        a = nengo.Ensemble(N, dimensions=1)
        inn = nengo.Node(output=np.sin)
        inh = nengo.Node(Piecewise({0: 0, 0.5: 1}))
        nengo.Connection(inn, a)
        nengo.Connection(inh, a.neurons, transform=[[-5]] * N)

        inn_p = nengo.Probe(inn, "output")
        a_p = nengo.Probe(a, "decoded_output", synapse=0.1)
        inh_p = nengo.Probe(inh, "output")

    with Simulator(m) as sim:
        sim.run(1.0)
    t = sim.trange()
    ideal = np.sin(t)
    ideal[t >= 0.5] = 0

    plt.plot(t, sim.data[inn_p], label="Input")
    plt.plot(t, sim.data[a_p], label="Neuron approx, synapse=0.1")
    plt.plot(t, sim.data[inh_p], label="Inhib signal")
    plt.plot(t, ideal, label="Ideal output")
    plt.legend(loc="best", fontsize="small")

    assert allclose(sim.data[a_p][-10:], 0, atol=0.1, rtol=0.01)
Esempio n. 11
0
def test_ensemble_to_neurons(Simulator, nl_nodirect, plt, seed, allclose):
    with nengo.Network(seed=seed) as net:
        net.config[nengo.Ensemble].neuron_type = nl_nodirect()
        ens = nengo.Ensemble(40, dimensions=1)
        inhibitor = nengo.Ensemble(40, dimensions=1)
        stim = nengo.Node(output=np.sin)
        inhibition = nengo.Node(Piecewise({0: 0, 0.5: 1}))
        nengo.Connection(stim, ens)
        nengo.Connection(inhibition, inhibitor)
        nengo.Connection(inhibitor,
                         ens.neurons,
                         transform=-10 * np.ones((ens.n_neurons, 1)))

        stim_p = nengo.Probe(stim, "output")
        ens_p = nengo.Probe(ens, "decoded_output", synapse=0.05)
        inhibitor_p = nengo.Probe(inhibitor, "decoded_output", synapse=0.05)
        inhibition_p = nengo.Probe(inhibition, "output")

    with Simulator(net) as sim:
        sim.run(1.0)
    t = sim.trange()
    ideal = np.sin(t)
    ideal[t >= 0.5] = 0

    plt.plot(t, sim.data[stim_p], label="Input")
    plt.plot(t, sim.data[ens_p], label="`ens` value, pstc=0.05")
    plt.plot(t, sim.data[inhibitor_p], label="`inhibitor` value, pstc=0.05")
    plt.plot(t, sim.data[inhibition_p], label="Inhibition signal")
    plt.plot(t, ideal, label="Ideal output")
    plt.legend(loc=0, prop={"size": 10})

    assert allclose(sim.data[ens_p][-10:], 0, atol=0.1, rtol=0.01)
    assert allclose(sim.data[inhibitor_p][-10:], 1, atol=0.1, rtol=0.01)
Esempio n. 12
0
    def test_invalid_interpolation_on_func(self):
        def func(t):
            return t

        with pytest.warns(UserWarning):
            process = Piecewise({0.05: 0, 0.1: func}, interpolation="linear")
        assert process.interpolation == "zero"
Esempio n. 13
0
    def test_fallback_to_zero(self, Simulator, monkeypatch):
        # Emulate not having scipy in case we have scipy
        monkeypatch.setitem(sys.modules, "scipy.interpolate", None)

        with pytest.warns(UserWarning):
            process = Piecewise({0.05: 1, 0.1: 0}, interpolation="linear")
        assert process.interpolation == "zero"
Esempio n. 14
0
def test_piecewise():
    pytest.importorskip("scipy.optimize")
    for interpolation in ("linear", "nearest", "slinear", "quadratic", "cubic"):
        assert repr(Piecewise({1: 0.1, 2: 0.2, 3: 0.3}, interpolation)) == (
            "Piecewise(data={1: array([0.1]), 2: array([0.2]), 3: array([0.3])}, "
            "interpolation=%r)" % interpolation
        )
Esempio n. 15
0
def test_oscillator(Simulator, plt, seed):
    model = nengo.Network(seed=seed)
    with model:
        inputs = {0: [1, 0], 0.5: [0, 0]}
        input = nengo.Node(Piecewise(inputs), label="Input")

        tau = 0.1
        freq = 5
        T = nengo.networks.Oscillator(tau, freq, n_neurons=100)
        nengo.Connection(input, T.input)

        A = nengo.Ensemble(100, dimensions=2)
        nengo.Connection(A,
                         A,
                         synapse=tau,
                         transform=[[1, -freq * tau], [freq * tau, 1]])
        nengo.Connection(input, A)

        in_probe = nengo.Probe(input, sample_every=0.01)
        A_probe = nengo.Probe(A, synapse=0.01, sample_every=0.01)
        T_probe = nengo.Probe(T.ensemble, synapse=0.01, sample_every=0.01)

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

    t = sim.trange(sample_every=0.01)
    plt.plot(t, sim.data[A_probe], label="Manual")
    plt.plot(t, sim.data[T_probe], label="Template")
    plt.plot(t, sim.data[in_probe], "k", label="Input")
    plt.legend(loc="best")

    assert rmse(sim.data[A_probe], sim.data[T_probe]) < 0.2
Esempio n. 16
0
    def build(self, testY):
        self.count = 0

        def update(x):
            """
                Kalman Filter: X_k = A * X_k_1 + B * Y_k

            """
            Externalmat = np.mat(x[2:4]).T
            Inputmat = np.mat(x[0:2]).T
            Controlmat = np.matrix([[x[4], x[5]], [x[6], x[7]]])

            next_state = np.squeeze(
                np.asarray(Controlmat * Inputmat + Externalmat))
            return next_state

        with self.model:
            Dir_Nurons = nengo.Ensemble(1,
                                        dimensions=2 + 2 + 4,
                                        neuron_type=nengo.Direct())

            LIF_Neurons = nengo.Ensemble(
                self.N_A,
                dimensions=2,
                intercepts=Uniform(-1, 1),
                max_rates=Uniform(self.rate_A[0], self.rate_A[1]),
                neuron_type=nengo.LIFRate(tau_rc=self.t_rc,
                                          tau_ref=self.t_ref))

            state_func = Piecewise({
                0.0: [0.0, 0.0],
                self.dt:
                np.squeeze(np.asarray(np.mat([testY[0], testY[1]]).T)),
                2 * self.dt: [0.0, 0.0]
            })

            state = nengo.Node(output=state_func)
            # state_probe = nengo.Probe(state)

            external_input = nengo.Node(output=lambda t: self.data(t))
            # external_input_probe = nengo.Probe(external_input)

            control_signal = nengo.Node(output=lambda t: self.control(t))

            conn0 = nengo.Connection(state, Dir_Nurons[0:2])
            #
            conn1 = nengo.Connection(external_input, Dir_Nurons[2:4])

            conn2 = nengo.Connection(control_signal, Dir_Nurons[4:8])

            conn3 = nengo.Connection(Dir_Nurons,
                                     LIF_Neurons[0:2],
                                     function=update,
                                     synapse=self.tau)

            conn4 = nengo.Connection(LIF_Neurons[0:2], Dir_Nurons[0:2])

            self.output = nengo.Probe(LIF_Neurons[0:2])
            self.sim = nengo.Simulator(self.model, dt=self.dt)
Esempio n. 17
0
    def test_invalid_callable(self):
        def badcallable(t):
            raise RuntimeError()

        data = {0.05: 1, 0.1: badcallable}
        with pytest.raises(ValidationError,
                           match="should return a numerical const"):
            Piecewise(data)
Esempio n. 18
0
    def test_invalid_interpolation_on_func(self):
        def func(t):
            return t

        with pytest.warns(UserWarning,
                          match="cannot be applied.*callable was sup"):
            process = Piecewise({0.05: 0, 0.1: func}, interpolation="linear")
        assert process.interpolation == "zero"
Esempio n. 19
0
    def run_sim(self, data, interpolation, Simulator):
        process = Piecewise(data, interpolation=interpolation)

        with nengo.Network() as model:
            u = nengo.Node(process, size_out=process.default_size_out)
            up = nengo.Probe(u)

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

        return sim.trange(), sim.data[up]
Esempio n. 20
0
def test_processes():
    assert (
        repr(WhiteSignal(0.2, 10, rms=0.3))
        == "WhiteSignal(period=0.2, high=10, rms=0.3)"
    )

    check_init_args(WhiteNoise, ["dist", "scale"])
    check_repr(WhiteNoise(scale=False))
    assert repr(WhiteNoise()) == "WhiteNoise()"
    assert repr(WhiteNoise(scale=False)) == "WhiteNoise(scale=False)"

    check_init_args(FilteredNoise, ["synapse", "dist", "scale"])
    check_repr(FilteredNoise(scale=False))
    assert repr(FilteredNoise()) == "FilteredNoise()"
    assert repr(FilteredNoise(scale=False)) == "FilteredNoise(scale=False)"

    check_init_args(BrownNoise, ["dist"])
    check_repr(BrownNoise())
    assert repr(BrownNoise()) == "BrownNoise()"

    check_init_args(PresentInput, ["inputs", "presentation_time"])
    check_repr(PresentInput(inputs=np.array([1.2, 3.4]), presentation_time=5))
    assert (
        repr(PresentInput((1.2, 3.4), 5))
        == "PresentInput(inputs=array([1.2, 3.4]), presentation_time=5)"
    )

    check_init_args(WhiteSignal, ["period", "high", "rms", "y0"])
    check_repr(WhiteSignal(period=1.2, high=3.4, rms=5.6, y0=7.8))
    assert repr(WhiteSignal(1, 2)) == "WhiteSignal(period=1, high=2)"
    assert (
        repr(WhiteSignal(1.2, 3.4, 5.6, 7.8))
        == "WhiteSignal(period=1.2, high=3.4, rms=5.6, y0=7.8)"
    )

    check_init_args(Piecewise, ["data", "interpolation"])
    check_repr(Piecewise(data={1: 0.1, 2: 0.2, 3: 0.3}))
    assert (
        repr(Piecewise({1: 0.1, 2: 0.2, 3: 0.3}))
        == "Piecewise(data={1: array([0.1]), 2: array([0.2]), 3: array([0.3])})"
    )
Esempio n. 21
0
        def create_switcher(leg, swing, stance, init="swing"):
            start_signal = nengo.Node(Piecewise({
                0: -1 if init == "swing" else 1,
                0.01: 0,
            }),
                                      label=f"init_phase{leg}")

            s = nengo.Ensemble(2,
                               1,
                               radius=1,
                               intercepts=[0, 0],
                               max_rates=[400, 400],
                               encoders=[[-1], [1]],
                               label=f"s{leg}")
            nengo.Connection(s, s, synapse=tau)

            nengo.Connection(start_signal, s, synapse=tau)

            nengo.Connection(s,
                             swing.neurons,
                             function=positive_signal,
                             synapse=tau)
            nengo.Connection(s,
                             stance.neurons,
                             function=negative_signal,
                             synapse=tau)

            thresh_pos = nengo.Ensemble(1,
                                        1,
                                        intercepts=[0.47],
                                        max_rates=[400],
                                        encoders=[[1]],
                                        label=f"thresh_pos{leg}")
            nengo.Connection(swing[0],
                             thresh_pos,
                             function=lambda x: x - 0.5,
                             synapse=tau)
            nengo.Connection(thresh_pos, s, transform=[100], synapse=tau)
            thresh_neg = nengo.Ensemble(1,
                                        1,
                                        intercepts=[0.47],
                                        max_rates=[400],
                                        encoders=[[1]],
                                        label=f"thresh_neg{leg}")
            nengo.Connection(stance[0],
                             thresh_neg,
                             function=lambda x: x - 0.5,
                             synapse=tau)
            nengo.Connection(thresh_neg, s, transform=[-100], synapse=tau)

            return s, thresh_pos, thresh_neg
Esempio n. 22
0
    def temps2stimuli(self):

        for i in range(0, self.NumberOfInstances):

            stimulus = Stimulus(self.Temperatures[i], i)
            stimulus.spikecount2stimulus()
            self.SpikeCounts[i] = stimulus.SpikeCount
            self.StimuliMagnitude[i] = stimulus.StimulusMagnitude
            self.HPRewards.append(stimulus.HPReward)
            c = stimulus.StimulusDic[i]
            c = c[0]
            stimulus.StimulusDic = {self.MomentsInTime[i]: c}

        self.StimuliDic = {**self.StimuliDic, **stimulus.StimulusDic}
        self.NetworkInputs = Piecewise(self.StimuliDic)

import nengo
import numpy as np
from nengo.processes import Piecewise


model = nengo.Network()

with model:

    stimAinput = Piecewise({0: 0, 1 : 1, 2: 0, 3: 1, 4: 0, 5: 1, 6:0, 7:0, 8:0,9:0,10:0})
    stimBinput = Piecewise({0: 1, 1 : 0, 2: 1, 3: 0, 4: 1, 5: 0, 6:0, 7:0, 8:0,9:0,10:0})

    stimCinput = Piecewise({0: 0, 1 : 0, 2: 0, 3: 0, 4: 0, 5: 0, 6:1, 7:0, 8:1, 9:0, 10:1})
    stimDinput = Piecewise({0: 0, 1 : 0, 2: 0, 3: 0, 4: 0, 5: 0, 6:0, 7:1, 8:0, 9:1, 10:0})

    stimA = nengo.Node( stimAinput )
    stimB = nengo.Node( stimBinput )
    stimC = nengo.Node( stimCinput )
    stimD = nengo.Node( stimDinput )

    ensPreA  = nengo.Ensemble(100, dimensions = 1)
    ensPreB =  nengo.Ensemble(100, dimensions = 1)
    ensPreC  = nengo.Ensemble(100, dimensions = 1)
    ensPreD =  nengo.Ensemble(100, dimensions = 1)

    ensPost1 = nengo.Ensemble(100, dimensions = 1, radius = 1.4)
    ensPost2 = nengo.Ensemble(100, dimensions = 1, radius = 1.4)

    nengo.Connection(stimA, ensPreA)
Esempio n. 24
0
    def spikecount2stimulus(self):

        self.temperature2spikecount()
        self.StimulusMagnitude = 2 * (self.SpikeCount / 25) - 1
        self.StimulusDic = {self.TimeInstance: self.StimulusMagnitude}
        self.NetworkInput = Piecewise(self.StimulusDic)
Esempio n. 25
0
        nengo.Connection(AND.I,
                         AND.O,
                         function=prod_func,
                         learning_rule_type=nengo.PES(learning_rate=2e-4))
    return AND


model = nengo.Network(label='Fuzzy operations')
with model:
    time = np.arange(0, 2.5, 0.01)
    input_1 = time - 1.5
    input_2 = -time / 2 + 0.75
    input_3 = (time - 1.5)**2

    stim_1 = nengo.Node(Piecewise(dict(zip(time, input_1))))
    stim_2 = nengo.Node(Piecewise(dict(zip(time, input_2))))
    stim_3 = nengo.Node(Piecewise(dict(zip(time, input_3))))

    prod_op = AND_OPERATION()
    nengo.Connection(stim_1, prod_op.I[0])
    nengo.Connection(stim_2, prod_op.I[1])

    min_op = AND_OPERATION()
    nengo.Connection(stim_1, min_op.I[0])
    nengo.Connection(stim_2, min_op.I[1])

    bdif_op = AND_OPERATION()
    nengo.Connection(stim_1, bdif_op.I[0])
    nengo.Connection(stim_2, bdif_op.I[1])
Esempio n. 26
0
 Piecewise({
     0: 1,
     0.5: -1,
     1: 1,
     1.5: -1,
     2: 1,
     2.5: -1,
     3: 1,
     3.5: -1,
     4: 1,
     4.5: -1,
     5: 1,
     5.5: -1,
     6: 1,
     6.5: -1,
     7: 1,
     7.5: -1,
     8: 1,
     8.5: -1,
     9: 1,
     9.5: -1,
     10: 1,
     10.5: -1,
     11: 1,
     11.5: -1,
     12: 1,
     12.5: -1,
     13: 1,
     13.5: -1,
     14: 1,
     14.5: -1,
     15: 1,
     15.5: -1,
     16: 1,
     16.5: -1,
     17: 1,
     17.5: -1,
     18: 1,
     18.5: -1,
     19: 1,
     19.5: -1,
     20: 1
 }))
Esempio n. 27
0
# model
model = nengo.Network(label="Multiplication")

with model:
    A = nengo.Ensemble(100, dimensions=1, radius=10)
    B = nengo.Ensemble(100, dimensions=1, radius=10)

    combined = nengo.Ensemble(220, dimensions=2, radius=15)

    prod = nengo.Ensemble(100, dimensions=1, radius=20)

combined.encoders = Choice([[1, 1], [-1, 1], [1, -1], [-1, -1]])

with model:
    input_A = nengo.Node(Piecewise({0: 0, 2.5: 10, 4: -10}))
    input_B = nengo.Node(Piecewise({0: 10, 1.5: 2, 3: 0, 4.5: 2}))

    correct_ans = Piecewise({0: 0, 1.5: 0, 2.5: 20, 3: 0, 4: 0, 4.5: -20})

with model:
    nengo.Connection(input_A, A)
    nengo.Connection(input_B, B)

    nengo.Connection(A, combined[0])
    nengo.Connection(B, combined[1])

    def product(x):
        return x[0] * x[1]

    nengo.Connection(combined, prod, function=product)
Esempio n. 28
0
import nengo
import numpy as np
from nengo.processes import Piecewise

with nengo.Network() as model:
    nd_stim = nengo.Node(Piecewise({
        1.0: 1.0,
        2.0: 0.0,
    }))
    ens_x = nengo.Ensemble(
        n_neurons=100,
        dimensions=1,
    )

    tau = 100e-3

    A = np.array([[0.0]], dtype=float)

    B = np.array([[1.0]], dtype=float)

    Ap = tau * A + np.eye(A.shape[0])
    Bp = tau * B

    nengo.Connection(ens_x, ens_x, transform=Ap, synapse=tau)
    nengo.Connection(nd_stim, ens_x, transform=Bp, synapse=tau)
Esempio n. 29
0
def create_CPG(*, params, state_neurons=400, noise=0, **args):
    """
    Fuctions creates spiking CPG model using input parameters
    
    Parameters
    ----------
    params : dict
        Includes dicionary with CPG model parameters 
        describing model dynamics
    state_neurons : int
        Number of parameners to use for swing and stance 
        state representation including integrator and speed control 
    noise : float
        Controls noise for integrator output for all 4 states
        
    Returns
    -------
    Nengo model
    """
    def swing_feedback(state):
        """
            Function transforms differential equations for
            swing state updates to a format acceptable for nengo
            recurrent connection
        """
        x, speed = state
        dX = params["init_swing"] + params["speed_swing"] * speed + \
            params["inner_inhibit"] * x
        return dX * tau + x

    def stance_feedback(state):
        x, speed = state
        dX = params["init_stance"] + params["speed_stance"] * speed + \
            params["inner_inhibit"] * x
        return dX * tau + x

    def positive_signal(x):
        """
        Function implements inhibition for state neurons in case
        state variable is bigger then 0
        We use this function to switch active group 
        """
        if x > 0:
            return [-100] * state_neurons
        else:
            return [0] * state_neurons

    def negative_signal(x):
        if x < 0:
            return [-100] * state_neurons
        else:
            return [0] * state_neurons

    model = nengo.Network(seed=42)
    with model:
        # Becase we integrate from 0 to 1
        # There is no point to train our connections on negative numbers
        eval_points_dist = Uniform(0, 1)

        # Additional check in case we want to add noise
        if noise > 0:
            noise_proces = nengo.processes.WhiteNoise(
                dist=nengo.dists.Gaussian(0, noise), seed=1)
        else:
            noise_proces = None

        ## creating main state variables
        model.swing1 = nengo.Ensemble(state_neurons,
                                      2,
                                      radius=radius,
                                      label="swing1",
                                      noise=noise_proces,
                                      eval_points=eval_points_dist)

        model.stance1 = nengo.Ensemble(state_neurons,
                                       2,
                                       radius=radius,
                                       label="stance1",
                                       noise=noise_proces,
                                       eval_points=eval_points_dist)

        model.swing2 = nengo.Ensemble(state_neurons,
                                      2,
                                      radius=radius,
                                      label="swing2",
                                      noise=noise_proces,
                                      eval_points=eval_points_dist)

        model.stance2 = nengo.Ensemble(state_neurons,
                                       2,
                                       radius=radius,
                                       label="stance2",
                                       noise=noise_proces,
                                       eval_points=eval_points_dist)

        # Nengo automatically sample points
        # In out case we want to control this process
        eval_points_sample = np.random.rand(10000, 2)

        # Setting recurrent connections
        nengo.Connection(model.swing1,
                         model.swing1[0],
                         function=swing_feedback,
                         synapse=tau,
                         eval_points=eval_points_sample)
        nengo.Connection(model.stance1,
                         model.stance1[0],
                         function=stance_feedback,
                         synapse=tau,
                         eval_points=eval_points_sample)
        nengo.Connection(model.swing2,
                         model.swing2[0],
                         function=swing_feedback,
                         synapse=tau,
                         eval_points=eval_points_sample)
        nengo.Connection(model.stance2,
                         model.stance2[0],
                         function=stance_feedback,
                         synapse=tau,
                         eval_points=eval_points_sample)

        for group in [
            (model.swing1, model.stance1, model.swing2, model.stance2),
            (model.swing2, model.stance2, model.swing1, model.stance1)
        ]:
            swing_left, stance_left, swing_right, stance_right = group
            nengo.Connection(swing_left[0],
                             swing_right[0],
                             function=lambda x: tau *
                             (1 - x) * params["sw_sw_con"],
                             synapse=tau)

            nengo.Connection(swing_left[0],
                             stance_right[0],
                             function=lambda x: tau *
                             (1 - x) * params["sw_st_con"],
                             synapse=tau)

            nengo.Connection(stance_left[0],
                             swing_right[0],
                             function=lambda x: tau *
                             (1 - x) * params["st_sw_con"],
                             synapse=tau)

            nengo.Connection(stance_left[0],
                             stance_right[0],
                             function=lambda x: tau *
                             (1 - x) * params["st_st_con"],
                             synapse=tau)

        def create_switcher(leg, swing, stance, init="swing"):
            start_signal = nengo.Node(Piecewise({
                0: -1 if init == "swing" else 1,
                0.01: 0,
            }),
                                      label=f"init_phase{leg}")

            s = nengo.Ensemble(2,
                               1,
                               radius=1,
                               intercepts=[0, 0],
                               max_rates=[400, 400],
                               encoders=[[-1], [1]],
                               label=f"s{leg}")
            nengo.Connection(s, s, synapse=tau)

            nengo.Connection(start_signal, s, synapse=tau)

            nengo.Connection(s,
                             swing.neurons,
                             function=positive_signal,
                             synapse=tau)
            nengo.Connection(s,
                             stance.neurons,
                             function=negative_signal,
                             synapse=tau)

            thresh_pos = nengo.Ensemble(1,
                                        1,
                                        intercepts=[0.47],
                                        max_rates=[400],
                                        encoders=[[1]],
                                        label=f"thresh_pos{leg}")
            nengo.Connection(swing[0],
                             thresh_pos,
                             function=lambda x: x - 0.5,
                             synapse=tau)
            nengo.Connection(thresh_pos, s, transform=[100], synapse=tau)
            thresh_neg = nengo.Ensemble(1,
                                        1,
                                        intercepts=[0.47],
                                        max_rates=[400],
                                        encoders=[[1]],
                                        label=f"thresh_neg{leg}")
            nengo.Connection(stance[0],
                             thresh_neg,
                             function=lambda x: x - 0.5,
                             synapse=tau)
            nengo.Connection(thresh_neg, s, transform=[-100], synapse=tau)

            return s, thresh_pos, thresh_neg

        model.s1, thresh1, thresh2 = create_switcher("1",
                                                     model.swing1,
                                                     model.stance1,
                                                     init="swing")
        model.s2, thresh3, thresh4 = create_switcher("2",
                                                     model.swing2,
                                                     model.stance2,
                                                     init="stance")

        init_stance = nengo.Node(Piecewise({
            0: params["init_stance_position"],
            0.01: 0,
        }),
                                 label="init_stance")

        nengo.Connection(init_stance, model.stance2[0], synapse=tau)

        if "time" in args:
            time = args["time"]
        else:
            time = 95

        model.speed = nengo.Ensemble(state_neurons, 1, label="speed")
        speed_set = nengo.Node(lambda t: t / time)
        nengo.Connection(speed_set, model.speed)

        nengo.Connection(model.speed, model.swing1[1], synapse=tau)
        nengo.Connection(model.speed, model.stance1[1], synapse=tau)
        nengo.Connection(model.speed, model.swing2[1], synapse=tau)
        nengo.Connection(model.speed, model.stance2[1], synapse=tau)

        if "disable" in args:

            def funk(t):

                np.random.seed(0)

                disable_count = int(count * (t / 95))

                disable_i = np.random.choice(state_neurons,
                                             disable_count,
                                             replace=False)

                neuron_signal = np.zeros(state_neurons)

                neuron_signal[disable_i] = -30

                return neuron_signal

            if_damage = nengo.Node(funk, label="dmg")

            nengo.Connection(if_damage, model.swing1.neurons, synapse=tau)

            nengo.Connection(if_damage, model.stance1.neurons, synapse=tau)

            nengo.Connection(if_damage, model.swing2.neurons, synapse=tau)

            nengo.Connection(if_damage, model.stance2.neurons, synapse=tau)

    return model
Esempio n. 30
0
 def test_invalid_function_length(self):
     with pytest.raises(ValidationError, match="time 1.0 has size 2"):
         Piecewise({0.5: 0, 1.0: lambda t: [t, t**2]})
Esempio n. 31
0
 def test_invalid_interpolation_type(self):
     data = {0.05: 1, 0.1: 0}
     with pytest.raises(ValidationError):
         Piecewise(data, interpolation="not-interpolation")
Esempio n. 32
0
 def test_invalid_key(self):
     data = {0.05: 1, 0.1: 0, "a": 0.2}
     with pytest.raises(ValidationError,
                        match=r"Keys must be times \(floats or in"):
         Piecewise(data)