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})
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
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})
def __init__(self, name, **kwargs): ''' 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 ''' model = kwargs.get('model', 'iaf_neuron') n = kwargs.get('n', 1) params = kwargs.get('params', {}) ids = kwargs.get('ids', my_nest.Create(model, n, params)) self._ids = slice(ids[0], ids[-1], 1) self.local_ids = [] for _id in self.ids: if my_nest.GetStatus([_id], 'local'): self.local_ids.append(_id) self.model = model self.name = name self.n = n self.sets = kwargs.get('sets', [misc.my_slice(0, n, 1)])
def create_raw_spike_signal(self, start, stop): #signal=load:spikes() if self.sd['params']['to_file']: n_vp = my_nest.GetKernelStatus(['total_num_virtual_procs'])[0] data_path = my_nest.GetKernelStatus(['data_path'])[0] files = os.listdir(data_path) file_names = [ data_path + s for s in files if s.split('-')[0] == self.sd['model'] ] s, t = my_nest.get_spikes_from_file(file_names) else: s, t = my_nest.get_spikes_from_memory(self.sd['id']) e = my_nest.GetStatus(self.sd['id'])[0]['events'] # get events s = e['senders'] # get senders t = e['times'] # get spike times if comm.is_mpi_used(): s, t = my_nest.collect_spikes_mpi(s, t) if stop: s, t = s[t < stop], t[t < stop] # Cut out data s, t = s[t >= start], t[t >= start] # Cut out data signal = zip(s, t) return signal
def get_model_par(self, type='C_m'): ''' Retrieve one or several parameter values from all nodes ''' model_par = [my_nest.GetStatus([node], type)[0] for node in self.ids] return model_par
def find_connections(self): ''' FindConnections(self) Find connections for each node in layer ''' # Clear self.connections = {} for node in self.ids: self.connections[str(node)] = [ target for target in my_nest.GetStatus( my_nest.FindConnections([node]), 'target') if target not in self.sd + self.mm ]
def get_conn_par(self, type='delay'): ''' Get all connections parameter values for type ''' conn_par = {} if not self.connections: self.Find_connections() for source, targets in self.connections.iteritems(): conn_par[source] = [ my_nest.GetStatus( my_nest.FindConnections([int(source)], [target]), 'delay')[0] for target in targets ] return conn_par
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))})
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
def save_group(self): ''' Not complete ''' group = {} group["connections"] = self.connections group["models"] = self.models group["ids"] = self.ids group["recordables"] = self.recordables group["receptor_types"] = self.receptor_types group["sname"] = self.sname group["GID"] = str(my_nest.GetStatus(self.sd)[0]['global_id']) group["mm_dt"] = self.mm_dt output = open( self.spath + '/' + self.sname + '-' + str(my_nest.Rank()) + '.' + 'pickle', 'w') # Pickle dictionary pickle.dump(group, output) output.close()
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
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)
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
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
def _create_signal_object(self, dataType, recordable='spikes', start=None, stop=None): ''' -_create_signal_object(self, self, dataType, recordable='times', stop=None ) Creates NeuroTool signal object for the recordable simulation data. Arguments: dataType type of data. 's' or 'spikes' for spike data, 'g' for conductance data, 'c' for current data and 'v' for voltage data recordable Need to be supplied for conductance, current and voltage data. It is the name of my_nest recorded data with multimeter, e.g. V_m, I_GABAA_1, g_NMDA. stop end of signal in ms About files in nest [model|label]-gid-vp.[dat|gdf] The first part is the name of the model (e.g. voltmeter or spike_detector) or, if set, the label of the recording device. The second part is the global id (GID) of the recording device. The third part is the id of the virtual process the recorder is assigned to, counted from 0. The extension is gdf for spike files and dat for analog recordings. The label and file_extension of a recording device can be set like any other parameter of a node using SetStatus. ''' ids = self.local_ids # Eacj processor has its set of ids # Spike data if dataType in ['s', 'spikes']: signal = self.create_raw_spike_signal(start, stop) # create signal # Mulitmeter data, conductance, current or voltage data elif dataType in ['g', 'c', 'v']: mm_dt = self.mm['params']['interval'] e = my_nest.GetStatus(self.mm['id'])[0]['events'] # get events v = e[recordable] # get analog value s = e['senders'] # get senders t = e['times'] # get spike times #import pylab #pylab.plot(e['V_m'][e['senders'] ==12]) #pylab.show() if start != None and stop != None: s = s[(t > start) * (t < stop)] v = v[(t > start) * (t < stop)] t = t[(t > start) * (t < stop)] #start, stop=t[0], t[-1] if stop: s, v = s[t <= stop], v[t <= stop] # Cut out data start = stop - len(s) / len(ids) * float(mm_dt) else: start = t[0] # start time for NeuroTools # start, stop=t[0]-mm_dt/2, t[-1]+mm_dt/2 signal = zip(s, v) # create signal #abs(self.t_stop-self.t_start - self.dt * len(self.signal)) > 0.1*self.dt if dataType in ['s', 'spikes']: signal = MySpikeList(signal, ids, start, stop) if dataType in ['g']: signal = MyConductanceList(signal, ids, mm_dt, start, stop) if dataType in ['c']: signal = MyCurrentList(signal, ids, mm_dt, start, stop) if dataType in ['v']: signal = MyVmList(signal, ids, mm_dt, start, stop) return signal
def _create_signal_object(self, dataType, recordable='spikes', start=None, stop=None): ''' -_create_signal_object(self, self, dataType, recordable='times', stop=None ) Creates NeuroTool signal object for the recordable simulation data. Arguments: dataType type of data. 's' or 'spikes' for spike data, 'g' for conductance data, 'c' for current data and 'v' for voltage data recordable Need to be supplied for conductance, current and voltage data. It is the name of my_nest recorded data with multimeter, e.g. V_m, I_GABAA_1, g_NMDA. stop end of signal in ms ''' # Short cuts ids = self.local_ids # Eacj processor has its set of ids mm_dt = self.mm_dt spath = self.spath sname = self.sname # File to save to extension = '-' + recordable + '-' + str(my_nest.Rank()) + '.dat' fileName = spath + '/' + sname + extension # Spike data if dataType in ['s', 'spikes']: e = my_nest.GetStatus(self.sd)[0]['events'] # get events s = e['senders'] # get senders t = e['times'] # get spike times if stop: s, t = s[t < stop], t[t < stop] # Cut out data signal = zip(s, t) # create signal # Mulitmeter data, conductance, current or voltage data elif dataType in ['g', 'c', 'v']: e = my_nest.GetStatus(self.mm)[0]['events'] # get events v = e[recordable] # get analog value s = e['senders'] # get senders t = e['times'] # get spike times if stop: s, v = s[t < stop], v[t < stop] # Cut out data start = stop - len(s) / len(ids) * float(mm_dt) else: start = t[0] # start time for NeuroTools signal = zip(s, v) # create signal if dataType in ['s', 'spikes']: list = MySpikeList(signal, ids, start, stop) if dataType in ['g']: list = MyConductanceList(signal, ids, mm_dt, start, stop) if dataType in ['c']: list = MyCurrentList(signal, ids, mm_dt, start, stop) if dataType in ['v']: list = MyVmList(signal, ids, mm_dt, start, stop) return list