Example #1
0
def test_seed(Simulator, seed):
    with nengo.Network() as model:
        a = nengo.Node(WhiteSignal(0.1, high=100, seed=seed))
        b = nengo.Node(WhiteSignal(0.1, high=100, seed=seed + 1))
        c = nengo.Node(WhiteSignal(0.1, high=100))
        d = nengo.Node(WhiteNoise(seed=seed))
        e = nengo.Node(WhiteNoise())
        ap = nengo.Probe(a)
        bp = nengo.Probe(b)
        cp = nengo.Probe(c)
        dp = nengo.Probe(d)
        ep = nengo.Probe(e)

    with Simulator(model) as sim1:
        sim1.run(0.1)

    with Simulator(model) as sim2:
        sim2.run(0.1)

    tols = dict(atol=1e-7, rtol=1e-4)
    assert np.allclose(sim1.data[ap], sim2.data[ap], **tols)
    assert np.allclose(sim1.data[bp], sim2.data[bp], **tols)
    assert not np.allclose(sim1.data[cp], sim2.data[cp], **tols)
    assert not np.allclose(sim1.data[ap], sim1.data[bp], **tols)
    assert np.allclose(sim1.data[dp], sim2.data[dp], **tols)
    assert not np.allclose(sim1.data[ep], sim2.data[ep], **tols)
Example #2
0
def test_noise_gen(Simulator, nl_nodirect, seed, plt):
    """Ensure that setting Ensemble.noise generates noise."""
    with nengo.Network(seed=seed) as model:
        gain, bias = 1, 2
        neg_noise, pos_noise = -4, 5
        model.config[nengo.Ensemble].neuron_type = nl_nodirect()
        model.config[nengo.Ensemble].encoders = Choice([[1]])
        model.config[nengo.Ensemble].gain = Choice([gain])
        model.config[nengo.Ensemble].bias = Choice([bias])
        pos = nengo.Ensemble(1, 1, noise=WhiteNoise(Gaussian(pos_noise, 0.01)))
        normal = nengo.Ensemble(1, 1)
        neg = nengo.Ensemble(1, 1, noise=WhiteNoise(Gaussian(neg_noise, 0.01)))
        pos_p = nengo.Probe(pos.neurons, synapse=0.1)
        normal_p = nengo.Probe(normal.neurons, synapse=0.1)
        neg_p = nengo.Probe(neg.neurons, synapse=0.1)
    with Simulator(model) as sim:
        sim.run(0.06)

    t = sim.trange()
    plt.title("bias=%d, gain=%d" % (bias, gain))
    plt.plot(t, sim.data[pos_p], c='b', label="noise=%d" % pos_noise)
    plt.plot(t, sim.data[normal_p], c='k', label="no noise")
    plt.plot(t, sim.data[neg_p], c='r', label="noise=%d" % neg_noise)
    plt.legend(loc="best")

    assert np.all(sim.data[pos_p] >= sim.data[normal_p])
    assert np.all(sim.data[normal_p] >= sim.data[neg_p])
    assert not np.allclose(sim.data[normal_p], sim.data[pos_p])
    assert not np.allclose(sim.data[normal_p], sim.data[neg_p])
Example #3
0
def test_noise_gen(Simulator, nl_nodirect, seed, plt, allclose):
    """Ensure that setting Ensemble.noise generates noise."""
    with nengo.Network(seed=seed) as model:
        intercepts = -0.5
        neg_noise, pos_noise = -5, 5
        model.config[nengo.Ensemble].neuron_type = nl_nodirect()
        model.config[nengo.Ensemble].encoders = Choice([[1]])
        model.config[nengo.Ensemble].intercepts = Choice([intercepts])
        pos = nengo.Ensemble(1, 1, noise=WhiteNoise(Uniform(0, pos_noise)))
        normal = nengo.Ensemble(1, 1)
        neg = nengo.Ensemble(1, 1, noise=WhiteNoise(Uniform(neg_noise, 0)))
        pos_p = nengo.Probe(pos.neurons, synapse=0.1)
        normal_p = nengo.Probe(normal.neurons, synapse=0.1)
        neg_p = nengo.Probe(neg.neurons, synapse=0.1)
    with Simulator(model) as sim:
        sim.run(0.06)

    t = sim.trange()
    plt.title("intercepts=%d" % intercepts)
    plt.plot(t, sim.data[pos_p], c="b", label="noise=%d" % pos_noise)
    plt.plot(t, sim.data[normal_p], c="k", label="no noise")
    plt.plot(t, sim.data[neg_p], c="r", label="noise=%d" % neg_noise)
    plt.legend(loc="best")

    assert np.sum(sim.data[pos_p], axis=0) >= np.sum(sim.data[normal_p],
                                                     axis=0)
    assert np.sum(sim.data[normal_p], axis=0) >= np.sum(sim.data[neg_p],
                                                        axis=0)
    assert not allclose(sim.data[normal_p], sim.data[pos_p], record_rmse=False)
    assert not allclose(sim.data[normal_p], sim.data[neg_p], record_rmse=False)
