def test_source_space_from_label():
    """Test generating a source space from volume label."""
    tempdir = _TempDir()
    aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
    label_names = get_volume_labels_from_aseg(aseg_fname)
    volume_label = label_names[int(np.random.rand() * len(label_names))]

    # Test pos as dict
    pos = dict()
    pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=pos,
                  volume_label=volume_label, mri=aseg_fname)

    # Test no mri provided
    pytest.raises(RuntimeError, setup_volume_source_space, 'sample', mri=None,
                  volume_label=volume_label)

    # Test invalid volume label
    pytest.raises(ValueError, setup_volume_source_space, 'sample',
                  volume_label='Hello World!', mri=aseg_fname)

    src = setup_volume_source_space('sample', subjects_dir=subjects_dir,
                                    volume_label=volume_label, mri=aseg_fname,
                                    add_interpolator=False)
    assert_equal(volume_label, src[0]['seg_name'])

    # test reading and writing
    out_name = op.join(tempdir, 'temp-src.fif')
    write_source_spaces(out_name, src)
    src_from_file = read_source_spaces(out_name)
    _compare_source_spaces(src, src_from_file, mode='approx')
Exemple #2
0
def test_write_source_space():
    """Test writing and reading of source spaces
    """
    src0 = read_source_spaces(fname, add_geom=False)
    write_source_spaces(op.join(tempdir, 'tmp.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp.fif'), add_geom=False)
    _compare_source_spaces(src0, src1)
Exemple #3
0
def process_subject_source_space(subject):
    # make BEMs using watershed bem
    # NOTE: Use MNE version >= 20 or set overwrite=True!
    # mne.bem.make_watershed_bem(subject,
    #                            subjects_dir=subjects_dir,
    #                            show=False,
    #                            verbose=False,
    #                            overwrite=True)

    bem_surf_fname = op.join(subjects_dir, subject, 'bem',
                             f'{subject}-ico{bem_ico}-bem.fif')
    bem_sol_fname = op.join(subjects_dir, subject, 'bem',
                            f'{subject}-ico{bem_ico}-bem-sol.fif')
    src_fname = op.join(subjects_dir, subject, 'bem',
                        f'{subject}-ico{bem_ico}-src.fif')

    # make BEM models
    # ico5 is for downsamping
    bem_surf = mne.make_bem_model(
        subject,
        ico=bem_ico,
        conductivity=[0.3],  # for MEG data, 1 layer model is enough
        subjects_dir=subjects_dir)
    mne.write_bem_surfaces(bem_surf_fname, bem_surf)
    # make BEM solution
    bem_sol = mne.make_bem_solution(bem_surf)
    mne.write_bem_solution(bem_sol_fname, bem_sol)

    # Create the surface source space
    src = mne.setup_source_space(subject, spacing, subjects_dir=subjects_dir)
    mne.write_source_spaces(src_fname, src, overwrite=True)
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)
def test_discrete_source_space(tmpdir):
    """Test setting up (and reading/writing) discrete source spaces."""
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = tmpdir.join('temp-src.fif')
    # save
    temp_pos = tmpdir.join('temp-pos.txt')
    np.savetxt(str(temp_pos), np.c_[src[0]['rr'][v], src[0]['nn'][v]])
    # let's try the spherical one (no bem or surf supplied)
    run_subprocess(['mne_volume_source_space', '--meters',
                    '--pos', temp_pos, '--src', temp_name])
    src_c = read_source_spaces(temp_name)
    pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v])
    src_new = setup_volume_source_space(pos=pos_dict)
    assert src_new.kind == 'discrete'
    _compare_source_spaces(src_c, src_new, mode='approx')
    assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
                    rtol=1e-3, atol=1e-6)
    assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
                    rtol=1e-3, atol=1e-6)

    # now do writing
    write_source_spaces(temp_name, src_c, overwrite=True)
    src_c2 = read_source_spaces(temp_name)
    _compare_source_spaces(src_c, src_c2)

    # now do MRI
    pytest.raises(ValueError, setup_volume_source_space, 'sample',
                  pos=pos_dict, mri=fname_mri)
    assert repr(src_new) == repr(src_c)
    assert src_new.kind == 'discrete'
    assert _get_src_type(src_new, None) == 'discrete'
def _get_bf_data(save_fieldtrip=False):
    raw, epochs, evoked, data_cov, _, _, _, _, _, fwd = _get_data(proj=False)

    if save_fieldtrip is True:
        # raw needs to be saved with all channels and picked in FieldTrip
        raw.save(op.join(ft_data_path, 'raw.fif'), overwrite=True)

        # src (tris are not available in fwd['src'] once imported into MATLAB)
        src = fwd['src'].copy()
        mne.write_source_spaces(op.join(ft_data_path, 'src.fif'), src)

    # pick gradiometers only:
    epochs.pick_types(meg='grad')
    evoked.pick_types(meg='grad')

    # compute covariance matrix
    data_cov = mne.compute_covariance(epochs,
                                      tmin=0.04,
                                      tmax=0.145,
                                      method='empirical')

    if save_fieldtrip is True:
        # if the covariance matrix and epochs need resaving:
        # data covariance:
        cov_savepath = op.join(ft_data_path, 'sample_cov')
        sample_cov = {'sample_cov': data_cov['data']}
        savemat(cov_savepath, sample_cov)
        # evoked data:
        ev_savepath = op.join(ft_data_path, 'sample_evoked')
        data_ev = {'sample_evoked': evoked.data}
        savemat(ev_savepath, data_ev)

    return evoked, data_cov, fwd
def test_add_source_space_distances_limited():
    """Test adding distances to source space with a dist_limit."""
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    src_new = read_source_spaces(fname)
    del src_new[0]['dist']
    del src_new[1]['dist']
    n_do = 200  # limit this for speed
    src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy()
    src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy()
    out_name = op.join(tempdir, 'temp-src.fif')
    try:
        add_source_space_distances(src_new, dist_limit=0.007)
    except RuntimeError:  # what we throw when scipy version is wrong
        raise SkipTest('dist_limit requires scipy > 0.13')
    write_source_spaces(out_name, src_new)
    src_new = read_source_spaces(out_name)

    for so, sn in zip(src, src_new):
        assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32))
        assert_array_equal(sn['dist_limit'], np.array([0.007], np.float32))
        do = so['dist']
        dn = sn['dist']

        # clean out distances > 0.007 in C code
        do.data[do.data > 0.007] = 0
        do.eliminate_zeros()

        # make sure we have some comparable distances
        assert np.sum(do.data < 0.007) > 400

        # do comparison over the region computed
        d = (do - dn)[:sn['vertno'][n_do - 1]][:, :sn['vertno'][n_do - 1]]
        assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-6)
