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 #2
0
def test_make_bem_model(tmpdir):
    """Test BEM model creation from Python with I/O."""
    tempdir = str(tmpdir)
    fname_temp = op.join(tempdir, 'temp-bem.fif')
    for kwargs, fname in zip((dict(), dict(conductivity=[0.3])),
                             [fname_bem_3, fname_bem_1]):
        model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir,
                               **kwargs)
        model_c = read_bem_surfaces(fname)
        _compare_bem_surfaces(model, model_c)
        write_bem_surfaces(fname_temp, model)
        model_read = read_bem_surfaces(fname_temp)
        _compare_bem_surfaces(model, model_c)
        _compare_bem_surfaces(model_read, model_c)
    # bad conductivity
    with pytest.raises(ValueError, match='conductivity must be'):
        make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
Beispiel #3
0
def test_bem_model_topology(tmpdir):
    """Test BEM model topological checks."""
    # bad topology (not enough neighboring tris)
    tempdir = str(tmpdir)
    makedirs(op.join(tempdir, 'foo', 'bem'))
    for fname in ('inner_skull', 'outer_skull', 'outer_skin'):
        fname += '.surf'
        copy(op.join(subjects_dir, 'sample', 'bem', fname),
             op.join(tempdir, 'foo', 'bem', fname))
    outer_fname = op.join(tempdir, 'foo', 'bem', 'outer_skull.surf')
    rr, tris = read_surface(outer_fname)
    tris = tris[:-1]
    write_surface(outer_fname, rr, tris[:-1])
    with pytest.raises(RuntimeError, match='Surface outer skull is not compl'):
        make_bem_model('foo', None, subjects_dir=tempdir)
    # Now get past this error to reach gh-6127 (not enough neighbor tris)
    rr_bad = np.concatenate([rr, np.mean(rr, axis=0, keepdims=True)], axis=0)
    write_surface(outer_fname, rr_bad, tris)
    with pytest.raises(RuntimeError, match='Surface outer skull.*triangles'):
        make_bem_model('foo', None, subjects_dir=tempdir)
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 #5
0
def test_bem_model():
    """Test BEM model creation from Python with I/O"""
    tempdir = _TempDir()
    fname_temp = op.join(tempdir, "temp-bem.fif")
    for kwargs, fname in zip((dict(), dict(conductivity=[0.3])), [fname_bem_3, fname_bem_1]):
        model = make_bem_model("sample", ico=2, subjects_dir=subjects_dir, **kwargs)
        model_c = read_bem_surfaces(fname)
        _compare_bem_surfaces(model, model_c)
        write_bem_surfaces(fname_temp, model)
        model_read = read_bem_surfaces(fname_temp)
        _compare_bem_surfaces(model, model_c)
        _compare_bem_surfaces(model_read, model_c)
    assert_raises(
        ValueError, make_bem_model, "sample", conductivity=[0.3, 0.006], subjects_dir=subjects_dir  # bad conductivity
    )
Beispiel #6
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)
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
def process_subject_anat(subject_id, force_recon_all=False):
    subject = "sub%03d" % subject_id
    print("Processing %s" % subject)

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

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

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

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

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

    # Create the surface source space
    fname_src = op.join(subjects_dir, subject, 'bem', '%s-%s-src.fif'
                        % (subject, spacing))
    if not op.isfile(fname_src):
        print('  Setting up source space')
        src = mne.setup_source_space(subject, spacing,
                                     subjects_dir=subjects_dir)
        mne.write_source_spaces(fname_src, src)
Beispiel #9
0
# ------------------------
#
# We can now compute the forward solution.
# To reduce computation we'll just compute a single layer BEM (just inner
# skull) that can then be used for MEG (not EEG).
#
# We specify if we want a one-layer or a three-layer BEM using the
# conductivity parameter.
#
# The BEM solution requires a BEM model which describes the geometry
# of the head the conductivities of the different tissues.

conductivity = (0.3,)  # for single layer
# conductivity = (0.3, 0.006, 0.3)  # for three layers
model = mne.make_bem_model(subject='sample', ico=4,
                           conductivity=conductivity,
                           subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)

###############################################################################
# Note that the BEM does not involve any use of the trans file. The BEM
# only depends on the head geometry and conductivities.
# It is therefore independent from the MEG data and the head position.
#
# Let's now compute the forward operator, commonly referred to as the
# gain or leadfield matrix.
#
# See :func:`mne.make_forward_solution` for details on parameters meaning.

fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=bem,
                                meg=True, eeg=False, mindist=5.0, n_jobs=2)
