コード例 #1
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)
コード例 #2
0
def prepare_bem(subject, fsMRI_dir):
    meg_subject_dir = op.join(config.meg_dir, subject)

    dcm_subdir = op.join(config.root_path, 'data', 'MRI', 'orig_dicom', subject, 'organized')
    flashfold = glob.glob(op.join(dcm_subdir, '*5°_PDW'))
    if len(flashfold) > 0:
        # In case watershed version was computed before, remove it to avoid confusion
        watersheddir = op.join(config.root_path, 'data', 'MRI', 'fs_converted', subject, 'bem', 'watershed')
        if op.exists(watersheddir):
            shutil.rmtree(watersheddir)
        # Also delete previously created symbolic links (overwrite issue...)
        bemdir = op.join(config.root_path, 'data', 'MRI', 'fs_converted', subject, 'bem')
        files_in_directory = os.listdir(bemdir)
        filtered_files = [file for file in files_in_directory if file.endswith(".surf")]
        for file in filtered_files:
            os.remove(op.join(bemdir, file))
        # Create BEM surfaces from (already converted) 5°Flash MRI using freesurfer(6.0!) mri_make_bem_surfaces
        print('Subject ' + subject + ': make_flash_bem ======================')
        mne.bem.make_flash_bem(subject, overwrite=True, show=False, subjects_dir=fsMRI_dir)
    else:
        # Create BEM surfaces from T1 MRI using freesurfer watershed
        print('Subject ' + subject + ': make_watershed_bem ======================')
        mne.bem.make_watershed_bem(subject=subject, subjects_dir=fsMRI_dir, overwrite=True)

    # BEM model meshes
    model = mne.make_bem_model(subject=subject, subjects_dir=fsMRI_dir)
    mne.write_bem_surfaces(op.join(meg_subject_dir, subject + '-5120-5120-5120-bem.fif'), model, overwrite=True)

    # BEM solution
    bem_sol = mne.make_bem_solution(model)
    mne.write_bem_solution(op.join(meg_subject_dir, subject + '-5120-5120-5120-bem-sol.fif'), bem_sol, overwrite=True)
コード例 #3
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-s", "--surf", dest="surf",
                      help="Surface in Freesurfer format", metavar="FILE")
    parser.add_option("-f", "--fif", dest="fif",
                      help="FIF file produced", metavar="FILE")
    parser.add_option("-i", "--id", dest="id", default=4,
                      help=("Surface Id (e.g. 4 sur head surface)"))

    options, args = parser.parse_args()

    if options.surf is None:
        parser.print_help()
        sys.exit(1)

    print("Converting %s to BEM FIF file." % options.surf)
    points, tris = mne.read_surface(options.surf)
    points *= 1e-3
    surf = dict(coord_frame=5, id=int(options.id), nn=None, np=len(points),
                ntri=len(tris), rr=points, sigma=1, tris=tris)
    mne.write_bem_surfaces(options.fif, surf)
コード例 #4
0
ファイル: test_bem.py プロジェクト: yikai28/mne-python
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.deprecated_call(match='overwrite'):
        write_bem_surfaces(temp_bem, surf[0])
    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 model does not have'):
        _bem_find_surface(sol, 3)
コード例 #5
0
ファイル: mne_surf2bem.py プロジェクト: zahransa/mne-python
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-s",
                      "--surf",
                      dest="surf",
                      help="Surface in Freesurfer format",
                      metavar="FILE")
    parser.add_option("-f",
                      "--fif",
                      dest="fif",
                      help="FIF file produced",
                      metavar="FILE")
    parser.add_option("-i",
                      "--id",
                      dest="id",
                      default=4,
                      help=("Surface Id (e.g. 4 for head surface)"))

    options, args = parser.parse_args()

    if options.surf is None:
        parser.print_help()
        sys.exit(1)

    print("Converting %s to BEM FIF file." % options.surf)
    surf = mne.bem._surfaces_to_bem([options.surf], [int(options.id)],
                                    sigmas=[1])
    mne.write_bem_surfaces(options.fif, surf)
コード例 #6
0
ファイル: test_bem.py プロジェクト: JohnGriffiths/mne-python
def test_make_bem_model(tmpdir, kwargs, fname):
    """Test BEM model creation from Python with I/O."""
    fname_temp = tmpdir.join('temp-bem.fif')
    with catch_logging() as log:
        model = make_bem_model('sample',
                               ico=2,
                               subjects_dir=subjects_dir,
                               verbose=True,
                               **kwargs)
    log = log.getvalue()
    if len(kwargs.get('conductivity', (0, 0, 0))) == 1:
        assert 'distance' not in log
    else:
        assert re.search(r'urfaces is approximately *3\.4 mm', log) is not None
    assert re.search(r'inner skull CM is *0\.65 *-9\.62 *43\.85 mm',
                     log) is not None
    model_c = read_bem_surfaces(fname)
    _compare_bem_surfaces(model, model_c)
    write_bem_surfaces(fname_temp, model)
    model_read = read_bem_surfaces(fname_temp)
    _compare_bem_surfaces(model, model_c)
    _compare_bem_surfaces(model_read, model_c)
    # bad conductivity
    with pytest.raises(ValueError, match='conductivity must be'):
        make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
コード例 #7
0
def create_bem_sol(sbj_dir, sbj_id):
    """Create bem solution."""
    import os.path as op
    import mne

    from mne.bem import make_watershed_bem
    from mne.report import Report

    report = Report()

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

    surf_name = 'inner_skull.surf'
    sbj_inner_skull_fname = op.join(bem_dir, sbj_id + '-' + surf_name)
    inner_skull_fname = op.join(bem_dir, surf_name)

    # check if bem-sol was created, if not creates the bem sol using C MNE
    bem_fname = op.join(bem_dir, '%s-5120-bem-sol.fif' % sbj_id)
    model_fname = op.join(bem_dir, '%s-5120-bem.fif' % sbj_id)

    if not op.isfile(bem_fname):
        # chek if inner_skull surf exists, if not BEM computation is
        # performed by MNE python functions mne.bem.make_watershed_bem
        if not (op.isfile(sbj_inner_skull_fname)
                or op.isfile(inner_skull_fname)):
            print("%s ---> FILE NOT FOUND!!!---> BEM "
                  "computed" % inner_skull_fname)
            make_watershed_bem(sbj_id, sbj_dir, overwrite=True)
        else:
            print(("\n*** inner skull %s surface "
                   "exists!!!\n" % inner_skull_fname))

        # Create a BEM model for a subject
        surfaces = mne.make_bem_model(sbj_id,
                                      ico=4,
                                      conductivity=[0.3],
                                      subjects_dir=sbj_dir)

        # Write BEM surfaces to a fiff file
        mne.write_bem_surfaces(model_fname, surfaces)

        # Create a BEM solution using the linear collocation approach
        bem = mne.make_bem_solution(surfaces)
        mne.write_bem_solution(bem_fname, bem)

        print(('\n*** BEM solution file %s written ***\n' % bem_fname))

        # add BEM figures to a Report
        report.add_bem_to_section(subject=sbj_id, subjects_dir=sbj_dir)
        report_filename = op.join(bem_dir, "BEM_report.html")
        print(('\n*** REPORT file %s written ***\n' % report_filename))
        print(report_filename)
        report.save(report_filename, open_browser=False, overwrite=True)
    else:
        bem = bem_fname
        print(('\n*** BEM solution file %s exists!!! ***\n' % bem_fname))

    return bem
