Beispiel #1
0
def cellsim(stimamp0=0.055, stimamp1=0.0, **kwargs):

    cell = InterneuronTemplate(**kwargs)

    PPparams0 = {
        'idx': 0,
        'pptype': 'IClamp',
        'delay': 100,
        'dur': 900,
        'amp': stimamp0
    }
    PPparams1 = {
        'idx': 0,
        'pptype': 'IClamp',
        'delay': 0,
        'dur': 20000,
        'amp': stimamp1,
    }

    if stimamp0 != 0:
        stim0 = LFPy.StimIntElectrode(cell, **PPparams0)
    if stimamp1 != 0:
        stim1 = LFPy.StimIntElectrode(cell, **PPparams1)

    cell.simulate(rec_vmem=True)

    return cell
Beispiel #2
0
def exercise2(soma_clamp_params, apic_clamp_params, electrode_parameters, noise_level):
    ### MAKING THE CELL
    cell_parameters = {
        'morphology': 'A140612.hoc',
        'v_init': -62,
        'passive': False,
        'nsegs_method': None,
        'dt': 2**-3,  # [ms] Should be a power of 2
        'tstart': -50,  # [ms] Simulation start time
        'tstop': 50,  # [ms] Simulation end time
        'custom_code': ['cell_model.hoc'] # Loads model specific code
    }
    cell = LFPy.Cell(**cell_parameters)

    ### MAKING THE INPUT
    apic_clamp_params['idx'] = cell.get_closest_idx(x=-150., y=750., z=0.)
    cl_soma = LFPy.StimIntElectrode(cell, **soma_clamp_params)
    cl_apic = LFPy.StimIntElectrode(cell, **apic_clamp_params)

    cell.simulate(rec_imem=True, rec_vmem=True)

    ### MAKING THE ELECTRODE
    electrode = LFPy.RecExtElectrode(cell, **electrode_parameters)
    electrode.calc_lfp()

    ### PLOTTING THE RESULTS
    cell_plot_idxs = [soma_clamp_params['idx'], apic_clamp_params['idx']]
    cell_idx_colors = {cell_plot_idxs[idx]: plt.cm.Greens_r(1./(len(cell_plot_idxs) + 1) * idx + 0.1) for idx in range(len(cell_plot_idxs))}
    elec_idx_colors = {idx: plt.cm.Reds_r(1./(len(electrode_parameters['x']) + 1) * idx) for idx in range(len(electrode_parameters['x']))}

    plt.figure(figsize=(16,9))
    # Plotting the morphology
    plt.subplots_adjust(hspace=0.5, wspace=0.5)
    plt.subplot(141, aspect='equal', xlabel='x [$\mu m$]', ylabel='y [$\mu m$]', xlim=[-400, 400], xticks=[-400, 0, 400], 
                title='Green dots: Inputs\nRed diamonds: Extracellular electrodes')
    [plt.plot([cell.xstart[idx], cell.xend[idx]], [cell.ystart[idx], cell.yend[idx]], c='k') for idx in range(cell.totnsegs)]
    [plt.plot(cell.xmid[idx], cell.ymid[idx], 'o', c=cell_idx_colors[idx], ms=12) for idx in cell_plot_idxs]
    [plt.plot(electrode_parameters['x'][idx], electrode_parameters['y'][idx], 'D', c=elec_idx_colors[idx], ms=12) for idx in range(len(electrode_parameters['x']))]

    # Plotting the membrane potentials
    plt.subplot(242, title='Membrane\npotential', xlabel='Time [ms]', ylabel='mV', ylim=[-80, 20])
    [plt.plot(cell.tvec, cell.vmem[idx, :], c=cell_idx_colors[idx], lw=2) for idx in cell_plot_idxs]

    # Plotting the input currents
    stim_lim = [2*np.min([cl_soma.i, cl_apic.i]), 2*np.max([cl_soma.i, cl_apic.i])]
    plt.subplot(246, title='Input currents', xlabel='Time [ms]', ylabel='nA', ylim=stim_lim)
    plt.plot(cell.tvec, cl_soma.i, c=cell_idx_colors[soma_clamp_params['idx']], lw=2)
    plt.plot(cell.tvec, cl_apic.i, '--', c=cell_idx_colors[apic_clamp_params['idx']], lw=2)

    # Plotting the extracellular potentials
    LFP = 1000 * electrode.LFP + noise_level * (np.random.random(electrode.LFP.shape) - 0.5)

    plt.subplot(243, title='Extracellular\npotentials', xlabel='Time [ms]', ylabel='$\mu$V', xlim=[9, 18])
    [plt.plot(cell.tvec, LFP[idx], c=elec_idx_colors[idx], lw=2) for idx in range(len(electrode_parameters['x']))]

    norm_LFP = [LFP[idx] - LFP[idx, 0] for idx in range(len(electrode_parameters['x']))]
    plt.subplot(247, title='Extracellular\npotentials', xlabel='Time [ms]', ylabel='Normalized', xlim=[9, 18])
    [plt.plot(cell.tvec, norm_LFP[idx] / np.max(np.abs(norm_LFP[idx])), c=elec_idx_colors[idx], lw=2) for idx in range(len(electrode_parameters['x']))]
Beispiel #3
0
    def test_StimIntElectrode_03(self):
        cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test',
                                                 'ball_and_sticks.hoc'))
        stim0 = LFPy.StimIntElectrode(cell=cell,
                                      idx=0,
                                      pptype='IClamp',
                                      amp=1.,
                                      dur=20.,
                                      delay=10.,
                                      record_potential=True,
                                      record_current=True)

        stim1 = LFPy.StimIntElectrode(cell=cell,
                                      idx=1,
                                      pptype='IClamp',
                                      amp=1.,
                                      dur=20.,
                                      delay=30.,
                                      record_potential=True,
                                      record_current=False)

        stim2 = LFPy.StimIntElectrode(cell=cell,
                                      idx=2,
                                      pptype='IClamp',
                                      amp=1.,
                                      dur=20.,
                                      delay=50.,
                                      record_potential=False,
                                      record_current=True)

        stim3 = LFPy.StimIntElectrode(cell=cell,
                                      idx=3,
                                      pptype='IClamp',
                                      amp=1.,
                                      dur=20.,
                                      delay=70.,
                                      record_potential=False,
                                      record_current=False)

        cell.simulate()
        gt = np.zeros(cell.tvec.size)
        gt[(cell.tvec > 10.) & (cell.tvec <= 30.)] = 1.
        np.testing.assert_equal(gt, stim0.i)
        np.testing.assert_equal(cell.somav, stim0.v)

        self.assertTrue(hasattr(stim1, 'v'))
        self.assertTrue(cell.tvec.shape == stim1.v.shape)
        self.assertFalse(hasattr(stim2, 'v'))
        self.assertFalse(hasattr(stim3, 'v'))
        self.assertFalse(hasattr(stim1, 'i'))
        self.assertTrue(hasattr(stim2, 'i'))
        self.assertTrue(cell.tvec.shape == stim2.i.shape)
        self.assertFalse(hasattr(stim3, 'i'))
Beispiel #4
0
    def test_cell_tstart_00(self):
        stickParams = {
            'morphology': os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
            'cm': 1,
            'Ra': 150,
            'v_init': -65,
            'passive': True,
            'passive_parameters': {
                'g_pas': 1. / 30000,
                'e_pas': -65
            },
            'dt': 2**-4,
            'nsegs_method': 'lambda_f',
            'lambda_f': 100,
        }

        stimParams = {
            'pptype': 'SinSyn',
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'bias': 0.,
            'record_current': False
        }

        stick0 = LFPy.Cell(tstart=0, tstop=200, **stickParams)
        synapse0 = LFPy.StimIntElectrode(stick0,
                                         stick0.get_closest_idx(0, 0, 1000),
                                         delay=0,
                                         phase=0.,
                                         **stimParams)
        stick0.simulate(rec_imem=True,
                        rec_vmem=True,
                        rec_current_dipole_moment=True)

        stick1 = LFPy.Cell(tstart=-100, tstop=100, **stickParams)
        synapse1 = LFPy.StimIntElectrode(stick1,
                                         stick1.get_closest_idx(0, 0, 1000),
                                         delay=-100,
                                         phase=0.,
                                         **stimParams)
        stick1.simulate(rec_imem=True,
                        rec_vmem=True,
                        rec_current_dipole_moment=True)

        inds = stick0.tvec >= 100
        np.testing.assert_allclose(stick0.vmem[:, inds], stick1.vmem)
        np.testing.assert_allclose(stick0.imem[:, inds], stick1.imem)
        np.testing.assert_allclose(stick0.current_dipole_moment[inds, :],
                                   stick1.current_dipole_moment)
Beispiel #5
0
 def test_StimIntElectrode_02(self):
     cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test',
                                              'ball_and_sticks.hoc'),
                      dt=1.,
                      v_init=-65.,
                      Ra=150.,
                      cm=1.,
                      passive=True,
                      passive_parameters=dict(g_pas=1. / 30000, e_pas=-65))
     stim = LFPy.StimIntElectrode(cell=cell,
                                  record_potential=True,
                                  **{
                                      'idx': 0,
                                      'pptype': 'SEClamp',
                                      'amp1': -65,
                                      'dur1': 10,
                                      'amp2': -55.,
                                      'dur2': 20,
                                      'amp3': -65,
                                      'dur3': 10,
                                  })
     cell.simulate()
     gt = np.zeros(cell.tvec.size) - 65.
     gt[(cell.tvec > 10.) & (cell.tvec <= 30.)] = -55.
     np.testing.assert_allclose(gt, cell.somav, rtol=1E-2)
     np.testing.assert_equal(cell.somav, stim.v)
Beispiel #6
0
    def instantiate(self, sim=None, icell=None, LFPyCell=None):
        """Run stimulus"""
        from .locations import NrnSomaDistanceCompLocation

        if hasattr(self.location, "sec_index"):
            sec_index = self.location.sec_index
        elif isinstance(self.location, NrnSomaDistanceCompLocation):
            # compute sec_index closest to soma_distance
            cell_seg_locs = np.array([LFPyCell.x, LFPyCell.y, LFPyCell.z]).T
            soma_loc = LFPyCell.somapos
            dist_from_soma = np.array(
                [np.linalg.norm(loc - soma_loc) for loc in cell_seg_locs])
            sec_index = np.argmin(
                np.abs(dist_from_soma - self.location.soma_distance))
        else:
            raise NotImplementedError(
                f"{type(self.location)} is currently not implemented "
                "with the LFPy backend")

        self.iclamp = LFPy.StimIntElectrode(cell=LFPyCell,
                                            idx=sec_index,
                                            pptype="IClamp",
                                            amp=self.step_amplitude,
                                            delay=self.step_delay,
                                            dur=self.step_duration,
                                            record_current=True)
        logger.debug(
            "Adding square step stimulus to %s with delay %f, "
            "duration %f, and amplitude %f",
            str(self.location),
            self.step_delay,
            self.step_duration,
            self.step_amplitude,
        )
