Пример #1
0
    def runFor(self, time, early_test=None):
        from neuron import h
        h.cvode_active(self.config.cvode_active)

        if not hasattr(self, "time_flag"):
            raise Exception("self.time_flag must be set to the parameter passed into NeuronRunner call")

        self.time_flag.value = h.t

        h.tstop = h.t + time
        t = h.t
        while t < h.tstop and h.t < h.tstop:
            t += 1.0

            h.continuerun(t)

            if early_test is not None:
                # Notify sim is paused during test eval
                self.time_flag.value = -1

                t_np, v_np = self.get_tv()
                if early_test(t_np, v_np):
                    return (t_np, v_np)

            # Notify change in sim time
            self.time_flag.value = h.t

        # -1 indicates simulation stopped
        self.time_flag.value = -1

        # Get the waveform
        return self.get_tv()
Пример #2
0
def _common_config(fit_window_start, fit_window_end, up_data, down_data):
    h.v_init = 0
    h.tstop = 100
    h.cvode_active(1)

    v_rec = h.Vector()
    t_rec = h.Vector()
    v_rec.record(h.soma[0](0.5)._ref_v)
    t_rec.record(h._ref_t)

    mrf = h.MulRunFitter[0]
    gen0 = mrf.p.pf.generatorlist.object(0)
    gen0.toggle()
    fit0 = gen0.gen.fitnesslist.object(0)

    up_t = h.Vector(up_data[:, 0])
    up_v = h.Vector(up_data[:, 1])
    fit0.set_data(up_t, up_v)
    fit0.boundary.x[0] = fit_window_start
    fit0.boundary.x[1] = fit_window_end
    fit0.set_w()

    gen1 = mrf.p.pf.generatorlist.object(1)
    gen1.toggle()
    fit1 = gen1.gen.fitnesslist.object(0)

    down_t = h.Vector(down_data[:, 0])
    down_v = h.Vector(down_data[:, 1])
    fit1.set_data(down_t, down_v)
    fit1.boundary.x[0] = fit_window_start
    fit1.boundary.x[1] = fit_window_end
    fit1.set_w()

    return mrf
Пример #3
0
    def get_number_of_model_state_variables(self, h):
        print("Turning on CVODE to compute number of equations...")
        h.cvode_active(1)

        result = h.Vector()
        h.cvode.spike_stat(result)
        return int(result[0])
Пример #4
0
    def restore_state(self, state_file='state.bin', keep_events=False):
        from neuron import h
        ns = h.SaveState()
        sf = h.File(os.path.join(self.get_permanent_model_directory(), state_file))
        ns.fread(sf)

        h.stdinit()

        if keep_events:
            ns.restore(1)

            # Workaround - without the fixed step cycle, NEURON crashes with same error as in:
            # https://www.neuron.yale.edu/phpBB/viewtopic.php?f=2&t=3845&p=16542#p16542
            # Only happens when there is a vector.play added after a state restore
            # Running one cycle using the fixed integration method addresses the problem
            h.cvode_active(0)
            prev_dt = h.dt
            h.dt = 0.000001
            h.steprun()
            h.dt = prev_dt
            # END Workaround

        else:
            ns.restore()

        h.cvode_active(self.config.cvode_active)
Пример #5
0
def passive_fit_2(info, up_data, down_data):
    h.v_init = 0
    h.tstop = 100
    h.cvode_active(1)

    fit_start = 4.0025

    v_rec = h.Vector()
    t_rec = h.Vector()
    v_rec.record(h.soma[0](0.5)._ref_v)
    t_rec.record(h._ref_t)

    mrf = h.MulRunFitter[0]
    gen0 = mrf.p.pf.generatorlist.object(0)
    gen0.toggle()
    fit0 = gen0.gen.fitnesslist.object(0)

    up_t = h.Vector(up_data[:, 0])
    up_v = h.Vector(up_data[:, 1])
    fit0.set_data(up_t, up_v)
    fit0.boundary.x[0] = fit_start
    fit0.boundary.x[1] = info["limit"]
    fit0.set_w()

    gen1 = mrf.p.pf.generatorlist.object(1)
    gen1.toggle()
    fit1 = gen1.gen.fitnesslist.object(0)

    down_t = h.Vector(down_data[:, 0])
    down_v = h.Vector(down_data[:, 1])
    fit1.set_data(down_t, down_v)
    fit1.boundary.x[0] = fit_start
    fit1.boundary.x[1] = info["limit"]
    fit1.set_w()

    minerr = 1e12
    for i in range(3):
        # Need to re-initialize the internal MRF variables, not top-level proxies
        # for randomize() to work
        mrf.p.pf.parmlist.object(0).val = 1
        mrf.p.pf.parmlist.object(1).val = 10000
        mrf.randomize()
        mrf.prun()
        if mrf.opt.minerr < minerr:
            fit_Ri = h.Ri
            fit_Cm = h.Cm
            fit_Rm = h.Rm
            minerr = mrf.opt.minerr

    results = {
        "ra": fit_Ri,
        "cm": fit_Cm,
        "rm": fit_Rm,
        "err": minerr,
        "a1": h.somaaxon_area(),
        "a2": h.alldend_area(),
    }

    return results
Пример #6
0
    def set_abs_tolerance(self, abs_tol):
        from neuron import h

        # NRN will ignore this using cvode
        h.steps_per_ms = 1.0/self.config.collection_period_ms
        h.dt = self.config.dt

        h.cvode_active(self.config.cvode_active)
        h.cvode.condition_order(2)
        h.cvode.atol(abs_tol)
Пример #7
0
def run_simulation():
    from neuron import h, gui
    h.tstop = setting['simulation']['TSTOP']
    h.dt = setting['simulation']['DT']
    h.v_init = -65
    h.celsius = 35
    h.finitialize(-65)
    h.fcurrent()
    h.cvode_active(0)
    h.run()
    del h, gui
Пример #8
0
def test_fastimem():
    cells = [Cell(id, 10) for id in range(2)]
    # h.topology()
    cvode = h.CVode()
    ics = h.List("IClamp")
    syns = h.List("ExpSyn")
    cvode.use_fast_imem(1)
    h.finitialize(-65)
    run(1.0, ics, 1e-13)
    total_syn_g(syns)
    h.cvode_active(1)
    run(1.0, ics, 1e-12)
    cvode.use_fast_imem(0)
    h.cvode_active(0)
Пример #9
0
def simulate(v_init, mainlength, prelength=0, cvode=True):
    """

    :param h:
    :param v_init:
    :param prelength:
    :param mainlength:
    :param cvode:
    """
    h.cvode_active(1 if cvode else 0)
    h.finitialize(v_init)
    h.tstop = prelength + mainlength
    h.fadvance()
    h.continuerun(h.tstop)
