def initialize():
    '''
    initializing function, setting the membrane voltages to v_init and
    resetting all state variables
    '''
    h.finitialize(v_init)
    h.fcurrent()
def simulate(pool, tstop=50000, vinit=-55):
    ''' simulation control
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    for i in pool:
        cell = pc.gid2cell(i)
        balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    pc.set_maxstep(0.5)
    h.stdinit()
    pc.psolve(tstop)
Exemple #3
0
def DetermineStdI(leftStd, rightStd, precision_std, apc, mean, stim, tau, dt,
                  T, fr_set, seednumber):
    import neuron
    from neuron import h
    from I_proc import stimulate
    while ((rightStd - leftStd) >
           precision_std * max([abs(rightStd), abs(leftStd)])):
        if leftStd == 0 and rightStd < 1e-7:
            break
            return rightStd
        print("leftStd is %f, rightStd is %f" % (leftStd, rightStd))
        print("rightStd-leftStd: %f , precision_std: %f \n" %
              ((rightStd - leftStd), precision_std))
        h.finitialize()
        h.fcurrent()
        h.frecord_init()
        apc.n = 0
        std = (leftStd + rightStd) / 2
        print('std for test is %f' % (std))
        h.stim = stimulate([1, stim, mean, std, tau, dt, T, seednumber])
        h.tstop = T
        h.run()
        fr = apc.n / float(T / 1000)
        print('fr is %f' % (fr))
        if (fr <= fr_set):
            leftStd = std
        else:
            rightStd = std

    return std
Exemple #4
0
    def reinit(self):
        """
        This method restart simulation time to 0, reinitialize the voltage to the init value and
        clear all recorded values in Record objects (its clear inside vector for each segment
        recorded).

        After creating the Simulation object and execute the run() method for the first time
        reinit() will be called. You can also call reinit() to re-init the NEURON any time.

        No other Hoc object is removed, eg. all sections remains. If you want to remove NEURON from
        objects you can:
          * call remove_immediate_from_neuron() method on each Wrapper object (eg. Sec, Seg, NetCon)
          * call remove_immediate_from_neuron() method on each Cell object, which automatically
            removes also containing wrappers
          * delete or reassign all references to the object you want to delete

        To check how many Sections in NEURON remains check simulation.size property.
        """
        if self.check_pointers:
            self._check_point_process_pointers()
        h.fcurrent()
        h.finitialize(self.init_v * mV)

        if self.init_sleep > 0:
            print("sleep before run for: %s seconds" % self.init_sleep)
            time.sleep(self.init_sleep)

        self.warmup_done = False
        h.dt = self.dt
def simulate(pool, tstop=1000, vinit=-55):
    ''' simulation control 
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    for i in pool:
        cell = pc.gid2cell(i)
        balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    pc.set_maxstep(0.5)
    h.stdinit()
    pc.psolve(tstop)
Exemple #6
0
def FiringOnset(leftI, rightI, precision, apc, stim, T, fr_set):
    import neuron
    from neuron import h
    from I_proc import stimulate
    while ((rightI - leftI) > precision * max([abs(rightI), abs(leftI)])):
        print("leftI is %f, rightI is %f" % (leftI, rightI))
        print("rightI-leftI: %f , precision: %f \n" %
              ((rightI - leftI), precision))
        h.finitialize()
        h.fcurrent()
        h.frecord_init()
        apc.n = 0
        mean = (leftI + rightI) / 2
        print('mean is %f' % (mean))
        h.stim = stimulate([0, stim, mean])
        h.tstop = T
        h.run()
        fr = apc.n / float(T / 1000)
        print('fr is %f' % (fr))
        if (fr <= fr_set):
            leftI = mean  # If the firing rate is too small, we will replace lowerbound with middle point
        else:
            rightI = mean  # If the firing rate is too large, we will replace upperbound with middle point

    if fr_set > 0:
        return rightI
    else:
        return leftI
Exemple #7
0
def go():
    h.dt = 0.1
    h.celsius = celsius
    h.finitialize(v_init)
    #neuron.init()

    # params:        RERE,        RETCa,        ***RETCb,     TCRE,        PYPY,       PYIN,       INPYa,                     ***INPYb,                  PYRE,        PYTC,        TCPY,        TCIN
    assign_synapses(RERE * 0.2, RETCa * 0.02, RETCb * 0.04, TCRE * 0.2,
                    PYPY * 0.6, PYIN * 0.2, INPYa * gabaapercent * 0.15,
                    INPYb * gababpercent * 0.03, PYRE * 1.2, PYTC * 0.01,
                    TCPY * 1.2, TCIN * 0.4)
    #assign_synapses(gRERE_GABAA, gRETC_GABAA,  gRETC_GABAB,  gTCRE_AMPA,  gPYPY_AMPA, gPYIN_AMPA, gINPY_GABAA,               gINPY_GABAB,               gPYRE_AMPA,  gPYTC_AMPA,  gTCPY_AMPA,  gTCIN_AMPA)

    h.fcurrent()
    h.cvode.re_init()
    h.frecord_init()

    printPYinfo(0)
    printINinfo(0)
    printTCinfo(0)
    printREinfo(0)
    printWeight(0)

    field.append(0)
    while h.t < tstop:
        h.fadvance()
        field.append(xfield(230, fielddist, watchneuron))