Exemple #8
0
def _mne_source_space(subject, src_tag, subjects_dir):
    """Load mne source space

    Parameters
    ----------
    subject : str
        Subejct
    src_tag : str
        Spacing (e.g., 'ico-4').
    """
    src_file = os.path.join(subjects_dir, subject, 'bem',
                            '%s-%s-src.fif' % (subject, src_tag))
    src, spacing = src_tag.split('-')
    if os.path.exists(src_file):
        return mne.read_source_spaces(src_file, False)
    elif src == 'ico':
        ss = mne.setup_source_space(subject,
                                    spacing=src + spacing,
                                    subjects_dir=subjects_dir,
                                    add_dist=True)
    elif src == 'vol':
        mri_file = os.path.join(subjects_dir, subject, 'mri', 'orig.mgz')
        bem_file = os.path.join(subjects_dir, subject, 'bem',
                                'sample-5120-5120-5120-bem-sol.fif')
        ss = mne.setup_volume_source_space(subject,
                                           pos=float(spacing),
                                           mri=mri_file,
                                           bem=bem_file,
                                           mindist=0.,
                                           exclude=0.,
                                           subjects_dir=subjects_dir)
    else:
        raise ValueError("src_tag=%s" % repr(src_tag))
    mne.write_source_spaces(src_file, ss)
    return ss
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces
    """
    src = read_source_spaces(fname)
    v = src[0]["vertno"]

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, "temp-src.fif")
    try:
        # save
        temp_pos = op.join(tempdir, "temp-pos.txt")
        np.savetxt(temp_pos, np.c_[src[0]["rr"][v], src[0]["nn"][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(["mne_volume_source_space", "--meters", "--pos", temp_pos, "--src", temp_name])
        src_c = read_source_spaces(temp_name)
        pos_dict = dict(rr=src[0]["rr"][v], nn=src[0]["nn"][v])
        src_new = setup_volume_source_space("sample", None, pos=pos_dict, subjects_dir=subjects_dir)
        _compare_source_spaces(src_c, src_new, mode="approx")
        assert_allclose(src[0]["rr"][v], src_new[0]["rr"], rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]["nn"][v], src_new[0]["nn"], rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c)
        src_c2 = read_source_spaces(temp_name)
        _compare_source_spaces(src_c, src_c2)

        # now do MRI
        assert_raises(ValueError, setup_volume_source_space, "sample", pos=pos_dict, mri=fname_mri)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
def test_volume_source_space():
    """Test setting up volume source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, 'temp-src.fif')
    surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN)
    surf['rr'] *= 1e3  # convert to mm
    # The one in the testing dataset (uses bem as bounds)
    for bem, surf in zip((fname_bem, None), (None, surf)):
        src_new = setup_volume_source_space(
            'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz',
            subjects_dir=subjects_dir)
        write_source_spaces(temp_name, src_new, overwrite=True)
        src[0]['subject_his_id'] = 'sample'  # XXX: to make comparison pass
        _compare_source_spaces(src, src_new, mode='approx')
        del src_new
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')
    pytest.raises(IOError, setup_volume_source_space, 'sample',
                  pos=7.0, bem=None, surface='foo',  # bad surf
                  mri=fname_mri, subjects_dir=subjects_dir)
    assert repr(src) == repr(src_new)
    assert src.kind == 'volume'
    # Spheres
    sphere = make_sphere_model(r0=(0., 0., 0.), head_radius=0.1,
                               relative_radii=(0.9, 1.0), sigmas=(0.33, 1.0))
    src = setup_volume_source_space(pos=10)
    src_new = setup_volume_source_space(pos=10, sphere=sphere)
    _compare_source_spaces(src, src_new, mode='exact')
    pytest.raises(ValueError, setup_volume_source_space, sphere='foo')
    # Need a radius
    sphere = make_sphere_model(head_radius=None)
    pytest.raises(ValueError, setup_volume_source_space, sphere=sphere)
def test_add_source_space_distances_limited(tmpdir):
    """Test adding distances to source space with a dist_limit."""
    src = read_source_spaces(fname)
    src_new = read_source_spaces(fname)
    del src_new[0]['dist']
    del src_new[1]['dist']
    n_do = 200  # limit this for speed
    src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy()
    src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy()
    out_name = tmpdir.join('temp-src.fif')
    add_source_space_distances(src_new, dist_limit=0.007)
    write_source_spaces(out_name, src_new)
    src_new = read_source_spaces(out_name)

    for so, sn in zip(src, src_new):
        assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32))
        assert_array_equal(sn['dist_limit'], np.array([0.007], np.float32))
        do = so['dist']
        dn = sn['dist']

        # clean out distances > 0.007 in C code
        do.data[do.data > 0.007] = 0
        do.eliminate_zeros()

        # make sure we have some comparable distances
        assert np.sum(do.data < 0.007) > 400

        # do comparison over the region computed
        d = (do - dn)[:sn['vertno'][n_do - 1]][:, :sn['vertno'][n_do - 1]]
        assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-6)
