def test_coreg_gui_pyvista_file_support(inst_path, tmp_path, renderer_interactive_pyvistaqt): """Test reading supported files.""" from mne.gui import coregistration if inst_path == 'gen_montage': # generate a montage fig to use as inst. tmp_info = read_info(raw_path) eeg_chans = [] for pt in tmp_info['dig']: if pt['kind'] == FIFF.FIFFV_POINT_EEG: eeg_chans.append(f"EEG {pt['ident']:03d}") dig = DigMontage(dig=tmp_info['dig'], ch_names=eeg_chans) inst_path = tmp_path / 'tmp-dig.fif' dig.save(inst_path) if inst_path == ctf_raw_path: ctx = pytest.warns(RuntimeWarning, match='MEG ref channel RMSP') elif inst_path == snirf_nirsport2_raw_path: # TODO: This is maybe a bug? ctx = pytest.warns(RuntimeWarning, match='assuming "head"') else: ctx = nullcontext() with ctx: coregistration(inst=inst_path, subject='sample', subjects_dir=subjects_dir)
def test_coreg_gui_pyvista_file_support(inst_path, tmp_path, renderer_interactive_pyvistaqt): """Test reading supported files.""" from mne.gui import coregistration if inst_path == 'gen_montage': # generate a montage fig to use as inst. tmp_info = read_info(raw_path) eeg_chans = [] for pt in tmp_info['dig']: if pt['kind'] == FIFF.FIFFV_POINT_EEG: eeg_chans.append(f"EEG {pt['ident']:03d}") dig = DigMontage(dig=tmp_info['dig'], ch_names=eeg_chans) inst_path = tmp_path / 'tmp-dig.fif' dig.save(inst_path) # Suppressing warnings here is not ideal. # However ctf_raw_path (catch-alp-good-f.ds) is poorly formed and causes # mne.io.read_raw to issue warning. # XXX consider replacing ctf_raw_path and removing warning ignore filter. with warnings.catch_warnings(): warnings.simplefilter("ignore") coregistration(inst=inst_path, subject='sample', subjects_dir=subjects_dir)
def test_coreg_gui_notebook(renderer_notebook, nbexec): """Test the coregistration UI in a notebook.""" import os import mne from mne.datasets import testing from mne.gui import coregistration mne.viz.set_3d_backend('notebook') # set the 3d backend data_path = testing.data_path() subjects_dir = os.path.join(data_path, 'subjects') coregistration(subject='sample', subjects_dir=subjects_dir)
def test_coreg_gui_notebook(renderer_notebook, nbexec): """Test the coregistration UI in a notebook.""" import os import mne from mne.datasets import testing from mne.gui import coregistration mne.viz.set_3d_backend('notebook') # set the 3d backend with mne.utils.modified_env(_MNE_FAKE_HOME_DIR=None): data_path = testing.data_path(download=False) subjects_dir = os.path.join(data_path, 'subjects') coregistration(subject='sample', subjects_dir=subjects_dir)
def forward_pipeline(raw_fname, freesurfer_dir, subject, trans_fname=None, fwd_fname=None, oct_fname=None, bem_sol_fname=None, save_dir=None, overwrite=False): import os.path as op from jr.meg import check_freesurfer, mne_anatomy # Setup paths if save_dir is None: save_dir = '/'.join(raw_fname.split('/')[:-1]) print('Save/read directory: %s' % save_dir) if trans_fname is None: trans_fname = op.join(save_dir, subject + '-trans.fif') bem_sol_fname = op.join(freesurfer_dir, subject, 'bem', subject + '-5120-bem-sol.fif') oct_fname = op.join(freesurfer_dir, subject, 'bem', subject + '-oct-6-src.fif') fwd_fname = op.join(save_dir, subject + '-meg-fwd.fif') # Checks Freesurfer segmentation and compute watershed bem if check_freesurfer(subjects_dir=freesurfer_dir, subject=subject): mne_anatomy(subjects_dir=freesurfer_dir, subject=subject, overwrite=overwrite) # Manual coregisteration head markers with coils if overwrite or not op.isfile(trans_fname): from mne.gui import coregistration coregistration(subject=subject, subjects_dir=freesurfer_dir, inst=raw_fname) # Forward solution if overwrite or not op.exists(fwd_fname): from mne import (make_forward_solution, convert_forward_solution, write_forward_solution) fwd = make_forward_solution( raw_fname, trans_fname, oct_fname, bem_sol_fname, fname=None, meg=True, eeg=False, mindist=5.0, overwrite=True, ignore_ref=True) # convert to surface orientation for better visualization fwd = convert_forward_solution(fwd, surf_ori=True) # save write_forward_solution(fwd_fname, fwd, overwrite=True) else: from mne import read_forward_solution fwd = read_forward_solution(fwd_fname, surf_ori=True) return fwd
def test_coreg_gui_scraper(tmp_path, renderer_interactive_pyvistaqt): """Test the scrapper for the coregistration GUI.""" from mne.gui import coregistration coreg = coregistration(subject='sample', subjects_dir=subjects_dir, trans=fname_trans) (tmp_path / '_images').mkdir() image_path = str(tmp_path / '_images' / 'temp.png') gallery_conf = dict(builder_name='html', src_dir=str(tmp_path)) block_vars = dict(example_globals=dict(gui=coreg), image_path_iterator=iter([image_path])) assert not op.isfile(image_path) assert not getattr(coreg, '_scraped', False) mne.gui._GUIScraper()(None, block_vars, gallery_conf) assert op.isfile(image_path) assert coreg._scraped
def test_no_sparse_head(subjects_dir_tmp, renderer_interactive_pyvistaqt, monkeypatch): """Test mne.gui.coregistration with no sparse head.""" from mne.gui import coregistration subject = 'sample' out_rr, out_tris = mne.read_surface( op.join(subjects_dir_tmp, subject, 'bem', 'outer_skin.surf')) for head in ('sample-head.fif', 'outer_skin.surf'): os.remove(op.join(subjects_dir_tmp, subject, 'bem', head)) # Avoid actually doing the decimation (it's slow) monkeypatch.setattr(mne.coreg, 'decimate_surface', lambda rr, tris, n_triangles: (out_rr, out_tris)) with pytest.warns(RuntimeWarning, match='No low-resolution head found'): coreg = coregistration(inst=raw_path, subject=subject, subjects_dir=subjects_dir_tmp) coreg.close()
def test_coreg_gui_pyvista_basic(tmp_path, renderer_interactive_pyvistaqt, monkeypatch): """Test that using CoregistrationUI matches mne coreg.""" from mne.gui import coregistration config = get_config() # the sample subject in testing has MRI fids assert op.isfile( op.join(subjects_dir, 'sample', 'bem', 'sample-fiducials.fif')) coreg = coregistration(subject='sample', subjects_dir=subjects_dir, trans=fname_trans) assert coreg._lock_fids coreg._reset_fiducials() coreg.close() # make it always log the distances monkeypatch.setattr(_3d.logger, 'info', _3d.logger.warning) with catch_logging() as log: coreg = coregistration( inst=raw_path, subject='sample', head_high_res=False, # for speed subjects_dir=subjects_dir, verbose='debug') log = log.getvalue() assert 'Total 16/78 points inside the surface' in log coreg._set_fiducials_file(fid_fname) assert coreg._fiducials_file == fid_fname # fitting (with scaling) assert not coreg._mri_scale_modified coreg._reset() coreg._reset_fitting_parameters() coreg._set_scale_mode("uniform") coreg._fits_fiducials() assert_allclose(coreg.coreg._scale, np.array([97.46, 97.46, 97.46]) * 1e-2, atol=1e-3) shown_scale = [coreg._widgets[f's{x}'].get_value() for x in 'XYZ'] assert_allclose(shown_scale, coreg.coreg._scale * 100, atol=1e-2) coreg._set_icp_fid_match("nearest") coreg._set_scale_mode("3-axis") coreg._fits_icp() assert_allclose(coreg.coreg._scale, np.array([104.43, 101.47, 125.78]) * 1e-2, atol=1e-3) shown_scale = [coreg._widgets[f's{x}'].get_value() for x in 'XYZ'] assert_allclose(shown_scale, coreg.coreg._scale * 100, atol=1e-2) coreg._set_scale_mode("None") coreg._set_icp_fid_match("matched") assert coreg._mri_scale_modified # unlock fiducials assert coreg._lock_fids coreg._set_lock_fids(False) assert not coreg._lock_fids # picking assert not coreg._mri_fids_modified vtk_picker = TstVTKPicker(coreg._surfaces['head'], 0, (0, 0)) coreg._on_mouse_move(vtk_picker, None) coreg._on_button_press(vtk_picker, None) coreg._on_pick(vtk_picker, None) coreg._on_button_release(vtk_picker, None) coreg._on_pick(vtk_picker, None) # also pick when locked assert coreg._mri_fids_modified # lock fiducials coreg._set_lock_fids(True) assert coreg._lock_fids # fitting (no scaling) assert coreg._nasion_weight == 10. coreg._set_point_weight(11., 'nasion') assert coreg._nasion_weight == 11. coreg._fit_fiducials() with catch_logging() as log: coreg._redraw() # actually emit the log log = log.getvalue() assert 'Total 6/78 points inside the surface' in log with catch_logging() as log: coreg._fit_icp() coreg._redraw() log = log.getvalue() assert 'Total 38/78 points inside the surface' in log assert coreg.coreg._extra_points_filter is None coreg._omit_hsp() with catch_logging() as log: coreg._redraw() log = log.getvalue() assert 'Total 29/53 points inside the surface' in log assert coreg.coreg._extra_points_filter is not None coreg._reset_omit_hsp_filter() with catch_logging() as log: coreg._redraw() log = log.getvalue() assert 'Total 38/78 points inside the surface' in log assert coreg.coreg._extra_points_filter is None assert coreg._grow_hair == 0 coreg._fit_fiducials() # go back to few inside to start with catch_logging() as log: coreg._redraw() log = log.getvalue() assert 'Total 6/78 points inside the surface' in log norm = np.linalg.norm(coreg._head_geo['rr']) # what's used for inside assert_allclose(norm, 5.949288, atol=1e-3) coreg._set_grow_hair(20.0) with catch_logging() as log: coreg._redraw() assert coreg._grow_hair == 20.0 norm = np.linalg.norm(coreg._head_geo['rr']) assert_allclose(norm, 6.555220, atol=1e-3) # outward log = log.getvalue() assert 'Total 8/78 points inside the surface' in log # more outside now # visualization assert not coreg._helmet coreg._set_helmet(True) assert coreg._helmet assert coreg._orient_glyphs assert coreg._scale_by_distance assert coreg._mark_inside assert_allclose(coreg._head_opacity, float(config.get('MNE_COREG_HEAD_OPACITY', '0.8'))) assert coreg._hpi_coils assert coreg._eeg_channels assert coreg._head_shape_points assert coreg._scale_mode == 'None' assert coreg._icp_fid_match == 'matched' assert coreg._head_resolution is False assert coreg._trans_modified tmp_trans = tmp_path / 'tmp-trans.fif' coreg._save_trans(tmp_trans) assert not coreg._trans_modified assert op.isfile(tmp_trans) # first, disable auto cleanup coreg._renderer._window_close_disconnect(after=True) # test _close_callback() coreg.close() coreg._widgets['close_dialog'].trigger('Discard') # do not save coreg._clean() # finally, cleanup internal structures # Coregistration instance should survive assert isinstance(coreg.coreg, Coregistration) # Fullscreen mode coreg = coregistration(subject='sample', subjects_dir=subjects_dir, fullscreen=True)
"""MRI <--> head coordinates coregistration""" from argparse import ArgumentParser from mne.gui import coregistration from metacog import bp from metacog.paths import dirs parser = ArgumentParser(description=__doc__) parser.add_argument("subject", help="subject id") args = parser.parse_args() subj = args.subject info_src = bp.root.fpath(subject=subj, task="questions", run=1, session=None) trans_path = bp.trans.fpath(subject=subj) trans_path.parent.mkdir(exist_ok=True) trans_path = trans_path if trans_path.exists() else None coregistration( subject=f"sub-{subj}", subjects_dir=dirs.fsf_subjects, inst=info_src, trans=trans_path, )
def test_coreg_gui_pyvista(tmp_path, renderer_interactive_pyvistaqt): """Test that using CoregistrationUI matches mne coreg.""" from mne.gui import coregistration from mne.gui._coreg import CoregistrationUI config = get_config(home_dir=os.environ.get('_MNE_FAKE_HOME_DIR')) # the sample subject in testing has MRI fids assert op.isfile( op.join(subjects_dir, 'sample', 'bem', 'sample-fiducials.fif')) deprecated_params = ['standalone', 'head_transparency', 'project_eeg'] for param in deprecated_params: kwargs = {p: None for p in deprecated_params} kwargs[param] = True with pytest.warns(DeprecationWarning, match=f'{param} is deprecated'): coreg = CoregistrationUI(info_file=None, subject='sample', subjects_dir=subjects_dir, **kwargs) coreg.close() del kwargs deprecated_params = ['project_eeg'] for param in deprecated_params: kwargs = {p: None for p in deprecated_params} kwargs[param] = True with pytest.warns(DeprecationWarning, match=f'{param} is deprecated'): coreg = coregistration(subject='sample', subjects_dir=subjects_dir, **kwargs) coreg.close() del kwargs coreg = coregistration(subject='sample', subjects_dir=subjects_dir, trans=fname_trans) assert coreg._lock_fids coreg._reset_fiducials() coreg.close() coreg = coregistration(inst=raw_path, subject='sample', subjects_dir=subjects_dir) coreg._set_fiducials_file(fid_fname) assert coreg._fiducials_file == fid_fname # fitting (with scaling) assert not coreg._mri_scale_modified coreg._reset() coreg._reset_fitting_parameters() coreg._set_scale_mode("uniform") coreg._fits_fiducials() assert_allclose(coreg.coreg._scale, np.array([97.46, 97.46, 97.46]) * 1e-2, atol=1e-3) coreg._set_icp_fid_match("nearest") coreg._set_scale_mode("3-axis") coreg._fits_icp() assert_allclose(coreg.coreg._scale, np.array([104.43, 101.47, 125.78]) * 1e-2, atol=1e-3) coreg._set_scale_mode("None") coreg._set_icp_fid_match("matched") assert coreg._mri_scale_modified # unlock fiducials assert coreg._lock_fids coreg._set_lock_fids(False) assert not coreg._lock_fids # picking assert not coreg._mri_fids_modified vtk_picker = TstVTKPicker(coreg._surfaces['head'], 0, (0, 0)) coreg._on_mouse_move(vtk_picker, None) coreg._on_button_press(vtk_picker, None) coreg._on_pick(vtk_picker, None) coreg._on_button_release(vtk_picker, None) coreg._on_pick(vtk_picker, None) # also pick when locked assert coreg._mri_fids_modified # lock fiducials coreg._set_lock_fids(True) assert coreg._lock_fids # fitting (no scaling) assert coreg._nasion_weight == 10. coreg._set_point_weight(11., 'nasion') assert coreg._nasion_weight == 11. coreg._fit_fiducials() coreg._fit_icp() assert coreg.coreg._extra_points_filter is None coreg._omit_hsp() assert coreg.coreg._extra_points_filter is not None coreg._reset_omit_hsp_filter() assert coreg.coreg._extra_points_filter is None assert coreg._grow_hair == 0 coreg._set_grow_hair(0.1) assert coreg._grow_hair == 0.1 # visualization assert not coreg._helmet coreg._set_helmet(True) assert coreg._helmet assert coreg._orient_glyphs assert coreg._scale_by_distance assert coreg._mark_inside assert_allclose(coreg._head_opacity, float(config.get('MNE_COREG_HEAD_OPACITY', '0.8'))) assert coreg._hpi_coils assert coreg._eeg_channels assert coreg._head_shape_points assert coreg._scale_mode == 'None' assert coreg._icp_fid_match == 'matched' assert coreg._head_resolution == \ (config.get('MNE_COREG_HEAD_HIGH_RES', 'true') == 'true') assert coreg._trans_modified tmp_trans = tmp_path / 'tmp-trans.fif' coreg._save_trans(tmp_trans) assert not coreg._trans_modified assert op.isfile(tmp_trans) # first, disable auto cleanup coreg._renderer._window_close_disconnect(after=True) # test _close_callback() coreg.close() coreg._widgets['close_dialog'].trigger('Discard') # do not save coreg._clean() # finally, cleanup internal structures # Coregistration instance should survive assert isinstance(coreg.coreg, Coregistration)
def forward_pipeline(raw_fname, freesurfer_dir, subject, trans_fname=None, fwd_fname=None, oct_fname=None, bem_sol_fname=None, save_dir=None, overwrite=False): import os.path as op from jr.meg import check_freesurfer, mne_anatomy # Setup paths if save_dir is None: save_dir = '/'.join(raw_fname.split('/')[:-1]) print('Save/read directory: %s' % save_dir) if trans_fname is None: trans_fname = op.join(save_dir, subject + '-trans.fif') bem_sol_fname = op.join(freesurfer_dir, subject, 'bem', subject + '-5120-bem-sol.fif') oct_fname = op.join(freesurfer_dir, subject, 'bem', subject + '-oct-6-src.fif') fwd_fname = op.join(save_dir, subject + '-meg-fwd.fif') # Checks Freesurfer segmentation and compute watershed bem if check_freesurfer(subjects_dir=freesurfer_dir, subject=subject): mne_anatomy(subjects_dir=freesurfer_dir, subject=subject, overwrite=overwrite) # Manual coregisteration head markers with coils if overwrite or not op.isfile(trans_fname): from mne.gui import coregistration coregistration(subject=subject, subjects_dir=freesurfer_dir, inst=raw_fname) # Forward solution if overwrite or not op.exists(fwd_fname): from mne import (make_forward_solution, convert_forward_solution, write_forward_solution) fwd = make_forward_solution(raw_fname, trans_fname, oct_fname, bem_sol_fname, fname=None, meg=True, eeg=False, mindist=5.0, overwrite=True, ignore_ref=True) # convert to surface orientation for better visualization fwd = convert_forward_solution(fwd, surf_ori=True) # save write_forward_solution(fwd_fname, fwd, overwrite=True) else: from mne import read_forward_solution fwd = read_forward_solution(fwd_fname, surf_ori=True) return fwd
def test_coreg_gui_pyvista(tmp_path, renderer_interactive_pyvistaqt): """Test that using CoregistrationUI matches mne coreg.""" from mne.gui import coregistration config = get_config(home_dir=os.environ.get('_MNE_FAKE_HOME_DIR')) tmp_trans = tmp_path / 'tmp-trans.fif' # the sample subject in testing has MRI fids assert op.isfile( op.join(subjects_dir, 'sample', 'bem', 'sample-fiducials.fif')) coreg = coregistration(subject='sample', subjects_dir=subjects_dir, trans=fname_trans) assert coreg._lock_fids coreg._reset_fiducials() coreg.close() coreg = coregistration(inst=raw_path, subject='sample', subjects_dir=subjects_dir) coreg._set_fiducials_file(fid_fname) assert coreg._fiducials_file == fid_fname # unlock fiducials assert coreg._lock_fids coreg._set_lock_fids(False) assert not coreg._lock_fids # picking vtk_picker = TstVTKPicker(coreg._surfaces['head'], 0, (0, 0)) coreg._on_mouse_move(vtk_picker, None) coreg._on_button_press(vtk_picker, None) coreg._on_pick(vtk_picker, None) coreg._on_button_release(vtk_picker, None) coreg._on_pick(vtk_picker, None) # also pick when locked # lock fiducials coreg._set_lock_fids(True) assert coreg._lock_fids # fitting assert coreg._nasion_weight == 10. coreg._set_point_weight(11., 'nasion') assert coreg._nasion_weight == 11. coreg._fit_fiducials() coreg._fit_icp() assert coreg._coreg._extra_points_filter is None coreg._omit_hsp() assert coreg._coreg._extra_points_filter is not None coreg._reset_omit_hsp_filter() assert coreg._coreg._extra_points_filter is None assert coreg._grow_hair == 0 coreg._set_grow_hair(0.1) assert coreg._grow_hair == 0.1 # visualization assert coreg._orient_glyphs == \ (config.get('MNE_COREG_ORIENT_TO_SURFACE', '') == 'true') assert coreg._hpi_coils assert coreg._eeg_channels assert coreg._head_shape_points assert coreg._scale_mode == 'None' assert coreg._icp_fid_match == 'nearest' assert coreg._head_resolution == \ (config.get('MNE_COREG_HEAD_HIGH_RES', 'true') == 'true') assert not coreg._head_transparency coreg._set_head_transparency(True) assert coreg._head_transparency coreg._save_trans(tmp_trans) assert op.isfile(tmp_trans) coreg.close()
from mne.viz import plot_trans from mne.gui import coregistration if True: for meg_subject, subject in zip(range(1, 21), subjects_id): if subject in missing_mri + bad_mri: continue raw_fname = paths('sss', subject=meg_subject, block=1) trans_fname = paths('trans', subject=meg_subject) # XXX for one subject the HPI were adequately triangulated before the # first block if subject == 'ps120458': raw_fname.split('1-sss.fif')[0] + '2-sss.fif' # Manual coregistration print(subject, meg_subject) coregistration(subject=subject, subjects_dir=subjects_dir, inst=raw_fname) # Plot info = read_info(raw_fname) plot_trans(info, trans_fname, subject=subject, dig=True, meg_sensors=True) def _copy_from_fsaverage(subject, subjects_dir, overwrite=False): """Copy fsaverage files for subjects with missing MRI""" for this_dir in ['bem', 'surf']: bem_dir = os.path.join(subjects_dir, subject, this_dir) if not os.path.exists(bem_dir):
# Manual Coregistration ------------------------------------------------------- from mne.viz import plot_trans from mne.gui import coregistration if True: for meg_subject, subject in zip(range(1, 21), subjects_id): if subject in missing_mri + bad_mri: continue raw_fname = paths('sss', subject=meg_subject, block=1) trans_fname = paths('trans', subject=meg_subject) # XXX for one subject the HPI were adequately triangulated before the # first block if subject == 'ps120458': raw_fname.split('1-sss.fif')[0] + '2-sss.fif' # Manual coregistration print(subject, meg_subject) coregistration(subject=subject, subjects_dir=subjects_dir, inst=raw_fname) # Plot info = read_info(raw_fname) plot_trans(info, trans_fname, subject=subject, dig=True, meg_sensors=True) def _copy_from_fsaverage(subject, subjects_dir, overwrite=False): """Copy fsaverage files for subjects with missing MRI""" for this_dir in ['bem', 'surf']: bem_dir = os.path.join(subjects_dir, subject, this_dir) if not os.path.exists(bem_dir): os.makedirs(bem_dir) f_from = os.path.join(subjects_dir, 'fsaverage', 'bem', 'fsaverage-5120-bem.fif') f_to = os.path.join(subjects_dir, subject, 'bem',