Esempio n. 1
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)
Esempio n. 2
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)
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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.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
Esempio n. 6
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
Esempio n. 7
0
def get_recording_vecs(st):
    # record voltage in every ais segment (between AP init to the soma)
    vecs_ais = []

    for sec in cell.h.allsec():
        if sec.name() == 'axon[0]': # axon[0] is first section of the axon
            no_segs = sec.nseg
            if no_segs > 1:
                centers = np.linspace(0, 1., no_segs-1)
                centers += centers[1]/2.
            else:
                centers = [0.5]
        
            for seg_idx in range(0,no_segs-2):
                # don't take two segments on the edges (neuron specs)
                temp_axon_v= h.Vector()
                temp_axon_v.record(eval('h.'+sec.name()+'('+str(centers[seg_idx])+')._ref_v'), sec = eval('h.'+sec.name()))
                vecs_ais.append(temp_axon_v)

    vec_soma = h.Vector()
    vec_soma.record(h.soma(0.5)._ref_v, sec=h.soma) # vector for recording voltage at thes soma

    vec_st = h.Vector()
    vec_st.record(st._ref_i) # vector for recording current
    return vecs_ais, vec_soma, vec_st
Esempio n. 8
0
def exp_model2(Ra=157.3621, gpas=0.000403860792, cm=7.849480, dt=0.1):
    # -- Biophysics --
    # Sec parameters and conductance
    for sec in h.allsec():
        sec.Ra = Ra  # Ra is a parameter to infer
        sec.cm = cm  # parameter optimisation algorithm found this
        sec.v = 0

        sec.insert('pas')
        sec.g_pas = gpas  # gpas is a parameter to infer
        sec.e_pas = 0

    # Print information
    #h.psection()

    # Stimulus
    stim1 = h.IClamp(h.soma(0.01))
    stim1.delay = 199.9
    stim1.amp = 0.5
    stim1.dur = 3.1

    stim2 = h.IClamp(h.soma(0.01))
    stim2.delay = 503
    stim2.amp = 0.01
    stim2.dur = 599.9

    # Run simulation ->
    # Set up recording Vectors
    v_vec = h.Vector()  # Membrane potential vector
    t_vec = h.Vector()  # Time stamp vector
    v_vec.record(h.soma(0.5)._ref_v)
    t_vec.record(h._ref_t)

    # Simulation duration and RUN
    h.tstop = (15000 - 1) * dt  # Simulation end
    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt
    h.v_init = 0
    h.finitialize(h.v_init)

    h.init()
    h.run()

    t = t_vec.to_python()
    v = v_vec.to_python()

    return t, v
Esempio n. 9
0
def test_simple_sim():
    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)
    h.run()
    assert v[0] == -65.0
Esempio n. 10
0
    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
Esempio n. 11
0
def test_simple_sim():
    h("""create soma""")
    h.load_file("stdrun.hoc")
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    expect_hocerr(h.ion_register, ("na", 2))
    assert h.ion_charge("na_ion") == 1.0
    expect_hocerr(h.ion_register, ("ca", 3))
    assert h.ion_charge("ca_ion") == 2.0
    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)
    h.run()
    assert v[0] == -65.0
Esempio n. 12
0
    def get_membrane_potential_soma(self, tstop):
        # to supress hoc output from Jupyter notebook
        save_stdout = sys.stdout
        sys.stdout = open('/dev/stdout', 'w')

        t_vec = h.Vector()
        v_vec = h.Vector()
        t_vec.record(h._ref_t)
        v_vec.record(h.soma(0.5)._ref_v)
        h.tstop = tstop
        h.run()

        sys.stdout = save_stdout  #setting output back to before
        return [t_vec.to_python(), v_vec.to_python()]
