Ejemplo n.º 1
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)
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
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)
def run_forward(subject, session=None):
    print("Processing subject: %s" % subject)

    # Construct the search path for the data file. `sub` is mandatory
    subject_path = op.join('sub-{}'.format(subject))
    # `session` is optional
    if session is not None:
        subject_path = op.join(subject_path, 'ses-{}'.format(session))

    subject_path = op.join(subject_path, config.kind)

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

    fpath_deriv = op.join(config.bids_root, 'derivatives',
                          config.PIPELINE_NAME, subject_path)
    fname_evoked = \
        op.join(fpath_deriv, bids_basename + '-ave.fif')

    print("Input: ", fname_evoked)

    fname_trans = \
        op.join(fpath_deriv, 'sub-{}'.format(subject) + '-trans.fif')

    fname_fwd = \
        op.join(fpath_deriv, bids_basename + '-fwd.fif')

    print("Output: ", fname_fwd)

    # Find the raw data file
    # XXX : maybe simplify
    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.task,
                                       acquisition=config.acq,
                                       run=config.runs[0],
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    data_dir = op.join(config.bids_root, subject_path)
    search_str = op.join(data_dir, bids_basename) + '_' + config.kind + '*'
    fnames = sorted(glob.glob(search_str))
    fnames = [f for f in fnames if op.splitext(f)[1] in mne_bids_readers]

    if len(fnames) >= 1:
        bids_fname = fnames[0]
    elif len(fnames) == 0:
        raise ValueError('Could not find input data file matching: '
                         '"{}"'.format(search_str))

    bids_fname = op.basename(bids_fname)

    mne.gui.coregistration()
    trans = get_head_mri_trans(bids_fname=bids_fname,
                               bids_root=config.bids_root)

    mne.write_trans(fname_trans, trans)

    # create the boundary element model (BEM) once
    from mne.bem import make_watershed_bem, make_flash_bem

    if 'eeg' in config.ch_types or config.kind == 'eeg':
        make_flash_bem(subject, subjects_dir=subjects_dir, overwrite=True)
    else:
        mne.bem.make_watershed_bem(subject,
                                   subjects_dir=subjects_dir,
                                   overwrite=True)
Ejemplo n.º 5
0
def _prepare_forward(cfg, bids_path, fname_trans):
    # Generate a head ↔ MRI transformation matrix from the
    # electrophysiological and MRI sidecar files, and save it to an MNE
    # "trans" file in the derivatives folder.
    subject, session = bids_path.subject, bids_path.session

    if config.mri_t1_path_generator is None:
        t1_bids_path = None
    else:
        t1_bids_path = BIDSPath(subject=subject,
                                session=session,
                                root=cfg.bids_root)
        t1_bids_path = config.mri_t1_path_generator(t1_bids_path.copy())
        if t1_bids_path.suffix is None:
            t1_bids_path.update(suffix='T1w')
        if t1_bids_path.datatype is None:
            t1_bids_path.update(datatype='anat')

    msg = 'Estimating head ↔ MRI transform'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    trans = get_head_mri_trans(bids_path.copy().update(run=cfg.runs[0],
                                                       root=cfg.bids_root,
                                                       extension=None),
                               t1_bids_path=t1_bids_path,
                               fs_subject=cfg.fs_subject,
                               fs_subjects_dir=cfg.fs_subjects_dir)

    # Create the source space.
    msg = 'Creating source space'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))
    src = mne.setup_source_space(subject=cfg.fs_subject,
                                 subjects_dir=cfg.fs_subjects_dir,
                                 spacing=cfg.spacing,
                                 add_dist=False,
                                 n_jobs=cfg.n_jobs)

    # Calculate the BEM solution.
    # Here we only use a 3-layers BEM only if EEG is available.
    msg = 'Calculating BEM solution'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    if 'eeg' in cfg.ch_types:
        conductivity = (0.3, 0.006, 0.3)
    else:
        conductivity = (0.3, )

    try:
        bem_model = mne.make_bem_model(subject=cfg.fs_subject,
                                       subjects_dir=cfg.fs_subjects_dir,
                                       ico=4,
                                       conductivity=conductivity)
    except FileNotFoundError:
        message = ("Could not make BEM model due to a missing file. \n"
                   "Can be solved by setting recreate_bem=True in the config "
                   "to force recreation of the BEM model, or by deleting the\n"
                   f" {cfg.bids_root}/derivatives/freesurfer/"
                   f"subjects/sub-{subject}/bem/ folder")
        raise FileNotFoundError(message)

    bem_sol = mne.make_bem_solution(bem_model)
    return src, trans, bem_sol
