def passive_soma(quad, show=False): """ Creates the model with basic pyramidal passive properties. """ # Load the hoc into neuron h('xopen(%s)' %quad.hocfile) h.load_file('stdrun.hoc') seclist = list(h.allsec()) for sec in seclist: sec.insert('pas') sec.Ra = 200. # Current injection into soma or tip soma_sec = return_soma_seg(quad, h) stim_loc = 0. stim = h.IClamp(stim_loc, sec=soma_sec) stim.delay = 1 # ms stim.dur = 1 # ms stim.amp = 20 # nA # Run sim and record data (v, labels) = ez_record(h) # PyNeuron to record all compartments t, I = h.Vector(), h.Vector() t.record(h._ref_t) I.record(stim._ref_i) h.init() h.tstop = 10 # s? h.run() v = ez_convert(v) # Convert v to numpy 2D array # If show, plot, else just return v if show:
def run_syn(self): # initiate recording rec_t = h.Vector() rec_t.record(h._ref_t) rec_v = h.Vector() rec_v.record(h.somaA(0.5)._ref_v) rec_v_dend = h.Vector() rec_v_dend.record(self.dendrite(self.xloc)._ref_v) print "- running model", self.name # initialze and run #h.load_file("stdrun.hoc") h.stdinit() dt = 0.025 h.dt = dt h.steps_per_ms = 1 / dt h.v_init = -65 h.celsius = 34 h.init() h.tstop = 300 h.run() # get recordings t = numpy.array(rec_t) v = numpy.array(rec_v) v_dend = numpy.array(rec_v_dend) return t, v, v_dend
def calc_rise_and_width(PLOT_MODE=0): Vvec = h.Vector() Vvec.record(HCell.soma[0](0.5)._ref_v) h.init(h.v_init) h.run() np_v = np.array(Vvec) max_idx = np.argmax(np_v) rise_time = max_idx * DT - Stim1.start half_v = E_PAS + (np_v[max_idx] - E_PAS) / 2.0 for i in range(max_idx): if np_v[i] > half_v: rise_half = i * h.dt break for i in range(max_idx, np_v.size): if np_v[i] < half_v: decay_half = i * h.dt break half_width = decay_half - rise_half if PLOT_MODE: print "rise ,", rise_time, " half width ", half_width np_t = np.arange(0, h.tstop + h.dt, h.dt) print np_v.size, np_t.size plt.plot(np_t, np_v, 'b') plt.plot(np_t[max_idx], np_v[max_idx], 'b*') plt.plot(np.array([rise_half, decay_half]), np.array([half_v, half_v]), 'r') plt.show() return rise_time, half_width
def run_cclamp_somatic_feature(self, section_rec, loc_rec): exec("self.sect_loc=h." + str(section_rec) + "(" + str(loc_rec) + ")") print "- running model", self.name rec_t = h.Vector() rec_t.record(h._ref_t) rec_v = h.Vector() rec_v.record(self.sect_loc._ref_v) h.stdinit() dt = 0.025 h.dt = dt h.steps_per_ms = 1 / dt h.v_init = -65 h.celsius = 34 h.init() h.tstop = 1600 h.run() t = numpy.array(rec_t) v = numpy.array(rec_v) return t, v
def runSimulation(young_chem1_con1, young_elec1_con1, numNeurons, young, fileIndex): """ This defintion will run the simulation. """ print 'Run simulation!!' #Create neurons in the networks. numSegs = 3 Neurons = [] for i in range(0, numNeurons): Neurons.append(h.Section()) #Set biophysics for the different neural structures. IAF will contain all data pertaining to the refractory period between spikes. for sec in Neurons: sec.insert('hh') sec.nseg = numSegs #Import connectivity between neurons. gapsYoung = constructConnections1(young_elec1_con1, numNeurons, Neurons) synYoung, ncYoung = constructConnections2(young_chem1_con1, numNeurons, Neurons) #Create vectors for recording potentials, currents, etc in the neural network during the simulation. vec = recordData(numNeurons, Neurons) #Stimulate system with random noise. stims = [] for i in range(0, numNeurons): stims.append(makeStimulus(Neurons[i], simTime)) #Run the simulation. h.load_file("stdrun.hoc") h.init() h.tstop = simTime h.run() #Simplify the files and write out the data of neural ID and spike times. canFire = [] for i in range(0, numNeurons): canFire.append(1) if young == 1: file = open(path + 'spikesYoung' + fileIndex + '.txt', "wb") else: file = open(path + 'spikesOld' + fileIndex + '.txt', "wb") print "Writing results..." for i in range(0, len(vec['t '])): for j in range(0, numNeurons + 1): for var in vec: if (var == str(j + 1)): if (vec[var][i] > 0) & (canFire[j] == 1): file.write(str(j + 1) + "\n") file.write(str(vec['t '][i]) + "\n") canFire[j] = 0 if (vec[var][i] < 0): canFire[j] = 1 file.close() #Destroy neuron sections. Neurons = []
def test(infile='/data/rays3/ggn/olfactory_network/mb_net_UTC2018_09_19__00_49_12-PID4273-JID9673664.h5'): with h5.File(infile, 'r') as fd: pn_spikes = load_pn_spikes(fd) pns, spikes = zip(*pn_spikes) spikes[0] = np.array([1.0, 10.0, 20.0]) stimvecs, vecstims = create_pn_output(spikes) kcs = create_kcs(fd) kc_name_sec_dict = {kc.soma.name(): kc.soma for kc in kcs} ggn = create_ggn() ggn_name_sec_dict = {sec.name(): sec for sec in ggn.all} nc_pn_kc, syn_pn_kc = create_pn_kc_conn(fd, {pn: vecstim for pn, vecstim in zip(pns, vecstims)}, kc_name_sec_dict) for nc in nc_pn_kc: assert nc.valid() syn_ggn_kc = create_ggn_kc_conn(fd, kc_name_sec_dict, ggn_name_sec_dict) syn_kc_ggn, nc_kc_ggn = create_kc_ggn_conn(fd, kc_name_sec_dict, ggn_name_sec_dict, path=kc_ggn_alphaL_syn_path) # kc_st = {kc: np.random.random_sample(5) for kc in np.random.choice(kcs, size=5, replace=False)} # pn_st = {pn: np.random.random_sample(5) for pn in np.random.choice(pns, size=5, replace=False)} # ggn_vm = {sec: np.arange(10) for sec in np.random.choice(list(ggn_name_sec_dict.keys()), # size=5, replace=False)} # kc_vm = {kc: np.random.random_sample(5) for kc in np.random.choice(kcs, size=5, replace=False)} data = setup_recording(kcs, ggn, n_kc_vm=10, n_ggn_vm=10, t=0.25) h.tstop = 100 h.init() h.run() kc_st = {kc: st for kc, (nc, st) in data['kc_spikes'].items()} save(infile, 'test.h5', kc_st, pn_spikes, data['kc_vm'], data['ggn_output_vm'], data['ggn_alphaL_input_vm'], data['ggn_basal_vm'], None, data['time']) cfg.logger.info('finished')
def run_and_save_simulation(shaft_ref, x_shaft, on_spine=False, PLOT_RES=1): V_Shaft = h.Vector() V_Soma = h.Vector() tvec = h.Vector() V_Soma.record(HCell.soma[0](0.5)._ref_v) V_Shaft.record(shaft_ref.sec(x_shaft)._ref_v) tvec.record(h._ref_t) if on_spine: V_Spine = h.Vector() V_Spine.record(HCell.spine[1](1)._ref_v) h.v_init = V_INIT h.init(h.v_init) h.run() if (PLOT_RES > 0): if on_spine: plt.close('all') plt.plot(np.array(tvec), np.array(V_Soma), c=c_soma) plt.plot(np.array(tvec), np.array(V_Shaft), c=c_shaft) if on_spine: plt.plot(np.array(tvec), np.array(V_Spine), c=c_spine) plt.xlim(0, 50) M = np.array([ np.array(tvec), np.array(V_Soma), np.array(V_Shaft), np.array(V_Spine) ]).T np.savetxt("example_stimulation of_a_spine_connected_to_dend_62.txt", M)
def insert(self): h = self.h if not hasattr(h, 'cvode'): h.load_file('stdrun.hoc') if not h.cvode.use_fast_imem(): h.cvode.use_fast_imem(1) h.init() if self.method == 'Point': LfpClass = SectionLfpPointMethod elif self.method == 'Line': LfpClass = SectionLfpLineMethod else: # self.method == 'RC': LfpClass = SectionLfpRCMethod for sec in self.sec_list: # h.allsec(): if self.is_lfp_section(sec.name()): # Let NEURON create 3D points if missing if h.n3d(sec=sec) <= 0: h.define_shape(sec=sec) # Keep track of sections being monitored self.section_lfps[sec] = LfpClass(self, sec)
def run_vclamp( self, vc_range, tstop=50.0, ): h.load_file('stdrun.hoc') rec = {} for label in 't', 'v', 'i': rec[label] = h.Vector() rec['t'].record(h._ref_t) rec['i'].record(self.clamp._ref_i) rec['v'].record(self.root(0.5)._ref_v) v_list, i_list, t_list = [], [], [] h.tstop = tstop h.celsius = 32.0 for vc in vc_range: h.init() #h.finitialize(v_init) self.clamp.amp2 = vc h.run() i = rec['i'].to_python() v = rec['v'].to_python() t = rec['t'].to_python() v_list.append(v) i_list.append(i) t_list.append(t) v = np.array(v_list).transpose() i = np.array(i_list).transpose() t = np.array(t_list).transpose() return v, i, t
def run_exp(): h.init(h.v_init) Vvec = h.Vector() Vvec.record(h.cell.soma[0](0.5)._ref_v) h.run() return Vvec
def run_cclamp(self): print "- running model", self.name rec_t = h.Vector() rec_t.record(h._ref_t) rec_v = h.Vector() rec_v.record(h.soma(0.5)._ref_v) h.stdinit() dt = 0.025 h.dt = dt h.steps_per_ms = 1 / dt h.v_init = -65 h.celsius = 34 h.init() h.tstop = 1600 h.run() t = numpy.array(rec_t) v = numpy.array(rec_v) return t, v
def corrected_experimental_protocol_with_linear_gpas_distr( Ra=157.3621, gpas_soma=0.000403860792, k=0.001, cm=3., dt=0.1): # -- Biophysics -- # Sec parameters and conductance for sec in h.allsec(): sec.Ra = Ra # Ra is a parameter to infer sec.cm = cm # parameter optimisation algorithm found this sec.v = 0 sec.insert('pas') sec.g_pas = gpas_soma # gpas is a parameter to infer for seg in sec: h('soma distance()') dist = (h.distance(seg.x)) gpas = gpas_soma * (1 + k * dist) if gpas < 0: seg.g_pas = 0 print("WARNING!!! 'gpas' is in negative! Corrected to zero.") else: seg.g_pas = gpas sec.e_pas = 0 # Print information #h.psection() # Stimulus stim1 = h.IClamp(h.soma(0.01)) stim1.delay = 199.9 stim1.amp = 0.5 stim1.dur = 3.1 stim2 = h.IClamp(h.soma(0.01)) stim2.delay = 503 stim2.amp = 0.01 stim2.dur = 599.9 # Run simulation -> # Set up recording Vectors v_vec = h.Vector() # Membrane potential vector t_vec = h.Vector() # Time stamp vector v_vec.record(h.soma(0.5)._ref_v) t_vec.record(h._ref_t) # Simulation duration and RUN h.tstop = (15000 - 1) * dt # Simulation end h.dt = dt # Time step (iteration) h.steps_per_ms = 1 / dt h.v_init = 0 h.finitialize(h.v_init) h.init() h.run() t = t_vec.to_python() v = v_vec.to_python() return t, v
def run_exp(HCell, h): h.init(h.v_init) Vvec = h.Vector() Vvec.record(HCell.soma[0](0.5)._ref_v) h.run() np_v = np.array(Vvec) np_v = np_v[1:] # remove the 0 timing that is not part of the EPSPs data return np_v
def runSimulation(young_chem1_con1, young_elec1_con1, numNeurons, fileIndex, simTime, inhibInd, age, delay, stimInterval, con): """ This defintion will run the simulation. """ print 'Run simulation!!' # Load file to make model regular spiking excitory cells. h.load_file ("sPY_template") # Load file to make model fast spiking inhibitory cells. h.load_file ("sIN_template") #Create neurons in the networks. numSegs = 3 Neurons = [] for i in range(0, numNeurons): if i < inhibInd: neuron = h.sPY() Neurons.append(neuron) else: neuron = h.sIN() Neurons.append(neuron) #Import connectivity between neurons. gapsYoung = constructConnections1( young_elec1_con1, numNeurons, Neurons) synYoung,ncYoung = constructConnections2( young_chem1_con1, numNeurons, Neurons, inhibInd, delay ) #Create vectors for recording potentials, currents, etc in the neural network during the simulation. vec = recordData( numNeurons, Neurons ) #Stimulate system with random noise. stims = [] for i in range(0,numNeurons): stims.append(makeStimulus(Neurons[i],simTime,int(stimInterval))) #Run the simulation. h.load_file("stdrun.hoc") h.init() h.tstop = simTime h.run() #Write results. file = open(path + 'spikes' + str(con) + '_' + str(age) + '_' + str(fileIndex) + '_' + str(stimInterval) + '.txt',"wb") print "Writing results to..." print file for j in range(0,numNeurons): canFire = 1 var = str(j+1) for i in range(0,len(vec ['t '])): if (vec[var][i] > 0) & (canFire == 1): file.write(str(j+1)+"\n") file.write(str(vec['t '][i])+"\n") canFire = 0 if (vec[var][i] < 0): canFire = 1 file.close()
def real_morphology_model_srsoma_rdend(stim, gpas=0.0001, Ra=100., cm=1., dt=0.1): # -- Biophysics -- # Sec parameters and conductance for sec in h.allsec(): sec.Ra = Ra # Ra is a parameter to infer sec.cm = cm # parameter optimisation algorithm found this sec.v = 0 sec.insert('pas') sec.g_pas = gpas # gpas is a parameter to infer sec.e_pas = 0 # Print information # h.psection() h.dt = dt # Time step (iteration) h.steps_per_ms = 1 / dt # Stimulus h.tstop = len(stim) * dt h.load_file("vplay.hoc") vec = h.Vector(stim) istim = h.IClamp(h.soma(0.5)) vec.play(istim._ref_amp, h.dt) istim.delay = 0 # Just for Neuron istim.dur = 1e9 # Just for Neuron # Run simulation -> # Set up recording Vectors vs_vec = h.Vector() # Membrane potential vector vd_vec = h.Vector() t_vec = h.Vector() # Time stamp vector vd_vec.record(h.apic[30](0.5)._ref_v) vs_vec.record(h.soma(0.5)._ref_v) t_vec.record(h._ref_t) # Simulation duration and RUN # h.tstop = 1200 # Simulation end h.v_init = 0 h.finitialize(h.v_init) h.init() h.run() t = t_vec.to_python() v_soma = vs_vec.to_python() v_dend = vd_vec.to_python() v_soma = np.array(v_soma) v_dend = np.array(v_dend) v = np.concatenate((v_soma, v_dend)) return t, v
def go(self): self.set_recording() h.dt = self.dt h.tstop = self.sim_time h.finitialize(-60)#self.v_init) h.init() h.run() self.rec_i = self.rec_ina.to_python()
def real_morphology_model_2(stim, gpas=0.0001, Ra=100., ffact=1., dt=0.1): # -- Biophysics -- # Sec parameters and conductance for sec in h.allsec(): sec.Ra = Ra # Ra is a parameter to infer sec.cm = 1 # parameter optimisation algorithm found this sec.v = -69.196 sec.insert('pas') for seg in sec: seg.g_pas = gpas # gpas is a parameter to infer seg.e_pas = -69.196 for sec in h.basal: sec.cm *= ffact for seg in sec: seg.g_pas *= ffact for sec in h.apical: sec.cm *= ffact for seg in sec: seg.g_pas *= ffact # Print information # h.psection() h.dt = dt # Time step (iteration) h.steps_per_ms = 1 / dt # Stimulus h.tstop = len(stim) * dt h.load_file("vplay.hoc") vec = h.Vector(stim) istim = h.IClamp(h.apic[93](0.5)) vec.play(istim._ref_amp, h.dt) istim.delay = 0 # Just for Neuron istim.dur = 1e9 # Just for Neuron # Run simulation -> # Set up recording Vectors v_vec = h.Vector() # Membrane potential vector t_vec = h.Vector() # Time stamp vector v_vec.record(h.apic[93](0.5)._ref_v) t_vec.record(h._ref_t) # Simulation duration and RUN # h.tstop = 1200 # Simulation end h.v_init = 0 h.finitialize(h.v_init) h.init() h.run() t = t_vec.to_python() v = v_vec.to_python() return t, v
def runSimulation_v1(young_chem1_con1, young_elec1_con1, numNeurons, fileIndex, simTime, inhibInd, age, delay): """ This defintion will run the simulation. """ print 'Run simulation!!' #Create neurons in the networks. numSegs = 3 Neurons = [] for i in range(0, numNeurons): Neurons.append(h.Section()) #Set biophysics for the different neural structures. IAF will contain all data pertaining to the refractory period between spikes. for sec in Neurons: sec.insert('hh') sec.nseg = numSegs #Import connectivity between neurons. synYoung, ncYoung = constructConnections2(young_chem1_con1, numNeurons, Neurons, inhibInd, delay) #Create vectors for recording potentials, currents, etc in the neural network during the simulation. vec = recordData(numNeurons, Neurons) #Stimulate system with random noise. stims = [] for i in range(0, numNeurons): stims.append(makeStimulus(Neurons[i], simTime)) #Run the simulation. h.load_file("stdrun.hoc") h.init() h.tstop = simTime h.run() #Write results. if age == 1: file = open(path + 'spikesYoung_1_' + fileIndex + '.txt', "wb") elif age == 2: file = open(path + 'spikesOld1_1_' + fileIndex + '.txt', "wb") else: file = open(path + 'spikesOld2_1_' + fileIndex + '.txt', "wb") print "Writing results to..." print file for j in range(0, numNeurons): canFire = 1 var = str(j + 1) for i in range(0, len(vec['t '])): if (vec[var][i] > 0) & (canFire == 1): file.write(str(j + 1) + "\n") file.write(str(vec['t '][i]) + "\n") canFire = 0 if (vec[var][i] < 0): canFire = 1 file.close()
def find_vrest(h, section_name): h.load_file("stdrun.hoc") tstop = 100 h.dt = dt = 0.1 soma, sec = fetch_soma_sec(section_name) h.init() h.cvode.re_init() t_vec, soma_vm, sec_vm = record(soma, sec) h.execute('tstop = 100') h.run() vrest = np.array(sec_vm)[-1] return vrest
def run_and_save_simulation(c='r'): V_Soma = h.Vector() tvec = h.Vector() V_Soma.record(HCell.soma[0](0.5)._ref_v) tvec.record(h._ref_t) h.v_init = V_INIT h.init(h.v_init) h.run() plt.plot(np.array(tvec), np.array(V_Soma) - E_PAS, c=c)
def run(self): self.reset() h.init() h.tstop = self.t_trial # print("-------------------------- Run NEURON simulation ----------------------------") start_time = time.time() for i in range(self.n_trials): h.run() self.extract_values() self.run_time = time.time() - start_time # print("-------------------------- End NEURON simulation ----------------------------") Simulation.run(self)
def myrun(): clockStart = clock() if h.t > 0: # was this sim run already? if ip3_stimT == 0: place_ip3_stim(minx=stim_minx, maxx=stim_maxx, IP3Stim=ip3_stim) if ca_stimT == 0: place_ca_stim(minx=stim_minx, maxx=stim_maxx, CAStim=ca_stim) print "starting simulation..." initrec( ) # initialize recording data structures - does not create any events or call Vector record h.init() # contains a call to h.finitialize # must setup hotspots after h.init/h.finitialize, otherwise the rxd.Parameter initial values are set/used place_branch(minx=dend.L / 2 - boost_halfw, maxx=dend.L / 2 + boost_halfw, IP3Origin=ip3_origin, ERScale=er_scale) set_boost(BoostEvery=boost_every) if loadState: loadstate(statestr) # load initial values from saved file (hoc/rxd) elif useInitDict: setHocStateVars(fcfg) # load initial values from config file setRxDStateVars(fcfg) else: # make sure ca[er].concentration initialized cae_init = (caAvg_init - caCYT_init * fc) / fe ca[er].concentration = cae_init h.cvode.re_init() if IP3ForceInit: ip3[cyt].concentration = ip3_init h.cvode.re_init() print '\ntstart:', tstart, ' tstop:', tstop, 'h.tstop:', h.tstop # only set event if supposed to place stim(s) after t=0 (otherwise already set above) if ip3_stimT > 0: h.cvode.event(tstart + ip3_stimT, place_ip3_stim) # put an event on queue to set ip3 stim if ca_stimT > 0: h.cvode.event(tstart + ca_stimT, place_ca_stim) # put an event on queue to set ca stim for t in numpy.arange(tstart, tstop, recdt): h.cvode.event(t, dorecord) for t in numpy.arange(tstart, tstop, 500): h.cvode.event(t, displaySimTime) #displays h.t every 500 msec # set synapse properties based on specification in config file - only changing number,active seems to work # using FInitializeHandler type 2,3 did not help if electrical: setSynProps() h.continuerun(tstop) # does not guarantee that tstop is reached while h.t < tstop: h.advance() # make sure get to tstop #print 'ran from ' , timeVec[0], ' to ', timeVec[1], ' to ', timeVec[-1] #printt('final time') clockEnd = clock() print '\nsim runtime:', str( datetime.timedelta(seconds=clockEnd - clockStart)), 'secs' #format s as hh:mm:ss
def run_simulation(): V_Soma = h.Vector() tvec = h.Vector() V_Soma.record(HCell.soma[0](0.5)._ref_v) tvec.record(h._ref_t) h.v_init = V_INIT h.init (h.v_init) h.run() return np.array(V_Soma)
def run_simulation(self, update_dt=None): # update_dt is an optional parameter that allows to breakdown a lengthy simulation into shorter chunks for more responsiveness h.init() h.finitialize(h.v_init) flag = True if h.t + h.dt < h.tstop else False sim_output = None while flag: flag = True if h.t + h.dt < h.tstop and update_dt else False h.continuerun( min(h.tstop, h.t + (update_dt if update_dt else h.tstop))) sim_output = self.model.get_data() return sim_output
def run_exp(): h.init(h.v_init) h.run() np_v_soma = np.array(v_soma) np_v_axon_0 = np.array(v_axon_0) np_v_axon_1 = np.array(v_axon_1) np_t = np.array(tvec) return np_t, np_v_soma, np_v_axon_0, np_v_axon_1
def run_simulation(): V_Soma = h.Vector() V_Dend = h.Vector() tvec = h.Vector() V_Soma.record(HCell.soma[0](0.5)._ref_v) V_Dend.record(HCell.dend[DEND_SEC](DEND_X)._ref_v) tvec.record(h._ref_t) h.v_init = V_INIT h.init(h.v_init) h.run() return np.array(tvec), np.array(V_Soma), np.array(V_Dend)
def custom_cable(length=526., tiprad=1.4, somarad=15.4, inj=1.2, tinj=1., injloc=1., Ra=35.4): """ Simulate a simple passive current injection. Length=um, rads=um, inj=nA, tinj=ms, injloc=1 (tip). Recorded from all 11 segments. """ # Set up model h.load_file('stdrun.hoc') cell = h.Section() cell.nseg = 11 # It is a good idea to have nseg be an odd number cell.Ra = 35.4 # Ohm*cm cell.insert('pas') # Create structure h.pt3dadd(0,0,0,somarad,sec=cell) h.pt3dadd(length,0,0,tiprad,sec=cell) stim = h.IClamp(injloc, sec=cell) stim.delay = 5 # ms stim.dur = tinj # ms stim.amp = inj # nA print("Stim: %.2f nA, %.2f ms, at location %.2f" %(stim.amp, stim.dur, injloc)) # Segment positions, equall spaced from 0 to 1 seg_positions = np.linspace(0,1,cell.nseg) # Use toolbox to record v # ez_record records v in all compartments by default (v,v_labels) = ez_record(h) # Manually record time and current t, I = h.Vector(), h.Vector() t.record(h._ref_t) I.record(stim._ref_i) # Run the simulation h.init() h.tstop = 30 h.run() # Use toolbox convert v into a numpy 2D array v = ez_convert(v) # Plotting options fig = plt.figure() for i in range(cell.nseg): t = [v[u][i] for u in range(len(v))] ax = fig.add_subplot(cell.nseg, 1, i+1) ax.plot(t) plt.show() return h, v
def main(args): global nseg, nchan, simulator, _args _args = args loadModel(args.swc_file, args) print("Done loading") h.init() print("[INFO] Running NEURON for %s sec" % args.sim_time) t1 = time.time() h.tstop = 1e3 * float(args.sim_time) h.run() t = time.time() - t1 print("Time taken by neuron: %s sec" % t) makePlots()
def __init__(self, model_name, tstop=20.0): if model_name != "": if not (os.path.isfile(model_name)): raise AttributeError( u"File: {0:s} doesn't exist please check the path to the file or name of file".format(model_name)) h.load_file(model_name) h.init() h.tstop = tstop self.out_data = {} self.neurons = {AVM: MyNeuron(AVM), ALML: MyNeuron(ALML), ALMR: MyNeuron(ALMR)} # Initialization of segments and data arrays for k, val in self.neurons.iteritems(): val.init_sections(h, paramVec) else: raise ValueError("Name of file with Model shouldn't be empty")
def run_and_save_simulation(HCell, shaft_ref, x_shaft, f_output, on_spine=False, PLOT_RES=0): V_Shaft = h.Vector() V_Soma = h.Vector() tvec = h.Vector() V_Soma.record(HCell.soma[0](0.5)._ref_v) V_Shaft.record(shaft_ref.sec(x_shaft)._ref_v) tvec.record(h._ref_t) if on_spine: V_Spine = h.Vector() V_Spine.record(HCell.spine[1](1)._ref_v) h.v_init = V_INIT h.init(h.v_init) h.run() if (PLOT_RES > 0): if on_spine: plt.close('all') plt.plot(np.array(tvec), np.array(V_Soma), c='g') plt.plot(np.array(tvec), np.array(V_Shaft), c='r') if on_spine: plt.plot(np.array(tvec), np.array(V_Spine), c='m') if on_spine: f_output.write("1,") else: f_output.write("0,") f_output.write("%s,%0.3f," % (shaft_ref.sec.name(), x_shaft)) if on_spine: f_output.write("%g,%g,%g," % (V_Soma.max(), V_Shaft.max(), V_Spine.max())) f_output.write("%g,%g,%g," % (V_Soma.sub(V_INIT).sum(), V_Shaft.sub(V_INIT).sum(), V_Spine.sub(V_INIT).sum())) else: f_output.write("%g,%g,%g," % (V_Soma.max(), V_Shaft.max(), 0)) f_output.write( "%g,%g,%g," % (V_Soma.sub(V_INIT).sum(), V_Shaft.sub(V_INIT).sum(), 0))
def passive_cable(stimloc=1., stimdur=5., show=False): """ This simulates a pulse injected into a simple passive cable. """ # Set up model h.load_file('stdrun.hoc') cell = h.Section() cell.nseg = 11 # It is a good idea to have nseg be an odd number cell.Ra = 35.4 # Ohm*cm cell.insert('pas') # create 3d structure h.pt3dadd(0,0,0,1.0,sec=cell) h.pt3dadd(1732,1732,1732,1.0,sec=cell) # Specify current injection stim = h.IClamp(stimloc,sec=cell) # Stim @ 1th end of segment stim.delay = 5 # ms stim.dur = stimdur # ms stim.amp = 0.2 # nA print("Stim: %.2f nA, %.2f ms, at location %.2f" %(stim.amp, stim.dur, stimloc)) # Segment positions, equall spaced from 0 to 1 seg_positions = np.linspace(0,1,cell.nseg) # Use toolbox to record v # ez_record records v in all compartments by default (v,v_labels) = ez_record(h) # Manually record time and current t, I = h.Vector(), h.Vector() t.record(h._ref_t) I.record(stim._ref_i) # Run the simulation h.init() h.tstop = 30 h.run() # Use toolbox convert v into a numpy 2D array v = ez_convert(v) # Plotting options if show: fig = plt.figure() for i in range(cell.nseg): t = [v[u][i] for u in range(len(v))] ax = fig.add_subplot(cell.nseg, 1, i+1) ax.plot(t) plt.show() return h, v
def response(x): if x.shape != (10000, ): print('your input curent must be an array of shape (1000,) ') print(h.PY[0]) stim = h.IClamp(0.5, sec=h.PY[0].soma[0]) stim.delay = 0 #necessary to choose the Iclamp see documentation. stim.dur = 1e9 ramp = h.Vector(x) ramp.play(stim._ref_amp, 0.1) vm = h.Vector() vm.record(h.PY[0].soma[0](0.5)._ref_v) h.init() print(h.t) h.run() print(h.t) return np.array(vm)
def runModel(tstop,recorders = None,parameters = None,vectorparameters = None,verbose = False): ''' Clears the recorders. Passes parameters to NEURON. Initializes the model and runs until tstop. ''' # print "Resetting model." for ii in recorders.itervalues(): ii.clear() h.rec_electrode.clear() passValuesToNeuron(parameters,verbose) passValuesToNeuron(vectorparameters,vectorparameters.keys(),verbose) h('resetModel()') h.initialize() h.init() h.continuerun(tstop)
def run_exp(HCell, config): Vsoma = h.Vector() Vsoma.record(HCell.soma[0](.5)._ref_v) tvec = h.Vector() tvec.record(h._ref_t) apc = h.APCount(0.5, sec=HCell.soma[0]) apc.thresh = 0 apc.time = 10000000. h.init(h.v_init) h.run() np_t = np.array(tvec) np_v = np.array(Vsoma) max_v = np.max(np_v[np.where(np_t > config.Spike_time)[0][0]:]) return apc.n, max_v
def exp_model2(Ra=157.3621, gpas=0.000403860792, cm=7.849480, dt=0.1): # -- Biophysics -- # Sec parameters and conductance for sec in h.allsec(): sec.Ra = Ra # Ra is a parameter to infer sec.cm = cm # parameter optimisation algorithm found this sec.v = 0 sec.insert('pas') sec.g_pas = gpas # gpas is a parameter to infer sec.e_pas = 0 # Print information #h.psection() # Stimulus stim1 = h.IClamp(h.soma(0.01)) stim1.delay = 199.9 stim1.amp = 0.5 stim1.dur = 3.1 stim2 = h.IClamp(h.soma(0.01)) stim2.delay = 503 stim2.amp = 0.01 stim2.dur = 599.9 # Run simulation -> # Set up recording Vectors v_vec = h.Vector() # Membrane potential vector t_vec = h.Vector() # Time stamp vector v_vec.record(h.soma(0.5)._ref_v) t_vec.record(h._ref_t) # Simulation duration and RUN h.tstop = (15000 - 1) * dt # Simulation end h.dt = dt # Time step (iteration) h.steps_per_ms = 1 / dt h.v_init = 0 h.finitialize(h.v_init) h.init() h.run() t = t_vec.to_python() v = v_vec.to_python() return t, v
def run_iclamp(cell, record_dt=0.1, dt=0.0125, celsius=36., prelength=1000.0, mainlength=10000.0, stimdur=500.0, stim_amp=0.0001, use_cvode=True): h.cvode.use_fast_imem(1) h.cvode.cache_efficient(1) h.secondorder = 2 h.dt = dt if record_dt < dt: record_dt = dt # Enable variable time step solver if use_cvode: h.cvode.active(1) h.celsius = celsius h.tstop = mainlength vec_t = h.Vector() vec_v = h.Vector() vec_t.record(h._ref_t, record_dt) # Time vec_v.record(list(cell.soma)[0](0.5)._ref_v, record_dt) # Voltage # Put an IClamp at the soma stim = h.IClamp(0.5, sec=list(cell.soma)[0]) stim.delay = prelength # Stimulus start stim.dur = stimdur # Stimulus length stim.amp = stim_amp # strength of current injection h.init() h.run() t = np.asarray(vec_t) v = np.asarray(vec_v) t0 = prelength t1 = prelength + stimdur return {'t0': t0, 't1': t1, 't': t, 'v': v}
def runsim (izhm): global Iin, ax1, recvecs h.dt = 0.025 f1 = [] ax1=None if fig1 is not None: plt.clf() for Iin in IinRange: izhm.Iin=Iin h.init() if burstMode: izhm.Iin=IinHyper h.init() h.continuerun(120) izhm.Iin=Iin h.run() else: h.run() plotall()
def run_sim(h, section_name, v_peak, tau_raise, tau_fall, onset=100): tstop = 500 h.dt = dt = 0.1 h.load_file("stdrun.hoc") soma, sec = fetch_soma_sec(section_name) v_rest = -75.711 # find_vrest(h, section_name) h.init() h.cvode.re_init() s_v, a_v = fetch_soma_apic_pots() vv = voltage_clamp(tstop, dt, v_rest, v_peak, tau_raise, tau_fall, onset) vc = h.SEClamp(sec(0.5)) vc.rs = 0.001 vc.dur1 = tstop vamp = h.Vector(vv) vamp.play(vc._ref_amp1, h.dt) t_vec, soma_vm, sec_vm = record(soma, sec) h.execute('tstop = ' + str(tstop)) h.run() diff_v = np.array(a_v) - np.array(s_v) return t_vec, soma_vm, sec_vm, diff_v, vv
def __init__(self,increment=0.1): #create pre- and post- synaptic sections self.increment = increment self.pre = h.Section() self.post = h.Section() for sec in self.pre,self.post: sec.insert('hh') #inject current in the pre-synaptic section self.stim = h.IClamp(0.5, sec=self.pre) self.stim.amp = 10.0 self.stim.delay = 5.0 self.stim.dur = 5.0 #create a synapse in the pre-synaptic section self.syn = h.ExpSyn(0.5,sec=self.post) #connect the pre-synaptic section to the synapse object: self.nc = h.NetCon(self.pre(0.5)._ref_v,self.syn) self.nc.weight[0] = 2.0 # record the membrane potentials and # synaptic currents vec = {} for var in 'v_pre', 'v_post', 'i_syn', 't': vec[var] = h.Vector() vec['v_pre'].record(self.pre(0.5)._ref_v ) vec['v_post'].record(self.post(0.5)._ref_v ) vec['i_syn'].record(self.syn._ref_i ) vec['t'].record(h._ref_t) self.vector = vec #Initialize the simulation h.load_file ("stdrun.hoc") h.init()
def play(self, fileroot='cell', show_colorbar=True, show_title=False): ''' Step through cell response over time ''' dt = self.play_dt tstop = self.play_tstop nrn.init() nrn.cvode_active(0) img_counter=0 f = mlab.gcf() if show_colorbar: mlab.colorbar(self.mlab_cell) nrn.initPlot() nrn.init() nrn.initPlot() nrn.init() for x in xrange(0, int(tstop/dt)): timestamp = "TIME: %.1f" % (x*dt) print timestamp if show_title: try: ftitle.text = timestamp except: ftitle = mlab.title(timestamp) nrn.continuerun(x*dt) dataset = self.mlab_cell.mlab_source.dataset v = array(self.calculate_voltage()) dataset.point_data.remove_array('data') array_id = dataset.point_data.add_array(v.T.ravel()) dataset.point_data.get_array(array_id).name = 'data' dataset.point_data.update() self.mlab_cell.update_data() self.mlab_cell.update_pipeline() if self.save_img: f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter)) img_counter += 1
def init(): log.info("Initializing..") h.init() log.info("Initialized..")
stim.dur = 5.0 # create a synapse in the pre-synaptic section syn = h.ExpSyn(0.5, sec=post) # connect the pre-synaptic section to the # synapse object nc = h.NetCon(pre(0.5)._ref_v, syn, sec=pre) vec={} for var in 'v_pre', 'v_post', 'i_syn', 't': vec[var] = h.Vector() # record the membrane potentials and # synaptic currents vec['v_pre'].record(pre(0.5)._ref_v) vec['v_post'].record(post(0.5)._ref_v) vec['i_syn'].record(syn._ref_i) vec['t'].record(h._ref_t) # run the simulation h.load_file("stdrun.hoc") h.init() h.tstop = 20.0 h.run() # check the values on command line list(vec['v_pre']) list(vec['v_post']) list(vec['i_syn']) list(vec['t'])