mag=0.05, grad=0.05, eeg=0.1, proj=True)

data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)

# Run free orientation (vector) beamformer. Source orientation can be
# restricted by setting pick_ori to 'max-power' (or 'normal' but only when
# using a surface-based source space)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori=None)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume('lcmv_inverse.nii.gz', stc,
        forward['src'], mri_resolution=False)  # True for full MRI resolution

# plot result (one slice)
plt.close('all')
data = img.get_data()
coronal_slice = data[:, 10, :, 60]
plt.figure()
plt.imshow(np.ma.masked_less(coronal_slice, 1), cmap=plt.cm.Reds,
           interpolation='nearest')
plt.colorbar()
plt.contour(coronal_slice != 0, 1, colors=['black'])
plt.xticks([])
plt.yticks([])

# plot source time courses with the maximum peak amplitudes
plt.figure()
예제 #2
0
def compute_lcmv_example_data(data_path, fname=None):
    raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
    event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
    fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-vol-7-fwd.fif'
    # Get epochs
    event_id, tmin, tmax = [1, 2], -0.2, 0.5

    # Setup for reading the raw data
    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bad channels
    events = mne.read_events(event_fname)

    # Set up pick list: gradiometers and magnetometers, excluding bad channels
    picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                           exclude='bads')

    # Pick the channels of interest
    raw.pick_channels([raw.ch_names[pick] for pick in picks])

    # Re-normalize our empty-room projectors, so they are fine after
    # subselection
    raw.info.normalize_proj()
    # Read epochs
    proj = False  # already applied
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=(None, 0), preload=True, proj=proj,
                        reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
    evoked = epochs.average()

    # Read regularized noise covariance and compute regularized data covariance
    noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0,
                                       method='shrunk')
    data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15,
                                      method='shrunk')
    # Read forward model
    forward = mne.read_forward_solution(fname_fwd)

    # Compute weights of free orientation (vector) beamformer with weight
    # normalization (neural activity index, NAI). Providing a noise covariance
    # matrix enables whitening of the data and forward solution. Source
    # orientation is optimized by setting pick_ori to 'max-power'.
    # weight_norm can also be set to 'unit-noise-gain'. Source orientation can
    # also be 'normal' (but only when using a surface-based source space) or
    # None, which computes a vector beamfomer. Note, however, that not all
    # combinations of orientation selection and weight normalization are
    # implemented yet.
    filters = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                        noise_cov=noise_cov, pick_ori='max-power',
                        weight_norm='nai')

    # Apply this spatial filter to the evoked data.
    stc = apply_lcmv(evoked, filters, max_ori_out='signed')

    # take absolute values for plotting
    stc.data[:, :] = np.abs(stc.data)

    # Save result in stc files if desired
    if fname is not None:
        stc.save('lcmv-vol')

    # select time window (tmin, tmax) in ms - consider changing for real data
    # scenario, since those values were chosen to optimize computation time
    stc.crop(0.087, 0.087)

    src = forward['src']

    # Save result in a 4D nifti file
    img = mne.save_stc_as_volume(fname, stc, src,
                                 mri_resolution=True)

    return img, stc, src
예제 #3
0
# take absolute values for plotting
stc2.data = np.abs(stc.data.copy())
#stc.data = np.abs(stc.data)

ax[1, 0].plot(x_ax, stc2.data[np.argsort(np.max(stc2.data, axis=1))[-40:]].T)
# -40: plots the last (highest?) 40 voxels\
ax[1, 0].set_ylabel('LCMV value')
ax[1, 0].set_xlabel('Time (ms)')
ax[1, 0].set_xlim(-200, 500)  #(x_ax[0], x_ax[-1])
ax[1, 0].set_title('%s %s, reg=%.3f, '
                   ' 40 max voxels' % (megtype, 'flash', rv))

#  plot brain activity at the max mimum time point in volume
vox, timep = np.unravel_index(stc.data.argmax(), stc.data.shape)

img_mne = mne.save_stc_as_volume(op.join(reg_folder, 'test.nii.gz'), stc2,
                                 fwd['src'])
if trial is 'pulse':
    timep = abs(stc.times + .001).argmin()
else:
    timep = abs(stc.times - 0.108).argmin()
# plotting threshold based on activity:
thresh = np.max(stc2.data[:, timep]) * 0.75

#which_times=find_subset(stc.times,.105,.110)
#timep=which_times
# voxel 128.0 128.0 48.0, mm 1.0 -81.0 1.0 coords = (1,81,1)# fwd['source_rr'][vox]