Example #4
0
def test_whitenoise(rng):
    dist = DistributionMock(42)
    process = WhiteNoise(dist, scale=False)
    samples = process.run_steps(5, d=2, rng=rng)
    assert np.all(samples == 42 * np.ones((5, 2)))
    assert process.run_steps(5, rng=rng).shape == (5, 1)
    assert process.run_steps(1, d=1, rng=rng).shape == (1, 1)
    assert process.run_steps(2, d=3, rng=rng).shape == (2, 3)
Example #5
0
def test_whitenoise(rng):
    dist = DistributionMock(42)
    process = WhiteNoise(dist, scale=False)
    samples = process.run_steps(5, d=2, rng=rng)
    assert np.all(samples == 42 * np.ones((5, 2)))
    assert process.run_steps(5, rng=rng).shape == (5, 1)
    assert process.run_steps(1, d=1, rng=rng).shape == (1, 1)
    assert process.run_steps(2, d=3, rng=rng).shape == (2, 3)
Example #6
0
def test_operators():
    sig = Signal(np.array([0.0]), name="sig")
    assert fnmatch(repr(TimeUpdate(sig, sig)), "<TimeUpdate at 0x*>")
    assert fnmatch(repr(TimeUpdate(sig, sig, tag="tag")),
                   "<TimeUpdate 'tag' at 0x*>")
    assert fnmatch(repr(Reset(sig)), "<Reset at 0x*>")
    assert fnmatch(repr(Reset(sig, tag="tag")), "<Reset 'tag' at 0x*>")
    assert fnmatch(repr(Copy(sig, sig)), "<Copy at 0x*>")
    assert fnmatch(repr(Copy(sig, sig, tag="tag")), "<Copy 'tag' at 0x*>")
    assert fnmatch(repr(ElementwiseInc(sig, sig, sig)),
                   "<ElementwiseInc at 0x*>")
    assert fnmatch(repr(ElementwiseInc(sig, sig, sig, tag="tag")),
                   "<ElementwiseInc 'tag' at 0x*>")
    assert fnmatch(repr(DotInc(sig, sig, sig)), "<DotInc at 0x*>")
    assert fnmatch(repr(DotInc(sig, sig, sig, tag="tag")),
                   "<DotInc 'tag' at 0x*>")
    assert fnmatch(repr(SimPyFunc(sig, lambda x: 0.0, True, sig)),
                   "<SimPyFunc at 0x*>")
    assert fnmatch(
        repr(SimPyFunc(sig, lambda x: 0.0, True, sig, tag="tag")),
        "<SimPyFunc 'tag' at 0x*>",
    )
    assert fnmatch(repr(SimPES(sig, sig, sig, 0.1)), "<SimPES at 0x*>")
    assert fnmatch(repr(SimPES(sig, sig, sig, 0.1, tag="tag")),
                   "<SimPES 'tag' at 0x*>")
    assert fnmatch(repr(SimBCM(sig, sig, sig, sig, 0.1)), "<SimBCM at 0x*>")
    assert fnmatch(repr(SimBCM(sig, sig, sig, sig, 0.1, tag="tag")),
                   "<SimBCM 'tag' at 0x*>")
    assert fnmatch(repr(SimOja(sig, sig, sig, sig, 0.1, 1.0)),
                   "<SimOja at 0x*>")
    assert fnmatch(repr(SimOja(sig, sig, sig, sig, 0.1, 1.0, tag="tag")),
                   "<SimOja 'tag' at 0x*>")
    assert fnmatch(repr(SimVoja(sig, sig, sig, sig, 1.0, sig, 1.0)),
                   "<SimVoja at 0x*>")
    assert fnmatch(
        repr(SimVoja(sig, sig, sig, sig, 0.1, sig, 1.0, tag="tag")),
        "<SimVoja 'tag' at 0x*>",
    )
    assert fnmatch(repr(SimRLS(sig, sig, sig, sig)), "<SimRLS at 0x*>")
    assert fnmatch(
        repr(SimRLS(sig, sig, sig, sig, tag="tag")),
        "<SimRLS 'tag' at 0x*>",
    )
    assert fnmatch(repr(SimNeurons(LIF(), sig, {"sig": sig})),
                   "<SimNeurons at 0x*>")
    assert fnmatch(
        repr(SimNeurons(LIF(), sig, {"sig": sig}, tag="tag")),
        "<SimNeurons 'tag' at 0x*>",
    )
    assert fnmatch(repr(SimProcess(WhiteNoise(), sig, sig, sig)),
                   "<SimProcess at 0x*>")
    assert fnmatch(
        repr(SimProcess(WhiteNoise(), sig, sig, sig, tag="tag")),
        "<SimProcess 'tag' at 0x*>",
    )