コード例 #8
0
def __make_bem_individual(sub, fs_sub_dir, outdir, single_layers):
    """

    :param sub:
    :param fs_sub_dir:
    :param single_layers:
    :return:
    """

    #  see if file exists and skip if so
    if os.path.isfile(f'{outdir}/{sub}-5120-5120-5120-bem.fif'):
        print(f'{sub} has full file skipping')
        model = mne.read_bem_surfaces(f'{outdir}/{sub}-5120-5120-5120-bem.fif')
        solname = f'{outdir}/{sub}-5120-5120-5120-bem-sol.fif'
    # if single layers is true check for this, if not we want to try full model
    elif os.path.isfile(f'{outdir}/{sub}-5120-5120-5120-single-bem.fif'):
        if single_layers:
            print(f'{sub} has single layer file skipping')
            model = mne.read_bem_surfaces(
                f'{outdir}/{sub}-5120-5120-5120-single-bem.fif')
            solname = f'{outdir}/{sub}-5120-5120-5120-single-bem-sol.fif'
    else:

        #  make model
        try:
            model = mne.make_bem_model(sub, subjects_dir=fs_sub_dir)
            bemname = f'{outdir}/{sub}-5120-5120-5120-bem.fif'
            solname = f'{outdir}/{sub}-5120-5120-5120-bem-sol.fif'
        except:
            print('failed to make BEM model with input')
            if single_layers:
                try:
                    print(
                        'falling back to single layer model due to BEM suckiness'
                    )
                    model = mne.make_bem_model(sub,
                                               subjects_dir=fs_sub_dir,
                                               conductivity=[0.3])
                    bemname = f'{outdir}/{sub}-5120-5120-5120-single-bem.fif'
                    solname = f'{outdir}/{sub}-5120-5120-5120-single-bem-sol.fif'
                except:
                    print(f'oops that also failed for {sub}')
                    return ''

            else:
                print('wont allow single layer model so skipping')
                return ''

        # save model
        mne.write_bem_surfaces(bemname, model)  # save to source dir

    bem_sol = mne.make_bem_solution(model)  # make bem solution using model
    mne.write_bem_solution(solname, bem_sol)  # save as well to the outdir
    return solname
コード例 #9
0
def create_bem_sol(sbj_dir, sbj_id):
    import os.path as op
    import mne

    from mne.bem import make_watershed_bem
    from mne.report import Report

    report = Report()

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

    surf_name = 'inner_skull.surf'
    sbj_inner_skull_fname = op.join(bem_dir, sbj_id + '-' + surf_name)
    inner_skull_fname = op.join(bem_dir, surf_name)

    # check if bem-sol was created, if not creates the bem sol using C MNE
    bem_fname = op.join(bem_dir, '%s-5120-bem-sol.fif' % sbj_id)
    model_fname = op.join(bem_dir, '%s-5120-bem.fif' % sbj_id)

    if not op.isfile(bem_fname):
        # chek if inner_skull surf exists, if not BEM computation is
        # performed by MNE python functions mne.bem.make_watershed_bem
        if not (op.isfile(sbj_inner_skull_fname) or
                op.isfile(inner_skull_fname)):
            print inner_skull_fname + '---> FILE NOT FOUND!!!---> BEM computed'
            make_watershed_bem(sbj_id, sbj_dir, overwrite=True)
        else:
            print '\n*** inner skull %s surface exists!!!\n' % inner_skull_fname

        # Create a BEM model for a subject
        surfaces = mne.make_bem_model(sbj_id, ico=4, conductivity=[0.3],
                                      subjects_dir=sbj_dir)

        # Write BEM surfaces to a fiff file
        mne.write_bem_surfaces(model_fname, surfaces)

        # Create a BEM solution using the linear collocation approach
        bem = mne.make_bem_solution(surfaces)
        mne.write_bem_solution(bem_fname, bem)

        print '\n*** BEM solution file %s written ***\n' % bem_fname

        # add BEM figures to a Report
        report.add_bem_to_section(subject=sbj_id, subjects_dir=sbj_dir)
        report_filename = op.join(bem_dir, "BEM_report.html")
        print '\n*** REPORT file %s written ***\n' % report_filename
        print report_filename
        report.save(report_filename, open_browser=False, overwrite=True)
    else:
        bem = bem_fname
        print '\n*** BEM solution file %s exists!!! ***\n' % bem_fname

    return bem
コード例 #10
0
ファイル: test_bem.py プロジェクト: mdclarke/mne-python
def test_bem_model():
    """Test BEM model creation from Python with I/O"""
    tempdir = _TempDir()
    fname_temp = op.join(tempdir, "temp-bem.fif")
    for kwargs, fname in zip((dict(), dict(conductivity=[0.3])), [fname_bem_3, fname_bem_1]):
        model = make_bem_model("sample", ico=2, subjects_dir=subjects_dir, **kwargs)
        model_c = read_bem_surfaces(fname)
        _compare_bem_surfaces(model, model_c)
        write_bem_surfaces(fname_temp, model)
        model_read = read_bem_surfaces(fname_temp)
        _compare_bem_surfaces(model, model_c)
        _compare_bem_surfaces(model_read, model_c)
    assert_raises(
        ValueError, make_bem_model, "sample", conductivity=[0.3, 0.006], subjects_dir=subjects_dir  # bad conductivity
    )
