コード例 #1
0
def test_multysinapse():
    neuron1 = nest.Create("iaf_psc_alpha_multisynapse_neuron")
    neuron2 = nest.Create("iaf_psc_alpha_multisynapse_neuron")

    nest.SetDefaults("iaf_psc_alpha_multisynapse", {"tau_syn": [1.0, 2.0]})

    spikegenerator = nest.Create('spike_generator',
                                 params={'spike_times': [100.0, 200.0]})

    syn_dict = {"model": "static_synapse", "weight": 2.5, 'receptor_type': 1}

    nest.Connect(spikegenerator, neuron2, syn_spec=syn_dict)
    nest.Connect(spikegenerator, neuron1, syn_spec=syn_dict)

    # nest.SetStatus(neuron1, {"I_e": 376.0})
    # nest.SetStatus(neuron2, {"I_e": 376.0})

    multimeter1 = nest.Create('multimeter')
    multimeter2 = nest.Create('multimeter')

    V_m_specifier = 'V_m'  # 'delta_V_m'
    nest.SetStatus(multimeter1, {
        "withtime": True,
        "record_from": [V_m_specifier]
    })
    nest.SetStatus(multimeter2, {
        "withtime": True,
        "record_from": [V_m_specifier]
    })

    nest.Connect(multimeter1, neuron1)
    nest.Connect(multimeter2, neuron2)

    nest.Simulate(400.0)
    dmm1 = nest.GetStatus(multimeter1)[0]
    Vms1 = dmm1["events"][V_m_specifier]
    ts1 = dmm1["events"]["times"]

    events1 = dmm1["events"]
    pylab.figure(1)

    dmm2 = nest.GetStatus(multimeter2)[0]
    Vms2 = dmm2["events"][V_m_specifier]
    ts2 = dmm2["events"]["times"]

    pylab.plot(ts1, Vms1)
    pylab.plot(ts2, Vms2)

    pylab.show()

    for index in range(0, len(Vms1)):
        if abs(Vms1[index] - Vms2[index]) > 0.000001:
            print('!!!!!!!!!!!!!!!!!!!!')
            print(
                str(Vms1[index]) + " divers from  " + str(Vms2[index]) +
                " at iteration: " + str(index) + " of overall iterations: " +
                str(len(Vms1)))
            print('!!!!!!!!!!!!!!!!!!!!')
            raise Exception("TEST FAILED")
        elif abs(Vms1[index] - Vms2[index]) > 0:
            print("Greater than 0 difference" +
                  str(abs(Vms1[index] - Vms2[index])) + " at iteration: " +
                  str(index) + " of overall iterations: " + str(len(Vms1)))
    print("Test: PASSED")
コード例 #2
0
def create(model, number):
    """Allow multiple model instance to be unpack as they are created."""
    return map(lambda x: (x, ), nest.Create(model, number))
コード例 #3
0
#
# To directly simulate the mesoscopic population activities (i.e. generating
# the activity of a finite-size population without simulating single
# neurons), we can build the populations using the NEST model
# ``gif_pop_psc_exp``:

nest.set_verbosity("M_WARNING")
nest.ResetKernel()
nest.SetKernelStatus({
    'resolution': dt,
    'print_time': True,
    'local_num_threads': 1
})
t0 = nest.GetKernelStatus('time')

nest_pops = nest.Create('gif_pop_psc_exp', M)

C_m = 250.  # irrelevant value for membrane capacity, cancels out in simulation
g_L = C_m / tau_m

