Example #1
0
    def gaussian_model_par(self, types=['C_m'], std_rel=0.1, sead=None):
        '''
        GaussianModelPar(self, types=['C_m'], std_rel=0.1, sead=None)
        Make model parameters gaussian distributed
        '''

        #! Used identical sead.
        if sead:
            random.seed(sead)

        for par in types:

            for node in self.ids:

                # OBS Does not work when GetStatus is taken on all nodes. Simulation
                # hang. Need to reproduce this on the side and post on my_nest forum.
                # sta=my_nest.GetStatus([nodes[0]])[0]

                # If node type is proxynode then do nothing. The node is then a
                # a shadow node for mpi process as I understand it.
                nodetype = my_nest.GetStatus([node])[0]['model']

                if nodetype != 'proxynode':

                    val = my_nest.GetStatus([node], par)[0]
                    rand = numpy.abs(random.gauss(val, std_rel * val))
                    if par in ['V_t', 'V_r']: rand = -rand
                    my_nest.SetStatus([node], {par: rand})
Example #2
0
    def voltage_response(self, currents, times, start, sim_time, id):

        scg = my_nest.Create('step_current_generator', n=1)
        my_nest.SetStatus(scg, {
            'amplitude_times': times,
            'amplitude_values': currents
        })

        rec = my_nest.GetStatus([id])[0]['receptor_types']
        my_nest.Connect(scg, [id], params={'receptor_type': rec['CURR']})

        my_nest.MySimulate(sim_time)

        self.get_signal('v', 'V_m', start=start, stop=sim_time)
        self.get_signal('s')  #, start=start, stop=sim_time)
        self.signals['V_m'].my_set_spike_peak(15,
                                              spkSignal=self.signals['spikes'])
        voltage = self.signals['V_m'][id].signal
        times = numpy.arange(0,
                             len(voltage) * self.mm['params']['interval'],
                             self.mm['params']['interval'])

        if len(times) != len(voltage):
            raise Exception('The vectors has to be the same length')

        return times, voltage
Example #3
0
    def model_par_randomize(self):
        '''
        Example:
        self.randomization={ 'C_m':{'active':True, 
                                    'gaussian':{'sigma':0.2*C_m, 'my':C_m}}}
        '''
        pyrngs = self.set_random_states_nest()
        for p, val in self.rand.iteritems():
            if not val['active']:
                continue

            local_nodes = []
            #             st=my_nest.GetStatus(self.ids, ['local', 'gloabal_id', 'vp'])
            for _id in self.ids:
                ni = my_nest.GetStatus([_id])[0]
                if ni['local']:
                    local_nodes.append((ni['global_id'], ni['vp']))


#             local_nodes=[(ni['global_id'], ni['vp'])
#                          for ni in st if ni['local']]

            for gid, vp in local_nodes:
                val_rand = numpy.round(get_random_number(pyrngs, vp, val), 2)
                #                 print val_rand
                my_nest.SetStatus([gid], {p: val_rand})
Example #4
0
    def update_spike_times(self,
                           rates=[],
                           times=[],
                           t_stop=None,
                           ids=None,
                           seed=None,
                           idx=None):
        if 'poisson_generator' == self.type_model:

            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)]
            my_nest.SetStatus(self.ids_generator[hash(tuple(idx))], params)
Example #5
0
    def gaussian_conn_par(self, type='delay', std_rel=0.1, sead=None):
        '''
        GaussianConnPar(self, type='delay', std_rel=0.1, sead=None)
        Make connection parameters gaussian distributed
        '''

        #! Used identical sead.
        if sead:
            random.seed(sead)

        if not self.connections:
            self.find_connections()

        for source, targets in self.connections.iteritems():

            for target in targets:

                conn = my_nest.FindConnections([int(source)], [target])
                val = my_nest.GetStatus(conn, type)[0]
                my_nest.SetStatus(
                    conn,
                    params={type: numpy.abs(random.gauss(val, std_rel * val))})
Example #6
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
Example #7
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)
Example #8
0
    def IV_I_clamp(self, I_vec, id=None, tStim=2000):
        '''
        Assure no simulations has been run before this (reset kernel).
        Function that creates I-V by injecting hyperpolarizing currents 
        and then measuring steady-state membrane (current clamp). Each 
        trace is preceded and followed by 1/5 of the simulation time 
        of no stimulation
        Inputs:
            I_vec          - step currents to inject
            id             - id of neuron to use for calculating I-F relation
            tStim          - lenght of each step current stimulation in ms

        Returns: 
            I_vec          - current for each voltage
            vSteadyState   - steady state voltage 
                
        Examples:
                >> n  = my_nest.Create('izhik_cond_exp')
                >> sc = [ float( x ) for x in range( -300, 100, 50 ) ] 
                >> tr_t, tr_v, v_ss = IV_I_clamp( id = n, tSim = 500, 
                I_vec = sc ):
        '''

        vSteadyState = []

        if not id: id = self.ids[0]
        if isinstance(id, int): id = [id]

        tAcum = 1  # accumulated simulation time, step_current_generator
        # recuires it to start at t>0

        scg = my_nest.Create('step_current_generator')
        rec = my_nest.GetStatus(id)[0]['receptor_types']
        my_nest.Connect(scg, id, params={'receptor_type': rec['CURR']})

        ampTimes = []
        ampValues = []
        for I_e in I_vec:

            ampTimes.extend([float(tAcum)])
            ampValues.extend([float(I_e)])
            tAcum += tStim

        my_nest.SetStatus(scg,
                          params={
                              'amplitude_times': ampTimes,
                              'amplitude_values': ampValues
                          })
        my_nest.Simulate(tAcum)

        self.get_signal('v', 'V_m', stop=tAcum)  # retrieve signal
        self.get_signal('s')
        if 0 < self.signals['spikes'].mean_rate():
            print 'hej'
        tAcum = 1
        for I_e in I_vec:

            if 0 >= self.signals['spikes'].mean_rate(tAcum + 10,
                                                     tAcum + tStim):
                signal = self.signals['V_m'].my_time_slice(
                    tAcum + 10, tAcum + tStim)
                vSteadyState.append(signal[1].signal[-1])
            tAcum += tStim

        I_vec = I_vec[0:len(vSteadyState)]
        return I_vec, vSteadyState
