Ejemplo n.º 1
0
    def run(self, temp=34.0, dt=0.025, seed=575982035, simulator=None):
        preCell = cells.DummySGC(cf=4000, sr=2)
        postCell = cells.Bushy.create()
        synapse = preCell.connect(postCell)
        self.pre_cell = preCell
        self.post_cell = postCell
        self.synapse = synapse

        self.stim = sound.TonePip(rate=100e3,
                                  duration=0.1,
                                  f0=4000,
                                  dbspl=80,
                                  ramp_duration=2.5e-3,
                                  pip_duration=0.04,
                                  pip_start=[0.02])

        preCell.set_sound_stim(self.stim, seed=seed, simulator=simulator)

        self['vm'] = postCell.soma(0.5)._ref_v
        #self['prevm'] = preCell.soma(0.5)._ref_v
        for i in range(30):
            self['xmtr%d' % i] = synapse.terminal.relsite._ref_XMTR[i]
            synapse.terminal.relsite.Dep_Flag = False
        self['t'] = h._ref_t

        h.tstop = 100.0  # duration of a run
        h.celsius = temp
        h.dt = dt

        custom_init()
        h.run()
Ejemplo n.º 2
0
def init_model(cell, mode='iclamp', vinit=-65., restore_from_file=False, filename=None, electrode_site=None, reinit=False):
    """
    Model initialization procedure to set RMP to the resting RMP of the model cell.
    Does not instantiate recording or stimulating.
    
    Params
    ------
    cell : cell, including hoc_reader file object (as .hr)
    mode : str (default: iclamp)
        mode string ('iclamp', 'vc', 'vclamp'). 
    vinit : float
        initial voltage to start initialization, in mV. Default -65 mV
    restore_from_file : boolean
        flag to cause model to be restored from previously saved state file.
        The state file must be from the same model construction that exists at the
        time of the call to init_model.
    filename : str (default: None)
        Name of a state file to restore the initial conditions from
    electrode_site : NEURON section object (default: None)
        Site for the recording electrode to be located
    reinit : boolean (default: False)
        If restoring from file, setting reinit to True will also force a reinitialization.
    
    Returns
    -------
    boolean : Success of initialization. Always True, just to indicate we were called.
        Errors result in exceptions.
    
    """
    print('initmodel')
    if mode in ['vc', 'vclamp']:
        cell.hr.h.finitialize(vinit)  # this is sufficient for initialization in voltage clamp
        print('vclamp')
        return True
    if mode not in ['iclamp']:
        raise ValueError('Mode must be "vc", "vclamp" or "iclamp"; got %s' % mode)

    # otherwise we are in current clamp
    # get state if one is specified
    if restore_from_file:
        print('restore: ', filename)
        restore_initial_conditions_state(cell, electrode_site=electrode_site, filename=filename, reinit=reinit)
        try:
            print('init?: ')
            cell.hr.h.frecord_init()  # try an intialization
        except:
            raise ValueError('Unable to restore initial state')
        print('init OK')
        return True  # much easier here...
    
    print('custom init')
    CU.custom_init(v_init=vinit)
    
    if electrode_site is not None:
        vm = electrode_site.v
    else:
        vm = 0.
    print('Initialized with finitialize, starting at %8.2f, ending %8.2f ' % (vinit, vm))
    return True
Ejemplo n.º 3
0
print( 'build vectors')
res = {}
res['v_soma'] = h.Vector()
res['v_soma'].record(soma(0.5)._ref_v)
res['i_inj'] = h.Vector()
res['i_inj'].record(vstim._ref_i)
res['time'] = h.Vector()
res['time'].record(h._ref_t)
res['delec'] = h.Vector()
res['delec'].record(dends[-1](0.5)._ref_v)

print( 'init')
h.dt = 0.025

custom_init(v_init=-65)
h.finitialize()
h.tstop = np.max(stimtimes) + tipi
h.t = 0.
while h.t < h.tstop:
        h.fadvance()
# h.batch_save() # save nothing
# h.batch_run(h.tstop, h.dt, "dend.dat")
fig, ax = mpl.subplots(4, 1, figsize=(5, 10))

ax = ax.ravel()
ax[0].plot(res['time'], res['i_inj'])
for i in range(nsyn):
    it0 = np.argmin(np.fabs(np.array(res['time']) - (5+i*tipi)))
    it1 = np.argmin(np.fabs(np.array(res['time']) - (5+i*tipi + tipi/2.)))
    print( it0, it1)
Ejemplo n.º 4
0
    def run(self, pre_sec, post_sec, n_synapses, temp=34.0, dt=0.025, 
            vclamp=40.0, iterations=1, tstop=240.0, stim_params=None, synapsetype='multisite', **kwds):
        """ 
        Basic synapse test. Connects sections of two cells with *n_synapses*.
        The cells are allowed to negotiate the details of the connecting 
        synapse. The presynaptic soma is then driven with a pulse train
        followed by a recovery pulse of varying delay.
        
        *stim_params* is an optional dictionary with keys 'NP', 'Sfreq', 'delay',
        'dur', 'amp'.
        
        Analyses:
        
        * Distribution of PSG amplitude, kinetics, and latency
        * Synaptic depression / facilitation and recovery timecourses
        """
        Protocol.run(self, **kwds)
        
        pre_cell = cells.cell_from_section(pre_sec)
        post_cell = cells.cell_from_section(post_sec)
        synapses = []
        for i in range(n_synapses):
            synapses.append(pre_cell.connect(post_cell, type=synapsetype))
        
        self.synapses = synapses
        self.pre_sec = synapses[0].terminal.section
        self.post_sec = synapses[0].psd.section
        self.pre_cell = pre_cell
        self.post_cell = post_cell
        self.plots={}  # store plot information here
        #
        # voltage clamp the target cell
        #
        clampV = vclamp
        vccontrol = h.VClamp(0.5, sec=post_cell.soma)
        vccontrol.dur[0] = 10.0
        vccontrol.amp[0] = clampV
        vccontrol.dur[1] = 100.0
        vccontrol.amp[1] = clampV
        vccontrol.dur[2] = 20.0
        vccontrol.amp[2] = clampV

        #
        # set up stimulation of the presynaptic axon/terminal
        #
        
        istim = h.iStim(0.5, sec=pre_cell.soma)
        stim = {
            'NP': 10,
            'Sfreq': 100.0,
            'delay': 10.0,
            'dur': 0.5,
            'amp': 10.0,
            'PT': 0.0,
            'dt': dt,
        }
        if stim_params is not None:
            stim.update(stim_params)
        (secmd, maxt, tstims) = util.make_pulse(stim)
        self.stim = stim

        if tstop is None:
            tstop = len(secmd) * dt
        
        istim.delay = 0
        istim.dur = 1e9 # these actually do not matter...
        istim.iMax = 0.0

        # istim current pulse train
        i_stim_vec = h.Vector(secmd)
        i_stim_vec.play(istim._ref_i, dt, 0)

        # create hoc vectors for each parameter we wish to monitor and display
        synapse = synapses[0]
        self.all_psd = []
        if isinstance(synapses[0].psd, GlyPSD) or isinstance(synapses[0].psd, GluPSD):
            for syn in synapses:
                self.all_psd.extend(syn.psd.all_psd)
        elif isinstance(synapses[0].psd, Exp2PSD):
            for syn in synapses:
                self.all_psd.append(syn)

        #for i, cleft in enumerate(synapse.psd.clefts):
            #self['cleft_xmtr%d' % i] = cleft._ref_CXmtr
            #self['cleft_pre%d' % i] = cleft._ref_pre
            #self['cleft_xv%d' % i] = cleft._ref_XV
            #self['cleft_xc%d' % i] = cleft._ref_XC
            #self['cleft_xu%d' % i] = cleft._ref_XU

        #
        # Run simulation
        #
        h.tstop = tstop # duration of a run
        h.celsius = temp
        h.dt = dt
        self.temp = temp
        self.dt = dt
        self.isoma = []
        self.currents = {'ampa': [], 'nmda': []}
        self.all_releases = []
        self.all_release_events = []
        start_time = timeit.default_timer()
        for nrep in xrange(iterations): # could do multiple runs.... 
            self.reset()
            self['v_pre'] = pre_cell.soma(0.5)._ref_v
            self['t'] = h._ref_t
            self['v_soma'] = pre_cell.soma(0.5)._ref_v
            if not isinstance(synapse.psd, Exp2PSD):
                self['relsite_xmtr'] = synapse.terminal.relsite._ref_XMTR[0]

            if isinstance(synapse.psd, GluPSD):
                # make a synapse monitor for each release zone
                self.all_nmda = []
                self.all_ampa = []
                for syn in synapses:
                    # collect all PSDs across all synapses
                    self.all_ampa.extend(syn.psd.ampa_psd)
                    self.all_nmda.extend(syn.psd.nmda_psd)
                    
                    # Record current through all PSDs individually
                    syn.psd.record('i', 'g', 'Open')
            
                #for k,p in enumerate(self.all_nmda):
                    #self['iNMDA%03d' % k] = p._ref_i
                    #self['opNMDA%03d' % k] = p._ref_Open
                #for k,p in enumerate(self.all_ampa):
                    #self['iAMPA%03d' % k] = p._ref_i
                    #self['opAMPA%03d' % k] = p._ref_Open
        
            elif isinstance(synapse.psd, GlyPSD):
                #  Record current through all PSDs individually
                for k,p in enumerate(self.all_psd):
                    self['iGLY%03d' % k] = p._ref_i
                    self['opGLY%03d' % k] = p._ref_Open
                
                psd = self.all_psd
                if synapse.psd.psdType == 'glyslow':
                    nstate = 7
                    self['C0'] = psd[0]._ref_C0
                    self['C1'] = psd[0]._ref_C1
                    self['C2'] = psd[0]._ref_C2
                    self['O1'] = psd[0]._ref_O1
                    self['O2'] = psd[0]._ref_O2
                    self['D1'] = psd[0]._ref_D1
                    #self['D3'] = psd[0]._ref_D3
                    #self['O1'] = psd[0]._ref_O1
                elif synapse.psd.psdType == 'glyfast':
                    nstate = 7
                    self['C0'] = psd[0]._ref_C0
                    self['C1'] = psd[0]._ref_C1
                    self['C2'] = psd[0]._ref_C2
                    self['C3'] = psd[0]._ref_C3
                    self['O1'] = psd[0]._ref_O1
                    self['O2'] = psd[0]._ref_O2
            elif isinstance(synapse.psd, Exp2PSD):
                self['iPSD'] = self.all_psd[0].psd.syn._ref_i

            if not isinstance(synapse.psd, Exp2PSD):
                for i, s in enumerate(synapses):
                    s.terminal.relsite.rseed = util.random_seed.current_seed() + nrep
            util.custom_init()
            h.run()

            # add up psd current across all runs
            if isinstance(synapse.psd, GluPSD):
                iampa = np.zeros_like(synapse.psd.get_vector('ampa', 'i'))
                inmda = iampa.copy()
                for syn in self.synapses:
                    for i in range(syn.psd.n_psd):
                        iampa += syn.psd.get_vector('ampa', 'i', i)
                        inmda += syn.psd.get_vector('nmda', 'i', i)
                isoma = iampa + inmda
                self.currents['ampa'].append(iampa)
                self.currents['nmda'].append(inmda)
            elif isinstance(synapse.psd, GlyPSD):
                isoma = np.zeros_like(self['iGLY000'])
                for k in range(len(self.all_psd)):
                    isoma += self['iGLY%03d'%k]
            elif isinstance(synapse.psd, Exp2PSD):
                 isoma = self['iPSD']
            self.isoma.append(isoma)
            self.all_releases.append(self.release_timings())
            self.all_release_events.append(self.release_events())

        elapsed = timeit.default_timer() - start_time
        print 'Elapsed time for %d Repetions: %f' % (iterations, elapsed)
    def run_one(self, istim, stim, initflag=True, sites=None):
        """
        Perform one run in current-clamp for the selected cell
        and add the data to the traces
        Monitor the presyanptic cell body and axon, as well as
        the current in a voltage-clamped target cell
        
        Parameters
        ----------
        istim : Stimulus electrode instance
        stim : waveform information
        initflag : boolean (default: True)
            If true, force initialziation of the cell and computation of 
            point Rin, tau and Vm
        sites : list of sections to monitor in addition to the soma
        """
        h.dt = self.dt  # establish this before we do any play/record setup

        # print('iv_curve:run_one')
        (secmd, maxt, tstims) = cnmodel.util.stim.make_pulse(stim)
        # print('maxt, dt*lencmd: ', maxt, len(secmd)*self.dt)# secmd = np.append(secmd, [0.])
        # print('stim: ', stim, self.tend)

        # connect current command vector
        playvector = h.Vector(secmd)  # sets up to "play" the array in secmd to # the stimulating electrode in the cell 
        # Python-> neuron call to set up the stimulus
        playvector.play(istim._ref_i, h.dt, 0, sec=self.cell.soma)

        self.r = {}  # results stored in a dict
        # Connect recording vectors
        self.r['v_soma'] = h.Vector()  # neuron arrays are "Vector"
        # set up an electrode to record from the cell that is directly stimulated
        self.r['v_soma'].record(self.cell.soma(0.5)._ref_v, sec=self.cell.soma)
        # self['q10'] = self.cell.soma(0.5).ihpyr_adj._ref_q10
        # self['ih_ntau'] = self.cell.soma(0.5).ihpyr_adj._ref_kh_n_tau
        # also record the current injection.
        self.r['i_inj'] = h.Vector()
        self.r['i_inj'].record(istim._ref_i, sec=self.cell.soma)
        self.r['time'] = h.Vector()
        self.r['time'].record(h._ref_t)

        # possibly record from all the axon nodes in the cell 
        # sites is set up in the main initialization routine
        if sites is not None:
            recvec = [h.Vector() for x in sites]
            for i, r in enumerate(recvec):
                r.record(sites[i](0.5)._ref_v, h.dt, 0, sec=sites[i])
        
        # for fun, monitor the presynaptic calcium concentration
        self.r['calyxca'] = h.Vector()
        self.r['calyxca'].record(sites[-1](1)._ref_cai, h.dt, 0, sec=sites[-1])
        h.celsius = self.cell.status['temperature']
        # print("iv_curve:run_one:calling cell_initialize")
        # set up an electrode in the postaynaptic cell.
        # This is a voltage clamp electrode, but we are just holding
        # the voltage constant. The parameters are required to be
        # set for this to work.
        clampV = -65.
        vccontrol = h.SEClamp(0.5, sec=self.post_cell.soma)
        vccontrol.dur1 = 10.0
        vccontrol.amp1 = clampV
        vccontrol.dur2 = 100.0
        vccontrol.amp2 = clampV
        vccontrol.dur3 = 25.0
        vccontrol.amp3 = clampV
        vccontrol.rs = 1e-9  # close to perfect - no series resistance
        
        # record the current through the postsynaptic cell membrane
        # this is the synaptic current
        self.r['i_post'] = h.Vector()
        self.r['i_post'].record(vccontrol._ref_i, sec=self.post_cell.soma)

        # print("iv_curve:run_one:calling custom_init")
        CU.custom_init()  # using our own initialization

        # now we can actually set up the run
        h.t = 0.
        h.tstop = np.sum(self.default_durs)
        print('stop: ', h.tstop, '  dt: ', h.dt)
        # and here it goes...
        while h.t < h.tstop:
            h.fadvance()
        # done! so now save the data from this run
        print('stop: ', h.tstop)
        # store the results in lists
        self.sgc_voltage_traces.append(self.r['v_soma'])
        self.current_traces.append(self.r['i_inj'])
        self.calyx_ca.append(self.r['calyxca'])
        self.post_cell_current_traces.append(self.r['i_post'])
        print('sgc  trace len: ', len(self.sgc_voltage_traces))
        print('post trace len: ', len(self.post_cell_current_traces))
        self.time_values = np.array(self.r['time'])
        if sites is not None:
            # for i, r in enumerate(recvec):
            #     print('r2: ', np.array(recvec[i]))
            self.axon_voltage_traces.append(np.array(recvec.copy()))
Ejemplo n.º 6
0
    def run(self,
            pre_sec,
            post_sec,
            temp=34.0,
            dt=0.025,
            vclamp=-65.0,
            iterations=1,
            tstop=200.0,
            stim_params=None,
            **kwds):
        """ 
        """
        Protocol.run(self, **kwds)

        pre_cell = cells.cell_from_section(pre_sec)
        post_cell = cells.cell_from_section(post_sec)
        synapse = pre_cell.connect(post_cell, type='simple')

        self.synapse = synapse
        self.pre_sec = synapse.terminal.section
        self.post_sec = synapse.psd.section
        self.pre_cell = pre_cell
        self.post_cell = post_cell

        #
        # voltage clamp the target cell
        #
        vccontrol = h.VClamp(0.5, sec=post_cell.soma)
        vccontrol.dur[0] = tstop
        vccontrol.amp[0] = vclamp
        #vccontrol.dur[1] = 100.0
        #vccontrol.amp[1] = clampV
        #vccontrol.dur[2] = 20.0
        #vccontrol.amp[2] = clampV

        #
        # set up stimulation of the presynaptic axon/terminal
        #

        istim = h.iStim(0.5, sec=pre_cell.soma)
        stim = {
            'NP': 10,
            'Sfreq': 100.0,
            'delay': 10.0,
            'dur': 0.5,
            'amp': 10.0,
            'PT': 0.0,
            'dt': dt,
        }
        if stim_params is not None:
            stim.update(stim_params)
        (secmd, maxt, tstims) = util.make_pulse(stim)
        self.stim = stim

        if tstop is None:
            tstop = len(secmd) * dt

        istim.delay = 0
        istim.dur = 1e9  # these actually do not matter...
        istim.iMax = 0.0

        # istim current pulse train
        i_stim_vec = h.Vector(secmd)
        i_stim_vec.play(istim._ref_i, dt, 0)

        #
        # Run simulation
        #
        h.tstop = tstop  # duration of a run
        h.celsius = temp
        h.dt = dt
        self.temp = temp
        self.dt = dt
        for nrep in xrange(iterations):  # could do multiple runs....
            self.reset()
            self['v_pre'] = pre_cell.soma(0.5)._ref_v
            self['t'] = h._ref_t
            self['v_soma'] = post_cell.soma(0.5)._ref_v
            self['i_soma'] = vccontrol._ref_i
            util.custom_init()
            h.run()
Ejemplo n.º 7
0
    def run(self, temp=38.0, dt=0.025, seed=575982035, simulator=None):
        ears = {'left': [500., 502, 498], 'right': [500., 502., 498]}
        
        self.beatfreq = 0.
        self.f0 = 500.
        f0 = {'left': self.f0, 'right': self.f0+self.beatfreq}
        nsgc = len(ears.keys())
        sgcCell = {}
        bushyCell = {}
        msoCell = {}
        synapse = {}
        self.stim = {}
        self.ears = ears
        self.stimdur = 0.2
        self.stimdelay = 0.02
        self.rundur = self.stimdelay + self.stimdur + 0.02

        for i, ear in enumerate(ears.keys()):
            nsgc = len(ears[ear])  # how many sgcs are specified for this ear
            sgcCell[ear] = [cells.DummySGC(cf=ears[ear][k], sr=2) for k in range(nsgc)]
            bushyCell[ear] = [cells.Bushy.create(temperature=temp)]
            synapse[ear] = [sgcCell[ear][k].connect(bushyCell[ear][0]) for k in range(nsgc)]
            self.stim[ear] = [sound.TonePip(rate=100e3, duration=self.stimdur+0.1, f0=f0[ear], dbspl=80,
                                  ramp_duration=2.5e-3, pip_duration=self.stimdur, 
                                  pip_start=[self.stimdelay]) for k in range(nsgc)]
            for k in range(len(self.stim[ear])):
                sgcCell[ear][k].set_sound_stim(self.stim[ear][k], seed=seed + i*seed + k, simulator=simulator)
            self['vm_bu_%s' % ear] = bushyCell[ear][0].soma(0.5)._ref_v
            for k in range(30):
                self['xmtr%d_%s'%(k, ear)] = synapse[ear][0].terminal.relsite._ref_XMTR[k]
            for k in range(len(synapse[ear])):
                synapse[ear][k].terminal.relsite.Dep_Flag = False  # turn off depression

        msoCell = cells.MSO.create(temperature=temp)  # one target MSO cell
        msosyn = {}
        for ear in ears:
            msosyn[ear] = bushyCell[ear][0].connect(msoCell)
        self.sgc_cells = sgcCell
        self.bushy_cells = bushyCell
        self.synapses = synapse
        self.msyns = msosyn
        self.msoCell = msoCell
        self.all_cells = []  # hold all "real" cells (DummySGC does not have mechanisms)
        for ear in ears.keys():
            self.all_cells.append([c for c in self.bushy_cells[ear]])
        self.all_cells.append([self.msoCell])
        
        self['vm_mso'] = self.msoCell.soma(0.5)._ref_v
        for k, ear in enumerate(ears.keys()):
            for i in range(30):
                self['mso_xmtr%d_%s'%(i, ear)] = msosyn[ear].terminal.relsite._ref_XMTR[i]
            msosyn[ear].terminal.relsite.Dep_Flag = False  # turn off depression

        self['t'] = h._ref_t
        
        h.tstop = self.rundur*1e3 # duration of a run
        h.celsius = temp
        h.dt = dt
        
        custom_init()
        # confirm that all cells are ok
        for cg in self.all_cells:
            for c in cg:
                c.check_all_mechs()
        while h.t < h.tstop:
            h.fadvance()