예제 #1
0
# Simulation parameters

h.tstop = 500  # ms, more than long enough for 15 spikes at ISI = 25 ms
AMP0 = 0.1  # nA -- minimum stimulus
D_AMP = 0.02  # nA -- stim increment between runs
NRUNS = 30

# model specification
from cell import Cell
cell = Cell()

# instrumentation

# experimental manipulations
stim = h.IClamp(cell.soma(0.5))
stim.delay = 1  # ms
stim.dur = 1e9
stim.amp = 0.1  # nA


def fstimamp(run_id):
    """takes run i_d, returns corresponding stimulus amplitude"""
    return AMP0 + run_id * D_AMP


def set_params(run_id):
    """sets stimulus amplitude to appropriate value for this run"""
    stim.amp = fstimamp(run_id)

예제 #2
0
STIM_POINT = 187
STOPTIME = 8000
TIMESTEP = 0.025
LENGTH = 0.5
AMPLITUDE = 15
FREQUENCY = 300
L_RATIO = 2.0  # ratio of length (pre+post)/pre
A_RATIO = 0.3  # ratio of amplitude
POLAR_T = 0.0

volt_time = h.Vector()
RN1 = h.Vector()
RN2 = h.Vector()
RN3 = h.Vector()
vec_i = h.Vector()
ic = h.IClamp(0.5, sec=cell.Dend[STIM_POINT])


def setVoltageRecord():
    volt_time.record(h._ref_t)
    RN1.record(cell.Dend[STIM_POINT](0.5)._ref_v)
    RN2.record(cell.Dend[0](0.5)._ref_v)
    RN3.record(cell.Dend[343](0.5)._ref_v)
    vec_i.record(ic._ref_i)


def writeVoltage():
    h('objref mt,outfile')
    h('mt = new Matrix()')
    h('outfile = new File()')
예제 #3
0
soma.e_leak = -65

The Hodgkin-Huxley channels add the following new properties to the section:

gnabar_hh: The maximum specific sodium channel conductance [Default value = 0.120 S/cm^2]
gkbar_hh: The maximum specific potassium channel conductance [Default value = 0.036 S/cm^2]
gl_hh: The maximum specific leakage conductance [Default value = 0.0003 S/cm^2]
ena: The reversal potential for the sodium channel [Default value = 50 mV]
ek: The reversal potential for the potassium channel [Default value = -77 mV]
el_hh: The reversal potential for the leakage channel [Default value = -54.3 mV]

