Beispiel #1
0
 def __init__(self,
              pc,
              tstop,
              max_walltime_hours,
              results_write_time,
              setup_time,
              dt_status=1.0,
              dt_checksimtime=10.0):
     if (int(pc.id()) == 0):
         logger.info("*** allocated wall time is %.2f hours" %
                     (max_walltime_hours))
     wt = time.time()
     self.pc = pc
     self.tstop = tstop
     self.walltime_status = wt
     self.walltime_checksimtime = wt
     self.dt_status = dt_status
     self.tcsum = 0.
     self.tcma = 0.
     self.nsimsteps = 0
     self.walltime_max = max_walltime_hours * 3600. - setup_time
     self.results_write_time = results_write_time
     self.dt_checksimtime = dt_checksimtime
     self.fih_checksimtime = h.FInitializeHandler(1, self.checksimtime)
     self.fih_simstatus = h.FInitializeHandler(1, self.simstatus)
     if (int(self.pc.id()) == 0):
         logger.info(
             "*** max wall time is %.2f s; max setup time was %.2f s" %
             (self.walltime_max, setup_time))
Beispiel #2
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
Beispiel #3
0
 def reset(self):
     wt = time.time()
     self.walltime_max = self.walltime_max - self.tcsum
     self.tcsum = 0.
     self.tcma = 0.
     self.nsimsteps = 0
     self.walltime_status = wt
     self.walltime_checksimtime = wt
     self.fih_checksimtime = h.FInitializeHandler(1, self.checksimtime)
     self.fih_simstatus = h.FInitializeHandler(1, self.simstatus)
Beispiel #4
0
def cellset ():
  global cell07, cell03, izh, vref, uvvset, fih, izhtype
  if newmodel():
    cell07 =  choices[izhtype][0]()
    izh = cell07.izh
    def uvvset () : pass
  else: 
    cell03 = h.Section(name="cell2003") # this cell will be used for 2003/4; different cell created in izhi2007Wrapper for those
    izh =  choices[izhtype][0]()
    def uvvset () : vref[0], izh.u = vviv, vviv*izh.b
    cell03.L, cell03.diam = 6.37, 5 # empirically tuned -- cell size only used for Izh1
  fih = [h.FInitializeHandler(uvvset), h.FInitializeHandler(0,Isend)]
  vref = choices[izhtype][1]() # can define this afterwards even though used in uvvset above
Beispiel #5
0
 def __init__(self,
              label,
              pc,
              pop_gid_dict,
              pos,
              rho=333.0,
              fdst=0.1,
              maxEDist=100.,
              dt_lfp=0.5,
              seed=1):
     self.label = label
     self.pc = pc
     self.dt_lfp = dt_lfp
     self.seed = seed
     self.epoint = pos
     self.maxEDist = maxEDist
     self.rho = rho  ## extracellular resistivity, [ohm cm]
     self.fdst = fdst  ## percent of distant cells to include in the computation
     self.meanlfp = []
     self.t = []
     self.lfp_ids = {}
     self.lfp_types = {}
     self.lfp_coeffs = {}
     self.pop_gid_dict = pop_gid_dict
     self.fih_lfp = h.FInitializeHandler(1, self.sample_lfp)
     self.setup_lfp()
Beispiel #6
0
 def setup(self):
     h.cvode.use_fast_imem(
         1
     )  # enables fast calculation of transmembrane current (nA) at each segment
     self.bscallback = h.beforestep_callback(h.cas()(.5))
     self.bscallback.set_callback(self.callback)
     fih = h.FInitializeHandler(1, self.LFPinit)
Beispiel #7
0
def test_finithandler():
    soma = h.Section(name="soma")
    fih = h.FInitializeHandler(1, (callback, (0)))
    for i in range(2):
        h.finitialize()

    fih = h.FInitializeHandler(1, (callback, (1)))
    for i in range(1):
        expect_err("h.finitialize()")

    del fih  # a mysterious consequence of expect_err is that need this
    locals()  # in order for the callback to be deleted in time for next
    if __name__ == "__main__":
        print("another test")
        fih = h.FInitializeHandler(1, (callback, (2)))
        h.finitialize()
        print("this line gets printed in interactive mode")
Beispiel #8
0
 def __init__(self):
     """
     Create an `FinitializeHandler` object in Hoc, which will call the
     `_initialize()` method when NEURON is initialized.
     """
     h('objref initializer')
     h.initializer = self
     self.fih = h.FInitializeHandler(1, "initializer._initialize()")
     self.clear()
