Exemple #1
0
def simulate_IF(I_vec):

    tStim = 700

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)

    SNR = MyGroup(NEURON_MODELS[0], 1, mm=True, sd=True, mm_dt=0.1)

    I_e0 = my_nest.GetStatus(SNR[:])[0]['I_e']
    my_nest.SetStatus(SNR[:], params={'I_e': I_e0 + I_E})  # Set I_e
    I_e = my_nest.GetStatus(SNR.ids, 'I_e')[0]

    I_vec, fIsi, mIsi, lIsi = SNR.IF(I_vec, tStim=tStim)

    speed_f = numpy.diff(1000.0 / fIsi) / numpy.diff(I_vec)
    speed_l = numpy.diff(1000.0 / lIsi) / numpy.diff(I_vec)
    speed_f = speed_f[speed_f > 0]
    speed_l = speed_l[speed_l > 0]
    s = '\n'
    s = s + 'IF:\n'
    s = s + ' %s %5s %3s \n' % ('First to Last ISI:', tStim, 'ms')
    s = s + ' %s %5s %3s \n' % ('Added I_e:', I_e, 'pA')
    s = s + ' %s %4s %s %4s %s %4s\n' % (
        'Speed first ((Hz/pA), min:', str(min(speed_f))[0:4], 'max',
        str(max(speed_f))[0:4], 'mean', str(sum(speed_f) / len(speed_f))[0:4])
    s = s + ' %s %4s %s %4s %s %4s\n' % (
        'Speed last (Hz/pA), min:', str(min(speed_l))[0:4], 'max',
        str(max(speed_l))[0:4], 'mean', str(sum(speed_l) / len(speed_l))[0:4])
    infoString = s

    return I_vec, fIsi, mIsi, lIsi, infoString
Exemple #2
0
def simulate_IV(I_vec):

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)

    SNR = MyGroup(NEURON_MODELS[0], 1, sd=True, mm=True, mm_dt=0.1)

    I_e0 = my_nest.GetStatus(SNR[:])[0]['I_e']
    my_nest.SetStatus(SNR[:], params={'I_e': I_e0 + I_E})  # Set I_e
    I_e = my_nest.GetStatus(SNR.ids, 'I_e')[0]

    I_vec, voltage = SNR.IV_I_clamp(I_vec)

    #current=current
    speed = numpy.diff(voltage) / numpy.diff(I_vec) * 1000.
    speed = speed[speed > 0]

    s = '\n'
    s = s + 'IV:\n'
    s = s + ' %s %5s %3s \n' % ('I_e:', I_e, 'pA')
    '''
    s = s + ' %s %4s %s %4s %s %4s\n' % ( 'Speed (mV/pA=MOhm), min:', 
                                          str(min(speed))[0:4],  
                                          'max',str(max(speed))[0:4],
                                          'mean', 
                                          str(sum(speed)/len(speed))[0:4])
    '''#
    infoString = s

    I_vec = numpy.array(I_vec)
    voltage = numpy.array(voltage)

    return I_vec, voltage, infoString
def simulate_voltage_ipsp(I_vec):

    v_mat = []
    ipsp_mat = []

    for receptor, syn_model in zip(['V_m', 'V_m', 'V_m'], SYNAPSE_MODELS):

        my_nest.ResetKernel()
        model_list, model_dict = models()
        my_nest.MyLoadModels(model_list, NEURON_MODELS)
        my_nest.MyLoadModels(model_list, [syn_model])

        SNR = MyGroup(NEURON_MODELS[0], 1, mm=True, mm_dt=0.1)

        voltage, ipsp = SNR.I_PSE(I_vec,
                                  synapse_model=syn_model,
                                  id=0,
                                  receptor=receptor)
        v_mat.append(voltage)
        ipsp_mat.append(ipsp)

    v_mat = numpy.array(v_mat)
    ipsp_mat = numpy.array(ipsp_mat)

    return v_mat, ipsp_mat
Exemple #4
0
def simulate_response_example_clamped_spiking(I_e):
    '''
    Response when SNR is clamped to a voltage for strong and weak synapse
    '''
    spike_at = 500.  # ms
    simTime = 700.  # ms

    my_nest.ResetKernel()
    model_list = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)
    my_nest.MyLoadModels(model_list, SYNAPES_MODELS)

    SNR = MyGroup(NEURON_MODELS[0],
                  len(SYNAPES_MODELS) + 1,
                  mm=True,
                  mm_dt=0.1,
                  params={'I_e': I_e})

    SG = my_nest.Create('spike_generator', params={'spike_times': [spike_at]})

    for i in range(len(SYNAPES_MODELS)):
        my_nest.Connect(SG, [SNR[i]], model=SYNAPES_MODELS[i])

    my_nest.MySimulate(simTime)

    SNR.get_signal('v', 'V_m', stop=simTime)  # retrieve signal
    SNR.signals['V_m'] = SNR.signals['V_m'].my_time_slice(500, 560)

    return SNR
Exemple #5
0
def simulate_voltage_ipsp(I_vec):

    simTime = 700.  # ms
    spikes_at = numpy.arange(500., len(I_vec) * simTime, simTime)  # ms

    voltage = []  # mV
    ipsp_weak = []  # mV
    ipsp_strong = []  # mV

    my_nest.ResetKernel()
    model_list = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)
    my_nest.MyLoadModels(model_list, SYNAPES_MODELS)

    SNR = MyGroup(NEURON_MODELS[0], len(SYNAPES_MODELS), mm=True, mm_dt=0.1)

    SG = my_nest.Create('spike_generator', params={'spike_times': spikes_at})

    for i in range(len(SYNAPES_MODELS)):
        my_nest.Connect(SG, [SNR[i]], model=SYNAPES_MODELS[i])

    simTimeTot = 0
    for I_e in I_vec:

        my_nest.SetStatus(SNR[:], params={'I_e': float(I_e)})
        my_nest.MySimulate(simTime)
        simTimeTot += simTime

    SNR.get_signal('v', 'V_m', stop=simTimeTot)  # retrieve signal
    simTimeAcum = 0

    for I_e in I_vec:

        signal = SNR.signals['V_m'].my_time_slice(400 + simTimeAcum,
                                                  700 + simTimeAcum)
        simTimeAcum += simTime

        clamped_at = signal[1].signal[-1]
        minV = min(signal[1].signal)
        maxV = max(signal[1].signal)
        if abs(minV - clamped_at) < abs(maxV - clamped_at):

            size_weak = max(signal[1].signal) - clamped_at
            size_strong = max(signal[2].signal) - clamped_at
        else:
            size_weak = min(signal[1].signal) - clamped_at
            size_strong = min(signal[2].signal) - clamped_at

        voltage.append(clamped_at)
        ipsp_weak.append(size_weak)
        ipsp_strong.append(size_strong)

    ipsp = numpy.array([ipsp_weak, ipsp_strong])
    return voltage, ipsp
def simulate_steady_state_freq(frequencies, flag='ss'):
    global sname_nb
    
    relativeFacilitation=[]
    model_list=models()
    data={}
    n=len(frequencies)
    
    for syn in synapseModels:
        my_nest.ResetKernel()       
        my_nest.MyLoadModels( model_list, neuronModels )
        my_nest.MyLoadModels( model_list, [syn])
        
        ss=my_nest.GetDefaults(syn)       
        synapticEficacy = ss['weight']*ss['U'] 
            
        SNR = MyGroup( neuronModels[0], n, mm_dt = .1, params={'I_e':-150.},
                       record_from=['g_GABAA_2'], spath=spath, 
                       sname_nb=sname_nb )
        sname_nb+=1
        
        tSim=3*1000/frequencies[0]  
        spikeTimes=[]        
        for f in frequencies :
            isi  = 1000./f
            spikeTimes.append(numpy.arange(1,tSim,isi))
        
        
        if not LOAD:
            for target, st in zip(SNR, spikeTimes ) :
                source = my_nest.Create('spike_generator', 
                                    params={'spike_times':st} )
                my_nest.SetDefaults(syn, params={'delay':1.})
                my_nest.Connect(source, [target], model=syn)
        
            my_nest.MySimulate(tSim)
            SNR.get_signal( 'g','g_GABAA_2', stop=tSim ) # retrieve signal
            SNR.save_signal( 'g','g_GABAA_2', stop=tSim )
        
        elif LOAD: 
            SNR.load_signal( 'g','g_GABAA_2')

        signal=SNR.signals['g_GABAA_2']
        
        tmpSteadyState=[]
        for i, st in enumerate(spikeTimes, start=1):
            
            if SNR.mm_dt==0.1:  indecies=numpy.int64(numpy.ceil(st*10))+9
            elif SNR.mm_dt==1.: indecies=numpy.int64(numpy.ceil(st))
            
            values=signal[i].signal[indecies]-signal[i].signal[indecies-1]
            
            if flag=='ss':  tmpSteadyState.append(values[-1]/synapticEficacy)
            if flag=='max': tmpSteadyState.append(max(values)/synapticEficacy)
            
        relativeFacilitation.append(tmpSteadyState)
        
    relativeFacilitation=numpy.array(relativeFacilitation)
        
    return frequencies, relativeFacilitation
def simulate_recovery(revoceryTimes):
    global sname_nb
    
    relativeRecovery=[]
    model_list=models()
    data={}
    n=len(revoceryTimes)
    
    for syn in synapseModels:
        my_nest.ResetKernel()       
        my_nest.MyLoadModels( model_list, neuronModels )
        my_nest.MyLoadModels( model_list, [syn])
        
        ss=my_nest.GetDefaults(syn)       
        synapticEficacy = ss['weight']*ss['U'] 

        SNR = MyGroup( neuronModels[0], n, mm_dt = .1, params={'I_e':-150.},
                       record_from=['g_GABAA_2'], spath=spath, 
                       sname_nb=sname_nb)
        sname_nb+=1
        
        tSim=5000
        spikeTimes=[]
        for rt in revoceryTimes:
            spikeTimes.append(numpy.array([1.,11.,21.,31.,41.,41+rt]))
            
        if not LOAD:
            for target, st in zip(SNR, spikeTimes ) :
       
                source = my_nest.Create('spike_generator', 
                                    params={'spike_times':st} )
                my_nest.SetDefaults(syn, params={'delay':1.})
                my_nest.Connect(source, [target], model=syn)
        
            my_nest.MySimulate(tSim)
            SNR.get_signal( 'g','g_GABAA_2', stop=tSim ) # retrieve signal
            SNR.save_signal( 'g','g_GABAA_2', stop=tSim )
        
        elif LOAD: 
            SNR.load_signal( 'g','g_GABAA_2')
        
        signal=SNR.signals['g_GABAA_2']
        
        tmpSteadyState=[]
        for i, st in enumerate(spikeTimes, start=1):
            
            if SNR.mm_dt==0.1:  indecies=numpy.int64(numpy.ceil(st*10))+9
            elif SNR.mm_dt==1.: indecies=numpy.int64(numpy.ceil(st))
            
            values=signal[i].signal[indecies]-signal[i].signal[indecies-1]
            
            tmpSteadyState.append(values[-1]/synapticEficacy)
            #tmpSteadyState.append(max(values)/synapticEficacy)
            
        relativeRecovery.append(tmpSteadyState)
        
    relativeRecovery=numpy.array(relativeRecovery)
        
    return revoceryTimes, relativeRecovery
def simulate_basa_line_SNr(msn_rate, gpe_rate, stn_rate, n_msn, n_gpe, n_stn, neuron_model, snr_current, sim_time=1000, threads=8, stn_syn='STN_SNR_ampa_s'):

    SNR_INJECTED_CURRENT=snr_current
    SYNAPSE_MODEL_BACKROUND_STN=[stn_syn]
    
    model_list, model_dict=models()
    my_nest.ResetKernel(threads=threads)       
    my_nest.MyLoadModels( model_dict, neuron_model )
    my_nest.MyLoadModels( model_dict, SYNAPSE_MODEL_BACKROUND_MSN)       
    my_nest.MyLoadModels( model_dict, SYNAPSE_MODEL_BACKROUND_GPE)      
    my_nest.MyLoadModels( model_dict, SYNAPSE_MODEL_BACKROUND_STN)      
    
    SNR_list=[] # List with SNR groups for synapse. 
    
    if n_msn>0: MSN_base=MyPoissonInput(n=n_msn, sd=True)
    if n_gpe>0: GPE=MyPoissonInput(n=n_gpe, sd=False)
    if n_stn>0: STN=MyPoissonInput(n=n_stn, sd=False)
    
    if n_msn>0: MSN_base.set_spike_times(rates=[ msn_rate], times=[1], t_stop=sim_time, seed=0)    
    if n_gpe>0: GPE.set_spike_times(rates=[gpe_rate], times=[1], t_stop=sim_time, seed=0)     
    if n_stn>0: STN.set_spike_times(rates=[stn_rate], times=[1], t_stop=sim_time, seed=0)     
           
    I_e=my_nest.GetDefaults(neuron_model[0])['I_e']+SNR_INJECTED_CURRENT

    SNR=MyGroup( neuron_model[0], n=1, sd=True, params={'I_e':I_e}, mm_dt=.1, mm=True)    

        
    if n_msn>0: my_nest.Connect(MSN_base[:], SNR[:]*len(MSN_base[:]), model=SYNAPSE_MODEL_BACKROUND_MSN[0])
    if n_gpe>0: my_nest.Connect(GPE[:],SNR[:]*len(GPE[:]), model=SYNAPSE_MODEL_BACKROUND_GPE[0])   
    if n_stn>0: my_nest.Connect(STN[:],SNR[:]*len(STN[:]), model=SYNAPSE_MODEL_BACKROUND_STN[0])
                    
    my_nest.MySimulate(sim_time)    
    
    SNR.get_signal( 's', start=0, stop=sim_time )
    
    meanRate=round(SNR.signals['spikes'].mean_rate(1000,sim_time),1)
    spk=SNR.signals['spikes'].time_slice(1000,sim_time).raw_data()
    CV=numpy.std(numpy.diff(spk[:,0],axis=0))/numpy.mean(numpy.diff(spk[:,0],axis=0))

    SNR.get_signal( 'v',recordable='V_m', start=0, stop=sim_time )  
    SNR.signals['V_m'].my_set_spike_peak( 15, spkSignal= SNR.signals['spikes'] ) 
    pylab.rcParams.update( {'path.simplify':False}    )
    SNR.signals['V_m'].plot()
    pylab.title(str(meanRate)+ 'Hz, CV='+str(CV))
    pylab.show()
    
   
    return 
def simulate_ahp(I_vec):

    simTime = 3000.  # ms
    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)

    n = len(I_vec)

    STN = MyGroup(NEURON_MODELS[0], n, sd=True, mm=True, mm_dt=1.0)
    I_e0 = my_nest.GetStatus(STN[:])[0]['I_e']
    #my_nest.SetStatus(STN[:], params={'I_e':-10.}) # Set I_e
    my_nest.SetStatus(STN[:], params={'I_e': 1.0})  # Set I_e
    I_e = my_nest.GetStatus(STN.ids, 'I_e')[0]
    scg = my_nest.Create('step_current_generator', n=n)
    rec = my_nest.GetStatus(STN[:])[0]['receptor_types']

    for source, target, I in zip(scg, STN[:], I_vec):
        my_nest.SetStatus([source], {
            'amplitude_times': [500., 1000.],
            'amplitude_values': [float(I), 0.]
        })
        my_nest.Connect([source], [target],
                        params={'receptor_type': rec['CURR']})

    my_nest.MySimulate(simTime)

    STN.get_signal('s')  # retrieve signal
    STN.signals['spikes'] = STN.signals['spikes'].time_slice(700, 2000)

    delays = []
    for i, curr in enumerate(I_vec):
        delays.append(
            max(
                numpy.diff(
                    STN.signals['spikes'].spiketrains[i + 1.0].spike_times)))

    meanRate = round(STN.signals['spikes'].mean_rate(0, 500), 1)

    s = '\n'
    s = s + 'Example inhibitory current:\n'
    s = s + ' %s %5s %3s %s %5s %3s \n' % ('Mean rate:', meanRate, 'Hz', 'I_e',
                                           I_e, 'pA')
    s = s + 'Steps:\n'
    s = s + ' %5s %3s \n' % (I_vec, 'pA')
    infoString = s

    return I_vec, delays
Exemple #10
0
def plot_text(ax, infoString=''):

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)

    SNR = MyGroup(NEURON_MODELS[0], 1, mm_dt=0.1)
    statusSNR = my_nest.GetStatus(SNR[:])[0]

    tb = ''
    tb = tb + infoString

    tb = tb + '\n'
    for key, val in statusSNR.iteritems():
        if not key in [
                'vp', 'state', 't_spike', 'local', 'parent', 'Delta_T',
                'tau_minus_triplet', 'address', 't_ref', 'thread', 'frozen',
                'archiver_length', 'global_id', 'local_id', 'recordables',
                'receptor_types'
        ]:
            tb = tb + ' %s %5s %3s \n' % (key + ':', str(val), '--')

    ax.text(
        0.85,
        0.5,
        tb,
        fontsize=font_size_text,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes,  # to define coordinates in right scale
        **{'fontname': 'monospace'})

    ax.my_remove_axis(xaxis=True, yaxis=True)
    ax.my_remove_spine(left=True, bottom=True, right=True, top=True)
def plot_text(ax, infoString=''):

    my_nest.ResetKernel()
    model_list = models()
    my_nest.MyLoadModels(model_list, neuronModels)

    SNR = MyGroup(neuronModels[0], 1, mm_dt=0.1)
    statusSNR = my_nest.GetStatus(SNR[:])[0]

    tb = ''

    tb = tb + ' %s %10s\n' % ('Neuron model', statusSNR['model'])
    tb = tb + infoString

    tb = tb + '\n'

    ax.text(
        0.85,
        0.5,
        tb,
        fontsize=font_size_text,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes,  # to define coordinates in right scale
        **{'fontname': 'monospace'})

    ax.my_remove_axis(xaxis=True, yaxis=True)
    ax.my_remove_spine(left=True, bottom=True, right=True, top=True)
def plot_text(ax, info_string=''):

    my_nest.ResetKernel()
    MODEL_LIST = models()
    my_nest.MyLoadModels(MODEL_LIST, NEURON_MODELS)

    SNR = MyGroup(NEURON_MODELS[0], 1, mm_dt=0.1)
    statusSNR = my_nest.GetStatus(SNR[:])[0]

    tb = ''
    tb = tb + info_string

    tb = tb + '\n'

    ax.text(
        0.85,
        0.5,
        tb,
        fontsize=font_size_text,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes,  # to define coordinates in right scale
        **{'fontname': 'monospace'})

    ax.my_remove_axis(xaxis=True, yaxis=True)
    ax.my_remove_spine(left=True, bottom=True, right=True, top=True)
def simulate_basa_line_GPe(msn_rate, stn_rate, gpe_rate,  n_msn, n_stn, n_gpe, neuron_model, syn_models, gpe_current, sim_time=1000, threads=8):
    
    
    model_list, model_dict=models()
    my_nest.ResetKernel(threads=threads)       
    my_nest.MyLoadModels( model_dict, neuron_model )
    my_nest.MyLoadModels( model_dict, syn_models)       
    
    SNR_list=[] # List with SNR groups for synapse. 
    
    if n_msn>0: MSN=MyPoissonInput(n=n_msn, sd=False)
    if n_stn>0: STN=MyPoissonInput(n=n_stn, sd=False)
    if n_gpe>0: GPE=MyPoissonInput(n=n_gpe, sd=False)
    
    if n_msn>0: MSN.set_spike_times(rates=[msn_rate], times=[1], t_stop=sim_time, seed=0)    
    if n_stn>0: STN.set_spike_times(rates=[stn_rate], times=[1], t_stop=sim_time, seed=0)     
    if n_gpe>0: GPE.set_spike_times(rates=[gpe_rate], times=[1], t_stop=sim_time, seed=0)  
               
    I_e=my_nest.GetDefaults(neuron_model[0])['I_e']+gpe_current

    GPE_target=MyGroup( neuron_model[0], n=1, sd=True, params={'I_e':I_e}, 
                 mm_dt=.1, mm=True)    
        
    if n_msn>0: my_nest.Connect(MSN[:], GPE_target[:]*len(MSN[:]), model=syn_models[0])
    if n_stn>0: my_nest.Connect(STN[:],GPE_target[:]*len(STN[:]), model=syn_models[1])   
    if n_gpe>0: my_nest.Connect(GPE[:],GPE_target[:]*len(GPE[:]), model=syn_models[2])   
                    
    my_nest.MySimulate(sim_time)    
    
    GPE_target.get_signal( 's', start=0, stop=sim_time )
    
    meanRate=round(GPE_target.signals['spikes'].mean_rate(1000,sim_time),1)
    spk=GPE_target.signals['spikes'].time_slice(1000,sim_time).raw_data()
    CV=numpy.std(numpy.diff(spk[:,0],axis=0))/numpy.mean(numpy.diff(spk[:,0],axis=0))

    GPE_target.get_signal( 'v',recordable='V_m', start=0, stop=sim_time )   
    GPE_target.signals['V_m'].my_set_spike_peak( 15, spkSignal= GPE_target.signals['spikes'] ) 
    
             
    pylab.rcParams.update( {'path.simplify':False}    )
    
    GPE_target.signals['V_m'].plot()
    pylab.title(str(meanRate)+ 'Hz, CV='+str(CV))
    pylab.show()
    
   
    return        
def simulate_response_example_clamped_silent(I_e):
    '''
    Response when SNR is clamped to a voltage for Ref 2 and Ref 1 synapse
    '''
    spike_at = 500.  # ms
    simTime = 700.  # ms

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)
    my_nest.MyLoadModels(model_list, SYNAPSE_MODELS)

    SNR = MyGroup(NEURON_MODELS[0],
                  len(SYNAPSE_MODELS),
                  mm=True,
                  mm_dt=0.1,
                  params={'I_e': I_e})

    SG = my_nest.Create('spike_generator', params={'spike_times': [spike_at]})

    for i in range(len(SYNAPSE_MODELS)):
        my_nest.Connect(SG, [SNR[i]], model=SYNAPSE_MODELS[i])

    my_nest.MySimulate(simTime)

    SNR.get_signal('v', 'V_m', stop=simTime)  # retrieve signal
    SNR.signals['V_m'] = SNR.signals['V_m'].my_time_slice(400, 700)

    clamped_at = SNR.signals['V_m'][1].signal[-1]
    size_MSN_weak = min(SNR.signals['V_m'][1].signal) - clamped_at
    size_MSN_strong = min(SNR.signals['V_m'][2].signal) - clamped_at
    size_GPE_ref = min(SNR.signals['V_m'][3].signal) - clamped_at
    s = ''
    s = s + ' %s %5s %3s \n' % ('Clamped at:', str(round(clamped_at, 1)), 'mV')
    s = s + ' %s %5s %3s \n' % (r'$\delta_w^{MSN}$',
                                str(round(size_MSN_weak, 1)), 'mV')
    s = s + ' %s %5s %3s \n' % (r'$\delta_s^{MSN}$',
                                str(round(size_MSN_strong, 1)), 'mV')
    s = s + ' %s %5s %3s \n' % (r'$\delta_s^{MSN}$', str(round(
        size_GPE_ref, 1)), 'mV')

    infoString = s

    return SNR, infoString
Exemple #15
0
def simulate_example(I_e):

    simTime = 1000.  # ms

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)

    I_e0 = my_nest.GetDefaults(NEURON_MODELS[0])['I_e']
    SNR = MyGroup(NEURON_MODELS[0],
                  1,
                  sd=True,
                  mm=True,
                  mm_dt=1.,
                  params={'I_e': I_e + I_e0})

    my_nest.MySimulate(simTime)
    SNR.get_signal('v', 'V_m', stop=simTime)  # retrieve signal

    SNR.get_signal('s')  # retrieve signal
    meanRate = round(SNR.signals['spikes'].mean_rate(0, 1000), 1)
    print SNR.signals['spikes'].isi()
    SNR.signals['V_m'].my_set_spike_peak(21, spkSignal=SNR.signals['spikes'])

    s = '\n'
    s = s + 'Example:\n'
    s = s + ' %s %5s %3s %s %5s %3s \n' % ('Mean rate:', meanRate, 'Hz', 'I_e',
                                           I_e, 'pA')

    infoString = s

    return SNR, infoString
def create_output_population(nOutput, outputAddCurrent, outputName, sname,
                             spath):

    create_models(outputName)

    Output = MyGroup(outputName, nOutput, mm_dt=1.0, sname=sname, spath=spath)

    I_e = my_nest.GetStatus(Output.local_ids, 'I_e')[0]

    # add  output current
    my_nest.SetStatus(Output[:], {'I_e': I_e + outputAddCurrent})

    return Output
def create_input_population(nInput, nRep=1, simTime=20000):
    ''' Define input as inhomogenous poisson processes '''

    spike_times = []
    inputName = 'spike_generator'
    Input = MyGroup(inputName,
                    nInput,
                    mm_dt=1.0,
                    spath=spath,
                    sname='MSN',
                    mm=False,
                    sd=False)
    for i in range(nInput):
        rates = meanInputRates[:]
        times = meanInputTimings[:]

        if Input.ids[i] in selectedInputIds:
            rates.extend(selectedInputRates)
            times.extend(selectedInputTimings)

        rates.append(inbetweenInputRate)
        times.append(inbetweenInputTime)

        spikes = misc.inh_poisson_spikes(rates,
                                         times,
                                         t_stop=simTime,
                                         n_rep=nRep,
                                         seed=i)

        # create spike list for input
        for spk in spikes:
            spike_times.append((i, spk))
        my_nest.SetStatus([Input.ids[i]], params={'spike_times': spikes})

    # add spike list for input to input spike list
    Input.signals['spikes'] = my_signals.MySpikeList(spike_times, Input.ids)

    return Input
Exemple #18
0
def plot_text(ax, infoString=''):

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)
    my_nest.MyLoadModels(model_list, SYNAPSE_MODELS)
    my_nest.MyLoadModels(model_list,
                         ['GPE_SNR_gaba_s_ref', 'GPE_SNR_gaba_s_max'])

    SNR = MyGroup(NEURON_MODELS[0], 2, mm_dt=0.1)
    statusSNR = my_nest.GetStatus(SNR[:])[0]

    statusSynapes = []
    for s in SYNAPSE_MODELS:
        statusSynapes.append(my_nest.GetDefaults(s))
    tb = ''
    tb = tb + infoString

    for ss in statusSynapes:
        tb = tb + '\n'
        tb = tb + ' %s %10s\n' % ('Synapse', ss['synapsemodel'])
        tb = tb + ' %s %5s %3s\n' % ('Weight', str(round(ss['weight'],
                                                         1)), 'nS')

        tb = tb + ' %s %5s %3s \n' % ('U:', str(ss['U']), '--')
        tb = tb + ' %s %5s %3s \n' % ('tau_fac:', str(ss['tau_fac']), 'ms')
        tb = tb + ' %s %5s %3s \n' % ('tau_rec:', str(ss['tau_rec']), 'ms')
        tb = tb + ' %s %5s %3s \n' % ('tau_psc:', str(ss['tau_psc']), 'ms')
        synapticEficacy = ss['weight'] * ss['U']
        tb = tb + ' %s %5s %3s \n' % ('P1:', synapticEficacy, 'nS')

    sw = my_nest.GetDefaults('GPE_SNR_gaba_s_ref')
    tb = tb + ' %s %5s %3s \n' % (r'$ref_{32 Hz}^{GPe}$ fraction',
                                  str(sw['weight'] / synapticEficacy), '--')
    sw = my_nest.GetDefaults('GPE_SNR_gaba_s_max')
    tb = tb + ' %s %5s %3s \n' % (r'$dep^{GPe}$ max', str(sw['weight']), '--')
    ax.text(
        0.85,
        0.5,
        tb,
        fontsize=font_size_text,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes,  # to define coordinates in right scale
        **{'fontname': 'monospace'})

    ax.my_remove_axis(xaxis=True, yaxis=True)
    ax.my_remove_spine(left=True, bottom=True, right=True, top=True)
def simulate_basa_line_STN(ctx_rate,
                           gpe_rate,
                           n_ctx,
                           n_gpe,
                           neuron_model,
                           syn_models,
                           stn_current,
                           sim_time=1000,
                           threads=8,
                           w_GPE_STN=0):

    Params_in = {}
    if w_GPE_STN: Params_in['GPE_STN_gaba_s'] = w_GPE_STN

    model_list, model_dict = models(Params_in)
    my_nest.ResetKernel(threads=threads)
    my_nest.MyLoadModels(model_dict, neuron_model)
    my_nest.MyLoadModels(model_dict, syn_models)

    SNR_list = []  # List with SNR groups for synapse.

    if n_ctx > 0: CTX = MyPoissonInput(n=n_ctx, sd=True)
    if n_gpe > 0: GPE = MyPoissonInput(n=n_gpe, sd=False)

    if n_ctx > 0:
        CTX.set_spike_times(rates=[ctx_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)
    if n_gpe > 0:
        GPE.set_spike_times(rates=[gpe_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)

    I_e = my_nest.GetDefaults(neuron_model[0])['I_e'] + stn_current

    STN = MyGroup(neuron_model[0],
                  n=1,
                  sd=True,
                  params={'I_e': I_e},
                  mm_dt=.1,
                  mm=True)

    if n_ctx > 0:
        my_nest.Connect(CTX[:], STN[:] * len(CTX[:]), model=syn_models[0])
    if n_gpe > 0:
        my_nest.Connect(GPE[:], STN[:] * len(GPE[:]), model=syn_models[1])

    my_nest.MySimulate(sim_time)

    STN.get_signal('s', start=0, stop=sim_time)
    STN.get_signal('v', recordable='V_m', start=0, stop=sim_time)

    return STN
Exemple #20
0
def plot_text(ax, infoString):

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)
    my_nest.MyLoadModels(model_list, SYNAPSE_MODELS)

    SNR = MyGroup(NEURON_MODELS[0], 2, mm_dt=0.1)
    statusSNR = my_nest.GetStatus(SNR[:])[0]

    statusSynapes = []
    for s in SYNAPSE_MODELS:
        statusSynapes.append(my_nest.GetDefaults(s))
    tb = ''
    tb = tb + infoString

    tb = tb + '\n'
    tb = tb + 'Neuron models:\n '
    tb = tb + ' %s \n' % (NEURON_MODELS[0])

    tb = tb + '\n'
    tb = tb + ' %s %5s %3s \n' % ('E rev:', str(
        statusSNR['GABAA_1_E_rev']), 'mV')
    tb = tb + ' %s %5s %3s \n' % ('Tau_decay:',
                                  str(statusSNR['GABAA_1_Tau_decay']), 'mV')

    tb = tb + ' %s %5s %3s \n' % ('E rev:', str(statusSNR['AMPA_E_rev']), 'mV')
    tb = tb + ' %s %5s %3s \n' % ('Tau_decay:', str(
        statusSNR['AMPA_Tau_decay']), 'mV')
    for ss in statusSynapes:
        tb = tb + '\n'
        tb = tb + ' %s %10s\n' % ('Synapse', ss['synapsemodel'])
        tb = tb + ' %s %5s %3s\n' % ('Weight', str(round(ss['weight'],
                                                         1)), 'nS')

    ax.text(
        0.85,
        0.5,
        tb,
        fontsize=font_size_text,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes,  # to define coordinates in right scale
        **{'fontname': 'monospace'})

    ax.my_remove_axis(xaxis=True, yaxis=True)
    ax.my_remove_spine(left=True, bottom=True, right=True, top=True)
def simulate_example_inh_current(I_vec):

    simTime = 1000.  # ms
    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)
    df = my_nest.GetDefaults(NEURON_MODELS[0])
    n = len(I_vec)

    STN = MyGroup(NEURON_MODELS[0],
                  n,
                  sd=True,
                  mm=True,
                  mm_dt=1.0,
                  record_from=['V_m', 'u'])
    I_e0 = my_nest.GetStatus(STN[:])[0]['I_e']
    my_nest.SetStatus(STN[:], params={'I_e': I_e0 + I_E + 50})  # Set I_e

    I_e = my_nest.GetStatus(STN.ids, 'I_e')[0]
    scg = my_nest.Create('step_current_generator', n=n)
    rec = my_nest.GetStatus(STN[:])[0]['receptor_types']

    for source, target, I in zip(scg, STN[:], I_vec):
        my_nest.SetStatus([source], {
            'amplitude_times': [280., 700.],
            'amplitude_values': [float(I), 0.]
        })
        my_nest.Connect([source], [target],
                        params={'receptor_type': rec['CURR']})

    my_nest.MySimulate(simTime)
    STN.get_signal('v', 'V_m', stop=simTime)  # retrieve signal
    STN.get_signal('s')  # retrieve signal
    STN.signals['V_m'].my_set_spike_peak(21, spkSignal=STN.signals['spikes'])

    e = my_nest.GetStatus(STN.mm)[0]['events']  # get events
    #pylab.plot(e['u'])
    #pylab.show()
    meanRate = round(STN.signals['spikes'].mean_rate(0, 500), 1)

    s = '\n'
    s = s + 'Example inhibitory current:\n'
    s = s + ' %s %5s %3s %s %5s %3s \n' % ('Mean rate:', meanRate, 'Hz', 'I_e',
                                           I_e, 'pA')
    s = s + 'Steps:\n'
    s = s + ' %5s %3s \n' % (I_vec, 'pA')
    infoString = s

    return STN, infoString
Exemple #22
0
def plot_text(ax, infoString=''):

    my_nest.ResetKernel()
    model_list = models()
    my_nest.MyLoadModels(model_list, neuronModels)
    my_nest.MyLoadModels(model_list, synapseModels)

    SNR = MyGroup(neuronModels[0], 2, mm_dt=0.1)
    statusSNR = my_nest.GetStatus(SNR[:])[0]

    statusSynapes = []
    for s in synapseModels:
        statusSynapes.append(my_nest.GetDefaults(s))
    tb = ''
    tb = tb + infoString

    for ss in statusSynapes:
        tb = tb + '\n'
        tb = tb + ' %s %10s\n' % ('Synapse', ss['synapsemodel'])
        tb = tb + ' %s %5s %3s\n' % ('Weight', str(round(ss['weight'],
                                                         1)), 'nS')

        if 'U' in ss.keys():
            tb = tb + ' %s %5s %3s \n' % ('U:', str(ss['U']), '--')
            tb = tb + ' %s %5s %3s \n' % ('tau_fac:', str(ss['tau_fac']), 'ms')
            tb = tb + ' %s %5s %3s \n' % ('tau_rec:', str(ss['tau_rec']), 'ms')
            tb = tb + ' %s %5s %3s \n' % ('tau_psc:', str(ss['tau_psc']), 'ms')

    ax.text(
        0.85,
        0.5,
        tb,
        fontsize=font_size_text,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes,  # to define coordinates in right scale
        **{'fontname': 'monospace'})

    ax.my_remove_axis(xaxis=True, yaxis=True)
    ax.my_remove_spine(left=True, bottom=True, right=True, top=True)
