def test_morph_data(): """Test morphing of data """ subject_from = 'sample' subject_to = 'fsaverage' fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc_from = read_source_estimate(fname, subject='sample') fname = op.join(data_path, 'MEG', 'sample', 'fsaverage_audvis-meg') stc_to = read_source_estimate(fname) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation stc_to1 = stc_from.morph(subject_to, grade=3, smooth=12, buffer_size=1000) stc_to1.save(op.join(tempdir, '%s_audvis-meg' % subject_to)) # make sure we can specify vertices vertices_to = grade_to_vertices(subject_to, grade=3) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=1000) # make sure we can use different buffer_size stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3) # indexing silliness here due to mne_make_movie's indexing oddities assert_array_almost_equal(stc_to.data, stc_to1.data, 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) assert_array_almost_equal(stc_to1.data, stc_to3.data) # make sure precomputed morph matrices work morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertno, vertices_to, smooth=12) stc_to3 = stc_from.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999) # make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3) assert_true(stc_to5.data.shape[0] == 163842 + 163842)
def test_morph_data(): """Test morphing of data """ subject_from = 'sample' subject_to = 'fsaverage' fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc_from = read_source_estimate(fname) stc_from.crop(0.09, 0.1) # for faster computation # After running this: # stc_from.save('%s_audvis-meg-cropped' % subject_from) # this was run from a command line: # mne_make_movie --stcin sample_audvis-meg-cropped-lh.stc # --subject sample --morph fsaverage --smooth 12 --morphgrade 3 # --stc fsaverage_audvis-meg-cropped # XXX These files should eventually be moved to the sample dataset and # removed from mne/fiff/tests/data/ fname = op.join(op.dirname(__file__), '..', 'fiff', 'tests', 'data', 'fsaverage_audvis-meg-cropped') stc_to = read_source_estimate(fname) stc_to1 = morph_data(subject_from, subject_to, stc_from, grade=3, smooth=12, buffer_size=1000) stc_to1.save('%s_audvis-meg' % subject_to) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=3, smooth=12, buffer_size=3) # indexing silliness here due to mne_make_movie's indexing oddities assert_array_almost_equal(stc_to.data, stc_to1.data[:, 0][:, None], 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) # make sure precomputed morph matrices work vertices_to = grade_to_vertices(subject_to, grade=3) morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertno, vertices_to, smooth=12) stc_to3 = morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999) # test two types of morphing: # 1) make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3) assert_true(stc_to5.data.shape[0] == 163842 + 163842) # 2) make sure we can specify vertices vertices_to = [np.arange(10242), np.arange(10242)] stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3) stc_to4 = morph_data(subject_from, subject_to, stc_from, grade=5, smooth=12, buffer_size=3) assert_array_almost_equal(stc_to3.data, stc_to4.data)
def test_morph_data(): """Test morphing of data """ subject_from = 'sample' subject_to = 'fsaverage' fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc_from = read_source_estimate(fname, subject='sample') fname = op.join(data_path, 'MEG', 'sample', 'fsaverage_audvis-meg') stc_to = read_source_estimate(fname) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation stc_to1 = stc_from.morph(subject_to, grade=3, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) stc_to1.save(op.join(tempdir, '%s_audvis-meg' % subject_to)) # make sure we can specify vertices vertices_to = grade_to_vertices(subject_to, grade=3) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) # make sure we can use different buffer_size stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert_array_almost_equal(stc_to.data, stc_to1.data, 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) assert_array_almost_equal(stc_to1.data, stc_to3.data) # make sure precomputed morph matrices work morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertno, vertices_to, smooth=12, subjects_dir=subjects_dir) stc_to3 = stc_from.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999) # make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert_true(stc_to5.data.shape[0] == 163842 + 163842) # test morphing to the same subject stc_to6 = stc_from.morph(subject_from, grade=stc_from.vertno, smooth=1, subjects_dir=subjects_dir) mask = np.ones(stc_from.data.shape[0], dtype=np.bool) # XXX: there is a bug somewhere that causes a difference at 2 vertices.. mask[6799] = False mask[6800] = False assert_array_almost_equal(stc_from.data[mask], stc_to6.data[mask], 5)
def apply_STC_epo(fnepo, event, method='MNE', snr=1.0, min_subject='fsaverage', subjects_dir=None): from mne import morph_data from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs fnlist = get_files_from_list(fnepo) # loop across all filenames for fname in fnlist: fn_path = os.path.split(fname)[0] name = os.path.basename(fname) subject = name.split('_')[0] min_dir = subjects_dir + '/%s' %min_subject snr = snr lambda2 = 1.0 / snr ** 2 stcs_path = min_dir + '/stcs/%s/%s/' % (subject,event) reset_directory(stcs_path) # fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' fn_inv = fn_path + '/%s_epo-inv.fif' %subject # noise_cov = mne.read_cov(fn_cov) epo = mne.read_epochs(fname) epo.pick_types(meg=True, ref_meg=False) inv = read_inverse_operator(fn_inv) stcs = apply_inverse_epochs(epo, inv, lambda2, method, pick_ori='normal') s = 0 while s < len(stcs): stc_morph = morph_data(subject, min_subject, stcs[s]) stc_morph.save(stcs_path + '/trial%s_fsaverage' % (str(s)), ftype='stc') s = s + 1
def __call__(self, data): output = deepcopy(data) from_surf_file = dirname(dirname(self.from_surf.surf_file)) SUBJECTS_DIR, from_surf_name = split(from_surf_file) if 'lh' == self.from_surf.surf_file.stem: vertices = [arange(data.data[0].shape[0]), arange(0)] else: vertices = [arange(0), arange(data.data[0].shape[0])] try: stc = SourceEstimate(atleast_2d(data.data[0]).T, vertices=vertices, tstep=0, tmin=0) except NameError: raise ImportError('mne needs to be installed for this function') m = morph_data(from_surf_name, self.to_surf, stc, subjects_dir=SUBJECTS_DIR, grade=None, smooth=self.smooth, verbose=False) output.data[0] = squeeze(m.data, axis=1) output.axis['surf'][0] = arange(m.data.shape[0]) return output
def morph_data_to_fsaverage(name, save_dir, subjects_dir, subject, lowpass, method, overwrite): stcs = io.read_source_estimates(name, save_dir, lowpass, method) subject_to = 'fsaverage' stcs_morph = dict() for trial_type in stcs: stc_morph_name = name + filter_string(lowpass) + '_' + \ trial_type + '_' + method + '_morph' stc_morph_path = join(save_dir, stc_morph_name) if overwrite or not isfile(stc_morph_path + '-lh.stc'): stc_from = stcs[trial_type] stcs_morph[trial_type] = mne.morph_data(subject, subject_to, stc_from, subjects_dir=subjects_dir, n_jobs=-1) else: print('morphed source estimates for: '+ stc_morph_path + \ ' already exists') for trial_type in stcs_morph: stc_morph_name = name + filter_string(lowpass) + '_' + \ trial_type + '_' + method + '_morph' stc_morph_path = join(save_dir, stc_morph_name) if overwrite or not isfile(stc_morph_path + '-lh.stc'): stcs_morph[trial_type].save(stc_morph_path)
def apply_inverse(fnevo, method='dSPM', snr=3.0, event='LLst', baseline=False, btmin=-0.3, btmax=-0.1, min_subject='fsaverage'): ''' Parameter --------- fnevo: string or list The evoked file with ECG, EOG and environmental noise free. method: inverse method, 'MNE' or 'dSPM' event: string The event name related with epochs. min_subject: string The subject name as the common brain. snr: signal to noise ratio for inverse solution. ''' #Get the default subjects_dir from mne.minimum_norm import apply_inverse fnlist = get_files_from_list(fnevo) # loop across all filenames for fname in fnlist: fn_path = os.path.split(fname)[0] name = os.path.basename(fname) stc_name = name[:name.rfind('-ave.fif')] subject = name.split('_')[0] subject_path = subjects_dir + '/%s' %subject min_dir = subjects_dir + '/%s' %min_subject fn_trans = fn_path + '/%s-trans.fif' % subject fn_cov = fn_path + '/%s_empty,nr-cov.fif' % subject fn_src = subject_path + '/bem/%s-ico-5-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject snr = snr lambda2 = 1.0 / snr ** 2 #noise_cov = mne.read_cov(fn_cov) [evoked] = mne.read_evokeds(fname) noise_cov = mne.read_cov(fn_cov) # this path used for ROI definition stc_path = min_dir + '/%s_ROIs/%s' %(method,subject) #fn_cov = meg_path + '/%s_empty,fibp1-45,nr-cov.fif' % subject set_directory(stc_path) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, proj=True) fwd_ev = mne.make_forward_solution(evoked.info, trans=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) fwd_ev = mne.convert_forward_solution(fwd_ev, surf_ori=True) forward_meg_ev = mne.pick_types_forward(fwd_ev, meg=True, eeg=False) inverse_operator_ev = mne.minimum_norm.make_inverse_operator( evoked.info, forward_meg_ev, noise_cov, loose=0.2, depth=0.8) # Compute inverse solution stc = apply_inverse(evoked, inverse_operator_ev, lambda2, method, pick_ori=None) # Morph STC stc_morph = mne.morph_data(subject, min_subject, stc, grade=5, smooth=5) stc_morph.save(stc_path + '/%s' % (stc_name), ftype='stc') if baseline == True: stc_base = stc_morph.crop(btmin, btmax) stc_base.save(stc_path + '/%s_%s_baseline' % (subject, event), ftype='stc')
def morph_stc(subject_from, subject_to, stc_from_file): stc_from = mne.read_source_estimate(stc_from_file) vertices_to = [np.arange(10242), np.arange(10242)] stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=4, grade=vertices_to) stc_to.save('{}_{}.stc'.format(stc_from_file[:-4], subject_to))
def test_morph_data(): """Test morphing of data """ subject_from = 'sample' subject_to = 'fsaverage' fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc_from = SourceEstimate(fname) stc_from.crop(0.09, 0.1) # for faster computation stc_to = morph_data(subject_from, subject_to, stc_from, grade=3, smooth=12, buffer_size=1000) stc_to.save('%s_audvis-meg' % subject_to) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=3, smooth=12, buffer_size=3) assert_array_almost_equal(stc_to.data, stc_to2.data) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999)
def test_morph_data(): """Test morphing of data """ subject_from = 'sample' subject_to = 'fsaverage' fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc_from = read_source_estimate(fname, subject='sample') fname = op.join(data_path, 'MEG', 'sample', 'fsaverage_audvis-meg') stc_to = read_source_estimate(fname) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation stc_to1 = stc_from.morph(subject_to, grade=3, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) stc_to1.save(op.join(tempdir, '%s_audvis-meg' % subject_to)) # make sure we can specify vertices vertices_to = grade_to_vertices(subject_to, grade=3) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) # make sure we can use different buffer_size stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3, subjects_dir=subjects_dir) # indexing silliness here due to mne_make_movie's indexing oddities assert_array_almost_equal(stc_to.data, stc_to1.data, 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) assert_array_almost_equal(stc_to1.data, stc_to3.data) # make sure precomputed morph matrices work morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertno, vertices_to, smooth=12, subjects_dir=subjects_dir) stc_to3 = stc_from.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999) # make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert_true(stc_to5.data.shape[0] == 163842 + 163842)
def _morphed_epochs_files(params): subject, cond_name, stc_file_name, inverse_method, subjects_dir = params print('morphing {}'.format(stc_file_name)) epoch_id = utils.namebase(stc_file_name).split('_')[2] morphed_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc_epochs_morphed', '{}_{}_{}_{}'.format(subject, cond_name, epoch_id, inverse_method)) if not op.isfile('{}-stc.h5'.format(morphed_stc_file_name)): stc = mne.read_source_estimate(stc_file_name) stc_morphed = mne.morph_data(subject, 'fsaverage', stc, grade=5, smooth=20, subjects_dir=subjects_dir) stc_morphed.save(morphed_stc_file_name, ftype='h5') else: print('{} {} {} already morphed'.format(subject, cond_name, epoch_id))
def smooth_ttest_results(tmin, tstep, subjects_dir, inverse_method='dSPM', n_jobs=1): for cond_id, cond_name in enumerate(events_id.keys()): for patient in get_patients(): results_file_name = op.join(LOCAL_ROOT_DIR, 'permutation_ttest_results', '{}_{}_{}_clusters.npy'.format(patient, cond_name, inverse_method)) if op.isfile(results_file_name): data = np.load(results_file_name) print('smoothing {} {}'.format(patient, cond_name)) fsave_vertices = [np.arange(10242), np.arange(10242)] stc = _make_stc(data, fsave_vertices, tmin=tmin, tstep=tstep, subject='fsaverage') vertices_to = mne.grade_to_vertices('fsaverage', grade=None, subjects_dir=subjects_dir) print(stc.data.shape, vertices_to[0].shape) stc_smooth = mne.morph_data('fsaverage', 'fsaverage', stc, n_jobs=n_jobs, grade=vertices_to, subjects_dir=subjects_dir) stc_smooth.save(op.join(LOCAL_ROOT_DIR, 'results_for_blender', '{}_{}_{}'.format(patient, cond_name, inverse_method)), ftype='h5') else: print('no results for {} {}'.format(patient, cond_name))
def test_morph_data(): """Test morphing of data """ import mne subject_from = 'sample' subject_to = 'morph' fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc_from = mne.SourceEstimate(fname) stc_to = mne.morph_data(subject_from, subject_to, stc_from, 3) stc_to.save('%s_audvis-meg' % subject_to) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to.data.mean(axis=0) assert np.corrcoef(mean_to, mean_from).min() > 0.99
def extractActivity(s): for condition in conditions: subject = 'dh' + '{:02d}'.format(int(s)) + 'a' inverseFile = expDir + subject + '/' + subject + '__-5120-ico-5p-' + subject + '-aligned-inv.fif' # Estimate SNR snr = 3.0 regularization = 1.0 / (snr ** 2) print 'Prepare saving' activityFile = datDir + subject + '/' + condition + '_average.mat' matlabDict = {} print 'Populate a dictionary with Matlab variables named after the ROI' matlabDict['conditions'] = np.array(conditions, dtype=np.object) for roi in ROIs: # Prepare each variable as a cell array for the single trials matlabDict[cleanName(roi)] = np.zeros((1,), dtype=np.object) print 'Load inverse operator' inverseOperator = mne.minimum_norm.read_inverse_operator(inverseFile) print 'Load evoked file' evokedFile = expDir + subject + '/' + subject + '_mc_hp004_l80_' + condition + '_average-ica.fif' evoked = mne.fiff.Evoked(evokedFile, condition=0, baseline=None) evoked.crop(tmin=0.0, tmax=0.01) print 'Convert sensor space to source space' # sourceActivity = mne.minimum_norm.apply_inverse(evoked, inverseOperator, regularization, inverseMethod, pick_ori="normal") sourceActivity = mne.minimum_norm.apply_inverse(evoked, inverseOperator, regularization, inverseMethod, pick_ori="normal") print 'Morph to standard subject' morphedSourceActivity = mne.morph_data(subject, 'dh58a', sourceActivity, grade=5, smooth=20, subjects_dir=subjectsDir) for roi in ROIs: # Load the label of interest label = mne.read_label(labelsDir + '/' + roi + '.label') print 'Select only the labeled activity' roiActivity = sourceActivity.in_label(label) averageActivity = roiActivity.data.mean(0) #src = inverseOperator['src'] #averageActivity = mne.extract_label_time_course(morphedSourceActivity, label, src, mode='mean_flip',return_generator=True) print 'Store the average activity in the corresponding cell array' matlabDict[cleanName(roi)] = averageActivity # Write the Matlab dictionary to disk spio.savemat(activityFile, matlabDict, do_compression=True)
def morph_STC(fn_list, method, template='fsaverage', btmin=-0.3, btmax=0., subjects_dir=None): ''' Morph individual STC into the common brain space. Parameter ------------------------------------ fn_list: list The paths of the individual STCs. subjects_dir: The total bath of all the subjects. template: string The subject name as the common brain. btmin, btmax: float If 'baseline' is True, baseline is croped using this period. ''' from mne import read_source_estimate, morph_data for fname in fn_list: name = os.path.basename(fname) subject = name.split('_')[0] cond = name.split('_')[-2] import pdb pdb.set_trace() stc_name = name[:name.rfind('-lh.stc')] min_dir = subjects_dir + '/%s' % template # this path used for ROI definition stc_path = min_dir + '/%_ROIs/%s' % (method, subject) # fn_cov = meg_path + '/%s_empty,fibp1-45,nr-cov.fif' % subject set_directory(stc_path) # Morph STC stc = read_source_estimate(fname) stc_morph = morph_data(subject, template, stc, grade=5, subjects_dir=subjects_dir) stc_morph.save(stc_path + '/%s' % (stc_name), ftype='stc') if cond[2:] == 'st': stc_base = stc_morph.crop(btmin, btmax) stc_base.save(stc_path + '/%s_%s_baseline' % (subject, cond[:2]), ftype='stc')
def morph_STC(fn_stc, grade, template='fsaverage', event='LLst', baseline=True, btmin=-0.3, btmax=0.): from mne import read_source_estimate, morph_data fnlist = get_files_from_list(fn_stc) for fname in fnlist: name = os.path.basename(fname) subject = name.split('_')[0] stc_name = name[:name.rfind('-ave.fif')] min_dir = subjects_dir + '/%s' %template # this path used for ROI definition stc_path = min_dir + '/dSPM_ROIs/%s' %(subject) #fn_cov = meg_path + '/%s_empty,fibp1-45,nr-cov.fif' % subject set_directory(stc_path) # Morph STC stc = read_source_estimate(fname) stc_morph = morph_data(subject, template, stc, grade=grade) stc_morph.save(stc_path + '/%s' % (stc_name), ftype='stc') if baseline == True: stc_base = stc_morph.crop(btmin, btmax) stc_base.save(stc_path + '/%s_%s_baseline' % (subject, event[:2]), ftype='stc')
def morph_STC(fn_stc, grade, subjects_dir, template='fsaverage', event='LLst', baseline=True, btmin=-0.3, btmax=0.): ''' Morph individual STC into the common brain space. Parameter ------------------------------------ fn_stc: string or list The path of the individual STC. subjects_dir: The total bath of all the subjects. template: string The subject name as the common brain. event: string The name of event baseline: bool If true, prestimulus segment from 'btmin' to 'btmax' will be saved, If false, no baseline segment is saved. btmin, btmax: float If 'baseline' is True, baseline is croped using this period. ''' from mne import read_source_estimate, morph_data fnlist = get_files_from_list(fn_stc) for fname in fnlist: name = os.path.basename(fname) subject = name.split('_')[0] stc_name = name[:name.rfind('-lh.stc')] min_dir = subjects_dir + '/%s' % template # this path used for ROI definition stc_path = min_dir + '/dSPM_ROIs/%s' % (subject) # fn_cov = meg_path + '/%s_empty,fibp1-45,nr-cov.fif' % subject set_directory(stc_path) # Morph STC stc = read_source_estimate(fname) stc_morph = morph_data(subject, template, stc, grade=grade) stc_morph.save(stc_path + '/%s' % (stc_name), ftype='stc') if baseline is True: stc_base = stc_morph.crop(btmin, btmax) stc_base.save(stc_path + '/%s_%s_baseline' % (subject, event[:2]), ftype='stc')
def __call__(self, data): output = deepcopy(data) from_surf_file = dirname(dirname(self.from_surf.surf_file)) SUBJECTS_DIR, from_surf_name = split(from_surf_file) if 'lh' in self.from_surf.surf_file: # TODO: not good, we need to check vertices = [arange(data.data[0].shape[0]), arange(0)] else: vertices = [arange(0), arange(data.data[0].shape[0])] stc = SourceEstimate(atleast_2d(data.data[0]).T, vertices=vertices, tstep=0, tmin=0) m = morph_data(from_surf_name, self.to_surf, stc, subjects_dir=SUBJECTS_DIR, grade=None, smooth=self.smooth, verbose=False) output.data[0] = squeeze(m.data, axis=1) output.axis['surf'][0] = arange(m.data.shape[0]) return output
def morph_stcs_to_fsaverage(events_id, stc_per_epoch=False, inverse_method='dSPM', subjects_dir='', n_jobs=1): if subjects_dir is '': subjects_dir = os.environ['SUBJECTS_DIR'] for subject in get_subjects(): for cond_name in events_id.keys(): print('morphing {}, {}'.format(subject, cond_name)) if not stc_per_epoch: morphed_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc_morphed', '{}_{}_morphed_{}'.format(subject, cond_name, inverse_method)) if op.isfile('{}-stc.h5'.format(morphed_stc_file_name)): print('{} {} already morphed'.format(subject, cond_name)) else: local_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc', '{}_{}_{}'.format(subject, cond_name, inverse_method)) if op.isfile('{}-stc.h5'.format(local_stc_file_name)): stc = mne.read_source_estimate(local_stc_file_name) stc_morphed = mne.morph_data(subject, 'fsaverage', stc, grade=5, smooth=20, subjects_dir=subjects_dir) stc_morphed.save(morphed_stc_file_name, ftype='h5') else: print("can't find stc file for {}, {}".format(subject, cond_name)) else: stcs = glob.glob(op.join(LOCAL_ROOT_DIR, 'stc_epochs', '{}_{}_*_{}-stc.h5'.format(subject, cond_name, inverse_method))) params = [(subject, cond_name, stc_file_name, inverse_method, subjects_dir) for stc_file_name in stcs] utils.parallel_run(pool, _morphed_epochs_files, params, n_jobs)
def morph_stc(subject_from, subject_to, stc_from_file): stc_from = mne.read_source_estimate(stc_from_file) vertices_to = [np.arange(10242), np.arange(10242)] stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=4, grade=vertices_to) stc_to.save("{}_{}.stc".format(stc_from_file[:-4], subject_to))
def GDAVG_source_trialsfromFT_2cond(condnames,datasource): #ipython --pylab import mne import numpy as np from scipy import io from matplotlib import pyplot as plt from matplotlib import image as mpimg from mne.fiff import Raw from mne.minimum_norm import apply_inverse, make_inverse_operator from copy import deepcopy import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') import MatchEventsFT2MNE as match os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' # get a full list of subject and associated runs ListSubj= ('sd130343', 'cb130477', 'rb130313', 'jm100042', 'jm100109', 'sb120316', 'tk130502', 'lm130479', 'sg120518','ms130534','ma100253', 'sl130503','mb140004', 'mp140019', 'mm130405', 'dm130250', 'hr130504', 'wl130316', 'rl130571') listRunPerSubj = (('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD')) # list of bad EEG channels for EEG processing EEGbadlist = (['EEG25', 'EEG036'],['EEG035', 'EEG036'],['EEG025', 'EEG035', 'EEG036'],['EEG035'],['EEG017', 'EEG025'],['EEG026', 'EEG036'], [],['EEG025', 'EEG035', 'EEG036' 'EEG037'],['EEG002', 'EEG055'],['EEG025', 'EEG035'], ['EEG009', 'EEG022', 'EEG045', 'EEG046', 'EEG053', 'EEG054', 'EEG059'], ['EEG035', 'EEG057'],['EEG043'],['EEG035'],['EEG017', 'EEG025', 'EEG035'],['EEG025', 'EEG035'], ['EEG025', 'EEG035'],['EEG025', 'EEG035', 'EEG036', 'EEG017'],['EEG0017', 'EEG0025', 'EEG0036', 'EEG0026', 'EEG0034']) for i in range(len(ListSubj)): for j in range(len(listRunPerSubj[i])): print(j) print(i) # load trans_sss data # raw = Raw("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/preproc_"+listRunPerSubj[i][j]+"_trans_sss_raw.fif") raw.info['bads'] += EEGbadlist[i] # define events # tmp = str(j+1) fileE = io.loadmat("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/From_laptop/Subjects/"+ListSubj[i]+"/PsychData/events"+tmp+".mat") eventsFT = fileE['fullsubj'] eventsMNE = mne.find_events(raw, stim_channel=['STI101'],consecutive = False) print "%d events found" %len(eventsMNE) # find events corresponding to FT run j itemindex = np.where(eventsFT[:,7]==(j+1)) eventsFT = eventsFT[itemindex[0],:] ###################################################################### ###################################################################### if datasource == 'EVT': origevent = (16,20,24,28,32,17,21,25,29,33) # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent(0)) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] elif datasource == 'EVS': origevent = (18,22,26,30,34,19,23,27,31,35) # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent(0)) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] elif datasource == 'QTT': origevent = (6,8,10,12,14) # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent(0)) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] elif datasource == 'QTS': origevent = (7,9,11,13,15) # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent(0)) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] ######################################################################## ######################################################################## # set the "zero point" to a target event in MNE event initsampmne = eventsMNE[np.where(eventsMNE[:,2] == 18)[0][0],0] for l in range(eventsMNE.shape[0]): eventsMNE[l,0] = eventsMNE[l,0] - initsampmne # set the "zero point" to a target event in FT event initsampft = eventsFT[np.where(eventsFT[:,6] == 18)[0][0],0] for l in range(eventsFT.shape[0]): eventsFT[l,0] = eventsFT[l,0] - initsampft # reject bad data based on fieldtrip "ft_rejectvisual" good = np.where(eventsFT[:,8]== 1) eventsFT = eventsFT[good[0],:] # get the FT event in MNE events (should be the same but a small sample of events isn't matched # I need to check that soon SelEve = match.MatchEventsFT2MNE(eventsMNE,eventsFT) # get back to the original timing for m in range(SelEve.shape[0]): SelEve[m,0] = SelEve[m,0] + initsampmne # correct for photodelay for n in range(SelEve.shape[0]): SelEve[n,0] = SelEve[n,0] + 60; TMPset1 = io.loadmat("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/From_laptop/Scripts/event_def_for_mne/"+condnames[0]+".mat") TMPset2 = io.loadmat("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/From_laptop/Scripts/event_def_for_mne/"+condnames[1]+".mat") DATASET1 = TMPset1['cond'] DATASET2 = TMPset2['cond'] # process cond1&2 event_id1, tmin, tmax = DATASET1[:,0].tolist(), -0.2,1.1 event_id2, tmin, tmax = DATASET2[:,0].tolist(), -0.2,1.1 # epoched data picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, include=[], exclude='bads') epochs_cond1 = mne.Epochs(raw, SelEve, event_id1, tmin, tmax, baseline=(-0.2, 0),picks = picks,preload = True,reject = None,on_missing = 'warning') epochs_cond2 = mne.Epochs(raw, SelEve, event_id2, tmin, tmax, baseline=(-0.2, 0),picks = picks,preload = True,reject = None,on_missing = 'warning') baseline_cond1 = mne.Epochs(raw, SelEve, event_id1, -0.2, 0, baseline=(None, 0),picks = picks,preload = True,reject = None,on_missing = 'warning') baseline_cond2 = mne.Epochs(raw, SelEve, event_id2, -0.2, 0, baseline=(None, 0),picks = picks,preload = True,reject = None,on_missing = 'warning') # compute noise covariance matrix from emptyroom epochs # evokedcond1 = epochs_cond1.average() evokedcond2 = epochs_cond2.average() noise_cov1 = mne.compute_covariance(baseline_cond1,keep_sample_mean=True, tmin=-0.2, tmax=0) noise_cov2 = mne.compute_covariance(baseline_cond2,keep_sample_mean=True, tmin=-0.2, tmax=0) noise_cov1 = mne.cov.regularize(noise_cov1, evokedcond1.info, grad=0.1, mag=0.1, eeg=0.1) noise_cov2 = mne.cov.regularize(noise_cov2, evokedcond2.info, grad=0.1, mag=0.1, eeg=0.1) # append subject's runs if j == 0: epochs_tot_cond1 = deepcopy(epochs_cond1) epochs_tot_base1 = deepcopy(baseline_cond1) COV1 = noise_cov1 else: epochs_tmp_cond1 = epochs_cond1 epochs_tmp_base1 = baseline_cond1 COV1['data'] += noise_cov1['data'] COV1['nfree'] += noise_cov1['nfree'] COV1 = COV1 + noise_cov1 epochs_tot_cond1._data = np.vstack((epochs_tot_cond1._data,epochs_tmp_cond1._data)) epochs_tot_cond1.events = np.vstack((epochs_tot_cond1.events,epochs_tmp_cond1.events)) #epochs_tot_cond1.selection = np.concatenate((epochs_tot_cond1.selection,epochs_tmp_cond1.selection)) epochs_tot_base1._data = np.vstack((epochs_tot_base1._data,epochs_tmp_base1._data)) epochs_tot_base1.events = np.vstack((epochs_tot_base1.events,epochs_tmp_base1.events)) #epochs_tot_base1.selection = np.concatenate((epochs_tot_base1.selection,epochs_tmp_base1.selection)) # append subject's runs if j == 0: epochs_tot_cond2 = deepcopy(epochs_cond2) epochs_tot_base2 = deepcopy(baseline_cond2) COV2 = noise_cov2 else: epochs_tmp_cond2 = epochs_cond2 epochs_tmp_base2 = baseline_cond2 COV2['data'] += noise_cov2['data'] COV2['nfree'] += noise_cov2['nfree'] COV2 = COV2 + noise_cov2 epochs_tot_cond2._data = np.vstack((epochs_tot_cond2._data,epochs_tmp_cond2._data)) epochs_tot_cond2.events = np.vstack((epochs_tot_cond2.events,epochs_tmp_cond2.events)) #epochs_tot_cond2.selection = np.concatenate((epochs_tot_cond2.selection,epochs_tmp_cond2.selection)) epochs_tot_base2._data = np.vstack((epochs_tot_base2._data,epochs_tmp_base2._data)) epochs_tot_base2.events = np.vstack((epochs_tot_base2.events,epochs_tmp_base2.events)) #epochs_tot_base2.selection = np.concatenate((epochs_tot_base2.selection,epochs_tmp_base2.selection)) SelEve = None # save data evokedcond1 = epochs_tot_cond1.average() evokedcond1.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/"+condnames[1]+"_"+ListSubj[i]+"-ave.fif") # save data evokedcond2 = epochs_tot_cond2.average() evokedcond2.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/"+condnames[2]+"_"+ListSubj[i]+"-ave.fif") # compute noise covariance matrix from emptyroom epochs # NOISE_COV1 =mne.cov.regularize(COV1, evokedcond1.info, grad=0.1, mag=0.1, eeg=0.1) NOISE_COV2 =mne.cov.regularize(COV2, evokedcond2.info, grad=0.1, mag=0.1, eeg=0.1) print(noise_cov1) # Show covariance mne.viz.plot_cov(noise_cov1, raw.info, colorbar=True, proj=True,show_svd=False,show=False) plt.savefig("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/plots/"+ListSubj[i]+"covmat") plt.close() # dSPM solution # fname_fwd=("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/run3_ico-5-fwd.fif") forward = mne.read_forward_solution(fname_fwd,surf_ori=True) inverse_operator1 = make_inverse_operator(evokedcond1.info, forward, noise_cov1, loose=0.4, depth=0.8) inverse_operator2 = make_inverse_operator(evokedcond2.info, forward, noise_cov2, loose=0.4, depth=0.8) snr = 3.0 lambda2 = 1.0 / snr **2 dSPM = True stccond1 = apply_inverse(evokedcond1, inverse_operator1, lambda2, 'dSPM', pick_normal=False) stccond1.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/"+ListSubj[i]+"_"+condnames[0]+"_dPSMinverse_ico-5-fwd.fif") stc_fsaverage_cond1 = mne.morph_data(ListSubj[i], 'fsaverage', stccond1) stc_fsaverage_cond1.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/"+ListSubj[i]+"_"+condnames[0]+"_dPSMinverse_ico-5-fwd-fsaverage.fif") stccond2 = apply_inverse(evokedcond2, inverse_operator2, lambda2, 'dSPM', pick_normal=False) stccond2.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/"+ListSubj[i]+"_"+condnames[1]+"_dPSMinverse_ico-5-fwd.fif") stc_fsaverage_cond2 = mne.morph_data(ListSubj[i], 'fsaverage', stccond2) stc_fsaverage_cond2.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/"+ListSubj[i]+"_"+condnames[1]+"_dPSMinverse_ico-5-fwd-fsaverage.fif")
print(__doc__) ############################################################################### # Set parameters data_path = sample.data_path() stc_fname = data_path + '/MEG/sample/sample_audvis-meg-lh.stc' subjects_dir = data_path + '/subjects' # Load stc to in common cortical space (fsaverage) stc = mne.read_source_estimate(stc_fname) stc.resample(50) stc = mne.morph_data('sample', 'fsaverage', stc, grade=5, smooth=20, subjects_dir=subjects_dir) n_vertices_fsave, n_times = stc.data.shape tstep = stc.tstep n_subjects1, n_subjects2 = 7, 9 print('Simulating data for %d and %d subjects.' % (n_subjects1, n_subjects2)) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X1 = np.random.randn(n_vertices_fsave, n_times, n_subjects1) * 10 X2 = np.random.randn(n_vertices_fsave, n_times, n_subjects2) * 10 X1[:, :, :] += stc.data[:, :, np.newaxis] # make the activity bigger for the second set of subjects X2[:, :, :] += 3 * stc.data[:, :, np.newaxis]
from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' subjects_dir = data_path + '/subjects' os.environ['SUBJECTS_DIR'] = subjects_dir stc_fname = data_path + '/MEG/sample/sample_audvis-meg' stc = mne.read_source_estimate(stc_fname) new_stc = mne.morph_data('sample', 'fsaverage', stc, grade=5, subjects_dir=subjects_dir, n_jobs=2) subject = 'fsaverage' # Plot brain in 3D with PySurfer if available brain = new_stc.plot(subject, hemi='lh', subjects_dir=subjects_dir) brain.show_view('lateral') # use peak getter to move vizualization to the time point of the peak vertno_max, time_idx = new_stc.get_peak(hemi='lh', time_as_index=True) brain.set_data_time_index(time_idx) # draw marker at maximum peaking vertex
def test_morph_data(): """Test morphing of data """ tempdir = _TempDir() subject_from = 'sample' subject_to = 'fsaverage' stc_from = read_source_estimate(fname_smorph, subject='sample') stc_to = read_source_estimate(fname_fmorph) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation assert_array_equal(stc_to.time_as_index([0.09, 0.1], use_rounding=True), [0, len(stc_to.times) - 1]) assert_raises(ValueError, stc_from.morph, subject_to, grade=3, smooth=-1, subjects_dir=subjects_dir) stc_to1 = stc_from.morph(subject_to, grade=3, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) stc_to1.save(op.join(tempdir, '%s_audvis-meg' % subject_to)) # Morphing to a density that is too high should raise an informative error # (here we need to push to grade=6, but for some subjects even grade=5 # will break) assert_raises(ValueError, stc_to1.morph, subject_from, grade=6, subjects_dir=subjects_dir) # make sure we can specify vertices vertices_to = grade_to_vertices(subject_to, grade=3, subjects_dir=subjects_dir) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) # make sure we can use different buffer_size stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3, subjects_dir=subjects_dir) # make sure we get a warning about # of steps with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=1, buffer_size=3, subjects_dir=subjects_dir) assert_equal(len(w), 2) assert_array_almost_equal(stc_to.data, stc_to1.data, 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) assert_array_almost_equal(stc_to1.data, stc_to3.data) # make sure precomputed morph matrices work morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, smooth=12, subjects_dir=subjects_dir) stc_to3 = stc_from.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) assert_raises(ValueError, stc_from.morph_precomputed, subject_to, vertices_to, 'foo') assert_raises(ValueError, stc_from.morph_precomputed, subject_to, [vertices_to[0]], morph_mat) assert_raises(ValueError, stc_from.morph_precomputed, subject_to, [vertices_to[0][:-1], vertices_to[1]], morph_mat) assert_raises(ValueError, stc_from.morph_precomputed, subject_to, vertices_to, morph_mat, subject_from='foo') # steps warning with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, smooth=1, subjects_dir=subjects_dir) assert_equal(len(w), 2) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999) # make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert_true(stc_to5.data.shape[0] == 163842 + 163842) # Morph sparse data # Make a sparse stc stc_from.vertices[0] = stc_from.vertices[0][[100, 500]] stc_from.vertices[1] = stc_from.vertices[1][[200]] stc_from._data = stc_from._data[:3] assert_raises(RuntimeError, stc_from.morph, subject_to, sparse=True, grade=5, subjects_dir=subjects_dir) stc_to_sparse = stc_from.morph(subject_to, grade=None, sparse=True, subjects_dir=subjects_dir) assert_array_almost_equal(np.sort(stc_from.data.sum(axis=1)), np.sort(stc_to_sparse.data.sum(axis=1))) assert_equal(len(stc_from.rh_vertno), len(stc_to_sparse.rh_vertno)) assert_equal(len(stc_from.lh_vertno), len(stc_to_sparse.lh_vertno)) assert_equal(stc_to_sparse.subject, subject_to) assert_equal(stc_from.tmin, stc_from.tmin) assert_equal(stc_from.tstep, stc_from.tstep) stc_from.vertices[0] = np.array([], dtype=np.int64) stc_from._data = stc_from._data[:1] stc_to_sparse = stc_from.morph(subject_to, grade=None, sparse=True, subjects_dir=subjects_dir) assert_array_almost_equal(np.sort(stc_from.data.sum(axis=1)), np.sort(stc_to_sparse.data.sum(axis=1))) assert_equal(len(stc_from.rh_vertno), len(stc_to_sparse.rh_vertno)) assert_equal(len(stc_from.lh_vertno), len(stc_to_sparse.lh_vertno)) assert_equal(stc_to_sparse.subject, subject_to) assert_equal(stc_from.tmin, stc_from.tmin) assert_equal(stc_from.tstep, stc_from.tstep)
def test_morph_data(): """Test morphing of data """ tempdir = _TempDir() subject_from = 'sample' subject_to = 'fsaverage' stc_from = read_source_estimate(fname_smorph, subject='sample') stc_to = read_source_estimate(fname_fmorph) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation stc_to1 = stc_from.morph(subject_to, grade=3, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) stc_to1.save(op.join(tempdir, '%s_audvis-meg' % subject_to)) # make sure we can specify vertices vertices_to = grade_to_vertices(subject_to, grade=3, subjects_dir=subjects_dir) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) # make sure we can use different buffer_size stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert_array_almost_equal(stc_to.data, stc_to1.data, 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) assert_array_almost_equal(stc_to1.data, stc_to3.data) # make sure precomputed morph matrices work morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, smooth=12, subjects_dir=subjects_dir) stc_to3 = stc_from.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert_true(np.corrcoef(mean_to, mean_from).min() > 0.999) # make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert_true(stc_to5.data.shape[0] == 163842 + 163842) # Morph sparse data # Make a sparse stc stc_from.vertices[0] = stc_from.vertices[0][[100, 500]] stc_from.vertices[1] = stc_from.vertices[1][[200]] stc_from._data = stc_from._data[:3] assert_raises(RuntimeError, stc_from.morph, subject_to, sparse=True, grade=5, subjects_dir=subjects_dir) stc_to_sparse = stc_from.morph(subject_to, grade=None, sparse=True, subjects_dir=subjects_dir) assert_array_almost_equal(np.sort(stc_from.data.sum(axis=1)), np.sort(stc_to_sparse.data.sum(axis=1))) assert_equal(len(stc_from.rh_vertno), len(stc_to_sparse.rh_vertno)) assert_equal(len(stc_from.lh_vertno), len(stc_to_sparse.lh_vertno)) assert_equal(stc_to_sparse.subject, subject_to) assert_equal(stc_from.tmin, stc_from.tmin) assert_equal(stc_from.tstep, stc_from.tstep) stc_from.vertices[0] = np.array([], dtype=np.int64) stc_from._data = stc_from._data[:1] stc_to_sparse = stc_from.morph(subject_to, grade=None, sparse=True, subjects_dir=subjects_dir) assert_array_almost_equal(np.sort(stc_from.data.sum(axis=1)), np.sort(stc_to_sparse.data.sum(axis=1))) assert_equal(len(stc_from.rh_vertno), len(stc_to_sparse.rh_vertno)) assert_equal(len(stc_from.lh_vertno), len(stc_to_sparse.lh_vertno)) assert_equal(stc_to_sparse.subject, subject_to) assert_equal(stc_from.tmin, stc_from.tmin) assert_equal(stc_from.tstep, stc_from.tstep)
subject_from = 'sample' subject_to = 'fsaverage' subjects_dir = data_path + '/subjects' fname = data_path + '/MEG/sample/sample_audvis-meg' src_fname = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' # Read input stc file stc_from = mne.read_source_estimate(fname) # Morph using one method (supplying the vertices in fsaverage's source # space makes it faster). Note that for any generic subject, you could do: # vertices_to = mne.grade_to_vertices(subject_to, grade=5) # But fsaverage's source space was set up so we can just do this: vertices_to = [np.arange(10242), np.arange(10242)] stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1, grade=vertices_to, subjects_dir=subjects_dir) stc_to.save('%s_audvis-meg' % subject_to) # Morph using another method -- useful if you're going to do a lot of the # same inter-subject morphing operations; you could save and load morph_mat morph_mat = mne.compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, subjects_dir=subjects_dir) stc_to_2 = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat) stc_to_2.save('%s_audvis-meg_2' % subject_to) # View source activations plt.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from') plt.plot(stc_to.times, stc_to.data.mean(axis=0), 'b', label='to') plt.plot(stc_to_2.times, stc_to.data.mean(axis=0), 'g', label='to_2')
def make_inverse_operator(fname_evoked): from mne.minimum_norm import (apply_inverse) import mne, os fnlist = get_files_from_list(fname_evoked) # loop across all filenames for fn_evoked in fnlist: #extract the subject infromation from the file name name = os.path.basename(fn_evoked) subject = name.split('_')[0] fn_inv = fn_evoked.split('.fif')[0] + '-inv.fif' fn_stc = fn_evoked.split('.fif')[0] fn_morph = fn_evoked.split('.fif')[0] + ',morph' subject_path = subjects_dir + subject fn_cov = subject_path + '/MEG/%s,bp1-45Hz,empty-cov.fif' % subject fn_trans = subject_path + '/MEG/%s-trans.fif' % subject fn_src = subject_path + '/bem/%s-ico-4-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject snr = 3.0 lambda2 = 1.0 / snr**2 # Load data evoked = mne.read_evokeds(fn_evoked, condition=0, baseline=(None, 0)) fwd = mne.make_forward_solution(evoked.info, mri=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) fwd = mne.convert_forward_solution(fwd, surf_ori=True) noise_cov = mne.read_cov(fn_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, proj=True) forward_meg = mne.pick_types_forward(fwd, meg=True, eeg=False) inverse_operator = mne.minimum_norm.make_inverse_operator(evoked.info, forward_meg, noise_cov, loose=0.2, depth=0.8) mne.minimum_norm.write_inverse_operator(fn_inv, inverse_operator) stcs = dict() # Compute inverse solution stcs[subject] = apply_inverse(evoked, inverse_operator, lambda2, "dSPM", pick_ori=None) # Morph STC subject_id = 'fsaverage' #vertices_to = mne.grade_to_vertices(subject_to, grade=5) #stcs['morph'] = mne.morph_data(subject, subject_to, stcs[subject], n_jobs=1, # grade=vertices_to) stcs[subject].save(fn_stc) stcs['morph'] = mne.morph_data(subject, subject_id, stcs[subject], 4, smooth=4) stcs['morph'].save(fn_morph) fig_out = fn_morph + '.png' plot_evoked_stc(subject, stcs, fig_out)
def apply_inverse(fn_epo, event='LLst',ctmin=0.05, ctmax=0.25, nctmin=-0.2, nctmax=0, fmin=4, fmax=8, min_subject='fsaverage', STCs=False): """ Inverse evokes into source space using DICS method. ---------- fn_epo : epochs of raw data. event_id: event id related with epochs. ctmin: the min time for computing CSD ctmax: the max time for computing CSD fmin: min value of the interest frequency band fmax: max value of the interest frequency band min_subject: the subject for the common brain space. STCs: bool, make STCs of epochs. """ from mne import Epochs, pick_types from mne.io import Raw from mne.event import make_fixed_length_events fnlist = get_files_from_list(fn_epo) # loop across all filenames for fname in fnlist: subjects_dir = os.environ['SUBJECTS_DIR'] # extract the subject infromation from the file name meg_path = os.path.split(fname)[0] name = os.path.basename(fname) stc_name = name[:name.rfind('-epo.fif')] subject = name.split('_')[0] subject_path = subjects_dir + '/%s' %subject min_dir = subjects_dir + '/%s' %min_subject fn_trans = meg_path + '/%s-trans.fif' % subject fn_src = subject_path + '/bem/%s-ico-4-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject # Make sure the target path is exist stc_path = min_dir + '/DICS_ROIs/%s' % subject set_directory(stc_path) # Read the MNI source space epochs = mne.read_epochs(fname) evoked = epochs.average() forward = mne.make_forward_solution(epochs.info, trans=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) forward = mne.convert_forward_solution(forward, surf_ori=True) from mne.time_frequency import compute_epochs_csd from mne.beamformer import dics data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=ctmin, tmax=ctmax, fmin=fmin, fmax=fmax) noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=nctmin, tmax=nctmax, fmin=fmin, fmax=fmax) stc = dics(evoked, forward, noise_csd, data_csd) from mne import morph_data stc_morph = morph_data(subject, min_subject, stc, grade=4, smooth=4) stc_morph.save(stc_path + '/%s_%d_%d' % (stc_name, fmin, fmax), ftype='stc') if STCs == True: stcs_path = stc_path + '/STCs-%s/' %event reset_directory(stcs_path) stcs = dics(epochs, forward, noise_csd, data_csd) s = 0 while s < len(stcs): stc_morph = mne.morph_data(subject, min_subject, stcs[s], grade=4, smooth=4) stc_morph.save(stcs_path + '/trial_%s' % (str(s)), ftype='stc') s = s + 1
sol = abs(np.dot(weights, data)) stc = mne.SourceEstimate( sol, [forward['src'][0]['vertno'], forward['src'][1]['vertno']], 0, 1, subject=subj) stc.save(dir_out + 'lcmv-%dto%d-' % (l_freq, h_freq) + subj) # morph all subjects subject_to = 'fsaverage' for l_freq, h_freq in bands: for subj in subjs: fname = dir_out + 'lcmv-%dto%d-' % (l_freq, h_freq) + subj stc_from = mne.read_source_estimate(fname) vertices_to = [np.arange(10242), np.arange(10242)] stc = mne.morph_data(subj, subject_to, stc_from, grade=vertices_to) stc.save(dir_out + 'morphed-lcmv-%dto%d-' % (l_freq, h_freq) + subj) # concatenate all subjects and apply ICA band_ICs = [] band_corr_ICs = [] for l_freq, h_freq in bands: print 'Concatenating sources in band %d to %d Hz' % (l_freq, h_freq) init_sources = 20500 init_time = 38500 # create huge array so we can add all the data and then resize it appropriately data = np.empty([init_sources, init_time]) data[:] = np.nan cnt = 0 for subj in subjs: fname = dir_out + 'morphed-lcmv-%dto%d-' % (l_freq, h_freq) + subj
def GDAVG_source_trialsfromFT_1cond(condnames,datasource): #ipython --pylab import mne import numpy as np from scipy import io from matplotlib import pyplot as plt from mne.fiff import Raw from mne.minimum_norm import apply_inverse, make_inverse_operator from copy import deepcopy import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') import MatchEventsFT2MNE as match os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' # get a full list of subject and associated runs ListSubj= ('sd130343', 'cb130477', 'rb130313', 'jm100042', 'jm100109', 'sb120316', 'tk130502', 'lm130479', 'sg120518','ms130534','ma100253', 'sl130503','mb140004', 'mp140019', 'dm130250', 'hr130504', 'wl130316', 'rl130571') listRunPerSubj = (('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD'), ('run1_GD','run2_GD','run3_DG','run4_DG','run5_GD')) # list of bad EEG channels for EEG processing EEGbadlist = (['EEG25', 'EEG036'],['EEG035', 'EEG036'],['EEG025', 'EEG035', 'EEG036'],['EEG035'],['EEG017', 'EEG025'],['EEG026', 'EEG036'], [],['EEG025', 'EEG035', 'EEG036' 'EEG037'],['EEG002', 'EEG055'],['EEG025', 'EEG035'], ['EEG009', 'EEG022', 'EEG045', 'EEG046', 'EEG053', 'EEG054', 'EEG059'], ['EEG035', 'EEG057'],['EEG043'],['EEG035'],['EEG025', 'EEG035'], ['EEG025', 'EEG035'],['EEG025', 'EEG035', 'EEG036', 'EEG017'],['EEG0017', 'EEG0025', 'EEG0036', 'EEG0026', 'EEG0034']) for i in range(len(ListSubj)): # open a text logfile logfile = open("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/logfile_preproc.txt", "w") for j in range(len(listRunPerSubj[i])): print(j) print(i) # load trans_sss data raw = io.RawFIFF("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/preproc_"+listRunPerSubj[i][j]+"_trans_sss_raw.fif", preload = True) # band-pass filter 1-35Hz raw.filter(l_freq = 1, h_freq=35, method = 'iir',n_jobs=4) # Specify bad channels raw.info['bads'] += EEGbadlist[i] # define events : import trial definition from fieldtrip and with mne_function tmp = str(j+1) fileE = io.loadmat("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/From_laptop/Subjects/"+ListSubj[i]+"/PsychData/events"+tmp+".mat") eventsFT = fileE['fullsubj'] eventsMNE = mne.find_events(raw, stim_channel=['STI101'],consecutive = False) print "%d events found" %len(eventsMNE) logfile.write("%d mne events found" %len(eventsMNE) "\n") logfile.write("%d ft events found" %len(eventsFT) "\n") # find events corresponding to FT run j itemindex = np.where(eventsFT[:,7]==(j+1)) eventsFT = eventsFT[itemindex[0],:] # set the "zero point" to a target event in MNE event initsampmne = eventsMNE[np.where(eventsMNE[:,2] == 18)[0][0],0] for l in range(eventsMNE.shape[0]): eventsMNE[l,0] = eventsMNE[l,0] - initsampmne # set the "zero point" to a target event in FT event initsampft = eventsFT[np.where(eventsFT[:,6] == 18)[0][0],0] for l in range(eventsFT.shape[0]): eventsFT[l,0] = eventsFT[l,0] - initsampft # Select original event before recoding according to the condition and the source dataset if datasource == 'EVT': origevent = [16,20,24,28,32,17,21,25,29,33] # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent[0]) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] elif datasource == 'EVS': origevent = [18,22,26,30,34,19,23,27,31,35] # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent[0]) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] elif datasource == 'QTT': origevent = [6,8,10,12,14] # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent[0]) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] elif datasource == 'QTS': origevent = [7,9,11,13,15] # find events corresponding to "Historical events" stimuli init = np.where(eventsFT[:,6]== origevent[0]) for k in origevent[1:]: init = np.append(init,np.where(eventsFT[:,6]== k)[0]) eventsFT = eventsFT[init,:] # reject bad data based on fieldtrip "ft_rejectvisual" good = np.where(eventsFT[:,8]== 1) eventsFT = eventsFT[good[0],:] # get the FT event in MNE events (should be the same but a small sample of events isn't matched # (FIXME) SelEve = match.MatchEventsFT2MNE(eventsMNE,eventsFT) # get back to the original timing for m in range(SelEve.shape[0]): SelEve[m,0] = SelEve[m,0] + initsampmne # correct for photodelay for n in range(SelEve.shape[0]): SelEve[n,0] = SelEve[n,0] + 60 TMPset1 = io.loadmat("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/From_laptop/Scripts/event_def_for_mne/"+condnames+".mat") DATASET1 = TMPset1['cond'] logfile.write("%d selected final events" %len(SelEve) "\n") # process cond1 event_id1, tmin, tmax = DATASET1[:,0].tolist(), -0.2,1.1 # epoched data picks_meg = mne.pick_types(raw.info, meg=False, eeg=True, stim=True , eog=False, include=[], exclude='bads') picks_eeg = mne.pick_types(raw.info, meg=True , eeg=False, stim=True, eog=False, include=[], exclude='bads') picks_meeg = mne.pick_types(raw.info, meg=True , eeg=True, stim=True , eog=False, include=[], exclude='bads') epochs_cond1_meg = mne.Epochs(raw, SelEve, event_id1, tmin, tmax, baseline=(-0.2, 0),picks_meg = picks,preload = True,decim=4,reject = None,on_missing = 'warning') epochs_cond1_eeg = mne.Epochs(raw, SelEve, event_id1, tmin, tmax, baseline=(-0.2, 0),picks_eeg = picks,preload = True,decim=4,reject = None,on_missing = 'warning') epochs_cond1_meeg= mne.Epochs(raw, SelEve, event_id1, tmin, tmax, baseline=(-0.2, 0),picks_meeg = picks,preload = True,decim=4,reject = None,on_missing = 'warning') baseline_cond1_meg = mne.Epochs(raw, SelEve, event_id1, -0.2, 0, baseline=(None, 0),picks_meg = picks,preload = True,reject = None,on_missing = 'warning') baseline_cond1_meg = mne.Epochs(raw, SelEve, event_id1, -0.2, 0, baseline=(None, 0),picks_eeg = picks,preload = True,reject = None,on_missing = 'warning') baseline_cond1_meeg= mne.Epochs(raw, SelEve, event_id1, -0.2, 0, baseline=(None, 0),picks_meeg= picks,preload = True,reject = None,on_missing = 'warning') # compute noise covariance matrix from emptyroom epochs # evokedcond1_meg = epochs_cond1.average() evokedcond1_eeg = epochs_cond1.average() evokedcond1_meeg= epochs_cond1.average() noise_cov1_meg = mne.compute_covariance(baseline_cond1_meg,keep_sample_mean=True, tmin=-0.2, tmax=0) noise_cov1_meg = mne.cov.regularize(noise_cov1_meg, evokedcond1_meg.info, grad=0.1, mag=0.1, eeg=0.1) noise_cov1_eeg = mne.compute_covariance(baseline_cond1_eeg,keep_sample_mean=True, tmin=-0.2, tmax=0) noise_cov1_eeg = mne.cov.regularize(noise_cov1_eeg, evokedcond1_meg.info, grad=0.1, mag=0.1, eeg=0.1) noise_cov1_meeg = mne.compute_covariance(baseline_cond1_meeg,keep_sample_mean=True, tmin=-0.2, tmax=0) noise_cov1_meeg = mne.cov.regularize(noise_cov1_meeg, evokedcond1_meg.info, grad=0.1, mag=0.1, eeg=0.1) # append subject's meg runs if j == 0: epochs_tot_cond1_meg = deepcopy(epochs_cond1_meg) epochs_tot_base1_meg = deepcopy(baseline_cond1_meg) COV1_meg = noise_cov1_meg else: epochs_tmp_cond1_meg = epochs_cond1_meg epochs_tmp_base1_meg = baseline_cond1_meg COV1_meg['data'] += noise_cov1_meg['data'] COV1_meg['nfree'] += noise_cov1_meg['nfree'] COV1_meg = COV1_meg + noise_cov1_meg epochs_tot_cond1_meg._data = np.vstack((epochs_tot_cond1_meg._data,epochs_tmp_cond1_meg._data)) epochs_tot_cond1_meg.events = np.vstack((epochs_tot_cond1_meg.events,epochs_tmp_cond1_meg.events)) #epochs_tot_cond1.selection = np.concatenate((epochs_tot_cond1.selection,epochs_tmp_cond1.selection)) epochs_tot_base1_meg._data = np.vstack((epochs_tot_base1_meg._data,epochs_tmp_base1_meg._data)) epochs_tot_base1_meg.events = np.vstack((epochs_tot_base1_meg.events,epochs_tmp_base1_meg.events)) #epochs_tot_base1.selection = np.concatenate((epochs_tot_base1.selection,epochs_tmp_base1.selection)) SelEve = None # save evoked data evokedcond1_meg = epochs_tot_cond1_meg.average() write_evokeds("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEEG_"+condnames+"_"+ListSubj[i]+"-ave.fif",evokedcond1_meeg) #compute noise covariance matrix from emptyroom epochs # NOISE_COV1_meg = mne.cov.regularize(COV1_meg, evokedcond1_meg.info, grad=0.1, mag=0.1, eeg=0.1) # append subject's eeg runs if j == 0: epochs_tot_cond1_eeg = deepcopy(epochs_cond1_eeg) epochs_tot_base1_eeg = deepcopy(baseline_cond1_eeg) COV1_eeg = noise_cov1_eeg else: epochs_tmp_cond1_eeg = epochs_cond1_eeg epochs_tmp_base1_eeg = baseline_cond1_eeg COV1_eeg['data'] += noise_cov1_eeg['data'] COV1_eeg['nfree'] += noise_cov1_eeg['nfree'] COV1_eeg = COV1_eeg + noise_cov1_eeg epochs_tot_cond1_eeg._data = np.vstack((epochs_tot_cond1_eeg._data,epochs_tmp_cond1_eeg._data)) epochs_tot_cond1_eeg.events = np.vstack((epochs_tot_cond1_eeg.events,epochs_tmp_cond1_eeg.events)) #epochs_tot_cond1.selection = np.concatenate((epochs_tot_cond1.selection,epochs_tmp_cond1.selection)) epochs_tot_base1_eeg._data = np.vstack((epochs_tot_base1_eeg._data,epochs_tmp_base1_eeg._data)) epochs_tot_base1_eeg.events = np.vstack((epochs_tot_base1_eeg.events,epochs_tmp_base1_eeg.events)) #epochs_tot_base1.selection = np.concatenate((epochs_tot_base1.selection,epochs_tmp_base1.selection)) # save evoked data evokedcond1_eeg = epochs_tot_cond1_eeg.average() write_evokeds("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/EEG_"+condnames+"_"+ListSubj[i]+"-ave.fif",evokedcond1_eeg) #compute noise covariance matrix from emptyroom epochs # NOISE_COV1_eeg = mne.cov.regularize(COV1_eeg, evokedcond1_eeg.info, grad=0.1, mag=0.1, eeg=0.1) # append subject's meeg runs if j == 0: epochs_tot_cond1_meeg = deepcopy(epochs_cond1_meeg) epochs_tot_base1_meeg = deepcopy(baseline_cond1_meeg) COV1_meeg = noise_cov1_meeg else: epochs_tmp_cond1_meeg = epochs_cond1_meeg epochs_tmp_base1_meeg = baseline_cond1_meeg COV1_meeg['data'] += noise_cov1_meeg['data'] COV1_meeg['nfree'] += noise_cov1_meeg['nfree'] COV1_meeg = COV1_meeg + noise_cov1_meeg epochs_tot_cond1_meeg._data = np.vstack((epochs_tot_cond1_meeg._data,epochs_tmp_cond1_meeg._data)) epochs_tot_cond1_meeg.events = np.vstack((epochs_tot_cond1_meeg.events,epochs_tmp_cond1_meeg.events)) #epochs_tot_cond1.selection = np.concatenate((epochs_tot_cond1.selection,epochs_tmp_cond1.selection)) epochs_tot_base1_meeg._data = np.vstack((epochs_tot_base1_meeg._data,epochs_tmp_base1_meeg._data)) epochs_tot_base1_meeg.events = np.vstack((epochs_tot_base1_meeg.events,epochs_tmp_base1_meeg.events)) #epochs_tot_base1.selection = np.concatenate((epochs_tot_base1.selection,epochs_tmp_base1.selection)) # save evoked data evokedcond1_meeg = epochs_tot_cond1_meeg.average() write_evokeds("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEEG_"+condnames+"_"+ListSubj[i]+"-ave.fif",evokedcond1_meeg) #compute noise covariance matrix from emptyroom epochs # NOISE_COV1_meeg = mne.cov.regularize(COV1_meeg, evokedcond1_meeg.info, grad=0.1, mag=0.1, eeg=0.1) print(NOISE_COV1_meeg) # Show covariance mne.viz.plot_cov(NOISE_COV1_meeg, raw.info, colorbar=True, proj=True,show_svd=False,show=False) plt.savefig("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/plots/covmat/MEEG_"+ListSubj[i]+condnames+"covmat") plt.close() # dSPM solution # fname_fwd=("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/run3_ico-5-fwd.fif") forward = mne.read_forward_solution(fname_fwd,surf_ori=True) # save evoked info (FIXME, used to be able to reuse evoked.info for dPSM) evokedcond1_meg.info.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEGevokedinfo_"+condnames+"_"+ListSubj[i]) evokedcond1_eeg.info.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/EEGevokedinfo_"+condnames+"_"+ListSubj[i]) evokedcond1_meeg.info.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEEGevokedinfo_"+condnames+"_"+ListSubj[i]) inverse_operator1_meg = make_inverse_operator(evokedcond1_meg.info, forward, NOISE_COV1_meg, loose=0.2, depth=0.8) inverse_operator1_eeg = make_inverse_operator(evokedcond1_eeg.info, forward, NOISE_COV1_eeg, loose=0.2, depth=0.8) inverse_operator1_meeg = make_inverse_operator(evokedcond1_meeg.info, forward, NOISE_COV1_meeg, loose=0.2, depth=0.8) # dSPM solution # snr = 3.0 lambda2 = 1.0 / snr **2 stccond1_meg = apply_inverse(evokedcond1_meg, inverse_operator1_meg, lambda2,method ='dSPM', pick_ori= None) stccond1_meg.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEG_"+ListSubj[i]+"_"+condnames+"_pick_oriNone_dPSMinverse_ico-5-fwd.fif") stccond1bis_meg = apply_inverse(evokedcond1_meg, inverse_operator1_meg, lambda2,method ='dSPM', pick_ori= "normal") stccond1bis_meg.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEG_"+ListSubj[i]+"_"+condnames+"_pick_orinormal_dPSMinverse_ico-5-fwd.fif") stc_fsaverage_cond1_meg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_meg) stc_fsaverage_cond1_meg.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEG_"+ListSubj[i]+"_"+condnames+"_pick_oriNone_dPSMinverse_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1bis_meg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1bis_meg) stc_fsaverage_cond1bis_meg.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"+ListSubj[i]+"/mne_python/MEG_"+ListSubj[i]+"_"+condnames+"_pick_orinormal_dPSMinverse_ico-5-fwd-fsaverage.fif")
def test_morph_stc_dense(): """Test morphing stc.""" subject_from = 'sample' subject_to = 'fsaverage' stc_from = read_source_estimate(fname_smorph, subject='sample') stc_to = read_source_estimate(fname_fmorph) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation assert_array_equal(stc_to.time_as_index([0.09, 0.1], use_rounding=True), [0, len(stc_to.times) - 1]) # After dep change this to: # stc_to1 = compute_source_morph( # subject_to=subject_to, spacing=3, smooth=12, src=stc_from, # subjects_dir=subjects_dir).apply(stc_from) with pytest.deprecated_call(): stc_to1 = stc_from.morph( subject_to=subject_to, grade=3, smooth=12, subjects_dir=subjects_dir) assert_allclose(stc_to.data, stc_to1.data, atol=1e-5) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert np.corrcoef(mean_to, mean_from).min() > 0.999 vertices_to = grade_to_vertices(subject_to, grade=3, subjects_dir=subjects_dir) # make sure we can fill by morphing with pytest.warns(RuntimeWarning, match='consider increasing'): morph = compute_source_morph( stc_from, subject_from, subject_to, spacing=None, smooth=1, subjects_dir=subjects_dir) # after deprecation change this to: # stc_to5 = morph.apply(stc_from) with pytest.deprecated_call(): stc_to5 = stc_from.morph_precomputed( morph_mat=morph.morph_mat, subject_to=subject_to, vertices_to=morph.vertices_to) assert stc_to5.data.shape[0] == 163842 + 163842 # after deprecation delete this with pytest.deprecated_call(): stc_to6 = morph_data( subject_from, subject_to, stc_from, grade=None, smooth=1, subjects_dir=subjects_dir) assert_allclose(stc_to6.data, stc_to5.data) # Morph vector data stc_vec = _real_vec_stc() stc_vec_to1 = compute_source_morph( stc_vec, subject_from, subject_to, subjects_dir=subjects_dir, spacing=vertices_to, smooth=1, warn=False).apply(stc_vec) assert stc_vec_to1.subject == subject_to assert stc_vec_to1.tmin == stc_vec.tmin assert stc_vec_to1.tstep == stc_vec.tstep assert len(stc_vec_to1.lh_vertno) == 642 assert len(stc_vec_to1.rh_vertno) == 642 # Degenerate conditions # Morphing to a density that is too high should raise an informative error # (here we need to push to grade=6, but for some subjects even grade=5 # will break) with pytest.raises(ValueError, match='Cannot use icosahedral grade 6 '): compute_source_morph( stc_to1, subject_from=subject_to, subject_to=subject_from, spacing=6, subjects_dir=subjects_dir) del stc_to1 with pytest.raises(ValueError, match='smooth.* has to be at least 1'): compute_source_morph( stc_from, subject_from, subject_to, spacing=5, smooth=-1, subjects_dir=subjects_dir) # subject from mismatch with pytest.raises(ValueError, match="does not match source space subj"): compute_source_morph(stc_from, subject_from='foo', subjects_dir=subjects_dir) # only one set of vertices with pytest.raises(ValueError, match="grade.*list must have two elements"): compute_source_morph( stc_from, subject_from=subject_from, spacing=[vertices_to[0]], subjects_dir=subjects_dir)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=0.5, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) # compute evoked response and noise covariance, and plot evoked evoked = epochs.average() cov = mne.compute_covariance(epochs, tmax=0) evoked.plot() # compute inverse operator fwd_fname = 'sample_audvis-meg-eeg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fwd_fname, surf_ori=True) inv = mne.minimum_norm.make_inverse_operator(raw.info, fwd, cov, loose=0.2) # compute inverse solution stc = mne.minimum_norm.apply_inverse(evoked, inv, lambda2=1 / 3.0**2, method='dSPM') # morph it to average brain for group study stc_avg = mne.morph_data('sample', 'fsaverage', stc, 5, smooth=5) stc_avg.plot()
def SourceReconstruction_eq(condnames, ListSubj, modality, Method, covmatsource): # condnames = ('signDT8_1','signDT8_8') # ListSubj = ('jm100109',) # modality = 'MEG' # covmatsource = 'EV' import mne from mne.minimum_norm import apply_inverse, make_inverse_operator import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" for i in range(len(ListSubj)): epochs_list = [] for c in range(len(condnames)): # which modality? if modality == 'MEG': megtag = True eegtag = False fname_fwd = (wdir + str(ListSubj[i]) + "/mne_python/run3_ico5_megonly_icacorr_-fwd.fif") elif modality == 'EEG': megtag = False eegtag = True fname_fwd = (wdir + str(ListSubj[i]) + "/mne_python/run3_ico5_eegonly_icacorr_-fwd.fif") elif modality == 'MEEG': megtag = True eegtag = True fname_fwd = (wdir + str(ListSubj[i]) + "/mne_python/run3_ico5_meeg_icacorr_-fwd.fif") # load noise covariance matrice fname_noisecov = (wdir + str(str(ListSubj[i])) + "/mne_python/COVMATS/" + modality + "_noisecov_icacorr_" + covmatsource + "_" + str(ListSubj[i]) + "-cov.fif") NOISE_COV1 = mne.read_cov(fname_noisecov) # load MEEG epochs, then pick fname_epochs = (wdir + str(ListSubj[i]) + "/mne_python/EPOCHS/MEEG_epochs_icacorr_" + str(condnames[c]) + '_' + str(ListSubj[i]) + "-epo.fif") epochs = mne.read_epochs(fname_epochs) epochs_list.append(epochs) mne.epochs.equalize_epoch_counts(epochs_list) for c in range(len(condnames)): epochs = [] epochs = epochs_list[c] # compute evoked picks = mne.pick_types(epochs.info, meg=megtag, eeg=eegtag, stim=False, eog=False) evokedcond1 = epochs.average(picks=picks) forward = mne.read_forward_solution(fname_fwd, surf_ori=True) inverse_operator1 = make_inverse_operator(evokedcond1.info, forward, NOISE_COV1, loose=0.2, depth=0.8) snr = 3.0 lambda2 = 1.0 / snr**2 # MEG source reconstruction stccond1 = apply_inverse(evokedcond1, inverse_operator1, lambda2, method=Method, pick_ori=None) stccond1.save(wdir + str(ListSubj[i]) + "/mne_python/STCS/" + modality + "_" + str(ListSubj[i]) + "_" + condnames[c] + "_pick_oriNone_" + Method + "_ico-5-fwd.fif") stccond1norm = apply_inverse(evokedcond1, inverse_operator1, lambda2, method=Method, pick_ori="normal") stccond1norm.save(wdir + str(ListSubj[i]) + "/mne_python/STCS/" + modality + "_" + str(ListSubj[i]) + "_" + condnames[c] + "_pick_orinormal_" + Method + "_ico-5-fwd.fif") # morphing to fsaverage stc_fsaverage_cond1 = mne.morph_data(str(ListSubj[i]), 'fsaverage', stccond1, smooth=20) stc_fsaverage_cond1.save(wdir + str(ListSubj[i]) + "/mne_python/STCS/" + modality + "_" + str(ListSubj[i]) + "_" + condnames[c] + "_pick_oriNone_" + Method + "_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm = mne.morph_data(str(ListSubj[i]), 'fsaverage', stccond1norm, smooth=20) stc_fsaverage_cond1norm.save(wdir + str(ListSubj[i]) + "/mne_python/STCS/" + modality + "_" + str(ListSubj[i]) + "_" + condnames[c] + "_pick_orinormal_" + Method + "_ico-5-fwd-fsaverage.fif")
print 'cov for subj=%s does not exist, creating file...' %subj cov = mne.compute_covariance(epochs_rej,tmin=None,tmax=0, method=['shrunk', 'diagonal_fixed', 'empirical']) cov.save('MEG/%s/%s-cov.fif' %(subj,subj)) print 'Done. File saved.' #---------------------Inverse operator-------------------------# print 'Getting inverse operator' if fixed == True: fwd = mne.convert_forward_solution(fwd, surf_ori=True) inv = mne.minimum_norm.make_inverse_operator(info, fwd, cov, depth=None, loose=None, fixed=fixed) #fixed=False: Ignoring dipole direction. lambda2 = 1.0 / 3.0 ** SNR #--------------------------STCs--------------------------------# print '%s: Creating STCs...'%subj os.makedirs('STC/%s' %subj) for ev in evoked: stc = mne.minimum_norm.apply_inverse(ev, inv, lambda2=lambda2, method='dSPM') #mophing stcs to the fsaverage: vertices_to = mne.grade_to_vertices('fsaverage', grade=4, subjects_dir=subjects_dir) #fsaverage's source space stc_morph = mne.morph_data(subject_from=subj, subject_to='fsaverage',stc_from=stc, grade=vertices_to,subjects_dir=subjects_dir) stc_morph.save('STC/%s/%s_%s_dSPM' %(subj,subj,ev.comment)) del stc, stc_morph print '>> DONE CREATING STCS FOR SUBJ=%s'%subj print '-----------------------------------------\n' #deleting variables del epochs_rej, evoked, info, trans, bem, src, fwd, cov, inv
# License: BSD (3-clause) print __doc__ import mne from mne.datasets import sample data_path = sample.data_path('..') subject_from = 'sample' subject_to = 'fsaverage' fname = data_path + '/MEG/sample/sample_audvis-meg' src_fname = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' # Read input stc file stc_from = mne.SourceEstimate(fname) # Morph stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1) stc_to.save('%s_audvis-meg' % subject_to) # View source activations import pylab as pl pl.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from') pl.plot(stc_to.times, stc_to.data.mean(axis=0), 'b', label='to') pl.xlabel('time (ms)') pl.ylabel('Mean Source amplitude') pl.legend() pl.show()
def SourceSingleTrial(combs,subject,modality,Method): combs = ('Qt_all','Qs_all') subject = 'jm100109' modality = 'MEG' Method = 'MNE' import mne from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator import os import pickle os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" for c,cond in enumerate(combs): # which modality? Import forward model accordingly if modality == 'MEG': mod = 'meg' fname_fwd = (wdir + subject + "/mne_python/run3_oct-6_megonly_-fwd.fif") elif modality == 'EEG': mod = 'eeg' fname_fwd = (wdir + subject + "/mne_python/run3_oct-6_eegonly_-fwd.fif") elif modality == 'MEEG': mod = 'meeg' fname_fwd = (wdir + subject + "/mne_python/run3_oct-6_meeg_-fwd.fif") # load noise covariance matrice, forward model, evoked and epochs #noisecov = mne.read_cov((wdir + subject + "/mne_python/COVMATS/" + # modality + "noisecov_" + + "_" + # subject + "-cov.fif")) forward = mne.read_forward_solution(fname_fwd ,surf_ori=True) epochs = mne.read_epochs(wdir + subject + "/mne_python/EPOCHS/MEEG_epochs_" + cond + '_' + subject + "-epo.fif") evoked = mne.read_evokeds((wdir + subject + "/mne_python/" + modality + "_" + cond + "_" + subject + "-ave.fif"), baseline = (-0.2, 0)) inverse_operator = make_inverse_operator(evoked.info, forward, noise_cov, loose=0.2, depth=0.8) write_inverse_operator(wdir + subject + "/mne_python/INVS/"+condnames+"_"+ mod +"_ico5-inv.fif",inverse_operator) ############################### # dSPM/ MNE/ sLORETA solution # ############################### if Method == 'dSPM' or Method == 'MNE' or Method == 'sLORETA': snr = 3.0 lambda2 = 1.0 / snr **2 #MEG source reconstruction #stc = apply_inverse_epochs(epochs, invop, lambda2,method = Method, # pick_ori= None, nave=evoked[0].nave) #stc[0].save(wdir + subject + "/mne_python/STCS/SgTr_" + modality + "_" + # subject + "_" + cond + "_pick_oriNone_" + Method + # "_ico-5-fwd.fif") stcnorm = apply_inverse_epochs(epochs, invop, lambda2,method = Method, pick_ori = "normal", nave=evoked[0].nave) savefolder = [] savefolder = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/' + subject + '/mne_python/STCS/SgTr_' + modality + "_" + subject + "_" + cond + "_pick_orinormal_" + Method ) if os.path.exists(savefolder) == False: os.mkdir(savefolder) [stcnorm[c].save(savefolder + '/trial' + str(c) + '.fif') for c in range(len(stcnorm))] # morphing to fsaverage #stc_fsaverage_ = mne.morph_data(subject, 'fsaverage', stc[0]) #stc_fsaverage_.save(wdir + subject + "/mne_python/STCS/SgTr_" + modality + # "_" + subject + "_" + cond + "_pick_oriNone_" + # Method + "_ico-5-fwd-fsaverage.fif") stc_fsaverage_norm = mne.morph_data(subject, 'fsaverage', stcnorm[0]) stc_fsaverage_norm.save(wdir + subject + "/mne_python/STCS/SgTr_" + modality + "_" + subject + "_" + cond + "_pick_orinormal_" + Method + "_ico-5-fwd-fsaverage.fif")
from mne.stats import spatio_temporal_cluster_test, summarize_clusters_stc from mne.datasets import sample print(__doc__) ############################################################################### # Set parameters data_path = sample.data_path() stc_fname = data_path + "/MEG/sample/sample_audvis-meg-lh.stc" subjects_dir = data_path + "/subjects" # Load stc to in common cortical space (fsaverage) stc = mne.read_source_estimate(stc_fname) stc.resample(50) stc = mne.morph_data("sample", "fsaverage", stc, grade=5, smooth=20, subjects_dir=subjects_dir) n_vertices_fsave, n_times = stc.data.shape tstep = stc.tstep n_subjects1, n_subjects2 = 7, 9 print("Simulating data for %d and %d subjects." % (n_subjects1, n_subjects2)) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X1 = np.random.randn(n_vertices_fsave, n_times, n_subjects1) * 10 X2 = np.random.randn(n_vertices_fsave, n_times, n_subjects2) * 10 X1[:, :, :] += stc.data[:, :, np.newaxis] # make the activity bigger for the second set of subjects X2[:, :, :] += 3 * stc.data[:, :, np.newaxis] # We want to compare the overall activity levels for each subject
def SourceReconstructionv4(condarray,condrenames,ListSubj,modality,Method,covmatsource): # # condarray = (('EtPre','EtPre'),('EtPast','EtFut')) # condrenames = ('NoProjT','ProjT') # ListSubj = ('jm100109',) # modality = 'MEG' # Method = 'dSPM' # covmatsource = 'EV' import mne from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.beamformer import lcmv import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" for c in range(len(condarray)): for i in range(len(ListSubj)): # which modality? if modality == 'MEG': megtag=True eegtag=False fname_fwd = (wdir+ListSubj[i]+"/mne_python/run3_ico5_megonly_icacorr_-fwd.fif") elif modality == 'EEG': megtag=False eegtag=True fname_fwd = (wdir+ListSubj[i]+"/mne_python/run3_ico5_eegonly_icacorr_-fwd.fif") elif modality == 'MEEG': megtag=True eegtag=True fname_fwd = (wdir+ListSubj[i]+"/mne_python/run3_ico5_meeg_icacorr_-fwd.fif") # load noise covariance matrice fname_noisecov = (wdir+ListSubj[i]+"/mne_python/COVMATS/"+modality+"_noisecov_icacorr_"+ covmatsource +"_"+ ListSubj[i] +"-cov.fif") NOISE_COV1 = mne.read_cov(fname_noisecov) # concatenate epochs if several conditions if len(condarray[c]) == 1: condnames = [] condnames = condarray[c][0] # load MEEG epochs, then pick fname_epochs = (wdir+ListSubj[i]+"/mne_python/EPOCHS/MEEG_epochs_icacorr_" +condnames+ '_' + ListSubj[i]+"-epo.fif") epochs = mne.read_epochs(fname_epochs) picks = mne.pick_types(epochs.info, meg=megtag, eeg=eegtag, stim=False , eog=False) # compute evoked evokedcond1 = epochs.average(picks = picks) forward = mne.read_forward_solution(fname_fwd ,surf_ori=True) inverse_operator1 = make_inverse_operator(evokedcond1.info, forward, NOISE_COV1, loose=0.2, depth=0.8) elif len(condarray[c]) > 1: epochlist = [] for ca in range(len(condarray[c])): condnames = [] condnames = condarray[c][ca] # load MEEG epochs, then pick fname_epochs = (wdir+ListSubj[i]+"/mne_python/EPOCHS/MEEG_epochs_icacorr_" +condnames+ '_' + ListSubj[i]+"-epo.fif") epochs = mne.read_epochs(fname_epochs) picks = mne.pick_types(epochs.info, meg=megtag, eeg=eegtag, stim=False , eog=False) epochlist.append(epochs) epochs = [] epochs = mne.epochs.concatenate_epochs(epochlist) # compute evoked evokedcond1 = epochs.average(picks = picks) forward = mne.read_forward_solution(fname_fwd ,surf_ori=True) inverse_operator1 = make_inverse_operator(evokedcond1.info, forward, NOISE_COV1, loose=0.2, depth=0.8) if Method == 'LCMV': fname_datacov = (wdir+ListSubj[i]+"/mne_python/COVMATS/"+modality+"datacov_"+condnames[c]+"_"+ListSubj[i]+"-cov.fif") DATA_COV1 = mne.read_cov(fname_datacov) ############################### # dSPM/ MNE/ sLORETA solution # ############################### if Method == 'dSPM' or Method == 'MNE' or Method == 'sLORETA': snr = 3.0 lambda2 = 1.0 / snr **2 # MEG source reconstruction stccond1 = apply_inverse(evokedcond1, inverse_operator1, lambda2,method = Method, pick_ori= None) stccond1.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd.fif") stccond1norm = apply_inverse(evokedcond1, inverse_operator1, lambda2,method =Method, pick_ori= "normal") stccond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd.fif") # morphing to fsaverage stc_fsaverage_cond1 = mne.morph_data(ListSubj[i], 'fsaverage', stccond1,smooth = 20) stc_fsaverage_cond1.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm,smooth = 20) stc_fsaverage_cond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd-fsaverage.fif") ################### # LCMV Beamformer # ################### elif Method == 'LCMV': # MEG source reconstruction stccond1 = lcmv(evokedcond1, forward, NOISE_COV1,DATA_COV1, reg=0.01,pick_ori= None) stccond1.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd.fif") stccond1norm = lcmv(evokedcond1, forward, NOISE_COV1,DATA_COV1, reg=0.01,pick_ori= "normal") stccond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd.fif") # morphing to fsaverage stc_fsaverage_cond1 = mne.morph_data(ListSubj[i], 'fsaverage', stccond1,smooth = 20) stc_fsaverage_cond1.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm,smooth = 20) stc_fsaverage_cond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd-fsaverage.fif")
# downsample to 1 Hz effective sampling resolution. Use this instead of raw.resample() to avoid further filtering of the signal data = data[:, np.arange(0,data.shape[1],int(raw.info['sfreq']))] print 'Multiplying data by beamformer weights...' # get the abs() of Hilbert transform (Hilbert envelope) sol = abs(np.dot(weights, data)) stc = mne.SourceEstimate(sol, [forward['src'][0]['vertno'], forward['src'][1]['vertno']], 0, 1, subject=subj) stc.save(dir_out + 'lcmv-%dto%d-'%(l_freq,h_freq) + subj) # morph all subjects subject_to = 'fsaverage' for l_freq, h_freq in bands: for subj in subjs: fname = dir_out + 'lcmv-%dto%d-'%(l_freq,h_freq) + subj stc_from = mne.read_source_estimate(fname) vertices_to = [np.arange(10242), np.arange(10242)] stc = mne.morph_data(subj, subject_to, stc_from, grade=vertices_to) stc.save(dir_out + 'morphed-lcmv-%dto%d-'%(l_freq,h_freq) + subj) # concatenate all subjects and apply ICA band_ICs = [] band_corr_ICs = [] for l_freq, h_freq in bands: print 'Concatenating sources in band %d to %d Hz'%(l_freq, h_freq) init_sources = 20500 init_time = 38500 # create huge array so we can add all the data and then resize it appropriately data = np.empty([init_sources, init_time]) data[:] = np.nan cnt = 0 for subj in subjs: fname = dir_out + 'morphed-lcmv-%dto%d-'%(l_freq,h_freq) + subj
inverse_operator1 = mne.minimum_norm.make_inverse_operator(evokedcond1.info, forward, NOISE_COV1, loose=0.2, depth=0.8) snr = 3.0 lambda2 = 1.0 / snr**2 stccond1 = mne.minimum_norm.apply_inverse(evokedcond1, inverse_operator1, lambda2, method='dSPM', pick_ori=None) stccond1.save('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/test.stc') stc_fsaverage_cond1 = mne.morph_data('rl130571', 'fsaverage', stccond1, smooth=20) stc_fsaverage_cond1.save( '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/test_morphed.stc') evoked[0].data.shape # test replace data epo = mne.read_epochs( '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/rl130571/' + 'mne_python/EPOCHS/MEEG_epochs_icacorr_RefFut_rl130571-epo.fif') picks = mne.pick_types(epo.info, meg=False, eeg=True, stim=False, eog=False) # compute evoked evokedcond1 = epo.average(picks=picks) evokedcond1.data = evoked[0].data evokedcond1.times = evoked[0].times
depth=0.8) snr = 3.0 lambda2 = 1.0 / snr**2 dSPM = True stccond1 = apply_inverse(evokedcond1, inverse_operator1, lambda2, 'dSPM', pick_normal=False) stccond1.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" + ListSubj[i] + "/mne_python/" + ListSubj[i] + "_EtDtq1G_QRT2_dPSMinverse_ico-5-fwd.fif") stc_fsaverage_cond1 = mne.morph_data(ListSubj[i], 'fsaverage', stccond1) stc_fsaverage_cond1.save( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" + ListSubj[i] + "/mne_python/" + ListSubj[i] + "_EtDtq1G_QRT2_dPSMinverse_ico-5-fwd-fsaverage.fif") stccond2 = apply_inverse(evokedcond2, inverse_operator2, lambda2, 'dSPM', pick_normal=False) stccond2.save("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" + ListSubj[i] + "/mne_python/" + ListSubj[i] + "_EtDtq2G_QRT2_dPSMinverse_ico-5-fwd.fif") stc_fsaverage_cond2 = mne.morph_data(ListSubj[i], 'fsaverage', stccond2)
def test_morph_data(): """Test morphing of data.""" tempdir = _TempDir() subject_from = 'sample' subject_to = 'fsaverage' stc_from = read_source_estimate(fname_smorph, subject='sample') stc_to = read_source_estimate(fname_fmorph) # make sure we can specify grade stc_from.crop(0.09, 0.1) # for faster computation stc_to.crop(0.09, 0.1) # for faster computation assert_array_equal(stc_to.time_as_index([0.09, 0.1], use_rounding=True), [0, len(stc_to.times) - 1]) pytest.raises(ValueError, stc_from.morph, subject_to, grade=3, smooth=-1, subjects_dir=subjects_dir) stc_to1 = stc_from.morph(subject_to, grade=3, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) stc_to1.save(op.join(tempdir, '%s_audvis-meg' % subject_to)) # Morphing to a density that is too high should raise an informative error # (here we need to push to grade=6, but for some subjects even grade=5 # will break) pytest.raises(ValueError, stc_to1.morph, subject_from, grade=6, subjects_dir=subjects_dir) # make sure we can specify vertices vertices_to = grade_to_vertices(subject_to, grade=3, subjects_dir=subjects_dir) stc_to2 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) # make sure we can use different buffer_size stc_to3 = morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=12, buffer_size=3, subjects_dir=subjects_dir) # make sure we get a warning about # of steps with pytest.warns(RuntimeWarning, match='consider increasing'): morph_data(subject_from, subject_to, stc_from, grade=vertices_to, smooth=1, buffer_size=3, subjects_dir=subjects_dir) assert_array_almost_equal(stc_to.data, stc_to1.data, 5) assert_array_almost_equal(stc_to1.data, stc_to2.data) assert_array_almost_equal(stc_to1.data, stc_to3.data) # make sure precomputed morph matrices work morph_mat = compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, smooth=12, subjects_dir=subjects_dir) stc_to3 = stc_from.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_to1.data, stc_to3.data) pytest.raises(ValueError, stc_from.morph_precomputed, subject_to, vertices_to, 'foo') pytest.raises(ValueError, stc_from.morph_precomputed, subject_to, [vertices_to[0]], morph_mat) pytest.raises(ValueError, stc_from.morph_precomputed, subject_to, [vertices_to[0][:-1], vertices_to[1]], morph_mat) pytest.raises(ValueError, stc_from.morph_precomputed, subject_to, vertices_to, morph_mat, subject_from='foo') # steps warning with pytest.warns(RuntimeWarning, match='steps'): compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, smooth=1, subjects_dir=subjects_dir) mean_from = stc_from.data.mean(axis=0) mean_to = stc_to1.data.mean(axis=0) assert (np.corrcoef(mean_to, mean_from).min() > 0.999) # make sure we can fill by morphing stc_to5 = morph_data(subject_from, subject_to, stc_from, grade=None, smooth=12, buffer_size=3, subjects_dir=subjects_dir) assert (stc_to5.data.shape[0] == 163842 + 163842) # Morph sparse data # Make a sparse stc stc_from.vertices[0] = stc_from.vertices[0][[100, 500]] stc_from.vertices[1] = stc_from.vertices[1][[200]] stc_from._data = stc_from._data[:3] pytest.raises(RuntimeError, stc_from.morph, subject_to, sparse=True, grade=5, subjects_dir=subjects_dir) stc_to_sparse = stc_from.morph(subject_to, grade=None, sparse=True, subjects_dir=subjects_dir) assert_array_almost_equal(np.sort(stc_from.data.sum(axis=1)), np.sort(stc_to_sparse.data.sum(axis=1))) assert_equal(len(stc_from.rh_vertno), len(stc_to_sparse.rh_vertno)) assert_equal(len(stc_from.lh_vertno), len(stc_to_sparse.lh_vertno)) assert_equal(stc_to_sparse.subject, subject_to) assert_equal(stc_from.tmin, stc_from.tmin) assert_equal(stc_from.tstep, stc_from.tstep) stc_from.vertices[0] = np.array([], dtype=np.int64) stc_from._data = stc_from._data[:1] stc_to_sparse = stc_from.morph(subject_to, grade=None, sparse=True, subjects_dir=subjects_dir) assert_array_almost_equal(np.sort(stc_from.data.sum(axis=1)), np.sort(stc_to_sparse.data.sum(axis=1))) assert_equal(len(stc_from.rh_vertno), len(stc_to_sparse.rh_vertno)) assert_equal(len(stc_from.lh_vertno), len(stc_to_sparse.lh_vertno)) assert_equal(stc_to_sparse.subject, subject_to) assert_equal(stc_from.tmin, stc_from.tmin) assert_equal(stc_from.tstep, stc_from.tstep) # Morph vector data stc_vec = _real_vec_stc() # Ignore warnings about number of steps stc_vec_to1 = stc_vec.morph(subject_to, grade=3, smooth=12, buffer_size=1000, subjects_dir=subjects_dir) stc_vec_to2 = stc_vec.morph_precomputed(subject_to, vertices_to, morph_mat) assert_array_almost_equal(stc_vec_to1.data, stc_vec_to2.data)
def SourceReg(ListSubj,modality,Method): #pre-defined conditions covmatsource = 'EV' condarray = ('dist1t_evt','dist2t_evt','dist3t_evt','dist4t_evt','dist5t_evt','dist6t_evt', 'dist7t_evt','dist8t_evt','dist9t_evt','dist10t_evt','dist11t_evt','dist12t_evt', 'dist13t_evt','dist14t_evt','dist15t_evt','dist16t_evt','dist17t_evt','dist18t_evt', 'dist19t_evt','dist20t_evt','dist21t_evt','dist22t_evt','dist23t_evt','dist24t_evt') # condarray = ('dist1s_evs','dist2s_evs','dist3s_evs','dist4s_evs','dist5s_evs','dist6s_evs', # 'dist7s_evs','dist8s_evs','dist9s_evs','dist10s_evs','dist11s_evs','dist12s_evs', # 'dist13s_evs','dist14s_evs','dist15s_evs','dist16s_evs','dist17s_evs','dist18s_evs', # 'dist19s_evs','dist20s_evs','dist21s_evs','dist22s_evs','dist23s_evs','dist24s_evs') tag = 't_evt' Name = 'TEVT' import mne import numpy as np from mne.minimum_norm import apply_inverse, make_inverse_operator import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" # dist = [1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27] dist = [5, 10, 15, 20, 25, 30, 35, 41, 46, 51, 56, 61, 66, 71, 77, 82, 87, 92, 97, 102, 107, 113, 118, 123, 128] BETAS = [] RegEpochList = [] for s,subj in enumerate(ListSubj): # which modality? if modality == 'MEG': megtag=True eegtag=False fname_fwd = (wdir+subj+"/mne_python/run3_ico5_megonly_icacorr_-fwd.fif") elif modality == 'EEG': megtag=False eegtag=True fname_fwd = (wdir+subj+"/mne_python/run3_ico5_eegonly_icacorr_-fwd.fif") elif modality == 'MEEG': megtag=True eegtag=True fname_fwd = (wdir+subj+"/mne_python/run3_ico5_meeg_icacorr_-fwd.fif") DistPerTrial = [] # initiate data size fname_epochs0 = (wdir + subj + '/mne_python/EPOCHS/MEEG_epochs_icacorr_dist1'+tag+'_'+subj+'-epo.fif') epochs0 = mne.read_epochs(fname_epochs0) epochs0.pick_types(meg=megtag, eeg=eegtag) if ListSubj[s] == 'sd130343': epochs0.drop_channels(('EEG064',)) nchans = epochs0.get_data().shape[1] ntime = epochs0.get_data().shape[2] DATAMAT = np.zeros((0,nchans,ntime)) for c,cond in enumerate(condarray): fname_epochs = (wdir+ListSubj[s]+"/mne_python/EPOCHS/MEEG_epochs_icacorr_" +cond+ '_' + subj+"-epo.fif") epochs = mne.read_epochs(fname_epochs) epochs.pick_types(meg=megtag, eeg=eegtag) if ListSubj[s] == 'sd130343': epochs.drop_channels(('EEG064',)) ntrials = epochs.get_data().shape[0] DistPerTrial = np.hstack((DistPerTrial,(np.ones(ntrials))*dist[c])) DATAMAT= np.concatenate((DATAMAT,epochs.get_data()),axis = 0) Predictor = np.transpose(np.vstack([DistPerTrial,np.ones(len(DistPerTrial))])) BETAS.append(np.zeros([nchans,ntime])) for c in range(nchans): for t in range(ntime): a,b = np.linalg.lstsq(Predictor,DATAMAT[:,c,t])[0] # resp = a*pred + b BETAS[s][c,t] = a #use a dummy epochs to store regression betas fname_epochsdummy = (wdir + subj + '/mne_python/EPOCHS/MEEG_epochs_icacorr_dist1'+tag+'_'+subj+'-epo.fif') epochsdummy = mne.read_epochs(fname_epochsdummy) epochsdummy.pick_types(meg=megtag, eeg=eegtag) if ListSubj[s] == 'sd130343': epochsdummy.drop_channels(('EEG064',)) fakeavg = epochsdummy.average() fakeavg.data = BETAS[s] RegEpochList.append(fakeavg) for s in range(len(ListSubj)): # load noise covariance matrice fname_noisecov = (wdir+subj+"/mne_python/COVMATS/"+modality+"_noisecov_icacorr_"+ covmatsource +"_"+ subj +"-cov.fif") NOISE_COV1 = mne.read_cov(fname_noisecov) # concatenate epochs if several conditions forward = mne.read_forward_solution(fname_fwd ,surf_ori=True) inverse_operator1 = make_inverse_operator(RegEpochList[s].info, forward, NOISE_COV1, loose=0.2, depth=0.8) snr = 3.0 lambda2 = 1.0 / snr **2 # MEG source reconstruction stccond1 = apply_inverse(RegEpochList[s], inverse_operator1, lambda2,method = Method, pick_ori= None) stccond1.save(wdir+subj+"/mne_python/STCS/"+modality+"_"+subj+"_dist"+Name+"_pick_oriNone_"+Method+"_ico-5-fwd.fif") stccond1norm = apply_inverse(RegEpochList[s], inverse_operator1, lambda2,method =Method, pick_ori= "normal") stccond1norm.save(wdir+subj+"/mne_python/STCS/"+modality+"_"+subj+"_dist"+Name+"_pick_orinormal_"+Method+"_ico-5-fwd.fif") # morphing to fsaverage stc_fsaverage_cond1 = mne.morph_data(subj, 'fsaverage', stccond1,smooth = 20) stc_fsaverage_cond1.save(wdir+subj+"/mne_python/STCS/"+modality+"_"+subj+"_dist"+Name+"_pick_oriNone_"+Method+"_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm = mne.morph_data(subj, 'fsaverage', stccond1norm,smooth = 20) stc_fsaverage_cond1norm.save(wdir+subj+"/mne_python/STCS/"+modality+"_"+subj+"_dist"+Name+"_pick_orinormal_"+Method+"_ico-5-fwd-fsaverage.fif")
raw.save(fname[:-4] + '_beta.fif') # extract epochs picks = mne.fiff.pick_types(raw.info, meg=True, eeg=True, eog=True, exclude=raw.info['bads']) events = mne.find_events(raw, stim_channel='STI 014') epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=0.5, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) # compute evoked response and noise covariance evoked = epochs.average() cov = mne.compute_covariance(epochs, tmax=0) # Plot evoked from mne.viz import plot_evoked plot_evoked(evoked) # Inverse modeling # compute inverse operator fwd_fname = 'sample_audvis-meg-eeg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fwd_fname, surf_ori=True) inv = mne.minimum_norm.make_inverse_operator(raw.info, fwd, cov, loose=0.2) # compute inverse solution stc = mne.minimum_norm.apply_inverse(evoked, inv, lambda2=1 / 3.0 ** 2, method='dSPM') # morph it to average brain for group study stc_avg = mne.morph_data('sample', 'fsaverage', stc, 5, smooth=5)
def DICS_inverse(fn_epo, event_id=1,event='LLst', ctmin=0.05, ctmax=0.25, fmin=4, fmax=8, min_subject='fsaverage'): """ Inverse evokes into source space using DICS method. ---------- fn_epo : epochs of raw data. event_id: event id related with epochs. ctmin: the min time for computing CSD ctmax: the max time for computing CSD fmin: min value of the interest frequency band fmax: max value of the interest frequency band min_subject: the subject for the common brain space. save_forward: Whether save the forward solution or not. """ from mne import Epochs, pick_types from mne.io import Raw from mne.event import make_fixed_length_events fnlist = get_files_from_list(fn_epo) # loop across all filenames for fname in fnlist: meg_path = os.path.split(fname)[0] name = os.path.basename(fname) stc_name = name[:name.rfind('-epo.fif')] subject = name.split('_')[0] subject_path = subjects_dir + '/%s' %subject min_dir = subjects_dir + '/%s' %min_subject fn_trans = meg_path + '/%s-trans.fif' % subject fn_src = subject_path + '/bem/%s-ico-5-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject # Make sure the target path is exist stc_path = min_dir + '/DICS_ROIs/%s' % subject set_directory(stc_path) # Read the MNI source space epochs = mne.read_epochs(fname) tmin = epochs.times.min() tmax = epochs.times.max() fn_empty = meg_path + '/%s_empty,nr-raw.fif' % subject raw_noise = Raw(fn_empty, preload=True) epochs.info['bads'] = raw_noise.info['bads'] picks_noise = pick_types(raw_noise.info, meg='mag', exclude='bads') events_noise = make_fixed_length_events(raw_noise, event_id, duration=1.) epochs_noise = Epochs(raw_noise, events_noise, event_id, tmin, tmax, proj=True, picks=picks_noise, baseline=None, preload=True, reject=None) # Make sure the number of noise epochs is the same as data epochs epochs_noise = epochs_noise[:len(epochs.events)] evoked = epochs.average() forward = mne.make_forward_solution(epochs.info, trans=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) forward = mne.convert_forward_solution(forward, surf_ori=True) from mne.time_frequency import compute_epochs_csd from mne.beamformer import dics data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=ctmin, tmax=ctmax, fmin=fmin, fmax=fmax) noise_csd = compute_epochs_csd(epochs_noise, mode='multitaper', tmin=ctmin, tmax=ctmax, fmin=fmin, fmax=fmax) stc = dics(evoked, forward, noise_csd, data_csd) from mne import morph_data stc_morph = morph_data(subject, min_subject, stc, grade=5, smooth=5) stc_morph.save(stc_path + '/%s_%d_%d' % (event, fmin, fmax), ftype='stc')
def apply_inverse(fnepo, method='dSPM', event='LLst', min_subject='fsaverage', STC_US='ROI', snr=5.0): ''' Parameter --------- fnepo: string or list The epochs file with ECG, EOG and environmental noise free. method: inverse method, 'MNE' or 'dSPM' event: string The event name related with epochs. min_subject: string The subject name as the common brain. STC_US: string The using of the inversion for further analysis. 'ROI' stands for ROIs definition, 'CAU' stands for causality analysis. snr: signal to noise ratio for inverse solution. ''' #Get the default subjects_dir from mne.minimum_norm import (apply_inverse, apply_inverse_epochs) subjects_dir = os.environ['SUBJECTS_DIR'] fnlist = get_files_from_list(fnepo) # loop across all filenames for fname in fnlist: fn_path = os.path.split(fname)[0] name = os.path.basename(fname) stc_name = name[:name.rfind('-epo.fif')] subject = name.split('_')[0] subject_path = subjects_dir + '/%s' %subject min_dir = subjects_dir + '/%s' %min_subject fn_trans = fn_path + '/%s-trans.fif' % subject fn_cov = fn_path + '/%s_empty,nr-cov.fif' % subject fn_src = subject_path + '/bem/%s-ico-4-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject snr = snr lambda2 = 1.0 / snr ** 2 #noise_cov = mne.read_cov(fn_cov) epochs = mne.read_epochs(fname) noise_cov = mne.read_cov(fn_cov) if STC_US == 'ROI': # this path used for ROI definition stc_path = min_dir + '/%s_ROIs/%s' %(method,subject) #fn_cov = meg_path + '/%s_empty,fibp1-45,nr-cov.fif' % subject evoked = epochs.average() set_directory(stc_path) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, proj=True) fwd_ev = mne.make_forward_solution(evoked.info, trans=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) fwd_ev = mne.convert_forward_solution(fwd_ev, surf_ori=True) forward_meg_ev = mne.pick_types_forward(fwd_ev, meg=True, eeg=False) inverse_operator_ev = mne.minimum_norm.make_inverse_operator( evoked.info, forward_meg_ev, noise_cov, loose=0.2, depth=0.8) # Compute inverse solution stc = apply_inverse(evoked, inverse_operator_ev, lambda2, method, pick_ori=None) # Morph STC subject_id = min_subject stc_morph = mne.morph_data(subject, subject_id, stc, grade=5, smooth=5) stc_morph.save(stc_path + '/%s' % (stc_name), ftype='stc') elif STC_US == 'CAU': stcs_path = min_dir + '/stcs/%s/%s/' % (subject,event) reset_directory(stcs_path) noise_cov = mne.cov.regularize(noise_cov, epochs.info, mag=0.05, grad=0.05, proj=True) fwd = mne.make_forward_solution(epochs.info, trans=fn_trans, src=fn_src, bem=fn_bem, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) fwd = mne.convert_forward_solution(fwd, surf_ori=True) forward_meg = mne.pick_types_forward(fwd, meg=True, eeg=False) inverse_operator = mne.minimum_norm.make_inverse_operator( epochs.info, forward_meg, noise_cov, loose=0.2, depth=0.8) # Compute inverse solution stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method=method, pick_ori='normal') s = 0 while s < len(stcs): stc_morph = mne.morph_data( subject, min_subject, stcs[s], grade=5, smooth=5) stc_morph.save(stcs_path + '/trial%s_fsaverage' % (subject, str(s)), ftype='stc') s = s + 1
def SourceReconstruction(condnames, ListSubj): #ipython --pylab import mne from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.beamformer import lcmv import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri' os.environ['MNE_ROOT'] = '/neurospin/local/mne' wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" #wdir = "/media/bgauthie/Seagate Backup Plus Drive/TMP_MEG_SOURCE/MEG/" for i in range(len(ListSubj)): # open a text logfile logfile = open(wdir + ListSubj[i] + "/mne_python/logfile_preproc.txt", "w") # load covariance matrices fname_fwd_eeg = (wdir + ListSubj[i] + "/mne_python/run3_ico-5_eegonly_-fwd.fif") fname_fwd_meg = (wdir + ListSubj[i] + "/mne_python/run3_ico-5_megonly_-fwd.fif") fname_fwd_meeg = (wdir + ListSubj[i] + "/mne_python/run3_ico-5_meeg_-fwd.fif") fname_noisecov1 = (wdir + ListSubj[i] + "/mne_python/MEGnoisecov_" + condnames + "_" + ListSubj[i] + "-cov.fif") fname_noisecov2 = (wdir + ListSubj[i] + "/mne_python/EEGnoisecov_" + condnames + "_" + ListSubj[i] + "-cov.fif") fname_noisecov3 = (wdir + ListSubj[i] + "/mne_python/MEEGnoisecov_" + condnames + "_" + ListSubj[i] + "-cov.fif") fname_datacov1 = (wdir + ListSubj[i] + "/mne_python/MEGdatacov_" + condnames + "_" + ListSubj[i] + "-cov.fif") fname_datacov2 = (wdir + ListSubj[i] + "/mne_python/EEGdatacov_" + condnames + "_" + ListSubj[i] + "-cov.fif") fname_datacov3 = (wdir + ListSubj[i] + "/mne_python/MEEGdatacov_" + condnames + "_" + ListSubj[i] + "-cov.fif") forward_meg = mne.read_forward_solution(fname_fwd_meg, surf_ori=True) forward_eeg = mne.read_forward_solution(fname_fwd_eeg, surf_ori=True) forward_meeg = mne.read_forward_solution(fname_fwd_meeg, surf_ori=True) fname_ave_meg = (wdir + ListSubj[i] + "/mne_python/MEG_" + condnames + "_" + ListSubj[i] + "-ave.fif") fname_ave_eeg = (wdir + ListSubj[i] + "/mne_python/EEG_" + condnames + "_" + ListSubj[i] + "-ave.fif") fname_ave_meeg = (wdir + ListSubj[i] + "/mne_python/MEEG_" + condnames + "_" + ListSubj[i] + "-ave.fif") NOISE_COV1_meg = mne.read_cov(fname_noisecov1) NOISE_COV1_eeg = mne.read_cov(fname_noisecov2) NOISE_COV1_meeg = mne.read_cov(fname_noisecov3) DATA_COV1_meg = mne.read_cov(fname_datacov1) DATA_COV1_eeg = mne.read_cov(fname_datacov2) DATA_COV1_meeg = mne.read_cov(fname_datacov3) # load evoked evokedcond1_meg = mne.read_evokeds(fname_ave_meg, condition=0, baseline=(-0.2, 0)) evokedcond1_eeg = mne.read_evokeds(fname_ave_eeg, condition=0, baseline=(-0.2, 0)) evokedcond1_meeg = mne.read_evokeds(fname_ave_meeg, condition=0, baseline=(-0.2, 0)) inverse_operator1_meg = make_inverse_operator(evokedcond1_meg.info, forward_meg, NOISE_COV1_meg, loose=0.2, depth=0.8) inverse_operator1_eeg = make_inverse_operator(evokedcond1_eeg.info, forward_eeg, NOISE_COV1_eeg, loose=0.2, depth=0.8) inverse_operator1_meeg = make_inverse_operator(evokedcond1_meeg.info, forward_meeg, NOISE_COV1_meeg, loose=0.2, depth=0.8) ################################################################################################################################# # dSPM solution # ################################################################################################################################# snr = 3.0 lambda2 = 1.0 / snr**2 # MEG source reconstruction stccond1_meg = apply_inverse(evokedcond1_meg, inverse_operator1_meg, lambda2, method='dSPM', pick_ori=None) stccond1_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd.fif") stccond1norm_meg = apply_inverse(evokedcond1_meg, inverse_operator1_meg, lambda2, method='dSPM', pick_ori="normal") stccond1norm_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd.fif") stc_fsaverage_cond1_meg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_meg) stc_fsaverage_cond1_meg.save( wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm_meg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm_meg) stc_fsaverage_cond1norm_meg.save( wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd-fsaverage.fif") logfile.write("" "\n") logfile.write("processing subject " + ListSubj[i] + "\n") logfile.write("MEG dSPM source reconstruction: orinone & orinormal " + "\n") logfile.write("Morphing on fsaverage " + "\n") logfile.write("" "\n") # EEG source reconstruction stccond1_eeg = apply_inverse(evokedcond1_eeg, inverse_operator1_eeg, lambda2, method='dSPM', pick_ori=None) stccond1_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd.fif") stccond1norm_eeg = apply_inverse(evokedcond1_eeg, inverse_operator1_eeg, lambda2, method='dSPM', pick_ori="normal") stccond1norm_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd.fif") stc_fsaverage_cond1_eeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_eeg) stc_fsaverage_cond1_eeg.save( wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1bis_eeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm_eeg) stc_fsaverage_cond1bis_eeg.save( wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd-fsaverage.fif") logfile.write("" "\n") logfile.write("processing subject " + ListSubj[i] + "\n") logfile.write("EEG dSPM source reconstruction: orinone & orinormal " + "\n") logfile.write("Morphing on fsaverage " + "\n") logfile.write("" "\n") # MEEG source reconstruction stccond1_meeg = apply_inverse(evokedcond1_meeg, inverse_operator1_meeg, lambda2, method='dSPM', pick_ori=None) stccond1_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd.fif") stccond1norm_meeg = apply_inverse(evokedcond1_meeg, inverse_operator1_meeg, lambda2, method='dSPM', pick_ori="normal") stccond1norm_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd.fif") stc_fsaverage_cond1_meeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_meeg) stc_fsaverage_cond1_meeg.save( wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1bis_meeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm_meeg) stc_fsaverage_cond1bis_meeg.save( wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd-fsaverage.fif") logfile.write("" "\n") logfile.write("processing subject " + ListSubj[i] + "\n") logfile.write("MEEG dSPM source reconstruction: orinone & orinormal " + "\n") logfile.write("Morphing on fsaverage " + "\n") logfile.write("" "\n") ################################################################################################################################# # LCMV Beamformer # ################################################################################################################################# # MEG source reconstruction stccond1_meg = lcmv(evokedcond1_meg, forward_meg, NOISE_COV1_meg, DATA_COV1_meg, reg=0.01, pick_ori=None) stccond1_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_LCMV_ico-5-fwd.fif") stccond1norm_meg = lcmv(evokedcond1_meg, forward_meg, NOISE_COV1_meg, DATA_COV1_meg, reg=0.01, pick_ori="normal") stccond1norm_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_LCMV_ico-5-fwd.fif") stc_fsaverage_cond1_meg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_meg) stc_fsaverage_cond1_meg.save( wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_LCMV_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm_meg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm_meg) stc_fsaverage_cond1norm_meg.save( wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_LCMV_ico-5-fwd-fsaverage.fif") logfile.write("" "\n") logfile.write("processing subject " + ListSubj[i] + "\n") logfile.write("MEG LCMV source reconstruction: orinone & orinormal " + "\n") logfile.write("Morphing on fsaverage " + "\n") logfile.write("" "\n") # EEG source reconstruction stccond1_eeg = lcmv(evokedcond1_eeg, forward_eeg, NOISE_COV1_eeg, DATA_COV1_eeg, reg=0.01, pick_ori=None) stccond1_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_LCMV_ico-5-fwd.fif") stccond1norm_eeg = lcmv(evokedcond1_eeg, forward_eeg, NOISE_COV1_eeg, DATA_COV1_eeg, reg=0.01, pick_ori="normal") stccond1norm_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_LCMV_ico-5-fwd.fif") stc_fsaverage_cond1_eeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_eeg) stc_fsaverage_cond1_eeg.save( wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_LCMV_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm_eeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm_eeg) stc_fsaverage_cond1norm_eeg.save( wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_LCMV_ico-5-fwd-fsaverage.fif") logfile.write("" "\n") logfile.write("processing subject " + ListSubj[i] + "\n") logfile.write("EEG dSPM source reconstruction: orinone & orinormal " + "\n") logfile.write("Morphing on fsaverage " + "\n") logfile.write("" "\n") # MEEG source reconstruction stccond1_meeg = lcmv(evokedcond1_meeg, forward_meeg, NOISE_COV1_meeg, DATA_COV1_meeg, reg=0.01, pick_ori=None) stccond1_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_LCMV_ico-5-fwd.fif") stccond1norm_meeg = lcmv(evokedcond1_meeg, forward_meeg, NOISE_COV1_meeg, DATA_COV1_meeg, reg=0.01, pick_ori="normal") stccond1norm_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_LCMV_ico-5-fwd.fif") stc_fsaverage_cond1_meeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1_meeg) stc_fsaverage_cond1_meeg.save( wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_oriNone_LCMV_ico-5-fwd-fsaverage.fif") stc_fsaverage_cond1norm_meeg = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm_meeg) stc_fsaverage_cond1norm_meeg.save( wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" + condnames + "_pick_orinormal_LCMV_ico-5-fwd-fsaverage.fif") logfile.write("" "\n") logfile.write("processing subject " + ListSubj[i] + "\n") logfile.write("MEEG dSPM source reconstruction: orinone & orinormal " + "\n") logfile.write("Morphing on fsaverage " + "\n") logfile.write("" "\n") logfile.close()
import mne from mne import spatial_tris_connectivity, grade_to_tris from mne.stats import spatio_temporal_cluster_test, summarize_clusters_stc from mne.datasets import sample ############################################################################### # Set parameters data_path = sample.data_path() stc_fname = data_path + '/MEG/sample/sample_audvis-meg-lh.stc' subjects_dir = data_path + '/subjects' # Load stc to in common cortical space (fsaverage) stc = mne.read_source_estimate(stc_fname) stc.resample(50) stc = mne.morph_data('sample', 'fsaverage', stc, grade=5, smooth=20, subjects_dir=subjects_dir) n_vertices_fsave, n_times = stc.data.shape tstep = stc.tstep n_subjects1, n_subjects2 = 7, 9 print('Simulating data for %d and %d subjects.' % (n_subjects1, n_subjects2)) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X1 = np.random.randn(n_vertices_fsave, n_times, n_subjects1) * 10 X2 = np.random.randn(n_vertices_fsave, n_times, n_subjects2) * 10 X1[:, :, :] += stc.data[:, :, np.newaxis] # make the activity bigger for the second set of subjects X2[:, :, :] += 3 * stc.data[:, :, np.newaxis] # We want to compare the overall activity levels for each subject
label_fname = '/home/qdong/freesurfer/subjects/fsaverage/label/lh.RefROI1.label' label = mne.read_label(label_fname) label.values.fill(1.0) label_morph = label.morph(subject_from='fsaverage', subject_to=subject, smooth=5, n_jobs=1, copy=True) # First, we find the most active vertex in the left auditory cortex, which # we will later use as seed for the connectivity computation snr = 3.0 method = "dSPM" lambda2 = 1.0 / snr ** 2 evoked = epochs.average() stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori="normal") #For defining REF_ROI stc_morph = mne.morph_data(subject, 'fsaverage', stc, 5, smooth=5) stc_morph.save(subject_path+'/Ref_fsaverage'+subject+'_' +trigger, ftype='stc') # Restrict the source estimate to the label in the left auditory cortex #(reference ROI) stc_label = stc.in_label(label_morph) # Find number and index of vertex with most power src_pow = np.sum(stc_label.data ** 2, axis=1) seed_vertno = stc_label.vertno[0][np.argmax(src_pow)] seed_idx = np.searchsorted(stc.vertno[0], seed_vertno) # index in original stc # Generate index parameter for seed-based connectivity analysis n_sources = stc.data.shape[0] indices = seed_target_indices([seed_idx], np.arange(n_sources)) # Compute inverse solution and for each epoch. By using "return_generator=True"
subject_from = 'sample' subject_to = 'fsaverage' fname = data_path + '/MEG/sample/sample_audvis-meg' src_fname = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' # Read input stc file stc_from = mne.read_source_estimate(fname) # Morph using one method (supplying the vertices in fsaverage's source # space makes it faster). Note that for any generic subject, you could do: # vertices_to = mne.grade_to_vertices(subject_to, grade=5) # But fsaverage's source space was set up so we can just do this: vertices_to = [np.arange(10242), np.arange(10242)] stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1, grade=vertices_to) stc_to.save('%s_audvis-meg' % subject_to) # Morph using another method -- useful if you're going to do a lot of the # same inter-subject morphing operations; you could save and load morph_mat morph_mat = mne.compute_morph_matrix(subject_from, subject_to, stc_from.vertno, vertices_to) stc_to_2 = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat) stc_to_2.save('%s_audvis-meg_2' % subject_to) # View source activations import matplotlib.pyplot as plt plt.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from')
forward_meg = mne.fiff.pick_types_forward(fwd, meg=True, eeg=False) inverse_operator_meg = mne.minimum_norm.make_inverse_operator(evoked.info, forward_meg, noise_cov, loose=0.2, depth=0.8) mne.minimum_norm.write_inverse_operator( subject_path + '/%s_%s-inv.fif' % (subject, trigger), inverse_operator_meg) #Write inverse operator ################################################################################################## # make sourcetime course and morph it to the common brain space # ################################################################################################## stc = mne.minimum_norm.apply_inverse(evoked, inverse_operator_meg, lambda2, "dSPM") stc_avg = mne.morph_data(subject, 'fsaverage', stc, 5, smooth=5) #stc_avg.plot() stc_avg.save(subject_path + '/fsaverage_' + subject + trigger, ftype='stc') brain = stc_avg.plot(surface='inflated', hemi='lh', subjects_dir=subjects_dir) brain.scale_data_colormap(fmin=8, fmid=12, fmax=15, transparent=True) brain.show_view('lateral') ### #### use peak getter to move vizualization to the time point of the peak vertno_max, time_idx = stc_avg.get_peak(hemi='lh', time_as_index=True) brain.set_data_time_index(time_idx) ### #### draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh',
import mne import matplotlib.pyplot as plt from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' subjects_dir = data_path + '/subjects' os.environ['SUBJECTS_DIR'] = subjects_dir stc_fname = data_path + '/MEG/sample/sample_audvis-meg' stc = mne.read_source_estimate(stc_fname) new_stc = mne.morph_data('sample', 'fsaverage', stc, grade=5, subjects_dir=subjects_dir, n_jobs=2) subject = 'fsaverage' # Plot brain in 3D with PySurfer if available brain = new_stc.plot(subject, hemi='lh', subjects_dir=subjects_dir) brain.show_view('lateral') # use peak getter to move vizualization to the time point of the peak vertno_max, time_idx = new_stc.get_peak(hemi='lh', time_as_index=True) brain.set_data_time_index(time_idx) # draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue', scale_factor=0.6, map_surface='white')