Ejemplo n.º 6
0
    image=t1_mgh_fname,  # path to the MRI scan
    bids_path=t1w_bids_path,
    raw=raw,  # the raw MEG data file connected to the MRI
    trans=trans,  # our transformation matrix
    verbose=True  # this will print out the sidecar file
)
anat_dir = t1w_bids_path.directory

###############################################################################
# Let's have another look at our BIDS directory
print_dir_tree(output_path)

###############################################################################
# Our BIDS dataset is now ready to be shared. We can easily estimate the
# transformation matrix using ``MNE-BIDS`` and the BIDS dataset.
estim_trans = get_head_mri_trans(bids_path=bids_path)

###############################################################################
# Finally, let's use the T1 weighted MRI image and plot the anatomical
# landmarks Nasion, LPA, and RPA (=left and right preauricular points) onto
# the brain image. For that, we can extract the location of Nasion, LPA, and
# RPA from the MEG file, apply our transformation matrix :code:`trans`, and
# plot the results.

# Get Landmarks from MEG file, 0, 1, and 2 correspond to LPA, NAS, RPA
# and the 'r' key will provide us with the xyz coordinates
pos = np.asarray((raw.info['dig'][0]['r'],
                  raw.info['dig'][1]['r'],
                  raw.info['dig'][2]['r']))

Ejemplo n.º 7
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')

    # Generate a head ↔ MRI transformation matrix from the
    # electrophysiological and MRI sidecar files, and save it to an MNE
    # "trans" file in the derivatives folder.
    if config.mri_t1_path_generator is None:
        t1_bids_path = None
    else:
        t1_bids_path = BIDSPath(subject=bids_path.subject,
                                session=bids_path.session,
                                root=config.bids_root)
        t1_bids_path = config.mri_t1_path_generator(t1_bids_path.copy())
        if t1_bids_path.suffix is None:
            t1_bids_path.update(suffix='T1w')
        if t1_bids_path.datatype is None:
            t1_bids_path.update(datatype='anat')

    msg = 'Estimating head ↔ MRI transform'
    logger.info(
        gen_log_message(message=msg, step=10, subject=subject,
                        session=session))

    trans = get_head_mri_trans(bids_path.copy().update(
        run=config.get_runs()[0], root=config.bids_root),
                               t1_bids_path=t1_bids_path)
    mne.write_trans(fname_trans, trans)

    fs_subject = config.get_fs_subject(subject)
    fs_subjects_dir = config.get_fs_subjects_dir()

    # Create the source space.
    msg = 'Creating source space'
    logger.info(
        gen_log_message(message=msg, step=10, subject=subject,
                        session=session))
    src = mne.setup_source_space(subject=fs_subject,
                                 subjects_dir=fs_subjects_dir,
                                 spacing=config.spacing,
                                 add_dist=False,
                                 n_jobs=config.N_JOBS)

    # Calculate the BEM solution.
    # Here we only use a 3-layers BEM only if EEG is available.
    msg = 'Calculating BEM solution'
    logger.info(
        gen_log_message(message=msg, step=10, subject=subject,
                        session=session))

    if 'eeg' in config.ch_types:
        conductivity = (0.3, 0.006, 0.3)
    else:
        conductivity = (0.3, )

    bem_model = mne.make_bem_model(subject=fs_subject,
                                   subjects_dir=fs_subjects_dir,
                                   ico=4,
                                   conductivity=conductivity)
    bem_sol = mne.make_bem_solution(bem_model)

    # Finally, calculate and save the forward solution.
    msg = 'Calculating forward solution'
    logger.info(
        gen_log_message(message=msg, step=10, subject=subject,
                        session=session))
    info = mne.io.read_info(fname_evoked)
    fwd = mne.make_forward_solution(info,
                                    trans=trans,
                                    src=src,
                                    bem=bem_sol,
                                    mindist=config.mindist)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
