stim2 = h.IClamp(cells[0].soma(0.5))
stim2.delay = 500
stim2.dur = 300

stim2.amp = 0
stim.amp = 5e-1 - stim2.amp
#stim.amp = 0

soma_v_vec, soma_m_vec, soma_h_vec, soma_n_vec,\
     soma_inap_vec, soma_idap_vec, soma_ical_vec,\
     soma_ican_vec, soma_ikca_vec, soma_ina_vec, soma_ikrect_vec,\
    dend_v_vec, t_vec\
    = simrun.set_recording_vectors(cells[0])

# Set recording vectors
syn_i_vec = h.Vector()
syn_i_vec.record(stim._ref_i)

#h('v_init = 89')
h.v_init = -65
fih = h.FInitializeHandler(2, (tweak_leak, (cells, N)))

# Draw
fig1 = pyplot.figure(figsize=(4, 4))
ax1a = fig1.add_subplot(1, 1, 1)
#ax1b = ax1a.twinx()
#step = 2.5e-2 #CaN
#step = 1e-5 #CaL
#step = 5e-2 #KCa
#step = 4e-5 #napbar
#step = 5 #tau_mc
Exemple #2
0
s.L = 3
s.nseg = 1
s.insert('hh')
h.usetable_hh = 0
stim = h.IClamp(s(.5))
stim.delay = 0.5
stim.dur = 0.1
stim.amp = .3

s.gkbar_hh = 0
k = kchan()
h.run()

h.cvode.active(True)
r = h.ref('')
h.finitialize()
states = h.Vector()
h.cvode.states(states)
print("states")
states.printf()

dstates = h.Vector()
print("dstates")
h.cvode.dstates(dstates)
dstates.printf()

print("statenames")
for i in range(len(states)):
    h.cvode.statename(i, r)
    print(r[0])
h.load_file('init_models_with_ca/init_model2.hoc')
default_sca = h.tuft.gbar_sca
default_cm = h.tuft.cm
default_apical_Ra = h.apical.Ra

# 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
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)
t_vec = h.Vector()
t_vec.record(h._ref_t)

# Simulation parameters
dt = 0.025
h.tstop = 1000 - dt

Ih = np.arange(0, 1.25, .25) 
l = np.arange(200, 605, 5)
array_size = [2, 2, l.size, Ih.size]  # Ca compartment length Ih
Exemple #4
0
HCell.geom_nsec()
HCell.geom_nseg()
HCell.delete_axon()
HCell.insertChannel()
HCell.init_biophys()
HCell.biophys()

# The stimulus
icl = h.IClamp(0.5, sec=HCell.soma[0])
icl.dur = 1000
icl.delay = 120.33
amp = models_dirs[cell]['stim_amp']
icl.amp = amp

# Record the voltage at the soma
Vsoma = h.Vector()
Vsoma.record(HCell.soma[0](.5)._ref_v)
tvec = h.Vector()
tvec.record(h._ref_t)

HCell.soma[0].push()

h.init(h.v_init)
h.run()

np_t = np.array(tvec)
np_v = np.array(Vsoma)

models_dirs[cell]['t'] = np_t
models_dirs[cell]['v'] = np_v
Exemple #5
0
    def setup_lfp(self):
        ## Calculate distances from recording electrode to all
        ## compartments of all cells, calculate scaling coefficients
        ## for the LFP calculation, and save them in lfp_coeffs.

        ex, ey, ez = self.epoint

        ##printf ("host %d: entering setup_npole_lfp" % int(self.pc.id()))

        ## Determine which cells will be used for the LFP computation and the sizes of their compartments
        for (ipop, pop_name) in enumerate(sorted(self.pop_gid_dict.keys())):

            ranlfp = h.Random(self.seed + ipop)
            ranlfp.uniform(0, 1)

            lfp_ids = h.Vector()
            lfp_types = h.Vector()
            lfp_coeffs = h.List()

            for gid in self.pop_gid_dict[pop_name]:

                ransample = ranlfp.repick()

                if not self.pc.gid_exists(gid):
                    continue

                cell = self.pc.gid2cell(gid)
                is_art = False
                if hasattr(cell, 'is_art'):
                    is_art = cell.is_art() > 0
                if is_art:
                    continue

                is_reduced = False
                if hasattr(cell, 'is_reduced'):
                    is_reduced = cell.is_reduced
                if is_reduced:
                    continue

                try:
                    somasec = list(cell.soma)
                except:
                    logger.info("cell %d = %s (dir: %s)" %
                                (gid, str(cell), str(dir(cell))))
                    raise
                x = somasec[0].x3d(0)
                y = somasec[0].y3d(0)
                z = somasec[0].z3d(0)

                ## Relative to the recording electrode position
                if (math.sqrt((x - ex)**2 + (y - ey)**2 +
                              (z - ez)**2) < self.maxEDist):
                    lfptype = 1  ## proximal cell; compute extracellular potential
                else:
                    if (ransample < self.fdst):
                        lfptype = 2  ## distal cell -- compute extracellular potential only for fdst fraction of total
                    else:
                        lfptype = 0  ## do not compute extracellular potential

                if (lfptype > 0):
                    lfp_ids.append(gid)
                    lfp_types.append(lfptype)
                    n = 0
                    for sec in list(cell.all):
                        sec.insert('extracellular')
                        n = n + sec.nseg
                    vec = h.Vector()
                    vec.resize(n)
                    lfp_coeffs.append(vec)

            self.lfp_ids[pop_name] = lfp_ids
            self.lfp_types[pop_name] = lfp_types
            self.lfp_coeffs[pop_name] = lfp_coeffs

        self.setup_lfp_coeffs()