コード例 #11
0
ファイル: test_bem.py プロジェクト: talcloud/mne-python
def test_bem_model():
    """Test BEM model creation from Python with I/O"""
    tempdir = _TempDir()
    fname_temp = op.join(tempdir, 'temp-bem.fif')
    for kwargs, fname in zip((dict(), dict(conductivity=[0.3])),
                             [fname_bem_3, fname_bem_1]):
        model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir,
                               **kwargs)
        model_c = read_bem_surfaces(fname)
        _compare_bem_surfaces(model, model_c)
        write_bem_surfaces(fname_temp, model)
        model_read = read_bem_surfaces(fname_temp)
        _compare_bem_surfaces(model, model_c)
        _compare_bem_surfaces(model_read, model_c)
    assert_raises(ValueError, make_bem_model, 'sample',  # bad conductivity
                  conductivity=[0.3, 0.006], subjects_dir=subjects_dir)
コード例 #12
0
ファイル: test_bem.py プロジェクト: Eric89GXL/mne-python
def test_make_bem_model(tmpdir):
    """Test BEM model creation from Python with I/O."""
    tempdir = str(tmpdir)
    fname_temp = op.join(tempdir, 'temp-bem.fif')
    for kwargs, fname in zip((dict(), dict(conductivity=[0.3])),
                             [fname_bem_3, fname_bem_1]):
        model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir,
                               **kwargs)
        model_c = read_bem_surfaces(fname)
        _compare_bem_surfaces(model, model_c)
        write_bem_surfaces(fname_temp, model)
        model_read = read_bem_surfaces(fname_temp)
        _compare_bem_surfaces(model, model_c)
        _compare_bem_surfaces(model_read, model_c)
    # bad conductivity
    with pytest.raises(ValueError, match='conductivity must be'):
        make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
コード例 #13
0
ファイル: bem.py プロジェクト: StanSStanman/bv2mne
def create_bem(subject, bem_dir=None, json_fname='default'):
    """ Create the BEM model from FreeSurfer files

    Parameters:
    ----------
    subject : str
        Name of the subject to calculate the BEM model

    Returns:
    -------
    surfaces : list of dict
        BEM surfaces
    bem : instance of ConductorModel
        BEM model
    -------
    """

    db_fs, _, db_mne = read_db_coords(json_fname)
    assert not (db_mne == None
                and bem_dir == None), 'Pleas specify the bem_dir location'
    if db_mne != None:
        _, _, _, _, _, bem_dir, _, _ = mne_directories(json_fname)
        bem_dir = bem_dir.format(subject)

    print('\n---------- Resolving BEM model and BEM soultion ----------\n')

    # database, project, db_mne, db_bv, db_fs = read_databases(json_fname)
    #
    # raw_dir, prep_dir, trans_dir, mri_dir, src_dir, bem_dir, fwd_dir, hga_dir = read_directories(json_fname)

    fname_bem_model = op.join(bem_dir, '{0}-bem-model.fif'.format(subject))
    fname_bem_sol = op.join(bem_dir, '{0}-bem-sol.fif'.format(subject))

    # Make bem model: single-shell model. Depends on anatomy only.
    bem_model = mne.make_bem_model(subject,
                                   ico=None,
                                   conductivity=[0.3],
                                   subjects_dir=op.join(db_fs))
    mne.write_bem_surfaces(fname_bem_model, bem_model)

    # Make bem solution. Depends on anatomy only.
    bem_sol = mne.make_bem_solution(bem_model)
    mne.write_bem_solution(fname_bem_sol, bem_sol)

    return bem_model, bem_sol
コード例 #14
0
def test_make_bem_model(tmpdir):
    """Test BEM model creation from Python with I/O."""
    fname_temp = tmpdir.join('temp-bem.fif')
    for kwargs, fname in zip((dict(), dict(conductivity=[0.3])),
                             [fname_bem_3, fname_bem_1]):
        model = make_bem_model('sample',
                               ico=2,
                               subjects_dir=subjects_dir,
                               **kwargs)
        model_c = read_bem_surfaces(fname)
        _compare_bem_surfaces(model, model_c)
        write_bem_surfaces(fname_temp, model)
        model_read = read_bem_surfaces(fname_temp)
        _compare_bem_surfaces(model, model_c)
        _compare_bem_surfaces(model_read, model_c)
    # bad conductivity
    with pytest.raises(ValueError, match='conductivity must be'):
        make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
コード例 #15
0
ファイル: getPsd.py プロジェクト: PajuRantala/Masters-thesis
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
コード例 #16
0
ファイル: test_bem.py プロジェクト: yu2shi4/mne-python
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)
コード例 #17
0
ファイル: test_bem.py プロジェクト: Eric89GXL/mne-python
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)
コード例 #18
0
ファイル: mne_surf2bem.py プロジェクト: Eric89GXL/mne-python
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-s", "--surf", dest="surf",
                      help="Surface in Freesurfer format", metavar="FILE")
    parser.add_option("-f", "--fif", dest="fif",
                      help="FIF file produced", metavar="FILE")
    parser.add_option("-i", "--id", dest="id", default=4,
                      help=("Surface Id (e.g. 4 sur head surface)"))

    options, args = parser.parse_args()

    if options.surf is None:
        parser.print_help()
        sys.exit(1)

    print("Converting %s to BEM FIF file." % options.surf)
    surf = mne.bem._surfaces_to_bem([options.surf], [int(options.id)],
                                    sigmas=[1])
    mne.write_bem_surfaces(options.fif, surf)
コード例 #19
0
def run():
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-s", "--surf", dest="surf",
                      help="Surface in Freesurfer format", metavar="FILE")
    parser.add_option("-f", "--fif", dest="fif",
                      help="FIF file produced", metavar="FILE")
    parser.add_option("-i", "--id", dest="id", default=4,
                      help=("Surface Id (e.g. 4 sur head surface)"))

    options, args = parser.parse_args()

    if options.surf is None:
        parser.print_help()
        sys.exit(1)

    print("Converting %s to BEM FIF file." % options.surf)
    points, tris = mne.read_surface(options.surf)
    points *= 1e-3
    surf = dict(coord_frame=5, id=int(options.id), nn=None, np=len(points),
                ntri=len(tris), rr=points, sigma=1, tris=tris)
    mne.write_bem_surfaces(options.fif, surf)
コード例 #20
0
ファイル: bem.py プロジェクト: brainets/bv2mne
def create_bem(json_fname, subject):
    """ Create the BEM model from FreeSurfer files

    Parameters:
    ----------
    subject : str
        Name of the subject to calculate the BEM model

    Returns:
    -------
    surfaces : list of dict
        BEM surfaces
    bem : instance of ConductorModel
        BEM model
    -------
    """

    print('\n---------- Resolving BEM model and BEM soultion ----------\n')


    database, project, db_mne, db_bv, db_fs = read_databases(json_fname)

    raw_dir, prep_dir, trans_dir, mri_dir, src_dir, bem_dir, fwd_dir, hga_dir = read_directories(json_fname)

    fname_bem_model = op.join(bem_dir.format(subject), '{0}-bem-model.fif'.format(subject))
    fname_bem_sol = op.join(bem_dir.format(subject), '{0}-bem-sol.fif'.format(subject))

    # Make bem model: single-shell model. Depends on anatomy only.
    bem_model = mne.make_bem_model(subject, ico=None, conductivity=[0.3], subjects_dir=op.join(db_fs, project))
    mne.write_bem_surfaces(fname_bem_model, bem_model)

    # Make bem solution. Depends on anatomy only.
    bem_sol = mne.make_bem_solution(bem_model)
    mne.write_bem_solution(fname_bem_sol, bem_sol)

    return bem_model, bem_sol
コード例 #21
0
def process_subject_anat(subject_id, force_recon_all=False):
    subject = "sub%03d" % subject_id
    print("Processing %s" % subject)

    t1_fname = op.join(study_path, 'ds117', subject, 'anatomy',
                       'highres001.nii.gz')
    log_fname = op.join(study_path, 'ds117', subject, 'my-recon-all.txt')
    subject_dir = op.join(subjects_dir, subject)
    if op.isdir(subject_dir):
        print('  Skipping reconstruction (folder exists)')
    else:
        print('  Running reconstruction (usually takes hours)')
        t0 = time.time()
        tee_output([
            'recon-all', '-all', '-s', subject, '-sd', subjects_dir, '-i',
            t1_fname
        ], log_fname)
        print('  Recon for %s complete in %0.1f hours' %
              (subject_id, (time.time() - t0) / 60. / 60.))

    # Move flash data
    fnames = glob.glob(
        op.join(study_path, 'ds117', subject, 'anatomy', 'FLASH', 'meflash*'))
    dst_flash = op.join(subjects_dir, subject, 'mri', 'flash')
    if not op.isdir(dst_flash):
        print('  Copying FLASH files')
        os.makedirs(dst_flash)
        for f_src in fnames:
            f_dst = op.basename(f_src).replace("meflash_", "mef")
            f_dst = op.join(dst_flash, f_dst)
            shutil.copy(f_src, f_dst)

    # Fix the headers for subject 19
    if subject_id == 19:
        print('  Fixing FLASH files for %s' % (subject, ))
        fnames = (['mef05_%d.mgz' % x
                   for x in range(7)] + ['mef30_%d.mgz' % x for x in range(7)])
        for fname in fnames:
            dest_fname = op.join(dst_flash, fname)
            dest_img = nib.load(op.splitext(dest_fname)[0] + '.nii.gz')

            # Copy the headers from subjects 1
            src_img = nib.load(
                op.join(subjects_dir, "sub001", "mri", "flash", fname))
            hdr = src_img.header
            fixed = nib.MGHImage(dest_img.get_data(), dest_img.affine, hdr)
            nib.save(fixed, dest_fname)

    # Make BEMs
    if not op.isfile("%s/%s/mri/flash/parameter_maps/flash5.mgz" %
                     (subjects_dir, subject)):
        print('  Converting flash MRIs')
        mne.bem.convert_flash_mris(subject,
                                   convert=False,
                                   subjects_dir=subjects_dir,
                                   verbose=False)
    if not op.isfile("%s/%s/bem/flash/outer_skin.surf" %
                     (subjects_dir, subject)):
        print('  Making BEM')
        mne.bem.make_flash_bem(subject,
                               subjects_dir=subjects_dir,
                               show=False,
                               verbose=False)
    for n_layers in (1, 3):
        extra = '-'.join(['5120'] * n_layers)
        fname_bem_surfaces = op.join(subjects_dir, subject, 'bem',
                                     '%s-%s-bem.fif' % (subject, extra))
        if not op.isfile(fname_bem_surfaces):
            print('  Setting up %d-layer BEM' % (n_layers, ))
            conductivity = (0.3, 0.006, 0.3)[:n_layers]
            try:
                bem_surfaces = mne.make_bem_model(subject,
                                                  ico=4,
                                                  conductivity=conductivity,
                                                  subjects_dir=subjects_dir)
            except RuntimeError as exp:
                print('  FAILED to create %d-layer BEM for %s: %s' %
                      (n_layers, subject, exp.args[0]))
                continue
            mne.write_bem_surfaces(fname_bem_surfaces, bem_surfaces)
        fname_bem = op.join(subjects_dir, subject, 'bem',
                            '%s-%s-bem-sol.fif' % (subject, extra))
        if not op.isfile(fname_bem):
            print('  Computing  %d-layer BEM solution' % (n_layers, ))
            bem_model = mne.read_bem_surfaces(fname_bem_surfaces)
            bem = mne.make_bem_solution(bem_model)
            mne.write_bem_solution(fname_bem, bem)

    # Create the surface source space
    fname_src = op.join(subjects_dir, subject, 'bem',
                        '%s-%s-src.fif' % (subject, spacing))
    if not op.isfile(fname_src):
        print('  Setting up source space')
        src = mne.setup_source_space(subject,
                                     spacing,
                                     subjects_dir=subjects_dir)
        mne.write_source_spaces(fname_src, src)