params = [
    {
        'C_m': C_m,
        'I_e': mu[i] * g_L[i],
        'lambda_0': c[i],  # in Hz!
        'Delta_V': Delta_u[i],
        'tau_m': tau_m[i],
        'tau_sfa': tau_theta[i],
        'q_sfa': J_theta[i] / tau_theta[i],  # [J_theta]= mV*ms -> [q_sfa]=mV
        'V_T_star': V_th[i],
        'V_reset': V_reset[i],
コード例 #4
0
    'period_first': 500.0,
    'period_second': 500.0,
    'rate_first': 1000.,
    'rate_second': 800.
}

df = nest.GetDefaults("aeif_cond_exp")
# pp(df)

nest.CopyModel("aeif_cond_exp", "STN", getPramsSTN())

# rec=nest.GetDefaults("my_aeif_cond_exp")["receptor_types"]
# pp(rec)
n = nest.Create(**{
    'model': 'poisson_generator_periodic',
    'n': 1000,
    'params': par
})

# n=nest.Create(**{
#     'model':'poisson_generator',
#     'n':1000,
#     'params':{'rate':900.}})

m = nest.Create('aeif_cond_exp', 1000)
# m=nest.Create('my_aeif_cond_exp', 100)
# m=nest.Create('izhik_cond_exp', 100)
#
nest.CopyModel(
    "static_synapse",
    "excitatory",
コード例 #5
0
    if (Dt >= 0):
        fact = Wplus * math.exp(-Dt / tau_plus)
        w1 = w + fact * math.pow(1.0 - w / Wmax, mu_plus)
        if w1 > Wmax:
            w1 = Wmax

    else:
        fact = -alpha * Wplus * math.exp(Dt / tau_minus)
        w1 = w + fact * math.pow(w / Wmax, mu_minus)
        if w1 < 0.0:
            w1 = 0.0
    return w1


# presynaptic and postsynaptic neurons
neuron_pre = nest.Create("parrot_neuron")
neuron_post = nest.Create("parrot_neuron")

#spike generators
sg_pre = nest.Create("spike_generator")
sg_post = nest.Create("spike_generator")

# spike times
spike_times_pre = [4.0]
spike_times_post = [1.0, 5.0]
nest.SetStatus(sg_pre, {"spike_times": spike_times_pre})
nest.SetStatus(sg_post, {"spike_times": spike_times_post})

# connect spike generators to neurons
syn_dict = {"weight": 1.0, "delay": 1.0}
nest.Connect(sg_pre, neuron_pre, "one_to_one", syn_dict)
コード例 #6
0
    def create_network(self):

        #! =============================
        #! Configuration of the network
        #! =============================

        # Load the LIF neuron model
        model = nest.Models(mtype='nodes',sel='iaf_bw_2003')
        if not model:
            nest.Install("mymodule")

        # Layers are configured as free layers (no spatial structure)
        pos_exc = [[np.random.uniform(-self.extent/2.0,self.extent/2.0),
                    np.random.uniform(-self.extent/2.0,self.extent/2.0)]
                    for j in range(self.N_exc)]
        layerProps_exc = {
            'positions': pos_exc,
            'extent'   : [self.extent, self.extent],
            'edge_wrap': False
            }

        pos_inh = [[np.random.uniform(-self.extent/2.0,self.extent/2.0),
                    np.random.uniform(-self.extent/2.0,self.extent/2.0)]
                    for j in range(self.N_inh)]
        layerProps_inh = {
            'positions': pos_inh,
            'extent'   : [self.extent, self.extent],
            'edge_wrap': False
            }

        # Layers of thalamocortical and cortical-cortical inputs have a single
        # poisson generator that sends independent spike trains to each cell,
        # instead of a layer with multiple poisson generators (to decrease
        # memory consumption)
        pos_th = [[np.random.uniform(-self.extent/2.0,self.extent/2.0),
                    np.random.uniform(-self.extent/2.0,self.extent/2.0)]
                    for j in range(1)]
        layerProps_th = {
            'positions': pos_th,
            'extent'   : [self.extent, self.extent],
            'edge_wrap': False
            }

        pos_cc = [[np.random.uniform(-self.extent/2.0,self.extent/2.0),
                    np.random.uniform(-self.extent/2.0,self.extent/2.0)]
                    for j in range(1)]
        layerProps_cc = {
            'positions': pos_cc,
            'extent'   : [self.extent, self.extent],
            'edge_wrap': False
            }

        # There is one parrot neuron for each excitatory/inhibitory cell of the network
        pos_parrot = [[np.random.uniform(-self.extent/2.0,self.extent/2.0),
                        np.random.uniform(-self.extent/2.0,self.extent/2.0)]
                        for j in range(self.N_exc + self.N_inh)]
        layerProps_parrot = {
            'positions': pos_parrot,
            'extent'   : [self.extent, self.extent],
            'edge_wrap': False
            }

        # NEST Kernel and Network settings
        np.random.seed(int(time.time()))
        seeds = np.arange(self.num_threads) + int((time.time()*100)%2**32) # Seeds
                                        # are different in each simulation
        nest.ResetKernel()
        nest.ResetNetwork()
        nest.SetKernelStatus({"local_num_threads": self.num_threads,
                              "resolution": self.simstep,
                              "data_path": os.path.abspath(os.path.join(__file__ ,"../results")),
                              "rng_seeds": list(seeds)})

        # Define properties of neuron models
        nest.CopyModel("iaf_bw_2003", "exc_cell", self.excitatory_cell_params)
        nest.CopyModel("iaf_bw_2003", "inh_cell", self.inhibitory_cell_params)

        # Thalamocortical and cortical-cortical inputs are defined as poisson generators
        nest.CopyModel("inhomogeneous_poisson_generator", "thalamocortical_input")
        nest.CopyModel("inhomogeneous_poisson_generator", "cortical_input")

        # Create layers
        self.exc = tp.CreateLayer(tools.updateDicts(layerProps_exc, {'elements': 'exc_cell'}))
        self.inh = tp.CreateLayer(tools.updateDicts(layerProps_inh, {'elements': 'inh_cell'}))
        self.thalamo = tp.CreateLayer(tools.updateDicts(layerProps_th,
                                {'elements': 'thalamocortical_input'}))
        self.cort = tp.CreateLayer(tools.updateDicts(layerProps_cc,
                                {'elements': 'cortical_input'}))
        # The layers of parrot neurons are used to compute the PSP (see below).
        # They also facilitate the computation of spike times from external inputs
        self.parrot_layer_th = tp.CreateLayer(tools.updateDicts(layerProps_parrot,
                                {'elements': 'parrot_neuron'}))
        self.parrot_layer_cc = tp.CreateLayer(tools.updateDicts(layerProps_parrot,
                                {'elements': 'parrot_neuron'}))

        # Ornstein-Uhlenbeck process (solved by Euler method)
        time_array = np.arange(self.simstep,self.simtime-
        self.simstep,self.simstep)
        OU_n = len(time_array)  # Number of time steps.
        # Define renormalized variables (to avoid recomputing these constants
        # at every time step)
        OU_sigma_bis = self.OU_sigma * np.sqrt(2. / self.OU_tau)
        OU_sqrtdt = np.sqrt(self.simstep)
        OU_x = np.zeros(OU_n) # OU output

        for i in range(OU_n - 1):
            OU_x[i + 1] = OU_x[i] + self.simstep * (-OU_x[i]  / self.OU_tau) + \
                OU_sigma_bis * OU_sqrtdt * np.random.randn()

        # Sinusoidal rate
        v_signal = self.A_ext * np.sin(2.0 * np.pi * self.f_ext *
         time_array/1000.0) + self.v_0

        # Final rate of the Poisson generators
        for n in nest.GetLeaves(self.thalamo)[0]:
            nest.SetStatus([n],{'rate_times' : time_array,
            'rate_values':v_signal})

        for n in nest.GetLeaves(self.cort)[0]:
            nest.SetStatus([n],{'rate_times' : time_array,
            'rate_values':OU_x})

        # Recurrent connections
        # (the size of the mask is big enough to ensure all cells are included within it)
        dict_exc_exc_recurrent = {
            "connection_type":"convergent",
            "mask": {'rectangular': {'lower_left':[-self.extent,-self.extent],
                                    'upper_right':[self.extent,self.extent]}},
            "kernel": self.P,
            "synapse_model": 'static_synapse',
            "weights": self.exc_exc_recurrent,
            "sources": {"model": 'exc_cell'},
            "targets": {"model": 'exc_cell'},
            "allow_autapses":False,
            "allow_multapses":False
        }

        dict_exc_inh_recurrent = {
            "connection_type":"convergent",
            "mask": {'rectangular': {'lower_left':[-self.extent,-self.extent],
                                    'upper_right':[self.extent,self.extent]}},
            "kernel": self.P,
            "synapse_model": 'static_synapse',
            "weights": self.exc_inh_recurrent,
            "sources": {"model": 'exc_cell'},
            "targets": {"model": 'inh_cell'},
            "allow_autapses":False,
            "allow_multapses":False
        }

        dict_inh_inh_recurrent = {
            "connection_type":"convergent",
            "mask": {'rectangular': {'lower_left':[-self.extent,-self.extent],
                                    'upper_right':[self.extent,self.extent]}},
            "kernel": self.P,
            "synapse_model": 'static_synapse',
            "weights": self.inh_inh_recurrent,
            "sources": {"model": 'inh_cell'},
            "targets": {"model": 'inh_cell'},
            "allow_autapses":False,
            "allow_multapses":False
        }

        dict_inh_exc_recurrent = {
            "connection_type":"convergent",
            "mask": {'rectangular': {'lower_left':[-self.extent,-self.extent],
                                    'upper_right':[self.extent,self.extent]}},
            "kernel": self.P,
            "synapse_model": 'static_synapse',
            "weights": self.inh_exc_recurrent,
            "sources": {"model": 'inh_cell'},
            "targets": {"model": 'exc_cell'},
            "allow_autapses":False,
            "allow_multapses":False
        }

        tp.ConnectLayers(self.exc,self.exc,dict_exc_exc_recurrent)
        tp.ConnectLayers(self.exc,self.inh,dict_exc_inh_recurrent)
        tp.ConnectLayers(self.inh,self.inh,dict_inh_inh_recurrent)
        tp.ConnectLayers(self.inh,self.exc,dict_inh_exc_recurrent)

        # Connections of the external inputs: each cell receives the same number of
        # external inputs as recurrent excitatory inputs (800 for the 5000-neuron network)
        dict_th_parrot = {
            "connection_type":"convergent",
            "mask": {'rectangular': {'lower_left':[-self.extent,-self.extent],
                                    'upper_right':[self.extent,self.extent]}},
            "kernel": 1.,
            "synapse_model": 'static_synapse',
            "number_of_connections": 800, # constant fan in
            "weights": 1.0,
            "sources": {"model": 'thalamocortical_input'},
            "targets": {"model": 'parrot_neuron'},
            "allow_autapses":False,
            "allow_multapses":True
        }

        dict_cc_parrot = {
            "connection_type":"convergent",
            "mask": {'rectangular': {'lower_left':[-self.extent,-self.extent],
                                    'upper_right':[self.extent,self.extent]}},
            "kernel": 1.,
            "synapse_model": 'static_synapse',
            "number_of_connections": 800, # constant fan in
            "weights": 1.0,
            "sources": {"model": 'cortical_input'},
            "targets": {"model": 'parrot_neuron'},
            "allow_autapses":False,
            "allow_multapses":True
        }

        # A parrot neuron is necessary to send the same spike train to both
        # original cells and cloned cells (used to compute the PSP).

        # Connection of Poisson generators with parrot neurons
        tp.ConnectLayers(self.thalamo,self.parrot_layer_th,dict_th_parrot)
        tp.ConnectLayers(self.cort,self.parrot_layer_cc,dict_cc_parrot)

        parrot_n_th = nest.GetLeaves(self.parrot_layer_th)[0]
        parrot_n_cc = nest.GetLeaves(self.parrot_layer_cc)[0]

        # Connection of parrot neurons with excitatory/inhibitory neurons
        i = 0
        for n in nest.GetLeaves(self.exc)[0]:
            nest.Connect([parrot_n_th[i]],[n],
                'one_to_one',syn_spec={"model":"static_synapse",
                "weight":self.th_exc_external})
            nest.Connect([parrot_n_cc[i]],[n],
                'one_to_one',syn_spec={"model":"static_synapse",
                "weight":self.cc_exc_external})
            i+=1

        for n in nest.GetLeaves(self.inh)[0]:
            nest.Connect([parrot_n_th[i]],[n],
                'one_to_one',syn_spec={"model":"static_synapse",
                "weight":self.th_inh_external})
            nest.Connect([parrot_n_cc[i]],[n],
                'one_to_one',syn_spec={"model":"static_synapse",
                "weight":self.cc_inh_external})
            i+=1

        #! =================
        #! Checkpoint
        #! =================

        # # Plot mask and kernel of connections
        # fig = tp.PlotLayer(self.exc,nodesize =80)
        # ctr = tp.FindCenterElement(self.exc)
        #
        # tp.PlotTargets(ctr, self.exc, fig = fig,
        # mask=dict_exc_exc_recurrent['mask'], kernel=dict_exc_exc_recurrent['kernel'] ,
        # src_size =250 , tgt_color = 'red' , tgt_size =20 ,
        # kernel_color = 'green' )
        #
        # plt.show()

        # # Print the avg. number of input connections
        # pop_ex = nest.GetLeaves(self.exc)[0]
        # pop_in = nest.GetLeaves(self.inh)[0]
        # pop_parrot_th = nest.GetLeaves(self.parrot_layer_th)[0]
        # pop_parrot_cc = nest.GetLeaves(self.parrot_layer_cc)[0]
        # pop_thalamo = nest.GetLeaves(self.thalamo)[0]
        # pop_cc = nest.GetLeaves(self.cort)[0]
        #
        # number_of_connections = [0,0,0,0]
        # for k in range(100):
        #     conns_ex = nest.GetConnections(target = [pop_ex[k]])
        #     conns_th = nest.GetConnections(target = [pop_parrot_th[k]])
        #     conns_cc = nest.GetConnections(target = [pop_parrot_cc[k]])
        #
        #     st_ex = nest.GetStatus(conns_ex)
        #     st_th = nest.GetStatus(conns_th)
        #     st_cc = nest.GetStatus(conns_cc)
        #
        #     for st_con in st_ex:
        #         if st_con["source"] >= pop_ex[0] and st_con["source"] <= pop_ex[-1]:
        #             number_of_connections[0]+=1
        #         if st_con["source"] >= pop_in[0] and st_con["source"] <= pop_in[-1]:
        #             number_of_connections[1]+=1
        #
        #     for st_con in st_th:
        #         if st_con["source"] >= pop_thalamo[0] and st_con["source"] <= pop_thalamo[-1]:
        #             number_of_connections[2]+=1
        #
        #     for st_con in st_cc:
        #         if st_con["source"] >= pop_cc[0] and st_con["source"] <= pop_cc[-1]:
        #             number_of_connections[3]+=1
        #
        # print("\nExc: %s, Inh: %s, Thalamo: %s, Cort: %s\n" % (number_of_connections[0]/\
        # 100.,number_of_connections[1]/100.,number_of_connections[2]/100.,
        # number_of_connections[3]/100.))

        #! =================================================
        #! Computation of the average postsynaptic potential
        #! =================================================

        # Make a copy of a subset of neurons that receive same the synaptic input of
        # the original ones. The cloned neurons receive an extra spike, from the synapse under
        # investigation, each 100 ms

        if self.Compute_PSP:

            spike_gen_cloned = nest.Create("spike_generator")
            nest.SetStatus(spike_gen_cloned,{"spike_times":np.arange(500.0,self.simtime,100.0)})

            cloned_n_AMPA = nest.Create("exc_cell",self.PSP_number_cells)
            cloned_n_GABA = nest.Create("exc_cell",self.PSP_number_cells)

            j=0
            for n in nest.GetLeaves(self.exc)[0]:
                if j < self.PSP_number_cells:
                    conns = nest.GetConnections(target = [n])
                    st = nest.GetStatus(conns)
                    for st_con in st:
                        conn_dict = {'rule': 'one_to_one'}
                        syn_dict = {'weight': st_con["weight"]}
                        nest.Connect([st_con["source"]],[cloned_n_AMPA[j]],
                                    conn_dict, syn_dict)
                        nest.Connect([st_con["source"]],[cloned_n_GABA[j]],
                                    conn_dict, syn_dict)
                    # extra spike
                    nest.Connect(spike_gen_cloned,[cloned_n_AMPA[j]],conn_dict,
                                {'weight': self.exc_exc_recurrent})
                    nest.Connect(spike_gen_cloned,[cloned_n_GABA[j]],conn_dict,
                                {'weight': self.inh_exc_recurrent})
                    j+=1

        #! =================
        #! Recording devices
        #! =================

        # Membrane potential and conductances
        if self.toMemory:
            record_to = 'memory'
        else:
            record_to = 'file'

        if len(self.To_be_measured)>0:
            nest.CopyModel('multimeter', 'RecordingNode',
                    {'interval'   : self.simstep,
                    'record_from': self.To_be_measured,
                    'record_to'  : [record_to],
                    'withgid'    : True,
                    'withtime'   : True})

        # Spikes
        nest.CopyModel('spike_detector', 'SpikesRecorder',
                {'record_to'  : [record_to],
                'withgid'    : True,
                'withtime'   : True})
def myRun(rr1, rr2, Tstim=Tstim, Tblank=Tblank, Ntrials=Ntrials, bw = bw, \
            rec_conn={'EtoE':1, 'EtoI':1, 'ItoE':1, 'ItoI':1}, nn_stim=0):

    # -- restart the simulator
    net_tools._nest_start_()

    init_seed = np.random.randint(1, 1234, n_cores)
    nest.SetStatus([0], [{'rng_seeds': init_seed.tolist()}])

    # -- exc & inh neurons
    exc_neurons = net_tools._make_neurons_(NE, neuron_model=cell_type, \
    myparams={'b':NE*[0.], 'a':NE*[0.]})
    inh_neurons = net_tools._make_neurons_(NI, neuron_model=cell_type, \
    myparams={'b':NE*[0.],'a':NE*[0.]})

    all_neurons = exc_neurons + inh_neurons

    # -- recurrent connectivity
    if rec_conn['EtoE']:
        net_tools._connect_pops_(exc_neurons, exc_neurons, W_EtoE)
    if rec_conn['EtoI']:
        net_tools._connect_pops_(exc_neurons, inh_neurons, W_EtoI)
    if rec_conn['ItoE']:
        net_tools._connect_pops_(inh_neurons, exc_neurons, W_ItoE)
    if rec_conn['ItoI']:
        net_tools._connect_pops_(inh_neurons, inh_neurons, W_ItoI)

    # -- recording spike data
    spikes_all = net_tools._recording_spikes_(neurons=all_neurons)

    # -- background input
    pos_inp = nest.Create("poisson_generator", N)

    for ii in range(N):
        nest.Connect([pos_inp[ii]], [all_neurons[ii]], \
        syn_spec = {'weight':Be_bkg, 'delay':delay_default})

    # -- simulating network for N-trials
    for tri in range(Ntrials):
        print('')
        print('# -> trial # ', tri + 1)

        ## transient
        for ii in range(N):
            nest.SetStatus([pos_inp[ii]], {'rate': rr1[ii]})
        net_tools._run_simulation_(Ttrans)

        ## baseline
        for ii in range(N):
            nest.SetStatus([pos_inp[ii]], {'rate': rr1[ii]})
        net_tools._run_simulation_(Tblank)

        ## perturbing a subset of inh
        for ii in range(N):
            nest.SetStatus([pos_inp[ii]], {'rate': rr2[ii]})
        net_tools._run_simulation_(Tstim)

    # -- reading out spiking activity
    spd = net_tools._reading_spikes_(spikes_all)

    # -- computes the rates out of spike data in a given time interval
    def _rate_interval_(spikedata, T1, T2, bw=bw):
        tids = (spikedata['times'] > T1) * (spikedata['times'] < T2)
        rr = np.histogram2d(spikedata['times'][tids], spikedata['senders'][tids], \
             range=((T1,T2),(1,N)), bins=((T2-T1)/bw,N))[0] / (bw/1e3)
        return rr

    rout_blank = np.zeros((Ntrials, int(Tblank / bw), N))
    rout_stim = np.zeros((Ntrials, int(Tstim / bw), N))
    for tri in range(Ntrials):
        Tblock = Tstim + Tblank + Ttrans
        rblk = _rate_interval_(spd, Tblock * tri + Ttrans,
                               Tblock * tri + Ttrans + Tblank)
        rstm = _rate_interval_(spd, Tblock * tri + Ttrans + Tblank,
                               Tblock * (tri + 1))
        rout_blank[tri, :, :] = rblk
        rout_stim[tri, :, :] = rstm

    print('##########')
    print('## Mean firing rates {Exc | Inh (pert.) | Inh (non-pert.)}')
    print('## Before pert.: ', \
    np.round(rout_blank[:,:,0:NE].mean(),1), \
    np.round(rout_blank[:,:,NE:NE+nn_stim].mean(),1), \
    np.round(rout_blank[:,:,NE+nn_stim:].mean(),1) )
    print('## After pert.: ', \
    np.round(rout_stim[:,:,0:NE].mean(),1), \
    np.round(rout_stim[:,:,NE:NE+nn_stim].mean(),1), \
    np.round(rout_stim[:,:,NE+nn_stim:].mean(),1) )
    print('##########')

    return rout_blank, rout_stim, spd
コード例 #8
0
# synapse time constant is [2.0] ms, which is for neuron with one port.

syn_tau = [2.0, 1.0]

###############################################################################
# We create the five levels of GLIF model to be tested, i.e.,
# ``lif``, ``lif_r``, ``lif_asc``, ``lif_r_asc``, ``lif_r_asc_a``.
# For each level of GLIF model, we create  a ``glif_psc`` node. The node is
# created by setting relative model mechanism parameters and the time constant
# of the 2 synaptic ports as mentioned above. Other neuron parameters are set
# as default. The five ``glif_psc`` node handles were combined as a list.

n_lif = nest.Create("glif_psc",
                    params={
                        "spike_dependent_threshold": False,
                        "after_spike_currents": False,
                        "adapting_threshold": False,
                        "tau_syn": syn_tau
                    })
n_lif_r = nest.Create("glif_psc",
                      params={
                          "spike_dependent_threshold": True,
                          "after_spike_currents": False,
                          "adapting_threshold": False,
                          "tau_syn": syn_tau
                      })
n_lif_asc = nest.Create("glif_psc",
                        params={
                            "spike_dependent_threshold": False,
                            "after_spike_currents": True,
                            "adapting_threshold": False,
コード例 #9
0
    def run_protocol(self, dt):
        """Set up a network with pre-post spike pairings with
        t_post - t_pre = dt"""

        nest.set_verbosity("M_WARNING")
        nest.ResetKernel()

        # set pre and postsynaptic spike times
        delay = 1.  # delay for connections
        dspike = 100.  # ISI

        # set the correct real spike times for generators (correcting for
        # delays)
        pre_times = [100., 100. + dspike]
        post_times = [k + dt for k in pre_times]

        # create spike_generators with these times
        pre_spikes = nest.Create("spike_generator",
                                 params={
                                     "spike_times": pre_times,
                                     'precise_times': True
                                 })
        post_spikes = nest.Create("spike_generator",
                                  params={
                                      "spike_times": post_times,
                                      'precise_times': True
                                  })

        # create parrot neurons and connect spike_generators
        pre_parrot = nest.Create("parrot_neuron_ps", 1)
        post_parrot = nest.Create("parrot_neuron_ps", 1)

        nest.Connect(pre_spikes, pre_parrot, syn_spec={"delay": delay})
        nest.Connect(post_spikes, post_parrot, syn_spec={"delay": delay})

        # create spike recorder
        spikes = nest.Create("spike_recorder")
        nest.Connect(pre_parrot, spikes)
        nest.Connect(post_parrot, spikes)

        # connect both parrot neurons with a stdp synapse onto port 1
        # thereby spikes transmitted through the stdp connection are
        # not repeated postsynaptically.
        syn_spec = {
            "synapse_model": "stdp_synapse",
            # set receptor 1 postsynaptically, to not generate extra spikes
            "receptor_type": 1,
        }
        conn_spec = {
            "rule": "one_to_one",
        }
        nest.Connect(pre_parrot,
                     post_parrot,
                     syn_spec=syn_spec,
                     conn_spec=conn_spec)

        # get STDP synapse and weight before protocol
        syn = nest.GetConnections(source=pre_parrot,
                                  synapse_model="stdp_synapse")
        w_pre = syn.get('weight')

        last_time = max(pre_times[-1], post_times[-1])
        nest.Simulate(_round_up(last_time + 2 * delay))

        # get weight post protocol
        w_post = syn.get('weight')

        return w_pre, w_post
コード例 #10
0
# - The end of the time window to plot

n_blocks = 5
t_block = 20.
t_dep = [t_block] * n_blocks
t_hyp = [t_block * 2**n for n in range(n_blocks)]
I_dep = 10.
I_hyp = -5.

t_end = 500.

###############################################################################
# We create the one neuron instance and the DC current generator and store
# the returned handles.

nrn = nest.Create('ht_neuron')
dc = nest.Create('dc_generator')

###############################################################################
# We create a multimeter to record
#
# - membrane potential ``V_m``
# - threshold value ``theta``
# - intrinsic currents ``I_NaP``, ``I_KNa``, ``I_T``, ``I_h``
#
# by passing these names in the ``record_from`` list.
#
# To find out which quantities can be recorded from a given neuron,
# run::
#
#   nest.GetDefaults('ht_neuron')['recordables']
コード例 #11
0
    'tau_m': tau_m,
    'tau_syn_ex': tau_syn_ex,
    'tau_syn_in': tau_syn_in,
    'C_m': C_m,
    'E_L': E_L,
    't_ref': t_ref,
    'V_m': E_L,
    'V_reset': E_L
}

###############################################################################
# Neurons and devices are instantiated. We set a high threshold as we want
# free membrane potential. In addition we choose a small resolution for
# recording the membrane to collect good statistics.

n = nest.Create('iaf_psc_alpha', n_neurons, params=neurondict)
n_free = nest.Create('iaf_psc_alpha', params=dict(neurondict, V_th=1e12))
pg = nest.Create('poisson_generator', len(rates), {'rate': rates})
vm = nest.Create('voltmeter', params={'interval': .1})
sr = nest.Create('spike_recorder')

###############################################################################
# We connect devices and neurons and start the simulation.

pg_n_synspec = {'weight': np.tile(J, ((n_neurons), 1)), 'delay': 0.1}
nest.Connect(pg, n, syn_spec=pg_n_synspec)
nest.Connect(pg, n_free, syn_spec={'weight': [J]})
nest.Connect(vm, n_free)
nest.Connect(n, sr)

nest.Simulate(simtime)
コード例 #12
0
ファイル: runiafts_exp.py プロジェクト: Trinity-wang/147117
    "E_L": 0.0,
    "V_th": 15.0,
    "V_reset": 13.5,
    "V_m": 13.5,
    "I_e": Ie,
    "tau_syn_ex": 3.0,
    "tau_syn_in": 3.0
}
nest.CopyModel('iaf_psc_exp', 'iaf_e', neuron_pars)
nest.CopyModel('iaf_psc_exp', 'iaf_i', neuron_pars)
nest.SetDefaults('iaf_i', {
    "t_ref": 2.0,
    "I_e": Ii
})  #faster recovery for inhibitory neurons

noise_e = nest.Create("noise_generator", Ne)
if Ni > 0:
    noise_i = nest.Create("noise_generator", Ni)
else:
    noise_i = 0

for n in range(0, Ne):
    nest.SetStatus([noise_e[n]], {"mean": 0.0, "std": noisestd})
for n in range(0, Ni):
    nest.SetStatus([noise_i[n]], {"mean": 0.0, "std": noisestd})

synapse_pars_e = {
    "tau_psc": 3.0,
    "tau_rec": 800.0,
    "tau_fac": 0.0,
    "U": 0.5,
コード例 #13
0
exc_neuron = neuron[0:NE]  # excitatory neurons
inh_neuron = neuron[NE:n_neurons]  # inhibitory neurons

# receptor parameters
E_rev = [0.0, -85.0]
tau_decay = [1.0, 1.0]
tau_rise = [1.0, 1.0]

ngpu.SetStatus(neuron, {
    "E_rev": E_rev,
    "tau_decay": tau_decay,
    "tau_rise": tau_rise,
    "t_ref": 0.5
})

nest_neuron = nest.Create("aeif_cond_beta_multisynapse", n_test)
nest.SetStatus(nest_neuron, {
    "E_rev": E_rev,
    "tau_decay": tau_decay,
    "tau_rise": tau_rise,
    "t_ref": 0.5
})

neuron_image = ngpu_nest.CreateNeuronImage(nest_neuron, 3)

mean_delay = 0.5
std_delay = 0.25
min_delay = 0.1
# Excitatory connections
# connect excitatory neurons to port 0 of all neurons
# normally distributed delays, weight Wex and CE connections per neuron
コード例 #14
0
    def add_spike_trains(self,
                         spike_trains,
                         node_set,
                         sg_params={'precise_times': True}):
        # Build the virtual nodes
        src_nodes = [
            node_pop for node_pop in self.node_populations
            if node_pop.name in node_set.population_names()
        ]
        virt_gid_map = self._virtual_gids
        for node_pop in src_nodes:
            if node_pop.name in self._virtual_ids_map:
                continue

            virt_node_map = {}
            if node_pop.virtual_nodes_only:
                for node in node_pop.get_nodes():
                    nest_ids = nest.Create('spike_generator', node.n_nodes,
                                           sg_params)
                    virt_gid_map.add_nestids(name=node_pop.name,
                                             nest_ids=nest_ids,
                                             node_ids=node.node_ids)
                    for node_id, nest_id in zip(node.node_ids, nest_ids):
                        virt_node_map[node_id] = nest_id

                        st = np.array(spike_trains.get_times(node_id=node_id))
                        if len(st) == 0:
                            continue
                        st.sort()
                        nest.SetStatus([nest_id], {'spike_times': st})

            elif node_pop.mixed_nodes:
                for node in node_pop.get_nodes():
                    if node.model_type != 'virtual':
                        continue

                    nest_ids = nest.Create('spike_generator', node.n_nodes,
                                           sg_params)
                    for node_id, nest_id in zip(node.node_ids, nest_ids):
                        virt_node_map[node_id] = nest_id
                        nest.SetStatus(
                            [nest_id], {
                                'spike_times':
                                np.array(
                                    spike_trains.get_times(node_id=node_id))
                            })

            self._virtual_ids_map[node_pop.name] = virt_node_map

        # Create virtual synaptic connections
        for source_reader in src_nodes:
            for edge_pop in self.find_edges(source_nodes=source_reader.name):
                for edge in edge_pop.get_edges():
                    nest_trgs = self.gid_map.get_nestids(
                        edge_pop.target_nodes, edge.target_node_ids)
                    nest_srcs = virt_gid_map.get_nestids(
                        edge_pop.source_nodes, edge.source_node_ids)
                    nest.Connect(nest_srcs,
                                 nest_trgs,
                                 conn_spec='one_to_one',
                                 syn_spec=edge.nest_params)
コード例 #15
0
ファイル: gap_junctions.py プロジェクト: heidarinejad/MyNests
import nest
import numpy as np
import pylab as pl

# In this program 2 neuron connected by gap junction. they are synchronized based of same level of currnet input

nest.ResetKernel()

# First we set the resolution of the simulation, create two neurons and
# create a `voltmeter` for recording.
nest.SetKernelStatus({'resolution': 0.05})
neuron = nest.Create('hh_psc_alpha_gap', 2)
vm = nest.Create('voltmeter',
                 params={
                     'to_file': False,
                     'withgid': True,
                     'withtime': True,
                     'interval': 0.1
                 })

# Then we set the constant current input, modify the initial membrane
# potential of one of the neurons and connect the neurons to the `voltmeter`.
nest.SetStatus(neuron, {'I_e': 100.0})
nest.SetStatus([neuron[0]], {'V_m': -10.0})
nest.Connect(vm, neuron, 'all_to_all')

# In order to create the `gap_junction` connection we employ the `all_to_all`
# connection rule: Gap junctions are bidirectional connections, therefore we
# need to connect `neuron[0]` to `neuron[1]` and `neuron[1]` to `neuron[0]`:
nest.Connect(neuron, neuron, {
    'rule': 'all_to_all',
コード例 #16
0
# repeat a stimulation protocol using the 'origin' property of devices
# actually 'poisson generator' generates a spike train which is recorded by 'spike detector'
# within each trial the poisson generator is active from 100ms to 500ms

rate = 1000.0  # generator rate in spikes/s
start = 100.0  # start of simulation relative to trial start, in ms
stop = 500.0  # end of simulation relative to trial start, in ms

trial_duration = 1000.0  # trial duration, in ms
num_trials = 5  # number of trials to perform

nest.ResetKernel()
pg = nest.Create('poisson_generator',
                 params={
                     'rate': rate,
                     'start': start,
                     'stop': stop
                 })

sd = nest.Create('spike_detector')
nest.Connect(pg, sd)

# 'origin' property of devices
for n in range(num_trials):
    nest.SetStatus(pg, {'origin': nest.GetKernelStatus()['time']})
    nest.Simulate(trial_duration)

nest.raster_plot.from_device(sd,
                             hist=True,
                             hist_binwidth=50.0,
                             title='Repeated stimulation by Poisson generator')
コード例 #17
0
simtime = 10000.  # needs to match the stoptime (here in ms) defined in the music config
max_rate = 50.  # needs to match the max rate defined for the encoder in the music config

tau_m = 1.
tau_syn = 20.
J = 200.

# setup and simulate

nest.ResetKernel()

nest.SetKernelStatus({'resolution': 1.})

C_m = nest.GetDefaults('iaf_psc_exp', 'C_m')

music_in_proxy = nest.Create('music_event_in_proxy', 1, {'port_name': 'in'})
music_out_proxy = nest.Create('music_event_out_proxy', 1, {'port_name': 'out'})

neuron_left = nest.Create(
    'iaf_psc_exp',
    1,
    {
        'E_L': -60.3 + get_current_offset(
            J, max_rate / 2., tau_m, tau_syn, C_m
        ),  # add additional 0.3mV to make the left neuron a bit less excitable
        'V_th': -60.,
        'tau_m': tau_m,
        'tau_syn_ex': tau_syn,
        'tau_syn_in': tau_syn,
        'C_m': C_m
    })
コード例 #18
0
        )
    else:
        nest.Install('pt_module')

initial_weight = np.log(
    nest.GetDefaults('bcpnn_synapse')['p_ij'] /
    (nest.GetDefaults('bcpnn_synapse')['p_i'] *
     nest.GetDefaults('bcpnn_synapse')['p_j']))
initial_bias = np.log(nest.GetDefaults('bcpnn_synapse')['p_j'])
syn_param = {
    "weight": initial_weight,
    "bias": initial_bias,
    "K": 1.0,
    "delay": 1.0,
    "tau_i": 10.0,
    "tau_j": 10.0,
    "tau_e": 100.0,
    "tau_p": 1000.0
}

neuron1_spike_gen = nest.Create('poisson_generator', params={'rate': f_in})
neuron2_spike_gen = nest.Create('poisson_generator', params={'rate': f_in})

neuron1 = nest.Create("iaf_neuron")
neuron2 = nest.Create("iaf_neuron")

nest.Connect(neuron1_spike_gen, neuron1, params={'weight': 1000.0})
nest.Connect(neuron2_spike_gen, neuron2, params={'weight': 1000.0})
nest.Connect(neuron1, neuron2, params=syn_param, model="bcpnn_synapse")
nest.Simulate(t_sim)
コード例 #19
0
    def simulate_network(self,interval):

        #! =================
        #! Recording devices
        #! =================

        # Membrane potential and conductances
        if len(self.To_be_measured)>0:

            self.subthreshold_recorders = []

            # Exc
            rec_exc = nest.Create('RecordingNode')
            tgts = [nd for nd in nest.GetLeaves(self.exc)[0]]
            nest.Connect(rec_exc,tgts)
            self.subthreshold_recorders.append(rec_exc)

            # Inh
            rec_inh = nest.Create('RecordingNode')
            tgts = [nd for nd in nest.GetLeaves(self.inh)[0]]
            nest.Connect(rec_inh,tgts)
            self.subthreshold_recorders.append(rec_inh)

            # Cloned neurons
            if self.Compute_PSP:
                rec_cloned_AMPA = nest.Create('RecordingNode')
                tgts = [nd for nd in cloned_n_AMPA]
                nest.Connect(rec_cloned_AMPA,tgts)
                self.subthreshold_recorders.append(rec_cloned_AMPA)

                rec_cloned_GABA = nest.Create('RecordingNode')
                tgts = [nd for nd in cloned_n_GABA]
                nest.Connect(rec_cloned_GABA,tgts)
                self.subthreshold_recorders.append(rec_cloned_GABA)

        # Spikes
        self.spikes = []

        # For raster plots of spikes
        self.mult_exc = nest.Create('spike_detector',1)
        self.mult_inh = nest.Create('spike_detector',1)
        if self.Compute_PSP:
            mult_cloned_AMPA = nest.Create('spike_detector',1)
            mult_cloned_GABA = nest.Create('spike_detector',1)

        # Exc
        sp_exc = nest.Create('SpikesRecorder')
        tgts = [nd for nd in nest.GetLeaves(self.exc)[0]]
        nest.Connect(tgts,sp_exc)
        self.spikes.append(sp_exc)
        nest.Connect([tgts[i] for i in self.cells_to_analyze],self.mult_exc)

        # Inh
        sp_inh = nest.Create('SpikesRecorder')
        tgts = [nd for nd in nest.GetLeaves(self.inh)[0]]
        nest.Connect(tgts,sp_inh)
        self.spikes.append(sp_inh)
        nest.Connect([tgts[i] for i in self.cells_to_analyze],self.mult_inh)

        # Cloned neurons
        if self.Compute_PSP:
            sp_cloned_AMPA = nest.Create('SpikesRecorder')
            tgts = [nd for nd in cloned_n_AMPA]
            nest.Connect(tgts,sp_cloned_AMPA)
            self.spikes.append(sp_cloned_AMPA)
            nest.Connect([tgts[i] for i in range(self.PSP_number_cells)],mult_cloned_AMPA)

            sp_cloned_GABA = nest.Create('SpikesRecorder')
            tgts = [nd for nd in cloned_n_GABA]
            nest.Connect(tgts,sp_cloned_GABA)
            self.spikes.append(sp_cloned_GABA)
            nest.Connect([tgts[i] for i in range(self.PSP_number_cells)],mult_cloned_GABA)

        # Thalamocortical input
        sp_th = nest.Create('SpikesRecorder')
        tgts = [nd for nd in nest.GetLeaves(self.parrot_layer_th)[0]]
        nest.Connect(tgts,sp_th)
        self.spikes.append(sp_th)

        # Cortical-cortical_input
        sp_cc = nest.Create('SpikesRecorder')
        tgts = [nd for nd in nest.GetLeaves(self.parrot_layer_cc)[0]]
        nest.Connect(tgts,sp_cc)
        self.spikes.append(sp_cc)

        print ("\n--- Simulation ---\n")
        nest.SetStatus([0],{'print_time': True})
        nest.Simulate(interval)

        #! =================
        #! Gather results
        #! =================

        if self.Compute_PSP:
            n_rec = 4
        else:
            n_rec = 2

        data_v=[]
        for i in range(n_rec):
            if len(self.To_be_measured)>0:
                data_v.append(nest.GetStatus(self.subthreshold_recorders[i],keys='events'))
            else:
                data_v.append([])

        data_s=[]
        for i in range(n_rec+2):
            data_s.append(nest.GetStatus(self.spikes[i],keys='events'))

        senders_v = []
        for i in range(n_rec):
            if len(self.To_be_measured)>0:
                senders_v.append(data_v[i][0]['senders'])
            else:
                senders_v.append([])

        senders_s = []
        for i in range(n_rec+2):
            senders_s.append(data_s[i][0]['senders'])

        pop_ex = nest.GetLeaves(self.exc)[0]
        pop_in = nest.GetLeaves(self.inh)[0]
        pop_parrot_th = nest.GetLeaves(self.parrot_layer_th)[0]
        pop_parrot_cc = nest.GetLeaves(self.parrot_layer_cc)[0]
        pop_thalamo = nest.GetLeaves(self.thalamo)[0]
        pop_cc = nest.GetLeaves(self.cort)[0]

        if self.Compute_PSP:
            pop_cloned_AMPA = [nd for nd in cloned_n_AMPA]
            pop_cloned_GABA = [nd for nd in cloned_n_GABA]

            return [self.simtime,data_v,data_s,senders_v,senders_s,pop_ex,pop_in,
            pop_thalamo,pop_cc,pop_parrot_th,pop_parrot_cc,pop_cloned_AMPA,
            pop_cloned_GABA,self.mult_exc,self.mult_inh,mult_cloned_AMPA,mult_cloned_GABA]

        else:
            return [self.simtime,data_v,data_s,senders_v,senders_s,
            pop_ex,pop_in,pop_thalamo,pop_cc,pop_parrot_th,pop_parrot_cc,
            self.mult_exc,self.mult_inh]
コード例 #20
0
# Author: Abigail Morrison & Susanne Kunkel, 2011
# on the basis of Eilif Muller's comparison9ml_iaf_cond_exp.py

# See: README for the build process for the "MyModule" required
# by nest.Install below which contains stdp_guetig_9ml

import nest
nest.Install("mymodule")
import numpy

import time

nest.ResetKernel()

dt   = 0.01 # [ms]
tsim = 0.5  # [s]

nest.SetStatus([0],{'resolution':dt})

pg  = nest.Create('poisson_generator',1)
nest.SetStatus(pg, {'rate': 10.0})
pre  = nest.Create('parrot_neuron',1)
post = nest.Create('iaf_neuron', 1)
nest.SetStatus(post, {'I_e': 500.0})

nest.Connect(pg, pre, model='static_synapse')
nest.Connect(pre, post, model='stdp_guetig_9ml')

nest.Simulate(1000.0)
コード例 #21
0
ファイル: nest_example.py プロジェクト: bitSlayer29090/CSL
    @property
    def len(self):
        return self._len

    @property
    def dlen(self):
        return self._dlen


slg = SpindleLengthGenerator()

# muscle spindle population
# with primary and secondary afferents
nest.Install("muscle_module")
ms = nest.Create("muscle_spindle", 2 * pop_size)
nest.SetStatus(ms[pop_size:2 * pop_size], {'primary': False})

# fusimotor activation
dyn_gen = nest.Create('poisson_generator', 1, {'rate': 100.0})
nest.Connect(dyn_gen, ms, 'all_to_all', {
    'weight': 1.0,
    'delay': 1.0,
    'receptor_type': 1
})
st_gen = nest.Create('poisson_generator', 1, {'rate': 30.0})
nest.Connect(st_gen, ms, 'all_to_all', {
    'weight': 1.0,
    'delay': 1.0,
    'receptor_type': 2
})
コード例 #22
0
def networkclassical(**kwargs):
    globals().update(kwargs)

    nest.ResetKernel()
    startbuild = tim()
    order = int(orderCE / (epsilon * 4))  #2500
    NE = 4 * order  # number of excitatory neurons
    NI = 1 * order  # number of inhibitory neurons
    N_neurons = NE + NI  # number of neurons in total
    #    N_rec = 50  # record from 50 neurons
    CE = int(epsilon * NE)  # number of excitatory synapses per neuron
    CI = int(epsilon * NI)  # number of inhibitory synapses per neuron
    #C_tot = int(CI + CE)  # total number of synapses per neuron
    neuron_params = {
        "C_m": 1.0,
        "tau_m": tauMem,
        "t_ref": 2.0,
        "E_L": 0.0,
        "V_reset": Vr,
        "V_m": 0.0,
        "V_th": theta
    }
    J_ex = J  # amplitude of excitatory postsynaptic potential
    J_in = -g * J_ex  # amplitude of inhibitory postsynaptic potential
    nu_th = theta / (J * CE * tauMem)
    nu_ex = eta * nu_th
    p_rate = 1000.0 * nu_ex * CE
    nest.SetKernelStatus({
        "resolution": dt,
        "print_time": True,
        "overwrite_files": True,
        "local_num_threads": nthreads
    })
    nest.SetDefaults("iaf_psc_delta", neuron_params)
    nest.SetDefaults("poisson_generator", {"rate": p_rate})  # `CE` gen's in 1
    nodes_ex = nest.Create("iaf_psc_delta", NE)
    nodes_in = nest.Create("iaf_psc_delta", NI)
    noise = nest.Create("poisson_generator")  #, CE) in the superdiffusive case
    espikes = nest.Create("spike_detector")
    ispikes = nest.Create("spike_detector")
    nest.SetStatus(espikes,
                   [{
                       "label": "%s/alpha%.2fespikes" % (datafolder, alpha),
                       "withtime": True,
                       "withgid": True,
                       "to_file": True
                   }])
    nest.SetStatus(ispikes,
                   [{
                       "label": "%s/alpha%.2fispikes" % (datafolder, alpha),
                       "withtime": True,
                       "withgid": True,
                       "to_file": True
                   }])
    nest.CopyModel("static_synapse", "excitatory", {
        "weight": J_ex,
        "delay": delay
    })
    nest.CopyModel("static_synapse", "inhibitory", {
        "weight": J_in,
        "delay": delay
    })
    multimeter = nest.Create("multimeter")
    nest.SetStatus(
        multimeter, {
            "to_memory": False,
            "withtime": True,
            "record_from": ["V_m"],
            "to_file": True,
            "label": "%s/alpha%.2fV_m" % (datafolder, alpha)
        })
    #"interval": 100.0,
    nest.Connect(multimeter, nodes_ex + nodes_in)  # nodes_ex[:N_rec]+...
    nest.Connect(noise, nodes_ex, syn_spec="excitatory")
    nest.Connect(noise, nodes_in, syn_spec="excitatory")
    nest.Connect(nodes_ex, espikes, syn_spec="excitatory")  # nodes_ex[:N_rec]
    nest.Connect(nodes_in, ispikes, syn_spec="excitatory")  # nodes_in[:N_rec]
    conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE}
    nest.Connect(nodes_ex, nodes_ex + nodes_in, conn_params_ex, "excitatory")
    conn_params_in = {'rule': 'fixed_indegree', 'indegree': CI}
    nest.Connect(nodes_in, nodes_ex + nodes_in, conn_params_in, "inhibitory")
    endbuild = tim()
    nest.Simulate(simtime)
    endsimulate = tim()
    events_ex = nest.GetStatus(espikes, "n_events")[0]
    events_in = nest.GetStatus(ispikes, "n_events")[0]
    rate_ex = events_ex / simtime * 1000.0 / NE
    rate_in = events_in / simtime * 1000.0 / NI
    num_synapses = (nest.GetDefaults("excitatory")["num_connections"] +
                    nest.GetDefaults("inhibitory")["num_connections"])
    build_time = endbuild - startbuild
    sim_time = endsimulate - endbuild
    print("alpha             : {0}".format(alpha))
    print("Number of neurons : {0}".format(N_neurons))
    print("Number of synapses: {0}".format(num_synapses))
    print("       Exitatory  : {0}".format(int(CE * N_neurons) + N_neurons))
    print("       Inhibitory : {0}".format(int(CI * N_neurons)))
    print("Excitatory rate   : %.2f Hz" % rate_ex)
    print("Inhibitory rate   : %.2f Hz" % rate_in)
    print("Building time     : %.2f s" % build_time)
    print("Simulation time   : %.2f s" % sim_time)
コード例 #23
0
ファイル: main.py プロジェクト: Ziaeemehr/itng_nest
import nest
import pylab as pl

nest.Install("testModuleInstallmodule")
model = "izhikevich_nestml"

neuron = nest.Create(model)
parameters = nest.GetDefaults(model)
# for i in parameters:
#     print(i, parameters[i])
# exit(0)

# nest.SetStatus(neuron, {'I_ext': 630.0})
multimeter = nest.Create("multimeter")
nest.SetStatus(multimeter, {"withtime": True, "record_from": ["v"]})
spikedetector = nest.Create("spike_detector",
                            params={
                                "withgid": True,
                                "withtime": True
                            })
nest.Connect(multimeter, neuron)
nest.Connect(neuron, spikedetector)
nest.Simulate(200.0)
dmm = nest.GetStatus(multimeter)[0]
Vms = dmm["events"]["v"]
ts = dmm["events"]["times"]
# dSD = nest.GetStatus(spikedetector, keys='events')[0]
# evs = dSD['senders']
# ts = dSD["times"]

pl.plot(ts, Vms)
コード例 #24
0
def network(**kwargs):
    with nfailures_tightbalance.get_lock():
        nfailures_tightbalance.value = 0
    globals().update(kwargs)

    nest.ResetKernel()
    startbuild = tim()
    order = int(orderCE / (epsilon * 4))  #2500
    NE = 4 * order  # number of excitatory neurons
    NI = 1 * order  # number of inhibitory neurons
    N_neurons = NE + NI  # number of neurons in total
    #    N_rec = 50  # record from 50 neurons
    CE = int(epsilon * NE)  # number of excitatory synapses per neuron
    CI = int(epsilon * NI)  # number of inhibitory synapses per neuron
    #C_tot = int(CI + CE)  # total number of synapses per neuron
    neuron_params = {
        "C_m": 1.0,
        "tau_m": tauMem,
        "t_ref": 2.0,
        "E_L": 0.0,
        "V_reset": Vr,
        "V_m": 0.0,
        "V_th": theta
    }
    J_ex = J  # amplitude of excitatory postsynaptic potential
    J_in = -g * J_ex  # amplitude of inhibitory postsynaptic potential
    nu_th = theta / (J * CE * tauMem)
    nu_ex = eta * nu_th
    p_rate = 1000.0 * nu_ex * CE
    nest.SetKernelStatus({
        "resolution": dt,
        "print_time": True,
        "overwrite_files": True,
        "local_num_threads": nthreads
    })
    nest.SetDefaults("iaf_psc_delta", neuron_params)
    nest.SetDefaults("poisson_generator", {"rate": p_rate / CE})
    nodes_ex = nest.Create("iaf_psc_delta", NE)
    nodes_in = nest.Create("iaf_psc_delta", NI)
    noise = nest.Create("poisson_generator", CE)
    espikes = nest.Create("spike_detector")
    ispikes = nest.Create("spike_detector")
    nest.SetStatus(espikes,
                   [{
                       "label": "%s/alpha%.2fespikes" % (datafolder, alpha),
                       "withtime": True,
                       "withgid": True,
                       "to_file": True
                   }])
    nest.SetStatus(ispikes,
                   [{
                       "label": "%s/alpha%.2fispikes" % (datafolder, alpha),
                       "withtime": True,
                       "withgid": True,
                       "to_file": True
                   }])
    nest.CopyModel("static_synapse", "excitatory", {
        "weight": J_ex,
        "delay": delay
    })
    nest.CopyModel("static_synapse", "inhibitory", {
        "weight": J_in,
        "delay": delay
    })
    A_alpha = gamma(1 + alpha) * numpy.sin(numpy.pi * alpha / 2) / numpy.pi
    D = 0.5
    # pareto pdf = alpha*x1**alpha/(x-x0)**(alpha+1), defined for x > x0+x1
    x1fac = (2 * A_alpha * D / alpha)**(1 / alpha)
    x0fac = 1 - x1fac * alpha / (alpha - 1)
    J_noise_ex = J_ex * (x1fac * (pareto(alpha, (NE, CE)) + 1) + x0fac)
    J_noise_in = J_ex * (x1fac * (pareto(alpha, (NI, CE)) + 1) + x0fac)
    # correlated amplitude populations:
    samples_ex = x1fac * (pareto(alpha, (NE + NI, CE)) + 1) + x0fac
    #    print x0fac,x1fac

    with Pool_(nthreads) as p:
        samples_in = numpy.array(
            p.map(partial(f, alpha, x0fac, x1fac, CE, CI),
                  numpy.sum(samples_ex, 1), 1))
    J_ex_tot = J_ex * samples_ex
    J_in_tot = J_in * samples_in
    multimeter = nest.Create("multimeter")
    nest.SetStatus(
        multimeter, {
            "to_memory": False,
            "withtime": True,
            "record_from": ["V_m"],
            "to_file": True,
            "label": "%s/alpha%.2fV_m" % (datafolder, alpha)
        })
    #"interval": 100.0,
    nest.Connect(multimeter, nodes_ex + nodes_in)  # nodes_ex[:N_rec]+...
    nest.Connect(noise,
                 nodes_ex,
                 syn_spec={
                     "model": "excitatory",
                     "weight": J_noise_ex
                 })
    nest.Connect(noise,
                 nodes_in,
                 syn_spec={
                     "model": "excitatory",
                     "weight": J_noise_in
                 })
    nest.Connect(nodes_ex, espikes, syn_spec="excitatory")  # nodes_ex[:N_rec]
    nest.Connect(nodes_in, ispikes, syn_spec="excitatory")  # nodes_in[:N_rec]
    conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE}
    nest.Connect(nodes_ex,
                 nodes_ex + nodes_in,
                 conn_params_ex,
                 syn_spec={
                     "model": "excitatory",
                     "weight": J_ex_tot
                 })
    conn_params_in = {'rule': 'fixed_indegree', 'indegree': CI}
    nest.Connect(nodes_in,
                 nodes_ex + nodes_in,
                 conn_params_in,
                 syn_spec={
                     "model": "inhibitory",
                     "weight": J_in_tot
                 })
    endbuild = tim()
    nest.Simulate(simtime)
    endsimulate = tim()
    events_ex = nest.GetStatus(espikes, "n_events")[0]
    events_in = nest.GetStatus(ispikes, "n_events")[0]
    rate_ex = events_ex / simtime * 1000.0 / NE
    rate_in = events_in / simtime * 1000.0 / NI
    num_synapses = (nest.GetDefaults("excitatory")["num_connections"] +
                    nest.GetDefaults("inhibitory")["num_connections"])
    build_time = endbuild - startbuild
    sim_time = endsimulate - endbuild
    print("Number of tight balance failures: {0}".format(
        nfailures_tightbalance.value))
    print("alpha             : {0}".format(alpha))
    print("Number of neurons : {0}".format(N_neurons))
    print("Number of synapses: {0}".format(num_synapses))
    print("       Exitatory  : {0}".format(int(CE * N_neurons) + N_neurons))
    print("       Inhibitory : {0}".format(int(CI * N_neurons)))
    print("Excitatory rate   : %.2f Hz" % rate_ex)
    print("Inhibitory rate   : %.2f Hz" % rate_in)
    print("Building time     : %.2f s" % build_time)
    print("Simulation time   : %.2f s" % sim_time)
コード例 #25
0
def generateSpikes(neuron, times):
    """Trigger spike to given neuron at specified times."""
    delay = 1.0
    gen = nest.Create("spike_generator", 1,
                      {"spike_times": [t - delay for t in times]})
    nest.Connect(gen, neuron, syn_spec={"delay": delay})
コード例 #26
0
    "tau_m": Tau,
    "t_ref": TauR,
    "tau_syn_ex": Tau_psc,
    "tau_syn_in": Tau_psc,
    "C_m": C,
    "V_reset": U0,
    "E_L": U0,
    "V_m": U0,
    "V_th": Theta
}

# set defaults of desired neuron type with chosen parameters:
nest.SetDefaults("iaf_psc_exp", neuron_param)

# create two neurons of desired type:
neurons = nest.Create("iaf_psc_exp", 2)

# set properties of dc:
nest.SetDefaults("dc_generator", {
    "amplitude": I0,
    "start": TIstart,
    "stop": TIend
})

# create dc_generator:
dc_gen = nest.Create("dc_generator")

# set properties of voltmeter:
volts = nest.Create("voltmeter")

# create voltmeter:
コード例 #27
0
def evaluate(rho, dt, nearest):
    """Evaluate connection change of weight and returns it."""
    nest.ResetKernel()
    nest.SetKernelStatus({
        "local_num_threads": 1,
        "resolution": 0.1,
        "print_time": False
    })

    step = 1000.0 / rho
    simulation_duration = np.ceil(n * step)
    times_pre = np.arange(start_spikes, simulation_duration, step).round(1)
    times_post = [t + dt for t in times_pre]

    # Entities
    local_spec = syn_spec.copy()
    local_spec.update({"nearest_spike": nearest})
    neuron_pre = nest.Create("parrot_neuron")
    neuron_post = nest.Create("parrot_neuron")
    triplet_synapse = nest.Create("stdp_longterm_node", params=local_spec)

    multi = nest.Create("multimeter")
    nest.SetStatus(multi,
                   params={
                       "withtime":
                       True,
                       "interval":
                       nest.GetKernelStatus()["resolution"],
                       "record_from": [
                           "weight", "weight_ref", "B", "C", "Zplus", "Zslow",
                           "Zminus", "Zht"
                       ],
                   })
    nest.Connect(multi, triplet_synapse)

    # Connections
    generateSpikes(neuron_pre, times_pre)
    generateSpikes(neuron_post, times_post)
    nest.Connect(neuron_pre, triplet_synapse)
    nest.Connect(triplet_synapse, neuron_post,
                 syn_spec={"receptor_type": 1})  # do not repeat spike
    nest.Connect(neuron_post, triplet_synapse,
                 syn_spec={"receptor_type":
                           1})  # differentiate post-synaptic feedback

    # Simulation
    current_weight = nest.GetStatus(triplet_synapse, keys="weight")[0]
    nest.Simulate(start_spikes + simulation_duration)

    stats = nest.GetStatus(multi, keys="events")[0]
    # plt.figure()
    #
    # plt.subplot(211)
    # plt.title(str(rho))
    # plt.plot(stats["times"], stats["weight"])
    # plt.plot(stats["times"], stats["weight_ref"])
    # plt.plot(stats["times"], stats["B"])
    # plt.plot(stats["times"], stats["Zplus"])
    # plt.plot(stats["times"], stats["Zslow"])
    # plt.plot(stats["times"], stats["Zminus"])
    # plt.legend(["weight", "weight_ref", "B", "Zplus", "Zslow", "Zminus"], loc = "upper left", frameon = False)
    # plt.ylim([-10, 10])
    # plt.subplot(212)
    # plt.plot(stats["times"], stats["C"])
    # plt.plot(stats["times"], stats["Zht"])
    # plt.legend(["C", "Zht"], loc = "upper left", frameon = False)

    # Results
    end_weight = nest.GetStatus(triplet_synapse, keys="weight")[0]
    return end_weight - current_weight
コード例 #28
0
# Configuration of the model `iaf_psc_alpha` and `poisson_generator` using
# SetDefaults(). This function expects the model to be the inserted as a
# string and the parameter to be specified in a dictionary. All instances of
# theses models created after this point will have the properties specified
# in the dictionary by default.

nest.SetDefaults("iaf_psc_alpha", neuron_params)
nest.SetDefaults("poisson_generator", {"rate": p_rate})

###############################################################################
# Creation of the nodes using `Create`. We store the returned handles in
# variables for later reference. Here the excitatory and inhibitory, as well
# as the poisson generator and two spike detectors. The spike detectors will
# later be used to record excitatory and inhibitory spikes.

nodes_ex = nest.Create("iaf_psc_alpha", NE)
nodes_in = nest.Create("iaf_psc_alpha", NI)
noise = nest.Create("poisson_generator")
espikes = nest.Create("spike_detector")
ispikes = nest.Create("spike_detector")

###############################################################################
# Configuration of the spike detectors recording excitatory and inhibitory
# spikes using `SetStatus`, which expects a list of node handles and a list
# of parameter dictionaries. Setting the variable "to_file" to True ensures
# that the spikes will be recorded in a .gdf file starting with the string
# assigned to label. Setting "withtime" and "withgid" to True ensures that
# each spike is saved to file by stating the gid of the spiking neuron and
# the spike time in one line.

nest.SetStatus(espikes, [{
コード例 #29
0
    def test_multisynapse(self):
        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "resources",
                             "iaf_psc_exp_multisynapse.nestml")))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install(module_name)

        # network construction

        neuron = nest.Create("iaf_psc_exp_multisynapse_neuron_nestml")

        sg = nest.Create("spike_generator", params={"spike_times": [20., 80.]})
        nest.Connect(sg,
                     neuron,
                     syn_spec={
                         "receptor_type": 1,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg2 = nest.Create("spike_generator",
                          params={"spike_times": [40., 60.]})
        nest.Connect(sg2,
                     neuron,
                     syn_spec={
                         "receptor_type": 2,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg3 = nest.Create("spike_generator",
                          params={"spike_times": [30., 70.]})
        nest.Connect(sg3,
                     neuron,
                     syn_spec={
                         "receptor_type": 3,
                         "weight": 500.,
                         "delay": 0.1
                     })

        mm = nest.Create('multimeter',
                         params={
                             'record_from': [
                                 'I_kernel1__X__spikes1',
                                 'I_kernel2__X__spikes2',
                                 'I_kernel3__X__spikes3'
                             ],
                             'interval':
                             0.1
                         })
        nest.Connect(mm, neuron)

        vm_1 = nest.Create('voltmeter')
        nest.Connect(vm_1, neuron)

        # simulate

        nest.Simulate(125.)

        # analysis
        V_m_timevec = nest.GetStatus(vm_1)[0]["events"]["times"]
        V_m = nest.GetStatus(vm_1)[0]["events"]["V_m"]
        mm = nest.GetStatus(mm)[0]["events"]
        MAX_ABS_ERROR = 1E-6
        print("Final V_m = " + str(V_m[-1]))
        assert abs(V_m[-1] - -72.89041451202348) < MAX_ABS_ERROR

        if TEST_PLOTS:

            fig, ax = plt.subplots(nrows=4)

            ax[0].plot(V_m_timevec, V_m, label="V_m")
            ax[0].set_ylabel("voltage")

            ax[1].plot(mm["times"],
                       mm["I_kernel1__X__spikes1"],
                       label="I_kernel1")
            ax[1].set_ylabel("current")

            ax[2].plot(mm["times"],
                       mm["I_kernel2__X__spikes2"],
                       label="I_kernel2")
            ax[2].set_ylabel("current")

            ax[3].plot(mm["times"],
                       mm["I_kernel3__X__spikes3"],
                       label="I_kernel3")
            ax[3].set_ylabel("current")

            for _ax in ax:
                _ax.legend(loc="upper right")
                _ax.set_xlim(0., 125.)
                _ax.grid(True)

            for _ax in ax[:-1]:
                _ax.set_xticklabels([])

            ax[-1].set_xlabel("time")

            plt.show()
コード例 #30
0
def test(referenceModel, testant, gsl_error_tol, tolerance=0.000001):
    nest.ResetKernel()

    neuron1 = nest.Create(referenceModel)
    neuron2 = nest.Create(testant)

    if not (gsl_error_tol is None):
        nest.SetStatus(neuron2, {"gsl_error_tol": gsl_error_tol})

    spikegenerator = nest.Create('spike_generator',
                                 params={
                                     'spike_times': [100.0, 200.0],
                                     'spike_weights': [1.0, -1.0]
                                 })

    nest.Connect(spikegenerator, neuron1)
    nest.Connect(spikegenerator, neuron2)

    multimeter1 = nest.Create('multimeter')
    multimeter2 = nest.Create('multimeter')

    V_m_specifier = 'V_m'  # 'delta_V_m'
    nest.SetStatus(multimeter1, {
        "withtime": True,
        "record_from": [V_m_specifier]
    })
    nest.SetStatus(multimeter2, {
        "withtime": True,
        "record_from": [V_m_specifier]
    })

    nest.Connect(multimeter1, neuron1)
    nest.Connect(multimeter2, neuron2)

    nest.Simulate(400.0)
    dmm1 = nest.GetStatus(multimeter1)[0]
    Vms1 = dmm1["events"][V_m_specifier]
    ts1 = dmm1["events"]["times"]

    events1 = dmm1["events"]
    pylab.figure(1)

    dmm2 = nest.GetStatus(multimeter2)[0]
    Vms2 = dmm2["events"][V_m_specifier]
    ts2 = dmm2["events"]["times"]

    # pylab.plot(ts1, Vms1, label = "Reference " + referenceModel)
    # pylab.plot(ts2, Vms2, label = "Testant " + testant)
    # pylab.legend(loc='upper right')

    for index in range(0, len(Vms1)):
        if abs(Vms1[index] - Vms2[index]) > tolerance:
            print('!!!!!!!!!!!!!!!!!!!!')
            print(
                str(Vms1[index]) + " divers from  " + str(Vms2[index]) +
                " at iteration: " + str(index) + " of overall iterations: " +
                str(len(Vms1)))
            print('!!!!!!!!!!!!!!!!!!!!')
            raise Exception(testant + ": TEST FAILED")
        elif abs(Vms1[index] - Vms2[index]) > 0:
            None  # print("Greater than 0 difference" + str(abs(Vms1[index]-Vms2[index])) + " at iteration: " + str(index) + " of overall iterations: " + str(len(Vms1)))
    print(testant + " PASSED")