Exemplo n.º 1
0
def test_clean_eog_ecg():
    """Test mne clean_eog_ecg."""
    check_usage(mne_clean_eog_ecg)
    tempdir = _TempDir()
    raw = concatenate_raws(
        [read_raw_fif(f) for f in [raw_fname, raw_fname, raw_fname]])
    raw.info['bads'] = ['MEG 2443']
    use_fname = op.join(tempdir, op.basename(raw_fname))
    raw.save(use_fname)
    with ArgvSetter(('-i', use_fname, '--quiet')):
        mne_clean_eog_ecg.run()
    fnames = glob.glob(op.join(tempdir, '*proj.fif'))
    assert len(fnames) == 2  # two projs
    fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
    assert len(fnames) == 3  # raw plus two projs
Exemplo n.º 2
0
def test_maxfilter():
    """Test mne maxfilter."""
    check_usage(mne_maxfilter)
    with ArgvSetter(('-i', raw_fname, '--st', '--movecomp', '--linefreq', '60',
                     '--trans', raw_fname)) as out:
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            os.environ['_MNE_MAXFILTER_TEST'] = 'true'
            try:
                mne_maxfilter.run()
            finally:
                del os.environ['_MNE_MAXFILTER_TEST']
        assert len(w) == 1
        for check in ('maxfilter', '-trans', '-movecomp'):
            assert check in out.stdout.getvalue(), check
def test_compute_proj_exg(tmpdir, fun):
    """Test mne compute_proj_ecg/eog."""
    check_usage(fun)
    tempdir = str(tmpdir)
    use_fname = op.join(tempdir, op.basename(raw_fname))
    bad_fname = op.join(tempdir, 'bads.txt')
    with open(bad_fname, 'w') as fid:
        fid.write('MEG 2443\n')
    shutil.copyfile(raw_fname, use_fname)
    with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname,
                     '--rej-eeg', '150')):
        with pytest.warns(None):  # samples, sometimes
            fun.run()
    fnames = glob.glob(op.join(tempdir, '*proj.fif'))
    assert len(fnames) == 1
    fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
    assert len(fnames) == 1
Exemplo n.º 4
0
def test_compute_proj_ecg_eog():
    """Test mne compute_proj_ecg/eog"""
    for fun in (mne_compute_proj_ecg, mne_compute_proj_eog):
        check_usage(fun)
        tempdir = _TempDir()
        use_fname = op.join(tempdir, op.basename(raw_fname))
        bad_fname = op.join(tempdir, 'bads.txt')
        with open(bad_fname, 'w') as fid:
            fid.write('MEG 2443\n')
        shutil.copyfile(raw_fname, use_fname)
        with ArgvSetter(
            ('-i', use_fname, '--bad=' + bad_fname, '--rej-eeg', '150')):
            fun.run()
        fnames = glob.glob(op.join(tempdir, '*proj.fif'))
        assert_true(len(fnames) == 1)
        fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
        assert_true(len(fnames) == 1)
Exemplo n.º 5
0
def test_crosstalk_to_bids(tmp_path):
    """Test mne_bids crosstalk_to_bids."""

    # Check that help is printed
    check_usage(mne_bids_crosstalk_to_bids)

    output_path = str(tmp_path)
    data_path = Path(testing.data_path())
    crosstalk_fname = data_path / 'SSS' / 'ct_sparse.fif'
    bids_path = BIDSPath(subject=subject_id, root=output_path)

    # Write fine-calibration file and check that it was actually written.
    # Write fine-calibration file and check that it was actually written.
    args = ('--file', crosstalk_fname, '--subject', subject_id,
            '--bids_root', output_path)
    with ArgvSetter(args):
        mne_bids_crosstalk_to_bids.run()
    assert bids_path.meg_crosstalk_fpath.exists()
Exemplo n.º 6
0
def _test_fetch(url):
    """Helper to test URL retrieval."""
    tempdir = _TempDir()
    with ArgvSetter(disable_stderr=False):  # to capture stdout
        archive_name = op.join(tempdir, "download_test")
        _fetch_file(url, archive_name, timeout=30., verbose=False,
                    resume=False)
        assert_raises(Exception, _fetch_file, 'NOT_AN_ADDRESS',
                      op.join(tempdir, 'test'), verbose=False)
        resume_name = op.join(tempdir, "download_resume")
        # touch file
        with open(resume_name + '.part', 'w'):
            os.utime(resume_name + '.part', None)
        _fetch_file(url, resume_name, resume=True, timeout=30.,
                    verbose=False)
        assert_raises(ValueError, _fetch_file, url, archive_name,
                      hash_='a', verbose=False)
        assert_raises(RuntimeError, _fetch_file, url, archive_name,
                      hash_='a' * 32, verbose=False)
Exemplo n.º 7
0
def test_watershed_bem():
    """Test mne watershed bem"""
    check_usage(mne_watershed_bem)
    # Copy necessary files to tempdir
    tempdir = _TempDir()
    mridata_path = op.join(subjects_dir, 'sample', 'mri')
    mridata_path_new = op.join(tempdir, 'sample', 'mri')
    os.mkdir(op.join(tempdir, 'sample'))
    os.mkdir(mridata_path_new)
    if op.exists(op.join(mridata_path, 'T1')):
        shutil.copytree(op.join(mridata_path, 'T1'), op.join(mridata_path_new,
                        'T1'))
    if op.exists(op.join(mridata_path, 'T1.mgz')):
        shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
                        op.join(mridata_path_new, 'T1.mgz'))

    with ArgvSetter(('-d', tempdir, '-s', 'sample', '-o'),
                    disable_stdout=False, disable_stderr=False):
        mne_watershed_bem.run()
Exemplo n.º 8
0
def test_fetch_parcellations(tmpdir):
    """Test fetching parcellations."""
    this_subjects_dir = str(tmpdir)
    os.mkdir(op.join(this_subjects_dir, 'fsaverage'))
    os.mkdir(op.join(this_subjects_dir, 'fsaverage', 'label'))
    os.mkdir(op.join(this_subjects_dir, 'fsaverage', 'surf'))
    for hemi in ('lh', 'rh'):
        shutil.copyfile(
            op.join(subjects_dir, 'fsaverage', 'surf', '%s.white' % hemi),
            op.join(this_subjects_dir, 'fsaverage', 'surf', '%s.white' % hemi))
    # speed up by prenteding we have one of them
    with open(op.join(this_subjects_dir, 'fsaverage', 'label',
                      'lh.aparc_sub.annot'), 'wb'):
        pass
    datasets.fetch_aparc_sub_parcellation(subjects_dir=this_subjects_dir)
    with ArgvSetter(('--accept-hcpmmp-license',)):
        datasets.fetch_hcp_mmp_parcellation(subjects_dir=this_subjects_dir)
    for hemi in ('lh', 'rh'):
        assert op.isfile(op.join(this_subjects_dir, 'fsaverage', 'label',
                                 '%s.aparc_sub.annot' % hemi))
Exemplo n.º 9
0
def test_make_scalp_surfaces():
    """Test mne make_scalp_surfaces."""
    check_usage(mne_make_scalp_surfaces)
    # Copy necessary files to avoid FreeSurfer call
    tempdir = _TempDir()
    surf_path = op.join(subjects_dir, 'sample', 'surf')
    surf_path_new = op.join(tempdir, 'sample', 'surf')
    os.mkdir(op.join(tempdir, 'sample'))
    os.mkdir(surf_path_new)
    subj_dir = op.join(tempdir, 'sample', 'bem')
    os.mkdir(subj_dir)
    shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)

    orig_fs = os.getenv('FREESURFER_HOME', None)
    if orig_fs is not None:
        del os.environ['FREESURFER_HOME']
    cmd = ('-s', 'sample', '--subjects-dir', tempdir)
    os.environ['_MNE_TESTING_SCALP'] = 'true'
    dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
    medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
    try:
        with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
            assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
            os.environ['FREESURFER_HOME'] = tempdir  # don't actually use it
            mne_make_scalp_surfaces.run()
            assert_true(op.isfile(dense_fname))
            assert_true(op.isfile(medium_fname))
            assert_raises(IOError, mne_make_scalp_surfaces.run)  # no overwrite
    finally:
        if orig_fs is not None:
            os.environ['FREESURFER_HOME'] = orig_fs
        else:
            del os.environ['FREESURFER_HOME']
        del os.environ['_MNE_TESTING_SCALP']
    # actually check the outputs
    head_py = read_bem_surfaces(dense_fname)
    assert_equal(len(head_py), 1)
    head_py = head_py[0]
    head_c = read_bem_surfaces(
        op.join(subjects_dir, 'sample', 'bem', 'sample-head-dense.fif'))[0]
    assert_allclose(head_py['rr'], head_c['rr'])
