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 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 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 fiff_mne(ds, fwd='{fif}*fwd.fif', cov='{fif}*cov.fif', label=None, name=None, tstart= -0.1, tstop=0.6, baseline=(None, 0)): """ adds data from one label as """ if name is None: if label: _, lbl = os.path.split(label) lbl, _ = os.path.splitext(lbl) name = lbl.replace('-', '_') else: name = 'stc' info = ds.info['info'] raw = ds.info['raw'] fif_name = raw.info['filename'] fif_name, _ = os.path.splitext(fif_name) if fif_name.endswith('raw'): fif_name = fif_name[:-3] fwd = fwd.format(fif=fif_name) if '*' in fwd: d, n = os.path.split(fwd) names = fnmatch.filter(os.listdir(d), n) if len(names) == 1: fwd = os.path.join(d, names[0]) else: raise IOError("No unique fwd file matching %r" % fwd) cov = cov.format(fif=fif_name) if '*' in cov: d, n = os.path.split(cov) names = fnmatch.filter(os.listdir(d), n) if len(names) == 1: cov = os.path.join(d, names[0]) else: raise IOError("No unique cov file matching %r" % cov) fwd = mne.read_forward_solution(fwd, force_fixed=False, surf_ori=True) cov = mne.Covariance(cov) inv = _mn.make_inverse_operator(info, fwd, cov, loose=0.2, depth=0.8) epochs = mne_Epochs(ds, tstart=tstart, tstop=tstop, baseline=baseline) # mne example: snr = 3.0 lambda2 = 1.0 / snr ** 2 if label is not None: label = mne.read_label(label) stcs = _mn.apply_inverse_epochs(epochs, inv, lambda2, dSPM=False, label=label) x = np.vstack(s.data.mean(0) for s in stcs) s = stcs[0] dims = ('case', var(s.times, 'time'),) ds[name] = ndvar(x, dims, properties=None, info='') return stcs
def calc_inverse_operator(events_id, epochs_fn, fwd_sub_fn, inv_fn, min_crop_t=None, max_crop_t=0): for cond in events_id.keys(): epochs = mne.read_epochs(epochs_fn.format(cond=cond)) noise_cov = mne.compute_covariance(epochs.crop(min_crop_t, max_crop_t, copy=True)) forward_sub = mne.read_forward_solution(fwd_sub_fn.format(cond=cond)) inverse_operator_sub = make_inverse_operator(epochs.info, forward_sub, noise_cov, loose=None, depth=None) write_inverse_operator(inv_fn.format(cond=cond), inverse_operator_sub)
def test_inverse_ctf_comp(): """Test interpolation with compensated CTF data.""" raw = mne.io.read_raw_ctf(fname_raw_ctf).crop(0, 0) raw.apply_gradient_compensation(1) sphere = make_sphere_model() cov = make_ad_hoc_cov(raw.info) src = mne.setup_volume_source_space( pos=dict(rr=[[0., 0., 0.01]], nn=[[0., 1., 0.]])) fwd = make_forward_solution(raw.info, None, src, sphere, eeg=False) raw.apply_gradient_compensation(0) with pytest.raises(RuntimeError, match='Compensation grade .* not match'): make_inverse_operator(raw.info, fwd, cov, loose=1.) raw.apply_gradient_compensation(1) inv = make_inverse_operator(raw.info, fwd, cov, loose=1.) apply_inverse_raw(raw, inv, 1. / 9.) # smoke test raw.apply_gradient_compensation(0) with pytest.raises(RuntimeError, match='Compensation grade .* not match'): apply_inverse_raw(raw, inv, 1. / 9.)
def test_make_inverse_operator_vector(evoked, noise_cov): """Test MNE inverse computation (vector result).""" fwd_surf = read_forward_solution_meg(fname_fwd, surf_ori=True) fwd = read_forward_solution_meg(fname_fwd, surf_ori=False) # Make different version of the inverse operator inv_1 = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1) inv_2 = make_inverse_operator(evoked.info, fwd_surf, noise_cov, depth=None, use_cps=True) inv_3 = make_inverse_operator(evoked.info, fwd_surf, noise_cov, fixed=True, use_cps=True) inv_4 = make_inverse_operator(evoked.info, fwd, noise_cov, loose=.2, depth=None) # Apply the inverse operators and check the result for ii, inv in enumerate((inv_1, inv_2, inv_4)): # Don't do eLORETA here as it will be quite slow methods = ['MNE', 'dSPM', 'sLORETA'] if ii < 2 else ['MNE'] for method in methods: stc = apply_inverse(evoked, inv, method=method) stc_vec = apply_inverse(evoked, inv, pick_ori='vector', method=method) assert_allclose(stc.data, stc_vec.magnitude().data) # Vector estimates don't work when using fixed orientations with pytest.raises(RuntimeError, match='fixed orientation'): apply_inverse(evoked, inv_3, pick_ori='vector') # When computing with vector fields, computing the difference between two # evokeds and then performing the inverse should yield the same result as # computing the difference between the inverses. evoked0 = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked0.crop(0, 0.2) evoked1 = read_evokeds(fname_data, condition=1, baseline=(None, 0)) evoked1.crop(0, 0.2) diff = combine_evoked((evoked0, evoked1), [1, -1]) stc_diff = apply_inverse(diff, inv_1, method='MNE') stc_diff_vec = apply_inverse(diff, inv_1, method='MNE', pick_ori='vector') stc_vec0 = apply_inverse(evoked0, inv_1, method='MNE', pick_ori='vector') stc_vec1 = apply_inverse(evoked1, inv_1, method='MNE', pick_ori='vector') assert_allclose(stc_diff_vec.data, (stc_vec0 - stc_vec1).data, atol=1e-20) assert_allclose(stc_diff.data, (stc_vec0 - stc_vec1).magnitude().data, atol=1e-20)
def run(): args = sys.argv if len(args) <= 1: print 'Usage: run_anatomy_tutorial.sh <sample data directory>' return sample_dir = args[1] subjects_dir = join(sample_dir, 'subjects') meg_dir = join(sample_dir, 'MEG', 'sample') os.environ['SUBJECTS_DIR'] = subjects_dir os.environ['MEG_DIR'] = meg_dir subject = 'sample' bem = join(subjects_dir, subject, 'bem', 'sample-5120-bem-sol.fif') mri = join(subjects_dir, subject, 'mri', 'T1.mgz') fname = join(subjects_dir, subject, 'bem', 'volume-7mm-src.fif') src = setup_volume_source_space(subject, fname=fname, pos=7, mri=mri, bem=bem, overwrite=True, subjects_dir=subjects_dir) ############################################################################### # Compute forward solution a.k.a. lead field raw = mne.io.Raw(join(meg_dir, 'sample_audvis_raw.fif')) fwd_fname = join(meg_dir, 'sample_audvis-meg-vol-7-fwd.fif') trans = join(meg_dir, 'sample_audvis_raw-trans.fif') # for MEG only fwd = make_forward_solution(raw.info, trans=trans, src=src, bem=bem, fname=fwd_fname, meg=True, eeg=False, overwrite=True) # Make a sensitivity map smap = mne.sensitivity_map(fwd, ch_type='grad', mode='free') smap.save(join(meg_dir, 'sample_audvis-grad-vol-7-fwd-sensmap'), ftype='w') ############################################################################### # Compute MNE inverse operators # # Note: The MEG/EEG forward solution could be used for all # noise_cov = mne.read_cov(join(meg_dir, 'sample_audvis-cov.fif')) inv = make_inverse_operator(raw.info, fwd, noise_cov) fname = join(meg_dir, 'sample_audvis-meg-vol-7-meg-inv.fif') write_inverse_operator(fname, inv)
def compute_ts_inv_sol(raw, fwd_filename, cov_fname, snr, inv_method, aseg): """Compute ts inverse solution.""" import os.path as op import numpy as np import mne from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from nipype.utils.filemanip import split_filename as split_f print(('***** READ FWD SOL %s *****' % fwd_filename)) forward = mne.read_forward_solution(fwd_filename) # Convert to surface orientation for cortically constrained # inverse modeling if not aseg: forward = mne.convert_forward_solution(forward, surf_ori=True) lambda2 = 1.0 / snr**2 # compute inverse operator print('***** COMPUTE INV OP *****') inverse_operator = make_inverse_operator(raw.info, forward, cov_fname, loose=0.2, depth=0.8) # apply inverse operator to the time windows [t_start, t_stop]s # TEST t_start = 0 # sec t_stop = 3 # sec start, stop = raw.time_as_index([t_start, t_stop]) print(('***** APPLY INV OP ***** [%d %d]sec' % (t_start, t_stop))) stc = apply_inverse_raw(raw, inverse_operator, lambda2, inv_method, label=None, start=start, stop=stop, pick_ori=None) print('***') print(('stc dim ' + str(stc.shape))) print('***') subj_path, basename, ext = split_f(raw.info['filename']) data = stc.data print(('data dim ' + str(data.shape))) # save results in .npy file that will be the input for spectral node print('***** SAVE SOL *****') ts_file = op.abspath(basename + '.npy') np.save(ts_file, data) return ts_file
def test_volume_labels_morph(tmpdir, sl, n_real, n_mri, n_orig): """Test generating a source space from volume label.""" import nibabel as nib n_use = (sl.stop - sl.start) // (sl.step or 1) # 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') lut, _ = read_freesurfer_lut() label_names = sorted(get_volume_labels_from_aseg(aseg_fname)) use_label_names = label_names[sl] src = setup_volume_source_space('sample', subjects_dir=subjects_dir, volume_label=use_label_names, mri=aseg_fname) assert len(src) == n_use 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) assert img.shape == (86, 86, 86, 1) n_on = np.array(img.dataobj).astype(bool).sum() aseg_img = _get_img_fdata(nib.load(fname_aseg)) n_got_real = np.in1d(aseg_img.ravel(), [lut[name] for name in use_label_names]).sum() assert n_got_real == n_real # - This was 291 on `master` before gh-5590 # - Refactoring transforms it became 279 with a < 1e-8 change in vox_mri_t # - Dropped to 123 once nearest-voxel was used in gh-7653 # - Jumped back up to 330 with morphing fixes actually correctly # interpolating across all volumes assert aseg_img.shape == img.shape[:3] assert n_on == n_mri for ii in range(2): # should work with (ii=0) or without (ii=1) the interpolator if ii: src[0]['interpolator'] = None img = stc.as_volume(src, mri_resolution=False) n_on = np.array(img.dataobj).astype(bool).sum() # was 20 on `master` before gh-5590 # then 44 before gh-7653, which took it back to 20 assert n_on == n_orig # without the interpolator, this should fail assert src[0]['interpolator'] is None with pytest.raises(RuntimeError, match=r'.*src\[0\], .* mri_resolution'): stc.as_volume(src, mri_resolution=True)
def test_make_inverse_operator_fixed(evoked, noise_cov): """Test MNE inverse computation (fixed orientation).""" fwd = read_forward_solution_meg(fname_fwd) # can't make fixed inv with depth weighting without free ori fwd fwd_fixed = convert_forward_solution(fwd, force_fixed=True, use_cps=True) pytest.raises(ValueError, make_inverse_operator, evoked.info, fwd_fixed, noise_cov, depth=0.8, fixed=True) # now compare to C solution # note that the forward solution must not be surface-oriented # to get equivalence (surf_ori=True changes the normals) with catch_logging() as log: inv_op = make_inverse_operator( # test depth=0. alias for depth=None evoked.info, fwd, noise_cov, depth=0., fixed=True, use_cps=False, verbose=True) log = log.getvalue() assert 'MEG: rank 302 computed from 305' in log assert 'EEG channels: 0' in repr(inv_op) assert 'MEG channels: 305' in repr(inv_op) del fwd_fixed inverse_operator_nodepth = read_inverse_operator(fname_inv_fixed_nodepth) # XXX We should have this but we don't (MNE-C doesn't restrict info): # assert 'EEG channels: 0' in repr(inverse_operator_nodepth) assert 'MEG channels: 305' in repr(inverse_operator_nodepth) _compare_inverses_approx(inverse_operator_nodepth, inv_op, evoked, rtol=1e-5, atol=1e-4) # Inverse has 306 channels - 6 proj = 302 assert (compute_rank_inverse(inverse_operator_nodepth) == 302) # Now with depth fwd_surf = convert_forward_solution(fwd, surf_ori=True) # not fixed for kwargs, use_fwd in zip([dict(fixed=True), dict(loose=0.)], [fwd, fwd_surf]): # Should be equiv. inv_op_depth = make_inverse_operator( evoked.info, use_fwd, noise_cov, depth=0.8, use_cps=True, **kwargs) inverse_operator_depth = read_inverse_operator(fname_inv_fixed_depth) # Normals should be the adjusted ones assert_allclose(inverse_operator_depth['source_nn'], fwd_surf['source_nn'][2::3], atol=1e-5) _compare_inverses_approx(inverse_operator_depth, inv_op_depth, evoked, rtol=1e-3, atol=1e-4)
def test_localization_bias_free(bias_params_free, method, lower, upper, kwargs, depth, loose): """Test inverse localization bias for free minimum-norm solvers.""" evoked, fwd, noise_cov, _, want = bias_params_free inv_free = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1., depth=depth) loc = apply_inverse(evoked, inv_free, lambda2, method, pick_ori='vector', verbose='debug', **kwargs).data loc = np.linalg.norm(loc, axis=1) # Compute the percentage of sources for which there is no loc bias: perc = (want == np.argmax(loc, axis=0)).mean() * 100 assert lower <= perc <= upper, method
def test_localization_bias_fixed(bias_params_fixed, method, lower, upper, depth): """Test inverse localization bias for fixed minimum-norm solvers.""" evoked, fwd, noise_cov, _, want = bias_params_fixed fwd_use = convert_forward_solution(fwd, force_fixed=False) inv_fixed = make_inverse_operator(evoked.info, fwd_use, noise_cov, loose=0., depth=depth) loc = np.abs(apply_inverse(evoked, inv_fixed, lambda2, method, verbose='debug').data) # Compute the percentage of sources for which there is no loc bias: perc = (want == np.argmax(loc, axis=0)).mean() * 100 assert lower <= perc <= upper, method
def run_inverse(subject, session=None): deriv_path = config.get_subject_deriv_path(subject=subject, session=session, kind=config.get_kind()) bids_basename = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, recording=config.rec, space=config.space, prefix=deriv_path, extension='.fif', check=False) fname_ave = bids_basename.copy().update(kind='ave') fname_fwd = bids_basename.copy().update(kind='fwd') fname_cov = bids_basename.copy().update(kind='cov') fname_inv = bids_basename.copy().update(kind='inv') evokeds = mne.read_evokeds(fname_ave) cov = mne.read_cov(fname_cov) forward = mne.read_forward_solution(fname_fwd) info = evokeds[0].info inverse_operator = make_inverse_operator(info, forward, cov, loose=0.2, depth=0.8, rank='info') write_inverse_operator(fname_inv, inverse_operator) # Apply inverse snr = 3.0 lambda2 = 1.0 / snr**2 for condition, evoked in zip(config.conditions, evokeds): method = config.inverse_method pick_ori = None cond_str = condition.replace(op.sep, '').replace('_', '') inverse_str = method hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'. fname_stc = bids_basename.copy().update( kind=f'{cond_str}+{inverse_str}+{hemi_str}', extension=None) stc = apply_inverse(evoked=evoked, inverse_operator=inverse_operator, lambda2=lambda2, method=method, pick_ori=pick_ori) stc.save(fname_stc)
def run_inverse(subject, session=None): deriv_path = config.get_subject_deriv_path(subject=subject, session=session, kind=config.get_kind()) bids_basename = make_bids_basename(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, processing=config.proc, recording=config.rec, space=config.space) fname_ave = op.join(deriv_path, bids_basename + '-ave.fif') fname_fwd = op.join(deriv_path, bids_basename + '-fwd.fif') fname_cov = op.join(deriv_path, bids_basename + '-cov.fif') fname_inv = op.join(deriv_path, bids_basename + '-inv.fif') evokeds = mne.read_evokeds(fname_ave) cov = mne.read_cov(fname_cov) forward = mne.read_forward_solution(fname_fwd) info = evokeds[0].info inverse_operator = make_inverse_operator(info, forward, cov, loose=0.2, depth=0.8, rank='info') write_inverse_operator(fname_inv, inverse_operator) # Apply inverse snr = 3.0 lambda2 = 1.0 / snr**2 for condition, evoked in zip(config.conditions, evokeds): method = config.inverse_method pick_ori = None cond_str = 'cond-%s' % condition.replace(op.sep, '') inverse_str = 'inverse-%s' % method hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'. fname_stc = op.join( deriv_path, '_'.join([bids_basename, cond_str, inverse_str, hemi_str])) stc = apply_inverse(evoked=evoked, inverse_operator=inverse_operator, lambda2=lambda2, method=method, pick_ori=pick_ori) stc.save(fname_stc)
def test_localization_bias_loose(bias_params_fixed, method, lower, upper, depth, loose): """Test inverse localization bias for loose minimum-norm solvers.""" evoked, fwd, noise_cov, _, want = bias_params_fixed fwd = convert_forward_solution(fwd, surf_ori=False, force_fixed=False) assert not is_fixed_orient(fwd) inv_loose = make_inverse_operator(evoked.info, fwd, noise_cov, loose=loose, depth=depth) loc = apply_inverse(evoked, inv_loose, lambda2, method).data assert (loc >= 0).all() # Compute the percentage of sources for which there is no loc bias: perc = (want == np.argmax(loc, axis=0)).mean() * 100 assert lower <= perc <= upper, method
def mne_inv_operator(self, overwrite=False): from mne.minimum_norm import (read_inverse_operator, make_inverse_operator, write_inverse_operator) fname = self.subject + '_' + self.experiment + '_mne-inv.fif.gz' out_fname = op.join(self.out_srcData, fname) if op.exists(out_fname) and not overwrite: print('Reading inverse operator from file') self.inv = read_inverse_operator(out_fname) else: self.inv = make_inverse_operator(self.epochs.info, self.fwd, self.ncov, loose=0.2, depth=0.8) write_inverse_operator(out_fname, self.inv)
def test_make_inverse_operator_free(evoked, noise_cov): """Test MNE inverse computation (free orientation).""" fwd = read_forward_solution_meg(fname_fwd) fwd_surf = convert_forward_solution(fwd, surf_ori=True) fwd_fixed = convert_forward_solution(fwd, force_fixed=True, use_cps=True) # can't make free inv with fixed fwd with pytest.raises(ValueError, match='can only be used'): make_inverse_operator(evoked.info, fwd_fixed, noise_cov, depth=None) # for depth=None (or depth=0.8), surf_ori of the fwd should not matter inv_surf = make_inverse_operator(evoked.info, fwd_surf, noise_cov, depth=None, loose=1.) inv = make_inverse_operator(evoked.info, fwd, noise_cov, depth=None, loose=1.) _compare_inverses_approx(inv, inv_surf, evoked, rtol=1e-5, atol=1e-8, check_nn=False, check_K=False) for pick_ori in (None, 'vector', 'normal'): stc = apply_inverse(evoked, inv, pick_ori=pick_ori) stc_surf = apply_inverse(evoked, inv_surf, pick_ori=pick_ori) assert_allclose(stc_surf.data, stc.data, atol=1e-2)
def _gen_mne(active_cov, baseline_cov, common_cov, fwd, info, method='dSPM'): inverse_operator = make_inverse_operator(info, fwd, common_cov) stc_act = apply_inverse_cov(active_cov, info, inverse_operator, method=method, verbose=True) stc_base = apply_inverse_cov(baseline_cov, info, inverse_operator, method=method, verbose=True) stc_act /= stc_base return stc_act
def test_make_inverse_operator_diag(evoked, noise_cov): """Test MNE inverse computation with diagonal noise cov.""" noise_cov = noise_cov.as_diag() fwd_op = convert_forward_solution(read_forward_solution(fname_fwd), surf_ori=True) inv_op = make_inverse_operator(evoked.info, fwd_op, noise_cov, loose=0.2, depth=0.8) _compare_io(inv_op) inverse_operator_diag = read_inverse_operator(fname_inv_meeg_diag) # This one is pretty bad _compare_inverses_approx(inverse_operator_diag, inv_op, evoked, rtol=1e-1, atol=1e-1, ctol=0.99, check_K=False) # Inverse has 366 channels - 6 proj = 360 assert (compute_rank_inverse(inverse_operator_diag) == 360)
def test_make_inverse_operator_bads(evoked, noise_cov): """Test MNE inverse computation given a mismatch of bad channels.""" fwd_op = read_forward_solution_meg(fname_fwd, surf_ori=True) assert evoked.info['bads'] == noise_cov['bads'] assert evoked.info['bads'] == fwd_op['info']['bads'] + ['EEG 053'] # one fewer bad in evoked than cov bad = evoked.info['bads'].pop() inv_ = make_inverse_operator(evoked.info, fwd_op, noise_cov, loose=1.) union_good = set(noise_cov['names']) & set(evoked.ch_names) union_bads = set(noise_cov['bads']) & set(evoked.info['bads']) evoked.info['bads'].append(bad) assert len(set(inv_['info']['ch_names']) - union_good) == 0 assert len(set(inv_['info']['bads']) - union_bads) == 0
def run_inverse(subject, session=None): bids_path = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, recording=config.rec, space=config.space, extension='.fif', datatype=config.get_datatype(), root=config.deriv_root, check=False) fname_ave = bids_path.copy().update(suffix='ave') fname_fwd = bids_path.copy().update(suffix='fwd') fname_cov = bids_path.copy().update(suffix='cov') fname_inv = bids_path.copy().update(suffix='inv') evokeds = mne.read_evokeds(fname_ave) cov = mne.read_cov(fname_cov) forward = mne.read_forward_solution(fname_fwd) info = evokeds[0].info inverse_operator = make_inverse_operator(info, forward, cov, loose=0.2, depth=0.8, rank='info') write_inverse_operator(fname_inv, inverse_operator) # Apply inverse snr = 3.0 lambda2 = 1.0 / snr ** 2 for condition, evoked in zip(config.conditions, evokeds): method = config.inverse_method pick_ori = None cond_str = config.sanitize_cond_name(condition) inverse_str = method hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'. fname_stc = bids_path.copy().update( suffix=f'{cond_str}+{inverse_str}+{hemi_str}', extension=None) if "eeg" in config.ch_types: evoked.set_eeg_reference('average', projection=True) stc = apply_inverse(evoked=evoked, inverse_operator=inverse_operator, lambda2=lambda2, method=method, pick_ori=pick_ori) stc.save(fname_stc)
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_highpass-%sHz-ave.fif' % (subject, l_freq)) fname_cov = op.join(data_path, '%s_highpass-%sHz-cov.fif' % (subject, l_freq)) fname_fwd = op.join(data_path, '%s-meg-eeg-%s-fwd.fif' % (subject, spacing)) fname_inv = op.join( data_path, '%s_highpass-%sHz-meg-eeg-%s-inv.fif' % (subject, l_freq, spacing)) evokeds = mne.read_evokeds(fname_ave, condition=[ 'scrambled', 'unfamiliar', 'famous', 'faces', 'contrast', 'faces_eq', 'scrambled_eq' ]) cov = mne.read_cov(fname_cov) forward = mne.read_forward_solution(fname_fwd) # This will be an MEG-only inverse because the 3-layer BEMs are not # reliable, so our forward only has MEG channels. 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) # Apply inverse snr = 3.0 lambda2 = 1.0 / snr**2 for evoked in evokeds: stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM", pick_ori='vector') stc.save( op.join( data_path, 'mne_dSPM_inverse_highpass-%sHz-%s' % (l_freq, evoked.comment)))
def compute_ts_inv_sol(raw, fwd_filename, cov_fname, snr, inv_method, aseg): import os.path as op import numpy as np import mne from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from nipype.utils.filemanip import split_filename as split_f print '***** READ FWD SOL %s *****' % fwd_filename forward = mne.read_forward_solution(fwd_filename) # Convert to surface orientation for cortically constrained # inverse modeling if not aseg: forward = mne.convert_forward_solution(forward, surf_ori=True) lambda2 = 1.0 / snr ** 2 # compute inverse operator print '***** COMPUTE INV OP *****' inverse_operator = make_inverse_operator(raw.info, forward, cov_fname, loose=0.2, depth=0.8) # apply inverse operator to the time windows [t_start, t_stop]s # TEST t_start = 0 # sec t_stop = 3 # sec start, stop = raw.time_as_index([t_start, t_stop]) print '***** APPLY INV OP ***** [%d %d]sec' % (t_start, t_stop) stc = apply_inverse_raw(raw, inverse_operator, lambda2, inv_method, label=None, start=start, stop=stop, pick_ori=None) print '***' print 'stc dim ' + str(stc.shape) print '***' subj_path, basename, ext = split_f(raw.info['filename']) data = stc.data print 'data dim ' + str(data.shape) # save results in .npy file that will be the input for spectral node print '***** SAVE SOL *****' ts_file = op.abspath(basename + '.npy') np.save(ts_file, data) return ts_file
def calc_inverse_operator(events_id, epochs_fn, fwd_sub_fn, inv_fn, min_crop_t=None, max_crop_t=0): for cond in events_id.keys(): epochs = mne.read_epochs(epochs_fn.format(cond=cond)) noise_cov = mne.compute_covariance( epochs.crop(min_crop_t, max_crop_t, copy=True)) forward_sub = mne.read_forward_solution(fwd_sub_fn.format(cond=cond)) inverse_operator_sub = make_inverse_operator(epochs.info, forward_sub, noise_cov, loose=None, depth=None) write_inverse_operator(inv_fn.format(cond=cond), inverse_operator_sub)
def test_apply_inverse_eLORETA_MNE_equiv(bias_params_free, loose, lambda2): """Test that eLORETA with no iterations is the same as MNE.""" method_params = dict(max_iter=0, force_equal=False) pick_ori = None if loose == 0 else 'vector' evoked, fwd, noise_cov, _, _ = bias_params_free inv = make_inverse_operator( evoked.info, fwd, noise_cov, loose=loose, depth=None, verbose='debug') stc_mne = apply_inverse(evoked, inv, lambda2, 'MNE', pick_ori=pick_ori, verbose='debug') with pytest.warns(RuntimeWarning, match='converge'): stc_e = apply_inverse(evoked, inv, lambda2, 'eLORETA', method_params=method_params, pick_ori=pick_ori, verbose='debug') atol = np.mean(np.abs(stc_mne.data)) * 1e-6 assert 3e-9 < atol < 3e-6 # nothing has blown up assert_allclose(stc_mne.data, stc_e.data, atol=atol, rtol=1e-4)
def get_stc(epoch_data): """Returns stc for a given `epoch_data`, assumes `fwr` path from `epoch_data.filename` basename[0:9]+ fwd.fif """ fwd_name_dir = op.dirname(epoch_data.filename) fwd_name_base = op.basename(epoch_data.filename)[0:9] + '_oct5-fwd.fif' fwd_name = op.join(fwd_name_dir, fwd_name_base) fwd = read_forward_solution(fwd_name) noise_cov = compute_covariance(epoch_data, tmax=0, method='shrunk') fwd_fixed = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) inv = make_inverse_operator(epoch_data.info, fwd_fixed, noise_cov, loose=0.2) evoked = epoch_data.epochs.average() stc = apply_inverse(evoked, inv, lambda2=1. / 9.)
def estimate_inverse_solution(info, noise_cov_mat, fwd_sol=None, fname_fwd=None, fname_inv=None): """"Estimates inverse solution for the given data set.""" if fwd_sol is not None: pass elif fname_fwd is not None: fwd_sol = mne.read_forward_solution(fname_fwd, surf_ori=True) else: print "ERROR: Neither a forward solution given nor the filename of one!" sys.exit() # restrict forward solution as necessary for MEG fwd = mne.fiff.pick_types_forward(fwd_sol, meg=True, eeg=False) # # regularize noise covariance # # --> not necessary as the data set to estimate the # # noise-covariance matrix is quiet long, i.e. # # the noise-covariance matrix is robust # noise_cov_mat = mne.cov.regularize(noise_cov_mat, # info, # mag=0.1, # proj=True, # verbose=verbose) # create the MEG inverse operators print ">>>> estimate inverse operator..." inverse_operator = min_norm.make_inverse_operator(info, fwd, noise_cov_mat, loose=0.2, depth=0.8) if fname_inv is not None: min_norm.write_inverse_operator(fname_inv, inverse_operator) return inverse_operator
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 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 apply_inverse_ave(fnevo, subjects_dir): ''' Make individual inverse operator. Parameter --------- fnevo: string or list The evoked file with ECG, EOG and environmental noise free. subjects_dir: The total bath of all the subjects. ''' from mne import make_forward_solution from mne.minimum_norm import make_inverse_operator, write_inverse_operator 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) subject = name.split('_')[0] fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' % subject subject_path = subjects_dir + '/%s' % subject fn_trans = fn_path + '/%s-trans.fif' % subject fn_cov = fn_path + '/%s_empty,fibp1-45-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 [evoked] = mne.read_evokeds(fname) evoked.pick_types(meg=True, ref_meg=False) noise_cov = mne.read_cov(fn_cov) # noise_cov = dSPM.cov.regularize(noise_cov, evoked.info, # mag=0.05, grad=0.05, proj=True) fwd = make_forward_solution(evoked.info, fn_trans, fn_src, fn_bem) fwd['surf_ori'] = True inv = make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.2, depth=0.8, limit_depth_chs=False) write_inverse_operator(fn_inv, inv)
def test_orientation_prior(bias_params_free, method, looses, vmin, vmax, nmin, nmax): """Test that orientation priors are handled properly.""" evoked, fwd, noise_cov, _, _ = bias_params_free stcs = list() vec_stc = None for loose in looses: inv = make_inverse_operator(evoked.info, fwd, noise_cov, loose=loose) if looses[0] == 0.: pick_ori = None if loose == 0 else 'normal' else: pick_ori = 'vector' stcs.append(apply_inverse( evoked, inv, method=method, pick_ori=pick_ori)) if loose in (1., 0.2): assert vec_stc is None vec_stc = apply_inverse( evoked, inv, method=method, pick_ori='vector') assert vec_stc is not None rot = _normal_orth(np.concatenate( [_get_src_nn(s) for s in inv['src']])) vec_stc_surf = np.matmul(rot, vec_stc.data) if 0. in looses: vec_stc_normal = vec_stc.normal(inv['src']) assert_allclose(stcs[1].data, vec_stc_normal.data) del vec_stc assert_allclose(vec_stc_normal.data, vec_stc_surf[:, 2]) assert_allclose(vec_stc_normal.data, stcs[1].data) # Ensure that our relative strengths are reasonable # (normal should be much larger than tangential) normal = np.linalg.norm(vec_stc_surf[:, 2].ravel()) for ii in range(2): tangential = np.linalg.norm(vec_stc_surf[:, ii].ravel()) ratio = normal / tangential assert nmin < ratio < nmax assert stcs[0].data.shape == stcs[1].data.shape R2 = 1. - ( np.linalg.norm(stcs[0].data.ravel() - stcs[1].data.ravel()) / np.linalg.norm(stcs[0].data.ravel())) assert vmin < R2 < vmax
def _calc_inverse(params): subject, epochs, overwrite = params epo = op.join(REMOTE_ROOT_DIR, 'ave', '{}_ecr_nTSSS_conflict-epo.fif'.format(subject)) fwd = op.join(REMOTE_ROOT_DIR, 'fwd', '{}_ecr-fwd.fif'.format(subject)) local_inv_file_name = op.join(LOCAL_ROOT_DIR, 'inv', '{}_ecr_nTSSS_conflict-inv.fif'.format(subject)) if os.path.isfile(local_inv_file_name) and not overwrite: inverse_operator = read_inverse_operator(local_inv_file_name) print('inv already calculated for {}'.format(subject)) else: if epochs is None: epochs = mne.read_epochs(epo) noise_cov = mne.compute_covariance(epochs.crop(None, 0, copy=True)) inverse_operator = None if not os.path.isfile(fwd): print('no fwd for {}'.format(subject)) else: forward = mne.read_forward_solution(fwd) inverse_operator = make_inverse_operator(epochs.info, forward, noise_cov, loose=None, depth=None) write_inverse_operator(local_inv_file_name, inverse_operator) return inverse_operator
def test_apply_mne_inverse_fixed_raw(): """Test MNE with fixed-orientation inverse operator on Raw.""" raw = read_raw_fif(fname_raw) start = 3 stop = 10 _, times = raw[0, start:stop] label_lh = read_label(fname_label % 'Aud-lh') # create a fixed-orientation inverse operator fwd = read_forward_solution_meg(fname_fwd, force_fixed=False, surf_ori=True) noise_cov = read_cov(fname_cov) pytest.raises(ValueError, make_inverse_operator, raw.info, fwd, noise_cov, loose=1., fixed=True) inv_op = make_inverse_operator(raw.info, fwd, noise_cov, fixed=True, use_cps=True) inv_op2 = prepare_inverse_operator(inv_op, nave=1, lambda2=lambda2, method="dSPM") stc = apply_inverse_raw(raw, inv_op2, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None, prepared=True) stc2 = apply_inverse_raw(raw, inv_op2, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=3, prepared=True) stc3 = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None) assert (stc.subject == 'sample') assert (stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc3.times, times) assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.data, stc3.data)
def run_inverse(subject): print("Processing subject: %s" % subject) meg_subject_dir = op.join(config.meg_dir, subject) extension = '-ave' fname_ave = op.join(meg_subject_dir, config.base_fname.format(**locals())) extension = '_%s-fwd' % (config.spacing) fname_fwd = op.join(meg_subject_dir, config.base_fname.format(**locals())) extension = '-cov' fname_cov = op.join(meg_subject_dir, config.base_fname.format(**locals())) extension = '_%s-inv' % (config.spacing) fname_inv = op.join(meg_subject_dir, config.base_fname.format(**locals())) evokeds = mne.read_evokeds(fname_ave) cov = mne.read_cov(fname_cov) forward = mne.read_forward_solution(fname_fwd) 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) # Apply inverse snr = 3.0 lambda2 = 1.0 / snr ** 2 for condition, evoked in zip(config.conditions, evokeds): stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM", pick_ori=None) stc.save(op.join(meg_subject_dir, '%s_%s_mne_dSPM_inverse-%s' % (config.study_name, subject, condition.replace(op.sep, ''))))
def apply_inverse_ave(fnevo, subjects_dir): ''' Make individual inverse operator. Parameter --------- fnevo: string or list The evoked file with ECG, EOG and environmental noise free. subjects_dir: The total bath of all the subjects. ''' from mne import make_forward_solution from mne.minimum_norm import make_inverse_operator, write_inverse_operator 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) subject = name.split('_')[0] fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' % subject subject_path = subjects_dir + '/%s' % subject fn_trans = fn_path + '/%s-trans.fif' % subject fn_cov = fn_path + '/%s_empty,fibp1-45-cov.fif' % subject fn_src = subject_path + '/bem/%s-oct-6-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject [evoked] = mne.read_evokeds(fname) evoked.pick_types(meg=True, ref_meg=False) noise_cov = mne.read_cov(fn_cov) # noise_cov = mne.cov.regularize(noise_cov, evoked.info, # mag=0.05, grad=0.05, proj=True) fwd = make_forward_solution(evoked.info, fn_trans, fn_src, fn_bem) fwd['surf_ori'] = True inv = make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.2, depth=0.8, limit_depth_chs=False) write_inverse_operator(fn_inv, inv)
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() # This was 291 on `master` before gh-5590. Then refactoring transforms # it became 279 despite a < 1e-8 change in vox_mri_t # Then it dropped to 123 once nearest-voxel was used in gh-7653 assert n_on in (123, 279, 291) img = stc.as_volume(src, mri_resolution=False) n_on = np.array(img.dataobj).astype(bool).sum() # was 20 on `master` before gh-5590 # then 44 before gh-7653, which took it back to 20 assert n_on == 20
def apply_inverse_oper(fnepo, tmin=-0.2, tmax=0.8, subjects_dir=None): ''' Apply inverse operator Parameter --------- fnepo: string or list The epochs file with ECG, EOG and environmental noise free. tmax, tmax:float The time period (second) of each epoch. ''' # Get the default subjects_dir from mne import make_forward_solution from mne.minimum_norm import make_inverse_operator, write_inverse_operator fnlist = get_files_from_list(fnepo) # loop across all filenames for fname in fnlist: fn_path = os.path.split(fname)[0] name = os.path.basename(fname) subject = name.split('_')[0] subject_path = subjects_dir + '/%s' % subject fn_trans = fn_path + '/%s-trans.fif' % subject fn_cov = fn_path + '/%s_empty-cov.fif' % subject fn_src = subject_path + '/bem/%s-oct-6-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject fn_inv = fn_path + '/%s_epo-inv.fif' % subject epochs = mne.read_epochs(fname) epochs.crop(tmin, tmax) epochs.pick_types(meg=True, ref_meg=False) noise_cov = mne.read_cov(fn_cov) fwd = make_forward_solution(epochs.info, fn_trans, fn_src, fn_bem) fwd['surf_ori'] = True inv = make_inverse_operator(epochs.info, fwd, noise_cov, loose=0.2, depth=0.8, limit_depth_chs=False) write_inverse_operator(fn_inv, inv)
def compute_ROIs_inv_sol(raw, sbj_id, sbj_dir, fwd_filename, cov_fname, snr, inv_method, parc, aseg, aseg_labels): import os.path as op import numpy as np import mne from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from nipype.utils.filemanip import split_filename as split_f from neuropype_ephy.compute_inv_problem import get_aseg_labels print '***** READ noise covariance %s *****' % cov_fname noise_cov = mne.read_cov(cov_fname) print '***** READ FWD SOL %s *****' % 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 '***** COMPUTE INV OP *****' if not aseg: loose = 0.2 depth = 0.8 else: loose = None depth = None inverse_operator = make_inverse_operator(raw.info, forward, noise_cov, loose=loose, depth=depth, fixed=False) # apply inverse operator to the time windows [t_start, t_stop]s print '***** APPLY INV OP *****' 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 '***' labels_cortex = mne.read_labels_from_annot(sbj_id, parc=parc, subjects_dir=sbj_dir) 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 # TODO cosa accade se la uso con solo la cortex? -> OK!!! label_ts = mne.extract_label_time_course_AP(stc, labels_cortex, src, mode='mean_flip', allow_empty=True, return_generator=False) # save results in .npy file that will be the input for spectral node print '***** SAVE SOL *****' subj_path, basename, ext = split_f(raw.info['filename']) ts_file = op.abspath(basename + '.npy') np.save(ts_file, label_ts) if aseg: labels_aseg = get_aseg_labels(src, sbj_dir, sbj_id, aseg_labels) labels = labels_cortex + labels_aseg else: labels = labels_cortex return ts_file, labels
evoked = Evoked(fname_evoked, setno=0, baseline=(None, 0)) forward_meeg = mne.read_forward_solution(fname_fwd_meeg, 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_meeg, meg=True, eeg=False) # Alternatively, you can just load a forward solution that is restricted forward_eeg = mne.read_forward_solution(fname_fwd_eeg, surf_ori=True) # make an M/EEG, MEG-only, and EEG-only inverse operators info = evoked.info inverse_operator_meeg = make_inverse_operator(info, forward_meeg, noise_cov, 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",
fname_fwd = fwd_dir + '%s_task-5-fwd.fif' % subj forward = mne.read_forward_solution(fname_fwd) evoked_fname = data_dir + '%s_stop_parsed_matched_clean_BP1-100_DS300-ave.fif' % subj evoked = mne.read_evokeds(evoked_fname) epochs_fname = data_dir + '%s_stop_parsed_matched_clean_BP1-100_DS300-epo.fif.gz' % subj epochs = mne.read_epochs(epochs_fname) # we're interested in time points every 50ms (for now). That's sfreq of 20Hz. # the niquist there is 10Hz, so let's downsample our data that way. epochs_ds = epochs.copy() epochs_ds.resample(20) evoked_ds = [epochs_ds[name].average() for name in ['STI-correct', 'STI-incorrect']] # 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])
# Define epochs for left-auditory condition event_id, tmin, tmax = 1, -0.2, 0.5 epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, eog=150e-6)) # Compute inverse solution and for each epoch snr = 1.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(raw.info, fwd, noise_cov, loose=None, depth=None, fixed=False) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=None, return_generator=True) # 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 structures contained in the src space # If mode = 'mean_flip' this option is used only for the cortical label src = inverse_operator['src'] label_ts = mne.extract_label_time_course(stcs, labels_parc, src,
cov = mne.cov.regularize(cov, evoked.info) ############################################################################### # Run solver # 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, wsize=16, tstep=4, window=0.05, return_residual=True) # Crop to remove edges stc.crop(tmin=-0.05, tmax=0.3) evoked.crop(tmin=-0.05, tmax=0.3) residual.crop(tmin=-0.05, tmax=0.3)
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)
def test_compute_LF_matrix(): import os import os.path as op import nipype.pipeline.engine as pe from nipype.interfaces.mne import WatershedBEM import mne import mne.io as io from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from mne.report import Report from nipype.utils.filemanip import split_filename as split_f main_path = '/home/karim/Documents/pasca/data/resting_state/' sbj_id = 'K0002' sbj_dir = op.join(main_path, 'FSF') bem_dir = op.join(sbj_dir, sbj_id, 'bem') surface_dir = op.join(sbj_dir, sbj_id, 'bem/watershed') data_dir = op.join(main_path, 'MEG') raw_fname = op.join(data_dir, '%s/%s_rest_tsss_mc.fif' % (sbj_id, sbj_id)) raw = io.Raw(raw_fname, preload=True) picks = mne.pick_types(raw.info, meg=True, ref_meg=False, exclude='bads') raw.filter(l_freq=0.1, h_freq=300, picks=picks, method='iir', n_jobs=2) raw.resample(sfreq=300, npad=0) report = Report() surfaces = [sbj_id + '_brain_surface', sbj_id + '_inner_skull_surface', sbj_id + '_outer_skull_surface', sbj_id + '_outer_skin_surface'] new_surfaces = ['brain.surf', 'inner_skull.surf', 'outer_skull.surf', 'outer_skin.surf'] sbj_inner_skull_fname = op.join(bem_dir, sbj_id + '-' + new_surfaces[1]) inner_skull_fname = op.join(bem_dir, new_surfaces[1]) if not (op.isfile(sbj_inner_skull_fname) or op.isfile(inner_skull_fname)): bem_IF = WatershedBEM() bem_IF.inputs.subject_id = sbj_id bem_IF.inputs.subjects_dir = sbj_dir bem_IF.inputs.atlas_mode = True bem_IF.run() for i in range(len(surfaces)): os.system('cp %s %s' % (op.join(surface_dir, surfaces[i]), op.join(bem_dir, sbj_id + '-' + new_surfaces[i]))) else: print '*** inner skull surface exists!!!' bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % sbj_id) if not op.isfile(bem): os.system('$MNE_ROOT/bin/mne_setup_forward_model --subject ' + sbj_id + ' --homog --surf --ico 4') else: print '*** BEM solution file exists!!!' src_fname = op.join(bem_dir, '%s-ico-5-src.fif' % sbj_id) if not op.isfile(src_fname): src = mne.setup_source_space(sbj_id, fname=True, spacing='ico5', subjects_dir=sbj_dir, overwrite=True, n_jobs=2) else: print '*** source space file exists!!!' src = mne.read_source_spaces(src_fname) trans_fname = op.join(data_dir, '%s/%s-trans.fif' % (sbj_id, sbj_id)) data_path, basename, ext = split_f(raw_fname) fwd_filename = op.join(data_path, '%s-fwd.fif' % basename) forward = mne.make_forward_solution(raw_fname, trans_fname, src, bem, fwd_filename, n_jobs=2, overwrite=True) forward = mne.convert_forward_solution(forward, surf_ori=True) snr = 1.0 lambda2 = 1.0 / snr ** 2 method = 'MNE' reject = dict(mag=4e-12, grad=4e-10, eog=0.00025) noise_cov = mne.compute_raw_data_covariance(raw, picks=picks, reject=reject) inverse_operator = make_inverse_operator(raw.info, forward, noise_cov, loose=0.2, depth=0.8) start, stop = raw.time_as_index([0, 30]) stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label=None, start=start, stop=stop, pick_ori=None) print '***' stc.shape print '***' subj_path, basename, ext = split_f(raw_fname) stc_filename = op.join(subj_path, basename) stc.save(stc_filename) report_filename = op.join(subj_path, basename + '-BEM-report.html') print report_filename report.save(report_filename, open_browser=False, overwrite=True) return
plot_cov_diag_topomap(evoked_data_cov_white, 'grad') ############################################################################### # Apply inverse operator to covariance # ------------------------------------ # Finally, we can construct an inverse using the empty-room noise covariance: # Read the forward solution and compute the inverse operator fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fname_fwd) # make an MEG inverse operator info = evoked.info inverse_operator = make_inverse_operator(info, fwd, noise_cov, loose=0.2, depth=0.8) ############################################################################### # Project our data and baseline covariance to source space: stc_data = apply_inverse_cov(data_cov, evoked.info, inverse_operator, nave=len(epochs), method='dSPM', verbose=True) stc_base = apply_inverse_cov(base_cov, evoked.info, inverse_operator,
# 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. ###############################################################################
# Power mapping # ------------- # With our simulated dataset ready, we can now pretend to be researchers that # 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(source_vert1, coords_as_verts=True, hemi='lh') brain.add_foci(source_vert2, coords_as_verts=True, hemi='rh') # Rotate the view and add a title. mlab.view(0, 0, 550, [0, 0, 0])
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
from my_settings import (mne_folder, epochs_folder) import sys import mne from mne.minimum_norm import make_inverse_operator subject = sys.argv[1] fwd = mne.read_forward_solution(mne_folder + "%s-fwd.fif" % subject, surf_ori=False) fwd = mne.pick_types_forward(fwd, meg="grad", eeg=False) cov = mne.read_cov(mne_folder + "%s-cov.fif" % subject) epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject, preload=False) inv = make_inverse_operator(epochs.info, fwd, cov, loose=0.2, depth=0.8) mne.minimum_norm.write_inverse_operator(mne_folder + "%s_grad-inv.fif" % subject, inv)
forward = mne.read_forward_solution(fwd_fname, surf_ori=True) 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),
def get_mne_sample(tmin=-0.1, tmax=0.4, baseline=(None, 0), sns=False, src=None, sub="modality=='A'", fixed=False, snr=2, method='dSPM'): """Load events and epochs from the MNE sample data Parameters ---------- tmin, tmax baseline : Epoch parameters. sns : bool Add sensor space data as NDVar as ``ds['sns']``. src : None | 'ico' | 'vol' Add source space data as NDVar as ``ds['src']``. sub : str | None Expresion for subset of events to load. fixed : bool MNE inverse parameter. snr : scalar MNE inverse parameter. method : str MNE inverse parameter. Returns ------- ds : Dataset Dataset with epochs from the MNE sample dataset. """ data_dir = mne.datasets.sample.data_path() meg_dir = os.path.join(data_dir, 'MEG', 'sample') raw_file = os.path.join(meg_dir, 'sample_audvis_filt-0-40_raw.fif') subjects_dir = os.path.join(data_dir, 'subjects') subject = 'sample' label_path = os.path.join(subjects_dir, subject, 'label', '%s.label') ds = load.fiff.events(raw_file, stim_channel='STI 014') ds.info['subjects_dir'] = subjects_dir ds.info['subject'] = subject ds.info['label'] = label_path # get the trigger variable form the dataset for eaier access trigger = ds['trigger'] # use trigger to add various labels to the dataset ds['condition'] = Factor(trigger, labels={1:'LA', 2:'RA', 3:'LV', 4:'RV', 5:'smiley', 32:'button'}) ds['side'] = Factor(trigger, labels={1: 'L', 2:'R', 3:'L', 4:'R', 5:'None', 32:'None'}) ds['modality'] = Factor(trigger, labels={1: 'A', 2:'A', 3:'V', 4:'V', 5:'None', 32:'None'}) if sub: ds = ds.sub(sub) load.fiff.add_mne_epochs(ds, tmin, tmax, baseline) if sns: ds['sns'] = load.fiff.epochs_ndvar(ds['epochs']) if not src: return ds bem_dir = os.path.join(subjects_dir, subject, 'bem') bem_file = os.path.join(bem_dir, 'sample-5120-5120-5120-bem-sol.fif') trans_file = os.path.join(meg_dir, 'sample_audvis_raw-trans.fif') epochs = ds['epochs'] if src == 'ico': src_tag = 'ico-4' elif src == 'vol': src_tag = 'vol-10' else: raise ValueError("src = %r" % src) fwd_file = os.path.join(meg_dir, 'sample-%s-fwd.fif' % src_tag) if os.path.exists(fwd_file): fwd = mne.read_forward_solution(fwd_file) else: src_file = os.path.join(bem_dir, 'sample-%s-src.fif' % src_tag) if os.path.exists(src_file): src_ = src_file elif src == 'ico': src_ = mne.setup_source_space(subject, src_file, 'ico4', subjects_dir=subjects_dir) elif src == 'vol': mri_file = os.path.join(subjects_dir, subject, 'mri', 'orig.mgz') src_ = mne.setup_volume_source_space(subject, src_file, pos=10., mri=mri_file, bem=bem_file, mindist=0., exclude=0., subjects_dir=subjects_dir) fwd = mne.make_forward_solution(epochs.info, trans_file, src_, bem_file, fwd_file) cov_file = os.path.join(meg_dir, 'sample_audvis-cov.fif') cov = mne.read_cov(cov_file) inv = mn.make_inverse_operator(epochs.info, fwd, cov, None, None, fixed) ds.info['inv'] = inv stcs = mn.apply_inverse_epochs(epochs, inv, 1. / (snr ** 2), method) ds['src'] = load.fiff.stc_ndvar(stcs, subject, src_tag, subjects_dir) return ds
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)
# Setup for reading the raw data events_nrm = mne.find_events(raw_nrm) events_hyp = mne.find_events(raw_hyp) picks = mne.pick_types(raw_nrm.info, meg=True, eeg=False, stim=False, eog=False, include=[], exclude='bads') # Read epochs epochs_nrm = mne.Epochs(raw_nrm, events_nrm, event_id, tmin, tmax, picks=picks, baseline=(None, -0.5), reject=reject, preload=True) epochs_hyp = mne.Epochs(raw_hyp, events_hyp, event_id, tmin, tmax, picks=picks, baseline=(None, -0.5), reject=reject, preload=True) cov_nrm = mne.compute_covariance(epochs_nrm, tmin=None, tmax=-0.5, method="shrunk") cov_hyp = mne.compute_covariance(epochs_hyp, tmin=None, tmax=-0.5, method="shrunk") cov_nrm.save("subj_1-nrm-cov.fif") cov_hyp.save("subj_1-hyp-cov.fif") inv_nrm = make_inverse_operator(epochs_nrm.info, fwd_nrm, cov_nrm, loose=0.2, depth=0.8) inv_hyp = make_inverse_operator(epochs_hyp.info, fwd_hyp, cov_hyp, loose=0.2, depth=0.8) mne.minimum_norm.write_inverse_operator("subj_1-nrm-inv.fif", inv_nrm) mne.minimum_norm.write_inverse_operator("subj_1-hyp-inv.fif", inv_hyp)
# Load data condition = 'Left Auditory' 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(
############################################################################### # 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')
# Handling forward solution forward = mne.read_forward_solution(fwd_fname) ############################################################################### # Run solver # alpha parameter is between 0 and 100 (100 gives 0 active source) alpha = 40. # general regularization parameter # l1_ratio parameter between 0 and 1 promotes temporal smoothness # (0 means no temporal regularization) l1_ratio = 0.03 # 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 with dipole output dipoles, residual = tf_mixed_norm( evoked, forward, cov, alpha=alpha, l1_ratio=l1_ratio, loose=loose, depth=depth, maxit=200, tol=1e-6, weights=stc_dspm, weights_min=8., debias=True, wsize=16, tstep=4, window=0.05, return_as_dipoles=True, return_residual=True) # Crop to remove edges for dip in dipoles: dip.crop(tmin=-0.05, tmax=0.3) evoked.crop(tmin=-0.05, tmax=0.3) residual.crop(tmin=-0.05, tmax=0.3)
# prepare contrast evokeds = [epochs_train[k].average() for k in conditions] 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))