Example #7
0
def test_reset(Simulator, nl_nodirect, seed, rng):
    """Make sure resetting actually resets."""
    m = nengo.Network(seed=seed)
    with m:
        m.config[nengo.Ensemble].neuron_type = nl_nodirect()
        u = nengo.Node(output=WhiteNoise(0.15, 5).f(d=2, rng=rng))
        ens = nengo.Ensemble(60, dimensions=2)
        square = nengo.Ensemble(60, dimensions=2)
        nengo.Connection(u, ens)
        nengo.Connection(ens, square, function=lambda x: x ** 2,
                         solver=LstsqL2nz(weights=True))
        square_p = nengo.Probe(square, synapse=0.1)

    sim = Simulator(m)
    sim.run(0.1)
    sim.run(0.2)

    first_t = sim.trange()
    first_square_p = np.array(sim.data[square_p], copy=True)

    sim.reset()
    sim.run(0.3)

    assert np.all(sim.trange() == first_t)
    assert np.all(sim.data[square_p] == first_square_p)
Example #8
0
def test_izhikevich(Simulator, plt, seed, rng):
    """Smoke test for using Izhikevich neurons.

    Tests that the 6 parameter sets listed in the original paper can be
    simulated in Nengo (but doesn't test any properties of them).
    """
    with nengo.Network() as m:
        u = nengo.Node(output=WhiteNoise(0.6, 8).f(d=1, rng=rng))

        # Seed the ensembles (not network) so we get the same sort of neurons
        ens_args = {'n_neurons': 4, 'dimensions': 1, 'seed': seed}
        rs = nengo.Ensemble(neuron_type=nengo.Izhikevich(), **ens_args)
        ib = nengo.Ensemble(neuron_type=nengo.Izhikevich(reset_voltage=-55,
                                                         reset_recovery=4),
                            **ens_args)
        ch = nengo.Ensemble(neuron_type=nengo.Izhikevich(reset_voltage=-50,
                                                         reset_recovery=2),
                            **ens_args)
        fs = nengo.Ensemble(neuron_type=nengo.Izhikevich(tau_recovery=0.1),
                            **ens_args)
        lts = nengo.Ensemble(neuron_type=nengo.Izhikevich(coupling=0.25),
                             **ens_args)
        rz = nengo.Ensemble(neuron_type=nengo.Izhikevich(tau_recovery=0.1,
                                                         coupling=0.26),
                            **ens_args)

        ensembles = (rs, ib, ch, fs, lts, rz)
        out = {}
        spikes = {}
        for ens in ensembles:
            nengo.Connection(u, ens)
            out[ens] = nengo.Probe(ens, synapse=0.05)
            spikes[ens] = nengo.Probe(ens.neurons)
        up = nengo.Probe(u)

    sim = Simulator(m)
    sim.run(0.6)
    t = sim.trange()

    def plot(ens, title, ix):
        ax = plt.subplot(len(ensembles), 1, ix)
        plt.title(title)
        plt.plot(t, sim.data[out[ens]], c='k', lw=1.5)
        plt.plot(t, sim.data[up], c='k', ls=':')
        ax = ax.twinx()
        ax.set_yticks(())
        rasterplot(t, sim.data[spikes[ens]], ax=ax)

    plt.figure(figsize=(10, 12))
    plot(rs, "Regular spiking", 1)
    plot(ib, "Intrinsically bursting", 2)
    plot(ch, "Chattering", 3)
    plot(fs, "Fast spiking", 4)
    plot(lts, "Low-threshold spiking", 5)
    plot(rz, "Resonator", 6)