Пример #10
0
def simulate(v_init, mainlength, prelength=0, use_cvode=True):
    """

    :param h:
    :param v_init:
    :param prelength:
    :param mainlength:
    :param cvode:
    """
    h.cvode_active(1 if use_cvode else 0)
    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)
    h.secondorder = 2
    h.finitialize(v_init)
    h.tstop = prelength + mainlength
    h.fadvance()
    h.continuerun(h.tstop)
Пример #11
0
def test():
    global s, h
    fitglobals.debugon()
    h.load_file('nrngui.hoc')
    from math import pi
    h('create soma')
    s = h.soma
    s.diam = 10
    s.L = 100 / pi / s.diam
    s.insert('pas')
    s.e_pas = 0
    s.g_pas = .5 * .001
    h.tstop = 10
    h.dt = 0.1
    h.v_init = 1
    h.load_file('pasfit.ses')
    h.cvode_active(1)
Пример #12
0
def fig6b(cell, voltage_graph, concentration_graph):
    """setup to run Fig 6B

    The model is the same as in Fig 3A except some of the sections are
    different lengths and the discretization is different.

    The cell receives a different stimulus and different time series are
    plotted. An additional graph plots sodium concentration as a function of
    position."""
    # differences to the morphology and discretization from Fig 3A
    cell.myelin[0].L = 51
    cell.myelin[1].L = 60
    cell.myelin[0].nseg = 255
    cell.myelin[1].nseg = 300
    cell.AIS.L = 48
    cell.AIS.nseg = 240

    h.cvode_active(True)

    # setup the graphs

    voltage_graph.view(0, -80, 50, 140, 528, 440, 549, 267.4)
    voltage_graph.addvar('soma(0.5).v', cell.soma(0.5)._ref_v)
    voltage_graph.addvar('AIS(0.5).v', cell.AIS(0.5)._ref_v, 2, 1)
    voltage_graph.addvar('node(0.5).v', cell.node(0.5)._ref_v, 4, 1)

    concentration_graph.view(-1, 4, 51, 0.58, 528, 870, 548.1, 238.6)
    concentration_graph.addvar('soma(0.5).nai', cell.soma(0.5)._ref_nai)
    concentration_graph.addvar('AIS(0.25).nai', cell.AIS(0.25)._ref_nai, 2, 1)
    concentration_graph.addvar('node(0.5).nai', cell.node(0.5)._ref_nai, 4, 1)

    # additional graph plotting sodium concentration along a path
    rvp = h.Graph(False)
    rvp.size(-40, 160, 4, 4.58)
    rvp.view(-40, 4, 200, 0.58, 534, 18, 544.5, 262)
    h.flush_list.append(rvp)
    rvp_ = h.RangeVarPlot("nai")
    rvp_.begin(cell.ApD(0))
    rvp_.end(cell.myelin[1](1))
    rvp.addobject(rvp_, 1, 1, 0.8, 0.9)

    # start time of current pulse
    cell.ic.delay = 10
    # default simulation length
    h.tstop = 50
Пример #13
0
def fig3a(cell, voltage_graph, concentration_graph):
    """setup to run Fig 3A"""
    h.cvode_active(True)

    # setup the graphs
    voltage_graph.view(0, -90, 3000, 150, 518, 27, 549, 267.4)
    voltage_graph.addvar('soma(0.5).v', cell.soma(0.5)._ref_v)

    concentration_graph.view(0, 4, 3000, 0.4, 517, 457, 548.1, 238.6)
    concentration_graph.addvar('soma(0.5).nai', cell.soma(0.5)._ref_nai)
    concentration_graph.addvar('AIS(0.4).nai', cell.AIS(0.4)._ref_nai, 2, 1)
    concentration_graph.addvar('myelin[0](0.2).nai', cell.myelin[0](0.2)._ref_nai, 3, 1)
    concentration_graph.addvar('AIS(0.8).nai', cell.AIS(0.8)._ref_nai, 4, 1)

    # start time of current pulse
    cell.ic.delay = 1000
    # default simulation length
    h.tstop = 3000
Пример #14
0
    def run_from_steady_state(self, tstop):
        self._update_current_sources(tstop)
        self._pre_run()
        self.parallel_context.set_maxstep(self.default_maxstep)
        self.tstop = tstop

        h.stdinit()

        ns = h.SaveState()
        sf = h.File('steady_state.bin')
        ns.fread(sf)
        #print("Time before restore = %g ms" % h.t)
        ns.restore(0)

        h.cvode_active(0)
        #print("Time after restore = %g ms" % h.t)
        #logger.info("Running the simulation until %g ms" % tstop)
        if self.tstop > self.t:
            self.parallel_context.psolve(self.tstop)
Пример #15
0
    def get_sim_params(self):
        params = {}

        params["t"] = h.t
        params["tstop"] = h.tstop
        params["dt"] = h.dt
        params["atol"] = h.cvode.atol()
        params["celsius"] = h.celsius
        params["cvode"] = str(h.cvode_active())

        return params
Пример #16
0
def simple():
    soma = h.Section()
    soma.insert('pas')
    soma.e_pas = -65
    #soma.g_pas = 1./200e3
    synapse = syn.AMPANMDASynapse(soma, 0.5, 0, 10000)
    synapse.set_presynaptic_spike_times([100])
    h.nmdafactor_AmpaNmda = 0
    rec = {}
    for lbl in 't','vsoma','vapical','vbasal','gampa','gnmda','iampa','inmda':
        rec[lbl] = h.Vector()
    rec['t'].record(h._ref_t)
    rec['vsoma'].record(soma(0.5)._ref_v)
    rec['gampa'].record(synapse.syn._ref_gampa)
    rec['gnmda'].record(synapse.syn._ref_gnmda)
    rec['iampa'].record(synapse.syn._ref_iampa)
    rec['inmda'].record(synapse.syn._ref_inmda)        
    h.load_file('stdrun.hoc')
    h.celsius = 35
    h.cvode_active(1)
    h.cvode.maxstep(10)
    h.tstop = 500
    h.finitialize(soma.e_pas)
    h.run()
    p.subplot(3,1,1)
    p.plot(rec['t'],rec['vsoma'],'k',label='Soma')
    p.subplot(3,1,2)
    p.plot(rec['t'],np.array(rec['gampa'])*1e3,'k',label='AMPA')
    p.plot(rec['t'],np.array(rec['gnmda'])*1e3,'r',label='NMDA')
    p.legend(loc='best')
    p.ylabel('Conductance (nS)')
    p.subplot(3,1,3)
    p.plot(rec['t'],np.array(rec['iampa']),'k',label='AMPA')
    p.plot(rec['t'],np.array(rec['inmda']),'r',label='NMDA')
    p.legend(loc='best')
    p.xlabel('Time (ms)')
    p.ylabel('Current (nA)')
    p.show()