'''

## POINT PROCESSES ################################

stim = h.IClamp(0.5, soma)

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

## Current to be applied

VecT = h.Vector([0, 100, 200])
VecStim = h.Vector([0.2, 0.4])

stim.delay = 5
stim.dur = 1e9
##stim.amp = 0.4

VecStim.play(stim._ref_amp, VecT)
예제 #4
0
from neuron import h
soma = h.Section(name='soma')
soma.insert('hh')
istim = h.IClamp(soma(.5))
print(dir(soma(.5).hh))
예제 #5
0
def simulate_models_IF(cells_list,
                       models_dirs,
                       models_path="../ActiveModels/",
                       morphs_path="../Morphs/",
                       save_traces=False,
                       save_path='simulated_models_IF_Curve/',
                       thresh=0):
    h.load_file("import3d.hoc")
    h.steps_per_ms = 25
    h.dt = 1.0 / h.steps_per_ms
    h.tstop = 1500
    h.celsius = 37
    h.v_init = -86

    for ix, cell in enumerate(cells_list):
        model = models_dirs[cell]['model']
        print "simulates model", model
        h.load_file(models_path + model + ".hoc")
        h("objref HCell")
        h("HCell = new " + model + "()")
        HCell = h.HCell
        nl = h.Import3d_Neurolucida3()

        # Creating the model
        nl.quiet = 1
        nl.input(morphs_path + models_dirs[cell]['morph'])
        imprt = h.Import3d_GUI(nl, 0)
        imprt.instantiate(HCell)
        HCell.indexSections(imprt)
        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
        icl.amp = 0

        # 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()
        MODEL_IF = []
        range_amps = range(0, 3000, 100)
        bar = progressbar.ProgressBar(max_value=len(range_amps),
                                      widgets=[
                                          ' [',
                                          progressbar.Timer(),
                                          '] ',
                                          progressbar.Bar(),
                                          ' (',
                                          progressbar.ETA(),
                                          ') ',
                                      ])

        for jx, amp1000 in enumerate(range_amps):
            amp = amp1000 / 1000.0
            icl.amp = amp
            h.init(h.v_init)
            h.run()
            n = count_spikes(np.array(Vsoma), thresh)
            MODEL_IF.append((amp, n))

            bar.update(jx)

        MODEL_IF = np.array(MODEL_IF)

        models_dirs[cell]['I'] = MODEL_IF[:, 0]
        models_dirs[cell]['F'] = MODEL_IF[:, 1]

        if save_traces:
            if not os.path.exists(save_path):
                os.mkdir(save_path)
            np.savetxt(save_path + model + "IF.txt", np.array(MODEL_IF))
예제 #6
0
h.load_file("nrngui.hoc")
h.celsius = 34
# create one of each cell type
# olm_cell2, axoaxonic_cell17S, basket_cell17S, bistratified_cell13S, pyramidal_cell_14Vb.hoc
h.load_file("pyramidal_cell_14Vb.hoc")
h('objref hoccell')
h('hoccell = new PyramidalCell()')
print("Made a hoc cell")

from model import cellClasses

pycell = cellClasses.PyramidalCell()
print("Made a python cell")

# add a current clamp to each one
newclamp = h.IClamp(pycell.soma(0.5))
newclamp.delay = 10
newclamp.dur = 500
newclamp.amp = .1

h('objref oldclamp')
h('hoccell.soma oldclamp = new IClamp(0.5)')
h.oldclamp.delay = 10
h.oldclamp.dur = 500
h.oldclamp.amp = .1

h.tstop = 500
print("Set current injection")
#%%
# record membrane potential, run a simulation, and compare results
py_soma_v = h.Vector().record(pycell.soma(0.5)._ref_v)
예제 #7
0
def run_cell(diam,cm,el,gl,gna,gh,gk,tstop,dur,amp,mhalf,hhalf,mk,hk,nhalf,kn,multiply,multiply1,multiply2,seg1,seg2,seg3):
    #Load the mechanisms in the current directory
    neuron.load_mechanisms(os.path.dirname(os.path.abspath(__file__)))

    Passive = [1,-1,-65]
    soma = h.Section(name='soma')
    soma.L = 100 # um
    soma.insert('hh')
    
    v0_vec = h.Vector()
    t_vec = h.Vector()
    
    v0_vec.record(soma(0.5)._ref_v)
    t_vec.record(h._ref_t)
    
    soma.insert('na1')
    soma.insert('k1')
    soma.insert('hd')

    m_na = h.Vector()
    h_hd = h.Vector()
    n_k = h.Vector()
    tau_m = h.Vector()
    tau_h = h.Vector()
    tau_n = h.Vector()
    
    m_na.record(soma(0.5)._ref_minf_na1)
    h_hd.record(soma(0.5)._ref_linf_hd)
    n_k.record(soma(0.5)._ref_ninf_k1)
    tau_m.record(soma(0.5)._ref_mtau_na1)
    tau_h.record(soma(0.5)._ref_taul_hd)
    tau_n.record(soma(0.5)._ref_taun_k1)

    soma.diam = diam
    soma.cm = cm*1.4884e-4/6.2832e-4
    soma.gbar_na1 = gna*1e-3
    soma.gbar_k1 = gk*1e-3
    soma.gl_hh = gl*1e-6
    soma.ghdbar_hd = gh*1e-4
    soma.el_hh = el
    soma.mhalf_na1 = mhalf
    soma.vhalfl_hd = hhalf
    soma.mk_na1 = mk
    soma.kl_hd = hk
    soma.vhalfn_k1 = nhalf
    soma.kn_k1 = kn
    soma.multiply1_na1 = multiply1
    soma.multiply2_na1 = multiply2
    soma.multiply_k1 = multiply
    soma.seg_value1_k1 = seg1
    soma.seg_value2_na1 = seg2
    soma.seg_value3_hd = seg3
        
    Source = h.IClamp(soma(0.5))
    Source.delay = dur[0]
    Source.dur = dur[1]-dur[0]
    Source.amp = amp
    
    h.tstop = tstop
    h.v_init = el
    
    nc = h.NetCon(soma(0.5)._ref_v,None,sec=soma)
    nc.threshold = 0
    spvec = h.Vector()
    nc.record(spvec)
    if Source.amp < 0:
        h.run()
        print('number of spikes:',len(spvec))
        
        R_in_1 = 1/(soma.gl_hh*1000)
        tau_1 = soma.cm*R_in_1
        V_rest_1 = v0_vec[int(tstop)-20]
        
        R_in_2 = Passive[1]
        tau_2 = Passive[0]
        V_rest_2 = Passive[2]
    
        df1 = pd.DataFrame([[tau_1],[V_rest_1],[R_in_1],[tau_2],[V_rest_2],[R_in_2]],
        columns=['value  '],
        index = ['tau_seg  ', 'Vrest_seg  ', 'Rin_seg  ','tau_ori  ', 'Vrest_ori  ', 'Rin_ori  '])
        print (df1)
        plt.figure(figsize=(10,6))
        plt.plot(t_vec, v0_vec,'b')
        plt.xlim(0, tstop)
        plt.ylabel('mV')
    
    frequency =["all"]
    amplitude =["all"]  
    # FIR Curve

    freq1 = []
    I1 = []
    freq2 = []
    I2 = []
    if (Source.amp > 0):
        for Source.amp in np.arange(amp,amp+1,0.1):
            h.run()
            freq1.append(len(spvec)*1000/Source.dur)
            I1.append(Source.amp)
        plt.figure(figsize=(16,14))
        plt.subplot(4,1,1)
        plt.plot(t_vec, v0_vec,'b')
        plt.xlim(0, tstop)
        plt.ylabel('mV')
        plt.subplot(4,1,2)
        plt.plot(amplitude,frequency,'bo')
        plt.plot(I1,freq1,'yo')
        #plt.legend([soma.flag_k1,1-soma.flag_k1])
        plt.xlabel('Injected current (nA)')
        plt.ylabel('frequency') 
        plt.subplot(4,1,3)
        plt.plot(v0_vec, m_na,'r.')
        plt.plot(v0_vec, h_hd,'b.')
        plt.plot(v0_vec, n_k, 'g.')
        #plt.xlim(0, tstop)
        plt.xlabel('voltage (mV)')
        plt.ylabel('Probability')
        plt.legend(['minf','hinf','ninf'])
        plt.subplot(4,1,4)
        plt.plot(v0_vec, tau_m,'r.')
        plt.plot(v0_vec, tau_h,'b.')
        plt.plot(v0_vec, tau_n, 'g.')
        plt.xlabel('voltage (mV)')
        plt.ylabel('tau')
        plt.legend(['minf','hinf','ninf'])
    image = BytesIO()
    #plt.show()
    plt.savefig(image, format='png')
    ret = base64.b64encode(image.getvalue())
    return str(ret)
hoc_setup()

cable = h.Section(name='cable')
h.pt3dadd(0.0, 0.0, 0.0, d0,  sec=cable)
h.pt3dadd(length, 0.0, 0.0, d1, sec=cable)

cable.cm = 100*cm       # [µF/cm² = 0.01 F/m²]
cable.Ra = 100*ra       # [Ω cm = 0.01 Ω m]
cable.nseg = int(n)

cable.insert('pas')
cable.g_pas = 0.0001/rm  # [S/cm² = 10000 S/m²]
cable.e_pas = Erev

stim = h.IClamp(cable(1))
stim.delay = 0
stim.dur = tend
stim.amp = iinj

h.v_init = Erev

# Run model

# Take samples from the middle of each compartment.
xs = [(2.0*i+1)/(2*n) for i in range(int(n))]

tvec = h.Vector([tsample])
vrecs = []
for x in xs:
    vrecs.append(h.Vector())
예제 #9
0
def update_vclamp(vclamp, dur, amp):
    vclamp.dur[0] = float(dur)  # in ms
    vclamp.amp[0] = float(amp)  # in mV


# ----- Create Single Cell -----
simpleCell = CellTemplate.Cell()

# ----- Simulation Parameters -----
h.v_init = -60
h.tstop = 100
h.dt = 0.001
h.steps_per_ms = 1000.0

# ----- Stimulation Parameters -----
ccl = h.IClamp(simpleCell.soma(0.8))
update_iclamp(ccl, 10, 50, -1)

# ----- Create Vectors to Record Plotting Parameters -----
t_vec = h.Vector()
ccl_vec = h.Vector()
vcl_vec = h.Vector()
v_vec = h.Vector()
i_cadyn_vec = h.Vector()
i_im_vec = h.Vector()
il_leak_vec = h.Vector()

# ----- Create Recording for Each Parameter -----
t_vec.record(h._ref_t)
ccl_vec.record(ccl._ref_i)
v_vec.record(simpleCell.soma(0.5)._ref_v)
예제 #10
0
    def plot_voltage(self,
                     ax=None,
                     delay=2,
                     duration=100,
                     dt=0.2,
                     amplitude=1,
                     show=True):
        """Plot voltage on soma for an injected current

        Parameters
        ----------
        ax : instance of matplotlib axis | None
            An axis object from matplotlib. If None,
            a new figure is created.
        delay : float (in ms)
            The start time of the injection current.
        duration : float (in ms)
            The duration of the injection current.
        dt : float (in ms)
            The integration time step
        amplitude : float (in nA)
            The amplitude of the injection current.
        show : bool
            Call plt.show() if True. Set to False if working in
            headless mode (e.g., over a remote connection).
        """
        import matplotlib.pyplot as plt
        from neuron import h
        h.load_file('stdrun.hoc')

        soma = self.soma

        h.tstop = duration
        h.dt = dt
        h.celsius = 37

        iclamp = h.IClamp(soma(0.5))
        iclamp.delay = delay
        iclamp.dur = duration
        iclamp.amp = amplitude

        v_membrane = h.Vector().record(self.soma(0.5)._ref_v)
        times = h.Vector().record(h._ref_t)

        print('Simulating soma voltage')
        h.finitialize()

        def simulation_time():
            print('Simulation time: {0} ms...'.format(round(h.t, 2)))

        for tt in range(0, int(h.tstop), 10):
            h.CVode().event(tt, simulation_time)

        h.continuerun(duration)
        print('[Done]')

        if ax is None:
            fig, ax = plt.subplots(1, 1)
        ax.plot(times, v_membrane)
        ax.set_xlabel('Time (ms)')
        ax.set_ylabel('Voltage (mV)')
        if show:
            plt.show()
예제 #11
0
# The model that I choose is:
# A model of spike initiation in neocortical pyramidal neurons
# Z. F. Mainen, J. Joerges, J. R. Huguenard and T. J. Sejnowski
# Neuron 15, 1427-1439 (1995)

# From the original demo I deleted the synapses and the interview panel for clarity.

# You need to compile the hoc file before launching it
# $ nrnivmodl

# Importing the NeuronVisio
from neuronvisio.controls import Controls
controls = Controls()

# Importing hoc interpreter
from neuron import h

# loading the model
# importing the interview so the GUI does not freeze
# Uncomment this if you want to use also the interview GUI
#import neuron.gui

# Load the script
h.load_file("demo.hoc")

## Insert an IClamp
st = h.IClamp(0.5, sec=h.soma)
st.amp = 0.25
st.delay = 3
st.dur = 40
예제 #12
0
# Channels
soma.insert('hh')
soma.gnabar_hh = 0.12
soma.gkbar_hh = 0.036
soma.gl_hh = 0.0003
soma.el_hh = -54.3
'''
dend.insert('hh')
dend.gkbar_hh = 0.05 # Your channel conductance. # try 0, 0.05 and 0.5
dend.gl_hh = 0.0003
dend.el_hh = -54.3
'''
# Connect soma and dendrite

# stimulation at dend
stim = h.IClamp(dend(1.0))
stim.amp = 0.003  # Try variations 0, 0.003, 0.03, 0.3 and 3.
stim.delay = 40
stim.dur = 1

# recordings
t_vec = h.Vector()
v_vec_soma = h.Vector()
v_vec_dend = h.Vector()
v_vec_soma.record(soma(1.0)._ref_v)
v_vec_dend.record(dend(1.0)._ref_v)
t_vec.record(h._ref_t)

h.tstop = 60

for g in [0, 0.05, 0.5, 5, 50]:
예제 #13
0
def ap_rate_test(tree, v_init):

    cell = cells.make_neurotree_cell("NGFCell", neurotree_dict=tree)
    h.dt = 0.025

    prelength = 1000.0
    mainlength = 2000.0

    tstop = prelength + mainlength

    stimdur = 1000.0

    stim1 = h.IClamp(cell.sections[0](0.5))
    stim1.delay = prelength
    stim1.dur = stimdur
    stim1.amp = 0.2

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

    h.Vlog = h.Vector()
    h.Vlog.record(cell.sections[0](0.5)._ref_v)

    h.spikelog = h.Vector()
    nc = h.NetCon(cell.sections[0](0.5)._ref_v, h.nil)
    nc.threshold = -40.0
    nc.record(h.spikelog)

    h.tstop = tstop

    it = 1
    ## Increase the injected current until at least 60 spikes occur
    ## or up to 5 steps
    while (h.spikelog.size() < 60):

        utils.simulate(h, v_init, prelength, mainlength)

        if ((h.spikelog.size() < 50) & (it < 5)):
            print("ap_rate_test: stim1.amp = %g spikelog.size = %d\n" %
                  (stim1.amp, h.spikelog.size()))
            stim1.amp = stim1.amp + 0.1
            h.spikelog.clear()
            h.tlog.clear()
            h.Vlog.clear()
            it += 1
        else:
            break

    print("ap_rate_test: stim1.amp = %g spikelog.size = %d\n" %
          (stim1.amp, h.spikelog.size()))

    isivect = h.Vector(h.spikelog.size() - 1, 0.0)
    tspike = h.spikelog.x[0]
    for i in range(1, int(h.spikelog.size())):
        isivect.x[i - 1] = h.spikelog.x[i] - tspike
        tspike = h.spikelog.x[i]

    print("ap_rate_test: isivect.size = %d\n" % isivect.size())
    isimean = isivect.mean()
    isivar = isivect.var()
    isistdev = isivect.stdev()

    isilast = int(isivect.size()) - 1
    if (isivect.size() > 10):
        isi10th = 10
    else:
        isi10th = isilast

    ## Compute the last spike that is largest than the first one.
    ## This is necessary because some variants of the model generate spike doublets,
    ## (i.e. spike with very short distance between them, which confuse the ISI statistics.
    isilastgt = int(isivect.size()) - 1
    while (isivect.x[isilastgt] < isivect.x[1]):
        isilastgt = isilastgt - 1

    if (not (isilastgt > 0)):
        isivect.printf()
        raise RuntimeError(
            "Unable to find ISI greater than first ISI: forest_path = %s gid = %d"
            % (forest_path, gid))

    f = open("NGFCell_ap_rate_results.dat", 'w')

    f.write("## number of spikes: %g\n" % h.spikelog.size())
    f.write("## FR mean: %g\n" % (1.0 / isimean))
    f.write("## ISI mean: %g\n" % isimean)
    f.write("## ISI variance: %g\n" % isivar)
    f.write("## ISI stdev: %g\n" % isistdev)
    f.write("## ISI adaptation 1: %g\n" % (old_div(isivect.x[0], isimean)))
    f.write("## ISI adaptation 2: %g\n" %
            (old_div(isivect.x[0], isivect.x[isilast])))
    f.write("## ISI adaptation 3: %g\n" %
            (old_div(isivect.x[0], isivect.x[isi10th])))
    f.write("## ISI adaptation 4: %g\n" %
            (old_div(isivect.x[0], isivect.x[isilastgt])))

    f.close()

    f = open("NGFCell_voltage_trace.dat", 'w')
    for i in range(0, int(h.tlog.size())):
        f.write('%g %g\n' % (h.tlog.x[i], h.Vlog.x[i]))
    f.close()
예제 #14
0
def gap_junction_test(tree, v_init):

    h('objref gjlist, cells, Vlog1, Vlog2')

    h.pc = h.ParallelContext()
    h.cells = h.List()
    h.gjlist = h.List()

    cell1 = cells.make_neurotree_cell("NGFCell", neurotree_dict=tree)
    cell2 = cells.make_neurotree_cell("NGFCell", neurotree_dict=tree)

    h.cells.append(cell1)
    h.cells.append(cell2)

    ggid = 20000000
    source = 10422930
    destination = 10422670
    srcbranch = 1
    dstbranch = 2
    weight = 5.4e-4

    stimdur = 500
    tstop = 2000

    h.pc.set_gid2node(source, int(h.pc.id()))
    nc = cell1.connect2target(h.nil)
    h.pc.cell(source, nc, 1)

    h.pc.set_gid2node(destination, int(h.pc.id()))
    nc = cell2.connect2target(h.nil)
    h.pc.cell(destination, nc, 1)

    stim1 = h.IClamp(cell1.sections[0](0.5))
    stim1.delay = 250
    stim1.dur = stimdur
    stim1.amp = -0.1

    stim2 = h.IClamp(cell2.sections[0](0.5))
    stim2.delay = 500 + stimdur
    stim2.dur = stimdur
    stim2.amp = -0.1

    log_size = old_div(tstop, h.dt) + 1

    h.tlog = h.Vector(log_size, 0)
    h.tlog.record(h._ref_t)

    h.Vlog1 = h.Vector(log_size)
    h.Vlog1.record(cell1.sections[0](0.5)._ref_v)

    h.Vlog2 = h.Vector(log_size)
    h.Vlog2.record(cell2.sections[0](0.5)._ref_v)

    h.mkgap(h.pc, h.gjlist, source, srcbranch, ggid, ggid + 1, weight)
    h.mkgap(h.pc, h.gjlist, destination, dstbranch, ggid + 1, ggid, weight)

    h.pc.setup_transfer()
    h.pc.set_maxstep(10.0)

    h.stdinit()
    h.finitialize(v_init)
    h.pc.barrier()

    h.tstop = tstop
    h.pc.psolve(h.tstop)

    f = open("NGFCellGJ.dat", 'w')
    for (t, v1, v2) in zip(h.tlog, h.Vlog1, h.Vlog2):
        f.write("%f %f %f\n" % (t, v1, v2))
    f.close()
예제 #15
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
예제 #16
0
print syn

#Create vectors for recording potentials, currents, etc in the neural network during the simulation.

vec = recordData(numNeurons, Soma)

#Create random, unique simulation for the network.
"""
numberStimulations = random.randint(1,numNeurons-1)
stim = []
for i in range(0,numberStimulations):
	stim.append(constructStimulations( numNeurons-1, simTime, Soma, Axon, BD, AD ))
print stim
"""

stim = h.IClamp(Soma[0](0.5))
stim.delay = 5
stim.dur = 1
stim.amp = 1
"""
stim1 = h.IClamp(Soma[7](0.5) )		
stim1.delay = 5	
stim1.dur = 1		
stim1.amp = 10
"""

# run the simulation
h.load_file("stdrun.hoc")
h.init()
h.tstop = simTime
h.run()
예제 #17
0
# Make model

hoc_setup()

cable = h.Section(name='cable')
cable.diam = diam
cable.L= length
cable.cm = 100*cm       # [µF/cm² = 0.01 F/m²]
cable.Ra = 100*ra       # [Ω cm = 0.01 Ω m]
cable.nseg = int(n)

cable.insert('pas')
cable.g_pas = 0.0001/rm  # [S/cm² = 10000 S/m²]
cable.e_pas = Erev

stim = h.IClamp(cable(0))
stim.delay = 0
stim.dur = tend
stim.amp = iinj

h.v_init = Erev

# Run model

v0 = h.Vector()
v0.record(cable(x0)._ref_v, sample_dt)

v1 = h.Vector()
v1.record(cable(x1)._ref_v, sample_dt)

t = h.Vector()
def main(       cell_type=None,
                mdl_ID=0         ): 
    
    modeldir    =   './Striatal_network_models/{}/{}'.format(cell_type, cells_dirs[cell_type][mdl_ID])
    
    par         =   '{}/parameters_with_modulation.json'.format(modeldir)
    mech        =   '{}/mechanisms.json'.format(modeldir)
    protocols   =   '{}/protocols.json'.format(modeldir)
    morphology  =   glob.glob(modeldir+'/*.swc')[0] # ONLY 1 swc file / model allowed.
    
        
    # initiate cell 
    cell = build.CELL(  params=par,
                        mechanisms=mech,
                        morphology=morphology,
                        replace_axon=True,
                        N=40.0,
                        ffactor=ffactor  )
    
    #  ADD SPINES----
    SPINES = {}
    ID = 0
    for sec in cell.dendlist:
        SPINES[sec.name()] = {}
        for i,seg in enumerate(sec):
            for j in range(10):
                SPINES[sec.name()][ID] = spine.Spine(h,sec,seg.x)
                ID += 1
    
    print(ID)
    #return [1,1]
    #h.topology()          
      
    # THIS PART IS OPTIONAL oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
    # set input here
    
    # set current injection
    with open(protocols) as file:
        prot = json.load(file)
    
    # select first spiking prot
    all_keys    = sorted(prot.keys())
    key         = all_keys[0]
    
    i=1
    while 'sub' in key:
        key = all_keys[i]
        i += 1
    print(key)
    
    stim        =   h.IClamp(0.5, sec=cell.soma)
    s0          =   h.IClamp(0.5, sec=cell.soma)
    
    for stim_prot, stimuli, j in zip(prot[key]['stimuli'], [stim,s0], [0,1]): 
        stimuli.amp    =   stim_prot['amp']
        stimuli.delay  =   [200,0][j]
        stimuli.dur    =   stim_prot['duration']
    
    
    # oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
     
    # record vectors: set recordings here
    tm  = h.Vector()
    tm.record(h._ref_t)
    vm  = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)
    
    tstop  = 600    # sim time (ms)
    
    h.finitialize(cell.v_init)
    
    # run simulation
    while h.t < tstop:
        h.fadvance()
        
    # save output ------------------------------------------------------------------------
    time    = tm.to_python()
    voltage = vm.to_python()
    
    return [time, voltage]
예제 #19
0
파일: HHmunge.py 프로젝트: wwlytton/AP
from neuron import h
import axonA
vvec = [h.Vector() for i in range(3)]
svec, ivec = h.Vector(), h.Vector()
ncl = []

axon = axonA.AxonA()
axon.axon.nseg = 100
axon.axon.gnabar_hh, axon.axon.gkbar_hh, axon.axon.gl_hh, axon.axon.el_hh = 0.12, 0.036, 3e-4, -54.3  # set for all segments with underscore notation

stim = h.IClamp()
stim.loc(0.0, sec=axon.axon)
stim.amp = 2
stim.dur = 5
ena = 50


def setena(en=50):
    global ena
    ena = en
    for x in axon.axon:
        x.ena = ena


def ae():
    for x, v, i in zip(np.linspace(0, 1, len(vvec)), vvec, range(len(vvec))):
        v.record(axon.axon(x)._ref_v)
        nc = h.NetCon(axon.axon(x)._ref_v, None, sec=axon.axon)
        ncl.append(nc)
        nc.threshold = -20
        nc.record(svec, ivec, i + 1)
예제 #20
0
gna = pA * gnabar * mgate ** 3 * hgate
gk = pA * gkbar * ngate ** 4

na_current = rxd.MultiCompartmentReaction(
    nai, nao, gna * (v - ena), mass_action=False, membrane=mem, membrane_flux=True
)
k_current = rxd.MultiCompartmentReaction(
    ki, ko, gk * (v - ek), mass_action=False, membrane=mem, membrane_flux=True
)
leak_current = rxd.MultiCompartmentReaction(
    xi, xo, pA * gl * (v - el), mass_action=False, membrane=mem, membrane_flux=True
)

# stimulate
stimA = h.IClamp(mycellA.soma[0](0.5))
stimA.delay = 50
stimA.amp = 5
stimA.dur = 50

stimB = h.IClamp(mycellB.soma[0](0.5))
stimB.delay = 50
stimB.amp = 5
stimB.dur = 50

# record
tvec = h.Vector().record(h._ref_t)

vvecA = h.Vector().record(mycellA.soma[0](0.5)._ref_v)
mvecA = h.Vector().record(mgate.nodes(mycellA.soma[0](0.5))[0]._ref_value)
nvecA = h.Vector().record(ngate.nodes(mycellA.soma[0](0.5))[0]._ref_value)
예제 #21
0
 def mkstim(self):
     self.ic = h.IClamp(self.cells[0].soma(0.5))
     self.ic.delay = 1
     self.ic.dur = 0.2
     self.ic.amp = 0.3
예제 #22
0
sec4 = h.Section()
fill_section(sec)
fill_section(sec2)
fill_section(sec3)
fill_section(sec4)
sec2.connect(sec)
sec3.connect(sec)
sec4.connect(sec, .3, 0)

nstim = 5
st_dur = 2
st_interv = 50
st_start = 1000
stims = []
for i in range(nstim):
    stim = h.IClamp(0.5, sec=sec)
    stim.delay = st_start + i * (st_interv)
    stim.dur = st_dur
    stim.amp = 1.0 / 8000 * 1200
    stims.append(stim)

h.CVode().active(1)
h.cvode.atol(1e-6)


def set_plotshape_colormap(plotshape, cmap='jet'):
    import matplotlib.cm
    s = matplotlib.cm.ScalarMappable(cmap=cmap)
    cmap = s.get_cmap()
    s.set_clim(0, cmap.N)
    rs, gs, bs = itertools.islice(zip(*s.to_rgba(list(range(cmap.N)))), 0, 3)
예제 #23
0
파일: basicHH.py 프로젝트: wwlytton/AP
h.load_file('stdrun.hoc')
fig, axi = None, None
datestr = os.popen('datestring').read()


def setparams(pnafjr=0.0, gnabar=0.12):
    soma.gnabar_nafjr = pnafjr * gnabar
    soma.gnabar_hh = (1.0 - pnafjr) * gnabar
    return 1.0


soma = h.Section(name='soma')
soma.insert('hh')
soma.insert('nafjr')
soma.gnabar_nafjr = 0
stim = h.IClamp(soma(0.5))
stim.delay, stim.dur, stim.amp = 0, 1, 15
h.tstop = 10
fig, axi = plt.subplots(1, 1)
tvec = h.Vector()
vecl = [h.Vector()]
tvec.record(h._ref_t)
vecl[0].record(soma(0.5)._ref_v)

# sim runs
axi.clear()
setparams(0.0)
h.run()
plt.plot(tvec, vecl[0], color='red', linewidth=5)
setparams(1.0)
h.run()
예제 #24
0
def simulate_single_param(args):
    """
  Simulates a specific input parameter vector
  
  :param args: The parameters for the simulation: 
                 The list of excitatory presynpatic inputs,
                 The list of inhibitory presynpatic inputs,
                 and the input parameter dictionary
  :returns: The voltage trace of the simulation
  """
    from neuron import h
    from neuron import gui
    h.load_file("nrngui.hoc")
    h.load_file("import3d.hoc")

    param_dict = args[0]

    hoc_code = '''h("create soma")
