Example #1
0
def run():
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(nsat.fnames.pickled)
    nsat.run_c_nsat()

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, nsat.fnames)
    states = c_nsat_reader.read_states()
    states_core0 = states[0][1]
    states_core1 = states[1][1]

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, 10):
        ax = fig.add_subplot(10, 1, i)
        ax.plot(states_core0[:500, i, 0], 'b', lw=3)
        ax.set_ylim([0, 110])
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, 10):
        ax = fig.add_subplot(10, 1, i)
        ax.plot(states_core1[:500, i, 0], 'r', lw=3)
        ax.set_ylim([0, 110])

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
def run():
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(nsat.fnames.pickled)

    nsat.run_c_nsat()

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, nsat.fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]

    out_spikelist = nsat.importAER(nsat.read_from_file(nsat.fnames.events +
                                                       '_core_0.dat'),
                                   sim_ticks=sim_ticks,
                                   id_list=[0])

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, 9):
        ax = fig.add_subplot(8, 1, i)
        ax.plot(states_core0[:, 0, i - 1], 'b', lw=2)

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #3
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    states_core0 = states[0][1]
    # np.save('states', states_core0)

    in_spikelist = SL
    ifname = fnames.events + '_core_0.dat'
    out_spikelist = nsat.importAER(nsat.read_from_file(ifname),
                                   sim_ticks=sim_ticks,
                                   id_list=[0])

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, 9):
        ax = fig.add_subplot(8, 1, i)
        ax.plot(states_core0[:-1, 15, i - 1], 'b', lw=1.5)

    # fig = plt.figure(figsize=(10, 10))
    # for i in range(1, 9):
    #     ax = fig.add_subplot(8, 1, i)
    #     ax.plot(states_core0[:-1, 16, i-1], 'b', lw=1.5)

    # out_spikelist.raster_plot()

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #4
0
def run():
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(nsat.fnames.pickled)
    nsat.run_c_nsat()

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, nsat.fnames)
    states = c_nsat_reader.read_c_nsat_states()
    states_core0 = states[0][1]

    # wt = c_nsat_reader.read_c_nsat_weights_evo(0)[:, 1, 1]
    wt, pids = c_nsat_reader.read_synaptic_weights_history(post=[0])
    in_spikelist = SL
    out_spikelist = nsat.importAER(nsat.read_from_file(nsat.fnames.events+'_core_0.dat'),
                                   sim_ticks=sim_ticks,
                                   id_list=[0])

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    i = 1
    ax = fig.add_subplot(4, 1, i)
    ax.plot(states_core0[:-1, 0, i - 1], 'b', lw=3, label='$V_m$')
    ax.set_ylabel('$V_m$')
    ax.set_xticks([])
    plt.locator_params(axis='y', nbins=4)
    i = 2
    ax = fig.add_subplot(4, 1, i)
    ax.plot(states_core0[:-1, 0, i - 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')
    ax.set_xticks([])
    plt.locator_params(axis='y', nbins=4)
    for t in SL[0].spike_times:
        plt.axvline(t, color='k')

    i = 4
    ax = fig.add_subplot(4, 1, i)
    for t in SL[0].spike_times:
        plt.axvline(t, color='k')
    ax.plot(states_core0[:-1, 0, 2], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$x_m$')
    plt.axhline(0, color='b', alpha=.5, linewidth=3)
    plt.locator_params(axis='y', nbins=4)
    i = 3

    ax = fig.add_subplot(4, 1, i)
    for t in SL[0].spike_times:
        plt.axvline(t, color='k')
    ax.plot(wt[0][:, 1, 1], 'r', lw=3)
    ax.set_ylabel('$w$')
    ax.set_xticks([])
    plt.locator_params(axis='y', nbins=4)

    plt.savefig('/tmp/%s.png' % (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #5
0
def run():
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(nsat.fnames.pickled)
    nsat.run_c_nsat()

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, nsat.fnames)
    states = c_nsat_reader.read_c_nsat_states()
    states_core0 = states[0][1]

    plt.figure()
    for i in range(1, 5):
        plt.subplot(4, 1, i)
        plt.plot(states_core0[:, :, i - 1])

    plt.figure()
    S = np.maximum(states_core0[:, :, 0], 0)
    plt.imshow(
        S,
        interpolation='spline36',
        cmap=plt.get_cmap('gray'),  #plt.cm.gray,
        aspect='auto',
        origin='lower')

    spks = nsat.importAER(nsat.read_from_file(nsat.fnames.events +
                                              '_core_0.dat'),
                          sim_ticks=sim_ticks,
                          id_list=list(range(cfg.core_cfgs[0].n_neurons)))

    try:
        raster = spks.raster_plot()
        raster.savefig('/tmp/%s_raster.png' %
                       (os.path.splitext(os.path.basename(__file__))[0]))
        raster.close()
    except:
        print('test_nf: Failed to generate /tmp/%s_raster.png' %
              (os.path.splitext(os.path.basename(__file__))[0]))

    # Plot the results


#     events = spks.convert()
#     mat = np.zeros((sim_ticks, N_NEURONS[0]))
#     print(mat.shape)
#     print(len(events[0]))
#     print(len(events[1]))
#     mat[events[0].astype('i'), events[1].astype('i')] = 1

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #6
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, 5):
        ax = fig.add_subplot(4, 1, i)
        ax.plot(states_core0[:-1, 0, i - 1], 'b', lw=3)

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #7
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    ww = np.array(c_nsat_reader.read_c_nsat_synaptic_weights()[0])

    spk = nsat.importAER(c_nsat_reader.read_events(0), sim_ticks=sim_ticks)
    spk.raster_plot()

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(ww[:cfg.core_cfgs[0].n_inputs, cfg.core_cfgs[0].n_inputs, 1], 'k.')

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #8
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    print("Plotting data")
    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]

    pip = nsat.importAER(c_nsat_reader.read_events(0),
                         sim_ticks=sim_ticks,
                         id_list=list(range(
                             cfg.core_cfgs[0].n_neurons))).time_slice(
                                 1000, sim_ticks - 1000).mean_rates()
    x = np.arange(pip.shape[0])

    from scipy.optimize import curve_fit

    # define "to-fit" function
    def sigmoid(x, a, b, c):
        return a / (1 + np.exp(-b * x / a) * (a - c) / a)

    # Fit data to function sigmoid
    popt, pcov = curve_fit(sigmoid, x, pip)
    print(("Sigmoid's parameters: a = {}, b = {}, c = {}".format(
        popt[0], popt[1], popt[2])))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x, pip, 'k', lw=2)
    ax.plot(x, sigmoid(x, popt[0], popt[1], popt[2]), 'r--', lw=2)

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #9
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    _, states_core0 = states[0][0], states[0][1]
    _, states_core1 = states[1][0], states[1][1]

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, states_core0.shape[2] + 1):
        ax = fig.add_subplot(2, 1, i)
        ax.plot(states_core0[:-1, 0, i - 1], 'b', lw=3)

    plt.savefig('/tmp/%s_0.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))

    fig = plt.figure(figsize=(10, 10))
    for i in range(1, states_core0.shape[2] + 1):
        ax = fig.add_subplot(2, 1, i)
        ax.plot(states_core1[:-1, 0, i - 1], 'b', lw=3)

    plt.savefig('/tmp/%s_1.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))

    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))

    out_spikelist = nsat.importAER(c_nsat_reader.read_events(0),
                                   sim_ticks=100,
                                   id_list=[0])
    out_spikelist.id_slice([0]).raster_plot(kwargs={'color': 'b'})
    plt.show()
