Esempio n. 1
0
 def _randomDivergentConnectII(self,
                               pre,
                               post,
                               n,
                               weights,
                               allow_autapses=False,
                               allow_multapses=False):
     '''Connect each neuron in ``pre`` (I population) to n randomly selected
     neurons in ``post`` (I population), with weights specified in
     ``weights``. If weights is a float then all the weights are constant.
     '''
     if isinstance(weights, collections.Iterable):
         delay = [self.no.delay] * len(weights)
     else:
         delay = self.no.delay
     nest.RandomDivergentConnect(
         (self.I_pop[0] + np.asanyarray(pre)).tolist(),
         (self.I_pop[0] + np.asanyarray(post)).tolist(),
         n,
         weight=weights,
         model='E_GABA_A',
         delay=delay,
         options={
             'allow_autapses': allow_autapses,
             'allow_multapses': allow_multapses
         })
    def test_ConvergentDivergentConnectOptions(self):
        """Convergent/DivergentConnect with non-standard options and
        ensure that the option settings are properly restored before
        returning."""

        nest.ResetKernel()

        copts = nest.sli_func('GetOptions',
                              '/RandomConvergentConnect',
                              litconv=True)
        dopts = nest.sli_func('GetOptions',
                              '/RandomDivergentConnect',
                              litconv=True)

        ncopts = dict(
            (k, not v) for k, v in copts.items() if k != 'DefaultOptions')
        ndopts = dict(
            (k, not v) for k, v in dopts.items() if k != 'DefaultOptions')

        n = nest.Create('iaf_neuron', 3)

        nest.RandomConvergentConnect(n, n, 1, options=ncopts)
        nest.RandomDivergentConnect(n, n, 1, options=ndopts)

        opts = nest.sli_func('GetOptions',
                             '/RandomConvergentConnect',
                             litconv=True)
        self.assertEqual(copts, opts)

        opts = nest.sli_func('GetOptions',
                             '/RandomDivergentConnect',
                             litconv=True)
        self.assertEqual(dopts, opts)
Esempio n. 3
0
    def test_ConnectOptions(self):
        """ConnectOptions"""

        nest.ResetKernel()

        copts = nest.sli_func('GetOptions',
                              '/RandomConvergentConnect',
                              litconv=True)
        dopts = nest.sli_func('GetOptions',
                              '/RandomDivergentConnect',
                              litconv=True)

        ncopts = dict([(k, not v) for k, v in copts.iteritems()
                       if k != 'DefaultOptions'])
        ndopts = dict([(k, not v) for k, v in dopts.iteritems()
                       if k != 'DefaultOptions'])

        n = nest.Create('iaf_neuron', 3)

        nest.RandomConvergentConnect(n, n, 1, options=ncopts)
        nest.RandomDivergentConnect(n, n, 1, options=ndopts)

        self.assertEqual(
            copts,
            nest.sli_func('GetOptions',
                          '/RandomConvergentConnect',
                          litconv=True))
        self.assertEqual(
            dopts,
            nest.sli_func('GetOptions',
                          '/RandomDivergentConnect',
                          litconv=True))
    def _connect(self):
        '''Connect populations.'''

        if self._fan == 'in':
            nest.RandomConvergentConnect(self._source_pop,
                                         self._target_pop,
                                         self._C,
                                         options={'allow_multapses': True})
        elif self._fan == 'out':
            nest.RandomDivergentConnect(self._source_pop,
                                        self._target_pop,
                                        self._C,
                                        options={'allow_multapses': True})
