# This file is for network behavior observation. # Author: Huang-Yu Yao import nest import numpy as np import matplotlib.pylab as plt # Number of input Gammatone bands bands = 32 # Neuronal parameters edict = {"I_e": 100.0, "tau_m": 20.0} nest.CopyModel("iaf_psc_alpha", "exc_iaf_psc_alpha", params=edict) idict = {"I_e": 0.0} nest.CopyModel("iaf_psc_alpha", "inh_iaf_psc_alpha", params=idict) nest.SetDefaults("static_synapse", {"weight": 150.0}) # Create neurons and meters BandSpikeGen = nest.Create("poisson_generator", bands) nest.SetStatus(BandSpikeGen, {"rate": 50.0}) ExcReceiveBand = nest.Create("exc_iaf_psc_alpha", int(bands / 4)) LocInh = nest.Create("inh_iaf_psc_alpha", int(bands / 4)) Detection = nest.Create("exc_iaf_psc_alpha", 1) Vmeter = nest.Create("voltmeter", params={"withtime": True}) Smeter = nest.Create("spike_detector", params={ "withgid": True, "withtime": True }) # Connect neurons and meters conn_dict = {"rule": "fixed_indegree", "indegree": 5} nest.Connect(BandSpikeGen, ExcReceiveBand, conn_dict) nest.Connect(ExcReceiveBand, LocInh, "one_to_one", { "weight": 180, "delay": 1.0
'configbit_0': config_0, 'configbit_1': config_1, 'reset_pattern': reset_pattern, 'a_thresh_th': lut_th_causal, 'a_thresh_tl': lut_th_acausal } ################# # build network # stim = nest.Create('spike_generator') neuronA = nest.Create('parrot_neuron') neuronB = nest.Create('parrot_neuron') #recorder = nest.Create('spike_detector') nest.SetStatus(stim, [{'spike_times': spikesIn}]) nest.SetDefaults(modelName, synapseDict) #check if Get returns same values as have been Set synapseDictGet = nest.GetDefaults(modelName) for key in synapseDict.keys(): assert (all(np.atleast_1d(synapseDictGet[key] == synapseDict[key]))) nest.Connect(stim, neuronA) nest.Connect(neuronA, neuronB, float(startWeight) / 15.0 * Wmax, delay, model=modelName) #nest.Connect(neuronA, recorder) #nest.Connect(neuronB, recorder)
############################################################################### # To record the instantaneous population rate `Abar(t)` we use a multimeter, # and to get the population activity `A_N(t)` we use spike recorder: # monitor the output using a multimeter, this only records with dt_rec! nest_mm = nest.Create('multimeter') nest_mm.set(record_from=['n_events', 'mean'], interval=dt_rec) nest.Connect(nest_mm, nest_pops) # monitor the output using a spike recorder nest_sr = [] for i in range(M): nest_sr.append(nest.Create('spike_recorder')) nest_sr[i].time_in_steps = True nest.SetDefaults('static_synapse', {'weight': 1., 'delay': dt}) nest.Connect(nest_pops[i], nest_sr[i]) ############################################################################### # All neurons in a given population will be stimulated with a step input # current: # set initial value (at t0+dt) of step current generator to zero tstep = np.hstack((dt * np.ones((M, 1)), tstep)) step = np.hstack((np.zeros((M, 1)), step)) # create the step current devices nest_stepcurrent = nest.Create('step_current_generator', M) # set the parameters for the step currents for i in range(M): nest_stepcurrent[i].set(amplitude_times=tstep[i] + t0,
rqs = nest.GetDefaults('iaf_cond_alpha_mc')['recordables'] print("iaf_cond_alpha_mc recordables : {0}".format(rqs)) ############################################################################### # The simulation parameters are assigned to variables. nest.SetDefaults( 'iaf_cond_alpha_mc', { 'V_th': -60.0, # threshold potential 'V_reset': -65.0, # reset potential 't_ref': 10.0, # refractory period 'g_sp': 5.0, # somato-proximal coupling conductance 'soma': { 'g_L': 12.0 }, # somatic leak conductance # proximal excitatory and inhibitory synaptic time constants 'proximal': { 'tau_syn_ex': 1.0, 'tau_syn_in': 5.0 }, 'distal': { 'C_m': 90.0 } # distal capacitance }) ############################################################################### # The nodes are created using ``Create``. We store the returned handles # in variables for later reference. n = nest.Create('iaf_cond_alpha_mc')
# parameter set for facilitation fac_params = {"U": 0.03, "u": 0.03, "tau_fac": 500., "tau_rec": 200., "weight": 1.} dep_params = {"U": 0.5, "u": 0.5, "tau_fac": 15., "tau_rec": 670., "weight": 1.} lin_params = {"U": 0.3, "u": 0.3, "tau_fac": 330., "tau_rec": 330., "weight": 1.} # Here we assign the parameter set to the synapse models t1_params = fac_params # for tsodyks2_synapse t2_params = t1_params.copy() # for furhmann_synapse t2_params['n'] = n_syn t2_params['weight'] = 1. / n_syn nest.SetDefaults("tsodyks2_synapse", t1_params) nest.SetDefaults("quantal_stp_synapse", t2_params) nest.SetDefaults("iaf_psc_exp", {"tau_syn_ex": 3., 'tau_m': 70.}) source = nest.Create('spike_generator') nest.SetStatus(source, {'spike_times': [30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330., 360., 390., 900.]}) parrot = nest.Create('parrot_neuron') neuron = nest.Create("iaf_psc_exp", 2) nest.Connect(source, parrot) nest.Connect(parrot, neuron[:1], syn_spec="tsodyks2_synapse") nest.Connect(parrot, neuron[1:], syn_spec="quantal_stp_synapse")
import pylab import nest import sys flag=(sys.argv[1]) msd=int(sys.argv[2]) n_cues=int(sys.argv[3]) NS_flag=float(sys.argv[4]) PFC_flag=float(sys.argv[5]) ACC_PFC_flag=float(sys.argv[6]) nest.ResetKernel() nest.SetKernelStatus({"resolution":0.1, "print_time":True, "overwrite_files":True}) nest.SetDefaults('iaf_psc_exp',{'tau_syn_ex':2.0,'tau_syn_in':2.0,'t_ref':3.0}) N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0] pyrngs = [numpy.random.RandomState(s) for s in range(msd, msd+N_vp)] nest.SetKernelStatus({'grng_seed' : msd+N_vp}) nest.SetKernelStatus({'rng_seeds' : range(msd+N_vp+1, msd+2*N_vp+1)}) numpy.random.seed(msd) PFC_turn=nest.Create('iaf_psc_exp',400) PFC_push=nest.Create('iaf_psc_exp',400) PFC_turn_i=nest.Create('iaf_psc_exp',100) PFC_push_i=nest.Create('iaf_psc_exp',100) PFC_inh=nest.Create('iaf_psc_exp',100) motor_turn=nest.Create('iaf_psc_exp',400) motor_push=nest.Create('iaf_psc_exp',400)
# Configuration of the simulation kernel by the previously defined time # resolution used in the simulation. Setting ``print_time`` to True prints # the already processed simulation time as well as its percentage of the # total simulation time. nest.ResetKernel() nest.SetKernelStatus({"resolution": dt, "use_wfr": False, "print_time": True, "overwrite_files": True}) print("Building network") ############################################################################### # Configuration of the neuron model using ``SetDefaults``. nest.SetDefaults(neuron_model, neuron_params) ############################################################################### # Creation of the nodes using ``Create``. n_e = nest.Create(neuron_model, NE) n_i = nest.Create(neuron_model, NI) ################################################################################ # To record from the rate neurons a ``multimeter`` is created and the parameter # ``record_from`` is set to `rate` as well as the recording interval to `dt` mm = nest.Create('multimeter', params={'record_from': ['rate'], 'interval': dt})
# voltmeter = nest.Create('voltmeter') # nest.SetStatus(voltmeter, {'to_file': True, 'interval': 0.1 }) # nest.Connect(voltmeter,hh_neuron) # nest.Simulate(100) # nest.voltage_trace.from_device(voltmeter) # nest.voltage_trace.show() ## Current vs FR Curve # Env Setup nest.ResetKernel() nest.SetDefaults('hh_cond_exp_traub', hh_defaults) nest.SetKernelStatus({'resolution': 0.01}) nest.SetKernelStatus({'overwrite_files': True}) hh_neurons = nest.Create('hh_cond_exp_traub', n=20) for k in range(20): nest.SetStatus([hh_neurons[k]], {'I_e': k * 200.}) sd = nest.Create('spike_detector') nest.SetStatus(sd, {'to_file': True}) nest.ConvergentConnect(hh_neurons, sd) nest.Simulate(1000) figure()
vm = nest.Create('voltmeter', 1, vm_pars) ############################################################################### # Now, we connect each pulse generator to one neuron via static synapses. # We want to keep all properties of the static synapse constant except the # synaptic weight. Therefore we change the weight with the help of the command # ``SetDefaults``. # The command ``Connect`` connects all kinds of nodes/devices. Since multiple # nodes/devices can be connected in different ways e.g., each source connects # to all targets, each source connects to a subset of targets or each source # connects to exactly one target, we have to specify the connection. In our # case we use the ``one_to_one`` connection routine since we connect one pulse # generator (source) to one neuron (target). # In addition we also connect the `voltmeter` to the `neurons`. nest.SetDefaults('static_synapse', {'weight': weight}) nest.Connect(ppgs, neurons, 'one_to_one') nest.Connect(vm, neurons) ############################################################################### # In the next step we run the simulation for a given duration in ms. nest.Simulate(simtime) ############################################################################### # Finally, we record the membrane potential, when it occurred and to which # neuron it belongs. The sender and the time point of a voltage # data point at position x in the voltage array (``V_m``), can be found at the # same position x in the sender (`senders`) and the time array (`times`). Vm = vm.get('events', 'V_m')
def __setup_neurons(self): """Setup neuron sets.""" # populations self.populations = { 'E': 8000, 'I': 2000, 'P': 800, 'R': 400, 'D': 200, 'STIM': 1000, 'Poisson': 1 } # Growth curves # eta is the minimum calcium concentration # epsilon is the target mean calcium concentration # Excitatory synaptic elements of excitatory neurons self.growth_curve_axonal = { 'growth_curve': "gaussian", 'growth_rate': 0.0001, # (elements/ms) 'continuous': False, 'eta': 0.4, 'eps': 0.7, } # Inhibitory synaptic elements of excitatory neurons self.growth_curve_dendritic = { 'growth_curve': "gaussian", 'growth_rate': 0.0001, # (elements/ms) 'continuous': False, 'eta': 0.1, 'eps': self.growth_curve_axonal['eps'], } self.synaptic_elements_E = { 'Den_ex': self.growth_curve_dendritic, 'Den_in': self.growth_curve_dendritic, 'Axon_ex': self.growth_curve_axonal } self.synaptic_elements_I = { 'Den_ex': self.growth_curve_dendritic, 'Den_in': self.growth_curve_dendritic, 'Axon_in': self.growth_curve_axonal } # see the aif source for symbol definitions self.neuronDict = { 'V_m': -60., 't_ref': 5.0, 'V_reset': -60., 'V_th': -50., 'C_m': 200., 'E_L': -60., 'g_L': 10., 'E_ex': 0., 'E_in': -80., 'tau_syn_ex': 5., 'tau_syn_in': 10. } # Set up TIF neurons # Setting up two models because then it makes it easier for me to get # them when I need to set up patterns nest.CopyModel("iaf_cond_exp", "tif_neuronE") nest.SetDefaults("tif_neuronE", self.neuronDict) nest.CopyModel("iaf_cond_exp", "tif_neuronI") nest.SetDefaults("tif_neuronI", self.neuronDict) # external current self.poissonExtDict = {'rate': 10., 'origin': 0., 'start': 0.}
def brunel_network(eta, g, delay, J): """ A brunel network, from: Brunel N, Dynamics of Sparsely Connected Networks of Excitatory and Inhibitory Spiking Neurons, Journal of Computational Neuroscience 8, 183-208 (2000). Implementation adapted from: http://www.nest-simulator.org/py_sample/random-balanced-network-exp-synapses-multiple-time-constants/ Parameters ---------- g : {int, float}, optional Ratio inhibitory weight/excitatory weight. Default is 5. eta : {int, float}, optional External rate relative to threshold rate. Default is 2. delay : {int, float}, optional Synaptic delay in ms. Default is 1.5. J : {int, float}, optional Amplitude of excitatory postsynaptic current. Default is 0.1 Raises ------ ImportError If nest is not installed. """ if not nest_prerequisite: raise ImportError("brunel_network requires: nest") # Reduced number of neurons and simulation time # Network parameters N_rec = 20 # Record from 20 neurons simulation_end = 100 # Simulation time tau_m = 20.0 # Time constant of membrane potential in ms V_th = 20.0 N_E = 1000 # Number of inhibitory neurons N_I = 250 # Number of excitatory neurons N_neurons = N_E + N_I # Number of neurons in total C_E = int(N_E/10) # Number of excitatory synapses per neuron C_I = int(N_I/10) # Number of inhibitory synapses per neuron J_I = -g*J # Amplitude of inhibitory postsynaptic current nu_ex = eta*V_th/(J*C_E*tau_m) p_rate = 1000.0*nu_ex*C_E nest.ResetKernel() # Configure kernel nest.SetKernelStatus({"grng_seed": 10}) nest.SetDefaults('iaf_psc_delta', {'C_m': 1.0, 'tau_m': tau_m, 't_ref': 2.0, 'E_L': 0.0, 'V_th': V_th, 'V_reset': 10.0}) # Create neurons nodes = nest.Create('iaf_psc_delta', N_neurons) nodes_E = nodes[:N_E] nodes_I = nodes[N_E:] noise = nest.Create('poisson_generator',1,{'rate': p_rate}) spikes = nest.Create('spike_detector',2, [{'label': 'brunel-py-ex'}, {'label': 'brunel-py-in'}]) spikes_E = spikes[:1] spikes_I = spikes[1:] # Connect neurons to each other nest.CopyModel('static_synapse_hom_w', 'excitatory', {'weight':J, 'delay':delay}) nest.Connect(nodes_E, nodes, {'rule': 'fixed_indegree', 'indegree': C_E}, 'excitatory') nest.CopyModel('static_synapse_hom_w', 'inhibitory', {'weight': J_I, 'delay': delay}) nest.Connect(nodes_I, nodes, {'rule': 'fixed_indegree', 'indegree': C_I}, 'inhibitory') # Connect poisson generator to all nodes nest.Connect(noise, nodes, syn_spec='excitatory') nest.Connect(nodes_E[:N_rec], spikes_E) nest.Connect(nodes_I[:N_rec], spikes_I) # Run the simulation nest.Simulate(simulation_end) events_E = nest.GetStatus(spikes_E, 'events')[0] events_I = nest.GetStatus(spikes_I, 'events')[0] # Excitatory spike trains # Makes sure the spiketrain is added even if there are no results # to get a regular result spiketrains = [] for sender in nodes_E[:N_rec]: spiketrain = events_E["times"][events_E["senders"] == sender] spiketrains.append(spiketrain) return simulation_end, spiketrains
def build(self): #Initialization of the parameters of the integrate and fire neuron and the synapses. The parameter of the neuron are stored in a dictionary. self.neuron_params = { "C_m": self.CMem, "tau_m": self.tauMem, "t_ref": self.t_ref, "E_L": 0.0, "V_reset": self.V_res, "V_m": self.V_m, "V_th": self.theta } if self.verbose: print(self.neuron_params) self.J_ex = self.J # amplitude of excitatory postsynaptic potential self.J_in = -self.g * self.J_ex # amplitude of inhibitory postsynaptic potential if self.verbose: print('J_i = %s' % (self.J_in)) #Poisson Rate self.nu_th = self.theta / ( self.J * self.CE * self.tauMem ) # (theta * CMem) / (J_ex * CE * exp(1) * tauMem * tauSyn) self.nu_ex = self.eta * self.nu_th self.p_rate = 1000.0 * self.nu_ex * self.CE nest.SetDefaults("iaf_psc_delta", self.neuron_params) nest.SetDefaults("poisson_generator", {"rate": self.p_rate}) self.nodes_ex = nest.Create("iaf_psc_delta", self.NE) self.nodes_in = nest.Create("iaf_psc_delta", self.NI) self.noise = nest.Create("poisson_generator") self.espikes = nest.Create("spike_detector") if self.record_vol: self.voltmeter = nest.Create("multimeter") #self.ispikes = nest.Create("spike_detector") self.nodes_al = self.nodes_ex + self.nodes_in nest.SetStatus( self.espikes, [{ "label": self.simulation, "withtime": True, "withgid": True, #%(n_i_), "to_file": True }]) if self.record_vol: nest.SetStatus( self.voltmeter, [{ "label": self.simulation + '_voltage', 'record_from': ['V_m'], 'interval': 0.05, "withtime": True, "withgid": True, #%(n_i_), "to_file": True }]) #nest.SetStatus(self.ispikes,[{"label": "brunel-py-in", # "withtime": True, # "withgid": True}])#%(n_i_)"to_file": True self.vinit = np.random.normal(10, 3.5, [self.NE + self.NI]) #for FR = 0.1 #self.vinit[:] = -25. nest.SetStatus(self.nodes_al, "V_m", self.vinit) self.built = True
def build(self, amp=0, c_start=0, init_voltage=False, nu=0.15): #n_st = 0): #Initialization of the parameters of the integrate and fire neuron and the synapses. The parameter of the neuron are stored in a dictionary. self.neuron_params = { "C_m": self.CMem, "tau_m": self.tauMem, "t_ref": self.t_ref, "E_L": 0.0, "V_reset": self.V_res, "V_m": self.V_m, "V_th": self.theta } if self.verbose: print(self.neuron_params) self.J_ex = self.J # amplitude of excitatory postsynaptic potential self.J_in = -self.g * self.J_ex # amplitude of inhibitory postsynaptic potential if self.verbose: print('J_i = %s' % (self.J_in)) #Poisson Rate self.nu_th = self.theta / ( self.J * self.CE * self.tauMem ) # (theta * CMem) / (J_ex * CE * exp(1) * tauMem * tauSyn) self.nu_ex = self.eta * self.nu_th self.p_rate = 1000.0 * self.nu_ex * self.CE nest.SetDefaults("iaf_psc_delta_canon", self.neuron_params) nest.SetDefaults("poisson_generator_ps", {"rate": self.p_rate}) self.nodes_ex = nest.Create("iaf_psc_delta_canon", self.NE) self.nodes_in = nest.Create("iaf_psc_delta_canon", self.NI) self.noise = nest.Create("poisson_generator_ps") self.espikes = nest.Create("spike_detector") if self.record_vol: self.voltmeter = nest.Create("multimeter") #self.ispikes = nest.Create("spike_detector") self.nodes_al = self.nodes_ex + self.nodes_in nest.SetStatus( self.espikes, [{ "label": self.simulation, "withtime": True, "precise_times": True, "precision": 50, "withgid": True, #%(n_i_), "to_file": True }]) if self.record_vol: nest.SetStatus( self.voltmeter, [{ "label": self.simulation + '_voltage', 'record_from': ['V_m'], 'interval': 0.05, "withtime": True, "withgid": True, #%(n_i_), "to_file": True }]) if init_voltage: # #_ = self.get_analytical_V(nu) self.mu_s = 9.76 self.sigma_s = 2.701 # self.vinit = np.random.normal(self.mu_s,self.sigma_s,[self.NE+self.NI]) #for FR = 0.1 # #self.vinit = np.random.normal(10,3.7,[self.NE+self.NI]) #for FR = 0.1 # self.stim_n = np.random.randint(1,self.NE, n_st) # print(self.stim_n) # nest.SetStatus(self.nodes_al, "V_m", self.vinit) #nest.SetStatus(self.ispikes,[{"label": "brunel-py-in", # "withtime": True, # "withgid": True}])#%(n_i_)"to_file": True # DC stimulation #t_stim = 0. # perturbation time (time of the extra spike) #fade_out = 0.5*self.delay[0] # fade out time (ms) *0.5 #c_start =c_start# 2.4 #c_stop = c_start#3.5 #self.amp = amp #self.current = nest.Create("dc_generator", # params={'amplitude': self.amp, # 'start': c_start, # 'stop': c_stop+t_stim+fade_out})#10e4 self.built = True
def f_sim(flag): ''' perform simulation and save the results ''' np.random.seed(35) # set python seed for reproducibility G_syn_temp=copy.deepcopy(G_syn) if flag=='noampa': G_syn_temp[:,0]*=0. if flag=='nonmda': G_syn_temp[:,1]*=0. if flag=='nogaba': G_syn_temp[:,2]*=0. ################################################## ######## CREATE CONNECTIVITY MAPS ############# ################################################## # initialize connection maps ConMap=[] for t_pop in range(2): ConMap += [[]] for s_pop in range(2): ConMap[t_pop] += [np.zeros([N[t_pop], N[s_pop]])] ind_to_con_ex = np.arange(0, N[0], 1) # indices of neurons in exc population ind_to_con_in = np.arange(0, N[1], 1) # indices of neurons in inh population ind_to_con = np.arange(0,np.sum(N),1) # indices of combined neurons for s_pop in range(2): # create Gaussian distributed out-degrees for source neurons Outdegree = np.random.normal(outdegree_mu, outdegree_sd, N[s_pop]) Outdegree[Outdegree < 1] = 1 Outdegree = np.array(Outdegree, dtype=int) for s_ind in range(N[s_pop]): # create probability weights for target excitatory population target_position = 1. * s_ind/N[s_pop] * (N[0]-1) Weight_list_ex = f_gaussian(ind_to_con_ex, target_position, sigma[0][s_pop]) # create probability weights for target inhibitory population target_position = 1. * s_ind/N[s_pop] * (N[1]-1) Weight_list_in = f_gaussian(ind_to_con_in, target_position, sigma[1][s_pop]) # create lists of weights and ids for merged populations Weight_list = np.append(Weight_list_ex, Weight_list_in) ind_to_con = np.arange(0,np.sum(N),1) # remove autapses s_gid = s_ind + N[0]*s_pop Weight_list = np.delete(Weight_list, s_gid) ind_to_con = np.delete(ind_to_con, s_gid) # randomly select targets from both populations according to # connection probability target_choice = np.random.choice(ind_to_con, size = Outdegree[s_ind], p = Weight_list/np.sum(Weight_list), replace = True) # split targets to individual populations target_ids = [target_choice[target_choice < N[0]]] target_ids += [target_choice[target_choice >= N[0]]] target_ids[1] -= N[0] # to make ids to start from zero # fill connectivity maps with numbers of synapses for chosen # connections for t_pop in range(2): Con_local=ConMap[t_pop][s_pop] for t_ind in target_ids[t_pop]: Con_local[t_ind, s_ind] += 1 ConMap[t_pop][s_pop] = Con_local ########################################### #### CREATE OBJECTS #################### ########################################### # initialize NEST kernel nest.ResetKernel() nest.SetKernelStatus({"resolution": dt, "local_num_threads": 4 }) # create neurons Neurons=[] for t_pop in range(2): neuron_name = 'compte2003_' + ['ex','in'][t_pop] nest.SetDefaults(neuron_name,Params_neuron[t_pop]) # distribute membrane E_L, g_L randomly g_L = (np.random.normal(1., cv_gL[t_pop], N[t_pop]) * Params_neuron[t_pop]['g_L']) E_L = (np.random.normal(0., sd_EL[t_pop], N[t_pop]) + Params_neuron[t_pop]['E_L']) # axial conductance is distributed only for exc neurons if t_pop==0: g_conn = (np.random.normal(0., sd_Gax, N[t_pop]) + Params_neuron[t_pop]['g_conn']) # create list of dictionaries with distributed neuronal parameters params = [{'g_L': g_L[i], 'E_L': E_L[i], #'V_m_s': E_L[i], 'g_conn' : g_conn[i]} for i in range(N[t_pop])] else: # create list of dictionaries with distributed neuronal parameters params = [{'g_L': g_L[i], 'E_L' : E_L[i]} for i in range(N[t_pop])] Neurons += [nest.Create(model=neuron_name, n=N[t_pop], params=params)] # create spike detectors Sd = nest.Create('spike_detector', params=Sd_params) # for exc neurons Sd += nest.Create('spike_detector', params=Sd_params) # for inh neurons # create multimeters Mm =[nest.Create('multimeter', n=min(N[0],num_mm), params=Mm_params)] # create hyper-polarizing generator to measure R gen_R_basic = nest.Create('dc_generator', params={ 'start': 0. , 'stop' : sim_time, 'amplitude':params_R['ampl_base']}) # create generators for each pulse injection while measuring R t0 = params_R['dur_off'] gen_R_pulse = [] while t0 < (sim_time): # create generator for base current injection (off period) gen_R_pulse += nest.Create('dc_generator', params={ 'start': t0, 'stop': t0+params_R['dur_on'], 'amplitude': params_R['ampl_pulse']}) t0 += params_R['dur_off'] + params_R['dur_on'] ########################################### #### CONNECT OBJECTS ################### ########################################### # create temporal copies of synaptic models nest.CopyModel('static_synapse','static_temp') nest.CopyModel('tsodyks2_synapse','tsodyks_temp') for t_pop in range(2): # for each target population for s_pop in range(2): # for each source population for s_ind in range(N[s_pop]): # for each source neuron # connect to those target neurons, where number of synapses per # connection is>0 mask = ConMap[t_pop][s_pop][:,s_ind]>0 target_gid = list(np.array(Neurons[t_pop])[mask]) if s_pop == 0: # if source population is excitatory # connect AMPA weights = np.transpose( np.array([ G_syn_temp[t_pop, 0] * ConMap[t_pop][s_pop][:, s_ind][mask]])) nest.SetDefaults('static_temp', params={ 'receptor_type': syns['ampa']}) nest.Connect([Neurons[s_pop][s_ind]], target_gid, {'rule': 'all_to_all'}, {'model': 'static_temp', 'weight': weights, 'delay': syn_delay}) # connect NMDA weights = np.transpose( np.array([G_syn_temp[t_pop, 1] * ConMap[t_pop][s_pop][:, s_ind][mask]])) nest.SetDefaults('tsodyks_temp', params={ 'receptor_type': syns['nmda_fast'], 'tau_rec': tsodyks_tau_rec, 'tau_fac': tsodyks_tau_fac, 'U': tsodyks_u}) nest.Connect([Neurons[s_pop][s_ind]], target_gid, {'rule': 'all_to_all'}, {'model': 'tsodyks_temp', 'weight': weights, 'delay': syn_delay}) else: # connect GABA weights = np.transpose( np.array([ G_syn_temp[t_pop,2] * ConMap[t_pop][s_pop][:,s_ind][mask]])) nest.SetDefaults('static_temp', params={ 'receptor_type': syns['gaba']}) nest.Connect([Neurons[s_pop][s_ind]], target_gid, {'rule': 'all_to_all'}, {'model': 'static_temp', 'weight': weights, 'delay': syn_delay}) # connect spike detectors nest.Connect(Neurons[t_pop], [Sd[t_pop]], {'rule': 'all_to_all'}) # randomly connect multimeters if t_pop==0: n_gids = list(np.random.choice(Neurons[t_pop], len(Mm[t_pop]), replace = False)) nest.Connect(Mm[t_pop], n_gids, {'rule':'one_to_one'}) # connect hyperpolarizing generators to first recorded PY neuron if t_pop == 0: nest.Connect(gen_R_basic, [n_gids[0]], {'rule':'all_to_all'}, {'receptor_type':syns['curr']}) nest.Connect(gen_R_pulse, [n_gids[0]], {'rule':'all_to_all'}, {'receptor_type':syns['curr']}) ############################################# ##### SIMULATE ########################### ############################################# nest.Simulate(sim_time) ########################################### #### SAVE DATA ################# ########################################### # prepare multimeter data for saving Mm_raw = [] for t_pop in [0]:#range(2): Mm_raw += [[]] mm_id = 0 for mm in Mm[t_pop]: data = nest.GetStatus([mm])[0]['events'] temp = {'V_m': data['V_m_s']} temp['times'] = data['times'] temp['g_ex'] = (data['g_ampa'] + data['g_nmda_slow'] - data['g_nmda_fast']) temp['g_in'] = data['g_gaba'] temp['senders'] = data['senders'] a_m = 0.1 *(data['V_m_s']+33.)/(1.-np.exp(-(data['V_m_s']+33.)/10.)) b_m = 4. * np.exp( -(data['V_m_s']+53.7) / 12.) m_inf = a_m / (a_m+b_m) temp['g_Na'] = (Params_neuron[t_pop]['g_Na'] * np.power(m_inf,3)*data['Na_h'] ) temp['g_K'] = (Params_neuron[t_pop]['g_K'] * np.power(data['K_m'],4) ) m_inf = 1. / (1. + np.exp( -(data['V_m_s']+50.) / 20.)) temp['g_K_A'] = (Params_neuron[t_pop]['g_K_A'] * np.power(m_inf,3) * data['K_A_h']) temp['g_K_s'] = (Params_neuron[t_pop]['g_K_s'] * data['K_s_m'] ) Na_p_m = 1. / (1. + np.exp( -(data['V_m_d']+ 55.7) / 7.7)) temp['g_Na_p'] = (Params_neuron[t_pop]['g_Na_p'] * np.power(Na_p_m,3) ) K_ar_h = 1. / (1. + np.exp((data['V_m_d'] + 75.) / 4.)) temp['g_K_ar'] = K_ar_h*Params_neuron[t_pop]['g_K_AR'] m_inf = 1. / (1. + np.exp( -(data['V_m_d']+20.) / 9.)) temp['g_Ca'] = (Params_neuron[t_pop]['g_Ca'] * np.power(m_inf,2) ) temp['n_Ca'] = data['n_Ca'] temp['g_K_Ca'] = (Params_neuron[t_pop]['g_K_Ca'] * 1./ (1. + 30./data['n_Ca']) ) temp['n_Na'] = data['n_Na'] temp['g_K_Na'] = (Params_neuron[t_pop]['g_K_Na'] * 0.37 / (1.+np.power(38.7/data['n_Na'],3.5)) ) Mm_raw[t_pop] += [temp] mm_id += 1 # prepare sd data for saving Sd_raw = [] for t_pop in range(2): Sd_raw += [nest.GetStatus([Sd[t_pop]])[0]['events']] # save data np.savez('./Compte2003_mm_block_%s' %flag, Mm_raw) np.savez('./Compte2003_sd_block_%s' %flag, Sd_raw) return None
amplitudes = np.zeros((nEnc, len(u))) for n in range(nEnc): amplitudes[n, :] = u * tuning[n] nest.SetStatus([enc_layer[n]], {'V_m': Vm0[n], 'V_th': thresholds[n]}) nest.SetStatus([step_generator[n]], {'amplitude_times': input_times, 'amplitude_values': amplitudes[n]}) nest.Connect([step_generator[n]], [enc_layer[n]]) enc_v = nest.Create('multimeter', 1, {'record_from': ['V_m'], 'interval': dt*subsampling_factor}) nest.Connect(enc_v, enc_layer) # Distribution of tau_m according to sigma tau_m_distrib = np.random.normal(tau_m, sigma, NE + int(0.25 * NE)) # set default parameters for neurons and create neurons nest.SetDefaults('iaf_psc_delta', neuron_params) neurons_e = nest.Create(n_ex_model, NE) neurons_i = nest.Create(n_inh_model, NI) for n in range(NE): nest.SetStatus([neurons_e[n]], {'V_m': Vm0_circ[n], 'V_th': Thresh_circ[n], 'tau_m': tau_m_distrib[n]}) for n in range(NI): nest.SetStatus([neurons_i[n]], {'V_m': Vm0_circ[NE + n], 'V_th': Thresh_circ[NE + n], 'tau_m': tau_m_distrib[NE + n]}) # E synapses syn_exc = {'delay': d, 'weight': w} conn_exc = {'rule': 'fixed_indegree', 'indegree': CE} nest.Connect(neurons_e, neurons_e, conn_exc, syn_exc) nest.Connect(neurons_e, neurons_i, conn_exc, syn_exc)
def initNeurons(): nest.SetDefaults("iaf_psc_alpha_multisynapse", CommonParams)
# see the aif source for symbol definitions self.neuronDict = { 'V_m': -60., 't_ref': 5.0, 'V_reset': -60., 'V_th': -50., 'C_m': 200., 'E_L': -60., 'g_L': 10., 'E_ex': 0., 'E_in': -80., 'tau_syn_ex': 5., 'tau_syn_in': 10. } # Set up TIF neurons # Setting up two models because then it makes it easier for me to get # them when I need to set up patterns nest.CopyModel("iaf_cond_exp", "tif_neuronE") nest.SetDefaults("tif_neuronE", self.neuronDict) nest.CopyModel("iaf_cond_exp", "tif_neuronI") nest.SetDefaults("tif_neuronI", self.neuronDict) self.neuronsE = nest.Create('tif_neuronE', 8000) self.neuronsI = nest.Create('tif_neuronI', 2000) self.poissonExtE = nest.Create('poisson_generator', self.populations['Poisson'], params=self.poissonExtDict) self.poissonExtI = nest.Create('poisson_generator', self.populations['Poisson'], params=self.poissonExtDict)
def do_the_nest_simulation(self): """ This function is where calls to NEST reside. Returns the generated pre- and post spike sequences and the resulting weight established by STDP. """ nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.SetKernelStatus({'resolution': self.resolution}) neurons = nest.Create("parrot_neuron", 2, params=self.neuron_parameters) presynaptic_neuron = neurons[0] postsynaptic_neuron = neurons[1] generators = nest.Create( "poisson_generator", 2, params=({ "rate": self.presynaptic_firing_rate, "stop": (self.simulation_duration - self.hardcoded_trains_length) }, { "rate": self.postsynaptic_firing_rate, "stop": (self.simulation_duration - self.hardcoded_trains_length) })) presynaptic_generator = generators[0] postsynaptic_generator = generators[1] # While the random sequences, fairly long, would supposedly # reveal small differences in the weight change between NEST # and ours, some low-probability events (say, coinciding # spikes) can well not have occurred. To generate and # test every possible combination of pre/post precedence, we # append some hardcoded spike sequences: # pre: 1 5 6 7 9 11 12 13 # post: 2 3 4 8 9 10 12 hardcoded_pre_times, hardcoded_post_times = [[ self.simulation_duration - self.hardcoded_trains_length + t for t in train ] for train in ((1, 5, 6, 7, 9, 11, 12, 13), (2, 3, 4, 8, 9, 10, 12))] spike_senders = nest.Create("spike_generator", 2, params=({ "spike_times": hardcoded_pre_times }, { "spike_times": hardcoded_post_times })) pre_spike_generator = spike_senders[0] post_spike_generator = spike_senders[1] # The recorder is to save the randomly generated spike trains. spike_recorder = nest.Create("spike_recorder") nest.Connect(presynaptic_generator + pre_spike_generator, presynaptic_neuron, syn_spec={"synapse_model": "static_synapse"}) nest.Connect(postsynaptic_generator + post_spike_generator, postsynaptic_neuron, syn_spec={"synapse_model": "static_synapse"}) nest.Connect(presynaptic_neuron + postsynaptic_neuron, spike_recorder, syn_spec={"synapse_model": "static_synapse"}) # The synapse of interest itself nest.SetDefaults(self.synapse_parameters["synapse_model"], self.synapse_constants) nest.Connect(presynaptic_neuron, postsynaptic_neuron, syn_spec=self.synapse_parameters) plastic_synapse_of_interest = nest.GetConnections( synapse_model=self.synapse_parameters["synapse_model"]) nest.Simulate(self.simulation_duration) all_spikes = spike_recorder.events pre_spikes = all_spikes['times'][all_spikes['senders'] == presynaptic_neuron.tolist()[0]] post_spikes = all_spikes['times'][all_spikes['senders'] == postsynaptic_neuron.tolist()[0]] weight = plastic_synapse_of_interest.weight return (pre_spikes, post_spikes, weight)
'V_th': V_th, '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. ''' nest.SetDefaults('iaf_psc_alpha', neurondict) n = nest.Create('iaf_psc_alpha', n_neurons) n_free = nest.Create('iaf_psc_alpha', 1, [{'V_th': 1e12}]) pg = nest.Create('poisson_generator', len(rates), [{ 'rate': float(rate_i) } for rate_i in rates]) vm = nest.Create('voltmeter', 1, [{'interval': .1}]) sd = nest.Create('spike_detector', 1) ''' We connect devices and neurons and start the simulation. ''' for i, currentpg in enumerate(pg): nest.Connect([currentpg], n, syn_spec={ 'weight': float(J[i]),
# set neuron parameters: neuron_param = { "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") # create voltmeter
def build(self, N_total_neuron=12500, N_rec_volt=3, N_rec=50, J=0.1, **neuron_params): """Arguments @param N_total_neuron : (int) the amount population @param N_rec_volt : (int) the amount of neurons whose voltages are recorded. @param N_rec : (int) @param J : (float) postsynaptic amplitude in mV. """ self.n_rec_volt = N_rec_volt self.n_rec = N_rec if len(neuron_params) == 0: print( f"Using default neuron parameters for `iaf_psc_delta` model. If you want to know more, please look at 'https://github.com/iwasakishuto/University/blob/gh-pages/3A/theme/program/OIST/tutorial3.py#L67'" ) neuron_params = Default_Neuron_Params #=== Initialization of the parameters ========= nest.ResetKernel() start = time.time() n_excitatory = int(N_total_neuron * 0.8) n_inhibitory = N_total_neuron - n_excitatory neuron_digit = len(str(N_total_neuron)) print(f"Number of neurons : {N_total_neuron:>{neuron_digit}}") print(f" Excitatory: {n_excitatory:>{neuron_digit}}") print(f" Inhibitory: {n_inhibitory:>{neuron_digit}}") #---------------------------------------------- ex_synapses_per_neuron = int( self.epsilon * n_excitatory) # num of excitatory synapses per neuron. in_synapses_per_neuron = int( self.epsilon * n_inhibitory) # num of inhibitory synapses per neuron. tot_synapses_per_neuron = ex_synapses_per_neuron + in_synapses_per_neuron # total number of synapse per neuron. synapses_digit = len(str(int(tot_synapses_per_neuron * N_total_neuron))) print( f"Number of synapses: {int(tot_synapses_per_neuron * N_total_neuron):>{synapses_digit}}" ) print( f" Excitatory: {int(ex_synapses_per_neuron * N_total_neuron):>{synapses_digit}}" ) print( f" Inhibitory: {int(in_synapses_per_neuron * N_total_neuron):>{synapses_digit}}" ) #---------------------------------------------- tauMem = neuron_params.get( "tau_m") # Time constant of membrane potential in ms theta = neuron_params.get("V_th") # Membrane threshold potential in mV p_rate = self.calcurate_Poisson_params(J, tauMem, theta, ex_synapses_per_neuron) ############################################### #=== Configuration of the simulation kernel === nest.SetKernelStatus({ "resolution": self.dt, "print_time": True, "overwrite_files": True }) nest.SetDefaults("iaf_psc_delta", neuron_params) nest.CopyModel("static_synapse", "excitatory", { "weight": self.J_ex, "delay": self.delay }) nest.CopyModel("static_synapse", "inhibitory", { "weight": self.J_in, "delay": self.delay }) BrunelNodes.syn_spec = "excitatory" poisson_noise = nest.Create("poisson_generator", params={"rate": p_rate}) nodes_ex = BrunelNodes(n_excitatory, N_rec_volt, N_rec, poisson_noise) nodes_in = BrunelNodes(n_inhibitory, N_rec_volt, N_rec, poisson_noise) nest.Connect(nodes_ex.neuron, nodes_ex.neuron + nodes_in.neuron, { 'rule': 'fixed_indegree', 'indegree': ex_synapses_per_neuron }, "excitatory") nest.Connect(nodes_in.neuron, nodes_ex.neuron + nodes_in.neuron, { 'rule': 'fixed_indegree', 'indegree': in_synapses_per_neuron }, "inhibitory") self.nodes_ex = nodes_ex self.nodes_in = nodes_in print(f"Building time : {time.time()-start:.2f} s")
def simulate(self, pattern): # ====== RESET ========= nest.ResetKernel( ) # gets rid of all nodes, customised models and resets internal clock to 0 nest.SetKernelStatus({ 'resolution': self.resolution, 'print_time': False, 'local_num_threads': self.n_threads }) # ====== MAKE NEURON POPULATIONS ========= group_size = int((self.N_total / len(pattern))) SUB_pop = [] SUPRA_pop = [] for i in range(len(pattern)): # parameterise the AdEx neuron model nest.SetDefaults('aeif_cond_exp', self.model_params) if pattern[i] == 1: # create supra population of given group size with the set parameter values n_supra = nest.Create('aeif_cond_exp', group_size) SUPRA_pop.append(n_supra) elif pattern[i] == 0: # create sub population of given group size with the set parameter values n_sub = nest.Create('aeif_cond_exp', group_size) SUB_pop.append(n_sub) # convert to one tuple because NEST likes that neurons_supra = tuple( [item for sublist in SUPRA_pop for item in sublist]) neurons_sub = tuple([item for sublist in SUB_pop for item in sublist]) # combine neurons into one big population (for spikedetector and multimeter) neurons_all = neurons_supra + neurons_sub # ====== CREATE DC GENERATORS + SPIKE DETECT + MULTMETER ========= # create two independent dc generators dcgen_sub = nest.Create('dc_generator', params={ 'amplitude': self.Asub, 'start': self.stim_start, 'stop': self.stim_end }) dcgen_supra = nest.Create('dc_generator', params={ 'amplitude': self.Asupra, 'start': self.stim_start, 'stop': self.stim_end }) # create spikedetector spikedet = nest.Create('spike_detector') # create multimeter that records the voltage multimet = nest.Create( 'multimeter', params={'record_from': ['V_m', 'w', 'g_ex', 'g_in']}) # set status voltage meter with a recording interval nest.SetStatus(multimet, params={'interval': 1.}) # set status spikedetector nest.SetStatus(spikedet, params={"withgid": True, "withtime": True}) # ====== CONNECT NEURONS ========= nest.CopyModel(existing='static_synapse', new='syn_ex', params={ 'weight': self.sim_params['J_ex'], 'delay': self.sim_params['delay'] }) nest.CopyModel(existing='static_synapse', new='syn_in', params={ 'weight': self.sim_params['J_in'], 'delay': self.sim_params['delay'] }) # how we want to connect the neurons conn_rule = {'rule': 'pairwise_bernoulli', 'p': 0.1} # make connections between the two populations nest.Connect(neurons_all[:self.NE], neurons_all, conn_spec=conn_rule, syn_spec='syn_ex') nest.Connect(neurons_all[self.NE:], neurons_all, conn_spec=conn_rule, syn_spec='syn_in') # ====== CONNECT TO DEVICES ========= nest.Connect(neurons_all, spikedet) nest.Connect(multimet, neurons_all) # connect dc_generators to neuron populatioddns nest.Connect(dcgen_sub, neurons_sub) nest.Connect(dcgen_supra, neurons_supra) # ====== SIMULATE ========= # simulate for a certain time period (ms) nest.Simulate(self.simtime) # spike detector data spike_times = nest.GetStatus(spikedet, 'events')[0]['times'] spike_neurons = nest.GetStatus(spikedet, 'events')[0]['senders'] # multimeter data events = nest.GetStatus(multimet)[0]['events'] etimes = events['times'] # volt_neuron_ids = nest.GetStatus(multimet, 'events')[0]['senders'] # voltage_traces = nest.GetStatus(multimet, 'events')[0]['V_m'] # voltage_times = nest.GetStatus(multimet, 'events')[0]['times'] return spikedet, multimet, events, etimes, spike_times, spike_neurons
# already processed simulation time as well as its percentage of the total # simulation time. nest.SetKernelStatus({"resolution": dt, "print_time": True, "overwrite_files": True}) print("Building network") ############################################################################### # Configuration of the model ``iaf_psc_delta`` 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_delta", 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_delta", NE) nodes_in = nest.Create("iaf_psc_delta", NI) noise = nest.Create("poisson_generator") espikes = nest.Create("spike_detector") ispikes = nest.Create("spike_detector") ###############################################################################
mg.set(rate=nu, p_copy=pc) cd = nest.Create('correlation_detector') cd.set(tau_max=tau_max, delta_tau=delta_tau) sd = nest.Create('spike_detector', params={'time_in_steps': True}) pn1 = nest.Create('parrot_neuron') pn2 = nest.Create('parrot_neuron') nest.Connect(mg, pn1) nest.Connect(mg, pn2) nest.Connect(pn1, sd) nest.Connect(pn2, sd) nest.SetDefaults('static_synapse', {'weight': 1.0, 'receptor_type': 0}) nest.Connect(pn1, cd) nest.SetDefaults('static_synapse', {'weight': 1.0, 'receptor_type': 1}) nest.Connect(pn2, cd) nest.Simulate(T) n_events = cd.get('n_events') n1 = n_events[0] n2 = n_events[1] lmbd1 = (n1 / (T - tau_max)) * 1000.0 lmbd2 = (n2 / (T - tau_max)) * 1000.0 h = 0.1
sr = nest.Create('spike_recorder', n_pg) nest.Connect(prrt_nrns_pg, sr, {'rule': 'one_to_one'}) nest.Simulate(pattern_duration) t_srs = [] for i, ssr in enumerate(nest.GetStatus(sr)): t_sr = ssr['events']['times'] t_srs.append(t_sr) nest.ResetKernel() nest.SetKernelStatus({'resolution': resolution}) ''' neuron and devices ''' nest.SetDefaults(nrn_model, nrn_params) nrn = nest.Create(nrn_model) # poisson generators are connected to parrot neurons which are # connected to the mc neuron prrt_nrns = nest.Create('parrot_neuron', n_pg) # excitatory input to the soma spike_times_soma_inp = np.arange(resolution, simulation_time, resolution) sg_soma_exc = nest.Create('spike_generator', params={ 'spike_times': spike_times_soma_inp, 'spike_weights': soma_exc_inp(spike_times_soma_inp) }) # inhibitory input to the soma
def build_network(logger): """Builds the network including setting of simulation and neuron parameters, creation of neurons and connections Requires an instance of Logger as argument """ tic = time.time() # start timer on construction # unpack a few variables for convenience NE = brunel_params['NE'] NI = brunel_params['NI'] model_params = brunel_params['model_params'] stdp_params = brunel_params['stdp_params'] # set global kernel parameters nest.SetKernelStatus({ 'total_num_virtual_procs': params['nvp'], 'resolution': params['dt'], 'overwrite_files': True}) nest.SetDefaults('iaf_psc_alpha', model_params) nest.message(M_INFO, 'build_network', 'Creating excitatory population.') E_neurons = nest.Create('iaf_psc_alpha', NE) nest.message(M_INFO, 'build_network', 'Creating inhibitory population.') I_neurons = nest.Create('iaf_psc_alpha', NI) if brunel_params['randomize_Vm']: nest.message(M_INFO, 'build_network', 'Randomzing membrane potentials.') random_vm = nest.random.normal(brunel_params['mean_potential'], brunel_params['sigma_potential']) nest.GetLocalNodeCollection(E_neurons).V_m = random_vm nest.GetLocalNodeCollection(I_neurons).V_m = random_vm # number of incoming excitatory connections CE = int(1. * NE / params['scale']) # number of incomining inhibitory connections CI = int(1. * NI / params['scale']) nest.message(M_INFO, 'build_network', 'Creating excitatory stimulus generator.') # Convert synapse weight from mV to pA conversion_factor = convert_synapse_weight( model_params['tau_m'], model_params['tau_syn_ex'], model_params['C_m']) JE_pA = conversion_factor * brunel_params['JE'] nu_thresh = model_params['V_th'] / ( CE * model_params['tau_m'] / model_params['C_m'] * JE_pA * np.exp(1.) * tau_syn) nu_ext = nu_thresh * brunel_params['eta'] E_stimulus = nest.Create('poisson_generator', 1, { 'rate': nu_ext * CE * 1000.}) nest.message(M_INFO, 'build_network', 'Creating excitatory spike recorder.') if params['record_spikes']: recorder_label = os.path.join( brunel_params['filestem'], 'alpha_' + str(stdp_params['alpha']) + '_spikes') E_recorder = nest.Create('spike_recorder', params={ 'record_to': 'ascii', 'label': recorder_label }) BuildNodeTime = time.time() - tic logger.log(str(BuildNodeTime) + ' # build_time_nodes') logger.log(str(memory_thisjob()) + ' # virt_mem_after_nodes') tic = time.time() nest.SetDefaults('static_synapse_hpc', {'delay': brunel_params['delay']}) nest.CopyModel('static_synapse_hpc', 'syn_std') nest.CopyModel('static_synapse_hpc', 'syn_ex', {'weight': JE_pA}) nest.CopyModel('static_synapse_hpc', 'syn_in', {'weight': brunel_params['g'] * JE_pA}) stdp_params['weight'] = JE_pA nest.SetDefaults('stdp_pl_synapse_hom_hpc', stdp_params) nest.message(M_INFO, 'build_network', 'Connecting stimulus generators.') # Connect Poisson generator to neuron nest.Connect(E_stimulus, E_neurons, {'rule': 'all_to_all'}, {'synapse_model': 'syn_ex'}) nest.Connect(E_stimulus, I_neurons, {'rule': 'all_to_all'}, {'synapse_model': 'syn_ex'}) nest.message(M_INFO, 'build_network', 'Connecting excitatory -> excitatory population.') nest.Connect(E_neurons, E_neurons, {'rule': 'fixed_indegree', 'indegree': CE, 'allow_autapses': False, 'allow_multapses': True}, {'synapse_model': 'stdp_pl_synapse_hom_hpc'}) nest.message(M_INFO, 'build_network', 'Connecting inhibitory -> excitatory population.') nest.Connect(I_neurons, E_neurons, {'rule': 'fixed_indegree', 'indegree': CI, 'allow_autapses': False, 'allow_multapses': True}, {'synapse_model': 'syn_in'}) nest.message(M_INFO, 'build_network', 'Connecting excitatory -> inhibitory population.') nest.Connect(E_neurons, I_neurons, {'rule': 'fixed_indegree', 'indegree': CE, 'allow_autapses': False, 'allow_multapses': True}, {'synapse_model': 'syn_ex'}) nest.message(M_INFO, 'build_network', 'Connecting inhibitory -> inhibitory population.') nest.Connect(I_neurons, I_neurons, {'rule': 'fixed_indegree', 'indegree': CI, 'allow_autapses': False, 'allow_multapses': True}, {'synapse_model': 'syn_in'}) if params['record_spikes']: if params['nvp'] != 1: local_neurons = nest.GetLocalNodeCollection(E_neurons) # GetLocalNodeCollection returns a stepped composite NodeCollection, which # cannot be sliced. In order to allow slicing it later on, we're creating a # new regular NodeCollection from the plain node IDs. local_neurons = nest.NodeCollection(local_neurons.tolist()) else: local_neurons = E_neurons if len(local_neurons) < brunel_params['Nrec']: nest.message( M_ERROR, 'build_network', """Spikes can only be recorded from local neurons, but the number of local neurons is smaller than the number of neurons spikes should be recorded from. Aborting the simulation!""") exit(1) nest.message(M_INFO, 'build_network', 'Connecting spike recorders.') nest.Connect(local_neurons[:brunel_params['Nrec']], E_recorder, 'all_to_all', 'static_synapse_hpc') # read out time used for building BuildEdgeTime = time.time() - tic logger.log(str(BuildEdgeTime) + ' # build_edge_time') logger.log(str(memory_thisjob()) + ' # virt_mem_after_edges') return E_recorder if params['record_spikes'] else None
def simulate(parameters): # Simulates the network and returns recorded spikes for excitatory # and inhibitory population # Code taken from brunel_alpha_nest.py def LambertWm1(x): # Using scipy to mimic the gsl_sf_lambert_Wm1 function. return sp.lambertw(x, k=-1 if x < 0 else 0).real def ComputePSPnorm(tauMem, CMem, tauSyn): a = (tauMem / tauSyn) b = (1.0 / tauSyn - 1.0 / tauMem) # time of maximum t_max = 1.0 / b * (-LambertWm1(-np.exp(-1.0 / a) / a) - 1.0 / a) # maximum of PSP for current of unit amplitude return (np.exp(1.0) / (tauSyn * CMem * b) * ((np.exp(-t_max / tauMem) - np.exp(-t_max / tauSyn)) / b - t_max * np.exp(-t_max / tauSyn))) # number of excitatory neurons NE = int(parameters['gamma'] * parameters['N']) # number of inhibitory neurons NI = parameters['N'] - NE # number of excitatory synapses per neuron CE = int(parameters['epsilon'] * NE) # number of inhibitory synapses per neuron CI = int(parameters['epsilon'] * NI) tauSyn = 0.5 # synaptic time constant in ms tauMem = 20.0 # time constant of membrane potential in ms CMem = 250.0 # capacitance of membrane in in pF theta = 20.0 # membrane threshold potential in mV neuron_parameters = { 'C_m': CMem, 'tau_m': tauMem, 'tau_syn_ex': tauSyn, 'tau_syn_in': tauSyn, 't_ref': 2.0, 'E_L': 0.0, 'V_reset': 0.0, 'V_m': 0.0, 'V_th': theta } J = 0.1 # postsynaptic amplitude in mV J_unit = ComputePSPnorm(tauMem, CMem, tauSyn) J_ex = J / J_unit # amplitude of excitatory postsynaptic current # amplitude of inhibitory postsynaptic current J_in = -parameters['g'] * J_ex nu_th = (theta * CMem) / (J_ex * CE * np.exp(1) * tauMem * tauSyn) nu_ex = parameters['eta'] * nu_th p_rate = 1000.0 * nu_ex * CE nest.ResetKernel() nest.set_verbosity('M_FATAL') nest.SetKernelStatus({ 'rng_seeds': [parameters['seed']], 'resolution': parameters['dt'] }) nest.SetDefaults('iaf_psc_alpha', neuron_parameters) nest.SetDefaults('poisson_generator', {'rate': p_rate}) 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', params={'label': 'brunel-py-ex'}) ispikes = nest.Create('spike_detector', params={'label': 'brunel-py-in'}) nest.CopyModel('static_synapse', 'excitatory', { 'weight': J_ex, 'delay': parameters['delay'] }) nest.CopyModel('static_synapse', 'inhibitory', { 'weight': J_in, 'delay': parameters['delay'] }) nest.Connect(noise, nodes_ex, syn_spec='excitatory') nest.Connect(noise, nodes_in, syn_spec='excitatory') if parameters['N_rec'] > NE: raise ValueError('Requested recording from {} neurons, \ but only {} in excitatory population'.format( parameters['N_rec'], NE)) if parameters['N_rec'] > NI: raise ValueError('Requested recording from {} neurons, \ but only {} in inhibitory population'.format( parameters['N_rec'], NI)) nest.Connect(nodes_ex[:parameters['N_rec']], espikes) nest.Connect(nodes_in[:parameters['N_rec']], ispikes) conn_parameters_ex = {'rule': 'fixed_indegree', 'indegree': CE} nest.Connect(nodes_ex, nodes_ex + nodes_in, conn_parameters_ex, 'excitatory') conn_parameters_in = {'rule': 'fixed_indegree', 'indegree': CI} nest.Connect(nodes_in, nodes_ex + nodes_in, conn_parameters_in, 'inhibitory') nest.Simulate(parameters['sim_time']) return (espikes.events, ispikes.events)
from nest_values import * from funciones import * ########################################################### Nest ################################################################### nest.ResetKernel() nest.SetKernelStatus({'local_num_threads': local_num_threads}) nest.SetKernelStatus({'print_time': True}) nest.SetKernelStatus({'overwrite_files': True}) nest.SetKernelStatus({"resolution": resolution}) nest.CopyModel("izhikevich", "exc", RS_dict) nest.CopyModel("izhikevich", "inh", FS_dict) nest.SetDefaults("vogels_sprekeler_synapse", stdp_v1_inh_dict) nest.SetDefaults("stdp_synapse", stdp_lgn_exc_dict) ########################################################### Image processing #################################################################### create_folder(gabor_folder) remove_contents(gabor_folder) create_folder(positions_path) remove_contents(positions_path) create_folder(connections_path) remove_contents(connections_path) t = time.time() gabors_to_nest = full_img_filtering(images_to_simulate) gabors_time = time.time() - t
def build_network(order, T=1): NE = int(4 * order) # number of excitatory neurons NI = int(1 * order) # number of inhibitory neurons N = int(NE + NI) # total number of neurons d_e = 5. # delay of excitatory connections in ms g = 5.0 # ratio inhibitory weight/excitatory weight epsilon = 0.1 # connection probability w = 0.1 / numpy.sqrt(N) # excitatory connection strength KE = int(epsilon * NE) # number of excitatory synapses per neuron (outdegree) KI = int(epsilon * NI) # number of inhibitory synapses per neuron (outdegree) K_tot = int(KI + KE) # total number of synapses per neuron connection_rule = 'fixed_outdegree' # connection rule print('number neurons: ', N) print('number synapses per neuron: ', K_tot) neuron_model = 'lin_rate_ipn' # neuron model neuron_params = { 'linear_summation': True, # type of non-linearity (not affecting linear rate models) 'tau': 10.0, # time constant of neuronal dynamics in ms 'mean': 0.0, # mean of Gaussian white noise input 'std': 5. # standard deviation of Gaussian white noise input } nest.ResetKernel() nest.SetKernelStatus({ "resolution": dt, "use_wfr": False, "local_num_threads": T, #"print_time": True, "overwrite_files": True }) nest.SetDefaults(neuron_model, neuron_params) n_e = nest.Create(neuron_model, NE) n_i = nest.Create(neuron_model, NI) mm = nest.Create('multimeter', params={ 'record_from': ['rate'], 'interval': dt }) syn_e = {'weight': w, 'delay': d_e, 'model': 'rate_connection_delayed'} syn_i = {'weight': -g * w, 'model': 'rate_connection_instantaneous'} conn_e = {'rule': connection_rule, 'outdegree': KE} conn_i = {'rule': connection_rule, 'outdegree': KI} nest.Connect(n_e, n_e, conn_e, syn_e) nest.Connect(n_i, n_i, conn_i, syn_i) nest.Connect(n_e, n_i, conn_i, syn_e) nest.Connect(n_i, n_e, conn_e, syn_i) nest.Connect(mm, n_e + n_i) return n_e, n_i, mm
def setup_stdp(): global eN, eP, eP1, cD, sD, stdp_params global dt global espikes nest.ResetKernel() nest.SetKernelStatus({'resolution':dt, 'overwrite_files': True}) [eN]= nest.Create('iaf_cond_exp_sfa_rr',1) # set neuron model params eParams = {'V_th':-57.0, 'V_reset': -70.0, 't_ref': 0.5, 'g_L':28.95, 'C_m':289.5, 'E_L' : -70.0, 'E_ex': 0.0, 'E_in': -75.0, 'tau_syn_ex':1.5, 'tau_syn_in': 10.0, 'E_sfa': -70.0, 'q_sfa':14.48, 'tau_sfa':110.0, 'E_rr': -70.0, 'q_rr': 3214.0, 'tau_rr': 1.97,'tau_minus':33.7,'tau_minus_triplet':110.0} nest.SetStatus([eN],eParams) # spike generator input [eP,eP1] = nest.Create('spike_generator',2) nest.SetStatus([eP], {'spike_times':numpy.array([50.0])}) # static synapse to stimulate neuron to spike nest.Connect([eP],[eN],100.0,dt, model='static_synapse') # hippocampus ee_synParams = {'tau_plus':16.8,'tau_x':946.0, 'A_2p':6.1e-3,'A_3p':6.7e-3, 'A_2m':1.6e-3/2.0,'A_3m':1.4e-3/2.0} neuron_stdpParams = {'tau_minus':33.7,'tau_minus_triplet':125.0} # cortex #ee_synParams = {'tau_plus':16.8,'tau_x':100.0, # 'A_2p':0.0,'A_3p':6.2e-3, # 'A_2m':7.0e-3,'A_3m':2.3e-4} #nest.SetStatus([eN],{'tau_minus':33.7,'tau_minus_triplet':27.0}) ee_synParams['weight'] = 2.0 ee_synParams['delay'] = dt nest.SetDefaults('stdp_triplet_synapse_S',ee_synParams) nest.SetStatus([eN],neuron_stdpParams) # save STDP params in a global dictionary for the analytical calculations stdp_params.update(ee_synParams) stdp_params.update(neuron_stdpParams) # finally, make the stdp_triplet connection nest.Connect([eP1],[eN], model='stdp_triplet_synapse_S') # measure voltage in the neuron [cD] = nest.Create('voltmeter',1) nest.SetStatus([cD],[{"to_file": True, "withtime": True}]) nest.Connect([cD],[eN], model='stdp_triplet_synapse_S') # spike detector [sD] = nest.Create('spike_detector',1) # nest.SetStatus([sD],{'record_events':True}) nest.Connect([eN],[sD], model='static_synapse')