# plot statistical map on volume
plot_stat_map(
    index_img(img_mne, timep),
    t1_fname,
예제 #4
0
def set_up(cfg):
    '''Calculate NNs, generate replications
    '''
    
    # extract relevant paths   
    subjectsDir = cfg["file_io"]["dirs"]["subjectsDir"]
    simDir = cfg["file_io"]["dirs"]["simDir"]
    relDir = cfg["file_io"]["dirs"]["relDir"] 
    os.environ["SUBJECTS_DIR"] = subjectsDir
       
    # extract settings for finding nearest neighbours
    nbrhd = cfg["reliability_mapping"]["nn"]["neighbourhood"]
    rad = cfg["reliability_mapping"]["nn"]["radius"] 
    
    # extract settings for data division into replications
    num_rep = cfg["reliability_mapping"]["data_division"]["num_replications"]
    chron = cfg["reliability_mapping"]["data_division"]["chronological"]
    
    # extract settings for data processing & beamformer
    baseStart = cfg["data_processing"]["baseline"]["baseStart"]
    baseEnd = cfg["data_processing"]["baseline"]["baseEnd"]
    bfBaselineMin = cfg["data_processing"]["LCMV"]["bfBaselineMin"]
    bfBaselineMax = cfg["data_processing"]["LCMV"]["bfBaselineMax"]
    bfActiveMin = cfg["data_processing"]["LCMV"]["bfActiveMin"]
    bfActiveMax = cfg["data_processing"]["LCMV"]["bfActiveMax"]
    regularization = cfg["data_processing"]["LCMV"]["regularization"]
    #spacing = cfg["data_processing"]["LCMV"]["spacing"]
    
    for subject_id in cfg["studySettings"]["subjects"]:   
        # subject-specific data:
        subjectDir = os.path.join(subjectsDir, subject_id)
        mriFile = os.path.join(subjectDir, 'mri', 'T1-neuromag', 'sets', cfg["file_io"]["file_ext"]["mri_fif"])
        bemFile = os.path.join(subjectDir, 'bem', "".join([subject_id, cfg["file_io"]["file_ext"]["bem_fif"]]))
        srcFile = os.path.join(subjectDir, 'bem', "".join([subject_id, cfg["file_io"]["file_ext"]["src_fif"]]))
        # nearest neighbours csv file to write to
        nnFile = os.path.join(subjectDir, 'bem', "".join([subject_id, cfg["file_io"]["file_ext"]["nn_file"]]))
        # find nearest neighbours for each point in src space and write to file
        sf.get_nn_src(srcFile, nnFile, nbrhd, rad)
        
        for sim_mode in cfg["studySettings"]["sim_modes"]:
            # split epochs file into a number of epochs files (ie. replications) & save an ERB map for each
            
            epochFile = os.path.join(simDir, 'sim_data', subject_id, sim_mode,
                                     cfg["file_io"]["file_ext"]["sim_epoch_fif"])
            
            repDir = os.path.join(relDir, subject_id, sim_mode)
            if not os.path.exists(repDir):
                logger.debug("Path does not exist.  Making {}".format(repDir))
                os.makedirs(repDir)
                            
            # read in & divide epochs    
            logger.info("Reading epoch data ...")
            epochs = mne.read_epochs(epochFile)
            if epochs.info['sfreq'] == 1000.:
                pass
            else:
                logger.debug('Resampling epochs to 1000 Hz')
                epochs.resample(1000., npad=0)   
            idxs = np.arange(len(epochs))
            if chron == False:
                random.shuffle(idxs)    
            splits = np.array_split(idxs, num_rep)
            # note: number of epochs in each replication may differ by 1
            
            # get forward solution
            fwdFile = os.path.join(simDir, 'python_data', subject_id, 
                                   "".join(['SEF_good', cfg["file_io"]["file_ext"]["forward_fif"]]))
              
            if os.path.exists(fwdFile):
                pass
            else:
                logger.debug("Forward solution does not exist.  Making forward solution.")
                src = mne.read_source_spaces(srcFile)
                forward = mne.make_forward_solution(epochs.info, trans=mriFile, 
                                    src=src, bem=bemFile, meg=True, eeg=False)
                mne.write_forward_solution(fwdFile, forward, overwrite=True)
            forward = mne.read_forward_solution(fwdFile)
            
            split_num = 1
            # create ERB map for each replication
            for split in splits:
                evoked = epochs[split].average()
                evoked.apply_baseline((baseStart, baseEnd))
                # calculate covariance
                noise_cov = mne.compute_covariance(epochs[split], 
                                tmin=bfBaselineMin, tmax=bfBaselineMax, n_jobs = 4)
                data_cov = mne.compute_covariance(epochs[split], 
                                tmin=bfActiveMin, tmax=bfActiveMax, n_jobs = 4)
                # run LCMV beamformer
                filters = mne.beamformer.make_lcmv(epochs.info, forward, data_cov, 
                            reg=regularization, noise_cov=noise_cov, pick_ori='max-power')
                stc = mne.beamformer.apply_lcmv(evoked, filters)
                # crop beamformer result to times of interest
                stc.crop(bfActiveMin, bfActiveMax)
                # take absolute value of beamformer (to eliminate anti-phase issue)
                np.abs(stc.data, out=stc.data)
                
                # save ERB maps
                niiFile = os.path.join(repDir, "".join(['replication_', 
                                str(split_num), '_', cfg["file_io"]["file_ext"]["nifti_file"]]))
                mne.save_stc_as_volume(niiFile, stc, forward['src'], dest='surf',
                                                             mri_resolution=False)
                
                split_num = split_num + 1    
          
            # also create an ERB map for the entire dataset
            evoked = epochs.average()
            evoked.apply_baseline((baseStart, baseEnd))
            # calculate covariance
            noise_cov = mne.compute_covariance(epochs, 
                                tmin=bfBaselineMin, tmax=bfBaselineMax, n_jobs = 4)
            data_cov = mne.compute_covariance(epochs, 
                                tmin=bfActiveMin, tmax=bfActiveMax, n_jobs = 4)
            # run LCMV beamformer
            filters = mne.beamformer.make_lcmv(epochs.info, forward, data_cov, 
                            reg=regularization, noise_cov=noise_cov, pick_ori='max-power')
            stc = mne.beamformer.apply_lcmv(evoked, filters)
            # crop beamformer result to times of interest
            stc.crop(bfActiveMin, bfActiveMax)
            # take absolute value of beamformer (to eliminate anti-phase issue)
            np.abs(stc.data, out=stc.data)
                
            # save ERB map
            niiFile = os.path.join(repDir, "".join(['full', cfg["file_io"]["file_ext"]["nifti_file"]]))
            mne.save_stc_as_volume(niiFile, stc, forward['src'], dest='surf',
                                                             mri_resolution=False)
snr = 3.0
lambda2 = 1.0 / snr**2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Load data
evoked = Evoked(fname_evoked, setno=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method)
stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume(
    'mne_%s_inverse.nii.gz' % method, stc, src,
    mri_resolution=False)  # set to True for full MRI resolution
data = img.get_data()

# plot result (one slice)
coronal_slice = data[:, 10, :, 60]
pl.close('all')
pl.imshow(np.ma.masked_less(coronal_slice, 8),
          cmap=pl.cm.Reds,
          interpolation='nearest')
pl.colorbar()
pl.contour(coronal_slice != 0, 1, colors=['black'])
pl.xticks([])
pl.yticks([])
pl.show()
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)

