Example #1
0
 def __init__(self, post_cell, info):
     """
     info is a dict
     """
     pre_cells = []
     synapses = []
     j = 0
     xmtr = {}
     for nsgc, sgc in enumerate(range(info['n_sgc'])):
         pre_cells.append(cells.DummySGC(cf=info['cf'], sr=info['sr']))
         if synapseType == 'simple':
             synapses.append(pre_cells[-1].connect(post_cell, type=synapseType))
             synapses[-1].terminal.netcon.weight[0] =info['gmax']*2.0
         elif synapseType == 'multisite':
             synapses.append(pre_cells[-1].connect(post_cell, post_opts={'AMPAScale': 2.0, 'NMDAScale': 2.0}, type=synapseType))
             for i in range(synapses[-1].terminal.n_rzones):
                 xmtr['xmtr%04d'%j] = h.Vector()
                 xmtr['xmtr%04d'%j].record(synapses[-1].terminal.relsite._ref_XMTR[i])
                 j = j + 1
             synapses[-1].terminal.relsite.Dep_Flag = False  # no depression in these simulations
         pre_cells[-1].set_sound_stim(info['stim'], seed = info['seed'] + nsgc, simulator=info['simulator'])
     Vm = h.Vector()
     Vm.record(post_cell.soma(0.5)._ref_v)
     rtime = h.Vector()
     rtime.record(h._ref_t)
     h.tstop = 1e3*info['run_duration'] # duration of a run
     h.celsius = info['temp']
     h.dt = info['dt']
     post_cell.cell_initialize()
     info['init']()
     h.t = 0.
     h.run()
     return {'time': np.array(rtime), 'vm': Vm.to_python(), 'xmtr': xmtr, 'pre_cells': pre_cells, 'post_cell': post_cell, 'synapses': synapses}
Example #2
0
def getfi(amp, simiter):
    h.tstop = 500  # to match synaptic input runs
    h.tsamp = h.tstop / h.dt + 1
    tsamp = int(h.tsamp)

    # 'background' injection
    npy.random.seed(int(simiter + h.luckyoffset))
    icr = h.IClamp(0.5, sec=h.soma)
    icr.dur = h.tstop
    if numbranches == 2:
        icmean = .75
    if numbranches == 8:
        icmean = 0
    icstd = 1
    icvals = icmean + icstd * npy.random.randn(tsamp)
    icrand = h.Vector(tsamp)
    for i in xrange(tsamp):
        icrand.x[i] = icvals[i]
    icrand.play(icr._ref_amp, h.dt)

    # do current injection run
    ic = h.IClamp(0.5, sec=h.soma)
    ap = h.APCount(0.5, sec=h.soma)
    ic.delay = 0
    ic.dur = h.tstop
    ic.amp = amp
    h.run()
    return ap.n * 1000. / h.tstop
Example #3
0
def gabaInit(excmin):
    oldtstop = h.tstop
    h.tstop = 5000  # Simulation time
    print "Setting initial glutamatergic synapse..."
    # Set excitatory conductances with minimal tone
    topo.excGset(BPsyn,
                 gmax=excmin,
                 gmin=excmin,
                 synapse_type=synapse_type,
                 tau=BPsyn_tau)
    if is_spatiotemporal:
        topo.apply_spatiotemporal_synaptic_input(BPsyn, dend_input_segments,
                                                 BPtau1, BPtau2)
    stim.set_stimulus(BPsyn, stimulus_type, t_es, synapse_type, **stim_param)
    print "Setting gabaergic synapse parameters..."
    topo.gabaGset(gabasyn, synM, gabaGmax, gabaGmin, k1, k2, th1, th2)
    param_log()
    print "Parameters OK. Steady-state simulation started..."
    nrn_init(v_init)
    print "RUN, Neuron...RUN!"
    h.run()
    print "Saving steady-state outputs..."
    initsc1 = [syn.sc1 for syn in gabasyn]
    initsc2 = [syn.sc2 for syn in gabasyn]
    print "Steady-state simulation finished!"
    h.tstop = oldtstop
    return initsc1, initsc2
Example #4
0
	def RunSim(self):

		num_iters = 60
		recovered_thresh = -40

		# Prepare simulation
		record_loc_idx = int(self.n_exc/2)
		record_loc = self.exc_locs[record_loc_idx]

		# Prepare recording vectors
		t = h.Vector(); t.record(h._ref_t)
		shaft_v = h.Vector(); shaft_v.record(self.dend(record_loc)._ref_v)

		if self.soma:
			soma_v = h.Vector(); soma_v.record(self.soma(0.5)._ref_v)
		else:
			soma_v = [] # Reset soma_v between simulations

		if self.spine_heads:
			spine_v = h.Vector(); spine_v.record(self.spine_heads[record_loc_idx](1)._ref_v)
		else:
			spine_v = [] # Reset spine_v between simulations

		# Run simulation (hoc interpreter commands)
		h.finitialize() # Initialize gating mechanisms
		h.run()			# Run simulation

		# Plot traces
		self.vectors['t'] = t
		self.vectors['shaft_v'] = shaft_v
		self.vectors['soma_v'] = soma_v
		self.vectors['spine_v'] = spine_v
Example #5
0
def run(tstop=1000, dt=0, V=-65):
    h.load_file('stdrun.hoc')
    #h.finitialize(V)
    if dt > 0:
        h.dt = dt
    h.tstop = tstop
    h.run()