Exemplo n.º 10
0
def test_make_scalp_surfaces(tmp_path, monkeypatch):
    """Test mne make_scalp_surfaces."""
    pytest.importorskip('nibabel')
    pytest.importorskip('pyvista')
    check_usage(mne_make_scalp_surfaces)
    has = 'SUBJECTS_DIR' in os.environ
    # Copy necessary files to avoid FreeSurfer call
    tempdir = str(tmp_path)
    surf_path = op.join(subjects_dir, 'sample', 'surf')
    surf_path_new = op.join(tempdir, 'sample', 'surf')
    os.mkdir(op.join(tempdir, 'sample'))
    os.mkdir(surf_path_new)
    subj_dir = op.join(tempdir, 'sample', 'bem')
    os.mkdir(subj_dir)

    cmd = ('-s', 'sample', '--subjects-dir', tempdir)
    monkeypatch.setattr(
        mne.bem, 'decimate_surface', lambda points, triangles, n_triangles:
        (points, triangles))
    dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
    medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
    with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
        monkeypatch.delenv('FREESURFER_HOME', None)
        with pytest.raises(RuntimeError, match='The FreeSurfer environ'):
            mne_make_scalp_surfaces.run()
        shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)
        monkeypatch.setenv('FREESURFER_HOME', tempdir)
        mne_make_scalp_surfaces.run()
        assert op.isfile(dense_fname)
        assert op.isfile(medium_fname)
        with pytest.raises(IOError, match='overwrite'):
            mne_make_scalp_surfaces.run()
    # actually check the outputs
    head_py = read_bem_surfaces(dense_fname)
    assert_equal(len(head_py), 1)
    head_py = head_py[0]
    head_c = read_bem_surfaces(
        op.join(subjects_dir, 'sample', 'bem', 'sample-head-dense.fif'))[0]
    assert_allclose(head_py['rr'], head_c['rr'])
    if not has:
        assert 'SUBJECTS_DIR' not in os.environ
Exemplo n.º 11
0
def test_fetch_file():
    """Test file downloading
    """
    tempdir = _TempDir()
    urls = ['http://martinos.org/mne/',
            'ftp://surfer.nmr.mgh.harvard.edu/pub/data/bert.recon.md5sum.txt']
    with ArgvSetter(disable_stderr=False):  # to capture stdout
        for url in urls:
            archive_name = op.join(tempdir, "download_test")
            _fetch_file(url, archive_name, verbose=False)
            assert_raises(Exception, _fetch_file, 'NOT_AN_ADDRESS',
                          op.join(tempdir, 'test'), verbose=False)
            resume_name = op.join(tempdir, "download_resume")
            # touch file
            with open(resume_name + '.part', 'w'):
                os.utime(resume_name + '.part', None)
            _fetch_file(url, resume_name, resume=True, verbose=False)
            assert_raises(ValueError, _fetch_file, url, archive_name,
                          hash_='a', verbose=False)
            assert_raises(RuntimeError, _fetch_file, url, archive_name,
                          hash_='a' * 32, verbose=False)
