コード例 #1
0
def compute_fwd_sol(raw_info, trans_fname, src, bem, fwd_filename):
    import mne

    mne.make_forward_solution(raw_info, trans_fname, src, bem,
                              fwd_filename,
                              mindist=5.0, # ignore sources <= 0mm from inner skull
                              meg=True, eeg=False,
                              n_jobs=2,
                              overwrite=True)

    print '\n*** FWD file %s written!!!\n' % fwd_filename
コード例 #2
0
def test_make_forward_solution():
    """Test making M-EEG forward solution from python."""
    fwd_py = make_forward_solution(fname_raw, fname_trans, fname_src,
                                   fname_bem, mindist=5.)
    assert (isinstance(fwd_py, Forward))
    fwd = read_forward_solution(fname_meeg)
    assert (isinstance(fwd, Forward))
    _compare_forwards(fwd, fwd_py, 366, 1494, meg_rtol=1e-3)
    # Homogeneous model
    with pytest.raises(RuntimeError, match='homogeneous.*1-layer.*EEG'):
        make_forward_solution(fname_raw, fname_trans, fname_src,
                              fname_bem_meg)
コード例 #3
0
def test_inverse_operator_channel_ordering():
    """Test MNE inverse computation is immune to channel reorderings
    """
    # These are with original ordering
    evoked = _get_evoked()
    noise_cov = read_cov(fname_cov)

    fwd_orig = make_forward_solution(evoked.info, fname_trans, src_fname,
                                     fname_bem, eeg=True, mindist=5.0)
    fwd_orig = convert_forward_solution(fwd_orig, surf_ori=True)
    inv_orig = make_inverse_operator(evoked.info, fwd_orig, noise_cov,
                                     loose=0.2, depth=0.8,
                                     limit_depth_chs=False)
    stc_1 = apply_inverse(evoked, inv_orig, lambda2, "dSPM")

    # Assume that a raw reordering applies to both evoked and noise_cov,
    # so we don't need to create those from scratch. Just reorder them,
    # then try to apply the original inverse operator
    new_order = np.arange(len(evoked.info['ch_names']))
    randomiser = np.random.RandomState(42)
    randomiser.shuffle(new_order)
    evoked.data = evoked.data[new_order]
    evoked.info['chs'] = [evoked.info['chs'][n] for n in new_order]
    evoked.info._update_redundant()
    evoked.info._check_consistency()

    cov_ch_reorder = [c for c in evoked.info['ch_names']
                      if (c in noise_cov.ch_names)]

    new_order_cov = [noise_cov.ch_names.index(name) for name in cov_ch_reorder]
    noise_cov['data'] = noise_cov.data[np.ix_(new_order_cov, new_order_cov)]
    noise_cov['names'] = [noise_cov['names'][idx] for idx in new_order_cov]

    fwd_reorder = make_forward_solution(evoked.info, fname_trans, src_fname,
                                        fname_bem, eeg=True, mindist=5.0)
    fwd_reorder = convert_forward_solution(fwd_reorder, surf_ori=True)
    inv_reorder = make_inverse_operator(evoked.info, fwd_reorder, noise_cov,
                                        loose=0.2, depth=0.8,
                                        limit_depth_chs=False)

    stc_2 = apply_inverse(evoked, inv_reorder, lambda2, "dSPM")

    assert_equal(stc_1.subject, stc_2.subject)
    assert_array_equal(stc_1.times, stc_2.times)
    assert_allclose(stc_1.data, stc_2.data, rtol=1e-5, atol=1e-5)
    assert_true(inv_orig['units'] == inv_reorder['units'])

    # Reload with original ordering & apply reordered inverse
    evoked = _get_evoked()
    noise_cov = read_cov(fname_cov)

    stc_3 = apply_inverse(evoked, inv_reorder, lambda2, "dSPM")
    assert_allclose(stc_1.data, stc_3.data, rtol=1e-5, atol=1e-5)
コード例 #4
0
ファイル: stat_cluster.py プロジェクト: dongqunxi/Chronopro
def apply_inverse_ave(fnevo, min_subject='fsaverage'):
    
    from mne import make_forward_solution
    from mne.minimum_norm import 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)
        #fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' 
        subject = name.split('_')[0]
        fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' %subject
        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,fibp1-45-cov.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 = mne.minimum_norm.make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.2,
                                                     depth=0.8, limit_depth_chs=False)
        write_inverse_operator(fn_inv, inv)
コード例 #5
0
    def compute_forward_and_inverse_solutions(self, orientation = 'fixed'):
        """docstring for compute_forward_solution"""

        info = self.grand_average_evoked.info
        trans = mne.read_trans(op.join(self.processed_files, '%s-trans.fif' %self.subject))
        src = glob.glob(op.join(self.subjects_dir, self.subject, 'bem', '*-ico-4-src.fif'))[0]
        bem = glob.glob(op.join(self.subjects_dir, self.subject, 'bem', '*-bem-sol.fif'))[0]
        fname = op.join(self.processed_files, '%s_forward.fif' %self.subject)

        # check if fwd exists, if not, make it
        if not op.exists(fname):
            fwd = mne.make_forward_solution(info = info, trans = trans, src = src,
                                            bem = bem, fname = fname, meg = True, eeg = False,
                                            overwrite = True, ignore_ref = True)

            self.add_preprocessing_notes("Forward solution generated and saved to %s" %fname)

        if orientation == 'fixed':
            force_fixed = True
        else:
            force_fixed = False

        fwd = mne.read_forward_solution(fname,force_fixed=force_fixed)

        self.forward_solution = fwd

        inv = mne.minimum_norm.make_inverse_operator(info, self.forward_solution, self.cov_reg, loose = None, depth = None, fixed = force_fixed)
        self.inverse_solution = inv
        mne.minimum_norm.write_inverse_operator(op.join(self.processed_files, '%s_inv.fif' %self.subject), self.inverse_solution)

        self.add_preprocessing_notes("Inverse solution generated and saved to %s" %op.join(self.processed_files, '%s_inv.fif' %self.subject))
        return fwd, inv
コード例 #6
0
ファイル: test_inverse.py プロジェクト: teonbrooks/mne-python
def test_apply_inverse_sphere():
    """Test applying an inverse with a sphere model (rank-deficient)."""
    evoked = _get_evoked()
    evoked.pick_channels(evoked.ch_names[:306:8])
    evoked.info['projs'] = []
    cov = make_ad_hoc_cov(evoked.info)
    sphere = make_sphere_model('auto', 'auto', evoked.info)
    fwd = read_forward_solution(fname_fwd)
    vertices = [fwd['src'][0]['vertno'][::5],
                fwd['src'][1]['vertno'][::5]]
    stc = SourceEstimate(np.zeros((sum(len(v) for v in vertices), 1)),
                         vertices, 0., 1.)
    fwd = restrict_forward_to_stc(fwd, stc)
    fwd = make_forward_solution(evoked.info, fwd['mri_head_t'], fwd['src'],
                                sphere, mindist=5.)
    evoked = EvokedArray(fwd['sol']['data'].copy(), evoked.info)
    assert fwd['sol']['nrow'] == 39
    assert fwd['nsource'] == 101
    assert fwd['sol']['ncol'] == 303
    tempdir = _TempDir()
    temp_fname = op.join(tempdir, 'temp-inv.fif')
    inv = make_inverse_operator(evoked.info, fwd, cov, loose=1.)
    # This forces everything to be float32
    write_inverse_operator(temp_fname, inv)
    inv = read_inverse_operator(temp_fname)
    stc = apply_inverse(evoked, inv, method='eLORETA',
                        method_params=dict(eps=1e-2))
    # assert zero localization bias
    assert_array_equal(np.argmax(stc.data, axis=0),
                       np.repeat(np.arange(101), 3))
コード例 #7
0
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)
コード例 #8
0
ファイル: test_gamma_map.py プロジェクト: nfoti/mne-python
def test_gamma_map_vol_sphere():
    """Gamma MAP with a sphere forward and volumic source space"""
    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)

    info = evoked.info
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=15., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0,
                                        exclude=2.0)
    fwd = mne.make_forward_solution(info, trans=None, src=src, bem=sphere,
                                    eeg=False, meg=True)

    alpha = 0.5
    assert_raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
                  loose=0, return_residual=False)

    assert_raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
                  loose=0.2, return_residual=False)

    stc = gamma_map(evoked, fwd, cov, alpha, tol=1e-4,
                    xyz_same_gamma=False, update_mode=2,
                    return_residual=False)

    assert_array_almost_equal(stc.times, evoked.times, 5)
