Ejemplo n.º 1
0
def plotSingleTuningCurve(dataPath, gaussianDistance, ax1=None):
    b.rcParams['font.size'] = 20
    averagingWindowSize = 1
    nE = 1600
    ymax = 1
    
    if ax1==None:
        b.figure(figsize=(8,6.5))
        fig_axis = b.subplot(1,1,1)
    else:
        fig_axis = ax1
        b.sca(ax1)
        
    path = dataPath + '/dist'+str(gaussianDistance)+'/' +'activity/'
    spikeCount = np.load(path + 'spikeCountPerExample.npy')
    spikeCountSingleNeuron = (spikeCount[:,nE/2-2,0])
    numMeasurements = len(spikeCount[:,0,0])
    
    spikeCount = movingaverage(spikeCountSingleNeuron,averagingWindowSize)
    spikeCount /= np.max(spikeCountSingleNeuron)
    b.plot(spikeCount, color='deepskyblue', marker='o', alpha=0.6, linewidth=0, label='Output')#alpha=0.5+(0.5*float(i)/float(len(lower_peaks))), 
    fig_axis.set_xticks([0., numMeasurements/2, numMeasurements])
    fig_axis.set_xticklabels(['0', '0.5', '1'])
    fig_axis.set_yticks([0., ymax/2, ymax])
    fig_axis.spines['top'].set_visible(False)
    fig_axis.spines['right'].set_visible(False)
    fig_axis.get_xaxis().tick_bottom()
    fig_axis.get_yaxis().tick_left()
    b.ylabel('Normalized response')
    b.ylim(0,ymax+0.05)

#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))
    if ax1==None:
        b.legend(loc='upper left', fancybox=True, framealpha=0.0)
        b.savefig(dataPath + '/tuningCurveSingleNeuron.png', dpi=300, bbox_inches='tight')
Ejemplo n.º 2
0
def Plot(M, Mu, Mv, number):
    br.plot(211)
    #pudb.set_trace()
    br.plot(Mu.times / br.ms, Mu[0] / br.mvolt, label='u')
    br.plot((Mv.times) / br.ms, 2000 * (Mv[0] / br.mvolt) - 58000, label='v')
    br.plot((M.times) / br.ms, 2000 * (M[0] / br.mvolt) - 58000, label='ge')
    #br.plot(Mv.times/br.ms,Mv[
    br.legend()
    br.show()
Ejemplo n.º 3
0
def plotPopulationTuningCurve(dataPath, gaussianDistance, ax1=None):
    b.rcParams['font.size'] = 20
    averagingWindowSize = 1
    nE = 1600
    ymax = 1
    
    if ax1==None:
        b.figure(figsize=(8,6.5))
        fig_axis = b.subplot(1,1,1)
    else:
        fig_axis = ax1
        b.sca(ax1)
        
    
    path = dataPath + '/dist'+str(gaussianDistance)+'/' +'activity/'
    spikeCount = np.load(path + 'spikeCountPerExample.npy')
    numMeasurements = len(spikeCount[:,0,0])
    measurementSpace = np.arange(numMeasurements)
    populationSpikeCount = np.zeros((numMeasurements))
    for i in xrange(nE):
        populationSpikeCount += np.roll(spikeCount[:,i,0], int(-1.*i/nE*numMeasurements+ numMeasurements/2))
    populationSpikeCount = movingaverage(populationSpikeCount,averagingWindowSize)
    populationSpikeCount /= np.max(populationSpikeCount)
    if gaussianDistance==0.:
        mean = sum(measurementSpace*populationSpikeCount)/numMeasurements                   #note this correction
        sigma = sum(populationSpikeCount*(measurementSpace-mean)**2)/numMeasurements        #note this correction
        popt, _ = curve_fit(gaus,measurementSpace,populationSpikeCount,p0=[1,mean,sigma])
        print 'Gaussian amplitude: ', popt[0], ', mean: ', popt[1], ', std.: ', popt[2]**2
        
        b.plot(measurementSpace,gaus(measurementSpace,*popt),'k')
    
    b.plot(populationSpikeCount, color='deepskyblue', marker='o', alpha=0.6, linewidth=0, label='Output')#alpha=0.5+(0.5*float(i)/float(len(lower_peaks))), 
    fig_axis.set_xticks([0., numMeasurements/2, numMeasurements])
    fig_axis.set_xticklabels(['0', '0.5', '1'])
    fig_axis.set_yticks([0., ymax/2, ymax])
    fig_axis.spines['top'].set_visible(False)
    fig_axis.spines['right'].set_visible(False)
    fig_axis.get_xaxis().tick_bottom()
    fig_axis.get_yaxis().tick_left()