Example #9
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])})"
    )
Example #10
0
def test_frozen():
    """Test attributes inherited from FrozenObject"""
    a = WhiteNoise(dist=Gaussian(0.3, 0.2))
    b = WhiteNoise(dist=Gaussian(0.3, 0.2))
    c = FilteredNoise(dist=Gaussian(0.3, 0.2), synapse=Lowpass(0.02))

    assert hash(a) == hash(a)
    assert hash(b) == hash(b)
    assert hash(c) == hash(c)

    assert a == b
    assert hash(a) == hash(b)
    assert a != c
    assert hash(a) != hash(c)  # not guaranteed, but highly likely
    assert b != c
    assert hash(b) != hash(c)  # not guaranteed, but highly likely

    with pytest.raises(ValueError):
        a.dist = Gaussian(0.3, 0.5)  # test that dist param is frozen
    with pytest.raises(ValueError):
        a.dist.std = 0.4  # test that dist object is frozen
Example #11
0
def test_frozen():
    """Test attributes inherited from FrozenObject"""
    a = WhiteNoise(dist=Gaussian(0.3, 0.2))
    b = WhiteNoise(dist=Gaussian(0.3, 0.2))
    c = FilteredNoise(dist=Gaussian(0.3, 0.2), synapse=Lowpass(0.02))

    assert hash(a) == hash(a)
    assert hash(b) == hash(b)
    assert hash(c) == hash(c)

    assert a == b
    assert hash(a) == hash(b)
    assert a != c
    assert hash(a) != hash(c)  # not guaranteed, but highly likely
    assert b != c
    assert hash(b) != hash(c)  # not guaranteed, but highly likely

    with pytest.raises(ValueError):
        a.dist = Gaussian(0.3, 0.5)  # test that dist param is frozen
    with pytest.raises(ValueError):
        a.dist.std = 0.4  # test that dist object is frozen
Example #12
0
def test_gaussian_whitenoise(rms, rng, plt):
    d = 500
    t = 0.1
    dt = 0.001

    process = WhiteNoise(Gaussian(0., rms))

    values = process.run(t, d=d, dt=dt, rng=rng)
    freq, val_psd = psd(values)

    trange = process.trange(t, dt=dt)
    plt.subplot(2, 1, 1)
    plt.title("First two dimensions of white noise process, rms=%.1f" % rms)
    plt.plot(trange, values[:, :2])
    plt.xlim(right=trange[-1])
    plt.subplot(2, 1, 2)
    plt.title("Power spectrum")
    plt.plot(freq, val_psd, drawstyle='steps')

    val_rms = npext.rms(values, axis=0) * np.sqrt(dt)
    assert np.allclose(val_rms.mean(), rms, rtol=0.02)
    assert np.allclose(val_psd[1:-1] * np.sqrt(dt), rms, rtol=0.2)
Example #13
0
def test_gaussian_whitenoise(rms, rng, plt):
    d = 500
    t = 0.1
    dt = 0.001

    process = WhiteNoise(Gaussian(0., rms))

    values = process.run(t, d=d, dt=dt, rng=rng)
    freq, val_psd = psd(values)

    trange = process.trange(t, dt=dt)
    plt.subplot(2, 1, 1)
    plt.title("First two dimensions of white noise process, rms=%.1f" % rms)
    plt.plot(trange, values[:, :2])
    plt.xlim(right=trange[-1])
    plt.subplot(2, 1, 2)
    plt.title("Power spectrum")
    plt.plot(freq, val_psd, drawstyle='steps')

    val_rms = npext.rms(values, axis=0) * np.sqrt(dt)
    assert np.allclose(val_rms.mean(), rms, rtol=0.02)
    assert np.allclose(val_psd[1:-1] * np.sqrt(dt), rms, rtol=0.2)