import mne
import mne_bids
from mayavi import mlab

from config import fname, subject_id, n_jobs

info = mne.io.read_info(fname.raw)

# From T1-weighted MRI to forward solution
trans = mne_bids.get_head_mri_trans(fname.raw, fname.bids_root)
bem = mne.make_bem_model(subject_id, ico=4, subjects_dir=fname.subjects_dir)
bem_sol = mne.make_bem_solution(bem)
mne.write_bem_solution(fname.bem, bem_sol)

# create surface source space & forward solution
src_surf = mne.setup_source_space(subject=subject_id,
                                  subjects_dir=fname.subjects_dir,
                                  n_jobs=n_jobs)
fwd_surf = mne.make_forward_solution(info=info,
                                     trans=trans,
                                     src=src_surf,
                                     bem=bem_sol)

# create volume source space & forward solution
src = mne.setup_volume_source_space(subject=subject_id,
                                    pos=7.,
                                    mri=fname.mri,
                                    bem=bem_sol,
                                    subjects_dir=fname.subjects_dir)
fwd = mne.make_forward_solution(info=info, trans=trans, src=src, bem=bem_sol)
Ejemplo n.º 9
0
    t1w=t1_mgh_fname,  # path to the MRI scan
    session=ses,
    raw=raw,  # the raw MEG data file connected to the MRI
    trans=trans,  # our transformation matrix
    verbose=True  # this will print out the sidecar file
)

###############################################################################
# Let's have another look at our BIDS directory
print_dir_tree(output_path)

###############################################################################
# Our BIDS dataset is now ready to be shared. We can easily estimate the
# transformation matrix using ``MNE-BIDS`` and the BIDS dataset.
estim_trans = get_head_mri_trans(
    bids_basename=bids_basename,
    bids_root=output_path  # root of our BIDS dir
)

###############################################################################
# Finally, let's use the T1 weighted MRI image and plot the anatomical
# landmarks Nasion, LPA, and RPA (=left and right preauricular points) onto
# the brain image. For that, we can extract the location of Nasion, LPA, and
# RPA from the MEG file, apply our transformation matrix :code:`trans`, and
# plot the results.

# Get Landmarks from MEG file, 0, 1, and 2 correspond to LPA, NAS, RPA
# and the 'r' key will provide us with the xyz coordinates
pos = np.asarray((raw.info['dig'][0]['r'], raw.info['dig'][1]['r'],
                  raw.info['dig'][2]['r']))

# We use a function from MNE-Python to convert MEG coordinates to MRI space
Ejemplo n.º 10
0
                import numpy as np
                import matplotlib.pyplot as plt

                from nilearn.plotting import plot_anat
                from mne.source_space import head_to_mri
                from mne_bids import get_head_mri_trans

                # Get Landmarks from MEG file, 0, 1, and 2 correspond to LPA, NAS, RPA
                # and the 'r' key will provide us with the xyz coordinates
                pos = np.asarray(
                    (raw.info['dig'][0]['r'], raw.info['dig'][1]['r'],
                     raw.info['dig'][2]['r']))

                bids_fname = bids_basename + '_meg.fif'
                estim_trans = get_head_mri_trans(
                    bids_fname=bids_fname,  # name of the MEG file
                    bids_root=bids_root  # root of our BIDS dir
                )

                # We use a function from MNE-Python to convert MEG coordinates to MRI space
                # for the conversion we use our estimated transformation matrix and the
                # MEG coordinates extracted from the raw file. `subjects` and `subjects_dir`
                # are used internally, to point to the T1-weighted MRI file: `t1_mgh_fname`
                mri_pos = head_to_mri(pos=pos,
                                      subject=subject,
                                      mri_head_t=estim_trans,
                                      subjects_dir=subjects_dir)

                # Our MRI written to BIDS, we got `anat_dir` from our `write_anat` function
                t1_nii_fname = op.join(
                    anat_dir, 'sub-' + subject + '_acq-t1w_T1w.nii.gz')
                # sub-SB01_acq-t1w_T1w
