def run_sim(self): self.setup_sim() ''' Cache some parameters This simulation assumes electrode is same distance away from all nerves. All nerves have same number of nodes. ''' num_nodes = [nerve.params.num_nodes for nerve in self.bundle] rho_e = [nerve.params.rho_e for nerve in self.bundle] ''' Calculate r_vec -- distance from stim to each ndoes on all nerves r_vec is a list, each entry corresponds to a nerve. Each of those entries is a list of distance from node to electrode ''' r_vec = [] for j in range(len(self.bundle)): r_vec.append([]) r_vec[j] = [ self.calcDist(self.bundle[j], i) for i in range(num_nodes[j]) ] ''' If dummy_stim.i is in nA, then I/(4*pi*sigma*r) = (I*rho_e)/(4*pi*r) = ([nA][ohm-cm])/([um]) -> multiply by (1/10^6)/(1/10^4)=10^-2 to get mV ''' while (h.t < h.tstop): amp = self.elec.dummy_stim.i for j in range(len(self.bundle)): for i in range(num_nodes[j]): self.bundle[j].axons[i].e_extracellular = \ (10**-2)*rho_e[j]*amp/(4*pi*r_vec[j][i]) h.fadvance()
def go(): h.dt = 0.1 h.celsius = celsius h.finitialize(v_init) #neuron.init() # params: RERE, RETCa, ***RETCb, TCRE, PYPY, PYIN, INPYa, ***INPYb, PYRE, PYTC, TCPY, TCIN assign_synapses(RERE * 0.2, RETCa * 0.02, RETCb * 0.04, TCRE * 0.2, PYPY * 0.6, PYIN * 0.2, INPYa * gabaapercent * 0.15, INPYb * gababpercent * 0.03, PYRE * 1.2, PYTC * 0.01, TCPY * 1.2, TCIN * 0.4) #assign_synapses(gRERE_GABAA, gRETC_GABAA, gRETC_GABAB, gTCRE_AMPA, gPYPY_AMPA, gPYIN_AMPA, gINPY_GABAA, gINPY_GABAB, gPYRE_AMPA, gPYTC_AMPA, gTCPY_AMPA, gTCIN_AMPA) h.fcurrent() h.cvode.re_init() h.frecord_init() printPYinfo(0) printINinfo(0) printTCinfo(0) printREinfo(0) printWeight(0) field.append(0) while h.t < tstop: h.fadvance() field.append(xfield(230, fielddist, watchneuron))
def run(cell, v0, vThres, cpi, untilTol = False): f = open('pylog','a') if cpi: cell.cp_init() else: cell.init(v0) print ' cell initiated' print >>f, ' cell initiated' tsps = np.empty(int((h.tstop)/h.dt/2)) vold = v0 nc = 0 tsp = 0 firing = 0 h.t = 0 tol = 2e-14 while (int(round(h.t/h.dt)) < int(round(h.tstop/h.dt))) or (untilTol and np.abs(cell.soma(0.5).v - vold) > tol): vold = cell.soma(0.5).v h.fadvance() if cell.soma(0.5).v > vThres+15 and cell.soma(0.5).v < vold and not firing: tsp = h.t tsps[nc] = tsp firing = 1 nc = nc + 1 print >>f, ' fired at', tsp, ', ', nc, 'spike(s) in total' print ' fired at', tsp, ', ', nc, 'spike(s) in total' if (cell.soma(0.5).v <= vThres+7.5): firing = 0 print 'stopping with v', cell.soma(0.5).v, 'v0:', v0, 'with', cpi, 'and', untilTol, 'with', cell.soma(0.5).v-vold print >>f, 'stopping with v', cell.soma(0.5).v, 'v0:', v0, 'with', cpi, 'and', untilTol, 'with', cell.soma(0.5).v-vold f.close() return nc, int(round(h.t/h.dt))+1
def clamp(v_cl): f3cl.amp[1] = v_cl h.finitialize( v_init ) # calling the INITIAL block of the mechanism inserted in the section. # parameters initialization peak_curr = 0 dens = 0 t_peak = 0 while (h.t < h.tstop): # runs a single trace, calculates peak current dens = f3cl.i / soma(0.5).area() * 100.0 - soma( 0.5).i_cap # clamping current in mA/cm2, for each dt t_vec.append(h.t) # code for store the current v_vec_t.append(soma.v) # trace to be plotted i_vec.append(dens) # trace to be plotted if ((h.t >= 540) and (h.t <= 542)): # evaluate the peak (I know it is there) if (abs(dens) > abs(peak_curr)): peak_curr = dens t_peak = h.t h.fadvance() # updates the vectors at the end of the run v_vec.append(v_cl) ipeak_vec.append(peak_curr)
def test_syn(): precell = BallStick() postcell = BallStick() nc = precell.connect2target(postcell.synlist[0]) nc.weight[0] = 0.01 nc.delay = 0 stim = h.IClamp(0.5, sec=precell.soma) stim.amp = 0.700 stim.delay = 700 stim.dur = 1000 vec = {} for var in 't', 'pre', 'post': vec[var] = h.Vector() vec['t'].record(h._ref_t) vec['pre'].record(precell.soma(0.5)._ref_v) vec['post'].record(postcell.soma(0.5)._ref_v) cvode = h.CVode() cvode.active(1) h.finitialize(-65) tstop = 2000 while h.t < tstop: h.fadvance() with open("vm.out", "w") as out: for time, vsoma in zip(vec['t'], vec['post']): out.write("%g %g\n" % (time, vsoma)) try: import matplotlib.pyplot as plt plt.plot(vec['t'], vec['pre'], vec['t'], vec['post']) plt.show() except ImportError: pass
def clamp(v_cl): f3cl.dur[1] = dur # ms f3cl.amp[1] = v_cl # mV h.finitialize(v_init) peak_curr = 0 dens = 0 t_peak = 0 while (h.t < h.tstop): # runs a single trace, calculates peak current dens = f3cl.i / soma(0.5).area() * 100.0 - soma( 0.5).i_cap # clamping current in mA/cm2, for each dt t_vec.append(h.t) # code for store the current v_vec_t.append(soma.v) # trace to be plotted i_vec.append(dens) # trace to be plotted if ((h.t >= 540) and (h.t <= 542)): # evaluate the peak if (abs(dens) > abs(peak_curr)): peak_curr = dens # updates the peak current t_peak = h.t h.fadvance() if len( v_vec ) > L - 1: #resizing v_vec and ipeak_vec when the protocol is completed (it is needed for looping the animation) v_vec.resize(0) ipeak_vec.resize(0) v_vec.append(v_cl) # updates the vectors at the end of the run ipeak_vec.append(peak_curr)
def run(cell, v0, vThres, cpi): f = open('pylog','a') if cpi: cell.cp_init() else: cell.init(v0) print ' cell initiated' print >>f, ' cell initiated' tsps = np.empty(int((h.tstop)/h.dt/2)) vold = v0 nc = 0 tsp = 0 firing = 0 h.t = 0 while (int(round(h.t/h.dt)) < int(round(h.tstop/h.dt))): h.fadvance() if cell.soma(0.5).v > vThres+15 and cell.soma(0.5).v < vold and not firing: tsp = h.t tsps[nc] = tsp firing = 1 nc = nc + 1 print >>f, ' fired at', tsp, ', ', nc, 'spike(s) in total' print ' fired at', tsp, ', ', nc, 'spike(s) in total' vold = cell.soma(0.5).v if (cell.soma(0.5).v <= vThres+7.5): firing = 0 print 'stopping with v', cell.soma(0.5).v print >>f, 'stopping with v', cell.soma(0.5).v f.close() return nc
def clamp(v_cl): curr_tr = 0 # initialization of peak current cond_tr = 0 # initialization of peak conductance h.finitialize( v_init ) # calling the INITIAL block of the mechanism inserted in the section. # initialization of variables used to commute the peak current and conductance pre_i = 0 dens = 0 f3cl.amp[1] = v_cl # mV while (h.t < h.tstop): # runs a single trace, calculates peak current dens = f3cl.i / soma(0.5).area() * 100.0 - soma( 0.5).i_cap # clamping current in mA/cm2, for each dt t_vec.append(h.t) # code for storing the current v_vec_t.append(soma.v) # trace to be plotted i_vec.append(dens) # trace to be plotted if ((h.t > 5) and (h.t <= 10)): # evaluate the peak if (abs(dens) > abs(pre_i)): cond_tr = soma.g_na15 # updates the peak conductance curr_tr = dens # updates the peak current h.fadvance() pre_i = dens # updates the vectors at the end of the run v_vec.append(v_cl) gpeak_vec.append(cond_tr) ipeak_vec.append(curr_tr)
def test_max_open_probability(): reset( raiseError=False ) # reset() fails as unable to remove all neuron objects, unless we ignore the error sec = h.Section() # Create AMPA and NMDA mechanisms # AMPA uses mode=0; no rectification apsd = h.AMPATRUSSELL(0.5, sec=sec) # For NMDA we will hold the cell at +40 mV npsd = h.NMDA_Kampa(0.5, sec=sec) # And a presynaptic terminal to provide XMTR input term = h.MultiSiteSynapse(0.5, sec=sec) term.nZones = 1 term.setpointer(term._ref_XMTR[0], 'XMTR', apsd) term.setpointer(term._ref_XMTR[0], 'XMTR', npsd) h.celsius = 34.0 h.finitialize() op = [[], []] for i in range(100): # force very high transmitter concentration for every timestep term.XMTR[0] = 10000 sec.v = 40.0 h.fadvance() op[0].append(apsd.Open) op[1].append(npsd.Open) assert np.allclose(max(op[0]), apsd.MaxOpen) assert np.allclose(max(op[1]), npsd.MaxOpen)
def test_cell(): cell = BallStick() stim = h.IClamp(0.5, sec=cell.soma) stim.amp = 0.620 stim.delay = 700 stim.dur = 1000 tm = h.Vector() vm = h.Vector() ca = h.Vector() tm.record(h._ref_t) vm.record(cell.soma(0.5)._ref_v) ca.record(cell.soma(0.5)._ref_cai) cvode = h.CVode() cvode.active(1) h.finitialize(-65) tstop = 2000 while h.t < tstop: h.fadvance() with open("vm.out", "w") as out: for time, vsoma in zip(tm, vm): out.write("%g %g\n" % (time, vsoma)) with open("ca.out", "w") as out: for time, conc in zip(tm, ca): out.write("%g %g\n" % (time, conc)) try: import matplotlib.pyplot as plt plt.plot(tm, vm) plt.show() except ImportError: pass
def checkdts(iters=1000): ldt, lt = [], [] for i in xrange(iters): ldt.append(h.dt) lt.append(h.t) h.fadvance() return ldt, lt
def srun(cell, v0, trans, t0): f = open('pylog', 'a') cell.init() print ' cell initiated' print >> f, ' cell initiated' steps = 0 h.t = t0 print 't0 = ', h.t print >> f, 't0 = ', h.t while int(round(h.t / h.dt)) < int(round((t0 + trans) / h.dt)): h.fadvance() steps = steps + 1 print trans, 'ms trans complete, used ', steps, ' steps, t+trans = ', h.t, 'v = ', '%7.5f.' % cell.soma( 0.5).v print ' distant apical dend v = ', '%7.5f.' % cell.dend[121](0.0).v print ' distant basal dend v = ', '%7.5f.' % cell.dend[153](0.0).v print >> f, trans, 'ms trans complete, used ', steps, ' steps, t+trans = ', h.t, 'v = ', '%7.5f.' % cell.soma( 0.5).v print >> f, ' distant apical dend v = ', '%7.5f.' % cell.dend[121](0.0).v print >> f, ' distant basal dend v = ', '%7.5f.' % cell.dend[153](0.0).v while (h.t < h.tstop): h.fadvance() steps = steps + 1 print 'srun ended in ', steps, ' steps, t+trans = ', h.t, 'v = ', '%7.5f.' % cell.soma( 0.5).v print ' distant apical dend v = ', '%7.5f.' % cell.dend[121](0.0).v print ' distant basal dend v = ', '%7.5f.' % cell.dend[153](0.0).v print >> f, ' srun ended in ', steps, ' steps, t+trans = ', h.t, 'v = ', '%7.5f.' % cell.soma( 0.5).v print >> f, ' distant apical dend v = ', '%7.5f.' % cell.dend[121](0.0).v print >> f, ' distant basal dend v = ', '%7.5f.' % cell.dend[153](0.0).v f.close()
def run(self, vcrange, cell, dt=0.025): """ Run voltage-clamp I/V curve. Parameters: vmin : float Minimum voltage step value vmax : Maximum voltage step value vstep : Voltage difference between steps cell : The Cell instance to test. """ self.reset() self.cell = cell try: (vmin, vmax, vstep) = vcrange # unpack the tuple... except: raise TypeError( "run_iv argument 1 must be a tuple (imin, imax, istep)") vstim = h.SEClamp(0.5, cell.soma) # set up a single-electrode clamp vstim.dur1 = 50.0 vstim.amp1 = -60 vstim.dur2 = 500.0 vstim.amp2 = -60.0 vstim.dur3 = 400 vstim.amp3 = -60.0 vstim.rs = 0.01 cell.soma.cm = 0.001 # reduce capacitative transients (cap compensation) self.durs = [vstim.dur1, vstim.dur2, vstim.dur3] self.amps = [vstim.amp1, vstim.amp2, vstim.amp3] self.voltage_cmd = [] tend = 900.0 iv_nstepv = int(np.ceil((vmax - vmin) / vstep)) iv_minv = vmin iv_maxv = vmax vstep = (iv_maxv - iv_minv) / iv_nstepv for i in range(iv_nstepv): self.voltage_cmd.append(float(i * vstep) + iv_minv) nreps = iv_nstepv h.dt = dt self.dt = h.dt for i in range(nreps): # Connect recording vectors self['v_soma'] = cell.soma(0.5)._ref_v self['i_inj'] = vstim._ref_i self['time'] = h._ref_t vstim.amp2 = self.voltage_cmd[i] custom_init(v_init=-60.) h.tstop = tend self.cell.check_all_mechs() while h.t < h.tstop: h.fadvance() self.voltage_traces.append(self['v_soma']) self.current_traces.append(self['i_inj']) self.time_values = np.array(self['time'])
def run_sim(): h.finitialize(h.v_init) while(h.t < h.tstop): for i in range(num_nodes): # apply extracellular potential -- 10^3*(uV) = [mV] axons[i].e_extracellular = (10**3)*rho_e*dummy_stim.i/(4*pi*r_vec[i]) h.fadvance() Vm_vec_py = np.array(Vm_vec) return Vm_vec_py
def run_single_simulation(config, interactive): axon = Axon(config) axon.insert_stim(config['stim_position'], config['stim_amplitude'], config['stim_start_time'], config['stim_duration']) # set up recording vectors for python plots and the csv file t = h.Vector() t.record(h._ref_t) num_v_traces = config['num_v_traces'] v_traces = [] for i in range(num_v_traces): v = h.Vector() v.record(axon.section_at_f( # record at num_v_traces points along the axon, equally spaced # from eachother and from the end points (since we don't care # about things like the impedance mismatch at the ends) (i + 1) * 1.0 / (num_v_traces + 1)) (Axon.middle)._ref_v) v_traces.append(v) # set up NEURON plotting code (if we're in an interactive session) if interactive: g = h.Graph() g.size(0, config['integration_time'], -80, 55) for i in range(num_v_traces): g.addvar('v(0.5)', sec=axon.section_at_f((i+1) * 1.0 / (num_v_traces + 1))) # initialize the simulation h.dt = config['max_time_step'] tstop = config['integration_time'] h.finitialize(config['initial_membrane_potential']) h.fcurrent() # run the simulation if interactive: g.begin() while h.t < tstop: h.fadvance() g.plot(h.t) g.flush() else: while h.t < tstop: h.fadvance() # save the data as a csv with open(config['csv_filename'], 'w') as csv_file: # start with a header of the form "t_ms, V0_mV, V1_mv, V2_mV,..." csv_file.write(", ".join( ["t_ms"] + ["V{0}_mV".format(i) for i in range(num_v_traces)] ) + "\n") # write the time and each of the recorded voltages at that time for row in zip(t, *v_traces): csv_file.write(", ".join([str(x) for x in row]) + "\n")
def run(self, stim, seed): """Run the network simulation with *stim* as the sound source and a unique *seed* used to configure the random number generators. """ self.reset() # Generate 2 new seeds for the SGC spike generator and for the NEURON simulation rs = np.random.RandomState() rs.seed(self.seed ^ seed) seed1, seed2 = rs.randint(0, 2**32, 2) random.set_seed(seed1) self.sgc.set_seed(seed2) self.sgc.set_sound_stim(stim, parallel=False) # set up recording vectors for pop in self.bushy, self.dstellate, self.tstellate, self.tuberculoventral: for ind in pop.real_cells(): cell = pop.get_cell(ind) self[cell] = cell.soma(0.5)._ref_v self['t'] = h._ref_t h.tstop = stim.duration * 1000 h.celsius = self.temp h.dt = self.dt print "init.." self.custom_init() print "start.." last_update = time.time() while h.t < h.tstop: h.fadvance() now = time.time() if now - last_update > 1.0: print "%0.2f / %0.2f" % (h.t, h.tstop) last_update = now # record vsoma and spike times for all cells vec = {} for k in self._vectors: v = self[k].copy() if k == 't': vec[k] = v continue spike_inds = np.argwhere((v[1:] > -20) & (v[:-1] <= -20))[:, 0] spikes = self['t'][spike_inds] pop = k.type cell_ind = getattr(self, pop).get_cell_index(k) vec[(pop, cell_ind)] = [v, spikes] # record SGC spike trains for ind in self.sgc.real_cells(): cell = self.sgc.get_cell(ind) vec[('sgc', ind)] = [None, cell._spiketrain] return vec
def basicRxD3D(): from neuron import h, rxd s = h.Section(name='s') s.L = s.diam = 1 cyt = rxd.Region([s]) ca = rxd.Species(cyt) rxd.set_solve_type(dimension=3) h.finitialize(-65) h.fadvance() return 1
def run(self,do_plot = False): #run and return resting potential t_now = h.t while h.t < t_now + self.increment: h.fadvance() if do_plot: plot(self.vector) #return the post-synaptic membrane potential return self.vector['v_post'][-1]
def run(self, v_init=-60, tstop=20000., dt=0.1, cvode=True, ga_use_half=False): ''' Simulates this cell and all desired vectors are recorded. Uses fixed or variable timestep depending on the `cvode=` boolean. Parameters: ---------- v_init : int, float The starting voltage of the simulation. tstop : int, float The maximum time of integration dt : float The desired integration step. cvode : bool Selects variable time step integration. Default is False. ga_use_half : bool Will only use the 2nd have of recordings for GA ''' h.load_file('stdrun.hoc') h.v_init = v_init h.tstop = tstop h.dt = dt #set the recording into the vecs dictionary #the _ref dictionary contain the hoc object attribute references for key in self._ref.keys(): #This makes sure we overwrite any vectors if we already ran a sim if isinstance(self.vecs['time'], np.ndarray): self.vecs[key] = h.Vector() self.vecs[key].record(self._ref[key]) else: self.vecs[key].record(self._ref[key]) if cvode: solver = h.CVode() solver.active(1) h.finitialize(h.v_init) solver.solve(h.tstop) else: h.CVode().active(0) h.finitialize() for t in range(0, int(h.tstop/h.dt)): h.fadvance() for key, val in self.vecs.iteritems(): self.vecs[key] = np.array(val) if ga_use_half: for key, val in self.vecs.iteritems(): self.vecs[key] = val[(val.size)/2:] return self.vecs
def integrate(a, b, c, t): # g.begin() k = 0 h.finitialize() while h.t < tstop: h.fadvance() a[k - 1] = cell.ek b[k - 1] = cell.ko c[k - 1] = cell.ik t[k - 1] = h.dt * (k - 1) k = k + 1
def run(self, tstop): t_alert = 100.0 h.check_simulator() h.cvode.active(0) self.vm.resize(0) h.finitialize(h.v_init) while h.t < tstop: h.fadvance() if self.run_alerts and h.t > t_alert: print("\tTime: {} ms out of {} ms".format(t_alert, tstop)) t_alert += 100.0
def run(self): """Run the simulator till tstop""" #Initializing if self.init(): # Run msg = "Running simulation. It will take a while maybe..." self.ui.statusbar.showMessage(msg, 5000) while h.t < h.tstop: h.fadvance() self.ui.time_label.setText("<b>" + str(h.t) + "</b>")
def benchmark_cell(): cell = BallStick() stim = h.IClamp(0.5, sec=cell.soma) stim.amp = 0.700 stim.delay = 0 stim.dur = 1e6 cvode = h.CVode() cvode.active(1) h.finitialize(-65) tstop = 1e6 while h.t < tstop: h.fadvance()
def run(tstop, ics, tolerance): # to get nontrivial initialized i_membrane_, initialize to random voltage. r = h.Random() r.Random123(0, 1, 0) for sec in h.allsec(): for seg in sec.allseg(): # don't care if some segments counted twice seg.v = -65.0 + r.uniform(0, 5) h.finitialize() balanced(ics, tolerance) while h.t < 1.0: h.fadvance() balanced(ics, tolerance)
def run(self): """Run the simulator till tstop""" #Initializing if self.init(): # Run msg = "Running simulation. It will take a while maybe..." self.ui.statusbar.showMessage(msg, 5000) while h.t < h.tstop: h.fadvance() self.ui.time_label.setText("<b>" + str(h.t) + "</b>") self.animation()
def run_simulation(shotnoise_input, cables, params, tstop=2000.,\ dt=0.025, seed=3, recordings='full', recordings2='', nmda_on=False, Ca_spikes_on=False, HH_on=False,\ synchronous_stim={'location':[4,14], 'spikes':[]}): """ recordings is a set of tuple of the form : [branch_generation, branch_number, xseg] """ exc_synapses, exc_netcons, exc_Ks, exc_spike_trains,\ inh_synapses, inh_netcons, inh_Ks, inh_spike_trains,\ area_lists, spkout = Constructing_the_ball_and_tree(params, cables, nmda_on=nmda_on, Ca_spikes_on=Ca_spikes_on, HH_on=HH_on) # then synapses manually set_presynaptic_spikes_manually(shotnoise_input, cables, params,\ exc_spike_trains, exc_Ks, inh_spike_trains, inh_Ks, tstop, seed=seed,\ synchronous_stim=synchronous_stim) ## QUEUING OF PRESYNAPTIC EVENTS init_spike_train = queue_presynaptic_events_in_NEURON([exc_netcons, exc_spike_trains, inh_netcons, inh_spike_trains]) ## --- launching the simulation fih = nrn.FInitializeHandler((init_spike_train, [exc_netcons, exc_spike_trains, inh_netcons, inh_spike_trains])) ## --- recording t_vec = nrn.Vector() t_vec.record(nrn._ref_t) V = [] if recordings is 'soma': V.append(nrn.Vector()) exec('V[0].record(nrn.cable_0_0(0)._ref_v)') if recordings2 is 'cable_end': V.append(nrn.Vector()) exec('V[1].record(nrn.cable_5_15(1)._ref_v)') ## --- launching the simulation nrn.finitialize(params['El']*1e3) nrn.dt = dt if recordings is 'full': V.append(get_v(cables)) while nrn.t<(tstop-dt): nrn.fadvance() if recordings is 'full': V.append(get_v(cables)) print("=======================================") nrn('forall delete_section()') print(" --- checking if the neuron is destroyed") nrn.topology() print("=======================================") return np.array(t_vec), V
def run_sim(): h.finitialize(h.v_init) i = 0 while (h.t < h.tstop): for seg in smallFiber: #print i, ",", seg.x #if np.abs(dummy_stim.i)>0: seg.e_extracellular = (10**-2) * initBunch.rho_e * dummy_stim.i / ( 4 * pi * rVec[i]) i = i + 1 i = 0 h.fadvance() Vm_vec_py = np.array(Vm_vec) return Vm_vec_py
def simulate(v_init, mainlength, prelength=0, cvode=True): """ :param h: :param v_init: :param prelength: :param mainlength: :param cvode: """ h.cvode_active(1 if cvode else 0) h.finitialize(v_init) h.tstop = prelength + mainlength h.fadvance() h.continuerun(h.tstop)
def run_sim(self): self.setup_sim() # cache some parameters num_nodes = self.nerve.params.num_nodes rho_e = self.nerve.params.rho_e r_vec = [self.calcDist(i) for i in range(num_nodes)] while (h.t < h.tstop): for i in range(num_nodes): # apply extracellular potential amp = self.elec.dummy_stim.i self.nerve.axons[i].e_extracellular = ( 10**-2) * rho_e * amp / (4 * pi * r_vec[i]) h.fadvance()
def Clamp(dur): f3cl.dur[2] = dur h.tstop = 5 + 30 + dur + 20 + 5 h.finitialize(v_init) #variables initialization pre_i1 = 0 pre_i2 = 0 dens = 0 # initialization peak current peak_curr1 = 0 peak_curr2 = 0 while (h.t < h.tstop): # runs a single trace, calculates peak current dens = f3cl.i / soma(0.5).area() * 100.0 - soma( 0.5).i_cap # clamping current in mA/cm2, for each dt t_vec.append(h.t) v_vec_t.append(soma.v) i_vec_t.append(dens) if ((h.t > 5) and (h.t < 15)): # evaluate the first peak if (pre_i1 < abs(dens)): peak_curr1 = abs(dens) pre_i1 = abs(dens) if ((h.t > (5 + cond_st_dur + dur)) and (h.t < (15 + cond_st_dur + dur))): # evaluate the second peak if (pre_i2 < abs(dens)): peak_curr2 = abs(dens) pre_i2 = abs(dens) h.fadvance() if len( time_vec ) > L - 1: # resizing vectors when the protocol is completed (it is needed for looping the animation) rec_vec.resize(0) time_vec.resize(0) log_time_vec_vec.resize(0) time_vec.append(dur) log_time_vec_vec.append(np.log10(dur)) rec_vec.append(peak_curr2 / peak_curr1)
def go_by_steps(): """ Main driver for the simulation """ initialize() # Loop over time steps for i_t, t in enumerate(ws.tarray): h.fadvance() # Rest for 500 ms to allow the computer to cool down if False: time.sleep(0.5) # Time control t1 = datetime.now() msg = "Time step %i of %i. Total elapsed time: %i seconds" % ( i_t, ws.nt, (t1 - t0).total_seconds()) # Log the time step into the simulation log file ws.log(msg)
def run(self, **kwds): """Run the NEURON stimulator until the time reaches or passes tstop. All keyword parameters are passed to `init()`. By default, `init()` is called with `finit=True` only if this has not been done previously. """ self._check_active() kwds.setdefault('finit', not self._finitialized) self.init(**kwds) tstop = self.tstop try: while h.t < tstop: h.fadvance() finally: self.t = h.t
def min_sim(self): """ Launch a minimal simulation to test the model and determine its resting potential empirically """ for sec in h.allsec(): h.finitialize(-65, sec) h.fcurrent(sec) h.frecord_init() while h.t < 200: # Launch a simulation h.fadvance() # Record the soma voltage after this minimal stimulation to find v_rest soma = getattr(h, "soma") self.vrest = getattr(soma, "v")
def advance(self): """Run the NEURON simulator for one timestep. See also -------- http://www.neuron.yale.edu/neuron/static/new_doc/simctrl/programmatic.html#fadvance """ self._check_active() # make sure NEURON agrees with our variables self.init(finit=False) try: h.fadvance() finally: # update the clock self.t = h.t
def simulate(v_init, mainlength, prelength=0, use_cvode=True): """ :param h: :param v_init: :param prelength: :param mainlength: :param cvode: """ h.cvode_active(1 if use_cvode else 0) h.cvode.use_fast_imem(1) h.cvode.cache_efficient(1) h.secondorder = 2 h.finitialize(v_init) h.tstop = prelength + mainlength h.fadvance() h.continuerun(h.tstop)
def run_sim(self): self.setup_sim() # cache some parameters num_nodes = self.nerve.params.num_nodes rho_e = self.nerve.params.rho_e r_vec = [self.calcDist(i) for i in range(num_nodes)] ''' If dummy_stim.i is in nA, then I/(4*pi*sigma*r) = (I*rho_e)/(4*pi*r) = ([nA][ohm-cm])/([um]) -> multiply by (1/10^6)/(1/10^4)=10^-2 to get mV ''' while (h.t < h.tstop): for i in range(num_nodes): # apply extracellular potential amp = self.elec.dummy_stim.i self.nerve.axons[i].e_extracellular = ( 10**-2) * rho_e * amp / (4 * pi * r_vec[i]) h.fadvance()
def run_sim(axons, dummy_stim, r_vec, params): h.dt = params.dt h.tstop = params.tstop h.celsius = params.celsius h.finitialize(params.v_init) while (h.t < h.tstop): for i in range(params.num_nodes): """ apply extracellular potential -- If dummy_stim.i is in mA, then I/(4*pi*sigma*r) = (I*rho_e)/(4*pi*r) = ([mA][ohm-cm])/([um]) -> multiply by 10^4 to get mV If dummy_stim.i is in nA, then I/(4*pi*sigma*r) = (I*rho_e)/(4*pi*4) = ([nA][ohm-cm])/([um]) -> multiply by (1/10^6)/(1/10^4)=10^-2 to get mV """ axons[i].e_extracellular = ( 10**-2) * params.rho_e * dummy_stim.i / (4 * pi * r_vec[i]) h.fadvance()
def min_sim(self, TSTOP=100): """ Launch a minimal simulation to test the model and determine its resting potential empirically """ vrec = h.Vector() vrec.record(self.soma(0.5)._ref_v) for sec in h.allsec(): h.finitialize(-65, sec) h.fcurrent(sec) h.frecord_init() while h.t < TSTOP: #Launch a simulation h.fadvance() vrest = np.array(vrec)[-1] return vrest
def is_blocked(axon): v = h.Vector() v.record(axon.section_at_x(axon.config['block_test_position']) (Axon.middle)._ref_v) # initialize the simulation h.dt = axon.config['max_time_step'] tstop = axon.config['integration_time'] v_init = axon.config['initial_membrane_potential'] h.finitialize(v_init) h.fcurrent() # run the simulation while h.t < tstop: h.fadvance() if max(v) >= axon.config['block_test_threshold']: return False else: return True
def synch_simulators(self, tmp_tstop, nrnManager): """ Calculate the synapse weight, using the calcium in the spine_heads as input. Synch the two simulators using the following steps: 1. Calculate the calcium concentration in the spines head in NEURON and set this value in ecell. 2. Advance ecell for the specified_delta 3. Update the electric weight of the synapses in NEURON """ logger.info ("Current time: %f Synchronizing sims till [ms] %s" %(h.t, tmp_tstop)) stimulated_spines = self.param['stimulated_spines'] t_sync_start = h.t while h.t < tmp_tstop: h.fadvance() # run Neuron for step # We are updating the calcium according to our # delta calcium sampling. # due to numerical errors we can't use straight comparison, # but we need to wrap this into a lower/upper bounds # conditions. lower_time = t_sync_start + self.param['delta_calcium_sampling'] upper_time = lower_time + self.param['dtNeuron'] # logger.debug( "Lower time: %.15f h.t: %.15f Upper time: %.15f" %(lower_time, # h.t, # upper_time)) if lower_time <= h.t <= upper_time: for spine_id in stimulated_spines : spine = nrnManager.spines[spine_id] self.sync_calcium(spine) self.advance_ecell(spine, (h.t - t_sync_start) / 1e3) # Stopping flux from the input. spine.ecellMan.ca_in['k'] = 0 # Re-enabling pump and leak. spine.ecellMan.ca_leak['vmax'] = self.param['ca_leak_vmax'] spine.ecellMan.ca_pump['vmax'] = self.param['ca_pump_vmax'] self.update_synape_weight(spine) t_sync_start = h.t # Resetting the t_start to the new NEURON time.
def test_pop(): from random import random, choice ncells = 100 cells = [BallStick(random()*0.2+0.9) for i in range(ncells)] nclist = [] for postcell in cells: for i in range(20): precell = choice(cells) nc = precell.connect2target(postcell.synlist[0]) nc.weight[0] = 0.01 nc.delay = 0 nclist.append(nc) splist = [] stims = [] for (i, cell) in enumerate(cells): tvec = h.Vector() idvec = h.Vector() nc = h.NetCon(cell.axon(1)._ref_v, None, sec=cell.axon) nc.record(tvec, idvec, i+1) splist.append([tvec, idvec]) for cell in cells: stim = h.IClamp(0.5, sec=cell.soma) stim.amp = 0.700 stim.delay = 600 + 200*random() stim.dur = 1000 stims.append(stim) #cvode = h.CVode() #cvode.active(1) h.dt = 0.1 h.finitialize(-65) tstop = 2000 while h.t < tstop: h.fadvance() try: import matplotlib.pyplot as plt for spikes in splist: plt.scatter(spikes[0], spikes[1], marker='.') plt.show() except ImportError: pass
def run(self, simulation_time, reset=True, timestep='cvode', rtol=None, atol=None): """ Run the simulation for a certain time. """ self._time.record(h._ref_t) if timestep == 'cvode': self.cvode = h.CVode() if rtol is not None: self.cvode.rtol = rtol if atol is not None: self.cvode.atol = atol else: h.dt = timestep if reset or not self.running: self.initialize() self.running = True # Convert simulation time to float value in ms simulation_time = float(pq.Quantity(simulation_time, 'ms')) for _ in numpy.arange(h.dt, simulation_time + h.dt, h.dt): h.fadvance() self.tstop += simulation_time
def run_simulation(self, nrnManager, excitatory_stims): """ Run the simulation. If input synchronizes the two simulators, otherwise run each on its own and advance quickly """ # Processing the options tStop_final = self.param['tStop'] + self.param['t_equilibrium_neuron'] # Getting the calcium before the stims for spine_id in self.param['stimulated_spines']: spine = nrnManager.spines[spine_id] self.update_synape_weight(spine) while h.t < tStop_final: if excitatory_stims: t_stim = excitatory_stims.pop(0) s_log = "Current Neuron time: %s. \ Current t_stim: %s, remaining input: %s" %(h.t, t_stim, len(excitatory_stims)) logger.debug( s_log) if h.t < t_stim: self.advance_quickly(t_stim, nrnManager) tmp_tstop = t_stim + self.param['t_buffer'] self.synch_simulators(tmp_tstop, nrnManager) else: logger.debug( "No excitatory input remaining. Quickly to the end") self.advance_quickly(tStop_final, nrnManager) h.fadvance() # This is to force the latest step and avoid the infinite loop. # Recording last for spine_id in self.param['stimulated_spines']: spine = nrnManager.spines[spine_id] self.update_synape_weight(spine)
def run(duration): h.finitialize() while h.t < duration: h.fadvance()
def integrate(): #g.begin() h.finitialize() while h.t<tstop: h.fadvance()
def integrate(): h.finitialize() while h.t<tstop: h.fadvance()
res['i_inj'] = h.Vector() res['i_inj'].record(vstim._ref_i) res['time'] = h.Vector() res['time'].record(h._ref_t) res['delec'] = h.Vector() res['delec'].record(dends[-1](0.5)._ref_v) print( 'init') h.dt = 0.025 custom_init(v_init=-65) h.finitialize() h.tstop = np.max(stimtimes) + tipi h.t = 0. while h.t < h.tstop: h.fadvance() # h.batch_save() # save nothing # h.batch_run(h.tstop, h.dt, "dend.dat") fig, ax = mpl.subplots(4, 1, figsize=(5, 10)) ax = ax.ravel() ax[0].plot(res['time'], res['i_inj']) for i in range(nsyn): it0 = np.argmin(np.fabs(np.array(res['time']) - (5+i*tipi))) it1 = np.argmin(np.fabs(np.array(res['time']) - (5+i*tipi + tipi/2.))) print( it0, it1) y = np.array(res['i_inj'])[it0:it1] y = y - y[0] ax[1].plot(np.array(res['time'])[it0:it1] - (5+i*tipi), y) ax[2].plot(np.array(res['time'])[it0:it1] - (5+i*tipi), y/np.min(y)) rx = np.array(res['time'])[it0:it1] - np.array(res['time'])[it0]
def pythonsim(simid, rundir, inputdir, modeldir, outputdir, currentstr, vinitstr, delaystr, stimdurationstr, timestepstr, simstopstr, recordintervalstr): import neuron from neuron import h Section = h.Section # All the mods are in the simulator directory # Apparently this is already done by the import, if we use the "-dll" # option in the call to nrniv. Since the import behavior seems to be # inconsistent without the "-dll" option, we do it this way. #neuron.load_mechanisms(".") # NOT USING LOAD_MECHANISMS HERE # local auto-modified version for no gui and control over certain ion # channels is in the run dir h.xopen(rundir + '/' + simid + '.hoc') timefilepath = outputdir + '/' + 'timedata.txt' timefile = h.File() timefile.wopen(timefilepath, 'w') voltagefilepath = outputdir + '/' + 'voltagedata.txt' voltagefile = h.File() voltagefile.wopen(voltagefilepath, 'w') current = float(currentstr) vinit = float(vinitstr) delay = float(delaystr) stimduration = float(stimdurationstr) timestep = float(timestepstr) simstop = float(simstopstr) recordinterval = float(recordintervalstr) # ----- Current Injection stim = h.IClamp(0.5, sec=h.soma) stim.amp = current # nA stim.delay = delay # msec stim.dur = stimduration # msec # ----- Simulation Control (now mostly done through input arguments) h.dt = timestep # Preallocate record vectors for speed # Requires recordinterval to be an exact multiple of tstep. recordlength = simstop/recordinterval + 1 testt = h.Vector(recordlength) testv = h.Vector(recordlength) # Recording at the soma testt.record(h._ref_t, recordinterval) testv.record(h.soma(0.5)._ref_v, recordinterval) # Initialize h.finitialize(vinit) h.fcurrent() # Integrate while h.t <= simstop: v = h.soma.v h.fadvance() # Shutdown testt.printf(timefile, '%f\n') testv.printf(voltagefile, '%f\n') timefile.close() voltagefile.close() return(0)
def run(self, tStop): """Run the simulation until tStop""" h.tstop = tStop while h.t < h.tstop: h.fadvance()
def integrate(): while h.t<tstop: h.fadvance()