Esempio n. 1
0
def plot_pop_raster(net, plot_inh=False):
    """plot rasterplot of whole E/I populations"""
    pyplot.figure()
    bb.raster_plot(net.mon_spike_e)
    if plot_inh:
        pyplot.figure()
        bb.raster_plot(net.mon_spike_i)
def main():

    tmax = 50e-3                # second

    cn.set_fs(40e3)             # Hz

    # anf_trains are normally generated by something like
    # cochlea.run_zilany2009()
    anf_trains = pd.DataFrame([
        {'spikes': np.array([10e-3, 30e-3]), 'duration': tmax},
        {'spikes': np.array([20e-3, 40e-3]), 'duration': tmax},
    ])

    # Generate ANF and GBC groups
    anfs = cn.make_anf_group(anf_trains)
    gbcs = cn.make_gbc_group(10)

    # Connect ANFs and GBCs
    synapses = brian.Connection(
        anfs,
        gbcs,
        'ge_syn',
    )

    synapses.connect_random(
        anfs,
        gbcs,
        p=0.5,
        fixed=True,
        weight=1e-6*siemens
    )

    # Monitors for the GBCs
    spikes = brian.SpikeMonitor(gbcs)
    voltages = brian.StateMonitor(gbcs, 'vm', record=True)

    # Run the simulation
    cn.run(
        duration=tmax,
        objects=[anfs, gbcs, synapses, spikes, voltages]
    )

    # Present the results
    print(spikes.spikes)

    fig, ax = plt.subplots(2,1)

    plt.sca(ax[0])
    brian.raster_plot(spikes)

    plt.sca(ax[1])
    voltages.plot()
    plt.show()
def save_and_plot_results():
	global fig_num
	
	print '...saving results'

	if not test_mode:
		save_theta()
	if not test_mode:
		save_connections()
	else:
		np.save(top_level_path + 'activity/conv_patch_connectivity_activity/results_' + str(num_examples) + '_' + ending, result_monitor)
		np.save(top_level_path + 'activity/conv_patch_connectivity_activity/input_numbers_' + str(num_examples) + '_' + ending, input_numbers)

	if do_plot:
		if rate_monitors:
			b.figure(fig_num)
			fig_num += 1
			for i, name in enumerate(rate_monitors):
				b.subplot(len(rate_monitors), 1, i + 1)
				b.plot(rate_monitors[name].times / b.second, rate_monitors[name].rate, '.')
				b.title('Rates of population ' + name)

		if spike_monitors:
			b.figure(fig_num)
			fig_num += 1
			for i, name in enumerate(spike_monitors):
				b.subplot(len(spike_monitors), 1, i + 1)
				b.raster_plot(spike_monitors[name])
				b.title('Spikes of population ' + name)

		if spike_counters:
			b.figure(fig_num)
			fig_num += 1
			for i, name in enumerate(spike_counters):
				b.subplot(len(spike_counters), 1, i + 1)
				b.plot(np.asarray(spike_counters['Ae'].count[:]))
				b.title('Spike count of population ' + name)

		plot_2d_input_weights()
		plot_patch_weights()

		b.ioff()
		b.show()
    def _print_graphs(self, traj):
        """Makes some plots and stores them into subfolders"""
        print_folder = self._make_folder(traj)

        # If we use BRIAN's own raster_plot functionality we
        # need to sue the SpikeMonitor directly
        raster_plot(self.spike_monitor,
                    newfigure=True,
                    xlabel='t',
                    ylabel='Exc. Neurons',
                    title='Spike Raster Plot')

        filename = os.path.join(print_folder, 'spike.png')

        print 'Current plot: %s ' % filename
        plt.savefig(filename)
        plt.close()

        fig = plt.figure()
        self._plot_result(traj, 'monitors.V')
        filename = os.path.join(print_folder, 'V.png')
        print 'Current plot: %s ' % filename
        fig.savefig(filename)
        plt.close()

        plt.figure()
        self._plot_result(traj, 'monitors.I_syn_e')
        filename = os.path.join(print_folder, 'I_syn_e.png')
        print 'Current plot: %s ' % filename
        plt.savefig(filename)
        plt.close()

        plt.figure()
        self._plot_result(traj, 'monitors.I_syn_i')
        filename = os.path.join(print_folder, 'I_syn_i.png')
        print 'Current plot: %s ' % filename
        plt.savefig(filename)
        plt.close()

        if not traj.analysis.show_plots:
            plt.close('all')
        else:
            plt.show()
Esempio n. 5
0
def main():

    fs = 100e3
    cf = 1e3
    tmax = 50e-3

    sound = wv.ramped_tone(
        fs=fs,
        freq=cf,
        duration=tmax,
        pad=30e-3,
        dbspl=50,
    )

    anf_trains = cochlea.run_zilany2014(
        sound=sound,
        fs=fs,
        cf=cf,
        anf_num=(300, 0, 0),
        seed=0,
        species='cat',
    )

    anfs = cochlea.make_brian_group(anf_trains)

    print(anfs)


    brainstem = make_brainstem_group(100)

    print(brainstem)

    monitor = brian.SpikeMonitor(brainstem)


    net = brian.Network([brainstem, monitor])
    net.run(tmax*second)


    brian.raster_plot(monitor)
    brian.show()
Esempio n. 6
0
    def _print_graphs(self, traj):
        """Makes some plots and stores them into subfolders"""
        print_folder = self._make_folder(traj)

        # If we use BRIAN's own raster_plot functionality we
        # need to sue the SpikeMonitor directly
        raster_plot(self.spike_monitor, newfigure=True, xlabel='t', ylabel='Exc. Neurons',
                    title='Spike Raster Plot')

        filename=os.path.join(print_folder,'spike.png')

        print 'Current plot: %s ' % filename
        plt.savefig(filename)
        plt.close()

        fig=plt.figure()
        self._plot_result(traj, 'monitors.V')
        filename=os.path.join(print_folder,'V.png')
        print 'Current plot: %s ' % filename
        fig.savefig(filename)
        plt.close()

        plt.figure()
        self._plot_result(traj, 'monitors.I_syn_e')
        filename=os.path.join(print_folder,'I_syn_e.png')
        print 'Current plot: %s ' % filename
        plt.savefig(filename)
        plt.close()

        plt.figure()
        self._plot_result(traj, 'monitors.I_syn_i')
        filename=os.path.join(print_folder,'I_syn_i.png')
        print 'Current plot: %s ' % filename
        plt.savefig(filename)
        plt.close()

        if not traj.analysis.show_plots:
            plt.close('all')
        else:
            plt.show()
Esempio n. 7
0
def main():

    fs = 100e3
    cf = 1e3
    tmax = 50e-3

    sound = wv.ramped_tone(
        fs=fs,
        freq=cf,
        duration=tmax,
        pad=30e-3,
        dbspl=50,
    )

    anf_trains = cochlea.run_zilany2014(
        sound=sound,
        fs=fs,
        cf=cf,
        anf_num=(300, 0, 0),
        seed=0,
        species='cat',
    )

    anfs = cochlea.make_brian_group(anf_trains)

    print(anfs)

    brainstem = make_brainstem_group(100)

    print(brainstem)

    monitor = brian.SpikeMonitor(brainstem)

    net = brian.Network([brainstem, monitor])
    net.run(tmax * second)

    brian.raster_plot(monitor)
    brian.show()
Esempio n. 8
0
def plot_rast_V_I_contraster(net, nrn=-2, xlim = [16500,17500]):
    """ 
        For plotting Fig 2
        plots a ratser of a reduced PS,
        conductances, currents, voltage of a neuron in a single figure

        puts an extra raster of a continuous sequence replay
        
    """
    from figure_subplots import draw_evoked_rasta2
    tres = .1   # time resolution for conductance

    figure = pyplot.figure(figsize=(18., 12.))
    gs = gridspec.GridSpec(25, 12)
    gs.update(left=.04, wspace=.0, hspace=.0)
    ylab_xposit = xlim[0] - 80

    ################################################################
    # raster for continious ASS at the bottom of the figure
    x0 = 20500
    x1 = 21500

    xticks=numpy.arange(x0, x1+1, 200)
    xticks_lab = numpy.arange(0, x1-x0+1, 200)

    sub_rast2 = pyplot.subplot(gs[19:25, 1:12])

    fname = 'contin_ass_pf0.06pr0.06.npz'
    draw_evoked_rasta2(fname, '', x0=x0, x1=x1)

    yticks=[0, 100, 200, 300, 400, 500]
    yticks=[0, 2500, 5000]
    sub_rast2.set_yticks(yticks)
    sub_rast2.set_yticklabels(yticks, size=20)
    sub_rast2.xaxis.set_tick_params(width=1, length=5)
    sub_rast2.yaxis.set_tick_params(width=1, length=5)
    #sub_rast.set_ylabel('Neurons',size=18)
    sub_rast2.text(x0-80, 3750, 'Neuron #', rotation = 'vertical', size=20)
    sub_rast2.set_xticks(xticks)
    sub_rast2.set_xticklabels(xticks_lab, size=20)
    pyplot.xlabel('Time [ms]', size=20)
    sub_rast2.text(xticks[0]-130, 5000., 'D', size=28, color='black')


    ################################################################
    xticks=numpy.arange(xlim[0], xlim[1]+1, 200)
    xticks_lab = numpy.arange(0, xlim[1]-xlim[0]+1, 200)
    cxlim = [xlim[0]/tres, xlim[1]/tres] #lim for the vectors(with tres in mind)

    ################################################################
    sub_rast = pyplot.subplot(gs[12:18, 1:12])
    m = bb.Monitor()
    m.source = []
    frac = 1.
    m.spikes = calc_spikes.get_spike_times_ps(net, 0, frac)
    bb.raster_plot(m, color=(0, 0, 0))#, #showgrouplines=True,
                    #spacebetweengroups=0.1, grouplinecol=(0.5, 0.5, 0.5))

    # spikes of measured neuron in red o.,
    # now it works automatically just with neurons from the last group
    nrn_spikes_all = net.mon_spike_e[net.nrn_meas_e[nrn]]
    nrn_spikes = nrn_spikes_all[numpy.logical_and(
            nrn_spikes_all >= xlim[0]/1000., nrn_spikes_all <= xlim[1]/1000.)]

    raster_sp_x = nrn_spikes*1000.
    raster_sp_y = (net.nrn_meas_e[nrn])*numpy.ones(len(nrn_spikes))

    pyplot.plot(raster_sp_x, raster_sp_y, 'o', color='red')
    pyplot.plot(raster_sp_x, raster_sp_y, '.', color='red')

    sub_rast.set_xlim(xlim)
    sub_rast.set_xticks(xticks)
    sub_rast.set_xticklabels([])
    sub_rast.set_xlabel('')

    # put some lines between groups
    for i in range(net.n_ass):
        sub_rast.plot(numpy.arange(xlim[0],xlim[1]),
                        (i+1)*frac*net.s_ass*numpy.ones(1000),'gray')

    # put an arrow for the neuron we record from
    #pyplot.text(xlim[0]+500-18, -60, '$\Uparrow$', size=25)
    yticks=[0, 100, 200, 300, 400, 500]
    yticks=[0, 2500, 5000]
    sub_rast.set_ylabel('', size=20)
    sub_rast.set_yticks(yticks)
    sub_rast.set_yticklabels(yticks, size=20)
    sub_rast.xaxis.set_tick_params(width=1, length=5)
    sub_rast.yaxis.set_tick_params(width=1, length=5)
    sub_rast.text(ylab_xposit, 3750, 'Neuron #', rotation = 'vertical', size=20)
    #sub_rast.set_xticklabels(xticks_lab, size=20)
    #pyplot.xlabel('Time [ms]', size=20)
    sub_rast.text(xticks[0]-130, 5000., 'C', size=28, color='black')

    ################################################################
    #sub_curr = pyplot.subplot(gs[9:13,0:12])
    sub_curr = pyplot.subplot(gs[0:5,1:12])
    yticks=[-200,0,200,400]
    curr_e= net.mon_ecurr_e[net.nrn_meas_e[nrn]]/pA+200
    curr_i= net.mon_icurr_e[net.nrn_meas_e[nrn]]/pA
    volt_e= net.mon_volt_e[net.nrn_meas_e[nrn]]/mV # measured voltage here
    curr_leak = 10.*nS*(-60.-volt_e)*mV/pA
    curr_maxe=(curr_e[cxlim[0]:cxlim[1]]).max()
    curr_maxi=(curr_i[cxlim[0]:cxlim[1]]).max()
    curr_mine=(curr_e[cxlim[0]:cxlim[1]]).min()
    curr_mini=(curr_i[cxlim[0]:cxlim[1]]).min()
    pyplot.plot(net.mon_ecurr_e.times/ms, curr_e,'r')
    pyplot.plot(net.mon_ecurr_e.times/ms, curr_i,'b')
    pyplot.plot(net.mon_ecurr_e.times/ms, curr_e+curr_i+curr_leak,'black')
    ylim=[1.2*min(curr_mine,curr_mini),1.2*max(curr_maxe,curr_maxi)]
    remove_spines(sub_curr,xlim=xlim,ylim=ylim,xticks=[],yticks=yticks,
                    #ylabel='I [pA]',legend= ['$I_{exc}$','$I_{inh}$'])
                    ylabel='I [pA]',legend= [])
    sub_curr.set_ylabel('',size=20)
    sub_curr.text(ylab_xposit, 370, 'Current [pA]',
                    rotation = 'vertical', size=20)
    sub_curr.set_yticks(yticks)
    sub_curr.set_yticklabels(yticks,size=20)
    sub_curr.yaxis.set_tick_params(width=1, length=5)
    #sub_curr.text(xticks[-1]-00,-200.,'$I_{inh}$',color='red',size=18)
    #sub_curr.text(xticks[-1]-00,50.,'$I_{tot}$',color='black',size=18)
    #sub_curr.text(xticks[-1]-00,250.,'$I_{exc}$',color='green',size=18)
    sub_curr.text(xticks[-2]-5, -320., 'Inhibition', size=20,
                                        color='b', zorder=3)
    sub_curr.text(xticks[-2]-5, 80., 'Total', size=20, zorder=3)
    sub_curr.text(xticks[-2]-5, 300., 'Excitation', size=20,
                                        color='r', zorder=3)
    sub_curr.text(xticks[0]-130, 500., 'A', size=28, color='black')

    ################################################################
    #raster_sp_x = nrn_spikes*1000 
    #raster_sp_y = (491+nrn)*numpy.ones(len(nrn_spikes))
    #sub_volt = pyplot.subplot(gs[16:20,0:12])
    sub_volt = pyplot.subplot(gs[6:11,1:12])
    for i,v in enumerate(volt_e):
        if v<-59 and volt_e[i-1]>-55:
            #pyplot.vlines((i-1)*tres,-50,-40)
            volt_e[i-1] = -40
            #volt_e[i] = -40
            #volt_e[i+1] = -40
            #print i
    pyplot.plot(net.mon_volt_e.times/ms, volt_e,'black')

    volt_sp_x = nrn_spikes*1000 
    volt_sp_y = -40*numpy.ones(len(volt_sp_x)) 
    
    pyplot.plot(volt_sp_x,volt_sp_y,'o',color='red')
    
    #for i,v in enumerate(volt_e):
        #if volt_e[i-1]>-45:
            #pyplot.plot((i-1)*tres,-40,'o',color='red')

    ylim=[-62,-39]
    yticks=[-60,-50,-40]
    #remove_spines(sub_volt,xlim=xlim,ylim=ylim,
                #xticks=xticks,yticks=yticks,
                #ylabel='V [mV]',legend= [],keepx=True)
    remove_spines(sub_volt,xlim=xlim,ylim=ylim,
                xticks=[],yticks=yticks,
                ylabel='V [mV]',legend= [])
    #sub_volt.set_xticklabels(xticks_lab, size=18)
    #pyplot.xlabel('Time [ms]',size=18)
    sub_volt.set_ylabel('',size=20)
    sub_volt.text(ylab_xposit,-40,'Voltage [mV]',rotation = 'vertical',size=20)
    sub_volt.set_yticks(yticks)
    sub_volt.set_yticklabels(yticks,size=20)
    sub_volt.yaxis.set_tick_params(width=1,length=5)

    sub_volt.plot(numpy.arange(xlim[0],xlim[1]),
                                -50.*numpy.ones(1000),'-.',color = 'gray')
    
    sub_volt.text(xticks[0]-130,-40.,'B',size=28,color='black')
    #sub_volt.text(xticks[-1]-00,-55.,'$V_{m}$',color='black',size=18)

    # draw vertical lines between spikes in raster and voltage trace

    linii_nekvi=[]
    curr_sp_y = 400.
    for i in range(len(volt_sp_x)):
        #linii_nekvi.append(get_straightline(figure,sub_rast,sub_volt,
        #        raster_sp_x[i],raster_sp_y[i],volt_sp_x[i],volt_sp_y[i]))
        linii_nekvi.append(get_straightline(figure,sub_rast,sub_curr,
                raster_sp_x[i],raster_sp_y[i],volt_sp_x[i],curr_sp_y))
    '''
    transFigure = figure.transFigure.inverted()
    c1x = raster_sp_x[0]
    c1y = raster_sp_y[0]
    c2x = volt_sp_x[0]
    c2y = volt_sp_y[0]
    coord1 = transFigure.transform(sub_rast.transData.transform([c1x,c1y]))
    coord2 = transFigure.transform(sub_volt.transData.transform([c2x,c2y]))
    line = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]),
                        transform=figure.transFigure,color='gray',alpha=.9)

    print c1x,c1y,c2x,c2y
    print coord1, coord2
    '''
    figure.lines = linii_nekvi

    loc='tfigs/rcv6/'
    prefix = 'rccv_'
    fname = 'prf' + str(net.pr_ee) + str(net.pf_ee) + '_' + \
            str(-nrn) + '_int' + str(xlim[0])
    figure.savefig(loc+prefix+fname+'.eps', format='eps')
    figure.savefig(loc+prefix+fname+'.png', format='png')
    figure.savefig(loc+prefix+fname+'.pdf', format='pdf')

    #pyplot.close()
    pyplot.show()
Esempio n. 9
0
    def __init__(self,
                 n_input=784,
                 conv_size=16,
                 conv_stride=4,
                 conv_features=50,
                 connectivity='all',
                 weight_dependence=False,
                 post_pre=True,
                 weight_sharing=False,
                 lattice_structure='4',
                 random_lattice_prob=0.0,
                 random_inhibition_prob=0.0):
        '''
		Constructor for the spiking convolutional neural network model.

		n_input: (flattened) dimensionality of the input data
		conv_size: side length of convolution windows used
		conv_stride: stride (horizontal and vertical) of convolution windows used
		conv_features: number of convolution features (or patches) used
		connectivity: connection style between patches; one of 'none', 'pairs', all'; more to be added
		weight_dependence: whether to use weight STDP with weight dependence
		post_pre: whether to use STDP with both post- and pre-synpatic traces
		weight_sharing: whether to impose that all neurons within a convolution patch share a common set of weights
		lattice_structure: lattice connectivity pattern between patches; one of 'none', '4', '8', and 'all'
		random_lattice_prob: probability of adding random additional lattice connections between patches
		random_inhibition_prob: probability of adding random additional inhibition edges from the inhibitory to excitatory population
		'''
        self.n_input, self.conv_size, self.conv_stride, self.conv_features, self.connectivity, self.weight_dependence, \
         self.post_pre, self.weight_sharing, self.lattice_structure, self.random_lattice_prob, self.random_inhibition_prob = \
         n_input, conv_size, conv_stride, conv_features, connectivity, weight_dependence, post_pre, weight_sharing, lattice_structure, \
         random_lattice_prob, random_inhibition_prob

        # number of inputs to the network
        self.n_input_sqrt = int(math.sqrt(self.n_input))
        self.n_excitatory_patch = (
            (self.n_input_sqrt - self.conv_size) / self.conv_stride + 1)**2
        self.n_excitatory = self.n_excitatory_patch * self.conv_features
        self.n_excitatory_patch_sqrt = int(math.sqrt(self.n_excitatory_patch))
        self.n_inhibitory_patch = self.n_excitatory_patch
        self.n_inhibitory = self.n_excitatory
        self.conv_features_sqrt = int(math.ceil(math.sqrt(self.conv_features)))

        # time (in seconds) per data example presentation and rest period in between
        self.single_example_time = 0.35 * b.second
        self.resting_time = 0.15 * b.second

        # set update intervals
        self.update_interval = 100
        self.weight_update_interval = 10
        self.print_progress_interval = 10

        # rest potential parameters, reset potential parameters, threshold potential parameters, and refractory periods
        v_rest_e, v_rest_i = -65. * b.mV, -60. * b.mV
        v_reset_e, v_reset_i = -65. * b.mV, -45. * b.mV
        v_thresh_e, v_thresh_i = -52. * b.mV, -40. * b.mV
        refrac_e, refrac_i = 5. * b.ms, 2. * b.ms

        # time constants, learning rates, max weights, weight dependence, etc.
        tc_pre_ee, tc_post_ee = 20 * b.ms, 20 * b.ms
        nu_ee_pre, nu_ee_post = 0.0001, 0.01
        exp_ee_post = exp_ee_pre = 0.2
        w_mu_pre, w_mu_post = 0.2, 0.2

        # parameters for neuron equations
        tc_theta = 1e7 * b.ms
        theta_plus = 0.05 * b.mV
        scr_e = 'v = v_reset_e; theta += theta_plus; timer = 0*ms'
        offset = 20.0 * b.mV
        v_thresh_e = '(v>(theta - offset + ' + str(
            v_thresh_e) + ')) * (timer>refrac_e)'

        # equations for neurons
        neuron_eqs_e = '''
				dv / dt = ((v_rest_e - v) + (I_synE + I_synI) / nS) / (100 * ms)  : volt
				I_synE = ge * nS * - v  : amp
				I_synI = gi * nS * (-100. * mV - v)  : amp
				dge / dt = -ge / (1.0*ms)  : 1
				dgi / dt = -gi / (2.0*ms)  : 1
				dtheta / dt = -theta / (tc_theta)  : volt
				dtimer / dt = 100.0  : ms
			'''

        neuron_eqs_i = '''
				dv/dt = ((v_rest_i - v) + (I_synE + I_synI) / nS) / (10*ms)  : volt
				I_synE = ge * nS *         -v                           : amp
				I_synI = gi * nS * (-85.*mV-v)                          : amp
				dge/dt = -ge/(1.0*ms)                                   : 1
				dgi/dt = -gi/(2.0*ms)                                  : 1
			'''

        # STDP synaptic traces
        eqs_stdp_ee = '''
				dpre / dt = -pre / tc_pre_ee : 1.0
				dpost / dt = -post / tc_post_ee : 1.0
			'''

        # dictionaries for weights and delays
        self.weight, self.delay = {}, {}

        # setting weight, delay, and intensity parameters
        self.weight['ee_input'] = (conv_size**2) * 0.175
        self.delay['ee_input'] = (0 * b.ms, 10 * b.ms)
        self.delay['ei_input'] = (0 * b.ms, 5 * b.ms)
        self.input_intensity = self.start_input_intensity = 2.0
        self.wmax_ee = 1.0

        # populations, connections, saved connections, etc.
        self.input_population_names = ['X']
        self.population_names = ['A']
        self.input_connection_names = ['XA']
        self.save_connections = ['XeAe', 'AeAe']
        self.input_connection_names = ['ee_input']
        self.recurrent_connection_names = ['ei', 'ie', 'ee']

        # setting STDP update rule
        if weight_dependence:
            if post_pre:
                eqs_stdp_pre_ee = 'pre = 1.; w -= nu_ee_pre * post * w ** exp_ee_pre'
                eqs_stdp_post_ee = 'w += nu_ee_post * pre * (wmax_ee - w) ** exp_ee_post; post = 1.'

            else:
                eqs_stdp_pre_ee = 'pre = 1.'
                eqs_stdp_post_ee = 'w += nu_ee_post * pre * (wmax_ee - w) ** exp_ee_post; post = 1.'

        else:
            if post_pre:
                eqs_stdp_pre_ee = 'pre = 1.; w -= nu_ee_pre * post'
                eqs_stdp_post_ee = 'w += nu_ee_post * pre; post = 1.'

            else:
                eqs_stdp_pre_ee = 'pre = 1.'
                eqs_stdp_post_ee = 'w += nu_ee_post * pre; post = 1.'

        print '\n'

        # for filesaving purposes
        stdp_input = ''
        if self.weight_dependence:
            stdp_input += 'weight_dependence_'
        else:
            stdp_input += 'no_weight_dependence_'
        if self.post_pre:
            stdp_input += 'post_pre'
        else:
            stdp_input += 'no_post_pre'
        if self.weight_sharing:
            use_weight_sharing = 'weight_sharing'
        else:
            use_weight_sharing = 'no_weight_sharing'

        # set ending of filename saves
        self.ending = self.connectivity + '_' + str(self.conv_size) + '_' + str(self.conv_stride) + '_' + str(self.conv_features) + \
             '_' + str(self.n_excitatory_patch) + '_' + stdp_input + '_' + \
             use_weight_sharing + '_' + str(self.lattice_structure) + '_' + str(self.random_lattice_prob) + \
             '_' + str(self.random_inhibition_prob)

        self.fig_num = 1

        # creating dictionaries for various objects
        self.neuron_groups, self.input_groups, self.connections, self.input_connections, self.stdp_methods, self.rate_monitors, \
         self.spike_monitors, self.spike_counters, self.output_numbers = {}, {}, {}, {}, {}, {}, {}, {}, {}

        # creating convolution locations inside the input image
        self.convolution_locations = {}
        for n in xrange(self.n_excitatory_patch):
            self.convolution_locations[n] = [ ((n % self.n_excitatory_patch_sqrt) * self.conv_stride + (n // self.n_excitatory_patch_sqrt) \
                      * self.n_input_sqrt * self.conv_stride) + (x * self.n_input_sqrt) + y \
                      for y in xrange(self.conv_size) for x in xrange(self.conv_size) ]

        # instantiating neuron spike / votes monitor
        self.result_monitor = np.zeros(
            (self.update_interval, self.conv_features,
             self.n_excitatory_patch))

        # creating overarching neuron populations
        self.neuron_groups['e'] = b.NeuronGroup(self.n_excitatory, neuron_eqs_e, threshold=v_thresh_e, \
                     refractory=refrac_e, reset=scr_e, compile=True, freeze=True)
        self.neuron_groups['i'] = b.NeuronGroup(self.n_inhibitory, neuron_eqs_i, threshold=v_thresh_i, \
                     refractory=refrac_i, reset=v_reset_i, compile=True, freeze=True)

        # create neuron subpopulations
        for name in self.population_names:
            print '...creating neuron group:', name

            # get a subgroup of size 'n_e' from all exc
            self.neuron_groups[name + 'e'] = self.neuron_groups['e'].subgroup(
                self.conv_features * self.n_excitatory_patch)
            # get a subgroup of size 'n_i' from the inhibitory layer
            self.neuron_groups[name + 'i'] = self.neuron_groups['i'].subgroup(
                self.conv_features * self.n_excitatory_patch)

            # start the membrane potentials of these groups 40mV below their resting potentials
            self.neuron_groups[name + 'e'].v = v_rest_e - 40. * b.mV
            self.neuron_groups[name + 'i'].v = v_rest_i - 40. * b.mV

        print '...creating recurrent connections'

        for name in self.population_names:
            # set the adaptive additive threshold parameter at 20mV
            self.neuron_groups['e'].theta = np.ones(
                (self.n_excitatory)) * 20.0 * b.mV

            for connection_type in self.recurrent_connection_names:
                if connection_type == 'ei':
                    # create connection name (composed of population and connection types)
                    connection_name = name + connection_type[
                        0] + name + connection_type[1]
                    # create a connection from the first group in conn_name with the second group
                    self.connections[connection_name] = b.Connection(self.neuron_groups[connection_name[0:2]], \
                            self.neuron_groups[connection_name[2:4]], structure='sparse', state='g' + conn_type[0])
                    # instantiate the created connection
                    for feature in xrange(self.conv_features):
                        for n in xrange(self.n_excitatory_patch):
                            self.connections[conn_name][feature * self.n_excitatory_patch + n, \
                                    feature * self.n_excitatory_patch + n] = 10.4

                elif connection_type == 'ie':
                    # create connection name (composed of population and connection types)
                    connection_name = name + connection_type[
                        0] + name + connection_type[1]
                    # create a connection from the first group in conn_name with the second group
                    self.connections[connection_name] = b.Connection(self.neuron_groups[connection_name[0:2]], \
                            self.neuron_groups[connection_name[2:4]], structure='sparse', state='g' + conn_type[0])
                    # instantiate the created connection
                    for feature in xrange(self.conv_features):
                        for other_feature in xrange(self.conv_features):
                            if feature != other_feature:
                                for n in xrange(self.n_excitatory_patch):
                                    self.connections[connection_name][feature * self.n_excitatory_patch + n, \
                                          other_feature * self.n_excitatory_patch + n] = 17.4

                    # adding random inhibitory connections as specified
                    if self.random_inhibition_prob != 0.0:
                        for feature in xrange(self.conv_features):
                            for other_feature in xrange(self.conv_features):
                                for n_this in xrange(self.n_excitatory_patch):
                                    for n_other in xrange(
                                            self.n_excitatory_patch):
                                        if n_this != n_other:
                                            if b.random(
                                            ) < self.random_inhibition_prob:
                                                self.connections[connection_name][feature * self.n_excitatory_patch + n_this, \
                                                  other_feature * self.n_excitatory_patch + n_other] = 17.4

                elif connection_type == 'ee':
                    # create connection name (composed of population and connection types)
                    connection_name = name + connection_type[
                        0] + name + connection_type[1]
                    # create a connection from the first group in conn_name with the second group
                    self.connections[connection_name] = b.Connection(self.neuron_groups[connection_name[0:2]], \
                       self.neuron_groups[connection_name[2:4]], structure='sparse', state='g' + connection_type[0])
                    # instantiate the created connection
                    if self.connectivity == 'all':
                        for feature in xrange(self.conv_features):
                            for other_feature in xrange(self.conv_features):
                                if feature != other_feature:
                                    for this_n in xrange(
                                            self.n_excitatory_patch):
                                        for other_n in xrange(
                                                self.n_excitatory_patch):
                                            if is_lattice_connection(
                                                    self.
                                                    n_excitatory_patch_sqrt,
                                                    this_n, other_n):
                                                self.connections[connection_name][feature * self.n_excitatory_patch + this_n, \
                                                  other_feature * self.n_excitatory_patch + other_n] = \
                                                    (b.random() + 0.01) * 0.3

                    elif self.connectivity == 'pairs':
                        for feature in xrange(self.conv_features):
                            if feature % 2 == 0:
                                for this_n in xrange(self.n_excitatory_patch):
                                    for other_n in xrange(
                                            self.n_excitatory_patch):
                                        if is_lattice_connection(
                                                self.n_excitatory_patch_sqrt,
                                                this_n, other_n):
                                            self.connections[connection_name][feature * self.n_excitatory_patch + this_n, \
                                              (feature + 1) * self.n_excitatory_patch + other_n] = (b.random() + 0.01) * 0.3
                            elif feature % 2 == 1:
                                for this_n in xrange(self.n_excitatory_patch):
                                    for other_n in xrange(
                                            self.n_excitatory_patch):
                                        if is_lattice_connection(
                                                self.n_excitatory_patch_patch,
                                                this_n, other_n):
                                            self.connections[connection_name][feature * self.n_excitatory_patch + this_n, \
                                              (feature - 1) * self.n_excitatory_patch + other_n] = (b.random() + 0.01) * 0.3

                    elif connectivity == 'linear':
                        for feature in xrange(self.conv_features):
                            if feature != self.conv_features - 1:
                                for this_n in xrange(self.n_excitatory_patch):
                                    for other_n in xrange(
                                            self.n_excitatory_patch):
                                        if is_lattice_connection(
                                                self.n_excitatory_patch_sqrt,
                                                this_n, other_n):
                                            self.connections[connection_name][feature * self.n_excitatory_patch + this_n, \
                                              (feature + 1) * self.n_excitatory_patch + other_n] = \
                                                 (b.random() + 0.01) * 0.3
                            if feature != 0:
                                for this_n in xrange(self.n_excitatory_patch):
                                    for other_n in xrange(
                                            self.n_excitatory_patch):
                                        if is_lattice_connection(
                                                self.n_excitatory_patch_sqrt,
                                                this_n, other_n):
                                            self.connections[connection_name][feature * self.n_excitatory_patch + this_n, \
                                              (feature - 1) * self.n_excitatory_patch + other_n] = \
                                                 (b.random() + 0.01) * 0.3

                    elif self.connectivity == 'none':
                        pass

            # if STDP from excitatory -> excitatory is on and this connection is excitatory -> excitatory
            if 'ee' in self.recurrent_conn_names:
                self.stdp_methods[name + 'e' + name + 'e'] = b.STDP(self.connections[name + 'e' + name + 'e'], \
                            eqs=eqs_stdp_ee, pre=eqs_stdp_pre_ee, \
                            post=eqs_stdp_post_ee, wmin=0., wmax=self.wmax_ee)

            print '...creating monitors for:', name

            # spike rate monitors for excitatory and inhibitory neuron populations
            self.rate_monitors[name + 'e'] = b.PopulationRateMonitor(self.neuron_groups[name + 'e'], \
                      bin=(self.single_example_time + self.resting_time) / b.second)
            self.rate_monitors[name + 'i'] = b.PopulationRateMonitor(self.neuron_groups[name + 'i'], \
                      bin=(self.single_example_time + self.resting_time) / b.second)
            self.spike_counters[name + 'e'] = b.SpikeCounter(
                self.neuron_groups[name + 'e'])

            # record neuron population spikes
            self.spike_monitors[name + 'e'] = b.SpikeMonitor(
                self.neuron_groups[name + 'e'])
            self.spike_monitors[name + 'i'] = b.SpikeMonitor(
                self.neuron_groups[name + 'i'])

        if do_plot:
            b.figure(self.fig_num)
            fig_num += 1
            b.ion()
            b.subplot(211)
            b.raster_plot(self.spike_monitors['Ae'],
                          refresh=1000 * b.ms,
                          showlast=1000 * b.ms)
            b.subplot(212)
            b.raster_plot(self.spike_monitors['Ai'],
                          refresh=1000 * b.ms,
                          showlast=1000 * b.ms)

        # specifying locations of lattice connections
        self.lattice_locations = {}
        if self.connectivity == 'all':
            for this_n in xrange(self.conv_features * self.n_excitatory_patch):
                self.lattice_locations[this_n] = [ other_n for other_n in xrange(self.conv_features * self.n_excitatory_patch) \
                        if is_lattice_connection(self.n_excitatory_patch_sqrt, \
                        this_n % self.n_excitatory_patch, other_n % self.n_excitatory_patch) ]
        elif self.connectivity == 'pairs':
            for this_n in xrange(self.conv_features * self.n_excitatory_patch):
                self.lattice_locations[this_n] = []
                for other_n in xrange(self.conv_features *
                                      self.n_excitatory_patch):
                    if this_n // self.n_excitatory_patch % 2 == 0:
                        if is_lattice_connection(self.n_excitatory_patch_sqrt, this_n % self.n_excitatory_patch, \
                               other_n % self.n_excitatory_patch) and \
                               other_n // self.n_excitatory_patch == this_n // self.n_excitatory_patch + 1:
                            self.lattice_locations[this_n].append(other_n)
                    elif this_n // self.n_excitatory_patch % 2 == 1:
                        if is_lattice_connection(self.n_excitatory_patch_sqrt, this_n % self.n_excitatory_patch, \
                               other_n % self.n_excitatory_patch) and \
                               other_n // self.n_excitatory_patch == this_n // self.n_excitatory_patch - 1:
                            self.lattice_locations[this_n].append(other_n)
        elif self.connectivity == 'linear':
            for this_n in xrange(self.conv_features * self.n_excitatory_patch):
                self.lattice_locations[this_n] = []
                for other_n in xrange(conv_features * self.n_excitatory_patch):
                    if this_n // self.n_excitatory_patch != self.conv_features - 1:
                        if is_lattice_connection(self.n_excitatory_patch_sqrt, this_n % self.n_excitatory_patch, \
                               other_n % self.n_excitatory_patch) and \
                               other_n // self.n_excitatory_patch == this_n // self.n_excitatory_patch + 1:
                            self.lattice_locations[this_n].append(other_n)
                    elif this_n // self.n_excitatory_patch != 0:
                        if is_lattice_connection(self.n_excitatory_patch_sqrt, this_n % self.n_excitatory_patch, \
                               other_n % self.n_excitatory_patch) and \
                               other_n // self.n_excitatory_patch == this_n // self.n_excitatory_patch - 1:
                            self.lattice_locations[this_n].append(other_n)

        # setting up parameters for weight normalization between patches
        num_lattice_connections = sum(
            [len(value) for value in lattice_locations.values()])
        self.weight['ee_recurr'] = (num_lattice_connections /
                                    self.conv_features) * 0.15

        # creating Poission spike train from input image (784 vector, 28x28 image)
        for name in self.input_population_names:
            self.input_groups[name + 'e'] = b.PoissonGroup(self.n_input, 0)
            self.rate_monitors[name + 'e'] = b.PopulationRateMonitor(self.input_groups[name + 'e'], \
                       bin=(self.single_example_time + self.resting_time) / b.second)

        # creating connections from input Poisson spike train to convolution patch populations
        for name in self.input_connection_names:
            print '\n...creating connections between', name[0], 'and', name[1]

            # for each of the input connection types (in this case, excitatory -> excitatory)
            for connection_type in self.input_conn_names:
                # saved connection name
                connection_name = name[0] + connection_type[0] + name[
                    1] + connection_type[1]

                # create connections from the windows of the input group to the neuron population
                self.input_connections[connection_name] = b.Connection(self.input_groups['Xe'], \
                    self.neuron_groups[name[1] + connection_type[1]], structure='sparse', \
                    state='g' + connection_type[0], delay=True, max_delay=self.delay[connection_type][1])

                for feature in xrange(self.conv_features):
                    for n in xrange(self.n_excitatory_patch):
                        for idx in xrange(self.conv_size**2):
                            self.input_connections[connection_name][self.convolution_locations[n][idx], \
                                 feature * self.n_excitatory_patch + n] = (b.random() + 0.01) * 0.3

            # if excitatory -> excitatory STDP is specified, add it here (input to excitatory populations)
            print '...creating STDP for connection', name

            # STDP connection name
            connection_name = name[0] + connection_type[0] + name[
                1] + connection_type[1]
            # create the STDP object
            self.stdp_methods[connection_name] = b.STDP(self.input_connections[connection_name], \
              eqs=eqs_stdp_ee, pre=eqs_stdp_pre_ee, post=eqs_stdp_post_ee, wmin=0., wmax=self.wmax_ee)

        print '\n'
def build_network():
    global fig_num

    neuron_groups['e'] = b.NeuronGroup(n_e_total,
                                       neuron_eqs_e,
                                       threshold=v_thresh_e,
                                       refractory=refrac_e,
                                       reset=scr_e,
                                       compile=True,
                                       freeze=True)
    neuron_groups['i'] = b.NeuronGroup(n_e_total,
                                       neuron_eqs_i,
                                       threshold=v_thresh_i,
                                       refractory=refrac_i,
                                       reset=v_reset_i,
                                       compile=True,
                                       freeze=True)

    for name in ['A']:
        print '...Creating neuron group:', name

        # get a subgroup of size 'n_e' from all exc
        neuron_groups[name + 'e'] = neuron_groups['e'].subgroup(conv_features *
                                                                n_e)
        # get a subgroup of size 'n_i' from the inhibitory layer
        neuron_groups[name + 'i'] = neuron_groups['i'].subgroup(conv_features *
                                                                n_e)

        # start the membrane potentials of these groups 40mV below their resting potentials
        neuron_groups[name + 'e'].v = v_rest_e - 40. * b.mV
        neuron_groups[name + 'i'].v = v_rest_i - 40. * b.mV

    print '...Creating recurrent connections'

    for name in ['A']:
        neuron_groups['e'].theta = np.load(
            os.path.join(best_weights_dir,
                         '_'.join(['theta_A', ending + '_best.npy'])))

        for conn_type in ['ei', 'ie']:
            if conn_type == 'ei':
                # create connection name (composed of population and connection types)
                conn_name = name + conn_type[0] + name + conn_type[1]
                # create a connection from the first group in conn_name with the second group
                connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], \
                    neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0])
                # instantiate the created connection
                for feature in xrange(conv_features):
                    for n in xrange(n_e):
                        connections[conn_name][feature * n_e + n,
                                               feature * n_e + n] = 10.4

            elif conn_type == 'ie' and not remove_inhibition:
                # create connection name (composed of population and connection types)
                conn_name = name + conn_type[0] + name + conn_type[1]
                # create a connection from the first group in conn_name with the second group
                connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], \
                    neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0])
                # define the actual synaptic connections and strengths
                for feature in xrange(conv_features):
                    if inhib_scheme in ['far', 'strengthen']:
                        for other_feature in set(range(conv_features)) - set(
                                neighbor_mapping[feature]):
                            if inhib_scheme == 'far':
                                for n in xrange(n_e):
                                    connections[conn_name][feature * n_e + n,
                                                           other_feature *
                                                           n_e + n] = 17.4

                            elif inhib_scheme == 'strengthen':
                                if n_e == 1:
                                    x, y = feature // np.sqrt(
                                        n_e_total), feature % np.sqrt(
                                            n_e_total)
                                    x_, y_ = other_feature // np.sqrt(
                                        n_e_total), other_feature % np.sqrt(
                                            n_e_total)
                                else:
                                    x, y = feature // np.sqrt(
                                        conv_features), feature % np.sqrt(
                                            conv_features)
                                    x_, y_ = other_feature // np.sqrt(
                                        conv_features
                                    ), other_feature % np.sqrt(conv_features)

                                for n in xrange(n_e):
                                    connections[conn_name][feature * n_e + n, other_feature * n_e + n] = \
                                        min(17.4, inhib_const * np.sqrt(euclidean([x, y], [x_, y_])))

                    elif inhib_scheme == 'increasing':
                        for other_feature in xrange(conv_features):
                            if n_e == 1:
                                x, y = feature // np.sqrt(
                                    n_e_total), feature % np.sqrt(n_e_total)
                                x_, y_ = other_feature // np.sqrt(
                                    n_e_total), other_feature % np.sqrt(
                                        n_e_total)
                            else:
                                x, y = feature // np.sqrt(
                                    conv_features), feature % np.sqrt(
                                        conv_features)
                                x_, y_ = other_feature // np.sqrt(
                                    conv_features), other_feature % np.sqrt(
                                        conv_features)

                            if feature != other_feature:
                                for n in xrange(n_e):
                                    connections[conn_name][feature * n_e + n, other_feature * n_e + n] = \
                                        min(17.4, inhib_const * np.sqrt(euclidean([x, y], [x_, y_])))

                    else:
                        raise Exception(
                            'Expecting one of "far", "increasing", or "strengthen" for argument "inhib_scheme".'
                        )

        # spike rate monitors for excitatory and inhibitory neuron populations
        rate_monitors[name + 'e'] = b.PopulationRateMonitor(
            neuron_groups[name + 'e'],
            bin=(single_example_time + resting_time) / b.second)
        rate_monitors[name + 'i'] = b.PopulationRateMonitor(
            neuron_groups[name + 'i'],
            bin=(single_example_time + resting_time) / b.second)
        spike_counters[name + 'e'] = b.SpikeCounter(neuron_groups[name + 'e'])

        # record neuron population spikes if specified
        if record_spikes:
            spike_monitors[name + 'e'] = b.SpikeMonitor(neuron_groups[name +
                                                                      'e'])
            spike_monitors[name + 'i'] = b.SpikeMonitor(neuron_groups[name +
                                                                      'i'])

    if record_spikes and do_plot:
        if reset_state_vars:
            time_window = single_example_time * 1000
        else:
            time_window = (single_example_time + resting_time) * 1000

        b.figure(fig_num, figsize=(8, 6))
        b.ion()
        b.subplot(211)
        b.raster_plot(spike_monitors['Ae'],
                      refresh=time_window * b.ms,
                      showlast=time_window * b.ms,
                      title='Excitatory spikes per neuron')
        b.subplot(212)
        b.raster_plot(spike_monitors['Ai'],
                      refresh=time_window * b.ms,
                      showlast=time_window * b.ms,
                      title='Inhibitory spikes per neuron')
        b.tight_layout()

        fig_num += 1

    # creating Poission spike train from input image (784 vector, 28x28 image)
    for name in ['X']:
        input_groups[name + 'e'] = b.PoissonGroup(n_input, 0)
        rate_monitors[name + 'e'] = b.PopulationRateMonitor(
            input_groups[name + 'e'],
            bin=(single_example_time + resting_time) / b.second)

    # creating connections from input Poisson spike train to convolution patch populations
    for name in ['XA']:
        print '\n...Creating connections between', name[0], 'and', name[1]

        # for each of the input connection types (in this case, excitatory -> excitatory)
        for conn_type in ['ee_input']:
            # saved connection name
            conn_name = name[0] + conn_type[0] + name[1] + conn_type[1]

            # get weight matrix depending on training or test phase
            weight_matrix = np.load(
                os.path.join(best_weights_dir,
                             '_'.join([conn_name, ending + '_best.npy'])))

            # create connections from the windows of the input group to the neuron population
            input_connections[conn_name] = b.Connection(input_groups['Xe'], neuron_groups[name[1] + \
              conn_type[1]], structure='sparse', state='g' + conn_type[0], delay=True, max_delay=delay[conn_type][1])

            for feature in xrange(conv_features):
                for n in xrange(n_e):
                    for idx in xrange(conv_size**2):
                        input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = \
                             weight_matrix[convolution_locations[n][idx], feature * n_e + n]

            if do_plot:
                plot_2d_input_weights()
                fig_num += 1
Esempio n. 11
0
    rate_monitors[name + 'i'] = b.PopulationRateMonitor(
        neuron_groups[name + 'i'],
        bin=(single_example_time + resting_time) / b.second)
    spike_counters[name + 'e'] = b.SpikeCounter(neuron_groups[name + 'e'])

    if record_spikes:
        spike_monitors[name + 'e'] = b.SpikeMonitor(neuron_groups[name + 'e'])
        spike_monitors[name + 'i'] = b.SpikeMonitor(neuron_groups[name + 'i'])

if record_spikes:
    b.figure(fig_num)
    fig_num += 1
    b.ion()
    b.subplot(211)
    b.raster_plot(spike_monitors['Ae'],
                  refresh=1000 * b.ms,
                  showlast=1000 * b.ms)
    b.subplot(212)
    b.raster_plot(spike_monitors['Ai'],
                  refresh=1000 * b.ms,
                  showlast=1000 * b.ms)

#------------------------------------------------------------------------------
# create input population and connections from input populations
#------------------------------------------------------------------------------
pop_values = [0, 0, 0]
for i, name in enumerate(input_population_names):
    input_groups[name + 'e'] = b.PoissonGroup(n_input, 0)
    rate_monitors[name + 'e'] = b.PopulationRateMonitor(
        input_groups[name + 'e'],
        bin=(single_example_time + resting_time) / b.second)
Esempio n. 12
0
def plot_rast_V_I_disc(net, nrn=-2, xlim0=[19375,19625],
            xlim1 = [25625,26375], xlim2=[38625,36375], disc_only=False):
    """
        For plotting Fig 2
        - plots currents, voltage of a neuron in a single figure
        - plots a ratser of a PS with a discontinious x axis for
        showing off the dummpy plasticity
        
        xlimX : gives the limits of the x axes for the different plots
            X=0 : limits of pre-pff-boost
            X=1 : limits of discrete sequence sfter boost
            X=1 : limits of continuous sequence after boost

        puts an extra raster of a continuous sequence replay
    """
    from figure_subplots import draw_evoked_rasta2
    tres = .1   # time resolution for conductance
    subpzorder = 2

    figure = pyplot.figure(figsize=(18., 12.))
    grid_y = 26
    if disc_only:
        grid_y = 18
    gs = gridspec.GridSpec(grid_y, 13)
    gs.update(left=.04, wspace=.15, hspace=.0)

    ylab_xposit = xlim0[0] - 80

    # label size
    labsize = 20
    ################################################################
    dx_tick = 50
    xticks0 = numpy.arange(xlim0[0], xlim0[1]+1, dx_tick)
    xticks0_lab = numpy.arange(0, xlim0[1]-xlim0[0]+1, dx_tick)

    # first tick in second plot in plotting time
    shift_xtick = dx_tick - (xlim0[1]-xlim0[0]) % dx_tick 
    # last tick
    first_xtick= ((xlim0[1]-xlim0[0]+dx_tick)//dx_tick)*dx_tick
    last_xtick = first_xtick + xlim1[1]-xlim1[0] + 1
    xticks1 = numpy.arange(xlim1[0] + shift_xtick, xlim1[1]+1, dx_tick)
    xticks1_lab = numpy.arange(first_xtick, last_xtick, dx_tick)

    #xticks=numpy.arange(xlim[0], xlim[1]+1, 200)
    #xticks_lab = numpy.arange(0, xlim[1]-xlim[0]+1, 200)

    ################################################################
    sub_rast0 = pyplot.subplot(gs[12:18, 1:4], zorder = subpzorder )
    m = bb.Monitor()
    m.source = []
    frac = .1
    m.spikes = calc_spikes.get_spike_times_ps(net, 0, frac)
    bb.raster_plot(m, color=(0, 0, 0))
    #sub_rast0.plot(numpy.array(m.spikes)[:,0],numpy.array(m.spikes)[:,1], '.')

    # spikes of measured neuron in red o.,
    # now it works only with neurons from the last group
    nrn_spikes_all = net.mon_spike_e[net.nrn_meas_e[nrn]]
    nrn_spikes0 = nrn_spikes_all[numpy.logical_and(
        nrn_spikes_all >= xlim0[0]/1000., nrn_spikes_all <= xlim0[1]/1000.)]
    nrn_spikes1 = nrn_spikes_all[numpy.logical_and(
        nrn_spikes_all >= xlim1[0]/1000., nrn_spikes_all <= xlim1[1]/1000.)]

    raster_sp_x0 = nrn_spikes0*1000.
    raster_sp_y0 = (net.nrn_meas_e[nrn])*numpy.ones(len(nrn_spikes0))*frac

    pyplot.plot(raster_sp_x0, raster_sp_y0, 'o', color='red', zorder=3)
    pyplot.plot(raster_sp_x0, raster_sp_y0, '.', color='red', zorder=3)

    sub_rast0.set_xlim(xlim0)
    #sub_rast0.set_xticks([])
    #sub_rast0.set_xticklabels([])
    sub_rast0.set_xlabel('')

    # put some lines between groups
    for i in range(net.n_ass):
        sub_rast0.plot(numpy.arange(xlim0[0], xlim0[1]),
                    (i+1)*frac*net.s_ass*numpy.ones(xlim0[1]-xlim0[0]),
                    'gray', zorder=1)

    yticks=[0, 2500, 5000]
    yticks=[0, 250, 500]
    sub_rast0.set_ylabel('', size=20)
    sub_rast0.set_yticks(yticks)
    sub_rast0.set_yticklabels(yticks, size=labsize)
    sub_rast0.xaxis.set_tick_params(width=1, length=5)
    sub_rast0.yaxis.set_tick_params(width=1, length=5)

    sub_rast0.set_xlim(xlim0)
    sub_rast0.set_xticks(xticks0)
    sub_rast0.set_xticks([])
    sub_rast0.set_xticklabels(xticks0_lab, size=20)
    sub_rast0.set_xticklabels([], size=20)
    sub_rast0.text(xticks0[0]-130, yticks[-1], 'C', size=28, color='black')
    sub_rast0.text(ylab_xposit, 375, 'Neuron #', rotation = 'vertical',
                    size=20)
    pyplot.text(xlim0[0]+125-12, -60, '$\Uparrow$', size=25)

    sub_rast0.yaxis.tick_right()
    sub_rast0.spines['right'].set_visible(False)

    ###
    sub_rast = pyplot.subplot(gs[12:18, 4:13], zorder = subpzorder)
    m = bb.Monitor()
    m.source = []
    m.spikes = calc_spikes.get_spike_times_ps(net, 0, frac)
    bb.raster_plot(m, color=(0, 0, 0))
    #pyplot.plot(numpy.array(m.spikes)[:,0],numpy.array(m.spikes)[:,1], '.')

    raster_sp_x1 = nrn_spikes1*1000.
    raster_sp_y1 = (net.nrn_meas_e[nrn])*numpy.ones(len(nrn_spikes1))*frac

    pyplot.plot(raster_sp_x1, raster_sp_y1, 'o', color='red')
    pyplot.plot(raster_sp_x1, raster_sp_y1, '.', color='red')

    # put some lines between groups
    for i in range(net.n_ass):
        sub_rast.plot(numpy.arange(xlim1[0], xlim1[1]),
                    (i+1)*frac*net.s_ass*numpy.ones(xlim1[1]-xlim1[0]), 'gray')

    sub_rast.set_xlim(xlim1)
    sub_rast.set_xticks(xticks1)
    sub_rast.set_xticks([])
    sub_rast.set_xlabel('')
    sub_rast.spines['left'].set_visible(False)

    sub_rast.set_ylabel('', size=20)
    sub_rast.set_yticks([])
    sub_rast.xaxis.set_tick_params(width=1, length=5)
    sub_rast.yaxis.set_tick_params(width=1, length=5)
    sub_rast.set_xticklabels([], size=20)

    pyplot.text(xlim1[0]+375-12,-60, '$\Uparrow$', size=25)
    #sub_rast.set_xticklabels(xticks1_lab, size=20)
    #pyplot.xlabel('Time [ms]', size=20)

    # size of the diagonal lines in axes coordinates
    dx0 = .012 
    dy0 = .04 
    # the second subplot has different size than the prev
    dx1 = dx0*3./8 
    dy1 = dy0*1. 

    kwargs = dict(transform=sub_rast0.transAxes, color='k', clip_on=False)
    sub_rast0.yaxis.tick_left()
    # top-right diagonal
    sub_rast0.plot((1-dx0, 1+dx0), (1-dy0, 1+dy0), **kwargs)
    # bottom-right diagonal
    sub_rast0.plot((1-dx0, 1+dx0), (-dy0, +dy0), **kwargs)

    kwargs.update(transform=sub_rast.transAxes)  # switch to the bottom axes
    # top-left diagonal
    sub_rast.plot((-dx1, +dx1), (1-dy1, 1+dy1), **kwargs)
    # bottom-left diagonal
    sub_rast.plot((-dx1, dx1), (-dy1, +dy1), **kwargs)

    ################################################################
    sub_curr0 = pyplot.subplot(gs[0:5, 1:4], zorder = subpzorder)
    sub_curr0.patch.set_facecolor('None')

    #lim for the vectors(with tres in mind)
    cx0lim = [xlim0[0]/tres, xlim0[1]/tres]
    cx1lim = [xlim1[0]/tres, xlim1[1]/tres]

    yticks=[-200, 0, 200, 400]
    curr_e= net.mon_ecurr_e[net.nrn_meas_e[nrn]]/pA+200
    curr_i= net.mon_icurr_e[net.nrn_meas_e[nrn]]/pA
    volt_e= net.mon_volt_e[net.nrn_meas_e[nrn]]/mV # measured voltage here
    curr_leak = 10.*nS*(-60.-volt_e)*mV/pA
    curr_maxe = max((curr_e[cx0lim[0]:cx0lim[1]]).max(),
                    (curr_e[cx1lim[0]:cx1lim[1]]).max())
    curr_maxi = max((curr_i[cx0lim[0]:cx0lim[1]]).max(),
                    (curr_i[cx1lim[0]:cx1lim[1]]).max())
    curr_mine = min((curr_e[cx0lim[0]:cx0lim[1]]).min(),
                    (curr_e[cx1lim[0]:cx1lim[1]]).min())
    curr_mini = min((curr_i[cx0lim[0]:cx0lim[1]]).min(),
                    (curr_i[cx1lim[0]:cx1lim[1]]).min())

    sub_curr0.plot(net.mon_ecurr_e.times/ms, curr_e, 'r', zorder=3)
    sub_curr0.plot(net.mon_ecurr_e.times/ms, curr_i, 'b', zorder=1)
    sub_curr0.plot(net.mon_ecurr_e.times/ms, curr_e+curr_i+curr_leak,
                    'black', zorder=2)

    ylim=[1.02*min(curr_mine, curr_mini), 1.1*max(curr_maxe, curr_maxi)]
    remove_spines(sub_curr0, xlim=xlim0, ylim=ylim, xticks=[], yticks=yticks,
                    ylabel='I [pA]', legend= [])
    sub_curr0.set_ylabel('', size=20)
    sub_curr0.text(ylab_xposit, 330, 'Current [pA]',
                    rotation = 'vertical', size=20)
    sub_curr0.text(xticks0[0]-130, 500., 'A', size=28, color='black')
    sub_curr0.set_yticks(yticks)
    sub_curr0.set_yticklabels(yticks, size=20)
    sub_curr0.yaxis.set_tick_params(width=1, length=5)


    sub_curr = pyplot.subplot(gs[0:5, 4:13], zorder = subpzorder)
    sub_curr.patch.set_facecolor('None')

    pyplot.plot(net.mon_ecurr_e.times/ms, curr_e, 'r')
    pyplot.plot(net.mon_ecurr_e.times/ms, curr_i, 'b')
    pyplot.plot(net.mon_ecurr_e.times/ms, curr_e+curr_i+curr_leak, 'black')

    ylim=[1.2*min(curr_mine, curr_mini), 1.2*max(curr_maxe, curr_maxi)]
    remove_spines(sub_curr, xlim=xlim1, ylim=ylim, xticks=[], yticks=[],
                    ylabel='', legend= [])
    sub_curr.set_ylabel('', size=20)
    sub_curr.yaxis.set_tick_params(width=1, length=5)


    sub_curr.text(xlim1[1]-87, -320., 'Inhibition', size=20,
                                        color='b', zorder=3)
    sub_curr.text(xlim1[1]-45, 80., 'Total', size=20, zorder=3)
    sub_curr.text(xlim1[1]-92, 300., 'Excitation', size=20,
                                        color='r', zorder=3)
    '''
    '''
    sub_curr0.spines['right'].set_visible(False)
    sub_curr.spines['left'].set_visible(False)

    sub_curr0.yaxis.tick_left()
    '''
    kwargs.update(transform=sub_curr0.transAxes)  # switch to the bottom axes
    sub_rast0.yaxis.tick_left()
    # top-right diagonal
    sub_rast0.plot((1-dx0, 1+dx0), (1-dy0, 1+dy0), **kwargs)
    # bottom-right diagonal
    sub_rast0.plot((1-dx0, 1+dx0), (-dy0, +dy0), **kwargs)

    kwargs.update(transform=sub_curr.transAxes)  # switch to the bottom axes
    # top-left diagonal
    sub_rast.plot((-dx1, +dx1), (1-dy1, 1+dy1), **kwargs)
    # bottom-left diagonal
    sub_rast.plot((-dx1, dx1), (-dy1, +dy1), **kwargs)
    '''

    ################################################################
    #raster_sp_x = nrn_spikes*1000 
    #raster_sp_y = (491+nrn)*numpy.ones(len(nrn_spikes))
    #sub_volt = pyplot.subplot(gs[16:20,0:12])
    sub_volt0 = pyplot.subplot(gs[6:11,1:4], zorder = subpzorder)
    sub_volt0.patch.set_facecolor('None')
    ylim=[-61,-39]
    yticks=[-60,-50,-40]

    for i,v in enumerate(volt_e):
        if v<-59 and volt_e[i-1]>-55:
            volt_e[i-1] = -40

    volt_sp_x0 = nrn_spikes0*1000 
    volt_sp_y0 = -40*numpy.ones(len(volt_sp_x0)) 
    
    pyplot.plot(net.mon_volt_e.times/ms, volt_e,'black')
    pyplot.plot(volt_sp_x0, volt_sp_y0, 'o', color='red')

    remove_spines(sub_volt0, xlim=xlim0, ylim=ylim,
                xticks=[], yticks=yticks,
                ylabel='V [mV]', legend= [])
    sub_volt0.set_ylabel('', size=20)
    sub_volt0.text(ylab_xposit, -41, 'Voltage [mV]',
                    rotation='vertical', size=20)
    sub_volt0.set_yticks(yticks)
    sub_volt0.set_yticklabels(yticks, size=20)
    sub_volt0.yaxis.set_tick_params(width=1, length=5)
    sub_volt0.plot(numpy.arange(xlim0[0],xlim0[1]),
            -50.*numpy.ones(xlim0[1]-xlim0[0]), '-.', color='gray')
    sub_volt0.text(xticks0[0]-130, -40., 'B', size=28, color='black')


    sub_volt = pyplot.subplot(gs[6:11,4:13], zorder = subpzorder)
    sub_volt.patch.set_facecolor('None')

    volt_sp_x1 = nrn_spikes1*1000 
    volt_sp_y1 = -40*numpy.ones(len(volt_sp_x1)) 
    
    pyplot.plot(net.mon_volt_e.times/ms, volt_e,'black')
    pyplot.plot(volt_sp_x1, volt_sp_y1, 'o', color='red')
 
    remove_spines(sub_volt, xlim=xlim1, ylim=ylim,
                xticks=[], yticks=yticks,
                ylabel='', legend= [])
    sub_volt.set_yticks([])
    sub_volt.plot(numpy.arange(xlim1[0],xlim1[1]),
            -50.*numpy.ones(xlim1[1]-xlim1[0]), '-.', color='gray')

    sub_volt0.spines['right'].set_visible(False)
    sub_volt.spines['left'].set_visible(False)

    # draw vertical lines between spikes in raster and voltage trace
    linii_nekvi=[]
    curr_sp_y = 400.
    for i in range(len(volt_sp_x0)):
        linii_nekvi.append(get_straightline(figure, sub_rast0, sub_curr0,
                raster_sp_x0[i], raster_sp_y0[i], volt_sp_x0[i], curr_sp_y))

    for i in range(len(volt_sp_x1)):
        linii_nekvi.append(get_straightline(figure, sub_rast, sub_curr,
                raster_sp_x1[i], raster_sp_y1[i], volt_sp_x1[i], curr_sp_y))

    if disc_only:
        bar_x = xlim1[-1] - 100
        bar_y = -60
        x_len = 100
        sub_volt.text(bar_x+.15*x_len, bar_y+2, str(x_len)+' ms', size=20)
        transFigure = figure.transFigure.inverted()
        coord1 = transFigure.transform(
                        sub_volt.transData.transform([bar_x+0, bar_y]))
        coord2 = transFigure.transform(
                        sub_volt.transData.transform([bar_x+0+x_len, bar_y]))
        line_bar = matplotlib.lines.Line2D((coord1[0], coord2[0]),
                        (coord1[1], coord2[1]), transform=figure.transFigure, 
                        color='black', linewidth=3.)

        linii_nekvi.append(line_bar)
        figure.lines = linii_nekvi
        from random import randint
        loc='tfigs/rcv8/'
        prefix = 'rccv_'
        fname = 'prf' + str(net.pr_ee) + str(net.pf_ee_new) + '_' + \
            str(-nrn) + '_int' + str(xlim1[0]) + '_' + str(randint(0, 99999))
        figure.savefig(loc+prefix+fname+'rand_.eps', format='eps')
        figure.savefig(loc+prefix+fname+'rand_.png', format='png')
        figure.savefig(loc+prefix+fname+'rand_.pdf', format='pdf')
        pyplot.show()
        return 0


    ################################################################
    # raster for continious ASS at the bottom of the figure

    fname = 'contASS_pr0.1pfboost0.04frac0.1.npz'
    #fname = 'contin_modified.npz'
    xlim0 = [19375, 19625]
    xlim2 = [28625, 29375]

    #xticks=numpy.arange(x0, x1+1, 200)
    #xticks_lab = numpy.arange(0, x1-x0+1, 200)
    xticks=[]

    # first tick in second plot in plotting time
    shift_xtick = dx_tick - (xlim0[1]-xlim0[0]) % dx_tick 
    # last tick
    first_xtick= ((xlim0[1]-xlim0[0]+dx_tick)//dx_tick)*dx_tick
    last_xtick = first_xtick + xlim2[1]-xlim2[0] + 1
    xticks2 = numpy.arange(xlim2[0] + shift_xtick, xlim2[1]+1, dx_tick)
 
    sub_rast20 = pyplot.subplot(gs[20:26, 1:4], zorder = subpzorder)
    draw_evoked_rasta2(fname, '', x0=xlim0[0], x1=xlim0[1])
    yticks=[0, 100, 200, 300, 400, 500]
    yticks=[0, 250, 500]
    #yticks=[0, 2500, 5000]
    sub_rast20.set_xticks(xticks0)
    sub_rast20.set_xticks([])
    sub_rast20.set_xticklabels([])
    sub_rast20.set_yticks(yticks)
    sub_rast20.set_yticklabels(yticks, size=20)
    sub_rast20.text(xlim0[0]-80, 375, 'Neuron #',
                    rotation = 'vertical', size=20)
    sub_rast20.text(xlim0[0]-130, yticks[-1], 'D', size=28, color='black')
    sub_rast20.spines['right'].set_visible(False)
    sub_rast20.xaxis.set_tick_params(width=1, length=5)
    sub_rast20.yaxis.set_tick_params(width=1, length=5)
    pyplot.text(xlim0[0]+125-12,-60, '$\Uparrow$', size=25)

    kwargs = dict(transform=sub_rast20.transAxes, color='k', clip_on=False)
    sub_rast20.yaxis.tick_left()
    # top-right diagonal
    sub_rast20.plot((1-dx0, 1+dx0), (1-dy0, 1+dy0), **kwargs)
    # bottom-right diagonal
    sub_rast20.plot((1-dx0, 1+dx0), (-dy0, +dy0), **kwargs)

    #####
    sub_rast2 = pyplot.subplot(gs[20:26, 4:13], zorder = subpzorder)
    draw_evoked_rasta2(fname, '', x0=xlim2[0], x1=xlim2[1])

    sub_rast2.xaxis.set_tick_params(width=1, length=5)
    sub_rast2.yaxis.set_tick_params(width=1, length=5)
    #sub_rast.set_ylabel('Neurons',size=18)
    sub_rast2.set_xticks(xticks2)
    sub_rast2.set_xticks([])
    sub_rast2.set_xticklabels([])
    #pyplot.xlabel('Time [ms]', size=20)

    sub_rast2.spines['left'].set_visible(False)

    kwargs.update(transform=sub_rast2.transAxes)  # switch to the bottom axes
    # top-left diagonal
    sub_rast2.plot((-dx1, +dx1), (1-dy1, 1+dy1), **kwargs)
    # bottom-left diagonal
    sub_rast2.plot((-dx1, dx1), (-dy1, +dy1), **kwargs)
    pyplot.text(xlim2[0]+375-12,-60, '$\Uparrow$', size=25)

    '''
    bar_x = xlim2[-1] - 100
    bar_y = -100
    x_len = 100
    pyplot.text(bar_x+.15*x_len, bar_y+20, str(x_len)+' ms', size=20)
    transFigure = figure.transFigure.inverted()
    coord1 = transFigure.transform(
                    sub_rast2.transData.transform([bar_x+0, bar_y]))
    coord2 = transFigure.transform(
                    sub_rast2.transData.transform([bar_x+0+x_len, bar_y]))
    '''
    bar_x = xlim1[-1] - 100
    bar_y = -60
    x_len = 100
    sub_volt.text(bar_x+.15*x_len, bar_y+2, str(x_len)+' ms', size=20)
    transFigure = figure.transFigure.inverted()
    coord1 = transFigure.transform(
                    sub_volt.transData.transform([bar_x+0, bar_y]))
    coord2 = transFigure.transform(
                    sub_volt.transData.transform([bar_x+0+x_len, bar_y]))

    line_bar = matplotlib.lines.Line2D((coord1[0], coord2[0]),
                        (coord1[1], coord2[1]), transform=figure.transFigure, 
                        color='black', linewidth=3.)

    linii_nekvi.append(line_bar)
    figure.lines = linii_nekvi

    #1/0
    #pyplot.show()
    #return 0

    from random import randint
    loc='tfigs/rcv7/'
    prefix = 'rccv_'
    fname = 'prf' + str(net.pr_ee) + str(net.pf_ee) + '_' + \
        str(-nrn) + '_int' + str(xlim1[0]) + '_' + str(randint(0, 99999))
    figure.savefig(loc+prefix+fname+'.eps', format='eps')
    figure.savefig(loc+prefix+fname+'.png', format='png')
    figure.savefig(loc+prefix+fname+'.pdf', format='pdf')
Esempio n. 13
0
def test_neglect(net_params, input_level, delay_duration, output_base, record_lfp=True, record_voxel=True,
                 record_neuron_state=True, record_spikes=True, record_pop_firing_rate=True,
                 record_neuron_firing_rate=False, record_inputs=False, plot_output=False):
    instructed_mem_output=None
    if not output_base is None:
        instructed_mem_output='%s.instructed.memory.h5' % output_base
    instructed_mem_monitor=run_neglect([input_level,0], delay_duration, net_params=net_params,
        output_file=instructed_mem_output, record_lfp=record_lfp, record_voxel=record_voxel,
        record_neuron_state=record_neuron_state, record_spikes=record_spikes,
        record_pop_firing_rate=record_pop_firing_rate, record_neuron_firing_rate=record_neuron_firing_rate,
        record_inputs=record_inputs, mem_trial=True)

    instructed_delay_output=None
    if not output_base is None:
        instructed_delay_output='%s.instructed.delay.h5' % output_base
    instructed_delay_monitor=run_neglect([input_level,0], delay_duration, net_params=net_params,
        output_file=instructed_delay_output, record_lfp=record_lfp, record_voxel=record_voxel,
        record_neuron_state=record_neuron_state, record_spikes=record_spikes,
        record_pop_firing_rate=record_pop_firing_rate, record_neuron_firing_rate=record_neuron_firing_rate,
        record_inputs=record_inputs, mem_trial=True)

    free_choice_output=None
    if not output_base is None:
        free_choice_output='%s.free_choice.h5' % output_base
    free_choice_monitor=run_neglect([input_level,input_level], delay_duration, net_params=net_params,
        output_file=free_choice_output, record_lfp=record_lfp, record_voxel=record_voxel,
        record_neuron_state=record_neuron_state, record_spikes=record_spikes,
        record_pop_firing_rate=record_pop_firing_rate, record_neuron_firing_rate=record_neuron_firing_rate,
        record_inputs=record_inputs, mem_trial=True)

    if plot_output:
        if record_pop_firing_rate:
            figure()
            ax=subplot(221)
            ax.plot(instructed_monitor.population_rate_monitors['left_ec'].times/ms,
                instructed_monitor.population_rate_monitors['left_ec'].smooth_rate(width=5*ms)/hertz, label='left LIP EC')
            ax.plot(instructed_monitor.population_rate_monitors['left_ei'].times/ms,
                instructed_monitor.population_rate_monitors['left_ei'].smooth_rate(width=5*ms)/hertz, label='left LIP EI')
            ax.plot(instructed_monitor.population_rate_monitors['left_ic'].times/ms,
                instructed_monitor.population_rate_monitors['left_ic'].smooth_rate(width=5*ms)/hertz, label='left LIP IC')
            ax.plot(instructed_monitor.population_rate_monitors['left_ii'].times/ms,
                instructed_monitor.population_rate_monitors['left_ii'].smooth_rate(width=5*ms)/hertz, label='left LIP II')
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')
            title('Instructed')

            ax=subplot(222)
            ax.plot(instructed_monitor.population_rate_monitors['right_ec'].times/ms,
                instructed_monitor.population_rate_monitors['right_ec'].smooth_rate(width=5*ms)/hertz, label='right LIP EC')
            ax.plot(instructed_monitor.population_rate_monitors['right_ei'].times/ms,
                instructed_monitor.population_rate_monitors['right_ei'].smooth_rate(width=5*ms)/hertz, label='right LIP EI')
            ax.plot(instructed_monitor.population_rate_monitors['right_ic'].times/ms,
                instructed_monitor.population_rate_monitors['right_ic'].smooth_rate(width=5*ms)/hertz, label='right LIP IC')
            ax.plot(instructed_monitor.population_rate_monitors['right_ii'].times/ms,
                instructed_monitor.population_rate_monitors['right_ii'].smooth_rate(width=5*ms)/hertz, label='right LIP II')
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')
            title('Instructed')

            ax=subplot(223)
            ax.plot(free_choice_monitor.population_rate_monitors['left_ec'].times/ms,
                free_choice_monitor.population_rate_monitors['left_ec'].smooth_rate(width=5*ms)/hertz, label='left LIP EC')
            ax.plot(free_choice_monitor.population_rate_monitors['left_ei'].times/ms,
                free_choice_monitor.population_rate_monitors['left_ei'].smooth_rate(width=5*ms)/hertz, label='left LIP EI')
            ax.plot(free_choice_monitor.population_rate_monitors['left_ic'].times/ms,
                free_choice_monitor.population_rate_monitors['left_ic'].smooth_rate(width=5*ms)/hertz, label='left LIP IC')
            ax.plot(free_choice_monitor.population_rate_monitors['left_ii'].times/ms,
                free_choice_monitor.population_rate_monitors['left_ii'].smooth_rate(width=5*ms)/hertz, label='left LIP II')
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')
            title('Free choice')

            ax=subplot(224)
            ax.plot(free_choice_monitor.population_rate_monitors['right_ec'].times/ms,
                free_choice_monitor.population_rate_monitors['right_ec'].smooth_rate(width=5*ms)/hertz, label='right LIP EC')
            ax.plot(free_choice_monitor.population_rate_monitors['right_ei'].times/ms,
                free_choice_monitor.population_rate_monitors['right_ei'].smooth_rate(width=5*ms)/hertz, label='right LIP EI')
            ax.plot(free_choice_monitor.population_rate_monitors['right_ic'].times/ms,
                free_choice_monitor.population_rate_monitors['right_ic'].smooth_rate(width=5*ms)/hertz, label='right LIP IC')
            ax.plot(free_choice_monitor.population_rate_monitors['right_ii'].times/ms,
                free_choice_monitor.population_rate_monitors['right_ii'].smooth_rate(width=5*ms)/hertz, label='right LIP II')
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')
            title('Free Choice')

        if record_voxel:
            figure()
            ax=subplot(111)
            ax.plot(instructed_monitor.left_voxel_monitor['y'].times / ms, instructed_monitor.left_voxel_monitor['y'][0],
                label='instructed left LIP')
            ax.plot(instructed_monitor.right_voxel_monitor['G_total'].times / ms, instructed_monitor.right_voxel_monitor['y'][0],
                label='instructed right LIP')
            ax.plot(free_choice_monitor.left_voxel_monitor['G_total'].times / ms, free_choice_monitor.left_voxel_monitor['y'][0],
                label='free choice left LIP')
            ax.plot(free_choice_monitor.right_voxel_monitor['G_total'].times / ms, free_choice_monitor.right_voxel_monitor['y'][0],
                label='free choice right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('BOLD')

        # Spike raster plots
        if record_spikes:
            figure()
            title('Free Choice')
            subplot(811)
            raster_plot(*free_choice_monitor.spike_monitors['left_ec'],newfigure=False)
            ylabel('Left EC')
            subplot(812)
            raster_plot(*free_choice_monitor.spike_monitors['left_ei'],newfigure=False)
            ylabel('Left EI')
            subplot(813)
            raster_plot(*free_choice_monitor.spike_monitors['left_ic'],newfigure=False)
            ylabel('Left IC')
            subplot(814)
            raster_plot(*free_choice_monitor.spike_monitors['left_ii'],newfigure=False)
            ylabel('Left II')
            subplot(815)
            raster_plot(*free_choice_monitor.spike_monitors['right_ec'],newfigure=False)
            ylabel('Right EC')
            subplot(816)
            raster_plot(*free_choice_monitor.spike_monitors['right_ei'],newfigure=False)
            ylabel('Right EI')
            subplot(817)
            raster_plot(*free_choice_monitor.spike_monitors['right_ic'],newfigure=False)
            ylabel('Right IC')
            subplot(818)
            raster_plot(*free_choice_monitor.spike_monitors['right_ii'],newfigure=False)
            ylabel('Right II')

            figure()
            title('Instructed')
            subplot(811)
            raster_plot(*instructed_monitor.spike_monitors['left_ec'],newfigure=False)
            ylabel('Left EC')
            subplot(812)
            raster_plot(*instructed_monitor.spike_monitors['left_ei'],newfigure=False)
            ylabel('Left EI')
            subplot(813)
            raster_plot(*instructed_monitor.spike_monitors['left_ic'],newfigure=False)
            ylabel('Left IC')
            subplot(814)
            raster_plot(*instructed_monitor.spike_monitors['left_ii'],newfigure=False)
            ylabel('Left II')
            subplot(815)
            raster_plot(*instructed_monitor.spike_monitors['right_ec'],newfigure=False)
            ylabel('Right EC')
            subplot(816)
            raster_plot(*instructed_monitor.spike_monitors['right_ei'],newfigure=False)
            ylabel('Right EI')
            subplot(817)
            raster_plot(*instructed_monitor.spike_monitors['right_ic'],newfigure=False)
            ylabel('Right IC')
            subplot(818)
            raster_plot(*instructed_monitor.spike_monitors['right_ii'],newfigure=False)
            ylabel('Right II')
    print 'create monitors for', name
    rate_monitors[name+'e'] = b.PopulationRateMonitor(neuron_groups[name+'e'], bin = (single_example_time+resting_time)/b.second)
    rate_monitors[name+'i'] = b.PopulationRateMonitor(neuron_groups[name+'i'], bin = (single_example_time+resting_time)/b.second)
    spike_counters[name+'e'] = b.SpikeCounter(neuron_groups[name+'e'])
    
    if record_spikes:
        spike_monitors[name+'e'] = b.SpikeMonitor(neuron_groups[name+'e'])
        spike_monitors[name+'i'] = b.SpikeMonitor(neuron_groups[name+'i'])

if record_spikes:
    b.figure(fig_num)
    fig_num += 1
    b.ion()
    b.subplot(211)
    b.raster_plot(spike_monitors['Ae'], refresh=1000*b.ms, showlast=1000*b.ms)
    b.subplot(212)
    b.raster_plot(spike_monitors['Ai'], refresh=1000*b.ms, showlast=1000*b.ms)


#------------------------------------------------------------------------------ 
# create input population and connections from input populations 
#------------------------------------------------------------------------------ 
pop_values = [0,0,0]
for i,name in enumerate(input_population_names):
    input_groups[name+'e'] = b.PoissonGroup(n_input, 0)
    rate_monitors[name+'e'] = b.PopulationRateMonitor(input_groups[name+'e'], bin = (single_example_time+resting_time)/b.second)

for name in input_connection_names:
    print 'create connections between', name[0], 'and', name[1]
    for connType in input_conn_names:
Esempio n. 15
0
 def run(self):
     #------------------------------------------------------------------------------ 
     # run the simulation and set inputs
     #------------------------------------------------------------------------------ 
     previousSpikeCount = np.zeros((self.nE, self.numAllPops))
     currentSpikeCount = np.zeros((self.nE, self.numAllPops))
     if self.saveSpikeCountsPerExample:
         self.spikeCounts=np.zeros((self.numExamples, self.nE, self.numAllPops))
     
     if self.realTimePlotting and self.recordSpikes:
         b.ion()
         fig = b.figure(1)
         b.raster_plot(self.spikeMonitors['Ae'])
 
     if self.ending=='':
         initJ = 0
     else:
         initJ = int(self.ending)
     for j in xrange(int(self.numExamples)):            
         if self.restingTime or j==0:
             for i,name in enumerate(self.inputPopulationNames):
                 rates = np.ones(self.nE)  * 0
                 self.inputGroups[name+'e'].rate = rates
             self.net.run(self.restingTime)
             
         if j%self.normalization_interval == 0:
             self.normalizeWeights()
             
         print 'set new rates of the inputs'
         self.setNewInput(self,j)
                 
         print 'run number:', j+1, 'of', int(self.numExamples)
         self.net.run(self.singleExampleTime)
         for i,name in enumerate(self.populationNames):
             name += 'e'
             currentSpikeCount[:,i] = np.asarray(self.spikeCounters[name].count[:]) - previousSpikeCount[:,i]
             previousSpikeCount[:,i] = np.copy(self.spikeCounters[name].count[:])
             self.resultMonitor[j,i] = self.computePopVector(currentSpikeCount[:,i])
             print name, 'pop. activity: ', self.resultMonitor[j,i], ', spikecount:', sum(currentSpikeCount[:,i])
             if self.saveSpikeCountsPerExample:
                 self.spikeCounts[j,:,i] = currentSpikeCount[:,i]
                 
         for i,name in enumerate(self.inputPopulationNames):
             print name, 'pop. activity: ', (self.popValues[j,i])
             name += 'e'
             currentSpikeCount[:,i+self.numPops] = np.asarray(self.spikeCounters[name].count[:]) - previousSpikeCount[:,i+self.numPops]
             previousSpikeCount[:,i+self.numPops] = np.copy(self.spikeCounters[name].count[:])
             self.resultMonitor[j,i+self.numPops] = self.computePopVector(currentSpikeCount[:,i+self.numPops])
             if self.saveSpikeCountsPerExample:
                 self.spikeCounts[j,:,i+self.numPops] = currentSpikeCount[:,i+self.numPops]
             
                 
         if not self.testMode:
             if self.numExamples <= 1000:
                 if (j+1)%100==0 and not j==0:
                     self.saveConnections(str(j+initJ+1))
             else:
                 if (j+1)%5000==0 and not j==0:
                     self.saveConnections(str(j+initJ+1))
                     
         if self.realTimePlotting and self.recordSpikes:
             b.raster_plot(self.spikeMonitors['Ae'], showlast=1000*b.ms)
             fig.canvas.draw()
         
     
     #------------------------------------------------------------------------------ 
     # save results
     #------------------------------------------------------------------------------ 
     print 'save results'
     
     if self.testMode:
         np.savetxt(self.dataPath + 'activity/resultPopVecs' + str(self.numExamples) + '.txt', self.resultMonitor)
         np.savetxt(self.dataPath + 'activity/popVecs' + str(self.numExamples) + '.txt', self.popValues)
         for name in self.spikeCounters:
             np.savetxt(self.dataPath + 'activity/spikeCount' + name + '.txt', 
                        self.spikeCounters[name].count[:]/(self.singleExampleTime*int(self.numExamples)))
         if self.saveSpikeCountsPerExample:
             np.save(self.dataPath + 'activity/spikeCountPerExample', self.spikeCounts)
     else:
         self.saveConnections(str(self.numExamples+initJ))
         self.normalizeWeights()
         self.saveConnections()
Esempio n. 16
0
    def plot(self, trial_duration):

        # Spike raster plots
        if self.spike_monitors is not None:
            figure()
            subplot(811)
            raster_plot(self.spike_monitors['left_ec'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.left_lip.e_contra_size)
            ylabel('left EC')
            subplot(812)
            raster_plot(self.spike_monitors['left_ei'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.left_lip.e_ipsi_size)
            ylabel('left EI')
            subplot(813)
            raster_plot(self.spike_monitors['left_ic'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.left_lip.i_contra_size)
            ylabel('left IC')
            subplot(814)
            raster_plot(self.spike_monitors['left_ii'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.left_lip.i_ipsi_size)
            ylabel('left II')
            subplot(815)
            raster_plot(self.spike_monitors['right_ec'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.right_lip.e_contra_size)
            ylabel('right EC')
            subplot(816)
            raster_plot(self.spike_monitors['right_ei'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.right_lip.e_ipsi_size)
            ylabel('right EI')
            subplot(817)
            raster_plot(self.spike_monitors['right_ic'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.right_lip.i_contra_size)
            ylabel('right IC')
            subplot(818)
            raster_plot(self.spike_monitors['right_ii'],newfigure=False)
            xlim(0,trial_duration/ms)
            ylim(0,self.brain_network.right_lip.i_ipsi_size)
            ylabel('right II')

        # Network firing rate plots
        if self.population_rate_monitors is not None:
            smooth_width=10*ms
            left_ec_vis_rate=self.population_rate_monitors['left_ec_vis'].smooth_rate(width=smooth_width)/hertz
            left_ec_mem_rate=self.population_rate_monitors['left_ec_mem'].smooth_rate(width=smooth_width)/hertz
            left_ec_rate=self.population_rate_monitors['left_ec'].smooth_rate(width=smooth_width)/hertz
            left_ei_vis_rate=self.population_rate_monitors['left_ei_vis'].smooth_rate(width=smooth_width)/hertz
            left_ei_mem_rate=self.population_rate_monitors['left_ei_mem'].smooth_rate(width=smooth_width)/hertz
            left_ei_rate=self.population_rate_monitors['left_ei'].smooth_rate(width=smooth_width)/hertz
            left_ic_rate=self.population_rate_monitors['left_ic'].smooth_rate(width=smooth_width)/hertz
            left_ii_rate=self.population_rate_monitors['left_ii'].smooth_rate(width=smooth_width)/hertz
            
            right_ec_vis_rate=self.population_rate_monitors['right_ec_vis'].smooth_rate(width=smooth_width)/hertz
            right_ec_mem_rate=self.population_rate_monitors['right_ec_mem'].smooth_rate(width=smooth_width)/hertz
            right_ec_rate=self.population_rate_monitors['right_ec'].smooth_rate(width=smooth_width)/hertz
            right_ei_vis_rate=self.population_rate_monitors['right_ei_vis'].smooth_rate(width=smooth_width)/hertz
            right_ei_mem_rate=self.population_rate_monitors['right_ei_mem'].smooth_rate(width=smooth_width)/hertz
            right_ei_rate=self.population_rate_monitors['right_ei'].smooth_rate(width=smooth_width)/hertz
            right_ic_rate=self.population_rate_monitors['right_ic'].smooth_rate(width=smooth_width)/hertz
            right_ii_rate=self.population_rate_monitors['right_ii'].smooth_rate(width=smooth_width)/hertz
            
            max_rate=np.max([np.max(left_ec_vis_rate), np.max(left_ec_mem_rate), np.max(left_ec_rate), 
                             np.max(left_ei_vis_rate), np.max(left_ei_mem_rate), np.max(left_ic_rate),
                             np.max(left_ii_rate), 
                             np.max(right_ec_vis_rate), np.max(right_ec_mem_rate), np.max(right_ec_rate),
                             np.max(right_ei_vis_rate), np.max(right_ei_mem_rate), np.max(right_ei_rate),
                             np.max(right_ic_rate), np.max(right_ii_rate)])
            
            times_ms=self.population_rate_monitors['left_ec_vis'].times/ms
            
            figure()
            ax=subplot(211)
            ax.plot(times_ms, left_ec_vis_rate, label='left LIP EC vis')
            ax.plot(times_ms, left_ec_mem_rate, label='left LIP EC mem')
            #ax.plot(times_ms, left_ec_rate, label='left LIP EC')
            ax.plot(times_ms, left_ei_vis_rate, label='left LIP EI vis')
            ax.plot(times_ms, left_ei_mem_rate, label='left LIP EI mem')
            #ax.plot(times_ms, left_ei_rate, label='left LIP EI')
            ax.plot(times_ms, left_ic_rate, label='left LIP IC')
            ax.plot(times_ms, left_ii_rate, label='left LIP II')
            ylim(0,max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

            ax=subplot(212)
            ax.plot(times_ms, right_ec_vis_rate, label='right LIP EC vis')
            ax.plot(times_ms, right_ec_mem_rate, label='right LIP EC mem')
            #ax.plot(times_ms, right_ec_rate, label='right LIP EC')
            ax.plot(times_ms, right_ei_vis_rate, label='right LIP EI vis')
            ax.plot(times_ms, right_ei_mem_rate, label='right LIP EI mem')
            #ax.plot(times_ms, right_ei_rate, label='right LIP EI')
            ax.plot(times_ms, right_ic_rate, label='right LIP IC')
            ax.plot(times_ms, right_ii_rate, label='right LIP II')
            ylim(0,max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

            figure()
            ax=subplot(211)
            ax.plot(times_ms, left_ec_rate, label='left LIP EC')
            ax.plot(times_ms, left_ei_rate, label='left LIP EI')
            ylim(0,max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

            ax=subplot(212)
            ax.plot(times_ms, right_ec_rate, label='right LIP EC')
            ax.plot(times_ms, right_ei_rate, label='right LIP EI')
            ylim(0,max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

        # Input firing rate plots
        if self.left_background_rate_monitor is not None and self.right_background_rate_monitor is not None and\
           self.left_visual_cortex_monitor is not None and self.right_visual_cortex_monitor is not None and \
           self.go_input_monitor is not None:
            figure()
            max_rate=np.max([np.max(self.left_background_rate_monitor.smooth_rate(width=5*ms)/hertz),
                             np.max(self.right_background_rate_monitor.smooth_rate(width=5*ms)/hertz),
                             np.max(self.left_visual_cortex_monitor.smooth_rate(width=5*ms)/hertz),
                             np.max(self.right_visual_cortex_monitor.smooth_rate(width=5*ms)/hertz),
                             np.max(self.go_input_monitor.smooth_rate(width=5*ms)/hertz)])
            ax=subplot(111)
            ax.plot(self.left_background_rate_monitor.times/ms, self.left_background_rate_monitor.smooth_rate(width=5*ms)/hertz, label='left background')
            ax.plot(self.right_background_rate_monitor.times/ms, self.right_background_rate_monitor.smooth_rate(width=5*ms)/hertz, label='right background')
            ax.plot(self.left_visual_cortex_monitor.times/ms, self.left_visual_cortex_monitor.smooth_rate(width=5*ms)/hertz, label='left VC')
            ax.plot(self.right_visual_cortex_monitor.times/ms, self.right_visual_cortex_monitor.smooth_rate(width=5*ms)/hertz, label='right VC')
            ax.plot(self.go_input_monitor.times/ms, self.go_input_monitor.smooth_rate(width=5*ms)/hertz, label='Go')
            legend()
            ylim(0,max_rate)

        # Network state plots
        if self.left_network_monitor is not None and self.right_network_monitor is not None:
            max_conductances=[]
            for idx in self.left_record_idx:
                max_conductances.append(np.max(self.left_network_monitor['g_ampa_r'][idx]/nS))
                max_conductances.append(np.max(self.left_network_monitor['g_ampa_x'][idx]/nS))
                max_conductances.append(np.max(self.left_network_monitor['g_ampa_b'][idx]/nS))
                max_conductances.append(np.max(self.left_network_monitor['g_ampa_g'][idx]/nS))
                max_conductances.append(np.max(self.left_network_monitor['g_nmda'][idx]/nS))
                max_conductances.append(np.max(self.left_network_monitor['g_gaba_a'][idx]/nS))
                max_conductances.append(np.max(self.left_network_monitor['g_gaba_b'][idx]/nS))
            for idx in self.right_record_idx:
                max_conductances.append(np.max(self.right_network_monitor['g_ampa_r'][idx]/nS))
                max_conductances.append(np.max(self.right_network_monitor['g_ampa_x'][idx]/nS))
                max_conductances.append(np.max(self.right_network_monitor['g_ampa_b'][idx]/nS))
                max_conductances.append(np.max(self.right_network_monitor['g_ampa_g'][idx]/nS))
                max_conductances.append(np.max(self.right_network_monitor['g_nmda'][idx]/nS))
                max_conductances.append(np.max(self.right_network_monitor['g_gaba_a'][idx]/nS))
                max_conductances.append(np.max(self.right_network_monitor['g_gaba_b'][idx]/nS))
            max_conductance=np.max(max_conductances)

            figure()
            labels=['e_contra_vis','e_contra_mem','e_ipsi_vis','e_ipsi_mem','i_contra','i_ipsi']
            for i,idx in enumerate(self.left_record_idx):
                ax=subplot(len(self.left_record_idx),1,i+1)
                ax.plot(self.left_network_monitor['g_ampa_r'].times/ms, self.left_network_monitor['g_ampa_r'][idx]/nS,
                    label='AMPA recurrent')
                ax.plot(self.left_network_monitor['g_ampa_x'].times/ms, self.left_network_monitor['g_ampa_x'][idx]/nS,
                    label='AMPA task')
                ax.plot(self.left_network_monitor['g_ampa_b'].times/ms, self.left_network_monitor['g_ampa_b'][idx]/nS,
                    label='AMPA backgrnd')
                ax.plot(self.left_network_monitor['g_ampa_g'].times/ms, self.left_network_monitor['g_ampa_g'][idx]/nS,
                    label='AMPA go')
                ax.plot(self.left_network_monitor['g_nmda'].times/ms, self.left_network_monitor['g_nmda'][idx]/nS,
                    label='NMDA')
                ax.plot(self.left_network_monitor['g_gaba_a'].times/ms, self.left_network_monitor['g_gaba_a'][idx]/nS,
                    label='GABA_A')
                ax.plot(self.left_network_monitor['g_gaba_b'].times/ms, self.left_network_monitor['g_gaba_b'][idx]/nS,
                    label='GABA_B')
                ylim(0,max_conductance)
                ylabel(labels[i])
                if not i:
                    title('Left LIP - Conductance (nS)')
                    legend()
            xlabel('Time (ms)')

            figure()
            for i,idx in enumerate(self.right_record_idx):
                ax=subplot(len(self.right_record_idx),1,i+1)
                ax.plot(self.right_network_monitor['g_ampa_r'].times/ms, self.right_network_monitor['g_ampa_r'][idx]/nS,
                    label='AMPA recurrent')
                ax.plot(self.right_network_monitor['g_ampa_x'].times/ms, self.right_network_monitor['g_ampa_x'][idx]/nS,
                    label='AMPA task')
                ax.plot(self.right_network_monitor['g_ampa_b'].times/ms, self.right_network_monitor['g_ampa_b'][idx]/nS,
                    label='AMPA backgrnd')
                ax.plot(self.right_network_monitor['g_ampa_g'].times/ms, self.right_network_monitor['g_ampa_g'][idx]/nS,
                    label='AMPA go')
                ax.plot(self.right_network_monitor['g_nmda'].times/ms, self.right_network_monitor['g_nmda'][idx]/nS,
                    label='NMDA')
                ax.plot(self.right_network_monitor['g_gaba_a'].times/ms, self.right_network_monitor['g_gaba_a'][idx]/nS,
                    label='GABA_A')
                ax.plot(self.right_network_monitor['g_gaba_b'].times/ms, self.right_network_monitor['g_gaba_b'][idx]/nS,
                    label='GABA_B')
                ylim(0,max_conductance)
                ylabel(labels[i])
                if not i:
                    title('Right LIP - Conductance (nS)')
                    legend()
            xlabel('Time (ms)')

            min_currents=[]
            max_currents=[]
            for idx in self.left_record_idx:
                max_currents.append(np.max(self.left_network_monitor['I_ampa_r'][idx]/nA))
                max_currents.append(np.max(self.left_network_monitor['I_ampa_x'][idx]/nA))
                max_currents.append(np.max(self.left_network_monitor['I_ampa_b'][idx]/nA))
                max_currents.append(np.max(self.left_network_monitor['I_ampa_g'][idx]/nA))
                max_currents.append(np.max(self.left_network_monitor['I_nmda'][idx]/nA))
                max_currents.append(np.max(self.left_network_monitor['I_gaba_a'][idx]/nA))
                max_currents.append(np.max(self.left_network_monitor['I_gaba_b'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_ampa_r'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_ampa_x'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_ampa_b'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_ampa_g'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_nmda'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_gaba_a'][idx]/nA))
                min_currents.append(np.min(self.left_network_monitor['I_gaba_b'][idx]/nA))
            for idx in self.right_record_idx:
                max_currents.append(np.max(self.right_network_monitor['I_ampa_r'][idx]/nA))
                max_currents.append(np.max(self.right_network_monitor['I_ampa_x'][idx]/nA))
                max_currents.append(np.max(self.right_network_monitor['I_ampa_b'][idx]/nA))
                max_currents.append(np.max(self.right_network_monitor['I_ampa_g'][idx]/nA))
                max_currents.append(np.max(self.right_network_monitor['I_nmda'][idx]/nA))
                max_currents.append(np.max(self.right_network_monitor['I_gaba_a'][idx]/nA))
                max_currents.append(np.max(self.right_network_monitor['I_gaba_b'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_ampa_r'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_ampa_x'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_ampa_b'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_ampa_g'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_nmda'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_gaba_a'][idx]/nA))
                min_currents.append(np.min(self.right_network_monitor['I_gaba_b'][idx]/nA))
            max_current=np.max(max_currents)
            min_current=np.min(min_currents)

            figure()
            for i,neuron_idx in enumerate(self.left_record_idx):
                ax=subplot(len(self.left_record_idx),1,i+1)
                ax.plot(self.left_network_monitor['I_ampa_r'].times/ms, self.left_network_monitor['I_ampa_r'][neuron_idx]/nA,
                    label='AMPA-recurrent')
                ax.plot(self.left_network_monitor['I_ampa_x'].times/ms, self.left_network_monitor['I_ampa_x'][neuron_idx]/nA,
                    label='AMPA-task')
                ax.plot(self.left_network_monitor['I_ampa_b'].times/ms, self.left_network_monitor['I_ampa_b'][neuron_idx]/nA,
                    label='AMPA-backgrnd')
                ax.plot(self.left_network_monitor['I_ampa_b'].times/ms, self.left_network_monitor['I_ampa_g'][neuron_idx]/nA,
                    label='AMPA-go')
                ax.plot(self.left_network_monitor['I_nmda'].times/ms, self.left_network_monitor['I_nmda'][neuron_idx]/nA,
                    label='NMDA')
                ax.plot(self.left_network_monitor['I_gaba_a'].times/ms, self.left_network_monitor['I_gaba_a'][neuron_idx]/nA,
                    label='GABA_A')
                ax.plot(self.left_network_monitor['I_gaba_b'].times/ms, self.left_network_monitor['I_gaba_b'][neuron_idx]/nA,
                    label='GABA_B')
                ylim(min_current,max_current)
                ylabel(labels[i])
                if not i:
                    title('Left LIP - Current (nA)')
                    legend()
            xlabel('Time (ms)')

            figure()
            for i,neuron_idx in enumerate(self.right_record_idx):
                ax=subplot(len(self.right_record_idx),1,i+1)
                ax.plot(self.right_network_monitor['I_ampa_r'].times/ms, self.right_network_monitor['I_ampa_r'][neuron_idx]/nA,
                    label='AMPA-recurrent')
                ax.plot(self.right_network_monitor['I_ampa_x'].times/ms, self.right_network_monitor['I_ampa_x'][neuron_idx]/nA,
                    label='AMPA-task')
                ax.plot(self.right_network_monitor['I_ampa_b'].times/ms, self.right_network_monitor['I_ampa_b'][neuron_idx]/nA,
                    label='AMPA-backgrnd')
                ax.plot(self.right_network_monitor['I_ampa_b'].times/ms, self.right_network_monitor['I_ampa_g'][neuron_idx]/nA,
                    label='AMPA-go')
                ax.plot(self.right_network_monitor['I_nmda'].times/ms, self.right_network_monitor['I_nmda'][neuron_idx]/nA,
                    label='NMDA')
                ax.plot(self.right_network_monitor['I_gaba_a'].times/ms, self.right_network_monitor['I_gaba_a'][neuron_idx]/nA,
                    label='GABA_A')
                ax.plot(self.right_network_monitor['I_gaba_b'].times/ms, self.right_network_monitor['I_gaba_b'][neuron_idx]/nA,
                    label='GABA_B')
                ylim(min_current,max_current)
                ylabel(labels[i])
                if not i:
                    title('Right LIP - Current (nA)')
                    legend()
            xlabel('Time (ms)')

        # LFP plot
        if self.left_lfp_monitor is not None and self.right_lfp_monitor is not None:
            figure()
            ax=subplot(111)
            ax.plot(self.left_lfp_monitor.times / ms, self.left_lfp_monitor[0] / mA, label='left LIP')
            ax.plot(self.right_lfp_monitor.times / ms, self.right_lfp_monitor[0] / mA, label='right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('LFP (mA)')

        # Voxel activity plots
        if self.left_voxel_monitor is not None and self.right_voxel_monitor is not None:
            syn_max=np.max([np.max(self.left_voxel_monitor['G_total'][0] / nS),
                            np.max(self.right_voxel_monitor['G_total'][0] / nS)])
            y_max=np.max([np.max(self.left_voxel_monitor['y'][0]), np.max(self.right_voxel_monitor['y'][0])])
            y_min=np.min([np.min(self.left_voxel_monitor['y'][0]), np.min(self.right_voxel_monitor['y'][0])])
            figure()
            if self.left_voxel_exc_monitor is None and self.right_voxel_exc_monitor is None:
                ax=subplot(211)
            else:
                ax=subplot(221)
                syn_max=np.max([syn_max, np.max(self.left_voxel_exc_monitor['G_total'][0]),
                                np.max(self.right_voxel_exc_monitor['G_total'][0])])
                y_max=np.max([y_max, np.max(self.left_voxel_exc_monitor['y'][0]),
                              np.max(self.right_voxel_exc_monitor['y'][0])])
                y_min=np.min([y_min, np.min(self.left_voxel_exc_monitor['y'][0]),
                              np.min(self.right_voxel_exc_monitor['y'][0])])
            ax.plot(self.left_voxel_monitor['G_total'].times / ms, self.left_voxel_monitor['G_total'][0] / nS,
                label='left LIP')
            ax.plot(self.right_voxel_monitor['G_total'].times / ms, self.right_voxel_monitor['G_total'][0] / nS,
                label='right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('Total Synaptic Activity (nS)')
            ylim(0, syn_max)
            if self.left_voxel_exc_monitor is None and self.right_voxel_exc_monitor is None:
                ax=subplot(212)
            else:
                ax=subplot(222)
            ax.plot(self.left_voxel_monitor['y'].times / ms, self.left_voxel_monitor['y'][0], label='left LIP')
            ax.plot(self.right_voxel_monitor['y'].times / ms, self.right_voxel_monitor['y'][0], label='right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('BOLD')
            ylim(y_min, y_max*2.0)
            if self.left_voxel_exc_monitor is not None and self.right_voxel_exc_monitor is not None:
                ax=subplot(223)
                ax.plot(self.left_voxel_exc_monitor['G_total'].times / ms,
                    self.left_voxel_exc_monitor['G_total'][0] / nS, label='left LIP')
                ax.plot(self.right_voxel_exc_monitor['G_total'].times / ms,
                    self.right_voxel_exc_monitor['G_total'][0] / nS, label='right LIP')
                legend()
                xlabel('Time (ms)')
                ylabel('Total Synaptic Activity (nS)')
                ylim(0, syn_max)
                ax=subplot(224)
                ax.plot(self.left_voxel_exc_monitor['y'].times / ms, self.left_voxel_exc_monitor['y'][0], label='left LIP')
                ax.plot(self.right_voxel_exc_monitor['y'].times / ms, self.right_voxel_exc_monitor['y'][0], label='right LIP')
                legend()
                xlabel('Time (ms)')
                ylabel('BOLD')
                ylim(y_min, y_max)
        show()
    neuron_groups[i] = neuron_groups['e'].subgroup(num_neurons[i])

#     print 'create monitors for', i
    rate_monitors[i] = b.PopulationRateMonitor(neuron_groups[i], bin = (single_example_time+resting_time)/b.second)
    spike_counters[i] = b.SpikeCounter(neuron_groups[i])
    
    if record_spikes:
        spike_monitors[i] = b.SpikeMonitor(neuron_groups[i])

        state_monitors[i] = b.MultiStateMonitor(neuron_groups[i], ['v'], record=[0])

if record_spikes:
    b.figure()
    b.ion()
    b.subplot(211)
    b.raster_plot(spike_monitors[1], refresh=1000*b.ms, showlast=1000*b.ms)
    b.subplot(212)
    b.raster_plot(spike_monitors[1], refresh=1000*b.ms, showlast=1000*b.ms)



#------------------------------------------------------------------------------ 
# create input population
#------------------------------------------------------------------------------ 
pop_values = [0,0,0]
for i,name in enumerate(input_population_names):
    if poisson_inputs:
        input_groups[name] = b.PoissonGroup(n_input*2, 0)
    else:
        input_groups[name] = b.SpikeGeneratorGroup(n_input*2, [])
Esempio n. 18
0
    def run(self):
        #------------------------------------------------------------------------------ 
        # run the simulation and set inputs
        #------------------------------------------------------------------------------ 
        previousSpikeCountB = np.zeros(self.nE)
        previousSpikeCountC = np.zeros(self.nE)
        self.resultMonitor = np.zeros((self.numExamples,len(self.populationNames)))
        start = time.time()
        
        if self.recordSpikes:
            b.figure()
            b.ion()
            b.subplot(211)
            b.raster_plot(self.spikeMonitors['He'], refresh=1000*b.ms, showlast=1000*b.ms)
            b.subplot(212)
            b.raster_plot(self.spikeMonitors['Hi'], refresh=1000*b.ms, showlast=1000*b.ms)
        
#         realTimeMonitor = None
#         realTimeMonitor = rltmMon.RealtimeConnectionMonitor(self.connections['HeAe'], cmap=cm.get_cmap('gist_rainbow'), 
#                                                             wmin=0, wmax=self.wmaxEE, clock=Clock(1000*b.ms))
        
        
        for j in xrange(int(self.numExamples)):            
            if self.restingTime or j==0:
                for i,name in enumerate(self.inputPopulationNames):
                    rates = np.ones(self.nE)  * 0
                    self.inputGroups[name+'e'].rate = rates
                self.net.run(self.restingTime)#, report='text')
                
            if j%self.normalization_interval == 0:
                self.normalizeWeights()
                
            print 'set new rates of the inputs'
            self.popValues = [0]*len(self.inputPopulationNames)
            for i,name in enumerate(self.inputPopulationNames):
                if name == 'X':
                    self.popValues[i] = np.random.rand();
                    rates = self.createTopoInput(self.nE, self.popValues[i])
                    self.resultMonitor[j,0] = self.popValues[i]
                else:
                    if self.testMode:
                        rates = np.ones(self.nE)  * 0
                    elif name == 'Y':
                        self.popValues[i] = (self.popValues[0]*2) % 1.
                        rates = self.createTopoInput(self.nE, self.popValues[i])
                    elif name == 'Z':
                        self.popValues[i] = (self.popValues[0]**2) % 1.
                        rates = self.createTopoInput(self.nE, self.popValues[i])
                if self.testMode:
                    rates += noise
                self.inputGroups[name+'e'].rate = rates 
                    
                    
            print 'run number:', j+1, 'of', int(self.numExamples)
            self.net.run(self.singleExampleTime)#, report='text')
            currentSpikeCountB = np.asarray(self.spikeCounters['Be'].count[:]) - previousSpikeCountB
            currentSpikeCountC = np.asarray(self.spikeCounters['Ce'].count[:]) - previousSpikeCountC
        #     print currentSpikeCount,  np.asarray(spikeCounters['Ce'].count[:]), previousSpikeCount
            previousSpikeCountB = np.copy(self.spikeCounters['Be'].count[:])
            previousSpikeCountC = np.copy(self.spikeCounters['Ce'].count[:])
            self.resultMonitor[j,1] = self.computePopVector(currentSpikeCountB)
            self.resultMonitor[j,2] = self.computePopVector(currentSpikeCountC)
            difference = np.abs((self.resultMonitor[j,0]**2)%1. - self.resultMonitor[j,2])
            if difference > 0.5:
                difference = 1-difference
            print 'Pop. activity: ', self.resultMonitor[j,2], ', Desired activity: ', (self.resultMonitor[j,0]**2)%1., ', Difference: ', difference
            
                
                    
            if not self.testMode:
                if self.numExamples <= 1000:
                    if j%100 == 0:
                        self.saveConnections(str(j))
                else:
                    if j%1000 == 0:
                        self.saveConnections(str(j))
            
        end = time.time()
        print 'time needed to simulate:', end - start
        
        
        #------------------------------------------------------------------------------ 
        # save results
        #------------------------------------------------------------------------------ 
        print 'save results'
        
        if self.testMode:
            np.savetxt(self.dataPath + 'activity/resultPopVecs' + str(self.numExamples) + '.txt', self.resultMonitor)
        else:
            self.saveConnections(str(j))
            self.normalizeWeights()
            self.saveConnections()
Esempio n. 19
0
    win = minspikes//2
    #for win in np.linspace(1, minspikes/2, 3):
    print("\nWindow length: %i" % win)
    corrs = cor_movavg_all(allslopes, krinpdist, win)
    best_corr = np.argmin(corrs)
    for n, c in enumerate(corrs):
        print("%i\t%.4f" % (n, c))

if doplot:
    pyplot.ion()
# spike trains figure
    pyplot.figure("Spikes")
    pyplot.suptitle("Spike trains")
    pyplot.subplot(2,1,1)
    pyplot.title("Input")
    raster_plot(*inpmons)
    pyplot.axis(xmin=0, xmax=duration/ms)
    pyplot.subplot(2,1,2)
    pyplot.title("Neurons")
    raster_plot(spikemon)
    pyplot.axis(xmin=0, xmax=duration/ms)
# voltages of target neurons
    if Nnrns < 10:
        # skip plotting if too many
        pyplot.figure("Voltages")
        pyplot.title("Membrane potential traces")
        for idx in range(Nnrns):
            pyplot.subplot(Nnrns, 1, idx+1)
            pyplot.plot(vmon.times, vmon[idx])
            pyplot.plot([0*second, duration], [Vth, Vth], 'k--')
            pyplot.axis(ymax=float(Vth*2))
Esempio n. 20
0
def run_simulation(realizations=1, trials=1, t=3000 * ms, alpha=1, ree=1, k=50, winlen=50 * ms, verbose=True, t_stim=0):
    """
    Run the whole simulation with the specified parameters. All model parameter are set in the function.

    Keyword arguments:
    :param realizations: number of repititions of the whole simulation, number of network instances
    :param trials: number of trials for network instance
    :param t: simulation time
    :param alpha: scaling factor for number of neurons in the network
    :param ree: clustering coefficient
    :param k: number of clusters
    :param t_stim : duration of stimulation of a subset of clusters
    :param winlen: length of window in ms
    :param verbose: plotting flag
    :return: numpy matrices with spike times
    """

    # The equations defining our neuron model
    eqs_string = """
                dV/dt = (mu - V)/tau + x: volt
                dx/dt = -1.0/tau_2*(x - y/tau_1) : volt/second
                dy/dt = -y/tau_1 : volt
                mu : volt
                tau: second
                tau_2: second
                tau_1: second
                """
    # Model parameters
    n_e = int(4000 * alpha)  # number of exc neurons
    n_i = int(1000 * alpha)  # number of inh neurons
    tau_e = 15 * ms  # membrane time constant (for excitatory synapses)
    tau_i = 10 * ms  # membrane time constant (for inhibitory synapses)
    tau_syn_2_e = 3 * ms  # exc synaptic time constant tau2 in paper
    tau_syn_2_i = 2 * ms  # inh synaptic time constant tau2 in paper
    tau_syn_1 = 1 * ms  # exc/inh synaptic time constant tau1 in paper
    vt = -50 * mV  # firing threshold
    vr = -65 * mV  # reset potential
    dv = vt - vr  # delta v
    refrac = 5 * ms  # absolute refractory period

    # scale the weights to ensure same variance in the inputs
    wee = 0.024 * dv * np.sqrt(1.0 / alpha)
    wie = 0.014 * dv * np.sqrt(1.0 / alpha)
    wii = -0.057 * dv * np.sqrt(1.0 / alpha)
    wei = -0.045 * dv * np.sqrt(1.0 / alpha)

    # Connection probability
    p_ee = 0.2
    p_ii = 0.5
    p_ie = 0.5
    p_ei = 0.5

    # determine probs for inside and outside of clusters
    p_in, p_out = get_cluster_connection_probs(ree, k, p_ee)

    mu_min_e, mu_max_e = 1.1, 1.2
    mu_min_i, mu_max_i = 1.0, 1.05

    # increase cluster weights if there are clusters
    wee_cluster = wee if p_in == p_out else 1.9 * wee

    # define numpy array for data storing
    all_data = np.zeros((realizations, trials, n_e + n_i, int(t / winlen) // 2))

    for realization in range(realizations):
        # clear workspace to make sure that is a new realization of the network
        clear(True, True)
        reinit()

        # set up new random bias parameter for every type of neuron
        mu_e = vr + np.random.uniform(mu_min_e, mu_max_e, n_e) * dv  # bias for excitatory neurons
        mu_i = vr + np.random.uniform(mu_min_i, mu_max_i, n_i) * dv  # bias for excitatory neurons

        # Let's create an equation object from our string and parameters
        model_eqs = Equations(eqs_string)

        # Let's create 5000 neurons
        all_neurons = NeuronGroup(
            N=n_e + n_i,
            model=model_eqs,
            threshold=vt,
            reset=vr,
            refractory=refrac,
            freeze=True,
            method="Euler",
            compile=True,
        )

        # Divide the neurons into excitatory and inhibitory ones
        neurons_e = all_neurons[0:n_e]
        neurons_i = all_neurons[n_e : n_e + n_i]

        # set the bias
        neurons_e.mu = mu_e
        neurons_i.mu = mu_i
        neurons_e.tau = tau_e
        neurons_i.tau = tau_i
        neurons_e.tau_2 = tau_syn_2_e
        neurons_i.tau_2 = tau_syn_2_i
        all_neurons.tau_1 = tau_syn_1

        # set up connections
        connections = Connection(all_neurons, all_neurons, "y")

        # do the cluster connection like cross validation: cluster neuron := test idx; other neurons := train idx
        kf = KFold(n=n_e, n_folds=k)
        for idx_out, idx_in in kf:  # idx_out holds all other neurons; idx_in holds all cluster neurons
            # connect current cluster to itself
            connections.connect_random(
                all_neurons[idx_in[0] : idx_in[-1]],
                all_neurons[idx_in[0] : idx_in[-1]],
                sparseness=p_in,
                weight=wee_cluster,
            )
            # connect current cluster to other neurons
            connections.connect_random(
                all_neurons[idx_in[0] : idx_in[-1]], all_neurons[idx_out[0] : idx_out[-1]], sparseness=p_out, weight=wee
            )

        # connect all excitatory to all inhibitory, irrespective of clustering
        connections.connect_random(all_neurons[0:n_e], all_neurons[n_e : (n_e + n_i)], sparseness=p_ie, weight=wie)
        # connect all inhibitory to all excitatory
        connections.connect_random(all_neurons[n_e : (n_e + n_i)], all_neurons[0:n_e], sparseness=p_ei, weight=wei)
        # connect all inhibitory to all inhibitory
        connections.connect_random(
            all_neurons[n_e : (n_e + n_i)], all_neurons[n_e : (n_e + n_i)], sparseness=p_ii, weight=wii
        )

        # set up spike monitors
        spike_mon_e = SpikeMonitor(neurons_e)
        spike_mon_i = SpikeMonitor(neurons_i)
        # set up network with monitors
        network = Network(all_neurons, connections, spike_mon_e, spike_mon_i)

        # run this network for some number of trials, every time with
        for trial in range(trials):
            # different initial values
            all_neurons.V = vr + (vt - vr) * np.random.rand(len(all_neurons)) * 1.4

            # Calibration phase
            # run for the first half of the time to let the neurons adapt
            network.run(t / 2)

            # reset monitors to start recording phase
            spike_mon_i.reinit()
            spike_mon_e.reinit()

            # stimulation if duration is given
            # define index variable for the stimulation possibility (is 0 for stimulation time=0)
            t_stim_idx = int(t_stim / (winlen / ms))
            if not (t_stim == 0):
                # Stimulation phase, increase input to subset of clusters
                all_neurons[:400].mu += 0.07 * dv
                network.run(t_stim * ms, report="text")
                # set back to normal
                all_neurons[:400].mu -= 0.07 * dv
                # save data
                all_data[realization, trial, :n_e, :t_stim_idx] = spikes_counter(spike_mon_e, winlen)
                all_data[realization, trial, n_e:, :t_stim_idx] = spikes_counter(spike_mon_i, winlen)
                # reset monitors
                spike_mon_e.reinit()
                spike_mon_i.reinit()
            # run the remaining time of the simulation
            network.run((t / 2) - t_stim * ms, report="text")

            # save results
            all_data[realization, trial, :n_e, t_stim_idx:] = spikes_counter(spike_mon_e, winlen)
            all_data[realization, trial, n_e:, t_stim_idx:] = spikes_counter(spike_mon_i, winlen)

            if verbose:
                plt.ion()
                plt.figure()
                raster_plot(spike_mon_e)
                plt.title("Excitatory neurons")

            spike_mon_e.reinit()
            spike_mon_i.reinit()

    return all_data
Esempio n. 21
0
input_mon = SpikeMonitor(inp_group)
spike_mon = SpikeMonitor(lif_group)
network = Network(lif_group, inp_group, inp_conn, lif_conn,
                  trace_mon, spike_mon, input_mon)
print("Running for %f seconds ..." % (duration))
network.run(duration)
print("Simulation run finished.")
if spike_mon.nspikes == 0:
    print("No spikes were fired by the network. Aborting!")
    sys.exit()
print("Performing Gaussian convolution ...")
t, conv_spikes = sl.tools.spikeconvolve(spike_mon, 5*msecond)
figure("Spike trains")
splt = subplot(311)
title("External inputs")
raster_plot(input_mon)
axis(xmin=0, xmax=duration/msecond)
subplot(312)
title("Network spikes")
raster_plot(spike_mon)
axis(xmin=0, xmax=duration/msecond)
subplot(313)
plot(t, conv_spikes)
axis(xmin=0, xmax=float(duration))
scatter(t[np.argmax(conv_spikes)], max(conv_spikes), s=10)
#show(block=False)
print("Network synchrony peaked at t = %f s" % (t[np.argmax(conv_spikes)]))

# let's run NPSS on all neurons and see what we get
print("Calculating NPSS ...")
npss = []
Esempio n. 22
0
    def run(self):
        #------------------------------------------------------------------------------ 
        # run the simulation and set inputs
        #------------------------------------------------------------------------------ 
        start = time.time()
        previousSpikeCount = np.zeros((self.nE,len(self.populationNames)))
        currentSpikeCount = np.zeros((self.nE,len(self.populationNames)))
        
        if self.recordSpikes:
            b.figure()
            b.ion()
            b.subplot(411)
            b.raster_plot(self.spikeMonitors['Ae'], refresh=1000*b.ms, showlast=1000*b.ms)
            b.subplot(412)
            b.raster_plot(self.spikeMonitors['Be'], refresh=1000*b.ms, showlast=1000*b.ms)
            b.subplot(413)
            b.raster_plot(self.spikeMonitors['Ce'], refresh=1000*b.ms, showlast=1000*b.ms)
            b.subplot(414)
            b.raster_plot(self.spikeMonitors['He'], refresh=1000*b.ms, showlast=1000*b.ms)
        
#         realTimeMonitor = None
#         realTimeMonitor = rltmMon.RealtimeConnectionMonitor(self.connections['HeAe'], cmap=cm.get_cmap('gist_rainbow'), 
#                                                             wmin=0, wmax=self.wmaxEE, clock=Clock(1000*b.ms))
        
        for j in xrange(int(self.numExamples)):            
            if self.restingTime or j==0:
                for i,name in enumerate(self.inputPopulationNames):
                    rates = np.ones(self.nE)  * 0
                    self.inputGroups[name+'e'].rate = rates
                self.net.run(self.restingTime)#, report='text')
                
            if j%self.normalization_interval == 0:
                self.normalizeWeights()
                
            print 'set new rates of the inputs'
            self.setNewInput(self,j)
                    
                    
            print 'run number:', j+1, 'of', int(self.numExamples)
            self.net.run(self.singleExampleTime)#, report='text')
            for i,name in enumerate(self.populationNames):
                name += 'e'
                currentSpikeCount[:,i] = np.asarray(self.spikeCounters[name].count[:]) - previousSpikeCount[:,i]
            #     print currentSpikeCount,  np.asarray(spikeCounters['Ce'].count[:]), previousSpikeCount
                previousSpikeCount[:,i] = np.copy(self.spikeCounters[name].count[:])
                self.resultMonitor[j,i] = self.computePopVector(currentSpikeCount[:,i])
                print name, 'pop. activity: ', self.resultMonitor[j,i], ', spikecount:', sum(currentSpikeCount[:,i])
            
            for i,name in enumerate(self.inputPopulationNames):
                print name, 'pop. activity: ', (self.popValues[j,i])
                
                    
            if not self.testMode:
                if self.numExamples <= 1000:
                    if j%100==0 and not j==0:
                        self.saveConnections(str(j))
                else:
                    if j%10000==0 and not j==0:
                        self.saveConnections(str(j))
            
        end = time.time()
        print 'time needed to simulate:', end - start
        
        
        #------------------------------------------------------------------------------ 
        # save results
        #------------------------------------------------------------------------------ 
        print 'save results'
        
        if self.testMode:
            np.savetxt(self.dataPath + 'activity/resultPopVecs' + str(self.numExamples) + '.txt', self.resultMonitor)
            np.savetxt(self.dataPath + 'activity/spikeCount' + str(self.gaussian_peak_low) + '.txt', 
                       self.spikeCounters['Ae'].count[:]/(self.singleExampleTime*int(self.numExamples)))
            np.savetxt(self.dataPath + 'activity/inputSpikeCount' + str(self.gaussian_peak_low) + '.txt', 
                       self.spikeCounters['Xe'].count[:]/(self.singleExampleTime*int(self.numExamples)))
            np.savetxt(self.dataPath + 'activity/popVecs' + str(self.numExamples) + '.txt', self.popValues)
        else:
            self.saveConnections(str(j))
            self.normalizeWeights()
            self.saveConnections()
Esempio n. 23
0
def build_network():
    global fig_num, assignments

    neuron_groups['e'] = b.NeuronGroup(n_e_total,
                                       neuron_eqs_e,
                                       threshold=v_thresh_e,
                                       refractory=refrac_e,
                                       reset=scr_e,
                                       compile=True,
                                       freeze=True)
    neuron_groups['i'] = b.NeuronGroup(n_e_total,
                                       neuron_eqs_i,
                                       threshold=v_thresh_i,
                                       refractory=refrac_i,
                                       reset=v_reset_i,
                                       compile=True,
                                       freeze=True)

    for name in population_names:
        print '...Creating neuron group:', name

        # get a subgroup of size 'n_e' from all exc
        neuron_groups[name + 'e'] = neuron_groups['e'].subgroup(conv_features *
                                                                n_e)
        # get a subgroup of size 'n_i' from the inhibitory layer
        neuron_groups[name + 'i'] = neuron_groups['i'].subgroup(conv_features *
                                                                n_e)

        # start the membrane potentials of these groups 40mV below their resting potentials
        neuron_groups[name + 'e'].v = v_rest_e - 40. * b.mV
        neuron_groups[name + 'i'].v = v_rest_i - 40. * b.mV

    print '...Creating recurrent connections'

    for name in population_names:
        # if we're in test mode / using some stored weights
        if test_mode:
            # load up adaptive threshold parameters
            if save_best_model:
                neuron_groups['e'].theta = np.load(
                    os.path.join(best_weights_dir,
                                 '_'.join(['theta_A', ending + '_best.npy'])))
            else:
                neuron_groups['e'].theta = np.load(
                    os.path.join(end_weights_dir,
                                 '_'.join(['theta_A', ending + '_end.npy'])))
        else:
            # otherwise, set the adaptive additive threshold parameter at 20mV
            neuron_groups['e'].theta = np.ones((n_e_total)) * 20.0 * b.mV

        for conn_type in recurrent_conn_names:
            if conn_type == 'ei':
                # create connection name (composed of population and connection types)
                conn_name = name + conn_type[0] + name + conn_type[1]
                # create a connection from the first group in conn_name with the second group
                connections[conn_name] = b.Connection(
                    neuron_groups[conn_name[0:2]],
                    neuron_groups[conn_name[2:4]],
                    structure='sparse',
                    state='g' + conn_type[0])

                # instantiate the created connection
                for feature in xrange(conv_features):
                    for n in xrange(n_e):
                        connections[conn_name][feature * n_e + n,
                                               feature * n_e + n] = 10.4

            elif conn_type == 'ie':
                # create connection name (composed of population and connections types)
                conn_name = name + conn_type[0] + name + conn_type[
                    1] + '_' + ending
                # create a connection from the first group in conn_name with the second group
                connections[conn_name] = b.Connection(
                    neuron_groups[conn_name[0:2]],
                    neuron_groups[conn_name[2:4]],
                    structure='sparse',
                    state='g' + conn_type[0])
                # instantiate the created connection with the 'weightMatrix' loaded from file
                for feature in xrange(conv_features):
                    for other_feature in xrange(conv_features):
                        if feature != other_feature:
                            for n in xrange(n_e):
                                connections[conn_name][feature * n_e + n,
                                                       other_feature * n_e +
                                                       n] = 17.4

        print '...Creating monitors for:', name

        # spike rate monitors for excitatory and inhibitory neuron populations
        rate_monitors[name + 'e'] = b.PopulationRateMonitor(
            neuron_groups[name + 'e'],
            bin=(single_example_time + resting_time) / b.second)
        rate_monitors[name + 'i'] = b.PopulationRateMonitor(
            neuron_groups[name + 'i'],
            bin=(single_example_time + resting_time) / b.second)
        spike_counters[name + 'e'] = b.SpikeCounter(neuron_groups[name + 'e'])

        # record neuron population spikes if specified
        if record_spikes or plot:
            spike_monitors[name + 'e'] = b.SpikeMonitor(neuron_groups[name +
                                                                      'e'])
            spike_monitors[name + 'i'] = b.SpikeMonitor(neuron_groups[name +
                                                                      'i'])

    if record_spikes and plot:
        b.figure(fig_num, figsize=(8, 6))

        fig_num += 1

        b.ion()
        b.subplot(211)
        b.raster_plot(spike_monitors['Ae'],
                      refresh=1000 * b.ms,
                      showlast=1000 * b.ms,
                      title='Excitatory spikes per neuron')
        b.subplot(212)
        b.raster_plot(spike_monitors['Ai'],
                      refresh=1000 * b.ms,
                      showlast=1000 * b.ms,
                      title='Inhibitory spikes per neuron')
        b.tight_layout()

    # creating Poission spike train from input image (784 vector, 28x28 image)
    for name in input_population_names:
        input_groups[name + 'e'] = b.PoissonGroup(n_input, 0)
        rate_monitors[name + 'e'] = b.PopulationRateMonitor(
            input_groups[name + 'e'],
            bin=(single_example_time + resting_time) / b.second)

    # creating connections from input Poisson spike train to excitatory neuron population(s)
    for name in input_connection_names:
        print '\n...Creating connections between', name[0], 'and', name[1]

        # for each of the input connection types (in this case, excitatory -> excitatory)
        for conn_type in input_conn_names:
            # saved connection name
            conn_name = name[0] + conn_type[0] + name[1] + conn_type[1]

            # get weight matrix depending on training or test phase
            if test_mode:
                if save_best_model:
                    weight_matrix = np.load(
                        os.path.join(
                            best_weights_dir,
                            '_'.join([conn_name, ending + '_best.npy'])))
                else:
                    weight_matrix = np.load(
                        os.path.join(
                            end_weights_dir,
                            '_'.join([conn_name, ending + '_end.npy'])))

            # create connections from the windows of the input group to the neuron population
            input_connections[conn_name] = b.Connection(input_groups['Xe'], neuron_groups[name[1] + conn_type[1]], \
                structure='sparse', state='g' + conn_type[0], delay=True, max_delay=delay[conn_type][1])

            if test_mode:
                for feature in xrange(conv_features):
                    for n in xrange(n_e):
                        for idx in xrange(conv_size**2):
                            input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = \
                                    weight_matrix[convolution_locations[n][idx], feature * n_e + n]
            else:
                for feature in xrange(conv_features):
                    for n in xrange(n_e):
                        for idx in xrange(conv_size**2):
                            input_connections[conn_name][
                                convolution_locations[n][idx],
                                feature * n_e + n] = (b.random() + 0.01) * 0.3

            if test_mode:
                if plot:
                    plot_weights_and_assignments(assignments)
                    fig_num += 1

        # if excitatory -> excitatory STDP is specified, add it here (input to excitatory populations)
        if not test_mode:
            print '...Creating STDP for connection', name

            # STDP connection name
            conn_name = name[0] + conn_type[0] + name[1] + conn_type[1]
            # create the STDP object
            stdp_methods[conn_name] = b.STDP(input_connections[conn_name], eqs=eqs_stdp_ee, \
                pre=eqs_stdp_pre_ee, post=eqs_stdp_post_ee, wmin=0., wmax=wmax_ee)

    print '\n'
Esempio n. 24
0
    def plotResults(self):
        #------------------------------------------------------------------------------ 
        # plot results
        #------------------------------------------------------------------------------ 
        if self.rateMonitors:
            b.figure()
            for i, name in enumerate(self.rateMonitors):
                b.subplot(len(self.rateMonitors), 1, i)
                b.plot(self.rateMonitors[name].times/b.second, self.rateMonitors[name].rate, '.')
                b.title('rates of population ' + name)
            
        if self.spikeMonitors:
            b.figure()
            for i, name in enumerate(self.spikeMonitors):
                b.subplot(len(self.spikeMonitors), 1, i)
                b.raster_plot(self.spikeMonitors[name])
                b.title('spikes of population ' + name)
                if name=='Ce':
                    timePoints = np.linspace(0+(self.singleExampleTime+self.restingTime)/(2*b.second)*1000, 
                                             self.runtime/b.second*1000-(self.singleExampleTime+self.restingTime)/(2*b.second)*1000, 
                                             self.numExamples)
                    b.plot(timePoints, self.resultMonitor[:,0]*self.nE, 'g')
                    b.plot(timePoints, self.resultMonitor[:,1]*self.nE, 'r')
        
        if self.stateMonitors:
            b.figure()
            for i, name in enumerate(self.stateMonitors):
                b.plot(self.stateMonitors[name].times/b.second, self.stateMonitors[name]['v'][0], label = name + ' v 0')
                b.legend()
                b.title('membrane voltages of population ' + name)
            
        
            b.figure()
            for i, name in enumerate(self.stateMonitors):
                b.plot(self.stateMonitors[name].times/b.second, self.stateMonitors[name]['ge'][0], label = name + ' v 0')
                b.legend()
                b.title('conductances of population ' + name)
        
        plotWeights = [
        #                 'XeAe', 
        #                 'XeAi', 
        #                 'AeAe', 
        #                 'AeAi', 
        #                 'AiAe', 
        #                 'AiAi', 
        #                'BeBe', 
        #                'BeBi', 
        #                'BiBe', 
        #                'BiBi', 
        #                'CeCe', 
        #                'CeCi', 
                        'CiCe', 
        #                'CiCi', 
        #                'HeHe', 
        #                'HeHi', 
        #                'HiHe', 
        #                'HiHi', 
                        'AeHe',
        #                 'BeHe',
        #                 'CeHe',
                        'HeAe',
        #                 'HeBe',
        #                 'HeCe',
                       ]
        
        for name in plotWeights:
            b.figure()
#             my_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('own2',['#f4f4f4', '#000000'])
#             my_cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list('own2',['#000000', '#f4f4f4'])
            if name[1]=='e':
                nSrc = self.nE
            else:
                nSrc = self.nI
            if name[3]=='e':
                nTgt = self.nE
            else:
                nTgt = self.nI
                
            w_post = np.zeros((nSrc, nTgt))
            connMatrix = self.connections[name][:]
            for i in xrange(nSrc):
                w_post[i, connMatrix.rowj[i]] = connMatrix.rowdata[i]
            im2 = b.imshow(w_post, interpolation="nearest", vmin = 0, cmap=cm.get_cmap('gist_ncar')) #my_cmap
            b.colorbar(im2)
            b.title('weights of connection' + name)
            
            
        if self.plotError:
            error = np.abs(self.resultMonitor[:,1] - self.resultMonitor[:,0])
            correctionIdxs = np.where(error > 0.5)[0]
            correctedError = [1 - error[i] if (i in correctionIdxs) else error[i] for i in xrange(len(error))]
            correctedErrorSum = np.average(correctedError)
                 
            b.figure()
            b.scatter(self.resultMonitor[:,1], self.resultMonitor[:,0], c=range(len(error)), cmap=cm.get_cmap('gray'))
            b.title('Error: ' + str(correctedErrorSum))
            b.xlabel('Desired activity')
            b.ylabel('Population activity')
             
            b.figure()
            error = np.abs(self.resultMonitor[:,1] - self.resultMonitor[:,0])
            correctionIdxs = np.where(error > 0.5)[0]
            correctedError = [1 - error[i] if (i in correctionIdxs) else error[i] for i in xrange(len(error))]
            correctedErrorSum = np.average(correctedError)
            b.scatter(self.resultMonitor[:,1], self.resultMonitor[:,0], c=self.resultMonitor[:,2], cmap=cm.get_cmap('gray'))
            b.title('Error: ' + str(correctedErrorSum))
            b.xlabel('Desired activity')
            b.ylabel('Population activity')
        
        b.ioff()
        b.show()
class ConvolutionalSpikingNN(object):
	'''
	Object which represents a convolutional spiking neural network.
	'''

	def __init__(mode, connectivity, weight_dependence, post_pre, conv_size, conv_stride, conv_features, weight_sharing, lattice_structure, random_inhibition_prob, top_percent):
		'''
		Network initialization.
		'''

		# setting input parameters
		this.mode = mode
		this.connectivity = connectivity
		this.weight_dependence = weight_dependence
		this.post_pre = post_pre
		this.conv_size = conv_size
		this.conv_features = conv_features
		this.weight_sharing = weight_sharing
		this.lattice_structure = lattice_structure
		this.random_inhibition_prob = random_inhibition_prob

		# load training or testing data
		if mode == 'train':
		    start = time.time()
		    this.data = get_labeled_data(MNIST_data_path + 'training')
		    end = time.time()
		    print 'time needed to load training set:', end - start
		else:
		    start = time.time()
		    this.data = get_labeled_data(MNIST_data_path + 'testing', bTrain = False)
		    end = time.time()
		    print 'time needed to load test set:', end - start

		# set parameters for simulation based on train / test mode
		if test_mode:
			weight_path = top_level_path + 'weights/conv_patch_connectivity_weights/'
			this.num_examples = 10000 * 1
			this.do_plot_performance = False
			ee_STDP_on = False
		else:
			weight_path = top_level_path + 'random/conv_patch_connectivity_random/'
			this.num_examples = 60000 * 1
			this.do_plot_performance = True
			ee_STDP_on = True

		# plotting or not
		do_plot = True

		# number of inputs to the network
		this.n_input = 784
		this.n_input_sqrt = int(math.sqrt(n_input))

		# number of neurons parameters
		this.n_e = ((n_input_sqrt - conv_size) / conv_stride + 1) ** 2
		this.n_e_total = n_e * conv_features
		this.n_e_sqrt = int(math.sqrt(n_e))
		this.n_i = n_e
		this.conv_features_sqrt = int(math.sqrt(conv_features))

		# time (in seconds) per data example presentation and rest period in between, used to calculate total runtime
		this.single_example_time = 0.35 * b.second
		this.resting_time = 0.15 * b.second
		runtime = num_examples * (single_example_time + resting_time)

		# set the update interval
		if test_mode:
			this.update_interval = num_examples
		else:
			this.update_interval = 100

		# rest potential parameters, reset potential parameters, threshold potential parameters, and refractory periods
		v_rest_e, v_rest_i = -65. * b.mV, -60. * b.mV
		v_reset_e, v_reset_i = -65. * b.mV, -45. * b.mV
		v_thresh_e, v_thresh_i = -52. * b.mV, -40. * b.mV
		refrac_e, refrac_i = 5. * b.ms, 2. * b.ms

		# dictionaries for weights and delays
		weight, delay = {}, {}

		# populations, connections, saved connections, etc.
		input_population_names = [ 'X' ]
		population_names = [ 'A' ]
		input_connection_names = [ 'XA' ]
		save_conns = [ 'XeAe', 'AeAe' ]

		# weird and bad names for variables, I think
		input_conn_names = [ 'ee_input' ]
		recurrent_conn_names = [ 'ei', 'ie', 'ee' ]
		
		# setting weight, delay, and intensity parameters
		weight['ee_input'] = (conv_size ** 2) * 0.175
		delay['ee_input'] = (0 * b.ms, 10 * b.ms)
		delay['ei_input'] = (0 * b.ms, 5 * b.ms)
		input_intensity = start_input_intensity = 2.0

		# time constants, learning rates, max weights, weight dependence, etc.
		tc_pre_ee, tc_post_ee = 20 * b.ms, 20 * b.ms
		nu_ee_pre, nu_ee_post = 0.0001, 0.01
		wmax_ee = 1.0
		exp_ee_post = exp_ee_pre = 0.2
		w_mu_pre, w_mu_post = 0.2, 0.2

		# setting up differential equations (depending on train / test mode)
		if test_mode:
			scr_e = 'v = v_reset_e; timer = 0*ms'
		else:
			tc_theta = 1e7 * b.ms
			theta_plus_e = 0.05 * b.mV
			scr_e = 'v = v_reset_e; theta += theta_plus_e; timer = 0*ms'

		offset = 20.0 * b.mV
		v_thresh_e = '(v>(theta - offset + ' + str(v_thresh_e) + ')) * (timer>refrac_e)'

		# equations for neurons
		neuron_eqs_e = '''
				dv/dt = ((v_rest_e - v) + (I_synE + I_synI) / nS) / (100 * ms)  : volt
				I_synE = ge * nS *         -v                           : amp
				I_synI = gi * nS * (-100.*mV-v)                          : amp
				dge/dt = -ge/(1.0*ms)                                   : 1
				dgi/dt = -gi/(2.0*ms)                                  : 1
				'''
		if test_mode:
			neuron_eqs_e += '\n  theta      :volt'
		else:
			neuron_eqs_e += '\n  dtheta/dt = -theta / (tc_theta)  : volt'

		neuron_eqs_e += '\n  dtimer/dt = 100.0 : ms'

		neuron_eqs_i = '''
				dv/dt = ((v_rest_i - v) + (I_synE + I_synI) / nS) / (10*ms)  : volt
				I_synE = ge * nS *         -v                           : amp
				I_synI = gi * nS * (-85.*mV-v)                          : amp
				dge/dt = -ge/(1.0*ms)                                   : 1
				dgi/dt = -gi/(2.0*ms)                                  : 1
				'''

		# creating dictionaries for various objects
		this.neuron_groups = {}
		this.input_groups = {}
		this.connections = {}
		this.input_connections = {}
		this.stdp_methods = {}
		this.rate_monitors = {}
		this.spike_monitors = {}
		this.spike_counters = {}

		# creating excitatory, inhibitory populations
		this.neuron_groups['e'] = b.NeuronGroup(n_e_total, neuron_eqs_e, threshold=v_thresh_e, refractory=refrac_e, reset=scr_e, compile=True, freeze=True)
		this.neuron_groups['i'] = b.NeuronGroup(n_e_total, neuron_eqs_i, threshold=v_thresh_i, refractory=refrac_i, reset=v_reset_i, compile=True, freeze=True)

		# creating subpopulations of excitatory, inhibitory neurons
		for name in population_names:
			print '...creating neuron group:', name

			# get a subgroup of size 'n_e' from all exc
			neuron_groups[name + 'e'] = neuron_groups['e'].subgroup(conv_features * n_e)
			# get a subgroup of size 'n_i' from the inhibitory layer
			neuron_groups[name + 'i'] = neuron_groups['i'].subgroup(conv_features * n_e)

			# start the membrane potentials of these groups 40mV below their resting potentials
			neuron_groups[name + 'e'].v = v_rest_e - 40. * b.mV
			neuron_groups[name + 'i'].v = v_rest_i - 40. * b.mV

		print '...creating recurrent connections'

		for name in population_names:
			# if we're in test mode / using some stored weights
			if mode == 'test' or weight_path[-8:] == 'weights/conv_patch_connectivity_weights/':
				# load up adaptive threshold parameters
				neuron_groups['e'].theta = np.load(weight_path + 'theta_A' + '_' + ending +'.npy')
			else:
				# otherwise, set the adaptive additive threshold parameter at 20mV
				neuron_groups['e'].theta = np.ones((n_e_total)) * 20.0 * b.mV

			for conn_type in recurrent_conn_names:
				if conn_type == 'ei':
					# create connection name (composed of population and connection types)
					conn_name = name + conn_type[0] + name + conn_type[1]
					# create a connection from the first group in conn_name with the second group
					connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0])
					# instantiate the created connection
					for feature in xrange(conv_features):
						for n in xrange(n_e):
							connections[conn_name][feature * n_e + n, feature * n_e + n] = 10.4

				elif conn_type == 'ie':
					# create connection name (composed of population and connection types)
					conn_name = name + conn_type[0] + name + conn_type[1]
					# create a connection from the first group in conn_name with the second group
					connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0])
					# instantiate the created connection
					for feature in xrange(conv_features):
						for other_feature in xrange(conv_features):
							if feature != other_feature:
								for n in xrange(n_e):
									connections[conn_name][feature * n_e + n, other_feature * n_e + n] = 17.4

					if random_inhibition_prob != 0.0:
						for feature in xrange(conv_features):
							for other_feature in xrange(conv_features):
								for n_this in xrange(n_e):
									for n_other in xrange(n_e):
										if n_this != n_other:
											if b.random() < random_inhibition_prob:
												connections[conn_name][feature * n_e + n_this, other_feature * n_e + n_other] = 17.4

				elif conn_type == 'ee':
					# create connection name (composed of population and connection types)
					conn_name = name + conn_type[0] + name + conn_type[1]
					# get weights from file if we are in test mode
					if mode == 'test':
						weight_matrix = get_matrix_from_file(weight_path + conn_name + '_' + ending + '.npy', conv_features * n_e, conv_features * n_e)
					# create a connection from the first group in conn_name with the second group
					connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0])
					# instantiate the created connection
					if connectivity == 'all':
						for feature in xrange(conv_features):
							for other_feature in xrange(conv_features):
								if feature != other_feature:
									for this_n in xrange(n_e):
										for other_n in xrange(n_e):
											if is_lattice_connection(n_e_sqrt, this_n, other_n):
												if mode == 'test':
													connections[conn_name][feature * n_e + this_n, other_feature * n_e + other_n] = weight_matrix[feature * n_e + this_n, other_feature * n_e + other_n]
												else:
													connections[conn_name][feature * n_e + this_n, other_feature * n_e + other_n] = (b.random() + 0.01) * 0.3

					elif connectivity == 'pairs':
						for feature in xrange(conv_features):
							if feature % 2 == 0:
								for this_n in xrange(n_e):
									for other_n in xrange(n_e):
										if is_lattice_connection(n_e_sqrt, this_n, other_n):
											if mode == 'test':
												connections[conn_name][feature * n_e + this_n, (feature + 1) * n_e + other_n] = weight_matrix[feature * n_e + this_n, (feature + 1) * n_e + other_n]
											else:
												connections[conn_name][feature * n_e + this_n, (feature + 1) * n_e + other_n] = (b.random() + 0.01) * 0.3
							elif feature % 2 == 1:
								for this_n in xrange(n_e):
									for other_n in xrange(n_e):
										if is_lattimode == 'test'ce_connection(n_e_sqrt, this_n, other_n):
											if mode == 'test':
												connections[conn_name][feature * n_e + this_n, (feature - 1) * n_e + other_n] = weight_matrix[feature * n_e + this_n, (feature - 1) * n_e + other_n]
											else:
												connections[conn_name][feature * n_e + this_n, (feature - 1) * n_e + other_n] = (b.random() + 0.01) * 0.3

					elif connectivity == 'none':
						pass

			# if STDP from excitatory -> excitatory is on and this connection is excitatory -> excitatory
			if ee_STDP_on and 'ee' in recurrent_conn_names:
				stdp_methods[name + 'e' + name + 'e'] = b.STDP(connections[name + 'e' + name + 'e'], eqs=eqs_stdp_ee, pre=eqs_stdp_pre_ee, post=eqs_stdp_post_ee, wmin=0., wmax=wmax_ee)

			print '...creating monitors for:', name

			# spike rate monitors for excitatory and inhibitory neuron populations
			rate_monitors[name + 'e'] = b.PopulationRateMonitor(neuron_groups[name + 'e'], bin=(single_example_time + resting_time) / b.second)
			rate_monitors[name + 'i'] = b.PopulationRateMonitor(neuron_groups[name + 'i'], bin=(single_example_time + resting_time) / b.second)
			spike_counters[name + 'e'] = b.SpikeCounter(neuron_groups[name + 'e'])

			# record neuron population spikes if specified
			spike_monitors[name + 'e'] = b.SpikeMonitor(neuron_groups[name + 'e'])
			spike_monitors[name + 'i'] = b.SpikeMonitor(neuron_groups[name + 'i'])

		if do_plot:
			b.figure(fig_num)
			fig_num += 1
			b.ion()
			b.subplot(211)
			b.raster_plot(spike_monitors['Ae'], refresh=1000 * b.ms, showlast=1000 * b.ms)
			b.subplot(212)
			b.raster_plot(spike_monitors['Ai'], refresh=1000 * b.ms, showlast=1000 * b.ms)

		# creating lattice locations for each patch
		if connectivity == 'all':
			lattice_locations = {}
			for this_n in xrange(conv_features * n_e):
				lattice_locations[this_n] = [ other_n for other_n in xrange(conv_features * n_e) if is_lattice_connection(n_e_sqrt, this_n % n_e, other_n % n_e) ]
		elif connectivity == 'pairs':
			lattice_locations = {}
			for this_n in xrange(conv_features * n_e):
				lattice_locations[this_n] = []
				for other_n in xrange(conv_features * n_e):
					if this_n // n_e % 2 == 0:
						if is_lattice_connection(n_e_sqrt, this_n % n_e, other_n % n_e) and other_n // n_e == this_n // n_e + 1:
							lattice_locations[this_n].append(other_n)
					elif this_n // n_e % 2 == 1:
						if is_lattice_connection(n_e_sqrt, this_n % n_e, other_n % n_e) and other_n // n_e == this_n // n_e - 1:
							lattice_locations[this_n].append(other_n)
		elif connectivity == 'none':
			lattice_locations = {}

		# setting up parameters for weight normalization between patches
		num_lattice_connections = sum([ len(value) for value in lattice_locations.values() ])
		weight['ee_recurr'] = (num_lattice_connections / conv_features) * 0.15

		# creating Poission spike train from input image (784 vector, 28x28 image)
		for name in input_population_names:
			input_groups[name + 'e'] = b.PoissonGroup(n_input, 0)
			rate_monitors[name + 'e'] = b.PopulationRateMonitor(input_groups[name + 'e'], bin=(single_example_time + resting_time) / b.second)

		# creating connections from input Poisson spike train to convolution patch populations
		for name in input_connection_names:
			print '\n...creating connections between', name[0], 'and', name[1]
			
			# for each of the input connection types (in this case, excitatory -> excitatory)
			for conn_type in input_conn_names:
				# saved connection name
				conn_name = name[0] + conn_type[0] + name[1] + conn_type[1]

				# get weight matrix depending on training or test phase
				if mode == 'test':
					weight_matrix = get_matrix_from_file(weight_path + conn_name + '_' + ending + '.npy', n_input, conv_features * n_e)

				# create connections from the windows of the input group to the neuron population
				input_connections[conn_name] = b.Connection(input_groups['Xe'], neuron_groups[name[1] + conn_type[1]], structure='sparse', state='g' + conn_type[0], delay=True, max_delay=delay[conn_type][1])
				
				if mode == 'test':
					for feature in xrange(conv_features):
						for n in xrange(n_e):
							for idx in xrange(conv_size ** 2):
								input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = weight_matrix[convolution_locations[n][idx], feature * n_e + n]
				else:
					for feature in xrange(conv_features):
						for n in xrange(n_e):
							for idx in xrange(conv_size ** 2):
								input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = (b.random() + 0.01) * 0.3

			# if excitatory -> excitatory STDP is specified, add it here (input to excitatory populations)
			if ee_STDP_on:
				print '...creating STDP for connection', name
				
				# STDP connection name
				conn_name = name[0] + conn_type[0] + name[1] + conn_type[1]
				# create the STDP object
				stdp_methods[conn_name] = b.STDP(input_connections[conn_name], eqs=eqs_stdp_ee, pre=eqs_stdp_pre_ee, post=eqs_stdp_post_ee, wmin=0., wmax=wmax_ee)

		print '\n'
Esempio n. 26
0
    def plot(self):

        # Spike raster plots
        if self.record_spikes:
            num_plots=self.network_params.num_groups+1
            figure()
            for i in range(self.network_params.num_groups):
                subplot(num_plots,1,i+1)
                raster_plot(self.monitors['excitatory_spike_%d' % i],newfigure=False)
            subplot(num_plots,1,num_plots)
            raster_plot(self.monitors['inhibitory_spike'],newfigure=False)

        # Network firing rate plots
        if self.record_firing_rate:

            e_rate_0=self.monitors['excitatory_rate_0'].smooth_rate(width=5*ms)/hertz
            e_rate_1=self.monitors['excitatory_rate_1'].smooth_rate(width=5*ms)/hertz
            i_rate=self.monitors['inhibitory_rate'].smooth_rate(width=5*ms)/hertz
            plot_network_firing_rates(np.array([e_rate_0, e_rate_1]), i_rate, self.sim_params, self.network_params)

        # Input firing rate plots
        if self.record_inputs:
            figure()
            ax=subplot(111)
            max_rate=0
            task_rates=[]
            for i in range(self.network_params.num_groups):
                task_monitor=self.monitors['task_rate_%d' % i]
                task_rate=task_monitor.smooth_rate(width=5*ms,filter='gaussian')/hertz
                if np.max(task_rate)>max_rate:
                    max_rate=np.max(task_rate)
                task_rates.append(task_rate)

            rect=Rectangle((0,0),(self.sim_params.stim_end_time-self.sim_params.stim_start_time)/ms, max_rate+5,
                alpha=0.25, facecolor='yellow', edgecolor='none')
            ax.add_patch(rect)
            #            ax.plot(self.monitors['background_rate'].times/ms,
            #                self.monitors['background_rate'].smooth_rate(width=5*ms)/hertz)
            for i in range(self.network_params.num_groups):
                ax.plot((np.array(range(len(task_rates[i])))*self.sim_params.dt)/ms-self.sim_params.stim_start_time/ms, task_rates[i])
            ylim(0,90)
            ylabel('Firing rate (Hz)')
            xlabel('Time (ms)')

        # Network state plots
        if self.record_neuron_state:
            network_monitor=self.monitors['network']
            max_conductances=[]
            for neuron_idx in self.record_idx:
                max_conductances.append(np.max(network_monitor['g_ampa_r'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_ampa_x'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_ampa_b'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_nmda'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_gaba_a'][neuron_idx]/nS))
                #max_conductances.append(np.max(self.network_monitor['g_gaba_b'][neuron_idx]/nS))
            max_conductance=np.max(max_conductances)

            fig=figure()
            for i in range(self.network_params.num_groups):
                neuron_idx=self.record_idx[i]
                ax=subplot(int('%d1%d' % (self.network_params.num_groups+1,i+1)))
                title('e%d' % i)
                ax.plot(network_monitor['g_ampa_r'].times/ms, network_monitor['g_ampa_r'][neuron_idx]/nS,
                    label='AMPA-recurrent')
                ax.plot(network_monitor['g_ampa_x'].times/ms, network_monitor['g_ampa_x'][neuron_idx]/nS,
                    label='AMPA-task')
                ax.plot(network_monitor['g_ampa_b'].times/ms, network_monitor['g_ampa_b'][neuron_idx]/nS,
                    label='AMPA-backgrnd')
                ax.plot(network_monitor['g_nmda'].times/ms, network_monitor['g_nmda'][neuron_idx]/nS,
                    label='NMDA')
                ax.plot(network_monitor['g_gaba_a'].times/ms, network_monitor['g_gaba_a'][neuron_idx]/nS,
                    label='GABA_A')
                #ax.plot(network_monitor['g_gaba_b'].times/ms, network_monitor['g_gaba_b'][neuron_idx]/nS,
                #    label='GABA_B')
                ylim(0,max_conductance)
                xlabel('Time (ms)')
                ylabel('Conductance (nS)')
                legend()

            neuron_idx=self.record_idx[self.network_params.num_groups]
            ax=subplot('%d1%d' % (self.network_params.num_groups+1,self.network_params.num_groups+1))
            title('i')
            ax.plot(network_monitor['g_ampa_r'].times/ms, network_monitor['g_ampa_r'][neuron_idx]/nS,
                label='AMPA-recurrent')
            ax.plot(network_monitor['g_ampa_x'].times/ms, network_monitor['g_ampa_x'][neuron_idx]/nS,
                label='AMPA-task')
            ax.plot(network_monitor['g_ampa_b'].times/ms, network_monitor['g_ampa_b'][neuron_idx]/nS,
                label='AMPA-backgrnd')
            ax.plot(network_monitor['g_nmda'].times/ms, network_monitor['g_nmda'][neuron_idx]/nS,
                label='NMDA')
            ax.plot(network_monitor['g_gaba_a'].times/ms, network_monitor['g_gaba_a'][neuron_idx]/nS,
                label='GABA_A')
            #ax.plot(network_monitor['g_gaba_b'].times/ms, network_monitor['g_gaba_b'][neuron_idx]/nS,
            #    label='GABA_B')
            ylim(0,max_conductance)
            xlabel('Time (ms)')
            ylabel('Conductance (nS)')
            legend()

            min_currents=[]
            max_currents=[]
            for neuron_idx in self.record_idx:
                max_currents.append(np.max(network_monitor['I_ampa_r'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_ampa_x'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_ampa_b'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_nmda'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_gaba_a'][neuron_idx]/nS))
                #max_currents.append(np.max(network_monitor['I_gaba_b'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_ampa_r'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_ampa_x'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_ampa_b'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_nmda'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_gaba_a'][neuron_idx]/nS))
                #min_currents.append(np.min(network_monitor['I_gaba_b'][neuron_idx]/nS))
            max_current=np.max(max_currents)
            min_current=np.min(min_currents)

            fig=figure()
            for i in range(self.network_params.num_groups):
                ax=subplot(int('%d1%d' % (self.network_params.num_groups+1,i+1)))
                neuron_idx=self.record_idx[i]
                title('e%d' % i)
                ax.plot(network_monitor['I_ampa_r'].times/ms, network_monitor['I_ampa_r'][neuron_idx]/nA,
                    label='AMPA-recurrent')
                ax.plot(network_monitor['I_ampa_x'].times/ms, network_monitor['I_ampa_x'][neuron_idx]/nA,
                    label='AMPA-task')
                ax.plot(network_monitor['I_ampa_b'].times/ms, network_monitor['I_ampa_b'][neuron_idx]/nA,
                    label='AMPA-backgrnd')
                ax.plot(network_monitor['I_nmda'].times/ms, network_monitor['I_nmda'][neuron_idx]/nA,
                    label='NMDA')
                ax.plot(network_monitor['I_gaba_a'].times/ms, network_monitor['I_gaba_a'][neuron_idx]/nA,
                    label='GABA_A')
                #ax.plot(network_monitor['I_gaba_b'].times/ms, network_monitor['I_gaba_b'][neuron_idx]/nA,
                #    label='GABA_B')
                ylim(min_current,max_current)
                xlabel('Time (ms)')
                ylabel('Current (nA)')
                legend()

            ax=subplot(int('%d1%d' % (self.network_params.num_groups+1,self.network_params.num_groups+1)))
            neuron_idx=self.record_idx[self.network_params.num_groups]
            title('i')
            ax.plot(network_monitor['I_ampa_r'].times/ms, network_monitor['I_ampa_r'][neuron_idx]/nA,
                label='AMPA-recurrent')
            ax.plot(network_monitor['I_ampa_x'].times/ms, network_monitor['I_ampa_x'][neuron_idx]/nA,
                label='AMPA-task')
            ax.plot(network_monitor['I_ampa_b'].times/ms, network_monitor['I_ampa_b'][neuron_idx]/nA,
                label='AMPA-backgrnd')
            ax.plot(network_monitor['I_nmda'].times/ms, network_monitor['I_nmda'][neuron_idx]/nA,
                label='NMDA')
            ax.plot(network_monitor['I_gaba_a'].times/ms, network_monitor['I_gaba_a'][neuron_idx]/nA,
                label='GABA_A')
            #ax.plot(network_monitor['I_gaba_b'].times/ms, network_monitor['I_gaba_b'][neuron_idx]/nA,
            #    label='GABA_B')
            ylim(min_current,max_current)
            xlabel('Time (ms)')
            ylabel('Current (nA)')
            legend()

        # LFP plot
        if self.record_lfp:
            figure()
            ax=subplot(111)
            ax.plot(self.monitors['lfp'].times / ms, self.monitors['lfp'][0]/mA)
            xlabel('Time (ms)')
            ylabel('LFP (mA)')

        # Voxel activity plots
        if self.record_voxel:
            voxel_monitor=self.monitors['voxel']
            voxel_exc_monitor=None
            if 'voxel_exc' in self.monitors:
                voxel_exc_monitor=self.monitors['voxel_exc']
            syn_max=np.max(voxel_monitor['G_total'][0] / nS)
            y_max=np.max(voxel_monitor['y'][0])
            y_min=np.min(voxel_monitor['y'][0])
            figure()
            if voxel_exc_monitor is None:
                ax=subplot(211)
            else:
                ax=subplot(221)
                syn_max=np.max([syn_max, np.max(voxel_exc_monitor['G_total'][0])])
                y_max=np.max([y_max, np.max(voxel_exc_monitor['y'][0])])
                y_min=np.min([y_min, np.min(voxel_exc_monitor['y'][0])])
            ax.plot(voxel_monitor['G_total'].times / ms, voxel_monitor['G_total'][0] / nS)
            xlabel('Time (ms)')
            ylabel('Total Synaptic Activity (nS)')
            ylim(0, syn_max)
            if voxel_exc_monitor is None:
                ax=subplot(212)
            else:
                ax=subplot(222)
            ax.plot(voxel_monitor['y'].times / ms, voxel_monitor['y'][0])
            xlabel('Time (ms)')
            ylabel('BOLD')
            ylim(y_min, y_max)
            if voxel_exc_monitor is not None:
                ax=subplot(223)
                ax.plot(voxel_exc_monitor['G_total'].times / ms, voxel_exc_monitor['G_total'][0] / nS)
                xlabel('Time (ms)')
                ylabel('Total Synaptic Activity (nS)')
                ylim(0, syn_max)
                ax=subplot(224)
                ax.plot(voxel_exc_monitor['y'].times / ms, voxel_exc_monitor['y'][0])
                xlabel('Time (ms)')
                ylabel('BOLD')
                ylim(y_min, y_max)

        if self.record_connections:
            figure()
            ax=subplot(111)
            for mon in self.monitors:
                if mon.startswith('connection_'):
                    conn_name=mon[11:]
                    conns=np.zeros((len(self.monitors[mon].values),1))
                    conn_times=[]
                    for idx, (time, conn_matrix) in enumerate(self.monitors[mon].values):
                        conn_diag=np.diagonal(conn_matrix.todense())
                        mean_w=np.mean(conn_diag)
                        conns[idx,0]=mean_w
                        conn_times.append(time)
                    ax.plot(np.array(conn_times) / ms, conns[:,0]/nS, label=conn_name)
            legend(loc='best')
            xlabel('Time (ms)')
            ylabel('Connection Weight (nS)')
Esempio n. 27
0
# plot results
#------------------------------------------------------------------------------
if rate_monitors:
    b.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(rate_monitors):
        b.subplot(len(rate_monitors), 1, i)
        b.plot(rate_monitors[name].times / b.second, rate_monitors[name].rate,
               '.')
        b.title('Rates of population ' + name)

if spike_monitors:
    b.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(spike_monitors):
        b.subplot(len(spike_monitors), 1, i)
        b.raster_plot(spike_monitors[name])
        b.title('Spikes of population ' + name)

if spike_counters:
    b.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(spike_counters):
        b.subplot(len(spike_counters), 1, i)
        b.plot(spike_counters['Ae'].count[:])
        b.title('Spike count of population ' + name)

plot_2d_input_weights()
b.ioff()
b.show()
Esempio n. 28
0


# Let's run our simulation
network.run(duration, report='text')

#plt.figure()
#plt.plot(state_mon_isyn.times,state_mon_isyn.values[0,:])



# Plot spike raster plots, blue exc neurons, red inh neurons
plt.figure()
gs = gridspec.GridSpec(2, 1, height_ratios=[1, 3])
plt.subplot(gs[0])
raster_plot(spike_mon_i, color='r')
plt.title('Inhibitory neurons')
plt.subplot(gs[1])
raster_plot(spike_mon_e)
plt.title('Excitatory neurons')

# Plot the evolution of the membrane potentials
'''plt.figure()
for irun in range(1,6):
    plt.subplot(6,1,irun)
    if irun < 3:
        mon = state_mon_v_i
        idx = irun-1
        color='r'
    else:
        mon = state_mon_v_e
Esempio n. 29
0
def run_simulation(realizations=1, trials=1, t=3000 * ms, alpha=1, ree=1,
                   k=50, winlen = 50 * ms, verbose=True, t_stim = 0):
    """
    Run the whole simulation with the specified parameters. All model parameter are set in the function.

    Keyword arguments:
    :param realizations: number of repititions of the whole simulation, number of network instances
    :param trials: number of trials for network instance
    :param t: simulation time
    :param alpha: scaling factor for number of neurons in the network
    :param ree: clustering coefficient
    :param k: number of clusters
    :param t_stim : duration of stimulation of a subset of clusters
    :param winlen: length of window in ms
    :param verbose: plotting flag
    :return: numpy matrices with spike times
    """

    # The equations defining our neuron model
    eqs_string = '''
                dV/dt = (mu - V)/tau + x: volt
                dx/dt = -1.0/tau_2*(x - y/tau_1) : volt/second
                dy/dt = -y/tau_1 : volt
                mu : volt
                tau: second
                tau_2: second
                tau_1: second
                '''
    # Model parameters
    n_e = int(4000 * alpha)  # number of exc neurons
    n_i = int(1000 * alpha)  # number of inh neurons
    tau_e = 15 * ms  # membrane time constant (for excitatory synapses)
    tau_i = 10 * ms  # membrane time constant (for inhibitory synapses)
    tau_syn_2_e = 3 * ms  # exc synaptic time constant tau2 in paper
    tau_syn_2_i = 2 * ms  # inh synaptic time constant tau2 in paper
    tau_syn_1 = 1 * ms  # exc/inh synaptic time constant tau1 in paper
    vt = -50 * mV  # firing threshold
    vr = -65 * mV  # reset potential
    dv = vt - vr # delta v
    refrac = 5 * ms  # absolute refractory period

    # scale the weights to ensure same variance in the inputs
    wee = 0.024 * dv * np.sqrt(1. / alpha)
    wie = 0.014 * dv * np.sqrt(1. / alpha)
    wii = -0.057 * dv * np.sqrt(1. / alpha)
    wei = -0.045 * dv * np.sqrt(1. / alpha)

    # Connection probability
    p_ee = 0.2
    p_ii = 0.5
    p_ie = 0.5
    p_ei = 0.5
    
    # determine probs for inside and outside of clusters
    p_in, p_out = get_cluster_connection_probs(ree, k, p_ee)

    mu_min_e, mu_max_e = 1.1, 1.2
    mu_min_i, mu_max_i = 1.0, 1.05

    # increase cluster weights if there are clusters
    wee_cluster = wee if p_in == p_out else 1.9 * wee

    # define numpy array for data storing
    all_data = np.zeros((realizations, trials, n_e+n_i, int(t/winlen)//2))

    for realization in range(realizations):
        # clear workspace to make sure that is a new realization of the network
        clear(True, True)
        reinit()

        # set up new random bias parameter for every type of neuron
        mu_e = vr + np.random.uniform(mu_min_e, mu_max_e, n_e) * dv  # bias for excitatory neurons
        mu_i = vr + np.random.uniform(mu_min_i, mu_max_i, n_i) * dv  # bias for excitatory neurons

        # Let's create an equation object from our string and parameters
        model_eqs = Equations(eqs_string)

        # Let's create 5000 neurons
        all_neurons = NeuronGroup(N=n_e + n_i,
                                  model=model_eqs,
                                  threshold=vt,
                                  reset=vr,
                                  refractory=refrac,
                                  freeze=True,
                                  method='Euler',
                                  compile=True)

        # Divide the neurons into excitatory and inhibitory ones
        neurons_e = all_neurons[0:n_e]
        neurons_i = all_neurons[n_e:n_e + n_i]

        # set the bias
        neurons_e.mu = mu_e
        neurons_i.mu = mu_i
        neurons_e.tau = tau_e
        neurons_i.tau = tau_i
        neurons_e.tau_2 = tau_syn_2_e
        neurons_i.tau_2 = tau_syn_2_i
        all_neurons.tau_1 = tau_syn_1

        # set up connections
        connections = Connection(all_neurons, all_neurons, 'y')

        # do the cluster connection like cross validation: cluster neuron := test idx; other neurons := train idx
        kf = KFold(n=n_e, n_folds=k)
        for idx_out, idx_in in kf:  # idx_out holds all other neurons; idx_in holds all cluster neurons
            # connect current cluster to itself
            connections.connect_random(all_neurons[idx_in[0]:idx_in[-1]], all_neurons[idx_in[0]:idx_in[-1]],
                                       sparseness=p_in, weight=wee_cluster)
            # connect current cluster to other neurons
            connections.connect_random(all_neurons[idx_in[0]:idx_in[-1]], all_neurons[idx_out[0]:idx_out[-1]],
                                       sparseness=p_out, weight=wee)

        # connect all excitatory to all inhibitory, irrespective of clustering
        connections.connect_random(all_neurons[0:n_e], all_neurons[n_e:(n_e + n_i)], sparseness=p_ie, weight=wie)
        # connect all inhibitory to all excitatory
        connections.connect_random(all_neurons[n_e:(n_e + n_i)], all_neurons[0:n_e], sparseness=p_ei, weight=wei)
        # connect all inhibitory to all inhibitory
        connections.connect_random(all_neurons[n_e:(n_e + n_i)], all_neurons[n_e:(n_e + n_i)], sparseness=p_ii,
                                   weight=wii)

        # set up spike monitors
        spike_mon_e = SpikeMonitor(neurons_e)
        spike_mon_i = SpikeMonitor(neurons_i)
        # set up network with monitors
        network = Network(all_neurons, connections, spike_mon_e, spike_mon_i)

        # run this network for some number of trials, every time with
        for trial in range(trials):
            # different initial values
            all_neurons.V = vr + (vt - vr) * np.random.rand(len(all_neurons)) * 1.4

            # Calibration phase
            # run for the first half of the time to let the neurons adapt
            network.run(t/2)

            # reset monitors to start recording phase
            spike_mon_i.reinit()
            spike_mon_e.reinit()

            # stimulation if duration is given
            # define index variable for the stimulation possibility (is 0 for stimulation time=0)
            t_stim_idx = int(t_stim / (winlen/ms))
            if not(t_stim==0):
                # Stimulation phase, increase input to subset of clusters
                all_neurons[:400].mu += 0.07 * dv
                network.run(t_stim * ms, report='text')
                # set back to normal
                all_neurons[:400].mu -= 0.07 * dv
                # save data
                all_data[realization, trial, :n_e, :t_stim_idx] = spikes_counter(spike_mon_e, winlen)
                all_data[realization, trial, n_e:, :t_stim_idx] = spikes_counter(spike_mon_i, winlen)
                # reset monitors
                spike_mon_e.reinit()
                spike_mon_i.reinit()
            # run the remaining time of the simulation
            network.run((t/2) - t_stim*ms, report='text')

            # save results
            all_data[realization, trial, :n_e, t_stim_idx:] = spikes_counter(spike_mon_e, winlen)
            all_data[realization, trial, n_e:, t_stim_idx:] = spikes_counter(spike_mon_i, winlen)

            if verbose:
                plt.ion()
                plt.figure()
                raster_plot(spike_mon_e)
                plt.title('Excitatory neurons')

            spike_mon_e.reinit()
            spike_mon_i.reinit()

    return all_data
    def plot(self):

        # Spike raster plots
        if self.record_spikes:
            num_plots=self.network_params.num_groups+1
            plt.figure()
            for i in range(self.network_params.num_groups):
                plt.subplot(num_plots,1,i+1)
                raster_plot(self.monitors['excitatory_spike_%d' % i],newfigure=False)
            plt.subplot(num_plots,1,num_plots)
            raster_plot(self.monitors['inhibitory_spike'],newfigure=False)

        # Network firing rate plots
        if self.record_firing_rate:

            e_rate_0=self.monitors['excitatory_rate_0'].smooth_rate(width=5*ms)/hertz
            e_rate_1=self.monitors['excitatory_rate_1'].smooth_rate(width=5*ms)/hertz
            #i_rate=self.monitors['inhibitory_rate'].smooth_rate(width=5*ms)/hertz
            #plot_network_firing_rates(np.array([e_rate_0, e_rate_1]), i_rate, self.sim_params, self.network_params)
            plot_network_firing_rates(np.array([e_rate_0, e_rate_1]), self.sim_params, self.network_params)

        # Input firing rate plots
        if self.record_inputs:
            plt.figure()
            ax= plt.subplot(111)
            max_rate=0
            task_rates=[]
            for i in range(self.network_params.num_groups):
                task_monitor=self.monitors['task_rate_%d' % i]
                task_rate=task_monitor.smooth_rate(width=5*ms,filter='gaussian')/hertz
                if np.max(task_rate)>max_rate:
                    max_rate=np.max(task_rate)
                task_rates.append(task_rate)

            rect=Rectangle((0,0),(self.sim_params.stim_end_time-self.sim_params.stim_start_time)/ms, max_rate+5,
                alpha=0.25, facecolor='yellow', edgecolor='none')
            ax.add_patch(rect)
            for i in range(self.network_params.num_groups):
                ax.plot((np.array(range(len(task_rates[i])))*self.sim_params.dt)/ms-self.sim_params.stim_start_time/ms, task_rates[i])
            plt.ylim(0,90)
            plt.ylabel('Firing rate (Hz)')
            plt.xlabel('Time (ms)')

        # Network state plots
        if self.record_neuron_state:
            network_monitor=self.monitors['network']
            max_conductances=[]
            for neuron_idx in self.record_idx:
                max_conductances.append(np.max(network_monitor['g_ampa_r'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_ampa_x'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_ampa_b'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_nmda'][neuron_idx]/nS))
                max_conductances.append(np.max(network_monitor['g_gaba_a'][neuron_idx]/nS))
            max_conductance=np.max(max_conductances)

            fig= plt.figure()
            for i in range(self.network_params.num_groups):
                neuron_idx=self.record_idx[i]
                ax= plt.subplot(int('%d1%d' % (self.network_params.num_groups+1,i+1)))
                plt.title('e%d' % i)
                ax.plot(network_monitor['g_ampa_r'].times/ms, network_monitor['g_ampa_r'][neuron_idx]/nS,
                    label='AMPA-recurrent')
                ax.plot(network_monitor['g_ampa_x'].times/ms, network_monitor['g_ampa_x'][neuron_idx]/nS,
                    label='AMPA-task')
                ax.plot(network_monitor['g_ampa_b'].times/ms, network_monitor['g_ampa_b'][neuron_idx]/nS,
                    label='AMPA-backgrnd')
                ax.plot(network_monitor['g_nmda'].times/ms, network_monitor['g_nmda'][neuron_idx]/nS,
                    label='NMDA')
                ax.plot(network_monitor['g_gaba_a'].times/ms, network_monitor['g_gaba_a'][neuron_idx]/nS,
                    label='GABA_A')
                plt.ylim(0,max_conductance)
                plt.xlabel('Time (ms)')
                plt.ylabel('Conductance (nS)')
                plt.legend()

            neuron_idx=self.record_idx[self.network_params.num_groups]
            ax= plt.subplot('%d1%d' % (self.network_params.num_groups+1,self.network_params.num_groups+1))
            plt.title('i')
            ax.plot(network_monitor['g_ampa_r'].times/ms, network_monitor['g_ampa_r'][neuron_idx]/nS,
                label='AMPA-recurrent')
            ax.plot(network_monitor['g_ampa_x'].times/ms, network_monitor['g_ampa_x'][neuron_idx]/nS,
                label='AMPA-task')
            ax.plot(network_monitor['g_ampa_b'].times/ms, network_monitor['g_ampa_b'][neuron_idx]/nS,
                label='AMPA-backgrnd')
            ax.plot(network_monitor['g_nmda'].times/ms, network_monitor['g_nmda'][neuron_idx]/nS,
                label='NMDA')
            ax.plot(network_monitor['g_gaba_a'].times/ms, network_monitor['g_gaba_a'][neuron_idx]/nS,
                label='GABA_A')
            plt.ylim(0,max_conductance)
            plt.xlabel('Time (ms)')
            plt.ylabel('Conductance (nS)')
            plt.legend()

            min_currents=[]
            max_currents=[]
            for neuron_idx in self.record_idx:
                max_currents.append(np.max(network_monitor['I_ampa_r'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_ampa_x'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_ampa_b'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_nmda'][neuron_idx]/nS))
                max_currents.append(np.max(network_monitor['I_gaba_a'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_ampa_r'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_ampa_x'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_ampa_b'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_nmda'][neuron_idx]/nS))
                min_currents.append(np.min(network_monitor['I_gaba_a'][neuron_idx]/nS))
            max_current=np.max(max_currents)
            min_current=np.min(min_currents)

            fig=plt.figure()
            for i in range(self.network_params.num_groups):
                ax=plt.subplot(int('%d1%d' % (self.network_params.num_groups+1,i+1)))
                neuron_idx=self.record_idx[i]
                plt.title('e%d' % i)
                ax.plot(network_monitor['I_ampa_r'].times/ms, network_monitor['I_ampa_r'][neuron_idx]/nA,
                    label='AMPA-recurrent')
                ax.plot(network_monitor['I_ampa_x'].times/ms, network_monitor['I_ampa_x'][neuron_idx]/nA,
                    label='AMPA-task')
                ax.plot(network_monitor['I_ampa_b'].times/ms, network_monitor['I_ampa_b'][neuron_idx]/nA,
                    label='AMPA-backgrnd')
                ax.plot(network_monitor['I_nmda'].times/ms, network_monitor['I_nmda'][neuron_idx]/nA,
                    label='NMDA')
                ax.plot(network_monitor['I_gaba_a'].times/ms, network_monitor['I_gaba_a'][neuron_idx]/nA,
                    label='GABA_A')
                plt.ylim(min_current,max_current)
                plt.xlabel('Time (ms)')
                plt.ylabel('Current (nA)')
                plt.legend()

            ax=plt.subplot(int('%d1%d' % (self.network_params.num_groups+1,self.network_params.num_groups+1)))
            neuron_idx=self.record_idx[self.network_params.num_groups]
            plt.title('i')
            ax.plot(network_monitor['I_ampa_r'].times/ms, network_monitor['I_ampa_r'][neuron_idx]/nA,
                label='AMPA-recurrent')
            ax.plot(network_monitor['I_ampa_x'].times/ms, network_monitor['I_ampa_x'][neuron_idx]/nA,
                label='AMPA-task')
            ax.plot(network_monitor['I_ampa_b'].times/ms, network_monitor['I_ampa_b'][neuron_idx]/nA,
                label='AMPA-backgrnd')
            ax.plot(network_monitor['I_nmda'].times/ms, network_monitor['I_nmda'][neuron_idx]/nA,
                label='NMDA')
            ax.plot(network_monitor['I_gaba_a'].times/ms, network_monitor['I_gaba_a'][neuron_idx]/nA,
                label='GABA_A')
            plt.ylim(min_current,max_current)
            plt.xlabel('Time (ms)')
            plt.ylabel('Current (nA)')
            plt.legend()
def build_network():
    global fig_num

    neuron_groups['e'] = b.NeuronGroup(n_e_total, neuron_eqs_e, threshold=v_thresh_e, \
          refractory=refrac_e, reset=scr_e, compile=True, freeze=True)
    neuron_groups['i'] = b.NeuronGroup(n_e_total, neuron_eqs_i, threshold=v_thresh_i, \
         refractory=refrac_i, reset=v_reset_i, compile=True, freeze=True)

    for name in population_names:
        print '...Creating neuron group:', name

        # get a subgroup of size 'n_e' from all exc
        neuron_groups[name + 'e'] = neuron_groups['e'].subgroup(conv_features *
                                                                n_e)
        # get a subgroup of size 'n_i' from the inhibitory layer
        neuron_groups[name + 'i'] = neuron_groups['i'].subgroup(conv_features *
                                                                n_e)

        # start the membrane potentials of these groups 40mV below their resting potentials
        neuron_groups[name + 'e'].v = v_rest_e - 40. * b.mV
        neuron_groups[name + 'i'].v = v_rest_i - 40. * b.mV

    print '...Creating recurrent connections'

    for name in population_names:
        neuron_groups['e'].theta = np.load(
            os.path.join(best_weights_dir,
                         '_'.join(['theta_A', ending + '_best.npy'])))

        for conn_type in recurrent_conn_names:
            if conn_type == 'ei':
                # create connection name (composed of population and connection types)
                conn_name = name + conn_type[0] + name + conn_type[1]
                # create a connection from the first group in conn_name with the second group
                connections[conn_name] = b.Connection(
                    neuron_groups[conn_name[0:2]],
                    neuron_groups[conn_name[2:4]],
                    structure='sparse',
                    state='g' + conn_type[0])

                # instantiate the created connection
                for feature in xrange(conv_features):
                    for n in xrange(n_e):
                        connections[conn_name][feature * n_e + n,
                                               feature * n_e + n] = 10.4

            elif conn_type == 'ie':
                # create connection name (composed of population and connection types)
                conn_name = name + conn_type[0] + name + conn_type[1]

                # load weight matrix
                weight_matrix = np.load(
                    os.path.join(best_weights_dir,
                                 '_'.join([conn_name, ending, 'best.npy'])))

                # create a connection from the first group in conn_name with the second group
                connections[conn_name] = b.Connection(
                    neuron_groups[conn_name[0:2]],
                    neuron_groups[conn_name[2:4]],
                    structure='sparse',
                    state='g' + conn_type[0])

                # define the actual synaptic connections and strengths
                for feature in xrange(conv_features):
                    for other_feature in xrange(conv_features):
                        if feature != other_feature:
                            for n in xrange(n_e):
                                connections[conn_name][feature * n_e + n,
                                                       other_feature * n_e +
                                                       n] = inhibition_level

        print '...Creating monitors for:', name

        # spike rate monitors for excitatory and inhibitory neuron populations
        rate_monitors[name + 'e'] = b.PopulationRateMonitor(
            neuron_groups[name + 'e'],
            bin=(single_example_time + resting_time) / b.second)
        rate_monitors[name + 'i'] = b.PopulationRateMonitor(
            neuron_groups[name + 'i'],
            bin=(single_example_time + resting_time) / b.second)
        spike_counters[name + 'e'] = b.SpikeCounter(neuron_groups[name + 'e'])

        # record neuron population spikes if specified
        if record_spikes and do_plot:
            spike_monitors[name + 'e'] = b.SpikeMonitor(neuron_groups[name +
                                                                      'e'])
            spike_monitors[name + 'i'] = b.SpikeMonitor(neuron_groups[name +
                                                                      'i'])

    if record_spikes and do_plot:
        b.figure(fig_num, figsize=(8, 6))
        b.ion()
        b.subplot(211)
        b.raster_plot(spike_monitors['Ae'],
                      refresh=1000 * b.ms,
                      showlast=1000 * b.ms,
                      title='Excitatory spikes per neuron')
        b.subplot(212)
        b.raster_plot(spike_monitors['Ai'],
                      refresh=1000 * b.ms,
                      showlast=1000 * b.ms,
                      title='Inhibitory spikes per neuron')
        b.tight_layout()

        fig_num += 1

    # creating Poission spike train from input image (784 vector, 28x28 image)
    for name in input_population_names:
        input_groups[name + 'e'] = b.PoissonGroup(n_input, 0)
        rate_monitors[name + 'e'] = b.PopulationRateMonitor(
            input_groups[name + 'e'],
            bin=(single_example_time + resting_time) / b.second)

    # creating connections from input Poisson spike train to excitatory neuron population(s)
    for name in input_connection_names:
        print '\n...Creating connections between', name[0], 'and', name[1]

        # for each of the input connection types (in this case, excitatory -> excitatory)
        for conn_type in input_conn_names:
            # saved connection name
            conn_name = name[0] + conn_type[0] + name[1] + conn_type[1]

            # get weight matrix depending on training or test phase
            weight_matrix = np.load(
                os.path.join(best_weights_dir,
                             '_'.join([conn_name, ending + '_best.npy'])))

            # create connections from the windows of the input group to the neuron population
            input_connections[conn_name] = b.Connection(input_groups['Xe'], neuron_groups[name[1] + conn_type[1]], \
                structure='sparse', state='g' + conn_type[0], delay=True, max_delay=delay[conn_type][1])

            for feature in xrange(conv_features):
                for n in xrange(n_e):
                    for idx in xrange(conv_size**2):
                        input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = \
                                weight_matrix[convolution_locations[n][idx], feature * n_e + n]

            if do_plot:
                plot_2d_input_weights()
                fig_num += 1

    print '\n'
Esempio n. 32
0
    def plot(self, trial_duration):

        # Spike raster plots
        if self.spike_monitors is not None:
            figure()
            subplot(811)
            raster_plot(self.spike_monitors['left_ec'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.left_lip.e_contra_size)
            ylabel('left EC')
            subplot(812)
            raster_plot(self.spike_monitors['left_ei'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.left_lip.e_ipsi_size)
            ylabel('left EI')
            subplot(813)
            raster_plot(self.spike_monitors['left_ic'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.left_lip.i_contra_size)
            ylabel('left IC')
            subplot(814)
            raster_plot(self.spike_monitors['left_ii'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.left_lip.i_ipsi_size)
            ylabel('left II')
            subplot(815)
            raster_plot(self.spike_monitors['right_ec'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.right_lip.e_contra_size)
            ylabel('right EC')
            subplot(816)
            raster_plot(self.spike_monitors['right_ei'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.right_lip.e_ipsi_size)
            ylabel('right EI')
            subplot(817)
            raster_plot(self.spike_monitors['right_ic'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.right_lip.i_contra_size)
            ylabel('right IC')
            subplot(818)
            raster_plot(self.spike_monitors['right_ii'], newfigure=False)
            xlim(0, trial_duration / ms)
            ylim(0, self.brain_network.right_lip.i_ipsi_size)
            ylabel('right II')

        # Network firing rate plots
        if self.population_rate_monitors is not None:
            smooth_width = 10 * ms
            left_ec_vis_rate = self.population_rate_monitors[
                'left_ec_vis'].smooth_rate(width=smooth_width) / hertz
            left_ec_mem_rate = self.population_rate_monitors[
                'left_ec_mem'].smooth_rate(width=smooth_width) / hertz
            left_ec_rate = self.population_rate_monitors[
                'left_ec'].smooth_rate(width=smooth_width) / hertz
            left_ei_vis_rate = self.population_rate_monitors[
                'left_ei_vis'].smooth_rate(width=smooth_width) / hertz
            left_ei_mem_rate = self.population_rate_monitors[
                'left_ei_mem'].smooth_rate(width=smooth_width) / hertz
            left_ei_rate = self.population_rate_monitors[
                'left_ei'].smooth_rate(width=smooth_width) / hertz
            left_ic_rate = self.population_rate_monitors[
                'left_ic'].smooth_rate(width=smooth_width) / hertz
            left_ii_rate = self.population_rate_monitors[
                'left_ii'].smooth_rate(width=smooth_width) / hertz

            right_ec_vis_rate = self.population_rate_monitors[
                'right_ec_vis'].smooth_rate(width=smooth_width) / hertz
            right_ec_mem_rate = self.population_rate_monitors[
                'right_ec_mem'].smooth_rate(width=smooth_width) / hertz
            right_ec_rate = self.population_rate_monitors[
                'right_ec'].smooth_rate(width=smooth_width) / hertz
            right_ei_vis_rate = self.population_rate_monitors[
                'right_ei_vis'].smooth_rate(width=smooth_width) / hertz
            right_ei_mem_rate = self.population_rate_monitors[
                'right_ei_mem'].smooth_rate(width=smooth_width) / hertz
            right_ei_rate = self.population_rate_monitors[
                'right_ei'].smooth_rate(width=smooth_width) / hertz
            right_ic_rate = self.population_rate_monitors[
                'right_ic'].smooth_rate(width=smooth_width) / hertz
            right_ii_rate = self.population_rate_monitors[
                'right_ii'].smooth_rate(width=smooth_width) / hertz

            max_rate = np.max([
                np.max(left_ec_vis_rate),
                np.max(left_ec_mem_rate),
                np.max(left_ec_rate),
                np.max(left_ei_vis_rate),
                np.max(left_ei_mem_rate),
                np.max(left_ic_rate),
                np.max(left_ii_rate),
                np.max(right_ec_vis_rate),
                np.max(right_ec_mem_rate),
                np.max(right_ec_rate),
                np.max(right_ei_vis_rate),
                np.max(right_ei_mem_rate),
                np.max(right_ei_rate),
                np.max(right_ic_rate),
                np.max(right_ii_rate)
            ])

            times_ms = self.population_rate_monitors['left_ec_vis'].times / ms

            figure()
            ax = subplot(211)
            ax.plot(times_ms, left_ec_vis_rate, label='left LIP EC vis')
            ax.plot(times_ms, left_ec_mem_rate, label='left LIP EC mem')
            #ax.plot(times_ms, left_ec_rate, label='left LIP EC')
            ax.plot(times_ms, left_ei_vis_rate, label='left LIP EI vis')
            ax.plot(times_ms, left_ei_mem_rate, label='left LIP EI mem')
            #ax.plot(times_ms, left_ei_rate, label='left LIP EI')
            ax.plot(times_ms, left_ic_rate, label='left LIP IC')
            ax.plot(times_ms, left_ii_rate, label='left LIP II')
            ylim(0, max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

            ax = subplot(212)
            ax.plot(times_ms, right_ec_vis_rate, label='right LIP EC vis')
            ax.plot(times_ms, right_ec_mem_rate, label='right LIP EC mem')
            #ax.plot(times_ms, right_ec_rate, label='right LIP EC')
            ax.plot(times_ms, right_ei_vis_rate, label='right LIP EI vis')
            ax.plot(times_ms, right_ei_mem_rate, label='right LIP EI mem')
            #ax.plot(times_ms, right_ei_rate, label='right LIP EI')
            ax.plot(times_ms, right_ic_rate, label='right LIP IC')
            ax.plot(times_ms, right_ii_rate, label='right LIP II')
            ylim(0, max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

            figure()
            ax = subplot(211)
            ax.plot(times_ms, left_ec_rate, label='left LIP EC')
            ax.plot(times_ms, left_ei_rate, label='left LIP EI')
            ylim(0, max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

            ax = subplot(212)
            ax.plot(times_ms, right_ec_rate, label='right LIP EC')
            ax.plot(times_ms, right_ei_rate, label='right LIP EI')
            ylim(0, max_rate)
            legend()
            xlabel('Time (ms)')
            ylabel('Population Firing Rate (Hz)')

        # Input firing rate plots
        if self.left_background_rate_monitor is not None and self.right_background_rate_monitor is not None and\
           self.left_visual_cortex_monitor is not None and self.right_visual_cortex_monitor is not None and \
           self.go_input_monitor is not None:
            figure()
            max_rate = np.max([
                np.max(
                    self.left_background_rate_monitor.smooth_rate(width=5 * ms)
                    / hertz),
                np.max(
                    self.right_background_rate_monitor.smooth_rate(
                        width=5 * ms) / hertz),
                np.max(
                    self.left_visual_cortex_monitor.smooth_rate(width=5 * ms) /
                    hertz),
                np.max(
                    self.right_visual_cortex_monitor.smooth_rate(width=5 * ms)
                    / hertz),
                np.max(
                    self.go_input_monitor.smooth_rate(width=5 * ms) / hertz)
            ])
            ax = subplot(111)
            ax.plot(
                self.left_background_rate_monitor.times / ms,
                self.left_background_rate_monitor.smooth_rate(width=5 * ms) /
                hertz,
                label='left background')
            ax.plot(
                self.right_background_rate_monitor.times / ms,
                self.right_background_rate_monitor.smooth_rate(width=5 * ms) /
                hertz,
                label='right background')
            ax.plot(self.left_visual_cortex_monitor.times / ms,
                    self.left_visual_cortex_monitor.smooth_rate(width=5 * ms) /
                    hertz,
                    label='left VC')
            ax.plot(
                self.right_visual_cortex_monitor.times / ms,
                self.right_visual_cortex_monitor.smooth_rate(width=5 * ms) /
                hertz,
                label='right VC')
            ax.plot(self.go_input_monitor.times / ms,
                    self.go_input_monitor.smooth_rate(width=5 * ms) / hertz,
                    label='Go')
            legend()
            ylim(0, max_rate)

        # Network state plots
        if self.left_network_monitor is not None and self.right_network_monitor is not None:
            max_conductances = []
            for idx in self.left_record_idx:
                max_conductances.append(
                    np.max(self.left_network_monitor['g_ampa_r'][idx] / nS))
                max_conductances.append(
                    np.max(self.left_network_monitor['g_ampa_x'][idx] / nS))
                max_conductances.append(
                    np.max(self.left_network_monitor['g_ampa_b'][idx] / nS))
                max_conductances.append(
                    np.max(self.left_network_monitor['g_ampa_g'][idx] / nS))
                max_conductances.append(
                    np.max(self.left_network_monitor['g_nmda'][idx] / nS))
                max_conductances.append(
                    np.max(self.left_network_monitor['g_gaba_a'][idx] / nS))
                max_conductances.append(
                    np.max(self.left_network_monitor['g_gaba_b'][idx] / nS))
            for idx in self.right_record_idx:
                max_conductances.append(
                    np.max(self.right_network_monitor['g_ampa_r'][idx] / nS))
                max_conductances.append(
                    np.max(self.right_network_monitor['g_ampa_x'][idx] / nS))
                max_conductances.append(
                    np.max(self.right_network_monitor['g_ampa_b'][idx] / nS))
                max_conductances.append(
                    np.max(self.right_network_monitor['g_ampa_g'][idx] / nS))
                max_conductances.append(
                    np.max(self.right_network_monitor['g_nmda'][idx] / nS))
                max_conductances.append(
                    np.max(self.right_network_monitor['g_gaba_a'][idx] / nS))
                max_conductances.append(
                    np.max(self.right_network_monitor['g_gaba_b'][idx] / nS))
            max_conductance = np.max(max_conductances)

            figure()
            labels = [
                'e_contra_vis', 'e_contra_mem', 'e_ipsi_vis', 'e_ipsi_mem',
                'i_contra', 'i_ipsi'
            ]
            for i, idx in enumerate(self.left_record_idx):
                ax = subplot(len(self.left_record_idx), 1, i + 1)
                ax.plot(self.left_network_monitor['g_ampa_r'].times / ms,
                        self.left_network_monitor['g_ampa_r'][idx] / nS,
                        label='AMPA recurrent')
                ax.plot(self.left_network_monitor['g_ampa_x'].times / ms,
                        self.left_network_monitor['g_ampa_x'][idx] / nS,
                        label='AMPA task')
                ax.plot(self.left_network_monitor['g_ampa_b'].times / ms,
                        self.left_network_monitor['g_ampa_b'][idx] / nS,
                        label='AMPA backgrnd')
                ax.plot(self.left_network_monitor['g_ampa_g'].times / ms,
                        self.left_network_monitor['g_ampa_g'][idx] / nS,
                        label='AMPA go')
                ax.plot(self.left_network_monitor['g_nmda'].times / ms,
                        self.left_network_monitor['g_nmda'][idx] / nS,
                        label='NMDA')
                ax.plot(self.left_network_monitor['g_gaba_a'].times / ms,
                        self.left_network_monitor['g_gaba_a'][idx] / nS,
                        label='GABA_A')
                ax.plot(self.left_network_monitor['g_gaba_b'].times / ms,
                        self.left_network_monitor['g_gaba_b'][idx] / nS,
                        label='GABA_B')
                ylim(0, max_conductance)
                ylabel(labels[i])
                if not i:
                    title('Left LIP - Conductance (nS)')
                    legend()
            xlabel('Time (ms)')

            figure()
            for i, idx in enumerate(self.right_record_idx):
                ax = subplot(len(self.right_record_idx), 1, i + 1)
                ax.plot(self.right_network_monitor['g_ampa_r'].times / ms,
                        self.right_network_monitor['g_ampa_r'][idx] / nS,
                        label='AMPA recurrent')
                ax.plot(self.right_network_monitor['g_ampa_x'].times / ms,
                        self.right_network_monitor['g_ampa_x'][idx] / nS,
                        label='AMPA task')
                ax.plot(self.right_network_monitor['g_ampa_b'].times / ms,
                        self.right_network_monitor['g_ampa_b'][idx] / nS,
                        label='AMPA backgrnd')
                ax.plot(self.right_network_monitor['g_ampa_g'].times / ms,
                        self.right_network_monitor['g_ampa_g'][idx] / nS,
                        label='AMPA go')
                ax.plot(self.right_network_monitor['g_nmda'].times / ms,
                        self.right_network_monitor['g_nmda'][idx] / nS,
                        label='NMDA')
                ax.plot(self.right_network_monitor['g_gaba_a'].times / ms,
                        self.right_network_monitor['g_gaba_a'][idx] / nS,
                        label='GABA_A')
                ax.plot(self.right_network_monitor['g_gaba_b'].times / ms,
                        self.right_network_monitor['g_gaba_b'][idx] / nS,
                        label='GABA_B')
                ylim(0, max_conductance)
                ylabel(labels[i])
                if not i:
                    title('Right LIP - Conductance (nS)')
                    legend()
            xlabel('Time (ms)')

            min_currents = []
            max_currents = []
            for idx in self.left_record_idx:
                max_currents.append(
                    np.max(self.left_network_monitor['I_ampa_r'][idx] / nA))
                max_currents.append(
                    np.max(self.left_network_monitor['I_ampa_x'][idx] / nA))
                max_currents.append(
                    np.max(self.left_network_monitor['I_ampa_b'][idx] / nA))
                max_currents.append(
                    np.max(self.left_network_monitor['I_ampa_g'][idx] / nA))
                max_currents.append(
                    np.max(self.left_network_monitor['I_nmda'][idx] / nA))
                max_currents.append(
                    np.max(self.left_network_monitor['I_gaba_a'][idx] / nA))
                max_currents.append(
                    np.max(self.left_network_monitor['I_gaba_b'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_ampa_r'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_ampa_x'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_ampa_b'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_ampa_g'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_nmda'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_gaba_a'][idx] / nA))
                min_currents.append(
                    np.min(self.left_network_monitor['I_gaba_b'][idx] / nA))
            for idx in self.right_record_idx:
                max_currents.append(
                    np.max(self.right_network_monitor['I_ampa_r'][idx] / nA))
                max_currents.append(
                    np.max(self.right_network_monitor['I_ampa_x'][idx] / nA))
                max_currents.append(
                    np.max(self.right_network_monitor['I_ampa_b'][idx] / nA))
                max_currents.append(
                    np.max(self.right_network_monitor['I_ampa_g'][idx] / nA))
                max_currents.append(
                    np.max(self.right_network_monitor['I_nmda'][idx] / nA))
                max_currents.append(
                    np.max(self.right_network_monitor['I_gaba_a'][idx] / nA))
                max_currents.append(
                    np.max(self.right_network_monitor['I_gaba_b'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_ampa_r'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_ampa_x'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_ampa_b'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_ampa_g'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_nmda'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_gaba_a'][idx] / nA))
                min_currents.append(
                    np.min(self.right_network_monitor['I_gaba_b'][idx] / nA))
            max_current = np.max(max_currents)
            min_current = np.min(min_currents)

            figure()
            for i, neuron_idx in enumerate(self.left_record_idx):
                ax = subplot(len(self.left_record_idx), 1, i + 1)
                ax.plot(self.left_network_monitor['I_ampa_r'].times / ms,
                        self.left_network_monitor['I_ampa_r'][neuron_idx] / nA,
                        label='AMPA-recurrent')
                ax.plot(self.left_network_monitor['I_ampa_x'].times / ms,
                        self.left_network_monitor['I_ampa_x'][neuron_idx] / nA,
                        label='AMPA-task')
                ax.plot(self.left_network_monitor['I_ampa_b'].times / ms,
                        self.left_network_monitor['I_ampa_b'][neuron_idx] / nA,
                        label='AMPA-backgrnd')
                ax.plot(self.left_network_monitor['I_ampa_b'].times / ms,
                        self.left_network_monitor['I_ampa_g'][neuron_idx] / nA,
                        label='AMPA-go')
                ax.plot(self.left_network_monitor['I_nmda'].times / ms,
                        self.left_network_monitor['I_nmda'][neuron_idx] / nA,
                        label='NMDA')
                ax.plot(self.left_network_monitor['I_gaba_a'].times / ms,
                        self.left_network_monitor['I_gaba_a'][neuron_idx] / nA,
                        label='GABA_A')
                ax.plot(self.left_network_monitor['I_gaba_b'].times / ms,
                        self.left_network_monitor['I_gaba_b'][neuron_idx] / nA,
                        label='GABA_B')
                ylim(min_current, max_current)
                ylabel(labels[i])
                if not i:
                    title('Left LIP - Current (nA)')
                    legend()
            xlabel('Time (ms)')

            figure()
            for i, neuron_idx in enumerate(self.right_record_idx):
                ax = subplot(len(self.right_record_idx), 1, i + 1)
                ax.plot(self.right_network_monitor['I_ampa_r'].times / ms,
                        self.right_network_monitor['I_ampa_r'][neuron_idx] /
                        nA,
                        label='AMPA-recurrent')
                ax.plot(self.right_network_monitor['I_ampa_x'].times / ms,
                        self.right_network_monitor['I_ampa_x'][neuron_idx] /
                        nA,
                        label='AMPA-task')
                ax.plot(self.right_network_monitor['I_ampa_b'].times / ms,
                        self.right_network_monitor['I_ampa_b'][neuron_idx] /
                        nA,
                        label='AMPA-backgrnd')
                ax.plot(self.right_network_monitor['I_ampa_b'].times / ms,
                        self.right_network_monitor['I_ampa_g'][neuron_idx] /
                        nA,
                        label='AMPA-go')
                ax.plot(self.right_network_monitor['I_nmda'].times / ms,
                        self.right_network_monitor['I_nmda'][neuron_idx] / nA,
                        label='NMDA')
                ax.plot(self.right_network_monitor['I_gaba_a'].times / ms,
                        self.right_network_monitor['I_gaba_a'][neuron_idx] /
                        nA,
                        label='GABA_A')
                ax.plot(self.right_network_monitor['I_gaba_b'].times / ms,
                        self.right_network_monitor['I_gaba_b'][neuron_idx] /
                        nA,
                        label='GABA_B')
                ylim(min_current, max_current)
                ylabel(labels[i])
                if not i:
                    title('Right LIP - Current (nA)')
                    legend()
            xlabel('Time (ms)')

        # LFP plot
        if self.left_lfp_monitor is not None and self.right_lfp_monitor is not None:
            figure()
            ax = subplot(111)
            ax.plot(self.left_lfp_monitor.times / ms,
                    self.left_lfp_monitor[0] / mA,
                    label='left LIP')
            ax.plot(self.right_lfp_monitor.times / ms,
                    self.right_lfp_monitor[0] / mA,
                    label='right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('LFP (mA)')

        # Voxel activity plots
        if self.left_voxel_monitor is not None and self.right_voxel_monitor is not None:
            syn_max = np.max([
                np.max(self.left_voxel_monitor['G_total'][0] / nS),
                np.max(self.right_voxel_monitor['G_total'][0] / nS)
            ])
            y_max = np.max([
                np.max(self.left_voxel_monitor['y'][0]),
                np.max(self.right_voxel_monitor['y'][0])
            ])
            y_min = np.min([
                np.min(self.left_voxel_monitor['y'][0]),
                np.min(self.right_voxel_monitor['y'][0])
            ])
            figure()
            if self.left_voxel_exc_monitor is None and self.right_voxel_exc_monitor is None:
                ax = subplot(211)
            else:
                ax = subplot(221)
                syn_max = np.max([
                    syn_max,
                    np.max(self.left_voxel_exc_monitor['G_total'][0]),
                    np.max(self.right_voxel_exc_monitor['G_total'][0])
                ])
                y_max = np.max([
                    y_max,
                    np.max(self.left_voxel_exc_monitor['y'][0]),
                    np.max(self.right_voxel_exc_monitor['y'][0])
                ])
                y_min = np.min([
                    y_min,
                    np.min(self.left_voxel_exc_monitor['y'][0]),
                    np.min(self.right_voxel_exc_monitor['y'][0])
                ])
            ax.plot(self.left_voxel_monitor['G_total'].times / ms,
                    self.left_voxel_monitor['G_total'][0] / nS,
                    label='left LIP')
            ax.plot(self.right_voxel_monitor['G_total'].times / ms,
                    self.right_voxel_monitor['G_total'][0] / nS,
                    label='right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('Total Synaptic Activity (nS)')
            ylim(0, syn_max)
            if self.left_voxel_exc_monitor is None and self.right_voxel_exc_monitor is None:
                ax = subplot(212)
            else:
                ax = subplot(222)
            ax.plot(self.left_voxel_monitor['y'].times / ms,
                    self.left_voxel_monitor['y'][0],
                    label='left LIP')
            ax.plot(self.right_voxel_monitor['y'].times / ms,
                    self.right_voxel_monitor['y'][0],
                    label='right LIP')
            legend()
            xlabel('Time (ms)')
            ylabel('BOLD')
            ylim(y_min, y_max * 2.0)
            if self.left_voxel_exc_monitor is not None and self.right_voxel_exc_monitor is not None:
                ax = subplot(223)
                ax.plot(self.left_voxel_exc_monitor['G_total'].times / ms,
                        self.left_voxel_exc_monitor['G_total'][0] / nS,
                        label='left LIP')
                ax.plot(self.right_voxel_exc_monitor['G_total'].times / ms,
                        self.right_voxel_exc_monitor['G_total'][0] / nS,
                        label='right LIP')
                legend()
                xlabel('Time (ms)')
                ylabel('Total Synaptic Activity (nS)')
                ylim(0, syn_max)
                ax = subplot(224)
                ax.plot(self.left_voxel_exc_monitor['y'].times / ms,
                        self.left_voxel_exc_monitor['y'][0],
                        label='left LIP')
                ax.plot(self.right_voxel_exc_monitor['y'].times / ms,
                        self.right_voxel_exc_monitor['y'][0],
                        label='right LIP')
                legend()
                xlabel('Time (ms)')
                ylabel('BOLD')
                ylim(y_min, y_max)
        show()