def simulate_example(I_e):

    simTime = 3000.  # ms

    my_nest.ResetKernel()
    model_list, model_dict = models()
    my_nest.MyLoadModels(model_list, NEURON_MODELS)

    I_e0 = my_nest.GetDefaults(NEURON_MODELS[0])['I_e']
    STN = MyGroup(NEURON_MODELS[0],
                  1,
                  sd=True,
                  mm=True,
                  mm_dt=1.,
                  params={'I_e': I_e + I_e0})
    '''
    scg = my_nest.Create( 'step_current_generator',n=1 )  
    rec=my_nest.GetStatus(STN[:])[0]['receptor_types']
    

    my_nest.SetStatus(scg, {'amplitude_times':[280.,1700.],
                                'amplitude_values':[100.0,0.]})
    my_nest.Connect( scg, STN.ids, 
                         params = { 'receptor_type' : rec['CURR'] } )
    
    '''
    my_nest.MySimulate(simTime)
    STN.get_signal('v', 'V_m', stop=simTime)  # retrieve signal

    STN.get_signal('s')  # retrieve signal
    meanRate = round(STN.signals['spikes'].mean_rate(0, 1000), 1)
    print STN.signals['spikes'].isi()
    STN.signals['V_m'].my_set_spike_peak(21, spkSignal=STN.signals['spikes'])

    s = '\n'
    s = s + 'Example:\n'
    s = s + ' %s %5s %3s %s %5s %3s \n' % ('Mean rate:', meanRate, 'Hz', 'I_e',
                                           I_e, 'pA')

    infoString = s

    return STN, infoString
Exemple #24
0
def simulate_example_rebound_spike(I_vec):
    
    simTime  = 5000.  # ms
    my_nest.ResetKernel()
    model_list, model_dict=models()
    my_nest.MyLoadModels( model_list, NEURON_MODELS )
    
    n=len(I_vec)
    
    GPE = MyGroup( NEURON_MODELS[0], n, sd=True,  mm=True, mm_dt = 1.0 )
    I_e0=my_nest.GetStatus(GPE[:])[0]['I_e']
    #my_nest.SetStatus(GPE[:], params={'I_e':-10.}) # Set I_e
    my_nest.SetStatus(GPE[:], params={'I_e':-10.}) # Set I_e
    I_e = my_nest.GetStatus(GPE.ids,'I_e')[0]
    scg = my_nest.Create( 'step_current_generator',n=n )  
    rec=my_nest.GetStatus(GPE[:])[0]['receptor_types']
    
    for source, target, I in zip(scg, GPE[:], I_vec):
        my_nest.SetStatus([source], {'amplitude_times':[500.,700.],
                                'amplitude_values':[float(I),0.]})
        my_nest.Connect( [source], [target], 
                         params = { 'receptor_type' : rec['CURR'] } )
    
    
    my_nest.MySimulate(simTime)
    GPE.get_signal( 'v','V_m', stop=simTime ) # retrieve signal
    GPE.get_signal( 's') # retrieve signal
    GPE.signals['V_m'].my_set_spike_peak( 21, spkSignal= GPE.signals['spikes'] )

    
    
    meanRate=round(GPE.signals['spikes'].mean_rate(0,500),1)

    s='\n'
    s =s + 'Example inhibitory current:\n'
    s = s + ' %s %5s %3s %s %5s %3s \n' % ( 'Mean rate:', meanRate,  'Hz', 
                                            'I_e', I_e,'pA' )
    s = s + 'Steps:\n'
    s = s + ' %5s %3s \n' % ( I_vec,  'pA' )
    infoString=s
    
    return GPE, infoString
