Esempio n. 1
0
def test_io_bem(tmpdir, ext):
    """Test reading and writing of bem surfaces and solutions."""
    import h5py
    temp_bem = op.join(str(tmpdir), f'temp-bem.{ext}')
    # model
    with pytest.raises(ValueError, match='BEM data not found'):
        read_bem_surfaces(fname_raw)
    with pytest.raises(ValueError, match='surface with id 10'):
        read_bem_surfaces(fname_bem_3, s_id=10)
    surf = read_bem_surfaces(fname_bem_3, patch_stats=True)
    surf = read_bem_surfaces(fname_bem_3, patch_stats=False)
    write_bem_surfaces(temp_bem, surf[0])
    with pytest.raises(IOError, match='exists'):
        write_bem_surfaces(temp_bem, surf[0])
    write_bem_surfaces(temp_bem, surf[0], overwrite=True)
    if ext == 'h5':
        with h5py.File(temp_bem, 'r'):  # make sure it's valid
            pass
    surf_read = read_bem_surfaces(temp_bem, patch_stats=False)
    _compare_bem_surfaces(surf, surf_read)

    # solution
    with pytest.raises(RuntimeError, match='No BEM solution found'):
        read_bem_solution(fname_bem_3)
    temp_sol = op.join(str(tmpdir), f'temp-sol.{ext}')
    sol = read_bem_solution(fname_bem_sol_3)
    assert 'BEM' in repr(sol)
    write_bem_solution(temp_sol, sol)
    sol_read = read_bem_solution(temp_sol)
    _compare_bem_solutions(sol, sol_read)
    sol = read_bem_solution(fname_bem_sol_1)
    with pytest.raises(RuntimeError, match='BEM does not have.*triangulation'):
        _bem_find_surface(sol, 3)
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)
Esempio n. 3
0
def test_setup_forward_model(tmp_path):
    """Test mne setup_forward_model."""
    check_usage(mne_setup_forward_model, force_help=True)
    # Using the sample dataset
    use_fname = op.join(tmp_path, "model-bem.fif")
    # Test  command
    with ArgvSetter(('--model', use_fname, '-d', subjects_dir, '--homog', '-s',
                     'sample', '--ico', '3', '--verbose')):
        mne_setup_forward_model.run()
    model = read_bem_surfaces(use_fname)
    assert len(model) == 1
    sol_fname = op.splitext(use_fname)[0] + '-sol.fif'
    read_bem_solution(sol_fname)
Esempio n. 4
0
def test_simulate_round_trip():
    """Test simulate_raw round trip calculations."""
    # Check a diagonal round-trip
    raw, src, stc, trans, sphere = _get_data()
    raw.pick_types(meg=True, stim=True)
    bem = read_bem_solution(bem_1_fname)
    old_bem = bem.copy()
    old_src = src.copy()
    old_trans = trans.copy()
    fwd = make_forward_solution(raw.info, trans, src, bem)
    # no omissions
    assert (sum(len(s['vertno']) for s in src) ==
            sum(len(s['vertno']) for s in fwd['src']) ==
            36)
    # make sure things were not modified
    assert (old_bem['surfs'][0]['coord_frame'] ==
            bem['surfs'][0]['coord_frame'])
    assert trans == old_trans
    _compare_source_spaces(src, old_src)
    data = np.eye(fwd['nsource'])
    raw.crop(0, (len(data) - 1) / raw.info['sfreq'])
    stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']],
                         0, 1. / raw.info['sfreq'])
    for use_cps in (False, True):
        this_raw = simulate_raw(raw, stc, trans, src, bem, cov=None,
                                use_cps=use_cps)
        this_raw.pick_types(meg=True, eeg=True)
        assert (old_bem['surfs'][0]['coord_frame'] ==
                bem['surfs'][0]['coord_frame'])
        assert trans == old_trans
        _compare_source_spaces(src, old_src)
        this_fwd = convert_forward_solution(fwd, force_fixed=True,
                                            use_cps=use_cps)
        assert_allclose(this_raw[:][0], this_fwd['sol']['data'],
                        atol=1e-12, rtol=1e-6)
def compute_fwd(subject,
                src_ref,
                info,
                trans_fname,
                bem_fname,
                meg=True,
                eeg=True,
                mindist=3,
                subjects_dir=None,
                n_jobs=1,
                verbose=None):
    src = mne.morph_source_spaces(src_ref,
                                  subject_to=subject,
                                  verbose=verbose,
                                  subjects_dir=subjects_dir)
    bem = mne.read_bem_solution(bem_fname, verbose=verbose)
    fwd = mne.make_forward_solution(info,
                                    trans=trans_fname,
                                    src=src,
                                    bem=bem,
                                    meg=meg,
                                    eeg=eeg,
                                    mindist=mindist,
                                    verbose=verbose,
                                    n_jobs=n_jobs)
    return fwd
Esempio n. 6
0
def read_bem_solution(subject, subjects_dir):

    bem_path = join(subjects_dir, subject, 'bem',
                    subject + '-5120-bem-sol.fif')    
    bem = mne.read_bem_solution(bem_path)
    
    return bem