Exemple #6
0
    def recordTraces(self):
        from .. import sim

        # set up voltagse recording; recdict will be taken from global context
        for key, params in sim.cfg.recordTraces.items():
            conditionsMet = 1

            if 'conds' in params:
                for (condKey, condVal) in params['conds'].items(
                ):  # check if all conditions are met
                    # choose what to comapare to
                    if condKey in ['gid']:  # CHANGE TO GID
                        compareTo = self.gid
                    else:
                        compareTo = self.tags[condKey]

                    # check if conditions met
                    if isinstance(condVal, list) and isinstance(
                            condVal[0], Number):
                        if compareTo < condVal[0] or compareTo > condVal[1]:
                            conditionsMet = 0
                            break
                    elif isinstance(condVal, list) and isinstance(
                            condVal[0], basestring):
                        if compareTo not in condVal:
                            conditionsMet = 0
                            break
                    elif compareTo != condVal:
                        conditionsMet = 0
                        break
            if conditionsMet:
                try:
                    ptr = None
                    if 'loc' in params and params['sec'] in self.secs:
                        if 'mech' in params:  # eg. soma(0.5).hh._ref_gna
                            ptr = getattr(
                                getattr(
                                    self.secs[params['sec']]['hObj'](
                                        params['loc']), params['mech']),
                                '_ref_' + params['var'])
                        elif 'synMech' in params:  # eg. soma(0.5).AMPA._ref_g
                            sec = self.secs[params['sec']]
                            synMech = next(
                                (synMech for synMech in sec['synMechs']
                                 if synMech['label'] == params['synMech']
                                 and synMech['loc'] == params['loc']), None)
                            ptr = getattr(synMech['hObj'],
                                          '_ref_' + params['var'])
                        else:  # eg. soma(0.5)._ref_v
                            ptr = getattr(
                                self.secs[params['sec']]['hObj'](
                                    params['loc']), '_ref_' + params['var'])
                    elif 'synMech' in params:  # special case where want to record from multiple synMechs
                        if 'sec' in params:
                            sec = self.secs[params['sec']]
                            synMechs = [
                                synMech for synMech in sec['synMechs']
                                if synMech['label'] == params['synMech']
                            ]
                            ptr = [
                                getattr(synMech['hObj'],
                                        '_ref_' + params['var'])
                                for synMech in synMechs
                            ]
                            secLocs = [
                                params.sec + str(synMech['loc'])
                                for synMech in synMechs
                            ]
                        else:
                            ptr = []
                            secLocs = []
                            for secName, sec in self.secs.items():
                                synMechs = [
                                    synMech for synMech in sec['synMechs']
                                    if synMech['label'] == params['synMech']
                                ]
                                ptr.extend([
                                    getattr(synMech['hObj'],
                                            '_ref_' + params['var'])
                                    for synMech in synMechs
                                ])
                                secLocs.extend([
                                    secName + '_' + str(synMech['loc'])
                                    for synMech in synMechs
                                ])

                    else:
                        if 'pointp' in params:  # eg. soma.izh._ref_u
                            if params['pointp'] in self.secs[
                                    params['sec']]['pointps']:
                                ptr = getattr(
                                    self.secs[params['sec']]['pointps'][
                                        params['pointp']]['hObj'],
                                    '_ref_' + params['var'])
                        elif 'conns' in params:  # e.g. cell.conns
                            if 'mech' in params:
                                ptr = []
                                secLocs = []
                                for conn_idx, conn in enumerate(self.conns):
                                    if params['mech'] in conn.keys():
                                        if isinstance(
                                                conn[params['mech']],
                                                dict) and 'hObj' in conn[
                                                    params['mech']].keys():
                                            ptr.extend([
                                                getattr(
                                                    conn[params['mech']]
                                                    ['hObj'],
                                                    '_ref_' + params['var'])
                                            ])
                                        else:
                                            ptr.extend([
                                                getattr(
                                                    conn[params['mech']],
                                                    '_ref_' + params['var'])
                                            ])
                                        secLocs.extend([
                                            params['sec'] + '_conn_' +
                                            str(conn_idx)
                                        ])
                            else:
                                print(
                                    "Error!!! Specify conn mech to record from."
                                )
                        elif 'var' in params:  # point process cell eg. cell._ref_v
                            ptr = getattr(self.hPointp,
                                          '_ref_' + params['var'])

                    if ptr:  # if pointer has been created, then setup recording
                        if isinstance(ptr, list):
                            sim.simData[key]['cell_' + str(self.gid)] = {}
                            for ptrItem, secLoc in zip(ptr, secLocs):
                                if sim.cfg.recordStep == 'adaptive':
                                    recordStep = 0.1
                                else:
                                    recordStep = sim.cfg.recordStep
                                if hasattr(sim.cfg, 'use_local_dt'
                                           ) and sim.cfg.use_local_dt:
                                    self.secs[params['sec']]['hObj'].push()
                                    if hasattr(
                                            sim.cfg, 'recordStep'
                                    ) and sim.cfg.recordStep == 'adaptive':
                                        sim.simData[key]['cell_time_' + str(
                                            self.gid)][secLoc] = h.Vector()
                                        sim.simData[key]['cell_' + str(
                                            self.gid)][secLoc] = h.Vector()
                                        sim.cvode.record(
                                            ptrItem, sim.simData[key]
                                            ['cell_' + str(self.gid)][secLoc],
                                            sim.simData[key][
                                                'cell_time_' +
                                                str(self.gid)][secLoc])
                                    else:
                                        sim.simData[key][
                                            'cell_' +
                                            str(self.gid)][secLoc] = h.Vector(
                                                sim.cfg.duration / recordStep +
                                                1).resize(0)
                                        sim.cvode.record(
                                            ptrItem, sim.simData[key]
                                            ['cell_' + str(self.gid)][secLoc],
                                            sim.simData['t'], 1)
                                    h.pop_section()
                                else:

                                    sim.simData[key][
                                        'cell_' +
                                        str(self.gid)][secLoc] = h.Vector(
                                            sim.cfg.duration / recordStep +
                                            1).resize(0)
                                    sim.simData[key][
                                        'cell_' +
                                        str(self.gid)][secLoc].record(
                                            ptrItem, recordStep)
                        else:
                            if hasattr(
                                    sim.cfg,
                                    'use_local_dt') and sim.cfg.use_local_dt:
                                self.secs[params['sec']]['hObj'].push()
                                sim.simData[key]['cell_' +
                                                 str(self.gid)] = h.Vector()
                                if hasattr(
                                        sim.cfg, 'recordStep'
                                ) and sim.cfg.recordStep == 'adaptive':
                                    sim.simData[key][
                                        'cell_time_' +
                                        str(self.gid)] = h.Vector()
                                    sim.cvode.record(
                                        ptr, sim.simData[key]['cell_' +
                                                              str(self.gid)],
                                        sim.simData[key]['cell_time_' +
                                                         str(self.gid)])
                                else:
                                    sim.cvode.record(
                                        ptr, sim.simData[key]['cell_' +
                                                              str(self.gid)],
                                        sim.simData['t'], 1)
                                h.pop_section()
                            else:
                                sim.simData[key]['cell_' +
                                                 str(self.gid)] = h.Vector(
                                                     sim.cfg.duration /
                                                     sim.cfg.recordStep +
                                                     1).resize(0)
                                sim.simData[key]['cell_' +
                                                 str(self.gid)].record(
                                                     ptr, sim.cfg.recordStep)
                        if sim.cfg.verbose:
                            print('  Recording ', key, 'from cell ', self.gid,
                                  ' with parameters: ', str(params))
                            print(sim.simData[key]['cell_' + str(self.gid)])
                except:
                    if sim.cfg.verbose:
                        print('  Cannot record ', key, 'from cell ', self.gid)
            else:
                if sim.cfg.verbose:
                    print('  Conditions preclude recording ', key,
                          ' from cell ', self.gid)