Exemplo n.º 12
0
def test_flash_bem(tmp_path):
    """Test mne flash_bem."""
    check_usage(mne_flash_bem, force_help=True)
    # Copy necessary files to tempdir
    tempdir = str(tmp_path)
    mridata_path = op.join(subjects_dir, 'sample', 'mri')
    subject_path_new = op.join(tempdir, 'sample')
    mridata_path_new = op.join(subject_path_new, 'mri')
    os.makedirs(op.join(mridata_path_new, 'flash'))
    os.makedirs(op.join(subject_path_new, 'bem'))
    shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
                    op.join(mridata_path_new, 'T1.mgz'))
    shutil.copyfile(op.join(mridata_path, 'brain.mgz'),
                    op.join(mridata_path_new, 'brain.mgz'))
    # Copy the available mri/flash/mef*.mgz files from the dataset
    flash_path = op.join(mridata_path_new, 'flash')
    for kind in (5, 30):
        in_fname = op.join(mridata_path, 'flash', 'mef%02d.mgz' % kind)
        shutil.copyfile(in_fname, op.join(flash_path, op.basename(in_fname)))
    # Test mne flash_bem with --noconvert option
    # (since there are no DICOM Flash images in dataset)
    for s in ('outer_skin', 'outer_skull', 'inner_skull'):
        assert not op.isfile(op.join(subject_path_new, 'bem', '%s.surf' % s))
    with ArgvSetter(('-d', tempdir, '-s', 'sample', '-n'),
                    disable_stdout=False,
                    disable_stderr=False):
        mne_flash_bem.run()

    kwargs = dict(rtol=1e-5, atol=1e-5)
    for s in ('outer_skin', 'outer_skull', 'inner_skull'):
        rr, tris = read_surface(op.join(subject_path_new, 'bem',
                                        '%s.surf' % s))
        assert_equal(len(tris), 5120)
        assert_equal(tris.min(), 0)
        assert_equal(rr.shape[0], tris.max() + 1)
        # compare to the testing flash surfaces
        rr_c, tris_c = read_surface(
            op.join(subjects_dir, 'sample', 'bem', '%s.surf' % s))
        assert_allclose(rr, rr_c, **kwargs)
        assert_allclose(tris, tris_c, **kwargs)
Exemplo n.º 13
0
def test_fetch_file():
    """Test file downloading
    """
    tempdir = _TempDir()
    urls = ['http://google.com', 'ftp://ftp.openbsd.org/pub/OpenBSD/README']
    with ArgvSetter(disable_stderr=False):  # to capture stdout
        for url in urls:
            archive_name = op.join(tempdir, "download_test")
            _fetch_file(url,
                        archive_name,
                        timeout=30.,
                        verbose=False,
                        resume=False)
            assert_raises(Exception,
                          _fetch_file,
                          'NOT_AN_ADDRESS',
                          op.join(tempdir, 'test'),
                          verbose=False)
            resume_name = op.join(tempdir, "download_resume")
            # touch file
            with open(resume_name + '.part', 'w'):
                os.utime(resume_name + '.part', None)
            _fetch_file(url,
                        resume_name,
                        resume=True,
                        timeout=30.,
                        verbose=False)
            assert_raises(ValueError,
                          _fetch_file,
                          url,
                          archive_name,
                          hash_='a',
                          verbose=False)
            assert_raises(RuntimeError,
                          _fetch_file,
                          url,
                          archive_name,
                          hash_='a' * 32,
                          verbose=False)
Exemplo n.º 14
0
def test_fetch_parcellations(tmpdir):
    """Test fetching parcellations."""
    this_subjects_dir = str(tmpdir)
    os.mkdir(op.join(this_subjects_dir, 'fsaverage'))
    os.mkdir(op.join(this_subjects_dir, 'fsaverage', 'label'))
    os.mkdir(op.join(this_subjects_dir, 'fsaverage', 'surf'))
    for hemi in ('lh', 'rh'):
        shutil.copyfile(
            op.join(subjects_dir, 'fsaverage', 'surf', '%s.white' % hemi),
            op.join(this_subjects_dir, 'fsaverage', 'surf', '%s.white' % hemi))
    # speed up by prenteding we have one of them
    with open(
            op.join(this_subjects_dir, 'fsaverage', 'label',
                    'lh.aparc_sub.annot'), 'wb'):
        pass
    datasets.fetch_aparc_sub_parcellation(subjects_dir=this_subjects_dir)
    with ArgvSetter(('--accept-hcpmmp-license', )):
        datasets.fetch_hcp_mmp_parcellation(subjects_dir=this_subjects_dir)
    for hemi in ('lh', 'rh'):
        assert op.isfile(
            op.join(this_subjects_dir, 'fsaverage', 'label',
                    '%s.aparc_sub.annot' % hemi))
    # test our annot round-trips here
    kwargs = dict(subject='fsaverage',
                  hemi='both',
                  sort=False,
                  subjects_dir=this_subjects_dir)
    labels = read_labels_from_annot(parc='HCPMMP1', **kwargs)
    write_labels_to_annot(labels,
                          parc='HCPMMP1_round',
                          table_name='./left.fsaverage164.label.gii',
                          **kwargs)
    orig = op.join(this_subjects_dir, 'fsaverage', 'label', 'lh.HCPMMP1.annot')
    first = hashfunc(orig)
    new = orig[:-6] + '_round.annot'
    second = hashfunc(new)
    assert first == second
Exemplo n.º 15
0
def test_make_scalp_surfaces(tmpdir):
    """Test mne make_scalp_surfaces."""
    check_usage(mne_make_scalp_surfaces)
    has = 'SUBJECTS_DIR' in os.environ
    # Copy necessary files to avoid FreeSurfer call
    tempdir = str(tmpdir)
    surf_path = op.join(subjects_dir, 'sample', 'surf')
    surf_path_new = op.join(tempdir, 'sample', 'surf')
    os.mkdir(op.join(tempdir, 'sample'))
    os.mkdir(surf_path_new)
    subj_dir = op.join(tempdir, 'sample', 'bem')
    os.mkdir(subj_dir)
    shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)

    cmd = ('-s', 'sample', '--subjects-dir', tempdir)
    with modified_env(**{'_MNE_TESTING_SCALP': 'true'}):
        dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
        medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
        with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
            with modified_env(FREESURFER_HOME=None):
                pytest.raises(RuntimeError, mne_make_scalp_surfaces.run)
            with modified_env(FREESURFER_HOME=tempdir):
                mne_make_scalp_surfaces.run()
                assert op.isfile(dense_fname)
                assert op.isfile(medium_fname)
                with pytest.raises(IOError, match='overwrite'):
                    mne_make_scalp_surfaces.run()
    # actually check the outputs
    head_py = read_bem_surfaces(dense_fname)
    assert_equal(len(head_py), 1)
    head_py = head_py[0]
    head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
                                       'sample-head-dense.fif'))[0]
    assert_allclose(head_py['rr'], head_c['rr'])
    if not has:
        assert 'SUBJECTS_DIR' not in os.environ
Exemplo n.º 16
0
def test_what():
    """Test mne browse_raw."""
    check_usage(mne_browse_raw)
    with ArgvSetter((raw_fname,)) as out:
        mne_what.run()
    assert 'raw' == out.stdout.getvalue().strip()
Exemplo n.º 17
0
def test_browse_raw():
    """Test mne browse_raw."""
    check_usage(mne_browse_raw)
    with ArgvSetter(('--raw', raw_fname)):
        with pytest.warns(None):  # mpl show warning sometimes
            mne_browse_raw.run()
Exemplo n.º 18
0
def test_browse_raw():
    """Test mne browse_raw."""
    check_usage(mne_browse_raw)
    with ArgvSetter(('--raw', raw_fname)):
        with _record_warnings():  # mpl show warning
            mne_browse_raw.run()
Exemplo n.º 19
0
def test_show_info():
    """Test mne show_info."""
    check_usage(mne_show_info)
    with ArgvSetter((raw_fname, )):
        mne_show_info.run()
Exemplo n.º 20
0
def test_show_fiff():
    """Test mne compare_fiff"""
    check_usage(mne_show_fiff)
    with ArgvSetter((raw_fname, )):
        mne_show_fiff.run()
Exemplo n.º 21
0
def test_browse_raw():
    """Test mne browse_raw."""
    check_usage(mne_browse_raw)
    with ArgvSetter(('--raw', raw_fname)):
        mne_browse_raw.run()
Exemplo n.º 22
0
def test_flash_bem(tmp_path):
    """Test mne flash_bem."""
    check_usage(mne_flash_bem, force_help=True)
    # Copy necessary files to tempdir
    tempdir = Path(str(tmp_path))
    mridata_path = Path(subjects_dir) / 'sample' / 'mri'
    subject_path_new = tempdir / 'sample'
    mridata_path_new = subject_path_new / 'mri'
    flash_path = mridata_path_new / 'flash'
    flash_path.mkdir(parents=True, exist_ok=True)
    bem_path = mridata_path_new / 'bem'
    bem_path.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
                    op.join(mridata_path_new, 'T1.mgz'))
    shutil.copyfile(op.join(mridata_path, 'brain.mgz'),
                    op.join(mridata_path_new, 'brain.mgz'))
    # Copy the available mri/flash/mef*.mgz files from the dataset
    for kind in (5, 30):
        in_fname = mridata_path / "flash" / f'mef{kind:02d}.mgz'
        in_fname_echo = flash_path / f'mef{kind:02d}_001.mgz'
        shutil.copyfile(in_fname, flash_path / in_fname_echo.name)
    # Test mne flash_bem with --noconvert option
    # (since there are no DICOM Flash images in dataset)
    for s in ('outer_skin', 'outer_skull', 'inner_skull'):
        assert not op.isfile(subject_path_new / 'bem' / f'{s}.surf')

    # First test without flash30
    with ArgvSetter(('-d', tempdir, '-s', 'sample', '-n', '-r', '-3'),
                    disable_stdout=False,
                    disable_stderr=False):
        mne_flash_bem.run()
    for s in ('outer_skin', 'outer_skull', 'inner_skull'):
        surf_path = subject_path_new / 'bem' / f'{s}.surf'
        assert surf_path.exists()
        surf_path.unlink()  # cleanup
    shutil.rmtree(flash_path / "parameter_maps")  # remove old files

    # Test synthesize flash5 with MEF flash5 and flash30 default locations
    flash5_img = convert_flash_mris(subject="sample",
                                    subjects_dir=tempdir,
                                    convert=False,
                                    unwarp=False)
    assert flash5_img == (flash_path / "parameter_maps" / "flash5.mgz")
    assert flash5_img.exists()
    shutil.rmtree(flash_path / "parameter_maps")  # remove old files

    # Test with flash5 and flash30
    shutil.rmtree(flash_path)  # first remove old files
    with ArgvSetter(('-d', tempdir, '-s', 'sample', '-n', '-3',
                     str(mridata_path / "flash" / 'mef30.mgz'), '-5',
                     str(mridata_path / "flash" / 'mef05.mgz')),
                    disable_stdout=False,
                    disable_stderr=False):
        mne_flash_bem.run()

    kwargs = dict(rtol=1e-5, atol=1e-5)
    for s in ('outer_skin', 'outer_skull', 'inner_skull'):
        rr, tris = read_surface(op.join(subject_path_new, 'bem',
                                        '%s.surf' % s))
        assert_equal(len(tris), 5120)
        assert_equal(tris.min(), 0)
        assert_equal(rr.shape[0], tris.max() + 1)
        # compare to the testing flash surfaces
        rr_c, tris_c = read_surface(
            op.join(subjects_dir, 'sample', 'bem', '%s.surf' % s))
        assert_allclose(rr, rr_c, **kwargs)
        assert_allclose(tris, tris_c, **kwargs)