Example #6
0
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)
Example #7
0
def simulatepar(delay, dur, length, std, offset, amp, freq, dt, tau, mu, loc,
                simdur, init, cel, seed, loop):
    soma, axon = Mcm.create_sec('soma', 'axon')
    Mcm.define_geometry(soma, 30, 20, 1)
    Mcm.define_geometry(axon, length, 1, 11)
    Mcm.build_topology_axso(axon, soma, 0)
    Mcm.define_biophysics(2, soma, 250, 400, 0.3e-3, .75, 150, -65, 55, -70,
                          -25., 6., -35., 6., -15., 4.)
    Mcm.define_biophysics(2, axon, 0, 500, 0.3e-3, .75 * 0.75, 150, -65, 55,
                          -70, -25., 6., -35., 6., -15., 4.)

    axon(0.9).gbar_na = 1000 * 15
    counts = h.Vector()
    apc = h.APCount(soma(0.5))
    apc.thresh = -15
    apc.record(counts)
    stim = attach_noise_sin_clamp(soma, delay, dur, offset, amp, freq, dt, tau,
                                  std, mu, loc, seed)
    # soma_vec, axon_vec, i_inj_vec, t_vec = set_recording_vectors(stim, soma, axon)
    h.dt = dt
    h.tstop = simdur
    h.v_init = init
    h.celsius = cel
    h.run()
    filename = './OUTPUT/spiketrain5Hzmfr' + str(length) + 'length' + str(
        freq) + 'freq' + str(std) + 'std' + str(seed) + 'seed' + str(
            loop) + 'loop.txt'
    writetofile(filename, counts)
    return 0
Example #8
0
def test_spikes():
    ref_spikes = np.array([1.05])

    h('''create soma''')
    h.load_file("stdrun.hoc")
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    h.soma.insert("hh")
    ic = h.IClamp(h.soma(0.5))
    ic.delay = 0.5
    ic.dur = 0.1
    ic.amp = 0.3

    v = h.Vector()
    v.record(h.soma(0.5)._ref_v, sec=h.soma)
    tv = h.Vector()
    tv.record(h._ref_t, sec=h.soma)
    nc = h.NetCon(h.soma(0.5)._ref_v, None, sec=h.soma)
    spikestime = h.Vector()
    nc.record(spikestime)
    h.run()

    simulation_spikes = spikestime.to_python()

    assert np.allclose(simulation_spikes, ref_spikes)
Example #9
0
    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:
            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))
Example #10
0
def main():
    soma = h.Section()
    soma.insert('pas')
    soma.L = 100
    soma.diam = 100
    weight_min = 0.005
    weight_max = 0.05
    mu = (np.log(weight_min)+np.log(weight_max))/2
    sigma = (np.log(weight_max)-mu)/3
    weights = np.sort(np.exp(np.random.normal(mu,sigma,size=200)))
    synapses = [AMPASynapse(soma, 0.5, 0, w) for w in weights]
    for i,syn in enumerate(synapses):
        syn.set_presynaptic_spike_times([10+i*50])
    rec = {}
    for lbl in 't','v','g':
        rec[lbl] = h.Vector()
    rec['t'].record(h._ref_t)
    rec['v'].record(soma(0.5)._ref_v)
    rec['g'].record(syn.syn._ref_g)
    h.load_file('stdrun.hoc')
    h.v_init = -70
    h.celsius = 37
    h.tstop = len(weights)*50 + 100
    h.run()
    import pylab as p
    p.subplot(2,1,1)
    p.plot(rec['t'],rec['v'],'k')
    p.ylabel('Voltage (mV)')
    p.subplot(2,1,2)
    p.plot(rec['t'],rec['g'],'r')
    p.xlabel('Time (ms)')
    p.ylabel('Conductance (uS)')
    p.show()
Example #11
0
def test_simple_synaptic_input():
    soma = h.Section()
    soma.insert("hh")
    soma.insert("pas")
    tl = TargetLocation(soma, 0.5)
    proc = h.ExpSyn 

    ac = ArtificialCell()
    fire_times = np.linspace(0,50,10)
    firetimes = h.Vector(fire_times)
    ac.setFireTimes(firetimes)
    
    ic = InputConnection(ac, tl, proc)

    v = h.Vector()
    v.record(soma(0.5)._ref_v)
   
    h.tstop = 100
    h.run()

    test_result = np.array(v)
    correct = np.load("test_simple_synaptic_input_data.npy")

    print sum(abs(test_result - correct))

    #pyl.plot(test_result)
    #pyl.plot(correct)
    #pyl.show()

    assert np.all(test_result == correct)
    def simulate(self, tstop=100.0, dendrite_to_record=False, pandas=False):
        if dendrite_to_record:
            for section in self.dendrites:
                if section.name() == dendrite_to_record:
                    self.dendrite = section
        if self.dend_to_patch:
            print 'havent overwritten the simulate rdend argument - use it!'
        h.load_file('stdrun.hoc')

        self.rec = {}
        for label in 't', 'v', 'vdend':
            self.rec[label] = h.Vector()
        self.rec['t'].record(h._ref_t)
        self.rec['vdend'].record(self.dendrite(0.5)._ref_v)
        self.rec['v'].record(self.root(0.5)._ref_v)

        h.tstop = tstop
        h.v_init = self.leak_reversal
        h.celsius = 32.0
        h.dt = 0.01
        h.run()

        v_dend = self.rec['vdend'].to_python()
        v_soma = self.rec['v'].to_python()
        t = self.rec['t'].to_python()

        results = pd.DataFrame(np.array([t, v_soma, v_dend]).T,
                               columns=['time', 'v_soma', 'v_dend'])
        if pandas:
            return results
        else:
            if dendrite_to_record:
                return np.array(v_soma), np.array(t), np.array(v_dend)
            else:
                return np.array(v_soma), np.array(t)