Exemple #8
0
def make_uniform(Vrest):
    """ Makes the cell uniform. Doesn't really work for INaP yet,
    since it is way to strong it seems
    """
    nrn.t = 0

    nrn.finitialize(Vrest)
    nrn.fcurrent()

    for sec in nrn.allsec():
        for seg in sec:
            seg.e_pas = seg.v
            if nrn.ismembrane("na_ion"):
                seg.e_pas += seg.ina/seg.g_pas
            if nrn.ismembrane("k_ion"):
                seg.e_pas += seg.ik/seg.g_pas
            if nrn.ismembrane("ca_ion"):
                seg.e_pas += seg.ica/seg.g_pas
            if nrn.ismembrane("Ih_BK_prox"):
                seg.e_pas += seg.ih_Ih_BK_prox/seg.g_pas
            if nrn.ismembrane("Ih_BK_dist"):
                seg.e_pas += seg.ih_Ih_BK_dist/seg.g_pas
            if nrn.ismembrane("Ih_BK_prox_frozen"):
                seg.e_pas += seg.ih_Ih_BK_prox_frozen/seg.g_pas
            if nrn.ismembrane("Ih_BK_dist_frozen"):
                seg.e_pas += seg.ih_Ih_BK_dist_frozen/seg.g_pas
Exemple #9
0
  def initialize():
      global Epas
      h.celsius = celsius
      for sec in h.soma:
          h.distance()    
 
      for sec in h.allsec():
          sec.v = Epas
          sec.e_pas = Epas
  
          sec.insert("pas")
          sec.e_pas = Epas
          sec.g_pas = 1/Rm
          sec.Ra = rall
          sec.cm = cap
          sec.gnabar_hh2 = 0 
          sec.gkbar_hh2 = 0
          dist = h.distance(0.5)
          # sec.gcabar_it2 = gcat_func(dist)
          sec.gcabar_it2 = gcat
      for sec in h.soma:
          sec.gnabar_hh2 = gna 
          sec.gkbar_hh2 = gkdr
          # sec.gcabar_it2 = 0.1054*gcat
          sec.gcabar_it2 = gcat
                                                                           
      h.finitialize()       
      h.fcurrent()     
      cvode.re_init()
Exemple #10
0
  def initialize(Tdist):
      global Epas
      h.celsius = celsius
      for sec in h.soma:
          h.distance()    
 
      for sec in h.allsec():
          sec.v = Epas
          sec.e_pas = Epas
          sec.insert("pas")
          sec.e_pas = Epas
          sec.g_pas = 1/Rm
          sec.Ra = rall
          sec.cm = cap
          sec.gnabar_hh2 = 0 
          sec.gkbar_hh2 = 0
          for seg in sec:
              if Tdist == 1:
                  seg.gcabar_it2 = gcat
              if Tdist == 2:
                  seg.gcabar_it2 = gcat * (1 + 0.04 * (h.distance(0) + sec.L * seg.x)) * 0.10539397661220173
              
      for sec in h.soma:
          sec.gnabar_hh2 = gna 
          sec.gkbar_hh2 = gkdr
          if Tdist == 1:
              seg.gcabar_it2 = gcat
          if Tdist == 2:
              seg.gcabar_it2 = gcat * 0.10539397661220173
                                                                           
      h.finitialize()       
      h.fcurrent()     
      cvode.re_init()
def test_cells_default():
    """Test default cell objects."""
    load_custom_mechanisms()

    with pytest.raises(ValueError, match='Unknown pyramidal cell type'):
        l5p = pyramidal(pos=(0, 0, 0), cell_name='blah')

    l5p = pyramidal(pos=(0, 0, 0), cell_name='L5Pyr')
    assert len(l5p.sections) == 9
    assert 'apical_2' in l5p.sections

    # smoke test to check if cell can be used in simulation
    h.load_file("stdrun.hoc")
    h.tstop = 40
    h.dt = 0.025
    h.celsius = 37

    vsoma = l5p.rec_v.record(l5p.sections['soma'](0.5)._ref_v)
    times = h.Vector().record(h._ref_t)

    stim = h.IClamp(l5p.sections['soma'](0.5))
    stim.delay = 5
    stim.dur = 5.
    stim.amp = 2.

    h.finitialize()
    h.fcurrent()
    h.run()

    times = times.to_python()
    vsoma = vsoma.to_python()
    assert len(times) == len(vsoma)

    with pytest.raises(ValueError, match='Unknown basket cell type'):
        l5p = basket(pos=(0, 0, 0), cell_name='blah')
 def initialise(self, vrest=-65):
     """
     Initialise the model, to launch before each simulations
     """
     for sec in h.allsec():
         h.finitialize(vrest, sec)
         h.fcurrent(sec)
     h.frecord_init()
Exemple #13
0
def runsim():
    t0 = time.time()  # clock start time

    pc.set_maxstep(
        10)  # sets the default max solver step in ms (purposefully large)

    for elec in lelec:
        elec.setup()
        elec.LFPinit()

    h.finitialize(
    )  # initialize cells to -65 mV, after all the NetCon delays have been specified
    if pcID == 0:
        for tt in range(0, int(h.tstop), printdt):
            h.cvode.event(tt, prsimtime)  # print time callbacks

    h.fcurrent()
    h.frecord_init(
    )  # set state variables if they have been changed since h.finitialize
    pc.psolve(h.tstop)  # actual simulation - run the solver
    pc.barrier()

    # these calls aggregate data across procs/nodes
    pc.allreduce(dp_rec_L2, 1)
    pc.allreduce(
        dp_rec_L5,
        1)  # combine dp_rec on every node, 1=add contributions together
    for elec in lelec:
        elec.lfp_final()
    net.aggregate_currents(
    )  # aggregate the currents independently on each proc
    # combine net.current{} variables on each proc
    pc.allreduce(net.current['L5Pyr_soma'], 1)
    pc.allreduce(net.current['L2Pyr_soma'], 1)

    pc.barrier()

    # write time and calculated dipole to data file only if on the first proc
    # only execute this statement on one proc
    savedat(p, pcID, t_vec, dp_rec_L2, dp_rec_L5, net)

    for elec in lelec:
        print('end; t_vec.size()', t_vec.size(), 'elec.lfp_t.size()',
              elec.lfp_t.size())

    if pcID == 0:
        if debug: print("Simulation run time: %4.4f s" % (time.time() - t0))
        if debug: print("Simulation directory is: %s" % ddir.dsim)
        if paramrw.find_param(doutf['file_param'],
                              'save_spec_data') or usingOngoingInputs(
                                  doutf['file_param']):
            runanalysis(p, doutf['file_param'], doutf['file_dpl_norm'],
                        doutf['file_spec'])  # run spectral analysis
        if paramrw.find_param(doutf['file_param'], 'save_figs'):
            savefigs(ddir, p, p_exp)  # save output figures

    pc.barrier()  # make sure all done in case multiple trials
Exemple #14
0
def run_single_simulation(config, interactive):
    axon = Axon(config)
    axon.insert_stim(config['stim_position'], config['stim_amplitude'],
            config['stim_start_time'], config['stim_duration'])

    # set up recording vectors for python plots and the csv file
    t = h.Vector()
    t.record(h._ref_t)

    num_v_traces = config['num_v_traces']
    v_traces = []
    for i in range(num_v_traces):
        v = h.Vector()
        v.record(axon.section_at_f(
            # record at num_v_traces points along the axon, equally spaced
            # from eachother and from the end points (since we don't care
            # about things like the impedance mismatch at the ends)
            (i + 1) * 1.0 / (num_v_traces + 1))
            (Axon.middle)._ref_v)
        v_traces.append(v)

    # set up NEURON plotting code (if we're in an interactive session)
    if interactive:
        g = h.Graph()
        g.size(0, config['integration_time'], -80, 55)
        for i in range(num_v_traces):
            g.addvar('v(0.5)',
                    sec=axon.section_at_f((i+1) * 1.0 / (num_v_traces + 1)))

    # initialize the simulation
    h.dt = config['max_time_step']
    tstop = config['integration_time']
    h.finitialize(config['initial_membrane_potential'])
    h.fcurrent()

    # run the simulation
    if interactive:
        g.begin()
        while h.t < tstop:
            h.fadvance()
            g.plot(h.t)
        g.flush()
    else:
        while h.t < tstop:
            h.fadvance()

    # save the data as a csv
    with open(config['csv_filename'], 'w') as csv_file:
        # start with a header of the form "t_ms, V0_mV, V1_mv, V2_mV,..."
        csv_file.write(", ".join(
            ["t_ms"] + ["V{0}_mV".format(i) for i in range(num_v_traces)]
            ) + "\n")

        # write the time and each of the recorded voltages at that time
        for row in zip(t, *v_traces):
            csv_file.write(", ".join([str(x) for x in row]) + "\n")