Example #9
0
    def I_PSE(self, I_vec, synapse_model, id=0, receptor='I_GABAA_1'):
        '''
        Assure no simulations has been run before this (reset kernel).
        Function creates relation between maz size of postsynaptic 
        event (current, conductance, etc). The type is set by receptor. 
        
        Inputs:
            I_vec          - step currents to clamp at
            id             - id of neuron to use for calculating I-F relation
                             If not providet id=ids[0]
     
        Returns: 
            v_vec          - voltage clamped at
            size_vec       - PSE size at each voltage 
                
        Examples:
                >> n  = my_nest.Create('izhik_cond_exp')
                >> sc = [ float( x ) for x in range( -300, 100, 50 ) ] 
                >> tr_t, tr_v, v_ss = IV_I_clamp( id = n, tSim = 500, 
                I_vec = sc ):
        '''

        vSteadyState = []

        if not id: id = self.ids[0]
        if isinstance(id, int): id = [id]

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

        voltage = []  # mV
        pse = []  # post synaptic event

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

        my_nest.Connect(sg, id, model=synapse_model)

        simTimeTot = 0
        for I_e in I_vec:

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

        self.get_signal(receptor[0].lower(), receptor,
                        stop=simTimeTot)  # retrieve signal

        simTimeAcum = 0

        for I_e in I_vec:

            size = []

            signal = self.signals[receptor].my_time_slice(
                400 + simTimeAcum, 700 + simTimeAcum)
            simTimeAcum += simTime
            # First signal object at position 1
            clamped_at = signal[1].signal[999]
            minV = min(signal[1].signal)
            maxV = max(signal[1].signal)
            if abs(minV - clamped_at) < abs(maxV - clamped_at):
                size.append(max(signal[1].signal) - clamped_at)

            else:
                size.append(min(signal[1].signal) - clamped_at)

            voltage.append(clamped_at)
            pse.append(size[0])

        return voltage, pse
Example #10
0
    def IF(self, I_vec, id=None, tStim=None):
        '''
        Function that creates I-F curve
        Inputs:
                id      - id of neuron to use for calculating 
                                 I-F relation
                tStim   - lenght of each step current injection 
                                in miliseconds
                I_vec   - step currents to inject
        
        Returns: 
                fIsi          - first interspike interval 
                mIsi          - mean interspike interval

                
        Examples:
                >> n  = nest.Create('izhik_cond_exp')
                >> sc = [ float( x ) for x in range( 10, 270, 50 ) ]
                >> f_isi, m_isi, l_isi = IF_curve( id = n, sim_time = 500, I_vec = sc ):
        '''
        if not id: id = self.ids[0]
        if isinstance(id, int): id = [id]

        fIsi, mIsi, lIsi = [], [], []  # first, mean and last isi
        if not tStim: tStim = 500.0
        tAcum = 0

        I_e0 = my_nest.GetStatus(id)[0]['I_e']  # Retrieve neuron base current

        isi_list = []
        for I_e in I_vec:

            my_nest.SetStatus(id, params={'I_e': float(I_e + I_e0)})
            my_nest.SetStatus(id, params={'V_m': float(-61)})
            #my_nest.SetStatus( id, params = { 'w': float(0) } )
            my_nest.SetStatus(id, params={'u': float(0)})
            simulate = True
            tStart = tAcum
            while simulate:
                my_nest.Simulate(tStim)
                tAcum += tStim

                self.get_signal('s', start=tStart, stop=tAcum)

                signal = self.signals['spikes'].time_slice(tStart, tAcum)

                if signal.mean_rate() > 0.1 or tAcum > 20000:
                    simulate = False

            isi = signal.isi()[0]
            if not any(isi): isi = [1000000.]

            fIsi.append(isi[0])  # retrieve first isi
            mIsi.append(numpy.mean(isi))  # retrieve mean isi
            if len(isi) > 100: lIsi.append(isi[-1])
            else: lIsi.append(isi[-1])  # retrieve last isi
            isi_list.append(numpy.array(isi))

        fIsi = numpy.array(fIsi)
        mIsi = numpy.array(mIsi)
        lIsi = numpy.array(lIsi)

        I_vec = numpy.array(I_vec)

        return I_vec, fIsi, mIsi, lIsi
Example #11
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)