def test_add_source_space_distances_limited():
    """Test adding distances to source space with a dist_limit."""
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    src_new = read_source_spaces(fname)
    del src_new[0]['dist']
    del src_new[1]['dist']
    n_do = 200  # limit this for speed
    src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy()
    src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy()
    out_name = op.join(tempdir, 'temp-src.fif')
    try:
        add_source_space_distances(src_new, dist_limit=0.007)
    except RuntimeError:  # what we throw when scipy version is wrong
        raise SkipTest('dist_limit requires scipy > 0.13')
    write_source_spaces(out_name, src_new)
    src_new = read_source_spaces(out_name)

    for so, sn in zip(src, src_new):
        assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32))
        assert_array_equal(sn['dist_limit'], np.array([0.007], np.float32))
        do = so['dist']
        dn = sn['dist']

        # clean out distances > 0.007 in C code
        do.data[do.data > 0.007] = 0
        do.eliminate_zeros()

        # make sure we have some comparable distances
        assert np.sum(do.data < 0.007) > 400

        # do comparison over the region computed
        d = (do - dn)[:sn['vertno'][n_do - 1]][:, :sn['vertno'][n_do - 1]]
        assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-6)
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces
    """
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(['mne_volume_source_space', '--meters',
                        '--pos',  temp_pos, '--src', temp_name])
        src_c = read_source_spaces(temp_name)
        src_new = setup_volume_source_space('sample', None,
                                            pos=dict(rr=src[0]['rr'][v],
                                                     nn=src[0]['nn'][v]),
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
                        rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
                        rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c)
        src_c2 = read_source_spaces(temp_name)
        _compare_source_spaces(src_c, src_c2)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
def test_write_source_space():
    """Test writing and reading of source spaces
    """
    src0 = read_source_spaces(fname, add_geom=False)
    write_source_spaces(op.join(tempdir, 'tmp.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp.fif'), add_geom=False)
    _compare_source_spaces(src0, src1)
Exemple #15
0
    def __init_with_mne_sample_data(self):
        """
        Initializes MEG, BEM, Source space and tranforms with MNE sample data
        """
        self.data_path = os.path.abspath(join(self.subjects_dir, os.pardir))
        self.subject_name = 'sample'

        self.raw_path = join(self.data_path, 'MEG', 'sample',
                             'sample_audvis_raw.fif')
        self.info = mne.io.read_info(self.raw_path)
        self.bem_path = join(self.data_path, 'subjects', 'sample', 'bem',
                             'sample-5120-5120-5120-bem-sol.fif')
        src_file = 'sample-' + self.spacing[0:3] + '-' + self.spacing[
            -1] + '-src.fif'
        src_path = join(self.data_path, 'subjects', 'sample', 'bem', src_file)
        if not os.path.isfile(src_path):
            print(
                "Source space file not found, creating new source space file..."
            )
            src = mne.setup_source_space(str('sample'), spacing=self.spacing)
            # write source spaces
            mne.write_source_spaces(src_path, src)

        self.src_path = src_path
        # self.trans_path = None
        self.trans_path = join(self.data_path, 'MEG', 'sample',
                               'sample_audvis_raw-trans.fif')
        self.cov_path = join(self.data_path, 'MEG', 'sample',
                             'sample_audvis-cov.fif')
        self.raw_empty_room_path = join(self.data_path, 'MEG', 'sample',
                                        'ernoise_raw.fif')
Exemple #16
0
def _get_bf_data(save_fieldtrip=False):
    raw, epochs, evoked, data_cov, _, _, _, _, _, fwd = _get_data(proj=False)

    if save_fieldtrip is True:
        # raw needs to be saved with all channels and picked in FieldTrip
        raw.save(op.join(ft_data_path, 'raw.fif'), overwrite=True)

        # src (tris are not available in fwd['src'] once imported into MATLAB)
        src = fwd['src'].copy()
        mne.write_source_spaces(op.join(ft_data_path, 'src.fif'), src)

    # pick gradiometers only:
    epochs.pick_types(meg='grad')
    evoked.pick_types(meg='grad')

    # compute covariance matrix
    data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145,
                                      method='empirical')

    if save_fieldtrip is True:
        # if the covariance matrix and epochs need resaving:
        # data covariance:
        cov_savepath = op.join(ft_data_path, 'sample_cov')
        sample_cov = {'sample_cov': data_cov['data']}
        savemat(cov_savepath, sample_cov)
        # evoked data:
        ev_savepath = op.join(ft_data_path, 'sample_evoked')
        data_ev = {'sample_evoked': evoked.data}
        savemat(ev_savepath, data_ev)

    return evoked, data_cov, fwd
Exemple #17
0
def run_strural(subject,
                bem_ico=4,
                spacing='ico5',
                n_jobs=4,
                subjects_dir='/cluster/transcend/MRI/WMA/recons'):
    mne.bem.make_watershed_bem(subject,
                               subjects_dir=subjects_dir,
                               overwrite=True)
    src_fname = op.join(subjects_dir, subject,
                        '%s-pyimpress-src.fif' % spacing)
    if not os.path.isfile(src_fname):

        src = mne.setup_source_space(subject,
                                     spacing=spacing,
                                     subjects_dir=subjects_dir,
                                     overwrite=True,
                                     n_jobs=n_jobs,
                                     add_dist=True)
        mne.write_source_spaces(src_fname, src)
    else:
        src = mne.read_source_spaces(src_fname)

    bem_fname = op.join(subjects_dir, subject,
                        '%s-pyimpress-bem.fif' % bem_ico)

    if not os.path.isfile(bem_fname):
        bem_model = mne.make_bem_model(subject,
                                       ico=bem_ico,
                                       subjects_dir=subjects_dir,
                                       conductivity=(0.3, ))
        bem = mne.make_bem_solution(bem_model)
        mne.write_bem_solution(bem_fname, bem)
    else:
        bem = mne.read_bem_solution(bem_fname)
    return src, bem, src_fname, bem_fname
def _mne_source_space(subject, src_tag, subjects_dir):
    """Load mne source space

    Parameters
    ----------
    subject : str
        Subejct
    src_tag : str
        Spacing (e.g., 'ico-4').
    """
    src_file = os.path.join(subjects_dir, subject, 'bem',
                            '%s-%s-src.fif' % (subject, src_tag))
    src, spacing = src_tag.split('-')
    if os.path.exists(src_file):
        return mne.read_source_spaces(src_file, False)
    elif src == 'ico':
        ss = mne.setup_source_space(subject, spacing=src + spacing,
                                    subjects_dir=subjects_dir, add_dist=True)
    elif src == 'vol':
        mri_file = os.path.join(subjects_dir, subject, 'mri', 'orig.mgz')
        bem_file = os.path.join(subjects_dir, subject, 'bem',
                                'sample-5120-5120-5120-bem-sol.fif')
        ss = mne.setup_volume_source_space(subject, pos=float(spacing),
                                           mri=mri_file, bem=bem_file,
                                           mindist=0., exclude=0.,
                                           subjects_dir=subjects_dir)
    else:
        raise ValueError("src_tag=%s" % repr(src_tag))
    mne.write_source_spaces(src_file, ss)
    return ss
def test_volume_source_space():
    """Test setting up volume source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, 'temp-src.fif')
    surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN)
    surf['rr'] *= 1e3  # convert to mm
    # The one in the testing dataset (uses bem as bounds)
    for bem, surf in zip((fname_bem, None), (None, surf)):
        src_new = setup_volume_source_space('sample',
                                            pos=7.0,
                                            bem=bem,
                                            surface=surf,
                                            mri='T1.mgz',
                                            subjects_dir=subjects_dir)
        write_source_spaces(temp_name, src_new, overwrite=True)
        src[0]['subject_his_id'] = 'sample'  # XXX: to make comparison pass
        _compare_source_spaces(src, src_new, mode='approx')
        del src_new
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')
    assert_raises(
        IOError,
        setup_volume_source_space,
        'sample',
        pos=7.0,
        bem=None,
        surface='foo',  # bad surf
        mri=fname_mri,
        subjects_dir=subjects_dir)
    assert_equal(repr(src), repr(src_new))
    assert_equal(src.kind, 'volume')
def test_source_space_from_label():
    """Test generating a source space from volume label."""
    tempdir = _TempDir()
    aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
    label_names = get_volume_labels_from_aseg(aseg_fname)
    volume_label = label_names[int(np.random.rand() * len(label_names))]

    # Test pos as dict
    pos = dict()
    pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=pos,
                  volume_label=volume_label, mri=aseg_fname)

    # Test no mri provided
    pytest.raises(RuntimeError, setup_volume_source_space, 'sample', mri=None,
                  volume_label=volume_label)

    # Test invalid volume label
    pytest.raises(ValueError, setup_volume_source_space, 'sample',
                  volume_label='Hello World!', mri=aseg_fname)

    src = setup_volume_source_space('sample', subjects_dir=subjects_dir,
                                    volume_label=volume_label, mri=aseg_fname,
                                    add_interpolator=False)
    assert_equal(volume_label, src[0]['seg_name'])

    # test reading and writing
    out_name = op.join(tempdir, 'temp-src.fif')
    write_source_spaces(out_name, src)
    src_from_file = read_source_spaces(out_name)
    _compare_source_spaces(src, src_from_file, mode='approx')
Exemple #21
0
def process_subject_bem(subject, subjects_dir='/cluster/transcend/MRI/WMA/recons', spacing='ico4'):
    try:
        bem_fname = op.join(subjects_dir,subject,'bem', '%s-src.fif' % subject)
        src_fname = op.join(subjects_dir, subject, 'bem', '%s-src.fif' % spacing)
        #headsurf_log = op.join(subjects_dir, subject, 'bem', subject + '_headsurf.log')

        if not os.path.isfile(bem_fname):
            mne.bem.make_watershed_bem(subject=subject, subjects_dir=subjects_dir, overwrite=True, volume='T1', atlas=True,
                                       gcaatlas=False, preflood=None)
            conductivity = (0.3,)
            model = mne.make_bem_model(subject=subject, ico=4,
                                       conductivity=conductivity,
                                       subjects_dir=subjects_dir)
            bem = mne.make_bem_solution(model)
            mne.write_bem_solution(bem_fname, bem=bem)


        if not os.path.isfile(src_fname):
            src = mne.setup_source_space(subject, spacing=spacing,
                                         subjects_dir=subjects_dir,
                                         add_dist=False)
            mne.write_source_spaces(src_fname, src=src, overwrite=True)
    except Exception as ee:
        error = str(ee)
        print(subject, error)
        pass
def create_src_space(sbj_dir, sbj_id, spacing):
    """Create a source space."""
    import os.path as op
    import mne

    bem_dir = op.join(sbj_dir, sbj_id, 'bem')

    # check if source space exists, if not it creates using mne-python fun
    # we have to create the cortical surface source space even when aseg is
    # True
    src_fname = op.join(bem_dir, '%s-%s-src.fif' % (sbj_id, spacing))
    if not op.isfile(src_fname):
        src = mne.setup_source_space(sbj_id,
                                     subjects_dir=sbj_dir,
                                     spacing=spacing.replace('-', ''),
                                     add_dist=False,
                                     n_jobs=2)

        mne.write_source_spaces(src_fname, src, overwrite=True)
        print(('\n*** source space file %s written ***\n' % src_fname))
    else:
        print(('\n*** source space file %s exists!!!\n' % src_fname))
        src = mne.read_source_spaces(src_fname)

    return src