Example #10
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    states_core0 = states[0][1]

    in_spikelist = SL
    out_spikelist = nsat.importAER(c_nsat_reader.read_events(0),
                                   sim_ticks=sim_ticks,
                                   id_list=[0])

    spks = out_spikelist.convert("[times,ids]")
    spks = np.vstack([spks[0], spks[1]]).astype('int')
    pretty_fig(spks, states_core0, t_stop=t_stop)

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #11
0
c_nsat_writer_train = nsat.C_NSATWriter(cfg_train, path='/tmp/erbp_mnist_train1/', prefix='')
c_nsat_writer_train.write()

c_nsat_writer_test = nsat.C_NSATWriter(cfg_test, path='/tmp/erbp_mnist_test1/', prefix='')
c_nsat_writer_test.write()

fname_train = c_nsat_writer_train.fname
fname_test = c_nsat_writer_test.fname

c_nsat_reader_train = nsat.C_NSATReader(cfg_train, fname_train)
c_nsat_reader_test = nsat.C_NSATReader(cfg_test, fname_test)

print("############# Running simulation #####################")
pip = []
for i in range(nepochs):
    nsat.run_c_nsat(fname_train)

    copyfile(fname_train.shared_mem+'_core_0.dat',
             fname_test.syn_wgt_table+'_core_0.dat',)
    # cfg_test.core_cfgs[0].W = c_nsat_reader_train.read_c_nsat_weights()[0]
    # cfg_train.core_cfgs[0].W = cfg_test.core_cfgs[0].W.copy()
    # c_nsat_writer_test.write_L0connectivity()
    # c_nsat_writer_train.write_L0connectivity()
    if test_every>0:
        if i % test_every == test_every-1:
            nsat.run_c_nsat(fname_test)
            test_spikelist = nsat.importAER(c_nsat_reader_test.read_c_nsat_raw_events()[0],
                                            sim_ticks=sim_ticks_test,
                                            id_list=np.arange(sP, sP+Np))

            pip .append([i, float(sum(np.argmax(test_spikelist.id_slice(range(sP,sP+Np)).firing_rate(t_sample_test).T,axis=1) == targets_classify[:N_test]))/N_test*100])
Example #12
0
    ext_evts_data = nsat.exportAER(SL)
    cfg.set_ext_events(ext_evts_data)

    # Write the C NSAT parameters binary files
    c_nsat_writer = nsat.C_NSATWriter(cfg, path='/tmp', prefix='test_stdp')
    c_nsat_writer.write()

    # Write Intel FPGA hex parameters files
    #    intel_fpga_writer = nsat.IntelFPGAWriter(cfg, path='.',
    #                                             prefix='test_stdp')
    #    intel_fpga_writer.write()
    #    intel_fpga_writer.write_globals()

    # Call the C NSAT
    print("Running C NSAT!")
    nsat.run_c_nsat(c_nsat_writer.fname)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, c_nsat_writer.fname)
    #ww = np.array(c_nsat_reader.read_c_nsat_synaptic_weights()[0])
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]
    # wt = c_nsat_reader.read_c_nsat_weights_evo(2)[0]
    wt = c_nsat_reader.read_c_nsat_syn_evo()[0][0]

    spk = nsat.importAER(nsat.read_from_file(c_nsat_writer.fname.events +
                                             '_core_0.dat'),
                         sim_ticks=sim_ticks)
    spk.raster_plot()

    print((SL[0].spike_times))
Example #13
0
def run():
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(nsat.fnames.pickled)
    nsat.run_c_nsat()

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, nsat.fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[core][0], states[core][1]

    wt, pids = c_nsat_reader.read_synaptic_weights_history(
        post=[130, 150, 120])
    wt, pids = wt[0], pids[0]
    in_spikelist = SL
    out_spikelist = nsat.importAER(c_nsat_reader.read_events(0),
                                   sim_ticks=sim_ticks,
                                   id_list=[0])

    plt.matplotlib.rcParams['figure.subplot.bottom'] = .1
    plt.matplotlib.rcParams['figure.subplot.left'] = .2
    plt.matplotlib.rcParams['figure.subplot.right'] = .98
    plt.matplotlib.rcParams['figure.subplot.hspace'] = .1
    plt.matplotlib.rcParams['figure.subplot.top'] = 1.0
    # Plot the results
    fig = plt.figure(figsize=(14, 10))

    i = 4
    ax1 = fig.add_subplot(5, 1, i)
    for t in SL[100].spike_times:
        plt.axvline(t, color='g', alpha=.4)
    ax1.plot(states_core0[:-1, 0, 2], 'b', lw=3, label='$x_m$')
    ax1.set_ylabel('$x_m$')
    ax1.get_yaxis().set_label_coords(-0.12, 0.5)
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.axhline(0, color='b', alpha=.5, linewidth=3)
    plt.locator_params(axis='y', nbins=4)

    i = 5
    ax = fig.add_subplot(5, 1, i, sharex=ax1)
    for t in SL[0].spike_times:
        plt.axvline(t, color='k', alpha=.4)
    ax.plot(wt[:, 19, 1], 'r', lw=3)
    # ax.imshow(wt[:, :, 1], aspect='auto', interpolation='nearest')
    ax.set_ylabel('$w$')
    ax.set_xlabel('Time Step')
    ax.get_yaxis().set_label_coords(-0.12, 0.5)
    plt.locator_params(axis='y', nbins=4)

    i = 2
    ax = fig.add_subplot(5, 1, i, sharex=ax1)
    ax.plot(states_core0[:-1, 0, 0], 'b', lw=3, label='$V_m$')
    ax.set_ylabel('$V_m$')
    ax.get_yaxis().set_label_coords(-0.12, 0.5)
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.locator_params(axis='y', nbins=4)

    i = 3
    ax = fig.add_subplot(5, 1, i, sharex=ax1)
    ax.plot(states_core0[:-1, 0, 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')
    ax.get_yaxis().set_label_coords(-0.12, 0.5)
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.locator_params(axis='y', nbins=4)
    for t in np.ceil(SL[0].spike_times):
        plt.axvline(t, color='k', alpha=.4)

    ax1 = fig.add_subplot(5, 1, 1, sharex=ax1)
    out_spikelist.id_slice([0]).raster_plot(display=ax1, kwargs={'color': 'b'})
    out_spikelist.id_slice(list(range(1,
                                      30))).raster_plot(display=ax1,
                                                        kwargs={'color': 'k'})
    ax1.set_xlabel('')
    plt.setp(ax1.get_xticklabels(), visible=False)
    ax1.get_yaxis().set_label_coords(-0.12, 0.5)
    plt.tight_layout()

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #14
0
fname_test = c_nsat_writer_test.fname
c_nsat_reader_test = nsat.C_NSATReader(cfg_test, fname_test)

# cfg_train.core_cfgs[0].latex_print_parameters(2)

if __name__ == '__main__':
    n_epoch = 50
    e = []
    print("############## Training ##############")
    for i in range(n_epoch):
        # Call the C NSAT for learning
        print("Epoch #:  ", i)
        c_nsat_writer_train.fname.stats_nsat = \
                '/tmp/test_eCD_stats_nsat_full'+str(i)
        nsat.run_c_nsat(c_nsat_writer_train.fname)
        if n_epoch > 1:
            shutil.copyfile(
                fname_train.shared_mem + '_core_0.dat',
                fname_train.syn_wgt_table + '_core_0.dat',
            )
            shutil.copyfile(
                fname_train.shared_mem + '_core_0.dat',
                fname_test.syn_wgt_table + '_core_0.dat',
            )
        nsat.run_c_nsat(c_nsat_writer_test.fname)
        test_spk = nsat.importAER(
            nsat.read_from_file(c_nsat_writer_test.fname.events +
                                '_core_0.dat'),
            sim_ticks=sim_ticks_test)
        test_spk = nsat.importAER(c_nsat_reader_test.read_events(0),
Example #15
0
def erbp_convnet_2L(data_train, data_classify, targets_classify, nepochs=10):
    N_FEAT1 = 16
    N_FEAT2 = 32
    stride = 2
    ksize = 5

    exp_name = '/tmp/mnist_convnet_2L'
    exp_name_test = '/tmp/mnist_convnet_2L_test/'

    inputsize = 28
    Nchannel = 1
    Nxy = inputsize*inputsize
    Nv = Nxy*Nchannel
    Nl = 10
    Nconv1 = Nv//stride//stride*N_FEAT1//Nchannel
    Nconv2 = Nconv1//stride//stride*N_FEAT2//N_FEAT1
    Nh = 100

    t_sample_test = 3000
    t_sample_train = 1500
    N_train = 5000
    N_test = 1000
    test_every = 1
    inp_fact = 25

    sim_ticks = N_train*t_sample_train
    sim_ticks_test = N_test*t_sample_test

    np.random.seed(100)

    wpg = 96
    wgp = 37

    erbp_ptype_ = erbp_ptype.copy()
    erbp_ptype_.rr_num_bits = 12
    erbp_ptype_.hiac = [-7, OFF, OFF]

    erf_ntype_ = erf_ntype.copy()
    erf_ntype_.plasticity_type = [erbp_ptype_, nonplastic_ptype]
    erf_ntype_.Wgain[0] = 2

    net_graph = LogicalGraphSetup()

    pop_data = net_graph.create_population(Population(name='pop_data',
                                                      n=Nv,
                                                      core=-1,
                                                      is_external=True))
    pop_lab = net_graph.create_population(Population(name='pop_lab',
                                                     n=Nl,
                                                     core=-1,
                                                     is_external=True))
    pop_conv1 = net_graph.create_population(Population(name='pop_conv1',
                                                       n=Nconv1,
                                                       core=0,
                                                       neuron_cfg=erf_ntype_))
    pop_conv2 = net_graph.create_population(Population(name='pop_conv2',
                                                       n=Nconv2,
                                                       core=1,
                                                       neuron_cfg=erf_ntype_))
    pop_hid = net_graph.create_population(Population(name='pop_hid',
                                                     n=Nh,
                                                     core=1,
                                                     neuron_cfg=erf_ntype_))
    pop_out = net_graph.create_population(Population(name='pop_out',
                                                     n=Nl,
                                                     core=1,
                                                     neuron_cfg=output_ntype))

    net_graph.create_connection(pop_data, pop_conv1, 0,
                                connect_conv2dbank(inputsize,
                                                   Nchannel,
                                                   N_FEAT1,
                                                   stride,
                                                   ksize))
    net_graph.create_connection(pop_conv1, pop_conv2, 0,
                                connect_conv2dbank(inputsize//stride,
                                                   N_FEAT1,
                                                   N_FEAT2,
                                                   stride,
                                                   ksize))
    net_graph.create_connection(pop_conv2, pop_hid, 0,
                                connect_random_uniform(low=-16, high=16))
    net_graph.create_connection(pop_hid, pop_out, 0,
                                connect_random_uniform(low=-4, high=4))

    pop_err_pos = net_graph.create_population(Population(name='pop_err_pos',
                                                         n=Nl,
                                                         core=0,
                                                         neuron_cfg=error_ntype))
    pop_err_neg = net_graph.create_population(Population(name='pop_err_neg',
                                                         n=Nl,
                                                         core=0,
                                                         neuron_cfg=error_ntype))

    net_graph.create_connection(pop_out, pop_err_pos, 0, connect_one2one(-wpg))
    net_graph.create_connection(pop_out, pop_err_neg, 0, connect_one2one(wpg))

    net_graph.create_connection(pop_lab, pop_err_pos, 0, connect_one2one(wpg))
    net_graph.create_connection(pop_lab, pop_err_neg, 0, connect_one2one(-wpg))

    [p, w] = connect_shuffle(2000)(pop_err_pos, pop_conv1)
    net_graph.create_connection(pop_err_pos, pop_conv1, 1, [p, +w])
    net_graph.create_connection(pop_err_neg, pop_conv1, 1, [p, -w])

    [p, w] = connect_shuffle(2000)(pop_err_pos, pop_conv2)
    net_graph.create_connection(pop_err_pos, pop_conv2, 1, [p, +w])
    net_graph.create_connection(pop_err_neg, pop_conv2, 1, [p, -w])

    [p, w] = connect_shuffle(3000)(pop_err_pos, pop_hid)
    net_graph.create_connection(pop_err_pos, pop_hid, 1, [p, +w])
    net_graph.create_connection(pop_err_neg, pop_hid, 1, [p, -w])

    net_graph.create_connection(pop_err_pos, pop_out, 1, connect_one2one(wgp))
    net_graph.create_connection(pop_err_neg, pop_out, 1, connect_one2one(-wgp))

    setup = net_graph.generate_multicore_setup(NSATSetup)

    spk_rec_mon = [[] for i in range(setup.ncores)]

    cfg_train = setup.create_configuration_nsat(sim_ticks=sim_ticks,
                                                w_check=False,
                                                spk_rec_mon=spk_rec_mon,
                                                monitor_spikes=False,
                                                gated_learning=[True, True],
                                                plasticity_en=[True, True])

    spk_rec_mon = [[] for i in range(setup.ncores)]
    spk_rec_mon[pop_out.core] = pop_out.addr

    cfg_test = cfg_train.copy()
    cfg_test.sim_ticks = sim_ticks_test
    cfg_test.plasticity_en[:] = False
    cfg_test.spk_rec_mon = spk_rec_mon
    cfg_test.monitor_spikes = True

    SL_train = create_spike_train(data_train[:N_train],
                                  t_sample_train,
                                  scaling=inp_fact,
                                  with_labels=True)
    ext_evts_data_train = nsat.exportAER(SL_train)

    SL_test = create_spike_train(data_classify[:N_test],
                                 t_sample_test,
                                 scaling=inp_fact,
                                 with_labels=False)
    ext_evts_data_test = nsat.exportAER(SL_test)

    cfg_test.set_ext_events(ext_evts_data_test)
    cfg_train.set_ext_events(ext_evts_data_train)

    c_nsat_writer_train = nsat.C_NSATWriter(cfg_train,
                                            path=exp_name,
                                            prefix='')
    c_nsat_writer_train.write()

    c_nsat_writer_test = nsat.C_NSATWriter(cfg_test,
                                           path=exp_name_test,
                                           prefix='')
    c_nsat_writer_test.write()

    fname_train = c_nsat_writer_train.fname
    fname_test = c_nsat_writer_test.fname
    c_nsat_reader_test = nsat.C_NSATReader(cfg_test, fname_test)

    pip, total_time = [], []
    t0t, tft = 0, 0
    for i in range(nepochs):
        t0 = time.time()
        nsat.run_c_nsat(fname_train)
        tf = time.time()

        for j in range(setup.ncores):
            # train->test
            shutil.copy(exp_name+'/_shared_mem_core_{0}.dat'.format(
                j), exp_name_test+'/_wgt_table_core_{0}.dat'.format(j))
            # train->train
            shutil.copy(exp_name+'/_shared_mem_core_{0}.dat'.format(
                j), exp_name+'/_wgt_table_core_{0}.dat'.format(j))
        if test_every > 0:
            if i % test_every == test_every-1:
                t0t = time.time()
                nsat.run_c_nsat(fname_test)
                tft = time.time()
                acc, slout = test_accuracy(c_nsat_reader_test,
                                           targets=targets_classify[:N_test],
                                           pop=pop_out,
                                           sim_ticks=sim_ticks_test,
                                           duration=t_sample_test)
                pip.append(acc)
        total_time.append(tf - t0 + tft - t0t)
    return pip, total_time
Example #16
0
def erbp_mlp_2L_multicore(data_train, data_classify, targets_classify,
                          nepochs=10):
    exp_name = '/tmp/mnist_mlp_2L'
    exp_name_test = '/tmp/mnist_mlp_2L_test/'

    inputsize = 28
    Nchannel = 1
    Nxy = inputsize*inputsize
    Nv = Nxy*Nchannel
    Nl = 10
    Nh = 100

    t_sample_test = 3000
    t_sample_train = 1500
    N_train = 500
    N_test = 100
    test_every = 1
    inp_fact = 25

    sim_ticks = N_train*t_sample_train
    sim_ticks_test = N_test*t_sample_test

    np.random.seed(100)

    wpg = 96
    wgp = 37

    net_graph = LogicalGraphSetup()

    pop_data = net_graph.create_population(Population(name='data',
                                                      n=Nv,
                                                      core=-1,
                                                      is_external=True))
    pop_lab = net_graph.create_population(Population(name='lab',
                                                     n=Nl,
                                                     core=-1,
                                                     is_external=True))
    pop_hid1 = net_graph.create_population(Population(name='hid1',
                                                      n=Nh,
                                                      core=0,
                                                      neuron_cfg=erf_ntype))
    pop_hid2 = net_graph.create_population(Population(name='hid2',
                                                      n=Nh,
                                                      core=1,
                                                      neuron_cfg=erf_ntype))
    pop_out = net_graph.create_population(Population(name='out',
                                                     n=Nl,
                                                     core=0,
                                                     neuron_cfg=output_ntype))
    pop_err_pos = net_graph.create_population(Population(name='err_pos',
                                                         n=Nl,
                                                         core=0,
                                                         neuron_cfg=error_ntype))
    pop_err_neg = net_graph.create_population(Population(name='err_neg',
                                                         n=Nl,
                                                         core=0,
                                                         neuron_cfg=error_ntype))

    net_graph.create_connection(pop_data, pop_hid1, 0,
                                connect_random_uniform(low=-16, high=16))
    net_graph.create_connection(pop_hid1, pop_hid2, 0,
                                connect_random_uniform(low=-16, high=16))
    net_graph.create_connection(pop_hid2, pop_out,  0,
                                connect_random_uniform(low=-4, high=4))

    net_graph.create_connection(pop_out, pop_err_pos, 0, connect_one2one(-wpg))
    net_graph.create_connection(pop_out, pop_err_neg, 0, connect_one2one(wpg))

    net_graph.create_connection(pop_lab, pop_err_pos, 0, connect_one2one(wpg))
    net_graph.create_connection(pop_lab, pop_err_neg, 0, connect_one2one(-wpg))

    p, w = connect_shuffle(3000)(pop_err_pos, pop_hid1)

    net_graph.create_connection(pop_err_pos, pop_hid1, 1, [p,  w])
    net_graph.create_connection(pop_err_neg, pop_hid1, 1, [p, -w])

    p, w = connect_shuffle(3000)(pop_err_pos, pop_hid2)

    net_graph.create_connection(pop_err_pos, pop_hid2, 1, [p,  w])
    net_graph.create_connection(pop_err_neg, pop_hid2, 1, [p, -w])

    net_graph.create_connection(pop_err_pos, pop_out, 1, connect_one2one(wgp))
    net_graph.create_connection(pop_err_neg, pop_out, 1, connect_one2one(-wgp))

    setup = net_graph.generate_multicore_setup(NSATSetup)

    spk_rec_mon = [[] for i in range(setup.ncores)]
    spk_rec_mon[pop_out.core] = pop_out.addr

    cfg_train = setup.create_configuration_nsat(sim_ticks=sim_ticks,
                                                w_check=False,
                                                spk_rec_mon=spk_rec_mon,
                                                monitor_spikes=True,
                                                gated_learning=True,
                                                plasticity_en=True)

    spk_rec_mon = [[] for i in range(setup.ncores)]
    spk_rec_mon[pop_out.core] = pop_out.addr

    cfg_test = cfg_train.copy()
    cfg_test.sim_ticks = sim_ticks_test
    cfg_test.plasticity_en[:] = False
    cfg_test.spk_rec_mon = spk_rec_mon
    cfg_test.monitor_spikes = True

    SL_train = create_spike_train(data_train[:N_train],
                                  t_sample_train,
                                  scaling=inp_fact,
                                  with_labels=True)
    ext_evts_data_train = nsat.exportAER(SL_train)

    SL_test = create_spike_train(data_classify[:N_test],
                                 t_sample_test,
                                 scaling=inp_fact,
                                 with_labels=False)
    ext_evts_data_test = nsat.exportAER(SL_test)

    cfg_test.set_ext_events(ext_evts_data_test)
    cfg_train.set_ext_events(ext_evts_data_train)

    c_nsat_writer_train = nsat.C_NSATWriter(cfg_train,
                                            path=exp_name,
                                            prefix='')
    c_nsat_writer_train.write()

    c_nsat_writer_test = nsat.C_NSATWriter(cfg_test,
                                           path=exp_name_test,
                                           prefix='')
    c_nsat_writer_test.write()

    fname_train = c_nsat_writer_train.fname
    fname_test = c_nsat_writer_test.fname

    c_nsat_reader_test = nsat.C_NSATReader(cfg_test, fname_test)

    pip, tt = [], []
    tft, t0t = 0, 0
    for i in range(nepochs):
        t0 = time.time()
        nsat.run_c_nsat(fname_train)
        tf = time.time()

        for j in range(setup.ncores):
            # train->test
            shutil.copy(exp_name+'/_shared_mem_core_{0}.dat'.format(
                j), exp_name_test+'/_wgt_table_core_{0}.dat'.format(j))
            # train->train
            shutil.copy(exp_name+'/_shared_mem_core_{0}.dat'.format(
                j), exp_name+'/_wgt_table_core_{0}.dat'.format(j))
        if test_every > 0:
            if i % test_every == test_every-1:
                t0t = time.time()
                nsat.run_c_nsat(fname_test)
                tft = time.time()
                acc, slout = test_accuracy(c_nsat_reader_test,
                                           targets=targets_classify[:N_test],
                                           pop=pop_out,
                                           sim_ticks=sim_ticks_test,
                                           duration=t_sample_test)
                pip.append(acc)
        t_total = (tf - t0) + (tft - t0t)
        tt.append(t_total)
    return pip, tt
Example #17
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]

    # w0 = c_nsat_reader.read_synaptic_weights_history(post=0)[0][:, 0, 1]
    w0, pids0 = c_nsat_reader.read_synaptic_weights_history(post=[5])
    w0 = w0[0][:, 4, 1]
    w1, pids1 = c_nsat_reader.read_synaptic_weights_history(post=[6])
    w1 = w1[0][:, 4, 1]
    w2, pids2 = c_nsat_reader.read_synaptic_weights_history(post=[7])
    w2 = w2[0][:, 4, 1]
    np.save('w0', w0)
    np.save('w1', w1)
    np.save('w2', w2)
    # w = c_nsat_reader.read_synaptic_weights()

    out_spikelist = nsat.importAER(c_nsat_reader.read_events(0),
                                   sim_ticks=sim_ticks)
    np.save('spk0', out_spikelist[0].spike_times)
    np.save('spk1', out_spikelist[1].spike_times)
    np.save('spk2', out_spikelist[2].spike_times)
    np.save('spk3', out_spikelist[3].spike_times)

    # Plot the results
    fig = plt.figure(figsize=(15, 15))

    ax = fig.add_subplot(5, 2, 1)
    ax.plot(states_core0[:-1, 0, 0], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$V_m$')

    ax = fig.add_subplot(5, 2, 2)
    ax.plot(states_core0[:-1, 1, 0], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$V_m$')

    ax = fig.add_subplot(5, 2, 3)
    ax.plot(states_core0[:-1, 0, 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')

    ax = fig.add_subplot(5, 2, 4)
    ax.plot(states_core0[:-1, 1, 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')

    ax = fig.add_subplot(5, 2, 5)
    ax.plot(states_core0[:-1, 0, 2], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$x_m$')

    ax = fig.add_subplot(5, 2, 6)
    ax.plot(states_core0[:-1, 1, 2], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$x_m$')

    fig = plt.figure()
    ax = fig.add_subplot(4, 1, 1)
    for i in range(4):
        for i in out_spikelist[0].spike_times:
            ax.axvline(i, color='k', lw=1, zorder=0, label='lal')
        ax.set_ylabel('Spikes')
        ax.set_xlim([0, sim_ticks])

        # ax = fig.add_subplot(4, 1, 2)
        ax.step(w0, 'r', lw=2, zorder=10, where='post', label='lala')
        for i in out_spikelist[1].spike_times:
            ax.axvline(i, color='k', lw=1, zorder=0, label='dsds')
        # ax.set_ylabel('Spikes')
        # ax.set_xlim([0, sim_ticks])

        # ax = fig.add_subplot(4, 1, 3)
        ax.step(w1, 'r', lw=2, zorder=10, where='post', label='ta')
        for i in out_spikelist[2].spike_times:
            ax.axvline(i, color='k', lw=1, zorder=0, label='dss')
        # ax.set_xlim([0, sim_ticks])

        # ax = fig.add_subplot(4, 1, 4)
        ax.step(w2, 'r', lw=2, zorder=10, where='post', label='ar')
        for i in out_spikelist[3].spike_times:
            ax.axvline(i, color='k', lw=1, zorder=0, label='dadsa')
        # ax.set_xlim([0, sim_ticks])
    ax.set_xlim([0, sim_ticks])

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #18
0
def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]

    wt, _ = c_nsat_reader.read_c_nsat_weights_evo([0, 1])
    wt = wt[0]

    out_spikelist = nsat.importAER(nsat.read_from_file(fnames.events +
                                                       '_core_0.dat'),
                                   sim_ticks=sim_ticks)

    # Plot the results
    fig = plt.figure(figsize=(15, 15))

    ax = fig.add_subplot(4, 2, 1)
    ax.plot(states_core0[:-1, 0, 0], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$V_m$')

    ax = fig.add_subplot(4, 2, 2)
    ax.plot(states_core0[:-1, 1, 0], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$V_m$')

    ax = fig.add_subplot(4, 2, 3)
    ax.plot(states_core0[:-1, 0, 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')

    ax = fig.add_subplot(4, 2, 4)
    ax.plot(states_core0[:-1, 1, 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')

    ax = fig.add_subplot(4, 2, 5)
    ax.plot(states_core0[:-1, 0, 2], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$x_m$')

    ax = fig.add_subplot(4, 2, 6)
    ax.plot(states_core0[:-1, 1, 2], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$x_m$')

    ax = fig.add_subplot(4, 2, 7)
    ax.plot(wt[:, 1, 1], 'r', lw=3)
    ax.set_ylabel('$w$')

    ax = fig.add_subplot(4, 2, 8)
    ax.plot(wt[:, 0, 1], 'r', lw=3)
    ax.set_ylabel('$w$')

    fig = plt.figure(figsize=(10, 5))
    plt.plot(wt[:, 0, 1], 'r', lw=2, zorder=10)
    plt.plot(wt[:, 1, 1], 'y', lw=2, zorder=10)
    # for i in out_spikelist[0].spike_times:
    # plt.axvline(i, color='k', lw=1, zorder=0)
    # for i in out_spikelist[1].spike_times:
    # plt.axvline(i, color='b', lw=1, zorder=0)

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
Example #19
0
def run():
    # Call the C NSAT
    global spk0
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(nsat.fnames.pickled)
    nsat.run_c_nsat()

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, nsat.fnames)
    #ww = np.array(c_nsat_reader.read_c_nsat_synaptic_weights()[0])
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]
    # wt = c_nsat_reader.read_c_nsat_syn_evo()[0][0]
    wt, pids = c_nsat_reader.read_synaptic_weights_history()
    wt = wt[0]

    spk = nsat.importAER(c_nsat_reader.read_events(0), sim_ticks=sim_ticks)
    spk.raster_plot()

    print((SL[0].spike_times))
    print((SL[1].spike_times))
    print((spk[0].spike_times))

    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # ax.plot(ww[:N_INPUTS[0], N_INPUTS[0], 1], 'k.')

    # Plot the results
    fig = plt.figure(figsize=(15, 15))

    ax = fig.add_subplot(4, 2, 1)
    ax.plot(states_core0[:-1, 0, 0], 'b', lw=3, label='$x_m$')
    for i in spk[0].spike_times:
        plt.axvline(i, color='k', lw=1)
    ax.set_ylabel('$V_m$')

    # ax = fig.add_subplot(4, 2, 2)
    # ax.plot(states_core0[:-1, 1, 0], 'b', lw=3, label='$x_m$')
    # ax.set_ylabel('$V_m$')

    ax = fig.add_subplot(4, 2, 3)
    ax.plot(states_core0[:-1, 0, 1], 'b', lw=3, label='$I_{syn}$')
    ax.set_ylabel('$I_{syn}$')

    # ax = fig.add_subplot(4, 2, 4)
    # ax.plot(states_core0[:-1, 1, 1], 'b', lw=3, label='$I_{syn}$')
    # ax.set_ylabel('$I_{syn}$')

    ax = fig.add_subplot(4, 2, 5)
    ax.plot(states_core0[:-1, 0, 2], 'b', lw=3, label='$x_m$')
    ax.set_ylabel('$x_m$')

    # ax = fig.add_subplot(4, 2, 6)
    # ax.plot(states_core0[:-1, 1, 1], 'b', lw=3, label='$x_m$')
    # ax.set_ylabel('$x_m$')

    print(wt.shape)
    ax = fig.add_subplot(4, 2, 7)
    # ax.plot(wt[wt[:, 0, :] == 0, 0], wt[wt[:, 1, :] == 0, 4], 'r', lw=3)
    ax.plot(wt[:, 0, 0], wt[:, 1, 0], 'r', lw=3)
    for i in spk[0].spike_times:
        plt.axvline(i, color='k', lw=1)
    for i in spk0[1].spike_times:
        plt.axvline(i, color='r', lw=1)
    ax.set_ylabel('$w$')

    ax = fig.add_subplot(4, 2, 8)
    # ax.plot(wt[wt[:, 1, :] == 1, 0], wt[wt[:, 1, :] == 1, 4], 'r', lw=3)
    for i in spk[0].spike_times:
        plt.axvline(i, color='k', lw=1)
    for i in spk0[1].spike_times:
        plt.axvline(i, color='r', lw=1)
    ax.set_ylabel('$w$')

    # ax = fig.add_subplot(4, 2, 8)
    # ax.plot(wt[:, 1, 1], 'r', lw=3)
    # ax.set_ylabel('$w$')

    # fig = plt.figure(figsize=(10, 5))
    # for i in spk[0].spike_times:
    #    plt.plot(wt[:, 1, 1], 'r', lw=3)
    #    plt.axvline(i, color='k', lw=1)

    plt.savefig('/tmp/%s.png' %
                (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))