Esempio n. 7
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
Esempio n. 8
0
def get_bem_artifacts(
        template,
        montage_name="HGSN129-montage.fif",
        subjects_dir=None,
        include_vol_src=True,
        labels_vol=('Left-Amygdala', 'Left-Caudate', 'Left-Hippocampus',
                    'Left-Pallidum', 'Left-Putamen', 'Left-Thalamus',
                    'Right-Amygdala', 'Right-Caudate', 'Right-Hippocampus',
                    'Right-Pallidum', 'Right-Putamen', 'Right-Thalamus'),
        force_vol_computation=False):

    if subjects_dir is None:
        subjects_dir = Path(os.environ["SUBJECTS_DIR"])
    if template == "fsaverage":
        fs_dir = mne.datasets.fetch_fsaverage(verbose=True)
        trans = 'fsaverage'  # MNE has a built-in fsaverage transformation
        surface_src = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')
        bem_solution = op.join(fs_dir, 'bem',
                               'fsaverage-5120-5120-5120-bem-sol.fif')
        bem_model = None
        montage = mne.channels.make_standard_montage('GSN-HydroCel-129')
        return montage, trans, bem_model, bem_solution, surface_src

    montage = mne.channels.read_dig_fif(
        str(Path(subjects_dir) / template / "montages" / montage_name))
    trans = mne.channels.compute_native_head_t(montage)
    bem_model = mne.read_bem_surfaces(
        str(
            Path(subjects_dir) / template / "bem" /
            f"{template}-5120-5120-5120-bem.fif"))
    bem_solution = mne.read_bem_solution(
        str(
            Path(subjects_dir) / template / "bem" /
            f"{template}-5120-5120-5120-bem-sol.fif"))

    if not include_vol_src:
        surface_src = mne.read_source_spaces(
            str(
                Path(subjects_dir) / template / "bem" /
                f"{template}-oct-6-src.fif"))
        return montage, trans, bem_model, bem_solution, surface_src

    mixed_src_file_path = Path(
        subjects_dir) / template / "bem" / f"{template}-mixed-src.fif"
    if not mixed_src_file_path.exists() or force_vol_computation:
        surface_src = mne.read_source_spaces(
            str(
                Path(subjects_dir) / template / "bem" /
                f"{template}-oct-6-src.fif"))
        volume_src = mne.setup_volume_source_space(template,
                                                   pos=5.0,
                                                   bem=bem_solution,
                                                   add_interpolator=True,
                                                   volume_label=labels_vol)
        mixed_src = surface_src + volume_src
        mixed_src.save(str(mixed_src_file_path), overwrite=True)

    mixed_src = mne.read_source_spaces(str(mixed_src_file_path))

    return montage, trans, bem_model, bem_solution, mixed_src
Esempio n. 9
0
def test_simulate_round_trip(raw_data):
    """Test simulate_raw round trip calculations."""
    # Check a diagonal round-trip
    raw, src, stc, trans, sphere = raw_data
    raw.pick_types(meg=True, stim=True)
    bem = read_bem_solution(bem_1_fname)
    old_bem = bem.copy()
    old_src = src.copy()
    old_trans = trans.copy()
    fwd = make_forward_solution(raw.info, trans, src, bem)
    # no omissions
    assert (sum(len(s['vertno']) for s in src) ==
            sum(len(s['vertno']) for s in fwd['src']) ==
            36)
    # make sure things were not modified
    assert (old_bem['surfs'][0]['coord_frame'] ==
            bem['surfs'][0]['coord_frame'])
    assert trans == old_trans
    _compare_source_spaces(src, old_src)
    data = np.eye(fwd['nsource'])
    raw.crop(0, (len(data) - 1) / raw.info['sfreq'])
    stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']],
                         0, 1. / raw.info['sfreq'])
    for use_fwd in (None, fwd):
        if use_fwd is None:
            use_trans, use_src, use_bem = trans, src, bem
        else:
            use_trans = use_src = use_bem = None
        with pytest.deprecated_call():
            this_raw = simulate_raw(raw, stc, use_trans, use_src, use_bem,
                                    cov=None, forward=use_fwd)
        this_raw.pick_types(meg=True, eeg=True)
        assert (old_bem['surfs'][0]['coord_frame'] ==
                bem['surfs'][0]['coord_frame'])
        assert trans == old_trans
        _compare_source_spaces(src, old_src)
        this_fwd = convert_forward_solution(fwd, force_fixed=True)
        assert_allclose(this_raw[:][0], this_fwd['sol']['data'],
                        atol=1e-12, rtol=1e-6)
    with pytest.raises(ValueError, match='If forward is not None then'):
        simulate_raw(raw.info, stc, trans, src, bem, forward=fwd)
    # Not iterable
    with pytest.raises(TypeError, match='SourceEstimate, tuple, or iterable'):
        simulate_raw(raw.info, 0., trans, src, bem, None)
    # STC with a source that `src` does not have
    assert 0 not in src[0]['vertno']
    vertices = [[0, fwd['src'][0]['vertno'][0]], []]
    stc_bad = SourceEstimate(data[:2], vertices, 0, 1. / raw.info['sfreq'])
    with pytest.warns(RuntimeWarning,
                      match='1 of 2 SourceEstimate vertices'):
        simulate_raw(raw.info, stc_bad, trans, src, bem)
    assert 0 not in fwd['src'][0]['vertno']
    with pytest.warns(RuntimeWarning,
                      match='1 of 2 SourceEstimate vertices'):
        simulate_raw(raw.info, stc_bad, None, None, None, forward=fwd)
    # dev_head_t mismatch
    fwd['info']['dev_head_t']['trans'][0, 0] = 1.
    with pytest.raises(ValueError, match='dev_head_t.*does not match'):
        simulate_raw(raw.info, stc, None, None, None, forward=fwd)
Esempio n. 10
0
 def setup_bem():
     if not os.path.exists('bem/fsaverage_bem.fif'):
         model = mne.make_bem_model(MNE_Repo_Mat.subject)
         bem_sol = mne.make_bem_solution(model)
         mne.write_bem_solution('bem/fsaverage_bem.fif',bem_sol)
     else:
         bem_sol = mne.read_bem_solution('bem/fsaverage_bem.fif')
     return bem_sol
Esempio n. 11
0
def test_bem_solution():
    """Test making a BEM solution from Python with I/O"""
    # test degenerate conditions
    surf = read_bem_surfaces(fname_bem_1)[0]
    assert_raises(RuntimeError, _ico_downsample, surf, 10)  # bad dec grade
    s_bad = dict(tris=surf['tris'][1:], ntri=surf['ntri'] - 1, rr=surf['rr'])
    assert_raises(RuntimeError, _ico_downsample, s_bad, 1)  # not isomorphic
    s_bad = dict(tris=surf['tris'].copy(), ntri=surf['ntri'],
                 rr=surf['rr'])  # bad triangulation
    s_bad['tris'][0] = [0, 0, 0]
    assert_raises(RuntimeError, _ico_downsample, s_bad, 1)
    s_bad['id'] = 1
    assert_raises(RuntimeError, _assert_complete_surface, s_bad)
    s_bad = dict(tris=surf['tris'], ntri=surf['ntri'], rr=surf['rr'].copy())
    s_bad['rr'][0] = 0.
    assert_raises(RuntimeError, _get_ico_map, surf, s_bad)

    surfs = read_bem_surfaces(fname_bem_3)
    assert_raises(RuntimeError, _assert_inside, surfs[0], surfs[1])  # outside
    surfs[0]['id'] = 100  # bad surfs
    assert_raises(RuntimeError, _order_surfaces, surfs)
    surfs[1]['rr'] /= 1000.
    assert_raises(RuntimeError, _check_surface_size, surfs[1])

    # actually test functionality
    tempdir = _TempDir()
    fname_temp = op.join(tempdir, 'temp-bem-sol.fif')
    # use a model and solution made in Python
    conductivities = [(0.3, ), (0.3, 0.006, 0.3)]
    fnames = [fname_bem_sol_1, fname_bem_sol_3]
    for cond, fname in zip(conductivities, fnames):
        for model_type in ('python', 'c'):
            if model_type == 'python':
                model = make_bem_model('sample',
                                       conductivity=cond,
                                       ico=2,
                                       subjects_dir=subjects_dir)
            else:
                model = fname_bem_1 if len(cond) == 1 else fname_bem_3
        solution = make_bem_solution(model)
        solution_c = read_bem_solution(fname)
        _compare_bem_solutions(solution, solution_c)
        write_bem_solution(fname_temp, solution)
        solution_read = read_bem_solution(fname_temp)
        _compare_bem_solutions(solution, solution_c)
        _compare_bem_solutions(solution_read, solution_c)