Exemple #23
0
def test_write_source_space():
    """Test writing and reading of source spaces
    """
    src0 = read_source_spaces(fname, add_geom=False)
    src0_old = read_source_spaces(fname, add_geom=False)
    write_source_spaces(op.join(tempdir, 'tmp.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp.fif'), add_geom=False)
    for orig in [src0, src0_old]:
        for s0, s1 in zip(src0, src1):
            for name in [
                    'nuse', 'dist_limit', 'ntri', 'np', 'type', 'id',
                    'subject_his_id'
            ]:
                assert_true(s0[name] == s1[name])
            for name in [
                    'nn', 'rr', 'inuse', 'vertno', 'nuse_tri', 'coord_frame',
                    'use_tris', 'tris', 'nearest', 'nearest_dist'
            ]:
                assert_array_equal(s0[name], s1[name])
            for name in ['dist']:
                if s0[name] is not None:
                    assert_true(s1[name].shape == s0[name].shape)
                    assert_true(len((s0['dist'] - s1['dist']).data) == 0)
            for name in ['pinfo']:
                if s0[name] is not None:
                    assert_true(len(s0[name]) == len(s1[name]))
                    for p1, p2 in zip(s0[name], s1[name]):
                        assert_true(all(p1 == p2))
        # The above "if s0[name] is not None" can be removed once the sample
        # dataset is updated to have a source space with distance info
    for name in ['working_dir', 'command_line']:
        assert_true(src0.info[name] == src1.info[name])
def test_volume_source_space():
    """Test setting up volume source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, 'temp-src.fif')
    surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN)
    surf['rr'] *= 1e3  # convert to mm
    # The one in the testing dataset (uses bem as bounds)
    for bem, surf in zip((fname_bem, None), (None, surf)):
        src_new = setup_volume_source_space(
            'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz',
            subjects_dir=subjects_dir)
        write_source_spaces(temp_name, src_new, overwrite=True)
        src[0]['subject_his_id'] = 'sample'  # XXX: to make comparison pass
        _compare_source_spaces(src, src_new, mode='approx')
        del src_new
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')
    pytest.raises(IOError, setup_volume_source_space, 'sample',
                  pos=7.0, bem=None, surface='foo',  # bad surf
                  mri=fname_mri, subjects_dir=subjects_dir)
    assert repr(src) == repr(src_new)
    assert src.kind == 'volume'
    # Spheres
    sphere = make_sphere_model(r0=(0., 0., 0.), head_radius=0.1,
                               relative_radii=(0.9, 1.0), sigmas=(0.33, 1.0))
    src = setup_volume_source_space(pos=10)
    src_new = setup_volume_source_space(pos=10, sphere=sphere)
    _compare_source_spaces(src, src_new, mode='exact')
    pytest.raises(ValueError, setup_volume_source_space, sphere='foo')
    # Need a radius
    sphere = make_sphere_model(head_radius=None)
    pytest.raises(ValueError, setup_volume_source_space, sphere=sphere)
def test_write_source_space():
    """Test writing and reading of source spaces
    """
    src0 = read_source_spaces(fname, add_geom=False)
    src0_old = read_source_spaces(fname, add_geom=False)
    write_source_spaces(op.join(tempdir, 'tmp.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp.fif'), add_geom=False)
    for orig in [src0, src0_old]:
        for s0, s1 in zip(src0, src1):
            for name in ['nuse', 'dist_limit', 'ntri', 'np', 'type', 'id',
                         'subject_his_id']:
                assert_true(s0[name] == s1[name])
            for name in ['nn', 'rr', 'inuse', 'vertno', 'nuse_tri',
                         'coord_frame', 'use_tris', 'tris', 'nearest',
                         'nearest_dist']:
                assert_array_equal(s0[name], s1[name])
            for name in ['dist']:
                if s0[name] is not None:
                    assert_true(s1[name].shape == s0[name].shape)
                    assert_true(len((s0['dist'] - s1['dist']).data) == 0)
            for name in ['pinfo']:
                if s0[name] is not None:
                    assert_true(len(s0[name]) == len(s1[name]))
                    for p1, p2 in zip(s0[name], s1[name]):
                        assert_true(all(p1 == p2))
        # The above "if s0[name] is not None" can be removed once the sample
        # dataset is updated to have a source space with distance info
    for name in ['working_dir', 'command_line']:
        assert_true(src0.info[name] == src1.info[name])
def create_source_space(subject, fsMRI_dir):
    print('Subject ' + subject + ': create_source_space ======================')

    meg_subject_dir = op.join(config.meg_dir, subject)

    # Create source space
    src = mne.setup_source_space(subject, spacing=config.spacing, subjects_dir=fsMRI_dir)
    mne.write_source_spaces(op.join(meg_subject_dir, subject + '-oct6-src.fif'), src, overwrite=True)
def test_volume_source_space(tmpdir):
    """Test setting up volume source spaces."""
    src = read_source_spaces(fname_vol)
    temp_name = tmpdir.join('temp-src.fif')
    surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN)
    surf['rr'] *= 1e3  # convert to mm
    bem_sol = read_bem_solution(fname_bem_3_sol)
    bem = read_bem_solution(fname_bem_sol)
    # The one in the testing dataset (uses bem as bounds)
    for this_bem, this_surf in zip(
        (bem, fname_bem, fname_bem_3, bem_sol, fname_bem_3_sol, None),
        (None, None, None, None, None, surf)):
        src_new = setup_volume_source_space('sample',
                                            pos=7.0,
                                            bem=this_bem,
                                            surface=this_surf,
                                            subjects_dir=subjects_dir)
        write_source_spaces(temp_name, src_new, overwrite=True)
        src[0]['subject_his_id'] = 'sample'  # XXX: to make comparison pass
        _compare_source_spaces(src, src_new, mode='approx')
        del src_new
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')
    with pytest.raises(IOError, match='surface file.*not found'):
        setup_volume_source_space('sample',
                                  surface='foo',
                                  mri=fname_mri,
                                  subjects_dir=subjects_dir)
    bem['surfs'][-1]['coord_frame'] = FIFF.FIFFV_COORD_HEAD
    with pytest.raises(ValueError, match='BEM is not in MRI coord.* got head'):
        setup_volume_source_space('sample',
                                  bem=bem,
                                  mri=fname_mri,
                                  subjects_dir=subjects_dir)
    bem['surfs'] = bem['surfs'][:-1]  # no inner skull surf
    with pytest.raises(ValueError, match='Could not get inner skul.*from BEM'):
        setup_volume_source_space('sample',
                                  bem=bem,
                                  mri=fname_mri,
                                  subjects_dir=subjects_dir)
    del bem
    assert repr(src) == repr(src_new)
    assert ' MB' in repr(src)
    assert src.kind == 'volume'
    # Spheres
    sphere = make_sphere_model(r0=(0., 0., 0.),
                               head_radius=0.1,
                               relative_radii=(0.9, 1.0),
                               sigmas=(0.33, 1.0))
    src = setup_volume_source_space(pos=10, sphere=(0., 0., 0., 0.09))
    src_new = setup_volume_source_space(pos=10, sphere=sphere)
    _compare_source_spaces(src, src_new, mode='exact')
    with pytest.raises(ValueError, match='sphere, if str'):
        setup_volume_source_space(sphere='foo')
    # Need a radius
    sphere = make_sphere_model(head_radius=None)
    with pytest.raises(ValueError, match='be spherical with multiple layers'):
        setup_volume_source_space(sphere=sphere)
Exemple #28
0
def createSrc(subj):
    camcan_root = os.environ['CAMCAN_ROOT']
    ico4_fname = camcan_root + 'processed/cc700/mri/pipeline/release004/BIDSsep/megraw/' + subj + '/meg/' + subj + '-ico4-src.fif'
    try:
        src = mne.read_source_spaces(ico4_fname)
    except IOError:
        src = mne.setup_source_space(subj, spacing='ico4')
        mne.write_source_spaces(ico4_fname, src)

    return src
def test_setup_source_space():
    """Test setting up ico, oct, and all source spaces."""
    tempdir = _TempDir()
    fname_ico = op.join(data_path, 'subjects', 'fsaverage', 'bem',
                        'fsaverage-ico-5-src.fif')
    # first lets test some input params
    assert_raises(ValueError, setup_source_space, 'sample', spacing='oct',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='octo',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='oct6e',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='7emm',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='alls',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(IOError, setup_source_space, 'sample', spacing='oct6',
                  subjects_dir=subjects_dir, add_dist=False)

    # ico 5 (fsaverage) - write to temp file
    src = read_source_spaces(fname_ico)
    temp_name = op.join(tempdir, 'temp-src.fif')
    with warnings.catch_warnings(record=True):  # sklearn equiv neighbors
        warnings.simplefilter('always')
        src_new = setup_source_space('fsaverage', temp_name, spacing='ico5',
                                     subjects_dir=subjects_dir, add_dist=False,
                                     overwrite=True)
    _compare_source_spaces(src, src_new, mode='approx')
    assert_equal(repr(src), repr(src_new))
    assert_equal(repr(src).count('surface ('), 2)
    assert_array_equal(src[0]['vertno'], np.arange(10242))
    assert_array_equal(src[1]['vertno'], np.arange(10242))

    # oct-6 (sample) - auto filename + IO
    src = read_source_spaces(fname)
    temp_name = op.join(tempdir, 'temp-src.fif')
    with warnings.catch_warnings(record=True):  # sklearn equiv neighbors
        warnings.simplefilter('always')
        src_new = setup_source_space('sample', None, spacing='oct6',
                                     subjects_dir=subjects_dir,
                                     overwrite=True, add_dist=False)
        write_source_spaces(temp_name, src_new, overwrite=True)
    _compare_source_spaces(src, src_new, mode='approx', nearest=False)
    src_new = read_source_spaces(temp_name)
    _compare_source_spaces(src, src_new, mode='approx', nearest=False)

    # all source points - no file writing
    src_new = setup_source_space('sample', None, spacing='all',
                                 subjects_dir=subjects_dir, add_dist=False)
    assert_true(src_new[0]['nuse'] == len(src_new[0]['rr']))
    assert_true(src_new[1]['nuse'] == len(src_new[1]['rr']))

    # dense source space to hit surf['inuse'] lines of _create_surf_spacing
    assert_raises(RuntimeError, setup_source_space, 'sample', None,
                  spacing='ico6', subjects_dir=subjects_dir, add_dist=False)
def make_forward_solution(experiment,
                          subject,
                          spacing,
                          process_slug=DEFAULT_PROC):
    struct = sub_to_struct[experiment][subject]
    if struct == 'NA':
        raise IOError(
            'Freesurfer Reconstruction has not yet been done for this subject. See the Freesurfer Recommended Reconstruction page.')

    trans_fname = TRANS_FNAME.format(experiment=experiment, subject=subject, struct=struct)

    if not os.path.isfile(trans_fname):
        raise IOError(
            'Coregistration has not yet been done for this subject. Use mne_analyze on big-brain and follow MNE handbook chapter 7.')

    trans = mne.read_trans(trans_fname)

    fwd_path = FWD_PATH.format(experiment=experiment, subject=subject)
    if not os.path.exists(fwd_path):
        try:
            os.mkdir(fwd_path)
        except:
            os.mkdir(FWD_PATH.format(experiment=experiment, subject=''))
            os.mkdir(fwd_path)

    fwd_fname = FWD_FNAME.format(fwd_path=fwd_path, subject=subject, experiment=experiment, process_slug=process_slug,
                                 struct=struct, spacing=spacing)

    raw = mne.io.Raw(PROC_FNAME.format(experiment=experiment, subject=subject, process_slug=process_slug))

    bem_path = [fn for fn in os.listdir(BEM_PATH.format(struct=struct)) if fnmatch.fnmatch(fn, '*-bem-sol.fif')]

    if len(bem_path) == 0:
        raise IOError('BEM has not yet been done for this subject. See MNE_pipeline_2018.sh')

    bem_fname = pjoin(BEM_PATH.format(struct=struct), bem_path[0])

    src_file = SRC_FNAME.format(struct=struct, spacing=spacing)

    mne.set_config('SUBJECTS_DIR', SUBJ_DIR)

    # Not sure how to make sure this runs effectively
    if os.path.isfile(src_file):
        src = mne.read_source_spaces(src_file)
    else:
        src = mne.setup_source_space(struct, spacing='oct6')
        mne.write_source_spaces(src_file, src)

    fwd = mne.make_forward_solution(raw.info, trans,
                                    src=src,
                                    bem=bem_fname)

    mne.write_forward_solution(fwd_fname, fwd)

    return fwd
Exemple #31
0
def _get_bem_src_trans(p, info, subj, struc):
    subjects_dir = get_subjects_dir(p.subjects_dir, raise_error=True)
    assert isinstance(subjects_dir, str)
    if struc is None:  # spherical case
        bem, src, trans = _spherical_conductor(info, subj, p.src_pos)
        bem_type = 'spherical-model'
    else:
        from mne.transforms import _ensure_trans
        trans = op.join(p.work_dir, subj, p.trans_dir, subj + '-trans.fif')
        if not op.isfile(trans):
            old = trans
            trans = op.join(p.work_dir, subj, p.trans_dir,
                            subj + '-trans_head2mri.txt')
            if not op.isfile(trans):
                raise IOError('Unable to find head<->MRI trans files in:\n'
                              '%s\n%s' % (old, trans))
        trans = read_trans(trans)
        trans = _ensure_trans(trans, 'mri', 'head')
        this_src = _handle_dict(p.src, subj)
        assert isinstance(this_src, str)
        if this_src.startswith('oct'):
            kind = 'oct'
        elif this_src.startswith('vol'):
            kind = 'vol'
        else:
            raise RuntimeError('Unknown source space type %s, must be '
                               'oct or vol' % (this_src, ))
        num = int(this_src.split(kind)[-1].split('-')[-1])
        bem = op.join(subjects_dir, struc, 'bem',
                      '%s-%s-bem-sol.fif' % (struc, p.bem_type))
        for mid in ('', '-'):
            src_space_file = op.join(
                subjects_dir, struc, 'bem',
                '%s-%s%s%s-src.fif' % (struc, kind, mid, num))
            if op.isfile(src_space_file):
                break
        else:  # if neither exists, use last filename
            print('    Creating %s%s source space for %s...' %
                  (kind, num, subj))
            if kind == 'oct':
                src = setup_source_space(struc,
                                         spacing='%s%s' % (kind, num),
                                         subjects_dir=p.subjects_dir,
                                         n_jobs=p.n_jobs)
            else:
                assert kind == 'vol'
                src = setup_volume_source_space(struc,
                                                pos=num,
                                                bem=bem,
                                                subjects_dir=p.subjects_dir)
            write_source_spaces(src_space_file, src)
        src = read_source_spaces(src_space_file)
        bem = read_bem_solution(bem, verbose=False)
        bem_type = ('%s-layer BEM' % len(bem['surfs']))
    return bem, src, trans, bem_type
def test_setup_source_space(tmpdir):
    """Test setting up ico, oct, and all source spaces."""
    fname_ico = op.join(data_path, 'subjects', 'fsaverage', 'bem',
                        'fsaverage-ico-5-src.fif')
    # first lets test some input params
    for spacing in ('oct', 'oct6e'):
        with pytest.raises(ValueError, match='subdivision must be an integer'):
            setup_source_space('sample', spacing=spacing,
                               add_dist=False, subjects_dir=subjects_dir)
    for spacing in ('oct0', 'oct-4'):
        with pytest.raises(ValueError, match='oct subdivision must be >= 1'):
            setup_source_space('sample', spacing=spacing,
                               add_dist=False, subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='ico subdivision must be >= 0'):
        setup_source_space('sample', spacing='ico-4',
                           add_dist=False, subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='must be a string with values'):
        setup_source_space('sample', spacing='7emm',
                           add_dist=False, subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='must be a string with values'):
        setup_source_space('sample', spacing='alls',
                           add_dist=False, subjects_dir=subjects_dir)

    # ico 5 (fsaverage) - write to temp file
    src = read_source_spaces(fname_ico)
    with pytest.warns(None):  # sklearn equiv neighbors
        src_new = setup_source_space('fsaverage', spacing='ico5',
                                     subjects_dir=subjects_dir, add_dist=False)
    _compare_source_spaces(src, src_new, mode='approx')
    assert_equal(repr(src), repr(src_new))
    assert_equal(repr(src).count('surface ('), 2)
    assert_array_equal(src[0]['vertno'], np.arange(10242))
    assert_array_equal(src[1]['vertno'], np.arange(10242))

    # oct-6 (sample) - auto filename + IO
    src = read_source_spaces(fname)
    temp_name = tmpdir.join('temp-src.fif')
    with pytest.warns(None):  # sklearn equiv neighbors
        src_new = setup_source_space('sample', spacing='oct6',
                                     subjects_dir=subjects_dir, add_dist=False)
        write_source_spaces(temp_name, src_new, overwrite=True)
    assert_equal(src_new[0]['nuse'], 4098)
    _compare_source_spaces(src, src_new, mode='approx', nearest=False)
    src_new = read_source_spaces(temp_name)
    _compare_source_spaces(src, src_new, mode='approx', nearest=False)

    # all source points - no file writing
    src_new = setup_source_space('sample', spacing='all',
                                 subjects_dir=subjects_dir, add_dist=False)
    assert src_new[0]['nuse'] == len(src_new[0]['rr'])
    assert src_new[1]['nuse'] == len(src_new[1]['rr'])

    # dense source space to hit surf['inuse'] lines of _create_surf_spacing
    pytest.raises(RuntimeError, setup_source_space, 'sample',
                  spacing='ico6', subjects_dir=subjects_dir, add_dist=False)
Exemple #33
0
def test_setup_source_space():
    """Test setting up ico, oct, and all source spaces."""
    tempdir = _TempDir()
    fname_ico = op.join(data_path, 'subjects', 'fsaverage', 'bem',
                        'fsaverage-ico-5-src.fif')
    # first lets test some input params
    assert_raises(ValueError, setup_source_space, 'sample', spacing='oct',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='octo',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='oct6e',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='7emm',
                  add_dist=False, subjects_dir=subjects_dir)
    assert_raises(ValueError, setup_source_space, 'sample', spacing='alls',
                  add_dist=False, subjects_dir=subjects_dir)

    # ico 5 (fsaverage) - write to temp file
    src = read_source_spaces(fname_ico)
    with warnings.catch_warnings(record=True):  # sklearn equiv neighbors
        warnings.simplefilter('always')
        src_new = setup_source_space('fsaverage', spacing='ico5',
                                     subjects_dir=subjects_dir, add_dist=False)
    _compare_source_spaces(src, src_new, mode='approx')
    assert_equal(repr(src), repr(src_new))
    assert_equal(repr(src).count('surface ('), 2)
    assert_array_equal(src[0]['vertno'], np.arange(10242))
    assert_array_equal(src[1]['vertno'], np.arange(10242))

    # oct-6 (sample) - auto filename + IO
    src = read_source_spaces(fname)
    temp_name = op.join(tempdir, 'temp-src.fif')
    with warnings.catch_warnings(record=True):  # sklearn equiv neighbors
        warnings.simplefilter('always')
        src_new = setup_source_space('sample', spacing='oct6',
                                     subjects_dir=subjects_dir, add_dist=False)
        write_source_spaces(temp_name, src_new, overwrite=True)
    assert_equal(src_new[0]['nuse'], 4098)
    _compare_source_spaces(src, src_new, mode='approx', nearest=False)
    src_new = read_source_spaces(temp_name)
    _compare_source_spaces(src, src_new, mode='approx', nearest=False)

    # all source points - no file writing
    src_new = setup_source_space('sample', spacing='all',
                                 subjects_dir=subjects_dir, add_dist=False)
    assert_true(src_new[0]['nuse'] == len(src_new[0]['rr']))
    assert_true(src_new[1]['nuse'] == len(src_new[1]['rr']))

    # dense source space to hit surf['inuse'] lines of _create_surf_spacing
    assert_raises(RuntimeError, setup_source_space, 'sample',
                  spacing='ico6', subjects_dir=subjects_dir, add_dist=False)
Exemple #34
0
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces
    """
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess([
            'mne_volume_source_space', '--meters', '--pos', temp_pos, '--src',
            temp_name
        ])
        src_c = read_source_spaces(temp_name)
        pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v])
        src_new = setup_volume_source_space('sample',
                                            None,
                                            pos=pos_dict,
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v],
                        src_new[0]['rr'],
                        rtol=1e-3,
                        atol=1e-6)
        assert_allclose(src[0]['nn'][v],
                        src_new[0]['nn'],
                        rtol=1e-3,
                        atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c)
        src_c2 = read_source_spaces(temp_name)
        _compare_source_spaces(src_c, src_c2)

        # now do MRI
        assert_raises(ValueError,
                      setup_volume_source_space,
                      'sample',
                      pos=pos_dict,
                      mri=fname_mri)
        assert_equal(repr(src_new), repr(src_c))
        assert_equal(src_new.kind, 'discrete')
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
def test_write_source_space(tmpdir):
    """Test reading and writing of source spaces."""
    src0 = read_source_spaces(fname, patch_stats=False)
    temp_fname = tmpdir.join('tmp-src.fif')
    write_source_spaces(temp_fname, src0)
    src1 = read_source_spaces(temp_fname, patch_stats=False)
    _compare_source_spaces(src0, src1)

    # test warnings on bad filenames
    src_badname = tmpdir.join('test-bad-name.fif.gz')
    with pytest.warns(RuntimeWarning, match='-src.fif'):
        write_source_spaces(src_badname, src0)
    with pytest.warns(RuntimeWarning, match='-src.fif'):
        read_source_spaces(src_badname)