コード例 #22
0
def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None):
    this_env = copy.copy(os.environ)
    subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
    this_env['SUBJECTS_DIR'] = subjects_dir
    this_env['SUBJECT'] = subject
    if 'FREESURFER_HOME' not in this_env:
        raise RuntimeError('The FreeSurfer environment needs to be set up '
                           'for this script')
    incomplete = 'warn' if force else 'raise'
    subj_path = op.join(subjects_dir, subject)
    if not op.exists(subj_path):
        raise RuntimeError('%s does not exist. Please check your subject '
                           'directory path.' % subj_path)

    mri = 'T1.mgz' if op.exists(op.join(subj_path, 'mri', 'T1.mgz')) else 'T1'

    logger.info('1. Creating a dense scalp tessellation with mkheadsurf...')

    def check_seghead(surf_path=op.join(subj_path, 'surf')):
        surf = None
        for k in ['lh.seghead', 'lh.smseghead']:
            this_surf = op.join(surf_path, k)
            if op.exists(this_surf):
                surf = this_surf
                break
        return surf

    my_seghead = check_seghead()
    if my_seghead is None:
        run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri],
                       env=this_env)

    surf = check_seghead()
    if surf is None:
        raise RuntimeError('mkheadsurf did not produce the standard output '
                           'file.')

    dense_fname = '{0}/{1}/bem/{1}-head-dense.fif'.format(
        subjects_dir, subject)
    logger.info('2. Creating %s ...' % dense_fname)
    _check_file(dense_fname, overwrite)
    surf = mne.bem._surfaces_to_bem(
        [surf], [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
        incomplete=incomplete)[0]
    mne.write_bem_surfaces(dense_fname, surf)
    levels = 'medium', 'sparse'
    tris = [] if no_decimate else [30000, 2500]
    if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true':
        tris = [len(surf['tris'])]  # don't actually decimate
    for ii, (n_tri, level) in enumerate(zip(tris, levels), 3):
        logger.info('%i. Creating %s tessellation...' % (ii, level))
        logger.info('%i.1 Decimating the dense tessellation...' % ii)
        with ETSContext():
            points, tris = mne.decimate_surface(points=surf['rr'],
                                                triangles=surf['tris'],
                                                n_triangles=n_tri)
        dec_fname = dense_fname.replace('dense', level)
        logger.info('%i.2 Creating %s' % (ii, dec_fname))
        _check_file(dec_fname, overwrite)
        dec_surf = mne.bem._surfaces_to_bem(
            [dict(rr=points, tris=tris)],
            [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
            rescale=False,
            incomplete=incomplete)
        mne.write_bem_surfaces(dec_fname, dec_surf)
コード例 #23
0
fpath = mk_file_path('oct6-src.fif')
if os.path.exists(fpath):
    src = mne.read_source_spaces(fpath)
else:
    src = mne.setup_source_space(subject, spacing='oct6')
    mne.write_source_spaces(fpath, src)
print(src)

# Make bem model
# bem: boundary-element model (BEM)
fpath = mk_file_path('5120-5120-5120-bem.fif')
if os.path.exists(fpath):
    model = mne.read_bem_surfaces(fpath)
else:
    model = mne.make_bem_model(subject)
    mne.write_bem_surfaces(fpath, model)
print(model)

# Make bem solution
fpath = mk_file_path('5120-5120-5120-bem-sol.fif')
if os.path.exists(fpath):
    bem_sol = mne.read_bem_solution(fpath)
else:
    bem_sol = mne.make_bem_solution(model)
    mne.write_bem_solution(fpath, bem_sol)
print(bem_sol)

# Here we go
fwd = mne.make_forward_solution(raw.info, trans, src, bem_sol, eeg=False)
cov = mne.compute_covariance(epochs, method='empirical')
inv = mne.minimum_norm.make_inverse_operator(raw.info, fwd, cov, loose=0.2)
コード例 #24
0
def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None):
    this_env = copy.copy(os.environ)
    subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
    this_env['SUBJECTS_DIR'] = subjects_dir
    this_env['SUBJECT'] = subject
    if 'FREESURFER_HOME' not in this_env:
        raise RuntimeError('The FreeSurfer environment needs to be set up '
                           'for this script')
    incomplete = 'warn' if force else 'raise'
    subj_path = op.join(subjects_dir, subject)
    if not op.exists(subj_path):
        raise RuntimeError('%s does not exist. Please check your subject '
                           'directory path.' % subj_path)

    mri = 'T1.mgz' if op.exists(op.join(subj_path, 'mri', 'T1.mgz')) else 'T1'

    logger.info('1. Creating a dense scalp tessellation with mkheadsurf...')

    def check_seghead(surf_path=op.join(subj_path, 'surf')):
        surf = None
        for k in ['lh.seghead', 'lh.smseghead']:
            this_surf = op.join(surf_path, k)
            if op.exists(this_surf):
                surf = this_surf
                break
        return surf

    my_seghead = check_seghead()
    if my_seghead is None:
        run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri],
                       env=this_env)

    surf = check_seghead()
    if surf is None:
        raise RuntimeError('mkheadsurf did not produce the standard output '
                           'file.')

    bem_dir = op.join(subjects_dir, subject, 'bem')
    if not op.isdir(bem_dir):
        os.mkdir(bem_dir)
    dense_fname = op.join(bem_dir, '%s-head-dense.fif' % subject)
    logger.info('2. Creating %s ...' % dense_fname)
    _check_file(dense_fname, overwrite)
    surf = mne.bem._surfaces_to_bem(
        [surf], [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
        incomplete=incomplete)[0]
    mne.write_bem_surfaces(dense_fname, surf)
    levels = 'medium', 'sparse'
    tris = [] if no_decimate else [30000, 2500]
    if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true':
        tris = [len(surf['tris'])]  # don't actually decimate
    for ii, (n_tri, level) in enumerate(zip(tris, levels), 3):
        logger.info('%i. Creating %s tessellation...' % (ii, level))
        logger.info('%i.1 Decimating the dense tessellation...' % ii)
        with ETSContext():
            points, tris = mne.decimate_surface(points=surf['rr'],
                                                triangles=surf['tris'],
                                                n_triangles=n_tri)
        dec_fname = dense_fname.replace('dense', level)
        logger.info('%i.2 Creating %s' % (ii, dec_fname))
        _check_file(dec_fname, overwrite)
        dec_surf = mne.bem._surfaces_to_bem(
            [dict(rr=points, tris=tris)],
            [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1], rescale=False,
            incomplete=incomplete)
        mne.write_bem_surfaces(dec_fname, dec_surf)
コード例 #25
0
ファイル: Anatomist.py プロジェクト: RuKrei/SourceLoc
    def _make_bem_solution(self):
        bem_save_name = opj(self.fsrc, self.subject + "-single-shell-model")
        if not os.path.isfile(bem_save_name):
            try:
                bem = mne.make_bem_model(self.subject,
                                         ico=4,
                                         conductivity=[0.3],
                                         subjects_dir=self.subjects_dir,
                                         verbose=True)
                mne.write_bem_surfaces(bem_save_name, bem,
                                       overwrite=True)  #, overwrite=True)
            except Exception as e:
                print(
                    f"Failed to setup single shell BEM model for {self.subject} --> {e}"
                )
        bem_sol_filename = opj(self.fsrc,
                               self.subject + "-single-shell-BEM-sol.fif")
        if not os.path.isfile(bem_sol_filename):
            try:
                bem = mne.read_bem_surfaces(bem_save_name)
                bem_sol = mne.make_bem_solution(bem)
                mne.write_bem_solution(bem_sol_filename,
                                       bem_sol,
                                       overwrite=True)
            except Exception as e:
                print(
                    f"Failed to calculate BEM solution (single-shell) for {self.subject} --> {e}"
                )

        # BEM Solutions - 3-layer-BEM
        bem_save_name = opj(self.fsrc, self.subject + "-3-layer-BEM-model.fif")
        if not os.path.isfile(bem_save_name):
            try:
                bem = mne.make_bem_model(self.subject,
                                         ico=4,
                                         conductivity=[0.3, 0.006, 0.3],
                                         subjects_dir=self.subjects_dir,
                                         verbose=True)
                mne.write_bem_surfaces(bem_save_name, bem,
                                       overwrite=True)  #, overwrite=True)
            except Exception as e:
                print(
                    f"Failed to calculate 3-layer BEM model for {self.subject} --> {e}"
                )
        bem_sol_filename = opj(self.fsrc,
                               self.subject + "-3-layer-BEM-sol.fif")
        if not os.path.isfile(bem_sol_filename):
            try:
                bem = mne.read_bem_surfaces(bem_save_name)
                bem_sol = mne.make_bem_solution(bem)
                mne.write_bem_solution(bem_sol_filename,
                                       bem_sol,
                                       overwrite=True)
            except Exception as e:
                print(
                    f"Failed to calculate 3-layer BEM solution for {self.subject} --> {e}"
                )
                print(
                    "This is bad, please look into the freesurfer segmentation..."
                )
                print(
                    "Alternatively, you might be able to run the analysis with a single-shell-head-model (look into the configuration file"
                )
コード例 #26
0
The BEM only depends on the head geometry and conductivities. 
It is therefore independent from the MEG data and the head position.

The forward operator, commonly referred to as the gain or leadfield matrix
requires the co-registration later on. 
"""
conductivity = (0.3, 0.006, 0.3)  # for three layers

model = mne.make_bem_model(subjectName,
                           subjects_dir=subjectDir,
                           conductivity=conductivity,
                           verbose=None)

# save
bem2save = "".join([subjectName, '-bem.fif'])
mne.write_bem_surfaces(bem2save, model)

bem_sol = mne.make_bem_solution(model)
# save bem solution
bem2solution = "".join([subjectName, '-bemsol.fif'])
mne.write_bem_solution(bem2solution, bem_sol)
#%% STEP 3: CO-REGISTRATION STEP (MANUAL STEP)
mne.gui.coregistration(subject=subjectName, subjects_dir=subjectDir)
# at this stage you need to use GUI.

#%% MAKE FORWARD SOLUTION
pwd = os.getcwd()
trans = op.join(pwd, "".join([subjectName, '-trans.fif']))
info = mne.io.read_info(raw_fname)

import glob
コード例 #27
0
        # create BEM with watershed algorithm, this command does not work and
        # needs to be run manually with the command line given in
        # "Running subprocess: mri_watershed -h 25 ......."

        # Setup of Source Space
        src = mne.setup_source_space(SUBJECT, spacing=SRCSPACING,
                                     subjects_dir=SUBJECTS_DIR, add_dist=False)
        mne.viz.plot_bem(SUBJECT, SUBJECTS_DIR, src=src, show=True)
        text = input("Type in enter if the BEM is ok")
        if text == "":
            print(src)
            mne.write_source_spaces(SRCFILE, src, overwrite=True)
            # Compute the forward solution part 1 (MEG-data independent)
            model = mne.make_bem_model(subject=SUBJECT, ico=ICO_NTRI,
                                       conductivity=conductivity)
            mne.write_bem_surfaces(BEMFILE, model)
            bem = mne.make_bem_solution(model)
            mne.write_bem_solution(SOLFILE, bem)

    # find all _ssp files for this subject and do the following
    subject_folder = MEG_DIR + '/' + MEG_SUBJECT + '/'
    subject_files = os.listdir(subject_folder)

    for pieces in subject_files:
        if pieces[-8:] == '_ssp.fif': #find _ssp files
            final_path = subject_folder+pieces
            MEG_FILE = pieces
            MEG_SAVE = []
            if MEG_FILE[:4] == 'rest':
                MEG_SAVE = 'rest'
            elif MEG_FILE[:6] == 'speech':
コード例 #28
0
 def save_bem_model(self, bem_model):
     self._bem_model = bem_model
     mne.write_bem_surfaces(self.bem_model_path, bem_model)
     self.save_file_params(self.bem_model_path)
コード例 #29
0
# compute regularized noise covariance

noise_cov = mne.compute_covariance(
    epochs, tmax=0., method=['shrunk', 'empirical'])

fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info)



evoked = epochs.average()
evoked.plot()
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag')

# boundary-element model (BEM)
model = mne.make_bem_model('A')
mne.write_bem_surfaces(bem_model_file, model)

bem_sol = mne.make_bem_solution(model)
mne.write_bem_solution(bem_sol_file, bem_sol)

# You may wish to check things here to make sure things look ok
mne.viz.plot_bem(subject=subj, subjects_dir=subj_dir,
                 brain_surfaces='white', orientation='coronal')


mne.viz.plot_alignment(raw.info, fname_trans, subject=subj, dig=True,
                       meg=['helmet', 'sensors'], subjects_dir=subj_dir)

# make forward solution
# Make dipole grid on surface, save to fif
mne.set_config('SUBJECTS_DIR',subj_dir)
コード例 #30
0
def compute_LF_matrix(sbj_id, sbj_dir, raw_info, aseg, spacing, labels):
    import os.path as op
    import mne

    from mne.bem import make_watershed_bem
    from mne.report import Report

    from nipype.utils.filemanip import split_filename as split_f

    from neuropype_ephy.compute_fwd_problem import create_mixed_source_space

    report = Report()

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

    surf_name = 'inner_skull.surf'
    sbj_inner_skull_fname = op.join(bem_dir, sbj_id + '-' + surf_name)
    inner_skull_fname = op.join(bem_dir, surf_name)

    data_path, raw_fname, ext = split_f(raw_info['filename'])

    if aseg:
        fwd_filename = op.join(data_path, '%s-%s-aseg-fwd.fif'
                               % (raw_fname, spacing))
    else:
        fwd_filename = op.join(data_path, '%s-%s-fwd.fif'
                               % (raw_fname, spacing))

    # check if we have just created the fwd matrix
    if not op.isfile(fwd_filename):
        # check if bem-sol was created, if not creates the bem sol using C MNE
        bem_fname = op.join(bem_dir, '%s-5120-bem-sol.fif' % sbj_id)
        model_fname = op.join(bem_dir, '%s-5120-bem.fif' % sbj_id)
        if not op.isfile(bem_fname):
            # chek if inner_skull surf exists, if not BEM computation is
            # performed by MNE python functions mne.bem.make_watershed_bem
            if not (op.isfile(sbj_inner_skull_fname) or
                    op.isfile(inner_skull_fname)):
                print sbj_inner_skull_fname + '---> FILE NOT FOUND!!! ---> BEM is computed'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                make_watershed_bem(sbj_id, sbj_dir, overwrite=True)
            else:
                print '*** inner skull surface exists!!!'

            # Create a BEM model for a subject
            surfaces = mne.make_bem_model(sbj_id, ico=4, conductivity=[0.3],
                                          subjects_dir=sbj_dir)
            # Write BEM surfaces to a fiff file
            mne.write_bem_surfaces(model_fname, surfaces)

            # Create a BEM solution using the linear collocation approach
            bem = mne.make_bem_solution(surfaces)
            mne.write_bem_solution(bem_fname, bem)

            print '*** BEM solution file %s written ***' % bem_fname
            # add BEM figures to a Report
            report.add_bem_to_section(subject=sbj_id, subjects_dir=sbj_dir)
            report_filename = op.join(bem_dir, "BEM_report.html")
            print report_filename
            report.save(report_filename, open_browser=False, overwrite=True)
        else:
            bem = bem_fname
            print '*** BEM solution file %s exists!!!' % bem_fname

        # 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,
                                         fname=True,
                                         spacing=spacing.replace('-', ''),
                                         add_dist=False, overwrite=True,
                                         n_jobs=2)
            print '*** source space file %s written ***' % src_fname         
        else:
            print '*** source space file %s exists!!!' % src_fname
            src = mne.read_source_spaces(src_fname)

        if aseg:
            src = create_mixed_source_space(sbj_dir, sbj_id, spacing,
                                            labels, src)

        n = sum(src[i]['nuse'] for i in range(len(src)))
        print('il src space contiene %d spaces e %d vertici' % (len(src), n))

        # check if the co-registration file was created
        # if not raise an runtime error
        trans_fname = op.join(data_path, '%s-trans.fif' % raw_fname)
        if not op.isfile(trans_fname):
            raise RuntimeError('coregistration file %s NOT found!!!'
                               % trans_fname)

        # if all is ok creates the fwd matrix
        mne.make_forward_solution(raw_info, trans_fname, src, bem,
                                  fwd_filename,
                                  mindist=5.0, # ignore sources <= 0mm from inner skull
                                  meg=True, eeg=False,
                                  n_jobs=2,
                                  overwrite=True)

    else:
        print '*** FWD file %s exists!!!' % fwd_filename

    return fwd_filename
コード例 #31
0
        elif surf.hemi == 'rh':
            vertidx = np.where(src[1]['inuse'])[0]
        mayavi.mlab.points3d(surf.x[vertidx],
                             surf.y[vertidx],
                             surf.z[vertidx],
                             color=(1, 1, 0),
                             scale_factor=1.5)
        brain.save_image(sourceP_dir + subj_id + '_vertex.png')
    brain.close()

    #Compute BEM / forward model (aka electromagnetic current runs thusly...)
    conductivity = (0.3, )  # for single layer
    model = mne.make_bem_model(subject=subj_id,
                               ico=4,
                               conductivity=conductivity)
    mne.write_bem_surfaces(sourceP_dir + subj_id[:4] + '_bem_model.fif', model)

    bem_sol = mne.make_bem_solution(model)
    mne.write_bem_solution(sourceP_dir + subj_id[:4] + '_bem_sol.fif', bem_sol)

    infosrc = sensor_dir + subj_id[:4] + '_conds_freqs-ave.fif'
    fname = sourceP_dir + subj_id[:4] + '-fwd.fif'
    fwd = mne.make_forward_solution(info=infosrc,
                                    trans=trans,
                                    src=src,
                                    bem=bem_sol,
                                    fname=fname,
                                    meg=True,
                                    eeg=False,
                                    mindist=5.0,
                                    n_jobs=3)
コード例 #32
0
# Bands
band = (0, 4, 'Delta')

pprint(names)

# %%
## Load surfaces files

# Load bem
fname = names['fname_model']
if os.path.exists(fname):
    model = mne.read_bem_surfaces(fname)
else:
    model = mne.make_bem_model(subject)
    mne.write_bem_surfaces(fname, model)
# print(model)

# Load surface sources
fname = names['fname_src']
if os.path.exists(fname):
    src = mne.read_source_spaces(fname)
else:
    src = mne.setup_source_space(subject, spacing=spacing)
    mne.write_source_spaces(fname, src)
# print(src)

# Load bem solutions
fname = names['fname_bem']
if os.path.exists(fname):
    bem_sol = mne.read_bem_solution(fname)
コード例 #33
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser, _add_verbose_flag

    parser = get_optparser(__file__)

    parser.add_option("-s",
                      "--subject",
                      dest="subject",
                      help="Subject name (required)",
                      default=None)
    parser.add_option("--model",
                      dest="model",
                      help="Output file name. Use a name <dir>/<name>-bem.fif",
                      default=None,
                      type='string')
    parser.add_option('--ico',
                      dest='ico',
                      help='The surface ico downsampling to use, e.g. '
                      ' 5=20484, 4=5120, 3=1280. If None, no subsampling'
                      ' is applied.',
                      default=None,
                      type='int')
    parser.add_option('--brainc',
                      dest='brainc',
                      help='Defines the brain compartment conductivity. '
                      'The default value is 0.3 S/m.',
                      default=0.3,
                      type='float')
    parser.add_option('--skullc',
                      dest='skullc',
                      help='Defines the skull compartment conductivity. '
                      'The default value is 0.006 S/m.',
                      default=None,
                      type='float')
    parser.add_option('--scalpc',
                      dest='scalpc',
                      help='Defines the scalp compartment conductivity. '
                      'The default value is 0.3 S/m.',
                      default=None,
                      type='float')
    parser.add_option('--homog',
                      dest='homog',
                      help='Use a single compartment model (brain only) '
                      'instead a three layer one (scalp, skull, and '
                      ' brain). If this flag is specified, the options '
                      '--skullc and --scalpc are irrelevant.',
                      default=None,
                      action="store_true")
    parser.add_option('-d',
                      '--subjects-dir',
                      dest='subjects_dir',
                      help='Subjects directory',
                      default=None)
    _add_verbose_flag(parser)
    options, args = parser.parse_args()

    if options.subject is None:
        parser.print_help()
        sys.exit(1)

    subject = options.subject
    fname = options.model
    subjects_dir = options.subjects_dir
    ico = options.ico
    brainc = options.brainc
    skullc = options.skullc
    scalpc = options.scalpc
    homog = True if options.homog is not None else False
    verbose = True if options.verbose is not None else False
    # Parse conductivity option
    if homog is True:
        if skullc is not None:
            warn('Trying to set the skull conductivity for a single layer '
                 'model. To use a 3 layer model, do not set the --homog flag.')
        if scalpc is not None:
            warn('Trying to set the scalp conductivity for a single layer '
                 'model. To use a 3 layer model, do not set the --homog flag.')
        # Single layer
        conductivity = [brainc]
    else:
        if skullc is None:
            skullc = 0.006
        if scalpc is None:
            scalpc = 0.3
        conductivity = [brainc, skullc, scalpc]
    # Create source space
    bem_model = mne.make_bem_model(subject,
                                   ico=ico,
                                   conductivity=conductivity,
                                   subjects_dir=subjects_dir,
                                   verbose=verbose)
    # Generate filename
    if fname is None:
        n_faces = list(str(len(surface['tris'])) for surface in bem_model)
        fname = subject + '-' + '-'.join(n_faces) + '-bem.fif'
    else:
        if not (fname.endswith('-bem.fif') or fname.endswith('_bem.fif')):
            fname = fname + "-bem.fif"
            # Save to subject's directory
    subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
    fname = os.path.join(subjects_dir, subject, "bem", fname)
    # Save source space to file
    mne.write_bem_surfaces(fname, bem_model)
コード例 #34
0
ファイル: source_analysis.py プロジェクト: NathanCoppe/bv2mne
def forward_model(subject,
                  raw,
                  fname_trans,
                  src,
                  subjects_dir,
                  force_fixed=False,
                  surf_ori=False,
                  name='single-shell'):
    """construct forward model

    Parameters
    ----------
    subject : str
        The name of subject
    raw : instance of rawBTI
        functionnal data
    fname_trans : str
        The filename of transformation matrix
    src : instance of SourceSpaces | list
        Sources of each interest hemisphere
    subjects_dir : str
        The subjects directory
    force_fixed: Boolean
        Force fixed source orientation mode
    name : str
        Use to save output
       

    Returns
    -------
    fwd : instance of Forward
    -------
    Author : Alexandre Fabre
    """

    # Project 's directory
    subj_dir = '/hpc/comco/brovelli.a/db_mne/meg_te/'

    # files to save step
    fname_bem_model = subj_dir + '{0}/bem/{0}-{1}-bem.fif'.format(
        subject, name)
    fname_bem_sol = subj_dir + '{0}/bem/{0}-{1}-bem-sol.fif'.format(
        subject, name)
    fname_fwd = subj_dir + '{0}/fwd/{0}-{1}-fwd.fif'.format(subject, name)

    # Make bem model: single-shell model. Depends on anatomy only.
    model = mne.make_bem_model(
        subject,
        conductivity=[0.3],
        subjects_dir='/hpc/comco/brovelli.a/db_mne/meg_te/')
    mne.write_bem_surfaces(fname_bem_model, model)

    # Make bem solution. Depends on anatomy only.
    bem_sol = mne.make_bem_solution(model)
    mne.write_bem_solution(fname_bem_sol, bem_sol)

    # bem_sol=mne.read_bem_solution(fname_bem_sol)

    if len(src) == 2:
        # gather sources each the two hemispheres
        lh_src, rh_src = src
        src = lh_src + rh_src

    # Compute forward operator, commonly referred to as the gain or leadfield matrix.
    fwd = make_forward_solution(raw.info,
                                fname_trans,
                                src,
                                bem_sol,
                                fname_fwd,
                                mindist=0.0,
                                overwrite=True)

    # Set orientation of the source
    if force_fixed:
        # Force fixed
        fwd = mne.read_forward_solution(fname_fwd, force_fixed=True)
    elif surf_ori:
        # Surface normal
        fwd = mne.read_forward_solution(fname_fwd, surf_ori=True)
    else:
        # Free like a bird
        fwd = mne.read_forward_solution(fname_fwd)

    return fwd
コード例 #35
0
os.environ['SUBJECTS_DIR'] = subjects_dir_bids

# Run recon-all from FreeSurfer
run_subprocess(['recon-all', '-i', t1w_nii, '-s', '01', '-all'])

# Run make_scalp_surfaces ... use --force to prevent an error from
# topology defects
run_subprocess(['mne', 'make_scalp_surfaces', '-s', '01', '--overwrite',
                '--force'])

# Run watershed_bem
run_subprocess(['mne', 'watershed_bem', '-s', '01', '--overwrite'])

# Make BEM
model = mne.make_bem_model('01', conductivity=(0.3,), verbose=True)
mne.write_bem_surfaces(
    op.join(subjects_dir_bids, '01', 'bem', '01-5120-bem.fif'), model)
bem = mne.make_bem_solution(model, verbose=True)
mne.write_bem_solution(
    op.join(subjects_dir_bids, '01', 'bem', '01-5120-bem-sol.fif'), bem)

# Make a directory for our subject and move the forward model there
# NOTE: We need to adjust the subject id
sub_deri_dir = op.join(derivatives_dir, 'sub-01')
if not op.exists(sub_deri_dir):
    os.makedirs(sub_deri_dir)

old_forward = op.join(somato_path, 'MEG', 'somato',
                      'somato-meg-oct-6-fwd.fif')

fwd = mne.read_forward_solution(old_forward)
for ss in fwd['src']: