def _sim_one(self, ps, rng): """ Run the simulation for one setting of parameters. """ # set parameters h.IN.soma[0](0.5).g_pas = ps[0] # g_leak h.IN.soma[0](0.5).gnabar_hh2 = ps[1] # gbar_Na h.IN.soma[0](0.5).gkbar_hh2 = ps[2] # gbar_K h.IN.soma[0](0.5).gkbar_im = ps[3] # gbar_M h.IN.soma[0](0.5).e_pas = -ps[4] # E_leak h.IN.soma[0](0.5).ena = ps[5] # E_Na h.IN.soma[0](0.5).ek = -ps[6] # E_K h.IN.soma[0](0.5).vtraub_hh2 = -ps[7] # V_T h.IN.soma[0](0.5).kbetan1_hh2 = ps[8] # k_betan1 h.IN.soma[0](0.5).kbetan2_hh2 = ps[9] # k_betan2 h.taumax_im = ps[10] # tau_max sigma = ps[11] # sigma # set up current injection of noise Iinj = rng.normal(0.5, sigma, np.array(h.t_vec).size) Iinj_vec = h.Vector(Iinj) Iinj_vec.play(h.El._ref_amp, h.t_vec) # initialize and run neuron.init() h.finitialize(h.v_init) neuron.run(h.tstop) self.n_sims += 1 return np.array(h.v_vec)
def run(duration, anfs): """Run a simulation of spiral ganglion neurons. This function takes care of proper acoustic and electric initialization. Parameters ---------- duration : float Duration of the simulation in seconds. anfs : list of sg.ANF objects List of sg.ANF objects for initialization. """ for anf in anfs: if anf.electrodes: anf.einit() neuron.init() for anf in anfs: if len(anf.vesicles) > 0: anf.ainit() neuron.run(duration * 1e3) # s -> ms
def step_math(self, dt, J, spiked, cells, voltage): # 1. Determine voltage changes dV = (dt / self.tau_rc) * J spiketimes = np.array( [c.spiketime if not c.refractory else 0.0 for c in cells]) dV += spiketimes * J / nrn_duration(self.tau_rc) # 2. Apply voltage changes for c, w in zip(cells, dV): if not c.refractory: c.spiketime = 0.0 c.in_con.weight[0] = w c.in_con.event(neuron.h.t + nrn_duration(dt) / 2.0) # 3. Setup recording of spikes spikes = self._setup_spike_recorder(cells) # 4. Simulate for one time step neuron.run(neuron.h.t + nrn_duration(dt)) # 5. Check for spikes and record voltages spiked[:] = [s.size() > 0 for s in spikes] spiked /= dt voltage[:] = [np.clip(c.neuron.M(), 0, 1) for c in cells] # 6. Record spike times for idx in np.where(spiked)[0]: cells[idx].spiketime = neuron.h.t - spikes[idx][0] cells[idx].neuron.refrac = nrn_duration(self.tau_ref + dt) - cells[idx].spiketime
def run_simulation(record_site, stim, simulation_time=5000, noise_amplitude=0): rec_t, rec_v, rec_ca = record(record_site) cvode = nrn.CVode() if noise_amplitude == 0: cvode.active(1) nrn.finitialize(-60) neuron.init() neuron.run(simulation_time) else: cvode.active(0) nrn.dt = 0.25 nrn.finitialize(-60) neuron.init() n_steps = int(np.ceil(simulation_time / nrn.dt)) + 1 noise = noise_amplitude * np.random.normal(size=n_steps) / np.sqrt( nrn.dt) # Add noise i = 0 while nrn.t < simulation_time: stim.amp = noise[i] nrn.fadvance() i += 1 return np.array(rec_t), np.array(rec_v), np.array(rec_ca)
def simulate(model, t_stop=100, NMDA=False, recDend=False, i_recDend=11): trec, vrec = h.Vector(), h.Vector() gRec, iRec, vDendRec = [], [], [] gNMDA_rec, iNMDA_rec = [], [] trec.record(h._ref_t) vrec.record(model.soma(0.5)._ref_v) # if NMDA: # for n in np.arange(0, len(model.NMDAlist)): # loc = model.NMDAlist[n].get_loc() # h.pop_section() # gNMDA_rec.append(h.Vector()) # iNMDA_rec.append(h.Vector()) # gNMDA_rec[n].record(model.NMDAlist[n]._ref_g) # iNMDA_rec[n].record(model.NMDAlist[n]._ref_i) # gRec.append(gNMDA_rec) # iRec.append(iNMDA_rec) if recDend: n = 0 for i_dend in i_recDend: vDendRec.append(h.Vector()) vDendRec[n].record(model.dends[i_dend](0.5)._ref_v) n += 1 h.celsius = model.CELSIUS h.finitialize(model.E_PAS) neuron.run(t_stop) return np.array(trec), np.array(vrec), np.array(vDendRec)
def go(self, sim_time=None): """ Launch a simulation of a given time Parameters ---------- sim_time: an integer the time in millisecond of the simulation it replaces the self.sim_time if defined Comments -------- It seems that when multiple go method are done it does not change the output vector. """ h.t = 0 #Start recording self.set_recording() h.dt = self.dt self.cell.initialise() init() #while h.t < self.sim_time: #I was using this procedure before do not know which one is better # h.fadvance() if sim_time: run(sim_time) else: run(self.sim_time)
def step_math(self, dt, J, spiked, cells, voltage): # 1. Determine voltage changes dV = (dt / self.tau_rc) * J spiketimes = np.array( [c.spiketime if not c.refractory else 0.0 for c in cells]) dV += spiketimes * J / nrn_duration(self.tau_rc) # 2. Apply voltage changes for c, w in zip(cells, dV): if not c.refractory: c.spiketime = 0.0 c.in_con.weight[0] = w c.in_con.event(neuron.h.t + nrn_duration(dt) / 2.0) # 3. Setup recording of spikes spikes = self._setup_spike_recorder(cells) # 4. Simulate for one time step neuron.run(neuron.h.t + nrn_duration(dt)) # 5. Check for spikes and record voltages spiked[:] = [s.size() > 0 for s in spikes] spiked /= dt voltage[:] = [np.clip(c.neuron.M(), 0, 1) for c in cells] # 6. Record spike times for idx in np.where(spiked)[0]: cells[idx].spiketime = neuron.h.t - spikes[idx][0] cells[idx].neuron.refrac = nrn_duration( self.tau_ref + dt) - cells[idx].spiketime
def get_vmb(time): """ Returns the voltage at the soma at a given time""" neuron.run(time) if h("run()"): return soma(0.5).v else: return 0
def run(cmd): global h, t, soma, ic, vc, syn, icRec, vcRec, vcrs icRec.clear() vcRec.clear() dt = cmd['dt'] * 1e3 ## convert s -> ms h.dt = dt data = cmd['data'] mode = cmd['mode'] #print "data:", data.min(), data.max() #times = h.Vector(np.linspace(h.t, h.t+len(data)*dt, len(data))) #print "times:", times.min(), times.max() if mode == 'ic': #ic.delay = h.t ic.delay = 0 vc.rs = 1e9 im = h.Vector(data * 1e9) im.play(ic._ref_amp, dt) elif mode == 'vc': #vc.amp1 = data[0] vc.rs = vcrs ic.delay = 1e9 #vc.dur1 = h.t vm = h.Vector(data * 1e3) vm.play(vc._ref_amp1, dt) syn.onset = 400. #ms syn.tau = 1.5 # ms syn.gmax = 0.04 # umho syn.e = -7.0 # mV #syn.i --- nA else: sys.stderr.write("Unknown mode '%s'" % sys.argv[1]) raise Exception("Unknown mode '%s'" % sys.argv[1]) #t2 = t + dt * (len(data)+2) #print "run until:", t2 neuron.init() h.finitialize(-65.) tstop = (dt * len(data) + 2) neuron.run(tstop) #dt * (len(data)+2)) #neuron.run(t2) #t = t2 #print len(out), out #out = np.array(out)[:len(data)] if mode == 'ic': out = np.array(icRec)[:len(data)] * 1e-3 + np.random.normal( size=len(data), scale=0.3e-3) elif mode == 'vc': out = np.array(vcRec)[:len(data)] * 1e-9 + np.random.normal( size=len(data), scale=3.e-12) return out
def run(self, sim_time=None): self.set_recording() neuron.h.dt = self.dt neuron.h.finitialize(self.cell.E) neuron.init() if sim_time: neuron.run(sim_time) else: neuron.run(self.sim_time) self.run_already = True
def go(self, sim_time=None): self.set_recording() neuron.h.dt = self.dt neuron.h.finitialize(self.cell.E) neuron.init() if sim_time: neuron.run(sim_time) else: neuron.run(self.sim_time) self.go_already = True
def simulate(model): trec, vrec = h.Vector(), h.Vector() trec.record(h._ref_t) vrec.record(model.soma(0.5)._ref_v) h.celsius = model.CELSIUS #h.FInitializeHandler(1, initSpikes2) h.finitialize(model.E_PAS) neuron.run(model.tstop) return np.array(trec), np.array(vrec)
def step_math(self, dt, spiked, neurons, voltage, time): """ Run NEURON forward one nengo timestep. Compare the current and previous spike arrays for this bioneuron. If they're different, the neuron has spiked. """ neuron.run(time*1000) for i, bahl in enumerate(neurons): count, volt = bahl.update() spiked[i] = count / dt voltage[i] = volt
def step_math(self, dt, J, spiked, cells, voltage): for c in cells: c.spikes.resize(0) # 1. Simulate for one time step neuron.run(neuron.h.t + nrn_duration(dt)) # 2. Check for spikes spiked[:] = [c.spikes.size() > 0 for c in cells] spiked /= dt voltage[:] = [c.neuron.soma.v for c in cells]
def run(self): if self.verbose: print "Initializing Simulation" self.set_stim() neuron.h.dt = self.dt neuron.h.celsius = 36 neuron.h.finitialize(-60) neuron.h.load_file('parcom.hoc') neuron.init() if self.verbose: print "...Running Simulation" neuron.run(self.sim_time) if self.verbose: print "...Simulation Complete\n"
def run(duration, objects=None): if objects is not None: for obj in objects: obj.pre_init() neuron.init() if objects is not None: for obj in objects: obj.post_init() neuron.run(duration * 1000)
def go(self, simTime=None): self.set_recording() self.h.celsius = self.T print 'Temperature = %d' % int(self.h.celsius) # self.h.dt = self.dt self.cvode = self.h.CVode() self.cvode.active() self.h.finitialize(self.cell.E) neuron.init() if simTime: neuron.run(simTime) else: neuron.run(self.simTime) self.go_already = True
def run(cmd): global t, soma, ic, vc, icRec, vcRec, vcrs icRec.clear() vcRec.clear() dt = cmd['dt'] * 1e3 ## convert s -> ms h.dt = dt data = cmd['data'] mode = cmd['mode'] #print "data:", data.min(), data.max() #times = h.Vector(np.linspace(h.t, h.t+len(data)*dt, len(data))) #print "times:", times.min(), times.max() if mode == 'ic': #ic.delay = h.t ic.delay = 0 vc.rs = 1e9 im = h.Vector(data * 1e9) im.play(ic._ref_amp, dt) elif mode == 'vc': #vc.amp1 = data[0] vc.rs = vcrs ic.delay = 1e9 #vc.dur1 = h.t vm = h.Vector(data * 1e3) vm.play(vc._ref_amp1, dt) else: sys.stderr.write("Unknown mode '%s'" % sys.argv[1]) raise Exception("Unknown mode '%s'" % sys.argv[1]) #t2 = t + dt * (len(data)+2) #print "run until:", t2 neuron.init() #neuron.finitialize(-65) neuron.run(dt * (len(data)+2)) #neuron.run(t2) #t = t2 #print len(out), out #out = np.array(out)[:len(data)] if mode == 'ic': out = np.array(icRec)[:len(data)] * 1e-3 + np.random.normal(size=len(data), scale=0.3e-3) elif mode == 'vc': out = np.array(vcRec)[:len(data)] * 1e-9 + np.random.normal(size=len(data), scale=3.e-12) return out
def go(self, sim_time=None): """ Start the simulation once it's been intialized """ self.set_recording() h.dt = self.dt h.finitialize(self.v_init) neuron.init() if sim_time: neuron.run(sim_time) else: neuron.run(self.sim_time) self.go_already = True
def run_simulation(record_site): """ Runs the NEURON simulation :param record_site: Where to record membrane potential from. Example: soma(0.5), where 0.5 means 'center', 0 would mean start, and 1 would mean at the end of the segment in question. :return: Time and voltage numpy arrays """ rec_t = nrn.Vector() rec_t.record(nrn._ref_t) rec_v = nrn.Vector() rec_v.record(record_site._ref_v) neuron.h.dt = 2**-3 nrn.finitialize(-65) neuron.init() neuron.run(200) return np.array(rec_t), np.array(rec_v)
def simulate(model, t_stop=100, NMDA=False, recDend=False, recSec=False): trec, vrec = h.Vector(), h.Vector() gRec, iRec, vDendRec, caDendRec, vSecRec = [], [], [], [], [] gNMDA_rec, iNMDA_rec = [], [] trec.record(h._ref_t) vrec.record(model.soma(0.5)._ref_v) print("Running a simulation with duration %sms (dt: %sms)" % (t_stop, h.dt)) if NMDA: for n in np.arange(0, len(model.NMDAlist)): loc = model.NMDAlist[n].get_loc() h.pop_section() gNMDA_rec.append(h.Vector()) iNMDA_rec.append(h.Vector()) gNMDA_rec[n].record(model.NMDAlist[n]._ref_g) iNMDA_rec[n].record(model.NMDAlist[n]._ref_i) gRec.append(gNMDA_rec) iRec.append(iNMDA_rec) if recDend: n = 0 for dend in model.dends: vDendRec.append(h.Vector()) caDendRec.append(h.Vector()) vDendRec[n].record(dend(0.6)._ref_v) #caDendRec[n].record(dend(0.2)._ref_ica) caDendRec[n].record(dend(0.6)._ref_gna_na) # Hacked to get iNa n += 1 if recSec: n = 0 for sec in h.allsec(): for seg in sec.allseg(): vSecRec.append(h.Vector()) vSecRec[n].record(seg._ref_v) n += 1 h.celsius = model.CELSIUS h.finitialize(model.E_PAS) neuron.run(t_stop) return np.array(trec), np.array(vrec), np.array( vDendRec), gNMDA_rec, iNMDA_rec, np.array(caDendRec), np.array(vSecRec)
def calc_hh(): soma = neuron.h.Section(name="soma") soma.nseg = 3 # odd number soma.diam = 10 # [um] soma.L = 10 # [um] soma.insert("hh") meca = soma(0.5).hh stim = neuron.h.IClamp(soma(0.5)) stim.delay = 50 # [ms] stim.dur = 200 # [ms] stim.amp = 0.15 # [nA] rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) neuron.h.finitialize(-65) tstop = 300 neuron.run(tstop) # convert neuron array to numpy array time = rec_t.as_numpy() voltage = rec_v.as_numpy() # show graph by matplotlib plt.plot(time, voltage, color='b') plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]") plt.axis(xmin=0, xmax=max(time), ymin=min(voltage) - 5, ymax=max(voltage) + 5) plt.show()
def calc_hh(dt=25, method='cnexp', show_plot=False, type=0): """ dt = (int) [micro sec] method = cnexp | impl | euler | runge show_plot = True | False """ filename_template = './multi_result/hh_%d.txt' filename = filename_template % type if type == 0: pos_list = [331, 553, 1087, 2222, 3838] elif type == 1: pos_list = [290, 488, 955, 1684, 2820] elif type == 2: pos_list = [44, 76, 131, 439, 846] elif type == 3: pos_list = [26, 42, 64, 201, 366] elif type == 4: pos_list = [10, 15, 23, 101, 184] h = neuron.hoc.HocObject() h.execute('type = ' + str(type)) h('nrn_load_dll("./mod/x86_64/.libs/libnrnmech.so")') neuron.h.load_file('swc_main.hoc') for sec in h.allsec(): if method == 'cnexp': sec.insert("hh_cnexp") meca = sec(0.5).hh_cnexp elif method == 'impl': sec.insert("hh_impl") meca = sec(0.5).hh_impl elif method == 'euler': sec.insert("hh_euler") meca = sec(0.5).hh_euler elif method == 'runge': sec.insert("hh_runge") meca = sec(0.5).hh_runge else: print('wrong method.') quit() sec.nseg = 1 # neuron.h.psection() stim = neuron.h.IClamp(h.CellSwc[0].Dend[pos_list[0]](0.5)) stim.delay = 50 # [ms] stim.dur = 200 # [ms] stim.amp = 0.10 # [nA] rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) rec_v1 = neuron.h.Vector() rec_v1.record(h.CellSwc[0].Dend[pos_list[1]](0.5)._ref_v) rec_v2 = neuron.h.Vector() rec_v2.record(h.CellSwc[0].Dend[pos_list[2]](0.5)._ref_v) rec_v3 = neuron.h.Vector() rec_v3.record(h.CellSwc[0].Dend[pos_list[3]](0.5)._ref_v) rec_v4 = neuron.h.Vector() rec_v4.record(h.CellSwc[0].Dend[pos_list[4]](0.5)._ref_v) neuron.h.finitialize(-65) tstop = 300 neuron.h.dt = float(dt) / 1000. # neuron.h.secondorder = 2 neuron.run(tstop) print("dt = %f" % neuron.h.dt) # convert neuron array to numpy array time = rec_t.as_numpy() voltage1 = rec_v1.as_numpy() voltage2 = rec_v2.as_numpy() voltage3 = rec_v3.as_numpy() voltage4 = rec_v4.as_numpy() with open(filename, 'w') as f: f.write('# %s\n' % filename) f.write('# dt = %d [usec]\n' % dt) f.write('# t [usec], V [mV]\n') for i in range(len(time)): # checked_time = int((int(time[i]*10000)+1)/10) * 10 checked_time = int((int(time[i] * 1000) + 1) / 10) * 10 # checked_time = int(time[i]*1000) f.write("%d, %f, %f, %f, %f\n" % (checked_time, voltage1[i], voltage2[i], voltage3[i], voltage4[i])) # show graph by matplotlib if show_plot: plt.plot(time, voltage1, color='b') plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]") plt.axis(xmin=0, xmax=max(time), ymin=min(voltage) - 5, ymax=max(voltage) + 5) plt.show()
stim.dur = 3 # You can play with the NEURON-gui by typing # >>> from neuron import gui # For an overview (gui menu bar): Tools -> Model View -> 1 real cell -> root... # Record Time from NEURON (neuron.h._ref_t) rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) # Record Voltage from the center of the soma rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) neuron.h.finitialize(-60) neuron.init() neuron.run(5) # Plot the recordings with matplotlib # =================================== import matplotlib.pyplot as plt # get values from NEURON-vector format into Python format times = [] # Use list to add another trace later. voltages = [] times.append(list(rec_t)) # alternativ to `list(rec_t)`: `numpy.array(rec_t)` voltages.append(list(rec_v)) # check types by: # >>> type(rec_t) # >>> type(time[0])
dend.nseg = 100 dend.connect(soma, 1, 0) for sec in nrn.allsec(): sec.Ra = 100 # Ohm cm sec.cm = 1 # uF / cm2 sec.insert("hh") #sec.g_pas = 1.0 / 30000 #sec.e_pas = -65 stim = nrn.IClamp(soma(0.5)) stim.delay = 30 # ms stim.dur = 300 # ms stim.amp = -0.3 # nA t = nrn.Vector() t.record(nrn._ref_t) v = nrn.Vector() v.record(dend(1.)._ref_v) i = nrn.Vector() i.record(stim._ref_i) nrn.finitialize() neuron.run(600) plt.plot(t,v) plt.show()
def run(self, duration): self.initialize() neuron.run(duration)
def run(self, modfile='CaPCalyx', color='r'): if isinstance(modfile, list): modfile = modfile[0] if modfile in self.tdur: tstep = self.tdur[modfile] else: tstep = [200., 50.] tdelay = 5.0 # print 'modfile: ', modfile # Channel = nrnlibrary.utility.Mechanism(modfile) # leak = nrnlibrary.util.Mechanism('leak') # Channel.set_parameters({'gbar': 1}) # leak.set_parameters({'gbar': 1e-12}) #self.soma = nrnlibrary.nrnlibrary.util.Section(L=10, diam=10, mechanisms=[Channel, leak]) # Channel.insert_into(soma) # leak.insert_into(soma) # print dir(self.soma) self.soma = h.Section() self.soma.L = 10 self.soma.insert('leak') self.soma().leak.gbar = 1e-12 self.soma.insert(modfile) exec('self.soma().%s.gbar = 1' % modfile) h.celsius = 22 # set the temperature. ca_init = 70e-6 self.vec={} for var in ['time', 'V', 'IChan', 'Vcmd']: self.vec[var] = h.Vector() h.dt = 0.025 v_init = -65. clampV = v_init self.vcPost = h.SEClamp(0.5, sec=self.soma) self.vcPost.dur1 = tdelay self.vcPost.amp1 = clampV self.vcPost.dur2 = tstep[0] self.vcPost.amp2 = clampV-0.0 # just a tiny step to keep the system honest self.vcPost.dur3 = tstep[1] self.vcPost.amp3 = clampV self.vcPost.rs = 1e-6 print("soma: ", self.soma, end=' ') print(' vcpost sec: ', self.vcPost.Section()) if modfile[0:2] == 'ih': stimamp = np.linspace(-140, -40, num=21, endpoint=True) else: stimamp = np.linspace(-100, 60, num=35, endpoint=True) self.ivss = np.zeros((2, stimamp.shape[0])) self.ivmin = np.zeros((2, stimamp.shape[0])) print(dir(h)) for i, V in enumerate(stimamp): stim={} stim['NP'] = 1 stim['Sfreq'] = 1 # stimulus frequency stim['delay'] = 5 stim['dur'] = 100 stim['amp'] = V stim['PT'] = 0.0 self.vcPost.amp2=V self.vec['IChan'].record(self.vcPost._ref_i, sec=self.soma) self.vec['V'].record(self.soma()._ref_v, sec=self.soma) self.vec['time'].record(h._ref_t) print('V = ', V, end=' ') h.tstop = self.vcPost.dur1+self.vcPost.dur2+self.vcPost.dur3 h.finitialize(v_init) h.run() self.t = np.array(self.vec['time']) self.ichan = np.array(self.vec['IChan']) self.v = np.array(self.vec['V']) self.p1.plot(self.t, self.ichan, pen=pg.mkPen(color)) self.p3.plot(self.t, self.v, pen=pg.mkPen(color)) (self.ivss[1,i], r2) = Util.measure('mean', self.t, self.ichan, tdelay+tstep[0]-10., tdelay+tstep[0]) (self.ivmin[1,i], r2) = Util.measure('minormax', self.t, self.ichan, tdelay+0.1, tdelay+tstep[0]/5.0) self.ivss[0,i] = V self.ivmin[0,i] = V print(' T = ', h.celsius) self.p2.plot(self.ivss[0,:], self.ivss[1,:], symbol='o', symbolsize=2.0, pen= pg.mkPen(color)) self.p4.plot(self.ivmin[0,:], self.ivmin[1,:], symbol='s', symbolsize=2.0, pen=pg.mkPen(color))
cell.gkbar_hh = 0.01 # 0.02 #default:0.036 S/cm2 vrec = h.Vector() trec = h.Vector() vrec.record(cell(0.5)._ref_v) # record voltage at center of the Section trec.record(h._ref_t) # record time # record the potassium and sodium currents ik_rec = h.Vector() ik_rec.record(cell(0.5)._ref_ik) # pointer to potassium current at center ina_rec = h.Vector() ina_rec.record(cell(0.5)._ref_ina) # pointer to sodium current at center h.finitialize(-60) # initializes voltage h.dt = 0.025 # timestep in milliseconds neuron.run(100) # run the simulation for 100 milliseconds # plot the output subplot(2, 1, 1) plot(np.array(trec), np.array(vrec), label='Vm') ylabel('Vm (mV)') xlabel('Time (ms)') xlim((0, h.tstop)) legend() subplot(2, 1, 2) plot(np.array(trec), np.array(ik_rec), 'r', label='$I_{k}$') plot(np.array(trec), np.array(ina_rec), 'g', label='$I_{Na}$') xlabel('Time (ms)') xlim((0, h.tstop)) legend()
#---------parameters to recored------->(voltage and time) vrec = h.Vector() vrec.record(soma(0.5)._ref_v) trec = h.Vector() trec.record(h._ref_t) ikrec = h.Vector() ikrec.record(soma(0.5)._ref_ik) inarec = h.Vector() inarec.record(soma(0.5)._ref_ina) icarec = h.Vector() icarec.record(soma(0.5)._ref_ica) h.celsius = 35 # simulation temperature h.finitialize(-65) # initialization conditions neuron.run(1000) # simulation run time (ms) t = np.array(trec) v = np.array(vrec) plt.plot(t,v) # plots voltage over time plt.show() plt.plot(t,np.array(ikrec),label='ik') plt.plot(t,np.array(inarec),label='ina') plt.plot(t,np.array(icarec),label='ica') plt.show() # shows plot Rm = 1e2 / (soma(0.5).pas.g*soma.L*soma.diam*math.pi) # (MOhm) print('') print(' cell properties ')
rec_ina = h.Vector() rec_ina.record(muscle(0.5)._ref_ina) rec_ik = h.Vector() rec_ik.record(muscle(0.5)._ref_ik) rec_ica = h.Vector() rec_ica.record(muscle(0.5)._ref_ica) h.dt = 0.05 h.finitialize(-70.0) neuron.init() sim_time = 500 if sim_time: neuron.run(sim_time) else: neuron.run(sim_time) x = np.array(rec_t) y = np.array(rec_v) plt.figure(1) plt.subplot(411) plt.plot(x, y) na = np.array(rec_ina) plt.subplot(412) plt.plot(x, na) k = np.array(rec_ik) plt.subplot(413)
vinhrec.record(interneuron(0.5)._ref_v) grec = h.Vector() grec.record(exnc[0]._ref_weight[1]) # Run Simulation # In[10]: h.dt = DT h.celsius = 30 h.finitialize(-70) print('simulation is running') neuron.run(total_time) print("simulation is finished\nfigures will show up one after the other\nclose one to see the next") # In[11]: # data collection sampling_start = WARM_UP+50 sampling_interval = 1000.0/freq t = np.array(trec) inh_spikes = np.array(tvec) v = np.array(rec_v) v_inh = np.array(rec_v4) vinh = np.array(vinhrec) vd = np.array(rec_v9) g = np.array(grec)
stimulator.delay = 0.1 stimulator.dur = 0.8 stimulator.amp = 1.2 # test Vmb without perturbation # print "The initial membrane potential is %6.4f" %(soma(.5).v) print(soma(0.5).v) # Run simulation print(soma.v) # set tstop at 1.5 tstop = 1.5 neuron.run(tstop) print(soma.v) tstop = 5 neuron.run(tstop) print(soma.v) def get_vmb(time): """ Returns the voltage at the soma at a given time""" neuron.run(time)
def simple_geo(props=None, retsoma=False): # simulate stimulations, returns time, dend2_volt +/- soma_volt P = set_props() if props is None: props=P else: for k in P.keys(): if k not in props: props[k] = P[k] for k in props.keys(): if k not in P.keys(): print("Don't know what the f**k %s is. Options are: " %k) print(list(P.keys())) # Creating the morphology # soma (compartment: neuron.h.Section() ) soma = init_section(100, props['Ra'], 80, 10) # dendrite0 dend_0 = init_section(200, props['Ra'], bound0) # dendrite1, with taper dend_1 = init_section(200, props['Ra'], bound0) diams = np.linspace(bound0, bound1, dend_1.nseg) rad = -1 for seg in dend_1: rad = rad+1 seg.diam = diams[rad] # dendrite2 dend_2 = init_section(200, props['Ra'], bound1) dend_0.connect(soma, 1, 0) # connect soma(1) with dend_0(0) dend_1.connect(dend_0, 1, 0) # connect dend_0(1) with dend_1(0) dend_2.connect(dend_1, 1, 0) # connect dend_1(1) with dend_2(0) # Implementing a current clamp electrode # Locate the electrode at the center of the soma stim = neuron.h.IClamp(soma(0.5)) # Setting recording paradigm stim.delay = props['stim_delay'] stim.amp = props['stim_amp'] stim.dur = props['stim_dur'] # Setting passive parameters for sec in neuron.h.allsec(): # Do with the present `sec` sec.insert('pas') sec.Ra = props['Ra'] # Do for each segment within `sec`: for seg in sec: # Do with the segment `seg`: seg.pas.g = 0.01 seg.pas.e = -50 # Record Time from NEURON (neuron.h._ref_t) rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) # Record Voltage from the center of the soma and the end of dend_2 rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) rec_2 = neuron.h.Vector() rec_2.record(dend_2(1)._ref_v) neuron.h.finitialize(-50) neuron.init() neuron.run(props['run_time']) if retsoma==True: return list(rec_t), list(rec_2), list(rec_v) else: return list(rec_t), list(rec_2)
dend_1.connect(dend_0, 1, 0) # connect dend_0(1) with dend_1(0) dend_2.connect(dend_1, 1, 0) # connect dend_1(1) with dend_2(0) # Implementing a current clamp electrode # Locate the electrode at the center of the soma stim = neuron.h.IClamp(soma(0.5)) # Setting recording paradigm stim.delay = props['stim_delay'] stim.amp = props['stim_amp'] stim.dur = props['stim_dur'] # Record Time from NEURON (neuron.h._ref_t) rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) # Record Voltage from the center of the soma and the end of dend_2 rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) rec_2 = neuron.h.Vector() rec_2.record(dend_2(1)._ref_v) neuron.h.finitialize(-50) neuron.init() neuron.run(props['run_time']) if retsoma==True: return list(rec_t), list(rec_2), list(rec_v) else: return list(rec_t), list(rec_2)
def run(self) : # Find all the compartments of neuron n+1 that are closer than D to to each # compartment of neuron n (intersection points) and could accomodate # possible synapses and then create 'synapses_no' synapses..! ss = [] ssSize = 0 nc = [] ncSize = 0 for n in range(self.num_neurons-1): # Note: So we need at least two neurons for it to work! # -- Find intersection points ------------------------------------------ if self.verbose : print "Searching for synapses for neurons ", n, " and ", n+1 synapses = 0 syn = [] for a in range(self.NSize[n]) : minimum = sys.float_info.max (x1,y1,z1) = self.m_coordinates[a] for b in range(self.NSize[n],self.NSize[n]+self.NSize[n+1]) : (x2,y2,z2) = self.m_coordinates[b] dist = math.sqrt((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2) if synapses < self.max_synapses : if self.synaptic_distance > dist : synapses = synapses + 1 syn.append((a,b-self.NSize[n])) else : print "WORNING: We reached the maximum number of synapses" if self.verbose : print "Synapses found: ", synapses # -- Reduce intersection points to number of synapses ------------------ if synapses < self.num_synapses or len(syn) < self.num_synapses : sys.exit("ERROR: There are not enough intersections to create "+\ "synapses. Change parameter D and run again!!") random.seed(self.synapses_seed) # Reduce the amount of synapses while len(syn) > self.num_synapses : random_synapse = int(random.uniform(0,len(syn)-1)) syn.pop(random_synapse) print "Synapses used: ", len(syn) # ------------------------------------------------------------------- # if self.verbose : print "Generating synapses..." for pre, post in syn : if random.random() < 0.5 : #print "0 -> 1" # to prove that synapses are generated in both directions ssSize = ssSize + 1 exec "ss.append(h.Exp2Syn(h.neuron"+str(n+1)+"_tree[post](0.5)))" #ss.tau1 --- ms rise time #ss.tau2 --- ms decay time #ss.e -- mV reversal potential #ss.i -- nA synaptic current ss[ssSize-1].e = -75; # [mV] ncSize = ncSize + 1 exec "nc.append(h.NetCon(h.neuron"+str(n)+"_tree[pre](0.5)._ref_v, ss[ssSize-1], self.thresholds, self.delays, self.weights, sec=h.neuron"+str(n)+"_tree[pre]))" else : #print "1 -> 0" # to prove that synapses are generated in both directions ssSize = ssSize + 1 exec "ss.append(h.Exp2Syn(h.neuron"+str(n)+"_tree[pre](0.5)))" ss[ssSize-1].e = -75; # [mV] ncSize = ncSize + 1 exec "nc.append(h.NetCon(h.neuron"+str(n+1)+"_tree[post](0.5)._ref_v, ss[ssSize-1], self.thresholds, self.delays, self.weights, sec=h.neuron"+str(n+1)+"_tree[post]))" if self.verbose : print "OK!" if self.verbose : print "Generating parameters..." h('forall {uninsert pas}') h('forall {insert hh}') for sec in h.allsec() : sec.gnabar_hh = self.sodium sec.gkbar_hh = self.potassium #Stimulation self.stimNet = [] self.syn0net = [] self.nc0net = [] for p in range(self.num_pixels) : self.stimNet.append(h.IntFire2()) self.stimNet[p].taum = 100 self.stimNet[p].taus = 1 self.stimNet[p].ib = self.min_current # Connect every neuron to this input that represents a pixel for n in range(self.num_neurons) : Centre = np.sqrt(self.num_pixels)/2.0 x = p % np.sqrt(self.num_pixels) y = p / np.sqrt(self.num_pixels) Dist = np.sqrt( (x-Centre)**2 + (y-Centre)**2 ) weight = self.calc_rand_weight(Dist, self.min_weight, self.max_weight) exec "self.syn0net.append(h.Exp2Syn(h.neuron"+str(n)+"_tree[3](0.5)))" self.nc0net.append(h.NetCon(self.stimNet[p], self.syn0net[-1], 0, # Threshold 0.025+40.0*np.random.rand(), # Delay weight)) # Weight # Define the compartments whose activity will be recorded self.t_vec = [] #time self.id_vec = [] #cell number self.raster = [] # Initialize the electrodes for n in range(self.num_neurons) : self.t_vec.append(h.Vector()) self.id_vec.append(h.Vector()) exec "self.raster.append(h.NetCon(h.neuron"+str(n)+"_tree[1](.5)._ref_v, None, sec=h.neuron"+str(n)+"_tree[1]))" #(.5) self.raster[-1].threshold = 0 #-10 #set threshold to a value of your choice self.raster[-1].record(self.t_vec[-1], self.id_vec[-1], n) # ---------------------------------------------------------------------- # -- Spiking recording for pattern recognition output------------------- self.t_out_vec = [] # Time. self.id_out_vec = [] # Cell number. self.out_raster = [] # Initialize the electrodes #Choose the appropriate step for the compartments to be recorded self.step_patt_rec_index=min(self.step_patt_rec_index,(self.NSize[n]-self.start_patt_rec_index)/self.num_electrodes) for n in range(self.num_neurons) : for i in range(self.num_electrodes): # The compartment number which will be recorded comp_idx=self.start_patt_rec_index+i*self.step_patt_rec_index #print "Neuron No ",n, " elec no: ",i," comp num: ",comp_idx self.t_out_vec.append(h.Vector()) self.id_out_vec.append(h.Vector()) exec "self.out_raster.append(h.NetCon(h.neuron"+str(n)+"_tree[comp_idx](.5)._ref_v, None, sec=h.neuron"+str(n)+"_tree[comp_idx]))" #(.5) self.out_raster[-1].threshold = 0 #-10 #set threshold to a value of your choice self.out_raster[-1].record(self.t_out_vec[-1], self.id_out_vec[-1], n) # ---------------------------------------------------------------------- # RUN THE SIMULATION: Plot recordings #define the compartments whose activity will be recorded recsize=[] self.rec=[] for n in range(self.num_neurons) : self.rec.append([]) recsize.append(int(self.NSize[n] / self.electrodes)) for i in range(self.electrodes) : self.rec[n].append(recsize[n]*i) # Initialize the electrodes for e in range(self.electrodes): for n in range(self.num_neurons): exec "self.vrec" + str(n) + str(e) + " = h.Vector()" exec "self.trec" + str(n) + str(e) + " = h.Vector()" exec "self.vrec" + str(n) + str( e) + ".record(h.neuron" + str( n) + "_tree[" + str(self.rec[n][e]) + "](0.5)._ref_v)" exec "self.trec" + str(n) + str(e) + ".record(h._ref_t)" # Finalize initialization h.finitialize(-60) h.dt = self.dt # Run the simulation pixels=len(self.input[0]['frame']) print pixels #print "pix",len(self.input[0]),self.num_pixels self.runtime = self.duration for frame_object in self.input: frame = np.array(frame_object['frame']) print frame for n in range(pixels) : self.stimNet[n].ib = self.min_current+100*frame[n]*(self.max_current-self.min_current) neuron.run(self.runtime) self.runtime += self.duration print "Raster stuff:" for i in range(len(self.t_vec)): print "Spikes of neuron", str(i) + ":", len(self.t_vec[i]) return list(self.t_vec),self.sp_trains()
def runsimulation(legtext,amp1,dur1,start1): def recvolt(seg): rec_v=neuron.h.Vector() rec_v.record(seg._ref_v) return rec_v def rectime(seg): rec_t=neuron.h.Vector() rec_t.record(seg._ref_t) return rec_t def setstim(seg,amp,duration,start,segdist): stim=neuron.h.IClamp(seg(segdist)) stim.delay=start stim.dur=duration stim.amp=amp return stim load_mechanisms("/home/ben/boxing_bk/neuron_model/downloaded_models/Figure5/") #neuron.h.create soma cell1=cell(maxNa,maxK,maxLeak,NaRev,KRev,LeakRev) rec_v_cell1=recvolt(cell1.soma(0.5)) ###SPECIFY THE VALUES OF THE SECTION TO BE RECORDED## #record time from NEURON (neuron.h._ref_t) rec_t=neuron.h.Vector() rec_t.record(neuron.h._ref_t) #record voltage from center of the soma #for i in dends: cell1_stim=setstim(cell1.soma,amp1,dur1,start1,0.5) '''ATTRIBUTES OF ELECTRODE amp: Amplitude of the injected current delay: Time of activation in ms dur: Duration of the stimulation ''' #initialize the value of the voltage neuron.h.finitialize(-65) #set time of the simulation tstop=300 #create ndendrites ndend=1 dends=range(ndend) #Run the simulation neuron.run(tstop) #PLOT THE RESULT time=rec_t.as_numpy() cell1_volt=rec_v_cell1.as_numpy() plt.plot(time,cell1_volt,color=colors[cellnum],linewidth=3.0) legendlist.append(legtext) plt.legend(legendlist) global cellnum if cellnum==4: cellnum=0 else: cellnum=cellnum+1 #plt.plot(time,cell2_volt,color='k',linewidth=3.0) plt.xlabel("Time (ms)") plt.ylabel("Voltage (mV)") #plt.axis(xmin=210,xmax=216,\ #ymin=min(cell1_volt)-5,ymax=max(cell1_volt)+5) plt.show()
recVoltage_allSegments = [] for segInd, segment in enumerate(allSegments): voltageRecSegment = h.Vector() voltageRecSegment.record(segment._ref_v) recVoltage_allSegments.append(voltageRecSegment) preparationDurationInSeconds = time.time() - preparationStartTime print("preparing for single simulation took %.4f seconds" % (preparationDurationInSeconds)) ## simulate the cell simulationStartTime = time.time() # make sure the following line will be run after h.finitialize() fih = h.FInitializeHandler('nrnpython("AddAllSynapticEvents()")') h.finitialize(-76) neuron.run(totalSimDurationInMS) singleSimulationDurationInMinutes = (time.time() - simulationStartTime) / 60 print("single simulation took %.2f minutes" % (singleSimulationDurationInMinutes)) ## extract the params from the simulation # collect all relevent recoding vectors (input spike times, dendritic voltage traces, soma voltage trace) collectionStartTime = time.time() origRecordingTime = np.array(recTime.to_python()) origSomaVoltage = np.array(recVoltageSoma.to_python()) origNexusVoltage = np.array(recVoltageNexus.to_python()) # high res - origNumSamplesPerMS per ms recordingTimeHighRes = np.arange(0, totalSimDurationInMS,
def run(self): # Find all the compartments of neuron n+1 that are closer than D to to each # compartment of neuron n (intersection points) and could accomodate # possible synapses and then create 'synapses_no' synapses..! ss = [] ssSize = 0 nc = [] ncSize = 0 for n in range( self.num_neurons - 1): # Note: So we need at least two neurons for it to work! # -- Find intersection points ------------------------------------------ if self.verbose: print "Searching for synapses for neurons ", n, " and ", n + 1 synapses = 0 syn = [] for a in range(self.NSize[n]): minimum = sys.float_info.max (x1, y1, z1) = self.m_coordinates[a] for b in range(self.NSize[n], self.NSize[n] + self.NSize[n + 1]): (x2, y2, z2) = self.m_coordinates[b] dist = math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2) if synapses < self.max_synapses: if self.synaptic_distance > dist: synapses = synapses + 1 syn.append((a, b - self.NSize[n])) else: print "WORNING: We reached the maximum number of synapses" if self.verbose: print "Synapses found: ", synapses # -- Reduce intersection points to number of synapses ------------------ if synapses < self.num_synapses or len(syn) < self.num_synapses: sys.exit("ERROR: There are not enough intersections to create "+\ "synapses. Change parameter D and run again!!") random.seed(self.synapses_seed) # Reduce the amount of synapses while len(syn) > self.num_synapses: random_synapse = int(random.uniform(0, len(syn) - 1)) syn.pop(random_synapse) print "Synapses used: ", len(syn) # ------------------------------------------------------------------- # if self.verbose: print "Generating synapses..." for pre, post in syn: if random.random() < 0.5: #print "0 -> 1" # to prove that synapses are generated in both directions ssSize = ssSize + 1 exec "ss.append(h.Exp2Syn(h.neuron" + str( n + 1) + "_tree[post](0.5)))" #ss.tau1 --- ms rise time #ss.tau2 --- ms decay time #ss.e -- mV reversal potential #ss.i -- nA synaptic current ss[ssSize - 1].e = -75 # [mV] ncSize = ncSize + 1 exec "nc.append(h.NetCon(h.neuron" + str( n ) + "_tree[pre](0.5)._ref_v, ss[ssSize-1], self.thresholds, self.delays, self.weights, sec=h.neuron" + str( n) + "_tree[pre]))" else: #print "1 -> 0" # to prove that synapses are generated in both directions ssSize = ssSize + 1 exec "ss.append(h.Exp2Syn(h.neuron" + str( n) + "_tree[pre](0.5)))" ss[ssSize - 1].e = -75 # [mV] ncSize = ncSize + 1 exec "nc.append(h.NetCon(h.neuron" + str( n + 1 ) + "_tree[post](0.5)._ref_v, ss[ssSize-1], self.thresholds, self.delays, self.weights, sec=h.neuron" + str( n + 1) + "_tree[post]))" if self.verbose: print "OK!" if self.verbose: print "Generating parameters..." h('forall {uninsert pas}') h('forall {insert hh}') for sec in h.allsec(): sec.gnabar_hh = self.sodium sec.gkbar_hh = self.potassium #Stimulation self.stimNet = [] self.syn0net = [] self.nc0net = [] for p in range(self.num_pixels): self.stimNet.append(h.IntFire2()) self.stimNet[p].taum = 100 self.stimNet[p].taus = 1 self.stimNet[p].ib = self.min_current # Connect every neuron to this input that represents a pixel for n in range(self.num_neurons): Centre = np.sqrt(self.num_pixels) / 2.0 x = p % np.sqrt(self.num_pixels) y = p / np.sqrt(self.num_pixels) Dist = np.sqrt((x - Centre)**2 + (y - Centre)**2) weight = self.calc_rand_weight(Dist, self.min_weight, self.max_weight) exec "self.syn0net.append(h.Exp2Syn(h.neuron" + str( n) + "_tree[3](0.5)))" self.nc0net.append( h.NetCon( self.stimNet[p], self.syn0net[-1], 0, # Threshold 0.025 + 40.0 * np.random.rand(), # Delay weight)) # Weight # Define the compartments whose activity will be recorded self.t_vec = [] #time self.id_vec = [] #cell number self.raster = [] # Initialize the electrodes for n in range(self.num_neurons): self.t_vec.append(h.Vector()) self.id_vec.append(h.Vector()) exec "self.raster.append(h.NetCon(h.neuron" + str( n) + "_tree[1](.5)._ref_v, None, sec=h.neuron" + str( n) + "_tree[1]))" #(.5) self.raster[ -1].threshold = 0 #-10 #set threshold to a value of your choice self.raster[-1].record(self.t_vec[-1], self.id_vec[-1], n) # ---------------------------------------------------------------------- # -- Spiking recording for pattern recognition output------------------- self.t_out_vec = [] # Time. self.id_out_vec = [] # Cell number. self.out_raster = [] # Initialize the electrodes #Choose the appropriate step for the compartments to be recorded self.step_patt_rec_index = min( self.step_patt_rec_index, (self.NSize[n] - self.start_patt_rec_index) / self.num_electrodes) for n in range(self.num_neurons): for i in range(self.num_electrodes): # The compartment number which will be recorded comp_idx = self.start_patt_rec_index + i * self.step_patt_rec_index #print "Neuron No ",n, " elec no: ",i," comp num: ",comp_idx self.t_out_vec.append(h.Vector()) self.id_out_vec.append(h.Vector()) exec "self.out_raster.append(h.NetCon(h.neuron" + str( n ) + "_tree[comp_idx](.5)._ref_v, None, sec=h.neuron" + str( n) + "_tree[comp_idx]))" #(.5) self.out_raster[ -1].threshold = 0 #-10 #set threshold to a value of your choice self.out_raster[-1].record(self.t_out_vec[-1], self.id_out_vec[-1], n) # ---------------------------------------------------------------------- # RUN THE SIMULATION: Plot recordings #define the compartments whose activity will be recorded recsize = [] self.rec = [] for n in range(self.num_neurons): self.rec.append([]) recsize.append(int(self.NSize[n] / self.electrodes)) for i in range(self.electrodes): self.rec[n].append(recsize[n] * i) # Initialize the electrodes for e in range(self.electrodes): for n in range(self.num_neurons): exec "self.vrec" + str(n) + str(e) + " = h.Vector()" exec "self.trec" + str(n) + str(e) + " = h.Vector()" exec "self.vrec" + str(n) + str(e) + ".record(h.neuron" + str( n) + "_tree[" + str(self.rec[n][e]) + "](0.5)._ref_v)" exec "self.trec" + str(n) + str(e) + ".record(h._ref_t)" # Finalize initialization h.finitialize(-60) h.dt = self.dt # Run the simulation pixels = len(self.input[0]['frame']) print pixels #print "pix",len(self.input[0]),self.num_pixels self.runtime = self.duration for frame_object in self.input: frame = np.array(frame_object['frame']) print frame for n in range(pixels): self.stimNet[n].ib = self.min_current + 100 * frame[n] * ( self.max_current - self.min_current) neuron.run(self.runtime) self.runtime += self.duration print "Raster stuff:" for i in range(len(self.t_vec)): print "Spikes of neuron", str(i) + ":", len(self.t_vec[i]) return list(self.t_vec), self.sp_trains()
def run(self, modfile='CaPCalyx', color='r', export=False): if isinstance(modfile, list): modfile = modfile[0] if modfile in self.tdur: tstep = self.tdur[modfile] else: tstep = [200., 50.] tdelay = 5.0 Channel = cnmodel.util.Mechanism(modfile) leak = cnmodel.util.Mechanism('leak') Channel.set_parameters({'gbar': 1}) leak.set_parameters({'gbar': 1e-12}) # if modfile == 'nacncoop': # self.soma().nacncoop.p = 0. # self.soma().nacncoop.KJ = 0. # # Channel.set_parameters({'p': 0., 'KJ': 000.}) self.soma = cnmodel.util.Section(L=10, diam=10, mechanisms=[Channel, leak]) if modfile == 'bkpjk': ca_init = 100e-6 self.soma().cai = ca_init else: ca_init = 70e-6 if modfile == 'nacncoop': self.soma().nacncoop.p = 0.1 self.soma().nacncoop.KJ = 1000. # Channel.set_parameters({'p': 0., 'KJ': 000.}) h.celsius = 37. # set the temperature. self.vec = {} for var in ['time', 'V', 'IChan', 'Vcmd']: self.vec[var] = h.Vector() h.dt = 0.025 v_init = -65. clampV = v_init self.vcPost = h.SEClamp(0.5, sec=self.soma) self.vcPost.dur1 = tdelay self.vcPost.amp1 = clampV self.vcPost.dur2 = tstep[0] self.vcPost.amp2 = clampV - 0.0 # just a tiny step to keep the system honest self.vcPost.dur3 = tstep[1] self.vcPost.amp3 = clampV self.vcPost.rs = 1e-9 print "soma: ", self.soma, print ' vcpost sec: ', self.vcPost.Section() if modfile[0:2] == 'ih': stimamp = np.linspace(-140, -40, num=21, endpoint=True) else: stimamp = np.linspace(-100, 60, num=35, endpoint=True) self.ivss = np.zeros((2, stimamp.shape[0])) self.ivmin = np.zeros((2, stimamp.shape[0])) self.ivmax = np.zeros((2, stimamp.shape[0])) print('I range = %6.1f-%6.1f, T = %4.1f' % (np.min(stimamp), np.max(stimamp), h.celsius)) for i, V in enumerate(stimamp): stim = {} stim['NP'] = 1 stim['Sfreq'] = 1 # stimulus frequency stim['delay'] = 5 stim['dur'] = 100 stim['amp'] = V stim['PT'] = 0.0 self.vcPost.amp2 = V self.vec['IChan'].record(self.vcPost._ref_i, sec=self.soma) self.vec['V'].record(self.soma()._ref_v, sec=self.soma) self.vec['time'].record(h._ref_t) # print h.tstop = self.vcPost.dur1 + self.vcPost.dur2 + self.vcPost.dur3 h.finitialize(v_init) h.run() self.t = np.array(self.vec['time']) self.ichan = np.array(self.vec['IChan']) self.v = np.array(self.vec['V']) self.p1.plot(self.t, self.ichan, pen=pg.mkPen((i, len(stimamp) * 1.5))) self.p3.plot(self.t, self.v, pen=pg.mkPen((i, len(stimamp) * 1.5))) (self.ivss[1, i], r2) = Util.measure('mean', self.t, self.ichan, tdelay + tstep[0] - 10., tdelay + tstep[0]) (self.ivmin[1, i], r2) = Util.measure('min', self.t, self.ichan, tdelay + 0.1, tdelay + tstep[0] / 5.0) (self.ivmax[1, i], r2) = Util.measure('max', self.t, self.ichan, tdelay + 0.1, tdelay + tstep[0] / 5.0) self.ivss[0, i] = V self.ivmin[0, i] = V self.ivmax[0, i] = V self.p2.plot(self.ivss[0, :], self.ivss[1, :], symbol='o', symbolSize=4.0, pen=pg.mkPen(color)) self.p2.plot(self.ivmax[0, :], self.ivmax[1, :], symbol='t', symbolSize=4.0, pen=pg.mkPen(color)) self.p5.plot(self.ivmin[0, :], self.ivmin[1, :], symbol='s', symbolSize=4.0, pen=pg.mkPen(color)) print export if export: exporter = pg.exporters.MatplotlibExporter(self.p1) print 'exporting: ' + '%s_traces.svg' % modfile exporter.export(fileName='%s_traces.pdf' % modfile) exporter = pg.exporters.MatplotlibExporter(self.p3) exporter.export('%s_command.pdf' % modfile) exporter = pg.exporters.MatplotlibExporter(self.p2) exporter.export('%s_IV.pdf' % modfile)
rec_v=neuron.h.Vector() rec_v.record(parts['soma'](.5)._ref_v) rec_va=neuron.h.Vector() rec_va.record(parts['distal'](.5)._ref_v) rec_d=neuron.h.Vector() rec_d.record(parts['distal'](1)._ref_v) rec_db=neuron.h.Vector() rec_db.record(parts['distal'](0)._ref_v) rec_t=neuron.h.Vector() rec_t.record(neuron.h._ref_t) neuron.h.finitialize(-65) #self.cell.E neuron.init() neuron.run(500) import numpy as np time=np.array(rec_t) voltage_soma=np.array(rec_v) voltage_axon=np.array(rec_va) voltage_distal=np.array(rec_d) voltage_distal_backup=np.array(rec_db) import matplotlib.pyplot as plt plt.plot(time,voltage_soma,label="soma") plt.plot(time,voltage_axon,label="middle axon") plt.plot(time,voltage_distal,label="distal axon") plt.plot(time,voltage_distal_backup,label="distal axon backup") plt.legend(loc="upper right") plt.show()
from pylab import * # for drawing #h.celsius = 37 # set the temperature cell = h.Section() # create a section (cable) cell.insert('hh') # insert a Hodgkin-Huxley channel vrec = h.Vector() # setup recording Vectors trec = h.Vector() vrec.record( cell(0.5)._ref_v) # record voltage from middle (0.5) of the Section trec.record(h._ref_t) # record time variable h.finitialize(-60) # voltage at initialization, in mV h.dt = 0.025 # 0.025 millisecond timestep neuron.run(1000) # run simulation for 1000 milliseconds plot(np.array(trec), np.array(vrec)) # plot the output using matplotlib xlim((0, h.tstop)) xlabel('Time (ms)') ylabel('v(0.5)') show() data = {} data['vm'] = np.array(vrec) data['t'] = np.array(trec) pickle.dump(data, open('data_model1.pkl', 'w')) # save the output ''' check the saved data: (in the python prompt) x = pickle.load(open('data_model1.pkl')) plt.plot(x['t'],x['vm'])
def run(self, t_max, downsample=1, record_from_syns=False, record_from_iclamps=False, record_from_vclamps=False, record_from_channels=False, record_v_deriv=False, record_concentrations=[], pprint=False): """ Run the NEURON simulation. Records at all locations stored under the name 'rec locs' on `self` (see `MorphTree.storeLocs()`) Parameters ---------- t_max: float Duration of the simulation downsample: int (> 0) Records the state of the model every `downsample` time-steps record_from_syns: bool (default ``False``) Record currents of synapstic point processes (in `self.syns`). Accessible as `np.ndarray` in the output dict under key 'i_syn' record_from_iclamps: bool (default ``False``) Record currents of iclamps (in `self.iclamps`) Accessible as `np.ndarray` in the output dict under key 'i_clamp' record_from_vclamps: bool (default ``False``) Record currents of vclamps (in `self.vclamps`) Accessible as `np.ndarray` in the output dict under key 'i_vclamp' record_from_channels: bool (default ``False``) Record channel state variables from `neat` defined channels in `self`, at locations stored under 'rec locs' Accessible as `np.ndarray` in the output dict under key 'chan' record_v_deriv: bool (default ``False``) Record voltage derivative at locations stored under 'rec locs' Accessible as `np.ndarray` in the output dict under key 'dv_dt' record_from_concentrations: bool (default ``False``) Record ion concentration at locations stored under 'rec locs' Accessible as `np.ndarray` in the output dict with as key the ion's name Returns ------- dict Dictionary with the results of the simulation. Contains time and voltage as `np.ndarray` at locations stored under the name ' rec locs', respectively with keys 't' and 'v_m'. Also contains traces of other recorded variables if the option to record them was set to ``True`` """ assert isinstance(downsample, int) and downsample > 0 # simulation time recorder res = {'t': h.Vector()} res['t'].record(h._ref_t) # voltage recorders res['v_m'] = [] for loc in self.getLocs('rec locs'): res['v_m'].append(h.Vector()) res['v_m'][-1].record(self.sections[loc['node']](loc['x'])._ref_v) # synapse current recorders if record_from_syns: res['i_syn'] = [] for syn in self.syns: res['i_syn'].append(h.Vector()) res['i_syn'][-1].record(syn._ref_i) # current clamp current recorders if record_from_iclamps: res['i_clamp'] = [] for iclamp in self.iclamps: res['i_clamp'].append(h.Vector()) res['i_clamp'][-1].record(iclamp._ref_i) # voltage clamp current recorders if record_from_vclamps: res['i_vclamp'] = [] for vclamp in self.vclamps: res['i_vclamp'].append(h.Vector()) res['i_vclamp'][-1].record(vclamp._ref_i) # channel state variable recordings if record_from_channels: res['chan'] = {} channel_names = self.getChannelsInTree() for channel_name in channel_names: res['chan'][channel_name] = { str(var): [] for var in self.channel_storage[channel_name].statevars } for loc in self.getLocs('rec locs'): for ind, varname in enumerate( self.channel_storage[channel_name].statevars): var = str(varname) # assure xcoordinate is refering to proper neuron section (not endpoint) xx = loc['x'] if xx < 1e-3: xx += 1e-3 elif xx > 1. - 1e-3: xx -= 1e-3 # create the recorder try: rec = h.Vector() exec('rec.record(self.sections[loc[0]](xx).' + mechname[channel_name] + '._ref_' + str(var) + ')') res['chan'][channel_name][var].append(rec) except AttributeError: # the channel does not exist here res['chan'][channel_name][var].append([]) if len(record_concentrations) > 0: for c_ion in record_concentrations: res[c_ion] = [] for loc in self.getLocs('rec locs'): res[c_ion].append(h.Vector()) exec( 'res[c_ion][-1].record(self.sections[loc[\'node\']](loc[\'x\'])._ref_' + c_ion + 'i)') # record voltage derivative if record_v_deriv: res['dv_dt'] = [] for ii, loc in enumerate(self.getLocs('rec locs')): res['dv_dt'].append(h.Vector()) # res['dv_dt'][-1].deriv(res['v_m'][ii], self.dt) # initialize # neuron.celsius=37. h.finitialize(self.v_init) h.dt = self.dt # simulate if pprint: print('>>> Simulating the NEURON model for ' + str(t_max) + ' ms. <<<') start = posix.times()[0] neuron.run(t_max + self.t_calibrate) stop = posix.times()[0] if pprint: print('>>> Elapsed time: ' + str(stop - start) + ' seconds. <<<') runtime = stop - start # compute derivative if 'dv_dt' in res: for ii, loc in enumerate(self.getLocs('rec locs')): res['dv_dt'][ii].deriv(res['v_m'][ii], h.dt, 2) res['dv_dt'][ii] = np.array( res['dv_dt'][ii])[self.indstart:][::downsample] res['dv_dt'] = np.array(res['dv_dt']) # cast recordings into numpy arrays res['t'] = np.array( res['t'])[self.indstart:][::downsample] - self.t_calibrate for key in set(res.keys()) - {'t', 'chan', 'dv_dt'}: if key in res and len(res[key]) > 0: res[key] = np.array([np.array(reslist)[self.indstart:][::downsample] \ for reslist in res[key]]) if key in ('i_syn', 'i_clamp', 'i_vclamp'): res[key] *= -1. # cast channel recordings into numpy arrays if 'chan' in res: for channel_name in channel_names: channel = self.channel_storage[channel_name] for ind0, varname in enumerate(channel.statevars): var = str(varname) for ind1 in range(len(self.getLocs('rec locs'))): res['chan'][channel_name][var][ind1] = \ np.array(res['chan'][channel_name][var][ind1])[self.indstart:][::downsample] if len(res['chan'][channel_name][var][ind1]) == 0: res['chan'][channel_name][var][ ind1] = np.zeros_like(res['t']) res['chan'][channel_name][var] = \ np.array(res['chan'][channel_name][var]) # compute P_open # sv = np.zeros((len(channel.statevars), len(self.getLocs('rec locs')), len(res['t']))) sv = {} for varname in channel.statevars: var = str(varname) sv[var] = res['chan'][channel_name][var] res['chan'][channel_name]['p_open'] = channel.computePOpen( res['v_m'], **sv) return res
def initAndRun(self, reset_V=-65): nrn.h.finitialize(reset_V) nrn.init() nrn.run(self.tStop)
tstop = 200 v_init = -65 soma = h.Section() soma.diam = 30 soma.L = 30 soma.insert('hh') cvode = h.CVode() cvode.active(1) cvode.atol(1.0e-5) vv = h.Vector() tv = h.Vector() vv.record(soma(0.5)._ref_v) tv.record(h._ref_t) h.finitialize(v_init) h.fcurrent() neuron.run(tstop) ax = plt.subplot() ax.set_ylim([-80, 40]) ax.plot(tv.as_numpy(), vv.as_numpy()) plt.xlabel('Time (ms)') plt.ylabel('potential (mV)') plt.savefig('./figs/n01.pdf') plt.show()
rec_ina = h.Vector() rec_ina.record(muscle(0.5)._ref_ina) rec_ik = h.Vector() rec_ik.record(muscle(0.5)._ref_ik) rec_ica = h.Vector() rec_ica.record(muscle(0.5)._ref_ica) h.dt=0.05 h.finitialize(-70.0) neuron.init() sim_time=2000 if sim_time: neuron.run(sim_time) else: neuron.run(sim_time) x=np.array(rec_t) y=np.array(rec_v) plt.figure(1) plt.subplot(411) plt.plot(x,y) na=np.array(rec_ina) plt.subplot(412) plt.plot(x,na) k=np.array(rec_ik)
# You can play with the NEURON-gui by typing # >>> from neuron import gui # For an overview (gui menu bar): Tools -> Model View -> 1 real cell -> root... # Record Time from NEURON (neuron.h._ref_t) rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) # Record Voltage from the center of the soma rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) neuron.h.finitialize(-60) neuron.init() neuron.run(5) # Plot the recordings with matplotlib # =================================== import matplotlib.pyplot as plt # get values from NEURON-vector format into Python format times = [] # Use list to add another trace later. voltages = [] times.append(list(rec_t)) # alternativ to `list(rec_t)`: `numpy.array(rec_t)` voltages.append(list(rec_v)) # check types by: # >>> type(rec_t) # >>> type(time[0])
def calc_hh(dt = 25, method='cnexp', show_plot=False): ''' dt = (int) [micro sec] method = cnexp | impl | euler | runge show_plot = True | False ''' filename_template = 'hh_%s_%04d.txt' filename = filename_template % (method, dt) h = neuron.hoc.HocObject() h('nrn_load_dll("./mod/x86_64/.libs/libnrnmech.so")') soma = neuron.h.Section(name="soma") soma.nseg = 3 # odd number soma.diam = 10 # [um] soma.L = 10 # [um] if method == 'cnexp': soma.insert("hh_cnexp") meca = soma(0.5).hh_cnexp elif method == 'impl': soma.insert("hh_impl") meca = soma(0.5).hh_impl elif method == 'euler': soma.insert("hh_euler") meca = soma(0.5).hh_euler elif method == 'runge': soma.insert("hh_runge") meca = soma(0.5).hh_runge else: print 'wrong method.' quit() stim = neuron.h.IClamp(soma(0.5)) stim.delay = 50 # [ms] stim.dur = 200 # [ms] stim.amp = 0.15 # [nA] rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) neuron.h.finitialize(-65) tstop = 300 neuron.h.dt = float(dt)/1000. neuron.h.secondorder = 2 neuron.run(tstop) print "dt = %f" % neuron.h.dt # convert neuron array to numpy array time = rec_t.as_numpy() voltage = rec_v.as_numpy() f = open(filename, 'w') f.write('# %s\n' % filename) f.write('# dt = %d [usec]\n' % dt) f.write('# t [usec], V [mV]\n') for i in range(len(time)): checked_time = int((int(time[i]*1000)+1)/10) * 10 f.write("%d, %f\n" % (checked_time, voltage[i])) f.close() # show graph by matplotlib if show_plot == True: plt.plot(time, voltage, color='b') plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]") plt.axis(xmin=0, xmax=max(time), ymin=min(voltage)-5, ymax=max(voltage)+5) plt.show()
v = neuron.h.Vector() v.record(cell.soma(0.5)._ref_v) apcount = neuron.h.APCount(cell.soma(0.5)) spikes = neuron.h.Vector() apcount.record(neuron.h.ref(spikes)) freqs = np.linspace(10, 100, 9) weights = np.linspace(0.01, 0.05, 100) lower = [] upper = [] for f in freqs: outfreqs = [] for w in weights: nc.weight[0] = w neuron.init() for i in range(int(f)): nc.event(200 + i * 1000.0 / f) neuron.run(1500) outfreqs.append(len(spikes)) outfreqs = np.array(outfreqs) lower.append(weights[np.where(outfreqs > 1)[0][0]]) upper.append(weights[np.where(outfreqs >= f)[0][0]]) import matplotlib.pyplot as plt plt.plot(freqs, lower) plt.plot(freqs, upper) plt.savefig('plots/synfreq.pdf')
def calc_hh(dt=25, method='cnexp', show_plot=False): """ dt = (int) [micro sec] method = cnexp | impl | euler | runge show_plot = True | False """ filename_template = './result/hh_%s_%04d.txt' filename = filename_template % (method, dt) h = neuron.hoc.HocObject() h('nrn_load_dll("./mod/x86_64/.libs/libnrnmech.so")') soma = neuron.h.Section(name="soma") soma.nseg = 1 # odd number soma.diam = 10 # [um] soma.L = 10 # [um] if method == 'cnexp': soma.insert("hh_cnexp") meca = soma(0.5).hh_cnexp elif method == 'impl': soma.insert("hh_impl") meca = soma(0.5).hh_impl elif method == 'euler': soma.insert("hh_euler") meca = soma(0.5).hh_euler elif method == 'runge': soma.insert("hh_runge") meca = soma(0.5).hh_runge else: print('wrong method.') quit() stim = neuron.h.IClamp(soma(0.5)) stim.delay = 50 # [ms] stim.dur = 200 # [ms] stim.amp = 0.10 # [nA] neuron.h.psection() rec_t = neuron.h.Vector() rec_t.record(neuron.h._ref_t) rec_v = neuron.h.Vector() rec_v.record(soma(0.5)._ref_v) neuron.h.finitialize(-65) tstop = 300 neuron.h.dt = float(dt) / 1000. # neuron.h.secondorder = 2 neuron.run(tstop) print("dt = %f" % neuron.h.dt) # convert neuron array to numpy array time = rec_t.as_numpy() voltage = rec_v.as_numpy() with open(filename, 'w') as f: f.write('# %s\n' % filename) f.write('# dt = %d [usec]\n' % dt) f.write('# t [usec], V [mV]\n') for i in range(len(time)): # checked_time = int((int(time[i]*10000)+1)/10) * 10 if dt < 10: checked_time = int(time[i] * 1000) else: checked_time = int((int(time[i] * 1000) + 1) / 10) * 10 f.write("%d, %f\n" % (checked_time, voltage[i])) # show graph by matplotlib if show_plot: plt.plot(time, voltage, color='b') plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]") plt.axis(xmin=0, xmax=max(time), ymin=min(voltage) - 5, ymax=max(voltage) + 5) plt.show()