Esempio n. 12
0
def compute_fwd(subject,
                src_ref,
                info,
                trans_fname,
                bem_fname,
                meg=True,
                eeg=True,
                mindist=2,
                subjects_dir=None,
                n_jobs=1,
                verbose=None):
    """Morph the source space of fsaverage to a subject.

    Parameters
    ----------
    subject : str
        Name of the reference subject.
    src_ref : instance of SourceSpaces
        Source space of the reference subject. See `get_src_reference.`
    info : str | instance of mne.Info
        Instance of an MNE info file or path to a raw fif file.
    trans_fname : str
        Path to the trans file of the subject.
    bem_fname : str
        Path to the bem solution of the subject.
    meg : bool
        Include MEG channels or not.
    eeg : bool
        Include EEG channels or not.
    mindist : float
        Safety distance from the outer skull. Sources below `mindist` will be
        discarded in the forward operator.
    subjects_dir : str
        Path to the freesurfer `subjects` directory.
    n_jobs : int
        The number jobs to run in parallel.
    verbose : None | bool
        Use verbose mode. If None use MNE default.

    """
    print("Processing subject %s" % subject)

    src = mne.morph_source_spaces(src_ref,
                                  subject_to=subject,
                                  verbose=verbose,
                                  subjects_dir=subjects_dir)
    bem = mne.read_bem_solution(bem_fname, verbose=verbose)
    fwd = mne.make_forward_solution(info,
                                    trans=trans_fname,
                                    src=src,
                                    bem=bem,
                                    meg=meg,
                                    eeg=eeg,
                                    mindist=mindist,
                                    verbose=verbose,
                                    n_jobs=n_jobs)
    return fwd
Esempio n. 13
0
def test_bem_solution():
    """Test making a BEM solution from Python with I/O."""
    # test degenerate conditions
    surf = read_bem_surfaces(fname_bem_1)[0]
    pytest.raises(RuntimeError, _ico_downsample, surf, 10)  # bad dec grade
    s_bad = dict(tris=surf['tris'][1:], ntri=surf['ntri'] - 1, rr=surf['rr'])
    pytest.raises(RuntimeError, _ico_downsample, s_bad, 1)  # not isomorphic
    s_bad = dict(tris=surf['tris'].copy(), ntri=surf['ntri'],
                 rr=surf['rr'])  # bad triangulation
    s_bad['tris'][0] = [0, 0, 0]
    pytest.raises(RuntimeError, _ico_downsample, s_bad, 1)
    s_bad['id'] = 1
    pytest.raises(RuntimeError, _assert_complete_surface, s_bad)
    s_bad = dict(tris=surf['tris'], ntri=surf['ntri'], rr=surf['rr'].copy())
    s_bad['rr'][0] = 0.
    pytest.raises(RuntimeError, _get_ico_map, surf, s_bad)

    surfs = read_bem_surfaces(fname_bem_3)
    pytest.raises(RuntimeError, _assert_inside, surfs[0], surfs[1])  # outside
    surfs[0]['id'] = 100  # bad surfs
    pytest.raises(RuntimeError, _order_surfaces, surfs)
    surfs[1]['rr'] /= 1000.
    pytest.raises(RuntimeError, _check_surface_size, surfs[1])

    # actually test functionality
    tempdir = _TempDir()
    fname_temp = op.join(tempdir, 'temp-bem-sol.fif')
    # use a model and solution made in Python
    conductivities = [(0.3,), (0.3, 0.006, 0.3)]
    fnames = [fname_bem_sol_1, fname_bem_sol_3]
    for cond, fname in zip(conductivities, fnames):
        for model_type in ('python', 'c'):
            if model_type == 'python':
                model = make_bem_model('sample', conductivity=cond, ico=2,
                                       subjects_dir=subjects_dir)
            else:
                model = fname_bem_1 if len(cond) == 1 else fname_bem_3
        solution = make_bem_solution(model)
        solution_c = read_bem_solution(fname)
        _compare_bem_solutions(solution, solution_c)
        write_bem_solution(fname_temp, solution)
        solution_read = read_bem_solution(fname_temp)
        _compare_bem_solutions(solution, solution_c)
        _compare_bem_solutions(solution_read, solution_c)
Esempio n. 14
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
Esempio n. 15
0
def test_mne_prepare_bem_model(tmp_path):
    """Test mne setup_source_space."""
    check_usage(mne_prepare_bem_model, force_help=True)
    # Using the sample dataset
    bem_solution_fname = op.join(tmp_path, "bem_solution-bem-sol.fif")
    # Test  command
    with ArgvSetter(
        ('--bem', bem_model_fname, '--sol', bem_solution_fname, '--verbose')):
        mne_prepare_bem_model.run()
    bem_solution = read_bem_solution(bem_solution_fname)
    assert isinstance(bem_solution, ConductorModel)