Esempio n. 5
0
 def _randomDivergentConnectEI(self, pre, post, n, weights):
     '''Connect each neuron in ``pre`` (E population) to n randomly selected
     neurons in ``post`` (I population), with weights specified in
     ``weights``. If weights is a float then all the weights are constant.
     '''
     if isinstance(weights, collections.Iterable):
         delay = [self.no.delay] * len(weights)
     else:
         delay = self.no.delay
     nest.RandomDivergentConnect(
         (self.E_pop[0] + np.asanyarray(pre)).tolist(),
         (self.I_pop[0] + np.asanyarray(post)).tolist(),
         n,
         weight=weights,
         model='I_AMPA_NMDA',
         delay=delay)
    def __init__(self, prefix, new_pars=[], pars_file=[]):
        '''Creates and simulates a network in NEST'''

        #Temporary way to run without the selected pars file
        pars_file = []
        start_build_net = time.time()

        if pars_file == []:  # import generic params_d file
            import params_d_hysterisis
            reload(params_d_hysterisis)
            pars = params_d_hysterisis.Parameters(new_pars)
        else:  # import specific params_d file
            fobj, pathname, description = imp.find_module(pars_file)
            params_d_sp = imp.load_module(pars_file, fobj, pathname,
                                          description)
            pars = params_d_sp.Parameters(new_pars)

        self.T_sim = pars.T_sim + pars.T_wup + pars.T_cdown
        #self.record_spikes = pars.record_spikes
        self.record_vm = pars.record_vm
        self.recorders = {}
        self.events = {'spikes': [], 'vm': []}
        self.pars = pars
        self.pars.prefix = prefix

        # INITIALIZE NETWORK -----------------------------------------------------------------------
        nest_path_tmp = tempfile.mktemp(prefix=pars.nest_path_tmp)
        os.mkdir(nest_path_tmp)
        nest.ResetKernel()
        shutil.rmtree(nest.GetStatus([0], 'data_path')[0], ignore_errors=True)
        nest.SetStatus(
            [0], {
                'resolution': pars.dt,
                'print_time': pars.print_time,
                'overwrite_files': pars.owr_files,
                'rng_seeds': [int(pars.rnd_seeds)],
                'data_path': nest_path_tmp
            })

        print '\nBuilding network...'

        # CREATE SOURCES ----------------------------------------------------------------------------
        self.pg_exc = nest.Create('poisson_generator', 1)
        self.pg_inh = nest.Create('poisson_generator', 1)
        nest.SetStatus(self.pg_exc, {
            'rate': pars.pg_rate_exc,
            'stop': pars.T_sim + pars.T_wup
        })
        nest.SetStatus(self.pg_inh, {
            'rate': pars.pg_rate_inh,
            'stop': pars.T_sim + pars.T_wup
        })

        self.dc1_exc = nest.Create('dc_generator', 1)
        nest.SetStatus(self.dc1_exc, pars.dc1_pars)

        self.dc2_exc = nest.Create('dc_generator', 1)
        nest.SetStatus(self.dc2_exc, pars.dc2_pars)

        # CREATE POPULATIONS -----------------------------------------------------------------------
        print 'Creating populations...\n'

        neurons = []
        self.pops = range(len(pars.N))
        for ii, nr in enumerate(pars.N):
            self.pops[ii] = nest.Create(pars.model_type, abs(nr))
            neurons.extend(self.pops[ii])

#  set neuron parameters	for every population independently
        for ntypes in range(len(pars.N)):
            nest.SetStatus(self.pops[ntypes], pars.neuron_params[ntypes])

        if pars.rnd_dist:
            nest.SetStatus(neurons, 'tau_m', pars.tau_m_rnd)

# Make connections -------------------------------------------------------------------------
        self.exc_pop = self.pops[0]

        #Create AC generator
        self.shu_gen = nest.Create('poisson_generator',
                                   params={
                                       'rate': self.pars.shu_input,
                                       'start': pars.st_val,
                                       'stop': pars.st_val + 7 * pars.shu_width
                                   })

        J_exc = pars.J_exc

        J_inh = pars.J_inh

        total_neu = [item for sublist in self.pops for item in sublist]

        nest.DivergentConnect(self.pg_exc,
                              self.exc_pop,
                              weight=pars.J_exc,
                              delay=pars.min_del)
        for pop in self.pops[1:]:
            nest.DivergentConnect(self.pg_inh,
                                  pop,
                                  weight=pars.J_exc,
                                  delay=pars.min_del)

        for pop2 in self.pops:
            self.n_exc = int(pars.epsilon * len(pop2))
            nest.RandomDivergentConnect(self.exc_pop,
                                        pop2,
                                        self.n_exc,
                                        weight=J_exc,
                                        delay=pars.delay)

        for pop3 in self.pops:
            self.n_inh = int(pars.epsilon * len(pop3))
            nest.RandomDivergentConnect(self.pops[1],
                                        pop3,
                                        self.n_inh,
                                        weight=J_inh,
                                        delay=pars.delay)
            if len(self.pops) > 2:
                nest.RandomDivergentConnect(self.pops[2],
                                            pop3,
                                            self.n_inh,
                                            weight=J_inh,
                                            delay=pars.delay)

#CREATE RECORDERS----------------------------------------------------------------------------
        self.record_spikes = list(
            np.arange(self.pops[0][0], self.pops[-1][-1] + 1))
        #if self.record_spikes!= []:
        sd = nest.Create('spike_detector', 1)
        nest.SetStatus(sd, {'to_file': True, 'to_memory': True})
        nest.ConvergentConnect(self.record_spikes, sd)
        self.recorders['sd'] = sd

        if self.pars.record_vm != []:
            vm = nest.Create('voltmeter', 1)
            print 'Id of vm recorder: ', vm
            nest.SetStatus(
                vm, {
                    'withtime': True,
                    'withgid': True,
                    'to_file': True,
                    'to_memory': False
                })
            nest.DivergentConnect(vm, self.pars.record_vm)
            nest.SetStatus(self.pars.record_vm,
                           {'V_th': 1000.})  # record free Vm
            self.recorders['vm'] = vm

        self.build_net_time = time.time() - start_build_net
Esempio n. 7
0
    def __init__(self,prefix,new_pars=[],pars_file=[]):
        '''Creates and simulates a network in NEST'''
        
        #Temporary way to run without the selected pars file
        pars_file = []
        start_build_net = time.time()
        
        if pars_file==[]:	# import generic params_d file
	    import params_d_psdb
	    reload(params_d_psdb)
	    pars = params_d_psdb.Parameters(new_pars)		
	else: 			# import specific params_d file
	    fobj,pathname,description = imp.find_module(pars_file)
	    params_d_sp = imp.load_module(pars_file,fobj,pathname,description)
	    pars = params_d_sp.Parameters(new_pars)

	
	self.T_sim = pars.T_sim + pars.T_wup + pars.T_cdown
	#self.record_spikes = pars.record_spikes
	self.record_vm = pars.record_vm
	self.recorders = {}
	self.events = {'spikes':[],'vm':[]}	
	self.pars = pars
	self.pars.prefix = prefix	
	
	# INITIALIZE NETWORK -----------------------------------------------------------------------	        
        nest_path_tmp = tempfile.mktemp(prefix=pars.nest_path_tmp)
        os.mkdir(nest_path_tmp)
        nest.ResetKernel()
        shutil.rmtree(nest.GetStatus([0],'data_path')[0],ignore_errors=True)
        nest.SetStatus([0], {'resolution': pars.dt, 'print_time': pars.print_time,
        'overwrite_files':pars.owr_files, 'rng_seeds':[int(pars.rnd_seeds)],
        'data_path':nest_path_tmp})
        
        #print '\nBuilding network...'
        
        # CREATE SOURCES ----------------------------------------------------------------------------
        self.pg_exc = nest.Create('poisson_generator', 1)
        self.pg_inh = nest.Create('poisson_generator', 1)
        nest.SetStatus(self.pg_exc, {'rate': pars.pg_rate_exc, 'stop': pars.T_sim+pars.T_wup})
        nest.SetStatus(self.pg_inh, {'rate': pars.pg_rate_inh, 'stop': pars.T_sim+pars.T_wup})
                
        self.dc1_exc = nest.Create('dc_generator',1)
        nest.SetStatus(self.dc1_exc, pars.dc1_pars)
        
        self.dc2_exc = nest.Create('dc_generator',1)
        nest.SetStatus(self.dc2_exc, pars.dc2_pars)
        
         # CREATE POPULATIONS -----------------------------------------------------------------------
	#print 'Creating populations...\n'
	
	
	neurons_exc = []
	self.pops_exc = range(len(pars.N_exc))
	for ii,nr in enumerate(pars.N_exc):
	  self.pops_exc[ii] = nest.Create(pars.model_type, abs(nr))
	  neurons_exc.extend(self.pops_exc[ii])
	  
	#  set neuron parameters	for every population independently              
	for ntypes in range(len(pars.N_exc)):
	  nest.SetStatus(self.pops_exc[ntypes], pars.neuron_params_exc[ntypes])
	  
	
	if pars.rnd_dist:
	  nest.SetStatus(neurons_inh,'tau_m',pars.tau_m_rnd)
	  
	neurons_inh = []
	self.pops_inh = range(len(pars.N_inh))
	for ii,nr in enumerate(pars.N_inh):
	  self.pops_inh[ii] = nest.Create(pars.model_type, abs(nr))
	  neurons_inh.extend(self.pops_inh[ii])
	  
	#  set neuron parameters	for every population independently              
	for ntypes in range(len(pars.N_inh)):
	  nest.SetStatus(self.pops_inh[ntypes], pars.neuron_params_inh[ntypes])
	  
	
	if pars.rnd_dist:
	  nest.SetStatus(neurons_inh,'tau_m',pars.tau_m_rnd)
	  

	if pars.change_type:
	  self.time_lis = [pars.chg_time,pars.T_sim]
	  
	  
	self.pops = self.pops_exc + self.pops_inh
	
	self.pops_exc = [item for sublist in self.pops_exc for item in sublist]
	self.pops_inh = [item for sublist in self.pops_inh for item in sublist]
	    
	 # Make connections -------------------------------------------------------------------------
	#total_neu = [item for sublist in self.pops for item in sublist]
	self.pars.neurons_tot = len(self.pops_exc) + len(self.pops_inh) 

	self.pars.pops_exc = self.pops_exc
	self.pars.pops_inh = self.pops_inh
	
	nest.SetStatus(self.pops_exc, params = {'tau_m':pars.tau_m_exc,'C_m':pars.C_m_exc,'tau_syn':pars.tau_syn_ex})
	
	nest.DivergentConnect(self.pg_exc, self.pops_exc, weight = pars.J_ext, delay = pars.min_del)
 
	nest.DivergentConnect(self.pg_inh, self.pops_inh, weight = pars.J_ext, delay = pars.min_del)

         #STN connections
	num_stn_gpe = int(pars.epsilon_stn_gpe * len(self.pops_inh))
	nest.RandomDivergentConnect(self.pops_exc,self.pops_inh, num_stn_gpe, weight = pars.J_stn_gpe, delay = pars.delay_inter) 
	num_stn_stn = int(pars.epsilon_stn_stn* len(self.pops_exc))
	nest.RandomDivergentConnect(self.pops_exc,self.pops_exc, num_stn_stn, weight = pars.J_stn_stn, delay = pars.delay_intra) 

	#GPE connections
	num_gpe_gpe = int(pars.epsilon_gpe_gpe * len(self.pops_inh))
	nest.RandomDivergentConnect(self.pops_inh,self.pops_inh, num_gpe_gpe, weight = pars.J_gpe_gpe, delay = pars.delay_intra) 
	num_gpe_stn = int(pars.epsilon_gpe_stn* len(self.pops_exc))
	nest.RandomDivergentConnect(self.pops_inh,self.pops_exc, num_gpe_stn, weight = pars.J_gpe_stn, delay = pars.delay_inter)

	if pars.add_spikes == 1:
	    extra_spike = nest.Create('spike_generator',int(pars.num_gen))
	    def spike_times():
	      spt = np.random.uniform(pars.st_val+pars.beg_width,pars.st_val + pars.ex_width,1)
	      spike_times = (np.sort(np.random.uniform(spt,spt + pars.dur ,pars.num_spk))).tolist()     
	      return spike_times
	    

	    for ii in extra_spike:
	      spike_time = spike_times()
	      spike_time = np.around(spike_time,1)
	      nest.SetStatus([ii],params = {'spike_times':(np.array(spike_time)).flatten()})
	    
	    if self.pars.extra_spk == 'exc':
	      nest.RandomDivergentConnect(extra_spike,self.pops_inh,int(len(self.pops_inh)*pars.epsilon_stn_gpe),weight = pars.J_stn_gpe, delay = pars.delay_inter)
	      nest.RandomDivergentConnect(extra_spike,self.pops_exc,int(len(self.pops_exc)*pars.epsilon_stn_stn),weight = pars.J_stn_stn, delay = pars.delay_intra)
	    elif self.pars.extra_spk == 'inh':
	      nest.RandomDivergentConnect(extra_spike,self.pops_inh,int(len(self.pops_inh)*pars.epsilon_stn_gpe),weight = pars.J_gpe_stn, delay = pars.delay_inter)
	      nest.RandomDivergentConnect(extra_spike,self.pops_exc,int(len(self.pops_exc)*pars.epsilon_stn_stn),weight = pars.J_gpe_gpe, delay = pars.delay_intra)
 
	
	
#	pops_ch = self.pops_exc + self.pops_inh 
#	pops_ch = self.pops_exc + self.pops_inh 
#	pops_rd = random.sample(pops_ch,500)
	#CREATE RECORDERS----------------------------------------------------------------------------
	self.record_spikes = list(np.arange(self.pops_exc[0],self.pops_inh[-1]+1))
	#self.record_spikes_new = random.sample(self.record_spikes,1000) 
#	self.record_spikes = pops_rd
	#if self.record_spikes!= []:
	sd = nest.Create('spike_detector',1)
	nest.SetStatus(sd,{'to_file':True,'to_memory':True})
	nest.ConvergentConnect(self.record_spikes,sd)
	self.recorders['sd'] = sd
	
	
	if self.pars.record_vm != []:
	    vm = nest.Create('voltmeter',1)
	    #print 'Id of vm recorder: ',vm
	    nest.SetStatus(vm,{'withtime':True,'withgid':True,'to_file':True,'to_memory':False})
	    nest.DivergentConnect(vm,self.pars.record_vm)
	    nest.SetStatus(self.pars.record_vm,{'V_th':1000.}) # record free Vm
	    self.recorders['vm'] = vm
	    
	self.build_net_time = time.time()-start_build_net
Esempio n. 8
0
def RCC(pre,
        post,
        n,
        params={
            'd_mu': [],
            'w_mu': [],
            'd_rel_std': 0.0,
            'w_rel_std': 0.0
        },
        model='static_synapse'):
    '''
    As NEST RandomDivergentConnect, except it can take severals models and 
    make same connections for both models. This can be used to connect same
    source with  target with both AMPA and NMDA.Mean and standard deviation 
    for delays and weights can be given. Mean as a list of values one for 
    each model and standard deviation as single values applied to all 
    synapse models.
     
    Inputs:
        pre                      - list of source ids       
        post                     - list of target ids  
        n                        - number of neurons each source neuron connects to
        params[ 'd_mu' ]         - mean delay for each model
        params[ 'w_mu' ]            - mean weight for each model
        params[ 'd_rel_std' ]    - relative mean standard deviation delays
        params[ 'w_rel_std' ]    - relative mean standard deviation weights
        model                    - synapse model, can be a list of models
    '''

    rn = rand.normal  # copy function for generation of normal distributed random numbers

    for key, val in params.iteritems():
        exec '%s = %s' % (key, str(val)
                          )  # params dictionary entries as variables

    if isinstance(model, str):
        model = [model]  # if model is a string put into a list

    if not d_mu:
        d_mu = [nest.GetDefaults(m)['delay']
                for m in model]  # get mean delays d_mu
    d_sigma = [d_rel_std * mu for mu in d_mu]  # get delay standard deviation

    if not w_mu:
        w_mu = [nest.GetDefaults(m)['weight']
                for m in model]  # get mean weights w_mu
    w_sigma = [w_rel_std * mu for mu in w_mu]  # get weight standard deviation

    delays = [
        rand.normal(
            mu, sigma,
            [len(pre), n])  # calculate delays, randomized if sigma != 0
        if sigma else numpy.ones((len(pre), n)) * mu
        for mu, sigma in zip(d_mu, d_sigma)
    ]

    weights = [
        rand.normal(
            mu, sigma,
            [len(pre), n])  # calculate weights, randomized if sigma != 0
        if sigma else numpy.ones((len(pre), n)) * mu
        for mu, sigma in zip(w_mu, w_sigma)
    ]

    for i, pre_id in enumerate(pre):
        j = 0

        if d_sigma[j]:
            d = rn(d_mu[j], d_sigma[j],
                   [1, n])[0]  # if sigma len( targets ) randomized delays
        else:
            d = numpy.ones((1, n))[0] * d_mu[j]  # else no randomized delays

        if w_sigma[j]:
            w = rn(w_mu[j], w_sigma[j],
                   [1, n])[0]  # if signa len( targets ) randomized weights
        else:
            w = numpy.ones((1, n))[0] * w_mu[j]  # else no randomized weights

        d, w = list(d), list(w)  # as lists
        nest.RandomDivergentConnect(
            [pre_id],
            post,
            n,
            weight=w,  # connect with model[0]
            delay=d,
            model=model[0])

        if len(model) > 1:
            targets = [
                conn['target']
                for conn in  # find connections made by RandomDivergentConnect 
                nest.GetStatus(nest.FindConnections([pre_id]))
                if conn['synapse_type'] == model[0]
            ]
            nt = len(targets)

            for j, m in enumerate(
                    model[1:],
                    start=1):  # pre -> post with model[1], model[2] etc
                if d_sigma[j]:
                    d = rn(d_mu[j], d_sigma[j],
                           [1, nt
                            ])[0]  # if sigma len( targets ) randomized delays
                else:
                    d = numpy.ones(
                        (1, nt))[0] * d_mu[j]  # else no randomized delays

                if w_sigma[j]:
                    w = rn(w_mu[j], w_sigma[j],
                           [1, nt
                            ])[0]  # if signa len( targets ) randomized delays
                else:
                    w = numpy.ones((1, nt))[0] * w_mu[j]  # else not

                d, w = list(d), list(w)
                nest.ConvergentConnect([pre_id],
                                       targets,
                                       weight=w,
                                       delay=d,
                                       model=m)