Exemple #7
0
h.dt = 0.075  # ms - value of the fundamental integration time step, dt, used by fadvance().

# clamping parameters
min_inter = 0.1  # pre-stimulus starting interval
max_inter = 10000  # pre-stimulus endinging interval
num_pts = 50  # number of points in logaritmic scale
cond_st_dur = 1000  # conditioning stimulus duration
res_pot = -120  # resting potential
dur = 0.1

# vector containing 'num_pts' values equispaced between log10(min_inter) and log10(max_inter)
vec_pts = np.logspace(np.log10(min_inter), np.log10(max_inter), num=num_pts)
L = len(vec_pts)

# vectors for data handling
rec_vec = h.Vector()
time_vec = h.Vector()
log_time_vec = h.Vector()
t_vec = h.Vector()
v_vec_t = h.Vector()
i_vec_t = h.Vector()

# saving data (comment the following 4 lines if you don't want to save the data)
f1 = open('5_rec_s_inact_time_vec.dat', 'w')
f2 = open('5_rec_s_inact_rec_vec.dat', 'w')
f1.write("time=[\n")
f2.write("fractional_recovery=[\n")

# voltage clamp with "five" levels
f3cl = h.VClamp_plus(soma(0.5))
f3cl.dur[0] = 5  # ms
def record(what, func=lambda seg: seg._ref_concentration):
    result = []
    for w in what:
        s = h.Vector().record(func(w))
        result.append(s)
    return result
Exemple #9
0
 def test__local_count(self):
     self.rec.recorded['spikes'] = self.cells
     self.cells[0]._cell.spike_times = h.Vector(numpy.arange(101.0, 111.0))
     self.cells[1]._cell.spike_times = h.Vector(numpy.arange(13.0, 33.0))
     self.assertEqual(self.rec._local_count('spikes', filter_ids=None),
                      {self.cells[0]: 10, self.cells[1]: 20})