Esempio n. 16
0
def test_simulate_round_trip():
    """Test simulate_raw round trip calculations."""
    # Check a diagonal round-trip
    raw, src, stc, trans, sphere = _get_data()
    raw.pick_types(meg=True, stim=True)
    bem = read_bem_solution(bem_1_fname)
    old_bem = bem.copy()
    old_src = src.copy()
    old_trans = trans.copy()
    fwd = make_forward_solution(raw.info, trans, src, bem)
    # no omissions
    assert (sum(len(s['vertno'])
                for s in src) == sum(len(s['vertno'])
                                     for s in fwd['src']) == 36)
    # make sure things were not modified
    assert (
        old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame'])
    assert trans == old_trans
    _compare_source_spaces(src, old_src)
    data = np.eye(fwd['nsource'])
    raw.crop(0, (len(data) - 1) / raw.info['sfreq'])
    stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0,
                         1. / raw.info['sfreq'])
    for use_fwd in (None, fwd):
        if use_fwd is None:
            use_trans, use_src, use_bem = trans, src, bem
        else:
            use_trans = use_src = use_bem = None
        for use_cps in (False, True):
            this_raw = simulate_raw(raw,
                                    stc,
                                    use_trans,
                                    use_src,
                                    use_bem,
                                    cov=None,
                                    use_cps=use_cps,
                                    forward=use_fwd)
            this_raw.pick_types(meg=True, eeg=True)
            assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]
                    ['coord_frame'])
            assert trans == old_trans
            _compare_source_spaces(src, old_src)
            this_fwd = convert_forward_solution(fwd,
                                                force_fixed=True,
                                                use_cps=use_cps)
            assert_allclose(this_raw[:][0],
                            this_fwd['sol']['data'],
                            atol=1e-12,
                            rtol=1e-6)
    with pytest.raises(ValueError, match='If forward is not None then'):
        simulate_raw(raw, stc, trans, src, bem, forward=fwd)
    fwd['info']['dev_head_t']['trans'][0, 0] = 1.
    with pytest.raises(ValueError, match='dev_head_t.*does not match'):
        simulate_raw(raw, stc, None, None, None, forward=fwd)
Esempio n. 17
0
def test_io_bem(tmpdir):
    """Test reading and writing of bem surfaces and solutions."""
    temp_bem = op.join(str(tmpdir), 'temp-bem.fif')
    pytest.raises(ValueError, read_bem_surfaces, fname_raw)
    pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10)
    surf = read_bem_surfaces(fname_bem_3, patch_stats=True)
    surf = read_bem_surfaces(fname_bem_3, patch_stats=False)
    write_bem_surfaces(temp_bem, surf[0])
    surf_read = read_bem_surfaces(temp_bem, patch_stats=False)
    _compare_bem_surfaces(surf, surf_read)

    pytest.raises(RuntimeError, read_bem_solution, fname_bem_3)
    temp_sol = op.join(str(tmpdir), 'temp-sol.fif')
    sol = read_bem_solution(fname_bem_sol_3)
    assert 'BEM' in repr(sol)
    write_bem_solution(temp_sol, sol)
    sol_read = read_bem_solution(temp_sol)
    _compare_bem_solutions(sol, sol_read)
    sol = read_bem_solution(fname_bem_sol_1)
    pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
Esempio n. 18
0
def test_io_bem():
    """Test reading and writing of bem surfaces and solutions."""
    tempdir = _TempDir()
    temp_bem = op.join(tempdir, 'temp-bem.fif')
    pytest.raises(ValueError, read_bem_surfaces, fname_raw)
    pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10)
    surf = read_bem_surfaces(fname_bem_3, patch_stats=True)
    surf = read_bem_surfaces(fname_bem_3, patch_stats=False)
    write_bem_surfaces(temp_bem, surf[0])
    surf_read = read_bem_surfaces(temp_bem, patch_stats=False)
    _compare_bem_surfaces(surf, surf_read)

    pytest.raises(RuntimeError, read_bem_solution, fname_bem_3)
    temp_sol = op.join(tempdir, 'temp-sol.fif')
    sol = read_bem_solution(fname_bem_sol_3)
    assert 'BEM' in repr(sol)
    write_bem_solution(temp_sol, sol)
    sol_read = read_bem_solution(temp_sol)
    _compare_bem_solutions(sol, sol_read)
    sol = read_bem_solution(fname_bem_sol_1)
    pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
Esempio n. 19
0
def test_mne_prepare_bem_model(tmpdir):
    """Test mne setup_source_space."""
    check_usage(mne_prepare_bem_model, force_help=True)
    # Using the sample dataset
    bem_model_fname = op.join(testing.data_path(download=False), 'subjects',
                              'sample', 'bem', 'sample-320-320-320-bem.fif')
    bem_solution_fname = op.join(tmpdir, "bem_solution-bem-sol.fif")
    # Test  command
    with ArgvSetter(
        ('--bem', bem_model_fname, '--sol', bem_solution_fname, '--verbose')):
        mne_prepare_bem_model.run()
    bem_solution = read_bem_solution(bem_solution_fname)
    assert isinstance(bem_solution, ConductorModel)
Esempio n. 20
0
def createInv(subj):
    # subjdir = os.environ['SUBJECTS_DIR']
    file_path = '/m/nbe/scratch/restmeg/data/camcan/cc700/mri/pipeline/release004/BIDSsep/megraw/sub-' + subj + '/meg/'
    raw = mne.io.fiff.Raw(file_path + 'rest_raw.fif')
    fname_trans = file_path + 'rest_raw-trans.fif'
    src = mne.read_source_spaces(
        '/m/nbe/scratch/restmeg/data/camcan/subjects/' + subj + '/bem/' +
        subj + '-oct-6-src.fif')
    bem_sol = mne.read_bem_solution(subj + '-5120-5120-5120-bem-sol.fif')

    fwd = mne.make_forward_solution(raw.info, fname_trans, src, bem_sol)
    cov = mne.compute_raw_covariance(raw)
    inv = mne.minimum_norm.make_inverse_operator(raw.info, fwd, cov, loose=0.2)
    mne.minimum_norm.write_inverse_operator(subj + '-inv.fif', inv)
Esempio n. 21
0
def makeBem(subj):
    camcan_root = os.environ['CAMCAN_ROOT']
    bemmodel_fname = camcan_root + 'processed/cc700/mri/pipeline/release004/BIDSsep/megraw/' + subj + '/meg/' + subj + \
                    '-5120-5120-5120-singles-bem.fif'
    bemsolution_fname = camcan_root + 'processed/cc700/mri/pipeline/release004/BIDSsep/megraw/' + subj + '/meg/' + \
                    subj + '-5120-5120-5120-singles-bem-sol.fif'
    try:
        model = mne.read_bem_surfaces(bemmodel_fname)
    except IOError:
        model = mne.make_bem_model(subj, conductivity=[0.3])
        mne.write_bem_surfaces(bemmodel_fname, model)
        
    try:
        bem_sol = mne.read_bem_solution(bemsolution_fname)
    except IOError:
        bem_sol = mne.make_bem_solution(model)
        mne.write_bem_solution(bemsolution_fname, bem_sol)
        
    return bem_sol
Esempio n. 22
0
def compute_fwd(subject,
                src_ref,
                info,
                trans_fname,
                bem_fname,
                mindist=2,
                subjects_dir=None):
    """Morph source space of fsaverage to subject."""
    print("Processing subject %s" % subject)

    src = mne.morph_source_spaces(src_ref,
                                  subject_to=subject,
                                  subjects_dir=subjects_dir)
    bem = mne.read_bem_solution(bem_fname)
    fwd = mne.make_forward_solution(info,
                                    trans=trans_fname,
                                    src=src,
                                    bem=bem,
                                    mindist=mindist,
                                    n_jobs=1)
    return fwd
Esempio n. 23
0
def __make_inv_individual(rawf, transf, bemf, srcf, outdir):

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

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

        mne.minimum_norm.write_inverse_operator(f'{outdir}/{tmpid}_inv.fif',
                                                inv)
    except:
        print('error')
    return tmpath
Esempio n. 24
0
    def _get_source_stuff(self):
        # Get source stuffs
        # Get path of subject folder
        subject_path = os.path.join(RAW_DIR, self.running_name)

        def _path(ext):
            # Method to get file path that ends with [ext]
            return os.path.join(subject_path, f'{self.subject_name}{ext}')

        # Read source space
        src = mne.read_source_spaces(_path('-src.fif'))

        # Read bem surfaces
        model = mne.read_bem_surfaces(_path('-bem.fif'))

        # Read bem solution
        bem_sol = mne.read_bem_solution(_path('-bem-sol.fif'))

        # Read trans matrix
        trans = mne.read_trans(_path('-trans.fif'))

        # Return
        return dict(src=src, model=model, bem_sol=bem_sol, trans=trans)
Esempio n. 25
0
    def src_modelling(self, spacing=['oct5'], overwrite=False):
        from mne import (read_forward_solution, make_forward_solution,
                         write_forward_solution, setup_source_space)
        subject = self.subject
        task = self.experiment
        mne.set_config('SUBJECTS_DIR', self.pth_FS)
        FS_subj = op.join(self.pth_FS, subject)
        fname_trans = op.join(FS_subj, subject + '-trans.fif')
        fname_bem = op.join(FS_subj, '%s-bem_sol.fif' % subject)

        if not op.exists(fname_bem) or overwrite:
            # make_watershed_bem already run in the sh script
#            mne.bem.make_watershed_bem(subject, overwrite=True,
#                                       volume='T1', atlas=True, gcaatlas=False,
#                                       preflood=None)
            model = mne.make_bem_model(subject, ico=4, conductivity=[0.3])
            bem = mne.make_bem_solution(model)
            mne.write_bem_solution(fname_bem, bem)
        else:
            bem = mne.read_bem_solution(fname_bem)

        for space in spacing:
            fname_src = op.join(FS_subj, 'bem', '%s-src.fif' % space)
            bname_fwd = '%s_%s_%s-fwd.fif' % (subject, task, space)
            fname_fwd = op.join(self.out_srcData, bname_fwd)
            if not op.exists(fname_src) or overwrite:
                src = setup_source_space(subject, space,
                                         subjects_dir=self.pth_FS)
                src.save(fname_src, overwrite=overwrite)

            if op.exists(fname_fwd) and not overwrite:
                self.fwd = read_forward_solution(fname_fwd)
            else:
                self.fwd = make_forward_solution(self.raw.info, fname_trans,
                                                 fname_src, fname_bem)
                write_forward_solution(fname_fwd, self.fwd, overwrite)
Esempio n. 26
0
# 2 compute source space into "bem" folder
# src = mne.setup_source_space('fsaverage', )
src = mne.read_source_spaces(
    r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-oct-6-src.fif'
)

# make bem surf
#model = mne.make_bem_model(subject='fsaverage', ico=4)
#mne.write_bem_surfaces(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-bem-surf.fif', model)

# make bem solution
#surfs = mne.read_bem_surfaces(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-bem-surf.fif')
#bem = mne.make_bem_solution(surfs)
#mne.write_bem_solution('bem-solution.fif', bem)
bem = mne.read_bem_solution(
    r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\bem-solution-flash.fif'
)

# set trans
trans = r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-trans.fif'

# data
real = False
if not real:
    channels = [
        'Fp1', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'Ft9', 'Fc5', 'Fc1', 'Fc2',
        'Fc6', 'Ft10', 'T7', 'C3', 'Cz', 'C4', 'T8', 'Tp9', 'Cp5', 'Cp1',
        'Cp2', 'Cp6', 'Tp10', 'P7', 'P3', 'Pz', 'P4', 'P8', 'O1', 'Oz', 'O2'
    ]
    data = np.random.normal(loc=0, scale=0.00001, size=(5000, len(channels))).T
    fs = 500