コード例 #9
0
def run_forward(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_fwd = op.join(data_path, '%s-meg-%s-fwd.fif' % (subject, spacing))
    fname_trans = op.join(study_path, 'ds117', subject, 'MEG', '%s-trans.fif' % subject)

    src = mne.setup_source_space(subject, spacing=spacing,
                                 subjects_dir=subjects_dir, overwrite=True,
                                 n_jobs=1, add_dist=False)

    src_fname = op.join(subjects_dir, subject, '%s-src.fif' % spacing)
    mne.write_source_spaces(src_fname, src)

    bem_model = mne.make_bem_model(subject, ico=4, subjects_dir=subjects_dir,
                                   conductivity=(0.3,))
    bem = mne.make_bem_solution(bem_model)
    info = mne.read_evokeds(fname_ave, condition=0).info
    fwd = mne.make_forward_solution(info, trans=fname_trans, src=src, bem=bem,
                                    fname=None, meg=True, eeg=False,
                                    mindist=mindist, n_jobs=1, overwrite=True)
    fwd = mne.convert_forward_solution(fwd, surf_ori=True)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
コード例 #10
0
ファイル: test_morph.py プロジェクト: jhouck/mne-python
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
コード例 #11
0
ファイル: test_raw.py プロジェクト: jdammers/mne-python
def test_simulate_round_trip():
    """Test simulate_raw round trip calculations."""
    # Check a diagonal round-trip
    raw, src, stc, trans, sphere = _get_data()
    raw.pick_types(meg=True, stim=True)
    bem = read_bem_solution(bem_1_fname)
    old_bem = bem.copy()
    old_src = src.copy()
    old_trans = trans.copy()
    fwd = make_forward_solution(raw.info, trans, src, bem)
    # no omissions
    assert (sum(len(s['vertno']) for s in src) ==
            sum(len(s['vertno']) for s in fwd['src']) ==
            36)
    # make sure things were not modified
    assert (old_bem['surfs'][0]['coord_frame'] ==
            bem['surfs'][0]['coord_frame'])
    assert trans == old_trans
    _compare_source_spaces(src, old_src)
    data = np.eye(fwd['nsource'])
    raw.crop(0, (len(data) - 1) / raw.info['sfreq'])
    stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']],
                         0, 1. / raw.info['sfreq'])
    for use_cps in (False, True):
        this_raw = simulate_raw(raw, stc, trans, src, bem, cov=None,
                                use_cps=use_cps)
        this_raw.pick_types(meg=True, eeg=True)
        assert (old_bem['surfs'][0]['coord_frame'] ==
                bem['surfs'][0]['coord_frame'])
        assert trans == old_trans
        _compare_source_spaces(src, old_src)
        this_fwd = convert_forward_solution(fwd, force_fixed=True,
                                            use_cps=use_cps)
        assert_allclose(this_raw[:][0], this_fwd['sol']['data'],
                        atol=1e-12, rtol=1e-6)
コード例 #12
0
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)
コード例 #13
0
ファイル: cluster_ROIs.py プロジェクト: dongqunxi/ChronoProc
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')
コード例 #14
0
ファイル: test_raw.py プロジェクト: Eric89GXL/mne-python
def test_simulate_round_trip(raw_data):
    """Test simulate_raw round trip calculations."""
    # Check a diagonal round-trip
    raw, src, stc, trans, sphere = raw_data
    raw.pick_types(meg=True, stim=True)
    bem = read_bem_solution(bem_1_fname)
    old_bem = bem.copy()
    old_src = src.copy()
    old_trans = trans.copy()
    fwd = make_forward_solution(raw.info, trans, src, bem)
    # no omissions
    assert (sum(len(s['vertno']) for s in src) ==
            sum(len(s['vertno']) for s in fwd['src']) ==
            36)
    # make sure things were not modified
    assert (old_bem['surfs'][0]['coord_frame'] ==
            bem['surfs'][0]['coord_frame'])
    assert trans == old_trans
    _compare_source_spaces(src, old_src)
    data = np.eye(fwd['nsource'])
    raw.crop(0, (len(data) - 1) / raw.info['sfreq'])
    stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']],
                         0, 1. / raw.info['sfreq'])
    for use_fwd in (None, fwd):
        if use_fwd is None:
            use_trans, use_src, use_bem = trans, src, bem
        else:
            use_trans = use_src = use_bem = None
        with pytest.deprecated_call():
            this_raw = simulate_raw(raw, stc, use_trans, use_src, use_bem,
                                    cov=None, forward=use_fwd)
        this_raw.pick_types(meg=True, eeg=True)
        assert (old_bem['surfs'][0]['coord_frame'] ==
                bem['surfs'][0]['coord_frame'])
        assert trans == old_trans
        _compare_source_spaces(src, old_src)
        this_fwd = convert_forward_solution(fwd, force_fixed=True)
        assert_allclose(this_raw[:][0], this_fwd['sol']['data'],
                        atol=1e-12, rtol=1e-6)
    with pytest.raises(ValueError, match='If forward is not None then'):
        simulate_raw(raw.info, stc, trans, src, bem, forward=fwd)
    # Not iterable
    with pytest.raises(TypeError, match='SourceEstimate, tuple, or iterable'):
        simulate_raw(raw.info, 0., trans, src, bem, None)
    # STC with a source that `src` does not have
    assert 0 not in src[0]['vertno']
    vertices = [[0, fwd['src'][0]['vertno'][0]], []]
    stc_bad = SourceEstimate(data[:2], vertices, 0, 1. / raw.info['sfreq'])
    with pytest.warns(RuntimeWarning,
                      match='1 of 2 SourceEstimate vertices'):
        simulate_raw(raw.info, stc_bad, trans, src, bem)
    assert 0 not in fwd['src'][0]['vertno']
    with pytest.warns(RuntimeWarning,
                      match='1 of 2 SourceEstimate vertices'):
        simulate_raw(raw.info, stc_bad, None, None, None, forward=fwd)
    # dev_head_t mismatch
    fwd['info']['dev_head_t']['trans'][0, 0] = 1.
    with pytest.raises(ValueError, match='dev_head_t.*does not match'):
        simulate_raw(raw.info, stc, None, None, None, forward=fwd)
コード例 #15
0
def test_make_forward_solution():
    """Test making M-EEG forward solution from python."""
    fwd_py = make_forward_solution(fname_raw, fname_trans, fname_src,
                                   fname_bem, mindist=5.0, eeg=True, meg=True)
    assert (isinstance(fwd_py, Forward))
    fwd = read_forward_solution(fname_meeg)
    assert (isinstance(fwd, Forward))
    _compare_forwards(fwd, fwd_py, 366, 1494, meg_rtol=1e-3)
コード例 #16
0
def test_make_forward_solution():
    """Test making M-EEG forward solution from python
    """
    fname_bem = op.join(subjects_dir, 'sample', 'bem',
                        'sample-5120-5120-5120-bem-sol.fif')
    fwd_py = make_forward_solution(fname_raw, mindist=5.0,
                                   src=fname_src, eeg=True, meg=True,
                                   bem=fname_bem, mri=fname_mri)
    fwd = read_forward_solution(fname_meeg)
    _compare_forwards(fwd, fwd_py, 366, 22494)
コード例 #17
0
def test_make_forward_solution_discrete():
    """Test making and converting a forward solution with discrete src."""
    # smoke test for depth weighting and discrete source spaces
    src = read_source_spaces(fname_src)[0]
    src = SourceSpaces([src] + setup_volume_source_space(
        pos=dict(rr=src['rr'][src['vertno'][:3]].copy(),
                 nn=src['nn'][src['vertno'][:3]].copy())))
    sphere = make_sphere_model()
    fwd = make_forward_solution(fname_raw, fname_trans, src, sphere,
                                meg=True, eeg=False)
    convert_forward_solution(fwd, surf_ori=True)