# Run free orientation (vector) beamformer. Source orientation can be
# restricted by setting pick_ori to 'max-power' (or 'normal' but only when
# using a surface-based source space)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori=None)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume(
    'lcmv_inverse.nii.gz', stc, forward['src'],
    mri_resolution=False)  # True for full MRI resolution

# plot result (one slice)
plt.close('all')
data = img.get_data()
coronal_slice = data[:, 10, :, 60]
plt.figure()
plt.imshow(np.ma.masked_less(coronal_slice, 1),
           cmap=plt.cm.Reds,
           interpolation='nearest')
plt.colorbar()
plt.contour(coronal_slice != 0, 1, colors=['black'])
plt.xticks([])
plt.yticks([])
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Load data
evoked = Evoked(fname_evoked, setno=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method)
stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume('mne_%s_inverse.nii.gz' % method, stc,
        src, mri_resolution=False)  # set to True for full MRI resolution
data = img.get_data()

# plot result (one slice)
coronal_slice = data[:, 10, :, 60]
pl.close('all')
pl.imshow(np.ma.masked_less(coronal_slice, 8), cmap=pl.cm.Reds,
          interpolation='nearest')
pl.colorbar()
pl.contour(coronal_slice != 0, 1, colors=['black'])
pl.xticks([])
pl.yticks([])
pl.show()
예제 #8
0
# Apply this spatial filter to the evoked data.
stc = apply_lcmv(evoked, filters, max_ori_out='signed')

# take absolute values for plotting
stc.data[:, :] = np.abs(stc.data)

# Save result in stc files
stc.save('lcmv-vol')

# select time window (tmin, tmax)
stc.crop(0.0, 0.0)

# Save result in a 4D nifti file
mne.save_stc_as_volume('lcmv_inverse.nii.gz',
                       stc,
                       forward['src'],
                       mri_resolution=True)

###############################################################################
# Load nifti data and reslice

# isometric voxel size of 3 mm - reconsider for real data
voxel_size = (3., 3., 3.)

# number of iterations for each optimisation level
niter_affine = [100, 100, 10]
niter_sdr = [5, 5, 3]

# load lcmv inverse
img_vol = nib.load('lcmv_inverse.nii.gz')
예제 #9
0
                                    stc.data.max(axis=1))[ts_show:]].T)
                            plt.title(dfname +
                                      ' for %d largest sources' % abs(ts_show))
                            plt.xlabel('time (ms)')
                            plt.ylabel('%s value ' % 'LCMV stc' +
                                       '@reg=%.2f' % reg)
                            plt.show()

                            stc.crop(0.0, stc.times[-1])
                            thresh = stc.data.max() * 2 / 100
                            timepoint = int(t_peak // stc.tstep -
                                            stc.times[0] // stc.tstep)

                            img = mne.save_stc_as_volume('lcmv_stc.nii',
                                                         stc,
                                                         fwd['src'],
                                                         dest='mri',
                                                         mri_resolution=False)
                            plot_stat_map(
                                index_img(img, int(timepoint)),
                                mrifile,
                                draw_cross=True,
                                threshold=thresh,
                                title=dfname + '/ LCMV/ ' + 'reg=%.2f' % reg +
                                '/ Vpeak=%.3f\n' % stc.data.max() +
                                'Tpeak=%.3fs' % t_peak +
                                '/ Est_loc= [%.1f, %.1f, %.1f]' %
                                tuple(est_loc) + '/ Loc_err= %.1f' % loc_err)
                            os.remove('lcmv_stc.nii')

                        fid = open(resultfile_lcmv, 'a+')
예제 #10
0
# Save result in stc files
stc.save(op.join(datapath, subject, 'lcmv-vol'))
stc.crop(0.0, 1.0)
# plot dSPM time course in src space
kwargs = dict(color='c', linestyle='--', linewidth=.5)
f, ax = plt.subplots(1, 1, figsize=(8, 11))
mx = np.argmax(stc.data, axis=0)
ax.plot(stc.times, stc.data[mx[:100], :].T)
ax.autoscale(enable=True, axis='x', tight=True)
ax.grid(True, which='major', axis='y', **kwargs)
ax.set_xlabel('time (s)')
ax.set_ylabel('strength')

# Save result in a 4D nifti file
img = mne.save_stc_as_volume(op.join(datapath, subject, 'lcmv_inverse.nii.gz',),
                             stc, fwd['src'], mri_resolution=False)

t1_fname = subjects_dir + '/fsaverage/mri/T1.mgz'

# Plotting with nilearn
idx = stc.time_as_index(0.5)
plot_stat_map(index_img(img, idx), t1_fname, threshold=0.45,
              title='LCMV (t=%.3f s.)' % stc.times[idx])

# plot source time courses with the maximum peak amplitudes at idx
plt.figure()
plt.plot(stc.times, stc.data[np.argsort(np.max(stc.data[:, idx],
                                               axis=1))[-40:]].T)
plt.xlabel('Time (ms)')
plt.ylabel('LCMV value')
plt.show()
예제 #11
0
def vol_source_loc(evoked, cov, fs_subj, study_path, plot=True):
    cond = evoked.info['description']

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

    mri_file = op.join(subjects_dir, subj, 'mri', 'T1.mgz')
    v_source = mne.setup_volume_source_space(subject=fs_subj,
                                             mri=mri_file,
                                             bem=bem_fname,
                                             subjects_dir=subjects_dir,
                                             pos=2.)

    fwd = mne.make_forward_solution(
        evoked.info,
        trans_fname,
        v_source,
        bem_fname,
        mindist=5.0,  # ignore sources<=5mm from innerskull
        meg=False,
        eeg=True,
        n_jobs=2)

    mne.write_forward_solution(
        op.join(study_path, 'source_stim', subj, 'source_files',
                '%s_vol_source_space_2mm'), fwd)

    inv = mne.minimum_norm.make_inverse_operator(evoked.info,
                                                 fwd,
                                                 cov,
                                                 loose=1,
                                                 depth=1)
    method = "sLORETA"
    snr = 30.
    lambda2 = 1. / snr**2
    stc = mne.minimum_norm.apply_inverse(evoked,
                                         inv,
                                         lambda2,
                                         method=method,
                                         pick_ori=None)

    stc.crop(-0.005, 0.005)

    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')

    t0_img = index_img(img, 3)
    act_coord = ni.plotting.find_xyz_cut_coords(t0_img)
    #act_coord = [57, 122, 87]
    thr = np.percentile(t0_img.get_data(), 99.9)
    st_map = plot_stat_map(t0_img,
                           mri_file,
                           threshold=thr,
                           display_mode='ortho',
                           cmap=plt.cm.plasma)
    st_map.add_markers(np.reshape(act_coord, (-1, 3)),
                       marker_color='g',
                       marker_size=50)
    fname_fig = op.join(study_path, 'source_stim', subj, 'figures', 'volume',
                        '%s_%s_st_map.pdf' % (subj, cond))
    st_map.savefig(fname_fig)

    dist_vol = euclidean()
예제 #12
0
    
    vtx, _, trh = stcrh_label.center_of_mass('fsaverage')
    mnirh = mne.vertex_to_mni(vtx, 1, 'fsaverage')[0]
    testrh.append(mnirh)

###############################################################################
# save as nifti
src = mne.setup_source_space('fsaverage_tmp', spacing='ico5')

# Export result as a 4D nifti object
path = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plot_STATS/RefPast_vs_RefPre_vs_RefFut';
stc_fname = (path + '/fmapMEEG_RefPast_vs_RefPre_vs_RefFut-rh.stc')
stc = mne.read_source_estimate(stc_fname)

fname = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/nifti/Refpast_RefPre_RefFut.nii')
mne.save_stc_as_volume(fname, stc, src, dest='mri', mri_resolution=False)














예제 #13
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
예제 #14
0
dSPM = True

# Load data
evoked = Evoked(fname_evoked, setno=setno, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']

# Compute inverse solution
# default method='dSPM' (dynamical Statistical Parametric Mapping)
#  other options: MNE (mininum norm) or sLORETA (standardized low resolution brain electromagnetic tomography)
stc = apply_inverse(evoked, inverse_operator, lambda2, dSPM)
#stc.crop(0.0, 0.2) #why!? (10x bigger otherwise)

# Save result in a 4D nifti file
# saved as e.g. /data/Luna1/Multimodal/ANTI/10892/MEG/10892_anti_Correct_ave.nii.gz
img = mne.save_stc_as_volume(data_path+'/'+subject+'/MEG/'+subject+'_'+args['output']+'.nii.gz', stc, src)
# save_stc_as_volume: http://www.martinos.org/mne/generated/mne.save_stc_as_volume.html
# mri_resolution=False (default)  
#   set to True for full MRI resolution
# dest='mri' (default)
#     'mri': volume is defined in the coordinate system of the original T1 image. 
#    'surf': coordinate system of the FreeSurfer surface is used (Surface RAS).


## plot result (one slice)
#data = img.get_data()
#coronal_slice = data[:, 10, :, 60]
#pl.close('all')
#pl.imshow(np.ma.masked_less(coronal_slice, 8), cmap=pl.cm.Reds,
#          interpolation='nearest')
#pl.colorbar()
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)

# Run free orientation (vector) beamformer. Source orientation can be
# restricted by setting pick_ori to 'max-power' (or 'normal' but only when
# using a surface-based source space)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori=None)

# Save result in stc files
stc.save("lcmv-vol")

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume(
    "lcmv_inverse.nii.gz", stc, forward["src"], mri_resolution=False
)  # True for full MRI resolution

# plot result (one slice)
plt.close("all")
data = img.get_data()
coronal_slice = data[:, 10, :, 60]
plt.figure()
plt.imshow(np.ma.masked_less(coronal_slice, 1), cmap=plt.cm.Reds, interpolation="nearest")
plt.colorbar()
plt.contour(coronal_slice != 0, 1, colors=["black"])
plt.xticks([])
plt.yticks([])

# plot source time courses with the maximum peak amplitudes
plt.figure()