Esempio n. 27
0
# 2 compute source space into "bem" folder
# src = mne.setup_source_space('fsaverage', )
src = mne.read_source_spaces(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-oct-6-src.fif')


# make bem surf
#model = mne.make_bem_model(subject='fsaverage', ico=4)
#mne.write_bem_surfaces(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-bem-surf.fif', model)


# make bem solution
#surfs = mne.read_bem_surfaces(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-bem-surf.fif')
#bem = mne.make_bem_solution(surfs)
#mne.write_bem_solution('bem-solution.fif', bem)
bem = mne.read_bem_solution(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\bem-solution-flash.fif')

# set trans
trans = r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\av_brain\fsaverage\bem\fsaverage-trans.fif'


# data
real = False
if not real:
    channels = ['Fp1', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'Ft9', 'Fc5', 'Fc1', 'Fc2', 'Fc6', 'Ft10', 'T7', 'C3', 'Cz',
                'C4', 'T8', 'Tp9', 'Cp5', 'Cp1', 'Cp2', 'Cp6', 'Tp10', 'P7', 'P3', 'Pz', 'P4', 'P8', 'O1', 'Oz', 'O2']
    data = np.random.normal(loc=0, scale=0.00001, size=(5000, len(channels))).T
    fs = 500
else:
    import h5py
    from pynfb.postprocessing.utils import get_info
Esempio n. 28
0
def plot_evoked(widget,
                state,
                fwd_path,
                subject,
                info,
                ras_to_head_t,
                exact_solution,
                bem_path=None,
                head_to_mri_t=None,
                fwd_lookup_table=None,
                t1_img=None):
    if fwd_lookup_table is None:
        raise ValueError('Must prodive fwd_lookup_table')

    dipole_pos = (state['dipole_pos']['x'], state['dipole_pos']['y'],
                  state['dipole_pos']['z'])
    dipole_ori = (state['dipole_ori']['x'], state['dipole_ori']['y'],
                  state['dipole_ori']['z'])

    # dipole_pos = np.array(dipole_pos).reshape(1, 3)
    # dipole_pos = apply_trans(trans=ras_to_head_t, pts=dipole_pos)
    # dipole_pos /= 1000

    # dipole_ori = np.array(dipole_ori).reshape(1, 3)
    # dipole_ori = apply_trans(trans=ras_to_head_t, pts=dipole_ori, move=False)
    # dipole_ori /= 1000
    # dipole_ori /= np.linalg.norm(dipole_ori)

    # dipole_pos = np.array(dipole_pos).reshape(1, 3).round(3)
    # dipole_ori = np.array(dipole_ori).reshape(1, 3).round(3)

    dipole_pos_ras = np.array(dipole_pos).reshape(1, 3)
    dipole_pos_vox = apply_trans(t1_img.header.get_ras2vox(), dipole_pos_ras)
    dipole_pos_mri = apply_trans(t1_img.header.get_vox2ras_tkr(),
                                 dipole_pos_vox)
    dipole_pos_mri_m = dipole_pos_mri / 1000.
    dipole_pos_head = apply_trans(invert_transform(head_to_mri_t),
                                  dipole_pos_mri_m)
    dipole_pos = dipole_pos_head

    dipole_ori_ras = np.array(dipole_ori).reshape(1, 3)
    dipole_ori_vox = apply_trans(t1_img.header.get_ras2vox(),
                                 dipole_ori_ras,
                                 move=False)
    dipole_ori_mri = apply_trans(t1_img.header.get_vox2ras_tkr(),
                                 dipole_ori_vox,
                                 move=False)
    dipole_ori_mri_m = dipole_ori_mri / 1000.
    dipole_ori_head = apply_trans(invert_transform(head_to_mri_t),
                                  dipole_ori_mri_m,
                                  move=False)
    dipole_ori = dipole_ori_head
    dipole_ori /= np.linalg.norm(dipole_ori)

    dipole_amplitude = state['dipole_amplitude']

    if exact_solution:
        if (bem_path).exists():
            print(f'\nUsing existing BEM solution: {bem_path}\n')
        else:
            print('Retrieving BEM solution from GitHub.')
            try:
                download_bem_from_github(data_path=bem_path.parent,
                                         subject=subject,
                                         overwrite=False)
            except RuntimeError as e:
                msg = (f'Failed to retrieve the BEM solution. '
                       f'The error was: {e}\n')
                raise RuntimeError(msg)
        bem = mne.read_bem_solution(bem_path)
        fwd = gen_forward_solution(pos=dipole_pos,
                                   bem=bem,
                                   info=info,
                                   trans=head_to_mri_t)
    else:
        # Retrieve the dipole pos closest to the one we have a pre-calculated
        # fwd for.
        pos_head_grid = create_head_grid(info=info)
        dipole_pos_for_fwd = (find_closest(pos_head_grid[0], dipole_pos[0, 0]),
                              find_closest(pos_head_grid[1], dipole_pos[0, 1]),
                              find_closest(pos_head_grid[2], dipole_pos[0, 2]))

        print(f'Requested calculations for dipole located at:\n'
              f'    x={dipole_pos[0, 0]}, y={dipole_pos[0, 1]}, '
              f'z={dipole_pos[0, 2]} [m, MNE Head]\n'
              f'Using a forward solution for the following location:\n'
              f'    x={dipole_pos_for_fwd[0]}, y={dipole_pos_for_fwd[1]}, '
              f'z={dipole_pos_for_fwd[2]} [m, MNE Head]')

        fwd_fname = (f'{subject}-'
                     f'{dipole_pos_for_fwd[0]:.3f}-'
                     f'{dipole_pos_for_fwd[1]:.3f}-'
                     f'{dipole_pos_for_fwd[2]:.3f}-fwd.fif')
        if (fwd_path / fwd_fname).exists():
            print(f'\nUsing existing forward solution: {fwd_fname}\n')
        elif not fwd_lookup_table.loc[str(dipole_pos_for_fwd[0]),
                                      str(dipole_pos_for_fwd[1]),
                                      str(dipole_pos_for_fwd[2])].iloc[0]:
            msg = ('No pre-calculated foward solution available for this '
                   'dipole. Please select a dipole origin clearly inside the '
                   'brain.')
            print(msg)
            return
        else:
            print('Retrieving forward solution from GitHub.\n\n')
            try:
                download_fwd_from_github(fwd_path=fwd_path,
                                         subject=subject,
                                         dipole_pos=dipole_pos_for_fwd)
            except RuntimeError as e:
                msg = (f'Failed to retrieve pre-calculated forward solution. '
                       f'The error was: {e}\n\n'
                       f'Please try again with another dipole origin inside '
                       f'the brain.')
                raise RuntimeError(msg)

        fwd = mne.read_forward_solution(fwd_path / fwd_fname)
        del fwd_fname, pos_head_grid, dipole_pos_for_fwd

    evoked = gen_evoked(fwd=fwd,
                        dipole_ori=dipole_ori,
                        dipole_amplitude=dipole_amplitude,
                        info=info)

    for ch_type, fig in widget['topomap_fig'].items():
        ax_topomap = fig.axes[0]
        ax_colorbar = fig.axes[1]
        ax_topomap.clear()
        ax_colorbar.clear()
        ax_topomap.set_aspect('equal')

        if ch_type == 'eeg':
            outlines = 'head'
        else:
            outlines = 'skirt'

        evoked.plot_topomap(ch_type=ch_type,
                            colorbar=False,
                            outlines=outlines,
                            times=evoked.times[-1],
                            show=False,
                            axes=ax_topomap)
        ax_topomap.set_title(None)
        # ax_topomap.format_coord = _create_format_coord('topomap')
        cb = fig.colorbar(ax_topomap.images[-1],
                          cax=ax_colorbar,
                          orientation='horizontal')

        if ch_type == 'mag':
            label = 'fT'
        elif ch_type == 'grad':
            label = 'fT/cm'
        elif ch_type == 'eeg':
            label = 'µV'
            # Scale the topomap to approx. the same size as the MEG topomaps.
            mag_topomap_ax = widget['topomap_fig']['mag'].axes[0]
            ax_topomap.set_xlim(np.array(mag_topomap_ax.get_xlim()) * 1.05)
            ax_topomap.set_ylim(np.array(mag_topomap_ax.get_ylim()) * 1.05)

        cb.set_label(label, fontweight='bold')
        fig.canvas.draw()
Esempio n. 29
0
# Explore data

kinds = ('vv', 'opm')
n_fft = next_fast_len(int(round(4 * new_sfreq)))
print('Using n_fft=%d (%0.1f sec)' % (n_fft, n_fft / raws['vv'].info['sfreq']))
for kind in kinds:
    fig = raws[kind].plot_psd(n_fft=n_fft, proj=True)
    fig.suptitle(titles[kind])
    fig.subplots_adjust(0.1, 0.1, 0.95, 0.85)

##############################################################################
# Alignment and forward
# ---------------------

src = mne.read_source_spaces(src_fname)
bem = mne.read_bem_solution(bem_fname)
fwd = dict()
trans = dict(vv=vv_trans_fname, opm=opm_trans_fname)
# check alignment and generate forward
with mne.use_coil_def(opm_coil_def_fname):
    for kind in kinds:
        dig = True if kind == 'vv' else False
        fig = mne.viz.plot_alignment(
            raws[kind].info, trans=trans[kind], subject=subject,
            subjects_dir=subjects_dir, dig=dig, coord_frame='mri',
            surfaces=('head', 'white'))
        mlab.view(0, 90, focalpoint=(0., 0., 0.), distance=0.6, figure=fig)
        fwd[kind] = mne.make_forward_solution(
            raws[kind].info, trans[kind], src, bem, eeg=False, verbose=True)

##############################################################################
Esempio n. 30
0
if hostname == "Wintermute":
    data_path = "/home/mje/Projects/MEG_Hyopnosis/data/"
    subjects_dir = "/home/mje/Projects/MEG_Hyopnosis/data/fs_subjects_dir"
else:
    data_path = "/projects/" + \
                "MINDLAB2013_18-MEG-HypnosisAnarchicHand/" + \
                "scratch/Tone_task_MNE_ver_2/"
    subjects_dir = "/projects/" + \
                   "MINDLAB2013_18-MEG-HypnosisAnarchicHand/" + \
                   "scratch/fs_subjects_dir/"

# CHANGE DIR TO SAVE FILES THE RIGTH PLACE
os.chdir(data_path)


bem = mne.read_bem_solution(subjects_dir + "/subject_1/bem/" +
                            "subject_1-5120-bem-sol.fif")
nrm_fname = data_path + "tone_task-normal-tsss-mc-autobad-ica_raw.fif"
hyp_fname = data_path + "tone_task-hyp-tsss-mc-autobad-ica_raw.fif"

nrm_trans = data_path + "nrm2-trans.fif"
hyp_trans = data_path + "hyp2-trans.fif"

# src = mne.setup_source_space("subject_1",
#                              "nrm-src-oct6.fif",
#                              spacing="oct6",
#                              subjects_dir=subjects_dir,
#                              n_jobs=2)

src = mne.read_source_spaces(data_path + "subj_1-oct6-src.fif")

fwd_nrm = mne.make_forward_solution(nrm_fname,
Esempio n. 31
0
def run_fwd_inv(fname_raw,
                subject,
                cov,
                fname_trans,
                subjects_dir='/cluster/transcend/MRI/WMA/recons',
                src=None,
                bem=None,
                fname_fwd=None,
                meg=True,
                fname_inv=None,
                eeg=False,
                n_jobs=2,
                bem_ico=4,
                spacing='ico5',
                loose=0.2,
                rank=None,
                depth=0.8,
                fixed=True,
                limit_depth_chs=True,
                reject=None):
    if src is None:
        src_fname = op.join(subjects_dir, subject,
                            '%s-pyimpress-src.fif' % spacing)
        if not os.path.isfile(src_fname):
            src = run_strural(subject,
                              bem_ico=bem_ico,
                              spacing=spacing,
                              subjects_dir=subjects_dir)[0]
        else:
            src = mne.read_source_spaces(src_fname)

    if bem is None:
        bem_fname = op.join(subjects_dir, subject,
                            '%s-pyimpress-bem.fif' % bem_ico)
        if not os.path.isfile(bem_fname):
            bem = run_strural(subject,
                              bem_ico=bem_ico,
                              spacing=spacing,
                              subjects_dir=subjects_dir)[1]
        else:
            bem = mne.read_bem_solution(bem_fname)

    if fname_fwd is None:
        fname_fwd = fname_raw[:-4] + '-fwd.fif'
        if not os.path.isfile(fname_fwd):

            if os.path.isfile(fname_trans) and os.path.isfile(fname_raw):
                raw = mne.io.read_raw_fif(fname_raw)
                fwd = mne.make_forward_solution(fname_raw,
                                                trans=fname_trans,
                                                src=src,
                                                bem=bem,
                                                fname=fname_fwd,
                                                meg=meg,
                                                eeg=eeg,
                                                n_jobs=n_jobs)
                mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
            else:
                raise Exception('fname_trans and fname_raw both needed')

        else:
            fwd = mne.read_forward_solution(fname_fwd)
            if os.path.isfile(fname_raw):
                raw = mne.io.read_raw_fif(fname_raw)

    if fname_inv is None:
        if fixed:
            fname_inv = fname_raw[:-4] + '-fixed-inv.fif'
        else:
            fname_inv = fname_raw[:-4] + '-loose-inv.fif'
        if not os.path.isfile(fname_inv):
            if cov is not None:
                inv = mne.minimum_norm.make_inverse_operator(
                    raw.info,
                    fwd,
                    cov,
                    loose=loose,
                    depth=depth,
                    fixed=False,
                    limit_depth_chs=limit_depth_chs,
                    rank=rank)
                mne.minimum_norm.write_inverse_operator(fname_inv, inv)
        else:
            inv = mne.minimum_norm.read_inverse_operator(fname_inv)

    return fwd, inv
Esempio n. 32
0
        print 'Output already exists. Will not overwrite!'
        continue

    ### Make bem (or read)
    if not op.isfile(bemFile) or overwrite_pre:
        model = make_bem_model(subject=sub,
                               ico=4,
                               conductivity=conductivity,
                               subjects_dir=subjects_dir)
        bem = make_bem_solution(model)
        write_bem_solution(op.join(subjects_dir, sub, 'bem', 'bem-sol.fif'),
                           bem)
        print('Wrote BEM file ' +
              str(op.join(subjects_dir, sub, 'bem', 'bem-sol.fif')))
    else:
        bem = read_bem_solution(bemFile)

    ### Read source space
    src = read_source_spaces(srcFile)

    ### read trans
    trans = read_trans(traFile)

    ### Read noise covariance from empty room recordings
    noise_cov = read_cov(covFile)

    #### LOOP THROUGH RAWFILES
    for ff, rawFile in enumerate(rawfiles):
        print(rawFile)
        # Initiate filenames for loading and saving
        fwdFile = rawFile[:-12] + '-fwd.fif'
Esempio n. 33
0
from utils import make_discrete_forward_solutions

###############################################################################
# Create forward solutions based on manually created trans file
###############################################################################

# use same settings as in https://github.com/mne-tools/mne-scripts/tree/master/sample-data

info = mne.io.read_info(fname.sample_raw)
info = mne.pick_info(info, mne.pick_types(info, meg=True, eeg=False))
trans_man_head_to_mri = mne.read_trans(fname.trans_man)
trans_true_head_to_mri = mne.read_trans(fname.trans_true)

# create forward solution for surface source space
src_true_mri = mne.read_source_spaces(fname.src)
bem = mne.read_bem_solution(fname.bem)

fwd_true = mne.make_forward_solution(info, trans=trans_true_head_to_mri, src=src_true_mri,
                                     bem=bem, meg=True, eeg=False)

fwd_man = mne.make_forward_solution(info, trans=trans_man_head_to_mri, src=src_true_mri,
                                    bem=bem, meg=True, eeg=False)
mne.write_forward_solution(fname.fwd_man, fwd_man, overwrite=True)

###############################################################################
# Construct forward solutions for discrete source spaces
###############################################################################

rr = src_true_mri[0]['rr']
# use only vertices inuse to construct vrr
rr = rr[src_true_mri[0]['inuse'] == 1]
Esempio n. 34
0
    "TSM_24": "NOR76",
    "TSM_27": "NUT15_fa",
    "TSM_20": "RTB16",
    "TSM_23": "SRA67_fa",
    "TSM_06": "VIM71_fa",
    "TSM_13": "BEU80"
}
# sub_dict = {"NEM_26":"ENR41"}
runs = ["1", "2", "3", "4"]

## prep subjects

for meg, mri in sub_dict.items():

    # read BEM solution for subject
    bem = mne.read_bem_solution("{dir}{meg}-bem.fif".format(dir=meg_dir,
                                                            meg=meg))
    # load trans-file
    trans = "{dir}{mri}_{meg}-trans.fif".format(dir=trans_dir,
                                                mri=mri,
                                                meg=meg)
    # load source space
    src = mne.read_source_spaces("{dir}{meg}-oct6-src.fif".format(dir=meg_dir,
                                                                  meg=meg))
    # for each run, load info and plot alignment
    for run in runs:
        info = mne.io.read_info("{}{}_{}-epo.fif".format(
            preproc_dir, meg, run))
        mne.viz.plot_alignment(info,
                               trans,
                               subject=mri,
                               dig='fiducials',
for kind in kinds:
    fig = raws[kind].plot_psd(n_fft=n_fft, proj=True)
    fig.suptitle(titles[kind])
    fig.subplots_adjust(0.1, 0.1, 0.95, 0.85)

##############################################################################
# Alignment and forward
# ---------------------

# Here we use a reduced size source space (oct5) just for speed
src = mne.setup_source_space(
    subject, 'oct5', add_dist=False, subjects_dir=subjects_dir)
# This line removes source-to-source distances that we will not need.
# We only do it here to save a bit of memory, in general this is not required.
del src[0]['dist'], src[1]['dist']
bem = mne.read_bem_solution(bem_fname)
# For speed, let's just use a 1-layer BEM
bem = mne.make_bem_solution(bem['surfs'][-1:])
fwd = dict()

# check alignment and generate forward for VectorView
kwargs = dict(azimuth=0, elevation=90, distance=0.6, focalpoint=(0., 0., 0.))
fig = mne.viz.plot_alignment(
    raws['vv'].info, trans=vv_trans_fname, subject=subject,
    subjects_dir=subjects_dir, dig=True, coord_frame='mri',
    surfaces=('head', 'white'))
mne.viz.set_3d_view(figure=fig, **kwargs)
fwd['vv'] = mne.make_forward_solution(
    raws['vv'].info, vv_trans_fname, src, bem, eeg=False, verbose=True)

##############################################################################
Esempio n. 36
0
filename = '/home/stoutjd/hv_proc/MEG/APBWVFAR_airpuff_20200122_05.ds'
raw = mne.io.read_raw_ctf(filename, preload=True)
raw.resample(300)
raw.notch_filter([60, 120])

events = mne.events_from_annotations(raw)

stims = events[0][events[0][:, 2] == 2]

epochs = mne.Epochs(raw, stims, tmin=-0.1, tmax=0.4)
epochs = epochs.apply_baseline()

noise_cov = mne.compute_covariance(epochs, tmin=-0.1, tmax=0)
data_cov = mne.compute_covariance(epochs, tmin=0, tmax=0.3)

bem = mne.read_bem_solution(
    '/home/stoutjd/data/DEMO_ENIGMA/outputs/APBWVFAR_fs_ortho/bem_sol-sol.fif')
src = mne.read_source_spaces(
    '/home/stoutjd/data/DEMO_ENIGMA/outputs/APBWVFAR_fs_ortho/source_space-src.fif'
)
transfile = '/home/stoutjd/data/ENIGMA/transfiles/APBWVFAR-trans.fif'
trans = mne.read_trans(transfile)

forward = mne.make_forward_solution(epochs.info, trans, src, bem)

filters = mne.beamformer.make_lcmv(epochs.info,
                                   forward,
                                   data_cov=data_cov,
                                   noise_cov=noise_cov)

evoked = epochs.average()