Beispiel #1
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
Beispiel #2
0
def process_subject_source_space(subject):
    # make BEMs using watershed bem
    # NOTE: Use MNE version >= 20 or set overwrite=True!
    # mne.bem.make_watershed_bem(subject,
    #                            subjects_dir=subjects_dir,
    #                            show=False,
    #                            verbose=False,
    #                            overwrite=True)

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

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

    # Create the surface source space
    src = mne.setup_source_space(subject, spacing, subjects_dir=subjects_dir)
    mne.write_source_spaces(src_fname, src, overwrite=True)
def createBem(subj):
    src = mne.setup_source_space(subj, n_jobs=2)
    subprocess.call(['mne', 'watershed_bem', '-s', subj])
    model = mne.make_bem_model(subj, conductivity=[0.3])
    bem = mne.make_bem_solution(model)
    mne.write_bem_solution(subj + '-5120-5120-5120-bem-sol.fif', bem)
    mne.viz.plot_bem(subj)
def run_forward(subject_id):
    subject = "sub%03d" % subject_id
    print("processing subject: %s" % subject)
    data_path = op.join(meg_dir, subject)

    fname_ave = op.join(data_path, '%s-ave.fif' % subject)
    fname_fwd = op.join(data_path, '%s-meg-%s-fwd.fif' % (subject, spacing))
    fname_trans = op.join(study_path, 'ds117', subject, 'MEG', '%s-trans.fif' % subject)

    src = mne.setup_source_space(subject, spacing=spacing,
                                 subjects_dir=subjects_dir, overwrite=True,
                                 n_jobs=1, add_dist=False)

    src_fname = op.join(subjects_dir, subject, '%s-src.fif' % spacing)
    mne.write_source_spaces(src_fname, src)

    bem_model = mne.make_bem_model(subject, ico=4, subjects_dir=subjects_dir,
                                   conductivity=(0.3,))
    bem = mne.make_bem_solution(bem_model)
    info = mne.read_evokeds(fname_ave, condition=0).info
    fwd = mne.make_forward_solution(info, trans=fname_trans, src=src, bem=bem,
                                    fname=None, meg=True, eeg=False,
                                    mindist=mindist, n_jobs=1, overwrite=True)
    fwd = mne.convert_forward_solution(fwd, surf_ori=True)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
Beispiel #5
0
def process_subject_bem(subject, subjects_dir='/cluster/transcend/MRI/WMA/recons', spacing='ico4'):
    try:
        bem_fname = op.join(subjects_dir,subject,'bem', '%s-src.fif' % subject)
        src_fname = op.join(subjects_dir, subject, 'bem', '%s-src.fif' % spacing)
        #headsurf_log = op.join(subjects_dir, subject, 'bem', subject + '_headsurf.log')

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


        if not os.path.isfile(src_fname):
            src = mne.setup_source_space(subject, spacing=spacing,
                                         subjects_dir=subjects_dir,
                                         add_dist=False)
            mne.write_source_spaces(src_fname, src=src, overwrite=True)
    except Exception as ee:
        error = str(ee)
        print(subject, error)
        pass
def 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)
def bem_computation(subject: str,
                    subjects_dir: str,
                    conductivity: tuple,
                    _subject_tree: Optional[SubjectTree] = None,
                    _priority: Optional[int] = None) -> mne.bem.ConductorModel:
    """Computes bem_ solution, uses :func:`nodestimation.project.read_or_write` decorator

        :param subject: patient`s ID
        :type subject: str
        :param subjects_dir: path to directory with patient`s files
        :type subjects_dir: str
        :param conductivity: the conductivities to use for each brain tissue shell. Single element for single-layer model or three elements for three-layer model
        :type conductivity: tuple
        :param _subject_tree: representation of patient`s files structure, default None
        :type _subject_tree: *look for SubjectTree in* :mod:`nodestimation.project.annotations` *, optional*
        :param _priority: if several files are read, which one to choose, if None, read all of them, default None
        :type _priority: int, optional
        :return: bem_ solution
        :rtype: mne.bem.ConductorModel_

        .. _imne.bem.ConductorModel:
        .. _mne.bem.ConductorModel:
        .. _bem: https://mne.tools/stable/generated/mne.bem.ConductorModel.html?highlight=conductormodel#mne.bem.ConductorModel
    """
    model = mne.make_bem_model(subject=subject,
                               conductivity=conductivity,
                               subjects_dir=subjects_dir)
    return mne.make_bem_solution(model)
