def ivcurve(mechanism_name, i_type, vmin=-100, vmax=100, deltav=1, transient_time=50, test_time=50, rs=1, vinit=-665): """ Returns the (peak) current-voltage relationship for an ion channel. Args: mechanism_name = name of the mechanism (e.g. hh) i_type = which current to monitor (e.g. ik, ina) vmin = minimum voltage step to test vmax = maximum voltage step to test deltav = increment of voltage transient_time = how long to ignore for initial conditions to stabilize (ms) test_time = duration of the voltage clamp tests (ms) rs = resistance of voltage clamp in MOhm vinit = initialization voltage Returns: i = iterable of peak currents (in mA/cm^2) v = iterable of corresponding test voltages Note: The initialization potential (vinit) may affect the result. For example, consider the Hodgkin-Huxley sodium channel; a large fraction are inactivated at rest. Using a strongly hyperpolarizing vinit will uninactivate many channels, leading to more current. """ from neuron import h import numpy h.load_file('stdrun.hoc') sec = h.Section() sec.insert(mechanism_name) sec.L = 1 sec.diam = 1 seclamp = h.SEClamp(sec(0.5)) seclamp.amp1 = vinit seclamp.dur1 = transient_time seclamp.dur2 = test_time seclamp.rs = rs i_record = h.Vector() i_record.record(sec(0.5).__getattribute__('_ref_' + i_type)) result_i = [] result_v = numpy.arange(vmin, vmax, deltav) for test_v in result_v: seclamp.amp2 = test_v h.finitialize(vinit) h.continuerun(transient_time) num_transient_points = len(i_record) h.continuerun(test_time + transient_time) i_record2 = i_record.as_numpy()[num_transient_points:] baseline_i = i_record2[0] i_record_shift = i_record2 - baseline_i max_i = max(i_record_shift) min_i = min(i_record_shift) peak_i = max_i if abs(max_i) > abs(min_i) else min_i peak_i += baseline_i result_i.append(peak_i) return result_i, result_v
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 trivial_ecs(scale): from neuron import h, crxd as rxd import numpy import warnings warnings.simplefilter("ignore", UserWarning) h.load_file('stdrun.hoc') tstop = 10 if scale: #variable step case h.CVode().active(True) h.CVode().event(tstop) else: #fixed step case h.dt = 0.1 sec = h.Section() #NEURON requires at least 1 section # enable extracellular RxD rxd.options.enable.extracellular = True # simulation parameters dx = 1.0 # voxel size L = 9.0 # length of initial cube Lecs = 21.0 # lengths of ECS # define the extracellular region extracellular = rxd.Extracellular(-Lecs/2., -Lecs/2., -Lecs/2., Lecs/2., Lecs/2., Lecs/2., dx=dx, volume_fraction=0.2, tortuosity=1.6) # define the extracellular species k_rxd = rxd.Species(extracellular, name='k', d=2.62, charge=1, atolscale=scale, initial=lambda nd: 1.0 if abs(nd.x3d) <= L/2. and abs(nd.y3d) <= L/2. and abs(nd.z3d) <= L/2. else 0.0) # record the concentration at (0,0,0) ecs_vec = h.Vector() ecs_vec.record(k_rxd[extracellular].node_by_location(0, 0, 0)._ref_value) h.finitialize() h.continuerun(tstop) #run the simulation # compare with previous solution ecs_vec.sub(h.Vector(trivial_ecs_data[scale])) ecs_vec.abs() if ecs_vec.sum() > 1e-9: return -1 return 0
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 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 block_run(Dt=100.0, logger=None): """Run for tstop in blocks of Dt time""" if h.tstop < Dt: Dt = h.tstop if logger is not None: logger.info('Starting simulation for {}'.format(h.tstop)) print('Starting simulation for {}'.format(h.tstop)) start = timer() while h.t < (h.tstop - Dt): h.continuerun(h.t + Dt) end = timer() if logger is not None: logger.info('Finished till {} ms of simulation in {} s.'.format( h.t, end - start)) h.continuerun(h.tstop) end = timer() if logger is not None: logger.info('Finished {} ms of simulation in {} s.'.format( h.tstop, end - start))
def run(self): """Run the simulation: if beginning from a blank state, then will use h.run(), if continuing from the saved state, then will use h.continuerun() """ for mod in self._sim_mods: if isinstance(mod, mods.ClampReport): if mod.variable == "se": mod.initialize(self, self._seclamps) elif mod.variable == "ic": mod.initialize(self, self._iclamps) elif mod.variable == "f_ic": mod.initialize(self, self._f_iclamps) else: mod.initialize(self) self.start_time = h.startsw() s_time = time.time() pc.timeout(0) pc.barrier() # wait for all hosts to get to this point io.log_info( 'Running simulation for {:.3f} ms with the time step {:.3f} ms'. format(self.tstop, self.dt)) io.log_info('Starting timestep: {} at t_sim: {:.3f} ms'.format( self.tstep, h.t)) io.log_info('Block save every {} steps'.format(self.nsteps_block)) if self._start_from_state: h.continuerun(h.tstop) else: h.run(h.tstop) # <- runs simuation: works in parallel pc.barrier() for mod in self._sim_mods: mod.finalize(self) pc.barrier() end_time = time.time() sim_time = self.__elapsed_time(end_time - s_time) io.log_info('Simulation completed in {} '.format(sim_time))
def run(mode): pc.set_maxstep(10) h.stdinit() if mode == 0: pc.psolve(h.tstop) elif mode == 1: while h.t < h.tstop: pc.psolve(h.t + 1.0) else: while h.t < h.tstop: h.continuerun(h.t + 0.5) pc.psolve(h.t + 0.5) tran = [h.t, h.soma(0.5).v, h.soma(0.5).hh.m] assert tv.eq(tvstd) assert ( v.cl().sub(vstd).abs().max() < 1e-10 ) # usually v == vstd, some compilers might give slightly different results assert i_mem.cl().sub(i_memstd).abs().max() < 1e-10 assert h.Vector(tran_std).sub(h.Vector(tran)).abs().max() < 1e-10
def do_work(i): pc = h.ParallelContext() rank = int(pc.id()) nhost = int(pc.nhost()) print("worker %d of %d: %i" % (rank, nhost, i)) soma = h.Section(name='soma') soma.L = 20 soma.diam = 20 soma.insert('hh') iclamp = h.IClamp(soma(0.5)) iclamp.delay = 2 iclamp.dur = 0.1 iclamp.amp = 0.9 rec_v = h.Vector() rec_t = h.Vector() rec_v.record(soma(0.5)._ref_v) # Membrane potential vector rec_t.record(h._ref_t) h.finitialize(-65) h.fadvance() h.continuerun(250) return rec_v.max()
def myrun(): global fit # pointer to FinitializeHandler needs to be global so doesn't disappear dastart = datetime.now() print 'started at:', dastart if dconf['useWM']: setupWMInputs() h.stdinit() ca[er].concentration = dconf['caerinit'] # 100e-6 ca[cyt].concentration = dconf['cacytinit'] # 100e-6 if dconf['cvodeactive']: h.cvode.re_init() h.continuerun(h.t + tstop) # run for tstop daend = datetime.now() print 'finished ', tstop, ' ms sim at:', daend dadiff = daend - dastart print 'runtime:', dadiff, '(', tstop / 1e3, ' s)' # concatenate the results so can view/save all at once global lspks, lids lspks, lids = array([]), array([]) for i in xrange(len(ltimevec)): lspks = concatenate((lspks, ltimevec[i])) lids = concatenate((lids, lidvec[i])) ion() plotnew(xl=(9.9, 11))
def plot(self): stim = h.IClamp(self.cell.dend(1)) stim.get_segment() stim.delay = 5 stim.dur = 1 stim.amp = 0.1 soma_v = h.Vector().record(self.cell.soma(0.5)._ref_v) dend_v = h.Vector().record(self.cell.dend(0.5)._ref_v) t = h.Vector().record(h._ref_t) amps = [0.075 * i for i in range(1, 5)] colors = ['green', 'blue', 'red', 'black'] self.ax_soma.clear() self.ax_dend.clear() self.ax_dend.set_xlabel('t (ms)') self.ax_dend.set_ylabel('v (mV)') self.ax_soma.set_xlabel('t (ms)') self.ax_soma.set_ylabel('v (mV)') try: for amp, color in zip(amps, colors): stim.amp = amp h.finitialize(-65 * mV) h.continuerun(25 * ms) self.canvas_dend.draw() self.ax_dend.plot(t, dend_v, color) self.canvas_soma.draw() self.ax_soma.plot(t, soma_v, color) self.ax_dend.legend(["{:.2f}".format(elem) for elem in amps]) except: self.ax_soma.clear() self.ax_dend.clear()
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 sim(self): tMax = self.gettMax() tData = 0 tNoise = 0 h.stdinit() x = h.Vector() Data = [] while tData < tMax: noiseTimes = [] tData += self.Mdt if tData > tMax: tData = tMax while tNoise < min(tMax,tData): tNoise += self.Ndt noiseTimes.append(tNoise) if tNoise > tMax: tNoise = tMax h.continuerun(tNoise) cvodewrap.states(x) x.x[0] += self.sp*(self.evalW(tNoise) - self.evalW(tNoise-self.Ndt)) cvodewrap.yscatter(x) cvodewrap.re_init() Data.append([noiseTimes, x.x[0] + self.sm*self.evalM(tData)]) return Data
from neuron import h, crxd as rxd h.load_file("stdrun.hoc") cell = h.Section(name="cell") r = rxd.Region([cell]) def Declare_Parameters(**kwargs): """helper function enabling clean declaration of parameters in top namespace""" for key, value in kwargs.items(): globals()[key] = rxd.Parameter(r, name=key, initial=value) def Declare_Species(**kwargs): """helper function enabling clean declaration of species in top namespace""" for key, value in kwargs.items(): globals()[key] = rxd.Species(r, name=key, initial=value) k3 = rxd.Parameter(r, name="k3", initial=1.2) k4 = rxd.Parameter(r, name="k4", initial=0.6) P2 = rxd.Species(r, name="P2", initial=0.0614368) T2 = rxd.Species(r, name="T2", initial=0.0145428) C = rxd.Species(r, name="C", initial=0.207614) h.finitialize(-65) h.continuerun(72)
from matplotlib import pyplot import numpy import __main__ name = __main__.__file__ if name[-3 :] == '.py': name = name[: -3] h.load_file('stdrun.hoc') dend = h.Section() dend.diam = 2 dend.nseg = 101 dend.L = 100 diff_constant = 1 r = rxd.Region(h.allsec()) ca = rxd.Species(r, d=diff_constant, initial=lambda node: 1 if 0.4 < node.x < 0.6 else 0) h.finitialize() for t in [25, 50, 75, 100, 125]: h.continuerun(t) pyplot.plot([seg.x for seg in dend], ca.states) pyplot.tight_layout() pyplot.savefig('{0}.png'.format(name))
def continuerun(tstop, dt=0): if dt > 0: h.dt = dt h.continuerun(tstop)
cae_init = (0.0017 - cac_init * fc) / fe ca[er].concentration = cae_init #ip3.nodes.concentration = 2 for node in ip3.nodes: if node.x < .2: node.concentration = 2 h.CVode().re_init() s.variable('cai') #s.scale(-70, -50) s.scale(0, 2e-3) def dorec (dat, nl): i = 0 #to go over each node for node in nl: # print i dat[i][datacol] = node.concentration i += 1 tstop=3000 recdt = 100 datacol=0 tstop=1500 h.continuerun(tstop)
del my_other_cell h.topology() for sec in h.allsec(): print('%s: %s' % (sec, ', '.join(sec.psection()['density_mechs'].keys()))) stim = h.IClamp(my_cell.dend(1)) stim.get_segment() print(', '.join(item for item in dir(stim) if not item.startswith('__'))) stim.delay = 5 stim.dur = 1 stim.amp = 0.1 soma_v = h.Vector().record(my_cell.soma(0.5)._ref_v) dend_v = h.Vector().record(my_cell.dend(0.5)._ref_v) t = h.Vector().record(h._ref_t) amps = [0.075 * i for i in range(1, 5)] colors = ['green', 'blue', 'red', 'black'] f = plt.figure() for amp, color in zip(amps, colors): stim.amp = amp h.finitialize(-65 * mV) h.continuerun(25 * ms) plt.plot(t, soma_v, color=color) plt.plot(t, dend_v, color=color, LineStyle="--") plt.show()
soma.L = 18.8 soma.Ra = 123.0 soma.insert('hh') h.psection() # stim iclamp = h.IClamp(soma(0.5)) iclamp.delay = 100 iclamp.dur = 100 iclamp.amp = 0.1 # record v = h.Vector().record(soma(0.5)._ref_v) # Membrane potential vector t = h.Vector().record(h._ref_t) # Time stamp vector # run h.load_file('stdrun.hoc') #h.fcurrent() # Make all assigned variables (currents, conductances, etc) consistent with the values of the states. Useful in combination with finitialize(). h.finitialize(-64.97 * mV) h.continuerun(300 * ms) # plot import matplotlib.pyplot as plt plt.figure() plt.plot(t, v) plt.xlabel('t (ms)') plt.ylabel('v (mV)') plt.show() #input("Press Enter to continue...")
if name[-3 :] == '.py': name = name[: -3] h.load_file('stdrun.hoc') dend = h.Section() dend.diam = 2 dend.nseg = 101 dend.L = 100 rxd.set_solve_type(dimension=3) diff_constant = 1 r = rxd.Region(h.allsec(),dx=0.5) ca = rxd.Species(r, d=diff_constant, initial=lambda node: 1 if 0.4 < node.x < 0.6 else 0) h.finitialize() initial_amount = (numpy.array(ca.nodes.concentration) * numpy.array(ca.nodes.volume)).sum() for t in [25, 50, 75, 100, 125]: h.continuerun(t) pyplot.plot([nd.x for nd in ca.nodes], ca.nodes.concentration) final_amount = (numpy.array(ca.nodes.concentration) * numpy.array(ca.nodes.volume)).sum() print("initial {}\tfinal {}\tdiff {}".format(initial_amount, final_amount, initial_amount - final_amount)) pyplot.tight_layout() pyplot.savefig('{0}.png'.format(name)) pyplot.show()
cacyt_trace = h.Vector() cacyt_trace.record(ca[cyt].nodes(sec)(.5)[0]._ref_concentration) caer_trace = h.Vector() caer_trace.record(ca[er].nodes(sec)(.5)[0]._ref_concentration) ip3_trace = h.Vector() ip3_trace.record(ip3.nodes(sec)(.5)[0]._ref_concentration) times = h.Vector() times.record(h._ref_t) h.finitialize() cae_init = (0.0017 - cac_init *fc) / fe ca[er].concentration = cae_init for node in ip3.nodes: if node.x < 0.2: node.concentration = 2 h.CVode().re_init() h.continuerun(1000) pyplot.plot(times,cacyt_trace,label="ca[cyt]") pyplot.plot(times,caer_trace,label="ca[er]") pyplot.plot(times,ip3_trace,label="ip3") pyplot.legend() pyplot.show()
def flowJac(noiseTimes): cvodewrap.states(x) t0 = h.t print 't0' print t0 ss = [None] * (len(noiseTimes) + 1) k = 0 ss[0] = h.SaveState() ss[0].save() cvodewrap.re_init() while k < len(noiseTimes): print noiseTimes[k] h.continuerun(noiseTimes[k]) ss[k + 1] = h.SaveState() ss[k + 1].save() cvodewrap.re_init() k += 1 cvodewrap.states(value) # Derivative with respect to state DFx = pylab.zeros((len(value), len(x))) k = 0 while k < len(x): ss[0].restore(1) cvodewrap.re_init() cvodewrap.states(x) temp = x[k] if abs(temp) > 1: dx = sqrtEps * abs(temp) else: dx = sqrtEps x.x[k] = temp + dx cvodewrap.yscatter(x) cvodewrap.re_init() dx = x[k] - temp # trick to reduce finite precision error h.continuerun(noiseTimes[len(noiseTimes) - 1]) cvodewrap.states(df) df.sub(value) df.div(dx) DFx[:, k] = numpy.array(df) k += 1 # Derivative with respect to noise DFn = pylab.zeros((len(value), len(noiseTimes))) noiseTimes.insert(0, t0) k = 0 while k < len(noiseTimes) - 1: ss[k + 1].restore(1) cvodewrap.re_init() if k < len(noiseTimes) - 2: dx = sqrtEps cvodewrap.states(x) x.x[0] += sigp * math.sqrt(noiseTimes[k + 1] - noiseTimes[k]) * dx cvodewrap.yscatter(x) cvodewrap.re_init() h.continuerun(noiseTimes[len(noiseTimes) - 1]) cvodewrap.states(df) df.sub(value) df.div(dx) DFn[:, k] = numpy.array(df) else: DFn[:, k] = numpy.array( [sigp * math.sqrt(noiseTimes[k + 1] - noiseTimes[k]), 0, 0, 0]) k += 1 return [numpy.matrix(value).T, numpy.matrix(DFx), numpy.matrix(DFn)]
print "Max Step Set" h.stdinit() #h.cvode.queue_mode(1,0) h.celsius = 35.0 tfin = 0 if pc.id() == 0: print "Initialization Complete, Simulation Starting..." pc.barrier() tStart = time.time() for state in range(num_states): tvec.resize(0) idvec.resize(0) tfin += save_interval h.continuerun(tfin) spikes = {} for ii in range(len(tvec)): try: spikes[idvec[ii]].append(tvec[ii]) except KeyError: spikes[idvec[ii]] = [tvec[ii]] for ID in spikes: spikes[ID] = np.array(spikes[ID]) #time.sleep(int(pc.id())*0.1) # File writing issues; delays seem to work with open(scratchdir+"/spikeTimes"+str(int(pc.id())),'wb') as f: cPickle.dump(spikes,f,protocol=-1)
from neuron import h import matplotlib.pyplot as plt from neuron.units import mV, ms from diffusion.ca2.rectangular.cells.cell_rxd_ca import CellRxDCa from diffusion.ca2.rectangular.utils import record, plot3D_specie if __name__ == '__main__': h.load_file('stdrun.hoc') h.cvode.atol(1e-8) h.cvode.active(1) cell = CellRxDCa(name="cell") cell.add_sec(name="head", diam=1, l=1, nseg=11) cell.add_rxd() # record cas_head = record(cell.ca.nodes) t = h.Vector().record(h._ref_t) # init h.finitialize(-65 * mV) cell.ca.nodes[5].concentration = 0.01 h.cvode.re_init() # run h.continuerun(0.05 * ms) plot3D_specie(specie=cas_head, time=t) plt.show()
# WHERE the dynamics will take place where = rxd.Region(h.allsec()) # WHO the actors are u = rxd.Species(where, d=1, initial=0) # HOW they act bistable_reaction = rxd.Rate(u, -u * (1 - u) * (0.3 - u)) # initial conditions h.finitialize() for node in u.nodes: if node.x < .2: node.concentration = 1 def plot_it(color='k'): y = u.nodes.concentration x = u.nodes.x # convert x from normalized position to microns x = dend.L * numpy.array(x) pyplot.plot(x, y, color) plot_it('r') for i in xrange(1, 5): h.continuerun(i * 25) plot_it() pyplot.show()
def wave_search(size, size_segments, time_period, times, au, Du): # needed for standard run system h.load_file('stdrun.hoc') global dend dend = h.Section() dend.L = size dend.nseg = size_segments # WHERE the dynamics will take place where = rxd.Region(h.allsec()) # WHO the actors are global u global z global v u = rxd.Species(where, d=Du, initial=0.5) # activator z = rxd.Species(where, d=20, initial=0.5) # inhibitor v = rxd.Species(where, d=0, initial=(1 / dend.L) * 30) # modulator # HOW they act a = au b = -0.4 c = 0.6 d = -0.8 u0 = 0.5 z0 = 0.5 av = 5.0 kz = 0.001 bistable_reaction1 = rxd.Rate(u, (a * (u - u0) + b * (z - z0) - av * (u - u0)**3) * (v**-2)) bistable_reaction2 = rxd.Rate(z, (c * (u - u0) + d * (z - z0)) * (v**-2)) # initial conditions h.finitialize() for node in u.nodes: if node.x < .2: node.concentration = 0.6 if node.x > .8: node.concentration = 0.6 for node in z.nodes: if node.x < .2: node.concentration = 0.6 if node.x > .8: node.concentration = 0.6 # Setting up time frame global u_timespace T_d = times T = time_period u_timespace = [] for i in np.arange(0, T_d): h.continuerun(i * T) u_timespace.append(u.nodes.concentration) # activator FFT source files u_fft_y = u.nodes.concentration u_fft_y = u_fft_y - np.mean(u_fft_y) u_fft_x = u.nodes.x global u_fft_x_norm u_fft_x_norm = dend.L * np.array(u_fft_x) # inhibitor FFT source files z_fft_y = z.nodes.concentration z_fft_y = z_fft_y - np.mean(z_fft_y) z_fft_x = z.nodes.x z_fft_x_norm = dend.L * np.array(u_fft_x) # activator FFT Y1 = np.fft.fft(u_fft_y) N = len(Y1) / 2 + 1 dt = dend.L / dend.nseg fa = 1.0 / dt X = np.linspace(0, fa / 2, N, endpoint=True) # inhibitor FFT Y2 = np.fft.fft(z_fft_y) X2 = np.linspace(0, fa / 2, N, endpoint=True) # # if ((np.amax(Y1) - np.amin(Y1) < .01) or (np.amax(Y2) - np.amin(Y2) < .01)): # return 0 if (len(X) == len(2.0 * np.abs(Y1[:N] / N))): u_maxx = (np.argmax(2.0 * np.abs(Y1[:N] / N))) wavelen = np.around(1 / X[u_maxx]) plot_it(time_period, times, u_timespace) plt.savefig('results/plots/{0}_{1}_{2}_{3}_{4}_{5}.png'.format( size, size_segments, time_period, times, au, Du)) return wavelen
CNdegradation = rxd.Rate(CN, -kdN * CN) t = recorder(h._ref_t) h.finitialize(-65) mpvec = recorder(MP.nodes[0]._ref_concentration) cnvec = recorder(CN.nodes[0]._ref_concentration) p0vec = recorder(P0.nodes[0]._ref_concentration) p1vec = recorder(P1.nodes[0]._ref_concentration) p2vec = recorder(P2.nodes[0]._ref_concentration) cvec = recorder(C.nodes[0]._ref_concentration) h.finitialize(-65) h.CVode().active(True) print("starting simulation") start = time.time() h.continuerun(72 * hour) finish = time.time() - start print(finish) pt = (p0vec.as_numpy() + p1vec + p2vec + cvec + cnvec) / nM mp = mpvec.as_numpy() / nM cn = cnvec.as_numpy() / nM t_in_hours = t.as_numpy() / hour if __name__ == "__main__": from matplotlib import pyplot as plt plt.figure(figsize=(8, 6)) plt.plot(t_in_hours, mp, label="MP") plt.plot(t_in_hours, cn, label="CN") plt.plot(t_in_hours, pt, label="PT")
# WHO the actors are u = rxd.Species(where, d=1, initial=0) # HOW they act bistable_reaction = rxd.Rate(u, -u * (1 - u) * (0.3 - u)) # initial conditions h.finitialize() for node in u.nodes: if node.x < .2: node.concentration = 1 def plot_it(color='k'): y = u.nodes.concentration x = u.nodes.x # convert x from normalized position to microns x = dend.L * numpy.array(x) pyplot.plot(x, y, color) plot_it('r') interval = 50 t1 = time.time() for i in range(1, 5): h.continuerun(i * interval) plot_it() print(("Time = ", time.time() - t1)) pyplot.show()
def trivial_ecs(scale): from neuron import h, crxd as rxd import numpy import warnings warnings.simplefilter("ignore", UserWarning) h.load_file("stdrun.hoc") tstop = 10 if scale: # variable step case h.CVode().active(True) h.CVode().event(tstop) else: # fixed step case h.dt = 0.1 sec = h.Section() # NEURON requires at least 1 section # enable extracellular RxD rxd.options.enable.extracellular = True # simulation parameters dx = 1.0 # voxel size L = 9.0 # length of initial cube Lecs = 21.0 # lengths of ECS # define the extracellular region extracellular = rxd.Extracellular( -Lecs / 2.0, -Lecs / 2.0, -Lecs / 2.0, Lecs / 2.0, Lecs / 2.0, Lecs / 2.0, dx=dx, volume_fraction=0.2, tortuosity=1.6, ) # define the extracellular species k_rxd = rxd.Species( extracellular, name="k", d=2.62, charge=1, atolscale=scale, initial=lambda nd: 1.0 if abs(nd.x3d) <= L / 2.0 and abs(nd.y3d) <= L / 2.0 and abs(nd.z3d) <= L / 2.0 else 0.0, ) # record the concentration at (0,0,0) ecs_vec = h.Vector() ecs_vec.record(k_rxd[extracellular].node_by_location(0, 0, 0)._ref_value) h.finitialize() h.continuerun(tstop) # run the simulation # compare with previous solution ecs_vec.sub(h.Vector(trivial_ecs_data[scale])) ecs_vec.abs() if ecs_vec.sum() > 1e-9: return -1 return 0
h.load_file('stdrun.hoc') cell = Cell(name=0, mechanism='cadifusrect') cell.add_sec(name="head", diam=1, l=1, nseg=11) h.cvode.active(1) head = cell.secs['head'] # record cas_head = record(what=head, func=lambda seg: seg.cadifusrect._ref_ca[0]) t = h.Vector().record(h._ref_t) # init h.finitialize(-65 * mV) head(0.5).ca_cadifusrect[0] = 0.02 h.cvode.re_init() # run h.continuerun(0.1 * ms) data = [] for i in np.arange(start=0, stop=1 + 1e-10, step=1 / head.nseg): data.append(list(head(i).ca_cadifusrect)) data = np.array(data) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data) plot3D_specie(specie=cas_head, time=t) plt.show()
def run_current_steps_protocol(cell, amplitudes, ttran, tstep, dt=0.025, temperature=37., use_cvode=False): h.load_file('stdrun.hoc') print(timestamp() + '>> Inserting the stimulus...') stim = h.IClamp(cell.soma[0](0.5)) stim.dur = tstep stim.delay = ttran print(timestamp() + '>> Setting up the recorders...') rec = {} for lbl in 't','vsoma','spikes': rec[lbl] = h.Vector() rec['t'].record(h._ref_t) rec['vsoma'].record(cell.soma[0](0.5)._ref_v) apc = h.APCount(cell.soma[0](0.5)) apc.record(rec['spikes']) h.celsius = temperature h.dt = dt if use_cvode: h.tstop = stim.delay + stim.dur + 500 h.cvode_active(1) h.cvode.atol(1e-6) h.cvode.rtol(1e-6) h.cvode.maxstep(dt) else: h.tstop = stim.delay - 20 print(timestamp() + '>> Evolving the model until %g ms...' % h.tstop) sys.stdout.flush() h.run() print(timestamp() + '>> Saving the state...') ss = h.SaveState() ss.save() t = [] V = [] spike_times = [] for i,amp in enumerate(amplitudes): sys.stdout.write('\r' + timestamp() + '>> Trial [%02d/%02d] ' % (i+1,len(amplitudes))) sys.stdout.flush() if not use_cvode: ss.restore() stim.amp = amp apc.n = 0 rec['t'].resize(0) rec['vsoma'].resize(0) rec['spikes'].resize(0) if use_cvode: h.t = 0 h.run() else: h.continuerun(stim.delay + stim.dur + 500.) t.append(np.array(rec['t'])) V.append(np.array(rec['vsoma'])) spike_times.append(np.array(rec['spikes'])) sys.stdout.write('\n') if use_cvode: return np.array(t), np.array(V), np.array(spike_times) else: return np.array(V), np.array(spike_times)
def plot_voltage(self, ax=None, delay=2, duration=100, dt=0.2, amplitude=1, show=True): """Plot voltage on soma for an injected current Parameters ---------- ax : instance of matplotlib axis | None An axis object from matplotlib. If None, a new figure is created. delay : float (in ms) The start time of the injection current. duration : float (in ms) The duration of the injection current. dt : float (in ms) The integration time step amplitude : float (in nA) The amplitude of the injection current. show : bool Call plt.show() if True. Set to False if working in headless mode (e.g., over a remote connection). """ import matplotlib.pyplot as plt from neuron import h h.load_file('stdrun.hoc') soma = self.soma h.tstop = duration h.dt = dt h.celsius = 37 iclamp = h.IClamp(soma(0.5)) iclamp.delay = delay iclamp.dur = duration iclamp.amp = amplitude v_membrane = h.Vector().record(self.soma(0.5)._ref_v) times = h.Vector().record(h._ref_t) print('Simulating soma voltage') h.finitialize() def simulation_time(): print('Simulation time: {0} ms...'.format(round(h.t, 2))) for tt in range(0, int(h.tstop), 10): h.CVode().event(tt, simulation_time) h.continuerun(duration) print('[Done]') if ax is None: fig, ax = plt.subplots(1, 1) ax.plot(times, v_membrane) ax.set_xlabel('Time (ms)') ax.set_ylabel('Voltage (mV)') if show: plt.show()
# HOW they act bistable_reaction = rxd.Rate(u, -u * (1 - u) * (0.3 - u)) # initial conditions h.finitialize() for node in u.nodes: if node.x < .2: node.concentration = 1 def plot_it(color='k'): y = u.nodes.concentration x = u.nodes.x # convert x from normalized position to microns x = dend.L * numpy.array(x) pyplot.plot(x, y, color) plot_it('r') interval = 50 t1 = time.time() for i in range(1, 5): h.continuerun(i * interval) plot_it() print(("Time = ", time.time() - t1)) pyplot.show()
nc_grc.append(h.NetCon(grc, stl.GRC_L[0].input, 0, 0, 1)) pfs[0][0].seed(rnd.randint(0, 2e6)) fr = [] h.dt = 0.025 h.tstop = 1 h.v_init = -65 h.celsius = 21 import pylab h.run() #for i in range(-42,-42): h.continuerun(vc.dur[0] * .9) injects = [] injects.append(vc.i) h.continuerun(vc.dur[0] + vc.dur[1] * .9) injects.append(vc.i) h.continuerun(500) print injects print 'Rin = ', (vc.amp[0] - vc.amp[1]) * 1e-3 / ( (injects[0] - injects[1]) * 1e-9) * 1e-6, ' MOhm,' print h.area(.5) * 1e-8 print 'Gm = ', (injects[0] - injects[1]) * 1e-9 / ( (vc.amp[0] - vc.amp[1]) * 1e-3) / (h.area(.5) * 1e-8), ' S/cm2' print 'Temperature = ', h.celsius pylab.plot(stls[0].record['time'], vclampi) #pylab.plot(stls[0].record['time'],stls[0].PF_L[0].i['AMPA'][0]) pylab.ylim(-.1, .1)
10, -5) * (31.39 * math.exp((9.432 * pow(10, -5)) * time) - (3.059 * pow(10, 6)) * math.exp(-.06376 * time)) def turn_off(): for time in range(690, 1700): axon2(0.5475).hh.gl = 6.81 * pow( 10, -6) * (6.742 * pow(10, 10) * math.exp(-.03253 * time) + (22.43) * math.exp(-5 * pow(10, -5) * time)) axon2(0.5525).hh.gl = 6.81 * pow( 10, -6) * (6.742 * pow(10, 10) * math.exp(-.03253 * time) + (22.43) * math.exp(-5 * pow(10, -5) * time)) h.finitialize(-65) h.CVode().event(200, turn_on) h.CVode().event(700, turn_off) h.continuerun(1700) # Define the derivative function simulate laser induced temp change in water def difference(data_list): diff = list() for item in range(len(data_list) - 1): diff.append((data_list[item + 1] - data_list[item]) / 0.025) return diff ''' # Phase Plot of the Action Potentials list_v1 = list(v1) list_v2 = list(v2) list_v3 = list_v1[27644:28744] # Intercept a complete action potential list_v4 = list_v2[27450:28600] # Intercept a complete action potential list_v5 = difference(list_v3)
# -------------------------------- # Set up recording variables # -------------------------------- '''The cell should be configured to run a simulation. However, we need to indicate which variables we wish to record from; these will be stored in a NEURON Vector (h.Vector object). For now, we will record the membrane potential, which is soma(0.5).v and the corresponding time points (h.t). References to variables are available by preceding the last part of the variable name with a _ref_''' v = h.Vector().record(soma(0.5)._ref_v) # Membrane potential vector t = h.Vector().record(h._ref_t) # Time stamp vector # -------------------------------- # Run the simulation # -------------------------------- '''By default, the NEURON h module provides the low level fadvance function for advancing one time step. For higher-level simulation control specification, we load NEURON's stdrun library''' h.load_file('stdrun.hoc') '''We can then initialize our simulation such that our cell has a resting membrane potential of -65 mV''' h.finitialize(-65 * mV) '''And then continue the simulation from the current time (0) until 40 ms''' h.continuerun(40 * ms) # -------------------------------- # Plot the results # -------------------------------- print('\nPlotting model results...') plt.figure() plt.plot(t, v) plt.xlabel('t (ms)') plt.ylabel('v (mV)') plt.show()
ca_pump = rxd.MultiCompartmentReaction( ca[cyt], cao[ecs], ca[cyt] * scale, custom_dynamics=True, membrane_flux=True, membrane=mem, ) t = h.Vector().record(h._ref_t) ca_vec = h.Vector().record(soma(0.5)._ref_cai) ca_vec2 = h.Vector().record(cao.nodes(soma(0.5))._ref_value) v = h.Vector().record(soma(0.5)._ref_v) h.finitialize(-65 * mV) h.continuerun(100 * ms) if __name__ == "__main__": import matplotlib.pyplot as plt plt.subplot(2, 1, 1) plt.plot(t, ca_vec * 1000, label="inside") plt.plot(t, ca_vec2 * 1000, label="outside") plt.ylabel("[Ca] (uM)") plt.legend() plt.subplot(2, 1, 2) plt.plot(t, v) plt.ylabel("v (mV)") plt.xlabel("t (ms)") plt.show()
def run_atype_test(param_dict={}, inhib_levels=[0.0, 1.0], run_time=300, current_dict={ 'amp': 0.0, 'start': 0.0, 'dur': 0.0 }): t_path = join(os.getcwd(), 'morphologies/mpg141209_A_idA.asc') my_cells = [] my_clamps = [] soma_v_vecs = [] s_ika_vecs = [] apic_v_vecs = [] a_ika_vecs = [] for i_i, i_val in enumerate(inhib_levels): my_cells.append(ca1p.MyCell(t_path, True, param_dict)) for sec in my_cells[-1].apical: for seg in sec: pre_val = seg.gkabar_kad seg.gkabar_kad = i_val * pre_val my_clamps.append(h.IClamp(my_cells[-1].somatic[0](0.5))) my_clamps[-1].amp = current_dict['amp'] my_clamps[-1].delay = current_dict['start'] my_clamps[-1].dur = current_dict['dur'] soma_v_vecs.append(h.Vector().record( my_cells[-1].somatic[0](0.5)._ref_v)) apic_v_vecs.append(h.Vector().record( my_cells[-1].apical[35](0.5)._ref_v)) s_ika_vecs.append(h.Vector().record( my_cells[-1].somatic[0](0.5)._ref_ik_kap)) a_ika_vecs.append(h.Vector().record( my_cells[-1].apical[35](0.5)._ref_ik_kad)) t_vec = h.Vector().record(h._ref_t) print('Cells and Records created') cv_act = 1 h.cvode.active(cv_act) h.v_init = -69.4 h.celsius = 34.0 print('cvode active: {0}'.format(cv_act)) s_v_dict = {} a_v_dict = {} s_ika_dict = {} a_ika_dict = {} h.stdinit() print('Initialized') h.continuerun(run_time) print('Finished Running') for i_i, i_val in enumerate(inhib_levels): s_v_dict[i_i] = np.array(soma_v_vecs[i_i]) a_v_dict[i_i] = np.array(apic_v_vecs[i_i]) s_ika_dict[i_i] = np.array(s_ika_vecs[i_i]) a_ika_dict[i_i] = np.array(a_ika_vecs[i_i]) res_dict = { 'soma_v_dict': s_v_dict, 'apical_v_dict': a_v_dict, 'soma_ika_dict': s_ika_dict, 'apical_ika_dict': a_ika_dict, 'inhibition_values': np.array(inhib_levels), 't': np.array(t_vec), } return res_dict
cae_init = (0.0017 - cac_init * fc) / fe ca[er].concentration = cae_init #ip3.nodes.concentration = 2 for node in ip3.nodes: if node.x < .2: node.concentration = 2 h.CVode().re_init() s.variable('cai') #s.scale(-70, -50) s.scale(0, 2e-3) def dorec(dat, nl): i = 0 #to go over each node for node in nl: # print i dat[i][datacol] = node.concentration i += 1 tstop = 3000 recdt = 100 datacol = 0 tstop = 1500 h.continuerun(tstop)
def get_base_vm_cli(neuron_model=None, default_cli=4, **kwargs): """ Determine steady-state internal chloride concentration by 1) instantiating a class that extends BaseNeuron (NOTE: class should not have spiking at default values) 2) adding KCC2 using the add_kcc2() method 3) setting [Cl]_i to an arbitrary value (can be set in method invocation) 4) running a fast simulation for a long time 5) checking if chloride is at steady state (repeat 4 until it is) 6) return steady state Vm and [Cl]_i :param neuron_model: class extending BaseNeuron :param default_cli: arbitrary value of [Cl]_i hopefully close to steady state :return: steady state Vm and [Cl]_i """ from baseneuron import BaseNeuron remove_kcc2 = False if neuron_model is None: neuron_model = BaseNeuron if isinstance(neuron_model, BaseNeuron): # is instantiation of class base = neuron_model if not base.kcc2_inserted: base.add_kcc2() remove_kcc2 = True base.set_cl(default_cli) else: # is BaseNeuron class (or child class) base = neuron_model(**kwargs) base.add_kcc2() base.set_cl(default_cli) h.tstop = 50000 h.useCV() h.finitialize(-65) h.run() def at_steady_state(continue_dt): """ check if [Cl]_i is at steady state :param continue_dt: amount of time to run :return: [Cl]_i if at steady state, False otherwise """ v_start = base.soma(.5)._ref_v[0] cli_start = base.soma(.5)._ref_cli[0] h.continuerun(h.tstop + continue_dt) h.tstop += continue_dt v_after = base.soma(.5)._ref_v[0] cli_after = base.soma(.5)._ref_cli[0] if v_after - v_start < 1e-6 and cli_after - cli_start < 1e-6: return cli_after else: return False num_steady_state_checks = 0 while not at_steady_state(1): h.continuerun(h.tstop + 10000) h.tstop += 10000 num_steady_state_checks += 1 if num_steady_state_checks > 10: print("not at steady state even after {} ms".format( 50000 + num_steady_state_checks * 10000)) exit(-1) h.disableCV() vm, cli = base.soma(.5)._ref_v[0], base.soma(.5)._ref_cli[0] logger.info("steady state [Cl]_i {}".format(cli)) logger.info("steady state Vm {}".format(vm)) logger.info( "took {} ms (simulation time)".format(50000 + num_steady_state_checks * 10000)) if remove_kcc2: base.remove_kcc2() h.finitialize(vm) return vm, cli
cell1_X.record(cell1(0.5)._ref_xi) cell1_Xorg = h.Vector() cell1_Xorg.record(Xorg.nodes(cell1)(0.5)[0]._ref_concentration) cell1V = h.Vector() cell1V.record(cell1(0.5)._ref_v) cell2_X = h.Vector() cell2_X.record(cell2(0.5)._ref_xi) cell2_Xorg = h.Vector() cell2_Xorg.record(Xorg.nodes(cell2)(0.5)[0]._ref_concentration) cell2V = h.Vector() cell2V.record(cell2(0.5)._ref_v) # run and plot the results h.finitialize(-65) h.continuerun(1000) if __name__ == "__main__": from matplotlib import pyplot fig = pyplot.figure() pyplot.subplot(2, 2, 1) pyplot.plot(t_vec, cell1_X, label="cyt") pyplot.plot(t_vec, cell1_Xorg, label="org") pyplot.legend() pyplot.xlabel("t (ms)") pyplot.ylabel("cell 1 x (mM)") pyplot.subplot(2, 2, 2) pyplot.plot(t_vec, cell2_X, label="cyt") pyplot.plot(t_vec, cell2_Xorg, label="org") pyplot.xlabel("t (ms)")
from matplotlib import pyplot h.load_file('stdrun.hoc') sec = h.Section() sec.nseg = 5 sec.L = 100 r = rxd.Region([sec]) na = rxd.Species(r, initial=lambda foo: 1) ca = rxd.Species(r, initial=lambda foo: 0) # not at all biophysical, but just for a test na_wave = rxd.Rate(na, -ca) ca_wave = rxd.Rate(ca, na) def plot_it(): pyplot.subplot(2, 1, 1) pyplot.plot([seg.x * sec.L for seg in sec], ca.states) pyplot.subplot(2, 1, 2) pyplot.plot([seg.x * sec.L for seg in sec], na.states) h.finitialize() h.fadvance() h.continuerun(1.57) print na.states print ca.states