Exemple #15
0
    def i_currents(self, V):
        """
        For the steady-state case, return the total current at voltage V
        Used to find the zero current point
        vrange brackets the interval
        Implemented here are the basic known mechanisms. If you add or need
        more mechanisms, they either need to be accomadated in this routine,
        or this routine needs to be implemented (overridden) in the
        specific cell class. 
        
        """
        for part in self.all_sections.keys():
            for sec in self.all_sections[part]:
                sec.v = V
        h.celsius = self.status['temperature']
        h.t = 0.
        h.finitialize(V)
        h.fcurrent()
        self.ix = {}

        if 'na' in self.mechanisms:
            #print dir(self.soma().na)
            try:
                self.ix['na'] = self.soma().na.gna*(V - self.soma().ena)
            except:
                self.ix['na'] = self.soma().nav11.gna*(V - self.soma().ena)
        if 'jsrna' in self.mechanisms:
            self.ix['jsrna'] = self.soma().jsrna.gna*(V - self.soma().ena)
        if 'nav11' in self.mechanisms:
            self.ix['nav11'] = self.soma().nav11.gna*(V - self.soma().ena)
        if 'nacn' in self.mechanisms:
            self.ix['nacn'] = self.soma().nacn.gna*(V - self.soma().ena)
        if 'nacncoop' in self.mechanisms:
            self.ix['nacncoop'] = self.soma().nacncoop.gna*(V - self.soma().ena)
        if 'klt' in self.mechanisms:
            self.ix['klt'] = self.soma().klt.gklt*(V - self.soma().ek)
        if 'kht' in self.mechanisms:
            self.ix['kht'] = self.soma().kht.gkht*(V - self.soma().ek)
        if 'ka' in self.mechanisms:
            self.ix['ka'] = self.soma().ka.gka*(V - self.soma().ek)
        if 'ihvcn' in self.mechanisms:
            self.ix['ihvcn'] = self.soma().ihvcn.gh*(V - self.soma().ihvcn.eh)
        if 'hcno' in self.mechanisms:
            raise ValueError('HCNO is not supported - use hcnobo instead')
            #self.ix['hcno'] = self.soma().hcno.gh*(V - self.soma().hcno.eh)
        if 'hcnobo' in self.mechanisms:
            self.ix['hcnobo'] = self.soma().hcnobo.gh*(V - self.soma().hcnobo.eh)
        if 'leak' in self.mechanisms:
            self.ix['leak'] = self.soma().leak.gbar*(V - self.soma().leak.erev)
#        print self.status['name'], self.status['type'], V, self.ix
        isum = np.sum([self.ix[i] for i in self.ix])
#        print 'conductances: ', self.ix.keys()
#        print 'V, isum, values: ', V, isum, [self.ix[i] for i in self.ix]
        return isum
