def test_make_forward_solution_sphere(): """Test making a forward solution with a sphere model.""" temp_dir = _TempDir() fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif') src = setup_source_space('sample', 'oct2', subjects_dir=subjects_dir, add_dist=False) write_source_spaces(fname_src_small, src) # to enable working with MNE-C out_name = op.join(temp_dir, 'tmp-fwd.fif') run_subprocess(['mne_forward_solution', '--meg', '--eeg', '--meas', fname_raw, '--src', fname_src_small, '--mri', fname_trans, '--fwd', out_name]) fwd = read_forward_solution(out_name) sphere = make_sphere_model(verbose=True) fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=True, verbose=True) _compare_forwards(fwd, fwd_py, 366, 108, meg_rtol=5e-1, meg_atol=1e-6, eeg_rtol=5e-1, eeg_atol=5e-1) # Since the above is pretty lax, let's check a different way for meg, eeg in zip([True, False], [False, True]): fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg) fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg) assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(), fwd_py_['sol']['data'].ravel())[0, 1], 1.0, rtol=1e-3)
def test_make_forward_solution_sphere(): """Test making a forward solution with a sphere model""" temp_dir = _TempDir() fname_src_small = op.join(temp_dir, "sample-oct-2-src.fif") src = setup_source_space("sample", fname_src_small, "oct2", subjects_dir=subjects_dir, add_dist=False) out_name = op.join(temp_dir, "tmp-fwd.fif") run_subprocess( [ "mne_forward_solution", "--meg", "--eeg", "--meas", fname_raw, "--src", fname_src_small, "--mri", fname_trans, "--fwd", out_name, ] ) fwd = read_forward_solution(out_name) sphere = make_sphere_model(verbose=True) fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=True, verbose=True) _compare_forwards(fwd, fwd_py, 366, 108, meg_rtol=5e-1, meg_atol=1e-6, eeg_rtol=5e-1, eeg_atol=5e-1) # Since the above is pretty lax, let's check a different way for meg, eeg in zip([True, False], [False, True]): fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg) fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg) assert_allclose(np.corrcoef(fwd_["sol"]["data"].ravel(), fwd_py_["sol"]["data"].ravel())[0, 1], 1.0, rtol=1e-3)
def compute_correlation_distance_matix(fwd): print(' Computing correlation distance matrix...') distance_matrix = np.zeros( (fwd['sol']['data'].shape[1], fwd['sol']['data'].shape[1])) n_ch_tot = fwd['info']['nchan'] ch_types = set(map(lambda x: channel_type(fwd['info'], x), range(n_ch_tot))) for _t in ch_types: print(' Using {} sensors for computation...'.format(_t)) if _t in ['mag', 'grad', 'planar1', 'planar2']: _fwd_t = pick_types_forward(fwd, meg=_t, ref_meg=False) elif _t == 'eeg': _fwd_t = pick_types_forward(fwd, eeg=_t, ref_meg=False) else: raise NotImplementedError n_ch_t = _fwd_t['info']['nchan'] _lf_t = _fwd_t['sol']['data'] _dm_t = ssd.cdist(_lf_t.T, _lf_t.T, metric='correlation') distance_matrix += (n_ch_t / n_ch_tot) * _dm_t print(' [done]') return distance_matrix
def test_psf_ctf(): """Test computation of PSFs and CTFs for linear estimators """ inverse_operator = read_inverse_operator(fname_inv) forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) forward = pick_types_forward(forward, meg=True, eeg=False) labels = [mne.read_label(ss) for ss in fname_label] method = 'MNE' n_svd_comp = 2 # Test PSFs (then CTFs) for mode in ('sum', 'svd'): stc_psf, psf_ev = point_spread_function(inverse_operator, forward, method=method, labels=labels, lambda2=lambda2, pick_ori='normal', mode=mode, n_svd_comp=n_svd_comp) n_vert, n_samples = stc_psf.shape should_n_vert = (inverse_operator['src'][1]['vertno'].shape[0] + inverse_operator['src'][0]['vertno'].shape[0]) if mode == 'svd': should_n_samples = len(labels) * n_svd_comp + 1 else: should_n_samples = len(labels) + 1 assert_true(n_vert == should_n_vert) assert_true(n_samples == should_n_samples) n_chan, n_samples = psf_ev.data.shape assert_true(n_chan == forward['nchan']) forward = read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) forward = pick_types_forward(forward, meg=True, eeg=False) # Test CTFs for mode in ('sum', 'svd'): stc_ctf = cross_talk_function(inverse_operator, forward, labels, method=method, lambda2=lambda2, signed=False, mode=mode, n_svd_comp=n_svd_comp) n_vert, n_samples = stc_ctf.shape should_n_vert = (inverse_operator['src'][1]['vertno'].shape[0] + inverse_operator['src'][0]['vertno'].shape[0]) if mode == 'svd': should_n_samples = len(labels) * n_svd_comp + 1 else: should_n_samples = len(labels) + 1 assert_true(n_vert == should_n_vert) assert_true(n_samples == should_n_samples)
def test_make_forward_solution_sphere(): """Test making a forward solution with a sphere model.""" temp_dir = _TempDir() fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif') src = setup_source_space('sample', 'oct2', subjects_dir=subjects_dir, add_dist=False) write_source_spaces(fname_src_small, src) # to enable working with MNE-C out_name = op.join(temp_dir, 'tmp-fwd.fif') run_subprocess([ 'mne_forward_solution', '--meg', '--eeg', '--meas', fname_raw, '--src', fname_src_small, '--mri', fname_trans, '--fwd', out_name ]) fwd = read_forward_solution(out_name) sphere = make_sphere_model(verbose=True) fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=True, verbose=True) _compare_forwards(fwd, fwd_py, 366, 108, meg_rtol=5e-1, meg_atol=1e-6, eeg_rtol=5e-1, eeg_atol=5e-1) # Since the above is pretty lax, let's check a different way for meg, eeg in zip([True, False], [False, True]): fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg) fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg) assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(), fwd_py_['sol']['data'].ravel())[0, 1], 1.0, rtol=1e-3) # Number of layers in the sphere model doesn't matter for MEG # (as long as no sources are omitted due to distance) assert len(sphere['layers']) == 4 fwd = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=False) sphere_1 = make_sphere_model(head_radius=None) assert len(sphere_1['layers']) == 0 assert_array_equal(sphere['r0'], sphere_1['r0']) fwd_1 = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=False) _compare_forwards(fwd, fwd_1, 306, 108, meg_rtol=1e-12, meg_atol=1e-12)
def test_restrict_forward_to_stc(): """Test restriction of source space to source SourceEstimate """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_true(isinstance(fwd_out, Forward)) assert_equal(fwd_out['sol']['ncol'], 20) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_equal(fwd_out['sol']['ncol'], 60) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) # Test saving the restricted forward object. This only works if all fields # are properly accounted for. temp_dir = _TempDir() fname_copy = op.join(temp_dir, 'copy-fwd.fif') with warnings.catch_warnings(record=True): warnings.simplefilter('always') write_forward_solution(fname_copy, fwd_out, overwrite=True) fwd_out_read = read_forward_solution(fname_copy) fwd_out_read = convert_forward_solution(fwd_out_read, surf_ori=True, force_fixed=False) compare_forwards(fwd_out, fwd_out_read)
def test_restrict_forward_to_label(): """Test restriction of source space to label """ fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) vertno_lh = fwd['src'][0]['vertno'][src_sel_lh] nuse_lh = fwd['src'][0]['nuse'] src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) vertno_rh = fwd['src'][1]['vertno'][src_sel_rh] src_sel_rh += nuse_lh assert_equal(fwd_out['sol']['ncol'], len(src_sel_lh) + len(src_sel_rh)) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], vertno_lh) assert_equal(fwd_out['src'][1]['vertno'], vertno_rh) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) vertno_lh = fwd['src'][0]['vertno'][src_sel_lh] nuse_lh = fwd['src'][0]['nuse'] src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) vertno_rh = fwd['src'][1]['vertno'][src_sel_rh] src_sel_rh += nuse_lh assert_equal(fwd_out['sol']['ncol'], 3 * (len(src_sel_lh) + len(src_sel_rh))) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], vertno_lh) assert_equal(fwd_out['src'][1]['vertno'], vertno_rh)
def test_restrict_forward_to_stc(tmpdir): """Test restriction of source space to source SourceEstimate.""" start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert (isinstance(fwd_out, Forward)) assert_equal(fwd_out['sol']['ncol'], 20) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_equal(fwd_out['sol']['ncol'], 60) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) # Test saving the restricted forward object. This only works if all fields # are properly accounted for. fname_copy = tmpdir.join('copy-fwd.fif') with pytest.warns(RuntimeWarning, match='stored on disk'): write_forward_solution(fname_copy, fwd_out, overwrite=True) fwd_out_read = read_forward_solution(fname_copy) fwd_out_read = convert_forward_solution(fwd_out_read, surf_ori=True, force_fixed=False) compare_forwards(fwd_out, fwd_out_read)
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd) forward = convert_forward_solution(forward, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0), proj=False) evoked.resample(50, npad=100) evoked.crop(tmin=0.1, tmax=0.16) # crop to window around peak cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.5 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=True, update_mode=1) _check_stc(stc, evoked, 68477) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1) _check_stc(stc, evoked, 82010) dips = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1, return_as_dipoles=True) assert_true(isinstance(dips[0], Dipole)) stc_dip = make_stc_from_dipoles(dips, forward['src']) _check_stcs(stc, stc_dip) # force fixed orientation stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=2, loose=0, return_residual=False) _check_stc(stc, evoked, 85739, 20)
def _get_fwd_labels(): fwd = read_forward_solution(fname_fwd) fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True, eeg=False) labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label)) for label in label_names] return fwd, labels
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0), proj=False) evoked.resample(50, npad=100) evoked.crop(tmin=0.1, tmax=0.16) # crop to nice window near samp border cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.5 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=True, update_mode=1) _check_stc(stc, evoked, 68477) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1) _check_stc(stc, evoked, 82010) # force fixed orientation stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=2, loose=None, return_residual=False) _check_stc(stc, evoked, 85739, 20)
def read_forward_solution_eeg(fname, **kwargs): """Read EEG forward.""" fwd = convert_forward_solution(read_forward_solution(fname), copy=False, **kwargs) fwd = pick_types_forward(fwd, meg=False, eeg=True) return fwd
def test_gamma_map(): """Test Gamma MAP inverse.""" forward = read_forward_solution(fname_fwd) forward = convert_forward_solution(forward, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0), proj=False) evoked.resample(50, npad=100) evoked.crop(tmin=0.1, tmax=0.14) # crop to window around peak cov = read_cov(fname_cov) cov = regularize(cov, evoked.info, rank=None) alpha = 0.5 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=True, update_mode=1) _check_stc(stc, evoked, 68477, 'lh', fwd=forward) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1) _check_stc(stc, evoked, 82010, 'lh', fwd=forward) dips = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1, return_as_dipoles=True) assert (isinstance(dips[0], Dipole)) stc_dip = make_stc_from_dipoles(dips, forward['src']) _check_stcs(stc, stc_dip) # force fixed orientation stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=2, loose=0, return_residual=False) _check_stc(stc, evoked, 85739, 'lh', fwd=forward, ratio=20.)
def invs(): """Inverses of various amounts of loose.""" fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) fwd_surf = convert_forward_solution(fwd, surf_ori=True) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1.) free_surf = make_inverse_operator(evoked.info, fwd_surf, noise_cov, loose=1.) freeish = make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.9999) fixed = make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.) fixedish = make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.0001) assert_allclose(free['source_nn'], np.kron(np.ones(fwd['nsource']), np.eye(3)).T, atol=1e-7) # This is the one exception: assert not np.allclose(free['source_nn'], free_surf['source_nn']) assert_allclose(free['source_nn'], np.tile(np.eye(3), (free['nsource'], 1)), atol=1e-7) # All others are similar: for other in (freeish, fixedish): assert_allclose(free_surf['source_nn'], other['source_nn'], atol=1e-7) assert_allclose(free_surf['source_nn'][2::3], fixed['source_nn'], atol=1e-7) expected_nn = np.concatenate([_get_src_nn(s) for s in fwd['src']]) assert_allclose(fixed['source_nn'], expected_nn, atol=1e-7) return evoked, free, free_surf, freeish, fixed, fixedish
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) evoked.resample(50) evoked.crop(tmin=0, tmax=0.3) cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.2 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=True, update_mode=1, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) assert_true(np.concatenate(stc.vertices)[idx] == 96397) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=False, update_mode=1, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) assert_true(np.concatenate(stc.vertices)[idx] == 82010) # force fixed orientation stc, res = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=False, update_mode=2, loose=None, return_residual=True, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) # assert_true(np.concatenate(stc.vertices)[idx] == 83398) # XXX FIX assert_array_almost_equal(evoked.times, res.times)
def test_mxne_inverse_sure(): """Tests SURE criterion for automatic alpha selection on MEG data.""" def data_fun(times): data = np.zeros(times.shape) data[times >= 0] = 50e-9 return data n_dipoles = 2 raw = mne.io.read_raw_fif(fname_raw) info = mne.io.read_info(fname_data) with info._unlock(): info['projs'] = [] noise_cov = mne.make_ad_hoc_cov(info) label_names = ['Aud-lh', 'Aud-rh'] labels = [mne.read_label(data_path + '/MEG/sample/labels/%s.label' % ln) for ln in label_names] fname_fwd = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') forward = mne.read_forward_solution(fname_fwd) forward = mne.pick_types_forward(forward, meg="grad", eeg=False, exclude=raw.info['bads']) times = np.arange(100, dtype=np.float64) / raw.info['sfreq'] - 0.1 stc = simulate_sparse_stc(forward['src'], n_dipoles=n_dipoles, times=times, random_state=1, labels=labels, data_fun=data_fun) nave = 30 evoked = simulate_evoked(forward, stc, info, noise_cov, nave=nave, use_cps=False, iir_filter=None) evoked = evoked.crop(tmin=0, tmax=10e-3) stc_ = mixed_norm(evoked, forward, noise_cov, loose=0.9, n_mxne_iter=5, depth=0.9) assert_array_equal(stc_.vertices, stc.vertices)
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) evoked.resample(50) evoked.crop(tmin=0, tmax=0.3) cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.2 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=True, update_mode=1, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) assert_true(np.concatenate(stc.vertno)[idx] == 96397) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=False, update_mode=1, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) assert_true(np.concatenate(stc.vertno)[idx] == 82010) # force fixed orientation stc, res = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=False, update_mode=2, loose=None, return_residual=True, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) # assert_true(np.concatenate(stc.vertno)[idx] == 83398) # XXX FIX assert_array_almost_equal(evoked.times, res.times)
def test_simulate_evoked(): """Test simulation of evoked data.""" raw = read_raw_fif(raw_fname, add_eeg_ref=False) fwd = read_forward_solution(fwd_fname, force_fixed=True) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) snr = 6 # dB tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series for 2 dipoles stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times) stc._data *= 1e-9 # Generate noisy evoked data iir_filter = [1, -0.9] evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, snr, tmin=0.0, tmax=0.2, iir_filter=iir_filter) assert_array_almost_equal(evoked.times, stc.times) assert_true(len(evoked.data) == len(fwd['sol']['data'])) # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 assert_raises(RuntimeError, simulate_evoked, fwd, stc_bad, evoked_template.info, cov, snr, tmin=0.0, tmax=0.2) evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov, np.inf, tmin=0.0, tmax=0.2) evoked_2 = simulate_evoked(fwd, stc, evoked_template.info, cov, np.inf, tmin=0.0, tmax=0.2) assert_array_equal(evoked_1.data, evoked_2.data) # test snr definition in dB evoked_noise = simulate_evoked(fwd, stc, evoked_template.info, cov, snr=snr, tmin=None, tmax=None, iir_filter=None) evoked_clean = simulate_evoked(fwd, stc, evoked_template.info, cov, snr=np.inf, tmin=None, tmax=None, iir_filter=None) noise = evoked_noise.data - evoked_clean.data empirical_snr = 10 * np.log10(np.mean((evoked_clean.data ** 2).ravel()) / np.mean((noise ** 2).ravel())) assert_almost_equal(snr, empirical_snr, decimal=5) cov['names'] = cov.ch_names[:-2] # Error channels are different. assert_raises(ValueError, simulate_evoked, fwd, stc, evoked_template.info, cov, snr=3., tmin=None, tmax=None, iir_filter=None)
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 test_simulate_evoked(): """ Test simulation of evoked data """ raw = Raw(raw_fname) fwd = read_forward_solution(fwd_fname, force_fixed=True) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) snr = 6 # dB tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series for 2 dipoles stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times) stc._data *= 1e-9 # Generate noisy evoked data iir_filter = [1, -0.9] evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, snr, tmin=0.0, tmax=0.2, iir_filter=iir_filter) assert_array_almost_equal(evoked.times, stc.times) assert_true(len(evoked.data) == len(fwd['sol']['data'])) # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 assert_raises(RuntimeError, simulate_evoked, fwd, stc_bad, evoked_template.info, cov, snr, tmin=0.0, tmax=0.2) evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov, np.inf, tmin=0.0, tmax=0.2) evoked_2 = simulate_evoked(fwd, stc, evoked_template.info, cov, np.inf, tmin=0.0, tmax=0.2) assert_array_equal(evoked_1.data, evoked_2.data) # test snr definition in dB evoked_noise = simulate_evoked(fwd, stc, evoked_template.info, cov, snr=snr, tmin=None, tmax=None, iir_filter=None) evoked_clean = simulate_evoked(fwd, stc, evoked_template.info, cov, snr=np.inf, tmin=None, tmax=None, iir_filter=None) noise = evoked_noise.data - evoked_clean.data empirical_snr = 10 * np.log10(np.mean((evoked_clean.data ** 2).ravel()) / np.mean((noise ** 2).ravel())) assert_almost_equal(snr, empirical_snr, decimal=5) cov['names'] = cov.ch_names[:-2] # Error channels are different. assert_raises(ValueError, simulate_evoked, fwd, stc, evoked_template.info, cov, snr=3., tmin=None, tmax=None, iir_filter=None)
def test_restrict_forward_to_label(): """Test restriction of source space to label """ fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, "MEG", "sample", "labels") labels = ["Aud-lh", "Vis-rh"] label_lh = read_label(op.join(label_path, labels[0] + ".label")) label_rh = read_label(op.join(label_path, labels[1] + ".label")) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd["src"][0]["vertno"], label_lh.vertices) src_sel_lh = np.searchsorted(fwd["src"][0]["vertno"], src_sel_lh) src_sel_rh = np.intersect1d(fwd["src"][1]["vertno"], label_rh.vertices) src_sel_rh = np.searchsorted(fwd["src"][1]["vertno"], src_sel_rh) + len(fwd["src"][0]["vertno"]) assert_equal(fwd_out["sol"]["ncol"], len(src_sel_lh) + len(src_sel_rh)) assert_equal(fwd_out["src"][0]["nuse"], len(src_sel_lh)) assert_equal(fwd_out["src"][1]["nuse"], len(src_sel_rh)) assert_equal(fwd_out["src"][0]["vertno"], src_sel_lh) assert_equal(fwd_out["src"][1]["vertno"], src_sel_rh) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, "MEG", "sample", "labels") labels = ["Aud-lh", "Vis-rh"] label_lh = read_label(op.join(label_path, labels[0] + ".label")) label_rh = read_label(op.join(label_path, labels[1] + ".label")) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd["src"][0]["vertno"], label_lh.vertices) src_sel_lh = np.searchsorted(fwd["src"][0]["vertno"], src_sel_lh) src_sel_rh = np.intersect1d(fwd["src"][1]["vertno"], label_rh.vertices) src_sel_rh = np.searchsorted(fwd["src"][1]["vertno"], src_sel_rh) + len(fwd["src"][0]["vertno"]) assert_equal(fwd_out["sol"]["ncol"], 3 * (len(src_sel_lh) + len(src_sel_rh))) assert_equal(fwd_out["src"][0]["nuse"], len(src_sel_lh)) assert_equal(fwd_out["src"][1]["nuse"], len(src_sel_rh)) assert_equal(fwd_out["src"][0]["vertno"], src_sel_lh) assert_equal(fwd_out["src"][1]["vertno"], src_sel_rh)
def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
def test_simulate_evoked(): """Test simulation of evoked data.""" raw = read_raw_fif(raw_fname) fwd = read_forward_solution(fwd_fname) fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=False) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) cov = regularize(cov, evoked_template.info) nave = evoked_template.nave tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series for 2 dipoles stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times, random_state=42) # Generate noisy evoked data iir_filter = [1, -0.9] evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, iir_filter=iir_filter, nave=nave) assert_array_almost_equal(evoked.times, stc.times) assert_true(len(evoked.data) == len(fwd['sol']['data'])) assert_equal(evoked.nave, nave) # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 assert_raises(RuntimeError, simulate_evoked, fwd, stc_bad, evoked_template.info, cov) evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov, nave=np.inf) evoked_2 = simulate_evoked(fwd, stc, evoked_template.info, cov, nave=np.inf) assert_array_equal(evoked_1.data, evoked_2.data) # Test the equivalence snr to nave with warnings.catch_warnings(record=True): # deprecation evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, snr=6, random_state=42) assert_allclose(np.linalg.norm(evoked.data, ord='fro'), 0.00078346820226502716) cov['names'] = cov.ch_names[:-2] # Error channels are different. assert_raises(ValueError, simulate_evoked, fwd, stc, evoked_template.info, cov, nave=nave, iir_filter=None)
def test_apply_forward(): """Test projection of source space data to sensor space.""" start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True) assert isinstance(fwd, Forward) vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) gain_sum = np.sum(fwd['sol']['data'], axis=1) # Evoked evoked = read_evokeds(fname_evoked, condition=0) evoked.pick_types(meg=True) with pytest.warns(RuntimeWarning, match='only .* positive values'): evoked = apply_forward(fwd, stc, evoked.info, start=start, stop=stop) data = evoked.data times = evoked.times # do some tests assert_array_almost_equal(evoked.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) assert_array_almost_equal(times[0], t_start) assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq) # vector stc_vec = VectorSourceEstimate( fwd['source_nn'][:, :, np.newaxis] * stc.data[:, np.newaxis], stc.vertices, stc.tmin, stc.tstep) with pytest.warns(RuntimeWarning, match='very large'): evoked_2 = apply_forward(fwd, stc_vec, evoked.info) assert np.abs(evoked_2.data).mean() > 1e-5 assert_allclose(evoked.data, evoked_2.data, atol=1e-10) # Raw with pytest.warns(RuntimeWarning, match='only .* positive values'): raw_proj = apply_forward_raw(fwd, stc, evoked.info, start=start, stop=stop) data, times = raw_proj[:, :] # do some tests assert_array_almost_equal(raw_proj.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) atol = 1. / sfreq assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol) assert_allclose(raw_proj.last_samp / sfreq, t_start + (n_times - 1) / sfreq, atol=atol)
def test_apply_forward(): """Test projection of source space data to sensor space """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True) assert_true(isinstance(fwd, Forward)) vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) gain_sum = np.sum(fwd['sol']['data'], axis=1) # Evoked with warnings.catch_warnings(record=True) as w: evoked = read_evokeds(fname_evoked, condition=0) evoked.pick_types(meg=True) evoked = apply_forward(fwd, stc, evoked.info, start=start, stop=stop) assert_equal(len(w), 2) data = evoked.data times = evoked.times # do some tests assert_array_almost_equal(evoked.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) assert_array_almost_equal(times[0], t_start) assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq) # Raw raw_proj = apply_forward_raw(fwd, stc, evoked.info, start=start, stop=stop) data, times = raw_proj[:, :] # do some tests assert_array_almost_equal(raw_proj.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) atol = 1. / sfreq assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol) assert_allclose(raw_proj.last_samp / sfreq, t_start + (n_times - 1) / sfreq, atol=atol)
def _load_forward(): """Load forward models.""" fwd_free = mne.read_forward_solution(fname_fwd) fwd_free = mne.pick_types_forward(fwd_free, meg=True, eeg=False) fwd_free = mne.convert_forward_solution(fwd_free, surf_ori=False) fwd_surf = mne.convert_forward_solution(fwd_free, surf_ori=True, use_cps=False) fwd_fixed = mne.convert_forward_solution(fwd_free, force_fixed=True, use_cps=False) fwd_vol = mne.read_forward_solution(fname_fwd_vol) return fwd_free, fwd_surf, fwd_fixed, fwd_vol
def test_make_forward_solution_sphere(): """Test making a forward solution with a sphere model.""" temp_dir = _TempDir() fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif') src = setup_source_space('sample', 'oct2', subjects_dir=subjects_dir, add_dist=False) write_source_spaces(fname_src_small, src) # to enable working with MNE-C out_name = op.join(temp_dir, 'tmp-fwd.fif') run_subprocess(['mne_forward_solution', '--meg', '--eeg', '--meas', fname_raw, '--src', fname_src_small, '--mri', fname_trans, '--fwd', out_name]) fwd = read_forward_solution(out_name) sphere = make_sphere_model(verbose=True) fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=True, verbose=True) _compare_forwards(fwd, fwd_py, 366, 108, meg_rtol=5e-1, meg_atol=1e-6, eeg_rtol=5e-1, eeg_atol=5e-1) # Since the above is pretty lax, let's check a different way for meg, eeg in zip([True, False], [False, True]): fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg) fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg) assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(), fwd_py_['sol']['data'].ravel())[0, 1], 1.0, rtol=1e-3) # Number of layers in the sphere model doesn't matter for MEG # (as long as no sources are omitted due to distance) assert len(sphere['layers']) == 4 fwd = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=False) sphere_1 = make_sphere_model(head_radius=None) assert len(sphere_1['layers']) == 0 assert_array_equal(sphere['r0'], sphere_1['r0']) fwd_1 = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=False) _compare_forwards(fwd, fwd_1, 306, 108, meg_rtol=1e-12, meg_atol=1e-12) # Homogeneous model sphere = make_sphere_model(head_radius=None) with pytest.raises(RuntimeError, match='zero shells.*EEG'): make_forward_solution(fname_raw, fname_trans, src, sphere)
def test_restrict_forward_to_stc(): """Test restriction of source space to source SourceEstimate """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_true(isinstance(fwd_out, Forward)) assert_equal(fwd_out['sol']['ncol'], 20) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) fwd = read_forward_solution(fname, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_equal(fwd_out['sol']['ncol'], 60) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5])
def test_make_forward_solution_sphere(): """Test making a forward solution with a sphere model""" temp_dir = _TempDir() fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif') src = setup_source_space('sample', fname_src_small, 'oct2', subjects_dir=subjects_dir, add_dist=False) out_name = op.join(temp_dir, 'tmp-fwd.fif') run_subprocess([ 'mne_forward_solution', '--meg', '--eeg', '--meas', fname_raw, '--src', fname_src_small, '--mri', fname_trans, '--fwd', out_name ]) fwd = read_forward_solution(out_name) sphere = make_sphere_model(verbose=True) fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=True, verbose=True) _compare_forwards(fwd, fwd_py, 366, 108, meg_rtol=5e-1, meg_atol=1e-6, eeg_rtol=5e-1, eeg_atol=5e-1) # Since the above is pretty lax, let's check a different way for meg, eeg in zip([True, False], [False, True]): fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg) fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg) assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(), fwd_py_['sol']['data'].ravel())[0, 1], 1.0, rtol=1e-3)
def _load_forward(): """Load forward models.""" fwd_free = mne.read_forward_solution(fname_fwd) fwd_free = mne.pick_types_forward(fwd_free, meg=True, eeg=False) fwd_free = mne.convert_forward_solution(fwd_free, surf_ori=False) fwd_surf = mne.convert_forward_solution(fwd_free, surf_ori=True, use_cps=False) fwd_fixed = mne.convert_forward_solution(fwd_free, force_fixed=True, use_cps=False) fwd_vol = mne.read_forward_solution(fname_fwd_vol) label = mne.read_label(fname_label) return fwd_free, fwd_surf, fwd_fixed, fwd_vol, label
def test_restrict_forward_to_stc(): """Test restriction of source space to source SourceEstimate """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_true(isinstance(fwd_out, Forward)) assert_equal(fwd_out['sol']['ncol'], 20) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_equal(fwd_out['sol']['ncol'], 60) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5])
def test_simulate_evoked(): """Test simulation of evoked data.""" raw = read_raw_fif(raw_fname) fwd = read_forward_solution(fwd_fname) fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=False) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) cov = regularize(cov, evoked_template.info) nave = evoked_template.nave tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series for 2 dipoles stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times, random_state=42) # Generate noisy evoked data iir_filter = [1, -0.9] evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, iir_filter=iir_filter, nave=nave) assert_array_almost_equal(evoked.times, stc.times) assert len(evoked.data) == len(fwd['sol']['data']) assert_equal(evoked.nave, nave) assert len(evoked.info['projs']) == len(cov['projs']) evoked_white = whiten_evoked(evoked, cov) assert abs(evoked_white.data[:, 0].std() - 1.) < 0.1 # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 pytest.raises(RuntimeError, simulate_evoked, fwd, stc_bad, evoked_template.info, cov) evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov, nave=np.inf) evoked_2 = simulate_evoked(fwd, stc, evoked_template.info, cov, nave=np.inf) assert_array_equal(evoked_1.data, evoked_2.data) cov['names'] = cov.ch_names[:-2] # Error channels are different. with pytest.raises(RuntimeError, match='Not all channels present'): simulate_evoked(fwd, stc, evoked_template.info, cov)
def test_simulate_evoked(): """Test simulation of evoked data.""" raw = read_raw_fif(raw_fname) fwd = read_forward_solution(fwd_fname) fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=False) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) cov = regularize(cov, evoked_template.info) nave = evoked_template.nave tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series for 2 dipoles stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times, random_state=42) # Generate noisy evoked data iir_filter = [1, -0.9] evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, iir_filter=iir_filter, nave=nave) assert_array_almost_equal(evoked.times, stc.times) assert len(evoked.data) == len(fwd['sol']['data']) assert_equal(evoked.nave, nave) assert len(evoked.info['projs']) == len(cov['projs']) evoked_white = whiten_evoked(evoked, cov) assert abs(evoked_white.data[:, 0].std() - 1.) < 0.1 # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 pytest.raises(ValueError, simulate_evoked, fwd, stc_bad, evoked_template.info, cov) evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov, nave=np.inf) evoked_2 = simulate_evoked(fwd, stc, evoked_template.info, cov, nave=np.inf) assert_array_equal(evoked_1.data, evoked_2.data) cov['names'] = cov.ch_names[:-2] # Error channels are different. with pytest.raises(RuntimeError, match='Not all channels present'): simulate_evoked(fwd, stc, evoked_template.info, cov)
def test_simulate_evoked(): """ Test simulation of evoked data """ raw = Raw(raw_fname) fwd = read_forward_solution(fwd_fname, force_fixed=True) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) label_names = ['Aud-lh', 'Aud-rh'] labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label)) for label in label_names] evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template = pick_types_evoked(evoked_template, meg=True, eeg=True, exclude=raw.info['bads']) snr = 6 # dB tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series from 2 Morlet wavelets stc_data = np.zeros((len(labels), len(times))) Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5]) stc_data[0][:len(Ws[0])] = np.real(Ws[0]) stc_data[1][:len(Ws[1])] = np.real(Ws[1]) stc_data *= 100 * 1e-9 # use nAm as unit # time translation stc_data[1] = np.roll(stc_data[1], 80) stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep, random_state=0) # Generate noisy evoked data iir_filter = [1, -0.9] with warnings.catch_warnings(record=True): warnings.simplefilter('always') # positive semidefinite warning evoked = generate_evoked(fwd, stc, evoked_template, cov, snr, tmin=0.0, tmax=0.2, iir_filter=iir_filter) assert_array_almost_equal(evoked.times, stc.times) assert_true(len(evoked.data) == len(fwd['sol']['data'])) # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 assert_raises(RuntimeError, generate_evoked, fwd, stc_bad, evoked_template, cov, snr, tmin=0.0, tmax=0.2)
def calculate_forward_solution(self, data): """ Calculates the forward solution :param data: :return: """ print("Calculating forward solution...") self.fwd = mne.make_forward_solution(data.info, self.trans_path, self.src, self.bem_path, n_jobs=CPU_THREADS, verbose=self.verbose) self.fwd = mne.pick_types_forward(self.fwd, meg=self.channel_types['meg'], eeg=self.channel_types['eeg'], exclude=data.info['bads']) return self.fwd
def test_mxne_inverse_empty(): """Tests solver with too high alpha.""" evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.pick("grad", exclude="bads") fname_fwd = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') forward = mne.read_forward_solution(fname_fwd) forward = mne.pick_types_forward(forward, meg="grad", eeg=False, exclude=evoked.info['bads']) cov = read_cov(fname_cov) with pytest.warns(RuntimeWarning, match='too big'): stc, residual = mixed_norm( evoked, forward, cov, n_mxne_iter=3, alpha=99, return_residual=True) assert stc.data.size == 0 assert stc.vertices[0].size == 0 assert stc.vertices[1].size == 0 assert_allclose(evoked.data, residual.data)
def _load_restricted_forward(source_vertno1, source_vertno2): """Load forward models and restrict them so that they include source vertices""" fwd_free = mne.read_forward_solution(fname_fwd) fwd_free = mne.pick_types_forward(fwd_free, meg='grad', eeg=False) # Restrict forward vertno_lh = np.random.choice(fwd_free['src'][0]['vertno'], 40, replace=False) if source_vertno1 not in vertno_lh: vertno_lh = np.append(vertno_lh, source_vertno1) vertno_rh = np.random.choice(fwd_free['src'][1]['vertno'], 40, replace=False) if source_vertno2 not in vertno_rh: vertno_rh = np.append(vertno_rh, source_vertno2) fwd_free = restrict_forward_to_vertices(fwd_free, [vertno_lh, vertno_rh]) fwd_fixed = mne.convert_forward_solution(fwd_free, force_fixed=True, use_cps=False) return fwd_free, fwd_fixed
def test_simulate_evoked(): """ Test simulation of evoked data """ raw = Raw(raw_fname) fwd = read_forward_solution(fwd_fname, force_fixed=True) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) evoked_template = read_evokeds(ave_fname, condition=0, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) snr = 6 # dB tmin = -0.1 sfreq = 1000. # Hz tstep = 1. / sfreq n_samples = 600 times = np.linspace(tmin, tmin + n_samples * tstep, n_samples) # Generate times series for 2 dipoles stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times) stc._data *= 1e-9 # Generate noisy evoked data iir_filter = [1, -0.9] evoked = simulate_evoked(fwd, stc, evoked_template.info, cov, snr, tmin=0.0, tmax=0.2, iir_filter=iir_filter) assert_array_almost_equal(evoked.times, stc.times) assert_true(len(evoked.data) == len(fwd['sol']['data'])) # make a vertex that doesn't exist in fwd, should throw error stc_bad = stc.copy() mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']]) stc_bad.vertices[0][0] = mv + 1 assert_raises(RuntimeError, simulate_evoked, fwd, stc_bad, evoked_template.info, cov, snr, tmin=0.0, tmax=0.2) evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov, np.inf, tmin=0.0, tmax=0.2) evoked_2 = simulate_evoked(fwd, stc, evoked_template.info, cov, np.inf, tmin=0.0, tmax=0.2) assert_array_equal(evoked_1.data, evoked_2.data)
def read_forward_solution_meg(*args, **kwargs): """Read MEG forward.""" fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
############################################################################### # Load real data as templates data_path = sample.data_path() raw = Raw(data_path + '/MEG/sample/sample_audvis_raw.fif') proj = read_proj(data_path + '/MEG/sample/sample_audvis_ecg_proj.fif') raw.info['projs'] += proj raw.info['bads'] = ['MEG 2443', 'EEG 053'] # mark bad channels fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif' cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif' fwd = read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True) fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = read_cov(cov_fname) condition = 'Left Auditory' evoked_template = read_evokeds(ave_fname, condition=condition, baseline=None) evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads']) label_names = ['Aud-lh', 'Aud-rh'] labels = [ read_label(data_path + '/MEG/sample/labels/%s.label' % ln) for ln in label_names ] ############################################################################### # Generate source time courses and the correspond evoked data
############################################################################### # Load real data as templates data_path = sample.data_path() raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif') proj = mne.read_proj(data_path + '/MEG/sample/sample_audvis_ecg_proj.fif') raw.info['projs'] += proj raw.info['bads'] = ['MEG 2443', 'EEG 053'] # mark bad channels fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif' cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif' fwd = mne.read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True) fwd = mne.pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads']) cov = mne.read_cov(cov_fname) info = mne.io.read_info(ave_fname) label_names = ['Aud-lh', 'Aud-rh'] labels = [mne.read_label(data_path + '/MEG/sample/labels/%s.label' % ln) for ln in label_names] ############################################################################### # Generate source time courses from 2 dipoles and the correspond evoked data times = np.arange(300, dtype=np.float) / raw.info['sfreq'] - 0.1 rng = np.random.RandomState(42) def data_fun(times):
def read_forward_solution_meg(*args, **kwargs): fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag') # Show whitening evoked.plot_white(noise_cov) ############################################################################### # Inverse modeling: MNE/dSPM on evoked and raw data # ------------------------------------------------- # 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, surf_ori=True) # Restrict forward solution as necessary for MEG fwd = mne.pick_types_forward(fwd, meg=True, eeg=False) # 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.
data_path = sample.data_path() subjects_dir = data_path + '/subjects/' fname_fwd_emeg = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif' fname_evo = data_path + '/MEG/sample/sample_audvis-ave.fif' # read forward solution with EEG and MEG forward_emeg = mne.read_forward_solution(fname_fwd_emeg) # forward operator with fixed source orientations forward_emeg = mne.convert_forward_solution(forward_emeg, surf_ori=True, force_fixed=True) # create a forward solution with MEG only forward_meg = mne.pick_types_forward(forward_emeg, meg=True, eeg=False) # noise covariance matrix noise_cov = mne.read_cov(fname_cov) # evoked data for info evoked = mne.read_evokeds(fname_evo, 0) # make inverse operator from forward solution for MEG and EEGMEG inv_emeg = mne.minimum_norm.make_inverse_operator(info=evoked.info, forward=forward_emeg, noise_cov=noise_cov, loose=0., depth=None) inv_meg = mne.minimum_norm.make_inverse_operator(info=evoked.info,
# covariance of the temporal noise for each source point stc_covar = np.zeros([n_times, n_times], dtype = np.float) a = 1e-3 for i in range(n_times): for j in range(n_times): stc_covar[i,j] = np.exp(- a*(i-j)**2) if i == j: stc_covar[i,j] *= 1.01 amp = 10.0*1e-9 stc_data *= amp # use nAm as unit # load the forward solution fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True) fwd = mne.pick_types_forward(fwd, meg=True, eeg=False, exclude=bads) # get the indices of source points for each ROI src = fwd['src'] label_ind = list() for i in range(len(labels)): _, sel = mne.source_space.label_src_vertno_sel(labels[i],src) label_ind.append(sel) # stc0_data: source time series template with no noise n_source = fwd['sol']['ncol'] stc0_data = np.zeros([n_source, n_times]) for i in range(len(labels)): stc0 = mne.simulation.simulate_stc(fwd['src'], labels[i:i+1], stc_data[i:i+1,:], -0.1, 1.0/sfreq) stc0_data[label_ind[i],:] = stc0.data del(stc0)
def read_forward_solution_meg(*args, **kwargs): """Read forward MEG.""" fwd = read_forward_solution(*args) fwd = convert_forward_solution(fwd, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
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)
def _read_forward_solution_meg(*args, **kwargs): fwd = mne.read_forward_solution(*args) fwd = mne.convert_forward_solution(fwd, **kwargs) return mne.pick_types_forward(fwd, meg=True, eeg=False)
def read_forward_solution_eeg(*args, **kwargs): fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=False, eeg=True) return fwd
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
from tqdm import tqdm import config from config import dics_settings from config import fname from utils import set_directory ############################################################################### # Load volume source space ############################################################################### info = mne.io.read_info(fname.sample_raw) info = mne.pick_info(info, mne.pick_types(info, meg=True, eeg=False)) fwd = mne.read_forward_solution(fname.fwd_man) fwd = mne.pick_types_forward(fwd, meg=True, eeg=False) vsrc = fwd['src'] vertno = vsrc[0]['vertno'] # needs to be set for plot_vstc_sliced_old to work if vsrc[0]['subject_his_id'] is None: vsrc[0]['subject_his_id'] = 'sample' ############################################################################### # Get data from csv files ############################################################################### dfs = [] for vertex in tqdm(range(3756), total=3756): try:
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 # Load data evoked = mne.read_evokeds(fname_evoked, condition=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.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',