Example #14
0
def _test_rates(Simulator, rates, plt, seed, name=None):
    if name is None:
        name = rates.__name__

    n = 100
    intercepts = np.linspace(-0.99, 0.99, n)

    model = nengo.Network(seed=seed)
    with model:
        model.config[nengo.Ensemble].max_rates = Choice([50])
        model.config[nengo.Ensemble].encoders = Choice([[1]])
        u = nengo.Node(output=WhiteNoise(2., 5).f(
            rng=np.random.RandomState(seed=seed)))
        a = nengo.Ensemble(n, 1,
                           intercepts=intercepts, neuron_type=nengo.LIFRate())
        b = nengo.Ensemble(n, 1,
                           intercepts=intercepts, neuron_type=nengo.LIF())
        nengo.Connection(u, a, synapse=0)
        nengo.Connection(u, b, synapse=0)
        up = nengo.Probe(u)
        ap = nengo.Probe(a.neurons)
        bp = nengo.Probe(b.neurons)

    sim = Simulator(model)
    sim.run(2.)

    t = sim.trange()
    x = sim.data[up]
    a_rates = sim.data[ap]
    spikes = sim.data[bp]
    b_rates = rates(t, spikes)

    ax = plt.subplot(411)
    plt.plot(t, x)
    ax = plt.subplot(412)
    implot(plt, t, intercepts, a_rates.T, ax=ax)
    ax.set_ylabel('intercept')
    ax = plt.subplot(413)
    implot(plt, t, intercepts, b_rates.T, ax=ax)
    ax.set_ylabel('intercept')
    ax = plt.subplot(414)
    implot(plt, t, intercepts, (b_rates - a_rates).T, ax=ax)
    ax.set_xlabel('time [s]')
    ax.set_ylabel('intercept')
    plt.saveas = 'utils.test_neurons.test_rates.%s.pdf' % name

    tmask = (t > 0.1) & (t < 1.9)
    relative_rmse = rms(b_rates[tmask] - a_rates[tmask]) / rms(a_rates[tmask])
    return relative_rmse
Example #15
0
def test_reset(Simulator, seed):
    trun = 0.1

    with nengo.Network() as model:
        u = nengo.Node(WhiteNoise(Gaussian(0, 1), scale=False))
        up = nengo.Probe(u)

    with Simulator(model, seed=seed) as sim:
        sim.run(trun)
        x = np.array(sim.data[up])
        sim.reset()
        sim.run(trun)
        y = np.array(sim.data[up])

    assert x.shape == y.shape
    assert np.allclose(x, y)
Example #16
0
def test_reset(seed):
    trun = 0.1

    with nengo.Network() as model:
        u = nengo.Node(WhiteNoise(Gaussian(0, 1), scale=False))
        up = nengo.Probe(u)

    sim = nengo.Simulator(model, seed=seed)

    sim.run(trun)
    x = np.array(sim.data[up])

    sim.reset()
    sim.run(trun)
    y = np.array(sim.data[up])

    assert (x == y).all()
Example #17
0
def run_synapse(Simulator, seed, synapse, dt=1e-3, runtime=1., n_neurons=None):
    model = nengo.Network(seed=seed)
    with model:
        u = nengo.Node(output=WhiteNoise(runtime, 5).f(
            rng=np.random.RandomState(seed)))

        if n_neurons is not None:
            a = nengo.Ensemble(n_neurons, 1)
            nengo.Connection(u, a, synapse=None)
            target = a
        else:
            target = u

        ref = nengo.Probe(target)
        filtered = nengo.Probe(target, synapse=synapse)

    sim = Simulator(model, dt=dt)
    sim.run(runtime)

    return sim.trange(), sim.data[ref], sim.data[filtered]