def _create_mixed_source_space(subjects_dir, sbj_id, spacing, labels, src,
                               save_mixed_src_space):
    """Create a miwed source space."""

    bem_dir = op.join(subjects_dir, sbj_id, 'bem')

    src_aseg_fname = op.join(bem_dir, '%s-%s-aseg-src.fif' % (sbj_id, spacing))
    if not op.isfile(src_aseg_fname):

        aseg_fname = op.join(subjects_dir, sbj_id, 'mri/aseg.mgz')

        if spacing == 'oct-6':
            pos = 5.0
        elif spacing == 'oct-5':
            pos = 7.0
        elif spacing == 'ico-5':
            pos = 3.0

        model_fname = op.join(bem_dir, '%s-5120-bem.fif' % sbj_id)
        for l in labels:
            print(l)
            vol_label = mne.setup_volume_source_space(
                sbj_id,
                mri=aseg_fname,
                pos=pos,
                bem=model_fname,
                volume_label=l,
                subjects_dir=subjects_dir)  # noqa
            src += vol_label

        if save_mixed_src_space:
            mne.write_source_spaces(src_aseg_fname, src, overwrite=True)
            print("\n*** source space file {} written "
                  "***\n".format(src_aseg_fname))

        # Export source positions to nift file
        nii_fname = op.join(bem_dir, '%s-%s-aseg-src.nii' % (sbj_id, spacing))

        # Combine the source spaces
        src.export_volume(nii_fname, mri_resolution=True)
    else:
        print("\n*** source space file {} "
              "exists!!!\n".format(src_aseg_fname))
        src = mne.read_source_spaces(src_aseg_fname)
        print(('src contains {} src spaces'.format(len(src))))
        for s in src[2:]:
            print(('sub structure {} \n'.format(s['seg_name'])))

    return src
def test_source_space_from_label(tmpdir, pass_ids):
    """Test generating a source space from volume label."""
    aseg_short = 'aseg.mgz'
    atlas_ids, _ = read_freesurfer_lut()
    volume_label = 'Left-Cerebellum-Cortex'

    # Test pos as dict
    pos = dict()
    with pytest.raises(ValueError, match='mri must be None if pos is a dict'):
        setup_volume_source_space('sample',
                                  pos=pos,
                                  volume_label=volume_label,
                                  mri=aseg_short,
                                  subjects_dir=subjects_dir)

    # Test T1.mgz provided
    with pytest.raises(RuntimeError, match=r'Must use a \*aseg.mgz file'):
        setup_volume_source_space('sample',
                                  mri='T1.mgz',
                                  volume_label=volume_label,
                                  subjects_dir=subjects_dir)

    # Test invalid volume label
    mri = aseg_short
    with pytest.raises(ValueError, match="'Left-Cerebral' not found.*Did you"):
        setup_volume_source_space('sample',
                                  volume_label='Left-Cerebral',
                                  mri=mri,
                                  subjects_dir=subjects_dir)

    # These should be equivalent
    if pass_ids:
        use_volume_label = {volume_label: atlas_ids[volume_label]}
    else:
        use_volume_label = volume_label

    # ensure it works even when not provided (detect that it should be aseg)
    src = setup_volume_source_space('sample',
                                    volume_label=use_volume_label,
                                    add_interpolator=False,
                                    subjects_dir=subjects_dir)
    assert_equal(volume_label, src[0]['seg_name'])
    assert src[0]['nuse'] == 404  # for our given pos and label

    # test reading and writing
    out_name = tmpdir.join('temp-src.fif')
    write_source_spaces(out_name, src)
    src_from_file = read_source_spaces(out_name)
    _compare_source_spaces(src, src_from_file, mode='approx')
def test_write_source_space():
    """Test reading and writing of source spaces."""
    tempdir = _TempDir()
    src0 = read_source_spaces(fname, patch_stats=False)
    write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'),
                              patch_stats=False)
    _compare_source_spaces(src0, src1)

    # test warnings on bad filenames
    src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
    with pytest.warns(RuntimeWarning, match='-src.fif'):
        write_source_spaces(src_badname, src0)
    with pytest.warns(RuntimeWarning, match='-src.fif'):
        read_source_spaces(src_badname)
Exemple #39
0
def process_subject_bem(subject, spacing='ico5'):
    mne.bem.make_watershed_bem(subject=subject, subjects_dir=subjects_dir, overwrite=True, volume='T1', atlas=True,
                       gcaatlas=False, preflood=None)
    conductivity = (0.3,)
    model = mne.make_bem_model(subject=subject, ico=4,
                               conductivity=conductivity,
                               subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    src = mne.setup_source_space(subject, spacing=spacing,
                                 subjects_dir=subjects_dir,
                                 add_dist=False)
    bem_fname = op.join(subjects_dir,subject,'bem', '%s-src.fif' % subject)
    src_fname = op.join(subjects_dir, subject, 'bem', '%s-src.fif' % spacing)
    mne.write_bem_solution(bem_fname, bem=bem)
    mne.write_source_spaces(src_fname, src=src)
def test_write_source_space():
    """Test reading and writing of source spaces."""
    tempdir = _TempDir()
    src0 = read_source_spaces(fname, patch_stats=False)
    write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'),
                              patch_stats=False)
    _compare_source_spaces(src0, src1)

    # test warnings on bad filenames
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
        write_source_spaces(src_badname, src0)
        read_source_spaces(src_badname)
    assert_naming(w, 'test_source_space.py', 2)
Exemple #41
0
def test_write_source_space():
    """Test reading and writing of source spaces."""
    tempdir = _TempDir()
    src0 = read_source_spaces(fname, patch_stats=False)
    write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'),
                              patch_stats=False)
    _compare_source_spaces(src0, src1)

    # test warnings on bad filenames
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
        write_source_spaces(src_badname, src0)
        read_source_spaces(src_badname)
    assert_naming(w, 'test_source_space.py', 2)
def test_write_source_space():
    """Test writing and reading of source spaces
    """
    tempdir = _TempDir()
    src0 = read_source_spaces(fname, add_geom=False)
    write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), add_geom=False)
    _compare_source_spaces(src0, src1)

    # test warnings on bad filenames
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
        write_source_spaces(src_badname, src0)
        read_source_spaces(src_badname)
    assert_equal(len(w), 2)
def test_write_source_space():
    """Test writing and reading of source spaces
    """
    src0 = read_source_spaces(fname, add_geom=False)
    write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
    src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), add_geom=False)
    _compare_source_spaces(src0, src1)

    # test warnings on bad filenames
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
        write_source_spaces(src_badname, src0)
        read_source_spaces(src_badname)
        print([ww.message for ww in w])
    assert_equal(len(w), 2)
Exemple #44
0
 def _make_vol_source_space(self):
     srcfilename = opj(self.fsrc, self.subject + "-vol-src.fif")
     if not os.path.isfile(srcfilename):
         try:
             src_vol = mne.setup_volume_source_space(
                 self.subject,
                 pos=3.0,
                 subjects_dir=self.subjects_dir,
                 verbose=True)
             mne.write_source_spaces(srcfilename,
                                     src_vol,
                                     overwrite=True,
                                     verbose=True)
         except Exception as e:
             print(
                 f"Failed to setup volume source space for {self.subject} --> {e}"
             )
def test_add_source_space_distances():
    """Test adding distances to source space."""
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    src_new = read_source_spaces(fname)
    del src_new[0]['dist']
    del src_new[1]['dist']
    n_do = 19  # limit this for speed
    src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy()
    src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy()
    out_name = op.join(tempdir, 'temp-src.fif')
    n_jobs = 2
    assert n_do % n_jobs != 0
    add_source_space_distances(src_new, n_jobs=n_jobs)
    write_source_spaces(out_name, src_new)
    src_new = read_source_spaces(out_name)

    # iterate over both hemispheres
    for so, sn in zip(src, src_new):
        v = so['vertno'][:n_do]
        assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32))
        assert_array_equal(sn['dist_limit'], np.array([np.inf], np.float32))
        do = so['dist']
        dn = sn['dist']

        # clean out distances > 0.007 in C code (some residual), and Python
        ds = list()
        for d in [do, dn]:
            d.data[d.data > 0.007] = 0
            d = d[v][:, v]
            d.eliminate_zeros()
            ds.append(d)

        # make sure we actually calculated some comparable distances
        assert np.sum(ds[0].data < 0.007) > 10

        # do comparison
        d = ds[0] - ds[1]
        assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-9)
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(['mne_volume_source_space', '--meters',
                        '--pos', temp_pos, '--src', temp_name])
        src_c = read_source_spaces(temp_name)
        pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v])
        src_new = setup_volume_source_space(pos=pos_dict)
        assert src_new.kind == 'discrete'
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
                        rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
                        rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c, overwrite=True)
        src_c2 = read_source_spaces(temp_name)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
    _compare_source_spaces(src_c, src_c2)

    # now do MRI
    pytest.raises(ValueError, setup_volume_source_space, 'sample',
                  pos=pos_dict, mri=fname_mri)
    assert repr(src_new) == repr(src_c)
    assert src_new.kind == 'discrete'
    assert _get_src_type(src_new, None) == 'discrete'
def test_volume_source_space():
    """Test setting up volume source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, 'temp-src.fif')
    surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN)
    surf['rr'] *= 1e3  # convert to mm
    # The one in the testing dataset (uses bem as bounds)
    for bem, surf in zip((fname_bem, None), (None, surf)):
        src_new = setup_volume_source_space(
            'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz',
            subjects_dir=subjects_dir)
        write_source_spaces(temp_name, src_new, overwrite=True)
        src[0]['subject_his_id'] = 'sample'  # XXX: to make comparison pass
        _compare_source_spaces(src, src_new, mode='approx')
        del src_new
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')
    assert_raises(IOError, setup_volume_source_space, 'sample',
                  pos=7.0, bem=None, surface='foo',  # bad surf
                  mri=fname_mri, subjects_dir=subjects_dir)
    assert_equal(repr(src), repr(src_new))
    assert_equal(src.kind, 'volume')
# Setup a volume source space
# set pos=7.0 for speed issue
vol_src = setup_volume_source_space(subject, mri=fname_aseg,
                                    pos=7.0,
                                    bem=fname_model,
                                    volume_label=labels_vol,
                                    subjects_dir=subjects_dir)
# Generate the mixed source space
src += vol_src

n = sum(src[i]['nuse'] for i in range(len(src)))
print('the src space contains %d spaces and %d points' % (len(src), n))

# Write the mixed source space
write_source_spaces(fname_mixed_src, src)

# Export source positions to nift file
nii_fname = op.join(bem_dir, '%s-mixed-src.nii' % subject)
src.export_volume(nii_fname, mri_resolution=True)

plotting.plot_img(nii_fname, cmap=plt.cm.spectral)
plt.show()

# Compute the fwd matrix
fwd = make_forward_solution(fname_evoked, fname_trans, src, fname_bem,
                            mindist=5.0,  # ignore sources<=5mm from innerskull
                            meg=True, eeg=False,
                            n_jobs=1,
                            overwrite=True)
maps = mne.make_field_map(evoked[0], trans_fname, subject='spm',
                          subjects_dir=subjects_dir, n_jobs=1)

evoked[0].plot_field(maps, time=0.170)


###############################################################################
# Compute forward model

# Make source space
src_fname = data_path + '/subjects/spm/bem/spm-oct-6-src.fif'
if not op.isfile(src_fname):
    src = mne.setup_source_space('spm', spacing='oct6',
                                 subjects_dir=subjects_dir)
    mne.write_source_spaces(src_fname, src)
else:
    src = mne.read_source_spaces(src_fname)

bem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif'
forward = mne.make_forward_solution(contrast.info, trans_fname, src, bem)
forward = mne.convert_forward_solution(forward, surf_ori=True)

###############################################################################
# Compute inverse solution

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = 'dSPM'

inverse_operator = make_inverse_operator(contrast.info, forward, noise_cov,
Exemple #50
0
from __future__ import print_function
import mne
import subprocess
import sys
import os

from my_settings import * 

subject = sys.argv[1]

# make source space
src = mne.setup_source_space(subject, spacing='oct6',
                             subjects_dir=subjects_dir,
                             add_dist=False, overwrite=True)
# save source space
mne.write_source_spaces(mne_folder + "%s-oct-6-src.fif" % subject, src)
                  src_fs, subjects_dir=subjects_dir)
    src_fs[0]['subject_his_id'] = 'fsaverage'  # name mismatch
    pytest.raises(ValueError, stc_morph.to_original_src,
                  src_fs, subject_orig='foo', subjects_dir=subjects_dir)
    src_fs[0]['subject_his_id'] = 'sample'
    src = read_source_spaces(fname)  # wrong source space
    pytest.raises(RuntimeError, stc_morph.to_original_src,
                  src, subjects_dir=subjects_dir)


run_tests_if_main()

# The following code was used to generate small-src.fif.gz.
# Unfortunately the C code bombs when trying to add source space distances,
# possibly due to incomplete "faking" of a smaller surface on our part here.
"""
# -*- coding: utf-8 -*-

import os
import numpy as np
import mne

data_path = mne.datasets.sample.data_path()
src = mne.setup_source_space('sample', fname=None, spacing='oct5')
hemis = ['lh', 'rh']
fnames = [data_path + '/subjects/sample/surf/%s.decimated' % h for h in hemis]

vs = list()
for s, fname in zip(src, fnames):
    coords = s['rr'][s['vertno']]
    vs.append(s['vertno'])
os.chdir(raw_dir)

subs = ['NLR_102_RS','NLR_103_AC','NLR_105_BB','NLR_110_HH','NLR_127_AM',
        'NLR_130_RW','NLR_132_WP','NLR_133_ML','NLR_145_AC','NLR_150_MG','NLR_151_RD',
        'NLR_152_TC','NLR_160_EK','NLR_161_AK','NLR_162_EF','NLR_163_LF','NLR_164_SF',
        'NLR_170_GM','NLR_172_TH','NLR_174_HS','NLR_179_GM','NLR_180_ZD','NLR_187_NB',
        'NLR_201_GS','NLR_202_DD','NLR_203_AM','NLR_204_AM','NLR_205_AC','NLR_206_LM',
        'NLR_207_AH','NLR_210_SB','NLR_211_LB'
        ]
subs = ['NLR_GB310','NLR_KB218','NLR_JB423','NLR_GB267','NLR_JB420','NLR_HB275','NLR_197_BK','NLR_GB355','NLR_GB387']
subs = ['NLR_HB205','NLR_IB319','NLR_JB227','NLR_JB486','NLR_KB396']
subs = ['NLR_JB227','NLR_JB486','NLR_KB396']
for n, s in enumerate(subs):    
    subject = s
                       
    # Create source space
    os.chdir(os.path.join(fs_dir,subject,'bem'))
    """ NLR_205: Head is too small to create ico5 """
    if s == 'NLR_205_AC' or s == 'NLR_JB227':
        spacing='oct6' # ico5 = 10242, oct6 = 4098 ...8196 = 4098 * 2
        fn2 = subject + '-' + 'oct-6' + '-src.fif'
    else:
        spacing='ico5' # 10242 * 2
        fn2 = subject + '-' + 'ico-5' + '-src.fif'

    src = mne.setup_source_space(subject=subject, spacing=spacing, # source spacing = 5 mm
                                 subjects_dir=fs_dir, add_dist=False, n_jobs=18, overwrite=True)
    src = mne.add_source_space_distances(src, dist_limit=np.inf, n_jobs=18, verbose=None)
    mne.write_source_spaces(fn2, src, overwrite=True)