コード例 #18
0
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)
コード例 #19
0
ファイル: base.py プロジェクト: kingjr/jr-tools
def forward_pipeline(raw_fname, subject, fwd_fname=None, trans_fname=None,
                     subjects_dir=None, overwrite=False, ignore_ref=True):
    import os.path as op
    from mne.utils import get_config
    if subjects_dir is None:
        subjects_dir = get_config('SUBJECTS_DIR')

    # Setup paths
    save_dir = raw_fname.split('/')
    save_dir = ('/'.join(save_dir[:-1])
                if isinstance(save_dir, list) else save_dir)
    bem_dir = op.join(subjects_dir, subject, 'bem')

    bem_sol_fname = op.join(subjects_dir, subject, 'bem',
                            subject + '-5120-bem-sol.fif')
    oct_fname = op.join(subjects_dir, subject, 'bem',
                        subject + '-oct-6-src.fif')
    src_fname = op.join(bem_dir, subject + '-oct-6-src.fif')
    bem_sol_fname = op.join(bem_dir, subject + '-5120-bem-sol.fif')
    if trans_fname is None:
        trans_fname = op.join(save_dir, subject + '-trans.fif')
    if fwd_fname is None:
        fwd_fname = op.join(save_dir, subject + '-meg-fwd.fif')

    # 0. Checks Freesurfer segmentation and compute watershed bem
    miss_anatomy = not op.isfile(src_fname) or not op.exists(bem_sol_fname)
    for fname in [bem_sol_fname, oct_fname]:
        if not op.isfile(op.join(subjects_dir, subject, 'bem', fname)):
            miss_anatomy = True
    if miss_anatomy:
        raise RuntimeError('Could not find BEM (%s, %s), relaunch '
                           'pipeline_anatomy()' % (bem_sol_fname, oct_fname))

    # 1. Manual coregisteration head markers with coils
    if not op.isfile(trans_fname):
        raise RuntimeError('Could not find trans (%s), launch'
                           'coregistration.' % trans_fname)

    # 2. Forward solution
    if overwrite or not op.isfile(fwd_fname):
        from mne import (make_forward_solution, convert_forward_solution,
                         write_forward_solution)
        fwd = make_forward_solution(
            info=raw_fname, trans=trans_fname, src=oct_fname,
            bem=bem_sol_fname, fname=None, meg=True, eeg=False, mindist=5.0,
            overwrite=True, ignore_ref=ignore_ref)

        # Convert to surface orientation for better visualization
        fwd = convert_forward_solution(fwd, surf_ori=True)
        # save
        write_forward_solution(fwd_fname, fwd, overwrite=True)
    return
コード例 #20
0
ファイル: test_inverse.py プロジェクト: teonbrooks/mne-python
def test_inverse_ctf_comp():
    """Test interpolation with compensated CTF data."""
    ctf_dir = op.join(testing.data_path(download=False), 'CTF')
    raw_fname = op.join(ctf_dir, 'somMDYO-18av.ds')
    raw = mne.io.read_raw_ctf(raw_fname)
    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)
    inv = make_inverse_operator(raw.info, fwd, cov, loose=1.)
    apply_inverse_raw(raw, inv, 1. / 9.)
コード例 #21
0
def test_forward_mixed_source_space():
    """Test making the forward solution for a mixed source space
    """
    # get bem file
    fname_bem = op.join(subjects_dir, 'sample', 'bem',
                        'sample-5120-5120-5120-bem-sol.fif')
    # get the aseg file
    fname_aseg = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')

    # get the surface source space
    surf = setup_source_space('sample', fname=None, spacing='ico2')

    # setup two volume source spaces
    label_names = get_volume_labels_from_aseg(fname_aseg)
    vol_labels = [label_names[int(np.random.rand() * len(label_names))]
                  for _ in range(2)]
    vol1 = setup_volume_source_space('sample', fname=None, pos=20.,
                                     mri=fname_aseg,
                                     volume_label=vol_labels[0])
    vol2 = setup_volume_source_space('sample', fname=None, pos=20.,
                                     mri=fname_aseg,
                                     volume_label=vol_labels[1])

    # merge surfaces and volume
    src = surf + vol1 + vol2

    # calculate forward solution
    fwd = make_forward_solution(fname_raw, mri=fname_mri, src=src,
                                bem=fname_bem, fname=None)

    # extract source spaces
    src_from_fwd = fwd['src']

    # get the coordinate frame of each source space
    coord_frames = np.array([s['coord_frame'] for s in src_from_fwd])

    # assert that all source spaces are in head coordinates
    assert_true((coord_frames == FIFF.FIFFV_COORD_HEAD).all())

    # run tests for SourceSpaces.export_volume
    fname_img = op.join(temp_dir, 'temp-image.mgz')

    # head coordinates and mri_resolution, but trans file
    assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
                  mri_resolution=True, trans=None)

    # head coordinates and mri_resolution, but wrong trans file
    vox_mri_t = vol1[0]['vox_mri_t']
    assert_raises(RuntimeError, src_from_fwd.export_volume, fname_img,
                  mri_resolution=True, trans=vox_mri_t)
コード例 #22
0
ファイル: test_gamma_map.py プロジェクト: jhouck/mne-python
def test_gamma_map_vol_sphere():
    """Gamma MAP with a sphere forward and volumic source space."""
    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, rank=None)

    info = evoked.info
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=30., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0,
                                        exclude=2.0)
    fwd = mne.make_forward_solution(info, trans=None, src=src, bem=sphere,
                                    eeg=False, meg=True)

    alpha = 0.5
    pytest.raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
                  loose=0, return_residual=False)

    pytest.raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
                  loose=0.2, return_residual=False)

    stc = gamma_map(evoked, fwd, cov, alpha, tol=1e-4,
                    xyz_same_gamma=False, update_mode=2,
                    return_residual=False)

    assert_array_almost_equal(stc.times, evoked.times, 5)

    # Compare orientation obtained using fit_dipole and gamma_map
    # for a simulated evoked containing a single dipole
    stc = mne.VolSourceEstimate(50e-9 * np.random.RandomState(42).randn(1, 4),
                                vertices=stc.vertices[:1],
                                tmin=stc.tmin,
                                tstep=stc.tstep)
    evoked_dip = mne.simulation.simulate_evoked(fwd, stc, info, cov, nave=1e9,
                                                use_cps=True)

    dip_gmap = gamma_map(evoked_dip, fwd, cov, 0.1, return_as_dipoles=True)

    amp_max = [np.max(d.amplitude) for d in dip_gmap]
    dip_gmap = dip_gmap[np.argmax(amp_max)]
    assert (dip_gmap[0].pos[0] in src[0]['rr'][stc.vertices])

    dip_fit = mne.fit_dipole(evoked_dip, cov, sphere)[0]
    assert (np.abs(np.dot(dip_fit.ori[0], dip_gmap.ori[0])) > 0.99)
コード例 #23
0
ファイル: base.py プロジェクト: LauraGwilliams/jr-tools
def forward_pipeline(raw_fname, freesurfer_dir, subject,
                     trans_fname=None, fwd_fname=None, oct_fname=None,
                     bem_sol_fname=None, save_dir=None, overwrite=False):
    import os.path as op
    from jr.meg import check_freesurfer, mne_anatomy

    # Setup paths
    if save_dir is None:
        save_dir = '/'.join(raw_fname.split('/')[:-1])
        print('Save/read directory: %s' % save_dir)

    if trans_fname is None:
        trans_fname = op.join(save_dir, subject + '-trans.fif')
        bem_sol_fname = op.join(freesurfer_dir, subject, 'bem',
                                subject + '-5120-bem-sol.fif')
        oct_fname = op.join(freesurfer_dir, subject, 'bem',
                            subject + '-oct-6-src.fif')
        fwd_fname = op.join(save_dir, subject + '-meg-fwd.fif')

    # Checks Freesurfer segmentation and compute watershed bem
    if check_freesurfer(subjects_dir=freesurfer_dir,
                        subject=subject):
        mne_anatomy(subjects_dir=freesurfer_dir, subject=subject,
                    overwrite=overwrite)

    # Manual coregisteration head markers with coils
    if overwrite or not op.isfile(trans_fname):
        from mne.gui import coregistration
        coregistration(subject=subject, subjects_dir=freesurfer_dir,
                       inst=raw_fname)

    # Forward solution
    if overwrite or not op.exists(fwd_fname):
        from mne import (make_forward_solution, convert_forward_solution,
                         write_forward_solution)
        fwd = make_forward_solution(
            raw_fname, trans_fname, oct_fname, bem_sol_fname,
            fname=None, meg=True, eeg=False, mindist=5.0,
            overwrite=True, ignore_ref=True)

        # convert to surface orientation for better visualization
        fwd = convert_forward_solution(fwd, surf_ori=True)
        # save
        write_forward_solution(fwd_fname, fwd, overwrite=True)
    else:
        from mne import read_forward_solution
        fwd = read_forward_solution(fwd_fname, surf_ori=True)
    return fwd