Example #18
0
def test_whitenoise_rms(rms, rng, plt):
    d = 500
    t = 100
    dt = 0.001

    process = WhiteNoise(dt * t, rms=rms)
    values = nengo.processes.sample(t, process, dt=dt, d=d, rng=rng)
    freq, val_psd = psd(values)

    trange = np.arange(1, t + 1) * dt
    plt.subplot(2, 1, 1)
    plt.title("First two D of white noise process, rms=%.1f" % rms)
    plt.plot(trange, values[:, :2])
    plt.xlim(right=trange[-1])
    plt.subplot(2, 1, 2)
    plt.title("Power spectrum")
    plt.plot(freq, val_psd, drawstyle='steps')

    assert np.allclose(np.std(values), rms, rtol=0.02)
    assert np.allclose(val_psd[1:-1], rms, rtol=0.35)
Example #19
0
def test_dt_dependence(Simulator, nl_nodirect, plt, seed, rng):
    """Neurons should not wildly change with different dt."""
    with nengo.Network(seed=seed) as m:
        m.config[nengo.Ensemble].neuron_type = nl_nodirect()
        u = nengo.Node(output=WhiteNoise(0.1, 5).f(d=2, rng=rng))
        pre = nengo.Ensemble(60, dimensions=2)
        square = nengo.Ensemble(60, dimensions=2)
        nengo.Connection(u, pre)
        nengo.Connection(pre, square, function=lambda x: x**2)

        activity_p = nengo.Probe(square.neurons,
                                 synapse=.05,
                                 sample_every=0.001)
        out_p = nengo.Probe(square, synapse=.05, sample_every=0.001)

    activity_data = []
    out_data = []
    dts = (0.0001, 0.001)
    colors = ('b', 'g', 'r')
    for c, dt in zip(colors, dts):
        sim = Simulator(m, dt=dt)
        sim.run(0.1)
        t = sim.trange(dt=0.001)
        activity_data.append(sim.data[activity_p])
        out_data.append(sim.data[out_p])
        plt.subplot(2, 1, 1)
        plt.plot(t, sim.data[out_p], c=c)
        plt.subplot(2, 1, 2)
        # Just plot 5 neurons
        plt.plot(t, sim.data[activity_p][..., :5], c=c)

    plt.subplot(2, 1, 1)
    plt.xlim(right=t[-1])
    plt.ylabel("Decoded output")
    plt.subplot(2, 1, 2)
    plt.xlim(right=t[-1])
    plt.ylabel("Neural activity")

    assert rmse(activity_data[0], activity_data[1]) < ((1. / dt) * 0.01)
    assert np.allclose(out_data[0], out_data[1], atol=0.05)
Example #20
0
def test_unsupervised(Simulator, learning_rule_type, seed, rng, plt):
    n = 200

    m = nengo.Network(seed=seed)
    with m:
        u = nengo.Node(WhiteNoise(0.5, high=5).f(d=2, rng=rng))
        a = nengo.Ensemble(n, dimensions=2)
        u_learned = nengo.Ensemble(n, dimensions=2)

        initial_weights = rng.uniform(high=1e-3,
                                      size=(a.n_neurons, u_learned.n_neurons))

        nengo.Connection(u, a)
        conn = nengo.Connection(a.neurons,
                                u_learned.neurons,
                                transform=initial_weights,
                                learning_rule_type=learning_rule_type)
        inp_p = nengo.Probe(u)
        trans_p = nengo.Probe(conn, 'transform', sample_every=0.01)

        ap = nengo.Probe(a, synapse=0.03)
        up = nengo.Probe(u_learned, synapse=0.03)

    sim = Simulator(m)
    sim.run(0.5)
    t = sim.trange()

    name = learning_rule_type.__class__.__name__
    plt.subplot(2, 1, 1)
    plt.plot(t, sim.data[inp_p], label="Input")
    plt.plot(t, sim.data[ap], label="Pre")
    plt.plot(t, sim.data[up], label="Post")
    plt.legend(loc="best", fontsize="x-small")
    plt.subplot(2, 1, 2)
    plt.plot(sim.trange(dt=0.01), sim.data[trans_p][..., 4])
    plt.xlabel("Time (s)")
    plt.ylabel("Transform weight")
    plt.saveas = 'test_learning_rules.test_unsupervised_%s.pdf' % name

    assert not np.all(sim.data[trans_p][0] == sim.data[trans_p][-1])