Beispiel #9
0
def _do_nbs_register():
    global _has_nbs_registered, _nbs, _fih, _fih2

    if not _has_nbs_registered:
        from neuron import nonvint_block_supervisor as _nbs

        _has_nbs_registered = True
        _nbs.register(_callbacks)

        #
        # register the initialization handler and the ion register handler
        #
        _fih = h.FInitializeHandler(_init)
        _fih2 = h.FInitializeHandler(3, initializer._do_ion_register)

        #
        # register scatter/gather mechanisms
        #
        _cvode_object.extra_scatter_gather(0, _after_advance)
Beispiel #10
0
    def set_ecp_recording(self):
        '''
        Set recording of the ExtraCellular Potential
        '''

        self.rel = RecXElectrode(self.conf)

        for gid in self.gids['biophysical']:
            cell = self.net.cells[gid]
            self.rel.calc_transfer_resistance(gid, cell.get_seg_coords())

        h.cvode.use_fast_imem(1)  # make i_membrane_ a range variable
        self.fih1 = h.FInitializeHandler(0, self.set_pointers)
def run_simulation(shotnoise_input, cables, params, tstop=2000.,\
                   dt=0.025, seed=3, recordings='full', recordings2='', nmda_on=False, Ca_spikes_on=False, HH_on=False,\
                   synchronous_stim={'location':[4,14], 'spikes':[]}):
    """
    recordings is a set of tuple of the form : [branch_generation, branch_number, xseg]
    """
    exc_synapses, exc_netcons, exc_Ks, exc_spike_trains,\
       inh_synapses, inh_netcons, inh_Ks, inh_spike_trains,\
       area_lists, spkout = Constructing_the_ball_and_tree(params, cables, nmda_on=nmda_on, Ca_spikes_on=Ca_spikes_on, HH_on=HH_on)

    # then synapses manually
    set_presynaptic_spikes_manually(shotnoise_input, cables, params,\
                                    exc_spike_trains, exc_Ks,
                                    inh_spike_trains, inh_Ks, tstop, seed=seed,\
                                    synchronous_stim=synchronous_stim)
    
    ## QUEUING OF PRESYNAPTIC EVENTS
    init_spike_train = queue_presynaptic_events_in_NEURON([exc_netcons, exc_spike_trains, inh_netcons, inh_spike_trains])
    ## --- launching the simulation
    fih = nrn.FInitializeHandler((init_spike_train, [exc_netcons, exc_spike_trains, inh_netcons, inh_spike_trains]))
    
    ## --- recording
    t_vec = nrn.Vector()
    t_vec.record(nrn._ref_t)
    V = []

    if recordings is 'soma':
        V.append(nrn.Vector())
        exec('V[0].record(nrn.cable_0_0(0)._ref_v)')
    if recordings2 is 'cable_end':
        V.append(nrn.Vector())
        exec('V[1].record(nrn.cable_5_15(1)._ref_v)')

    ## --- launching the simulation
    nrn.finitialize(params['El']*1e3)
    nrn.dt = dt

    if recordings is 'full':
        V.append(get_v(cables))

    while nrn.t<(tstop-dt):
        nrn.fadvance()
        if recordings is 'full':
            V.append(get_v(cables))

    print("=======================================")
    nrn('forall delete_section()')
    print(" --- checking if the neuron is destroyed")
    nrn.topology()
    print("=======================================")
    return np.array(t_vec), V
Beispiel #12
0
    def setup_recorder(self):
        h = self.h

        collector_stim = h.NetStim(0.5)
        collector_stim.start = 0
        collector_stim.interval = self.sampling_period
        collector_stim.number = 1e9
        collector_stim.noise = 0

        collector_con = h.NetCon(collector_stim, None)
        collector_con.record(self.collect)

        self.collector_stim = collector_stim
        self.collector_con = collector_con

        # Clear previously recorded activity on h.run()
        self.fih = h.FInitializeHandler(self.clear)
Beispiel #13
0
    def from_skeletal_blender_group(self, blender_group, node):
        self.node = node
        self.name = blender_group['name']

        self.save_recording_params(blender_group)

        # Initialize selected roots and their children
        for blender_root in blender_group["roots"]:
            section = NeuronSection()
            section.from_skeletal_blender_root(blender_root, group=self)

            if section.name != '':
                self.roots[section.name] = section

        # Clear previously recorded activity on h.run()
        self.fih = h.FInitializeHandler(self.clear_activity)

        # Setup to collect activity during h.run()
        self.create_collector()