Exemple #16
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
Exemple #17
0
def simulate(cell, tstop=400, vinit=-55):
    ''' simulation control
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    h.run()
    if cell.numofmodel == 9 or cell.numofmodel == 10 or cell.numofmodel == 12:
        running_ = 1
        if cell.numofmodel == 9:
            dl = 0
            d_t = 60000
        elif cell.numofmodel == 10:
            dl = 1000
            d_t = 40
        else:
            dl = 800
            d_t = 10
        h.stdinit()
        for n in range(3):
            cell.x_application = cell.x_application + dl
            if n == 0:
                cell.dl = 5000
                cell.x_application = 0
                print(cell.x_application)
            else:
                cell.dl = 30050
                cell.x_application = -400
            cell.distance()
            for item in cell.diffs:
                item.tx1 = h.t + 5
                # item.initial = 0#item.atp
                # if n == 0:
                #     item.c0cleft = 0.01#item.c0cleft
                # else:
                item.c0cleft = item.c0cleft
                item.h = cell.distances.get(cell.diffusions.get(item))
            h.continuerun(h.t + d_t)
        h.continuerun(h.t + 500)
Exemple #18
0
def test_cells_default():
    """Test default cell objects."""
    load_custom_mechanisms()

    with pytest.raises(ValueError, match='Unknown pyramidal cell type'):
        l5p = pyramidal(cell_name='blah')

    l5p = pyramidal(cell_name='L5Pyr')
    l5p.build(sec_name_apical='apical_trunk')
    assert len(l5p.sections) == 9
    assert 'apical_2' in l5p.sections

    # check that after building, the vertical sections have the length
    # specified in get_L5Pyr_params_default (or overriden in a params file).
    # Note that the lengths implied by _secs_L5Pyr are completely ignored:
    # NEURON extends the sections as needed to match the sec.L 's
    vertical_secs = [
        'basal_1', 'soma', 'apical_trunk', 'apical_1', 'apical_2',
        'apical_tuft'
    ]
    for sec_name in vertical_secs:
        sec = l5p._nrn_sections[sec_name]
        vert_len = np.abs(sec.z3d(1) - sec.z3d(0))
        assert np.allclose(vert_len, sec.L)

    # smoke test to check if cell can be used in simulation
    h.load_file("stdrun.hoc")
    h.tstop = 40
    h.dt = 0.025
    h.celsius = 37

    vsoma = l5p.rec_v.record(l5p._nrn_sections['soma'](0.5)._ref_v)
    times = h.Vector().record(h._ref_t)

    stim = h.IClamp(l5p._nrn_sections['soma'](0.5))
    stim.delay = 5
    stim.dur = 5.
    stim.amp = 2.

    h.finitialize()
    h.fcurrent()
    h.run()

    times = times.to_python()
    vsoma = vsoma.to_python()
    assert len(times) == len(vsoma)

    with pytest.raises(ValueError, match='Unknown basket cell type'):
        l5p = basket(cell_name='blah')
Exemple #19
0
    def min_sim(self):
        """
        Launch a minimal simulation to test the model and determine its
        resting potential empirically
        """
        for sec in h.allsec():
            h.finitialize(-65, sec)
            h.fcurrent(sec)
        h.frecord_init()

        while h.t < 200:  # Launch a simulation
            h.fadvance()

        # Record the soma voltage after this minimal stimulation to find v_rest
        soma = getattr(h,   "soma")
        self.vrest = getattr(soma,   "v")
Exemple #20
0
 def init(self):
     """Set the vm_init from the spin button and prepare the simulator"""
     
     if not self.manager.refs.has_key('VecRef') :
         logger.info("No vector Created. Create at least one vector to run the simulation")
         return False
     else:
         v_init = self.ui.vSpinBox.value()
         # Set the v_init
         h.v_init = v_init
         h.finitialize(v_init)
         h.fcurrent()
     
         # Reset the time in the GUI
         self.ui.time_label.setNum(h.t)
         return True
    def min_sim(self, TSTOP=100):
        """
        Launch a minimal simulation to test the model and determine its resting potential empirically
        """
        vrec = h.Vector()
        vrec.record(self.soma(0.5)._ref_v)

        for sec in h.allsec():
            h.finitialize(-65, sec)
            h.fcurrent(sec)
        h.frecord_init()

        while h.t < TSTOP: #Launch a simulation
            h.fadvance()

        vrest = np.array(vrec)[-1]

        return vrest
Exemple #22
0
 def init(self):
     """Set the vm_init from the spin button and prepare the simulator"""
     
     if not self.manager.refs.has_key('VecRef') :
         message = "No vector Created. Create at least one vector to run the simulation"
         logger.info(message)
         self.ui.statusbar.showMessage(message, 3500)
         return False
     else:
         v_init = self.ui.vSpinBox.value()
         # Set the v_init
         h.v_init = v_init
         h.finitialize(v_init)
         h.fcurrent()
     
         # Reset the time in the GUI
         self.ui.time_label.setNum(h.t)
         return True
Exemple #23
0
    def toggleStim(self):
        ''' Toggle stim state (ON -> OFF or OFF -> ON) and set appropriate next toggle event. '''
        # OFF -> ON at pulse onset
        if not self._stim:
            self._stim = self.setStimON(True)
            self.cvode.event(h.t + self._pulseWidth, self.toggleStim)
        # ON -> OFF at pulse offset
        else:
            self._stim = self.setStimON(False)
            self.cvode.event(
                h.t + self._stimulationInterval - self._pulseWidth,
                self.toggleStim)

        # Re-initialize cvode if active, otherwise update currents
        if self.cvode.active():
            self.cvode.re_init()
        else:
            h.fcurrent()
    def current_balancein(self):
        """ This is a translation from Poirazi's current-balancein.hoc code
        """
        h.finitialize(-48.9)  # min 42
        #        h.finitialize(-70.7)
        h.fcurrent()

        for sec in self.all:
            if h.ismembrane('na_ion'):
                sec.e_pas = sec.v + sec.ina / sec.g_pas
            if h.ismembrane('k_ion'):
                sec.e_pas = sec.e_pas + sec.ik / sec.g_pas
            if h.ismembrane('ca_ion'):
                sec.e_pas = sec.e_pas + sec.ica / sec.g_pas
            if h.ismembrane('h'):
                sec.e_pas = sec.e_pas + sec.ihi / sec.g_pas

        h.fcurrent()
Exemple #25
0
def is_blocked(axon):
    v = h.Vector()
    v.record(axon.section_at_x(axon.config['block_test_position'])
        (Axon.middle)._ref_v)

    # initialize the simulation
    h.dt = axon.config['max_time_step']
    tstop = axon.config['integration_time']
    v_init = axon.config['initial_membrane_potential']
    h.finitialize(v_init)
    h.fcurrent()

    # run the simulation
    while h.t < tstop:
        h.fadvance()

    if max(v) >= axon.config['block_test_threshold']:
        return False
    else:
        return True
Exemple #26
0
def simulate(cell, tstop=500, vinit=-60):
    ''' simulation control
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    h.run()
def simulate(cell, tstop=1500, vinit=-55):
    ''' simulation control 
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    h.run()
Exemple #28
0
 def init_pas(self, v_init, set_pas = False):
     e = {}
     h.finitialize(v_init)
     h.fcurrent()
     i_net = 0
     lgg.info("fcurrent() values (%s mV)" %(v_init))
     for sec in self.secs:
         for mech in sec.mechs:
             for ion in sec.ions:
                 try:
                     i = getattr(sec.sec, 'i%s_%s' %(ion, mech))
                     lgg.info("(%s)->%s:->%s=%s mA/cm2" %(sec.name, mech, ion, i))
                     i_net += i
                 except: pass
         lgg.info("(%s)->i_net = %s" %(sec.name, i_net))
         try:
             e_pas = sec.sec.v + i_net / sec.g_pas
             lgg.info("(%s)->e_pas calculated at %s mV" %(e_pas))
             if set_pas:
                 sec.sec.e_pas = e_pas
         except: pass
Exemple #29
0
def init(cell, glia, vinit=-70, vglia=-88):
    ''' simulation control 
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize()
    for sec in cell.all:
        sec.v = vinit
    for sec in glia.all:
        sec.v = vglia
        sec.nai = setnag_accum
        sec.ki = setkg_accum
        sec.cli = setclg_accum
        sec.ai = setag_accum

    h.fcurrent()
Exemple #30
0
def pythonsim(simid, rundir, inputdir, modeldir, outputdir, currentstr, vinitstr, delaystr, stimdurationstr, timestepstr, simstopstr, recordintervalstr):
	import neuron
	from neuron import h
	Section = h.Section

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

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

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

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

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

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

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

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

	# Shutdown
	testt.printf(timefile, '%f\n')
	testv.printf(voltagefile, '%f\n')
	timefile.close()
	voltagefile.close()
	return(0)
def _simulate_single_trial(neuron_net, trial_idx):
    """Simulate one trial."""

    from .dipole import Dipole

    global _PC, _CVODE

    h.load_file("stdrun.hoc")

    rank = _get_rank()
    nhosts = _get_nhosts()

    # Now let's simulate the dipole

    _PC.barrier()  # sync for output to screen
    if rank == 0:
        print("running trial %d on %d cores" %
              (trial_idx + 1, nhosts))

    # Set tstop before instantiating any classes
    h.tstop = neuron_net.net.params['tstop']
    h.dt = neuron_net.net.params['dt']  # simulation duration and time-step
    h.celsius = neuron_net.net.params['celsius']  # 37.0 - set temperature

    times = neuron_net.net.cell_response.times

    # sets the default max solver step in ms (purposefully large)
    _PC.set_maxstep(10)

    # initialize cells to -65 mV, after all the NetCon
    # delays have been specified
    h.finitialize()

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

    if rank == 0:
        for tt in range(0, int(h.tstop), 10):
            _CVODE.event(tt, simulation_time)

    h.fcurrent()

    # initialization complete, but wait for all procs to start the solver
    _PC.barrier()

    # actual simulation - run the solver
    _PC.psolve(h.tstop)

    _PC.barrier()

    # these calls aggregate data across procs/nodes
    neuron_net.aggregate_data()
    _PC.allreduce(neuron_net.dipoles['L5_pyramidal'], 1)
    _PC.allreduce(neuron_net.dipoles['L2_pyramidal'], 1)

    # aggregate the currents and voltages independently on each proc
    vsoma_list = _PC.py_gather(neuron_net._vsoma, 0)
    isoma_list = _PC.py_gather(neuron_net._isoma, 0)

    # combine spiking data from each proc
    spike_times_list = _PC.py_gather(neuron_net._spike_times, 0)
    spike_gids_list = _PC.py_gather(neuron_net._spike_gids, 0)

    # only rank 0's lists are complete

    if rank == 0:
        for spike_vec in spike_times_list:
            neuron_net._all_spike_times.append(spike_vec)
        for spike_vec in spike_gids_list:
            neuron_net._all_spike_gids.append(spike_vec)
        for vsoma in vsoma_list:
            neuron_net._vsoma.update(vsoma)
        for isoma in isoma_list:
            neuron_net._isoma.update(isoma)

    _PC.barrier()  # get all nodes to this place before continuing

    dpl_data = np.c_[np.array(neuron_net.dipoles['L2_pyramidal'].to_python()) +
                     np.array(neuron_net.dipoles['L5_pyramidal'].to_python()),
                     np.array(neuron_net.dipoles['L2_pyramidal'].to_python()),
                     np.array(neuron_net.dipoles['L5_pyramidal'].to_python())]

    dpl = Dipole(times, dpl_data)

    return dpl
Exemple #32
0
for i_syn in range(N_RHESYN):
	print i_syn
	h(DEND_IDS[i_syn]+' ActiveDendrites.append()') # fill in the section list
	h('RHESYN['+str(i_syn)+'] = new Spine()') # instantiation of the Spine template
	h('RHESYN['+str(i_syn)+'].neck RHESpines.append()') # neck added to the section list
	h('RHESYN['+str(i_syn)+'].spine RHESpines.append()') # spine added to the section list
	h(DEND_IDS[i_syn]+' connect RHESYN['+str(i_syn)+'].neck(1), '+RHESYN_POSITIONS[i_syn]+' ') # connection to the dendrite
	h('RHESYN['+str(i_syn)+'].spine I_RHESYN['+str(i_syn)+'] = new IClamp(0)') # instatiation of the IClamp
	h('I_RHESYN['+str(i_syn)+'].del = 0') # always on
	h('I_RHESYN['+str(i_syn)+'].dur = 1e12') # never stops
          
#initialization of neuron
h.dt =stepsize
h('Vrest = -74.25')
h.finitialize(h.Vrest)
h.fcurrent()

now=time.localtime(time.time())
filename="NRN"+time.strftime("%y%m%d%H%M",now) + ".dat"
file =open(filename,'w')

ct = 0

plotA = False
# plot branches
if (plotA):
	h('objref s')
	h('s = new Shape()')
	h('s = fast_flush_list.object(fast_flush_list.count()-1)')
#	h('fast_flush_list.append(s)')
	h('s.view(-50,-150,500,550,1680,0,840,1050) //view(mleft, mbottom, mwidth, mheight, sleft, stop,swidth, sheight)')
Exemple #33
0
def _simulate_single_trial(net):
    """Simulate one trial."""
    from .parallel import rank, nhosts, pc, cvode
    from neuron import h
    h.load_file("stdrun.hoc")

    # Now let's simulate the dipole
    if rank == 0:
        print("running on %d cores" % nhosts)

    # global variables, should be node-independent
    h("dp_total_L2 = 0.")
    h("dp_total_L5 = 0.")

    # Set tstop before instantiating any classes
    h.tstop = net.params['tstop']
    h.dt = net.params['dt']  # simulation duration and time-step
    h.celsius = net.params['celsius']  # 37.0 - set temperature

    # We define the arrays (Vector in numpy) for recording the signals
    t_vec = h.Vector()
    t_vec.record(h._ref_t)  # time recording
    dp_rec_L2 = h.Vector()
    dp_rec_L2.record(h._ref_dp_total_L2)  # L2 dipole recording
    dp_rec_L5 = h.Vector()
    dp_rec_L5.record(h._ref_dp_total_L5)  # L5 dipole recording

    net.move_cells_to_pos()  # position cells in 2D grid

    # sets the default max solver step in ms (purposefully large)
    pc.set_maxstep(10)

    # initialize cells to -65 mV, after all the NetCon
    # delays have been specified
    h.finitialize()

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

    printdt = 10
    if rank == 0:
        for tt in range(0, int(h.tstop), printdt):
            cvode.event(tt, prsimtime)  # print time callbacks

    h.fcurrent()
    # set state variables if they have been changed since h.finitialize
    h.frecord_init()
    # actual simulation - run the solver
    pc.psolve(h.tstop)

    pc.barrier()

    # these calls aggregate data across procs/nodes
    pc.allreduce(dp_rec_L2, 1)
    # combine dp_rec on every node, 1=add contributions together
    pc.allreduce(dp_rec_L5, 1)
    # aggregate the currents independently on each proc
    net.aggregate_currents()
    # combine net.current{} variables on each proc
    pc.allreduce(net.current['L5Pyr_soma'], 1)
    pc.allreduce(net.current['L2Pyr_soma'], 1)

    pc.barrier()  # get all nodes to this place before continuing

    dpl_data = np.c_[np.array(dp_rec_L2.to_python()) +
                     np.array(dp_rec_L5.to_python()),
                     np.array(dp_rec_L2.to_python()),
                     np.array(dp_rec_L5.to_python())]

    pc.gid_clear()
    pc.done()
    dpl = Dipole(np.array(t_vec.to_python()), dpl_data)
    if rank == 0:
        if net.params['save_dpl']:
            dpl.write('rawdpl.txt')

        dpl.baseline_renormalize(net.params)
        dpl.convert_fAm_to_nAm()
        dpl.scale(net.params['dipole_scalefctr'])
        dpl.smooth(net.params['dipole_smooth_win'] / h.dt)
    return dpl, net.spiketimes.to_python(), net.spikegids.to_python()
def initialize():
	h.finitialize()
	h.fcurrent()
Exemple #35
0
def _simulate_single_trial(net, tstop, dt, trial_idx):
    """Simulate one trial including building the network

    This is used by both backends. MPIBackend calls this in mpi_child.py, once
    for each trial (blocking), and JoblibBackend calls this for each trial
    (non-blocking)
    """

    neuron_net = NetworkBuilder(net, trial_idx=trial_idx)

    global _PC, _CVODE

    h.load_file("stdrun.hoc")

    rank = _get_rank()
    nhosts = _get_nhosts()

    # Now let's simulate the dipole

    _PC.barrier()  # sync for output to screen
    if rank == 0:
        print("running trial %d on %d cores" % (trial_idx + 1, nhosts))

    # Set tstop before instantiating any classes
    h.tstop = tstop
    h.dt = dt  # simulation duration and time-step
    h.celsius = net._params['celsius']  # 37.0 - set temperature

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

    # sets the default max solver step in ms (purposefully large)
    _PC.set_maxstep(10)

    # initialize cells to -65 mV, after all the NetCon
    # delays have been specified
    h.finitialize()

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

    if rank == 0:
        for tt in range(0, int(h.tstop), 10):
            _CVODE.event(tt, simulation_time)

    h.fcurrent()

    # initialization complete, but wait for all procs to start the solver
    _PC.barrier()

    # actual simulation - run the solver
    _PC.psolve(h.tstop)

    _PC.barrier()

    # these calls aggregate data across procs/nodes
    neuron_net.aggregate_data()

    # now convert data from Neuron into Python
    vsoma_py = dict()
    for gid, rec_v in neuron_net._vsoma.items():
        vsoma_py[gid] = rec_v.to_python()

    isoma_py = dict()
    for gid, rec_i in neuron_net._isoma.items():
        isoma_py[gid] = {
            key: rec_i.to_python()
            for key, rec_i in rec_i.items()
        }

    dpl_data = np.c_[neuron_net._nrn_dipoles['L2_pyramidal'].as_numpy() +
                     neuron_net._nrn_dipoles['L5_pyramidal'].as_numpy(),
                     neuron_net._nrn_dipoles['L2_pyramidal'].as_numpy(),
                     neuron_net._nrn_dipoles['L5_pyramidal'].as_numpy()]

    rec_arr_py = dict()
    rec_times_py = dict()
    for arr_name, nrn_arr in neuron_net._nrn_rec_arrays.items():
        rec_arr_py.update({arr_name: nrn_arr._get_nrn_voltages()})
        rec_times_py.update({arr_name: nrn_arr._get_nrn_times()})

    data = {
        'dpl_data': dpl_data,
        'spike_times': neuron_net._all_spike_times.to_python(),
        'spike_gids': neuron_net._all_spike_gids.to_python(),
        'gid_ranges': net.gid_ranges,
        'vsoma': vsoma_py,
        'isoma': isoma_py,
        'rec_data': rec_arr_py,
        'rec_times': rec_times_py,
        'times': times.to_python()
    }

    return data
def initialize(v):
	h.finitialize(v)
	h.fcurrent()
Exemple #37
0
 def initialize():
     """ Initialize the simulation for the first time step """
     h.finitialize(h.v_init)
     h.fcurrent()
def _simulate_single_trial(neuron_net, trial_idx):
    """Simulate one trial."""

    from .dipole import Dipole

    global _PC, _CVODE

    h.load_file("stdrun.hoc")

    rank = _get_rank()
    nhosts = _get_nhosts()

    # Now let's simulate the dipole

    _PC.barrier()  # sync for output to screen
    if rank == 0:
        print("running trial %d on %d cores" % (trial_idx + 1, nhosts))

    # create or reinitialize scalars in NEURON (hoc) context
    h("dp_total_L2 = 0.")
    h("dp_total_L5 = 0.")

    # Set tstop before instantiating any classes
    h.tstop = neuron_net.net.params['tstop']
    h.dt = neuron_net.net.params['dt']  # simulation duration and time-step
    h.celsius = neuron_net.net.params['celsius']  # 37.0 - set temperature

    # We define the arrays (Vector in numpy) for recording the signals
    t_vec = h.Vector()
    t_vec.record(h._ref_t)  # time recording
    dp_rec_L2 = h.Vector()
    dp_rec_L2.record(h._ref_dp_total_L2)  # L2 dipole recording
    dp_rec_L5 = h.Vector()
    dp_rec_L5.record(h._ref_dp_total_L5)  # L5 dipole recording

    # sets the default max solver step in ms (purposefully large)
    _PC.set_maxstep(10)

    # initialize cells to -65 mV, after all the NetCon
    # delays have been specified
    h.finitialize()

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

    if rank == 0:
        for tt in range(0, int(h.tstop), 10):
            _CVODE.event(tt, simulation_time)

    h.fcurrent()

    # initialization complete, but wait for all procs to start the solver
    _PC.barrier()

    # actual simulation - run the solver
    _PC.psolve(h.tstop)

    _PC.barrier()

    # these calls aggregate data across procs/nodes
    _PC.allreduce(dp_rec_L2, 1)
    # combine dp_rec on every node, 1=add contributions together
    _PC.allreduce(dp_rec_L5, 1)
    # aggregate the currents independently on each proc
    neuron_net.aggregate_currents()
    # combine neuron_net.current{} variables from each proc
    _PC.allreduce(neuron_net.current['L5Pyr_soma'], 1)
    _PC.allreduce(neuron_net.current['L2Pyr_soma'], 1)

    # combine spiking data from each proc
    spiketimes_list = _PC.py_gather(neuron_net._spiketimes, 0)
    spikegids_list = _PC.py_gather(neuron_net._spikegids, 0)
    # only rank 0's lists are complete

    if rank == 0:
        for spike_vec in spiketimes_list:
            neuron_net._all_spiketimes.append(spike_vec)
        for spike_vec in spikegids_list:
            neuron_net._all_spikegids.append(spike_vec)

    _PC.barrier()  # get all nodes to this place before continuing

    dpl_data = np.c_[np.array(dp_rec_L2.to_python()) +
                     np.array(dp_rec_L5.to_python()),
                     np.array(dp_rec_L2.to_python()),
                     np.array(dp_rec_L5.to_python())]

    dpl = Dipole(np.array(t_vec.to_python()), dpl_data)
    if rank == 0:
        if neuron_net.net.params['save_dpl']:
            dpl.write('rawdpl.txt')

        dpl.baseline_renormalize(neuron_net.net.params)
        dpl.convert_fAm_to_nAm()
        dpl.scale(neuron_net.net.params['dipole_scalefctr'])
        dpl.smooth(neuron_net.net.params['dipole_smooth_win'] / h.dt)

    return dpl
def initialize_rest():
	h.finitialize(-65)
	h.fcurrent()