Ejemplo n.º 1
0
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    create_default_subject(subjects_dir=tempdir)
    is_mri = _is_mri_subject('fsaverage', tempdir)
    assert_true(is_mri, "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-ico-6-src.fif')
    if not os.path.exists(path):
        cmd = ['mne_setup_source_space', '--subject', 'fsaverage', '--ico',
               '6']
        env = os.environ.copy()
        env['SUBJECTS_DIR'] = tempdir
        run_subprocess(cmd, env=env)

    # scale fsaverage
    scale_mri('fsaverage', 'flachkopf', [1, .2, .8], True, subjects_dir=tempdir)
    is_mri = _is_mri_subject('flachkopf', tempdir)
    assert_true(is_mri, "Scaling fsaverage failed")
    src_path = os.path.join(tempdir, 'flachkopf', 'bem',
                            'flachkopf-ico-6-src.fif')
    assert_true(os.path.exists(src_path), "Source space was not scaled")
    scale_labels('flachkopf', subjects_dir=tempdir)

    # scale source space separately
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-6', subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")
Ejemplo n.º 2
0
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    tempdir = _TempDir()
    create_default_subject(subjects_dir=tempdir)
    is_mri = _is_mri_subject('fsaverage', tempdir)
    assert_true(is_mri, "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # remove redundant label files
    label_temp = os.path.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-ico-0-src.fif')
    src = mne.setup_source_space('fsaverage',
                                 'ico0',
                                 subjects_dir=tempdir,
                                 add_dist=False)
    src_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-ico-0-src.fif')
    write_source_spaces(src_path, src)

    # scale fsaverage
    os.environ['_MNE_FEW_SURFACES'] = 'true'
    scale_mri('fsaverage',
              'flachkopf', [1, .2, .8],
              True,
              subjects_dir=tempdir)
    del os.environ['_MNE_FEW_SURFACES']
    is_mri = _is_mri_subject('flachkopf', tempdir)
    assert_true(is_mri, "Scaling fsaverage failed")
    src_path = os.path.join(tempdir, 'flachkopf', 'bem',
                            'flachkopf-ico-0-src.fif')

    assert_true(os.path.exists(src_path), "Source space was not scaled")
    scale_labels('flachkopf', subjects_dir=tempdir)

    # scale source space separately
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")

    # add distances to source space
    src = mne.read_source_spaces(path)
    mne.add_source_space_distances(src)
    src.save(path, overwrite=True)

    # scale with distances
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    tempdir = _TempDir()
    create_default_subject(subjects_dir=tempdir)
    is_mri = _is_mri_subject('fsaverage', tempdir)
    assert_true(is_mri, "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # remove redundant label files
    label_temp = os.path.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-ico-0-src.fif')
    mne.setup_source_space('fsaverage', path, 'ico0', overwrite=True,
                           subjects_dir=tempdir, add_dist=False)

    # scale fsaverage
    os.environ['_MNE_FEW_SURFACES'] = 'true'
    scale_mri('fsaverage', 'flachkopf', [1, .2, .8], True,
              subjects_dir=tempdir)
    del os.environ['_MNE_FEW_SURFACES']
    is_mri = _is_mri_subject('flachkopf', tempdir)
    assert_true(is_mri, "Scaling fsaverage failed")
    src_path = os.path.join(tempdir, 'flachkopf', 'bem',
                            'flachkopf-ico-0-src.fif')
    assert_true(os.path.exists(src_path), "Source space was not scaled")
    scale_labels('flachkopf', subjects_dir=tempdir)

    # scale source space separately
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")

    # add distances to source space
    src = mne.read_source_spaces(path)
    mne.add_source_space_distances(src)
    src.save(path)

    # scale with distances
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
Ejemplo n.º 4
0
def subjects_dir_tmp_few(tmp_path):
    """Copy fewer files to a tmp_path."""
    subjects_path = tmp_path / 'subjects'
    os.mkdir(subjects_path)
    # add fsaverage
    create_default_subject(subjects_dir=subjects_path, fs_home=test_path,
                           verbose=True)
    # add sample (with few files)
    sample_path = subjects_path / 'sample'
    os.makedirs(sample_path / 'bem')
    for dirname in ('mri', 'surf'):
        shutil.copytree(
            test_path / 'subjects' / 'sample' / dirname, sample_path / dirname)
    return subjects_path
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    tempdir = _TempDir()
    create_default_subject(subjects_dir=tempdir)
    is_mri = _is_mri_subject("fsaverage", tempdir)
    assert_true(is_mri, "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, "fsaverage", "bem", "fsaverage-fiducials.fif")
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # remove redundant label files
    label_temp = os.path.join(tempdir, "fsaverage", "label", "*.label")
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    path = os.path.join(tempdir, "fsaverage", "bem", "fsaverage-ico-0-src.fif")
    mne.setup_source_space("fsaverage", path, "ico0", overwrite=True, subjects_dir=tempdir, add_dist=False)

    # scale fsaverage
    os.environ["_MNE_FEW_SURFACES"] = "true"
    scale_mri("fsaverage", "flachkopf", [1, 0.2, 0.8], True, subjects_dir=tempdir)
    del os.environ["_MNE_FEW_SURFACES"]
    is_mri = _is_mri_subject("flachkopf", tempdir)
    assert_true(is_mri, "Scaling fsaverage failed")
    src_path = os.path.join(tempdir, "flachkopf", "bem", "flachkopf-ico-0-src.fif")
    assert_true(os.path.exists(src_path), "Source space was not scaled")
    scale_labels("flachkopf", subjects_dir=tempdir)

    # scale source space separately
    os.remove(src_path)
    scale_source_space("flachkopf", "ico-0", subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")

    # add distances to source space
    src = mne.read_source_spaces(path)
    mne.add_source_space_distances(src)
    src.save(path)

    # scale with distances
    os.remove(src_path)
    scale_source_space("flachkopf", "ico-0", subjects_dir=tempdir)
Ejemplo n.º 6
0
def test_scale_mri():
    """Test creating fsaverage and scaling it."""
    # create fsaverage using the testing "fsaverage" instead of the FreeSurfer
    # one
    tempdir = _TempDir()
    fake_home = testing.data_path()
    create_default_subject(subjects_dir=tempdir, fs_home=fake_home,
                           verbose=True)
    assert _is_mri_subject('fsaverage', tempdir), "Creating fsaverage failed"

    fid_path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir,
                           fs_home=fake_home)
    assert op.exists(fid_path), "Updating fsaverage"

    # copy MRI file from sample data (shouldn't matter that it's incorrect,
    # so here choose a small one)
    path_from = op.join(testing.data_path(), 'subjects', 'sample', 'mri',
                        'T1.mgz')
    path_to = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    copyfile(path_from, path_to)

    # remove redundant label files
    label_temp = op.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    print('Creating surface source space')
    path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage', 'ico0', subjects_dir=tempdir,
                                 add_dist=False)
    mri = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    print('Creating volume source space')
    vsrc = mne.setup_volume_source_space(
        'fsaverage', pos=50, mri=mri, subjects_dir=tempdir,
        add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    for scale in (.9, [1, .2, .8]):
        write_source_spaces(path % 'ico-0', src, overwrite=True)
        os.environ['_MNE_FEW_SURFACES'] = 'true'
        with pytest.warns(None):  # sometimes missing nibabel
            scale_mri('fsaverage', 'flachkopf', scale, True,
                      subjects_dir=tempdir, verbose='debug')
        del os.environ['_MNE_FEW_SURFACES']
        assert _is_mri_subject('flachkopf', tempdir), "Scaling failed"
        spath = op.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

        assert op.exists(spath % 'ico-0'), "Source space ico-0 was not scaled"
        assert os.path.isfile(os.path.join(tempdir, 'flachkopf', 'surf',
                                           'lh.sphere.reg'))
        vsrc_s = mne.read_source_spaces(spath % 'vol-50')
        pt = np.array([0.12, 0.41, -0.22])
        assert_array_almost_equal(
            apply_trans(vsrc_s[0]['src_mri_t'], pt * np.array(scale)),
            apply_trans(vsrc[0]['src_mri_t'], pt))
        scale_labels('flachkopf', subjects_dir=tempdir)

        # add distances to source space after hacking the properties to make
        # it run *much* faster
        src_dist = src.copy()
        for s in src_dist:
            s.update(rr=s['rr'][s['vertno']], nn=s['nn'][s['vertno']],
                     tris=s['use_tris'])
            s.update(np=len(s['rr']), ntri=len(s['tris']),
                     vertno=np.arange(len(s['rr'])),
                     inuse=np.ones(len(s['rr']), int))
        mne.add_source_space_distances(src_dist)
        write_source_spaces(path % 'ico-0', src_dist, overwrite=True)

        # scale with distances
        os.remove(spath % 'ico-0')
        scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
        ssrc = mne.read_source_spaces(spath % 'ico-0')
        assert ssrc[0]['dist'] is not None
Ejemplo n.º 7
0
def test_scale_mri_xfm():
    """Test scale_mri transforms and MRI scaling."""
    # scale fsaverage
    tempdir = _TempDir()
    os.environ['_MNE_FEW_SURFACES'] = 'true'
    fake_home = testing.data_path()
    # add fsaverage
    create_default_subject(subjects_dir=tempdir, fs_home=fake_home,
                           verbose=True)
    # add sample (with few files)
    sample_dir = op.join(tempdir, 'sample')
    os.mkdir(sample_dir)
    os.mkdir(op.join(sample_dir, 'bem'))
    for dirname in ('mri', 'surf'):
        copytree(op.join(fake_home, 'subjects', 'sample', dirname),
                 op.join(sample_dir, dirname))
    subject_to = 'flachkopf'
    spacing = 'oct2'
    for subject_from in ('fsaverage', 'sample'):
        if subject_from == 'fsaverage':
            scale = 1.  # single dim
        else:
            scale = [0.9, 2, .8]  # separate
        src_from_fname = op.join(tempdir, subject_from, 'bem',
                                 '%s-%s-src.fif' % (subject_from, spacing))
        src_from = mne.setup_source_space(
            subject_from, spacing, subjects_dir=tempdir, add_dist=False)
        write_source_spaces(src_from_fname, src_from)
        print(src_from_fname)
        vertices_from = np.concatenate([s['vertno'] for s in src_from])
        assert len(vertices_from) == 36
        hemis = ([0] * len(src_from[0]['vertno']) +
                 [1] * len(src_from[0]['vertno']))
        mni_from = mne.vertex_to_mni(vertices_from, hemis, subject_from,
                                     subjects_dir=tempdir)
        if subject_from == 'fsaverage':  # identity transform
            source_rr = np.concatenate([s['rr'][s['vertno']]
                                        for s in src_from]) * 1e3
            assert_allclose(mni_from, source_rr)
        if subject_from == 'fsaverage':
            overwrite = skip_fiducials = False
        else:
            with pytest.raises(IOError, match='No fiducials file'):
                scale_mri(subject_from, subject_to,  scale,
                          subjects_dir=tempdir)
            skip_fiducials = True
            with pytest.raises(IOError, match='already exists'):
                scale_mri(subject_from, subject_to,  scale,
                          subjects_dir=tempdir, skip_fiducials=skip_fiducials)
            overwrite = True
        scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir,
                  verbose='debug', overwrite=overwrite,
                  skip_fiducials=skip_fiducials)
        if subject_from == 'fsaverage':
            assert _is_mri_subject(subject_to, tempdir), "Scaling failed"
        src_to_fname = op.join(tempdir, subject_to, 'bem',
                               '%s-%s-src.fif' % (subject_to, spacing))
        assert op.exists(src_to_fname), "Source space was not scaled"
        # Check MRI scaling
        fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz')
        assert op.exists(fname_mri), "MRI was not scaled"
        # Check MNI transform
        src = mne.read_source_spaces(src_to_fname)
        vertices = np.concatenate([s['vertno'] for s in src])
        assert_array_equal(vertices, vertices_from)
        mni = mne.vertex_to_mni(vertices, hemis, subject_to,
                                subjects_dir=tempdir)
        assert_allclose(mni, mni_from, atol=1e-3)  # 0.001 mm
    del os.environ['_MNE_FEW_SURFACES']
Ejemplo n.º 8
0
def test_scale_mri(tmp_path, few_surfaces, scale):
    """Test creating fsaverage and scaling it."""
    # create fsaverage using the testing "fsaverage" instead of the FreeSurfer
    # one
    tempdir = str(tmp_path)
    fake_home = testing.data_path()
    create_default_subject(subjects_dir=tempdir,
                           fs_home=fake_home,
                           verbose=True)
    assert _is_mri_subject('fsaverage', tempdir), "Creating fsaverage failed"

    fid_path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True,
                           subjects_dir=tempdir,
                           fs_home=fake_home)
    assert op.exists(fid_path), "Updating fsaverage"

    # copy MRI file from sample data (shouldn't matter that it's incorrect,
    # so here choose a small one)
    path_from = op.join(testing.data_path(), 'subjects', 'sample', 'mri',
                        'T1.mgz')
    path_to = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    copyfile(path_from, path_to)

    # remove redundant label files
    label_temp = op.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    print('Creating surface source space')
    path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage',
                                 'ico0',
                                 subjects_dir=tempdir,
                                 add_dist=False)
    mri = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    print('Creating volume source space')
    vsrc = mne.setup_volume_source_space('fsaverage',
                                         pos=50,
                                         mri=mri,
                                         subjects_dir=tempdir,
                                         add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    write_source_spaces(path % 'ico-0', src, overwrite=True)
    with pytest.warns(None):  # sometimes missing nibabel
        scale_mri('fsaverage',
                  'flachkopf',
                  scale,
                  True,
                  subjects_dir=tempdir,
                  verbose='debug')
    assert _is_mri_subject('flachkopf', tempdir), "Scaling failed"
    spath = op.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

    assert op.exists(spath % 'ico-0'), "Source space ico-0 was not scaled"
    assert os.path.isfile(
        os.path.join(tempdir, 'flachkopf', 'surf', 'lh.sphere.reg'))
    vsrc_s = mne.read_source_spaces(spath % 'vol-50')
    for vox in ([0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 2, 3]):
        idx = np.ravel_multi_index(vox, vsrc[0]['shape'], order='F')
        err_msg = f'idx={idx} @ {vox}, scale={scale}'
        assert_allclose(apply_trans(vsrc[0]['src_mri_t'], vox),
                        vsrc[0]['rr'][idx],
                        err_msg=err_msg)
        assert_allclose(apply_trans(vsrc_s[0]['src_mri_t'], vox),
                        vsrc_s[0]['rr'][idx],
                        err_msg=err_msg)
    scale_labels('flachkopf', subjects_dir=tempdir)

    # add distances to source space after hacking the properties to make
    # it run *much* faster
    src_dist = src.copy()
    for s in src_dist:
        s.update(rr=s['rr'][s['vertno']],
                 nn=s['nn'][s['vertno']],
                 tris=s['use_tris'])
        s.update(np=len(s['rr']),
                 ntri=len(s['tris']),
                 vertno=np.arange(len(s['rr'])),
                 inuse=np.ones(len(s['rr']), int))
    mne.add_source_space_distances(src_dist)
    write_source_spaces(path % 'ico-0', src_dist, overwrite=True)

    # scale with distances
    os.remove(spath % 'ico-0')
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    ssrc = mne.read_source_spaces(spath % 'ico-0')
    assert ssrc[0]['dist'] is not None
    assert ssrc[0]['nearest'] is not None

    # check patch info computation (only if SciPy is new enough to be fast)
    if check_version('scipy', '1.3'):
        for s in src_dist:
            for key in ('dist', 'dist_limit'):
                s[key] = None
        write_source_spaces(path % 'ico-0', src_dist, overwrite=True)

        # scale with distances
        os.remove(spath % 'ico-0')
        scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
        ssrc = mne.read_source_spaces(spath % 'ico-0')
        assert ssrc[0]['dist'] is None
        assert ssrc[0]['nearest'] is not None
Ejemplo n.º 9
0
def test_scale_mri_xfm(tmp_path, few_surfaces):
    """Test scale_mri transforms and MRI scaling."""
    # scale fsaverage
    tempdir = str(tmp_path)
    fake_home = testing.data_path()
    # add fsaverage
    create_default_subject(subjects_dir=tempdir,
                           fs_home=fake_home,
                           verbose=True)
    # add sample (with few files)
    sample_dir = op.join(tempdir, 'sample')
    os.mkdir(sample_dir)
    os.mkdir(op.join(sample_dir, 'bem'))
    for dirname in ('mri', 'surf'):
        copytree(op.join(fake_home, 'subjects', 'sample', dirname),
                 op.join(sample_dir, dirname))
    subject_to = 'flachkopf'
    spacing = 'oct2'
    for subject_from in ('fsaverage', 'sample'):
        if subject_from == 'fsaverage':
            scale = 1.  # single dim
        else:
            scale = [0.9, 2, .8]  # separate
        src_from_fname = op.join(tempdir, subject_from, 'bem',
                                 '%s-%s-src.fif' % (subject_from, spacing))
        src_from = mne.setup_source_space(subject_from,
                                          spacing,
                                          subjects_dir=tempdir,
                                          add_dist=False)
        write_source_spaces(src_from_fname, src_from)
        vertices_from = np.concatenate([s['vertno'] for s in src_from])
        assert len(vertices_from) == 36
        hemis = ([0] * len(src_from[0]['vertno']) +
                 [1] * len(src_from[0]['vertno']))
        mni_from = mne.vertex_to_mni(vertices_from,
                                     hemis,
                                     subject_from,
                                     subjects_dir=tempdir)
        if subject_from == 'fsaverage':  # identity transform
            source_rr = np.concatenate(
                [s['rr'][s['vertno']] for s in src_from]) * 1e3
            assert_allclose(mni_from, source_rr)
        if subject_from == 'fsaverage':
            overwrite = skip_fiducials = False
        else:
            with pytest.raises(IOError, match='No fiducials file'):
                scale_mri(subject_from,
                          subject_to,
                          scale,
                          subjects_dir=tempdir)
            skip_fiducials = True
            with pytest.raises(IOError, match='already exists'):
                scale_mri(subject_from,
                          subject_to,
                          scale,
                          subjects_dir=tempdir,
                          skip_fiducials=skip_fiducials)
            overwrite = True
        if subject_from == 'sample':  # support for not needing all surf files
            os.remove(op.join(sample_dir, 'surf', 'lh.curv'))
        scale_mri(subject_from,
                  subject_to,
                  scale,
                  subjects_dir=tempdir,
                  verbose='debug',
                  overwrite=overwrite,
                  skip_fiducials=skip_fiducials)
        if subject_from == 'fsaverage':
            assert _is_mri_subject(subject_to, tempdir), "Scaling failed"
        src_to_fname = op.join(tempdir, subject_to, 'bem',
                               '%s-%s-src.fif' % (subject_to, spacing))
        assert op.exists(src_to_fname), "Source space was not scaled"
        # Check MRI scaling
        fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz')
        assert op.exists(fname_mri), "MRI was not scaled"
        # Check MNI transform
        src = mne.read_source_spaces(src_to_fname)
        vertices = np.concatenate([s['vertno'] for s in src])
        assert_array_equal(vertices, vertices_from)
        mni = mne.vertex_to_mni(vertices,
                                hemis,
                                subject_to,
                                subjects_dir=tempdir)
        assert_allclose(mni, mni_from, atol=1e-3)  # 0.001 mm
Ejemplo n.º 10
0
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    tempdir = _TempDir()
    create_default_subject(subjects_dir=tempdir)
    assert_true(_is_mri_subject('fsaverage', tempdir),
                "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # copy MRI file from sample data
    path = os.path.join('%s', 'fsaverage', 'mri', 'orig.mgz')
    sample_sdir = os.path.join(mne.datasets.sample.data_path(), 'subjects')
    copyfile(path % sample_sdir, path % tempdir)

    # remove redundant label files
    label_temp = os.path.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage', 'ico0', subjects_dir=tempdir,
                                 add_dist=False)
    write_source_spaces(path % 'ico-0', src)
    mri = os.path.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    vsrc = mne.setup_volume_source_space('fsaverage', pos=50, mri=mri,
                                         subjects_dir=tempdir,
                                         add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    os.environ['_MNE_FEW_SURFACES'] = 'true'
    scale = np.array([1, .2, .8])
    scale_mri('fsaverage', 'flachkopf', scale, True, subjects_dir=tempdir)
    del os.environ['_MNE_FEW_SURFACES']
    assert_true(_is_mri_subject('flachkopf', tempdir),
                "Scaling fsaverage failed")
    spath = os.path.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

    assert_true(os.path.exists(spath % 'ico-0'),
                "Source space ico-0 was not scaled")
    vsrc_s = mne.read_source_spaces(spath % 'vol-50')
    pt = np.array([0.12, 0.41, -0.22])
    assert_array_almost_equal(apply_trans(vsrc_s[0]['src_mri_t'], pt * scale),
                              apply_trans(vsrc[0]['src_mri_t'], pt))
    scale_labels('flachkopf', subjects_dir=tempdir)

    # add distances to source space
    mne.add_source_space_distances(src)
    src.save(path % 'ico-0', overwrite=True)

    # scale with distances
    os.remove(spath % 'ico-0')
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    ssrc = mne.read_source_spaces(spath % 'ico-0')
    assert_is_not(ssrc[0]['dist'], None)
Ejemplo n.º 11
0
def test_scale_mri():
    """Test creating fsaverage and scaling it."""
    # create fsaverage using the testing "fsaverage" instead of the FreeSurfer
    # one
    tempdir = _TempDir()
    fake_home = testing.data_path()
    create_default_subject(subjects_dir=tempdir, fs_home=fake_home,
                           verbose=True)
    assert _is_mri_subject('fsaverage', tempdir), "Creating fsaverage failed"

    fid_path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir,
                           fs_home=fake_home)
    assert op.exists(fid_path), "Updating fsaverage"

    # copy MRI file from sample data (shouldn't matter that it's incorrect,
    # so here choose a small one)
    path_from = op.join(testing.data_path(), 'subjects', 'sample', 'mri',
                        'T1.mgz')
    path_to = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    copyfile(path_from, path_to)

    # remove redundant label files
    label_temp = op.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    print('Creating surface source space')
    path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage', 'ico0', subjects_dir=tempdir,
                                 add_dist=False)
    write_source_spaces(path % 'ico-0', src)
    mri = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    print('Creating volume source space')
    vsrc = mne.setup_volume_source_space(
        'fsaverage', pos=50, mri=mri, subjects_dir=tempdir,
        add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    os.environ['_MNE_FEW_SURFACES'] = 'true'
    scale = np.array([1, .2, .8])
    scale_mri('fsaverage', 'flachkopf', scale, True, subjects_dir=tempdir,
              verbose='debug')
    del os.environ['_MNE_FEW_SURFACES']
    assert _is_mri_subject('flachkopf', tempdir), "Scaling fsaverage failed"
    spath = op.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

    assert op.exists(spath % 'ico-0'), "Source space ico-0 was not scaled"
    assert os.path.isfile(os.path.join(tempdir, 'flachkopf', 'surf',
                                       'lh.sphere.reg'))
    vsrc_s = mne.read_source_spaces(spath % 'vol-50')
    pt = np.array([0.12, 0.41, -0.22])
    assert_array_almost_equal(apply_trans(vsrc_s[0]['src_mri_t'], pt * scale),
                              apply_trans(vsrc[0]['src_mri_t'], pt))
    scale_labels('flachkopf', subjects_dir=tempdir)

    # add distances to source space
    mne.add_source_space_distances(src)
    src.save(path % 'ico-0', overwrite=True)

    # scale with distances
    os.remove(spath % 'ico-0')
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    ssrc = mne.read_source_spaces(spath % 'ico-0')
    assert ssrc[0]['dist'] is not None
Ejemplo n.º 12
0
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    tempdir = _TempDir()
    create_default_subject(subjects_dir=tempdir)
    assert_true(_is_mri_subject('fsaverage', tempdir),
                "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # copy MRI file from sample data
    path = os.path.join('%s', 'fsaverage', 'mri', 'orig.mgz')
    sample_sdir = os.path.join(mne.datasets.sample.data_path(), 'subjects')
    copyfile(path % sample_sdir, path % tempdir)

    # remove redundant label files
    label_temp = os.path.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage',
                                 'ico0',
                                 subjects_dir=tempdir,
                                 add_dist=False)
    write_source_spaces(path % 'ico-0', src)
    mri = os.path.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    vsrc = mne.setup_volume_source_space('fsaverage',
                                         pos=50,
                                         mri=mri,
                                         subjects_dir=tempdir,
                                         add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    os.environ['_MNE_FEW_SURFACES'] = 'true'
    scale = np.array([1, .2, .8])
    scale_mri('fsaverage', 'flachkopf', scale, True, subjects_dir=tempdir)
    del os.environ['_MNE_FEW_SURFACES']
    assert_true(_is_mri_subject('flachkopf', tempdir),
                "Scaling fsaverage failed")
    spath = os.path.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

    assert_true(os.path.exists(spath % 'ico-0'),
                "Source space ico-0 was not scaled")
    vsrc_s = mne.read_source_spaces(spath % 'vol-50')
    pt = np.array([0.12, 0.41, -0.22])
    assert_array_almost_equal(apply_trans(vsrc_s[0]['src_mri_t'], pt * scale),
                              apply_trans(vsrc[0]['src_mri_t'], pt))
    scale_labels('flachkopf', subjects_dir=tempdir)

    # add distances to source space
    mne.add_source_space_distances(src)
    src.save(path % 'ico-0', overwrite=True)

    # scale with distances
    os.remove(spath % 'ico-0')
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    ssrc = mne.read_source_spaces(spath % 'ico-0')
    assert_is_not(ssrc[0]['dist'], None)
Ejemplo n.º 13
0
def test_scale_mri(tmpdir, few_surfaces):
    """Test creating fsaverage and scaling it."""
    # create fsaverage using the testing "fsaverage" instead of the FreeSurfer
    # one
    tempdir = str(tmpdir)
    fake_home = testing.data_path()
    create_default_subject(subjects_dir=tempdir, fs_home=fake_home,
                           verbose=True)
    assert _is_mri_subject('fsaverage', tempdir), "Creating fsaverage failed"

    fid_path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir,
                           fs_home=fake_home)
    assert op.exists(fid_path), "Updating fsaverage"

    # copy MRI file from sample data (shouldn't matter that it's incorrect,
    # so here choose a small one)
    path_from = op.join(testing.data_path(), 'subjects', 'sample', 'mri',
                        'T1.mgz')
    path_to = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    copyfile(path_from, path_to)

    # remove redundant label files
    label_temp = op.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    print('Creating surface source space')
    path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage', 'ico0', subjects_dir=tempdir,
                                 add_dist=False)
    mri = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    print('Creating volume source space')
    vsrc = mne.setup_volume_source_space(
        'fsaverage', pos=50, mri=mri, subjects_dir=tempdir,
        add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    for scale in (.9, [1, .2, .8]):
        write_source_spaces(path % 'ico-0', src, overwrite=True)
        with pytest.warns(None):  # sometimes missing nibabel
            scale_mri('fsaverage', 'flachkopf', scale, True,
                      subjects_dir=tempdir, verbose='debug')
        assert _is_mri_subject('flachkopf', tempdir), "Scaling failed"
        spath = op.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

        assert op.exists(spath % 'ico-0'), "Source space ico-0 was not scaled"
        assert os.path.isfile(os.path.join(tempdir, 'flachkopf', 'surf',
                                           'lh.sphere.reg'))
        vsrc_s = mne.read_source_spaces(spath % 'vol-50')
        pt = np.array([0.12, 0.41, -0.22])
        assert_array_almost_equal(
            apply_trans(vsrc_s[0]['src_mri_t'], pt * np.array(scale)),
            apply_trans(vsrc[0]['src_mri_t'], pt))
        scale_labels('flachkopf', subjects_dir=tempdir)

        # add distances to source space after hacking the properties to make
        # it run *much* faster
        src_dist = src.copy()
        for s in src_dist:
            s.update(rr=s['rr'][s['vertno']], nn=s['nn'][s['vertno']],
                     tris=s['use_tris'])
            s.update(np=len(s['rr']), ntri=len(s['tris']),
                     vertno=np.arange(len(s['rr'])),
                     inuse=np.ones(len(s['rr']), int))
        mne.add_source_space_distances(src_dist)
        write_source_spaces(path % 'ico-0', src_dist, overwrite=True)

        # scale with distances
        os.remove(spath % 'ico-0')
        scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
        ssrc = mne.read_source_spaces(spath % 'ico-0')
        assert ssrc[0]['dist'] is not None