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 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 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
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 test_io_bem(tmpdir, ext): """Test reading and writing of bem surfaces and solutions.""" import h5py temp_bem = op.join(str(tmpdir), f'temp-bem.{ext}') # model with pytest.raises(ValueError, match='BEM data not found'): read_bem_surfaces(fname_raw) with pytest.raises(ValueError, match='surface with id 10'): read_bem_surfaces(fname_bem_3, s_id=10) surf = read_bem_surfaces(fname_bem_3, patch_stats=True) surf = read_bem_surfaces(fname_bem_3, patch_stats=False) write_bem_surfaces(temp_bem, surf[0]) with pytest.raises(IOError, match='exists'): write_bem_surfaces(temp_bem, surf[0]) write_bem_surfaces(temp_bem, surf[0], overwrite=True) if ext == 'h5': with h5py.File(temp_bem, 'r'): # make sure it's valid pass surf_read = read_bem_surfaces(temp_bem, patch_stats=False) _compare_bem_surfaces(surf, surf_read) # solution with pytest.raises(RuntimeError, match='No BEM solution found'): read_bem_solution(fname_bem_3) temp_sol = op.join(str(tmpdir), f'temp-sol.{ext}') sol = read_bem_solution(fname_bem_sol_3) assert 'BEM' in repr(sol) write_bem_solution(temp_sol, sol) sol_read = read_bem_solution(temp_sol) _compare_bem_solutions(sol, sol_read) sol = read_bem_solution(fname_bem_sol_1) with pytest.raises(RuntimeError, match='BEM does not have.*triangulation'): _bem_find_surface(sol, 3)
def 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 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
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)
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 __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
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) '''
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
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)
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)
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 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 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
def test_io_bem(tmpdir): """Test reading and writing of bem surfaces and solutions.""" temp_bem = op.join(str(tmpdir), 'temp-bem.fif') pytest.raises(ValueError, read_bem_surfaces, fname_raw) pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10) surf = read_bem_surfaces(fname_bem_3, patch_stats=True) surf = read_bem_surfaces(fname_bem_3, patch_stats=False) write_bem_surfaces(temp_bem, surf[0]) surf_read = read_bem_surfaces(temp_bem, patch_stats=False) _compare_bem_surfaces(surf, surf_read) pytest.raises(RuntimeError, read_bem_solution, fname_bem_3) temp_sol = op.join(str(tmpdir), 'temp-sol.fif') sol = read_bem_solution(fname_bem_sol_3) assert 'BEM' in repr(sol) write_bem_solution(temp_sol, sol) sol_read = read_bem_solution(temp_sol) _compare_bem_solutions(sol, sol_read) sol = read_bem_solution(fname_bem_sol_1) pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
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)
def test_io_bem(): """Test reading and writing of bem surfaces and solutions.""" tempdir = _TempDir() temp_bem = op.join(tempdir, 'temp-bem.fif') pytest.raises(ValueError, read_bem_surfaces, fname_raw) pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10) surf = read_bem_surfaces(fname_bem_3, patch_stats=True) surf = read_bem_surfaces(fname_bem_3, patch_stats=False) write_bem_surfaces(temp_bem, surf[0]) surf_read = read_bem_surfaces(temp_bem, patch_stats=False) _compare_bem_surfaces(surf, surf_read) pytest.raises(RuntimeError, read_bem_solution, fname_bem_3) temp_sol = op.join(tempdir, 'temp-sol.fif') sol = read_bem_solution(fname_bem_sol_3) assert 'BEM' in repr(sol) write_bem_solution(temp_sol, sol) sol_read = read_bem_solution(temp_sol) _compare_bem_solutions(sol, sol_read) sol = read_bem_solution(fname_bem_sol_1) pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
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)
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
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)
exisitngfiles = [ op.join(subDir, f) for f in listdir(subDir) if 'dSPM' in f ] if len(exisitngfiles) and not overwrite_out: print 'Output already exists. Will not overwrite!' continue ### Make bem (or read) if not op.isfile(bemFile) or overwrite_pre: model = make_bem_model(subject=sub, ico=4, conductivity=conductivity, subjects_dir=subjects_dir) bem = make_bem_solution(model) write_bem_solution(op.join(subjects_dir, sub, 'bem', 'bem-sol.fif'), bem) print('Wrote BEM file ' + str(op.join(subjects_dir, sub, 'bem', 'bem-sol.fif'))) else: bem = read_bem_solution(bemFile) ### Read source space src = read_source_spaces(srcFile) ### read trans trans = read_trans(traFile) ### Read noise covariance from empty room recordings noise_cov = read_cov(covFile) #### LOOP THROUGH RAWFILES
epochs = read_epochs(epochs_fname) print("Making covariance matrix...") noise_cov = compute_covariance(epochs, tmax=0., method=['shrunk']) write_cov(cov_fname, noise_cov) noise_cov = read_cov(cov_fname) print("Making BEM model...") surfaces = make_bem_model(subject, ico=4, conductivity=(0.3, ), subjects_dir=mri_dir, verbose=None) bem = make_bem_solution(surfaces) write_bem_solution(bem_fname, bem) # if not op.isfile(fwd_fname): print("Making forward solution...") src = setup_source_space(subject, spacing='ico4', subjects_dir=mri_dir) fwd = make_forward_solution(epochs.info, trans_fname, src, bem_fname, meg=True, ignore_ref=True) print("Converting forward solution...") fwd_fixed = convert_forward_solution(fwd, force_fixed=False, surf_ori=True) write_forward_solution(fwd_fname, fwd_fixed, overwrite=True) # else: # fwd = read_forward_solution(fwd_fname)
def forwardSolBatch(self): """ Usage example: -------------- from uhClass import Forward a = Forward() a.forwardSolBatch() """ #mainDir = 'C:\\uhdata\\freesurfer' os.chdir(self.mainDir) folder = os.listdir(u'.') for subject in folder: if subject[0] == self.foldername: # if folder starts with 'S' then proceed os.chdir(os.path.join(self.mainDir,subject)) #% STEP 1: COMPUTER THE SOURCE SPACE (SOURCE GRID ON MRI) """ The source space defines the position of the candidate source locations. The following code compute such a cortical source space with an OCT-5 resolution. """ filename2save = "".join([subject,'-src.fif']) src = mne.setup_source_space(subject, spacing='oct5', subjects_dir = self.mainDir) mne.write_source_spaces(filename2save, src, overwrite=True) #src.plot(head=True,brain=False,skull=False,subjects_dir = subjectDir) #% STEP 2: COMPUTER THE FORWARD SOLUTION """ The BEM solution requires a BEM model which describes the geometry of the head the conductivities of the different tissues. 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 EEG data and the head position. The forward operator, commonly referred to as the gain or leadfield matrix requires the co-registration later on. """ conductivity = (0.3, 0.006, 0.3) # for three layers model = mne.make_bem_model(subject, subjects_dir=self.mainDir, conductivity=conductivity, verbose=None) #bem2save = "".join([subjectName,'-bem.fif']) #mne.write_bem_surfaces(bem2save, model) bem_sol = mne.make_bem_solution(model) bem2solution = "".join([subject,'-bemsol.fif']) mne.write_bem_solution(bem2solution, bem_sol) #%% STEP 3: CO-REGISTRATION STEP (MANUAL STEP) # Forward.coregister(subject) #% MAKE FORWARD SOLUTION trans = os.path.join(os.getcwd(), "".join([subject,'-trans.fif'])) eegfile = os.path.join(os.path.join(self.mainDir,subject), glob.glob("*-epo.fif")[0]) fwd = mne.make_forward_solution(eegfile, trans=trans, src=src, bem=bem_sol, meg=False, eeg=True, mindist=5.0) fwdname = "".join([subject,'-fwd.fif']) mne.write_forward_solution(fwdname, fwd, overwrite=True, verbose=None) print("Processing finished for >>>", subject)
def convert_ANTS_surrogate(subject, trans, subjects_dir): """Convert an old ANTS surrogate to a modern one. Parameters ---------- subject : str The subject name. trans : str The path to the subject's MRI<->head transformation. subjects_dir : str The subjects dir that contains the old ``subject`` MRI. Notes ----- The "old" templates are the ones created by Eric Larson around 2019 and only include volumetric source spaces. The "modern" templates come from the 2021 NeuroImage paper by O'Reilly et al. and use the same templates, just processed differently. Given a surrogate created using the old template, this function will create an equivalent one for the new template. It operates in-place by first backing up (renaming) the MRI directory for the subject, copying the ``-trans.fif`` file to that directory, and then creating the new surrogate and overwriting the old trans file. """ # load morph params subjects_dir = mne.utils.get_subjects_dir(subjects_dir) config = mne.coreg.read_mri_cfg(subject, subjects_dir) n_params = config.pop('n_params') subject_from = config['subject_from'] if subject_from not in ('ANTS3-0Months3T', 'ANTS6-0Months3T', 'ANTS12-0Months3T'): raise RuntimeError('Cannot convert subject that used ' f'{repr(subject_from)} as a surrogate') age = int(subject_from.split('-')[0].split('S')[-1]) assert n_params in (3, 1), n_params out_dir = op.join(subjects_dir, subject) backup_dir = op.join(subjects_dir, subject + '_old') if not isinstance(trans, (str, os.PathLike)): raise TypeError(f'trans must be path-like, got {type(trans)}') assert isinstance(trans, str) trans, trans_fname = mne.transforms._get_trans(trans, 'head', 'mri') if op.exists(backup_dir): raise RuntimeError(f'Backup dir {backup_dir} must not already exist') backup_trans = op.join(out_dir, op.basename(trans_fname)) if op.exists(backup_trans): raise RuntimeError(f'Backup trans location {backup_trans} must not ' 'exist') from_dir = op.join(subjects_dir, subject_from) if not op.isdir(from_dir): raise RuntimeError(f'Template MRI directory not found: {from_dir}') bem_path = op.join( from_dir, 'bem', f'{subject_from}-5120-5120-5120-bem-sol.fif') if not op.isfile(bem_path): raise RuntimeError(f'{subject_from} in {repr(subjects_dir)} does not ' 'appear to be a new-style template, consider ' 'running:\n\n' 'import shutil, mne\n' f'shutil.rmtree({repr(from_dir)})\n' f'mne.datasets.fetch_infant_template(\'{age}mo\'' f', subjects_dir={repr(subjects_dir)}' ', verbose=True)\n') shutil.move(trans_fname, backup_trans) shutil.move(out_dir, backup_dir) print('Rescaling MRI (will be slow)...') mne.coreg.scale_mri(subject_to=subject, subjects_dir=subjects_dir, labels=True, annot=True, overwrite=False, **config) bem_path = op.join( out_dir, 'bem', f'{subject}-5120-5120-5120-bem-sol.fif') sol = mne.make_bem_solution(mne.read_bem_surfaces(bem_path[:-8] + '.fif')) mne.write_bem_solution(bem_path, sol) # A factor beacuse Christian's MRIs weren't conformed: # tra = { # 3: [3, 8, 7.5], 6: [-1, 10.5, 10], 12: [0.5, 8, 15], # } # But these factors didn't completely explain the differences. So these # adjustments were done by eye, and confirmed by # surface-matching code that follows this function. tra = { 3: [2, 7, 10], 6: [-1, 11, 8.5], 12: [-1, 10, 13], } x_rot = {3: -6.5, 6: 0, 12: 8} y_rot = {3: -2.5, 6: 2, 12: 0} rot = mne.transforms.rotation(x=np.deg2rad(x_rot[age]), y=np.deg2rad(y_rot[age])) tra = mne.transforms.translation(*tra[age]) xform = rot @ tra xform[:3, 3] *= config['scale'] / 1000. # scale and mm->m trans['trans'][:] = xform @ trans['trans'] mne.transforms.write_trans(trans_fname, trans)
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
src_file_out = op.join(meg_subj_path, "{}-src.fif".format(subj)) mne.write_source_spaces(src_file_out, src) conductivity = (0.3, ) model = mne.make_bem_model(subject=subj, ico=5, conductivity=conductivity, subjects_dir=fs_path) bem = mne.make_bem_solution(model) bem_file_out = op.join(meg_subj_path, "{}-bem.fif".format(subj)) mne.write_bem_solution(bem_file_out, bem) raw_files = files.get_files(meg_subj_path, "raw", "-raw.fif")[2] raw_files.sort() epo_files = files.get_files(meg_subj_path, "all", "-epo.fif")[2] epo_files.sort() trans_file = op.join(meg_subj_path, "{}-trans.fif".format(subj)) all_files = zip(raw_files, epo_files) for raw_file, epo_file in all_files: file_id = op.split(raw_file)[1].split("-")[1] fwd_out = op.join(meg_subj_path, "fwd-{}-fwd.fif".format(file_id))
def forward_model(subject, raw, fname_trans, src, subjects_dir, force_fixed=False, surf_ori=False, name='single-shell'): """construct forward model Parameters ---------- subject : str The name of subject raw : instance of rawBTI functionnal data fname_trans : str The filename of transformation matrix src : instance of SourceSpaces | list Sources of each interest hemisphere subjects_dir : str The subjects directory force_fixed: Boolean Force fixed source orientation mode name : str Use to save output Returns ------- fwd : instance of Forward ------- Author : Alexandre Fabre """ # Project 's directory subj_dir = '/hpc/comco/brovelli.a/db_mne/meg_te/' # files to save step fname_bem_model = subj_dir + '{0}/bem/{0}-{1}-bem.fif'.format( subject, name) fname_bem_sol = subj_dir + '{0}/bem/{0}-{1}-bem-sol.fif'.format( subject, name) fname_fwd = subj_dir + '{0}/fwd/{0}-{1}-fwd.fif'.format(subject, name) # Make bem model: single-shell model. Depends on anatomy only. model = mne.make_bem_model( subject, conductivity=[0.3], subjects_dir='/hpc/comco/brovelli.a/db_mne/meg_te/') mne.write_bem_surfaces(fname_bem_model, model) # Make bem solution. Depends on anatomy only. bem_sol = mne.make_bem_solution(model) mne.write_bem_solution(fname_bem_sol, bem_sol) # bem_sol=mne.read_bem_solution(fname_bem_sol) if len(src) == 2: # gather sources each the two hemispheres lh_src, rh_src = src src = lh_src + rh_src # Compute forward operator, commonly referred to as the gain or leadfield matrix. fwd = make_forward_solution(raw.info, fname_trans, src, bem_sol, fname_fwd, mindist=0.0, overwrite=True) # Set orientation of the source if force_fixed: # Force fixed fwd = mne.read_forward_solution(fname_fwd, force_fixed=True) elif surf_ori: # Surface normal fwd = mne.read_forward_solution(fname_fwd, surf_ori=True) else: # Free like a bird fwd = mne.read_forward_solution(fname_fwd) return fwd
from config import fname # Handle command line arguments parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('subject', metavar='sub###', type=int, help='The subject to process') args = parser.parse_args() subject = args.subject print('Processing subject:', subject) info = mne.io.read_info(fname.raw(subject=subject, run=1)) bem = mne.make_bem_model(fname.subject_id(subject=subject), ico=4, subjects_dir=fname.subjects_dir, conductivity=[0.3, 0.006, 0.3]) bem_sol = mne.make_bem_solution(bem) mne.write_bem_solution(fname.bem(subject=subject), bem_sol) src = mne.setup_volume_source_space(subject=fname.subject_id(subject=subject), bem=bem_sol, subjects_dir=fname.subjects_dir) fwd = mne.make_forward_solution(info=info, trans=fname.trans(subject=subject), src=src, bem=bem_sol, eeg=True) # Save things src.save(fname.src(subject=subject), overwrite=True) mne.write_forward_solution(fname.fwd(subject=subject), fwd, overwrite=True) # Visualize source space and MEG sensors fig = mne.viz.plot_alignment(info=info, trans=fname.trans(subject=subject), subject=fname.subject_id(subject=subject), subjects_dir=fname.subjects_dir, meg='sensors', src=src, bem=bem_sol) mlab.view(138, 73, 0.6, [0.02, 0.01, 0.03]) with mne.open_report(fname.report(subject=subject)) as report: report.add_figs_to_section(fig, 'Source space and MEG sensors', 'Source level', replace=True) report.save(fname.report_html(subject=subject), overwrite=True, open_browser=False)
# 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
#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 os.chdir('../covariance') fn = session1[n] + '-40-sss-cov.fif' cov = mne.read_cov(fn)