Beispiel #7
0
 def distal_cosine_current_injection(self, tstop=850):
     pre_syn_sptimes = self.stationary_poisson(nsyn=self.n_pre_syn,
                                               lambd=2,
                                               tstart=0,
                                               tstop=400)
     l = np.arange(self.n_pre_syn)
     pre_syn_pick = np.random.permutation(l)[0:self.n_synapses]
     pars = {}
     for i_syn in range(self.n_synapses):
         syn_idx = int(self.cell.get_rand_idx_area_norm())
         spike_times = pre_syn_sptimes[pre_syn_pick[i_syn]]
         if syn_idx in pars:
             pars[syn_idx].extend(list(spike_times))
         else:
             pars[syn_idx] = list(spike_times)
     for syn_idx in pars:
         self.synapse_parameters.update({'idx': syn_idx})
         synapse = LFPy.Synapse(self.cell, **self.synapse_parameters)
         synapse.set_spike_times(np.array(pars[syn_idx]))
    
     TimesStim = np.arange(850)
     stim = np.array(3.6*np.sin(2.*3.141*6.5*TimesStim/1000.))
     all_idxs = self.cell.get_idx()
     
     for istim in range(tstop):
         pointprocess = {
             'idx' : max(all_idxs),
             'pptype': 'IClamp',
             'record_current' : True,
             'amp': stim[istim],
             'dur' : 1.,
             'delay': istim,
             }
         stimulus = LFPy.StimIntElectrode(self.cell, **pointprocess)
Beispiel #8
0
def cell_thread_PSC(task_queue, done_queue):
    '''thread function for simulation of single neuron process'''
    for n in iter(task_queue.get, 'STOP'):
        print 'Cell number %s out of %d.' % (n, pop_params['n'] - 1)
        cell = LFPy.Cell(**cellparams)

        e_synparams = e_synparams_init.copy()
        for idx in allidx_e[n]:
            e_synparams = e_synparams_init.copy()
            e_synparams.update({'idx': int(idx), 'color': (0.8, 0.8, 0.8)})
            e_spiketimes = [pl.array([spiketime])]

            s_e = LFPy.Synapse(cell, **e_synparams)
            s_e.set_spike_times(e_spiketimes[0])

        e_synparams = e_synparams_init.copy()

        LFPy.StimIntElectrode(cell, **pointprocparams)

        cell.simulate(**simparams2)
        cell.tvec = pl.arange(
            -1, cellparams['timeres_python'] * len(cell.tvec) - 1,
            cellparams['timeres_python'])

        cell.strip_hoc_objects()

        done_queue.put(cell)
def generate_LFP_for_single_neuron(electrode, cell_name, params):
    cwd = os.getcwd()
    neuron.h.load_file('stdrun.hoc')
    neuron.h.load_file('import3d.hoc')

    #Loading the neuron models of interest
    neuron_model = '/home/baran/Desktop/neuron_models/' + cell_name

    load_mechanisms_from_neuron_model(cell_name)
    templatename = load_cell_properties(cell_name)
    os.chdir(neuron_model)
    morphologyfile = glob(os.path.join('morphology', '*'))[0]
    add_synapses = False

    cell = LFPy.TemplateCell(morphology=morphologyfile,
                             templatefile=(os.path.join(
                                 neuron_model, 'template.hoc')),
                             templatename=templatename,
                             templateargs=1 if add_synapses else 0,
                             tstop=params['tstop'],
                             dt=params['dt'],
                             nsegs_method=None,
                             pt3d=True,
                             verbose=True)

    #Add stimulation electrode
    pointProcess = LFPy.StimIntElectrode(cell, **params['PointProcParams'])

    cell.simulate(electrode=electrode)
    os.chdir(cwd)
    return electrode, cell
Beispiel #10
0
    def test_isotropic_version_of_anisotropic_methods(self):

        stickParams = {
            'morphology': os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
            'passive_parameters': {
                'g_pas': 1. / 30000,
                'e_pas': -65
            },
            'passive': True,
            'tstart': 0,
            'tstop': 20,
            'dt': 2**-4,
            'nsegs_method': 'lambda_f',
            'lambda_f': 1000,
        }
        stimParams = {
            'pptype': 'SinSyn',
            'delay': -100.,
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'phase': -np.pi / 2,
            'bias': 0.,
            'record_current': True
        }

        isotropic_electrodeParams = {
            'sigma': 0.3,
            'x': np.ones(11) * 100.,
            'y': np.zeros(11),
            'z': np.linspace(1000, 0, 11),
        }
        anisotropic_electrodeParams = isotropic_electrodeParams.copy()
        anisotropic_electrodeParams["sigma"] = [
            isotropic_electrodeParams["sigma"]
        ] * 3

        methods = ["pointsource", "linesource", "soma_as_point"]

        for method in methods:
            isotropic_electrodeParams["method"] = method
            anisotropic_electrodeParams["method"] = method

            isotropic_electrode = LFPy.RecExtElectrode(
                **isotropic_electrodeParams)
            anisotropic_electrode = LFPy.RecExtElectrode(
                **anisotropic_electrodeParams)

            stick = LFPy.Cell(**stickParams)
            stick.set_pos(z=-stick.zstart[0])

            synapse = LFPy.StimIntElectrode(stick,
                                            stick.get_closest_idx(0, 0, 1000),
                                            **stimParams)
            stick.simulate([isotropic_electrode, anisotropic_electrode],
                           rec_imem=True,
                           rec_vmem=True)

            np.testing.assert_allclose(isotropic_electrode.LFP,
                                       anisotropic_electrode.LFP)
Beispiel #11
0
 def cosine_current_injection(self, tstop=850):
     pre_syn_sptimes = self.stationary_poisson(nsyn=self.n_pre_syn,
                                               lambd=2,
                                               tstart=0,
                                               tstop=400)
     l = np.arange(self.n_pre_syn)
     pre_syn_pick = np.random.permutation(l)[0:self.n_synapses]
     self.synapse_parameters['weight'] = 0.05
     pars = {}
     for i_syn in range(self.n_synapses):
         syn_idx = int(self.cell.get_rand_idx_area_norm())
         spike_times = pre_syn_sptimes[pre_syn_pick[i_syn]]
         if syn_idx in pars:
             pars[syn_idx].extend(list(spike_times))
         else:
             pars[syn_idx] = list(spike_times)
     for syn_idx in pars:
         self.synapse_parameters.update({'idx': syn_idx})
         synapse = LFPy.Synapse(self.cell, **self.synapse_parameters)
         synapse.set_spike_times(np.array(pars[syn_idx]))
     self.point_process['dur'] = 1
     TimesStim = np.arange(tstop)
     stim = np.array(3.6e-1 * np.sin(2. * 3.141 * 6.5 * TimesStim / 1000.))
     for istim in range(tstop):
         self.point_process['amp'] = stim[istim]
         self.point_process['delay'] = istim
         stimulus = LFPy.StimIntElectrode(self.cell, **self.point_process)
Beispiel #12
0
def makeStimulus(cell):
    return LFPy.StimIntElectrode(cell=cell,
                                 idx=0,
                                 pptype='IClamp',
                                 amp=1 + (.05 * np.random.randn()),
                                 dur=100.,
                                 delay=5.,
                                 record_current=True)
Beispiel #13
0
def exercise1(soma_clamp_params, apic_clamp_params):

    cell_parameters = {
        'morphology': 'A140612.hoc',  # File with cell morphology
        'v_init': -62,
        'passive': False,
        'nsegs_method': None,
        'dt': 2**-3,  # [ms] Should be a power of 2
        'tstart': -50,  # [ms] Simulation start time
        'tstop': 50,  # [ms] Simulation end time
        'custom_code': ['cell_model.hoc'] # Loads model specific code
    }

    ### MAKING THE CELL
    cell = LFPy.Cell(**cell_parameters)

    ### MAKING THE INPUT
    apic_clamp_params['idx'] = cell.get_closest_idx(x=-150., y=750., z=0.)
    cl_soma = LFPy.StimIntElectrode(cell, **soma_clamp_params)
    cl_apic = LFPy.StimIntElectrode(cell, **apic_clamp_params)

    cell.simulate(rec_vmem=True)

    ### PLOTTING THE RESULTS
    cell_plot_idxs = [soma_clamp_params['idx'], apic_clamp_params['idx']]    
    cell_plot_colors = {cell_plot_idxs[idx]: plt.cm.Greens_r(1./(len(cell_plot_idxs) + 1) * idx + 0.1) for idx in range(len(cell_plot_idxs))}


    # Plotting the morphology
    plt.figure(figsize=(16,9))
    plt.subplots_adjust(hspace=0.5)
    plt.subplot(121, aspect='equal', xlabel='x [$\mu m$]', ylabel='y [$\mu m$]', xlim=[-400, 400], xticks=[-400, 0, 400], title='Green dots: Inputs')
    [plt.plot([cell.xstart[idx], cell.xend[idx]], [cell.ystart[idx], cell.yend[idx]], c='k') for idx in range(cell.totnsegs)]
    [plt.plot(cell.xmid[idx], cell.ymid[idx], 'o', c=cell_plot_colors[idx], ms=12) for idx in cell_plot_idxs]

    # Plotting the membrane potentials
    plt.subplot(222, title='Membrane potential', xlabel='Time [ms]', ylabel='mV', ylim=[-80, 20])
    [plt.plot(cell.tvec, cell.vmem[idx, :], c=cell_plot_colors[idx], lw=2) for idx in cell_plot_idxs]

    # Plotting the input currents
    stim_lim = [2*np.min([cl_soma.i, cl_apic.i]), 2*np.max([cl_soma.i, cl_apic.i])]
    plt.subplot(224, title='Input currents', xlabel='Time [ms]', ylabel='nA', ylim=stim_lim)
    plt.plot(cell.tvec, cl_soma.i, c=cell_plot_colors[soma_clamp_params['idx']], lw=2)
    plt.plot(cell.tvec, cl_apic.i, '--', c=cell_plot_colors[apic_clamp_params['idx']], lw=2)
Beispiel #14
0
def stickSimulationDotprodcoeffs(method):
    stickParams = {
        'morphology' : os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
        'cm' : 1,
        'Ra' : 150,
        'v_init' : -65,
        'passive' : True,
        'passive_parameters' : {'g_pas' : 1./30000, 'e_pas' : -65},
        'tstart' : -100,
        'tstop' : 100,
        'dt' : 2**-6,
        'nsegs_method' : 'lambda_f',
        'lambda_f' : 1000,

    }

    electrodeParams = {
        'sigma' : 0.3,
        'x' : np.ones(11) * 100.,
        'y' : np.zeros(11),
        'z' : np.linspace(1000, 0, 11),
        'method' : method
    }

    stimParams = {
        'pptype' : 'SinSyn',
        'delay' : -100.,
        'dur' : 1000.,
        'pkamp' : 1.,
        'freq' : 100.,
        'phase' : -np.pi/2,
        'bias' : 0.,
        'record_current' : True
    }



    stick = LFPy.Cell(**stickParams)
    stick.set_pos(z=-stick.zstart[0])
    
    #dummy variables for mapping
    stick.imem = np.eye(stick.totnsegs)
    stick.tvec = np.arange(stick.totnsegs)*stick.dt

    electrode = LFPy.RecExtElectrode(stick, **electrodeParams)
    electrode.calc_lfp()
    #not needed anymore:
    del stick.imem, stick.tvec

    synapse = LFPy.StimIntElectrode(stick, stick.get_closest_idx(0, 0, 1000),
                           **stimParams)
    stick.simulate(dotprodcoeffs=electrode.LFP,
                   rec_imem=True, rec_vmem=True)

    return stick.dotprodresults[0]
Beispiel #15
0
    def test_cell_simulate_current_dipole_moment_01(self):
        stickParams = {
            'morphology':
            os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
            'templatefile':
            os.path.join(LFPy.__path__[0], 'test', 'stick_template.hoc'),
            'templatename':
            'stick_template',
            'templateargs':
            None,
            'cm':
            1,
            'Ra':
            150,
            'v_init':
            -65,
            'passive':
            True,
            'passive_parameters': {
                'g_pas': 1. / 30000,
                'e_pas': -65
            },
            'tstart':
            -100,
            'tstop':
            100,
            'dt':
            2**-4,
            'nsegs_method':
            'lambda_f',
            'lambda_f':
            100,
        }

        stimParams = {
            'pptype': 'SinSyn',
            'delay': 0.,
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'phase': 0,
            'bias': 0.,
            'record_current': False
        }

        for idx in range(31):  #31 segments
            if idx != 15:  # no net dipole moment because of stick symmetry
                stick = LFPy.TemplateCell(**stickParams)
                synapse = LFPy.StimIntElectrode(stick, idx=idx, **stimParams)
                stick.simulate(rec_imem=True, rec_current_dipole_moment=True)
                p = np.dot(stick.imem.T, np.c_[stick.xmid, stick.ymid,
                                               stick.zmid])
                np.testing.assert_allclose(p, stick.current_dipole_moment)
Beispiel #16
0
def stickSimulationAveragingElectrode(contactRadius, contactNPoints, method):
    stickParams = {
        'morphology': os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
        'cm': 1,
        'Ra': 150,
        'v_init': -65,
        'passive': True,
        'passive_parameters': {
            'g_pas': 1. / 30000,
            'e_pas': -65
        },
        'tstart': -100,
        'tstop': 100,
        'dt': 2**-6,
        'nsegs_method': 'lambda_f',
        'lambda_f': 1000,
    }

    N = np.empty((11, 3))
    for i in range(N.shape[0]):
        N[i, ] = [1, 0, 0]  #normal unit vec. to contacts
    electrodeParams = {
        'sigma': 0.3,
        'x': np.ones(11) * 100.,
        'y': np.zeros(11),
        'z': np.linspace(1000, 0, 11),
        'r': contactRadius,
        'n': 10,
        'N': N,
        'method': method
    }

    stimParams = {
        'pptype': 'SinSyn',
        'delay': -100.,
        'dur': 1000.,
        'pkamp': 1.,
        'freq': 100.,
        'phase': -np.pi / 2,
        'bias': 0.,
        'record_current': True
    }

    electrode = LFPy.RecExtElectrode(**electrodeParams)

    stick = LFPy.Cell(**stickParams)
    stick.set_pos(z=-stick.zstart[0])

    synapse = LFPy.StimIntElectrode(stick, stick.get_closest_idx(0, 0, 1000),
                                    **stimParams)
    stick.simulate(electrode, rec_imem=True, rec_vmem=True)

    return electrode.LFP
Beispiel #17
0
def make_ZAP_stimuli(cell, input_idx, input_scaling):
    ZAP_clamp = {
        'idx': input_idx,
        'record_current': True,
        'dur': 20000,
        'delay': 0,
        'freq_start': 0,
        'freq_end': 15,
        'pkamp': input_scaling,
        'pptype': 'ZAPClamp',
    }
    current_clamp = LFPy.StimIntElectrode(cell, **ZAP_clamp)
    return cell, current_clamp
    def currentPulse(self, cell, stimamp0=0.055, stimamp1=0.0):

        PPparams0 = {
            'idx': 0,
            'pptype': 'IClamp',
            'delay': 100,
            'dur': 900,
            'amp': stimamp0
        }
        PPparams1 = {
            'idx': 0,
            'pptype': 'IClamp',
            'delay': 0,
            'dur': 20000,
            'amp': stimamp1,
        }

        if stimamp0 != 0:
            stim0 = LFPy.StimIntElectrode(cell, **PPparams0)
        if stimamp1 != 0:
            stim1 = LFPy.StimIntElectrode(cell, **PPparams1)

        cell.simulate(rec_vmem=True)
Beispiel #19
0
    def test_cell_with_recextelectrode_01(self):
        stickParams = {
            'morphology': os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
            'cm': 1,
            'Ra': 150,
            'v_init': -65,
            'passive': True,
            'passive_parameters': {
                'g_pas': 1. / 30000,
                'e_pas': -65
            },
            'tstart': -100,
            'tstop': 100,
            'dt': 2**-4,
            'nsegs_method': 'lambda_f',
            'lambda_f': 100,
        }

        electrodeParams = {
            'sigma': 0.3,
            'x': np.ones(11) * 100.,
            'y': np.zeros(11),
            'z': np.linspace(1000, 0, 11),
            'method': 'pointsource'
        }

        stimParams = {
            'pptype': 'SinSyn',
            'delay': 0.,
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'phase': 0,
            'bias': 0.,
            'record_current': False
        }

        stick = LFPy.Cell(**stickParams)
        synapse = LFPy.StimIntElectrode(stick,
                                        stick.get_closest_idx(0, 0, 1000),
                                        **stimParams)
        electrode = LFPy.RecExtElectrode(**electrodeParams)
        stick.simulate(electrode, rec_imem=True)

        electrode1 = LFPy.RecExtElectrode(cell=stick, **electrodeParams)
        electrode1.calc_lfp()

        np.testing.assert_allclose(electrode.LFP, electrode1.LFP)
Beispiel #20
0
 def test_StimIntElectrode_00(self):
     cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test',
                                              'ball_and_sticks.hoc'))
     stim = LFPy.StimIntElectrode(cell=cell,
                                  idx=0,
                                  pptype='IClamp',
                                  amp=1.,
                                  dur=20.,
                                  delay=10.,
                                  record_potential=True,
                                  record_current=True)
     cell.simulate()
     gt = np.zeros(cell.tvec.size)
     gt[(cell.tvec > 10.) & (cell.tvec <= 30.)] = 1.
     np.testing.assert_equal(gt, stim.i)
     np.testing.assert_equal(cell.somav, stim.v)
Beispiel #21
0
def stickSimulation(method):
    stickParams = {
        'morphology': os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
        'cm': 1,
        'Ra': 150,
        'v_init': -65,
        'passive': True,
        'passive_parameters': {
            'g_pas': 1. / 30000,
            'e_pas': -65
        },
        'tstart': -100,
        'tstop': 100,
        'dt': 2**-6,
        'nsegs_method': 'lambda_f',
        'lambda_f': 1000,
    }

    electrodeParams = {
        'sigma': 0.3,
        'x': np.ones(11) * 100.,
        'y': np.zeros(11),
        'z': np.linspace(1000, 0, 11),
        'method': method
    }

    stimParams = {
        'pptype': 'SinSyn',
        'delay': -100.,
        'dur': 1000.,
        'pkamp': 1.,
        'freq': 100.,
        'phase': -np.pi / 2,
        'bias': 0.,
        'record_current': True
    }

    electrode = LFPy.RecExtElectrode(**electrodeParams)

    stick = LFPy.Cell(**stickParams)
    stick.set_pos(z=-stick.zstart[0])

    synapse = LFPy.StimIntElectrode(stick, stick.get_closest_idx(0, 0, 1000),
                                    **stimParams)
    stick.simulate(electrode, rec_imem=True, rec_vmem=True)

    return electrode.LFP
Beispiel #22
0
def cellsim_w_HH(stim_I=0.2,
                 gnabar_hh=0.12,
                 gkbar_hh=0.036,
                 gl_hh=0.0003,
                 el_hh=-54.3):
    #LFPy.TemplateCell params
    cell_params = dict(
        morphology='soma.hoc',
        templatefile='LFPyCellTemplate.hoc',
        templatename='LFPyCellTemplate',
        passive=False,
        nsegs_method=None,
        tstartms=0,
        tstopms=1000,
        extracellular=False,
    )

    #LFPy.StimIntElectrode params
    stim_params = {
        'idx': 0,
        'pptype': 'IClamp',
        'delay': 100.,
        'dur': 800.,
        'amp': stim_I,
    }

    #Why templatecell - Hay2011 is one, see LFPy examples using it.
    cell = LFPy.TemplateCell(**cell_params)

    #throw on some HH channels
    for sec in cell.allseclist:
        sec.insert('hh')
        #These are important, basically the DOFs were attempting to fit
        for seg in sec:
            seg.hh.gnabar = gnabar_hh
            seg.hh.gkbar = gkbar_hh
            seg.hh.gl = gl_hh
            seg.hh.el = el_hh

    #set stimulus
    stim = LFPy.StimIntElectrode(cell, **stim_params)

    #run the sim
    cell.simulate()

    #return data
    return cell.tvec, cell.somav
Beispiel #23
0
    def stickSimulation(self, method):
        stickParams = {
            'morphology': os.path.join(LFPy.__path__[0], 'stick.hoc'),
            'rm': 30000,
            'cm': 1,
            'Ra': 150,
            'tstartms': -100,
            'tstopms': 100,
            'timeres_python': 0.01,
            'timeres_NEURON': 0.01,
            'nsegs_method': 'lambda_f',
            'lambda_f': 100,
        }

        electrodeParams = {
            'sigma': 0.3,
            'x': np.ones(11) * 100.,
            'y': np.zeros(11),
            'z': np.linspace(1000, 0, 11),
            'method': method
        }

        stimParams = {
            'pptype': 'SinSyn',
            'delay': -100.,
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'phase': -np.pi / 2,
            'bias': 0.,
            'record_current': True
        }

        electrode = LFPy.RecExtElectrode(**electrodeParams)

        stick = LFPy.Cell(**stickParams)

        synapse = LFPy.StimIntElectrode(stick,
                                        stick.get_closest_idx(0, 0, 1000),
                                        **stimParams)
        stick.simulate(electrode, rec_imem=True, rec_istim=True, rec_vmem=True)

        return electrode.LFP
Beispiel #24
0
 def sine_synaptic_input(self, tstop=None):
     if not tstop:
         tstop = self.cell.tstop
     frequencies = np.arange(0.5, 13, 0.5)
     i = 0
     distance = 0
     nseg = self.cell.get_idx()
     freq_step = sum(self.cell.length) / len(frequencies)
     for j, istim in enumerate(nseg):
         distance += self.cell.length[j]
         if distance > (i + 1) * freq_step:
             i += 1
         freq = frequencies[i]
         pointprocess = {
             'idx': istim,
             'pptype': 'SinSyn',
             'pkamp': 3.6,
             'freq': freq,
             'phase': -np.pi / 2,
             'dur': self.cell.tstop,
         }
         stimulus = LFPy.StimIntElectrode(self.cell, **pointprocess)
Beispiel #25
0
def clamp_ends(cell, pulse_start, pulse_end, voltage=-70., axis='z'):
    '''
    Clamp the extremities of a cell
    Should only be used for ball and stick models, otherwise to update
    Pay attention to the orientation, here the cell is assumed to be
    horizontally oriented along the corresponding x/y/z axis.
    '''
    pointprocesses = {'pptype': 'SEClamp', 'amp1': voltage, 'dur1': pulse_end}
    if axis == 'x':
        lfpy.StimIntElectrode(cell, np.argmax(cell.xend), **pointprocesses)
        lfpy.StimIntElectrode(cell, np.argmin(cell.xend), **pointprocesses)
    elif axis == 'y':
        lfpy.StimIntElectrode(cell, np.argmax(cell.yend), **pointprocesses)
        lfpy.StimIntElectrode(cell, np.argmin(cell.yend), **pointprocesses)
    elif axis == 'z':
        lfpy.StimIntElectrode(cell, np.argmax(cell.zend), **pointprocesses)
        lfpy.StimIntElectrode(cell, np.argmin(cell.zend), **pointprocesses)
    return
Beispiel #26
0
    def test_Network_02(self):
        cellParameters = dict(
            morphology=os.path.join(LFPy.__path__[0], 'test',
                                    'ball_and_sticks_w_lists.hoc'),
            templatefile=os.path.join(LFPy.__path__[0], 'test',
                                      'ball_and_stick_template.hoc'),
            templatename='ball_and_stick_template',
            templateargs=None,
            passive=False,
            dt=2**-3,
            tstop=100,
            delete_sections=False,
        )

        populationParameters = dict(
            CWD=None,
            CELLPATH=None,
            Cell=LFPy.NetworkCell,
            cell_args=cellParameters,
            pop_args=dict(radius=100, loc=0., scale=20.),
            rotation_args=dict(x=0, y=0),
            POP_SIZE=4,
            name='test',
        )
        networkParameters = dict(dt=2**-3,
                                 tstart=0.,
                                 tstop=100.,
                                 v_init=-65.,
                                 celsius=6.3,
                                 OUTPUTPATH='tmp_testNetworkPopulation')
        clampParams = {
            'idx': 0,
            'pptype': 'VClamp',
            'amp[0]': -65,
            'dur[0]': 10,
            'amp[1]': 0,
            'dur[1]': 1,
            'amp[2]': -65,
            'dur[2]': 1E8,
        }

        # set up
        network = LFPy.Network(**networkParameters)
        network.create_population(**populationParameters)
        connectivity = network.get_connectivity_rand(pre='test',
                                                     post='test',
                                                     connprob=1)

        # test connectivity
        self.assertTrue(
            np.all(connectivity == (
                np.eye(populationParameters['POP_SIZE']) == 0)))

        # connect
        network.connect(pre='test',
                        post='test',
                        connectivity=connectivity,
                        multapseargs=dict(loc=1, scale=1E-9))

        # create synthetic AP in cell with gid == 0
        for population in network.populations.values():
            for cell in population.cells:
                if cell.gid == 0:
                    vclamp = LFPy.StimIntElectrode(cell=cell, **clampParams)

        # simulate
        network.simulate()

        # test output
        for population in network.populations.values():
            for cell in population.cells:
                self.assertFalse(np.all(cell.somav == network.v_init))

        network.pc.gid_clear()
        os.system('rm -r tmp_testNetworkPopulation')
        neuron.h('forall delete_section()')
Beispiel #27
0
    def test_slice_shift_invariance_pointsource(self):
        h = 200
        z_shift_1 = 0
        z_shift_2 = -352

        electrodeParams_1 = {
            'sigma_T': 0.3,
            'sigma_S': 1.5,
            'sigma_G': 0.0,
            'h': h,
            'z_shift': z_shift_1,
            'x': np.linspace(0, 1000, 11),
            'y': np.zeros(11),
            'z': np.zeros(11) + z_shift_1,
            'squeeze_cell_factor': None,
        }

        electrodeParams_2 = {
            'sigma_T': 0.3,
            'sigma_S': 1.5,
            'sigma_G': 0.0,
            'h': h,
            'z_shift': z_shift_2,
            'x': np.linspace(0, 1000, 11),
            'y': np.zeros(11),
            'z': np.zeros(11) + z_shift_2,
            'squeeze_cell_factor': None,
        }
        stimParams = {
            'pptype': 'SinSyn',
            'delay': -100.,
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'phase': -np.pi / 2,
            'bias': 0.,
            'record_current': True
        }
        stickParams = {
            'morphology': os.path.join(
                LFPy.__path__[0],
                'test',
                'ball_and_sticks.hoc'),
            'passive_parameters': {
                'g_pas': 1. / 30000,
                'e_pas': -65},
            'passive': True,
            'tstart': -10,
            'tstop': 20,
            'dt': 2**-4,
            'nsegs_method': 'lambda_f',
            'lambda_f': 100,
        }
        stick = LFPy.Cell(**stickParams)
        stick.set_rotation(y=np.pi / 2)

        LFPy.StimIntElectrode(stick, stick.get_closest_idx(0, 0, 0),
                              **stimParams)

        stick.simulate(rec_imem=True)

        methods = ["pointsource", "linesource", "root_as_point"]

        for method in methods:
            electrodeParams_1["method"] = method
            electrodeParams_2["method"] = method

            stick.set_pos(z=z_shift_1 + h / 2)
            MEA_shift_1 = LFPy.RecMEAElectrode(stick, **electrodeParams_1)
            M_1 = MEA_shift_1.get_transformation_matrix()

            stick.set_pos(z=z_shift_2 + h / 2)
            MEA_shift_2 = LFPy.RecMEAElectrode(stick, **electrodeParams_2)
            M_2 = MEA_shift_2.get_transformation_matrix()

            np.testing.assert_allclose(M_1 @ stick.imem,
                                       M_2 @ stick.imem, rtol=1E-7)
Beispiel #28
0
        'record_current': True,
        'pptype': 'IClamp',
        'amp': amp,
        'dur': sim_length,
        'delay': 0
    }

    if z_injected == "soma":
        pointprocess['idx'] = cell.get_idx(section='soma')[0]
    elif z_injected == 'axon':
        pointprocess['idx'] = cell.get_idx(section='axon1')[10]
    else:
        print("Bipolar LFP not implemented")
        raise SystemExit(0)
    # Create synapse and set time of synaptic input
    stimulus = LFPy.StimIntElectrode(cell, **pointprocess)

    x = np.arange(L_soma, 1.2 * L_axon + 1, 1)
    y = np.array([1, 1.5, 2])
    X, Y = np.meshgrid(x, y)
    Z = np.zeros(X.shape)

    # Define electrode parameters
    grid_electrode_parameters = {
        'sigma': 0.05,  # extracellular conductivity (S/m?)
        'x': X.flatten(),  # electrode requires 1d vector of positions
        'y': Y.flatten(),  # electrode requires 1d vector of positions
        'z': Z.flatten(),
        'method': 'soma_as_point',  # treat soma segment as line source
    }
Beispiel #29
0
    for morphologyfile in glob(os.path.join('morphology', '*')):
        if COUNTER % SIZE == RANK:
            # Instantiate the cell(s) using LFPy
            cell = LFPy.TemplateCell(morphology=morphologyfile,
                                     templatefile=posixpth(
                                         os.path.join(NRN, 'template.hoc')),
                                     templatename=templatename,
                                     templateargs=1 if add_synapses else 0,
                                     tstop=tstop,
                                     dt=dt,
                                     nsegs_method=None)

            # set view as in most other examples
            cell.set_rotation(x=np.pi / 2)

            pointProcess = LFPy.StimIntElectrode(cell, **PointProcParams)

            electrode = LFPy.RecExtElectrode(x=np.array([-40, 40., 0, 0]),
                                             y=np.array([0, 0, -40, 40]),
                                             z=np.zeros(4),
                                             sigma=0.3,
                                             r=5,
                                             n=50,
                                             N=np.array([[1, 0, 0], [1, 0, 0],
                                                         [1, 0, 0], [1, 0,
                                                                     0]]),
                                             method='soma_as_point')
            # run simulation
            cell.simulate(electrode=electrode)

            # compute LFP
Beispiel #30
0
    def test_compare_anisotropic_lfp_methods(self):
        stickParams = {
            'morphology': os.path.join(LFPy.__path__[0], 'test', 'stick.hoc'),
            'passive_parameters': {'g_pas': 1. / 30000, 'e_pas': -65},
            'passive': True,
            'tstart': 0,
            'tstop': 20,
            'dt': 2**-4,
            'nsegs_method': 'lambda_f',
            'lambda_f': 1000,

        }
        stimParams = {
            'pptype': 'SinSyn',
            'delay': -100.,
            'dur': 1000.,
            'pkamp': 1.,
            'freq': 100.,
            'phase': -np.pi / 2,
            'bias': 0.,
            'record_current': True
        }

        electrodeParams = {
            'sigma': [0.3, 0.3, 0.45],
            'x': np.array([0, 1000]),
            'y': np.zeros(2),
            'z': np.zeros(2),
        }

        stick = LFPy.Cell(**stickParams)
        stick.set_pos(z=-stick.z[0, 0])

        LFPy.StimIntElectrode(stick, stick.get_closest_idx(0, 0, 1000),
                              **stimParams)

        ps_electrodeParams = electrodeParams.copy()
        ls_electrodeParams = electrodeParams.copy()
        sap_electrodeParams = electrodeParams.copy()

        ps_electrodeParams["method"] = "pointsource"
        ls_electrodeParams["method"] = "linesource"
        sap_electrodeParams["method"] = "root_as_point"

        electrode_ps = LFPy.RecExtElectrode(stick, **ps_electrodeParams)
        electrode_ls = LFPy.RecExtElectrode(stick, **ls_electrodeParams)
        electrode_sap = LFPy.RecExtElectrode(stick, **sap_electrodeParams)

        stick.simulate(probes=[electrode_ps, electrode_ls, electrode_sap],
                       rec_imem=True, rec_vmem=True)

        # Test that distant electrode is independent of choice of method
        np.testing.assert_almost_equal(electrode_ps.data[1, :],
                                       electrode_ls.data[1, :])

        np.testing.assert_almost_equal(electrode_ps.data[1, :],
                                       electrode_sap.data[1, :])

        # Hack to test that LFP close to stick is dependent on choice of method
        np.testing.assert_raises(AssertionError, np.testing.assert_array_equal,
                                 electrode_ps.data[0, :],
                                 electrode_ls.data[0, :])

        np.testing.assert_raises(AssertionError, np.testing.assert_array_equal,
                                 electrode_ps.data[0, :],
                                 electrode_sap.data[0, :])