Example #21
0
def test_whitenoise_high(high, rng, plt):
    rms = 0.5
    d = 500
    t = 1000
    dt = 0.001

    process = WhiteNoise(dt * t, high, rms=rms)
    values = nengo.processes.sample(t, process, dt=dt, d=d, rng=rng)
    freq, val_psd = psd(values)

    trange = np.arange(1, t + 1) * dt
    plt.subplot(2, 1, 1)
    plt.title("First two D of white noise process, high=%d Hz" % high)
    plt.plot(trange, values[:, :2])
    plt.xlim(right=trange[-1])
    plt.subplot(2, 1, 2)
    plt.title("Power spectrum")
    plt.plot(freq, val_psd, drawstyle='steps')
    plt.xlim(right=high * 2.0)

    assert np.allclose(np.std(values, axis=1), rms, rtol=0.15)
    assert np.all(val_psd[rfftfreq(t, dt) > high] < rms * 0.5)
Example #22
0
def test_gaussian_whitenoise(Simulator, rms, seed, plt):
    d = 500
    process = WhiteNoise(Gaussian(0., rms), scale=False)
    with nengo.Network() as model:
        u = nengo.Node(process, size_out=d)
        up = nengo.Probe(u)

    with Simulator(model, seed=seed) as sim:
        sim.run(0.3)
    values = sim.data[up]
    freq, val_psd = psd(values, dt=sim.dt)

    trange = sim.trange()
    plt.subplot(2, 1, 1)
    plt.title("First two dimensions of white noise process, rms=%.1f" % rms)
    plt.plot(trange, values[:, :2])
    plt.xlim(right=trange[-1])
    plt.subplot(2, 1, 2)
    plt.title("Power spectrum")
    plt.plot(freq, val_psd, drawstyle='steps')

    val_rms = npext.rms(values, axis=0)
    assert np.allclose(val_rms.mean(), rms, rtol=0.02)
    assert np.allclose(val_psd[1:-1], rms, rtol=0.2)
import numpy as np
import nengo
import nengo_spinnaker

# Import classes
from nengo.processes import WhiteNoise
from nengo_spinnaker.utils import profiling

# Parameters to profile
dimensions = 1
ensemble_size = 200

model = nengo.Network()
with model:
    # Create standard communication channel network with white noise input
    inp = nengo.Node(WhiteNoise(), label="inp")
    inp_p = nengo.Probe(inp)

    pre = nengo.Ensemble(ensemble_size, dimensions=dimensions, label="pre")
    pre_p = nengo.Probe(pre, synapse=0.01)
    nengo.Connection(inp, pre)

    post = nengo.Ensemble(ensemble_size, dimensions=dimensions, label="post")
    posts_p = nengo.Probe(post, synapse=0.01)
    nengo.Connection(pre,
                     post,
                     function=lambda x: np.random.random(dimensions))

    # Setup SpiNNaker-specific options to supply white noise from on
    # chip and profile the ensemble at the start of the channel
    nengo_spinnaker.add_spinnaker_params(model.config)
from nengo.processes import WhiteNoise
from nengo.utils.functions import piecewise
from nengo.utils.matplotlib import rasterplot
from nengo.dists import Uniform

model = nengo.Network(label='2D Decision Integrator', seed=11)
with model:
    #Input
    input1 = nengo.Node(-0.5)
    input2 = nengo.Node(0.5)

    #Ensembles
    input = nengo.Ensemble(100, dimensions=2)
    MT = nengo.Ensemble(100,
                        dimensions=2,
                        noise=WhiteNoise(dist=Uniform(-0.3, 0.3)))
    LIP = nengo.Ensemble(200,
                         dimensions=2,
                         noise=WhiteNoise(dist=Uniform(-0.3, 0.3)))
    output = nengo.Ensemble(100,
                            dimensions=2,
                            noise=WhiteNoise(dist=Uniform(-0.3, 0.3)))

    weight = 0.1
    #Connecting the input signal to the input ensemble
    nengo.Connection(input1, input[0], synapse=0.01)
    nengo.Connection(input2, input[1], synapse=0.01)

    #Providing input to MT ensemble
    nengo.Connection(input, MT, synapse=0.01)
Example #25
0
def test_sampling_shape():
    process = WhiteNoise(0.1)
    assert nengo.processes.sample(1, process).shape == (1, )
    assert nengo.processes.sample(5, process, d=1).shape == (5, 1)
    assert nengo.processes.sample(1, process, d=2).shape == (1, 2)