Exemple #10
0
def real_morphology_model_dend_spatial(stim,
                                       d=30,
                                       k=0.001,
                                       gpas_soma=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_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()

    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt

    # Stimulus
    h.tstop = len(stim) * dt
    h.load_file("vplay.hoc")
    vec = h.Vector(stim)
    istim = h.IClamp(h.apic[d](0.5))
    vec.play(istim._ref_amp, h.dt)
    istim.delay = 0  # Just for Neuron
    istim.dur = 1e9  # Just for Neuron

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

    # Simulation duration and RUN
    # h.tstop = 1200  # Simulation end
    h.v_init = 0
    h.finitialize(h.v_init)

    h.init()
    h.run()

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

    return t, v
Exemple #11
0
def real_morphology_model_srsoma_rdend_spatial(stim,
                                               d=30,
                                               k=0.001,
                                               gpas_soma=0.0001,
                                               Ra=100.,
                                               cm=1.,
                                               dt=0.1):
    """
    This simulation protocol  assumes spatial change of the 'gpas' parameter

    :param stim:
    :param d:     distance from soma in um
    :param m:     rate of linear change in gpas density moving away from soma (opt)
    :param gpas_soma: the value of gpas in soma (opt)
    :param Ra:    Axial resistance (opt)
    :param cm:    Membrane conductance (opt)
    :param dt:    Time step (opt)
    :return:
    """

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

    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 for soma recording
    vd_vec = h.Vector()  # Membrane potential vector for dendrite recording
    t_vec = h.Vector()  # Time stamp vector
    vd_vec.record(h.apic[d](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
Exemple #12
0
def one_compartment(cm=1.,
                    gpas=0.0001,
                    dt=0.1,
                    stype='broad',
                    custom_stim=None):
    """ One compartment simulation, variables: membrane capacitance and passive conductance """
    # Creating one compartment passive  model (interacting with neuron)
    soma = h.Section(name='soma')
    soma.L = soma.diam = 50  # it is a sphere
    soma.v = -65
    soma.cm = cm  # parameter to infer

    # Insert passive conductance
    soma.insert('pas')
    soma.g_pas = gpas  # parameter to infer
    soma.e_pas = -65

    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt

    # Creating stimulus
    # Here we define three kind of experimental protocol:
    # 1.) broad electrode current
    # 2.) narrow electrode current
    # 3.) both
    if stype == 'broad':
        h.tstop = 300
        stim = h.IClamp(soma(0.5))
        stim.delay = 20
        stim.amp = 0.1
        stim.dur = 175
    elif stype == 'narrow':
        h.tstop = 100
        stim = h.IClamp(soma(0.5))
        stim.delay = 10
        stim.amp = 0.5
        stim.dur = 5
    elif stype == 'both':
        h.tstop = 400
        stim1 = h.IClamp(soma(0.5))
        stim1.delay = 10
        stim1.amp = 0.5
        stim1.dur = 5

        stim2 = h.IClamp(soma(0.5))
        stim2.delay = 120
        stim2.amp = 0.1
        stim2.dur = 175
    elif stype == 'steps':
        h.tstop = 500
        stim1 = h.IClamp(soma(0.5))
        stim1.delay = 10
        stim1.amp = 0.5
        stim1.dur = 5

        stim2 = h.IClamp(soma(0.5))
        stim2.delay = 120
        stim2.amp = 0.1
        stim2.dur = 175

        stim3 = h.IClamp(soma(0.5))
        stim3.delay = 400
        stim3.amp = 0.35
        stim3.dur = 5
    elif stype == 'custom':
        h.tstop = len(custom_stim) * dt
        h.load_file("vplay.hoc")
        vec = h.Vector(custom_stim)
        istim = h.IClamp(soma(0.5))
        vec.play(istim._ref_amp, h.dt)
        istim.delay = 0  # Just for Neuron
        istim.dur = 1e9  # Just for Neuron

    # Print Information
    # h.psection()

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

    # Simulation  RUN
    h.v_init = -65
    h.finitialize(h.v_init)  # Starting membrane potential

    h.init()
    h.run()

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

    return np.array(t), np.array(v)
Exemple #13
0
def stick_and_ball(Ra=100.,
                   gpas=0.0001,
                   cm=1.,
                   Ra_max=250.,
                   dt=0.1,
                   stype='both',
                   custom_stim=None):
    """ Stick and Ball model variables: Passive conductance and axial resistance """
    # Create Sections
    soma = h.Section(name='soma')
    dend = h.Section(name='dend')

    # Topology
    dend.connect(soma(1))

    # Geometry
    soma.L = soma.diam = 30
    dend.L = 1000
    dend.diam = 3

    # Simulation duration and RUN
    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt

    # Set the appropriate "nseg"
    for sec in h.allsec():
        sec.Ra = Ra_max
    h('forall {nseg = int((L/(0.1*lambda_f(100))+.9)/2)*2 + 1}'
      )  # If Ra_max = 105 dend.nseg = 21 and soma.nseg = 1

    # -- Biophysics --
    # Sec parameters and conductance
    for sec in h.allsec():
        sec.Ra = Ra  # Ra is a parameter to infer
        sec.cm = cm
        sec.v = -65

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

    # Stimulus
    # Here we define three kind of experimental protocol:
    # 1.) brad electrode current
    # 2.) narrow electrode current
    # 3.) both
    if stype == 'broad':
        h.tstop = 300
        stim = h.IClamp(soma(0.5))
        stim.delay = 20
        stim.amp = 0.1
        stim.dur = 175
    elif stype == 'narrow':
        h.tstop = 100
        stim = h.IClamp(soma(0.5))
        stim.delay = 10
        stim.amp = 0.5
        stim.dur = 5
    elif stype == 'both':
        h.tstop = 400
        stim1 = h.IClamp(soma(0.5))
        stim1.delay = 10
        stim1.amp = 0.5
        stim1.dur = 5

        stim2 = h.IClamp(soma(0.5))
        stim2.delay = 120
        stim2.amp = 0.1
        stim2.dur = 175
    elif stype == 'steps':
        h.tstop = 500
        stim1 = h.IClamp(soma(0.5))
        stim1.delay = 10
        stim1.amp = 0.5
        stim1.dur = 5

        stim2 = h.IClamp(soma(0.5))
        stim2.delay = 120
        stim2.amp = 0.1
        stim2.dur = 175

        stim3 = h.IClamp(soma(0.5))
        stim3.delay = 400
        stim3.amp = 0.35
        stim3.dur = 5
    elif stype == 'custom':
        h.tstop = len(custom_stim) * dt
        h.load_file("vplay.hoc")
        vec = h.Vector(custom_stim)
        istim = h.IClamp(soma(0.5))
        vec.play(istim._ref_amp, h.dt)
        istim.delay = 0  # Just for Neuron
        istim.dur = 1e9  # Just for Neuron

    # Run simulation ->
    # Print information
    # h.psection()

    # Set up recording Vectors
    v_vec = h.Vector()
    t_vec = h.Vector()
    v_vec.record(soma(0.5)._ref_v)
    t_vec.record(h._ref_t)

    h.v_init = -65
    h.finitialize(h.v_init)  # Starting membrane potential

    h.init()
    h.run()

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

    return np.array(t), np.array(v)
Exemple #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(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 = bool(
        distutils.util.strtobool(os.environ.get("CORENRN_ENABLE_GPU", "false"))
    )
    coreneuron.num_gpus = 1

    pc = h.ParallelContext()

    def run(mode):
        pc.set_maxstep(10)
        h.stdinit()
        if mode == 0:
            pc.psolve(h.tstop)
        elif mode == 1:
            while abs(h.t - h.tstop) > 0.1 * h.dt:
                pc.psolve(h.t + 1.0)
        else:
            while abs(h.t - h.tstop) > 0.1 * h.dt:
                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)
Exemple #15
0
def setupRecording():
    from .. import sim

    sim.timing('start', 'setrecordTime')

    # spike recording
    sim.simData.update(
        {name: h.Vector(1e4).resize(0)
         for name in ['spkt', 'spkid']})  # initialize
    if sim.cfg.recordCellsSpikes == -1:
        sim.pc.spike_record(-1, sim.simData['spkt'], sim.simData['spkid']
                            )  # -1 means to record from all cells on this node
    else:
        recordGidsSpikes = utils.getCellsList(sim.cfg.recordCellsSpikes,
                                              returnGids=True)
        for gid in recordGidsSpikes:
            sim.pc.spike_record(
                float(gid), sim.simData['spkt'], sim.simData['spkid']
            )  # -1 means to record from all cells on this node

    # stim spike recording
    if 'plotRaster' in sim.cfg.analysis:
        if isinstance(sim.cfg.analysis['plotRaster'],
                      dict) and 'include' in sim.cfg.analysis['plotRaster']:
            netStimLabels = list(
                sim.net.params.stimSourceParams.keys()) + ['allNetStims']
            for item in sim.cfg.analysis['plotRaster']['include']:
                if item in netStimLabels:
                    sim.cfg.recordStim = True
                    break

    if 'plotSpikeHist' in sim.cfg.analysis:
        if sim.cfg.analysis['plotSpikeHist'] == True:
            sim.cfg.recordStim = True

        elif (isinstance(sim.cfg.analysis['plotSpikeHist'], dict)
              and 'include' in sim.cfg.analysis['plotSpikeHist']):
            netStimLabels = list(sim.net.params.stimSourceParams.keys()) + [
                'allNetStims', 'eachPop'
            ]
            for item in sim.cfg.analysis['plotSpikeHist']['include']:
                if item in netStimLabels:
                    sim.cfg.recordStim = True
                    break

    if sim.cfg.recordStim:
        sim.simData['stims'] = Dict()
        for cell in sim.net.cells:
            cell.recordStimSpikes()

    # intrinsic cell variables recording
    if sim.cfg.recordTraces:
        # get list of cells from argument of plotTraces function
        if 'plotTraces' in sim.cfg.analysis and 'include' in sim.cfg.analysis[
                'plotTraces']:
            cellsPlot = utils.getCellsList(
                sim.cfg.analysis['plotTraces']['include'])
        else:
            cellsPlot = []

        # get actual cell objects to record from, both from recordCell and plotCell lists
        cellsRecord = utils.getCellsList(sim.cfg.recordCells) + cellsPlot

        for key in list(sim.cfg.recordTraces.keys()):
            sim.simData[key] = Dict()  # create dict to store traces
        for cell in cellsRecord:
            cell.recordTraces()  # call recordTraces function for each cell

        # record h.t
        if sim.cfg.recordTime and len(sim.simData) > 0:
            try:
                sim.simData['t'] = h.Vector(
                )  #sim.cfg.duration/sim.cfg.recordStep+1).resize(0)
                sim.simData['t'].record(h._ref_t, sim.cfg.recordStep)
            except:
                if sim.cfg.verbose:
                    'Error recording h.t (could be due to no sections existing)'

        # print recorded traces
        cat = 0
        total = 0
        for key in sim.simData:
            if sim.cfg.verbose: print(("   Recording: %s:" % key))
            if len(sim.simData[key]) > 0: cat += 1
            for k2 in sim.simData[key]:
                if sim.cfg.verbose: print(("      %s" % k2))
                total += 1
        print(("Recording %s traces of %s types on node %i" %
               (total, cat, sim.rank)))

    # set LFP recording
    if sim.cfg.recordLFP:
        setupRecordLFP()

    sim.timing('stop', 'setrecordTime')

    return sim.simData
Exemple #16
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
config_file = 'simulation_config.json'

conf = bionet.Config.from_json(config_file, validate=True)
conf.build_env()

graph = bionet.BioNetwork.from_config(conf)
sim = bionet.BioSimulator.from_config(conf, network=graph)

cells = graph.get_local_cells()
cell = cells[list(cells.keys())[0]]

hobj = cell.hobj
conn = cell.connections()[0]

som = h.Vector()
som.record(hobj.soma[0](0.5)._ref_v)

syn = h.Vector()
syn.record(conn._connector.postseg()._ref_v)

fac = h.Vector()
try:
    fac.record(conn._syn._ref_igaba)
except:
    fac.record(conn._syn._ref_facfactor)
#import pdb; pdb.set_trace()
sim.run()

import matplotlib.pyplot as plt
plt.figure()
    def __init__(self,
                 parallelContext,
                 neuralNetwork,
                 amplitude,
                 frequency,
                 pulsesNumber=100000,
                 species="rat"):
        """ Object initialization.

		Keyword arguments:
		parallelContext -- Neuron parallelContext object.
		neuralNetwork -- NeuralNetwork instance to connect to this object.
		amplitude -- Aplitude of stimulation. It could either be an integer
		value between _minCur and _maxCur or a list containing the percentages
		of recruited primary afferents, secondary afferents and motoneurons.
		frequency -- Stimulation frequency in Hz; it has to be lower than the
		maximum stimulation frequency imposed by the AfferentFiber model.
		pulsesNumber -- number of pulses to send (default 100000).
		species -- rat or human (it loads different recruitment curves)
		"""
        self._pc = parallelContext
        self._nn = neuralNetwork
        self._species = species
        # Lets assign an Id to the stim object (high value to be sure is not already take from some cell)
        self._eesId = 1000000
        # Initialize a dictionary to contain all the connections between this object and the stimulated cells
        self._connections = {}

        self._maxFrequency = AfferentFiber.get_max_ees_frequency()
        self._current = None
        self._percIf = None
        self._percIIf = None
        self._percMn = None

        # Create the netStim Object in the first process
        if rank == 0:
            # Tell this host it has this cellId
            self._pc.set_gid2node(self._eesId, rank)

            # Create the stim objetc
            self._stim = h.NetStim()
            self._stim.number = pulsesNumber
            self._stim.start = 5  #lets give few ms for init purposes
            self._stim.noise = 0

            self._pulses = h.Vector()
            # Associate the cell with this host and id
            # the nc is also necessary to use this cell as a source for all other hosts
            nc = h.NetCon(self._stim, None)
            self._pc.cell(self._eesId, nc)
            # Record the stimulation pulses
            nc.record(self._pulses)

            # Load the recruitment data
            self._load_rec_data()

        # lets define which type of cells are recruited by the stimulation
        self._recruitedCells = sum(
            [self._nn.get_afferents_names(),
             self._nn.get_motoneurons_names()], [])

        # Connect the stimulation to all muscles of the neural network
        self._connect_to_network()
        # Set stimulation parameters
        self.set_amplitude(amplitude)
        self.set_frequency(frequency)
Exemple #19
0
#specs[6] AMP
#specs[7] ATP
#specs[8] PDE4
#specs[9] PDE4cAMP
reaction1 = rxd.Reaction(specs[3] + specs[0] * 4 <> specs[2], ks[0], ks[1])
reaction3 = rxd.Reaction(specs[2] <> specs[4] + specs[5] * 2,
                         ks[4] * specs[2],
                         ks[5] * specs[4] * specs[5],
                         custom_dynamics=True)

reaction4 = rxd.Reaction(specs[6] > specs[7], ks[6])
reaction5 = rxd.Reaction(specs[8] + specs[0] <> specs[9], ks[7], ks[8])
reaction6 = rxd.Reaction(specs[9] > specs[7] + specs[8], ks[9])

reaction_cAMP_flux = rxd.Rate(specs[0], cAMP_flux_rate)  # cAMP
vec_t = h.Vector()

vecs = []
vec_t = h.Vector()
vec_t.record(h._ref_t)
for ispec in range(0, len(species)):
    vecs.append(h.Vector())
    vecs[ispec].record(specs[ispec].nodes(dend)(0.5)[0]._ref_concentration)

cvode = h.CVode()
cvode.active(1)
hmax = cvode.maxstep(100)
hmin = cvode.minstep(1e-10)
cvode.atol(tolerance)

h.finitialize(-65)
Exemple #20
0
from neuron import h, gui
import matplotlib.pyplot as plt

soma = h.Section(name='soma')
soma.L = 20
soma.diam = 20
soma.insert('hh')

iclamp = h.IClamp(soma(0.5))
iclamp.delay = 10
iclamp.dur = 1
iclamp.amp = 0.9

v = h.Vector().record(soma(0.5)._ref_v)  # Membrane potential vector
t = h.Vector().record(h._ref_t)  # Time stamp vector

h.finitialize(-65)
h.continuerun(40)

plt.plot(t, v)
plt.xlabel('t (ms)')
plt.ylabel('v (mV)')
plt.show()
Exemple #21
0
leak = rxd.MultiCompartmentReaction(ca[er] != ca[cyt],
                                    gleak,
                                    gleak,
                                    membrane=cyt_er_membrane)

minf = ip3[cyt] * 1000. * ca[cyt] / (ip3[cyt] + kip3) / (1000. * ca[cyt] +
                                                         kact)
k = gip3r * (minf * h_gate)**3
ip3r = rxd.MultiCompartmentReaction(ca[er] != ca[cyt],
                                    k,
                                    k,
                                    membrane=cyt_er_membrane)
ip3rg = rxd.Rate(h_gate,
                 (1. / (1 + 1000. * ca[cyt] / (0.3)) - h_gate) / ip3rtau)

v1 = h.Vector()
v1.record(sec(0.5)._ref_v)
ca1 = h.Vector()
ca1.record(sec(0.5)._ref_cai)
v2 = h.Vector()
v2.record(sec(0.25)._ref_v)
ca2 = h.Vector()
ca2.record(sec(0.25)._ref_cai)
times = h.Vector()
times.record(h._ref_t)

h.finitialize()

cae_init = (0.0017 - cac_init * fc) / fe
ca[er].concentration = cae_init
 def __init__(self, numcells):
     neuron_utils.createProject(name='Simple Network')
     self.spkt = h.Vector()  # Spike time of all cells
     self.spkid = h.Vector()  # cell ids of spike times
     self.create_cells(numcells)  # call method to create cells
Exemple #23
0
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

lengths = np.array([200, 300, 400, 500, 600])

fig, axes = plt.subplots(1, 2, sharex='all', squeeze=False, figsize=(16, 8))

for i in range(lengths.size):
    h.apical.L = lengths[i]

    h('recalculate_passive_properties()')
Exemple #24
0
# Collect cells of interest and setup recorders
cellTypes = ['PL2', 'PL5']
cells = {}
imem_recorders = []
areas, diams = [], []
for cellType in cellTypes:
    currentCells = getattr(h, cellType)
    cells[cellType] = []
    for cellInx in range(len(currentCells)):
        currentCell = currentCells[cellInx]
        cells[cellType].append(currentCell)
        for seg in np.r_[currentCell.soma, currentCell.dend]:
            areas.append(seg(.5).area())
            diams.append(seg(.5).diam)
            imem_recorders.append(h.Vector().record(seg(.5)._ref_i_membrane_))
times = h.Vector().record(h._ref_t)  # Time stamp vector

# Record dipoles
dipole_recorders = {}
dipole_names = ['dipoleL2', 'dipoleL5']
for popName in dipole_names:
    dipole_recorders[popName] = []
    for cell in getattr(h, popName):
        for dipole in cell.bd:
            dipole_recorders[popName].append(h.Vector().record(
                dipole._ref_Qsum))

# Define grid recording electrode
gridLims = {'x': [-400, 1100], 'y': [-300, 1400]}
X, Y = np.mgrid[gridLims['x'][0]:gridLims['x'][1]:25,
Exemple #25
0
    def setup_lfp_coeffs(self):

        ex, ey, ez = self.epoint
        for pop_name in self.pop_gid_dict:

            lfp_ids = self.lfp_ids[pop_name]
            lfp_types = self.lfp_types[pop_name]
            lfp_coeffs = self.lfp_coeffs[pop_name]

            for i in range(0, int(lfp_ids.size())):
                ## Iterates over all cells chosen for the LFP computation

                gid = lfp_ids.x[i]
                cell = self.pc.gid2cell(gid)

                ## Iterates over each compartment of the cell
                for sec in list(cell.all):
                    if h.ismembrane('extracellular', sec=sec):

                        nn = sec.n3d()

                        xx = h.Vector(nn)
                        yy = h.Vector(nn)
                        zz = h.Vector(nn)
                        ll = h.Vector(nn)

                        for ii in range(0, nn):
                            xx.x[ii] = sec.x3d(ii)
                            yy.x[ii] = sec.y3d(ii)
                            zz.x[ii] = sec.z3d(ii)
                            ll.x[ii] = sec.arc3d(ii)

                        xint = h.Vector(sec.nseg + 2)
                        yint = h.Vector(sec.nseg + 2)
                        zint = h.Vector(sec.nseg + 2)

                        interpxyz(nn, sec.nseg, xx, yy, zz, ll, xint, yint,
                                  zint)

                        j = 0
                        sx0 = xint.x[0]
                        sy0 = yint.x[0]
                        sz0 = zint.x[0]
                        for seg in sec:

                            sx = xint.x[j]
                            sy = yint.x[j]
                            sz = zint.x[j]

                            ## l = L/nseg is compartment length
                            ## rd is the perpendicular distance from the electrode to a line through the compartment
                            ## ld is longitudinal distance along this line from the electrode to one end of the compartment
                            ## sd = l - ld is longitudinal distance to the other end of the compartment
                            l = float(sec.L) / sec.nseg
                            rd = math.sqrt((ex - sx) * (ex - sx) + (ey - sy) *
                                           (ey - sy) + (ez - sz) * (ez - sz))
                            ld = math.sqrt((sx - sx0) * (sx - sx0) +
                                           (sy - sy0) * (sy - sy0) +
                                           (sz - sz0) * (sz - sz0))
                            sd = l - ld
                            k = 0.0001 * h.area(seg.x) * (
                                self.rho / (4.0 * math.pi * l)) * abs(
                                    math.log(
                                        ((math.sqrt(ld * ld + rd * rd) - ld) /
                                         (math.sqrt(sd * sd + rd * rd) - sd))))
                            if math.isnan(k):
                                k = 0.
                            ## Distal cell
                            if (lfp_types.x[i] == 2):
                                k = (1.0 / self.fdst) * k
                            ##printf ("host %d: npole_lfp: gid = %d i = %d j = %d r = %g h = %g k = %g\n", pc.id, gid, i, j, r, h, k)
                            lfp_coeffs.o(i).x[j] = k
                            j = j + 1
Exemple #26
0
def likeEval(r, theta, nbf, alpha):
    global MLE
    d = h.Vector(2)
    d.x[0] = MLE[0] + r * math.cos(theta)
    d.x[1] = MLE[1] + r * math.sin(theta)
    return pMinusAlpha(nbf, d, alpha)
 def __init__(self, compartment):
     import neuron
     neuron.load_mechanisms('neuron')
     from neuron import h
     self.recorded_potential = h.Vector()
     self.recorded_potential.record(compartment(0.5)._ref_v)
def stim_pulse(stimsec,
               stimseg=0.5,
               delay=500,
               dur=1000,
               amp=0.1,
               tstop=2000,
               recsec="soma",
               recseg=0.5,
               inctime=True,
               plot=False,
               save=False):
    """Stimulates cell section with pulse current. 
	   Returns names and time/voltage vectors in a list. 
	   Option recsec is section to record from and can be 
	   "soma" (default), "all", or the name of a section."""

    cell = stimsec.cell()
    stim = h.IClamp(stimsec(stimseg))
    stim.delay = delay
    stim.dur = dur
    stim.amp = amp
    h.tstop = tstop
    names = []
    traces = []

    # Option to not create a time vector, e.g. multiple runs with same settings
    if inctime:
        t_vec = h.Vector()
        t_vec.record(h._ref_t)
        names.append("time")
        traces.append(t_vec)

    if recsec == "soma":
        names.append(cell.soma.name())
        hvec = h.Vector()
        hvec.record(cell.soma(recseg)._ref_v)
        traces.append(hvec)
    elif recsec == "all":
        for i, cursec in enumerate(cell.all_sec):
            names.append(cursec.name())
            hvec = h.Vector()
            hvec.record(cursec(recseg)._ref_v)
            traces.append(hvec)
    else:
        sec = getattr(cell, recsec)
        names.append(recsec.name())
        hvec = h.Vector()
        hvec.record(recsec(recseg)._ref_v)
        traces.append(hvec)

    h.run()

    fixsecname(names)
    out = [names, traces]

    if plot:
        fig = plt.figure()
        time = out[1][0]
        for i, data in enumerate(out[0]):
            if i > 0:
                name = out[0][i]
                trace = out[1][i]
                plt.plot(time, trace, label=name, linewidth=2)
        plt.xlabel("Time (ms)")
        plt.ylabel("Membrane Potential (mV)")
        plt.title("Cell ID: " + str(cell.ID) + " Current Clamp: " + str(amp) +
                  " nA into: " + fixsecname(stimsec.name()))
        plt.legend()

        if save:
            plt.savefig(
                os.path.join(
                    outputdir,
                    "Stim_pulse_" + cell.name + "_" + str(amp) + "_nA.png"))

    return out
Exemple #29
0
mf = [h.NetStim(0.5) for i in range(nmf)]
mfsyn = [Synapse('glom',grc,grc.soma,nrel=nrel) for i in range(nmf)]

start = 100
mfs_interval = 10

stim_times = np.arange(start, start+(mfs_interval*nmf), mfs_interval)

for i in range(nmf):
    mfsyn[i].input.start = stim_times[i]
    mfsyn[i].input.interval = 5
    mfsyn[i].input.number = 1
    mfsyn[i].input.noise = 0


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

h.celsius = 37
h.dt = 0.025
h.tstop = 500
h.v_init = -65
ica = h.Vector()
ica.record(grc.soma(0.5)._ref_cai,0.1)

h.run()

if plot:
    plt.plot(time,grc.record['vm'])
    plt.show()
# stim = h.IClamp(soma(0.5))
# stim.delay = 1000
# stim.dur = 500
# stim.amp = 0.5

stim = h.SEClamp(soma(0.5))
stim.rs = 0.05
stim.dur1 = 1000
stim.dur2 = 500
stim.dur3 = 500
stim.amp1 = -65
stim.amp2 = -70
stim.amp3 = -65

t_vec = h.Vector()  # Time stamp vector
v_vec = h.Vector()  # Membrane potential vector
cai_vec = h.Vector()
ichan_vec = h.Vector()
ihold_vec = h.Vector()
gate_vec = h.Vector()

t_vec.record(h._ref_t)
v_vec.record(soma(0.5)._ref_v)
cai_vec.record(soma(0.5)._ref_cai)
ichan_vec.record(
    soma(0.5).k_ion._ref_ik)  # change needed here for different channels
ihold_vec.record(stim._ref_i)
# gate_vec.record(soma(0.5).cal._ref_o)

h.tstop = 2000