Exemplo n.º 1
0
def return_eeg(cell, radii, sigmas, eeg_coords, morph_type):
    # compute current dipole moment
    cdm = LFPy.CurrentDipoleMoment(cell)
    P = cdm.get_transformation_matrix() @ cell.imem
    # set dipole position
    r_soma_syns = [cell.get_intersegment_vector(idx0=0, idx1=i)
                   for i in cell.synidx]
    r_mid = np.average(r_soma_syns, axis=0)
    if morph_type == 'l5i':
        somapos = np.array([0., 0., radii[0]-1200])
    else:
        somapos = np.array([0., 0., radii[0] - np.max(cell.z) - 50])
    dipole_pos = r_mid + somapos
    cell.set_pos(x=somapos[0], y=somapos[1], z=somapos[2])

    # multi_dipoles, dipole_locs = cell.get_multi_current_dipole_moments()
    # t_point = 800
    # P_from_multi_dipoles = np.sum(multi_dipoles[:,t_point,:],axis=0)
    # print('single dipole:', P[t_point])
    # print('sum of multi-dipoles', P_from_multi_dipoles)
    # compute eeg with 4S model
    fs_eeg = LFPy.FourSphereVolumeConductor(eeg_coords, radii=radii,
                                            sigmas=sigmas)

    eeg = fs_eeg.get_transformation_matrix(dipole_pos) @ P
    eeg_multidip = fs_eeg.get_dipole_potential_from_multi_dipoles(cell)

    eeg_avg = np.average(eeg, axis=0)
    eeg_multidip_avg = np.average(eeg_multidip, axis=0)
    # convert from mV to pV:
    eeg_avg = eeg_avg * 1e9
    eeg_multidip_avg = eeg_multidip_avg * 1e9

    return eeg_avg, eeg_multidip_avg
Exemplo n.º 2
0
def cell_w_synapse_from_sections_w_electrode(morphology, electrode_locs):
    '''
    Make cell and synapse objects, set spike, simulate and return cell
    '''
    cellParams = {
        'morphology': morphology,
        'cm': 1,
        'Ra': 150,
        'v_init': -65,
        'passive': True,
        'passive_parameters': {
            'g_pas': 1. / 30000,
            'e_pas': -65
        },
        'dt': 2**-6,
        'tstart': -50,
        'tstop': 50,
        'delete_sections': False
    }

    electrodeParams = {
        'sigma': 0.3,
        'x': electrode_locs[:, 0],
        'y': electrode_locs[:, 1],
        'z': electrode_locs[:, 2],
    }
    cell = LFPy.Cell(**cellParams)
    electrode = LFPy.RecExtElectrode(cell, **electrodeParams)
    cdm = LFPy.CurrentDipoleMoment(cell)

    synapse_parameters = {
        'e': 0.,
        'syntype': 'ExpSyn',
        'tau': 5.,
        'weight': .1,
        'record_current': True,
        'idx': cell.totnsegs - 1
    }

    synapse = LFPy.Synapse(cell, **synapse_parameters)
    synapse.set_spike_times(np.array([1.]))
    cell.simulate(probes=[electrode, cdm], rec_vmem=True)
    return cell, electrode, cdm
Exemplo n.º 3
0
def cell_w_synapse_from_sections(morphology, rec_current_dipole_moment=False):
    '''
    Make cell and synapse objects, set spike, simulate and return cell
    '''
    cellParams = {
        'morphology': morphology,
        'cm': 1,
        'Ra': 150,
        'v_init': -65,
        'passive': True,
        'passive_parameters': {
            'g_pas': 1. / 30000,
            'e_pas': -65
        },
        'dt': 2**-6,
        'tstart': -50,
        'tstop': 50,
        'delete_sections': False
    }

    synapse_parameters = {
        'e': 0.,
        'syntype': 'ExpSyn',
        'tau': 5.,
        'weight': .001,
        'record_current': True,
        'idx': 1
    }

    cell = LFPy.Cell(**cellParams)
    synapse = LFPy.Synapse(cell, **synapse_parameters)
    synapse.set_spike_times(np.array([1.]))
    if rec_current_dipole_moment:
        probes = [LFPy.CurrentDipoleMoment(cell)]
    else:
        probes = []
    cell.simulate(probes=probes, rec_vmem=True)
    if rec_current_dipole_moment:
        cell.current_dipole_moment = probes[0].data
    return cell
Exemplo n.º 4
0
def make_data(morphology, cell_model, rot, rz, radii, sigmas, electrode_locs,
              syn_idcs, spiking, syn_input_time):
    # set cell and synapse parameters
    cell_parameters, synapse_parameters = set_parameters(
        morphology, cell_model, spiking)
    [xrot, yrot, zrot] = rot
    # create four-sphere class instance
    fs = LFPy.FourSphereVolumeConductor(electrode_locs,
                                        radii=radii,
                                        sigmas=sigmas)
    # lists for storing data:
    p_list = []
    t_max_list = []
    p_loc_list = []
    lfp_single_dip_list = []
    lfp_multi_dip_list = []
    RE_list = []
    synlocs = []
    pz_traces = []
    # get data from num_syns simulations
    num_syns = len(syn_idcs)
    for j in range(num_syns):

        cell = create_cell(cell_parameters,
                           active=spiking,
                           x_rot=xrot,
                           y_rot=yrot,
                           z_rot=zrot)
        ## if you know synidx:
        syn_idx = syn_idcs[j]
        # if you only know synapse location:
        # syn_loc = syn_idcs[j]
        # syn_idx = cell.get_closest_idx(x=syn_loc[0], y=syn_loc[1], z=syn_loc[2])
        #        print('syn_idx:', syn_idx)
        cell, synapse = simulate(cell, synapse_parameters, [syn_idx],
                                 syn_input_time)
        # print('cell simulated')

        cell.set_pos(x=rz[0], y=rz[1], z=rz[2])
        syn_loc = (cell.x[syn_idx].mean(), cell.y[syn_idx].mean(),
                   cell.z[syn_idx].mean())
        synlocs.append((syn_loc[0], syn_loc[1], syn_loc[2]))

        # compute current dipole moment and subtract DC-component
        cdm = LFPy.CurrentDipoleMoment(cell)
        dipoles = cdm.get_transformation_matrix() @ cell.imem
        input_idx_before_input = np.argmin(
            np.abs(cell.tvec - syn_input_time)) - 1
        p_dc = dipoles[:, input_idx_before_input]
        dipoles -= p_dc[:, None]

        pz_traces.append(dipoles[2, :])
        # compute timepoint with biggest dipole
        timemax = [np.argmax(np.linalg.norm(np.abs(dipoles), axis=0))]
        t_max_list.append(timemax)
        p = dipoles[:, timemax]
        # compute LFP with single dipole
        # dip_loc = get_mass_center(cell, timemax)
        dip_loc = get_dipole_loc(rz, syn_loc)

        lfp_single_dip = fs.get_transformation_matrix(dip_loc) @ p
        # print('pot from single dip computed')
        # compute LFP with multi-dipole

        # subtract DC-component
        multi_p_319, multi_p_locs = cell.get_multi_current_dipole_moments(
            [input_idx_before_input])
        multi_p_dc = multi_p_319
        multi_p, multi_p_locs = cell.get_multi_current_dipole_moments(timemax)
        multi_p -= multi_p_dc

        Ni, Nd, Nt = multi_p.shape
        lfp_multi_dip = np.zeros((len(electrode_locs), Nt))
        for num in range(Ni):

            pot = fs.get_transformation_matrix(
                multi_p_locs[num]) @ multi_p[num]
            # fs.calc_potential(multi_p[num], multi_p_locs[num])
            lfp_multi_dip += pot

        # print('pot from multi dip computed')
        # compute relative errors
        RE = np.abs((lfp_single_dip - lfp_multi_dip) / lfp_multi_dip)
        print('syn number: {}; syn dist from soma: {}; RE_EEG: {}'.format(
            syn_idx, syn_loc[2] - rz[2], RE[-1]))
        #add data to lists for storage
        p_list.append(p)
        p_loc_list.append(dip_loc)
        lfp_single_dip_list.append(lfp_single_dip)
        lfp_multi_dip_list.append(lfp_multi_dip)
        RE_list.append(RE)

    # Do this for only one cell for plotting
    zips = []
    for x, z in cell.get_idx_polygons():
        zips.append(list(zip(x, z)))
    zmax = np.max(cell.z)
    soma_vmem = cell.vmem[0]
    tvec = cell.tvec

    return (p_list, pz_traces, lfp_multi_dip_list, lfp_single_dip_list,
            synlocs, zips, zmax, tvec, soma_vmem)
Exemplo n.º 5
0
        'syntype': 'ExpSyn',  # exponential synapse
        'tau': 5.,  # synapse time constant
        'weight': 0.001,  # 0.001, # synapse weight
        'record_current': True  # record synapse current
    }
    # create cell with parameters in dictionary
    cell = LFPy.Cell(**cell_params)
    pos = syn_loc
    synapse_params['idx'] = cell.get_closest_idx(x=pos[0], y=pos[1], z=pos[2])
    synapse = LFPy.Synapse(cell, **synapse_params)
    synapse.set_spike_times(np.array([5.]))

    cell.simulate(rec_imem=True)

    # compute dipole
    cdm = LFPy.CurrentDipoleMoment(cell)
    P = cdm.get_transformation_matrix() @ cell.imem

    somapos = np.array([0., 0., 77500])
    r_soma_syns = [
        cell.get_intersegment_vector(idx0=0, idx1=i) for i in cell.synidx
    ]
    r_mid = np.average(r_soma_syns, axis=0)
    r_mid = somapos + r_mid / 2.

    eeg_coords_top = np.array([[0., 0., radii[3] - rad_tol]])
    four_sphere_top = LFPy.FourSphereVolumeConductor(eeg_coords_top, radii,
                                                     sigmas)
    pot_db_4s_top = four_sphere_top.get_dipole_potential(P, r_mid)
    eeg_top = np.array(pot_db_4s_top) * 1e9
Exemplo n.º 6
0
    ##########################################################################
    # Set up extracellular electrodes and devices
    ##########################################################################
    probes = []

    if PSET.COMPUTE_LFP:
        electrode = LFPy.RecExtElectrode(cell=None, **PSET.electrodeParams)
        probes.append(electrode)

    if PSET.COMPUTE_ECOG:
        ecog_electrode = LFPy.RecMEAElectrode(cell=None, **PSET.ecogParameters)
        probes.append(ecog_electrode)

    if PSET.COMPUTE_P:
        current_dipole_moment = LFPy.CurrentDipoleMoment(cell=None)
        probes.append(current_dipole_moment)

    ##########################################################################
    # Recording of additional variables
    ##########################################################################
    if RANK == 0:
        network.t = neuron.h.Vector()
        network.t.record(neuron.h._ref_t)
    else:
        network.t = None

    ##########################################################################
    # run simulation, gather results across all RANKs
    ##########################################################################
    # Assert that connect routines has finished across RANKS before starting
Exemplo n.º 7
0
    def test_Network_01(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')
        # set up
        network = LFPy.Network(**networkParameters)
        network.create_population(**populationParameters)
        connectivity = network.get_connectivity_rand(pre='test',
                                                     post='test',
                                                     connprob=0.5)

        # connect
        network.connect(pre='test', post='test', connectivity=connectivity)

        # create CurrentDipoleMoment object for probing
        probes = [LFPy.CurrentDipoleMoment(cell=None)]

        # run simutation, record using probe, resolve into populations
        SPIKES, LFP = network.simulate(probes=probes,
                                       rec_pop_contributions=True)

        # current dipole momemnt
        P = probes[0].data

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

        self.assertTrue(np.all(P['test'] == 0.))
        self.assertTrue(P.shape[1] == cell.somav.size)

        network.pc.gid_clear()
        os.system('rm -r tmp_testNetworkPopulation')
        for population in network.populations.values():
            for cell in population.cells:
                cell.strip_hoc_objects()
        neuron.h('forall delete_section()')
Exemplo n.º 8
0
def run_cell_simulation(make_ca_spike, dt, cell_name, grid_elec_params,
                        elec_params):

    T = 100

    if cell_name == 'almog':
        model_folder = join('cell_models', 'almog')

        neuron.load_mechanisms(model_folder)
        os.chdir(model_folder)
        cell_parameters = {
            'morphology': join('A140612.hoc'),
            'v_init': -62,
            'passive': False,
            'nsegs_method': None,
            'dt': dt,  # [ms] Should be a power of 2
            'tstart': -200,  # [ms] Simulation start time
            'tstop': T,  # [ms] Simulation end time
            'custom_code':
            [join('cell_model.hoc')]  # Loads model specific code
        }

        cell = LFPy.Cell(**cell_parameters)
        os.chdir(join('..', '..'))
        cell.set_rotation(x=np.pi / 2, y=0.1)
    elif cell_name == 'hay':

        model_folder = join('cell_models', 'hay', 'L5bPCmodelsEH')
        neuron.load_mechanisms(join(model_folder, "mod"))

        ##define cell parameters used as input to cell-class
        cellParameters = {
            'morphology':
            join(model_folder, "morphologies", "cell1.asc"),
            'templatefile': [
                join(model_folder, "models", "L5PCbiophys3.hoc"),
                join(model_folder, "models", "L5PCtemplate.hoc")
            ],
            'templatename':
            'L5PCtemplate',
            'templateargs':
            join(model_folder, "morphologies", "cell1.asc"),
            'passive':
            False,
            'nsegs_method':
            None,
            'dt':
            dt,
            'tstart':
            -200,
            'tstop':
            T,
            'v_init':
            -60,
            'celsius':
            34,
            'pt3d':
            True,
        }
        cell = LFPy.TemplateCell(**cellParameters)
        cell.set_rotation(x=np.pi / 2, y=0.1)

    plot_idxs = [cell.somaidx[0], cell.get_closest_idx(z=500)]
    idx_clr = {idx: ['b', 'orange'][num] for num, idx in enumerate(plot_idxs)}

    if cell_name == 'hay':
        weights = [0.07, 0.15]
    elif cell_name == 'almog':
        weights = [0.05, 0.15]

    delay = 30
    synapse_s = LFPy.Synapse(cell,
                             idx=cell.get_closest_idx(z=0),
                             syntype='Exp2Syn',
                             weight=weights[0],
                             tau1=0.1,
                             tau2=1.)
    synapse_s.set_spike_times(np.array([delay]))

    synapse_a = None
    if make_ca_spike:
        synapse_a = LFPy.Synapse(cell,
                                 idx=cell.get_closest_idx(z=400),
                                 syntype='Exp2Syn',
                                 weight=weights[1],
                                 tau1=0.1,
                                 tau2=10.)
        synapse_a.set_spike_times(np.array([delay]))
    cell.simulate(rec_imem=True, rec_vmem=True)
    print("MAX |I_mem(soma, apic)|: ",
          np.max(np.abs(cell.imem[plot_idxs]), axis=1))

    elec = LFPy.RecExtElectrode(cell, **elec_params)
    elec_LFP = 1e3 * elec.get_transformation_matrix() @ cell.imem
    elec_LFP -= elec_LFP[:, 0, None]

    grid_electrode = LFPy.RecExtElectrode(cell, **grid_elec_params)
    grid_LFP = 1e3 * grid_electrode.get_transformation_matrix() @ cell.imem
    grid_LFP -= grid_LFP[:, 0, None]

    cdm = LFPy.CurrentDipoleMoment(cell)
    cdm = cdm.get_transformation_matrix() @ cell.imem
    cdm -= cdm[:, 0, None]

    cell_data_dict = {
        "vmem": cell.vmem.copy(),
        "tvec": cell.tvec.copy(),
        "elec_LFP": elec_LFP.copy(),
        "grid_LFP": grid_LFP.copy(),
        "cdm": cdm.copy(),
        "cell_x": cell.x.copy(),
        "cell_z": cell.z.copy(),
    }
    synapse_s = None
    synapse_a = None
    cell.__del__()
    return cell_data_dict, idx_clr, plot_idxs
Exemplo n.º 9
0
def make_data(morphology,
              syninds,
              dip_loc=None,
              cell_model=None,
              x_rot=0,
              y_rot=0,
              z_rot=0,
              active=False):

    sigma = 0.3  #extracellular conductivity
    k = 1e6  # convert from mV to nV

    # compute LFP close to neuron
    # set up electrodes close to neuron
    X, Z = np.meshgrid(np.linspace(-550, 550, 101),
                       np.linspace(-250, 850, 101))
    Y = np.zeros(X.shape)
    # simulate cell
    (cell_parameters, synapse_parameters,
     grid_electrode_parameters) = set_parameters(morphology,
                                                 X,
                                                 Y,
                                                 Z,
                                                 sigma=sigma,
                                                 cell_model=cell_model)
    cell, synapse, grid_electrode_LFP = simulate(cell_parameters,
                                                 synapse_parameters,
                                                 grid_electrode_parameters,
                                                 syninds,
                                                 x_rot=x_rot,
                                                 y_rot=y_rot,
                                                 z_rot=z_rot,
                                                 active=active)

    # multicompartment modeling of LFP close to cell
    cb_LFP_close = grid_electrode_LFP * k

    # multi-dipole modeling of LFP close to cell
    multi_dips, multi_dip_locs = cell.get_multi_current_dipole_moments()
    inf_vol = LFPy.InfiniteVolumeConductor(sigma)
    gridpoints_close = np.array([X.flatten(), Y.flatten(), Z.flatten()]).T
    multi_dip_LFP_close = inf_vol.get_multi_dipole_potential(
        cell, gridpoints_close) * k

    # single-dipole modeling of LFP close to cell
    cdm = LFPy.CurrentDipoleMoment(cell)
    single_dip = cdm.get_transformation_matrix() @ cell.imem
    syninds = cell.synidx
    if dip_loc is not None:
        r_mid = dip_loc
    else:
        r_soma_syns = [
            cell.get_intersegment_vector(idx0=0, idx1=i) for i in syninds
        ]
        r_mid = np.average(r_soma_syns, axis=0)
        r_mid = r_mid / 2. + cell.somapos

    db_LFP_close = inf_vol.get_dipole_potential(single_dip,
                                                gridpoints_close - r_mid) * k

    # compute LFP far from neuron
    # set up electrodes
    X_f, Z_f = np.meshgrid(np.linspace(-15000, 15001, 101),
                           np.linspace(-15000, 15000, 101))
    Y_f = np.zeros(X.shape)
    grid_electrode_parameters = {
        'x': X_f.flatten(),
        'y': Y_f.flatten(),
        'z': Z_f.flatten()
    }
    # simulate cell
    cell, synapse, grid_electrode_far_LFP = simulate(cell_parameters,
                                                     synapse_parameters,
                                                     grid_electrode_parameters,
                                                     syninds,
                                                     x_rot=x_rot,
                                                     y_rot=y_rot,
                                                     z_rot=z_rot,
                                                     active=active)

    # multicompartment modeling of LFP far from cell
    cb_LFP_far = grid_electrode_far_LFP * k
    # multi-dipole modeling of LFP far from cell
    gridpoints_far = np.array([X_f.flatten(), Y_f.flatten(), Z_f.flatten()]).T
    multi_dip_LFP_far = inf_vol.get_multi_dipole_potential(
        cell, gridpoints_far) * k
    # single-dipole modeling of LFP far from cell
    db_LFP_far = inf_vol.get_dipole_potential(single_dip,
                                              gridpoints_far - r_mid) * k

    cdm = LFPy.CurrentDipoleMoment(cell)
    single_dip = cdm.get_transformation_matrix() @ cell.imem
    time_max = np.argmax(np.abs(np.linalg.norm(single_dip, axis=0)))
    LFP_max = 100.  #nV #np.round(np.max(np.abs(grid_electrode_LFP[:, time_max])))

    return (cell, cb_LFP_close, cb_LFP_far, multi_dip_LFP_close,
            multi_dip_LFP_far, db_LFP_close, db_LFP_far, LFP_max, time_max,
            multi_dips, multi_dip_locs, single_dip, r_mid, X, Z, X_f, Z_f)