コード例 #24
0
def test_forward_mixed_source_space():
    """Test making the forward solution for a mixed source space
    """
    temp_dir = _TempDir()
    # get the surface source space
    surf = read_source_spaces(fname_src)

    # setup two volume source spaces
    label_names = get_volume_labels_from_aseg(fname_aseg)
    vol_labels = [label_names[int(np.random.rand() * len(label_names))]
                  for _ in range(2)]
    vol1 = setup_volume_source_space('sample', fname=None, pos=20.,
                                     mri=fname_aseg,
                                     volume_label=vol_labels[0],
                                     add_interpolator=False)
    vol2 = setup_volume_source_space('sample', fname=None, pos=20.,
                                     mri=fname_aseg,
                                     volume_label=vol_labels[1],
                                     add_interpolator=False)

    # merge surfaces and volume
    src = surf + vol1 + vol2

    # calculate forward solution
    fwd = make_forward_solution(fname_raw, fname_trans, src, fname_bem, None)
    assert_true(repr(fwd))

    # extract source spaces
    src_from_fwd = fwd['src']

    # get the coordinate frame of each source space
    coord_frames = np.array([s['coord_frame'] for s in src_from_fwd])

    # assert that all source spaces are in head coordinates
    assert_true((coord_frames == FIFF.FIFFV_COORD_HEAD).all())

    # run tests for SourceSpaces.export_volume
    fname_img = op.join(temp_dir, 'temp-image.mgz')

    # head coordinates and mri_resolution, but trans file
    assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
                  mri_resolution=True, trans=None)

    # head coordinates and mri_resolution, but wrong trans file
    vox_mri_t = vol1[0]['vox_mri_t']
    assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
                  mri_resolution=True, trans=vox_mri_t)
コード例 #25
0
def test_make_forward_solution_discrete(tmp_path):
    """Test making and converting a forward solution with discrete src."""
    # smoke test for depth weighting and discrete source spaces
    src = setup_source_space('sample',
                             'oct2',
                             subjects_dir=subjects_dir,
                             add_dist=False)
    src = src + setup_volume_source_space(
        pos=dict(rr=src[0]['rr'][src[0]['vertno'][:3]].copy(),
                 nn=src[0]['nn'][src[0]['vertno'][:3]].copy()))
    sphere = make_sphere_model()
    fwd = make_forward_solution(fname_raw,
                                fname_trans,
                                src,
                                sphere,
                                meg=True,
                                eeg=False)
    convert_forward_solution(fwd, surf_ori=True)
コード例 #26
0
def finalize_model(conductivity, src, trans, subjects_dir, raw_fname):
    model = mne.make_bem_model(subject='sample',
                               ico=4,
                               conductivity=conductivity,
                               subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    fwd = mne.convert_forward_solution(mne.make_forward_solution(raw_fname,
                                                                 trans=trans,
                                                                 src=src,
                                                                 bem=bem,
                                                                 meg=False,
                                                                 eeg=True,
                                                                 mindist=5.0,
                                                                 n_jobs=2),
                                       force_fixed=True)

    del bem, model
    return fwd
コード例 #27
0
ファイル: test_lcmv.py プロジェクト: SherazKhan/mne-python
def test_lcmv_ctf_comp():
    """Test interpolation with compensated CTF data."""
    ctf_dir = op.join(testing.data_path(download=False), 'CTF')
    raw_fname = op.join(ctf_dir, 'somMDYO-18av.ds')
    raw = mne.io.read_raw_ctf(raw_fname, preload=True)

    events = mne.make_fixed_length_events(raw, duration=0.2)[:2]
    epochs = mne.Epochs(raw, events, tmin=0., tmax=0.2)
    evoked = epochs.average()

    with pytest.warns(RuntimeWarning,
                      match='Too few samples .* estimate may be unreliable'):
        data_cov = mne.compute_covariance(epochs)
    fwd = mne.make_forward_solution(evoked.info, None,
                                    mne.setup_volume_source_space(pos=15.0),
                                    mne.make_sphere_model())
    filters = mne.beamformer.make_lcmv(evoked.info, fwd, data_cov)
    assert 'weights' in filters
コード例 #28
0
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 mismatch'):
        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 mismatch'):
        apply_inverse_raw(raw, inv, 1. / 9.)
コード例 #29
0
 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
コード例 #30
0
def gen_fwd(subject, conductivity, info):

    src = mne.read_source_spaces(subject_dir + '/sub-' + subject + '_free' +
                                 '/sub-' + subject + '_free-src.fif')
    trans = subject_dir + '/sub-' + subject + '_free' + '/sub-' + subject + '_free-trans.fif'
    model = mne.make_bem_model(subject='sub-' + subject + '_free',
                               ico=4,
                               conductivity=conductivity,
                               subjects_dir=subject_dir)
    bem = mne.make_bem_solution(model)
    return mne.make_forward_solution(info,
                                     trans=trans,
                                     src=src,
                                     bem=bem,
                                     eeg=True,
                                     meg=False,
                                     mindist=5.0,
                                     n_jobs=2)
コード例 #31
0
def test_make_forward_solution_compensation():
    """Test making forward solution from python with compensation
    """
    fname_ctf_raw = op.join(op.dirname(__file__), '..', '..', 'fiff', 'tests',
                            'data', 'test_ctf_comp_raw.fif')
    fname_bem = op.join(subjects_dir, 'sample', 'bem',
                        'sample-5120-bem-sol.fif')
    fname_src = op.join(temp_dir, 'oct2-src.fif')
    src = setup_source_space('sample', fname_src, 'oct2',
                             subjects_dir=subjects_dir)
    fwd_py = make_forward_solution(fname_ctf_raw, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=fname_mri)

    fwd = do_forward_solution('sample', fname_ctf_raw, src=fname_src,
                              mindist=0.0, bem=fname_bem, mri=fname_mri,
                              eeg=False, meg=True, subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, 108)
コード例 #32
0
def test_make_forward_solution_compensation():
    """Test making forward solution from python with compensation
    """
    fname_ctf_raw = op.join(op.dirname(__file__), '..', '..', 'fiff', 'tests',
                            'data', 'test_ctf_comp_raw.fif')
    fname_bem = op.join(subjects_dir, 'sample', 'bem',
                        'sample-5120-bem-sol.fif')
    fname_src = op.join(temp_dir, 'oct2-src.fif')
    src = setup_source_space('sample', fname_src, 'oct2',
                             subjects_dir=subjects_dir)
    fwd_py = make_forward_solution(fname_ctf_raw, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=fname_mri)

    fwd = do_forward_solution('sample', fname_ctf_raw, src=fname_src,
                              mindist=0.0, bem=fname_bem, mri=fname_mri,
                              eeg=False, meg=True, subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, 108)
コード例 #33
0
ファイル: test_rap_music.py プロジェクト: olafhauk/mne-python
def test_rap_music_sphere():
    """Test RAP-MUSIC with real data, sphere model, MEG only."""
    evoked, noise_cov = _get_data(ch_decim=8)
    sphere = mne.make_sphere_model(r0=(0., 0., 0.04))
    src = mne.setup_volume_source_space(subject=None, pos=10.,
                                        sphere=(0.0, 0.0, 40, 65.0),
                                        mindist=5.0, exclude=0.0)
    forward = mne.make_forward_solution(evoked.info, trans=None, src=src,
                                        bem=sphere)

    dipoles = rap_music(evoked, forward, noise_cov, n_dipoles=2)
    # Test that there is one dipole on each hemisphere
    pos = np.array([dip.pos[0] for dip in dipoles])
    assert_equal(pos.shape, (2, 3))
    assert_equal((pos[:, 0] < 0).sum(), 1)
    assert_equal((pos[:, 0] > 0).sum(), 1)
    # Check the amplitude scale
    assert_true(1e-10 < dipoles[0].amplitude[0] < 1e-7)
コード例 #34
0
ファイル: test_inverse.py プロジェクト: iuluc/mne-python
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.)
コード例 #35
0
def test_lcmv_ctf_comp():
    """Test interpolation with compensated CTF data."""
    ctf_dir = op.join(testing.data_path(download=False), 'CTF')
    raw_fname = op.join(ctf_dir, 'somMDYO-18av.ds')
    raw = mne.io.read_raw_ctf(raw_fname, preload=True)

    events = mne.make_fixed_length_events(raw, duration=0.2)[:2]
    epochs = mne.Epochs(raw, events, tmin=0., tmax=0.2)
    evoked = epochs.average()

    with pytest.warns(RuntimeWarning,
                      match='Too few samples .* estimate may be unreliable'):
        data_cov = mne.compute_covariance(epochs)
    fwd = mne.make_forward_solution(evoked.info, None,
                                    mne.setup_volume_source_space(pos=15.0),
                                    mne.make_sphere_model())
    filters = mne.beamformer.make_lcmv(evoked.info, fwd, data_cov)
    assert 'weights' in filters