Beispiel #14
0
def preRun():
    from .. import sim

    # set initial v of cells
    for cell in sim.net.cells:
        sim.fih.append(h.FInitializeHandler(0, cell.initV))

    # cvode variables
    sim.cvode.active(int(sim.cfg.cvode_active))
    sim.cvode.cache_efficient(int(sim.cfg.cache_efficient))
    sim.cvode.atol(sim.cfg.cvode_atol)

    # set h global params
    sim.setGlobals()

    # set h.dt
    h.dt = sim.cfg.dt

    # set v_init if doesn't exist
    if 'v_init' not in sim.cfg.hParams: sim.cfg.hParams['v_init'] = -65.0

    # parallelcontext vars
    sim.pc.set_maxstep(10)
    mindelay = sim.pc.allreduce(sim.pc.set_maxstep(10),
                                2)  # flag 2 returns minimum value
    if sim.rank == 0 and sim.cfg.verbose:
        print(('Minimum delay (time-step for queue exchange) is %.2f' %
               (mindelay)))
    sim.pc.setup_transfer()  # setup transfer of source_var to target_var

    # handler for printing out time during simulation run
    if sim.rank == 0 and sim.cfg.printRunTime:

        def printRunTime():
            print('%.1fs' % (h.t / 1000.0))
            sim.cvode.event(h.t + int(sim.cfg.printRunTime * 1000.0),
                            sim.printRunTime)

        sim.printRunTime = printRunTime
        sim.fih.append(h.FInitializeHandler(1, sim.printRunTime))

    # set global index used by all instances of the Random123 instances of Random
    if sim.cfg.rand123GlobalIndex is not None:
        rand = h.Random()
        rand.Random123_globalindex(int(sim.cfg.rand123GlobalIndex))

    # reset all netstim randomizers so runs are always equivalent
    for cell in sim.net.cells:
        if cell.tags.get('cellModel') == 'NetStim':
            #cell.hRandom.Random123(sim.hashStr('NetStim'), cell.gid, cell.params['seed'])
            utils._init_stim_randomizer(cell.hRandom, 'NetStim', cell.gid,
                                        cell.params['seed'])
            cell.hRandom.negexp(1)
            cell.hPointp.noiseFromRandom(cell.hRandom)
        pop = sim.net.pops[cell.tags['pop']]
        if 'originalFormat' in pop.tags and pop.tags[
                'originalFormat'] == 'NeuroML2_SpikeSource':
            if sim.cfg.verbose:
                print("== Setting random generator in NeuroML spike generator")
            cell.initRandom()
        else:
            for stim in cell.stims:
                if 'hRandom' in stim:
                    #stim['hRandom'].Random123(sim.hashStr(stim['source']), cell.gid, stim['seed'])
                    utils._init_stim_randomizer(stim['hRandom'], stim['type'],
                                                cell.gid, stim['seed'])
                    stim['hRandom'].negexp(1)
                    # Check if noiseFromRandom is in stim['hObj']; see https://github.com/Neurosim-lab/netpyne/issues/219
                    if not isinstance(stim['hObj'].noiseFromRandom, dict):
                        stim['hObj'].noiseFromRandom(stim['hRandom'])

    # handler for recording LFP
    if sim.cfg.recordLFP:

        def recordLFPHandler():
            sim.cvode.event(h.t + float(sim.cfg.recordStep), sim.calculateLFP)
            sim.cvode.event(h.t + float(sim.cfg.recordStep), recordLFPHandler)

        sim.recordLFPHandler = recordLFPHandler
        sim.fih.append(h.FInitializeHandler(
            0, sim.recordLFPHandler))  # initialize imemb
# stimulate
stimB = h.IClamp(somaB(0.5))
stimB.delay = 50
stimB.amp = 1
stimB.dur = 50

# record
tvec = h.Vector().record(h._ref_t)
vvecB = h.Vector().record(somaB(0.5)._ref_v)
kvecB = h.Vector().record(somaB(0.5)._ref_ik)
navecB = h.Vector().record(somaB(0.5)._ref_ina)
mvecB = h.Vector().record(somaB(0.5).hh._ref_m)
nvecB = h.Vector().record(somaB(0.5).hh._ref_n)
hvecB = h.Vector().record(somaB(0.5).hh._ref_h)

fih = h.FInitializeHandler(1, restoreSS)
h.finitialize()