def run_forward(subject, session=None):
    print("Processing subject: %s" % subject)

    # Construct the search path for the data file. `sub` is mandatory
    subject_path = op.join('sub-{}'.format(subject))
    # `session` is optional
    if session is not None:
        subject_path = op.join(subject_path, 'ses-{}'.format(session))

    subject_path = op.join(subject_path, config.kind)

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

    fpath_deriv = op.join(config.bids_root, 'derivatives',
                          config.PIPELINE_NAME, subject_path)
    fname_evoked = \
        op.join(fpath_deriv, bids_basename + '-ave.fif')

    print("Input: ", fname_evoked)

    fname_trans = \
        op.join(fpath_deriv, 'sub-{}'.format(subject) + '-trans.fif')

    fname_fwd = \
        op.join(fpath_deriv, bids_basename + '-fwd.fif')

    print("Output: ", fname_fwd)

    # Find the raw data file
    # XXX : maybe simplify
    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.task,
                                       acquisition=config.acq,
                                       run=config.runs[0],
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    data_dir = op.join(config.bids_root, subject_path)
    search_str = op.join(data_dir, bids_basename) + '_' + config.kind + '*'
    fnames = sorted(glob.glob(search_str))
    fnames = [f for f in fnames if op.splitext(f)[1] in mne_bids_readers]

    if len(fnames) >= 1:
        bids_fname = fnames[0]
    elif len(fnames) == 0:
        raise ValueError('Could not find input data file matching: '
                         '"{}"'.format(search_str))

    bids_fname = op.basename(bids_fname)
    trans = get_head_mri_trans(bids_fname=bids_fname,
                               bids_root=config.bids_root)

    mne.write_trans(fname_trans, trans)

    src = mne.setup_source_space(subject,
                                 spacing=config.spacing,
                                 subjects_dir=config.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 or config.kind == 'eeg':
        model = mne.make_bem_model(subject,
                                   ico=4,
                                   conductivity=(0.3, 0.006, 0.3),
                                   subjects_dir=config.subjects_dir)
    else:
        model = mne.make_bem_model(subject,
                                   ico=4,
                                   conductivity=(0.3, ),
                                   subjects_dir=config.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)
Ejemplo n.º 12
0
print_dir_tree(output_path)

# %%
# Our BIDS dataset is now ready to be shared. We can easily estimate the
# transformation matrix using ``MNE-BIDS`` and the BIDS dataset.
# This function converts the anatomical landmarks stored in the T1 sidecar
# file into FreeSurfer surface RAS space, and aligns the landmarks in the
# electrophysiology data with them. This way your electrophysiology channel
# locations can be transformed to surface RAS space using the ``trans`` which
# is crucial for source localization and other uses of the FreeSurfer surfaces.
#
# .. note:: If this dataset were shared with you, you would first have to use
#           the T1 image as input for the FreeSurfer recon-all, see
#           :ref:`tut-freesurfer-mne`.
estim_trans = get_head_mri_trans(bids_path=bids_path,
                                 fs_subject='sample',
                                 fs_subjects_dir=fs_subjects_dir)

# %%
# Finally, let's use the T1 weighted MRI image and plot the anatomical
# landmarks Nasion, LPA, and RPA onto the brain image. For that, we can
# extract the location of Nasion, LPA, and RPA from the MEG file, apply our
# transformation matrix :code:`trans`, and plot the results.

# Get Landmarks from MEG file, 0, 1, and 2 correspond to LPA, NAS, RPA
# and the 'r' key will provide us with the xyz coordinates. The coordinates
# are expressed here in MEG Head coordinate system.
pos = np.asarray((raw.info['dig'][0]['r'], raw.info['dig'][1]['r'],
                  raw.info['dig'][2]['r']))

# We now use the ``head_to_mri`` function from MNE-Python to convert MEG