Beispiel #10
0
# this process and all subprocesses
os.environ['SUBJECTS_DIR'] = subjects_dir_bids

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

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

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

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

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

old_forward = op.join(somato_path, 'MEG', 'somato',
                      'somato-meg-oct-6-fwd.fif')
src_fsaverage = mne.setup_source_space(
    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,
 #from mayavi import mlab  # noqa
 #from surfer import Brain  # noqa
 #
 #brain = Brain('sample', 'lh', 'inflated', subjects_dir=subjects_dir)
 #surf = brain._geo
 #
 #vertidx = np.where(src[0]['inuse'])[0]
 #
 #mlab.points3d(surf.x[vertidx], surf.y[vertidx],
 #              surf.z[vertidx], color=(1, 1, 0), scale_factor=1.5)
 
 # Create BEM model
 conductivity = (0.3,)  # for single layer
 #conductivity = (0.3, 0.006, 0.3)  # for three layers
 model = mne.make_bem_model(subject=subject, ico=5, # 5=20484, 4=5120
                            conductivity=conductivity, 
                            subjects_dir=fs_dir)
 bem = mne.make_bem_solution(model)
 fn = session1[n] + '-bem-sol.fif'
 mne.write_bem_solution(fn,bem)
 
 # Now create forward model
 fwd = mne.make_forward_solution(info, trans=trans, src=src, bem=bem,
                                 fname=None, meg=True, eeg=False,
                                 mindist=3.0, n_jobs=18)
 fn = session1[n] + '-fwd.fif'
 mne.write_forward_solution(fn,fwd,overwrite=True)
 
 
 #Inverse here
 
Beispiel #13
0
    def _run(self):
        """Compute 3-layer BEM based forward model from montage and anatomy"""
        montage = self.montage
        subjects_dir = self.subjects_dir
        subject = self.subject
        spacing = self.spacing
        conductivity = self.conductivity
        trans_file = self.trans_file
        dest_dir = self.dest_dir
        n_jobs = self.n_jobs
        verbose = self.verbose
        self._logger.debug('Computing forward with the following parameters.')
        self._logger.debug('montage: %s', montage)
        self._logger.debug('SUBJECT: %s', subject)
        self._logger.debug('SUBJECTS_DIR: %s', subjects_dir)
        self._logger.debug('spacing: %s', spacing)
        self._logger.debug('trans_file: %s', trans_file)
        self._logger.debug('conductivity: %s', conductivity)
        self._logger.debug('dest_dir: %s', dest_dir)

        try:
            montage = mne.channels.read_montage(kind=montage)
        except Exception:
            raise BadInputFile('Bad montage file: %s' % montage)

        os.makedirs(op.dirname(self.fwd_savename), exist_ok=True)

        fiducials = ['LPA', 'RPA', 'Nz', 'FidT9', 'FidT10', 'FidNz']
        self._logger.info('Setting up the source space ...')
        src = mne.setup_source_space(subject,
                                     spacing=spacing,
                                     subjects_dir=subjects_dir,
                                     add_dist=False,
                                     verbose=verbose)
        self.progress_updated.emit(25)

        # raise Exception('Some catastrophic shit happened')
        self._logger.info('Creating bem model (be patient) ...')
        model = mne.make_bem_model(subject=subject,
                                   ico=4,
                                   conductivity=conductivity,
                                   subjects_dir=subjects_dir,
                                   verbose=verbose)
        self.progress_updated.emit(50)
        bem = mne.make_bem_solution(model, verbose=verbose)
        self.progress_updated.emit(75)
        if not trans_file:
            trans_file = None
        n_jobs = n_jobs
        self._logger.info('Computing forward solution (be patient) ...')
        ch_names = montage.ch_names
        ch_names = [c for c in ch_names if c not in fiducials]
        info = mne.create_info(ch_names, sfreq=1, ch_types='eeg')
        raw = mne.io.RawArray(np.ones([len(info['ch_names']), 1]),
                              info,
                              verbose=verbose)
        raw.set_montage(montage)

        ch_names = montage.ch_names
        ch_names = [c for c in ch_names if c not in fiducials]
        fwd = mne.make_forward_solution(raw.info,
                                        trans=trans_file,
                                        src=src,
                                        bem=bem,
                                        meg=False,
                                        eeg=True,
                                        mindist=5.0,
                                        n_jobs=n_jobs,
                                        verbose=verbose)
        self.progress_updated.emit(100)

        mne.write_forward_solution(self.fwd_savename,
                                   fwd,
                                   overwrite=True,
                                   verbose=verbose)
Beispiel #14
0
    events=events_red,
)

#%%
noise_cov = mne.compute_covariance(epochs, method=['shrunk', 'empirical'])
#%%
trans = mne.read_trans('E:/sub-06_free-trans.fif')
subject = 'sub-06_free'
conductivity_base = (0.3, 0.006, 0.3)
src = mne.setup_source_space(subject,
                             spacing='oct6',
                             add_dist='patch',
                             subjects_dir=subjects_dir)
#%%
model = mne.make_bem_model(subject=subject,
                           ico=4,
                           conductivity=conductivity_base,
                           subjects_dir=subjects_dir)
#%%
bem = mne.make_bem_solution(model)
fwd = mne.make_forward_solution(fname_raw,
                                trans=trans,
                                src=src,
                                bem=bem,
                                meg=False,
                                eeg=True,
                                mindist=5.0,
                                n_jobs=2)
#%%
from mne.minimum_norm import make_inverse_operator, apply_inverse
evoked = epochs.average()
evoked.set_eeg_reference('average', projection=True)
Beispiel #15
0
    def _make_bem_solution(self):
        bem_save_name = opj(self.fsrc, self.subject + "-single-shell-model")
        if not os.path.isfile(bem_save_name):
            try:
                bem = mne.make_bem_model(self.subject,
                                         ico=4,
                                         conductivity=[0.3],
                                         subjects_dir=self.subjects_dir,
                                         verbose=True)
                mne.write_bem_surfaces(bem_save_name, bem,
                                       overwrite=True)  #, overwrite=True)
            except Exception as e:
                print(
                    f"Failed to setup single shell BEM model for {self.subject} --> {e}"
                )
        bem_sol_filename = opj(self.fsrc,
                               self.subject + "-single-shell-BEM-sol.fif")
        if not os.path.isfile(bem_sol_filename):
            try:
                bem = mne.read_bem_surfaces(bem_save_name)
                bem_sol = mne.make_bem_solution(bem)
                mne.write_bem_solution(bem_sol_filename,
                                       bem_sol,
                                       overwrite=True)
            except Exception as e:
                print(
                    f"Failed to calculate BEM solution (single-shell) for {self.subject} --> {e}"
                )

        # BEM Solutions - 3-layer-BEM
        bem_save_name = opj(self.fsrc, self.subject + "-3-layer-BEM-model.fif")
        if not os.path.isfile(bem_save_name):
            try:
                bem = mne.make_bem_model(self.subject,
                                         ico=4,
                                         conductivity=[0.3, 0.006, 0.3],
                                         subjects_dir=self.subjects_dir,
                                         verbose=True)
                mne.write_bem_surfaces(bem_save_name, bem,
                                       overwrite=True)  #, overwrite=True)
            except Exception as e:
                print(
                    f"Failed to calculate 3-layer BEM model for {self.subject} --> {e}"
                )
        bem_sol_filename = opj(self.fsrc,
                               self.subject + "-3-layer-BEM-sol.fif")
        if not os.path.isfile(bem_sol_filename):
            try:
                bem = mne.read_bem_surfaces(bem_save_name)
                bem_sol = mne.make_bem_solution(bem)
                mne.write_bem_solution(bem_sol_filename,
                                       bem_sol,
                                       overwrite=True)
            except Exception as e:
                print(
                    f"Failed to calculate 3-layer BEM solution for {self.subject} --> {e}"
                )
                print(
                    "This is bad, please look into the freesurfer segmentation..."
                )
                print(
                    "Alternatively, you might be able to run the analysis with a single-shell-head-model (look into the configuration file"
                )
# ------------------------
#
# We can now compute the forward solution.
# To reduce computation we'll just compute a single layer BEM (just inner
# skull) that can then be used for MEG (not EEG).
#
# We specify if we want a one-layer or a three-layer BEM using the
# conductivity parameter.
#
# The BEM solution requires a BEM model which describes the geometry
# of the head the conductivities of the different tissues.

conductivity = (0.3,)  # for single layer
# conductivity = (0.3, 0.006, 0.3)  # for three layers
model = mne.make_bem_model(subject='sample', ico=4,
                           conductivity=conductivity,
                           subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)

###############################################################################
# Note that the :term:`BEM` does not involve any use of the trans file. The BEM
# only depends on the head geometry and conductivities.
# It is therefore independent from the MEG data and the head position.
#
# Let's now compute the forward operator, commonly referred to as the
# gain or leadfield matrix.
#
# See :func:`mne.make_forward_solution` for details on parameters meaning.

fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=bem,
                                meg=True, eeg=False, mindist=5.0, n_jobs=2)
###############################################################################
# To save time and memory, the forward solution is read from a file. Set
# ``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:`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')
Beispiel #18
0
                                   spacing="ico5",
                                   subjects_dir=subjects_dir,
                                   add_dist=False)

# visualization of sources
# brain = Brain(subject, 'lh', 'inflated', subjects_dir=subjects_dir)
# surf = brain.geo['lh']
# vertidx = np.where(src[0]['inuse'])[0]
# mlab.points3d(surf.x[vertidx], surf.y[vertidx],
#               surf.z[vertidx], color=(1, 1, 0), scale_factor=1.5)

# BEM solution
conductivity = (0.3, )  # for single layer (inner skull)
# conductivity = (0.3, 0.006, 0.3)  # for three layers
model = mne.make_bem_model(subject=subject,
                           conductivity=conductivity,
                           subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)

mne.viz.plot_alignment(
    Data.info,
    subject=subject,
    subjects_dir=subjects_dir,
    meg="helmet",
    bem=bem,
    dig=True,
    surfaces=["brain"],
)

# forward operator
fwd_dense = mne.make_forward_solution(
Beispiel #19
0
                                       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)
Beispiel #20
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)
Beispiel #21
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)
Beispiel #22
0
meg_dir = "D:/NEMO_analyses/proc/"
trans_dir = "D:/NEMO_analyses/proc/trans_files/"
mri_dir = "D:/freesurfer/subjects/"

fsavg_src = mne.setup_source_space(
    "fsaverage",
    surface="white",
    subjects_dir=mri_dir,
    spacing='ico5',
    n_jobs=4)  ## uses 'oct6' as default, i.e. 4.9mm spacing appr.
# fsavg_src.save(meg_dir+"fsaverage_oct6-src.fif", overwrite=True)
# fsavg_src.save(meg_dir+"fsaverage_ico5-src.fif", overwrite=True)

bem_model = mne.make_bem_model('fsaverage',
                               subjects_dir=mri_dir,
                               conductivity=[0.3])
bem = mne.make_bem_solution(bem_model)
mne.write_bem_solution(meg_dir + "fsaverage-bem.fif", bem)
mne.viz.plot_bem(subject='fsaverage',
                 subjects_dir=mri_dir,
                 brain_surfaces='white',
                 src=fsavg_src,
                 orientation='coronal')

# create a mixed source space from here, adding subcortical volumes from label + aseg.mgz
labels_limb = [
    'Left-Thalamus-Proper', 'Left-Caudate', 'Left-Putamen', 'Left-Pallidum',
    'Left-Hippocampus', 'Left-Amygdala', 'Right-Thalamus-Proper',
    'Right-Caudate', 'Right-Putamen', 'Right-Pallidum', 'Right-Hippocampus',
    'Right-Amygdala'
###############################################################################
# To save time and memory, the forward solution is read from a file. Set
# ``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')
root = subject_dir + '/data/Sourceest/'
conductivity = [0.3, 0.01, 0.3]
for subject in subjects_with_trans:
    fname = subject_dir + '/sub-' + subject + '_free/'
    trans = fname + 'sub-' + subject + '_free-trans.fif'
    raw_fname = root = '/media/peter/Ekstren/ds000117-download/derivatives/meg_derivatives/sub-' + str(
        subject
    ) + '/ses-meg/meg/' + 'sub-' + subject + '_ses-meg_task-facerecognition_run-01_proc-sss_meg.fif'
    raw = mne.io.Raw(raw_fname, preload=True)
    raw.info['bads'] = ["EEG061", "EEG062", "EEG063"]
    raw.pick_types(meg=False, eeg=True, exclude='bads')
    src = mne.read_source_spaces(fname + 'sub-' + subject + '_free-src.fif',
                                 patch_stats=False,
                                 verbose=None)
    model = mne.make_bem_model(subject='sub-' + subject + '_free',
                               ico=4,
                               conductivity=conductivity,
                               subjects_dir=subject_dir)
    bem = mne.make_bem_solution(model)
    fwd = mne.convert_forward_solution(mne.make_forward_solution(raw.info,
                                                                 trans=trans,
                                                                 src=src,
                                                                 bem=bem,
                                                                 meg=False,
                                                                 eeg=True,
                                                                 mindist=5.0,
                                                                 n_jobs=2),
                                       force_fixed=True)
    gain = fwd['sol']['data']
    np.save(
        subject_dir + '/data/Sourceest/pinv/sub-' + subject +
        '/est_normal.npy',