コード例 #36
0
ファイル: test_make_forward.py プロジェクト: MJAS1/mne-python
def test_forward_mixed_source_space():
    """Test making the forward solution for a mixed source space."""
    temp_dir = _TempDir()
    # get the surface source space
    surf = read_source_spaces(fname_src)

    # setup two volume source spaces
    label_names = get_volume_labels_from_aseg(fname_aseg)
    vol_labels = [label_names[int(np.random.rand() * len(label_names))]
                  for _ in range(2)]
    vol1 = setup_volume_source_space('sample', pos=20., mri=fname_aseg,
                                     volume_label=vol_labels[0],
                                     add_interpolator=False)
    vol2 = setup_volume_source_space('sample', pos=20., mri=fname_aseg,
                                     volume_label=vol_labels[1],
                                     add_interpolator=False)

    # merge surfaces and volume
    src = surf + vol1 + vol2

    # calculate forward solution
    fwd = make_forward_solution(fname_raw, fname_trans, src, fname_bem, None)
    assert_true(repr(fwd))

    # extract source spaces
    src_from_fwd = fwd['src']

    # get the coordinate frame of each source space
    coord_frames = np.array([s['coord_frame'] for s in src_from_fwd])

    # assert that all source spaces are in head coordinates
    assert_true((coord_frames == FIFF.FIFFV_COORD_HEAD).all())

    # run tests for SourceSpaces.export_volume
    fname_img = op.join(temp_dir, 'temp-image.mgz')

    # head coordinates and mri_resolution, but trans file
    assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
                  mri_resolution=True, trans=None)

    # head coordinates and mri_resolution, but wrong trans file
    vox_mri_t = vol1[0]['vox_mri_t']
    assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
                  mri_resolution=True, trans=vox_mri_t)
コード例 #37
0
def test_forward_mixed_source_space(tmpdir):
    """Test making the forward solution for a mixed source space."""
    # get the surface source space
    rng = np.random.RandomState(0)
    surf = read_source_spaces(fname_src)

    # setup two volume source spaces
    label_names = get_volume_labels_from_aseg(fname_aseg)
    vol_labels = rng.choice(label_names, 2)
    vol1 = setup_volume_source_space('sample', pos=20., mri=fname_aseg,
                                     volume_label=vol_labels[0],
                                     add_interpolator=False)
    vol2 = setup_volume_source_space('sample', pos=20., mri=fname_aseg,
                                     volume_label=vol_labels[1],
                                     add_interpolator=False)

    # merge surfaces and volume
    src = surf + vol1 + vol2

    # calculate forward solution
    fwd = make_forward_solution(fname_raw, fname_trans, src, fname_bem)
    assert (repr(fwd))

    # extract source spaces
    src_from_fwd = fwd['src']

    # get the coordinate frame of each source space
    coord_frames = np.array([s['coord_frame'] for s in src_from_fwd])

    # assert that all source spaces are in head coordinates
    assert ((coord_frames == FIFF.FIFFV_COORD_HEAD).all())

    # run tests for SourceSpaces.export_volume
    fname_img = tmpdir.join('temp-image.mgz')

    # head coordinates and mri_resolution, but trans file
    with pytest.raises(ValueError, match='trans containing mri to head'):
        src_from_fwd.export_volume(fname_img, mri_resolution=True, trans=None)

    # head coordinates and mri_resolution, but wrong trans file
    vox_mri_t = vol1[0]['vox_mri_t']
    with pytest.raises(ValueError, match='head<->mri, got mri_voxel->mri'):
        src_from_fwd.export_volume(fname_img, mri_resolution=True,
                                   trans=vox_mri_t)
コード例 #38
0
def test_mxne_vol_sphere():
    """(TF-)MxNE with a sphere forward and volumic source space"""
    evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
    evoked.crop(tmin=-0.05, tmax=0.2)
    cov = read_cov(fname_cov)

    evoked_l21 = evoked.copy()
    evoked_l21.crop(tmin=0.081, tmax=0.1)

    info = evoked.info
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=15., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0,
                                        exclude=2.0)
    fwd = mne.make_forward_solution(info, trans=None, src=src,
                                    bem=sphere, eeg=False, meg=True)

    alpha = 80.
    assert_raises(ValueError, mixed_norm, evoked, fwd, cov, alpha,
                  loose=None, return_residual=False,
                  maxit=3, tol=1e-8, active_set_size=10)

    assert_raises(ValueError, mixed_norm, evoked, fwd, cov, alpha,
                  loose=0.2, return_residual=False,
                  maxit=3, tol=1e-8, active_set_size=10)

    # irMxNE tests
    stc = mixed_norm(evoked_l21, fwd, cov, alpha,
                     n_mxne_iter=1, maxit=30, tol=1e-8,
                     active_set_size=10)
    assert_true(isinstance(stc, VolSourceEstimate))
    assert_array_almost_equal(stc.times, evoked_l21.times, 5)

    # 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, fwd, cov, alpha_space, alpha_time,
                           maxit=3, tol=1e-4,
                           tstep=16, wsize=32, window=0.1,
                           return_residual=True)
    assert_true(isinstance(stc, VolSourceEstimate))
    assert_array_almost_equal(stc.times, evoked.times, 5)
コード例 #39
0
ファイル: test_dipole.py プロジェクト: cmoutard/mne-python
def test_accuracy():
    """Test dipole fitting to sub-mm accuracy
    """
    evoked = read_evokeds(fname_evo)[0].crop(
        0.,
        0.,
    )
    evoked.pick_types(meg=True, eeg=False)
    evoked.pick_channels([c for c in evoked.ch_names[::4]])
    bem = make_sphere_model('auto',
                            0.09,
                            evoked.info,
                            relative_radii=(0.999, 0.998, 0.997, 0.995))
    src = read_source_spaces(fname_src)

    fwd = make_forward_solution(evoked.info, None, src, bem)
    fwd = convert_forward_solution(fwd, force_fixed=True)
    vertices = [src[0]['vertno'], src[1]['vertno']]
    n_vertices = sum(len(v) for v in vertices)
    amp = 10e-9
    data = np.eye(n_vertices + 1)[:n_vertices]
    data[-1, -1] = 1.
    data *= amp
    stc = SourceEstimate(data, vertices, 0., 1e-3, 'sample')
    sim = simulate_evoked(fwd, stc, evoked.info, cov=None, snr=np.inf)

    cov = make_ad_hoc_cov(evoked.info)
    dip = fit_dipole(sim, cov, bem, min_dist=0.001)[0]

    ds = []
    for vi in range(n_vertices):
        if vi < len(vertices[0]):
            hi = 0
            vertno = vi
        else:
            hi = 1
            vertno = vi - len(vertices[0])
        vertno = src[hi]['vertno'][vertno]
        rr = src[hi]['rr'][vertno]
        d = np.sqrt(np.sum((rr - dip.pos[vi])**2))
        ds.append(d)
    # make sure that our median is sub-mm and the large majority are very close
    # (we expect some to be off by a bit e.g. because they are radial)
    assert_true((np.percentile(ds, [50, 90]) < [0.0005, 0.002]).all())