h("access soma")
h("nseg = 1")
h("L = 20")
h("diam = 20")
h("insert pas")
h("cm = 1")
h("Ra = 150")
h("forall nseg = 1")
h("forall e_pas = -90")

h("soma insert Ca_LVAst ")
h("soma insert Ca_HVA ")
h("soma insert SKv3_1 ")
h("soma insert SK_E2 ")
h("soma insert K_Tst ")
h("soma insert K_Pst ")
h("soma insert Nap_Et2 ")
h("soma insert NaTa_t")
h("soma insert CaDynamics_E2")
h("soma insert Ih")

h("ek = -85")
h("ena = 50")
h("gIhbar_Ih = 0.0002")
h("g_pas = 1.0 / 12000 ")
h("celsius = 36")
'''

    exec(hoc_code)
    exec('h("tstop = {}")'.format(simulation_length))
    exec('h("v_init = {}")'.format(v_init))

    for key in param_dict.keys():
        h(key + " = " + str(param_dict[key]))

    iclamp = h.IClamp(0.5)
    iclamp.delay = 500
    iclamp.dur = 1400

    amp = 0.05
    iclamp.amp = amp
    im = h.Impedance()
    h("access soma")
    h("nseg = 1")
    im.loc(0.5)
    im.compute(0)
    Ri = im.input(0.5)

    semitrial_start = time.time()

    ### Set the protocol

    h.finitialize()

    ### Simulate!

    voltageVector = h.Vector()
    voltageVector.record(eval("h.soma(0.5)._ref_v"))
    timeVector = h.Vector()
    timeVector.record(h._ref_t)

    h.run()

    timeVector = np.array(timeVector)
    voltageVector = np.array(voltageVector)

    trace = {}
    trace['T'] = timeVector[4000:]
    trace['V'] = np.array(voltageVector)[4000:]
    trace['stim_start'] = [500]
    trace['stim_end'] = [1900]
    del voltageVector, timeVector
    return trace
from neuron import h
from pylab import *
import timeit

start = timeit.default_timer()

cell = h.Section()
cell.insert('hha2')

stimulus = h.IClamp(0.5)
stimulus.delay = 100
stimulus.dur = 800
stimulus.amp = 7

trec = h.Vector()
vrec = h.Vector()

trec.record(h._ref_t)
vrec.record(cell(0.5)._ref_v)

stimuli_rec = h.Vector()
stimuli_rec.record(stimulus._ref_i)

h.load_file("stdrun.hoc")
h.init()
h.v_init = -65
h.tstop = 1000

before_run = timeit.default_timer()
print('initial time:%f' % (before_run - start))
from neuron import h

# create pre-and post-synaptic sections
pre = h.Section()
post = h.Section()

for sec in pre, post:
    sec.insert('hh')

# inject current in the pre-synaptic section
stim = h.IClamp(0.5, sec=pre)
stim.amp = 10.0
stim.delay = 5.0
stim.dur = 5.0

# create a synapse in the pre-synaptic section
syn = h.ExpSyn(0.5, sec=post)

# connect the pre-synaptic section to the
# synapse object
nc = h.NetCon(pre(0.5)._ref_v, syn, sec=pre)

vec = {}
for var in 'v_pre', 'v_post', 'i_syn', 't':
    vec[var] = h.Vector()

# record the membrane potentials and
# synaptic currents
vec['v_pre'].record(pre(0.5)._ref_v)
vec['v_post'].record(post(0.5)._ref_v)
vec['i_syn'].record(syn._ref_i)
예제 #27
0
                                          membrane_flux=True)
k_current = rxd.MultiCompartmentReaction(ki,
                                         ko,
                                         gk * (v - ek),
                                         mass_action=False,
                                         membrane=mem,
                                         membrane_flux=True)
leak_current = rxd.MultiCompartmentReaction(xi,
                                            xo,
                                            pA * gl * (v - el),
                                            mass_action=False,
                                            membrane=mem,
                                            membrane_flux=True)

# stimulate
stimA = h.IClamp(somaA(0.5))
stimA.delay = 50
stimA.amp = 1
stimA.dur = 50

stimB = h.IClamp(somaB(0.5))
stimB.delay = 50
stimB.amp = 1
stimB.dur = 50

# record
tvec = h.Vector().record(h._ref_t)

vvecA = h.Vector().record(somaA(0.5)._ref_v)
mvecA = h.Vector().record(mgate.nodes(somaA(0.5))[0]._ref_value)
nvecA = h.Vector().record(ngate.nodes(somaA(0.5))[0]._ref_value)
예제 #28
0
파일: de3.py 프로젝트: shhong/ocnc_model
##-----------------------------------------------------------------##
##----Add a bit of the Ornstein-Uhlenbeck noise (colored noise)----##
for sec in h.allsec():
    sec.insert("OU")
    sec.tau_OU = 20  #seems to reduce noise if increase
    sec.D_OU = 0.025

##-----------------------------------------------------------------##
##------------------------Recording conditions---------------------##
soma.push()  #record voltage at the soma

#h.celsius = 22 #typical lab temperature
h.tstop = 5000
h.xopen("de3_1.ses")

ic = h.IClamp(0.5,
              sec=axthick)  #current injection to axthick w/ electrode if want
ic.delay = 100
ic.dur = 25000
ic.amp = 0.5  #current amplitude

##-----------------------------------------------------------------##
##--------------------US-activated channel-------------------------##
soma.insert("uschan")
soma.onset_uschan = 5000  #US time on
soma.dur_uschan = 10000  #duration of US stimulus
soma.tact_uschan = 20000  # tau activation US-activated channel

##--------------------------------------------------------------##


##----Local temperature fluctuation ----##
예제 #29
0
h.pt3dadd(10, 10, 15, 3, sec=dend3)
h.pt3dadd(15, 10, 15, 2, sec=dend3)
h.pt3dadd(5, 5, 5, 1, sec=dend3)
dend4 = h.Section()
h.pt3dadd(10, 10, 5, 3, sec=dend4)
h.pt3dadd(5, 10, 5, 4, sec=dend4)
h.pt3dadd(5, 6, 5, 5, sec=dend4)
dend3.connect(soma1, 0, 0)
dend4.connect(soma1, 1, 0)

#Display what happens when you drive a current through the neuron..

for sec in soma, dend1, dend2, soma1, dend3, dend4:
    sec.insert('hh')
# inject current in the pre - synaptic section
stim = h.IClamp(0.5, sec=soma)
stim.amp = 10.0
stim.delay = 5.0
stim.dur = 5.0
stim1 = h.IClamp(0.5, sec=soma1)
stim1.amp = 10.0
stim1.delay = 5.0
stim1.dur = 5.0

vec = {}
for var in 'v_pre ', 'v_post ', 't ':
    vec[var] = h.Vector()

# record the membrane potentials
vec['v_pre '].record(soma(0.5)._ref_v)
vec['v_post '].record(soma1(0.5)._ref_v)
예제 #30
0
# open library (channel distributions etc)
with open(specs[cell_type]['lib'], 'rb') as f:
    model_sets = pickle.load(f, encoding="latin1")

# simulate model(s)
OUT = {}
for cell_index in model_iterator:

    # initiate cell
    cell = build.MSN(params=specs[cell_type]['par'],
                     morphology=specs[cell_type]['morph'],
                     variables=model_sets[cell_index]['variables'])

    # set current injection
    rheobase = model_sets[cell_index]['rheobase']
    Istim = h.IClamp(0.5, sec=cell.soma)
    Istim.delay = 100
    Istim.dur = 1000
    Istim.amp = (rheobase) * 1e-3

    # record vectors
    tm = h.Vector()
    tm.record(h._ref_t)
    vm = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)

    # run simulation
    h.finitialize(-80)

    # run simulation
    while h.t < 1000: