예제 #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
예제 #2
0
# Compute TF-MxNE inverse solution with dipole output
dipoles, residual = tf_mixed_norm(
    evoked, forward, cov, alpha=alpha, l1_ratio=l1_ratio, 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)

# Crop to remove edges
for dip in dipoles:
    dip.crop(tmin=-0.05, tmax=0.3)
evoked.crop(tmin=-0.05, tmax=0.3)
residual.crop(tmin=-0.05, tmax=0.3)

###############################################################################
# Plot dipole activations
plot_dipole_amplitudes(dipoles)

###############################################################################
# Plot location of the strongest dipole with MRI slices
idx = np.argmax([np.max(np.abs(dip.amplitude)) for dip in dipoles])
plot_dipole_locations(dipoles[idx], forward['mri_head_t'], 'sample',
                      subjects_dir=subjects_dir, mode='orthoview',
                      idx='amplitude')

# # Plot dipole locations of all dipoles with MRI slices
# for dip in dipoles:
#     plot_dipole_locations(dip, forward['mri_head_t'], 'sample',
#                           subjects_dir=subjects_dir, mode='orthoview',
#                           idx='amplitude')

###############################################################################
inverse_operator = make_inverse_operator(evoked.info, forward, cov,
                                         depth=depth, fixed=True,
                                         use_cps=True)
stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9.,
                         method='dSPM')

# Compute (ir)MxNE inverse solution with dipole output
dipoles, residual = mixed_norm(
    evoked, forward, cov, alpha, loose=loose, depth=depth, maxit=3000,
    tol=1e-4, active_set_size=10, debias=True, weights=stc_dspm,
    weights_min=8., n_mxne_iter=n_mxne_iter, return_residual=True,
    return_as_dipoles=True)

###############################################################################
# Plot dipole activations
plot_dipole_amplitudes(dipoles)

# Plot dipole location of the strongest dipole with MRI slices
idx = np.argmax([np.max(np.abs(dip.amplitude)) for dip in dipoles])
plot_dipole_locations(dipoles[idx], forward['mri_head_t'], 'sample',
                      subjects_dir=subjects_dir, mode='orthoview',
                      idx='amplitude')

# # Plot dipole locations of all dipoles with MRI slices
# for dip in dipoles:
#     plot_dipole_locations(dip, forward['mri_head_t'], 'sample',
#                           subjects_dir=subjects_dir, mode='orthoview',
#                           idx='amplitude')

###############################################################################
# Plot residual
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