#     b.ylabel('Normalized response')
    b.ylim(0,ymax+0.05)

#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))
    if ax1==None:
        b.legend(loc='upper left', fancybox=True, framealpha=0.0)
        b.savefig(dataPath + '/tuningCurvePopulation' + str(gaussianDistance) + '.png', dpi=300, bbox_inches='tight')
Ejemplo n.º 4
0
def plotActivity(dataPath, ax1=None):
    averagingWindowSize = 1
    nE = 1600
    ymax = 40
#     b.rcParams['lines.color'] = 'w'
#     b.rcParams['text.color'] = 'w'
#     b.rcParams['xtick.color'] = 'w'
#     b.rcParams['ytick.color'] = 'w'
#     b.rcParams['axes.labelcolor'] = 'w'
#     b.rcParams['axes.edgecolor'] = 'w'
    b.rcParams['font.size'] = 20
    if ax1==None:
        fig = b.figure(figsize=(8,6.5))
        fig_axis=b.subplot(1,1,1)
    else:
        fig_axis = ax1
        b.sca(ax1)
    path = dataPath + 'activity/'
    spikeCount = np.loadtxt(path + 'spikeCountCe.txt')
    popVecs = np.loadtxt(path + 'popVecs1.txt')
    desiredResult = (popVecs[0] + popVecs[1])%1.*1600
    resultMonitor = np.loadtxt(path + 'resultPopVecs1.txt')
    actualResult = resultMonitor[2]*1600
    ax1.axvline(desiredResult, color='r', linewidth=3, ymax=ymax, label='Desired result')
    ax1.axvline(actualResult, color='blue', linewidth=3, ymax=ymax, label='Population vector')
    
    print 'desiredResult', desiredResult, ', actual result', actualResult
#     spikeCount = np.roll(spikeCount, 800+int(-1*desiredResult))
    spikeCount = movingaverage(spikeCount,averagingWindowSize)
    b.plot(spikeCount, 'deepskyblue', alpha=0.6, linewidth=3, label='Population activity')
    fig_axis.set_xticks([0., nE/2, nE])
    fig_axis.set_xticklabels(['0', '0.5', '1'])
    fig_axis.set_yticks([0., ymax/2, ymax])
    fig_axis.spines['top'].set_visible(False)
    fig_axis.spines['right'].set_visible(False)
    fig_axis.get_xaxis().tick_bottom()
    fig_axis.get_yaxis().tick_left()
    b.ylabel('Firing Rate [Hz]')

    b.ylim(0,ymax)
    b.legend(fancybox=True, framealpha=0.0, loc='upper left')
#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))
    if ax1==None:
        b.xlabel('Neuron number (resorted)')
        b.savefig(dataPath + 'SignalRestoration.png', dpi=900, transparent=True)
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()
Ejemplo n.º 6
0
def plotSingleActivity(dataPath, gaussianDistance, ax1=None):
    b.rcParams['font.size'] = 20
    averagingWindowSize = 30
    nE = 1600
    ymax = 1
    
    if ax1==None:
        b.figure(figsize=(8,6.5))
        fig_axis = b.subplot(1,1,1)
    else:
        fig_axis = ax1
        b.sca(ax1)
        
    linewidth = 3
    path = dataPath + '/dist'+str(gaussianDistance)+'/' +'activity/'
    spikeCountTemp = np.load(path + 'spikeCountPerExample.npy')
    spikeCount = spikeCountTemp[25,:,0]#np.loadtxt(path + 'spikeCountAe.txt')
#     spikeCount = np.roll(spikeCount, 400)
    inputSpikeCount = np.roll(np.loadtxt(path + 'spikeCountXe.txt'), 400)
    
    spikeCount = movingaverage(spikeCount,averagingWindowSize)
    spikeCount /= np.max(spikeCount)
    inputSpikeCount = movingaverage(inputSpikeCount,averagingWindowSize)
    inputSpikeCount /= np.max(inputSpikeCount)
    b.plot(spikeCount, 'deepskyblue', alpha=0.6, linewidth=linewidth, label='Output')#alpha=0.5+(0.5*float(i)/float(len(lower_peaks))), 
    b.plot(inputSpikeCount, 'r', alpha=1., linewidth=linewidth, label='Input')
    fig_axis.set_xticks([0., nE/2, nE])
    fig_axis.set_xticklabels(['0', '0.5', '1'])
    fig_axis.set_yticks([0., ymax/2, ymax])
    fig_axis.spines['top'].set_visible(False)
    fig_axis.spines['right'].set_visible(False)
    fig_axis.get_xaxis().tick_bottom()
    fig_axis.get_yaxis().tick_left()
    b.ylabel('Normalized response')
    b.ylim(0,ymax)

#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))
    if ax1==None:
        b.legend(loc='upper left', fancybox=True, framealpha=0.0)
        b.savefig(dataPath + '/multipleAnglesSingleActivity.png', dpi=300)
def plotActivity(dataPath, inputStrengths, ax1=None):
    averagingWindowSize = 1
    nE = 1600
    ymax = 30
#     b.rcParams['lines.color'] = 'w'
#     b.rcParams['text.color'] = 'w'
#     b.rcParams['xtick.color'] = 'w'
#     b.rcParams['ytick.color'] = 'w'
#     b.rcParams['axes.labelcolor'] = 'w'
#     b.rcParams['axes.edgecolor'] = 'w'
    b.rcParams['font.size'] = 20
    if ax1==None:
        b.figure(figsize=(8,6.5))
        fig_axis = b.subplot(1,1,1)
    else:
        fig_axis = ax1
        b.sca(ax1)
    for i,inputStrength in enumerate(inputStrengths[:]):
        path = dataPath + '/peak_'+str(inputStrength)+'/' +'activity/'
        spikeCount = np.loadtxt(path + 'spikeCountAe.txt')
        inputSpikeCount = np.loadtxt(path + 'spikeCountXe.txt')
        
        spikeCount = movingaverage(spikeCount,averagingWindowSize)
        inputSpikeCount = movingaverage(inputSpikeCount,averagingWindowSize)
        if i==len(inputStrengths)-1:
            b.plot(inputSpikeCount, 'r', alpha=1., linewidth=3, label='Input')
            b.plot(spikeCount, 'deepskyblue', alpha=0.6, linewidth=3, label='Output')#alpha=0.5+(0.5*float(i)/float(len(numPeaks))), 
#         elif i==0:
#             b.plot(spikeCount, 'k--', alpha=1., linewidth=3)#
#             b.plot(inputSpikeCount, 'r--', alpha=1., linewidth=3)  
        else: 
            b.plot(spikeCount, 'k', alpha=0.2+(0.4*float(i)/float(len(inputStrength))), linewidth=0.6)
            b.plot(inputSpikeCount, 'r', alpha=0.2+(0.4*float(i)/float(len(inputStrength))), linewidth=0.6)
    fig_axis.set_xticks([0., nE/2, nE])
    fig_axis.set_xticklabels(['0', '0.5', '1'])
    fig_axis.set_yticks([0., ymax/2, ymax])
    fig_axis.spines['top'].set_visible(False)
    fig_axis.spines['right'].set_visible(False)
    fig_axis.get_xaxis().tick_bottom()
    fig_axis.get_yaxis().tick_left()
    b.ylabel('Firing Rate [Hz]')

    b.ylim(0,ymax)
#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))

    if ax1==None:
        b.xlabel('Neuron number (resorted)')
        b.legend(fancybox=True, framealpha=0.0, loc='upper left')
        b.savefig(dataPath + 'CueIntegration_single.png', dpi=900, transparent=True)
def lif_measures(synchrony, jitter, num_inp, freq, weight):
    # initializing (could go in a separate initializer)
    brian.reinit_default_clock(0*second)
    if brian.defaultclock.t > 0:
        warnings.warn("Clock start value > 0 : %f" % (
            brian.defaultclock.t))
    seed = int(time()+(synchrony+jitter+num_inp+freq+weight)*1e3)
    jitter = jitter*second
    freq = freq*hertz
    weight = weight*volt

    # neuron
    neuron = brian.NeuronGroup(1, "dV/dt = -V/tau : volt",
                               threshold="V>Vth", reset="V=0*mvolt",
                               refractory=1*msecond)
    neuron.V = 0*mvolt
    netw = brian.Network(neuron)
    config = {"id": seed,
              "S_in": synchrony,
              "sigma": jitter,
              "f_in": freq,
              "N_in": num_inp,
              "weight": weight}
    # inputs
    sync_inp, rand_inp = st.tools.gen_input_groups(num_inp, freq,
                                                 synchrony, jitter,
                                                 duration, dt)
    netw.add(sync_inp, rand_inp)
    # connections
    if len(sync_inp):
        sync_con = brian.Connection(sync_inp, neuron, "V", weight=weight)
        netw.add(sync_con)
    if len(rand_inp):
        rand_con = brian.Connection(rand_inp, neuron, "V", weight=weight)
        netw.add(rand_con)
    # monitors
    sync_mon = brian.SpikeMonitor(sync_inp)
    rand_mon = brian.SpikeMonitor(rand_inp)
    netw.add(sync_mon, rand_mon)
    v_mon = brian.StateMonitor(neuron, "V", record=True)
    out_mon = brian.SpikeMonitor(neuron)
    netw.add(v_mon, out_mon)
    # network operator for calculating measures every time spike is fired
    @brian.network_operation(when="end")
    def calc_measures():
        if len(out_mon[0]) > 1 and out_mon[0][-1]*second == brian.defaultclock.t:
            isi_edges = (out_mon[0][-2], out_mon[0][-1])
            isi_dura = isi_edges[1]-isi_edges[0]
            isi_dt = (int(isi_edges[0]/dt), int(isi_edges[1]/dt))
            interval_trace = v_mon[0][isi_dt[0]:isi_dt[1]+2]
            slope = (float(Vth)-interval_trace[-int(slope_w/dt)])/float(slope_w)
            # grab interval inputs
            interval_inputs = []
            for inp in sync_mon.spiketimes.itervalues():
                _idx = (isi_edges[0] < inp) & (inp < isi_edges[1])
                interval_inputs.append(inp[_idx]-isi_edges[0])
            for inp in rand_mon.spiketimes.itervalues():
                _idx = (isi_edges[0] < inp) & (inp < isi_edges[1])
                interval_inputs.append(inp[_idx]-isi_edges[0])
            kreuz =  st.metrics.kreuz.pairwise(interval_inputs,
                                              isi_edges[0], isi_edges[1],
                                              2)
            kreuz = kreuz[1][0]
            #if len(kreuz[1]) == 1:
            #    kreuz = kreuz[1][0]
            #else:
            #    warnings.warn("Kreuz metric returned multiple values.")
            #    print(kreuz[1])
            #    kreuz = brian.mean(kreuz[1])
            vp =  st.metrics.victor_purpura.pairwise(interval_inputs,
                                                    dcost)
            mod = st.metrics.modulus_metric.pairwise(interval_inputs,
                                                      isi_edges[0],
                                                      isi_edges[1]).item()
            #corr = st.metrics.corrcoef.corrcoef_spiketrains(interval_inputs,
            #                                                duration=isi_dura)
            measures.append({"slope": slope,
                             #"npss": npss,
                             "kreuz": kreuz,
                             "vp": vp,
                             "mod": mod})

    netw.add(calc_measures)
    # run
    netw.run(duration, report=None)
    brian.plot(v_mon.times, v_mon[0])
    brian.show()
    return {"id": seed, "config": config, "measures": measures}
Ejemplo n.º 9
0
b.ylim(ymin = 0, ymax = 1600)
b.savefig('evaluation' + ending, dpi = 300, transparent=True)


b.figure()
b.scatter(correctedDesDiff, correctedError[1:], c=resultMonitor[start_time+1:end_time,2], cmap=cmap.gray)
b.title('Error: ' + str(correctedErrorSum))
b.xlabel('Difference from last desired activity')
b.ylabel('Error')


b.figure()
b.scatter(correctedPopDiff, correctedError[1:], c=resultMonitor[start_time+1:end_time,2], cmap=cmap.gray)
b.title('Error: ' + str(correctedErrorSum))
b.xlabel('Difference from last population activity')
b.ylabel('Error')


b.figure()
b.scatter(resultMonitor[start_time:end_time,1], resultMonitor[start_time:end_time,0], c=resultMonitor[start_time:end_time,2], cmap=cmap.gray)
b.plot(np.linspace(0, 1, end_time - start_time), np.linspace(0, 1, end_time - start_time))
b.title('Error: ' + str(correctedErrorSum))
b.xlabel('Desired activity')
b.ylabel('Population activity')
# b.savefig('evaluation' + ending)




b.show()
Ejemplo n.º 10
0
    save_connections()
else:
    np.save(data_path + 'activity/resultPopVecs' + str(num_examples),
            result_monitor)
    np.save(data_path + 'activity/inputNumbers' + str(num_examples),
            input_numbers)

#------------------------------------------------------------------------------
# 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 + 1)
        b.plot(rate_monitors[name].times / b.second, rate_monitors[name].rate,
               '.')
        b.title('Rates of population ' + name)
    b.savefig('../plots/rate_monitors_' + str(n_e) + '_' + stdp_input +
              '_input_exc_weights_norm.png')

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)
    b.savefig('../plots/spike_monitors_' + str(n_e) + '_' + stdp_input +
              '_input_exc_weights_norm.png')

if spike_counters:
Ejemplo n.º 11
0
def hodgkin_huxley(duration=100, num=10, percent_excited=0.7, sample=1):
    """
    The hodgkin_huxley function takes the following parameters:

      duration - is the timeperiod to model for measured in milliseconds.
      num - an integer value represeting the number of neurons you want to model.
      percent_excited - a float between 0 and 1 representing the percentage of excited neurons.
      sample - gives the number of random neurons you would like plotted (default is 1)
    """
    # Assert that we are getting valid input
    assert(percent_excited >= 0 and percent_excited <= 1.0)
    assert(duration > 0)
    assert(num > 0)
    assert(sample > 0)
    assert(num >= sample)

    # Constants used in the modeling equation
    area = 20000*umetre**2
    Cm = (1*ufarad*cm**-2)*area
    gl = (5e-5*siemens*cm**-2)*area
    El = -60*mV
    EK = -90*mV
    ENa = 50*mV
    g_na = (100*msiemens*cm**-2)*area
    g_kd = (30*msiemens*cm**-2)*area
    VT = -63*mV

    # Time constants
    taue = 5*ms       # excitatory
    taui = 10*ms      # inhibitory
    
    # Reversal potentials
    Ee = 0*mV         # excitatory
    Ei = -80*mV       # inhibitory
    
    # Synaptic weights
    we = 6*nS         # excitatory
    wi = 67*nS        # inhibitory

    # The model equations
    eqs = Equations(
        '''
        dv/dt = (gl*(El-v)+ge*(Ee-v)+gi*(Ei-v)-g_na*(m*m*m)*h*(v-ENa)-g_kd*(n*n*n*n)*(v-EK))/Cm : volt
        dm/dt = alpham*(1-m)-betam*m : 1
        dn/dt = alphan*(1-n)-betan*n : 1
        dh/dt = alphah*(1-h)-betah*h : 1
        dge/dt = -ge*(1./taue) : siemens
        dgi/dt = -gi*(1./taui) : siemens
        alpham = 0.32*(mV**-1)*(13*mV-v+VT)/(exp((13*mV-v+VT)/(4*mV))-1.)/ms : Hz
        betam = 0.28*(mV**-1)*(v-VT-40*mV)/(exp((v-VT-40*mV)/(5*mV))-1)/ms : Hz
        alphah = 0.128*exp((17*mV-v+VT)/(18*mV))/ms : Hz
        betah = 4./(1+exp((40*mV-v+VT)/(5*mV)))/ms : Hz
        alphan = 0.032*(mV**-1)*(15*mV-v+VT)/(exp((15*mV-v+VT)/(5*mV))-1.)/ms : Hz
        betan = .5*exp((10*mV-v+VT)/(40*mV))/ms : Hz
        '''
    )

    # Build the neuron group
    neurons = NeuronGroup(
        num,
        model=eqs,
        threshold=EmpiricalThreshold(threshold=-20*mV,refractory=3*ms),
        implicit=True,
        freeze=True
    )

    num_excited = int(num * percent_excited)
    num_inhibited = num - num_excited
    excited = neurons.subgroup(num_excited)
    inhibited = neurons.subgroup(num_inhibited)
    excited_conn = Connection(excited, neurons, 'ge', weight=we, sparseness=0.02)
    inhibited_conn = Connection(inhibited, neurons, 'gi', weight=wi, sparseness=0.02)
    
    # Initialization
    neurons.v = El+(randn(num)*5-5)*mV
    neurons.ge = (randn(num)*1.5+4)*10.*nS
    neurons.gi = (randn(num)*12+20)*10.*nS
    
    # Record a few trace and run
    recorded = choice(num, sample)
    trace = StateMonitor(neurons, 'v', record=recorded)
    run(duration * msecond)

    for i in recorded:
        plot(trace.times/ms, trace[i]/mV)
        
    show()
Ejemplo n.º 12
0
def plotActivity(dataPath, lower_peaks, ax1=None):
    averagingWindowSize = 32
    if ax1==None:
        b.figure()
    else:
        b.sca(ax1)
    
    for i,gaussian_peak_low in enumerate(lower_peaks[:]):
        path = dataPath + '/peak_'+str(gaussian_peak_low)+'/' +'activity/'
        spikeCount = np.loadtxt(path + 'spikeCountAe.txt')
        inputSpikeCount = np.loadtxt(path + 'spikeCountXe.txt')
        
        spikeCount = movingaverage(spikeCount,averagingWindowSize)
        inputSpikeCount = movingaverage(inputSpikeCount,averagingWindowSize)
        if i==len(lower_peaks)-1:
            b.plot(spikeCount, 'k', alpha=1., linewidth=3, label='Output')#alpha=0.5+(0.5*float(i)/float(len(lower_peaks))), 
            b.plot(inputSpikeCount, 'r', alpha=1., linewidth=3, label='Input')
        elif i==0:
            b.plot(spikeCount, 'k', alpha=0.6, linewidth=3)#
            b.plot(inputSpikeCount, 'r', alpha=0.6, linewidth=3)  
        else: 
            b.plot(spikeCount, 'k', alpha=0.2+(0.4*float(i)/float(len(lower_peaks))), linewidth=0.6)
            b.plot(inputSpikeCount, 'r', alpha=0.2+(0.4*float(i)/float(len(lower_peaks))), linewidth=0.6)

    b.legend()
    b.ylim(0,35)
#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))
    if ax1==None:
        b.savefig(dataPath + 'CueIntegration.png', dpi=900)
Ejemplo n.º 13
0
if not test_mode:
    save_connections()
else:
    np.save(data_path + 'activity/resultPopVecs' + str(num_examples), result_monitor)
    np.save(data_path + 'activity/inputNumbers' + str(num_examples), input_numbers)
    

#------------------------------------------------------------------------------ 
# 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)
Ejemplo n.º 14
0
else:
    np.save(data_path + '/activity/resultPopVecs' + str(num_examples), result_monitor)
    np.save(data_path + '/activity/inputNumbers' + str(num_examples), input_numbers)
    


#------------------------------------------------------------------------------ 
# plot results
#------------------------------------------------------------------------------ 
# if not use_remote_access:
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)
Ejemplo n.º 15
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()
def plotActivity(dataPath, inputStrengths, ax1=None):
    averagingWindowSize = 10
    nE = 1600
    ymax = 40
    linewidth = 5
#     b.rcParams['lines.color'] = 'w'
#     b.rcParams['text.color'] = 'w'
#     b.rcParams['xtick.color'] = 'w'
#     b.rcParams['ytick.color'] = 'w'
#     b.rcParams['axes.labelcolor'] = 'w'
#     b.rcParams['axes.edgecolor'] = 'w'
    b.rcParams['font.size'] = 20
    if ax1==None:
        b.figure(figsize=(8,6.5))
        fig_axis = b.subplot(1,1,1)
    else:
        fig_axis = ax1
        b.sca(ax1)


    for i,inputStrength in enumerate(inputStrengths[:]):
        path = dataPath + '/in_'+str(inputStrength)+'/' +'activity/'
        spikeCount = np.loadtxt(path + 'spikeCountAe.txt')
        inputSpikeCount = np.loadtxt(path + 'spikeCountXe.txt')
        
        spikeCount = movingaverage(spikeCount,averagingWindowSize)
        inputSpikeCount = movingaverage(inputSpikeCount,averagingWindowSize)
        if i==len(inputStrengths)-1:
            b.plot([0], 'w', label=' ')#
            b.plot([0], 'w', label='Avg. input 20 Hz:')#
            b.plot(inputSpikeCount, 'coral', alpha=0.6, linewidth=linewidth, label='Input firing rate')
            b.plot(spikeCount, 'deepskyblue', alpha=0.6, linewidth=linewidth, label='Output firing rate')
        elif i==1:
            b.plot([0], 'w', label=' ')#
            b.plot([0], 'w', label='Avg. input 6 Hz:')#
            b.plot(inputSpikeCount, 'red', alpha=1., linewidth=linewidth,  label='Input firing rate')
            b.plot(spikeCount, 'blue', alpha=0.6, linewidth=linewidth, label='Output firing rate')
        elif i==0:
            b.plot([0], 'w', label='Avg. input 2 Hz:')#
            b.plot(inputSpikeCount, 'darkred', alpha=1., linewidth=linewidth, label='Input firing rate')
            b.plot(spikeCount, 'darkblue', alpha=1.0, linewidth=linewidth, label='Output firing rate')
        else: 
            b.plot(spikeCount, 'k', alpha=0.2+(0.4*float(i)/float(len(inputStrengths))), linewidth=0.6)
    b.legend(loc='upper right', fancybox=True, framealpha=0.0, fontsize = 17)




    handles, labels = fig_axis.get_legend_handles_labels()
    # fig_axis.legend(handles[::-1], labels[::-1], loc='upper left', fancybox=True, framealpha=0.0)
    fig_axis.set_xticks([0., nE/2, nE])
    fig_axis.set_yticks([0., ymax/2, ymax])
    fig_axis.spines['top'].set_visible(False)
    fig_axis.spines['right'].set_visible(False)
    fig_axis.get_xaxis().tick_bottom()
    fig_axis.get_yaxis().tick_left()
    b.xlabel('Neuron number (resorted)')
    b.ylabel('Firing rate [Hz]')
    b.ylim(0,ymax)
Ejemplo n.º 17
0
def plotActivity(dataPath, gaussianDistances, ax1=None):
    averagingWindowSize = 32
    
    if ax1==None:
        b.figure()
    else:
        b.sca(ax1)
        
    linewidth = 2
    for i,dist in enumerate(gaussianDistances[:]):
        path = dataPath + '/dist'+str(dist)+'/' +'activity/'
        spikeCountTemp = np.load(path + 'spikeCountPerExample.npy')
        spikeCount = spikeCountTemp[25,:,0]#np.loadtxt(path + 'spikeCountAe.txt')
#         spikeCount = np.roll(spikeCount, 400)
        inputSpikeCount = np.loadtxt(path + 'spikeCountXe.txt')
        
        spikeCount = movingaverage(spikeCount,averagingWindowSize)
        inputSpikeCount = movingaverage(inputSpikeCount,averagingWindowSize)
        if i==len(gaussianDistances)-1:
            b.plot(spikeCount, 'b', alpha=0.6, linewidth=linewidth, label='Max. dist output')#alpha=0.5+(0.5*float(i)/float(len(lower_peaks))), 
            b.plot(inputSpikeCount, 'r', alpha=1., linewidth=linewidth, label='Max. dist. input')
        elif i==0:
            b.plot(spikeCount, 'k--', alpha=0.6, linewidth=linewidth, label='Min. dist output')
            b.plot(inputSpikeCount, 'r--', alpha=1., linewidth=linewidth, label='Min. dist. input')
        else: 
            b.plot(spikeCount, 'k', alpha=0.2+(0.4*float(i)/float(len(gaussianDistances))), linewidth=0.6)
            b.plot(inputSpikeCount, 'r', alpha=0.2+(0.4*float(i)/float(len(gaussianDistances))), linewidth=0.6)
    b.ylim(0,35)

#         b.title('spikes:' + str(sum(spikeCount)) + ', pop. value: ' + str(computePopVector(spikeCount)))
    if ax1==None:
        b.legend(loc='upper left', fancybox=True, framealpha=0.0)
        b.savefig(dataPath + '/multipleAnglesActivity.png', dpi=300)