def run_inverse(subject_id): subject = "sub%03d" % subject_id print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) fname_ave = op.join(data_path, '%s-ave.fif' % subject) fname_cov = op.join(data_path, '%s-cov.fif' % subject) fname_fwd = op.join(data_path, '%s-meg-%s-fwd.fif' % (subject, spacing)) fname_inv = op.join(data_path, '%s-meg-%s-inv.fif' % (subject, spacing)) evokeds = mne.read_evokeds(fname_ave, condition=[0, 1, 2, 3, 4, 5]) cov = mne.read_cov(fname_cov) # cov = mne.cov.regularize(cov, evokeds[0].info, # mag=0.05, grad=0.05, eeg=0.1, proj=True) forward = mne.read_forward_solution(fname_fwd, surf_ori=True) # forward = mne.pick_types_forward(forward, meg=True, eeg=False) # make an M/EEG, MEG-only, and EEG-only inverse operators info = evokeds[0].info inverse_operator = make_inverse_operator(info, forward, cov, loose=0.2, depth=0.8) write_inverse_operator(fname_inv, inverse_operator) # Compute inverse solution snr = 3.0 lambda2 = 1.0 / snr ** 2 for evoked in evokeds: stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM", pick_ori=None) stc.save(op.join(data_path, 'mne_dSPM_inverse-%s' % evoked.comment))
def INVERSE(wdir, Subject, epoch_info, evokeds): # import parameters from configuration file from configuration import ( lambda2, method ) # compute noise covariance from empty room data emptyroom_raw = mne.io.Raw(wdir + '/data/maxfilter/' + Subject + '/'+ Subject +'_empty_sss.fif') noise_cov = mne.compute_raw_data_covariance(emptyroom_raw) # compute dSPM solution fname_fwd = wdir + '/data/forward/' + Subject + '/' + Subject + '_phase1_trans_sss_filt140_raw-ico5-fwd.fif' forward = mne.read_forward_solution(fname_fwd, surf_ori=True) # create inverse operator inverse_operator = make_inverse_operator(epoch_info, forward, noise_cov, loose=0.4, depth=0.8) # Compute inverse solution stcs = [] for evoked in evokeds: stcs.append(apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori = None)) # save a covariance picture for visual inspection mne.viz.plot_cov(noise_cov, epoch_info, colorbar=True, proj=True,show_svd=False,show=False) plt.savefig(wdir + "/plots/" + Subject + "_covmat") plt.close() return stcs
def _create_stcs(params): subject, events_id, epochs, evoked, inv, inverse_method, baseline, apply_for_epochs, apply_SSP_projection_vectors, add_eeg_ref = params snr = 3.0 lambda2 = 1.0 / snr ** 2 local_inv_file_name = op.join(LOCAL_ROOT_DIR, 'inv', '{}_ecr_nTSSS_conflict-inv.fif'.format(subject)) if inv is None and os.path.isfile(local_inv_file_name): inv = read_inverse_operator(local_inv_file_name) if inv is None: return print([s['vertno'] for s in inv['src']]) for cond_name in events_id.keys(): if not apply_for_epochs: local_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc', '{}_{}_{}'.format(subject, cond_name, inverse_method)) if os.path.isfile('{}-lh.stc'.format(local_stc_file_name)): print('stc was already calculated for {}'.format(subject)) else: if evoked is None: evoked_cond = mne.read_evokeds(op.join(LOCAL_ROOT_DIR, 'evo', '{}_ecr_{}-ave.fif'.format(subject, cond_name))) else: evoked_cond = evoked[cond_name] stcs = apply_inverse(evoked_cond, inv, lambda2, inverse_method, pick_ori=None) stcs.save(local_stc_file_name, ftype='h5') else: local_stc_template = op.join(LOCAL_ROOT_DIR, 'stc_epochs', '{}_{}_{}_{}'.format(subject, cond_name, '{epoch_ind}', inverse_method)) if len(glob.glob(local_stc_template.format(epoch_ind='*') == 36)): print('stc was already calculated for {}'.format(subject)) else: stcs = apply_inverse_epochs(epochs[cond_name], inv, lambda2, inverse_method, pick_ori=None, return_generator=True) for epoch_ind, stc in enumerate(stcs): if not os.path.isfile(local_stc_template.format(epoch_ind=epoch_ind)): stc.save(local_stc_template.format(epoch_ind=epoch_ind), ftype='h5')
def calc_sub_cortical_activity(events_id, evoked_fn, inv_fn, sub_corticals_codes_file, baseline_min_t=None, baseline_max_t = 0, snr = 3.0, inverse_method='dSPM'): sub_corticals = read_sub_corticals_code_file(sub_corticals_codes_file) if len(sub_corticals) == 0: return lambda2 = 1.0 / snr ** 2 lut = read_freesurfer_lookup_table(FREE_SURFER_HOME) for cond in events_id.keys(): evo = evoked_fn.format(cond=cond) evoked = {event:mne.read_evokeds(evo, baseline=(baseline_min_t, baseline_max_t))[0] for event in [event]} inverse_operator = read_inverse_operator(inv_fn.format(cond=cond)) stc = apply_inverse(evoked[cond], inverse_operator, lambda2, inverse_method) read_vertices_from = len(stc.vertices[0])+len(stc.vertices[1]) sub_corticals_activity = {} for sub_cortical_ind, sub_cortical_code in enumerate(sub_corticals): # +2 becasue the first two are the hemispheres sub_corticals_activity[sub_cortical_code] = stc.data[ read_vertices_from: read_vertices_from + len(stc.vertices[sub_cortical_ind + 2])] read_vertices_from += len(stc.vertices[sub_cortical_ind + 2]) if not os.path.isdir: os.mkdir(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals')) for sub_cortical_code, activity in sub_corticals_activity.iteritems(): sub_cortical, _ = get_numeric_index_to_label(sub_cortical_code, lut) np.save(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals', '{}-{}-{}'.format(cond, sub_cortical, inverse_method)), activity.mean(0)) np.save(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals', '{}-{}-{}-all-vertices'.format(cond, sub_cortical, inverse_method)), activity)
def test_volume_labels_morph(tmpdir): """Test generating a source space from volume label.""" # see gh-5224 evoked = mne.read_evokeds(fname_evoked)[0].crop(0, 0) evoked.pick_channels(evoked.ch_names[:306:8]) evoked.info.normalize_proj() n_ch = len(evoked.ch_names) aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz') label_names = get_volume_labels_from_aseg(aseg_fname) src = setup_volume_source_space( 'sample', subjects_dir=subjects_dir, volume_label=label_names[:2], mri=aseg_fname) assert len(src) == 2 assert src.kind == 'volume' n_src = sum(s['nuse'] for s in src) sphere = make_sphere_model('auto', 'auto', evoked.info) fwd = make_forward_solution(evoked.info, fname_trans, src, sphere) assert fwd['sol']['data'].shape == (n_ch, n_src * 3) inv = make_inverse_operator(evoked.info, fwd, make_ad_hoc_cov(evoked.info), loose=1.) stc = apply_inverse(evoked, inv) assert stc.data.shape == (n_src, 1) img = stc.as_volume(src, mri_resolution=True) n_on = np.array(img.dataobj).astype(bool).sum() assert n_on == 291 # was 291 on `master` before gh-5590 img = stc.as_volume(src, mri_resolution=False) n_on = np.array(img.dataobj).astype(bool).sum() assert n_on == 44 # was 20 on `master` before gh-5590
def apply_STC_ave(fnevo, method='dSPM', snr=3.0): ''' Inverse evoked data into the source space. Parameter --------- fnevo: string or list The evoked file with ECG, EOG and environmental noise free. method:string Inverse method, 'MNE' or 'dSPM' snr: float Signal to noise ratio for inverse solution. ''' #Get the default subjects_dir from mne.minimum_norm import apply_inverse, read_inverse_operator fnlist = get_files_from_list(fnevo) # loop across all filenames for fname in fnlist: name = os.path.basename(fname) fn_path = os.path.split(fname)[0] fn_stc = fname[:fname.rfind('-ave.fif')] # fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' subject = name.split('_')[0] fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' % subject snr = snr lambda2 = 1.0 / snr ** 2 # noise_cov = mne.read_cov(fn_cov) [evoked] = mne.read_evokeds(fname) evoked.pick_types(meg=True, ref_meg=False) inv = read_inverse_operator(fn_inv) stc = apply_inverse(evoked, inv, lambda2, method, pick_ori='normal') stc.save(fn_stc)
def test_epochs_vector_inverse(): """Test vector inverse consistency between evoked and epochs.""" raw = read_raw_fif(fname_raw) events = find_events(raw, stim_channel='STI 014')[:2] reject = dict(grad=2000e-13, mag=4e-12, eog=150e-6) epochs = Epochs(raw, events, None, 0, 0.01, baseline=None, reject=reject, preload=True) assert_equal(len(epochs), 2) evoked = epochs.average(picks=range(len(epochs.ch_names))) inv = read_inverse_operator(fname_inv) method = "MNE" snr = 3. lambda2 = 1. / snr ** 2 stcs_epo = apply_inverse_epochs(epochs, inv, lambda2, method=method, pick_ori='vector', return_generator=False) stc_epo = np.mean(stcs_epo) stc_evo = apply_inverse(evoked, inv, lambda2, method=method, pick_ori='vector') assert_allclose(stc_epo.data, stc_evo.data, rtol=1e-9, atol=0)
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 apply_STC_ave(fnevo, method='dSPM', snr=3.0, min_subject='fsaverage'): ''' Inverse evoked data into the source space. Parameter --------- fnevo: string or list The evoked file with ECG, EOG and environmental noise free. method:string Inverse method, 'MNE' or 'dSPM' snr: float Signal to noise ratio for inverse solution. event: string The event name related with evoked data. baseline: bool If true, prestimulus segment from 'btmin' to 'btmax' will be saved, If false, no baseline segment is saved. btmin: float The start time point (second) of baseline. btmax: float The end time point(second) of baseline. min_subject: string The subject name as the common brain. ''' #Get the default subjects_dir from mne.minimum_norm import apply_inverse, read_inverse_operator fnlist = get_files_from_list(fnevo) # loop across all filenames for fname in fnlist: name = os.path.basename(fname) fn_path = os.path.split(fname)[0] fn_stc = fname[:fname.rfind('-ave.fif')] #fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' subject = name.split('_')[0] fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' %subject snr = snr lambda2 = 1.0 / snr ** 2 #noise_cov = mne.read_cov(fn_cov) [evoked] = mne.read_evokeds(fname) evoked.pick_types(meg=True, ref_meg=False) inv = read_inverse_operator(fn_inv) stc = apply_inverse(evoked, inv, lambda2, method, pick_ori='normal') stc.save(fn_stc)
def get_mne_stc(ndvar=False, vol=False, subject='sample'): """MNE-Python SourceEstimate Parameters ---------- ndvar : bool Convert to NDVar (default False; src="ico-4" is false, but it works as long as the source space is not accessed). vol : bool Volume source estimate. """ data_path = Path(mne.datasets.testing.data_path()) meg_sdir = data_path / 'MEG/sample' subjects_dir = data_path / 'subjects' # scaled subject if subject == 'fsaverage_scaled': subject_dir = os.path.join(subjects_dir, subject) if not os.path.exists(subject_dir): mne.scale_mri('fsaverage', subject, .9, subjects_dir=subjects_dir, skip_fiducials=True, labels=False, annot=True) data_subject = 'fsaverage' else: data_subject = subject if vol: inv = mn.read_inverse_operator(str(meg_sdir / 'sample_audvis_trunc-meg-vol-7-meg-inv.fif')) evoked = mne.read_evokeds(str(meg_sdir / 'sample_audvis_trunc-ave.fif'), 'Left Auditory') stc = mn.apply_inverse(evoked, inv, method='MNE', pick_ori='vector') if data_subject == 'fsaverage': m = mne.compute_source_morph(stc, 'sample', data_subject, subjects_dir) stc = m.apply(stc) stc.subject = subject elif subject != 'sample': raise ValueError(f"subject={subject!r}") if ndvar: return load.fiff.stc_ndvar(stc, subject, 'vol-7', subjects_dir, 'MNE', sss_filename='{subject}-volume-7mm-src.fif') else: return stc stc_path = meg_sdir / f'{data_subject}_audvis_trunc-meg' if ndvar: return load.fiff.stc_ndvar(stc_path, subject, 'ico-5', subjects_dir) else: return mne.read_source_estimate(str(stc_path), subject)
def inverse_function(sub_id, session): """ Will calculate the inverse model based dSPM """ data_path = "/media/mje/My_Book/Data/MEG/MEG_libet/sub_2_tests" fname = "sub_%d_%s_tsss_mc" % (sub_id, session) fname_epochs = data_path + fname + "_epochs.fif" fname_fwd_meg = data_path + fname + "_fwd.fif" fname_cov = data_path + fname + "_cov.fif" fname_inv = data_path + fname + "_inv.fif" fname_stcs = fname + "_mne_dSPM_inverse" epochs = mne.read_epochs(fname_epochs) evoked = epochs.average() snr = 3.0 lambda2 = 1.0 / snr ** 2 # Load data forward_meg = mne.read_forward_solution(fname_fwd_meg, surf_ori=True) noise_cov = mne.read_cov(fname_cov) # regularize noise covariance noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) # Restrict forward solution as necessary for MEG forward_meg = mne.fiff.pick_types_forward(forward_meg, meg=True, eeg=False) # make an M/EEG, MEG-only, and EEG-only inverse operators info = evoked.info inverse_operator_meg = make_inverse_operator(info, forward_meg, noise_cov, loose=0.2, depth=0.8) write_inverse_operator(fname_inv, inverse_operator_meg) # Compute inverse solution stc = apply_inverse(evoked, inverse_operator_meg, lambda2, "dSPM", pick_normal=False) # Save result in stc files stc.save(fname_stcs)
def test_apply_inverse_operator(evoked, inv, min_, max_): """Test MNE inverse application.""" # use fname_inv as it will be faster than fname_full (fewer verts and chs) inverse_operator = read_inverse_operator(inv) # Inverse has 306 channels - 4 proj = 302 assert (compute_rank_inverse(inverse_operator) == 302) # Inverse has 306 channels - 4 proj = 302 assert (compute_rank_inverse(inverse_operator) == 302) stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE") assert stc.subject == 'sample' assert stc.data.min() > min_ assert stc.data.max() < max_ assert abs(stc).data.mean() > 1e-11 # test if using prepared and not prepared inverse operator give the same # result inv_op = prepare_inverse_operator(inverse_operator, nave=evoked.nave, lambda2=lambda2, method="MNE") stc2 = apply_inverse(evoked, inv_op, lambda2, "MNE") assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.times, stc2.times) # This is little more than a smoke test... stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA") assert stc.subject == 'sample' assert abs(stc).data.min() > 0 assert 2 < stc.data.max() < 7 assert abs(stc).data.mean() > 0.1 stc = apply_inverse(evoked, inverse_operator, lambda2, "eLORETA") assert stc.subject == 'sample' assert abs(stc).data.min() > min_ assert stc.data.max() < max_ * 2 assert abs(stc).data.mean() > 1e-11 stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM") assert stc.subject == 'sample' assert abs(stc).data.min() > 0 assert 7.5 < stc.data.max() < 15 assert abs(stc).data.mean() > 0.1 # test without using a label (so delayed computation is used) label = read_label(fname_label % 'Aud-lh') for method in INVERSE_METHODS: stc = apply_inverse(evoked, inv_op, lambda2, method) stc_label = apply_inverse(evoked, inv_op, lambda2, method, label=label) assert_equal(stc_label.subject, 'sample') label_stc = stc.in_label(label) assert label_stc.subject == 'sample' assert_allclose(stc_label.data, label_stc.data) # Test that no errors are raised with loose inverse ops and picking normals noise_cov = read_cov(fname_cov) fwd = read_forward_solution_meg(fname_fwd) inv_op_meg = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1, fixed='auto', depth=None) apply_inverse(evoked, inv_op_meg, 1 / 9., method='MNE', pick_ori='normal') # Test we get errors when using custom ref or no average proj is present evoked.info['custom_ref_applied'] = True pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") evoked.info['custom_ref_applied'] = False evoked.info['projs'] = [] # remove EEG proj pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") # But test that we do not get EEG-related errors on MEG-only inv (gh-4650) apply_inverse(evoked, inv_op_meg, 1. / 9.)
def run_inverse(subject_id): tasks = ['AVLearn', 'AVLearn'] days = [100, 200] for task, day in zip(tasks, days): subject = group_name + "%d" % subject_id print("processing subject: %s" % subject) fname = op.join(MEG_data_path, subject, task + '_%d' % (day + subject_id) + '_tsss_mc.fif') if day == 100: evokeds_AV = mne.read_evokeds(fname.replace("_tsss_mc", "-ave"), cond_day1_AV) evokeds_FB = mne.read_evokeds(fname.replace("_tsss_mc", "-ave"), cond_day1_FB) evokeds_IT = mne.read_evokeds(fname.replace( 'tsss_mc', 'evoked_RG')) elif day == 200: evokeds_AV = mne.read_evokeds(fname.replace("_tsss_mc", "-ave"), cond_day2_AV) evokeds_FB = mne.read_evokeds(fname.replace("_tsss_mc", "-ave"), cond_day2_FB) evokeds_IT = mne.read_evokeds(fname.replace( 'tsss_mc', 'evoked_RG')) epo_Nave_avg = np.load(fname.replace("tsss_mc.fif", 'epo_Nave_avg.npy'), allow_pickle=True).item() epo_Nave_avg_RG = np.load(fname.replace("tsss_mc.fif", 'epo_Nave_avg_RG.npy'), allow_pickle=True).item() # only for nave>15 evokeds_AV = [ evk for evk in evokeds_AV if (epo_Nave_avg[evk.comment] > 15) ] evokeds_FB = [ evk for evk in evokeds_FB if (epo_Nave_avg[evk.comment] > 15) ] cov_AV = mne.read_cov(fname.replace('_tsss_mc.fif', '_AV-cov.fif')) cov_FB = mne.read_cov(fname.replace('_tsss_mc.fif', '_FB-cov.fif')) forward = mne.read_forward_solution( fname.replace('_tsss_mc.fif', '-meg-ico5-fwd.fif')) inverse_operator_AV = make_inverse_operator(evokeds_AV[0].info, forward, cov_AV, loose=1, depth=0.8) inverse_operator_FB = make_inverse_operator(evokeds_FB[0].info, forward, cov_FB, loose=1, depth=0.8) inverse_operator_IT = make_inverse_operator(evokeds_IT[0].info, forward, cov_AV, loose=1, depth=0.8) labels = mne.read_labels_from_annot(subject=task + '_' + str(day + subject_id), parc='aparc', subjects_dir=MRI_data_path) label_names = [labels[indx].name for indx in range(len(labels))] STC_L = labels[0] + labels[60] #'bankssts-lh + superiortemporal-lh' STC_R = labels[1] + labels[61] #'bankssts-rh + superiortemporal-rh' labels.append(STC_L) labels.append(STC_R) label_names.append(STC_L.name) label_names.append(STC_R.name) snr = 3.0 lambda2 = 1.0 / snr**2 methods = ['dSPM', 'MNE'] pick_ori = None mode = 'mean' for method in methods: for evoked in evokeds_AV: stc = apply_inverse(evoked.apply_baseline(baseline=(None, 0)), inverse_operator_AV, lambda2, method=method, pick_ori=pick_ori) label_ts = mne.extract_label_time_course( stc, labels, inverse_operator_AV['src'], allow_empty=True, mode=mode) if method == 'dSPM': label_ts = label_ts * math.sqrt( epo_Nave_avg[evoked.comment]) / math.sqrt(evoked.nave) pd.DataFrame(label_ts.T, index=stc.times, columns=label_names).to_csv( fname.replace( 'tsss_mc.fif', evoked.comment.replace('/', '_') + '-' + method + '.csv')) stc_fsaverage = mne.compute_source_morph( stc, subjects_dir=MRI_data_path).apply(stc) if method == 'dSPM': stc_fsaverage = stc_fsaverage * math.sqrt( epo_Nave_avg[evoked.comment]) / math.sqrt(evoked.nave) stc_fsaverage.save( fname.replace( 'tsss_mc.fif', evoked.comment.replace('/', '_') + '-' + method)) for evoked in evokeds_FB: stc = apply_inverse(evoked.apply_baseline(baseline=(None, 0)), inverse_operator_FB, lambda2, method=method, pick_ori=pick_ori) label_ts = mne.extract_label_time_course( stc, labels, inverse_operator_FB['src'], allow_empty=True, mode=mode) if method == 'dSPM': label_ts = label_ts * math.sqrt( epo_Nave_avg[evoked.comment]) / math.sqrt(evoked.nave) pd.DataFrame(label_ts.T, index=stc.times, columns=label_names).to_csv( fname.replace( 'tsss_mc.fif', evoked.comment.replace('/', '_') + '-' + method + '.csv')) stc_fsaverage = mne.compute_source_morph( stc, subjects_dir=MRI_data_path).apply(stc) if method == 'dSPM': stc_fsaverage = stc_fsaverage * math.sqrt( epo_Nave_avg[evoked.comment]) / math.sqrt(evoked.nave) stc_fsaverage.save( fname.replace( 'tsss_mc.fif', evoked.comment.replace('/', '_') + '-' + method)) for evoked in evokeds_IT: stc = apply_inverse(evoked.apply_baseline(baseline=(None, 0)), inverse_operator_IT, lambda2, method=method, pick_ori=pick_ori) label_ts = mne.extract_label_time_course( stc, labels, inverse_operator_IT['src'], allow_empty=True, mode=mode) if method == 'dSPM': label_ts = label_ts * math.sqrt( epo_Nave_avg_RG[evoked.comment]) / math.sqrt( evoked.nave) pd.DataFrame(label_ts.T, index=stc.times, columns=label_names).to_csv( fname.replace( 'tsss_mc.fif', evoked.comment.replace('/', '_') + '-' + method + '.csv')) stc_fsaverage = mne.compute_source_morph( stc, subjects_dir=MRI_data_path).apply(stc) if method == 'dSPM': stc_fsaverage = stc_fsaverage * math.sqrt( epo_Nave_avg_RG[evoked.comment]) / math.sqrt( evoked.nave) stc_fsaverage.save( fname.replace( 'tsss_mc.fif', evoked.comment.replace('/', '_') + '-' + method))
for n in np.array([0]): # Reading epochs epo_name= data_path + meg + epochs_names[n] epochs = mne.read_epochs(epo_name, preload=True) epochs = epochs['words'] # Reading inverse operator inv_fname = data_path + meg + inv_op_name[n] inv_op = read_inverse_operator(inv_fname) # Evoked responses evoked = epochs.average().set_eeg_reference(ref_channels = \ 'average',projection=True) # Applying inverse solution to get sourse signals stc = apply_inverse(evoked, inv_op,lambda2,method ='MNE', pick_ori=None) # stc_corrected = stc_baseline_correction(stc) # for j in np.arange(0,len(SN_ROI)): morphed_labels[j].subject = sub_to label_ = stc.in_label(morphed_labels[j]) X[i,n*len(SN_ROI)+j,:] = abs(label_.data).copy().mean(0) # stc_corrected = stc_baseline_correction(label_) Y[i,n*len(SN_ROI)+j,:] = stc_baseline_correction(abs(label_.data).copy().mean(0),T ) t= np.arange(-300,901) plt.figure() plt.subplot(211)
def test_channel_name_limit(tmpdir, monkeypatch, fname): """Test that our remapping works properly.""" # # raw # if fname.endswith('fif'): raw = read_raw_fif(fname) raw.pick_channels(raw.ch_names[:3]) ref_names = [] data_names = raw.ch_names else: assert fname.endswith('.ds') raw = read_raw_ctf(fname) ref_names = [ raw.ch_names[pick] for pick in pick_types(raw.info, meg=False, ref_meg=True) ] data_names = raw.ch_names[32:35] proj = dict(data=np.ones((1, len(data_names))), col_names=data_names[:2].copy(), row_names=None, nrow=1) proj = Projection(data=proj, active=False, desc='test', kind=0, explained_var=0.) raw.add_proj(proj, remove_existing=True) raw.info.normalize_proj() raw.pick_channels(data_names + ref_names).crop(0, 2) long_names = ['123456789abcdefg' + name for name in raw.ch_names] fname = tmpdir.join('test-raw.fif') with catch_logging() as log: raw.save(fname) log = log.getvalue() assert 'truncated' not in log rename = dict(zip(raw.ch_names, long_names)) long_data_names = [rename[name] for name in data_names] long_proj_names = long_data_names[:2] raw.rename_channels(rename) for comp in raw.info['comps']: for key in ('row_names', 'col_names'): for name in comp['data'][key]: assert name in raw.ch_names if raw.info['comps']: assert raw.compensation_grade == 0 raw.apply_gradient_compensation(3) assert raw.compensation_grade == 3 assert len(raw.info['projs']) == 1 assert raw.info['projs'][0]['data']['col_names'] == long_proj_names raw.info['bads'] = bads = long_data_names[2:3] good_long_data_names = [ name for name in long_data_names if name not in bads ] with catch_logging() as log: raw.save(fname, overwrite=True, verbose=True) log = log.getvalue() assert 'truncated to 15' in log for name in raw.ch_names: assert len(name) > 15 # first read the full way with catch_logging() as log: raw_read = read_raw_fif(fname, verbose=True) log = log.getvalue() assert 'Reading extended channel information' in log for ra in (raw, raw_read): assert ra.ch_names == long_names assert raw_read.info['projs'][0]['data']['col_names'] == long_proj_names del raw_read # next read as if no longer names could be read monkeypatch.setattr(meas_info, '_read_extended_ch_info', lambda x, y, z: None) with catch_logging() as log: raw_read = read_raw_fif(fname, verbose=True) log = log.getvalue() assert 'extended' not in log if raw.info['comps']: assert raw_read.compensation_grade == 3 raw_read.apply_gradient_compensation(0) assert raw_read.compensation_grade == 0 monkeypatch.setattr( # restore meas_info, '_read_extended_ch_info', _read_extended_ch_info) short_proj_names = [ f'{name[:13 - bool(len(ref_names))]}-{len(ref_names) + ni}' for ni, name in enumerate(long_data_names[:2]) ] assert raw_read.info['projs'][0]['data']['col_names'] == short_proj_names # # epochs # epochs = Epochs(raw, make_fixed_length_events(raw)) fname = tmpdir.join('test-epo.fif') epochs.save(fname) epochs_read = read_epochs(fname) for ep in (epochs, epochs_read): assert ep.info['ch_names'] == long_names assert ep.ch_names == long_names del raw, epochs_read # cov epochs.info['bads'] = [] cov = compute_covariance(epochs, verbose='error') fname = tmpdir.join('test-cov.fif') write_cov(fname, cov) cov_read = read_cov(fname) for co in (cov, cov_read): assert co['names'] == long_data_names assert co['bads'] == [] del cov_read # # evoked # evoked = epochs.average() evoked.info['bads'] = bads assert evoked.nave == 1 fname = tmpdir.join('test-ave.fif') evoked.save(fname) evoked_read = read_evokeds(fname)[0] for ev in (evoked, evoked_read): assert ev.ch_names == long_names assert ev.info['bads'] == bads del evoked_read, epochs # # forward # with pytest.warns(None): # not enough points for CTF sphere = make_sphere_model('auto', 'auto', evoked.info) src = setup_volume_source_space( pos=dict(rr=[[0, 0, 0.04]], nn=[[0, 1., 0.]])) fwd = make_forward_solution(evoked.info, None, src, sphere) fname = tmpdir.join('temp-fwd.fif') write_forward_solution(fname, fwd) fwd_read = read_forward_solution(fname) for fw in (fwd, fwd_read): assert fw['sol']['row_names'] == long_data_names assert fw['info']['ch_names'] == long_data_names assert fw['info']['bads'] == bads del fwd_read # # inv # inv = make_inverse_operator(evoked.info, fwd, cov) fname = tmpdir.join('test-inv.fif') write_inverse_operator(fname, inv) inv_read = read_inverse_operator(fname) for iv in (inv, inv_read): assert iv['info']['ch_names'] == good_long_data_names apply_inverse(evoked, inv) # smoke test
snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Compute a label/ROI based on the peak power between 80 and 120 ms. # The label bankssts-lh is used for the comparison. aparc_label_name = 'bankssts-lh' tmin, tmax = 0.080, 0.120 # Load data evoked = Evoked(fname_evoked, setno=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # get the source space # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_normal=True) # Make an STC in the time interval of interest and take the mean stc_mean = stc.copy().crop(tmin, tmax).mean() # use the stc_mean to generate a functional label # region growing is halted at 60% of the peak value within the # anatomical label / ROI specified by aparc_label_name label = mne.labels_from_parc(subject, parc='aparc', subjects_dir=subjects_dir, regexp=aparc_label_name)[0][0] stc_mean_label = stc_mean.in_label(label) data = np.abs(stc_mean_label.data) stc_mean_label.data[data < 0.6 * np.max(data)] = 0. func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=5, subjects_dir=subjects_dir, connected=True)
# Read the forward solution and compute the inverse operator info = evoked.info trans = mne.read_trans(fname_trans) src = mne.read_source_spaces(fname_src) bem = mne.read_bem_solution(fname_bem) fwd = mne.make_forward_solution(info, trans, src, bem, meg=True, eeg=False, mindist=0.0, ignore_ref=False, n_jobs=1, verbose=None) fwd = mne.convert_forward_solution(fwd, surf_ori=True) # Inversion inverse = make_inverse_operator(info, fwd, noise_cov, loose=.2) stc_ = apply_inverse( EvokedArray(np.eye(len(info['ch_names'])), info, nave=evoked.nave), inverse).data stc = apply_inverse(evoked, inverse_operator=inverse) stc.plot(subject='sample', hemi='both', subjects_dir=subjects_dir, initial_time=0.1) assert np.allclose(stc.data, np.dot(stc_, evoked.data))
# Read data fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' evoked = mne.read_evokeds(fname_evoked, condition='Left Auditory', baseline=(None, 0)) fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif' fwd = mne.read_forward_solution(fname_fwd) cov = mne.read_cov(fname_cov) # Read inverse operator: inv_op = make_inverse_operator(evoked.info, fwd, cov, fixed=True, verbose=True) # Calculate MNE: snr = 3.0 lambda2 = 1.0 / snr ** 2 stc = apply_inverse(evoked, inv_op, lambda2, 'MNE', verbose=True) # Calculate SNR in source space: snr_stc = stc.estimate_snr(evoked.info, fwd, cov) # Plot an average SNR across source points over time: ave = np.mean(snr_stc.data, axis=0) fig, ax = plt.subplots() ax.plot(evoked.times, ave) ax.set(xlabel='Time (sec)', ylabel='SNR MEG-EEG') fig.tight_layout() # Find time point of maximum SNR: maxidx = np.argmax(ave)
# compute noise covariance matrix from emptyroom epochs # empty = Raw("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/sd130343/raw_sss/emptyroom_trans_sss.fif") noise_cov = mne.compute_raw_data_covariance(empty) # dSPM solution # fname_fwd='/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/sd130343/mne_python/sd130343_run1_ico-5-fwd.fif' forward = mne.read_forward_solution(fname_fwd,surf_ori=True) inverse_operator1 = make_inverse_operator(evokedcond1.info, forward, noise_cov, loose=0.4, depth=0.8) inverse_operator2 = make_inverse_operator(evokedcond2.info, forward, noise_cov, 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/sd130343/mne_python/sd130343_EtDtq1G_QRT2_dPSMinverse_ico-5-fwd.fif') stccond2 = apply_inverse(evokedcond2, inverse_operator2, lambda2, 'dSPM', pick_normal=False) stccond2.save('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/sd130343/mne_python/sd130343_EtDtq2G_QRT2_dPSMinverse_ico-5-fwd.fif')
subject=subject, surface='inflated', time_viewer=False, hemi='lh', initial_time=0.1, time_unit='s') del stc_standard, brain ############################################################################### # Deviant condition. stc_deviant = mne.minimum_norm.apply_inverse(evoked_dev, inv, lambda2, 'dSPM') brain = stc_deviant.plot(subjects_dir=subjects_dir, subject=subject, surface='inflated', time_viewer=False, hemi='lh', initial_time=0.1, time_unit='s') del stc_deviant, brain ############################################################################### # Difference. stc_difference = apply_inverse(evoked_difference, inv, lambda2, 'dSPM') brain = stc_difference.plot(subjects_dir=subjects_dir, subject=subject, surface='inflated', time_viewer=False, hemi='lh', initial_time=0.15, time_unit='s')
['best', 'worst'], best_colors): # We skip empirical rank estimation that we introduced in response to # the findings in reference [1] to use the naive code path that # triggered the behavior described in [1]. The expected true rank is # 274 for this dataset. Please do not do this with your data but # rely on the default rank estimator that helps regularizing the # covariance. inverse_operator = make_inverse_operator(epochs_train.info, forward, est, loose=0.2, depth=0.8, rank=274) stc_a, stc_b = (apply_inverse(e, inverse_operator, lambda2, "dSPM", pick_ori=None) for e in evokeds) stc = stc_a - stc_b brain = stc.plot(subjects_dir=subjects_dir, hemi='both', clim=clim) brain.set_time(175) im = brain_to_mpl(brain) brain.close() ax.axis('off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.imshow(im) ax.set_title('{0} ({1} epochs)'.format(kind, n_train * 2)) # plot spatial mean
equalize_epoch_counts([epochs1, epochs2]) ############################################################################### # Transform to source space fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' snr = 3.0 lambda2 = 1.0 / snr**2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) inverse_operator = read_inverse_operator(fname_inv) sample_vertices = [s['vertno'] for s in inverse_operator['src']] # Let's average and compute inverse, resampling to speed things up evoked1 = epochs1.average() evoked1.resample(50) condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method) evoked2 = epochs2.average() evoked2.resample(50) condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method) # Let's only deal with t > 0, cropping to reduce multiple comparisons condition1.crop(0, None) condition2.crop(0, None) tmin = condition1.tmin tstep = condition1.tstep ############################################################################### # Transform to common cortical space # Normally you would read in estimates across several subjects and morph # them to the same cortical space (e.g. fsaverage). For example purposes,
info = read_info(raw_fname) inv = make_inverse_operator(info, fwd, cov, loose=0.2, depth=0.8) save(inv, 'inv', subject=meg_subject, overwrite=True) # Morph anatomy into common model --------------------------------------------- from mne import EvokedArray from mne import compute_morph_matrix from mne.minimum_norm import apply_inverse if True: for meg_subject, subject in zip(range(1, 21), subjects_id): if subject in bad_mri: continue raw_fname = paths('sss', subject=meg_subject, block=1) info = read_info(raw_fname) # precompute morphing matrix for faster processing inv = load('inv', subject=meg_subject) evoked = EvokedArray(np.zeros((len(info['chs']), 2)), info, 0) evoked.pick_types(eeg=False, meg=True) stc = apply_inverse(evoked, inv, lambda2=1.0 / (2**3.0), method='dSPM', pick_ori=None) morph = compute_morph_matrix(subject, 'fsaverage', stc.vertices, vertices_to=[np.arange(10242)] * 2, subjects_dir=subjects_dir) save(morph, 'morph', subject=meg_subject)
# # >>> from mne.minimum_norm import write_inverse_operator # >>> write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', # inverse_operator) ############################################################################### # Compute inverse solution # ------------------------ method = "dSPM" snr = 3. lambda2 = 1. / snr**2 stc, residual = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori=None, return_residual=True, verbose=True) ############################################################################### # Visualization # ------------- # View activation time-series plt.figure() plt.plot(1e3 * stc.times, stc.data[::100, :].T) plt.xlabel('time (ms)') plt.ylabel('%s value' % method) plt.show()
loose=0.2, depth=0.8) inverse_operator_meg = make_inverse_operator(info, forward_meg, noise_cov, loose=0.2, depth=0.8) inverse_operator_eeg = make_inverse_operator(info, forward_eeg, noise_cov, loose=0.2, depth=0.8) write_inverse_operator('sample_audvis-meeg-oct-6-inv.fif', inverse_operator_meeg) write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', inverse_operator_meg) write_inverse_operator('sample_audvis-eeg-oct-6-inv.fif', inverse_operator_eeg) # Compute inverse solution stcs = dict() stcs['meeg'] = apply_inverse(evoked, inverse_operator_meeg, lambda2, "dSPM", pick_normal=False) stcs['meg'] = apply_inverse(evoked, inverse_operator_meg, lambda2, "dSPM", pick_normal=False) stcs['eeg'] = apply_inverse(evoked, inverse_operator_eeg, lambda2, "dSPM", pick_normal=False) # Save result in stc files names = ['meeg', 'meg', 'eeg'] for name in names: stcs[name].save('mne_dSPM_inverse-%s' % name) ############################################################################### # View activation time-series pl.close('all') pl.figure(figsize=(8, 6)) for ii in range(len(stcs)):
# make an MEG inverse operator info = evoked.info inverse_operator = make_inverse_operator(info, fwd, noise_cov, loose=0.2, depth=0.8) write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', inverse_operator) ############################################################################### # Compute inverse solution # ------------------------ method = "dSPM" snr = 3. lambda2 = 1. / snr ** 2 stc = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori=None) del fwd, epochs # to save memory ############################################################################### # Visualization # ------------- # View activation time-series plt.figure() plt.plot(1e3 * stc.times, stc.data[::100, :].T) plt.xlabel('time (ms)') plt.ylabel('%s value' % method) plt.show() ###############################################################################
# Show the dipoles as arrows pointing along the surface normal normals = lh['nn'][lh['vertno']] mlab.quiver3d(dip_pos[:, 0], dip_pos[:, 1], dip_pos[:, 2], normals[:, 0], normals[:, 1], normals[:, 2], color=red, scale_factor=1E-3) mlab.view(azimuth=180, distance=0.1) ############################################################################### # Restricting the dipole orientations in this manner leads to the following # source estimate for the sample data: # Compute the source estimate for the 'left - auditory' condition in the sample # dataset. inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=True) stc = apply_inverse(left_auditory, inv, pick_ori=None) # Visualize it at the moment of peak activity. _, time_max = stc.get_peak(hemi='lh') brain = stc.plot(surface='white', subjects_dir=subjects_dir, initial_time=time_max, time_unit='s', size=(600, 400)) ############################################################################### # The direction of the estimated current is now restricted to two directions: # inward and outward. In the plot, blue areas indicate current flowing inwards # and red areas indicate current flowing outwards. Given the curvature of the # cortex, groups of dipoles tend to point in the same direction: the direction # of the electromagnetic field picked up by the sensors. ############################################################################### # Loose dipole orientations
fname_evoked = os.path.join(sample_dir, 'sample_audvis-ave.fif') fname_inv = os.path.join(sample_dir, 'sample_audvis-meg-vol-7-meg-inv.fif') fname_t1_fsaverage = os.path.join(subjects_dir, 'fsaverage', 'mri', 'brain.mgz') ############################################################################### # Compute example data. For reference see # :ref:`sphx_glr_auto_examples_inverse_plot_compute_mne_inverse_volume.py` # # Load data: evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) # Apply inverse operator stc = apply_inverse(evoked, inverse_operator, 1.0 / 3.0**2, "dSPM") # To save time stc.crop(0.09, 0.09) ############################################################################### # Get a SourceMorph object for VolSourceEstimate # ---------------------------------------------- # # ``subject_from`` can typically be inferred from # :class:`src <mne.SourceSpaces>`, # and ``subject_to`` is set to 'fsaverage' by default. ``subjects_dir`` can be # None when set in the environment. In that case SourceMorph can be initialized # taking ``src`` as only argument. See :class:`mne.SourceMorph` for more # details. #
inv = mne.minimum_norm.make_inverse_operator(evoked_std.info, fwd, cov) snr = 3.0 lambda2 = 1.0 / snr ** 2 del fwd ############################################################################### # The sources are computed using dSPM method and plotted on an inflated brain # surface. For interactive controls over the image, use keyword # ``time_viewer=True``. # Standard condition. stc_standard = mne.minimum_norm.apply_inverse(evoked_std, inv, lambda2, 'dSPM') brain = stc_standard.plot(subjects_dir=subjects_dir, subject=subject, surface='inflated', time_viewer=False, hemi='lh', initial_time=0.1, time_unit='s') del stc_standard, brain ############################################################################### # Deviant condition. stc_deviant = mne.minimum_norm.apply_inverse(evoked_dev, inv, lambda2, 'dSPM') brain = stc_deviant.plot(subjects_dir=subjects_dir, subject=subject, surface='inflated', time_viewer=False, hemi='lh', initial_time=0.1, time_unit='s') del stc_deviant, brain ############################################################################### # Difference. stc_difference = apply_inverse(evoked_difference, inv, lambda2, 'dSPM') brain = stc_difference.plot(subjects_dir=subjects_dir, subject=subject, surface='inflated', time_viewer=False, hemi='lh', initial_time=0.15, time_unit='s')
subject=subject, subjects_dir=subjects_dir, coord_frame='head', scale=7e-4, fig=fig) mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.1) # %% # Restricting the dipole orientations in this manner leads to the following # source estimate for the sample data: # Compute the source estimate for the 'left - auditory' condition in the sample # dataset. inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=True) stc = apply_inverse(left_auditory, inv, pick_ori=None) # Visualize it at the moment of peak activity. _, time_max = stc.get_peak(hemi='lh') brain_fixed = stc.plot(surface='white', subjects_dir=subjects_dir, initial_time=time_max, time_unit='s', size=(600, 400)) mne.viz.set_3d_view(figure=brain_fixed, focalpoint=(0., 0., 50)) # %% # The direction of the estimated current is now restricted to two directions: # inward and outward. In the plot, blue areas indicate current flowing inwards # and red areas indicate current flowing outwards. Given the curvature of the # cortex, groups of dipoles tend to point in the same direction: the direction
data_path = sample.data_path() fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' snr = 3.0 lambda2 = 1.0 / snr**2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Load data evoked = Evoked(fname_evoked, setno=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method) stc.crop(0.0, 0.2) # Export result as a 4D nifti object img = stc.as_volume(src, mri_resolution=False) # set True for full MRI resolution # Save it as a nifti file import nibabel as nib nib.save(img, 'mne_%s_inverse.nii.gz' % method) data = img.get_data() # Plot result (one slice) coronal_slice = data[:, 10, :, 60] plt.close('all')
method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Compute a label/ROI based on the peak power between 80 and 120 ms. # The label bankssts-lh is used for the comparison. aparc_label_name = 'bankssts-lh' tmin, tmax = 0.080, 0.120 # Load data evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # get the source space # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_normal=True) # Make an STC in the time interval of interest and take the mean stc_mean = stc.copy().crop(tmin, tmax).mean() # use the stc_mean to generate a functional label # region growing is halted at 60% of the peak value within the # anatomical label / ROI specified by aparc_label_name label = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=subjects_dir, regexp=aparc_label_name)[0] stc_mean_label = stc_mean.in_label(label) data = np.abs(stc_mean_label.data)
def test_mxne_inverse_standard(forward): """Test (TF-)MxNE inverse computation.""" # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file loose = 0.0 depth = 0.9 evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.crop(tmin=-0.05, tmax=0.2) evoked_l21 = evoked.copy() evoked_l21.crop(tmin=0.081, tmax=0.1) label = read_label(fname_label) assert label.hemi == 'rh' forward = convert_forward_solution(forward, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked_l21.info, forward, cov, loose=loose, depth=depth, fixed=True, use_cps=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. weights_min = 0.5 # MxNE tests alpha = 70 # spatial regularization parameter with pytest.deprecated_call(match="will be solved"): stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='prox') with pytest.warns(None): # CD stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd') stc_bcd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='bcd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_bcd.times, evoked_l21.times, 5) assert_allclose(stc_prox.data, stc_cd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_prox.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_cd.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert stc_prox.vertices[1][0] in label.vertices assert stc_cd.vertices[1][0] in label.vertices assert stc_bcd.vertices[1][0] in label.vertices # vector with pytest.warns(None): # no convergence stc = mixed_norm(evoked_l21, forward, cov, alpha, loose=1, maxit=2) with pytest.warns(None): # no convergence stc_vec = mixed_norm(evoked_l21, forward, cov, alpha, loose=1, maxit=2, pick_ori='vector') assert_stcs_equal(stc_vec.magnitude(), stc) with pytest.warns(None), pytest.raises(ValueError, match='pick_ori='): mixed_norm(evoked_l21, forward, cov, alpha, loose=0, maxit=2, pick_ori='vector') with pytest.warns(None), catch_logging() as log: # CD dips = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd', return_as_dipoles=True, verbose=True) stc_dip = make_stc_from_dipoles(dips, forward['src']) assert isinstance(dips[0], Dipole) assert stc_dip.subject == "sample" assert_stcs_equal(stc_cd, stc_dip) assert_var_exp_log(log.getvalue(), 51, 53) # 51.8 # Single time point things should match with pytest.warns(None), catch_logging() as log: dips = mixed_norm(evoked_l21.copy().crop(0.081, 0.081), forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd', return_as_dipoles=True, verbose=True) assert_var_exp_log(log.getvalue(), 37.8, 38.0) # 37.9 gof = sum(dip.gof[0] for dip in dips) # these are now partial exp vars assert_allclose(gof, 37.9, atol=0.1) with pytest.warns(None), catch_logging() as log: stc, res = mixed_norm( evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, weights=stc_dspm, # gh-6382 active_set_size=10, return_residual=True, solver='cd', verbose=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert stc.vertices[1][0] in label.vertices assert_var_exp_log(log.getvalue(), 51, 53) # 51.8 assert stc.data.min() < -1e-9 # signed assert_stc_res(evoked_l21, stc, forward, res) # irMxNE tests with pytest.warns(None), catch_logging() as log: # CD stc, residual = mixed_norm(evoked_l21, forward, cov, alpha, n_mxne_iter=5, loose=0.0001, depth=depth, maxit=300, tol=1e-8, active_set_size=10, solver='cd', return_residual=True, pick_ori='vector', verbose=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert stc.vertices[1][0] in label.vertices assert stc.vertices == [[63152], [79017]] assert_var_exp_log(log.getvalue(), 51, 53) # 51.8 assert_stc_res(evoked_l21, stc, forward, residual) # Do with TF-MxNE for test memory savings alpha = 60. # overall regularization parameter l1_ratio = 0.01 # temporal regularization proportion stc, _ = tf_mixed_norm(evoked, forward, cov, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True, alpha=alpha, l1_ratio=l1_ratio) assert_array_almost_equal(stc.times, evoked.times, 5) assert stc.vertices[1][0] in label.vertices # vector stc_nrm = tf_mixed_norm(evoked, forward, cov, loose=1, depth=depth, maxit=2, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, alpha=alpha, l1_ratio=l1_ratio) stc_vec, residual = tf_mixed_norm(evoked, forward, cov, loose=1, depth=depth, maxit=2, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, alpha=alpha, l1_ratio=l1_ratio, pick_ori='vector', return_residual=True) assert_stcs_equal(stc_vec.magnitude(), stc_nrm) pytest.raises(ValueError, tf_mixed_norm, evoked, forward, cov, alpha=101, l1_ratio=0.03) pytest.raises(ValueError, tf_mixed_norm, evoked, forward, cov, alpha=50., l1_ratio=1.01)
############################################################################### # Look at the whitened evoked daat evoked[0].plot_white(noise_cov) ############################################################################### # Compute forward model src = data_path + '/subjects/spm/bem/spm-oct-6-src.fif' bem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif' forward = mne.make_forward_solution(contrast.info, trans_fname, src, bem) ############################################################################### # Compute inverse solution snr = 3.0 lambda2 = 1.0 / snr ** 2 method = 'dSPM' inverse_operator = make_inverse_operator(contrast.info, forward, noise_cov, loose=0.2, depth=0.8) # Compute inverse solution on contrast stc = apply_inverse(contrast, inverse_operator, lambda2, method, pick_ori=None) # stc.save('spm_%s_dSPM_inverse' % contrast.comment) # Plot contrast in 3D with PySurfer if available brain = stc.plot(hemi='both', subjects_dir=subjects_dir, initial_time=0.170, views=['ven'], clim={'kind': 'value', 'lims': [3., 6., 9.]}) # brain.save_image('dSPM_map.png')
del epochs_train, events_ # do contrast # We skip empirical rank estimation that we introduced in response to # the findings in reference [1] to use the naive code path that # triggered the behavior described in [1]. The expected true rank is # 274 for this dataset. Please do not do this with your data but # rely on the default rank estimator that helps regularizing the # covariance. stcs.append(list()) methods_ordered.append(list()) for cov in noise_covs: inverse_operator = make_inverse_operator(evokeds[0].info, forward, cov, loose=0.2, depth=0.8, rank=274) stc_a, stc_b = (apply_inverse(e, inverse_operator, lambda2, "dSPM", pick_ori=None) for e in evokeds) stc = stc_a - stc_b methods_ordered[-1].append(cov['method']) stcs[-1].append(stc) del inverse_operator, evokeds, cov, noise_covs, stc, stc_a, stc_b del raw, forward # save some memory ############################################################################## # Show the resulting source estimates fig, (axes1, axes2) = plt.subplots(2, 3, figsize=(9.5, 5)) for ni, (n_train, axes) in enumerate(zip(samples_epochs, (axes1, axes2))): # compute stc based on worst and best ax_dynamics = axes[1]
bem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif' forward = mne.make_forward_solution(contrast.info, trans_fname, src, bem) ############################################################################### # Compute inverse solution snr = 3.0 lambda2 = 1.0 / snr**2 method = 'dSPM' inverse_operator = make_inverse_operator(contrast.info, forward, noise_cov, loose=0.2, depth=0.8) # Compute inverse solution on contrast stc = apply_inverse(contrast, inverse_operator, lambda2, method, pick_ori=None) # stc.save('spm_%s_dSPM_inverse' % contrast.comment) # Plot contrast in 3D with PySurfer if available brain = stc.plot(hemi='both', subjects_dir=subjects_dir, initial_time=0.170, views=['ven'], clim={ 'kind': 'value', 'lims': [3., 6., 9.] }) # brain.save_image('dSPM_map.png')
def compute_ROIs_inv_sol(raw_filename, sbj_id, sbj_dir, fwd_filename, cov_fname, is_epoched=False, event_id=None, t_min=None, t_max=None, is_evoked=False, events_id=[], snr=1.0, inv_method='MNE', parc='aparc', aseg=False, aseg_labels=[], is_blind=False, labels_removed=[], save_stc=False): import os import os.path as op import numpy as np import mne import pickle from mne.io import read_raw_fif from mne import read_epochs from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from mne.minimum_norm import apply_inverse_epochs, apply_inverse from mne import get_volume_labels_from_src from nipype.utils.filemanip import split_filename as split_f from neuropype_ephy.preproc import create_reject_dict try: traits.undefined(event_id) except NameError: event_id = None print '\n*** READ raw filename %s ***\n' % raw_filename if is_epoched and event_id is None: epochs = read_epochs(raw_filename) info = epochs.info else: raw = read_raw_fif(raw_filename) info = raw.info subj_path, basename, ext = split_f(info['filename']) print '\n*** READ noise covariance %s ***\n' % cov_fname noise_cov = mne.read_cov(cov_fname) print '\n*** READ FWD SOL %s ***\n' % fwd_filename forward = mne.read_forward_solution(fwd_filename) if not aseg: forward = mne.convert_forward_solution(forward, surf_ori=True, force_fixed=False) lambda2 = 1.0 / snr ** 2 # compute inverse operator print '\n*** COMPUTE INV OP ***\n' if not aseg: loose = 0.2 depth = 0.8 else: loose = None depth = None inverse_operator = make_inverse_operator(info, forward, noise_cov, loose=loose, depth=depth, fixed=False) # apply inverse operator to the time windows [t_start, t_stop]s print '\n*** APPLY INV OP ***\n' if is_epoched and event_id is not None: events = mne.find_events(raw) picks = mne.pick_types(info, meg=True, eog=True, exclude='bads') reject = create_reject_dict(info) if is_evoked: epochs = mne.Epochs(raw, events, events_id, t_min, t_max, picks=picks, baseline=(None, 0), reject=reject) evoked = [epochs[k].average() for k in events_id] snr = 3.0 lambda2 = 1.0 / snr ** 2 ev_list = events_id.items() for k in range(len(events_id)): stc = apply_inverse(evoked[k], inverse_operator, lambda2, inv_method, pick_ori=None) print '\n*** STC for event %s ***\n' % ev_list[k][0] stc_file = op.abspath(basename + '_' + ev_list[k][0]) print '***' print 'stc dim ' + str(stc.shape) print '***' if not aseg: stc.save(stc_file) else: epochs = mne.Epochs(raw, events, event_id, t_min, t_max, picks=picks, baseline=(None, 0), reject=reject) stc = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=None) print '***' print 'len stc %d' % len(stc) print '***' elif is_epoched and event_id is None: stc = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=None) print '***' print 'len stc %d' % len(stc) print '***' else: stc = apply_inverse_raw(raw, inverse_operator, lambda2, inv_method, label=None, start=None, stop=None, buffer_size=1000, pick_ori=None) # None 'normal' print '***' print 'stc dim ' + str(stc.shape) print '***' if save_stc: if aseg: for i in range(len(stc)): try: os.mkdir(op.join(subj_path, 'TS')) except OSError: pass stc_file = op.join(subj_path, 'TS', basename + '_' + inv_method + '_stc_' + str(i) + '.npy') if not op.isfile(stc_file): np.save(stc_file, stc[i].data) labels_cortex = mne.read_labels_from_annot(sbj_id, parc=parc, subjects_dir=sbj_dir) if is_blind: for l in labels_cortex: if l.name in labels_removed: print l.name labels_cortex.remove(l) print '\n*** %d ***\n' % len(labels_cortex) src = inverse_operator['src'] # allow_empty : bool -> Instead of emitting an error, return all-zero time # courses for labels that do not have any vertices in the source estimate label_ts = mne.extract_label_time_course(stc, labels_cortex, src, mode='mean', allow_empty=True, return_generator=False) # save results in .npy file that will be the input for spectral node print '\n*** SAVE ROI TS ***\n' print len(label_ts) ts_file = op.abspath(basename + '_ROI_ts.npy') np.save(ts_file, label_ts) if aseg: print sbj_id labels_aseg = get_volume_labels_from_src(src, sbj_id, sbj_dir) labels = labels_cortex + labels_aseg else: labels = labels_cortex print labels[0].pos print len(labels) labels_file = op.abspath('labels.dat') with open(labels_file, "wb") as f: pickle.dump(len(labels), f) for value in labels: pickle.dump(value, f) label_names_file = op.abspath('label_names.txt') label_coords_file = op.abspath('label_coords.txt') label_names = [] label_coords = [] for value in labels: label_names.append(value.name) # label_coords.append(value.pos[0]) label_coords.append(np.mean(value.pos, axis=0)) np.savetxt(label_names_file, np.array(label_names, dtype=str), fmt="%s") np.savetxt(label_coords_file, np.array(label_coords, dtype=float), fmt="%f %f %f") return ts_file, labels_file, label_names_file, label_coords_file
# contruct two types of inverse solution: one based on baseline data (before the red square appears), and one based on blank data cov_blank = mne.compute_covariance(epochs_ds['STB'], tmin=0, tmax=None, method='auto') inv_blank = make_inverse_operator(epochs_ds.info, forward, cov_blank, loose=0.2, depth=0.8) blank_idx = np.nonzero(epochs_ds.events[:, 2] == 15)[0] epochs_ds.drop_epochs(blank_idx) cov_base = mne.compute_covariance(epochs_ds, tmin=None, tmax=0, method='auto') inv_base = make_inverse_operator(epochs_ds.info, forward, cov_base, loose=0.2, depth=0.8) vertices_to = [np.arange(10242), np.arange(10242)] vertices_from = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] morph_mat = mne.compute_morph_matrix(subj, 'fsaverage', vertices_from, vertices_to) for c in range(len(conds)): # start with the simplest method, MNE + dSPM stc = apply_inverse(evoked_ds[c], inv_base, lambda2, method) stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to, morph_mat) fname = out_dir + '%s_%s_dSPM_base_clean' % (subj, conds[c]) stc.save(fname) stc = apply_inverse(evoked_ds[c], inv_blank, lambda2, method) stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to, morph_mat) fname = out_dir + '%s_%s_dSPM_blank_clean' % (subj, conds[c]) stc.save(fname) # the next estimate is LCMV beamformer in time data_cov = mne.compute_covariance(epochs_ds[conds[c]], tmin=0, tmax=None, method='shrunk') stc = lcmv(evoked_ds[c], forward, cov_blank, data_cov, reg=0.01, pick_ori='max-power')
def _real_vec_stc(): inv = read_inverse_operator(fname_inv_surf) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0].crop(0, 0.01) return apply_inverse(evoked, inv, pick_ori='vector')
data_path = sample.data_path() subjects_dir = data_path + '/subjects' # Read evoked data fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) # Read inverse solution fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' inv = read_inverse_operator(fname_inv) # Apply inverse solution, set pick_ori='vector' to obtain a # :class:`mne.VectorSourceEstimate` object snr = 3.0 lambda2 = 1.0 / snr**2 stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector') # Use peak getter to move visualization to the time point of the peak magnitude _, peak_time = stc.magnitude().get_peak(hemi='lh') ############################################################################### # Plot the source estimate: brain = stc.plot(initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir) ############################################################################### # Plot the activation in the direction of maximal power for this data: stc_max, directions = stc.project('pca', src=inv['src']) # These directions must by design be close to the normals because this # inverse was computed with loose=0.2: print('Absolute cosine similarity between source normals and directions: '
brain_gen = stc_gen.plot(clim=clim, figure=figs, **kwargs) ############################################################################### # Simulate sensor-space signals # ----------------------------- # # Use the forward solution and add Gaussian noise to simulate sensor-space # (evoked) data from the known source-space signals. The amount of noise is # controlled by `nave` (higher values imply less noise). # evoked_gen = simulate_evoked(fwd, stc_gen, evoked.info, cov, nave, random_state=seed) # Map the simulated sensor-space data to source-space using the inverse # operator. stc_inv = apply_inverse(evoked_gen, inv_op, lambda2, method=method) ############################################################################### # Plot the point-spread of corrupted signal # ----------------------------------------- # # Notice that after applying the forward- and inverse-operators to the known # point sources that the point sources have spread across the source-space. # This spread is due to the minimum norm solution so that the signal leaks to # nearby vertices with similar orientations so that signal ends up crossing the # sulci and gyri. figs = [mlab.figure(5), mlab.figure(6), mlab.figure(7), mlab.figure(8)] brain_inv = stc_inv.plot(figure=figs, **kwargs) ############################################################################### # Exercises
def _real_vec_stc(): inv = read_inverse_operator(fname_inv) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0].crop(0, 0.01) return apply_inverse(evoked, inv, pick_ori='vector')
data_path = sample.data_path() fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Load data evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method) stc.crop(0.0, 0.2) # Export result as a 4D nifti object img = stc.as_volume(src, mri_resolution=False) # set True for full MRI resolution # Save it as a nifti file nib.save(img, 'mne_%s_inverse.nii.gz' % method) data = img.get_data() # Plot result (one slice) coronal_slice = data[:, 10, :, 60] plt.close('all') plt.imshow(np.ma.masked_less(coronal_slice, 8), cmap=plt.cm.Reds,
evoked = epochs.average() # Compute inverse solution and stcs for each epoch # Use the same inverse operator as with evoked data (i.e., set nave) # If you use a different nave, dSPM just scales by a factor sqrt(nave) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, label, pick_ori="normal", nave=evoked.nave) stc_evoked = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori="normal") stc_evoked_label = stc_evoked.in_label(label) # Mean across trials but not across vertices in label mean_stc = sum(stcs) / len(stcs) # compute sign flip to avoid signal cancellation when averaging signed values flip = mne.label_sign_flip(label, inverse_operator['src']) label_mean = np.mean(mean_stc.data, axis=0) label_mean_flip = np.mean(flip[:, np.newaxis] * mean_stc.data, axis=0) # Get inverse solution by inverting evoked data
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation""" # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file loose = None depth = 0.9 evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.crop(tmin=-0.05, tmax=0.2) evoked_l21 = evoked.copy() evoked_l21.crop(tmin=0.08, tmax=0.1) label = read_label(fname_label) forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked_l21.info, forward, cov, loose=loose, depth=depth, fixed=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. weights_min = 0.5 # MxNE tests alpha = 70 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=500, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='prox') stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=500, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd') stc_bcd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=500, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='bcd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_bcd.times, evoked_l21.times, 5) assert_allclose(stc_prox.data, stc_cd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_prox.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_cd.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert_true(stc_prox.vertices[1][0] in label.vertices) assert_true(stc_cd.vertices[1][0] in label.vertices) assert_true(stc_bcd.vertices[1][0] in label.vertices) stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=500, tol=1e-8, active_set_size=10, return_residual=True, solver='cd') assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert_true(stc.vertices[1][0] in label.vertices) # irMxNE tests stc = mixed_norm(evoked_l21, forward, cov, alpha, n_mxne_iter=5, loose=loose, depth=depth, maxit=500, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert_true(stc.vertices[1][0] in label.vertices) assert_equal(stc.vertices, [[63152], [79017]]) # Do with TF-MxNE for test memory savings alpha_space = 60. # spatial regularization parameter alpha_time = 1. # temporal regularization parameter stc, _ = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked.times, 5) assert_true(stc.vertices[1][0] in label.vertices)
cov = mne.cov.regularize(cov, evoked.info) import matplotlib.pyplot as plt plt.figure() ylim = dict(eeg=[-10, 10], grad=[-400, 400], mag=[-600, 600]) evoked.plot(ylim=ylim, proj=True) ############################################################################### # Run solver alpha = 70 # regularization parameter between 0 and 100 (100 is high) loose, depth = 0.2, 0.9 # loose orientation & depth weighting # Compute dSPM solution to be used as weights in MxNE inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=None, depth=depth, fixed=True) stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9., method='dSPM') # Compute MxNE inverse solution stc, residual = mixed_norm(evoked, forward, cov, alpha, loose=loose, depth=depth, maxit=3000, tol=1e-4, active_set_size=10, debias=True, weights=stc_dspm, weights_min=8., return_residual=True) plt.figure() residual.plot(ylim=ylim, proj=True) ############################################################################### # View in 2D and 3D ("glass" brain like 3D plot) plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1), opacity=0.1, fig_name="MxNE (cond %s)" % setno)
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
evoked2_fname = data_path + 'ave_projon/9367_s5_Noun_Place_All-ave.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) inverse_operator = read_inverse_operator(fname_inv) sample_vertices = [s['vertno'] for s in inverse_operator['src']] # Let's average and compute inverse, resampling to speed things up #evoked1 = epochs1.average() evoked1 = mne.read_evokeds(evoked1_fname, condition = 'epochs_TaggedWord') print evoked1 print print inverse_operator #evoked1.resample(50) condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method) #evoked2 = epochs2.average() evoked2 = mne.read_evokeds(evoked2_fname, condition = 'epochs_TaggedWord') print evoked1 print print inverse_operator #evoked2.resample(50) condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method) # Let's only deal with t > 0, cropping to reduce multiple comparisons condition1.crop(0, None) condition2.crop(0, None) tmin = condition1.tmin tstep = condition1.tstep #
def estimate_source_localization(fname_data, fname_inv, subject, snr=3.0, method="dSPM", fnout_src_loc=None, fnout_mov=None, verbose=None, show=True): """"Estimates source localization for the given data set and visualize results.""" print ">>>> performing source localization using " + method + "..." # estimate lambda square lambda2 = 1. / snr**2 # read in inverse operator inverse_operator = min_norm.read_inverse_operator(fname_inv) # read in data set for source localization data = mne.fiff.Evoked(fname_data) # perform real source localization src_loc = min_norm.apply_inverse(data, inverse_operator, lambda2, method=method, pick_ori=None) # save results if desired if fnout_src_loc is not None: src_loc.save(fnout_src_loc) # show results if desired if show is not None: subjects_dir = os.environ.get('SUBJECTS_DIR') brain = src_loc.plot(surface='inflated', hemi='both', subjects_dir=subjects_dir, config_opts={'cortex': 'bone'}, time_viewer=True) # create movie of activation if fnout_mov is not None: print ">>>> create movie of activations..." # check which method should be used if method == "dSPM": method_mov = " --spm" elif method == "sLORETA": method_mov = " --sLORETA" else: method_mov = "" os.system("mne_make_movie " + \ "--inv " + fname_inv + \ " --meas " + fname_data + \ " --subject " + subject + \ " --mov " + fnout_mov + \ method_mov + \ " --smooth 10 --surface inflated" + \ " --tmin 0 --tmax 150" + \ " --width 1920 --height 1200 --noscalebar" " --alpha 0.5 --view lat" + \ " --fthresh 5 --fmid 10 --fmax 15")
fname_inv = meg_path / 'sample_audvis-meg-oct-6-meg-inv.fif' snr = 3.0 lambda2 = 1.0 / snr**2 method = "dSPM" # use dSPM method (could also be MNE, sLORETA, or eLORETA) inverse_operator = read_inverse_operator(fname_inv) # we'll only use one hemisphere to speed up this example # instead of a second vertex array we'll pass an empty array sample_vertices = [inverse_operator['src'][0]['vertno'], np.array([], int)] # Let's average and compute inverse, then resample to speed things up conditions = [] for cond in ['l_aud', 'r_aud', 'l_vis', 'r_vis']: # order is important evoked = epochs[cond].average() evoked.resample(30).crop(0., None) condition = apply_inverse(evoked, inverse_operator, lambda2, method) # Let's only deal with t > 0, cropping to reduce multiple comparisons condition.crop(0, None) conditions.append(condition) tmin = conditions[0].tmin tstep = conditions[0].tstep * 1000 # convert to milliseconds # %% # Transform to common cortical space # ---------------------------------- # # Normally you would read in estimates across several subjects and morph them # to the same cortical space (e.g. fsaverage). For example purposes, we will # simulate this by just having each "subject" have the same response (just # noisy in source space) here.
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation""" # Handling forward solution evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file setno = 0 loose = None depth = 0.9 evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0)) evoked.crop(tmin=-0.1, tmax=0.4) evoked_l21 = copy.deepcopy(evoked) evoked_l21.crop(tmin=0.08, tmax=0.1) label = read_label(fname_label) weights_min = 0.5 forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=loose, depth=depth, fixed=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. # MxNE tests alpha = 60 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='prox') stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_prox.data, stc_cd.data, 5) assert_true(stc_prox.vertno[1][0] in label.vertices) assert_true(stc_cd.vertno[1][0] in label.vertices) stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=depth, maxit=500, tol=1e-4, active_set_size=10, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert_true(stc.vertno[1][0] in label.vertices) # Do with TF-MxNE for test memory savings alpha_space = 60. # spatial regularization parameter alpha_time = 1. # temporal regularization parameter stc, _ = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked.times, 5) assert_true(stc.vertno[1][0] in label.vertices)
# alpha_space regularization parameter is between 0 and 100 (100 is high) alpha_space = 50. # spatial regularization parameter # alpha_time parameter promotes temporal smoothness # (0 means no temporal regularization) alpha_time = 1. # temporal regularization parameter loose, depth = 0.2, 0.9 # loose orientation & depth weighting # Compute dSPM solution to be used as weights in MxNE inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=loose, depth=depth) stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9., method='dSPM') # Compute TF-MxNE inverse solution stc, residual = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time, loose=loose, depth=depth, maxit=200, tol=1e-4, weights=stc_dspm, weights_min=8., debias=True,
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation.""" # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file loose = 0.0 depth = 0.9 evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.crop(tmin=-0.05, tmax=0.2) evoked_l21 = evoked.copy() evoked_l21.crop(tmin=0.081, tmax=0.1) label = read_label(fname_label) forward = read_forward_solution(fname_fwd) forward = convert_forward_solution(forward, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked_l21.info, forward, cov, loose=loose, depth=depth, fixed=True, use_cps=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. weights_min = 0.5 # MxNE tests alpha = 70 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='prox') with pytest.warns(None): # CD stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd', pca=False) # pca=False deprecated, doesn't matter stc_bcd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='bcd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_bcd.times, evoked_l21.times, 5) assert_allclose(stc_prox.data, stc_cd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_prox.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_cd.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert stc_prox.vertices[1][0] in label.vertices assert stc_cd.vertices[1][0] in label.vertices assert stc_bcd.vertices[1][0] in label.vertices with pytest.warns(None): # CD dips = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd', return_as_dipoles=True) stc_dip = make_stc_from_dipoles(dips, forward['src']) assert isinstance(dips[0], Dipole) assert stc_dip.subject == "sample" _check_stcs(stc_cd, stc_dip) with pytest.warns(None): # CD stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, return_residual=True, solver='cd') assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert stc.vertices[1][0] in label.vertices # irMxNE tests with pytest.warns(None): # CD stc = mixed_norm(evoked_l21, forward, cov, alpha, n_mxne_iter=5, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert stc.vertices[1][0] in label.vertices assert stc.vertices == [[63152], [79017]] # Do with TF-MxNE for test memory savings alpha = 60. # overall regularization parameter l1_ratio = 0.01 # temporal regularization proportion stc, _ = tf_mixed_norm(evoked, forward, cov, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True, alpha=alpha, l1_ratio=l1_ratio) assert_array_almost_equal(stc.times, evoked.times, 5) assert stc.vertices[1][0] in label.vertices pytest.raises(ValueError, tf_mixed_norm, evoked, forward, cov, alpha=101, l1_ratio=0.03) pytest.raises(ValueError, tf_mixed_norm, evoked, forward, cov, alpha=50., l1_ratio=1.01)
evoked.decimate(10, verbose='error') ############################################################################### # Then, we can load the precomputed inverse operator from a file. fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' inv = read_inverse_operator(fname_inv) src = inv['src'] mri_head_t = inv['mri_head_t'] ############################################################################### # The source estimate is computed using the inverse operator and the # sensor-space data. snr = 3.0 lambda2 = 1.0 / snr**2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) stc = apply_inverse(evoked, inv, lambda2, method) del inv ############################################################################### # This time, we have a different container # (:class:`VolSourceEstimate <mne.VolSourceEstimate>`) for the source time # course. print(stc) ############################################################################### # This too comes with a convenient plot method. stc.plot(src, subject='sample', subjects_dir=subjects_dir) ############################################################################### # For this visualization, ``nilearn`` must be installed. # This visualization is interactive. Click on any of the anatomical slices
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) evoked.pick_types(meg=True, eeg=False) ############################################################################### # Then, we can load the precomputed inverse operator from a file. fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' inv = read_inverse_operator(fname_inv) src = inv['src'] ############################################################################### # The source estimate is computed using the inverse operator and the # sensor-space data. snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) stc = apply_inverse(evoked, inv, lambda2, method) stc.crop(0.0, 0.2) ############################################################################### # This time, we have a different container # (:class:`VolSourceEstimate <mne.VolSourceEstimate>`) for the source time # course. print(stc) ############################################################################### # This too comes with a convenient plot method. stc.plot(src, subject='sample', subjects_dir=subjects_dir) ############################################################################### # For this visualization, ``nilearn`` must be installed.
# have just recorded this from a real subject and are going to study what parts # of the brain communicate with each other. # # First, we'll create a source estimate of the MEG data. We'll use both a # straightforward MNE-dSPM inverse solution for this, and the DICS beamformer # which is specifically designed to work with oscillatory data. ############################################################################### # Computing the inverse using MNE-dSPM: # Compute the inverse operator fwd = mne.read_forward_solution(fwd_fname) inv = make_inverse_operator(epochs.info, fwd, cov) # Apply the inverse model to the trial that also contains the signal. s = apply_inverse(epochs['signal'].average(), inv) # Take the root-mean square along the time dimension and plot the result. s_rms = np.sqrt((s**2).mean()) brain = s_rms.plot('sample', subjects_dir=subjects_dir, hemi='both', figure=1, size=600) # Indicate the true locations of the source activity on the plot. brain.add_foci(vertices[0][0], coords_as_verts=True, hemi='lh') brain.add_foci(vertices[1][0], coords_as_verts=True, hemi='rh') # Rotate the view and add a title. mlab.view(0, 0, 550, [0, 0, 0])
evoked = mne.read_evokeds(fname_evoked, condition=condition, baseline=(None, 0)) noise_cov = mne.read_cov(fname_cov) # Compute inverse solution and for each epoch snr = 3.0 # use smaller SNR for raw data inv_method = 'dSPM' # sLORETA, MNE, dSPM parc = 'aparc' # the parcellation to use, e.g., 'aparc' 'aparc.a2009s' lambda2 = 1.0 / snr ** 2 # Compute inverse operator inverse_operator = make_inverse_operator(evoked.info, fwd, noise_cov, depth=None, fixed=False) stc = apply_inverse(evoked, inverse_operator, lambda2, inv_method, pick_ori=None) # Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi labels_parc = mne.read_labels_from_annot( subject, parc=parc, subjects_dir=subjects_dir) ############################################################################### # Average the source estimates within each label of the cortical parcellation # and each sub structure contained in the src space src = inverse_operator['src'] label_ts = mne.extract_label_time_course( [stc], labels_parc, src, mode='mean', allow_empty=True) # plot the times series of 2 labels
def test_lcmv_vector(): """Test vector LCMV solutions.""" info = mne.io.read_raw_fif(fname_raw).info # For speed and for rank-deficiency calculation simplicity, # just use grads info = mne.pick_info(info, mne.pick_types(info, meg='grad', exclude=())) info.update(bads=[], projs=[]) forward = mne.read_forward_solution(fname_fwd) forward = mne.pick_channels_forward(forward, info['ch_names']) vertices = [s['vertno'][::100] for s in forward['src']] n_vertices = sum(len(v) for v in vertices) assert 5 < n_vertices < 20 amplitude = 100e-9 stc = mne.SourceEstimate(amplitude * np.eye(n_vertices), vertices, 0, 1. / info['sfreq']) forward_sim = mne.convert_forward_solution(forward, force_fixed=True, use_cps=True, copy=True) forward_sim = mne.forward.restrict_forward_to_stc(forward_sim, stc) noise_cov = mne.make_ad_hoc_cov(info) noise_cov.update(data=np.diag(noise_cov['data']), diag=False) evoked = simulate_evoked(forward_sim, stc, info, noise_cov, nave=1) source_nn = forward_sim['source_nn'] source_rr = forward_sim['source_rr'] # Figure out our indices mask = np.concatenate([np.in1d(s['vertno'], v) for s, v in zip(forward['src'], vertices)]) mapping = np.where(mask)[0] assert_array_equal(source_rr, forward['source_rr'][mapping]) # Don't check NN because we didn't rotate to surf ori del forward_sim # Let's do minimum norm as a sanity check (dipole_fit is slower) inv = make_inverse_operator(info, forward, noise_cov, loose=1.) stc_vector_mne = apply_inverse(evoked, inv, pick_ori='vector') mne_ori = stc_vector_mne.data[mapping, :, np.arange(n_vertices)] mne_ori /= np.linalg.norm(mne_ori, axis=-1)[:, np.newaxis] mne_angles = np.rad2deg(np.arccos(np.sum(mne_ori * source_nn, axis=-1))) assert np.mean(mne_angles) < 35 # Now let's do LCMV data_cov = mne.make_ad_hoc_cov(info) # just a stub for later with pytest.raises(ValueError, match="pick_ori"): make_lcmv(info, forward, data_cov, 0.05, noise_cov, pick_ori='bad') lcmv_ori = list() for ti in range(n_vertices): this_evoked = evoked.copy().crop(evoked.times[ti], evoked.times[ti]) data_cov['data'] = (np.outer(this_evoked.data, this_evoked.data) + noise_cov['data']) vals = linalg.svdvals(data_cov['data']) assert vals[0] / vals[-1] < 1e5 # not rank deficient with catch_logging() as log: filters = make_lcmv(info, forward, data_cov, 0.05, noise_cov, verbose=True) log = log.getvalue() assert '498 sources' in log with catch_logging() as log: filters_vector = make_lcmv(info, forward, data_cov, 0.05, noise_cov, pick_ori='vector', verbose=True) log = log.getvalue() assert '498 sources' in log stc = apply_lcmv(this_evoked, filters) stc_vector = apply_lcmv(this_evoked, filters_vector) assert isinstance(stc, mne.SourceEstimate) assert isinstance(stc_vector, mne.VectorSourceEstimate) assert_allclose(stc.data, stc_vector.magnitude().data) # Check the orientation by pooling across some neighbors, as LCMV can # have some "holes" at the points of interest idx = np.where(cdist(forward['source_rr'], source_rr[[ti]]) < 0.02)[0] lcmv_ori.append(np.mean(stc_vector.data[idx, :, 0], axis=0)) lcmv_ori[-1] /= np.linalg.norm(lcmv_ori[-1]) lcmv_angles = np.rad2deg(np.arccos(np.sum(lcmv_ori * source_nn, axis=-1))) assert np.mean(lcmv_angles) < 55
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) inverse_operator = read_inverse_operator(fname_inv) # we'll only use one hemisphere to speed up this example # instead of a second vertex array we'll pass an empty array sample_vertices = [inverse_operator['src'][0]['vertno'], np.array([], int)] # Let's average and compute inverse, then resample to speed things up conditions = [] for cond in ['l_aud', 'r_aud', 'l_vis', 'r_vis']: # order is important evoked = epochs[cond].average() evoked.resample(50) condition = apply_inverse(evoked, inverse_operator, lambda2, method) # Let's only deal with t > 0, cropping to reduce multiple comparisons condition.crop(0, None) conditions.append(condition) tmin = conditions[0].tmin tstep = conditions[0].tstep ############################################################################### # Transform to common cortical space # Normally you would read in estimates across several subjects and morph # them to the same cortical space (e.g. fsaverage). For example purposes, # we will simulate this by just having each "subject" have the same # response (just noisy in source space) here.
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' snr = 3.0 lambda2 = 1.0 / snr**2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Load data evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori=None) # Save result in stc files stc.save('mne_%s_inverse' % method) ############################################################################### # View activation time-series plt.plot(1e3 * stc.times, stc.data[::100, :].T) plt.xlabel('time (ms)') plt.ylabel('%s value' % method) plt.show() # Plot brain in 3D with PySurfer if available brain = stc.plot(surface='inflated', hemi='rh', subjects_dir=subjects_dir,