Example #1
0
def nengo_plot_helper(offset,
                      t,
                      data,
                      label='',
                      removex=True,
                      yticks=None,
                      xlabel=None,
                      spikes=False):
    if offset:
        plt.subplot(offset)

    if spikes:
        rasterplot(t, data, label=label)
    else:
        plt.plot(t, data, label=label)

    plt.ylabel(label)
    plt.xlim(min(t), max(t))
    if yticks is not None:
        plt.yticks(yticks)
    if xlabel is not None:
        plt.xlabel(xlabel)
    if removex:
        frame = plt.gca()
        frame.axes.get_xaxis().set_ticklabels([])
    offset += 1

    ax = plt.gca()

    return ax, offset
def test_neurons2node(Simulator, seed, plt):
    with nengo.Network(seed=seed) as model:
        stim = nengo.Node(lambda t: [np.sin(t * 2 * np.pi)])
        p_stim = nengo.Probe(stim)

        a = nengo.Ensemble(100, 1, intercepts=nengo.dists.Choice([0]))

        nengo.Connection(stim, a)

        data = []
        output = nengo.Node(lambda t, x: data.append(x),
                            size_in=a.n_neurons,
                            size_out=0)
        nengo.Connection(a.neurons, output, synapse=None)

    with Simulator(model, precompute=True) as sim:
        sim.run(1.0)

    rasterplot(sim.trange(), np.array(data), ax=plt.gca())
    plt.twinx()
    plt.plot(sim.trange(), sim.data[p_stim])
    plt.title("Raster plot for sine input")

    pre = np.asarray(data[:len(data) // 2 - 100])
    post = np.asarray(data[len(data) // 2 + 100:])
    on_neurons = np.squeeze(sim.data[a].encoders == 1)
    assert np.sum(pre[:, on_neurons]) > 0
    assert np.sum(post[:, on_neurons]) == 0
    assert np.sum(pre[:, np.logical_not(on_neurons)]) == 0
    assert np.sum(post[:, np.logical_not(on_neurons)]) > 0
Example #3
0
 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)
Example #4
0
 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)
Example #5
0
def neural_activity_plot(probe, trange):
    fig, ax = plt.subplots(figsize=(12.8, 7.2), dpi=100)
    rasterplot(trange, probe, ax)
    ax.set_ylabel('Neuron')
    ax.set_xlabel('Time (s)')
    fig.get_axes()[0].annotate("Pre" + " neural activity", (0.5, 0.94),
                               xycoords='figure fraction',
                               ha='center',
                               fontsize=20)
    return fig
Example #6
0
def test_rasterplot(use_eventplot, Simulator, seed, plt):

    with nengo.Network(seed=seed) as model:
        u = nengo.Node(output=lambda t: np.sin(6 * t))
        a = nengo.Ensemble(100, 1)
        nengo.Connection(u, a)
        ap = nengo.Probe(a.neurons)

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

    rasterplot(sim.trange(), sim.data[ap], use_eventplot=use_eventplot)
Example #7
0
def test_rasterplot(use_eventplot, Simulator, seed, plt):
    from nengo.utils.matplotlib import rasterplot

    with nengo.Network(seed=seed) as model:
        u = nengo.Node(output=lambda t: np.sin(6 * t))
        a = nengo.Ensemble(100, 1)
        nengo.Connection(u, a)
        ap = nengo.Probe(a.neurons)

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

    rasterplot(sim.trange(), sim.data[ap], use_eventplot=use_eventplot)
def test_ensemble_to_neurons(Simulator, seed, allclose, plt):
    with nengo.Network(seed=seed) as net:
        stim = nengo.Node(lambda t: [np.sin(t * 2 * np.pi)])
        pre = nengo.Ensemble(20, 1)
        nengo.Connection(stim, pre)

        post = nengo.Ensemble(2, 1, gain=[1.0, 1.0], bias=[0.0, 0.0])

        # On and off neurons
        nengo.Connection(pre,
                         post.neurons,
                         synapse=None,
                         transform=[[5], [-5]])

        p_pre = nengo.Probe(pre, synapse=nengo.synapses.Alpha(0.03))
        p_post = nengo.Probe(post.neurons)

    # Compare to Nengo
    with nengo.Simulator(net) as nengosim:
        nengosim.run(1.0)

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

    t = sim.trange()
    plt.subplot(2, 1, 1)
    plt.title("Reference Nengo")
    plt.plot(t, nengosim.data[p_pre], c="k")
    plt.ylabel("Decoded pre value")
    plt.xlabel("Time (s)")
    plt.twinx()
    rasterplot(t, nengosim.data[p_post])
    plt.ylabel("post neuron number")
    plt.subplot(2, 1, 2)
    plt.title("Nengo Loihi")
    plt.plot(t, sim.data[p_pre], c="k")
    plt.ylabel("Decoded pre value")
    plt.xlabel("Time (s)")
    plt.twinx()
    rasterplot(t, sim.data[p_post])
    plt.ylabel("post neuron number")

    plt.tight_layout()

    # Compare the number of spikes for each neuron.
    # We'll let them be off by 5 for now.
    assert allclose(
        np.sum(sim.data[p_post], axis=0) * sim.dt,
        np.sum(nengosim.data[p_post], axis=0) * nengosim.dt,
        atol=5,
    )
Example #9
0
def test_rasterplot(use_eventplot, Simulator, seed, plt):
    from nengo.utils.matplotlib import rasterplot

    with nengo.Network(seed=seed) as model:
        u = nengo.Node(output=lambda t: np.sin(6 * t))
        a = nengo.Ensemble(100, 1)
        nengo.Connection(u, a)
        ap = nengo.Probe(a.neurons)

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

    rasterplot(sim.trange(), sim.data[ap], use_eventplot=use_eventplot)
    if use_eventplot:
        plt.saveas = 'utils.test_matplotlib.test_rasterplot.eventplot.pdf'
Example #10
0
def spike_plot(dt, t, y, tmin=None, tmax=None, ax=None):
    from nengo.utils.matplotlib import rasterplot
    ax = plt.gca() if ax is None else ax

    # y = learner['hs']
    if tmin is not None or tmax is not None:
        tmin = t[0] if tmin is None else tmin
        tmax = t[-1] if tmax is None else tmax
        tmask = (t >= tmin) & (t <= tmax)
        t = t[tmask]
        y = y[tmask]

    rasterplot(t, y)
    ax.get_xaxis().get_major_formatter().set_useOffset(False)
    ax.get_xaxis().get_major_formatter().set_scientific(False)
def raster_plot(network, input_signal, ax, n_ens_to_raster=None):
    '''
    Accepts a Nengo network and runs a simulation with the input_signal
    Plots rasterplot onto ax object up to n_ens_to_raster ensembles
    if n_ens_to_raster is None, all ensembles will be plotted

    PARAMETERS
    ----------
    network: .DynamicsAdaptation
        'abr_control.controllers.signals.dynamics_adaptation'
    input_signal: np array shape of (time_steps x input_dim)
        the input used for the network sim
    ax: ax object
        used for the rasterplot
    n_ens_to_raster: int, Optional (Default: None)
        the number of ensembles to plot in the raster,
        if None all will be plotted
    '''
    if n_ens_to_raster is None:
        n_ens_to_raster = len(network.adapt_ens)

    spike_trains = get_activities(network, input_signal)

    time = np.ones(len(input_signal))

    ax = rasterplot(np.cumsum(time), spike_trains, ax=ax)

    ax.set_ylabel('Neuron')
    ax.set_xlabel('Time [sec]')
    ax.set_title('Spiking Activity')

    return spike_trains
Example #12
0
    def plot_ensemble_spikes(self, name, spikes, decoded):
        fig, ax1 = plt.subplots()
        fig.set_size_inches(self.plot_sizes)
        ax1 = plt.subplot(1, 1, 1)
        rasterplot(self.time_vector, spikes, ax1)
        ax1.axvline(x=self.learning_time, c="k")
        ax2 = plt.twinx()
        ax2.plot(self.time_vector, decoded, c="k", alpha=0.3)
        ax1.set_xlim(0, max(self.time_vector))
        ax1.set_ylabel('Neuron')
        ax1.set_xlabel('Time (s)')
        fig.get_axes()[0].annotate(name + " neural activity", (0.5, 0.94),
                                   xycoords='figure fraction',
                                   ha='center',
                                   fontsize=20)

        return fig
Example #13
0
def izh_plot(sim):
    t = sim.trange()
    plt.figure(figsize=(12, 10))
    plt.subplot(4, 1, 1)
    plt.plot(t, sim.data[out_p])
    plt.ylabel("Decoded output")
    plt.xlim(right=t[-1])
    ax = plt.subplot(4, 1, 2)
    rasterplot(t, sim.data[spikes_p], ax=ax)
    plt.ylabel("Neuron")
    plt.xlim(right=t[-1])
    plt.subplot(4, 1, 3)
    plt.plot(t, sim.data[voltage_p])
    plt.ylabel("Voltage")
    plt.xlim(right=t[-1])
    plt.subplot(4, 1, 4)
    plt.plot(t, sim.data[recovery_p])
    plt.ylabel("Recovery")
    plt.xlim(right=t[-1])
def plot_ensemble_spikes(sim, name, ensemble, input=None, time=None):
    from nengo.utils.matplotlib import rasterplot
    import matplotlib.pyplot as plt

    # plot spikes from pre
    fig = plt.figure()
    # plt.suptitle( datetime.datetime.now().strftime( '%H:%M:%S %d-%m-%Y' ) )
    fig, ax1 = plt.subplots()
    ax1 = plt.subplot(1, 1, 1)
    rasterplot(sim.trange(), sim.data[ensemble], ax1)
    ax1.set_xlim(0, max(sim.trange()))
    ax1.set_ylabel('Neuron')
    ax1.set_xlabel('Time (s)')
    if input:
        ax2 = plt.twinx()
        ax2.plot(sim.trange(), sim.data[input], c="k")
    if time:
        time = int(time)
        for t in range(time):
            plt.axvline(x=t, c="k")
    plt.title(name + " neural activity")

    return fig
def plot(model, neurons, cos_probe, spikes, filtered):
    # run the simulation for one second
    with nengo.Simulator(model) as sim:
        eval_points, activities = tuning_curves(neurons, sim)
        sim.run(1)
    # Plot tuning-curves
    plt.figure()
    plt.plot(eval_points, activities)
    plt.ylabel("Firing rate (Hz)")
    plt.xlabel("Input scalar, x")
    # Plot the decoded output of the ensemble
    plt.figure()
    plt.plot(sim.trange(), sim.data[filtered])
    plt.plot(sim.trange(), sim.data[cos_probe])
    plt.ylabel("Signal")
    plt.xlabel("Time")
    plt.xlim(0, 1)
    # Plot the spiking output of the ensemble
    plt.figure()
    rasterplot(sim.trange(), sim.data[spikes])
    plt.ylabel("Neuron")
    plt.xlabel("Time of Spike-Occurrence")
    plt.xlim(0, 1)
    plt.show()
Example #16
0
def nengo_plot_helper(offset, t, data, label='', removex=True, yticks=None,
                      xlabel=None, spikes=False):
    if offset:
        plt.subplot(offset)

    if spikes:
        rasterplot(t, data, label=label)
    else:
        plt.plot(t, data, label=label)

    plt.ylabel(label)
    plt.xlim(min(t), max(t))
    if yticks is not None:
        plt.yticks(yticks)
    if xlabel is not None:
        plt.xlabel(xlabel)
    if removex:
        frame = plt.gca()
        frame.axes.get_xaxis().set_ticklabels([])
    offset += 1

    ax = plt.gca()

    return ax, offset
Example #17
0
    neplt.imshow(np.transpose(Xtest[col], (1, 2, 0)),
                 vmin=-128,
                 vmax=128,
                 ax=ax,
                 axes=True)
    ax.set_title(label0)
    ax.xaxis.set_ticks([])
    ax.yaxis.set_ticks([])
    if col == 0:
        ax.set_ylabel('input')

    # plot spike rasters
    for i, (spike_block,
            neuron_ind) in enumerate(zip(spike_blocks, neuron_inds)):
        ax = plt.subplot(rows, cols, (i + 1) * cols + col + 1)
        rasterplot(tj, spike_block[col][:, neuron_ind], ax=ax)
        ax.xaxis.set_ticks([])
        ax.yaxis.set_ticks([])
        if col == 0:
            ax.set_ylabel('%s neurons' % spike_names[i])

    # plot output
    ax = plt.subplot(rows, cols, (rows - 1) * cols + col + 1)
    jinds = choices[col][:5]
    jlabels = [label_names[k] for k in jinds]
    jvalues = values[col][jinds]
    cells = [['%s %0.2f%%' % (label, 100 * value)]
             for label, value in zip(jlabels, jvalues)]
    ax.table(cellText=cells, loc='center', fontsize=20)
    ax.xaxis.set_ticks([])
    ax.yaxis.set_ticks([])
Example #18
0
           np.arange(A.n_neurons))

model = nengo.Network(label="NEF summary")
with model:
    input = nengo.Node(WhiteSignal(1, high=5), size_out=1)
    input_probe = nengo.Probe(input)
    A = nengo.Ensemble(30, dimensions=1, max_rates=Uniform(80, 100))
    nengo.Connection(input, A)
    A_spikes = nengo.Probe(A.neurons)
    A_probe = nengo.Probe(A, synapse=0.01)

with nengo.Simulator(model) as sim:
    sim.run(1)

plt.figure(figsize=(10, 3.5))
plt.subplot(1, 2, 1)
plt.plot(sim.trange(), sim.data[input_probe], label="Input signal")
plt.plot(sim.trange(), sim.data[A_probe], label="Decoded esimate")
plt.legend(loc="best")
plt.xlabel("Time (s)")
plt.xlim(0, 1)

ax = plt.subplot(1, 2, 2)
rasterplot(sim.trange(), sim.data[A_spikes], ax)
plt.xlim(0, 1)
plt.xlabel("Time (s)")
plt.ylabel("Neuron")
hide_input()

plt.show()
Example #19
0
from nengo.utils.matplotlib import rasterplot

model = nengo.Network(label="Decoding with Two Neurons")
with model:
    # stim = nengo.Node(lambda t: np.sin(10 * t))
    stim = nengo.Node(sound)

    ens = nengo.Ensemble(2,
                         dimensions=1,
                         encoders=[[1], [-1]],
                         intercepts=[-.5, -.5],
                         max_rates=[100, 100])
    nengo.Connection(stim, ens)
    stim_p = nengo.Probe(stim)
    spikes_p = nengo.Probe(ens.neurons, "spikes")

sim = nengo.Simulator(model)
sim.run(.6)

# [+] draw figures
nengo.utils.matplotlib.plot_tuning_curves(ens, sim)
t = sim.trange()
plt.figure(figsize=(12, 6))
plt.plot(t, sim.data[stim_p], "g")
ax = plt.gca()
plt.ylabel("Output")
plt.xlabel("Time")
rasterplot(t, sim.data[spikes_p], ax=ax.twinx(), use_eventplot=True)
plt.ylabel("Neuron")
plt.show()
sim = nengo.Simulator(model) # Create the simulator
sim.run(1) # Run it for 1 seconds


# ##Step 6: Plot the Results

# In[ ]:

# Plot the decoded output of the ensemble
plt.plot(sim.trange(), sim.data[filtered])
plt.plot(sim.trange(), sim.data[cos_probe])
plt.xlim(0, 1)

# Plot the spiking output of the ensemble
from nengo.utils.matplotlib import rasterplot
plt.figure(figsize=(10, 8))
plt.subplot(221)
rasterplot(sim.trange(), sim.data[spikes])
plt.ylabel("Neuron")
plt.xlim(0, 1)

# Plot the soma voltages of the neurons
plt.subplot(222)
plt.plot(sim.trange(), sim.data[voltage][:,0], 'r')
plt.xlim(0, 1);


# The top graph shows that the input signal in green and the filtered output spikes from the single neuron population in blue. The spikes (that are filtered) from the neuron are shown in the bottom graph on the left. On the right is the subthreshold voltages for the neuron.
import pylab
pylab.show()
Example #21
0

with model:
    sin = nengo.Node(lambda t: np.sin(8*t))
    nengo.Connection(sin, A, synapse=0.01)

with model:
    sin_probe = nengo.Probe(sin)
    A_probe = nengo.Probe(A, synapse=0.1)
    A_spikes = nengo.Probe(A.neurons)


with nengo.Simulator(model) as sim:
    sim.run(10)


plt.figure()
plt.plot(sim.trange(), sim.data[A_probe], label="A output")
plt.plot(sim.trange(), sim.data[sin_probe], "r", label="Input")
plt.legend()
plt.show()

plt.figure()
rasterplot(sim.trange(), sim.data[A_spikes])
plt.show()

indices = sorted_neurons(A, sim, iterations=250)
plt.figure()
rasterplot(sim.trange(), sim.data[A_spikes][:, indices])
plt.show()
Example #22
0
def plot_sim_1(sp_c,
               sp_u,
               res_c,
               res_u,
               cal_c,
               cal_u=None,
               mem_cued=None,
               mem_uncued=None,
               sim=None,
               Nm=None):
    theme = theme_classic()
    plt.style.use('default')
    #FIGURE 31
    with plt.rc_context():
        plt.rcParams.update(theme.rcParams)

        fig, axes, = plt.subplots(2, 2, squeeze=True)
        theme.setup_figure(fig)
        t = sim.trange()
        plt.subplots_adjust(wspace=0.05, hspace=0.05)

        #spikes, calcium, resources Cued
        ax1 = axes[0, 0]
        ax1.set_title("Cued Module")
        ax1.set_ylabel('# cell', color='black')
        ax1.set_yticks(np.arange(0, Nm, 500))
        ax1.tick_params('y')  #, colors='black')
        rasterplot(sim.trange(), sp_c, ax1, colors=['black'] * sp_c.shape[0])
        ax1.set_xticklabels([])
        ax1.set_xticks([])
        ax1.set_xlim(0, 3)
        ax2 = ax1.twinx()
        ax2.plot(t, res_c, "#00bfc4", linewidth=2)
        ax2.plot(t, cal_c, "#e38900", linewidth=2)
        ax2.set_yticklabels([])
        ax2.set_yticks([])
        ax2.set_ylim(0, 1.1)

        if cal_u is not None:
            #spikes, calcium, resources Uncued
            ax3 = axes[0, 1]
            ax3.set_title("Uncued Module")
            rasterplot(sim.trange(),
                       sp_u,
                       ax3,
                       colors=['black'] * sp_u.shape[0])
            ax3.set_xticklabels([])
            ax3.set_xticks([])
            ax3.set_yticklabels([])
            ax3.set_yticks([])
            ax3.set_xlim(0, 3)
            ax4 = ax3.twinx()
            ax4.plot(t, res_u, "#00bfc4", linewidth=2)
            ax4.plot(t, cal_u, "#e38900", linewidth=2)
            ax4.set_ylabel('synaptic variables', color="black", size=11)
            ax4.tick_params('y',
                            labelcolor='#333333',
                            labelsize=9,
                            color='#333333')
            ax4.set_ylim(0, 1.1)

        #representations cued
        plot_mc = axes[1, 0]
        plot_mc.plot(sim.trange(), (mem_cued))

        plot_mc.set_ylabel("Cosine similarity")
        plot_mc.set_xticks(np.arange(0.0, 3.45, 0.5))
        plot_mc.set_xticklabels(np.arange(0, 3500, 500).tolist())
        plot_mc.set_xlabel('time (ms)')
        plot_mc.set_xlim(0, 3)
        colors = [
            "#00c094", "#00bfc4", "#00b6eb", "#06a4ff", "#a58aff", "#df70f8",
            "#fb61d7", "#ff66a8", "#c49a00"
        ]
        for i, j in enumerate(plot_mc.lines):
            j.set_color(colors[i])

        if cal_u is not None:
            #representations uncued
            plot_mu = axes[1, 1]

            plot_mu.plot(sim.trange(), (mem_uncued))
            plot_mu.set_xticks(np.arange(0.0, 3.45, 0.5))
            plot_mu.set_xticklabels(np.arange(0, 3500, 500).tolist())
            plot_mu.set_xlabel('time (ms)')
            plot_mu.set_yticks([])
            plot_mu.set_yticklabels([])
            plot_mu.set_xlim(0, 3)
            for i, j in enumerate(plot_mu.lines):
                j.set_color(colors[i])
            plot_mu.legend([
                "0°", "3°", "7°", "12°", "18°", "25°", "33°", "42°", "Impulse"
            ],
                           title="Stimulus",
                           bbox_to_anchor=(1.02, -0.25, .30, 0.8),
                           loc=3,
                           ncol=1,
                           mode="expand",
                           borderaxespad=0.)

        fig.set_size_inches(11, 5)
        theme.apply(fig.axes[0])
        theme.apply(fig.axes[1])
        # theme.apply(fig.axes[2]) # Gives error
        theme.apply(fig.axes[3])

        plt.savefig('Figure_3.eps', format='eps', dpi=1000)
        plt.show()

    #FIGURE 32
    with plt.rc_context():
        plt.rcParams.update(theme.rcParams)

        fig, axes, = plt.subplots(1, 2, squeeze=True)
        theme.setup_figure(fig)
        t = sim.trange()
        plt.subplots_adjust(wspace=0.1, hspace=0.05)

        plot_mc = axes[0]
        plot_mc.set_title("Cued Module")
        plot_mc.plot(sim.trange(), (mem_cued))
        plot_mc.set_ylabel("Cosine similarity")
        plot_mc.set_xticks(np.arange(2.15, 2.35, 0.05))
        plot_mc.set_xticklabels(np.arange(0, 250, 50).tolist())
        plot_mc.set_xlabel('time after onset impulse (ms)')
        plot_mc.set_xlim(2.15, 2.3)
        plot_mc.set_ylim(0, 0.9)
        colors = [
            "#00c094", "#00bfc4", "#00b6eb", "#06a4ff", "#a58aff", "#df70f8",
            "#fb61d7", "#ff66a8", "#c49a00"
        ]
        for i, j in enumerate(plot_mc.lines):
            j.set_color(colors[i])

        plot_mu = axes[1]
        plot_mu.set_title("Uncued Module")
        plot_mu.plot(sim.trange(), (mem_uncued))
        plot_mu.set_xticks(np.arange(2.15, 2.35, 0.05))
        plot_mu.set_xticklabels(np.arange(0, 250, 50).tolist())
        plot_mu.set_xlabel('time after onset impulse (ms)')
        plot_mu.set_yticks([])
        plot_mu.set_yticklabels([])
        plot_mu.set_xlim(2.15, 2.30)
        plot_mu.set_ylim(0, 0.9)
        for i, j in enumerate(plot_mu.lines):
            j.set_color(colors[i])
        plot_mu.legend(
            ["0°", "3°", "7°", "12°", "18°", "25°", "33°", "42°", "Impulse"],
            title="Stimulus",
            bbox_to_anchor=(0.85, 0.25, .55, 0.8),
            loc=3,
            ncol=1,
            mode="expand",
            borderaxespad=0.)

        fig.set_size_inches(6, 4)

        # theme.apply(fig.axes[0]) # Gives error
        theme.apply(fig.axes[1])
        # theme.apply(plt.gcf().axes[0])
        # theme.apply(plt.gcf().axes[1])
        plt.savefig('Figure_4.eps', format='eps', dpi=1000)
        plt.show()
Example #23
0
sim = nengo.Simulator(network)
sim.run(2*np.pi*1.)

# Plot (figsize determined from column width)
from nengo.utils.matplotlib import rasterplot
from nengo.utils.ensemble import response_curves
fig = plt.figure(figsize=(plot_settings.column_width, 3.5), frameon=False)

# Input and spikes
ax0 = fig.add_subplot(211)
ax0.plot(sim.trange(), sim.data[p_inp])
ax0.set_ylabel('Input')
ax0.set_xlabel('Time / s')

ax1 = ax0.twinx()
rasterplot(sim.trange(), sim.data[p_spikes], ax1)
ax1.set_yticks([])
ax1.set_title('Neuronal responses')

# Tuning curves
ax2 = fig.add_subplot(223)

for n, a in enumerate(['a', 'b', 'c', 'd']):
    angles = np.linspace(0, 2*np.pi, 100)
    vecs = np.vstack([np.sin(angles), np.cos(angles)]).T
    encoded = []

    for v in vecs[:]:
        encoded.append(np.dot(ens.encoders[n], v))

    ins, response = response_curves(ens, sim, np.array(encoded))
Example #24
0
def show_cortex():
    rasterplot(sim.trange(), sim.data[cortex_probe])
    plt.show()
Example #25
0
def show_str():
    rasterplot(sim.trange(), sim.data[striatum_probe])
    plt.show()
Example #26
0
def show_thalamus():
    rasterplot(sim.trange(), sim.data[thalamus_probe])
    plt.show()
Example #27
0
def show_snc():
    rasterplot(sim.trange(), sim.data[snc_probe])
    plt.show()
Example #28
0
# In[ ]:

sim = nengo.Simulator(model)  # Create the simulator
sim.run(1)  # Run it for 1 seconds

# ##Step 6: Plot the Results

# In[ ]:

# Plot the decoded output of the ensemble
plt.plot(sim.trange(), sim.data[filtered])
plt.plot(sim.trange(), sim.data[cos_probe])
plt.xlim(0, 1)

# Plot the spiking output of the ensemble
from nengo.utils.matplotlib import rasterplot
plt.figure(figsize=(10, 8))
plt.subplot(221)
rasterplot(sim.trange(), sim.data[spikes])
plt.ylabel("Neuron")
plt.xlim(0, 1)

# Plot the soma voltages of the neurons
plt.subplot(222)
plt.plot(sim.trange(), sim.data[voltage][:, 0], 'r')
plt.xlim(0, 1)

# The top graph shows that the input signal in green and the filtered output spikes from the single neuron population in blue. The spikes (that are filtered) from the neuron are shown in the bottom graph on the left. On the right is the subthreshold voltages for the neuron.
import pylab
pylab.show()
Example #29
0
labels = test_labels[inds]
allimage = np.zeros((28, 28 * len(images)), dtype=images.dtype)
for i, image in enumerate(images):
    allimage[:, i * 28 : (i + 1) * 28] = image.reshape(28, 28)

plt.figure(1)
plt.clf()
r, c = 6, 1

plt.subplot(r, c, 1)
plt.imshow(allimage, aspect="auto", interpolation="none", cmap="gray")
plt.xticks([])
plt.yticks([])

plt.subplot(r, c, 2)
rasterplot(t, sim.data[probe_layers[0]][:, :200])
plot_bars()
plt.xticks([])
plt.ylabel("layer 1 (500)")

plt.subplot(r, c, 3)
rasterplot(t, sim.data[probe_layers[1]])
plt.xticks([])
plt.yticks(np.linspace(0, 200, 5))
plot_bars()
plt.ylabel("layer 2 (200)")

plt.subplot(r, c, 4)
plt.plot(t, sim.data[probe_class])
plot_bars()
plt.ylabel("class")
Example #30
0
def show_gpi():
    rasterplot(sim.trange(), sim.data[gpi_probe])
    plt.show()
Example #31
0
with nengo.Simulator(model) as sim:  # Create a simulator
    sim.run(1)  # Run it for 1 second

# ## Step 6: Plot the results

# In[ ]:

# Plot the decoded output of the ensemble
plt.plot(sim.trange(), sim.data[filtered])
plt.plot(sim.trange(), sim.data[sin_probe])
plt.xlim(0, 1)

# Plot the spiking output of the ensemble
from nengo.utils.matplotlib import rasterplot
plt.figure(figsize=(10, 8))
plt.subplot(221)
rasterplot(sim.trange(), sim.data[spikes], colors=[(1, 0, 0), (0, 0, 0)])
plt.xlim(0, 1)
plt.yticks((0, 1), ("On neuron", "Off neuron"))

# Plot the soma voltages of the neurons
plt.subplot(222)
plt.plot(sim.trange(), sim.data[voltage][:, 0] + 1, 'r')
plt.plot(sim.trange(), sim.data[voltage][:, 1], 'k')
plt.yticks(())
plt.axis([0, 1, 0, 2])
plt.subplots_adjust(wspace=0.05)

# The top graph shows that the input signal in green and the filtered output spikes from the two neurons population in blue.  The spikes (that are filtered) from the 'on' and 'off' neurons are shown in the bottom graph on the left.  On the right are the subthreshold voltages for the neurons.
Example #32
0
def show_stn():
    rasterplot(sim.trange(), sim.data[stn_probe])
    plt.show()
plt.figure()
plt.plot(eval_points, activities, lw=2)
plt.xlabel("Input Signal")
plt.ylabel("Firing rate (Hz)")
# plt.show()

with model:
    nengo.Connection(input, A)
    A_spikes = nengo.Probe(A.neurons)

with nengo.Simulator(model) as sim:
    sim.run(1)

plt.figure()
ax = plt.subplot(1, 1, 1)
rasterplot(sim.trange(), sim.data[A_spikes], ax)
ax.set_xlim(0, 1)
ax.set_ylabel('Neuron')
ax.set_xlabel('Time (s)')
# plt.show()

# Decoding
model = nengo.Network(label="NEF Summary")
with model:
    input = nengo.Node(lambda t: t * 2 - 1)
    input_probe = nengo.Probe(input)
    intercepts, encoders = aligned(8)
    A = nengo.Ensemble(8,
                       dimensions=1,
                       intercepts=intercepts,
                       max_rates=Uniform(80, 100),
Example #34
0
for i, image in enumerate(images):
    allimage[:, i * 28:(i + 1) * 28] = image.reshape(28, 28)

z2 = np.argmax(y, axis=1) == labels.repeat(100)

plt.figure(1)
plt.clf()
r, c = 5, 1

plt.subplot(r, c, 1)
plt.imshow(allimage, aspect='auto', interpolation='none', cmap='gray')
plt.xticks([])
plt.yticks([])

plt.subplot(r, c, 2)
rasterplot(t, sim.data[probe_layers[0]][:, :200])
plot_bars()
plt.xticks([])
plt.ylabel('layer 1 (500)')

plt.subplot(r, c, 3)
rasterplot(t, sim.data[probe_layers[1]])
plt.xticks([])
plt.yticks(np.linspace(0, 200, 5))
plot_bars()
plt.ylabel('layer 2 (200)')

plt.subplot(r, c, 4)
# plt.plot(t, x)
rasterplot(t, sim.data[probe_code][:, :200])
plot_bars()
Example #35
0
def view_spiking(t, images, labels, classifier, test, pres_time, max_pres=20,
                 layers=[], savefile=None):
    from nengo.utils.matplotlib import rasterplot
    dt = float(t[1] - t[0])

    # --- compute statistics on whole data
    for i, layer in enumerate(layers):
        rate = (layer > 0).mean() / dt
        print("Layer %d: %0.3f spikes / neuron / s" % (i+1, rate))

    # --- plots for partial data
    def plot_bars():
        ylim = plt.ylim()
        for x in np.arange(0, t[-1], pres_time):
            plt.plot([x, x], ylim, 'k--')

    n_pres = min(int(t[-1] / pres_time), max_pres)
    images = images[:n_pres]
    labels = labels[:n_pres]

    max_t = n_pres * pres_time
    tmask = t <= max_t
    t = t[tmask]
    classifier = classifier[tmask]
    test = test[tmask]
    layers = [layer[tmask] for layer in layers]

    allimage = np.zeros((28, 28 * len(images)), dtype=images.dtype)
    for i, image in enumerate(images):
        allimage[:, i * 28:(i + 1) * 28] = image.reshape(28, 28)

    plt.figure()
    r, c = 3 + len(layers), 1
    def next_subplot(i=np.array([0])):
        i[:] += 1
        return plt.subplot(r, c, i)

    next_subplot()
    plt.imshow(allimage, aspect='auto', interpolation='none', cmap='gray')
    plt.xticks([])
    plt.yticks([])

    max_neurons = 200
    for i, layer in enumerate(layers):
        n_neurons = layer.shape[1]
        next_subplot()
        if n_neurons > max_neurons:
            layer = layer[:, :max_neurons]
        rasterplot(t, layer)
        plot_bars()
        plt.xticks([])
        plt.ylabel('layer %d (%d)' % (i+1, n_neurons))


    next_subplot()
    plt.plot(t, classifier)
    plot_bars()
    plt.ylabel('class')

    next_subplot()
    plt.plot(t, test)
    plt.ylim([-0.1, 1.1])
    plot_bars()
    plt.ylabel('correct')

    plt.tight_layout()

    if savefile is not None:
        plt.savefig(savefile)
        print("Saved image at '%s'" % savefile)

    plt.show()
Example #36
0
def plot_sim_1(sp_1, sp_2, res_1, res_2, cal_1, cal_2, mem_1, mem_2):

    #representations  & spikes
    with plt.rc_context():
        plt.rcParams.update(theme.rcParams)

        fig, axes, = plt.subplots(2, 2, squeeze=True)
        theme.setup_figure(fig)
        t = sim.trange()
        plt.subplots_adjust(wspace=0.05, hspace=0.05)

        #spikes, calcium, resources first
        ax1 = axes[0, 0]
        ax1.set_title("First Module")
        ax1.set_ylabel('# cell', color='black')
        ax1.set_yticks(np.arange(0, Nm, 500))
        ax1.tick_params('y')  #, colors='black')
        rasterplot(sim.trange(), sp_1, ax1, colors=['black'] * sp_1.shape[0])
        ax1.set_xticklabels([])
        ax1.set_xticks([])
        ax1.set_xlim(0, 4.6)
        ax2 = ax1.twinx()
        ax2.plot(t, res_1, "#00bfc4", linewidth=2)
        ax2.plot(t, cal_1, "#e38900", linewidth=2)
        ax2.set_yticklabels([])
        ax2.set_yticks([])
        ax2.set_ylim(0, 1.1)

        #spikes, calcium, resources second
        ax3 = axes[0, 1]
        ax3.set_title("Second Module")
        rasterplot(sim.trange(), sp_2, ax3, colors=['black'] * sp_2.shape[0])
        ax3.set_xticklabels([])
        ax3.set_xticks([])
        ax3.set_yticklabels([])
        ax3.set_yticks([])
        ax3.set_xlim(0, 4.6)
        ax4 = ax3.twinx()
        ax4.plot(t, res_2, "#00bfc4", linewidth=2)
        ax4.plot(t, cal_2, "#e38900", linewidth=2)
        ax4.set_ylabel('synaptic variables', color="black", size=11)
        ax4.tick_params('y',
                        labelcolor='#333333',
                        labelsize=9,
                        color='#333333')
        ax4.set_ylim(0, 1.1)

        #representations first
        plot_mc = axes[1, 0]
        plot_mc.plot(sim.trange(), (mem_1))

        plot_mc.set_ylabel("Cosine similarity")
        plot_mc.set_xticks(np.arange(0.0, 4.6, 0.5))
        plot_mc.set_xticklabels(np.arange(0, 4600, 500).tolist())
        plot_mc.set_xlabel('time (ms)')
        plot_mc.set_xlim(0, 4.6)
        colors = [
            "#00c094", "#00bfc4", "#00b6eb", "#06a4ff", "#a58aff", "#df70f8",
            "#fb61d7", "#c49a00"
        ]
        for i, j in enumerate(plot_mc.lines):
            j.set_color(colors[i])

        #representations uncued
        plot_mu = axes[1, 1]

        plot_mu.plot(sim.trange(), (mem_2))
        plot_mu.set_xticks(np.arange(0.0, 4.6, 0.5))
        plot_mu.set_xticklabels(np.arange(0, 4600, 500).tolist())
        plot_mu.set_xlabel('time (ms)')
        plot_mu.set_yticks([])
        plot_mu.set_yticklabels([])
        plot_mu.set_xlim(0, 4.6)
        for i, j in enumerate(plot_mu.lines):
            j.set_color(colors[i])
        plot_mu.legend(
            ["0°", "5°", "10°", "16°", "24°", "32°", "40°", "Impulse"],
            title="Stimulus",
            bbox_to_anchor=(1.02, -0.25, .30, 0.8),
            loc=3,
            ncol=1,
            mode="expand",
            borderaxespad=0.)

        fig.set_size_inches(11, 5)
        theme.apply(plt.gcf().axes[0])
        theme.apply(plt.gcf().axes[1])
        theme.apply(plt.gcf().axes[2])
        theme.apply(plt.gcf().axes[3])
        plt.savefig('representations_exp2_2003.eps', format='eps', dpi=1000)
        plt.show()

    # impulse 1
    with plt.rc_context():
        plt.rcParams.update(theme.rcParams)

        fig, axes, = plt.subplots(1, 2, squeeze=True)
        theme.setup_figure(fig)
        t = sim.trange()
        plt.subplots_adjust(wspace=0.1, hspace=0.05)

        plot_mc = axes[0]
        plot_mc.set_title("First Module")
        plot_mc.plot(sim.trange(), (mem_1))
        plot_mc.set_ylabel("Cosine similarity")
        plot_mc.set_xticks(np.arange(1.2, 1.4, 0.05))
        plot_mc.set_xticklabels(np.arange(0, 250, 50).tolist())
        plot_mc.set_xlabel('time after onset impulse (ms)')
        plot_mc.set_xlim(1.2, 1.35)
        plot_mc.set_ylim(0, 0.9)
        colors = [
            "#00c094", "#00bfc4", "#00b6eb", "#06a4ff", "#a58aff", "#df70f8",
            "#fb61d7", "#c49a00"
        ]
        for i, j in enumerate(plot_mc.lines):
            j.set_color(colors[i])

        plot_mu = axes[1]
        plot_mu.set_title("Second Module")
        plot_mu.plot(sim.trange(), (mem_2))
        plot_mu.set_xticks(np.arange(1.2, 1.4, 0.05))
        plot_mu.set_xticklabels(np.arange(0, 250, 50).tolist())
        plot_mu.set_xlabel('time after onset impulse (ms)')
        plot_mu.set_yticks([])
        plot_mu.set_yticklabels([])
        plot_mu.set_xlim(1.2, 1.35)
        plot_mu.set_ylim(0, 0.9)
        for i, j in enumerate(plot_mu.lines):
            j.set_color(colors[i])
        plot_mu.legend(
            ["0°", "5°", "10°", "16°", "24°", "32°", "40°", "Impulse"],
            title="Stimulus",
            bbox_to_anchor=(0.85, 0.25, .55, 0.8),
            loc=3,
            ncol=1,
            mode="expand",
            borderaxespad=0.)

        fig.set_size_inches(6, 4)

        theme.apply(plt.gcf().axes[0])
        theme.apply(plt.gcf().axes[1])
        plt.savefig('Impulse1_exp2_2003.eps', format='eps', dpi=1000)
        plt.show()

    # impulse 2
    with plt.rc_context():
        plt.rcParams.update(theme.rcParams)

        fig, axes, = plt.subplots(1, 2, squeeze=True)
        theme.setup_figure(fig)
        t = sim.trange()
        plt.subplots_adjust(wspace=0.1, hspace=0.05)

        plot_mc = axes[0]
        plot_mc.set_title("First Module")
        plot_mc.plot(sim.trange(), (mem_1))
        plot_mc.set_ylabel("Cosine similarity")
        plot_mc.set_xticks(np.arange(3.8, 4.0, 0.05))
        plot_mc.set_xticklabels(np.arange(0, 250, 50).tolist())
        plot_mc.set_xlabel('time after onset impulse (ms)')
        plot_mc.set_xlim(3.8, 3.95)
        plot_mc.set_ylim(0, 0.9)
        colors = [
            "#00c094", "#00bfc4", "#00b6eb", "#06a4ff", "#a58aff", "#df70f8",
            "#fb61d7", "#c49a00"
        ]
        for i, j in enumerate(plot_mc.lines):
            j.set_color(colors[i])

        plot_mu = axes[1]
        plot_mu.set_title("Second Module")
        plot_mu.plot(sim.trange(), (mem_2))
        plot_mu.set_xticks(np.arange(3.8, 4.0, 0.05))
        plot_mu.set_xticklabels(np.arange(0, 250, 50).tolist())
        plot_mu.set_xlabel('time after onset impulse (ms)')
        plot_mu.set_yticks([])
        plot_mu.set_yticklabels([])
        plot_mu.set_xlim(3.8, 3.95)
        plot_mu.set_ylim(0, 0.9)
        for i, j in enumerate(plot_mu.lines):
            j.set_color(colors[i])
        plot_mu.legend(
            ["0°", "5°", "10°", "16°", "24°", "32°", "40°", "Impulse"],
            title="Stimulus",
            bbox_to_anchor=(0.85, 0.25, .55, 0.8),
            loc=3,
            ncol=1,
            mode="expand",
            borderaxespad=0.)

        fig.set_size_inches(6, 4)

        theme.apply(plt.gcf().axes[0])
        theme.apply(plt.gcf().axes[1])
        plt.savefig('Impulse2_exp2_2003.eps', format='eps', dpi=1000)
        plt.show()