Beispiel #8
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
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
Beispiel #10
0
def make_anony_fwd(subject,
                   dir_base,
                   subjects_dir,
                   conductivity=(0.3, 0.006, 0.3),
                   ico=4):
    import os.path as op
    from mne.io.constants import FIFF
    from mne.bem import _surfaces_to_bem, _check_bem_size
    import glob
    import mayavi.mlab as mlab

    for m in ['anonymi', 'defaced', 'mf']:
        print('Preparing fwd - method: %s' % m)
        bem_dir = op.join(dir_base, 'spatial', 'bems', m)
        inner_skull = op.join(bem_dir,
                              '%s_%s_inner_skull_surface' % (subject, m))
        outer_skull = op.join(bem_dir,
                              '%s_%s_outer_skull_surface' % (subject, m))
        outer_skin = op.join(bem_dir,
                             '%s_%s_outer_skin_surface' % (subject, m))
        surfaces = [inner_skull, outer_skull, outer_skin]
        ids = [
            FIFF.FIFFV_BEM_SURF_ID_BRAIN, FIFF.FIFFV_BEM_SURF_ID_SKULL,
            FIFF.FIFFV_BEM_SURF_ID_HEAD
        ]

        surfaces = _surfaces_to_bem(surfaces, ids, conductivity, ico)
        _check_bem_size(surfaces)

        bem = mne.make_bem_solution(surfaces)
        bem_fname = op.join(dir_base, 'spatial', 'bems', m,
                            '%s_%s-bem.fif' % (subject, m))
        mne.write_bem_solution(bem_fname, bem)

        files_epochs = glob.glob(
            op.join(dir_base, 'data', 'fif', '%s*' % subject))
        epo = mne.read_epochs(files_epochs[0])

        trans_fname = op.join(dir_base, 'spatial', 'fwd',
                              '%s-trans.fif' % subject)
        src_fname = op.join(dir_base, 'spatial', 'fwd', '%s-src.fif' % subject)

        fwd = mne.make_forward_solution(epo.info, trans_fname, src_fname,
                                        bem_fname)

        trans = mne.read_trans(trans_fname)
        mne.viz.plot_alignment(epo.info,
                               trans,
                               subject=subject,
                               surfaces=['head', 'brain'],
                               bem=bem,
                               subjects_dir=subjects_dir)
        mlab.show()

        mne.write_forward_solution(
            op.join(dir_base, 'spatial', 'bems', m,
                    '%s_%s-fwd.fif' % (subject, m)), fwd)
Beispiel #11
0
def run_forward(subject, session=None):
    deriv_path = config.get_subject_deriv_path(subject=subject,
                                               session=session,
                                               kind=config.get_kind())

    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.get_task(),
                                       acquisition=config.acq,
                                       run=None,
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    fname_evoked = op.join(deriv_path, bids_basename + '-ave.fif')
    fname_trans = op.join(deriv_path, 'sub-{}'.format(subject) + '-trans.fif')
    fname_fwd = op.join(deriv_path, bids_basename + '-fwd.fif')

    msg = f'Input: {fname_evoked}, Output: {fname_fwd}'
    logger.info(gen_log_message(message=msg, step=10, subject=subject,
                                session=session))
    # Find the raw data file
    # XXX : maybe simplify
    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.get_task(),
                                       acquisition=config.acq,
                                       run=config.get_runs()[0],
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    trans = get_head_mri_trans(bids_basename=bids_basename,
                               bids_root=config.bids_root)

    mne.write_trans(fname_trans, trans)

    src = mne.setup_source_space(subject, spacing=config.spacing,
                                 subjects_dir=config.get_fs_subjects_dir(),
                                 add_dist=False)

    evoked = mne.read_evokeds(fname_evoked, condition=0)

    # Here we only use 3-layers BEM only if EEG is available.
    if 'eeg' in config.ch_types:
        model = mne.make_bem_model(subject, ico=4,
                                   conductivity=(0.3, 0.006, 0.3),
                                   subjects_dir=config.get_fs_subjects_dir())
    else:
        model = mne.make_bem_model(subject, ico=4, conductivity=(0.3,),
                                   subjects_dir=config.get_fs_subjects_dir())

    bem = mne.make_bem_solution(model)
    fwd = mne.make_forward_solution(evoked.info, trans, src, bem,
                                    mindist=config.mindist)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
Beispiel #12
0
def repeat_coreg(subject,
                 subjects_dir=None,
                 subjects_dir_old=None,
                 overwrite=False,
                 verbose=None):
    """Repeat a mne coreg warping of an MRI.

    This is useful for example when bugs are fixed with
    :func:`mne.scale_mri`.

    .. warning:: This function should not be used when the parameters
                 in ``'MRI scaling parameters.cfg'`` have been changed.

    Parameters
    ----------
    subject : str
        The subject name.
    subjects_dir : str | None
        The subjects directory where the redone subject should go.
        The template/surrogate MRI must also be in this directory.
    subjects_dir_old : str | None
        The subjects directory where the old subject is.
        Can be None to use ``subjects_dir``.
    overwrite : bool
        If True (default False), overwrite an existing subject directory
        if it exists.
    verbose : str | None
        The verbose level to use.

    Returns
    -------
    out_dir : str
        The output subject directory.
    """
    subjects_dir = mne.utils.get_subjects_dir(subjects_dir)
    if subjects_dir_old is None:
        subjects_dir_old = subjects_dir
    config = mne.coreg.read_mri_cfg(subject, subjects_dir_old)
    n_params = config.pop('n_params')
    assert n_params in (3, 1), n_params
    out_dir = op.join(subjects_dir, subject)
    mne.coreg.scale_mri(subject_to=subject,
                        subjects_dir=subjects_dir,
                        labels=True,
                        annot=True,
                        overwrite=overwrite,
                        **config)
    for pattern in ('-5120', '-5120-5120-5120', 'inner_skull'):
        fname_bem = op.join(subjects_dir, subject, 'bem',
                            f'{subject}{pattern}-bem.fif')
        fname_sol = fname_bem[:-4] + '-sol.fif'
        if op.isfile(fname_bem) and not op.isfile(fname_sol):
            bem = mne.read_bem_surfaces(fname_bem)
            sol = mne.make_bem_solution(bem)
            mne.write_bem_solution(fname_sol, sol)
    return out_dir