Example #13
0
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:
Example #14
0
    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 getRMP(self, parameters, debug=False):
        if not self.stop:
            # Simulation parameters
            h.load_file('stdrun.hoc')
            h.load_file('negative_init.hoc')
            tstop = 100
            dt = 0.025
            h.stdinit()
            h.celsius = 37.0
            h.tstop = tstop
            h.v_init = -65

            # Instantiate and parameterize cells
            testCell = cell.Cell(0, (0, 0), self.synvars, 'granulecell',
                                 'output0_updated.swc')
            self.parameterizeCell(testCell, parameters)

            # Instrument cells
            self.RMPv = h.Vector()
            self.RMPv.record(testCell.c.soma[0](0.5)._ref_v)

            # Run simulation
            h.run()

            # Get RMP
            self.RMP = self.RMPv[-1]
            if debug:
                return [np.array([self.RMP]), np.array([self.RMPv])]
            else:
                return np.array([self.RMP])
        else:
            return 1e9
Example #16
0
def simulate(tstop=25):
    """Initialize and run a simulation.

    :param tstop: Duration of the simulation.
    """
    h.tstop = tstop
    h.run()
Example #17
0
def simulate(tstop=25):
    """Initialize and run a simulation.

    :param tstop: Duration of the simulation.
    """
    h.tstop = tstop
    h.run()
Example #18
0
def p(nm, pm=None):
    global name, vviv, params, vvset
    import izhi2007Figs as iz07fig
    if pm is None: pm = choices[izhtype][2][nm]
    name, params = nm, pm
    if newmodel():
        izh.C, izh.k, izh.vr, izh.vt, izh.vpeak, izh.a, izh.b, izh.c, izh.d, izh.celltype = params
        h.tstop = 1000
    else:
        izh.a, izh.b, izh.c, izh.d, vviv, h.tstop = params
    g.size(0, h.tstop, -100, 50)
    try:
        if newmodel():
            graphx()  # interviews graphics
            iz07fig.recorder(
                cell07,
                choices[izhtype][1]())  # vectors to draw under matplotlib
            iz07fig.test1(cell07, nm, izhtype)
        else:
            iz07fig.closeFig()
            graphx()
            playinit()
            h.run()
    except:
        print sys.exc_info()[0], ' :', sys.exc_info()[1]
Example #19
0
    def run_syn(self):

        # initiate recording
        rec_t = h.Vector()
        rec_t.record(h._ref_t)

        rec_v = h.Vector()
        rec_v.record(h.soma(0.5)._ref_v)

        rec_v_dend = h.Vector()
        rec_v_dend.record(h.dendrite[self.ndend](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
Example #20
0
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')
Example #21
0
def synapses_vs_weights(filename="distal", param_list=None):
    """Clump synapses and vary synapse numbers and synapse weights.

    param_list contains tuples of (exc_syn, inh_syn, exc_weight, inh_weight, clump)

    """
    import itertools
    syn_list = param_list
    if not syn_list:
        syn_list = itertools.product([1, 10, 100], [1, 10, 100],  # E, I synapse numbers
                                     [1, 5, 10], [1, 5, 10],  # E, I synapse weights
                                     [1, 10, 100]  # clumping
                                     )
        syn_list = [(10, 10, 1, 1, 10), (10, 10, 5, 5, 10), (10, 10, 10, 20, 10),
                    (10, 100, 18, 6, 10),
                    (10, 10, 18, 60, 10), (10, 10*100, 18, 6, 10), (10, 10, 18, 6*100, 10)]
    load_file(filename)
    icl_rec_vec = h.Vector()
    icl_rec_vec.record(h.ldend(0.5)._ref_icl)
    h.tstop = 500
    h("forall{cli=4.25}")
    h.hoc_stdout("synapses_vs_weights.txt")
    base_gmax = 0.00005  # uS
    inh_hz = 10
    for gmax_weight in [False]:
        print("gmax_weight: {} ".format(gmax_weight))
        for (i, (exc, inh, exc_weight, inh_weight, clump)) in enumerate(syn_list):
            h.newSynapses(exc, inh)
            h.clumpSynapses(clump)
            print("clumped")
            g_rec_vec_list = list()
            for g in range(int(h.ninh)):
                g_rec_vec = h.Vector()
                g_rec_vec.record(h.GABAa[g]._ref_g)
                g_rec_vec_list.append(g_rec_vec)

            h.exHz(10000, 1, exc_weight)
            if gmax_weight:
                h.inHz(inh_hz, 1, 1)
                h.gmax_GABAa = base_gmax*inh_weight
            else:
                h.inHz(inh_hz, 1, inh_weight)
            print(syn_list[i])
            icl_mean = []
            icl_stdev = []
            spikes_mean = []
            g_total_mean = []
            for k in range(5):
                h.run()
                icl_mean.append(icl_rec_vec.mean()*1e6)
                icl_stdev.append(icl_rec_vec.stdev()*1e6)
                spikes_mean.append(h.apc.n)
                total_g = 0
                for g_rec_vec in g_rec_vec_list:
                    total_g += g_rec_vec.mean()
                g_total_mean.append(total_g)
            print("icl_mean: \tmean:\t {} \tstd:\t {}".format(np.mean(icl_mean), np.std(icl_mean)))
            print("icl_stdev: \tmean:\t {} \tstd:\t {}".format(np.mean(icl_stdev), np.std(icl_stdev)))
            print("g total: \tmean:\t {} \tstd:\t {}".format(np.mean(g_total_mean), np.std(g_total_mean)))
            print("spikes: \tmean:\t {} \tstd:\t {}".format(np.mean(spikes_mean), np.std(spikes_mean)))
Example #22
0
def simulatepar(delay, dur, Ra, std, offset, amp, freq, dt, tau, mu, loc,
                simdur, init, cel, seed):
    soma, axon = Mcm.create_sec('soma', 'axon')
    Mcm.define_geometry(soma, 30, 20, 5)
    Mcm.define_geometry(axon, 50, 1, 11)
    Mcm.build_topology_axso(axon, soma, 0)
    Mcm.define_biophysics(2, soma, 800, 320, 1 / 30000, 0.75, 150, -70, 60,
                          -80)
    Mcm.define_biophysics(2, axon, 0, 1600, 1 / 30000, 0.75 * 0.75, 150, -70,
                          60, -80)
    axon(Ra).gbar_na = 8000 * 15
    counts = h.Vector()
    apc = h.APCount(soma(0.5))
    apc.thresh = 0
    apc.record(counts)
    stim = attach_noise_sin_clamp(soma, delay, dur, offset, amp, freq, dt, tau,
                                  std, mu, loc, seed)
    # soma_vec, axon_vec, i_inj_vec, t_vec = set_recording_vectors(stim, soma, axon)
    h.dt = dt
    h.tstop = simdur
    h.v_init = init
    h.celsius = cel
    h.run()
    filename = './OUTPUT/spiketrain5Hzmfr' + str(Ra) + 'Ra' + str(
        freq) + 'freq' + str(std) + 'std' + str(seed) + 'seed.txt'
    writetofile(filename, counts)
    return 1
Example #23
0
def scalar_bistable(rxdstr):
    if rxdstr == 'rxd':
        from neuron import rxd
    else:
        from neuron import crxd as rxd
    h.load_file('stdrun.hoc')
    s = h.Section(name='s')
    s.nseg = 101
    cyt = rxd.Region(h.allsec())
    c = rxd.Species(cyt,
                    name='c',
                    initial=lambda node: 1 if 0.4 < node.x < 0.6 else 0,
                    d=1)
    r = rxd.Rate(c, -c * (1 - c) * (0.3 - c))
    h.finitialize()
    h.run()

    #check the results
    result = h.Vector(c.nodes.concentration)
    cmpV = h.Vector(scalar_bistable_data[rxdstr])
    cmpV.sub(result)
    cmpV.abs()
    if cmpV.sum() < 1e-6:
        sys.exit(0)
    sys.exit(-1)
Example #24
0
def FiringOnset(leftI, rightI, precision, apc, stim, T, fr_set):
    import neuron
    from neuron import h
    from I_proc import stimulate
    while ((rightI - leftI) > precision * max([abs(rightI), abs(leftI)])):
        print("leftI is %f, rightI is %f" % (leftI, rightI))
        print("rightI-leftI: %f , precision: %f \n" %
              ((rightI - leftI), precision))
        h.finitialize()
        h.fcurrent()
        h.frecord_init()
        apc.n = 0
        mean = (leftI + rightI) / 2
        print('mean is %f' % (mean))
        h.stim = stimulate([0, stim, mean])
        h.tstop = T
        h.run()
        fr = apc.n / float(T / 1000)
        print('fr is %f' % (fr))
        if (fr <= fr_set):
            leftI = mean  # If the firing rate is too small, we will replace lowerbound with middle point
        else:
            rightI = mean  # If the firing rate is too large, we will replace upperbound with middle point

    if fr_set > 0:
        return rightI
    else:
        return leftI
Example #25
0
    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](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
Example #26
0
def simulation(tstop, with_time = False):
    """
    runs the simulation and returns the current and
    time vectors as Numpy arrays
    """
    h.load_file('stdrun.hoc')
    h.v_init = -70
    
    h.tstop = tstop
    VC_patch.dur1 = tstop

    # define vectors
    current = h.Vector()
    current.record(VC_patch._ref_i)
   
    if with_time is True:
        time = h.Vector()
        time.record(h._ref_t)

    h.run()

    if with_time is True:
        return (time, np.array(current)*1000.)
    else:
        return np.array(current)*1000. 
Example #27
0
def get_passive_properties(soma):
    v_init = h.v_init = -60
    stim = h.IClamp(soma(0.5))
    stim.delay = 100.0  #ms
    stim.dur = 500.0  #ms
    tstop = h.tstop = 1000  #ms
    h.dt = 0.025
    q = int(tstop / h.dt)
    t_i = int((stim.delay + stim.dur - 5) / h.dt)
    t_r = int((stim.delay - 1) / h.dt)

    stim.amp = -0.1
    v0_vec = h.Vector()
    t_vec = h.Vector()
    v0_vec.record(soma(0.5)._ref_v)
    t_vec.record(h._ref_t)
    h.run()
    dt_V = v0_vec[t_i] - v0_vec[t_r]

    props = {}
    props["R_in"] = dt_V / stim.amp
    props["tau"] = soma.cm * props["R_in"]
    props["Vrest"] = v0_vec[30000]

    return props
Example #28
0
def get_F_properties(soma, I_0):
    f_prop = {}

    v_init = h.v_init = -60
    stim = h.IClamp(soma(0.5))
    stim.delay = 100.0  #ms
    stim.dur = 500.0  #ms
    tstop = h.tstop = 1000  #ms
    h.dt = 0.025
    freq = []
    count = 0

    for stim.amp in np.arange(I_0, I_0 + 0.41, 0.1):
        v0_vec = h.Vector()
        t_vec = h.Vector()
        v0_vec.record(soma(0.5)._ref_v)
        t_vec.record(h._ref_t)
        nc = h.NetCon(soma(0.5)._ref_v, None, sec=soma)
        nc.threshold = 0
        spvec = h.Vector()
        nc.record(spvec)
        h.run()

        if len(spvec) > 1 and spvec.x[0] > 100:
            #freq.append(len(spvec)/stim.dur)
            f_prop["F" + str(count)] = len(spvec) / stim.dur
            count = count + 1

    return f_prop
Example #29
0
def test_direct_memory_transfer():
    h('''create soma''')
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    h.soma.insert("hh")
    ic = h.IClamp(h.soma(.5))
    ic.delay = .5
    ic.dur = 0.1
    ic.amp = 0.3

    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    v = h.Vector()
    v.record(h.soma(.5)._ref_v, sec=h.soma)
    i_mem = h.Vector()
    i_mem.record(h.soma(.5)._ref_i_membrane_, sec=h.soma)
    tv = h.Vector()
    tv.record(h._ref_t, sec=h.soma)
    h.run()
    vstd = v.cl()
    tvstd = tv.cl()
    i_memstd = i_mem.cl()

    pc = h.ParallelContext()
    h.stdinit()
    pc.nrncore_run("-e %g" % h.tstop, 0)

    assert (tv.eq(tvstd))
    assert (v.cl().sub(vstd).abs().max() < 1e-10)
    assert (i_mem.cl().sub(i_memstd).abs().max() < 1e-10)
Example #30
0
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 simulate(celsius=20, tstop=20, dt=0.001):
    #Initialize and run a simulation.
    #	:param tstop: Duration of the simulation.
    #	:param dt: time resolution (ms).
    h.celsius = celsius
    h.tstop = tstop
    h.dt = dt
    h.run()
Example #32
0
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
Example #33
0
def runSimulation_v2(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.
    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))

    #Run the simulation.
    h.load_file("stdrun.hoc")
    h.init()
    h.tstop = simTime
    h.run()

    #Write results.
    if age == 1:
        file = open(path + 'spikesYoung_2_' + fileIndex + '.txt', "wb")
    elif age == 2:
        file = open(path + 'spikesOld1_2_' + fileIndex + '.txt', "wb")
    else:
        file = open(path + 'spikesOld2_2_' + 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()
Example #34
0
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()
Example #35
0
        def test():
            from blenderneuron.quick import bn

            with Blender(keep=False):

                from neuron import h
                h.load_file(test_hoc_file)
                tc1 = h.TestCell()
                tc2 = h.TestCell()

                ic = h.IClamp(0.5, sec=tc1.soma)
                ic.delay = 1
                ic.dur = 3
                ic.amp = 0.5

                bn.prepare_for_collection()
                bn.groups["all"]["3d_data"]["interaction_level"] = "Section"
                bn.groups["all"]["3d_data"]["color_level"] = "Cell"

                h.run()

                bn.to_blender()

                self.assertTrue(
                    bn.run_command(
                        "return_value = 'TestCell[0].soma' in bpy.data.objects"
                    ))
                self.assertTrue(
                    bn.run_command(
                        "return_value = 'TestCell[1].soma' in bpy.data.objects"
                    ))

                self.assertTrue(
                    bn.run_command(
                        "return_value = 'TestCell[0]' in bpy.data.materials"))
                self.assertTrue(
                    bn.run_command(
                        "return_value = 'TestCell[1]' in bpy.data.materials"))

                bn.run_command("bpy.data.scenes['Scene'].frame_current = 0")
                self.assertEqual(
                    bn.run_command(
                        "return_value = bpy.data.materials['TestCell[0]'].emit"
                    ), 0.0)
                self.assertEqual(
                    bn.run_command(
                        "return_value = bpy.data.materials['TestCell[1]'].emit"
                    ), 0.0)

                bn.run_command("bpy.data.scenes['Scene'].frame_current = 7")
                self.assertEqual(
                    bn.run_command(
                        "return_value = bpy.data.materials['TestCell[0]'].emit"
                    ), 2.0)
                self.assertEqual(
                    bn.run_command(
                        "return_value = bpy.data.materials['TestCell[1]'].emit"
                    ), 0.0)
Example #36
0
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
Example #37
0
    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()
Example #38
0
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
Example #39
0
def run():
    """
    Runs sim and plots figures, saves to outfig
    """
    t_vec.record(h._ref_t)
    v_vec.record(dend(0.5)._ref_v)
    h.tstop = 20000       #stop sim at 20000 ms or 20 s

    h.run()  # run sim
    outfig = "v" + date + ".png"
    pp.plot(t_vec, v_vec)    # plot time versus voltage
    pp.savefig(outfig)       # save figure using outfig
Example #40
0
def get_vRest(myEPas):
    """ 
    this functions returns the voltage in the given section
    as a function ePas. 
    
    Example:
    >>> get_vRest(soma(0.5), myEPas=-68)
    """
    mycell.soma.e_pas = myEPas
    
    h.run()
    return mycell.soma.v
Example #41
0
def simulate_voltage(tstop, list_seg):
    """ runs a simulation and recall the voltage vectors
    defined in segments entered in **args
    return a list of HocVector objects
    """
    myvector_list = list()
    for seg in list_seg:
        myvector_list.append(HocVector(seg))

    h.tstop = tstop
    h.run()

    # return a list of HocVector objects
    return myvector_list
Example #42
0
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
Example #43
0
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()
Example #44
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
Example #45
0
def iclamp(cell, sec, i_inj, v_init, tstop, dt, celsius=35, pos_i=0.5, pos_v=0.5):
    """
    Runs a NEURON simulation of the cell for the given parameters.

    :param sec: List with 1st entry the name of the section and 2nd entry the index (or None in case of soma)
    :type sec: list[str, int]
    :param i_inj: Amplitude of the injected current for all times t.
    :type i_inj: array_like
    :param v_init: Initial membrane potential of the cell.
    :type v_init: float
    :param tstop: Duration of a whole run.
    :type tstop: float
    :param dt: Time step.
    :type dt: float
    :param celsius: Temperature during the simulation (affects ion channel kinetics).
    :type celsius: float
    :param pos_i: Position of the IClamp on the Section (number between 0 and 1).
    :type pos_i: float
    :param pos_v: Position of the recording electrode on the Section (number between 0 and 1).
    :type pos_v: float
    :return: Membrane potential of the cell and time recorded at each time step.
    :rtype: tuple of three ndarrays
    """

    section = cell.substitute_section(sec[0], sec[1])

    # time
    t = np.arange(0, tstop + dt, dt)

    # insert an IClamp with the current trace from the experiment
    stim, i_vec, t_vec = section.play_current(i_inj, t, pos_i)

    # record the membrane potential
    v = section.record('v', pos_v)
    t = h.Vector()
    t.record(h._ref_t)

    # run simulation
    h.celsius = celsius
    h.v_init = v_init
    h.tstop = tstop
    h.steps_per_ms = 1 / dt  # change steps_per_ms before dt, otherwise dt not changed properly
    h.dt = dt
    h.run()

    return np.array(v), np.array(t)
Example #46
0
def main():
    fixedInput = {'probability': 0.5, 'spikeTimes': [100,215]}

    neurons = [KhaliqRaman(i) for i in range(2)]
    for n in neurons:
        n.addFixedInput(fixedInput['probability'], fixedInput['spikeTimes'])
        n.addPoissonInputs(clusterSize=5, stimulusProps={'frequency': 0.1, 'noise': 1.})
        n.addSomaticVoltageRecorder()

    time = h.Vector()
    time.record(h._ref_t)

    h.load_file('stdrun.hoc')
    h.tstop = 400
    h.run()
    for n in neurons:
        #print('Neuron [%d] emitted %d spikes.' % (n.ID, len(n.spikeTimes)))
        saveNeuron('neuron.h5', n)
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()
Example #48
0
def vclamp(v, t, sec, celsius):

    # create SEClamp
    v_clamp = h.Vector()
    v_clamp.from_python(v)
    t_clamp = h.Vector()
    t_clamp.from_python(np.concatenate((np.array([0]), t)))  # shifted because membrane potential lags behind vclamp
    clamp = h.SEClamp(0.5, sec=sec)
    clamp.rs = 1e-15  # series resistance should be as small as possible
    clamp.dur1 = 1e9
    v_clamp.play(clamp._ref_amp1, t_clamp)

    # simulate
    h.celsius = celsius
    dt = t[1] - t[0]
    h.tstop = t[-1]
    h.steps_per_ms = 1 / dt
    h.dt = dt
    h.v_init = v[0]
    h.run()
Example #49
0
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
Example #50
0
def simulate(tstop):
    """
    simulate the somatic EPSC and
    returns the time (in ms) and current (in pA)
    """
    
    # simulation details
    h.load_file('stdrun.hoc')
    h.v_init = -70
    time, current = h.Vector(), h.Vector()

    time.record(h._ref_t)
    current.record(VC_patch._ref_i)
    
    h.tstop = tstop
    VC_patch.dur1 = tstop
    
    h.run()
    # note that current is in pA
    return (time, np.array(current)*1000.)
Example #51
0
def main():
    pkj = h.DSB94()
    h.dt = 0.02
    Vrest = -74
    h.celsius = 37
    rec={}
    rec['v'] = h.Vector()
    rec['t'] = h.Vector()
    rec['v'].record(pkj.soma(0.5)._ref_v)  
    rec['t'].record(h._ref_t)
    iclamp = h.IClamp(pkj.soma(0.5))
    iclamp.amp = 0.300
    iclamp.dur = 1000
    iclamp.delay = 0
    h.finitialize(Vrest)
    h.tstop = 700
    h.run()
    plt.plot(rec['t'],rec['v'])
    plt.show()
    from ipdb import set_trace
    set_trace()
def p (nm, pm=None) :
  global name, vviv, params, vvset
  if pm is None : pm = choices[izhtype][2][nm]
  name, params = nm, pm
  if newmodel():
    izh.C, izh.k, izh.vr, izh.vt, izh.vpeak, izh.a, izh.b, izh.c, izh.d, izh.celltype = params
    h.tstop=1000
  else: 
    izh.a, izh.b, izh.c, izh.d, vviv, h.tstop = params
  g.size(0,h.tstop,-100,50)
  try: 
    if newmodel():
      graphx() # interviews graphics
      iz07fig.recorder(cell07, choices[izhtype][1]()) # vectors to draw under matplotlib
      iz07fig.test1(cell07, nm, izhtype)
    else:
      iz07fig.closeFig()
      graphx()
      playinit()
      h.run()
  except: print sys.exc_info()[0],' :',sys.exc_info()[1]
def simulate(cell, tstop=1500, vinit=-55):
    ''' simulation control 
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    h.run()
Example #54
0
def main():
    gid  = 0
    model = 'kr'
    cell_size = 120
    N = 20
    neurons = [KhaliqRaman(gid,
                           {'diameter':cell_size,'length':cell_size,
                            'nSynapses':0,'channelNoise':False})
               for gid in range(N)]
    baseline = []
    pulse = []
    for n,current in zip(neurons,np.linspace(0.04,0.07,N)):
        baseline.append(h.IClamp(n.soma(0.5)))
        baseline[-1].amp = -0.17
        baseline[-1].dur = 2000
        baseline[-1].delay = 0
        pulse.append(h.IClamp(n.soma(0.5)))
        pulse[-1].amp = current
        pulse[-1].dur = 1000
        pulse[-1].delay = 500
 
    for i,n in enumerate(neurons):
        n.addSomaticVoltageRecorder()
    time = h.Vector()
    time.record(h._ref_t)

    h.load_file('stdrun.hoc')
    h.tstop = 2000
    h.run()
    
    import pylab as plt
    fig = plt.figure()
    for i,n in enumerate(neurons):
#        fig.add_subplot(len(neurons),1,i)
        plt.plot(time,n.somaticVoltage()+(i-1)*5)
    plt.show()
    ipdb.set_trace()

    h.quit()
Example #55
0
def scalar_bistable(rxdstr):
    if rxdstr == 'rxd':
        from neuron import rxd
    else:
        from neuron import crxd as rxd
    h.load_file('stdrun.hoc')
    s = h.Section(name='s')
    s.nseg = 101
    cyt = rxd.Region(h.allsec())
    c = rxd.Species(cyt, name='c', initial=lambda node: 1 if 0.4 < node.x < 0.6 else 0, d=1)
    r = rxd.Rate(c, -c * (1-c)*(0.3-c))
    h.finitialize()
    h.run()

    #check the results
    result = h.Vector(c.nodes.concentration)
    cmpV = h.Vector(scalar_bistable_data[rxdstr])
    cmpV.sub(result)
    cmpV.abs()
    if cmpV.sum() < 1e-6:
        sys.exit(0) 
    sys.exit(-1)
Example #56
0
def simple():
    soma = h.Section()
    soma.insert('pas')
    soma.e_pas = -65
    #soma.g_pas = 1./200e3
    synapse = syn.AMPANMDASynapse(soma, 0.5, 0, 10000)
    synapse.set_presynaptic_spike_times([100])
    h.nmdafactor_AmpaNmda = 0
    rec = {}
    for lbl in 't','vsoma','vapical','vbasal','gampa','gnmda','iampa','inmda':
        rec[lbl] = h.Vector()
    rec['t'].record(h._ref_t)
    rec['vsoma'].record(soma(0.5)._ref_v)
    rec['gampa'].record(synapse.syn._ref_gampa)
    rec['gnmda'].record(synapse.syn._ref_gnmda)
    rec['iampa'].record(synapse.syn._ref_iampa)
    rec['inmda'].record(synapse.syn._ref_inmda)        
    h.load_file('stdrun.hoc')
    h.celsius = 35
    h.cvode_active(1)
    h.cvode.maxstep(10)
    h.tstop = 500
    h.finitialize(soma.e_pas)
    h.run()
    p.subplot(3,1,1)
    p.plot(rec['t'],rec['vsoma'],'k',label='Soma')
    p.subplot(3,1,2)
    p.plot(rec['t'],np.array(rec['gampa'])*1e3,'k',label='AMPA')
    p.plot(rec['t'],np.array(rec['gnmda'])*1e3,'r',label='NMDA')
    p.legend(loc='best')
    p.ylabel('Conductance (nS)')
    p.subplot(3,1,3)
    p.plot(rec['t'],np.array(rec['iampa']),'k',label='AMPA')
    p.plot(rec['t'],np.array(rec['inmda']),'r',label='NMDA')
    p.legend(loc='best')
    p.xlabel('Time (ms)')
    p.ylabel('Current (nA)')
    p.show()
Example #57
0
h.dt = 1/5.

h.finitialize(-75)

# cell with morphology and biophysics
mycell = create_cell(CA3NeuronJonas)

# stimulator
stim = h.IClamp(0.5, sec= mycell.dend[141])
stim.amp = .7
stim.dur = 5 
stim.delay = 10 

# Load HocVectors
soma_AP = HocVector(seg = mycell.soma(0.5)) 
dend_AP = HocVector(seg = mycell.dend[141](0.5)) 

# run simulation (stimulate in the dendrite)
h.run()
soma1 = soma_AP.voltage.copy()
dend1 = dend_AP.voltage.copy()

# plot resutls
fig1 = figure()
ax1 = fig1.add_subplot(111)
    
ax1.plot(soma_AP.time, soma1, 'k')
ax1.plot(soma_AP.time, dend1, 'r')

show()
Example #58
0
def test():    
    rall = 113 # axial resistance
    cap = 1.1 # membrane capacitance
    Rm = 45000.0 # membrane resistance
    
    ## INSERT ION CHANNELS:
    for sec in h.allsec():
        sec.insert("pas")
        sec.e_pas = Epas
        sec.g_pas = 1/Rm
        sec.Ra = rall
        sec.cm = cap
        sec.insert("Cad")
        sec.insert("it2")
        sec.insert("hh2")
        sec.ena = 50 # Reversal potential for sodium
        sec.ek = -90 # Reversal potential for potassium

     ##################################################################   
    # Channel densities
    gna  = 0.04 # S/cm2
    gkdr = 0.04
    gcat = 0.0001

    ###################################################################
    ## INSERT STIMULATION ELECTRODES
    stim = h.IClamp(h.soma(0.5))
    # stim = h.IClamp(h.dend[99](0.5))
    stim.delay = 1000
    stim.dur = 10
    stim.amp =  0#.25 #nA

    ###################################################################
    ## INSERT SYNAPSES    
    syn = h.Exp2Syn(h.dend[99](1)) # Sum of exp's
    syn.tau1 = 0.5 # Rise (ms)
    syn.tau2 = 2 # Decay (ms)
    syn.e = 10 # Reversal # pot.
              
    s = h.NetStim(0.5)
    s.start = 1000  # start for distal synapses
    s.number = 1
    s.noise = 0    
    
    nc = h.NetCon(s,syn,sec = sec)       
    nc.weight[0] = 0.015

    # syn1 = h.Exp2Syn(h.dend[83](1)) # Sum of exp's
    # syn1.tau1 = 0.5 # Rise (ms)
    # syn1.tau2 = 2 # Decay (ms)
    # syn1.e = 10 # Reversal # pot.
              
    # s1 = h.NetStim(0.5)
    # s1.start = 1100  # start for distal synapses
    # s1.number = 1
    # s1.noise = 0    
    
    # nc1 = h.NetCon(s1,syn1,sec = sec)       
    # nc1.weight[0] = 0.05
    #################################################################
    # Split the morphology up in a suitable number of segments
    freq = 50
    h.geom_nseg(freq)
    tot = 0
    for sec in h.allsec():
        tot += sec.nseg
    h.distance()
    print "total # of segments (50Hz):", tot      
              
    ##################################################################
    # INITIALIZE
    gcat_func = lambda dist : 0.1054*gcat*(1 + 0.04*dist)
    def initialize():
        global Epas
        h.celsius = celsius
        for sec in h.soma:
            h.distance()    
   
        for sec in h.allsec():
            sec.v = Epas
            sec.e_pas = Epas
    
            sec.insert("pas")
            sec.e_pas = Epas
            sec.g_pas = 1/Rm
            sec.Ra = rall
            sec.cm = cap
            sec.gnabar_hh2 = 0 
            sec.gkbar_hh2 = 0
            dist = h.distance(0.5)
            # sec.gcabar_it2 = gcat_func(dist)
            sec.gcabar_it2 = gcat
        for sec in h.soma:
            sec.gnabar_hh2 = gna 
            sec.gkbar_hh2 = gkdr
            # sec.gcabar_it2 = 0.1054*gcat
            sec.gcabar_it2 = gcat
                                                                             
        h.finitialize()       
        h.fcurrent()     
        cvode.re_init()
    
    initialize()

    vec ={}
    for var in 't', 'd_sec', 'd_seg', 'diam_sec','gc','diam_seg','stim_curr':
        vec[var] = h.Vector()
        
    for var in 'V_sec', 'V_seg', 'CaConc_sec','CaConc_seg':
        vec[var] = h.List()
    
    def create_lists(vec):        
        for sec in h.allsec():
            vec['d_sec'].append(h.distance(1))
            vec['diam_sec'].append(sec.diam)  
            rec0 = h.Vector()
            rec0.record(sec(0.5)._ref_v)         
            vec['V_sec'].append(rec0)
            rec_Ca = h.Vector()
            rec_Ca.record(sec(0.5)._ref_Cai)
            vec['CaConc_sec'].append(rec_Ca)        
            for seg in sec: 
                vec['d_seg'].append(h.distance(0) + sec.L * seg.x)
                vec['diam_seg'].append(seg.diam)
                vec['gc'].append(seg.gcabar_it2)   
                rec = h.Vector()
                rec.record(seg._ref_v)
                vec['V_seg'].append(rec)
                rec1 = h.Vector()
                rec1.record(seg._ref_Cai)
                vec['CaConc_seg'].append(rec1)                                   
        return vec
    #####################################    	
    create_lists(vec)       
    # run the simulation
    
    vec['t'].record(h._ref_t)
    # vec['current'].record(VC_patch._ref_i)
    vec['stim_curr'].record(stim._ref_i)
    h.load_file("stdrun.hoc")               
    h.tstop = 2500  # Simulation time
    h.t = -500
    h.run()
    return vec            
Example #59
0
# insert a current clamp with continuously fluctuating value
# inject a continues current
h.tstop = 1e3
h.dt = 0.025
AMP = 20 # scales amplitude of current clamp, 4.5 produces sub-threshold response, 20 causes soma spikes normally, 
         # change values to see effect
np.random.seed(21051982)
noise = np.random.rand(h.tstop/h.dt+1)*AMP
icc = h.IClamp(cell(0.5))
icc.delay=0 # start current clamp right away
icc.dur=1e9 # this means the value is played into for simulation duration
nvec = h.Vector( noise )
nvec.play(icc._ref_amp,h.dt)#updates icc's amplitude during the simulation using nvec's values

h.v_init = -60 # this is initialization voltage used by h.run() -- calls finitialize
h.run() # run simulation for duration in h.tstop

# plot output
subplot(1,2,1)
plot(trec.as_numpy(),vrec.as_numpy()) # as_numpy is more efficient than converting/copying Vector to numpy format
xlim((0,h.tstop))
xlabel('Time (ms)')
ylabel('Vm (mV)')
tight_layout()

subplot(1,2,2)
plot(trec.as_numpy(),nvec.as_numpy()) # display part of the noisy current-injection amplitude
xlim((0,h.tstop))
xlabel('Time (ms)')
ylabel('i (nA)')
xlim((0,10))
Example #60
0
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)