Пример #17
0
def test():
    from L5_pyramidal import L5Pyr
    cell = L5Pyr()

    h.load_file("stdgui.hoc")
    h.cvode_active(1)

    ns = h.NetStim()
    ns.number = 10
    ns.start = 100
    ns.interval = 50.0

    nc = h.NetCon(ns, cell.apicaltuft_ampa)
    nc.weight[0] = 0.001

    h.tstop = 2000.0

    elec = LFPElectrode([0, 100.0, 100.0], pc=h.ParallelContext())
    elec.setup()
    elec.LFPinit()
    h.run()
    elec.lfp_final()
    ion()
    plot(elec.lfp_t, elec.lfp_v)
Пример #18
0
    def play(self, fileroot='cell', show_colorbar=True, show_title=False):
        ''' Step through cell response over time '''
        dt = self.play_dt
        tstop = self.play_tstop
        nrn.init()
        nrn.cvode_active(0)
        img_counter=0
        f = mlab.gcf()
        if show_colorbar: mlab.colorbar(self.mlab_cell)
        nrn.initPlot()
        nrn.init()
        nrn.initPlot()
        nrn.init()
        for x in xrange(0, int(tstop/dt)):
            timestamp = "TIME: %.1f" % (x*dt)
            print timestamp
            if show_title:
                try:
                    ftitle.text = timestamp
                except:
                    ftitle = mlab.title(timestamp)
            nrn.continuerun(x*dt)

            dataset = self.mlab_cell.mlab_source.dataset
            v = array(self.calculate_voltage())
            dataset.point_data.remove_array('data')
            array_id = dataset.point_data.add_array(v.T.ravel())
            dataset.point_data.get_array(array_id).name = 'data'
            dataset.point_data.update()
            self.mlab_cell.update_data()
            self.mlab_cell.update_pipeline()

            if self.save_img:
                f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter))

            img_counter += 1
Пример #19
0
def test_ste():

    m1 = model()
    # one state ste with two self transitions
    var = m1["s"](0.5)._ref_v
    thresh1 = h.ref(-50)
    thresh2 = h.ref(-10)
    result = []
    ste = h.StateTransitionEvent(1)
    ste.transition(0, 0, var, thresh1, (act, (1, m1, thresh1, result)))
    ste.transition(0, 0, var, thresh2, (act, (2, m1, thresh2, result)))
    fih = h.FInitializeHandler((on_finit, (ste, result)))

    run(5)
    print("final v=%g" % m1["s"](0.5).v)
    chk_result(2, result, m1)

    h.cvode_active(1)
    run(20)
    chk_result(2, result, m1)

    h.cvode_active(1)
    h.cvode.condition_order(2)
    run(5)
    chk_result(2, result, m1)

    h.cvode.condition_order(1)
    h.cvode_active(0)

    # ste associated with point process
    del fih, ste
    ste = h.StateTransitionEvent(2, m1["ic"])
    fih = h.FInitializeHandler((on_finit, (ste, result)))
    run(5)

    # transition with hoc callback
    h("""proc foo() { printf("foo called at t=%g\\n", t) }""")
    thresh3 = h.ref(-30)
    ste.transition(0, 0, var, thresh3, "foo()")
    run(5)

    # transition with hoc callback in hoc object
    h("""
begintemplate FooSTEtest
objref this
proc foo() { printf("foo in %s called at t=%g\\n", this, t) }
endtemplate FooSTEtest
""")
    thresh4 = h.ref(-20)
    obj = h.FooSTEtest()
    ste.transition(0, 0, var, thresh4, "foo()", obj)
    run(5)

    del ste, fih
    assert h.List("StateTransitionEvent").count() == 0
    assert h.List("FInitializeHandler").count() == 0
    name = name[:-3]
h.load_file("stdrun.hoc")

dend1 = h.Section()
dend1.diam = 2
dend1.nseg = 101
dend1.L = 50

dend2 = h.Section()
dend2.diam = 2
dend2.nseg = 101
dend2.L = 50
dend2.connect(dend1)

diff_constant = 1
h.cvode_active(True)
r = rxd.Region(h.allsec(), dx=0.25)

rxd.set_solve_type([dend1], dimension=3)

ca = rxd.Species(
    r,
    d=diff_constant,
    atolscale=0.1,
    initial=lambda node: 1 if (0.8 < node.x and node.segment in dend1) or
    (node.x < 0.2 and node.segment in dend2) else 0,
)
bistable_reaction = rxd.Rate(ca, -ca * (1 - ca) * (0.01 - ca))
h.finitialize()

for i in range(2):
Пример #21
0
def iclamp_adaptive(cell, sec, i_inj, v_init, tstop, dt, celsius=35, pos_i=0.5, pos_v=0.5, atol=1e-2, continuous=True,
                    discontinuities=None, interpolate=True):
    """
    Runs a NEURON simulation of the cell for the given parameters using adaptive integration.

    :param sec: List with 1st entry the name of the section and 2nd entry the index (or None in case of soma)
    :type sec: list[str, int]
    :param i_inj: Amplitude of the injected current for all times t.
    :type i_inj: array_like
    :param v_init: Initial membrane potential of the cell.
    :type v_init: float
    :param tstop: Duration of a whole run.
    :type tstop: float
    :param dt: Time step.
    :type dt: float
    :param celsius: Temperature during the simulation (affects ion channel kinetics).
    :type celsius: float
    :param pos_i: Position of the IClamp on the Section (number between 0 and 1).
    :type pos_i: float
    :param pos_v: Position of the recording electrode on the Section (number between 0 and 1).
    :type pos_v: float
    :param atol: Absolute tolerance of the integration.
    :type atol: float
    :param: continuous: If true, linear interpolation is used to define the values between time points of i_inj.
    :type: continuous: bool
    :param: discontinuities: Indices where jumps in i_inj occur. This will insert a new point before each discontinuity
    in t with the time at the discontinuity and in i_inj with the value from i_inj before the discontinuity.
    :type discontinuities: array[int]
    :param interpolate: If true, the recorded values for v and t will be linearly interpolated to match dt.
    :type interpolate: bool
    :return: Membrane potential of the cell and time recorded at each time step.
    :rtype: tuple of three ndarrays
    """
    # turn on adaptive integration and set tolerance (only works when stdrun.hoc already loaded)
    h.cvode_active(1)
    h.cvode.atol(1e-8)

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

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

    # adapt i_vec to cope with discontinuities
    if discontinuities is not None:
        discontinuities = np.sort(discontinuities)
        discontinuities = discontinuities + np.arange(len(discontinuities))  # index shifts by the amount of already inserted values
        for discontinuity in discontinuities:
            i_inj = np.insert(i_inj, discontinuity, i_inj[discontinuity-1])
            t = np.insert(t, discontinuity, t[discontinuity])

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

    # record the membrane potential
    v_rec = section.record('v', pos_v)
    t_rec = h.Vector()
    t_rec.record(h._ref_t)
    i_rec = h.Vector()
    i_rec.record(stim._ref_amp)

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

    v_rec = np.array(v_rec)
    t_rec = np.array(t_rec)
    #i_rec = np.array(i_rec)

    if interpolate:
        #i_rec = np.interp(t, t_rec, i_rec)
        v_rec = np.interp(t, t_rec, v_rec)
        t_rec = np.interp(t, t_rec, t_rec)

        t_rec, unique_indices = np.unique(t_rec, return_index=True)  # remove double values (from discontinuities)
        v_rec = v_rec[unique_indices]  # second value is the right one
        #i_rec = i_rec[unique_indices]  # second value is the right one

    return v_rec, t_rec #  , i_rec
Пример #22
0
def run_step_full(amplitude=0.1,passive=True):
    parameters = {'swc_filename': '../../SWCs/FINAL/thorny/DH070813-.Edit.scaled.swc',
                  'proximal_limit': 35., 'scaling': 1,
                  'soma': {'Cm': 1., 'Ra': 100., 'El': -70., 'Rm': 20e3},
                  'proximal': {'Ra': 100., 'El': -70.},
                  'distal': {'Ra': 100., 'El': -70.},
                  'basal': {'Ra': 100., 'El': -70.}}
    # the passive properties of the axon are the same as the soma
    parameters['axon'] = parameters['soma'].copy()

    cell = SWCNeuron(parameters,with_axon=True,convert_to_3pt_soma=True)
    if DEBUG:
        for i,sec in enumerate(cell.sections):
            print('[%03d] %11s: L = %5.1f um, nseg = %2d, L/nseg = %5.1f um.' % \
                  (i+1,sec.name(),sec.L,sec.nseg,sec.L/sec.nseg))

    stim = h.IClamp(cell.soma[0](0.5))
    stim.amp = amplitude
    stim.dur = 1000
    stim.delay = 250

    # the recorders
    rec = {'t': h.Vector()}
    rec['t'].record(h._ref_t)
    for sec in cell.sections:
        for seg in sec:
            k = '%s_%.3f' % (sec.name(),seg.x)
            rec[k] = h.Vector()
            rec[k].record(seg._ref_v)

    h.load_file('stdrun.hoc')

    # run the simulation
    h.cvode_active(1)
    h.tstop = stim.dur + 2*stim.delay
    h.t = 0
    h.v_init = -70
    h.run()

    if 'DH070813' in parameters['swc_filename']:
        k = 'apical_6923_0.500'
        coeff = 60.
        min_v = 65.5
    elif 'DH070313' in parameters['swc_filename']:
        k = 'apical_5206_0.900'
        coeff = 60.
        min_v = 62.

    nseg = 0
    x = []
    y = []
    v = []
    import matplotlib.pyplot as plt
    plt.subplot(121)
    for sec in cell.sections:
        nseg += sec.nseg
        for seg in sec:
            k = '%s_%.3f' % (sec.name(),seg.x)
            v.append(np.max(np.array(rec[k])))
            n = np.floor(h.n3d(sec=sec)*seg.x)
            x.append(h.x3d(n,sec=sec))
            y.append(h.y3d(n,sec=sec))
            z = (255-coeff*(min_v+v[-1]))/255
            plt.plot(x[-1],y[-1],'.',color=[1-z,1-z,z])

    print('There are %d sections for a total of %d segments.' % (len(cell.sections),nseg))

    plt.subplot(122)
    plt.plot(rec['t'],rec[k],'r')
    plt.plot(rec['t'],rec['soma_1_0.500'],'k')
    plt.show()
Пример #23
0
        elif method in (8,9):
            args = (pc.dt(tid), pc.t(tid), pd1_array, pd2_array)
        for c in call:
            if c[method] is not None:
                c[method](*args)
  except:
    traceback.print_exc()
    rval = -1
  return rval

_callback = nonvint_block_prototype(nonvint_block)
set_nonvint_block(_callback)

if __name__ == '__main__':
  exec(test) # see above string

  s = h.Section()
  print "fixed step finitialize"
  h.finitialize(0)
  print "fixed step fadvance"
  h.fadvance()

  h.load_file('stdgui.hoc')
  print "cvode active"
  h.cvode_active(1)
  print "cvode step finitialize"
  h.finitialize(0)
  print "cvode fadvance"
  h.fadvance()

Пример #24
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)
Пример #25
0
def steps(step_number, parameters):

      # instantiate the class
    cell = GrCmono(parameters)

    # no table are in use from the mod files
    h.usetable_GrG_Na = 0
    h.usetable_GrC_pNa = 0
    h.usetable_GrC_CaHVA = 0
    h.usetable_GrG_KV = 0
    h.usetable_GrC_KA = 0
    h.usetable_GrC_Kir = 0
    h.usetable_GrC_KCa = 0
    h.usetable_GrG_KM = 0

    # load graph for the membrane voltage in mV
    # h('load_file("vm.ses")')
    # h.nrncontrolmenu()
    # Stimulation data. Del = delay in ms, dur = duration in ms, amp =
    # amplitude in nA
    stimdata = dict()

    if step_number == 0:
        stimdata['stim0del'] = 100
        stimdata['stim0dur'] = 500
        stimdata['stim0amp'] = 0.010
    elif step_number == 1:
        stimdata['stim1del'] = 100
        stimdata['stim1dur'] = 500
        stimdata['stim1amp'] = 0.016
    elif step_number == 2:
        stimdata['stim2del'] = 100
        stimdata['stim2dur'] = 500
        stimdata['stim2amp'] = 0.022

    # totale time of the simulation
    stimdata['timeglobal'] = 700

    # integration step
    h.dt = 0.025

    h.cvode_active(1)
    # temperature
    h.celsius = 30
    # time at which the simulation have to end
    h.tstop = stimdata['timeglobal']
    # initial voltage
    h.v_init = -80

    if step_number == 0:
        # actual current injections, one for each current step.
        stim = [h.IClamp(0.5, sec=cell.soma)]

        stim[0].delay = stimdata['stim0del']
        stim[0].dur = stimdata['stim0dur']
        stim[0].amp = stimdata['stim0amp']
    elif step_number == 1:
        stim2 = [h.IClamp(0.5, sec=cell.soma)]

        stim2[0].delay = stimdata['stim1del']
        stim2[0].dur = stimdata['stim1dur']
        stim2[0].amp = stimdata['stim1amp']
    elif step_number == 2:
        stim3 = [h.IClamp(0.5, sec=cell.soma)]

        stim3[0].delay = stimdata['stim2del']
        stim3[0].dur = stimdata['stim2dur']
        stim3[0].amp = stimdata['stim2amp']

        # Code to record everything.

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

    vm = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)

    # function to initialize the simulation.
    def initialize():
        h.finitialize()
        h.run()

    initialize()

    #np.savetxt('trace_%d.txt' % step_number, np.column_stack((np.array(time),np.array(vm))), delimiter = ' ')

    return np.array(time), np.array(vm)
Пример #26
0
def network_func(arr):
    """ Evaluates the simulation of the pacemaker nucleus
                with the parameters defined in LoParameters and returns
                the frequency of oscillations.

                @LoParameters: [EK, gKp, gKr]
                @returns: frequency of oscillations either 0 or freq > 0
                """
    LoParameters = arr[0]
    results_index = arr[1]
    start = time.time()
    # NEURON utilities
    h.cvode_active(1)
    h.finitialize(-65)
    h.celsius = 27
    # Biophysical parameters
    ek = LoParameters[0]
    ena = 50
    # Pacemaker cell soma specific
    ps_EL = - 70
    ps_gNa = 1.0
    ps_gK = LoParameters[1]
    ps_gL = 0.0001
    J = 30
    # Pacemaker cell axon specific
    pa_EL = - 70
    pa_gNa = 0.5
    pa_gK = 0.02
    pa_gL = 0.001
    M = 45
    # Relay cell soma specific
    rs_EL = -70
    rs_gNa = 0.75
    rs_gK = LoParameters[2]
    rs_gL = 0.0003
    K = 60
    # Relay cell axon specific
    ra_EL = -70
    ra_gNa = 0.5
    ra_gK = 0.05
    ra_gL = 0.001
    N = 40
    # Synapse Parameters
    conduct_rng = [0.5, 10]  # nS
    # Topology Parameters
    n_pacemakers = 87
    n_relays = 20
    n_p2p_projections = 6
    n_p2r_projections = 7
    # Duration Parameters
    T_STOP = 100  # (ms)
    # Object storage
    pacemaker_cells = []
    relay_cells = []
    pace_network_graph = pnm.Graph()

    # Build Synapse Adjacency List and initialize cell objects.
    for i in range(n_pacemakers + n_relays):
        # num vertices = num cells in network
        pace_network_graph.add_vertex(i)
        if i < n_pacemakers:  # LOOKING AT A PACEMAKER CELL
            p_p_projections = rdm.sample(range(0, n_pacemakers),
                                         n_p2p_projections)
            p_r_projections = rdm.sample(range(n_pacemakers,
                                               n_relays + n_pacemakers),
                                         n_p2r_projections)

            while i in p_p_projections:  # DON'T WANT TO SYNAPSE ONTO SELF
                p_p_projections = rdm.sample(range(0, n_pacemakers),
                                             n_p2p_projections)

            # Now have 2 unique lists of all cells that cell #i synapses to.
            # Add cell i's projections to graph
            all_projections = p_p_projections + p_r_projections
            for proj in all_projections:
                pace_network_graph.add_edge([i, proj])
            pacemaker_cells.append(
                pnm.PacemakerCell([ek, ena, ps_EL, ps_gNa, ps_gK, ps_gL, J],
                                  [ek, ena, pa_EL, pa_gNa, pa_gK, pa_gL, M],
                                  i))

        else:  # LOOKING AT A RELAY CELL
            # Relay cells don't synapse to anything.
            relay_cells.append(
                pnm.RelayCell([ek, ena, rs_EL, rs_gNa, rs_gK, rs_gL, K],
                              [ek, ena, ra_EL, ra_gNa, ra_gK, ra_gL, N],
                              i))
    all_cells = pacemaker_cells + relay_cells
    """
    Orient objects in 3D-space with polar coordinates (position, rotation)
    where the center of the coordinate system corresponds to
    the center of the pacemaker nucleus cell network.

    Default neuronal orientation before repositioning and rotation
    y    z         y
    ^  ^>          ^
    | /            | _______
    |/             |(       )_______________________________________
    |------>  (0,0)+(-So>ma-)______________Axon_____________________----> x
    |              |(_______)
    |              |
    V              v
    """
    t_pace = pacemaker_cells[0]
    t_relay = relay_cells[0]
    len_pace = t_pace.give_len("soma") + t_pace.give_len("axon")
    len_relay = t_relay.give_len("soma") + t_relay.give_len("axon")
    dt_pace = 2 * pi / n_pacemakers
    dt_relay = 2 * pi / n_relays
    # First for relay cells (position, rotation)
    for relay, cell in enumerate(relay_cells):
        cell.set_position((len_relay + 10) * cos(pi + (dt_relay * relay)),
                          (len_relay + 10) * sin(pi + (dt_relay * relay)),
                          0)
        cell.rotateZ(relay * (2 * pi / n_relays))
    # Second for pacemaker cells (position, rotation)
    for pace, cell in enumerate(pacemaker_cells):
        cell.set_position(
            (len_pace + len_relay + 10.001) * cos(pi + (dt_pace * pace)),
            (len_pace + len_relay + 10.001) * sin(pi + (dt_pace * pace)),
            0)
        cell.rotateZ(pace * (2 * pi / n_pacemakers))
    # For dict entries, create a Synapse b/t the key cell & each payload cell.
    for key in pace_network_graph.vertices():
        pre_syn_cell = all_cells[key]
        for ident in pace_network_graph.edges_of_vertex(key):
            post_syn_cell = all_cells[ident]
            pre_syn_cell.add_synapse(post_syn_cell, conduct_rng)

    # Begin simulation of model
    #print(f"Starting simulation {list(LoParameters)} on pc={pc.id()}")
    h.tstop = T_STOP
    h.run()

    # Simulation analysis
    time_spikes_pace_somas = []
    time_spikes_pace_axons = []
    time_spikes_relay_somas = []
    time_spikes_relay_axons = []
    soma_frequencies = []
    axon_frequencies = []
    # Determine if oscillating spontaneously
    last_ps_t = None
    last_rs_t = None
    for i, cell in enumerate(all_cells):
        soma_v, axon_v, t_v = cell.give_spikes()  # time vectors
        soma_f = len(list(soma_v)) / (T_STOP * 0.001)
        axon_f = len(list(axon_v)) / (T_STOP * 0.001)
        if i < 87:
            time_spikes_pace_somas.append(len(list(soma_v)))
            time_spikes_pace_axons.append(len(list(axon_v)))
            if time_spikes_pace_somas[-1] > 0:
                last_ps_t = list(soma_v)[-1]
        elif i < 107:
            time_spikes_relay_somas.append(len(list(soma_v)))
            time_spikes_relay_axons.append(len(list(axon_v)))
            if time_spikes_relay_somas[-1] > 0:
                last_rs_t = list(soma_v)[-1]
        soma_frequencies.append(soma_f)
        axon_frequencies.append(axon_f)

    # Store raw cellular spike data for this simulation.
    try:
        frequencies = [mode(soma_frequencies[0:87]),
                       mode(axon_frequencies[0:87]),
                       mode(soma_frequencies[87:]),
                       mode(axon_frequencies[87:])]
    except StatisticsError:
        frequencies = None
    if frequencies is not None \
            and last_ps_t is not None \
            and last_rs_t is not None \
            and (len(set(frequencies)) <=2) \
            and (np.isclose(frequencies[0], frequencies[3], rtol=0.15)) \
            and (np.isclose(frequencies[0], frequencies[2], rtol=0.15)) \
            and (np.isclose(frequencies[0], frequencies[1], rtol=0.15)) \
            and (frequencies[0] > 40) \
            and (frequencies[2] > 40) \
            and ((T_STOP - last_ps_t) < (T_STOP / 3 + 7)) \
            and ((T_STOP - last_rs_t) < (T_STOP / 3 + 7)):
        try:
            freq = mode(soma_frequencies)
            """pnm.raster(
                f"/Users/daniel/Desktop/Development/PacemakerNucleus/laptop"
                f"/sims",
                LoParameters, all_cells, frequencies)"""
        except StatisticsError:
            freq = -1e-15
    #       print("stats error")
    else:
        freq = -1e-15
    #print(freq)
    """pnm.raster(f"/scratch/hartman.da/scratch_3D_resim_code/rasters",
               LoParameters, all_cells, [p_s_f, p_a_f, r_s_f, r_a_f])
    pnm.cellular_potentials(f"/scratch/hartman.da/scratch_3D_resim_code"
                            f"/mem_potentials", LoParameters, all_cells,
                            [p_s_f, r_s_f])"""
    end = time.time()
    """simulation = Sim.Sim(LoParameters, freq, [], end - start, results_index)
    with open(f"{pickled_sims_dir}/Sim_{list(LoParameters)}.pkl", "wb") as \
            sim_file:
        pkl.dump(simulation, sim_file)"""
    print(end-start)
    return freq, results_index
Пример #27
0
def steps(step_number, parameters):

    # instantiate the class
    cell = GrCmono(parameters)

    # no table are in use from the mod files
    h.usetable_GrG_Na = 0
    h.usetable_GrC_pNa = 0
    h.usetable_GrC_CaHVA = 0
    h.usetable_GrG_KV = 0
    h.usetable_GrC_KA = 0
    h.usetable_GrC_Kir = 0
    h.usetable_GrC_KCa = 0
    h.usetable_GrG_KM = 0

    # load graph for the membrane voltage in mV
    # h('load_file("vm.ses")')
    # h.nrncontrolmenu()
    # Stimulation data. Del = delay in ms, dur = duration in ms, amp =
    # amplitude in nA
    stimdata = dict()

    if step_number == 0:
        stimdata['stim0del'] = 100
        stimdata['stim0dur'] = 500
        stimdata['stim0amp'] = 0.010
    elif step_number == 1:
        stimdata['stim1del'] = 100
        stimdata['stim1dur'] = 500
        stimdata['stim1amp'] = 0.016
    elif step_number == 2:
        stimdata['stim2del'] = 100
        stimdata['stim2dur'] = 500
        stimdata['stim2amp'] = 0.022

    # totale time of the simulation
    stimdata['timeglobal'] = 700

    # integration step
    h.dt = 0.025

    h.cvode_active(1)
    # temperature
    h.celsius = 30
    # time at which the simulation have to end
    h.tstop = stimdata['timeglobal']
    # initial voltage
    h.v_init = -80

    if step_number == 0:
        # actual current injections, one for each current step.
        stim = [h.IClamp(0.5, sec=cell.soma)]

        stim[0].delay = stimdata['stim0del']
        stim[0].dur = stimdata['stim0dur']
        stim[0].amp = stimdata['stim0amp']
    elif step_number == 1:
        stim2 = [h.IClamp(0.5, sec=cell.soma)]

        stim2[0].delay = stimdata['stim1del']
        stim2[0].dur = stimdata['stim1dur']
        stim2[0].amp = stimdata['stim1amp']
    elif step_number == 2:
        stim3 = [h.IClamp(0.5, sec=cell.soma)]

        stim3[0].delay = stimdata['stim2del']
        stim3[0].dur = stimdata['stim2dur']
        stim3[0].amp = stimdata['stim2amp']

        # Code to record everything.

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

    vm = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)

    # function to initialize the simulation.
    def initialize():
        h.finitialize()
        h.run()

    initialize()

    #np.savetxt('trace_%d.txt' % step_number, np.column_stack((np.array(time),np.array(vm))), delimiter = ' ')

    return np.array(time), np.array(vm)
def model(Duration,Freq,DFreq,Amps,YY):
    fs = 1000*50*4  # Hz, sampling rate

    h.cvode_active(0)  # turn off variable time step
    h.steps_per_ms = fs*1e-3  # steps per ms for NEURON simulation
    h.dt = 1/(fs*1e-3)  # ms, sample spacing
    h.celsius = h.celsius  # temperature at which to run simulation
    h.v_init = -80.  # mV, initial voltage to begin simulations
    ZZ=0
    MyTraj = np.array([[-50e-3,YY,ZZ], [+51e-3,YY,ZZ]])
    
    MyPath = os.getcwd() + '/'
    CELL_DIR = MyPath+'cells/'
    CELL_FILE_NAME = 'NewMRGaxon_for_Python.hoc'
    MyD = 8.7
    MyCell = MRG(axon_trajectory=MyTraj, fiberD=MyD,
                CELL_FILE_NAME=CELL_FILE_NAME, CELL_DIR=CELL_DIR)

    I = 1.  # current source amplitude in A

    # find xyz coordinates of center of each axon compartment
    nrn_xyz = list()
    for sec in MyCell.get_secs():
        nrn_xyz.append(MyCell.center_3Dcoords(sec))

    nrn_xyz = np.array(nrn_xyz)*1e-6  # m, convert from um to m

    sigmaXX=0.6
    sigmaYY=0.083
    sigmaZZ=0.083

    VS1=Voltages(nrn_xyz[:,0],nrn_xyz[:,1],nrn_xyz[:,2],-5e-3,+5e-3,+0e-3,+I,sigmaXX,sigmaYY,sigmaZZ,'V')['V']
    VS2=Voltages(nrn_xyz[:,0],nrn_xyz[:,1],nrn_xyz[:,2],+5e-3,+5e-3,+0e-3,-I,sigmaXX,sigmaYY,sigmaZZ,'V')['V']
    VS3=Voltages(nrn_xyz[:,0],nrn_xyz[:,1],nrn_xyz[:,2],-5e-3,-5e-3,+0e-3,+I,sigmaXX,sigmaYY,sigmaZZ,'V')['V']
    VS4=Voltages(nrn_xyz[:,0],nrn_xyz[:,1],nrn_xyz[:,2],+5e-3,-5e-3,+0e-3,-I,sigmaXX,sigmaYY,sigmaZZ,'V')['V']

    V1 = VS1+VS2  # voltage of first pair
    V2 = VS3+VS4  # voltage of second pair

    recordingDict = dict()
    location = 0.5
    variable = {'v'}
    iSec=0
    # MyPoints = list()
    for Sec in MyCell.get_secs():
        Sec.rx1_xtra=V1[iSec]
        Sec.rx2_xtra=V2[iSec]
        iSec=iSec+1
        if ("node" in Sec.name()):
            for vars in variable:
                rec_dict(recordingDict, Sec, location, vars)

    MyCell.record(recordingDict)

    h.load_file("stdrun.hoc")
    h.init()
    h.finitialize(h.v_init)
    h.fcurrent()

    h.tstop = Duration
    Times=np.arange(0,h.tstop+h.dt,h.dt)
    Sim1=Amps*np.sin(2*np.pi*Freq/1000.0*Times)
    Sim2=Amps*np.sin(2*np.pi*(Freq+DFreq)/1000.0*Times)

    t = h.Vector(Times)
    Stim1=h.Vector(Sim1*1e-3)
    Stim2=h.Vector(Sim2*1e-3)
    Stim1.play(h._ref_is1_xtra, t, 0)
    Stim2.play(h._ref_is2_xtra, t, 0)

    h.run()
    return MyCell
Пример #29
0
def run(tstop):
  h.cvode_active(1)
  h.cvode.atol(1e-7)
  h.tstop = tstop
  h.run()
  h.cvode_active(0)
Пример #30
0
Implementation by: Salvador Dura-Bernal, Cliff Kerr, Bill Lytton 
([email protected]; [email protected]; [email protected])
"""

# adapted from /u/billl/nrniv/sync/izh.hoc
import os, sys, collections
import numpy as np
from neuron import h, gui
h.load_file('stdrun.hoc')
import izhi2007Figs as iz07fig
import izhi2007Wrapper as izh07
import __main__
py = __main__
h.tstop=500
h.cvode_active(0)
h.dt=0.1
izh, cell07 = None, None # must be declared here since needs to be imported elsewhere


type2003 = collections.OrderedDict([
  #                                 a         b     c         d    vviv      tstop
 ('regular spiking (RS)'        , (0.02   ,  0.2 , -65.0 ,   8.0 , -63.0 ,   150.0)) ,
 ('intrinsically bursting (IB)' , (0.02   ,  0.2 , -55.0 ,   4.0 , -70.0 ,   150.0)) ,
 ('chattering (CH)'             , (0.02   ,  0.2 , -50.0 ,   2.0 , -70.0 ,   150.0)) ,
 ('fast spiking (FS)'           , (0.1    ,  0.2 , -65.0 ,   2.0 , -70.0 ,   150.0)) ,
 ('thalamo-cortical (TC)'       , (0.02   , 0.25,  -65.0 , 0.05 , -63.0 ,   150.0)) ,
 ('thalamo-cortical burst (TC)' , (0.02   , 0.25,  -65.0 , 0.05 , -87.0 ,   150.0)) ,
 ('resonator (RZ)'              , (0.1   ,  0.26 , -65.0 ,   2.0 , -70.0 ,   100.0)) ,
 ('low-threshold spiking (LTS)' , (0.02   , 0.25 , -65.0 ,   2.0 , -63.0 ,   250.0))])
Пример #31
0
 def set_sim_params(self, params):
     h.tstop = params["tstop"]
     h.dt = params["dt"]
     h.cvode.atol(params["atol"])
     h.celsius = params["celsius"]
     h.cvode_active(int(params["cvode"]))
Пример #32
0
def run_current_steps_protocol(cell, amplitudes, ttran, tstep, dt=0.025, temperature=37., use_cvode=False):
    h.load_file('stdrun.hoc')

    print(timestamp() + '>> Inserting the stimulus...')
    stim = h.IClamp(cell.soma[0](0.5))
    stim.dur = tstep
    stim.delay = ttran

    print(timestamp() + '>> Setting up the recorders...')
    rec = {}
    for lbl in 't','vsoma','spikes':
        rec[lbl] = h.Vector()
    rec['t'].record(h._ref_t)
    rec['vsoma'].record(cell.soma[0](0.5)._ref_v)
    apc = h.APCount(cell.soma[0](0.5))
    apc.record(rec['spikes'])

    h.celsius = temperature
    h.dt = dt

    if use_cvode:
        h.tstop = stim.delay + stim.dur + 500
        h.cvode_active(1)
        h.cvode.atol(1e-6)
        h.cvode.rtol(1e-6)
        h.cvode.maxstep(dt)
    else:
        h.tstop = stim.delay - 20
        print(timestamp() + '>> Evolving the model until %g ms...' % h.tstop)
        sys.stdout.flush()
        h.run()
        print(timestamp() + '>> Saving the state...')
        ss = h.SaveState()
        ss.save()

    t = []
    V = []
    spike_times = []

    for i,amp in enumerate(amplitudes):    
        sys.stdout.write('\r' + timestamp() + '>> Trial [%02d/%02d] ' % (i+1,len(amplitudes)))
        sys.stdout.flush()
        if not use_cvode:
            ss.restore()
        stim.amp = amp
        apc.n = 0
        rec['t'].resize(0)
        rec['vsoma'].resize(0)
        rec['spikes'].resize(0)
        if use_cvode:
            h.t = 0
            h.run()
        else:
            h.continuerun(stim.delay + stim.dur + 500.)
        t.append(np.array(rec['t']))
        V.append(np.array(rec['vsoma']))
        spike_times.append(np.array(rec['spikes']))
    sys.stdout.write('\n')

    if use_cvode:
        return np.array(t), np.array(V), np.array(spike_times)
    else:
        return np.array(V), np.array(spike_times)
Пример #33
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)
Пример #34
0
    axon.nseg = nseg
    axon.Ra = Ra
    axon.insert('hh')


    asyns = [h.AlphaSynapse(axon(0)), h.AlphaSynapse(axon(0))]
    for ix,t in enumerate(t_on):  
        asyns[ix].onset = t
        asyns[ix].gmax = g_max
    h.tstop = sim_length

    t_vec = h.Vector()  # Time stamp vector
    t_vec.record(h._ref_t)

    axon_segments = list(axon)
    v_vec = []
    for axon_segment in axon_segments:
        v_vec.append(h.Vector())
        v_vec[-1].record(axon_segment._ref_v)

    h.cvode_active(1)
    h.cvode.atol(1e-5)
    h.run()

    results = np.zeros((len(t_vec), len(axon_segments) + 1))
    results[:, 0] = t_vec.as_numpy()
    for ix, v in enumerate(v_vec):
        results[:, ix + 1] = v_vec[ix]

np.savetxt(save_dir+"/modelResult/" + model_name + ".csv", results, delimiter=",")
Пример #35
0
    def run(self):
        self.gui()
        self.g.label(0.1, 0.9, self.mechname, 2)
        self.g.label("secondorder=%g" % h.secondorder)
        self.g.label("dt=%g" % h.dt)
        vvec = h.Vector()
        tvec = h.Vector()
        if use_voltage_clamp:
            vvec.label("ic")
            vvec.record(self.syn, self.vc._ref_i, 0.1)
        else:
            vvec.label("v")
            #vvec.record(self.syn, self.soma(.5)._ref_v, 0.1)
            vvec.record(self.syn, self.syn._ref_A_AMPA, 0.1)
        tvec.record(self.syn, h._ref_t, 0.1)
        h.cvode.atol(1e-10)

        # cvode is standard but use first result to change weight so that
        # there is a substantial synaptic change
        dtsav = h.dt
        try:
            h.cvode_active(1)
            h.run()
        except:
            h.cvode_active(0)
            h.dt /= 1000
            print("cvode failed so try fixed step dt=%g as standard" % h.dt)
            h.run()
        sz = 10 * h.tstop
        scale = (vvec.max(10, sz) - vvec.min(10, sz)) / 10.
        print("scale=%g" % scale)
        if abs(scale) > 1e-6:
            self.nc.weight[0] /= scale
        elif math.isnan(scale) or abs(scale) > 1e6:
            print("numerical problem")
        else:
            print("No response")
        h.run()
        h.dt = dtsav
        vvec.resize(sz)
        tvec.resize(sz)
        vvec.line(self.g, tvec, 1, 3)
        vstd = vvec.c()
        tstd = tvec.c()
        vmag = vvec.c().sub(vvec.x[10]).abs().sum()

        result = []
        h.cvode_active(0)
        for adjust in [0, 1]:
            h.nrn_netrec_state_adjust = adjust
            color = 3 if adjust is 1 else 2
            for dt in [h.dt / 8, h.dt / 4, h.dt / 2, h.dt]:
                h.dt = dt
                h.run()
                vvec.resize(sz)
                tvec.resize(sz)
                vvec.line(self.g, tvec, color, 1)
                vdif = vvec.c().sub(vstd).abs().sum()
                tdif = tvec.c().sub(tstd).abs().sum()
                result.append((self.mechname, h.secondorder, adjust, dt, vdif,
                               tdif, vmag))
                print("%s %g %g %g %g %g" % result[-1][:-1])

            h.nrn_netrec_state_adjust = 0

        self.g.exec_menu("View = plot")
        return result
Пример #36
0
data1 = numpy.loadtxt(os.path.join(Exp_Dir, files_list1[0]))
data2 = numpy.loadtxt(os.path.join(Exp_Dir, files_list2[0]))
data3 = numpy.loadtxt(os.path.join(Exp_Dir, files_list3[0]))
data0 = data0[1:80000, :]
data1 = data1[1:80000, :]
data2 = data2[1:80000, :]
data3 = data3[1:80000, :]

### Parameters ###
Nsyns = numpy.array([0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60])
Nsyns_PYR = 3
freqs = numpy.array([1, 5, 8, 10, 20])

### Setup holding currents ###

h.cvode_active(1)  # i.e. to make it run faster for this portion
h.cvode.atol(1e-05)
h.tstop = 5000

spikerate_prev = 0
if find7HzHolding:
    for stepcurr in range(40, 101, 1):
        h.ic_hold.amp = stepcurr * 0.001  # holding current
        h.f(0, 0, 0)
        apctimes = numpy.array(h.apctimes)
        apctimes = apctimes[apctimes > 1000]  # Only spike times > 1s
        spikerate = len(apctimes) / 4
        print('Spike Rate = ' + str(spikerate) + ' Hz at ' +
              str(stepcurr * 0.001) + ' nA')
        if (spikerate > 7) & (spikerate < 7.6):
            print('Holding Current = ' + str(stepcurr * 0.001) + ' nA')
Пример #37
0
def iclamp_adaptive(cell,
                    sec,
                    i_inj,
                    v_init,
                    tstop,
                    dt,
                    celsius=35,
                    pos_i=0.5,
                    pos_v=0.5,
                    atol=1e-2,
                    continuous=True,
                    discontinuities=None,
                    interpolate=True):
    """
    Runs a NEURON simulation of the cell for the given parameters using adaptive integration.

    :param sec: List with 1st entry the name of the section and 2nd entry the index (or None in case of soma)
    :type sec: list[str, int]
    :param i_inj: Amplitude of the injected current for all times t.
    :type i_inj: array_like
    :param v_init: Initial membrane potential of the cell.
    :type v_init: float
    :param tstop: Duration of a whole run.
    :type tstop: float
    :param dt: Time step.
    :type dt: float
    :param celsius: Temperature during the simulation (affects ion channel kinetics).
    :type celsius: float
    :param pos_i: Position of the IClamp on the Section (number between 0 and 1).
    :type pos_i: float
    :param pos_v: Position of the recording electrode on the Section (number between 0 and 1).
    :type pos_v: float
    :param atol: Absolute tolerance of the integration.
    :type atol: float
    :param: continuous: If true, linear interpolation is used to define the values between time points of i_inj.
    :type: continuous: bool
    :param: discontinuities: Indices where jumps in i_inj occur. This will insert a new point before each discontinuity
    in t with the time at the discontinuity and in i_inj with the value from i_inj before the discontinuity.
    :type discontinuities: array[int]
    :param interpolate: If true, the recorded values for v and t will be linearly interpolated to match dt.
    :type interpolate: bool
    :return: Membrane potential of the cell and time recorded at each time step.
    :rtype: tuple of three ndarrays
    """
    # turn on adaptive integration and set tolerance (only works when stdrun.hoc already loaded)
    h.cvode_active(1)
    h.cvode.atol(1e-8)

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

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

    # adapt i_vec to cope with discontinuities
    if discontinuities is not None:
        discontinuities = np.sort(discontinuities)
        discontinuities = discontinuities + np.arange(
            len(discontinuities
                ))  # index shifts by the amount of already inserted values
        for discontinuity in discontinuities:
            i_inj = np.insert(i_inj, discontinuity, i_inj[discontinuity - 1])
            t = np.insert(t, discontinuity, t[discontinuity])

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

    # record the membrane potential
    v_rec = section.record('v', pos_v)
    t_rec = h.Vector()
    t_rec.record(h._ref_t)
    i_rec = h.Vector()
    i_rec.record(stim._ref_amp)

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

    v_rec = np.array(v_rec)
    t_rec = np.array(t_rec)
    #i_rec = np.array(i_rec)

    if interpolate:
        #i_rec = np.interp(t, t_rec, i_rec)
        v_rec = np.interp(t, t_rec, v_rec)
        t_rec = np.interp(t, t_rec, t_rec)

        t_rec, unique_indices = np.unique(
            t_rec,
            return_index=True)  # remove double values (from discontinuities)
        v_rec = v_rec[unique_indices]  # second value is the right one
        #i_rec = i_rec[unique_indices]  # second value is the right one

    return v_rec, t_rec  #  , i_rec