def run_forward(subject, session=None):
    deriv_path = config.get_subject_deriv_path(subject=subject,
                                               session=session,
                                               kind=config.get_kind())

    bids_basename = BIDSPath(subject=subject,
                             session=session,
                             task=config.get_task(),
                             acquisition=config.acq,
                             run=None,
                             recording=config.rec,
                             space=config.space,
                             prefix=deriv_path,
                             check=False)

    fname_evoked = bids_basename.copy().update(kind='ave', extension='.fif')
    fname_trans = bids_basename.copy().update(kind='trans', extension='.fif')
    fname_fwd = bids_basename.copy().update(kind='fwd', extension='.fif')

    msg = f'Input: {fname_evoked}, Output: {fname_fwd}'
    logger.info(
        gen_log_message(message=msg, step=10, subject=subject,
                        session=session))
    # Find the raw data file
    trans = get_head_mri_trans(bids_basename=(bids_basename.copy().update(
        run=config.get_runs()[0], prefix=None)),
                               bids_root=config.bids_root)

    mne.write_trans(fname_trans, trans)

    src = mne.setup_source_space(subject,
                                 spacing=config.spacing,
                                 subjects_dir=config.get_fs_subjects_dir(),
                                 add_dist=False)

    evoked = mne.read_evokeds(fname_evoked, condition=0)

    # Here we only use 3-layers BEM only if EEG is available.
    if 'eeg' in config.ch_types:
        model = mne.make_bem_model(subject,
                                   ico=4,
                                   conductivity=(0.3, 0.006, 0.3),
                                   subjects_dir=config.get_fs_subjects_dir())
    else:
        model = mne.make_bem_model(subject,
                                   ico=4,
                                   conductivity=(0.3, ),
                                   subjects_dir=config.get_fs_subjects_dir())

    bem = mne.make_bem_solution(model)
    fwd = mne.make_forward_solution(evoked.info,
                                    trans,
                                    src,
                                    bem,
                                    mindist=config.mindist)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
Beispiel #14
0
def finalize_model(conductivity,src,trans,subjects_dir,raw_fname,ico):
    model = mne.make_bem_model(subject='sample', ico=ico,
    conductivity=conductivity,
    subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    fwd = mne.convert_forward_solution(mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=bem,
                                meg=False,eeg=True, mindist=5.0, n_jobs=2),force_fixed=True)

    del model
    return fwd
Beispiel #15
0
def run_forward(subject, session=None):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=config.get_task(),
                         acquisition=config.acq,
                         run=None,
                         recording=config.rec,
                         space=config.space,
                         extension='.fif',
                         datatype=config.get_datatype(),
                         root=config.deriv_root,
                         check=False)

    fname_evoked = bids_path.copy().update(suffix='ave')
    fname_trans = bids_path.copy().update(suffix='trans')
    fname_fwd = bids_path.copy().update(suffix='fwd')

    msg = f'Input: {fname_evoked}, Output: {fname_fwd}'
    logger.info(
        gen_log_message(message=msg, step=10, subject=subject,
                        session=session))

    # Retrieve the head -> MRI transformation matrix from the MRI sidecar file
    # in the input data, and save it to an MNE "trans" file in the derivatives
    # folder.
    trans = get_head_mri_trans(bids_path.copy().update(
        run=config.get_runs()[0], root=config.bids_root))
    mne.write_trans(fname_trans, trans)

    src = mne.setup_source_space(subject,
                                 spacing=config.spacing,
                                 subjects_dir=config.get_fs_subjects_dir(),
                                 add_dist=False)

    evoked = mne.read_evokeds(fname_evoked, condition=0)

    # Here we only use 3-layers BEM only if EEG is available.
    if 'eeg' in config.ch_types:
        model = mne.make_bem_model(subject,
                                   ico=4,
                                   conductivity=(0.3, 0.006, 0.3),
                                   subjects_dir=config.get_fs_subjects_dir())
    else:
        model = mne.make_bem_model(subject,
                                   ico=4,
                                   conductivity=(0.3, ),
                                   subjects_dir=config.get_fs_subjects_dir())

    bem = mne.make_bem_solution(model)
    fwd = mne.make_forward_solution(evoked.info,
                                    trans,
                                    src,
                                    bem,
                                    mindist=config.mindist)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
Beispiel #16
0
def forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname):
    #conductivity = (0.3, 0.006, 0.3)  # for three layers
    conductivity = (0.3,) # for single layer
    model = mne.make_bem_model(subject=subject, ico=4,
                            conductivity=conductivity,
                            subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    fwd = mne.make_forward_solution(fname_meg, trans=trans, src=src, bem=bem,
                                    meg=True, eeg=False, mindist=5.06)
    # print(fwd)
    mne.write_forward_solution(fwd_fname, fwd, overwrite=True, verbose=None)
Beispiel #17
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
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
Beispiel #19
0
def get_leadfield(subject,
                  raw_filename,
                  epochs_filename,
                  trans_filename,
                  conductivity=(0.3, 0.006, 0.3),
                  njobs=4,
                  bem_sub_path='bem',
                  sdir=None):
    """Compute leadfield with presets for this subject

    Args:    
        subject : str
            Name of freesurfer subject
        raw_filename : str
            Filename that points to the raw data for this lead field.
            This file will be used to extract a CTF transformation matrix
            and an info struct.
        epochs_filename : str
            Filename from which fiducial locations will be extracted.
        trans_filename : str
            Points to transformation file between fiducials and MRI.
        conductivity : 3-tuple of floats
            Conductivities for BEM model
        njobs: int
            Number of cores to paralellize over
        bem_sub_path: str
            Sub-path of freesurfer subject path where to read bem
            surfaces from

    Returns:   
        Tuple of (forward model, BEM model, source space)
    """
    if sdir is None:
        sdir = subjects_dir

    src = get_source_space(subject, sdir=sdir)
    model = make_bem_model(subject=subject,
                           ico=None,
                           conductivity=conductivity,
                           subjects_dir=sdir,
                           bem_sub_path=bem_sub_path)
    bem = mne.make_bem_solution(model)
    info = get_info(raw_filename, epochs_filename)
    fwd = mne.make_forward_solution(info,
                                    trans=trans_filename,
                                    src=src,
                                    bem=bem,
                                    meg=True,
                                    eeg=False,
                                    mindist=2.5,
                                    n_jobs=njobs)
    return fwd, bem, fwd['src']
Beispiel #20
0
def make_bem_solutions(subject, subjects_dir):
    command = mne.make_bem_model(subject,
                                 ico=4,
                                 conductivity=[0.3],
                                 subjects_dir=subjects_dir,
                                 verbose=None)

    solution = mne.make_bem_solution(command, verbose=None)

    filename = subject + '-5120-bem-sol.fif'
    saveSolution_path = subjects_dir + subject + '/bem/' + filename
    mne.write_bem_solution(saveSolution_path, solution)
    '''   
Beispiel #21
0
def repeat_coreg(subject,
                 subjects_dir=None,
                 subjects_dir_old=None,
                 overwrite=False,
                 verbose=None):
    """Repeat a mne coreg warping of an MRI.

    This is useful for example when bugs are fixed with
    :func:`mne.scale_mri`.

    Parameters
    ----------
    subject : str
        The subject name.
    subjects_dir : str | None
        The subjects directory where the redone subject should go.
        The template/surrogate MRI must also be in this directory.
    subjects_dir_old : str | None
        The subjects directory where the old subject is.
        Can be None to use ``subjects_dir``.
    overwrite : bool
        If True (default False), overwrite an existing subject directory
        if it exists.
    verbose : str | None
        The verbose level to use.

    Returns
    -------
    out_dir : str
        The output subject directory.
    """
    subjects_dir = mne.utils.get_subjects_dir(subjects_dir)
    if subjects_dir_old is None:
        subjects_dir_old = subjects_dir
    config = mne.coreg.read_mri_cfg(subject, subjects_dir_old)
    n_params = config.pop('n_params')
    assert n_params in (3, 1), n_params
    out_dir = op.join(subjects_dir, subject)
    mne.coreg.scale_mri(subject_to=subject,
                        subjects_dir=subjects_dir,
                        labels=False,
                        annot=False,
                        overwrite=overwrite,
                        **config)
    sol_file = op.join(subjects_dir, subject, 'bem',
                       '%s-5120-bem-sol.fif' % subject)
    if not op.isfile(sol_file):
        print('  Computing BEM solution')
        sol = mne.make_bem_solution(sol_file[:-8] + '.fif')
        mne.write_bem_solution(sol_file, sol)
    return out_dir
Beispiel #22
0
def process_subject_bem(subject, spacing='ico5'):
    mne.bem.make_watershed_bem(subject=subject, subjects_dir=subjects_dir, overwrite=True, volume='T1', atlas=True,
                       gcaatlas=False, preflood=None)
    conductivity = (0.3,)
    model = mne.make_bem_model(subject=subject, ico=4,
                               conductivity=conductivity,
                               subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    src = mne.setup_source_space(subject, spacing=spacing,
                                 subjects_dir=subjects_dir,
                                 add_dist=False)
    bem_fname = op.join(subjects_dir,subject,'bem', '%s-src.fif' % subject)
    src_fname = op.join(subjects_dir, subject, 'bem', '%s-src.fif' % spacing)
    mne.write_bem_solution(bem_fname, bem=bem)
    mne.write_source_spaces(src_fname, src=src)
Beispiel #23
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)
Beispiel #24
0
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
def gen_fwd(subject, conductivity, info):

    src = mne.read_source_spaces(subject_dir + '/sub-' + subject + '_free' +
                                 '/sub-' + subject + '_free-src.fif')
    trans = subject_dir + '/sub-' + subject + '_free' + '/sub-' + subject + '_free-trans.fif'
    model = mne.make_bem_model(subject='sub-' + subject + '_free',
                               ico=4,
                               conductivity=conductivity,
                               subjects_dir=subject_dir)
    bem = mne.make_bem_solution(model)
    return mne.make_forward_solution(info,
                                     trans=trans,
                                     src=src,
                                     bem=bem,
                                     eeg=True,
                                     meg=False,
                                     mindist=5.0,
                                     n_jobs=2)
Beispiel #26
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)
Beispiel #27
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
Beispiel #28
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser, _add_verbose_flag

    parser = get_optparser(__file__)

    parser.add_option('--bem',
                      dest='bem_fname',
                      help='The name of the file containing the '
                      'triangulations of the BEM surfaces and the '
                      'conductivities of the compartments. The standard '
                      'ending for this file is -bem.fif.',
                      metavar="FILE")
    parser.add_option('--sol',
                      dest='bem_sol_fname',
                      help='The name of the resulting file containing BEM '
                      'solution (geometry matrix). It uses the linear '
                      'collocation approach. The file should end with '
                      '-bem-sof.fif.',
                      metavar='FILE',
                      default=None)
    _add_verbose_flag(parser)

    options, args = parser.parse_args()
    bem_fname = options.bem_fname
    bem_sol_fname = options.bem_sol_fname
    verbose = True if options.verbose is not None else False

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

    if bem_sol_fname is None:
        base, _ = os.path.splitext(bem_fname)
        bem_sol_fname = base + '-sol.fif'

    bem_model = mne.read_bem_surfaces(bem_fname,
                                      patch_stats=False,
                                      verbose=verbose)
    bem_solution = mne.make_bem_solution(bem_model, verbose=verbose)
    mne.write_bem_solution(bem_sol_fname, bem_solution)
Beispiel #29
0
def make_bem_and_source_space(subject, subjects_dir, dir_base):
    # BEM
    mne.bem.make_watershed_bem(subject, subjects_dir, volume='T1', show=True)

    conductivity = (0.3, 0.006, 0.3)
    model = mne.make_bem_model(subject=subject,
                               ico=4,
                               conductivity=conductivity,
                               subjects_dir=subjects_dir)

    bem = mne.make_bem_solution(model)
    mne.write_bem_solution(
        op.join(dir_base, 'spatial', 'fwd', '%s-bem.fif' % subject), bem)

    # Anatomical Source Space
    src = mne.setup_source_space(subject,
                                 spacing='oct6',
                                 subjects_dir=subjects_dir)

    mne.write_source_spaces(
        op.join(dir_base, 'spatial', 'fwd', '%s-src.fif' % subject), src)
Beispiel #30
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)
Beispiel #31
0
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
Beispiel #32
0
# preproc_dir = "G:/TSM_test/NEM_proc/"
# trans_dir = "G:/TSM_test/NEM_proc/" # enter your special trans file folder here
# meg_dir = "G:/TSM_test/NEM_proc/"
meg_dir = "V:/Alle/Müller-Voggel/anne/"
mri_dir = "D:/freesurfer/subjects/"
sub_dict = {"TSM_02":"BAE51","TSM_07":"DTN25_fa","TSM_17":"EAH91_fa","TSM_19":"HHH42","TSM_26":"LEN04_fa",
            "TSM_22":"NAI16_fa","TSM_16":"NIC98","TSM_11":"NLK24_fa","TSM_04":"NLL75_fa","TSM_21":"NNE17",
            "TSM_15":"NOI26_fa","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"}

## prep fsaverage

# build BEM model for fsaverage (as boundary for source space creation) --- only needed for volume or mixed source spaces
bem_model = mne.make_bem_model("fsaverage", subjects_dir=mri_dir, ico=5, conductivity=[0.3])
bem = mne.make_bem_solution(bem_model)
mne.write_bem_solution("{dir}fsaverage-bem.fif".format(dir=meg_dir),bem)
mne.viz.plot_bem(subject="fsaverage", subjects_dir=mri_dir, brain_surfaces='white', orientation='coronal')

# build fs_average mixed 'oct6' surface source space & save (to use as morph target later)
fs_src = mne.setup_source_space("fsaverage", spacing='oct6', surface="white", subjects_dir=mri_dir, n_jobs=6)
# print out the number of spaces and points
n = sum(fs_src[i]['nuse'] for i in range(len(fs_src)))
print('the fs_src space contains %d spaces and %d points' % (len(fs_src), n))
fs_src.plot(subjects_dir=mri_dir)
# save the surface source space
fs_src.save("{}fsaverage_oct6_mix-src.fif".format(meg_dir), overwrite=True)
del fs_src


## prep subjects
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
Beispiel #34
0
def test_iterable():
    """Test iterable support for simulate_raw."""
    raw = read_raw_fif(raw_fname_short).load_data()
    raw.pick_channels(raw.ch_names[:10] + ['STI 014'])
    src = setup_volume_source_space(
        pos=dict(rr=[[-0.05, 0, 0], [0.1, 0, 0]],
                 nn=[[0, 1., 0], [0, 1., 0]]))
    assert src.kind == 'discrete'
    trans = None
    sphere = make_sphere_model(head_radius=None, info=raw.info)
    tstep = 1. / raw.info['sfreq']
    rng = np.random.RandomState(0)
    vertices = np.array([1])
    data = rng.randn(1, 2)
    stc = VolSourceEstimate(data, vertices, 0, tstep)
    assert isinstance(stc.vertices, np.ndarray)
    with pytest.raises(ValueError, match='at least three time points'):
        simulate_raw(raw.info, stc, trans, src, sphere, None)
    data = rng.randn(1, 1000)
    n_events = (len(raw.times) - 1) // 1000 + 1
    stc = VolSourceEstimate(data, vertices, 0, tstep)
    assert isinstance(stc.vertices, np.ndarray)
    with catch_logging() as log:
        with pytest.deprecated_call():
            raw_sim = simulate_raw(raw, stc, trans, src, sphere, None,
                                   verbose=True)
    log = log.getvalue()
    assert 'Making 15 copies of STC' in log
    assert_allclose(raw.times, raw_sim.times)
    events = find_events(raw_sim, initial_event=True)
    assert len(events) == n_events
    assert_array_equal(events[:, 2], 1)

    # Degenerate STCs
    with pytest.raises(RuntimeError,
                       match=r'Iterable did not provide stc\[0\]'):
        simulate_raw(raw.info, [], trans, src, sphere, None)
    with pytest.raises(RuntimeError,
                       match=r'Iterable did not provide stc\[2\].*duration'):
        with pytest.deprecated_call():
            simulate_raw(raw, [stc, stc], trans, src, sphere, None)
    # tuple with ndarray
    event_data = np.zeros(len(stc.times), int)
    event_data[0] = 3
    raw_new = simulate_raw(raw.info, [(stc, event_data)] * 15,
                           trans, src, sphere, None, first_samp=raw.first_samp)
    assert raw_new.n_times == 15000
    raw_new.crop(0, raw_sim.times[-1])
    _assert_iter_sim(raw_sim, raw_new, 3)
    with pytest.raises(ValueError, match='event data had shape .* but need'):
        simulate_raw(raw.info, [(stc, event_data[:-1])], trans, src, sphere,
                     None)
    with pytest.raises(ValueError, match='stim_data in a stc tuple .* int'):
        simulate_raw(raw.info, [(stc, event_data * 1.)], trans, src, sphere,
                     None)

    # iterable
    def stc_iter():
        stim_data = np.zeros(len(stc.times), int)
        stim_data[0] = 4
        ii = 0
        while ii < 100:
            ii += 1
            yield (stc, stim_data)
    with pytest.deprecated_call():
        raw_new = simulate_raw(raw, stc_iter(), trans, src, sphere, None)
    _assert_iter_sim(raw_sim, raw_new, 4)

    def stc_iter_bad():
        ii = 0
        while ii < 100:
            ii += 1
            yield (stc, 4, 3)
    with pytest.raises(ValueError, match='stc, if tuple, must be length'):
        simulate_raw(raw.info, stc_iter_bad(), trans, src, sphere, None)
    _assert_iter_sim(raw_sim, raw_new, 4)

    def stc_iter_bad():
        ii = 0
        while ii < 100:
            ii += 1
            stc_new = stc.copy()
            stc_new.vertices = np.array([ii % 2])
            yield stc_new
    with pytest.raises(RuntimeError, match=r'Vertex mismatch for stc\[1\]'):
        simulate_raw(raw.info, stc_iter_bad(), trans, src, sphere, None)

    # Forward omission
    vertices = np.array([0, 1])
    data = rng.randn(2, 1000)
    stc = VolSourceEstimate(data, vertices, 0, tstep)
    assert isinstance(stc.vertices, np.ndarray)
    # XXX eventually we should support filtering based on sphere radius, too,
    # by refactoring the code in source_space.py that does it!
    surf = _get_ico_surface(3)
    surf['rr'] *= 60  # mm
    model = _surfaces_to_bem([surf], [FIFF.FIFFV_BEM_SURF_ID_BRAIN], [0.3])
    bem = make_bem_solution(model)
    with pytest.warns(RuntimeWarning,
                      match='1 of 2 SourceEstimate vertices'):
        simulate_raw(raw, stc, trans, src, bem, None)
    subject='fsaverage', subjects_dir=subjects_dir, add_dist=False,
    spacing='oct6', overwrite=True)

# now we morph it onto the subject.

src_subject = mne.morph_source_spaces(
    src_fsaverage, subject, subjects_dir=subjects_dir)

##############################################################################
# For the same reason `ico` has to be set to `None` when computing the bem.
# The headshape is not computed with MNE and has a none standard configuration.

bems = mne.make_bem_model(subject, conductivity=(0.3,),
                          subjects_dir=subjects_dir,
                          ico=None)  # ico = None for morphed SP.
bem_sol = mne.make_bem_solution(bems)
bem_sol['surfs'][0]['coord_frame'] = 5

##############################################################################
# Now we can read the channels that we want to map to the cortical locations.
# Then we can compute the forward solution.

info = hcp.read_info(subject=subject, hcp_path=hcp_path, data_type='rest',
                     run_index=0)

picks = mne.pick_types(info, meg=True, ref_meg=False)
info = mne.pick_info(info, picks)

fwd = mne.make_forward_solution(info, trans=head_mri_t, bem=bem_sol,
                                src=src_subject)
mag_map = mne.sensitivity_map(
Beispiel #36
0
def make_mne_forward(anatomy_path,
                     subject,
                     recordings_path,
                     info_from=(('data_type', 'rest'), ('run_index', 0)),
                     fwd_params=None, src_params=None,
                     hcp_path=op.curdir, n_jobs=1):
    """"
    Convenience script for conducting standard MNE analyses.

    Parameters
    ----------
    subject : str
        The subject name.
    hcp_path : str
        The directory containing the HCP data.
    recordings_path : str
        The path where MEG data and transformations are stored.
    anatomy_path : str
        The directory containing the extracted HCP subject data.
    info_from : tuple of tuples | dict
        The reader info concerning the data from which sensor positions
        should be read.
        Must not be empty room as sensor positions are in head
        coordinates for 4D systems, hence not available in that case.
        Note that differences between the sensor positions across runs
        are smaller than 12 digits, hence negligible.
    fwd_params : None | dict
        The forward parameters
    src_params : None | dict
        The src params. Defaults to:

        dict(subject='fsaverage', fname=None, spacing='oct6', n_jobs=2,
             surface='white', subjects_dir=anatomy_path, add_dist=True)
    hcp_path : str
        The prefix of the path of the HCP data.
    n_jobs : int
        The number of jobs to use in parallel.
    """
    if isinstance(info_from, tuple):
        info_from = dict(info_from)

    head_mri_t = mne.read_trans(
        op.join(recordings_path, subject, '{}-head_mri-trans.fif'.format(
            subject)))

    src_params = _update_dict_defaults(
        src_params,
        dict(subject='fsaverage', fname=None, spacing='oct6', n_jobs=n_jobs,
             surface='white', subjects_dir=anatomy_path, add_dist=True))

    add_source_space_distances = False
    if src_params['add_dist']:  # we want the distances on the morphed space
        src_params['add_dist'] = False
        add_source_space_distances = True

    src_fsaverage = mne.setup_source_space(**src_params)
    src_subject = mne.morph_source_spaces(
        src_fsaverage, subject, subjects_dir=anatomy_path)

    if add_source_space_distances:  # and here we compute them post hoc.
        src_subject = mne.add_source_space_distances(
            src_subject, n_jobs=n_jobs)

    bems = mne.make_bem_model(subject, conductivity=(0.3,),
                              subjects_dir=anatomy_path,
                              ico=None)  # ico = None for morphed SP.
    bem_sol = mne.make_bem_solution(bems)

    info = read_info_hcp(subject=subject, hcp_path=hcp_path, **info_from)
    picks = _pick_data_channels(info, with_ref_meg=False)
    info = pick_info(info, picks)

    # here we assume that as a result of our MNE-HCP processing
    # all other transforms in info are identity
    for trans in ['dev_head_t', 'ctf_head_t']:
        #  'dev_ctf_t' is not identity
        assert np.sum(info[trans]['trans'] - np.eye(4)) == 0

    fwd = mne.make_forward_solution(
        info, trans=head_mri_t, bem=bem_sol, src=src_subject,
        n_jobs=n_jobs)

    return dict(fwd=fwd, src_subject=src_subject,
                src_fsaverage=src_fsaverage,
                bem_sol=bem_sol, info=info)
# ``use_precomputed=False`` in the beginning of this script to build the
# forward solution from scratch. The head surfaces for constructing a BEM
# solution are read from a file. Since the data only contains MEG channels, we
# only need the inner skull surface for making the forward solution. For more
# information: :ref:`CHDBBCEJ`, :func:`mne.setup_source_space`,
# :ref:`create_bem_model`, :func:`mne.bem.make_watershed_bem`.
if use_precomputed:
    fwd_fname = op.join(data_path, 'MEG', 'bst_auditory',
                        'bst_auditory-meg-oct-6-fwd.fif')
    fwd = mne.read_forward_solution(fwd_fname)
else:
    src = mne.setup_source_space(subject, spacing='ico4',
                                 subjects_dir=subjects_dir, overwrite=True)
    model = mne.make_bem_model(subject=subject, ico=4, conductivity=[0.3],
                               subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    fwd = mne.make_forward_solution(evoked_std.info, trans=trans, src=src,
                                    bem=bem)

inv = mne.minimum_norm.make_inverse_operator(evoked_std.info, fwd, cov)
snr = 3.0
lambda2 = 1.0 / snr ** 2
del fwd

###############################################################################
# The sources are computed using dSPM method and plotted on an inflated brain
# surface. For interactive controls over the image, use keyword
# ``time_viewer=True``.
# Standard condition.
stc_standard = mne.minimum_norm.apply_inverse(evoked_std, inv, lambda2, 'dSPM')
brain = stc_standard.plot(subjects_dir=subjects_dir, subject=subject,
    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)

##############################################################################
# And for OPM:
Beispiel #39
0
def compute_forward_stack(subjects_dir,
                          subject,
                          recordings_path,
                          info_from=(('data_type', 'rest'), ('run_index', 0)),
                          fwd_params=None, src_params=None,
                          hcp_path=op.curdir, n_jobs=1, verbose=None):
    """
    Convenience function for conducting standard MNE analyses.

    .. note::
       this function computes bem solutions, source spaces and forward models
       optimized for connectivity computation, i.e., the fsaverage space
       is morphed onto the subject's space.

    Parameters
    ----------
    subject : str
        The subject name.
    hcp_path : str
        The directory containing the HCP data.
    recordings_path : str
        The path where MEG data and transformations are stored.
    subjects_dir : str
        The directory containing the extracted HCP subject data.
    info_from : tuple of tuples | dict
        The reader info concerning the data from which sensor positions
        should be read.
        Must not be empty room as sensor positions are in head
        coordinates for 4D systems, hence not available in that case.
        Note that differences between the sensor positions across runs
        are smaller than 12 digits, hence negligible.
    fwd_params : None | dict
        The forward parameters
    src_params : None | dict
        The src params. Defaults to:

        dict(subject='fsaverage', fname=None, spacing='oct6', n_jobs=2,
             surface='white', subjects_dir=subjects_dir, add_dist=True)
    hcp_path : str
        The prefix of the path of the HCP data.
    n_jobs : int
        The number of jobs to use in parallel.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see mne.verbose)

    Returns
    -------
    out : dict
        A dictionary with the following keys:
            fwd : instance of mne.Forward
                The forward solution.
            src_subject : instance of mne.SourceSpace
                The source model on the subject's surface
            src_fsaverage : instance of mne.SourceSpace
                The source model on fsaverage's surface
            bem_sol : dict
                The BEM.
            info : instance of mne.io.meas_info.Info
                The actual measurement info used.
    """
    if isinstance(info_from, tuple):
        info_from = dict(info_from)

    head_mri_t = mne.read_trans(
        op.join(recordings_path, subject, '{}-head_mri-trans.fif'.format(
            subject)))
    
    src_defaults = dict(subject='fsaverage', spacing='oct6', n_jobs=n_jobs,
             surface='white', subjects_dir=subjects_dir, add_dist=True)
    if 'fname' in mne.fixes._get_args(mne.setup_source_space):
        # needed for mne-0.14 and below
        src_defaults.update(dict(fname=None))
    else:
        # remove 'fname' argument (if necessary) when using mne-0.15+
        if 'fname' in src_params:
            del src_params['fname']
    src_params = _update_dict_defaults(src_params, src_defaults)

    add_source_space_distances = False
    if src_params['add_dist']:  # we want the distances on the morphed space
        src_params['add_dist'] = False
        add_source_space_distances = True

    src_fsaverage = mne.setup_source_space(**src_params)
    src_subject = mne.morph_source_spaces(
        src_fsaverage, subject, subjects_dir=subjects_dir)

    if add_source_space_distances:  # and here we compute them post hoc.
        src_subject = mne.add_source_space_distances(
            src_subject, n_jobs=n_jobs)

    bems = mne.make_bem_model(subject, conductivity=(0.3,),
                              subjects_dir=subjects_dir,
                              ico=None)  # ico = None for morphed SP.
    bem_sol = mne.make_bem_solution(bems)
    bem_sol['surfs'][0]['coord_frame'] = 5

    info = read_info(subject=subject, hcp_path=hcp_path, **info_from)
    picks = _pick_data_channels(info, with_ref_meg=False)
    info = pick_info(info, picks)

    # here we assume that as a result of our MNE-HCP processing
    # all other transforms in info are identity
    for trans in ['dev_head_t', 'ctf_head_t']:
        #  'dev_ctf_t' is not identity
        assert np.sum(info[trans]['trans'] - np.eye(4)) == 0

    fwd = mne.make_forward_solution(
        info, trans=head_mri_t, bem=bem_sol, src=src_subject,
        n_jobs=n_jobs)

    return dict(fwd=fwd, src_subject=src_subject,
                src_fsaverage=src_fsaverage,
                bem_sol=bem_sol, info=info)