Esempio n. 1
0
def dip_source_loc(evoked, cov,  fs_subj, study_path, plot=False):
    evo_crop = evoked.copy().crop(-0.003, 0.003)
    subj = fs_subj.strip('_an') if fs_subj.find('_an') > 0 else fs_subj
    img_type = 'anony' if fs_subj.find('_an') > 0 else 'orig'

    trans_fname = op.join(study_path, 'source_stim', subj, 'source_files', img_type, '%s_fid-trans.fif' % fs_subj)
    bem_fname = op.join(subjects_dir, fs_subj, 'bem', '%s-bem-sol.fif' % fs_subj)

    cond = evoked.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)

    dip, res = mne.fit_dipole(evo_crop, cov, bem_fname, trans_fname, min_dist=10, n_jobs=3)

    import mne.transforms as tra
    from scipy import linalg
    trans = mne.read_trans(trans_fname)

    stim_point = stim_coords['surf']  # get point for plot in mm
    #dip.pos[np.argmax(dip.gof)] = tra.apply_trans(surf_to_head, stim_coords['surf_ori']/1e3)  # check stim loc (apply affine in m)

    dip_surf = tra.apply_trans(trans['trans'], dip.pos[np.argmax(dip.gof)]) * 1e3  # transform from head to surface
    dist_surf = euclidean(dip_surf, stim_point)  # compute distance in surface space
    print(dist_surf)

    if plot:
        # Plot the result in 3D brain with the MRI image.
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        dip.plot_locations(trans_fname, fs_subj, subjects_dir, mode='orthoview', coord_frame='mri', ax=ax, show_all=True,
                           idx='gof')
        ax.scatter(stim_point[0], stim_point[1], stim_point[2])
        ax.plot([stim_point[0], -128], [stim_point[1], stim_point[1]], [stim_point[2], stim_point[2]], color='g')
        ax.plot([stim_point[0], stim_point[0]], [stim_point[1], -128], [stim_point[2], stim_point[2]], color='g')
        ax.plot([stim_point[0], stim_point[0]], [stim_point[1], stim_point[1]], [stim_point[2], -128], color='g')
        ax.text2D(0.05, 0.90, 'distance: %i mm \nstim coords = %0.1f %0.1f %0.1f' % (dist_surf, stim_point[0], stim_point[1], stim_point[2]),
                  transform=ax.transAxes)
        red_patch = mpatches.Patch(color='red')
        green_patch = mpatches.Patch(color='green')
        fig.legend(handles=[red_patch, green_patch], labels=['dipole', 'electrode'])

        fig.savefig(op.join(study_path, 'source_stim', subj, 'figures', 'dipole', '%s_dip_15mm.png' % cond))
        plt.close()

        plot_dipole_amplitudes(dip)
        plot_dipole_locations(dip, trans, subj, subjects_dir=subjects_dir)
    return dist_surf
Esempio n. 2
0
def single_trial_source(epo_alig):
    from mne.minimum_norm import apply_inverse_epochs
    evoked = epo_alig.average()
    cond = evoked.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)

    evo_crop = evoked.copy().crop(-0.001, 0.001)

    inv = mne.minimum_norm.make_inverse_operator(evoked.info, fwd, cov, loose=1, depth=None)

    snr = 30.
    lambda2 = 1. / snr ** 2
    method = 'dSPM'

    stcs = apply_inverse_epochs(epo_alig, inv, lambda2, method,
                                nave=evoked.nave)

    mean_stc = sum(stcs) / len(stcs)
Esempio n. 3
0
def source_loc(cond_fname, subj, fwd):
    eeg_epo = mne.read_epochs(cond_fname + '-epo.fif')
    cov = mne.compute_covariance(eeg_epo, method='shrunk', tmin=-0.5, tmax=-0.3)
    inv = mne.minimum_norm.make_inverse_operator(eeg_epo.info, fwd, cov, loose=0.2, depth=0.8)

    evoked = eeg_epo.average()

    method = "dSPM"
    snr = 3.
    lambda2 = 1. / snr ** 2
    stc = mne.minimum_norm.apply_inverse(evoked, inv, lambda2, method=method, pick_ori=None)

    # from surfer import Brain  # noqa
    # src_fname = op.join(study_path, 'source_stim', 'images', subj, '%s-oct5-src.fif' % subj)
    # src = mne.read_source_spaces(src_fname, patch_stats=True)
    #
    # brain = Brain(subj, 'lh', 'inflated', subjects_dir=subjects_dir)
    # surf = brain.geo['lh']
    #
    # vertidx = np.where(src[0]['inuse'])[0]
    #
    # mlab.points3d(surf.x[vertidx[:-1]], surf.y[vertidx[:-1]],
    #               surf.z[vertidx[:-1]], color=(1, 1, 0), scale_factor=1.5)
    # mlab.show()

    cond = eeg_epo.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)

    vertno_max, time_max = stc.get_peak(hemi='lh')
    stc_max = np.max(stc.data)

    brain_inf = stc.plot(surface='inflated', hemi='lh', subjects_dir=subjects_dir,
                         clim=dict(kind='value', lims=[0, stc_max*0.75, stc_max]),
                         initial_time=time_max, time_unit='s', alpha=1, background='w', foreground='k')

    brain_inf.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue',
                       scale_factor=0.8)

    brain_inf.add_foci(stim_coords, map_surface='inflated', hemi='lh', color='green', scale_factor=0.8)

    brain_inf.show_view('lateral')  # mlab.view(130, 90)
    fig_fname = op.join(study_path, 'source_stim', 'figures', '%s_inf_foci.eps' % cond)
    brain_inf.save_image(fig_fname)
    mlab.show()
def source_loc(evoked, cov, fwd, subj, img_type, study_path, plot=False):
    cond = evoked.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)
    stim_params = get_stim_params(cond)

    inv = mne.minimum_norm.make_inverse_operator(evoked.info,
                                                 fwd,
                                                 cov,
                                                 loose=0.2,
                                                 depth=0.8)
    method = "dSPM"
    snr = 300.
    lambda2 = 1. / snr**2
    stc = mne.minimum_norm.apply_inverse(evoked,
                                         inv,
                                         lambda2,
                                         method=method,
                                         pick_ori=None)
    stc.save(
        op.join(study_path, 'source_stim', subj, 'source_files', img_type,
                'stc', '%s_%s' % (subj, cond)))

    # plot_source_space(subj, study_path, subjects_dir)

    hemi = 'lh' if stim_params['is_left'] else 'rh'
    contact_nr = int(re.findall('\d+', stim_params['ch'])[0])
    view = 'medial' if contact_nr < 5 else 'lateral'  # improve view selection

    vertno_max, time_max = stc.get_peak(hemi=hemi)
    stc_max = np.max(stc.data)

    if plot:
        brain_inf = stc.plot(surface='inflated',
                             hemi=hemi,
                             subjects_dir=subjects_dir,
                             subject=fs_subj,
                             clim=dict(kind='value',
                                       lims=[0, stc_max * 0.75, stc_max]),
                             initial_time=time_max,
                             time_unit='s',
                             alpha=1,
                             background='w',
                             foreground='k')

        brain_inf.add_foci(vertno_max,
                           coords_as_verts=True,
                           hemi=hemi,
                           color='blue',
                           scale_factor=0.8)

        brain_inf.add_foci(stim_coords['surf_ori'],
                           map_surface='pial',
                           hemi=hemi,
                           color='green',
                           scale_factor=0.8)

        brain_inf.show_view(view)  # mlab.view(130, 90)
        fig_fname = op.join(study_path, 'source_stim', subj, 'figures',
                            'distributed', '%s_inf_foci.eps' % cond)
        #brain_inf.save_image(fig_fname)
        mlab.show()
        #mlab.clf()

    max_mni = mne.vertex_to_mni(
        vertno_max, hemis=0, subject=subj, subjects_dir=subjects_dir
    )  # mni coords of vertex (ojo vertex resolution ico-5)
    stim_mni = stim_coords['mni']  # mni coords of stimulation
    dist_mni = euclidean(max_mni, stim_mni)

    print(dist_mni)
    return dist_mni
def dipole_source_loc(evoked, cov, fs_subj, study_path, plot=False):
    evo_crop = evoked.copy().crop(-0.005, 0.005)
    subj = fs_subj.strip('_an') if fs_subj.find('_an') > 0 else fs_subj
    img_type = 'anony' if fs_subj.find('_an') > 0 else 'orig'

    seeg_ch_info = pd.read_csv(
        op.join(study_path, 'physio_data', subj, 'chan_info',
                '%s_seeg_ch_info.csv' % subj))

    # ori_to_an_fname = op.join(study_path, 'freesurfer_subjects', subj, 'mri', 'ori_to_an_trans.lta')  # mri to mri
    # ori_to_an_trans = np.genfromtxt(ori_to_an_fname, skip_header=8, skip_footer=18)

    trans_fname = op.join(study_path, 'source_stim', subj, 'source_files',
                          img_type, '%s_static-trans.fif' % fs_subj)
    bem_fname = op.join(subjects_dir, fs_subj, 'bem',
                        '%s-bem-sol.fif' % fs_subj)

    cond = eeg_epo.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)

    # Fit a dipole
    dip = mne.fit_dipole(evo_crop,
                         cov,
                         bem_fname,
                         trans_fname,
                         min_dist=5,
                         n_jobs=2)[0]

    from mne.beamformer import rap_music
    dip = rap_music(evo_crop,
                    fwd,
                    cov,
                    n_dipoles=1,
                    return_residual=True,
                    verbose=True)[0][0]

    import mne.transforms as tra
    from scipy import linalg
    trans = mne.read_trans(trans_fname)

    surf_to_head = linalg.inv(trans['trans'])

    # stim_point = tra.apply_trans(surf_to_head, stim_coords['surf']/1e3)
    stim_point = stim_coords['surf_ori']  # get point for plot in mm
    #dip.pos[np.argmax(dip.gof)] = tra.apply_trans(surf_to_head, stim_coords['surf_ori']/1e3)  # check stim loc (apply affine in m)

    #stim_point = tra.apply_trans(ori_to_an_trans, stim_point)

    dip_surf = tra.apply_trans(trans['trans'], dip.pos[np.argmax(
        dip.gof)]) * 1e3  # transform from head to surface
    dist_surf = euclidean(dip_surf,
                          stim_point)  # compute distance in surface space
    print(dist_surf)

    if plot:
        # Plot the result in 3D brain with the MRI image.
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        dip.plot_locations(trans_fname,
                           fs_subj,
                           subjects_dir,
                           mode='orthoview',
                           coord_frame='mri',
                           ax=ax,
                           show_all=True,
                           idx='gof')
        ax.scatter(stim_point[0], stim_point[1], stim_point[2])
        ax.plot([stim_point[0], -128], [stim_point[1], stim_point[1]],
                [stim_point[2], stim_point[2]],
                color='g')
        ax.plot([stim_point[0], stim_point[0]], [stim_point[1], -128],
                [stim_point[2], stim_point[2]],
                color='g')
        ax.plot([stim_point[0], stim_point[0]], [stim_point[1], stim_point[1]],
                [stim_point[2], -128],
                color='g')
        ax.text2D(0.05,
                  0.90,
                  'distance: %i mm \nstim coords = %0.1f %0.1f %0.1f' %
                  (dist_surf, stim_point[0], stim_point[1], stim_point[2]),
                  transform=ax.transAxes)
        red_patch = mpatches.Patch(color='red')
        green_patch = mpatches.Patch(color='green')
        fig.legend(handles=[red_patch, green_patch],
                   labels=['dipole', 'electrode'])

        fig.savefig(
            op.join(study_path, 'source_stim', subj, 'figures', 'dipole',
                    '%s_dip_15mm.png' % cond))
        plt.close()

        from mne.viz import plot_dipole_locations, plot_dipole_amplitudes
        plot_dipole_amplitudes(dip)
        plot_dipole_locations(dip, trans, subj, subjects_dir=subjects_dir)

    return dist_surf
Esempio n. 6
0
def vol_source_loc(evoked, fwd, cov, fs_subj, method='sLORETA', plot=False):
    cond = evoked.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)

    evo_crop = evoked.copy().crop(-0.003, 0.003)

    inv = mne.minimum_norm.make_inverse_operator(evoked.info, fwd, cov, loose=1, depth=0.8)

    snr = 30.
    lambda2 = 1. / snr ** 2
    stc = mne.minimum_norm.apply_inverse(evo_crop, inv, lambda2, method=method, pick_ori=None)

    from nilearn.plotting import plot_stat_map
    from nilearn.image import index_img
    import nilearn as ni

    nii_fname = op.join(study_path, 'source_stim', subj, 'source_files', img_type, 'stc', '%s_%s_stc.nii' % (subj, cond))
    img = mne.save_stc_as_volume(nii_fname, stc.copy().crop(-0.003, 0.003), fwd['src'], dest='mri', mri_resolution=True)
    mri_file = op.join(subjects_dir, fs_subj, 'mri', 'T1.mgz')

    from nibabel.affines import apply_affine
    mri = nib.load(mri_file)

    img_dat = img.get_data()
    stim_loc_vox = np.unravel_index(img_dat.argmax(), img_dat.shape)
    t_max = stim_loc_vox[-1]

    img_max = index_img(img, t_max)

    loc_coords = apply_affine(mri.affine, stim_loc_vox[:3])
    dist = euclidean(stim_coords['scanner_RAS'], loc_coords)

    max_coords = ni.plotting.find_xyz_cut_coords(img_max, activation_threshold=99.95)

    print('Distance: %0.1f mm' % dist)

    if plot:
        thr = np.percentile(img_max.get_data(), 99.95)
        st_map = plot_stat_map(img_max, mri_file, threshold=thr, display_mode='ortho', cmap=plt.cm.plasma,
                               cut_coords=max_coords)

    img_thr = ni.image.threshold_img(img_max, '99%')

    from scipy import linalg
    inv_aff = linalg.inv(mri.affine)
    stim_scan_coords = apply_affine(inv_aff, stim_loc_vox[:3])
    img_thr_dat = img_thr.get_data()

    dat = img_max.get_data()
    plt.hist(dat[np.nonzero(dat)].flatten())
    plot_stat_map(img_max, mri_file)



    # img_smo = ni.image.smooth_img(index_img(img, t_max), fwhm=50)
    # smo_dat = img_smo.get_data()
    # stim_loc_vox_smo = np.unravel_index(smo_dat.argmax(), smo_dat.shape)
    # loc_coords = apply_affine(mri.affine, stim_loc_vox_smo[:3])
    # dist = euclidean(stim_coords['scanner_RAS'], loc_coords)
    # print('Distance: %0.1f mm' % dist)
    #
    # thr = np.percentile(img_smo.get_data(), 99.99)
    # st_map = plot_stat_map(img_smo, mri_file, threshold=thr, display_mode='ortho', cmap=plt.cm.plasma,
    #                        cut_coords=loc_coords)
    # fname_fig = op.join(study_path, 'source_stim', subj, 'figures', 'distributed', '%s_%s_vol.pdf' % (subj, cond))
    # st_map.savefig(fname_fig)
    # plt.close()
    #
    # stc_dspm = mne.minimum_norm.apply_inverse(evo_crop, inv, lambda2=lambda2,
    #                           method='dSPM')
    #
    # Compute TF-MxNE inverse solution with dipole output
    # from mne.inverse_sparse import tf_mixed_norm, make_stc_from_dipoles
    # alpha_space = 50
    # alpha_time = 0
    # loose = 1
    # depth = 0.2


    # dipoles, residual = tf_mixed_norm(
    #     evo_crop, fwd, cov, alpha_space, alpha_time, loose=loose, depth=depth,
    #     maxit=200, tol=1e-6, weights=stc_dspm, weights_min=8., debias=True,
    #     wsize=16, tstep=4, window=0.05, return_as_dipoles=True,
    #     return_residual=True)
    #
    # stim_coords = find_stim_coords(cond, subj, study_path)
    #
    # import mne.transforms as tra
    # trans_fname = op.join(study_path, 'source_stim', subj, 'source_files', img_type, '%s_fid-trans.fif' % fs_subj)
    # trans = mne.read_trans(trans_fname)
    #
    # stim_point = stim_coords['surf']  # get point for plot in mm
    # #dip.pos[np.argmax(dip.gof)] = tra.apply_trans(surf_to_head, stim_coords['surf_ori']/1e3)  # check stim loc (apply affine in m)
    #
    # idx = np.argmax([np.max(np.abs(dip.amplitude)) for dip in dipoles])
    # dip_surf = tra.apply_trans(trans['trans'], dipoles[idx].pos[0]) * 1e3  # transform from head to surface
    # dist_surf = euclidean(dip_surf, stim_point)  # compute distance in surface space
    # print(dist_surf)
    #
    # plot_dipole_amplitudes(dipoles)
    #
    # # Plot dipole location of the strongest dipole with MRI slices
    #
    # plot_dipole_locations(dipoles[idx], fwd['mri_head_t'], subj,
    #                       subjects_dir=subjects_dir, mode='orthoview',
    #                       idx='amplitude')
    return dist
Esempio n. 7
0
fwd_fname = op.join(study_path, 'source_stim', subj, 'source_files', 'orig',
                    '%s-fwd.fif' % subj)

trans = op.join(study_path, 'source_stim', subj, 'source_files', 'orig', '%s_fid-trans.fif' % subj)

epo_path = op.join(study_path, 'source_stim', subj, 'epochs', 'fif')
conds = glob.glob(epo_path + '/*-epo.fif')

cond_fname = conds[0]

epochs = mne.read_epochs(cond_fname)
epochs.interpolate_bads(reset_bads=True)
epochs = epochs_fine_alignment(epochs)

cond = epochs.info['description']
stim_coords = find_stim_coords(cond, subj, study_path)

fwd = mne.read_forward_solution(fwd_fname)
fwd1 = mne.convert_forward_solution(fwd, force_fixed=True)
cov = mne.compute_covariance(epochs, method='shrunk', tmin=-0.5, tmax=-0.3)  # use method='auto' for final computation

evoked = epochs.average()
info = evoked.info


from nibabel.freesurfer.io import read_geometry
fname_surf = op.join(subjects_dir, subj, 'surf', 'lh.pial')
surf = read_geometry(fname_surf)


def closest_nodes(node, all_nodes, used_nodes):