Esempio n. 13
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

    #for testing external mod file
    h.soma.insert("Sample")

    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()
    # Save current (after run) value to compare with transfer back from coreneuron
    tran_std = [h.t, h.soma(.5).v, h.soma(.5).hh.m]

    from neuron import coreneuron
    coreneuron.enable = True
    coreneuron.gpu = bool(os.environ.get('CORENRN_ENABLE_GPU', ''))

    pc = h.ParallelContext()
    h.stdinit()
    pc.psolve(h.tstop)
    tran = [h.t, h.soma(.5).v, h.soma(.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
    # This check is disabled on GPU because fast imem is not implemented on
    # GPU: https://github.com/BlueBrain/CoreNeuron/issues/197
    assert (coreneuron.gpu or i_mem.cl().sub(i_memstd).abs().max() < 1e-10)
    assert (h.Vector(tran_std).sub(h.Vector(tran)).abs().max() < 1e-10)
Esempio n. 14
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

    #for testing external mod file
    h.soma.insert("Sample")

    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()
    # Save current (after run) value to compare with transfer back from coreneuron
    tran_std = [h.t, h.soma(.5).v, h.soma(.5).hh.m]

    from neuron import coreneuron
    coreneuron.enable = True

    pc = h.ParallelContext()
    h.stdinit()
    pc.psolve(h.tstop)
    tran = [h.t, h.soma(.5).v, h.soma(.5).hh.m]

    assert (v.eq(vstd))
    assert (tv.eq(tvstd))
    assert (v.cl().sub(vstd).abs().max() < 1e-10)
    assert (i_mem.cl().sub(i_memstd).abs().max() < 1e-10)
    assert (h.Vector(tran_std).sub(h.Vector(tran)).abs().max() < 1e-10)
Esempio n. 15
0
def test_spikes(use_mpi4py=False):
    if use_mpi4py:
        from mpi4py import MPI
    h('''create soma''')
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    h.soma.insert("hh")
    h.soma.nseg = 3
    ic = h.IClamp(h.soma(.25))
    ic.delay = .1
    ic.dur = 0.1
    ic.amp = 0.3

    ic2 = h.IClamp(h.soma(.75))
    ic2.delay = 5.5
    ic2.dur = 1
    ic2.amp = 0.3

    h.tstop = 10
    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    pc = h.ParallelContext()

    pc.set_gid2node(pc.id() + 1, pc.id())
    myobj = h.NetCon(h.soma(0.5)._ref_v, None, sec=h.soma)
    pc.cell(pc.id() + 1, myobj)

    # NEURON spikes run
    nrn_spike_t = h.Vector()
    nrn_spike_gids = h.Vector()
    pc.spike_record(-1, nrn_spike_t, nrn_spike_gids)

    h.run()

    nrn_spike_t = nrn_spike_t.to_python()
    nrn_spike_gids = nrn_spike_gids.to_python()

    # CORENEURON spike_record(-1) / spike_record(gidlist):
    from neuron import coreneuron
    coreneuron.enable = True
    coreneuron.verbose = 0
    h.stdinit()
    corenrn_all_spike_t = h.Vector()
    corenrn_all_spike_gids = h.Vector()

    pc.spike_record(-1 if pc.id() == 0 else (pc.id()), corenrn_all_spike_t,
                    corenrn_all_spike_gids)
    pc.psolve(h.tstop)

    corenrn_all_spike_t = corenrn_all_spike_t.to_python()
    corenrn_all_spike_gids = corenrn_all_spike_gids.to_python()

    # check spikes match
    assert (len(nrn_spike_t))  # check we've actually got spikes
    assert (len(nrn_spike_t) == len(nrn_spike_gids))
    # matching no. of gids
    assert (nrn_spike_t == corenrn_all_spike_t)
    assert (nrn_spike_gids == corenrn_all_spike_gids)

    h.quit()
Esempio n. 16
0
def test_spikes(use_mpi4py=False, use_nrnmpi_init=False, file_mode=False):
    # mpi4py needs tp be imported before importing h
    if use_mpi4py:
        from mpi4py import MPI
        from neuron import h, gui
    # without mpi4py we need to call nrnmpi_init explicitly
    elif use_nrnmpi_init:
        from neuron import h, gui
        h.nrnmpi_init()
    # otherwise serial execution
    else:
        from neuron import h, gui

    h('''create soma''')
    h.soma.L=5.6419
    h.soma.diam=5.6419
    h.soma.insert("hh")
    h.soma.nseg = 3
    ic = h.IClamp(h.soma(.25))
    ic.delay = .1
    ic.dur = 0.1
    ic.amp = 0.3

    ic2 = h.IClamp(h.soma(.75))
    ic2.delay = 5.5
    ic2.dur = 1
    ic2.amp = 0.3

    h.tstop = 10
    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    pc = h.ParallelContext()

    pc.set_gid2node(pc.id()+1, pc.id())
    myobj = h.NetCon(h.soma(0.5)._ref_v, None, sec=h.soma)
    pc.cell(pc.id()+1, myobj)

    # NEURON run
    nrn_spike_t = h.Vector()
    nrn_spike_gids = h.Vector()

    # rank 0 record spikes for all gid while others
    # for specific gid. this is for better test coverage.
    pc.spike_record(-1 if pc.id() == 0 else (pc.id()+1), nrn_spike_t, nrn_spike_gids)

    h.run()

    nrn_spike_t = nrn_spike_t.to_python()
    nrn_spike_gids = nrn_spike_gids.to_python()

    # CORENEURON run
    from neuron import coreneuron
    coreneuron.enable = True
    coreneuron.file_mode = file_mode
    coreneuron.verbose = 0
    h.stdinit()
    corenrn_all_spike_t = h.Vector()
    corenrn_all_spike_gids = h.Vector()

    pc.spike_record(-1, corenrn_all_spike_t, corenrn_all_spike_gids )
    pc.psolve(h.tstop)

    corenrn_all_spike_t = corenrn_all_spike_t.to_python()
    corenrn_all_spike_gids = corenrn_all_spike_gids.to_python()

    # check spikes match
    assert(len(nrn_spike_t)) # check we've actually got spikes
    assert(len(nrn_spike_t) == len(nrn_spike_gids)); # matching no. of gids
    assert(nrn_spike_t == corenrn_all_spike_t)
    assert(nrn_spike_gids == corenrn_all_spike_gids)

    h.quit()
Esempio n. 17
0
    for event in events:
        I_vcs_events[-1].append(event)
        IS_firing_times[-1].append(event)

    I_vcs[-1].play(I_vcs_events[-1])
    h("access {}".format(sec))
    placeGABA(loc, 0.001)
    h.pop_section()
    IS_ind += 1

firing_times = np.zeros(shape=(int(number_of_E_synapses), int(h.tstop) + 100))
for ind in range(len(spine_firing_times)):
    firing_times[ind, spine_firing_times[ind]] = 1

print('Running...')

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

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

E_densities = []
I_densities = []

h.stdinit()
h.run()

voltage_vectors = np.array(voltage_vectors)
timeVector = np.array(timeVector)
Esempio n. 18
0
def measure_width(trace):
    trace = np.array(trace)

    points = np.where(trace > (trace[15000] + 2))[0]
    points = points[np.logical_and(points >= 20000, points <= 30000)]

    width = dt * (points[-1] - points[0])

    return (width)


h.load_file('init_models_with_ca/init_model2.hoc')
default_sca = h.tuft.gbar_sca

# Set up stimulus
stim = h.Ipulse2(h.soma(.5))
stim.amp = 2
stim.dur = 3
stim.delay = 500
stim.per = 10
stim.num = 3

# Set up recording vectors
soma_v_vec = h.Vector()
soma_v_vec.record(h.soma(.5)._ref_v)
apical_end_v_vec = h.Vector()
apical_end_v_vec.record(h.apical(1)._ref_v)
tuft_v_vec = h.Vector()
tuft_v_vec.record(h.tuft(.5)._ref_v)
stim_vec = h.Vector()
stim_vec.record(stim._ref_i)
Esempio n. 19
0
def pyloop(ratio1=1.1, ratio2=2.2, loc1=128, loc2=128, simiter=0, subth=False):

    print '\n%s starting run' % (gethostname())
    iotim = 0
    tic = time()

    if subth:
        h5fn = 'paper-subth-%dum_%dum_run%d.h5' % (l1, l2, simiter)
        h.tstop = 200
        h.maxsyn2 = 20
    else:
        h5fn = 'paper-supth-%dum_%dum_run%d.h5' % (l1, l2, simiter)
        h.tstop = 500

    savd = './data/'
    filters = pyt.Filters(complevel=9,
                          complib='zlib',
                          shuffle=True,
                          fletcher32=True)
    h5f = pyt.openFile(os.path.join(savd, h5fn), 'w', filters=filters)

    maxsyn1 = int(h.maxsyn1) + 1
    maxsyn2 = int(h.maxsyn2) + 1
    h.tsamp = h.tstop / h.dt + 1
    tsamp = int(h.tsamp)
    shape = (maxsyn1, maxsyn2, tsamp)
    cshape = (1, 1, shape[-1])

    r = h.Random(simiter + h.luckyoffset)
    r.negexp(h.meanisi)

    # stimulated branch
    sec = h.a10_11

    syns = [[], []]
    for ind, loc in enumerate([loc1, loc2]):
        if subth:
            for delay, ratio in zip([2, 22], [ratio1, ratio2]):
                syn = h.synsuper(.5, r, sec=sec)
                syns[ind].append(syn)
                syndict = dict(sloc=loc, ratio=ratio, e1del=delay, e1flag=1)
                for name, value in syndict.iteritems():
                    setattr(syn.syn, name, value)
        else:
            syn = h.synsuper(.5, r, sec=sec)
            syns[ind].append(syn)
            syndict = dict(sloc=loc, ratio=ratio1, e1flag=0)
            for name, value in syndict.iteritems():
                setattr(syn.syn, name, value)

    # initialize nseg with two 'active' branches
    theseclist = [h.a10_11, h.a1_111]
    sl2 = h.SectionList()
    for sec in theseclist:
        sl2.append(sec=sec)
    poppedsecs = sl2.unique()
    h.refreshnseg(h.makeactivelist(sl2))
    print 'nseg: %d' % (h.nsegcnt())
    h.cvode.cache_efficient(1)
    h.cvode_active(0)

    # somatic voltage recordings, initialize after nseg is set
    v = h.Vector(tsamp)
    v.record(h.soma(.5)._ref_v)
    trash = v.label(h.soma.name())
    # voltage recording dictionary
    vd = {'s': v}

    # dendritic voltage recording
    h.distance(0, h.soma_con_pt, sec=h.soma)
    for n, sec in enumerate(theseclist):
        d = h.distance(0, sec=sec)
        # location 1 synapses
        locx1 = (loc1 - d) / sec.L
        v = h.Vector(tsamp)
        v.record(sec(locx1)._ref_v)
        trash = v.label(sec.name())
        vd.update({'dp' + str(n): v})
        # location 2 synapses
        locx2 = (loc2 - d) / sec.L
        v = h.Vector(tsamp)
        v.record(sec(locx2)._ref_v)
        trash = v.label(sec.name())
        vd.update({'dd' + str(n): v})

    if subth:
        h.poisson = 0
    else:
        h.poisson = 1
        # 'background' guassian current injection
        npy.random.seed(1)
        ic = h.IClamp(0.5, sec=h.soma)
        ic.dur = h.tstop
        icmean = .75
        icstd = 1
        icvals = icmean + icstd * npy.random.randn(h.tstop / h.dt + 1)
        icrand = h.Vector(tsamp)
        for i in xrange(tsamp):
            icrand.x[i] = icvals[i]
        icrand.play(ic._ref_amp, h.dt)

    h5d = {}
    for key in vd.keys():
        h5d.update({
            key:
            h5f.createCArray(h5f.root,
                             key,
                             shape=shape,
                             atom=pyt.Float64Atom(),
                             title=vd[key].label(),
                             chunkshape=cshape)
        })

    synpairs = [(i, j) for i in xrange(maxsyn1) for j in xrange(maxsyn2)]
    if not subth:
        # subsample stimulus configuration space to speed up simulations
        oddpairs = [(i, j) for i in npy.mgrid[1:maxsyn1:2]
                    for j in npy.mgrid[1:maxsyn2:2]]
        synpairs = list(set(synpairs) - set(oddpairs))

    # subset of input configurations needed for figure 7 traces
    realrunsdist = [3, 6, 9]
    realrunsprox = [17, 21, 25]

    iisi = simiter * (maxsyn1 + maxsyn2)  # inter-iteration seed interval

    for runcnt, (nsyn1, nsyn2) in enumerate(synpairs):
        # configure s(t)imulation
        if not subth:
            if ((nsyn1 in realrunsprox and nsyn2 == 0)
                    or (nsyn2 in realrunsdist and nsyn1 == 0)):
                h.fakerun = 0
            else:
                h.fakerun = 1
        for ssyn in syns[0]:
            ssyn.syn.nsyn = nsyn1
            seed1 = float(iisi + nsyn1 + h.luckyoffset)
            r1 = h.Random(seed1)
            r1.negexp(h.meanisi)
            ssyn.setrand(r1)
        for ssyn in syns[1]:
            ssyn.syn.nsyn = nsyn2
            seed2 = float(iisi + maxsyn1 + nsyn2 + h.luckyoffset)
            r2 = h.Random(seed2)
            r2.negexp(h.meanisi)
            ssyn.setrand(r2)

        # run simulation
        h.run()

        # get results
        iotic = time()
        if not h.fakerun:
            for key in h5d.keys():
                h5d[key][nsyn1, nsyn2] = npy.array(vd[key]).reshape(cshape)
        iotim += time() - iotic

    iotic = time()
    h5f.close()
    iotim += time() - iotic

    print '%s running %d runs took %d seconds, of which %d seconds was I/O' % (
        gethostname(), runcnt + 1, time() - tic, iotim)
Esempio n. 20
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(0.5))
    ic.delay = 0.5
    ic.dur = 0.1
    ic.amp = 0.3

    # for testing external mod file
    h.soma.insert("Sample")

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

    v = h.Vector()
    v.record(h.soma(0.5)._ref_v, sec=h.soma)
    i_mem = h.Vector()
    i_mem.record(h.soma(0.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()
    # Save current (after run) value to compare with transfer back from coreneuron
    tran_std = [h.t, h.soma(0.5).v, h.soma(0.5).hh.m]

    from neuron import coreneuron

    coreneuron.enable = True
    coreneuron.verbose = 0
    coreneuron.gpu = enable_gpu

    pc = h.ParallelContext()

    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

    for mode in [0, 1, 2]:
        run(mode)

    cnargs = coreneuron.nrncore_arg(h.tstop)
    h.stdinit()
    assert tv.size() == 1 and tvstd.size() != 1
    pc.nrncore_run(cnargs, 1)
    assert tv.eq(tvstd)

    # print warning if HocEvent on event queue when CoreNEURON starts
    def test_hoc_event():
        print("in test_hoc_event() at t=%g" % h.t)
        if h.t < 1.001:
            h.CVode().event(h.t + 1.0, test_hoc_event)

    fi = h.FInitializeHandler(2, test_hoc_event)
    coreneuron.enable = False
    run(0)
    coreneuron.enable = True
    run(0)
Esempio n. 21
0
    def set_cclamp(self, amp):

        self.stim = h.IClamp(h.soma(0.5))
        self.stim.amp = amp
        self.stim.delay = 500
        self.stim.dur = 1000
Esempio n. 22
0
from neuron import h, gui
import sys

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

# for testing external mod file
h.soma.insert("CaDynamics_E2")

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()

#h.CoreNeuronRun[0].run()
pc = h.ParallelContext()
h.soma.diam = 10
h.soma.Ra   = 100
h.soma.insert('pas')   # add passive properties  
h.soma.g_pas = 1/10000 # set the specific membrane resistance to 10000 ohm*cm^2

# add active conductances (the channels [mod files] are from Mainen and Sejnowski 1996)
h.soma.insert('kv') # add potassium channel
h.soma.gbar_kv = 2000 # set the potassium conductance

h.soma.insert('na') # add sodium channel
h.soma.gbar_na = 8000 # set the sodium conductance
h.celsius = 30


# current clamp
stim = h.IClamp(h.soma(0.5))
stim.amp   = 0.007446
stim.delay = 250
stim.dur   = 1000

# record voltage of some and injected current
# and the time
soma_v = h.Vector()
soma_v.record(h.soma(0.5)._ref_v)

stim_current = h.Vector()
stim_current.record(stim._ref_i)

t = h.Vector()
t.record(h._ref_t)
    points = np.where(trace > (trace[15000] + 2))[0]
    points = points[np.logical_and(points >= 20000, points <= 30000)]

    width = dt * (points[-1] - points[0])

    return width


h.load_file('init_models_with_ca/init_model2.hoc')

locations = [0, 0.1, 0.3, 0.5, 0.7, 0.9, 1]
probes = [0] * len(locations)

# Set up stimulus
stim = h.Ipulse2(h.soma(.5))
stim.amp = 2
stim.dur = 3
stim.delay = 500
stim.per = 10
stim.num = 1

# Set up recording vectors
for i in range(len(probes)):
    probes[i] = h.Vector()
    probes[i].record(h.apical(locations[i])._ref_v)
t_vec = h.Vector()
t_vec.record(h._ref_t)

dt = 0.025
h.tstop = 1000 - dt
from neuron import h, gui
from matplotlib import pyplot as plt
import numpy as np
import csv
from os import path

h.load_file('init_models_with_ca/init_model2.hoc')

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

stim = h.IClamp(h.soma(0.5))
stim_vec = h.Vector()
stim_vec.record(stim._ref_i)

t_vec = h.Vector()
t_vec.record(h._ref_t)
dt = 0.025
h.tstop = 1500 - dt

stim.dur = 500
stim.delay = 500

lengths = np.array([200, 300, 400, 500, 600])
fig, axes = plt.subplots(2,
                         lengths.size,
                         squeeze=False,
                         sharex='all',
                         sharey='row',
                         figsize=(16, 8))
Esempio n. 26
0
def pyrun(ratio=0, loc=0, nsyn=0, sec=h.a10_11, icamps=[], dendrec=True):

    print '\n%s starting run' % (gethostname())
    iotim = 0
    tic = time()

    h.tstop = 500

    h.tsamp = h.tstop / h.dt + 1
    h.synrec = 1
    tsamp = int(h.tsamp)

    r = h.Random(h.luckyoffset)
    r.negexp(h.meanisi)

    # stimulated branch
    syn = h.synsuper(.5, r, sec=sec)
    syndict = dict(sloc=loc, ratio=ratio, e1flag=0)
    for name, value in syndict.iteritems():
        setattr(syn.syn, name, value)

    # initialize nseg with 'active' branches
    seclist = [h.a1_111, h.a10_11]
    sl2 = h.SectionList()
    for sec in seclist:
        sl2.append(sec=sec)
    poppedsecs = sl2.unique()
    h.refreshnseg(h.makeactivelist(sl2))
    print 'nseg: %d' % (h.nsegcnt())
    h.cvode.cache_efficient(1)
    h.cvode_active(0)

    # somatic voltage recordings, after nseg initialization
    v = h.Vector(tsamp)
    v.record(h.soma(.5)._ref_v)
    trash = v.label(h.soma.name())
    # voltage recording dictionary
    vd = {'s': v}

    if dendrec:
        # dendritic voltage recording
        h.distance(0, h.soma_con_pt, sec=h.soma)
        d = h.distance(0, sec=sec)
        locx = (loc - d) / sec.L
        v = h.Vector(tsamp)
        v.record(sec(locx)._ref_v)
        trash = v.label(sec.name())
        vd.update({'d': v})

    h.poisson = 1
    # 'background' current injection
    ic = h.IClamp(0.5, sec=h.soma)
    ic.dur = h.tstop

    p_tstart = 100  # plot tstart, crop initial rising phase of current injection
    ind_tstart = p_tstart / h.dt
    t = npy.arange(0, h.tstop - p_tstart + h.dt, h.dt)
    fh = newfig(figsize=(4, 8))
    for runcnt, icamp in enumerate(icamps):
        ic.amp = icamp
        syn.syn.nsyn = nsyn
        seed1 = float(686)
        r1 = h.Random(seed1)
        r1.negexp(h.meanisi)
        syn.setrand(r1)

        # run simulation
        h.run()

        postrunrecgather(vd)

        # plot voltage and synaptic current
        ax = fh.add_subplot(6, 1, runcnt + 3)
        ax.plot(t, npy.array(vd['d'])[ind_tstart:], c='k', lw=1)
        ax = fh.add_subplot(6, 1, runcnt + 5)
        ax.plot(t,
                -(vd['nis'].sum(0) + vd['ais'].sum(0))[ind_tstart:],
                c='r',
                lw=1)

    ax = fh.add_subplot(6, 1, 1)
    for ind, ras in enumerate(vd['rasind']):
        ticks = ras[ras >= p_tstart]
        ax.scatter(ticks - p_tstart,
                   npy.ones(ticks.shape) * ind,
                   marker=[[[0, 0], [0, 1]], 0])
    ax.axis((0, h.tstop - p_tstart, 0, ind + 1))

    zero = npy.zeros(t.size)
    ax = fh.add_subplot(6, 1, 2)
    ax.fill_between(t,
                    zero, (vd['ngs'] / vd['nbs']).sum(0)[ind_tstart:],
                    lw=2,
                    color='k')
    ax.fill_between(t, zero, vd['ags'].sum(0)[ind_tstart:], lw=2, color='r')
    ax.set_xlim([0, h.tstop - p_tstart])

    fh.savefig('figs/Figure4.png')

    print '%s running %d runs took %d seconds' % (gethostname(), runcnt + 1,
                                                  time() - tic)
Esempio n. 27
0
h.dend.L = 500  # um
h.dend.diam = 1  # um
h.dend.Ra = 100  # ohm*cm
h.dend.insert('pas')
h.dend.g_pas = 1 / 10000

h.dend.connect(h.soma, 1,
               0)  #connect the end of the soma to the start of the dendrite

h("forall { nseg = int((L/(0.1*lambda_f(100))+0.9)/2)*2 + 1  }")

#########################
# # Set up experiment # #
#########################

stim = h.IClamp(h.soma(0.5))  # add a current clamp the the middle of the soma
stim.delay = 10  # ms
stim.dur = 100  # ms
stim.amp = 0.1  # nA

soma_v = h.Vector()  # set up a recording vector
soma_v.record(h.soma(0.5)._ref_v)  # record voltage at the middle of the soma

# Record voltage from all segments in the dendrite
dend_vs = []
for seg in h.dend:
    dend_vs.append(h.Vector())
    dend_vs[-1].record(seg._ref_v)

t = h.Vector()
t.record(h._ref_t)  #record time.
off_path_inhibition.e = v_rest

#create a NetStim that will activate the synapses  at t=1000
inhibition_netstim = h.NetStim(0.5, sec=h.dend)
inhibition_netstim.number = 1  # number of synaptic activation
inhibition_netstim.start = 1000  # activation start time
inhibition_netstim.noise = 0  # randomness
on_path_netcon = h.NetCon(inhibition_netstim, on_path_inhibition)
off_path_netcon = h.NetCon(inhibition_netstim, off_path_inhibition)

#########################
# # set up recording # #
#########################

soma_v = h.Vector()  # set up a recording vector
soma_v.record(h.soma(0.5)._ref_v)  # record voltage at the middle of the soma

# Record voltage from all segments in the dendrite
dend_vs = []
for seg in h.dend:
    dend_vs.append(h.Vector())
    dend_vs[-1].record(seg._ref_v)

t = h.Vector()
t.record(h._ref_t)  #record time.
h.v_init = v_rest  # set starting voltage
h.tstop = 5000  # set simulation time

###########################################
# Run simulation with proximal inhibition #
###########################################
Esempio n. 29
0
                   pulses_amp=1.5,
                   pulses_num=0,
                   pulses_period=10):
    stim.amp, stim.dur, stim.delay = Is, Is_dur, Is_onset
    apical_stim.amp, apical_stim.dur, apical_stim.delay = Ia, Ia_dur, Ia_onset
    tuft_stim.amp, tuft_stim.dur, tuft_stim.delay = It, It_dur, It_onset
    epsp.imax, epsp.tau0, epsp.tau1, epsp.onset = Id_max, Id_rise, Id_decay, Id_onset
    pulses.delay, pulses.dur, pulses.per, pulses.num, pulses.amp = pulses_onset, pulses_dur, pulses_period, pulses_num, pulses_amp
    h.tstop = simdur - dt
    h.run()


h.load_file('init_models_with_ca/init_model2.hoc')

# Set up stimulus
stim = h.IClamp(h.soma(0.5))
epsp = h.epsp(h.tuft(0.5))
pulses = h.Ipulse2(h.soma(0.5))
apical_stim = h.IClamp(h.apical(.5))
tuft_stim = h.IClamp(h.tuft(.5))

# Set up recording vectors
soma_v_vec = h.Vector()
soma_v_vec.record(h.soma(0.5)._ref_v)
apical_v_vec = h.Vector()
apical_v_vec.record(h.apical(0.5)._ref_v)
tuft_v_vec = h.Vector()
tuft_v_vec.record(h.tuft(0.5)._ref_v)
stim_vec = h.Vector()
stim_vec.record(stim._ref_i)
epsp_vec = h.Vector()
Esempio n. 30
0
def test_spikes(
    use_mpi4py=mpi4py_option,
    use_nrnmpi_init=nrnmpi_init_option,
    file_mode=file_mode_option,
):
    print(
        "test_spikes(use_mpi4py={}, use_nrnmpi_init={}, file_mode={})".format(
            use_mpi4py, use_nrnmpi_init, file_mode))
    h("""create soma""")
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    h.soma.insert("hh")
    h.soma.nseg = 3
    ic = h.IClamp(h.soma(0.25))
    ic.delay = 0.1
    ic.dur = 0.1
    ic.amp = 0.3

    ic2 = h.IClamp(h.soma(0.75))
    ic2.delay = 5.5
    ic2.dur = 1
    ic2.amp = 0.3

    h.tstop = 10
    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    pc = h.ParallelContext()

    pc.set_gid2node(pc.id() + 1, pc.id())
    myobj = h.NetCon(h.soma(0.5)._ref_v, None, sec=h.soma)
    pc.cell(pc.id() + 1, myobj)

    # NEURON run
    nrn_spike_t = h.Vector()
    nrn_spike_gids = h.Vector()

    # rank 0 record spikes for all gid while others
    # for specific gid. this is for better test coverage.
    pc.spike_record(-1 if pc.id() == 0 else (pc.id() + 1), nrn_spike_t,
                    nrn_spike_gids)

    h.run()

    nrn_spike_t = nrn_spike_t.to_python()
    nrn_spike_gids = nrn_spike_gids.to_python()

    # CORENEURON run
    from neuron import coreneuron

    coreneuron.enable = True
    coreneuron.gpu = enable_gpu
    coreneuron.file_mode = file_mode
    coreneuron.verbose = 0
    corenrn_all_spike_t = h.Vector()
    corenrn_all_spike_gids = h.Vector()

    pc.spike_record(-1, corenrn_all_spike_t, corenrn_all_spike_gids)

    pc.set_maxstep(10)

    def run(mode):
        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)

        corenrn_all_spike_t_py = corenrn_all_spike_t.to_python()
        corenrn_all_spike_gids_py = corenrn_all_spike_gids.to_python()

        # check spikes match
        assert len(nrn_spike_t)  # check we've actually got spikes
        assert len(nrn_spike_t) == len(nrn_spike_gids)  # matching no. of gids
        if nrn_spike_t != corenrn_all_spike_t_py:
            print(mode)
            print(nrn_spike_t)
            print(nrn_spike_gids)
            print(corenrn_all_spike_t_py)
            print(corenrn_all_spike_gids_py)
            print([
                corenrn_all_spike_t[i] - nrn_spike_t[i]
                for i in range(len(nrn_spike_t))
            ])
        assert nrn_spike_t == corenrn_all_spike_t_py
        assert nrn_spike_gids == corenrn_all_spike_gids_py

    if file_mode is False:
        for mode in [0, 1, 2]:
            run(mode)
    else:
        run(0)

    return h
Esempio n. 31
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            
Esempio n. 32
0
def pythonsim(simid, rundir, inputdir, modeldir, outputdir, currentstr, vinitstr, delaystr, stimdurationstr, timestepstr, simstopstr, recordintervalstr):
	import neuron
	from neuron import h
	Section = h.Section

	# All the mods are in the simulator directory
	# Apparently this is already done by  the import, if we use the "-dll" 
	# option in the call to nrniv. Since the import behavior seems to be 
	# inconsistent without the "-dll" option, we do it this way.
	#neuron.load_mechanisms(".")  # NOT USING LOAD_MECHANISMS HERE
	# local auto-modified version for no gui and control over certain ion 
	#  channels is in the run dir
	h.xopen(rundir + '/' + simid + '.hoc') 

	timefilepath = outputdir + '/' + 'timedata.txt'
	timefile = h.File()
	timefile.wopen(timefilepath, 'w')
	
	voltagefilepath = outputdir + '/' + 'voltagedata.txt'
	voltagefile = h.File()
	voltagefile.wopen(voltagefilepath, 'w')

	current = float(currentstr)
	vinit = float(vinitstr)
	delay = float(delaystr)
	stimduration = float(stimdurationstr)
	timestep = float(timestepstr)
	simstop = float(simstopstr)
	recordinterval = float(recordintervalstr)
	
	# ----- Current Injection
	stim = h.IClamp(0.5, sec=h.soma)
	stim.amp = current  # nA
	stim.delay = delay  # msec
	stim.dur = stimduration # msec

	# ----- Simulation Control (now mostly done through input arguments)
	h.dt = timestep

	# Preallocate record vectors for speed
	# Requires recordinterval to be an exact multiple of tstep.
	recordlength = simstop/recordinterval + 1
	testt = h.Vector(recordlength)
	testv = h.Vector(recordlength)

    # Recording at the soma
	testt.record(h._ref_t, recordinterval)
	testv.record(h.soma(0.5)._ref_v, recordinterval)

	# Initialize
	h.finitialize(vinit)
	h.fcurrent()

	# Integrate
	while h.t <= simstop:
		v = h.soma.v
		h.fadvance()

	# Shutdown
	testt.printf(timefile, '%f\n')
	testv.printf(voltagefile, '%f\n')
	timefile.close()
	voltagefile.close()
	return(0)