Ejemplo n.º 1
0
    def __init__(self, name, **kwargs):
        ''' 
        Constructor 
        
        Inherited attributes:
        self.t_start        = float(t_start)
        self.t_stop         = t_stop
        self.dt             = float(dt)
        self.dimensions     = dims
        self.analog_signals = {}
        
        New attributes:
        self.ids = sorted( id_list )     # sorted id list
        
        '''

        model = kwargs.get('model', 'poisson_generator')

        df = my_nest.GetDefaults(model)
        if df['type_id'] in [
                'spike_generator', 'mip_generator', 'poisson_generator',
                'poisson_generator_dynamic', 'my_poisson_generator'
        ]:
            input_model = model
            type_model = df['type_id']
            kwargs['model'] = 'parrot_neuron'

        super(MyPoissonInput, self).__init__(name, **kwargs)

        self._init_extra_attributes(input_model, type_model, **kwargs)

        if self.spike_setup != []:
            for k in self.spike_setup:
                self.set_spike_times(**k)
Ejemplo n.º 2
0
def sim_group(sim_time, *args, **kwargs):

    g = MyNetworkNode(*args, **kwargs)

    df = my_nest.GetDefaults('my_aeif_cond_exp')['receptor_types']

    inp_ex = my_nest.Create('poisson_generator', params={'rate': 30.})
    inp_ih = my_nest.Create('poisson_generator', params={'rate': 30.})

    for pre in inp_ex:
        for post in inp_ih:
            my_nest.Connect(pre, post, {'receptor_type': df['g_AMPA_1']})
    for pre in inp_ex:
        for post in inp_ih:
            my_nest.Connect(pre, post, {'receptor_type': df['g_GABAA_1']})

    my_nest.Simulate(sim_time)
    return g
Ejemplo n.º 3
0
    def _init_extra_attributes(self, *args, **kwargs):
        # Add new attribute

        #         self.sd_params=kwargs.get('sd_parans')
        self.mm = self.create_mm(self.name, kwargs.get('mm', {}))

        self.rand = kwargs.get('rand', {})

        self.receptor_types = my_nest.GetDefaults(self.model).get(
            'receptor_types', {})
        self.sd = self.create_sd(self.name, kwargs.get('sd', {}))

        self.signals = {
        }  # dictionary with signals for current, conductance, voltage or spikes
        self._signaled = {
        }  # for ech signal indicates if it have been loaded from nest or not
        self.target_rate = kwargs.get('rate', 10.0)

        if not {} == self.rand:
            self.model_par_randomize()
Ejemplo n.º 4
0
    def mean_weights(self):
        '''
        Return a dictionary with mean_weights for each synapse type with mean weight
        and receptor type
        '''

        print 'Calculating mean weights', self.models

        syn_dict = {}  # container weights per synapse type
        rev_rt = {}  # receptor type number dictionary
        rt_nb = []  # receptor type numbers

        for source in self.ids:  # retrieve all weights per synapse type
            for conn in my_nest.GetStatus(my_nest.FindConnections([source])):
                st = conn['synapse_type']

                if syn_dict.has_key(st):
                    syn_dict[st]['weights'].append(conn['weight'])
                else:
                    syn_dict[st] = {}
                    syn_dict[st]['weights'] = [conn['weight']]
                    syn_dict[st]['receptor_type'] = {
                        st: my_nest.GetDefaults(st)['receptor_type']
                    }

        mw = {}  # container mean weights per synapse type
        for key, val in syn_dict.iteritems():
            if len(val['weights']) > 0:
                syn_dict[key]['mean_weight'] = sum(val['weights']) / len(
                    val['weights'])  # calculate mean weight
                syn_dict[key]['weights'] = numpy.array(
                    syn_dict[key]['weights'])
                syn_dict[key]['nb_conn'] = len(val['weights'])
            else:
                syn_dict[key]['mean_weight'] = 0
                syn_dict[key]['nb_conn'] = 0

        return syn_dict
Ejemplo n.º 5
0
    def set_spike_times(self,
                        rates=[],
                        times=[],
                        t_stop=None,
                        ids=None,
                        seed=None,
                        idx=None):

        df = my_nest.GetDefaults(self.model)

        if ids is None and (not idx is None):
            tmp_ids = numpy.array(self.ids)
            ids = list(tmp_ids[idx])
        if ids is None:
            ids = self.ids

        #print df.keys()
        #print df['model']
        # Spike generator
        if 'spike_generator' == df['model']:

            for id in ids:
                seed = random_integers(0, 10**5)

                spikeTimes = misc.inh_poisson_spikes(rates,
                                                     times,
                                                     t_stop=t_stop,
                                                     n_rep=1,
                                                     seed=seed)
                if any(spikeTimes):
                    rs = my_nest.GetKernelStatus('resolution')
                    n_dec = int(-numpy.log10(rs))
                    spikeTimes = numpy.round(spikeTimes, n_dec)
                    my_nest.SetStatus([id], params={'spike_times': spikeTimes})

        # MIP
        elif 'mip_generator' == df['model']:
            c = df['p_copy']

            seed = random_integers(0, 10**6)
            new_ids = []
            t_starts = times
            t_stops = times[1:] + [t_stop]
            for id in ids:
                i = 0
                for r, start, stop in rates, t_starts, t_stops:
                    r_mother = r / c
                    params = {
                        'rate': r_mother,
                        'start': start,
                        'stop': stop,
                        'p_copy': c,
                        'mother_seed': seed
                    }
                    if i == 0:
                        nest.SetStatus(id, params)
                    else:
                        new_id = my_nest.Create('mip_generator', 1, params)

                    new_ids.append(new_id)
            self.ids.append(new_ids)

        # Poisson generator
        elif 'poisson_generator' == df['model']:

            t_starts = times
            t_stops = list(times[1:]) + list([t_stop])
            for i in range(len(ids)):

                id = ids[i]
                model = my_nest.GetStatus([id], 'model')[0]

                if model == 'parrot_neuron':
                    j = 1
                else:
                    ids[i] = my_nest.Create('parrot_neuron')[0]
                    my_nest.Connect([id], [ids[i]])
                    #self.ids_mul_visited[id]=True
                    j = 0
                for r, start, stop in zip(rates, t_starts, t_stops):
                    params = {'rate': r, 'start': start, 'stop': stop}
                    if j == 0:
                        #print my_nest.GetStatus([id])
                        my_nest.SetStatus([id], params)
                    else:
                        if params['rate'] != 0:
                            #print params
                            new_id = my_nest.Create('poisson_generator', 1,
                                                    params)
                            #self.ids_mul[ids[i]].append(new_id[0])
                            my_nest.Connect(new_id, [ids[i]])
                    j += 1

            if not idx is None:
                tmp_ids = numpy.array(self.ids)
                tmp_ids[idx] = list(ids)
                self.ids = list(tmp_ids)
            else:
                self.ids = list(ids)

            self.local_ids = list(self.ids)  # Nedd to put on locals also
Ejemplo n.º 6
0
    def __init__(self,
                 model='iaf_neuron',
                 n=1,
                 params={},
                 mm_dt=1.0,
                 sname='',
                 spath='',
                 sname_nb=0,
                 sd=False,
                 sd_params={},
                 mm=False,
                 record_from=[],
                 ids=[]):
        '''
        Constructor
        
        Arguments:
            ids         provide ids if nodes already created
            model       my_nest model type, can be a list
            n           number of model to create, can be a list
            params      common parameters for model to be set
            mm_dt       multimeter recording precision
            sname       file basename
            spath       Path to save file at 
            sd          boolean, True if spikes should me recorded
            mm          boolean, True if mulitmeter should record  
        '''

        self.connections = {
        }  # Set after network has been built with FindConnections
        self.ids = []
        self.local_ids = []
        self.mm = []  # Id of multimeter
        self.mm_dt = 0  # Recording interval multimeter
        self.model = model
        self.params = []
        self.record_from = []
        self.receptor_types = {}
        self.recordables = {}
        self.sd = []  # Id of spike detector
        self.sd_params = sd_params
        self.sname_nb = sname_nb  # number for sname string
        self.sname = ''  # Specific file basename
        self.spath = ''  # Path to save file at
        self.signals = {
        }  # dictionary with signals for current, conductance, voltage or spikes

        if not self.sname:
            self.sname = model + '-' + str(sname_nb) + '-'
        else:
            self.sname = self.snam + '-' + str(sname_nb) + '-'

        # If no spath is provided current path plus data_tmp is set to
        # spath.
        if spath is '':
            self.spath = os.getcwd() + '/output_tmp'
        else:
            self.spath = spath

        # Create save dir if it do not exist
        try:
            msg = os.system('mkdir ' + self.spath + ' 2>/dev/null')
        except:
            pass

        if ids:
            self.ids = ids
        else:
            self.ids = my_nest.Create(model, n, params)  # Create models

        # Get local ids on this processor. Necessary to have for mpi run.
        for id in self.ids:
            nodetype = my_nest.GetStatus([id])[0]['model']
            if nodetype != 'proxynode':
                self.local_ids.append(id)

        self.params = my_nest.GetStatus(self.ids)

        # Pick out recordables and receptor types using first model.
        try:
            self.recordables = my_nest.GetDefaults(model)['recordables']
        except:
            pass
        try:
            self.receptor_types = my_nest.GetDefaults(model)['receptor_types']
        except:
            pass

        if self.recordables:
            if any(record_from):
                self.record_from = record_from
            else:
                self.record_from = self.recordables

        # Add spike detector
        if sd:
            self.sd = my_nest.Create("spike_detector")
            self.sd_params.update({"withgid": True})
            my_nest.SetStatus(self.sd, self.sd_params)
            my_nest.ConvergentConnect(self.ids, self.sd)

        # Record with multimeter from first neuron

        if mm:
            self.mm = my_nest.Create("multimeter")
            self.mm_dt = mm_dt  # Recording interval
            my_nest.SetStatus(self.mm, {
                'interval': self.mm_dt,
                'record_from': self.record_from
            })
            my_nest.DivergentConnect(self.mm, self.ids)
Ejemplo n.º 7
0
    def set_spike_times(self,
                        rates=[],
                        times=[],
                        t_stop=None,
                        ids=None,
                        seed=None,
                        idx=None):

        df = my_nest.GetDefaults(self.input_model)['model']

        if ids is None and (not idx is None):
            tmp_ids = numpy.array(self.ids)
            ids = list(tmp_ids[idx])
        if ids is None:
            ids = self.ids

        # Spike generator
        if 'spike_generator' == self.type_model:
            for id in ids:
                seed = random_integers(0, 10**5)

                spikeTimes = misc.inh_poisson_spikes(rates,
                                                     times,
                                                     t_stop=t_stop,
                                                     n_rep=1,
                                                     seed=seed)
                if any(spikeTimes):
                    my_nest.SetStatus([id], params={'spike_times': spikeTimes})

        # MIP
        elif 'mip_generator' == self.type_model:
            c = df['p_copy']

            seed = random_integers(0, 10**6)
            new_ids = []
            t_starts = times
            t_stops = times[1:] + [t_stop]
            for id in ids:
                i = 0
                for r, start, stop in rates, t_starts, t_stops:
                    r_mother = r / c
                    params = {
                        'rate': r_mother,
                        'start': start,
                        'stop': stop,
                        'p_copy': c,
                        'mother_seed': seed
                    }
                    if i == 0:
                        my_nest.SetStatus(id, params)
                    else:
                        new_id = my_nest.Create('mip_generator', 1, params)

                    new_ids.append(new_id)
            self.ids.append(new_ids)

        # Poisson generator
        elif self.type_model in ['my_poisson_generator', 'poisson_generator']:

            t_starts = times
            t_stops = list(times[1:]) + list([t_stop])

            params = [{
                'rate': v[0],
                'start': v[1],
                'stop': v[2]
            } for v in zip(rates, t_starts, t_stops)]

            if len(params) == 1:
                source_nodes = my_nest.Create('poisson_generator', len(params),
                                              params[0]) * len(ids)
            else:
                source_nodes = my_nest.Create('poisson_generator', len(params),
                                              params) * len(ids)

            target_nodes = numpy.array([[id_] * len(rates) for id_ in ids])
            target_nodes = list(
                numpy.reshape(target_nodes, len(rates) * len(ids), order='C'))
            #             pp(my_nest.GetStatus([2]))
            my_nest.Connect(source_nodes, target_nodes)

            generators = []
            if hash(tuple(ids)) in self.ids_generator.keys():
                generators = self.ids_generator[hash(tuple(idx))]

            generators = list(set(source_nodes).union(generators))
            self.ids_generator[hash(tuple(idx))] = sorted(generators)
            self.local_ids = list(self.ids)  # Nedd to put on locals also

        elif 'poisson_generator_dynamic' == self.type_model:
            source_nodes = my_nest.Create(self.type_model, 1, {
                'timings': times,
                'rates': rates
            }) * len(ids)
            target_nodes = ids
            my_nest.Connect(source_nodes, target_nodes)

            generators = []
            if hash(tuple(ids)) in self.ids_generator.keys():
                generators = self.ids_generator[hash(tuple(idx))]

            generators = list(set(source_nodes).union(generators))
            self.ids_generator[hash(tuple(idx))] = sorted(generators)


#             v=my_nest.GetStatus(ids, 'local')
#             self.local_ids=[_id for _id in zip(ids,v) if  # Nedd to put on locals also

        else:
            msg = 'type_model ' + self.type_model + ' is not accounted for in set_spike_times'
            raise ValueError(msg)
Ejemplo n.º 8
0
 def recordables(self):
     # Pick out recordables and receptor types using first model.
     try:
         return my_nest.GetDefaults(self.model)['recordables']
     except:
         return []