h.continuerun(100)

# while h.t < tstop:
#     # pc.psolve(h.t + h.dt)
#     h.fadvance()
#     print(h.t)

# plotting 
fig = pyplot.figure()
# pyplot.plot(tvec, vvecA, label="rxd")
pyplot.plot(tvec, vvecB, label="mod")
pyplot.xlabel('t (ms)')
pyplot.ylabel('V$_m$ (mV)')
Beispiel #16
0
    for a in range(Ncells):
        cells[a].soma.el_clarke =\
        (cells[a].soma.ina_clarke + cells[a].soma.ikrect_clarke\
        + cells[a].soma.icaN_clarke + cells[a].soma.icaL_clarke\
        + cells[a].soma.ikca_clarke + cells[a].soma.inap_clarke\
        + cells[a].soma.gl_clarke*cells[a].soma.v) / cells[a].soma.gl_clarke

        cells[a].dend.e_pas =\
        (cells[a].dend.g_pas * cells[a].dend.v) / cells[a].dend.g_pas


#    print 'hello from inside init'

h.celsius = 37
net = ClarkeNetwork()
h.v_init = -65
fih = h.FInitializeHandler(2, (tweak_leak, (net.cells, len(net.cells))))
shape_window = h.PlotShape()
shape_window.exec_menu('Show Diam')
soma_v_vec, soma_m_vec, soma_h_vec, soma_n_vec,\
     soma_inap_vec, soma_idap_vec, soma_ical_vec,\
     soma_ican_vec, soma_ikca_vec, soma_ina_vec, soma_ikrect_vec,\
    dend_v_vec, t_vec\
    = simrun.set_recording_vectors(net.cells[0])

simrun.simulate(tstop=10000)
simrun.show_output(soma_v_vec, dend_v_vec, t_vec)
pyplot.show()
spikes = net.get_spikes()
sp = spikeplot.SpikePlot(savefig=True)
sp.plot_spikes(spikes)
    # record all segments voltage
    if collectAndSaveDVTs:
        recVoltage_allSegments = []
        for segInd, segment in enumerate(allSegments):
            voltageRecSegment = h.Vector()
            voltageRecSegment.record(segment._ref_v)
            recVoltage_allSegments.append(voltageRecSegment)

    preparationDurationInSeconds = time.time() - preparationStartTime
    print("preparing for single simulation took %.4f seconds" %
          (preparationDurationInSeconds))

    ## simulate the cell
    simulationStartTime = time.time()
    # make sure the following line will be run after h.finitialize()
    fih = h.FInitializeHandler('nrnpython("AddAllSynapticEvents()")')
    h.finitialize(-76)
    neuron.run(totalSimDurationInMS)
    singleSimulationDurationInMinutes = (time.time() -
                                         simulationStartTime) / 60
    print("single simulation took %.2f minutes" %
          (singleSimulationDurationInMinutes))

    ## extract the params from the simulation
    # collect all relevent recoding vectors (input spike times, dendritic voltage traces, soma voltage trace)
    collectionStartTime = time.time()

    origRecordingTime = np.array(recTime.to_python())
    origSomaVoltage = np.array(recVoltageSoma.to_python())
    origNexusVoltage = np.array(recVoltageNexus.to_python())
Beispiel #18
0
 def __init__(self):
     self.fih = h.FInitializeHandler(1, self.callback)
Beispiel #19
0
 def setup(self):
     """Enables fast calculation of transmembrane current (nA) at
        each segment."""
     h.cvode.use_fast_imem(1)
     self.bscallback = h.cvode.extra_scatter_gather(0, self.callback)
     fih = h.FInitializeHandler(1, self.LFPinit)
Beispiel #20
0
from neuron import h
h.load_file('nrngui.hoc')


def callback1(tol=0.01):
    print("callback1: t=%s" % h.t)
    1 / 0
    print("I just made a divide-by-zero error")
    interval = 10000
    print("next callback1 at %s" % (h.t + interval))
    h.cvode.event(h.t + interval, callback1)
    #return(interval)


h.cvode_active(1)
fih = h.FInitializeHandler(callback1)
h.stdinit()
h.cvode.solve(50000)
def get_cell(env, gid, population):
    """

    :param env:
    :param gid:
    :param population:
    :return:
    """
    h.load_file("nrngui.hoc")
    h.load_file("loadbal.hoc")
    h('objref fi_status, fi_checksimtime, pc, nclist, nc, nil')
    h('strdef datasetPath')
    h('numCells = 0')
    h('totalNumCells = 0')
    h('max_walltime_hrs = 0')
    h('mkcellstime = 0')
    h('mkstimtime = 0')
    h('connectcellstime = 0')
    h('connectgjstime = 0')
    h('results_write_time = 0')
    h.nclist = h.List()
    datasetPath = os.path.join(env.datasetPrefix, env.datasetName)
    h.datasetPath = datasetPath
    ##  new ParallelContext object
    # h.pc = h.ParallelContext()
    # env.pc = h.pc
    rank = int(env.pc.id())
    nhosts = int(env.pc.nhost())
    ## polymorphic value template
    h.load_file("./templates/Value.hoc")
    ## randomstream template
    h.load_file("./templates/ranstream.hoc")
    ## stimulus cell template
    h.load_file("./templates/StimCell.hoc")
    h.xopen("./lib.hoc")
    h.dt = env.dt
    h.tstop = env.tstop
    if env.optldbal or env.optlptbal:
        lb = h.LoadBalance()
        if not os.path.isfile("mcomplex.dat"):
            lb.ExperimentalMechComplex()

    if (env.pc.id() == 0):
        mkspikeout(env, env.spikeoutPath)
    env.pc.barrier()
    h.startsw()
    mkcells(env)
    env.mkcellstime = h.stopsw()
    env.pc.barrier()
    if (env.pc.id() == 0):
        print "*** Cells created in %g seconds" % env.mkcellstime
    print "*** Rank %i created %i cells" % (env.pc.id(), len(env.cells))
    h.startsw()
    mkstim(env)
    env.mkstimtime = h.stopsw()
    if (env.pc.id() == 0):
        print "*** Stimuli created in %g seconds" % env.mkstimtime
    env.pc.barrier()
    h.startsw()
    connectcells(env)
    env.connectcellstime = h.stopsw()
    env.pc.barrier()
    if (env.pc.id() == 0):
        print "*** Connections created in %g seconds" % env.connectcellstime
    print "*** Rank %i created %i connections" % (env.pc.id(), int(h.nclist.count()))
    h.startsw()
    # connectgjs(env)
    env.connectgjstime = h.stopsw()
    if (env.pc.id() == 0):
        print "*** Gap junctions created in %g seconds" % env.connectgjstime
    env.pc.setup_transfer()
    env.pc.set_maxstep(10.0)
    h.max_walltime_hrs = env.max_walltime_hrs
    h.mkcellstime = env.mkcellstime
    h.mkstimtime = env.mkstimtime
    h.connectcellstime = env.connectcellstime
    h.connectgjstime = env.connectgjstime
    h.results_write_time = env.results_write_time
    h.fi_checksimtime = h.FInitializeHandler("checksimtime(pc)")
    if (env.pc.id() == 0):
        print "dt = %g" % h.dt
        print "tstop = %g" % h.tstop
        h.fi_status = h.FInitializeHandler("simstatus()")
    h.v_init = env.v_init
    h.stdinit()
    h.finitialize(env.v_init)
    env.pc.barrier()
    if env.optldbal or env.optlptbal:
        cx(env)
        ld_bal(env)
        if env.optlptbal:
            lpt_bal(env)
Beispiel #22
0
def test_direct_memory_transfer():
    h("""create soma""")
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    h.soma.insert("hh")
    ic = h.IClamp(h.soma(0.5))
    ic.delay = 0.5
    ic.dur = 0.1
    ic.amp = 0.3

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

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

    v = h.Vector()
    v.record(h.soma(0.5)._ref_v, sec=h.soma)
    i_mem = h.Vector()
    i_mem.record(h.soma(0.5)._ref_i_membrane_, sec=h.soma)
    tv = h.Vector()
    tv.record(h._ref_t, sec=h.soma)
    h.run()
    vstd = v.cl()
    tvstd = tv.cl()
    i_memstd = i_mem.cl()
    # Save current (after run) value to compare with transfer back from coreneuron
    tran_std = [h.t, h.soma(0.5).v, h.soma(0.5).hh.m]

    from neuron import coreneuron

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

    pc = h.ParallelContext()

    def run(mode):
        pc.set_maxstep(10)
        h.stdinit()
        if mode == 0:
            pc.psolve(h.tstop)
        elif mode == 1:
            while h.t < h.tstop:
                pc.psolve(h.t + 1.0)
        else:
            while h.t < h.tstop:
                h.continuerun(h.t + 0.5)
                pc.psolve(h.t + 0.5)
        tran = [h.t, h.soma(0.5).v, h.soma(0.5).hh.m]

        assert tv.eq(tvstd)
        assert (
            v.cl().sub(vstd).abs().max() < 1e-10
        )  # usually v == vstd, some compilers might give slightly different results
        assert i_mem.cl().sub(i_memstd).abs().max() < 1e-10
        assert h.Vector(tran_std).sub(h.Vector(tran)).abs().max() < 1e-10

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

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

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

    fi = h.FInitializeHandler(2, test_hoc_event)
    coreneuron.enable = False
    run(0)
    coreneuron.enable = True
    run(0)
Beispiel #23
0
                matrix[row, i] = 0
            else:
                matrix[row, :] = 0
        global _mat_for_zero_volume_nodes
        _mat_for_zero_volume_nodes = matrix.tocsr()


def _init():
    # TODO: check about the 0<x<1 problem alluded to in the documentation
    h.define_shape()

    section1d._purge_cptrs()

    for sr in species._get_all_species().values():
        s = sr()
        if s is not None:
            s._register_cptrs()
            s._finitialize()
    _setup_matrices()


#
# register the initialization handler and the advance handler
#
_fih = h.FInitializeHandler(_init)

#
# register scatter/gather mechanisms
#
_cvode_object.extra_scatter_gather(0, _after_advance)
    nrn('create soma')
    nrn.soma.insert('pas')
    nrn.soma.L, nrn.soma.diam = 58, 58
    nrn.soma.g_pas, nrn.soma.e_pas = 5e-5, -70.
    syn = nrn.my_glutamate(0.5, sec=nrn.soma)
    netcon = nrn.NetCon(nrn.nil, syn)
    netcon.weight[0] = 1
    syn.gmax = 4

    def init_spike_train(ALL):
        netcon, spikes = ALL
        for spk in spikes:
            netcon.event(spk)

    syn.nmda_on = ntar
    fih = nrn.FInitializeHandler(
        (init_spike_train, [netcon, np.arange(10) * 7. + 50.]))
    t_vec = nrn.Vector()
    t_vec.record(nrn._ref_t)
    V = nrn.Vector()
    V.record(nrn.soma(0.5)._ref_v)
    A = nrn.Vector()
    A.record(syn._ref_gampa)

    nrn.finitialize(-70.)
    while nrn.t < 400.:
        nrn.fadvance()

    plt.plot(np.array(t_vec), V, '-', color=color, label=label)
plt.legend()
plt.ylim([-80, -30])
plt.show()
Beispiel #25
0
# make a 2003a STATE {u,vv} cell (used for 2003, 2004)
iz03a = h.Izhi2003a(0.5, sec=dummy)
iz03a.Iin = 4

# make a 2003b (Section v) cell
sec03b = h.Section()  # this section will actually be used
sec03b.L, sec03b.diam = 5, 6.3  # empirically tuned
iz03b = h.Izhi2003b(0.5, sec=sec03b)
iz03b.Iin = 4


def iz03b_init():
    sec03b(0.5).v, iz03b.u = -65, -65 * iz03b.b


fih.append(h.FInitializeHandler(iz03b_init))

# make a 2007a (NMODL) cell
iz07a = h.Izhi2007a(0.5, sec=dummy)
iz07a.Iin = 70

# make a 2007b (section) cell
sec07b = h.Section()
sec07b.L, sec07b.diam = 5, 6.3
iz07b = h.Izhi2007b(0.5, sec=sec07b)
iz07b.Iin = 70


def iz07b_init():
    sec07b.v = -60
Beispiel #26
0
                rds.negexp(1)

    fihSIGns = h.FInitializeHandler(0, initSigNetStims)
    setStims()  # create the inputs based on contents of nqm


#this should be called @ beginning of each sim - done in an FInitializeHandler
def init_NetStims():
    for i in xrange(len(nrl)):
        rds = nrl[i]
        sead = nrlsead[i]
        rds.MCellRan4(sead, sead)
        rds.negexp(1)


fihns = h.FInitializeHandler(0, init_NetStims)


#
def printt():
    sys.stdout.write('\rt: {0} ...'.format(h.t))
    sys.stdout.flush()


# handler for printing out time during simulation run
def fi():
    for i in xrange(int(tstart), int(tstart + tstop), 100):
        h.cvode.event(i, printt)


fih = h.FInitializeHandler(1, fi)
Beispiel #27
0
 def __init__(self, eventTime, cvode, nrnSim):
     self.eventTime = eventTime
     self.cvode = cvode
     self.fih = h.FInitializeHandler(1, self.callback)
Beispiel #28
0
def setupWMInputs():
    global nqm, rnnsl, rnncl, rnrds, rnseed, fihSIGns
    if os.path.exists(dconf['nqm']):  # read nqm if it exists
        nqm = h.NQS(dconf['nqm'])
    else:  # setup nqm here if nqm file path non-existant
        nqm = h.NQS('vid', 'startt', 'endt', 'rate', 'w')
        nqm.odec('vid')
        lvid = []
        nMem = dconf['nMem']
        memstartt = dconf['memstartt']
        memintert = dconf['memintert']
        memdurt = dconf['memdurt']
        memstartt += tstart  # this only has an effect when loadstate != 0
        startt = memstartt
        endt = startt + memdurt
        if verbose:
            print 'startt:', startt, ',memstartt:', memstartt, ',tstart:', tstart, ',loadstate:', loadstate
        for i in xrange(nMem):  # number of stimuli
            lvid.append(h.Vector())
            vtmp = Vector()
            vtmp.append(0)  # only one cell
            lvid[-1].append(vtmp)
            nqm.append(lvid[-1], startt, endt, dconf['memrate'], dconf['memW'])
            startt += (memdurt + memintert)
            if i == nMem - 2 and dconf['lastmemdurt'] != memdurt:
                endt = startt + dconf['lastmemdurt']
            else:
                endt = startt + memdurt
    # backup the nqm file for later retrieval
    fnqwm = 'meminput/' + simstr + '_nqm.nqs'
    if os.path.exists(fnqwm):
        os.remove(fnqwm)
    nqm.sv(fnqwm)
    if verbose:
        print 'this is nqm:'
        nqm.pr()

    def createNetStims(vid,
                       rate,
                       w,
                       startt,
                       endt,
                       seed=1234,
                       syn='Adend3AMPA'):
        global rnnsl, rnncl, rnrds, rnseed  # based on row number in nqm
        rnnsl.append([])  # a list for each row of nqm
        rnncl.append([])
        rnrds.append([])
        rnseed.append([])
        sidx = -1
        slist = [cell.Adend3, cell.Adend2, cell.Adend1]
        if syn.count('AMPA'): sidx = 0
        elif syn.count('NMDA'): sidx = 1
        elif syn.count('GABAss'): sidx = 2
        elif syn.count('mGLUR'): sidx = 3
        if syn.count('0'): slist = [cell.Adend3, cell.Adend2, cell.Adend1]
        elif syn.count('1'): slist = [cell.Adend1]
        elif syn.count('2'): slist = [cell.Adend2]
        elif syn.count('3'): slist = [cell.Adend3]
        if sidx == -1:
            ns = h.NetStim()
            ns.start = startt
            ns.number = (endt - startt) * rate / 1e3
            if verbose:
                print 'createNetStims:', startt, endt, ns.number, rate, w
            ns.interval = 1e3 / rate
            ns.noise = 1
            rnnsl[-1].append(ns)
            nc = h.NetCon(ns, ce[0].__dict__[syn].syn)
            nc.delay = h.dt * 2
            nc.weight[0] = w
            rnncl[-1].append(nc)
            rds = h.Random()
            rds.negexp(1)
            rds.MCellRan4(seed, seed)
            ns.noiseFromRandom(rds)
            rnrds[-1].append(rds)
            rnseed[-1].append(seed)
        else:
            tmpseed = seed
            for sec in slist:
                llsy = cell.dsy[sec]
                for lsy in llsy:
                    ns = h.NetStim()
                    ns.start = startt
                    ns.number = (endt - startt) * rate / 1e3
                    if verbose:
                        print 'createNetStims:', startt, endt, ns.number, rate, w
                    ns.interval = 1e3 / rate
                    ns.noise = 1
                    rnnsl[-1].append(ns)
                    nc = h.NetCon(ns, lsy[sidx].syn)
                    nc.delay = h.dt * 2
                    nc.weight[0] = w
                    rnncl[-1].append(nc)
                    rds = h.Random()
                    rds.negexp(1)
                    rds.MCellRan4(tmpseed, tmpseed)
                    ns.noiseFromRandom(rds)
                    rnrds[-1].append(rds)
                    rnseed[-1].append(tmpseed)
                    tmpseed += 1

    def createNetStimsFromNQ(nqm, row, seed=1234, syn='Adend3AMPA', wfctr=1.0):
        nqm.tog("DB")
        vid = h.Vector()
        rate = nqm.getcol("rate").x[row]
        w = nqm.getcol("w").x[row] * wfctr  # wfctr is weight scaling factor
        vid.copy(nqm.get("vid", row).o[0])
        startt = float(nqm.getcol("startt").x[row])  # + tstart
        endt = float(nqm.getcol("endt").x[row])  # + tstart
        createNetStims(vid, rate, w, startt, endt, seed, syn)

    def setStims():
        global nqm
        lapicIDX = []
        try:
            lapicIDX = [int(dconf['apicIDX'])]
        except:
            for i in dconf['apicIDX'].split(','):
                lapicIDX.append(int(i))
        nqm.tog("DB")
        sz = int(nqm.v[0].size())
        lastmGLURON = dconf['lastmGLURON']
        nMemInhib = dconf['nMemInhib']
        if lastmGLURON:
            for i in xrange(sz):
                if i == sz - 1:
                    for j in lapicIDX:
                        createNetStimsFromNQ(nqm,
                                             i,
                                             seed=(i + 1) * 12345,
                                             syn='Adend' + str(j) + 'mGLUR',
                                             wfctr=mGLURRWM)
                else:
                    for j in lapicIDX:
                        createNetStimsFromNQ(nqm,
                                             i,
                                             seed=(i + 1) * 12345,
                                             syn='Adend' + str(j) + 'AMPA',
                                             wfctr=AMRWM)
                        createNetStimsFromNQ(nqm,
                                             i,
                                             seed=(i + 1) * 12345,
                                             syn='Adend' + str(j) + 'NMDA',
                                             wfctr=NMAMRWM)
        elif nMemInhib > 0:
            for i in xrange(0, sz - nMemInhib, 1):
                for j in lapicIDX:
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'AMPA',
                                         wfctr=AMRWM)
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'NMDA',
                                         wfctr=NMAMRWM)
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'mGLUR',
                                         wfctr=mGLURRWM)
                for i in xrange(sz - nMemInhib, sz, 1):
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'GABAss',
                                         wfctr=GARWM)
        else:
            for i in xrange(sz):
                for j in lapicIDX:
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'AMPA',
                                         wfctr=AMRWM)
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'NMDA',
                                         wfctr=NMAMRWM)
                    createNetStimsFromNQ(nqm,
                                         i,
                                         seed=j * (i + 1) * 12345,
                                         syn='Adend' + str(j) + 'mGLUR',
                                         wfctr=mGLURRWM)

    def initSigNetStims():
        for i in xrange(len(rnnsl)):
            for j in xrange(len(rnnsl[i])):
                rds = rnrds[i][j]
                sead = rnseed[i][j]
                rds.MCellRan4(sead, sead)
                rds.negexp(1)

    fihSIGns = h.FInitializeHandler(0, initSigNetStims)
    setStims()  # create the inputs based on contents of nqm
        (cells[a].soma.ina_clarke + cells[a].soma.ikrect_clarke\
        + cells[a].soma.icaN_clarke + cells[a].soma.icaL_clarke\
        + cells[a].soma.ikca_clarke + cells[a].soma.inap_clarke\
        + cells[a].soma.gl_clarke*cells[a].soma.v) / cells[a].soma.gl_clarke

        cells[a].dend.e_pas =\
        (cells[a].dend.g_pas * cells[a].dend.v) / cells[a].dend.g_pas


cells = []
N = 3
r = 50  # Radius of cell locations from origin (0,0,0) in microns
h.celsius = 37
h.v_init = -65
h.dt = 0.01
fih = h.FInitializeHandler(2, (tweak_leak, (cells, N)))

#Set up Draw
fig1 = pyplot.figure(figsize=(8, 4))
ax1a = fig1.add_subplot(2, 1, 1)
ax2a = fig1.add_subplot(2, 1, 2, sharex=ax1a)

fig2 = pyplot.figure(figsize=(5, 16))
ax1b = fig2.add_subplot(3, 1, 1)
ax2b = fig2.add_subplot(3, 1, 2, sharex=ax1b)
ax3b = fig2.add_subplot(3, 1, 3, sharex=ax1b)
ax1b.set_xlim([0, 20])
ax1b.set_ylim([0, 1])
#ax1b.set_ylim([-72,-60])

#step = 2.5e-2 #CaN