Exemple #25
0
def simulate_basa_line_SNr(msn_rate,
                           gpe_rate,
                           stn_rate,
                           n_msn,
                           n_gpe,
                           n_stn,
                           neuron_model,
                           snr_current,
                           sim_time=1000,
                           threads=8,
                           stn_syn='STN_SNR_ampa_s'):

    SNR_INJECTED_CURRENT = snr_current
    SYNAPSE_MODEL_BACKROUND_STN = [stn_syn]

    model_list, model_dict = models()
    my_nest.ResetKernel(threads=threads)
    my_nest.MyLoadModels(model_dict, neuron_model)
    my_nest.MyLoadModels(model_dict, SYNAPSE_MODEL_BACKROUND_MSN)
    my_nest.MyLoadModels(model_dict, SYNAPSE_MODEL_BACKROUND_GPE)
    my_nest.MyLoadModels(model_dict, SYNAPSE_MODEL_BACKROUND_STN)

    SNR_list = []  # List with SNR groups for synapse.

    if n_msn > 0: MSN_base = MyPoissonInput(n=n_msn, sd=True)
    if n_gpe > 0: GPE = MyPoissonInput(n=n_gpe, sd=False)
    if n_stn > 0: STN = MyPoissonInput(n=n_stn, sd=False)

    if n_msn > 0:
        MSN_base.set_spike_times(rates=[msn_rate],
                                 times=[1],
                                 t_stop=sim_time,
                                 seed=0)
    if n_gpe > 0:
        GPE.set_spike_times(rates=[gpe_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)
    if n_stn > 0:
        STN.set_spike_times(rates=[stn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)

    I_e = my_nest.GetDefaults(neuron_model[0])['I_e'] + SNR_INJECTED_CURRENT

    SNR = MyGroup(neuron_model[0],
                  n=1,
                  sd=True,
                  params={'I_e': I_e},
                  mm_dt=.1,
                  mm=True)

    if n_msn > 0:
        my_nest.Connect(MSN_base[:],
                        SNR[:] * len(MSN_base[:]),
                        model=SYNAPSE_MODEL_BACKROUND_MSN[0])
    if n_gpe > 0:
        my_nest.Connect(GPE[:],
                        SNR[:] * len(GPE[:]),
                        model=SYNAPSE_MODEL_BACKROUND_GPE[0])
    if n_stn > 0:
        my_nest.Connect(STN[:],
                        SNR[:] * len(STN[:]),
                        model=SYNAPSE_MODEL_BACKROUND_STN[0])

    my_nest.MySimulate(sim_time)

    SNR.get_signal('s', start=0, stop=sim_time)

    meanRate = round(SNR.signals['spikes'].mean_rate(1000, sim_time), 1)
    spk = SNR.signals['spikes'].time_slice(1000, sim_time).raw_data()
    CV = numpy.std(numpy.diff(spk[:, 0], axis=0)) / numpy.mean(
        numpy.diff(spk[:, 0], axis=0))

    SNR.get_signal('v', recordable='V_m', start=0, stop=sim_time)
    SNR.signals['V_m'].my_set_spike_peak(15, spkSignal=SNR.signals['spikes'])
    pylab.rcParams.update({'path.simplify': False})
    SNR.signals['V_m'].plot()
    pylab.title(str(meanRate) + 'Hz, CV=' + str(CV))
    pylab.show()

    return
Exemple #26
0
def simulate_network(params_msn_d1,
                     params_msn_d2,
                     params_stn,
                     synapse_models,
                     sim_time,
                     seed,
                     I_e_add,
                     threads=1,
                     start_rec=0,
                     model_params={}):
    '''
        params_msn_d1 - dictionary with timing and burst freq setup for msn
                     {'base_rates':[0.1, 0.1, ..., 0.1], #Size number of actions 
                      'mod_rates': [[20,0,...,0],
                                    [0,20,...,0],...[0,0,...,20]] #size number of actions times number of events   
                      'mod_times':[[500,1000],[1500,2000],[9500,10000]] # size number of events 
                      'n_neurons':500}
                      
        params_msn_d2 - dictionary with timing and burst freq setup for gpe
        params_stn    - dictionary {'rate':50}
                     same as params_msn
        neuron_model - string, the neuron model to use 
        synapse_models - dict, {'MSN':'...', 'GPE':,'...', 'STN':'...'}
        sim_time - simulation time
        seed - seed for random generator
        I_e_add - diabled
        start_rec - start recording from
        model_params - general model paramters
    '''

    I_e_add = {'SNR': 300, 'STN': 0, 'GPE': 30}
    f = 0.01  #0.01#0.5

    I_e_variation = {'GPE': 25 * f, 'SNR': 100 * f, 'STN': 10 * f}

    my_nest.ResetKernel(threads=8)
    numpy.random.seed(seed)

    params = {
        'conns': {
            'MSN_D1_SNR': {
                'syn': synapse_models[0]
            },
            'GPE_SNR': {
                'syn': synapse_models[1]
            }
        }
    }

    params = misc.dict_merge(model_params, params)

    model_list, model_dict = models()
    group_list, group_dict, connect_list, connect_params = network(
        model_dict, params)
    print connect_params

    groups = {}
    for name, model, setup in group_list:

        # Update input current
        my_nest.MyLoadModels(model_dict, [model])
        if name in I_e_add.keys():
            I_e = my_nest.GetDefaults(model)['I_e'] + I_e_add[name]
            my_nest.SetDefaults(model, {'I_e': I_e})

        groups[name] = []
        for action in range(connect_params['misc']['n_actions']):
            if model in ['MSN_D1_spk_gen', 'MSN_D2_spk_gen']:
                group = MyPoissonInput(params=setup,
                                       sd=True,
                                       sd_params={
                                           'start': start_rec,
                                           'stop': sim_time
                                       })
            else:
                group = MyGroup(params=setup,
                                sd=True,
                                mm=False,
                                mm_dt=0.1,
                                sd_params={
                                    'start': start_rec,
                                    'stop': sim_time
                                })

            groups[name].append(group)

    for action in range(connect_params['misc']['n_actions']):
        groups['MSN_D1'][action].set_spike_times(
            list(params_msn_d1['mod_rates'][action]),
            list(params_msn_d1['mod_times']),
            sim_time,
            ids=groups['MSN_D1'][action].ids)
        groups['MSN_D2'][action].set_spike_times(
            params_msn_d2['mod_rates'][action],
            params_msn_d2['mod_times'],
            sim_time,
            ids=groups['MSN_D2'][action].ids)

    # Create neurons and synapses
    for source, target, props in connect_list:
        my_nest.MyLoadModels(model_dict, [props['model']])

        for action in range(connect_params['misc']['n_actions']):

            pre = list(groups[source][action].ids)
            post = list(groups[target][action].ids)
            my_nest.MyRandomConvergentConnect(pre, post, params=props)

    STN_CTX_input_base = my_nest.Create('poisson_generator',
                                        params={
                                            'rate': params_stn['rate'],
                                            'start': 0.,
                                            'stop': sim_time
                                        })
    my_nest.MyLoadModels(model_dict, ['CTX_STN_ampa_s'])

    for action in range(connect_params['misc']['n_actions']):
        my_nest.DivergentConnect(STN_CTX_input_base,
                                 groups['STN'][action].ids,
                                 model='CTX_STN_ampa_s')

    my_nest.MySimulate(sim_time)

    for action in range(connect_params['misc']['n_actions']):
        groups['MSN_D1'][action].get_signal('s',
                                            start=start_rec,
                                            stop=sim_time)
        groups['MSN_D2'][action].get_signal('s',
                                            start=start_rec,
                                            stop=sim_time)
        groups['GPE'][action].get_signal('s', start=start_rec, stop=sim_time)
        groups['SNR'][action].get_signal('s', start=start_rec, stop=sim_time)
        groups['STN'][action].get_signal('s', start=start_rec, stop=sim_time)

    return groups
Exemple #27
0
def simulate_basa_line_GPe(msn_rate,
                           stn_rate,
                           gpe_rate,
                           n_msn,
                           n_stn,
                           n_gpe,
                           neuron_model,
                           syn_models,
                           gpe_current,
                           sim_time=1000,
                           threads=8):

    model_list, model_dict = models()
    my_nest.ResetKernel(threads=threads)
    my_nest.MyLoadModels(model_dict, neuron_model)
    my_nest.MyLoadModels(model_dict, syn_models)

    SNR_list = []  # List with SNR groups for synapse.

    if n_msn > 0: MSN = MyPoissonInput(n=n_msn, sd=False)
    if n_stn > 0: STN = MyPoissonInput(n=n_stn, sd=False)
    if n_gpe > 0: GPE = MyPoissonInput(n=n_gpe, sd=False)

    if n_msn > 0:
        MSN.set_spike_times(rates=[msn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)
    if n_stn > 0:
        STN.set_spike_times(rates=[stn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)
    if n_gpe > 0:
        GPE.set_spike_times(rates=[gpe_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)

    I_e = my_nest.GetDefaults(neuron_model[0])['I_e'] + gpe_current

    GPE_target = MyGroup(neuron_model[0],
                         n=1,
                         sd=True,
                         params={'I_e': I_e},
                         mm_dt=.1,
                         mm=True)

    if n_msn > 0:
        my_nest.Connect(MSN[:],
                        GPE_target[:] * len(MSN[:]),
                        model=syn_models[0])
    if n_stn > 0:
        my_nest.Connect(STN[:],
                        GPE_target[:] * len(STN[:]),
                        model=syn_models[1])
    if n_gpe > 0:
        my_nest.Connect(GPE[:],
                        GPE_target[:] * len(GPE[:]),
                        model=syn_models[2])

    my_nest.MySimulate(sim_time)

    GPE_target.get_signal('s', start=0, stop=sim_time)

    meanRate = round(GPE_target.signals['spikes'].mean_rate(1000, sim_time), 1)
    spk = GPE_target.signals['spikes'].time_slice(1000, sim_time).raw_data()
    CV = numpy.std(numpy.diff(spk[:, 0], axis=0)) / numpy.mean(
        numpy.diff(spk[:, 0], axis=0))

    GPE_target.get_signal('v', recordable='V_m', start=0, stop=sim_time)
    GPE_target.signals['V_m'].my_set_spike_peak(
        15, spkSignal=GPE_target.signals['spikes'])

    pylab.rcParams.update({'path.simplify': False})

    GPE_target.signals['V_m'].plot()
    pylab.title(str(meanRate) + 'Hz, CV=' + str(CV))
    pylab.show()

    return
def simulate_selection_vs_neurons(selection_intervals=[0.0, 500.0],
                                  hz=20,
                                  load=True):
    global SNR_INJECTED_CURRENT
    global NEURON_MODELS
    global N_GPE
    global N_MSN_BURST
    global N_MSN
    global GPE_BASE_RATE
    global FILE_NAME
    global OUTPUT_PATH
    global SYNAPSE_MODELS_TESTED
    global SEL_ONSET

    #n_exp=100
    n_exp = 2

    if hz > 7:
        n_max_sel = 60
    if hz > 20:
        n_max_sel = 30
    else:
        n_max_sel = 100

    RATE_BASE = 0.1
    RATE_SELE = hz
    save_result_at = (OUTPUT_PATH + '/' + FILE_NAME +
                      '-simulate_selection_vs_neurons' + str(hz) + '-hz.pkl')
    save_header_at = (OUTPUT_PATH + '/' + FILE_NAME +
                      '-simulate_selection_vs_neurons' + str(hz) +
                      '-hz_header')

    burst_time = 500.
    sim_time = burst_time + SEL_ONSET + 500.

    EXPERIMENTS = range(n_exp)

    MODEL_LIST = models()
    my_nest.ResetKernel()
    my_nest.MyLoadModels(MODEL_LIST, NEURON_MODELS)
    my_nest.MyLoadModels(MODEL_LIST, SYNAPSE_MODELS_TESTED)
    my_nest.MyLoadModels(MODEL_LIST, SYNAPSE_MODELS_BACKGROUND)

    MSN_list = []  # MSN input for each experiment
    for i_exp in EXPERIMENTS:
        MSN = MyPoissonInput(n=N_MSN + n_max_sel, sd=True)
        MSN_list.append(MSN)

    GPE_list = []  # GPE input for each experiment
    for i_exp in EXPERIMENTS:
        GPE = MyPoissonInput(n=N_GPE, sd=True)
        GPE_list.append(GPE)

    SNR_list = []  # SNR groups for each synapse and number of selected MSN
    SNR_list_experiments = []
    for i_syn, syn in enumerate(SYNAPSE_MODELS_TESTED):
        SNR = []
        for i_sel in range(n_max_sel + 1):  # Plus one to get no burst point

            I_e = my_nest.GetDefaults(
                NEURON_MODELS[0])['I_e'] + SNR_INJECTED_CURRENT
            SNR.append(
                MyGroup(NEURON_MODELS[0],
                        n=n_exp,
                        sd=True,
                        params={'I_e': I_e}))

        SNR_list.append(SNR)

    if not load:
        for i_exp in EXPERIMENTS:
            MSN = MSN_list[i_exp]
            GPE = GPE_list[i_exp]

            # Set spike times
            # Base rate
            for id in MSN[1:N_MSN]:
                MSN.set_spike_times(id=id,
                                    rates=[RATE_BASE],
                                    times=[1],
                                    t_stop=sim_time,
                                    seed=int(numpy.random.random() * 10000.0))

            # Selection
            for id in MSN[N_MSN:N_MSN + n_max_sel]:
                rates = [RATE_BASE, RATE_SELE, RATE_BASE]
                times = [1, SEL_ONSET, burst_time + SEL_ONSET]
                t_stop = sim_time
                MSN.set_spike_times(id=id,
                                    rates=rates,
                                    times=times,
                                    t_stop=t_stop,
                                    seed=int(numpy.random.random() * 10000.0))

            # Base rate GPE
            for id in GPE[:]:
                GPE.set_spike_times(id=id,
                                    rates=[GPE_BASE_RATE],
                                    times=[1],
                                    t_stop=sim_time,
                                    seed=int(numpy.random.random() * 10000.0))

            # Connect
            for i_syn, syn in enumerate(SYNAPSE_MODELS_TESTED):
                # i_sel goes over 0,..., n_max_sel
                for i_sel in range(0, n_max_sel + 1):
                    target = SNR_list[i_syn][i_sel][i_exp]

                    my_nest.ConvergentConnect(MSN[0:N_MSN - i_sel], [target],
                                              model=syn)
                    my_nest.ConvergentConnect(MSN[N_MSN:N_MSN + i_sel],
                                              [target],
                                              model=syn)
                    my_nest.ConvergentConnect(
                        GPE[:], [target], model=SYNAPSE_MODELS_BACKGROUND[0])

        my_nest.MySimulate(sim_time)

        for SNR_sel in SNR_list:
            for SNR in SNR_sel:
                SNR.get_signal('s')

        sel_interval_mean_rates = []
        sel_interval_mean_rates_std = []
        for i_interval, interval in enumerate(selection_intervals):
            t1 = selection_intervals[i_interval][0]
            t2 = selection_intervals[i_interval][1]

            mean_rates = []
            mean_rates_std = []

            # Time until arrival of spikes in SNr
            delay = my_nest.GetDefaults(SYNAPSE_MODELS_BACKGROUND[0])['delay']
            for SNR_sel in SNR_list:
                m_r = []
                m_r_std = []
                for SNR in SNR_sel:

                    m_r.append(SNR.signals['spikes'].mean_rate(
                        SEL_ONSET + t1 + delay, SEL_ONSET + t2 + delay))
                    m_r_std.append(SNR.signals['spikes'].mean_rate_std(
                        SEL_ONSET + t1 + delay, SEL_ONSET + t2 + delay))

                mean_rates.append(m_r)
                mean_rates_std.append(m_r_std)

            mean_rates = numpy.array(mean_rates)
            mean_rates_std = numpy.array(mean_rates_std)

            sel_interval_mean_rates.append(mean_rates)
            sel_interval_mean_rates_std.append(mean_rates_std)

        nb_neurons = numpy.arange(0, n_max_sel + 1, 1)

        s = '\n'
        s = s + ' %s %5s %3s \n' % ('N MSNs:', str(N_MSN), '#')
        s = s + ' %s %5s %3s \n' % ('N experiments:', str(n_exp), '#')
        s = s + ' %s %5s %3s \n' % ('MSN base rate:', str(MSN_BASE_RATE), 'Hz')
        s = s + ' %s %5s %3s \n' % ('MSN burst rate:', str(MSN_BURST_RATE),
                                    'Hz')
        s = s + ' %s %5s %3s \n' % ('GPe rate:', str(GPE_BASE_RATE), 'Hz')
        s = s + ' %s %5s %3s \n' % ('Burst time:', str(burst_time), 'ms')
        s = s + ' %s %5s %3s \n' % ('SNR_INJECTED_CURRENT:',
                                    str(SNR_INJECTED_CURRENT), 'pA')
        for i_interval, interval in enumerate(selection_intervals):
            s = s + ' %s %5s %3s \n' % ('Sel interval ' + str(i_interval) +
                                        ':', str(selection_intervals), 'ms')

        info_string = s

        header = HEADER_SIMULATION_SETUP + s
        misc.text_save(header, save_header_at)
        misc.pickle_save([
            nb_neurons, sel_interval_mean_rates, sel_interval_mean_rates_std,
            info_string
        ], save_result_at)

    elif load:
        nb_neurons, sel_interval_mean_rates, sel_interval_mean_rates_std, info_string = misc.pickle_load(
            save_result_at)

    return nb_neurons, sel_interval_mean_rates, sel_interval_mean_rates_std, info_string
def simulate_example(load=True):

    global SNR_INJECTED_CURRENT
    global NEURON_MODELS
    global N_GPE
    global N_MSN_BURST
    global N_MSN
    global GPE_BASE_RATE
    global FILE_NAME
    global OUTPUT_PATH
    global SYNAPSE_MODELS_TESTED
    global SEL_ONSET

    #n_exp =200 # number of experiments
    n_exp = 20  # number of experiments

    # Path were raw data is saved. For example the spike trains.
    save_result_at = OUTPUT_PATH + '/' + FILE_NAME + '-simulate_example.pkl'
    save_header_at = OUTPUT_PATH + '/' + FILE_NAME + '-simulate_example_header'

    burst_time = 500.
    sim_time = burst_time + SEL_ONSET + 1000.

    MODEL_LIST = models()
    my_nest.ResetKernel()
    my_nest.MyLoadModels(MODEL_LIST, NEURON_MODELS)
    my_nest.MyLoadModels(MODEL_LIST, SYNAPSE_MODELS_TESTED)
    my_nest.MyLoadModels(MODEL_LIST, SYNAPSE_MODELS_BACKGROUND)

    SNR_list = []  # List with SNR groups for synapse.
    if not load:
        MSN_base = MyPoissonInput(n=N_MSN_BASE * n_exp, sd=True)
        MSN_burst = MyPoissonInput(n=N_MSN_BURST * n_exp, sd=True)
        GPE = MyPoissonInput(n=N_GPE * n_exp, sd=True)

        # Set spike times MSN and GPe
        # Non bursting MSNs

        for id in MSN_base[:]:
            seed = numpy.random.random_integers(0, 1000000.0)
            MSN_base.set_spike_times(id=id,
                                     rates=[MSN_BASE_RATE],
                                     times=[1],
                                     t_stop=sim_time,
                                     seed=seed)

        # Background GPe
        for id in GPE[:]:
            seed = numpy.random.random_integers(0, 1000000.0)
            GPE.set_spike_times(id=id,
                                rates=[GPE_BASE_RATE],
                                times=[1],
                                t_stop=sim_time,
                                seed=seed)

        # Bursting MSNs
        for id in MSN_burst[:]:
            rates = [MSN_BASE_RATE, MSN_BURST_RATE, MSN_BASE_RATE]
            times = [1, SEL_ONSET, burst_time + SEL_ONSET]
            t_stop = sim_time
            seed = numpy.random.random_integers(0, 1000000.0)

            MSN_burst.set_spike_times(id=id,
                                      rates=rates,
                                      times=times,
                                      t_stop=t_stop,
                                      seed=seed)

        for i_syn in range(len(SYNAPSE_MODELS_TESTED)):

            params = []
            I_e = my_nest.GetDefaults(
                NEURON_MODELS[0])['I_e'] + SNR_INJECTED_CURRENT
            for i in range(n_exp):
                #params.append({'I_e':numpy.random.normal(I_e,
                #                                         0.1*I_e)})
                params.append({'I_e': I_e})

            #{'I_e':SNR_INJECTED_CURRENT}
            SNR = MyGroup(NEURON_MODELS[0],
                          n=n_exp,
                          sd=True,
                          params=params,
                          mm_dt=.1,
                          record_from=[''])

            SNR_list.append(SNR)

        # Connect, experiment specific
        sources_MSN_SNR_base = numpy.arange(0, n_exp * N_MSN_BASE)
        sources_MSN_SNR_burst = numpy.arange(0, n_exp * N_MSN_BURST)

        targets_MSN_SNR_base = numpy.mgrid[0:n_exp, 0:N_MSN_BASE][0].reshape(
            1, N_MSN_BASE * n_exp)[0]
        targets_MSN_SNR_burst = numpy.mgrid[0:n_exp, 0:N_MSN_BURST][0].reshape(
            1, N_MSN_BURST * n_exp)[0]

        sources_GPE_SNR = numpy.arange(0, n_exp * N_GPE)
        targets_GPE_SNR = numpy.mgrid[0:n_exp,
                                      0:N_GPE][0].reshape(1, N_GPE * n_exp)[0]

        for i_syn, syn in enumerate(SYNAPSE_MODELS_TESTED):
            syn = SYNAPSE_MODELS_TESTED[i_syn]
            SNR = SNR_list[i_syn]
            my_nest.Connect(MSN_base[sources_MSN_SNR_base],
                            SNR[targets_MSN_SNR_base],
                            model=syn)
            my_nest.Connect(MSN_burst[sources_MSN_SNR_burst],
                            SNR[targets_MSN_SNR_burst],
                            model=syn)
            my_nest.Connect(GPE[sources_GPE_SNR],
                            SNR[targets_GPE_SNR],
                            model=SYNAPSE_MODELS_BACKGROUND[0])

        my_nest.MySimulate(sim_time)

        MSN_base.get_signal('s', start=0, stop=sim_time)
        MSN_burst.get_signal('s', start=0, stop=sim_time)

        for SNR in SNR_list:
            SNR.get_signal('s', start=0, stop=sim_time)

        # Get firing rates of MSNs
        MSN_firing_rates = []

        MSN_all = copy.deepcopy(MSN_base)
        MSN_all.merge(MSN_burst)

        time_bin = 20.
        groups = [MSN_base, MSN_burst, MSN_all]
        for group in groups:
            timeAxis, firingRates = group.signals['spikes'].my_firing_rate(
                bin=time_bin, display=False)
            MSN_firing_rates.append([timeAxis, firingRates])

        # Pick out spikes for burst, base and all to use in scatter plot
        MSN_spikes_and_ids = []

        g1 = MSN_burst.slice(MSN_burst[0:N_MSN_BURST])
        g2 = MSN_base.slice(MSN_base[0:N_MSN_BASE])

        ids_MSN_burst = range(450, 450 + N_MSN_BURST)
        ids_MSN_base = [id for id in range(N_MSN) if id not in IDS_MSN_BURST]

        # Rename ids for plotting purpose

        g1_dict = dict([[id1, id2] for id1, id2 in zip(g1.ids, ids_MSN_burst)])
        g2_dict = dict([[id1, id2] for id1, id2 in zip(g2.ids, ids_MSN_base)])

        groups = [g1, g2]
        dics = [g1_dict, g2_dict]
        for group, dic in zip(groups, dics):
            raw_data = group.signals['spikes'].raw_data()
            for i in range(raw_data.shape[0]):
                raw_data[i, 1] = dic[raw_data[i, 1]]
            MSN_spikes_and_ids.append(raw_data)

        #times, binned_data=MSN_base.signals['spikes'].binned_raw_data(0, sim_time, res=1, clip=0)
        #filtered_binned_data=misc.time_resolved_rate(binned_data, 100, kernel_type='triangle', res=1)

        pre_ref_1 = str(SNR_list[0].signals['spikes'].mean_rate(
            SEL_ONSET - 500, SEL_ONSET))
        pre_ref_2 = str(SNR_list[1].signals['spikes'].mean_rate(
            SEL_ONSET - 500, SEL_ONSET))
        pre_dyn = str(SNR_list[2].signals['spikes'].mean_rate(
            SEL_ONSET - 500, SEL_ONSET))

        s = '\n'
        s = s + 'Simulate example:\n'
        s = s + '%s %5s %3s \n' % ('N experiments:', str(n_exp), '#')
        s = s + '%s %5s %3s \n' % ('Bin size MSN hz:', str(time_bin), 'ms')
        s = s + '%s %5s %3s \n' % ('MSN base rate:', str(MSN_BASE_RATE), 'Hz')
        s = s + '%s %5s %3s \n' % ('MSN burst rate:', str(MSN_BURST_RATE),
                                   'Hz')
        s = s + '%s %5s %3s \n' % ('GPe rate:', str(GPE_BASE_RATE), 'Hz')
        s = s + '%s %5s %3s \n' % ('Burst time:', str(burst_time), 'ms')
        s = s + '%s %5s %3s \n' % ('Pre sel rate Ref:', pre_ref_1[0:4], 'Hz')
        s = s + '%s %5s %3s \n' % ('Pre sel rate Ref:', pre_ref_2[0:4], 'Hz')
        s = s + '%s %5s %3s \n' % ('Pre sel rate Dyn:', pre_dyn[0:4], 'Hz')

        header = HEADER_SIMULATION_SETUP + s

        misc.pickle_save([MSN_firing_rates, MSN_spikes_and_ids, SNR_list, s],
                         save_result_at)
        misc.text_save(header, save_header_at)

    else:
        MSN_firing_rates, MSN_spikes_and_ids, SNR_list, s = misc.pickle_load(
            save_result_at)

    return MSN_firing_rates, MSN_spikes_and_ids, SNR_list, s
def simulate_basa_line_SNr(msn_rate,
                           gpe_rate,
                           stn_rate,
                           n_msn,
                           n_gpe,
                           n_stn,
                           neuron_model,
                           syn_models,
                           snr_current,
                           sim_time=1000,
                           threads=8,
                           w_STN_SNR=0,
                           seed=0,
                           record_vm=True,
                           multiple=False):

    if not multiple:
        Params_in = {}
        if w_STN_SNR: Params_in['STN_SNR_ampa_s'] = w_STN_SNR

        model_list, model_dict = models(Params_in)

        my_nest.ResetKernel(threads=threads)
        my_nest.MyLoadModels(model_dict, neuron_model)
        my_nest.MyLoadModels(model_dict, syn_models)

    SNR_list = []  # List with SNR groups for synapse.

    if n_msn > 0: MSN = MyPoissonInput(n=n_msn, sd=True)
    if n_gpe > 0: GPE = MyPoissonInput(n=n_gpe, sd=False)
    if n_stn > 0: STN = MyPoissonInput(n=n_stn, sd=False)

    if n_msn > 0:
        MSN.set_spike_times(rates=[msn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=seed)
    if n_gpe > 0:
        GPE.set_spike_times(rates=[gpe_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=seed)
    if n_stn > 0:
        STN.set_spike_times(rates=[stn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=seed)

    I_e = my_nest.GetDefaults(neuron_model[0])['I_e'] + snr_current

    SNR = MyGroup(neuron_model[0],
                  n=1,
                  sd=True,
                  params={'I_e': I_e},
                  mm_dt=.1,
                  mm=record_vm)

    if n_msn > 0:
        my_nest.Connect(MSN[:], SNR[:] * len(MSN[:]), model=syn_models[0])
    if n_gpe > 0:
        my_nest.Connect(GPE[:], SNR[:] * len(GPE[:]), model=syn_models[1])
    if n_stn > 0:
        my_nest.Connect(STN[:], SNR[:] * len(STN[:]), model=syn_models[2])

    return SNR
def simulate_basa_line_GPe(msn_rate,
                           stn_rate,
                           gpe_rate,
                           n_msn,
                           n_stn,
                           n_gpe,
                           neuron_model,
                           syn_models,
                           gpe_current,
                           sim_time=1000,
                           threads=8,
                           w_GPE_GPE=False,
                           w_STN_GPE=False):

    Params_in = {}
    if w_GPE_GPE: Params_in['GPE_GPE_gaba_s'] = w_GPE_GPE
    if w_STN_GPE: Params_in['STN_GPE_ampa_s'] = w_STN_GPE

    model_list, model_dict = models(Params_in)
    my_nest.ResetKernel(threads=threads)
    my_nest.MyLoadModels(model_dict, neuron_model)
    my_nest.MyLoadModels(model_dict, syn_models)

    SNR_list = []  # List with SNR groups for synapse.

    if n_msn > 0: MSN = MyPoissonInput(n=n_msn, sd=False)
    if n_stn > 0: STN = MyPoissonInput(n=n_stn, sd=False)
    if n_gpe > 0: GPE = MyPoissonInput(n=n_gpe, sd=False)

    if n_msn > 0:
        MSN.set_spike_times(rates=[msn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)
    if n_stn > 0:
        STN.set_spike_times(rates=[stn_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)
    if n_gpe > 0:
        GPE.set_spike_times(rates=[gpe_rate],
                            times=[1],
                            t_stop=sim_time,
                            seed=0)

    I_e = my_nest.GetDefaults(neuron_model[0])['I_e'] + gpe_current

    GPE_target = MyGroup(neuron_model[0],
                         n=1,
                         sd=True,
                         params={'I_e': I_e},
                         mm_dt=.1,
                         mm=True)

    if n_msn > 0:
        my_nest.Connect(MSN[:],
                        GPE_target[:] * len(MSN[:]),
                        model=syn_models[0])
    if n_stn > 0:
        my_nest.Connect(STN[:],
                        GPE_target[:] * len(STN[:]),
                        model=syn_models[1])
    if n_gpe > 0:
        my_nest.Connect(GPE[:],
                        GPE_target[:] * len(GPE[:]),
                        model=syn_models[2])

    my_nest.MySimulate(sim_time)

    GPE_target.get_signal('s', start=0, stop=sim_time)
    GPE_target.get_signal('v', recordable='V_m', start=0, stop=sim_time)

    return GPE_target
sys.path.append(model_dir)
sys.path.append(code_dir + '/nest_toolbox')
spath = os.getcwd() + '/output/' + sys.argv[0].split('/')[-1].split('.')[0]

from model_params import models  # Then import models
from src import misc, my_nest, my_signals, plot_settings
from src.my_population import MyGroup
from src.my_axes import MyAxes

my_nest.ResetKernel()

model_list = models()  # Get model list
for model in model_list:
    my_nest.CopyModel(model[0], model[1], model[2])  # Create models
neuron_model = 'MSN_izh'
MSN = MyGroup(neuron_model, 3, mm_dt=0.1)

#! Spike train experiment 1. Train of 8 spikes at 20 Hz and the recovery spike
#! at 550 ms as in Planert 2009
spike_times = range(10, 430, 50)
spike_times.extend([430 + 550])

# input
sgs = my_nest.Create('spike_generator',
                     params={'spike_times': [float(sp) for sp in spike_times]})

syn_model = 'MSN_MSN_gaba_s'
my_nest.Connect(sgs, [MSN[0]], model=syn_model)  # connect MSNs
T = 2000  # simulation time
my_nest.Simulate(T)  # simulate