コード例 #40
0
ファイル: test_mxne_inverse.py プロジェクト: nfoti/mne-python
def test_mxne_vol_sphere():
    """(TF-)MxNE with a sphere forward and volumic source space"""
    evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
    evoked.crop(tmin=-0.05, tmax=0.2)
    cov = read_cov(fname_cov)

    evoked_l21 = evoked.copy()
    evoked_l21.crop(tmin=0.081, tmax=0.1)

    info = evoked.info
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=15., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0,
                                        exclude=2.0)
    fwd = mne.make_forward_solution(info, trans=None, src=src,
                                    bem=sphere, eeg=False, meg=True)

    alpha = 80.
    assert_raises(ValueError, mixed_norm, evoked, fwd, cov, alpha,
                  loose=0.0, return_residual=False,
                  maxit=3, tol=1e-8, active_set_size=10)

    assert_raises(ValueError, mixed_norm, evoked, fwd, cov, alpha,
                  loose=0.2, return_residual=False,
                  maxit=3, tol=1e-8, active_set_size=10)

    # irMxNE tests
    stc = mixed_norm(evoked_l21, fwd, cov, alpha,
                     n_mxne_iter=1, maxit=30, tol=1e-8,
                     active_set_size=10)
    assert_true(isinstance(stc, VolSourceEstimate))
    assert_array_almost_equal(stc.times, evoked_l21.times, 5)

    # 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, fwd, cov, alpha_space, alpha_time,
                           maxit=3, tol=1e-4,
                           tstep=16, wsize=32, window=0.1,
                           return_residual=True)
    assert_true(isinstance(stc, VolSourceEstimate))
    assert_array_almost_equal(stc.times, evoked.times, 5)
コード例 #41
0
ファイル: test_raw.py プロジェクト: tomfisher/mne-python
def test_simulate_round_trip():
    """Test simulate_raw round trip calculations."""
    # Check a diagonal round-trip
    raw, src, stc, trans, sphere = _get_data()
    raw.pick_types(meg=True, stim=True)
    bem = read_bem_solution(bem_1_fname)
    old_bem = bem.copy()
    old_src = src.copy()
    old_trans = trans.copy()
    fwd = make_forward_solution(raw.info, trans, src, bem)
    # no omissions
    assert (sum(len(s['vertno'])
                for s in src) == sum(len(s['vertno'])
                                     for s in fwd['src']) == 36)
    # make sure things were not modified
    assert (
        old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame'])
    assert trans == old_trans
    _compare_source_spaces(src, old_src)
    data = np.eye(fwd['nsource'])
    raw.crop(0, (len(data) - 1) / raw.info['sfreq'])
    stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0,
                         1. / raw.info['sfreq'])
    for use_cps in (False, True):
        this_raw = simulate_raw(raw,
                                stc,
                                trans,
                                src,
                                bem,
                                cov=None,
                                use_cps=use_cps)
        this_raw.pick_types(meg=True, eeg=True)
        assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]
                ['coord_frame'])
        assert trans == old_trans
        _compare_source_spaces(src, old_src)
        this_fwd = convert_forward_solution(fwd,
                                            force_fixed=True,
                                            use_cps=use_cps)
        assert_allclose(this_raw[:][0],
                        this_fwd['sol']['data'],
                        atol=1e-12,
                        rtol=1e-6)
コード例 #42
0
    def get_forward_sol(self, info, meg=False, eeg=True, force_fixed=True):
        blnOverwrite = self.blnOverwrite
        srcfile = self.srcfile
        transfile = self.transfile
        bemfile = self.bemfile

        meeg_sfx = get_meeg_suffix(bln_eeg=eeg, bln_meg=meg)
        fwdfile = get_fwdfile(self.mne_outputpath, self.filebasestr,
                              self.spacing_string, meeg_sfx)

        #
        # Compute forward solution
        #
        log.info('Reading the source space')
        src = mne.read_source_spaces(srcfile, patch_stats=True, verbose=None)

        if not blnOverwrite and op.isfile(fwdfile):
            log.info('Loading the forward solution')
            fwd = mne.read_forward_solution(fwdfile,
                                            include=[],
                                            exclude=[],
                                            verbose=None)
        else:
            log.info('Making the forward solution')
            fwd = mne.make_forward_solution(info,
                                            transfile,
                                            src,
                                            bemfile,
                                            meg=meg,
                                            eeg=eeg,
                                            mindist=5.0,
                                            ignore_ref=False)
            mne.write_forward_solution(fwdfile, fwd, overwrite=blnOverwrite)

        fwd = mne.convert_forward_solution(fwd,
                                           surf_ori=True,
                                           force_fixed=force_fixed,
                                           copy=False,
                                           use_cps=True,
                                           verbose=None)

        log.info('[Done]')
        return src, fwd
コード例 #43
0
def test_make_lcmv_sphere(pick_ori, weight_norm):
    """Test LCMV with sphere head model."""
    # unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    _, _, evoked, data_cov, noise_cov, _, _, _, _, _ = _get_data(proj=True)
    assert 'eeg' not in evoked
    assert 'meg' in evoked
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(
        pos=25., sphere=sphere, mindist=5.0, exclude=2.0)
    fwd_sphere = mne.make_forward_solution(evoked.info, None, src, sphere)

    # Test that we get an error if not reducing rank
    with pytest.raises(ValueError, match='Singular matrix detected'):
        with pytest.warns(RuntimeWarning, match='positive semidefinite'):
            make_lcmv(
                evoked.info, fwd_sphere, data_cov, reg=0.1,
                noise_cov=noise_cov, weight_norm=weight_norm,
                pick_ori=pick_ori, reduce_rank=False, rank='full')

    # Now let's reduce it
    filters = make_lcmv(evoked.info, fwd_sphere, data_cov, reg=0.1,
                        noise_cov=noise_cov, weight_norm=weight_norm,
                        pick_ori=pick_ori, reduce_rank=True)
    stc_sphere = apply_lcmv(evoked, filters, max_ori_out='signed')
    if isinstance(stc_sphere, VolVectorSourceEstimate):
        stc_sphere = stc_sphere.magnitude()
    else:
        stc_sphere = abs(stc_sphere)
    assert isinstance(stc_sphere, VolSourceEstimate)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]
    assert 0.08 < tmax < 0.15, tmax
    min_, max_ = 1.0, 4.5
    if weight_norm is None:
        min_ *= 2e-7
        max_ *= 2e-7
    assert min_ < np.max(max_stc) < max_, (min_, np.max(max_stc), max_)
コード例 #44
0
def make_fwd_solution(cond_fname, subj, study_path):
    eeg_epo = mne.read_epochs(cond_fname + '-epo.fif')

    trans_fname = op.join(study_path, 'source_stim', 'images', subj, '%s_coreg-trans.fif' % subj)
    src_fname = op.join(study_path, 'source_stim', 'images', subj, '%s-oct5-src.fif' % subj)
    bem_fname = op.join(study_path, 'freesurfer_subjects', '%s' % subj, 'bem', '%s-bem-sol.fif' % subj)

    fwd = mne.make_forward_solution(eeg_epo.info, trans_fname, src_fname, bem_fname)

    mne.viz.plot_bem(subject='S1', subjects_dir=subjects_dir, src=src_fname)
    mne.viz.plot_bem(subject='S3', subjects_dir=subjects_dir)

    # trans = mne.read_trans(trans_fname)
    # mne.viz.plot_alignment(eeg_epo.info, trans, subject='%s' % subj, subjects_dir=op.join(study_path, 'freesurfer_subjects'))
    # mlab.show()

    # mne.scale_bem('%s_coreg' % subj, 'bem-sol', subjects_dir=subjects_dir)

    mne.write_forward_solution(op.join(study_path, 'source_stim', 'images', subj, '%s-fwd.fif' % subj), fwd, overwrite=True)
    return fwd
コード例 #45
0
ファイル: conftest.py プロジェクト: qdong17/mne-python
def _fwd_subvolume(_evoked_cov_sphere):
    """Compute a forward for a surface source space."""
    evoked, cov, sphere = _evoked_cov_sphere
    volume_labels = ['Left-Cerebellum-Cortex', 'right-Cerebellum-Cortex']
    with pytest.raises(ValueError, match=r"Did you mean one of \['Right-Cere"):
        mne.setup_volume_source_space('sample',
                                      pos=20.,
                                      volume_label=volume_labels,
                                      subjects_dir=subjects_dir)
    volume_labels[1] = 'R' + volume_labels[1][1:]
    src_vol = mne.setup_volume_source_space('sample',
                                            pos=20.,
                                            volume_label=volume_labels,
                                            subjects_dir=subjects_dir,
                                            add_interpolator=False)
    return mne.make_forward_solution(evoked.info,
                                     fname_trans,
                                     src_vol,
                                     sphere,
                                     mindist=5.0)
コード例 #46
0
def create_forward_solution(name, save_dir, subject, subjects_dir,
                            overwrite):

    forward_name = name + '-fwd.fif'
    forward_path = join(save_dir, forward_name)

    if overwrite or not isfile(forward_path):

        info = io.read_info(name, save_dir)
        trans = io.read_transformation(name, save_dir)
        bem = io.read_bem_solution(subject, subjects_dir)
        source_space = io.read_source_space(subject, subjects_dir)

        forward = mne.make_forward_solution(info, trans, source_space, bem,
                                              n_jobs=1)
        
        mne.write_forward_solution(forward_path, forward, overwrite)
        
    else:
        print('forward solution: ' + forward_path + ' already exists')
コード例 #47
0
ファイル: test_dipole.py プロジェクト: jdammers/mne-python
def test_accuracy():
    """Test dipole fitting to sub-mm accuracy."""
    evoked = read_evokeds(fname_evo)[0].crop(0., 0.,)
    evoked.pick_types(meg=True, eeg=False)
    evoked.pick_channels([c for c in evoked.ch_names[::4]])
    for rad, perc_90 in zip((0.09, None), (0.002, 0.004)):
        bem = make_sphere_model('auto', rad, evoked.info,
                                relative_radii=(0.999, 0.998, 0.997, 0.995))
        src = read_source_spaces(fname_src)

        fwd = make_forward_solution(evoked.info, None, src, bem)
        fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=True)
        vertices = [src[0]['vertno'], src[1]['vertno']]
        n_vertices = sum(len(v) for v in vertices)
        amp = 10e-9
        data = np.eye(n_vertices + 1)[:n_vertices]
        data[-1, -1] = 1.
        data *= amp
        stc = SourceEstimate(data, vertices, 0., 1e-3, 'sample')
        evoked.info.normalize_proj()
        sim = simulate_evoked(fwd, stc, evoked.info, cov=None, nave=np.inf)

        cov = make_ad_hoc_cov(evoked.info)
        dip = fit_dipole(sim, cov, bem, min_dist=0.001)[0]

        ds = []
        for vi in range(n_vertices):
            if vi < len(vertices[0]):
                hi = 0
                vertno = vi
            else:
                hi = 1
                vertno = vi - len(vertices[0])
            vertno = src[hi]['vertno'][vertno]
            rr = src[hi]['rr'][vertno]
            d = np.sqrt(np.sum((rr - dip.pos[vi]) ** 2))
            ds.append(d)
        # make sure that our median is sub-mm and the large majority are very
        # close (we expect some to be off by a bit e.g. because they are
        # radial)
        assert_true((np.percentile(ds, [50, 90]) < [0.0005, perc_90]).all())
コード例 #48
0
def process_sources(epochs,
                    trans,
                    surface_src,
                    bem_solution,
                    fwd_mindist=5.0,
                    diag_cov=True,
                    cov_method="auto",
                    loose="auto",
                    fixed=True,
                    inv_method="eLORETA",
                    lambda2=1e-4,
                    pick_ori=None,
                    return_generator=True,
                    return_fwd=False,
                    include_vol_src=True):

    fwd = mne.make_forward_solution(epochs.info,
                                    trans,
                                    surface_src,
                                    bem_solution,
                                    mindist=fwd_mindist,
                                    eeg=True)
    noise_cov = mne.compute_covariance(epochs, method=cov_method)
    if diag_cov:
        noise_cov = noise_cov.as_diag()

    inverse_operator = mne.minimum_norm.make_inverse_operator(epochs.info,
                                                              fwd,
                                                              noise_cov,
                                                              loose=loose,
                                                              fixed=fixed)
    stcs = mne.minimum_norm.apply_inverse_epochs(
        epochs,
        inverse_operator,
        method=inv_method,
        lambda2=lambda2,
        pick_ori=pick_ori,
        return_generator=return_generator)
    if return_fwd:
        return stcs, fwd
    return stcs
コード例 #49
0
def forward_computation(
        info: mne.Info,
        trans: mne.Transform,
        src: mne.SourceSpaces,
        bem: mne.bem.ConductorModel,
        _subject_tree: Optional[SubjectTree] = None,
        _priority: Optional[int] = None) -> mne.forward.Forward:
    """computes `forward solution`_, uses :func:`nodestimation.project.read_or_write` decorator

        :param info: information about raw data
        :type info: |imne.Info|_
        :param trans: `transformation matrix`_
        :type trans: |imne.transforms.Transform|_
        :param src: `source spaces`_
        :type src: |imne.SourceSpaces|_
        :param bem: bem_ solution
        :type bem: mne.bem.ConductorModel_
        :param _subject_tree: representation of patient`s files structure, default None
        :type _subject_tree: *look for SubjectTree in* :mod:`nodestimation.project.annotations` *, optional*
        :param _priority: if several files are read, which one to choose, if None, read all of them, default None
        :type _priority: int, optional
        :return: `forward solution`_
        :rtype: mne.Forward_

        .. _imne.Forward:
        .. _mne.Forward:
        .. _`forward solution`: https://mne.tools/stable/generated/mne.Forward.html?highlight=forward#mne.Forward
        .. _imne.Info: https://mne.tools/stable/generated/mne.Info.html?highlight=info#mne.Info

        .. |imne.Info| replace:: *mne.Info*
    """

    return mne.make_forward_solution(info,
                                     trans=trans,
                                     src=src,
                                     bem=bem,
                                     meg=True,
                                     eeg=False,
                                     mindist=5.0,
                                     n_jobs=1,
                                     verbose=True)
コード例 #50
0
ファイル: b_source_loc.py プロジェクト: zekigit/intra_extra
def make_vol_fwd(epochs, fs_subj, study_path, subjects_dir):
    cond = epochs.info['description']

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

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

    mne.viz.plot_alignment(epochs.info, trans=trans_fname, subject=fs_subj, subjects_dir=subjects_dir,
                           surfaces=['seghead', 'brain'], bem=bem_fname, coord_frame='mri') #, src=v_source

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

    mne.write_forward_solution(op.join(study_path, 'source_stim', subj, 'source_files', img_type,
                               '%s_vol_source_space_5mm-fwd.fif' % subj), fwd, overwrite=True)
    return fwd
コード例 #51
0
def compute_fwd(subject,
                src_ref,
                info,
                trans_fname,
                bem_fname,
                mindist=2,
                subjects_dir=None):
    """Morph source space of fsaverage to subject."""
    print("Processing subject %s" % subject)

    src = mne.morph_source_spaces(src_ref,
                                  subject_to=subject,
                                  subjects_dir=subjects_dir)
    bem = mne.read_bem_solution(bem_fname)
    fwd = mne.make_forward_solution(info,
                                    trans=trans_fname,
                                    src=src,
                                    bem=bem,
                                    mindist=mindist,
                                    n_jobs=1)
    return fwd
コード例 #52
0
def compute_fwds_stc(position, perts, sphere):
    pos = position.copy()
    pos['rr'] = mne.transforms.apply_trans(head_mri_t, position['rr'])  # invert back to mri
    pos['nn'] = mne.transforms.apply_trans(head_mri_t, position['nn'])
    src = mne.setup_volume_source_space(subject=subject, pos=pos, mri=None,
                                        sphere=(0, 0, 0, 90), bem=None,
                                        surface=None, mindist=1.0, exclude=0.0,
                                        subjects_dir=None, volume_label=None,
                                        add_interpolator=True, verbose=None)
    fwd_pert = make_pert_forward_solution(raw_fname, trans=trans, src=src, bem=sphere, perts=perts,
                                          meg=True, eeg=False, mindist=1.0, n_jobs=1)
    fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=sphere,
                                    meg=True, eeg=False, mindist=1.0, n_jobs=1)
    fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                             use_cps=True)
    fwd_pert_fixed = mne.convert_forward_solution(fwd_pert, surf_ori=True, force_fixed=True,
                                                  use_cps=True)

    amplitude = 1e-5
    stc = mne.VolSourceEstimate(amplitude * np.eye(1), [[0]], tmin=0., tstep=1)
    return fwd_fixed, fwd_pert_fixed, stc
コード例 #53
0
ファイル: stat_cluster.py プロジェクト: jdammers/vis_dev
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)
コード例 #54
0
def fit_dips(min_rad, max_rad, nn, sphere, perts, sourcenorm):
    testsources = dict(rr=[], nn=[])
    nsources = max_rad - min_rad + 1
    vertices = np.zeros((nsources, 1))
    for i in range(min_rad, max_rad + 1):
        ex, ey, ez = sourcenorm[0], sourcenorm[1], sourcenorm[2]
        source = [.001*i*ex, .001*i*ey, .001*i*ez]
        normal = [nn[0], nn[1], nn[2]]
        testsources['rr'].append(source)
        testsources['nn'].append(normal)
        vertices[i - min_rad] = i

    pos = dict(rr=[0], nn=[0])
    pos['rr'] = mne.transforms.apply_trans(head_mri_t, testsources['rr'])  # invert back to mri
    pos['nn'] = mne.transforms.apply_trans(head_mri_t, testsources['nn'])
    src = mne.setup_volume_source_space(subject=subject, pos=pos, mri=None,
                                        sphere=(0, 0, 0, 90), bem=None,
                                        surface=None, mindist=1.0, exclude=0.0,
                                        subjects_dir=None, volume_label=None,
                                        add_interpolator=True, verbose=None)
    fwd_pert = make_pert_forward_solution(raw_fname, trans=trans, src=src, bem=sphere, perts=perts,
                                          meg=True, eeg=False, mindist=1.0, n_jobs=1)
    fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=sphere,
                                    meg=True, eeg=False, mindist=1.0, n_jobs=1)
    fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                             use_cps=True)
    fwd_pert_fixed = mne.convert_forward_solution(fwd_pert, surf_ori=True, force_fixed=True,
                                                  use_cps=True)

    amplitude = 1e-5
    source = np.eye(nsources) * amplitude

    stc = mne.VolSourceEstimate(source, vertices, tmin=0., tstep=1)
    evoked = mne.simulation.simulate_evoked(fwd_fixed, stc, info, cov, use_cps=True,
                                            iir_filter=None)
    evoked_pert = mne.simulation.simulate_evoked(fwd_pert_fixed, stc, info, cov, use_cps=True,
                                                 iir_filter=None)
    dip_fit_long = mne.fit_dipole(evoked, cov_fname, sphere, trans)[0]
    dip_fit_pert = mne.fit_dipole(evoked_pert, cov_fname, sphere, trans)[0]
    return dip_fit_long, dip_fit_pert, testsources
コード例 #55
0
def test_rap_music_sphere():
    """Test RAP-MUSIC with real data, sphere model, MEG only."""
    evoked, noise_cov = _get_data(ch_decim=8)
    sphere = mne.make_sphere_model(r0=(0., 0., 0.04))
    src = mne.setup_volume_source_space(subject=None, pos=10.,
                                        sphere=(0.0, 0.0, 40, 65.0),
                                        mindist=5.0, exclude=0.0)
    forward = mne.make_forward_solution(evoked.info, trans=None, src=src,
                                        bem=sphere)

    dipoles = rap_music(evoked, forward, noise_cov, n_dipoles=2)
    # Test that there is one dipole on each hemisphere
    pos = np.array([dip.pos[0] for dip in dipoles])
    assert_equal(pos.shape, (2, 3))
    assert_equal((pos[:, 0] < 0).sum(), 1)
    assert_equal((pos[:, 0] > 0).sum(), 1)
    # Check the amplitude scale
    assert (1e-10 < dipoles[0].amplitude[0] < 1e-7)
    # Check the orientation
    dip_fit = mne.fit_dipole(evoked, noise_cov, sphere)[0]
    assert (np.max(np.abs(np.dot(dip_fit.ori, dipoles[0].ori[0]))) > 0.99)
    assert (np.max(np.abs(np.dot(dip_fit.ori, dipoles[1].ori[0]))) > 0.99)
コード例 #56
0
def __make_inv_individual(rawf, transf, bemf, srcf, outdir):

    tmpid = os.path.basename(rawf).split("_")[0]
    tmpath = f'{outdir}/{tmpid}_inv.fif'

    if os.path.isfile(tmpath):
        print(f'{tmpid}_inv.fif already exists, skipping')
        return tmpath
    try:
        raw = mne.io.read_raw_fif(rawf)
        cov = mne.compute_raw_covariance(raw)
        src = mne.read_source_spaces(srcf)
        bem = mne.read_bem_solution(bemf)
        fwd = mne.make_forward_solution(raw.info, transf, src, bem)
        inv = mne.minimum_norm.make_inverse_operator(raw.info, fwd, cov)
        del fwd, src

        mne.minimum_norm.write_inverse_operator(f'{outdir}/{tmpid}_inv.fif',
                                                inv)
    except:
        print('error')
    return tmpath
コード例 #57
0
def compute_forward(info, bem, src, trans_fname, read_from_disk=False,
                    fwd_fname=None, save_to_disk=False):
    """Compute forward solution.

    Reads or computes forward solution.

    Parameters:
    -----------
    info : dict
        info from epoch, contains channel positions etc.
    bem : headmodel or path
        BEM model or path to BEM model.
    src : source space
        source grid.
    trans_fname : path
        path to transformation matrix.
    read_from_disk : bool
        if True, read pre-computed fwd model from disk.
    fwd_fname : path
        path to fwd model on disk, either for saving or reading.
    save_to_disk : bool
        whether fwd model should be saved to disk.

    Returns
    -------
    fwd : dict.
        MNE forward operator
    """
    if read_from_disk is True:
        fwd = mne.read_forward_solution(fwd_fname)
    else:
            fwd = mne.make_forward_solution(info, trans=trans_fname,
                                            src=src, bem=bem, meg=True,
                                            eeg=False, n_jobs=1)

            if save_to_disk is True:
                mne.write_forward_solution(fwd_fname, fwd, overwrite=True)

    return fwd
コード例 #58
0
def run_forward(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_fwd = op.join(data_path, '%s-meg-eeg-%s-fwd.fif'
                        % (subject, spacing))
    fname_trans = op.join(study_path, 'ds117', subject, 'MEG',
                          '%s-trans.fif' % subject)
    fname_src = op.join(subjects_dir, subject, 'bem', '%s-%s-src.fif'
                        % (subject, spacing))
    # Here we only use 1-layer BEM because the 3-layer is unreliable
    fname_bem = op.join(subjects_dir, subject, 'bem',
                        '%s-5120-5120-5120-bem-sol.fif' % subject)

    info = mne.io.read_info(fname_ave)
    # Because we use a 1-layer BEM, we do MEG only // CHANGED TO EEG
    fwd = mne.make_forward_solution(info, fname_trans, fname_src, fname_bem,
                                    meg=False, eeg=True, mindist=mindist)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
コード例 #59
0
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)
コード例 #60
0
def test_lcmv_ctf_comp():
    """Test interpolation with compensated CTF data."""
    raw = mne.io.read_raw_ctf(ctf_fname, preload=True)
    raw.pick(raw.ch_names[:70])

    events = mne.make_fixed_length_events(raw, duration=0.2)[:2]
    epochs = mne.Epochs(raw, events, tmin=-0.1, tmax=0.2)
    evoked = epochs.average()

    data_cov = mne.compute_covariance(epochs)
    fwd = mne.make_forward_solution(evoked.info, None,
                                    mne.setup_volume_source_space(pos=30.0),
                                    mne.make_sphere_model())
    with pytest.raises(ValueError, match='reduce_rank'):
        make_lcmv(evoked.info, fwd, data_cov)
    filters = make_lcmv(evoked.info, fwd, data_cov, reduce_rank=True)
    assert 'weights' in filters

    # test whether different compensations throw error
    info_comp = evoked.info.copy()
    set_current_comp(info_comp, 1)
    with pytest.raises(RuntimeError, match='Compensation grade .* not match'):
        make_lcmv(info_comp, fwd, data_cov)