def test_io_trans():
    """Test reading and writing of trans files
    """
    tempdir = _TempDir()
    os.mkdir(op.join(tempdir, 'sample'))
    assert_raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir)
    trans0 = read_trans(fname)
    fname1 = op.join(tempdir, 'sample', 'test-trans.fif')
    trans0.save(fname1)
    assert_true(fname1 == _find_trans('sample', subjects_dir=tempdir))
    trans1 = read_trans(fname1)

    # check all properties
    assert_true(trans0['from'] == trans1['from'])
    assert_true(trans0['to'] == trans1['to'])
    assert_array_equal(trans0['trans'], trans1['trans'])

    # check reading non -trans.fif files
    assert_raises(IOError, read_trans, fname_eve)

    # check warning on bad filenames
    with warnings.catch_warnings(record=True) as w:
        fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
        write_trans(fname2, trans0)
    assert_naming(w, 'test_transforms.py', 1)
Esempio n. 2
0
def test_io_trans():
    """Test reading and writing of trans files
    """
    tempdir = _TempDir()
    os.mkdir(op.join(tempdir, "sample"))
    assert_raises(RuntimeError, _find_trans, "sample", subjects_dir=tempdir)
    trans0 = read_trans(fname)
    fname1 = op.join(tempdir, "sample", "test-trans.fif")
    write_trans(fname1, trans0)
    assert_true(fname1 == _find_trans("sample", subjects_dir=tempdir))
    trans1 = read_trans(fname1)

    # check all properties
    assert_true(trans0["from"] == trans1["from"])
    assert_true(trans0["to"] == trans1["to"])
    assert_array_equal(trans0["trans"], trans1["trans"])

    # check reading non -trans.fif files
    assert_raises(IOError, read_trans, fname_eve)

    # check warning on bad filenames
    with warnings.catch_warnings(record=True) as w:
        fname2 = op.join(tempdir, "trans-test-bad-name.fif")
        write_trans(fname2, trans0)
    assert_true(len(w) >= 1)
Esempio n. 3
0
def test_get_head_mri_trans_ctf():
    """Test getting a trans object from BIDS data in CTF."""
    import nibabel as nib

    ctf_data_path = op.join(testing.data_path(), 'CTF')
    raw_ctf_fname = op.join(ctf_data_path, 'testdata_ctf.ds')
    raw_ctf = _read_raw_ctf(raw_ctf_fname)
    bids_root = _TempDir()
    bids_path = _bids_path.copy().update(root=bids_root)
    write_raw_bids(raw_ctf, bids_path, overwrite=False)

    # Take a fake trans
    trans = mne.read_trans(raw_fname.replace('_raw.fif', '-trans.fif'))

    # Get the T1 weighted MRI data file ... test write_anat with a nibabel
    # image instead of a file path
    t1w_mgh = op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz')
    t1w_mgh = nib.load(t1w_mgh)

    t1w_bids_path = BIDSPath(subject=subject_id,
                             session=session_id,
                             acquisition=acq,
                             root=bids_root)
    write_anat(t1w_mgh, bids_path=t1w_bids_path, raw=raw_ctf, trans=trans)

    # Try to get trans back through fitting points
    estimated_trans = get_head_mri_trans(bids_path=bids_path)

    assert_almost_equal(trans['trans'], estimated_trans['trans'])
Esempio n. 4
0
def test_plot_dipole_mri_orthoview():
    """Test mpl dipole plotting."""
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    for coord_frame, idx, show_all in zip(['head', 'mri'],
                                          ['gof', 'amplitude'], [True, False]):
        fig = dipoles.plot_locations(trans,
                                     'sample',
                                     subjects_dir,
                                     coord_frame=coord_frame,
                                     idx=idx,
                                     show_all=show_all,
                                     mode='orthoview')
        fig.canvas.scroll_event(0.5, 0.5, 1)  # scroll up
        fig.canvas.scroll_event(0.5, 0.5, -1)  # scroll down
        fig.canvas.key_press_event('up')
        fig.canvas.key_press_event('down')
        fig.canvas.key_press_event('a')  # some other key
    ax = plt.subplot(111)
    pytest.raises(TypeError,
                  dipoles.plot_locations,
                  trans,
                  'sample',
                  subjects_dir,
                  ax=ax)
    plt.close('all')
Esempio n. 5
0
def test_plot_dipole_mri_orthoview(coord_frame, idx, show_all, title):
    """Test mpl dipole plotting."""
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    fig = dipoles.plot_locations(trans=trans,
                                 subject='sample',
                                 subjects_dir=subjects_dir,
                                 coord_frame=coord_frame,
                                 idx=idx,
                                 show_all=show_all,
                                 title=title,
                                 mode='orthoview')
    fig.canvas.scroll_event(0.5, 0.5, 1)  # scroll up
    fig.canvas.scroll_event(0.5, 0.5, -1)  # scroll down
    fig.canvas.key_press_event('up')
    fig.canvas.key_press_event('down')
    fig.canvas.key_press_event('a')  # some other key
    ax = plt.subplot(111)
    pytest.raises(TypeError,
                  dipoles.plot_locations,
                  trans,
                  'sample',
                  subjects_dir,
                  ax=ax)
    plt.close('all')
def test_locate_scraper(_locate_ieeg, _fake_CT_coords, tmpdir):
    """Test sphinx-gallery scraping of the GUI."""
    raw = mne.io.read_raw_fif(raw_path)
    raw.pick_types(eeg=True)
    ch_dict = {
        'EEG 001': 'LAMY 1',
        'EEG 002': 'LAMY 2',
        'EEG 003': 'LSTN 1',
        'EEG 004': 'LSTN 2'
    }
    raw.pick_channels(list(ch_dict.keys()))
    raw.rename_channels(ch_dict)
    raw.set_montage(None)
    aligned_ct, _ = _fake_CT_coords
    trans = mne.read_trans(fname_trans)
    with pytest.warns(RuntimeWarning, match='`pial` surface not found'):
        gui = _locate_ieeg(raw.info,
                           trans,
                           aligned_ct,
                           subject=subject,
                           subjects_dir=subjects_dir)
    tmpdir.mkdir('_images')
    image_path = str(tmpdir.join('_images', 'temp.png'))
    gallery_conf = dict(builder_name='html', src_dir=str(tmpdir))
    block_vars = dict(example_globals=dict(gui=gui),
                      image_path_iterator=iter([image_path]))
    assert not op.isfile(image_path)
    assert not getattr(gui, '_scraped', False)
    mne.gui._LocateScraper()(None, block_vars, gallery_conf)
    assert op.isfile(image_path)
    assert gui._scraped
Esempio n. 7
0
def plot_coregistration(subject, subjects_dir, hcp_path, recordings_path,
                        info_from=(('data_type', 'rest'), ('run_index', 0)),
                        view_init=(('azim', 0), ('elev', 0))):
    """A diagnostic plot to show the HCP coregistration

    Parameters
    ----------
    subject : str
        The subject
    subjects_dir : str
        The path corresponding to MNE/freesurfer SUBJECTS_DIR (to be created)
    hcp_path : str
        The path where the HCP files can be found.
    recordings_path : str
        The path to converted data (including the head<->device transform).
    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.
    view_init : tuple of tuples | dict
        The initival view, defaults to azimuth and elevation of 0,
        a simple lateral view

    Returns
    -------
    fig : matplotlib.figure.Figure
        The figure object.
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D  #  noqa

    if isinstance(info_from, tuple):
        info_from = dict(info_from)
    if isinstance(view_init, tuple):
        view_init = dict(view_init)

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

    info = read_info(subject=subject, hcp_path=hcp_path, **info_from)

    info = pick_info(info, _pick_data_channels(info, with_ref_meg=False))
    sens_pnts = np.array([c['loc'][:3] for c in info['chs']])
    sens_pnts = apply_trans(head_mri_t, sens_pnts)
    sens_pnts *= 1e3  # put in mm scale

    pnts, tris = read_surface(
        op.join(subjects_dir, subject, 'bem', 'inner_skull.surf'))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(*sens_pnts.T, color='purple', marker='o')
    ax.scatter(*pnts.T, color='green', alpha=0.3)
    ax.view_init(**view_init)
    fig.tight_layout()
    return fig
Esempio n. 8
0
def test_plot_alignment_meg(renderer, system):
    """Test plotting of MEG sensors + helmet."""
    if system == 'Neuromag':
        this_info = read_info(evoked_fname)
    elif system == 'CTF':
        this_info = read_raw_ctf(ctf_fname).info
    elif system == 'BTi':
        this_info = read_raw_bti(
            pdf_fname, config_fname, hs_fname, convert=True,
            preload=False).info
    else:
        assert system == 'KIT'
        this_info = read_raw_kit(sqd_fname).info

    meg = ['helmet', 'sensors']
    if system == 'KIT':
        meg.append('ref')
    fig = plot_alignment(
        this_info, read_trans(trans_fname), subject='sample',
        subjects_dir=subjects_dir, meg=meg, eeg=False)
    assert isinstance(fig, Figure3D)
    # count the number of objects: should be n_meg_ch + 1 (helmet) + 1 (head)
    use_info = pick_info(this_info, pick_types(
        this_info, meg=True, eeg=False, ref_meg='ref' in meg, exclude=()))
    n_actors = use_info['nchan'] + 2
    _assert_n_actors(fig, renderer, n_actors)
    def compute_forward_and_inverse_solutions(self, orientation = 'fixed'):
        """docstring for compute_forward_solution"""

        info = self.grand_average_evoked.info
        trans = mne.read_trans(op.join(self.processed_files, '%s-trans.fif' %self.subject))
        src = glob.glob(op.join(self.subjects_dir, self.subject, 'bem', '*-ico-4-src.fif'))[0]
        bem = glob.glob(op.join(self.subjects_dir, self.subject, 'bem', '*-bem-sol.fif'))[0]
        fname = op.join(self.processed_files, '%s_forward.fif' %self.subject)

        # check if fwd exists, if not, make it
        if not op.exists(fname):
            fwd = mne.make_forward_solution(info = info, trans = trans, src = src,
                                            bem = bem, fname = fname, meg = True, eeg = False,
                                            overwrite = True, ignore_ref = True)

            self.add_preprocessing_notes("Forward solution generated and saved to %s" %fname)

        if orientation == 'fixed':
            force_fixed = True
        else:
            force_fixed = False

        fwd = mne.read_forward_solution(fname,force_fixed=force_fixed)

        self.forward_solution = fwd

        inv = mne.minimum_norm.make_inverse_operator(info, self.forward_solution, self.cov_reg, loose = None, depth = None, fixed = force_fixed)
        self.inverse_solution = inv
        mne.minimum_norm.write_inverse_operator(op.join(self.processed_files, '%s_inv.fif' %self.subject), self.inverse_solution)

        self.add_preprocessing_notes("Inverse solution generated and saved to %s" %op.join(self.processed_files, '%s_inv.fif' %self.subject))
        return fwd, inv
def read_transformation(name, save_dir):

    trans_name = name + '_dense-trans.fif'
    trans_path = join(save_dir, trans_name)
    trans = mne.read_trans(trans_path)

    return trans
def test_io_trans():
    """Test reading and writing of trans files
    """
    info0 = read_trans(fname)
    fname1 = op.join(tempdir, 'test-trans.fif')
    write_trans(fname1, info0)
    info1 = read_trans(fname1)

    # check all properties
    assert_true(info0['from'] == info1['from'])
    assert_true(info0['to'] == info1['to'])
    assert_array_equal(info0['trans'], info1['trans'])
    for d0, d1 in zip(info0['dig'], info1['dig']):
        assert_array_equal(d0['r'], d1['r'])
        for name in ['kind', 'ident', 'coord_frame']:
            assert_true(d0[name] == d1[name])
Esempio n. 12
0
def test_plot_dipole_locations():
    """Test plotting dipole locations."""
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    dipoles.plot_locations(trans, 'sample', subjects_dir, fig_name='foo')
    assert_raises(ValueError, dipoles.plot_locations, trans, 'sample',
                  subjects_dir, mode='foo')
Esempio n. 13
0
def test_do_forward_solution():
    """Test wrapping forward solution from python
    """
    mri = read_trans(fname_mri)
    fname_fake = op.join(temp_dir, 'no_have.fif')

    # ## Error checks
    # bad subject
    assert_raises(ValueError, do_forward_solution, 1, fname_raw,
                  subjects_dir=subjects_dir)
    # bad meas
    assert_raises(ValueError, do_forward_solution, 'sample', 1,
                  subjects_dir=subjects_dir)
    # meas doesn't exist
    assert_raises(IOError, do_forward_solution, 'sample', fname_fake,
                  subjects_dir=subjects_dir)
    # don't specify trans and meas
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  subjects_dir=subjects_dir)
    # specify both trans and meas
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  trans='me', mri='you', subjects_dir=subjects_dir)
    # specify non-existent trans
    assert_raises(IOError, do_forward_solution, 'sample', fname_raw,
                  trans=fname_fake, subjects_dir=subjects_dir)
    # specify non-existent mri
    assert_raises(IOError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_fake, subjects_dir=subjects_dir)
    # specify non-string mri
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=1, subjects_dir=subjects_dir)
    # specify non-string trans
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  trans=1, subjects_dir=subjects_dir)
    # test specifying an actual trans in python space -- this should work but
    # the transform I/O reduces our accuracy -- so we'll just hack a test here
    # by making it bomb with eeg=False and meg=False
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=mri, eeg=False, meg=False, subjects_dir=subjects_dir)
    # mindist as non-integer
    assert_raises(TypeError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, mindist=dict(), subjects_dir=subjects_dir)
    # mindist as string but not 'all'
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, eeg=False, mindist='yall',
                  subjects_dir=subjects_dir)
    # src, spacing, and bem as non-str
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, src=1, subjects_dir=subjects_dir)
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, spacing=1, subjects_dir=subjects_dir)
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, bem=1, subjects_dir=subjects_dir)
    # no overwrite flag
    assert_raises(IOError, do_forward_solution, 'sample', fname_raw,
                  existing_file, mri=fname_mri, subjects_dir=subjects_dir)
    # let's catch an MNE error, this time about trans being wrong
    assert_raises(CalledProcessError, do_forward_solution, 'sample',
                  fname_raw, existing_file, trans=fname_mri, overwrite=True,
                  spacing='oct6', subjects_dir=subjects_dir)
Esempio n. 14
0
def test_plot_alignment_surf(renderer):
    """Test plotting of a surface."""
    info = read_info(evoked_fname)
    fig = plot_alignment(
        info, read_trans(trans_fname), subject='sample',
        subjects_dir=subjects_dir, meg=False, eeg=False, dig=False,
        surfaces=['white', 'head'])
    _assert_n_actors(fig, renderer, 3)  # left and right hemis plus head
Esempio n. 15
0
def test_get_mri_head_t():
    """Test converting '-trans.txt' to '-trans.fif'"""
    trans = read_trans(fname)
    trans = invert_transform(trans)  # starts out as head->MRI, so invert
    trans_2 = _get_mri_head_t_from_trans_file(fname_trans)
    assert_equal(trans["from"], trans_2["from"])
    assert_equal(trans["to"], trans_2["to"])
    assert_allclose(trans["trans"], trans_2["trans"], rtol=1e-5, atol=1e-5)
Esempio n. 16
0
def test_get_trans():
    """Test converting '-trans.txt' to '-trans.fif'"""
    trans = read_trans(fname)
    trans = invert_transform(trans)  # starts out as head->MRI, so invert
    trans_2 = _get_trans(fname_trans)[0]
    assert_equal(trans['from'], trans_2['from'])
    assert_equal(trans['to'], trans_2['to'])
    assert_allclose(trans['trans'], trans_2['trans'], rtol=1e-5, atol=1e-5)
Esempio n. 17
0
def test_get_trans():
    """Test converting '-trans.txt' to '-trans.fif'"""
    trans = read_trans(fname)
    trans = invert_transform(trans)  # starts out as head->MRI, so invert
    trans_2 = _get_trans(fname_trans)[0]
    assert_equal(trans['from'], trans_2['from'])
    assert_equal(trans['to'], trans_2['to'])
    assert_allclose(trans['trans'], trans_2['trans'], rtol=1e-5, atol=1e-5)
Esempio n. 18
0
def test_plot_dipole_locations():
    """Test plotting dipole locations
    """
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    dipoles.plot_locations(trans, 'sample', subjects_dir, fig_name='foo')
    assert_raises(ValueError, dipoles.plot_locations, trans, 'sample',
                  subjects_dir, mode='foo')
Esempio n. 19
0
def make_anony_fwd(subject,
                   dir_base,
                   subjects_dir,
                   conductivity=(0.3, 0.006, 0.3),
                   ico=4):
    import os.path as op
    from mne.io.constants import FIFF
    from mne.bem import _surfaces_to_bem, _check_bem_size
    import glob
    import mayavi.mlab as mlab

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

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

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

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

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

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

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

        mne.write_forward_solution(
            op.join(dir_base, 'spatial', 'bems', m,
                    '%s_%s-fwd.fif' % (subject, m)), fwd)
Esempio n. 20
0
def test_combine():
    """Test combining transforms
    """
    trans = read_trans(fname)
    inv = invert_transform(trans)
    combine_transforms(trans, inv, trans["from"], trans["from"])
    assert_raises(RuntimeError, combine_transforms, trans, inv, trans["to"], trans["from"])
    assert_raises(RuntimeError, combine_transforms, trans, inv, trans["from"], trans["to"])
    assert_raises(RuntimeError, combine_transforms, trans, trans, trans["from"], trans["to"])
Esempio n. 21
0
def coreg_head2mri(subjects_dir, subject, native_fid, raw_path, raw_NosePtsOut, trans_dst, flag_fid=False):
    import scipy.io
    import numpy as np
    from mne.gui._coreg_gui import CoregModel
    
    model = CoregModel()
    model.mri.subjects_dir = subjects_dir
    model.mri.subject = subject
    
    # Remove Polhemus points around the nose (y>0, z<0)
    model.hsp.file = raw_path
    head_pts = model.hsp.points
    raw  = read_raw_fif(raw_path, preload=True)
    pos  = np.where((head_pts[:,1] <= 0) | (head_pts[:,2] >= 0))                                   
    dig  = raw.info['dig']
    dig2 = dig[0:8]
    dig3 = [dig[p+7] for p in pos[0]]
    dig_yeah = dig2+dig3
    raw.info['dig'] = dig_yeah
    raw.save(raw_NosePtsOut, overwrite=True)
    
    model.hsp.file = raw_NosePtsOut
    
    # Load CamCAN fiducials from matlab file
    if flag_fid:
        fid = scipy.io.loadmat(native_fid, struct_as_record=False, squeeze_me=True)
        fid = fid['fid']
  
        model.mri.lpa = np.reshape(fid.native.mm.lpa*0.001,(1,3))
        model.mri.nasion = np.reshape(fid.native.mm.nas*0.001,(1,3))
        model.mri.rpa = np.reshape(fid.native.mm.rpa*0.001,(1,3))
        assert (model.mri.fid_ok)
        
        lpa_distance = model.lpa_distance
        nasion_distance = model.nasion_distance
        rpa_distance = model.rpa_distance
              
        model.nasion_weight = 1.
        model.fit_fiducials(0)
        old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2
        new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 +
                 model.nasion_distance ** 2)
        assert new_x < old_x
        
    avg_point_distance = np.mean(model.point_distance)
    
    while True:
        model.fit_icp(0)
        new_dist = np.mean(model.point_distance)
        assert new_dist < avg_point_distance
        if model.status_text.endswith('converged)'):
            break
    
    model.save_trans(trans_dst)
    trans = mne.read_trans(trans_dst)
    np.testing.assert_allclose(trans['trans'], model.head_mri_t)
def test_eeg_field_interpolation():
    """Test interpolation of EEG field onto head
    """
    trans = read_trans(trans_fname)
    info = read_info(evoked_fname)
    surf = get_head_surface('sample', subjects_dir=subjects_dir)
    # we must have trans if surface is in MRI coords
    assert_raises(ValueError, make_surface_mapping, info, surf, 'eeg')
    data = make_surface_mapping(info, surf, 'eeg', trans, mode='accurate')
    assert_array_equal(data.shape, (2562, 60))  # maps data onto surf
Esempio n. 23
0
def test_plot_dipole_orientations(renderer):
    """Test dipole plotting in 3d."""
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    for coord_frame, mode in zip(['head', 'mri'],
                                 ['arrow', 'sphere']):
        dipoles.plot_locations(trans=trans, subject='sample',
                               subjects_dir=subjects_dir,
                               mode=mode, coord_frame=coord_frame)
    renderer._close_all()
Esempio n. 24
0
def make_forward_solution(experiment,
                          subject,
                          spacing,
                          process_slug=DEFAULT_PROC):
    struct = sub_to_struct[experiment][subject]
    if struct == 'NA':
        raise IOError(
            'Freesurfer Reconstruction has not yet been done for this subject. See the Freesurfer Recommended Reconstruction page.')

    trans_fname = TRANS_FNAME.format(experiment=experiment, subject=subject, struct=struct)

    if not os.path.isfile(trans_fname):
        raise IOError(
            'Coregistration has not yet been done for this subject. Use mne_analyze on big-brain and follow MNE handbook chapter 7.')

    trans = mne.read_trans(trans_fname)

    fwd_path = FWD_PATH.format(experiment=experiment, subject=subject)
    if not os.path.exists(fwd_path):
        try:
            os.mkdir(fwd_path)
        except:
            os.mkdir(FWD_PATH.format(experiment=experiment, subject=''))
            os.mkdir(fwd_path)

    fwd_fname = FWD_FNAME.format(fwd_path=fwd_path, subject=subject, experiment=experiment, process_slug=process_slug,
                                 struct=struct, spacing=spacing)

    raw = mne.io.Raw(PROC_FNAME.format(experiment=experiment, subject=subject, process_slug=process_slug))

    bem_path = [fn for fn in os.listdir(BEM_PATH.format(struct=struct)) if fnmatch.fnmatch(fn, '*-bem-sol.fif')]

    if len(bem_path) == 0:
        raise IOError('BEM has not yet been done for this subject. See MNE_pipeline_2018.sh')

    bem_fname = pjoin(BEM_PATH.format(struct=struct), bem_path[0])

    src_file = SRC_FNAME.format(struct=struct, spacing=spacing)

    mne.set_config('SUBJECTS_DIR', SUBJ_DIR)

    # Not sure how to make sure this runs effectively
    if os.path.isfile(src_file):
        src = mne.read_source_spaces(src_file)
    else:
        src = mne.setup_source_space(struct, spacing='oct6')
        mne.write_source_spaces(src_file, src)

    fwd = mne.make_forward_solution(raw.info, trans,
                                    src=src,
                                    bem=bem_fname)

    mne.write_forward_solution(fwd_fname, fwd)

    return fwd
Esempio n. 25
0
def _get_bem_src_trans(p, info, subj, struc):
    subjects_dir = get_subjects_dir(p.subjects_dir, raise_error=True)
    assert isinstance(subjects_dir, str)
    if struc is None:  # spherical case
        bem, src, trans = _spherical_conductor(info, subj, p.src_pos)
        bem_type = 'spherical-model'
    else:
        from mne.transforms import _ensure_trans
        trans = op.join(p.work_dir, subj, p.trans_dir, subj + '-trans.fif')
        if not op.isfile(trans):
            old = trans
            trans = op.join(p.work_dir, subj, p.trans_dir,
                            subj + '-trans_head2mri.txt')
            if not op.isfile(trans):
                raise IOError('Unable to find head<->MRI trans files in:\n'
                              '%s\n%s' % (old, trans))
        trans = read_trans(trans)
        trans = _ensure_trans(trans, 'mri', 'head')
        this_src = _handle_dict(p.src, subj)
        assert isinstance(this_src, str)
        if this_src.startswith('oct'):
            kind = 'oct'
        elif this_src.startswith('vol'):
            kind = 'vol'
        else:
            raise RuntimeError('Unknown source space type %s, must be '
                               'oct or vol' % (this_src, ))
        num = int(this_src.split(kind)[-1].split('-')[-1])
        bem = op.join(subjects_dir, struc, 'bem',
                      '%s-%s-bem-sol.fif' % (struc, p.bem_type))
        for mid in ('', '-'):
            src_space_file = op.join(
                subjects_dir, struc, 'bem',
                '%s-%s%s%s-src.fif' % (struc, kind, mid, num))
            if op.isfile(src_space_file):
                break
        else:  # if neither exists, use last filename
            print('    Creating %s%s source space for %s...' %
                  (kind, num, subj))
            if kind == 'oct':
                src = setup_source_space(struc,
                                         spacing='%s%s' % (kind, num),
                                         subjects_dir=p.subjects_dir,
                                         n_jobs=p.n_jobs)
            else:
                assert kind == 'vol'
                src = setup_volume_source_space(struc,
                                                pos=num,
                                                bem=bem,
                                                subjects_dir=p.subjects_dir)
            write_source_spaces(src_space_file, src)
        src = read_source_spaces(src_space_file)
        bem = read_bem_solution(bem, verbose=False)
        bem_type = ('%s-layer BEM' % len(bem['surfs']))
    return bem, src, trans, bem_type
Esempio n. 26
0
def make_forward_solution(info,
                          trans_fname,
                          src,
                          bem_model,
                          meg=True,
                          eeg=True,
                          mindist=0.0,
                          ignore_ref=False,
                          n_jobs=1,
                          verbose=None):
    assert not meg  # XXX for now

    coord_frame = 'head'
    trans = mne.read_trans(trans_fname)
    head_trans, meg_trans, mri_trans = _prepare_trans(info, trans, coord_frame)

    dipoles = _get_dipoles(src, mri_trans, head_trans)
    eeg_electrodes, ch_names = _get_sensors(info, head_trans)

    geom = _get_geom_files(bem_model, mri_trans, head_trans)
    assert geom.is_nested()
    assert geom.selfCheck()

    # OpenMEEG
    gauss_order = 3
    use_adaptive_integration = True
    # dipole_in_cortex = True

    hm = om.HeadMat(geom, gauss_order)
    hm.invert()
    hminv = hm
    dsm = om.DipSourceMat(geom, dipoles, gauss_order, use_adaptive_integration,
                          "Brain")

    # For EEG
    eeg_picks = mne.pick_types(info, meg=False, eeg=True)
    # meg_picks = mne.pick_types(info, meg=True, eeg=False)
    # seeg_picks = mne.pick_types(info, meg=False, seeg=True)

    if eeg and len(eeg_picks) > 0:
        h2em = om.Head2EEGMat(geom, eeg_electrodes)
        eeg_leadfield = om.GainEEG(hminv, dsm, h2em)
        eegfwd = _make_forward(eeg_leadfield, ch_names, info, src, trans_fname)

    # if meg and len(meg_picks) > 0:
    #     h2em = om.Head2EEGMat(geom, eeg_electrodes)
    #     eeg_leadfield = om.GainEEG(hminv, dsm, h2em)
    #     megfwd = _make_forward(eeg_leadfield, ch_names, info, src, trans_fname)

    # # merge forwards
    # fwd = _merge_meg_eeg_fwds(_to_forward_dict(megfwd, megnames),
    #                           _to_forward_dict(eegfwd, eegnames),
    #                           verbose=False)

    return eegfwd
Esempio n. 27
0
def test_combine():
    """Test combining transforms."""
    trans = read_trans(fname)
    inv = invert_transform(trans)
    combine_transforms(trans, inv, trans['from'], trans['from'])
    pytest.raises(RuntimeError, combine_transforms, trans, inv, trans['to'],
                  trans['from'])
    pytest.raises(RuntimeError, combine_transforms, trans, inv, trans['from'],
                  trans['to'])
    pytest.raises(RuntimeError, combine_transforms, trans, trans,
                  trans['from'], trans['to'])
Esempio n. 28
0
def test_get_head_mri_trans():
    """Test getting a trans object from BIDS data."""
    import nibabel as nib

    event_id = {'Auditory/Left': 1, 'Auditory/Right': 2, 'Visual/Left': 3,
                'Visual/Right': 4, 'Smiley': 5, 'Button': 32}
    events_fname = op.join(data_path, 'MEG', 'sample',
                           'sample_audvis_trunc_raw-eve.fif')

    # Drop unknown events.
    events = mne.read_events(events_fname)
    events = events[events[:, 2] != 0]

    # Write it to BIDS
    raw = _read_raw_fif(raw_fname)
    bids_root = _TempDir()
    bids_path = _bids_path.copy().update(root=bids_root)
    write_raw_bids(raw, bids_path, events_data=events, event_id=event_id,
                   overwrite=False)

    # We cannot recover trans, if no MRI has yet been written
    with pytest.raises(RuntimeError):
        estimated_trans = get_head_mri_trans(bids_path=bids_path)

    # Write some MRI data and supply a `trans` so that a sidecar gets written
    trans = mne.read_trans(raw_fname.replace('_raw.fif', '-trans.fif'))

    # Get the T1 weighted MRI data file ... test write_anat with a nibabel
    # image instead of a file path
    t1w_mgh = op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz')
    t1w_mgh = nib.load(t1w_mgh)

    t1w_bidspath = BIDSPath(subject=subject_id, session=session_id,
                            acquisition=acq, root=bids_root)
    t1w_bidspath = write_anat(t1w_mgh, bids_path=t1w_bidspath,
                              raw=raw, trans=trans, verbose=True)
    anat_dir = t1w_bidspath.directory

    # Try to get trans back through fitting points
    estimated_trans = get_head_mri_trans(bids_path=bids_path)

    assert trans['from'] == estimated_trans['from']
    assert trans['to'] == estimated_trans['to']
    assert_almost_equal(trans['trans'], estimated_trans['trans'])
    print(trans)
    print(estimated_trans)

    # provoke an error by introducing NaNs into MEG coords
    with pytest.raises(RuntimeError, match='AnatomicalLandmarkCoordinates'):
        raw.info['dig'][0]['r'] = np.ones(3) * np.nan
        sh.rmtree(anat_dir)
        bids_path = write_anat(t1w_mgh, bids_path=t1w_bidspath,
                               raw=raw, trans=trans, verbose=True)
        estimated_trans = get_head_mri_trans(bids_path=bids_path)
Esempio n. 29
0
def test_combine():
    """Test combining transforms."""
    trans = read_trans(fname)
    inv = invert_transform(trans)
    combine_transforms(trans, inv, trans['from'], trans['from'])
    pytest.raises(RuntimeError, combine_transforms, trans, inv,
                  trans['to'], trans['from'])
    pytest.raises(RuntimeError, combine_transforms, trans, inv,
                  trans['from'], trans['to'])
    pytest.raises(RuntimeError, combine_transforms, trans, trans,
                  trans['from'], trans['to'])
Esempio n. 30
0
    def compute_forward_and_inverse_solutions(self, orientation='fixed'):
        """docstring for compute_forward_solution"""

        info = self.grand_average_evoked.info
        trans = mne.read_trans(
            op.join(self.processed_files, '%s-trans.fif' % self.subject))
        src = glob.glob(
            op.join(self.subjects_dir, self.subject, 'bem',
                    '*-ico-4-src.fif'))[0]
        bem = glob.glob(
            op.join(self.subjects_dir, self.subject, 'bem',
                    '*-bem-sol.fif'))[0]
        fname = op.join(self.processed_files, '%s_forward.fif' % self.subject)

        # check if fwd exists, if not, make it
        if not op.exists(fname):
            fwd = mne.make_forward_solution(info=info,
                                            trans=trans,
                                            src=src,
                                            bem=bem,
                                            fname=fname,
                                            meg=True,
                                            eeg=False,
                                            overwrite=True,
                                            ignore_ref=True)

            self.add_preprocessing_notes(
                "Forward solution generated and saved to %s" % fname)

        if orientation == 'fixed':
            force_fixed = True
        else:
            force_fixed = False

        fwd = mne.read_forward_solution(fname, force_fixed=force_fixed)

        self.forward_solution = fwd

        inv = mne.minimum_norm.make_inverse_operator(info,
                                                     self.forward_solution,
                                                     self.cov_reg,
                                                     loose=None,
                                                     depth=None,
                                                     fixed=force_fixed)
        self.inverse_solution = inv
        mne.minimum_norm.write_inverse_operator(
            op.join(self.processed_files, '%s_inv.fif' % self.subject),
            self.inverse_solution)

        self.add_preprocessing_notes(
            "Inverse solution generated and saved to %s" %
            op.join(self.processed_files, '%s_inv.fif' % self.subject))
        return fwd, inv
Esempio n. 31
0
def test_io_trans():
    """Test reading and writing of trans files
    """
    trans0 = read_trans(fname)
    fname1 = op.join(tempdir, 'test-trans.fif')
    write_trans(fname1, trans0)
    trans1 = read_trans(fname1)

    # check all properties
    assert_true(trans0['from'] == trans1['from'])
    assert_true(trans0['to'] == trans1['to'])
    assert_array_equal(trans0['trans'], trans1['trans'])

    # check reading non -trans.fif files
    assert_raises(IOError, read_trans, fname_eve)
    
    # check warning on bad filenames
    with warnings.catch_warnings(record=True) as w:
        fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
        write_trans(fname2, trans0)
    assert_true(len(w) >= 1)
Esempio n. 32
0
def test_io_trans():
    """Test reading and writing of trans files."""
    tempdir = _TempDir()
    os.mkdir(op.join(tempdir, 'sample'))
    pytest.raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir)
    trans0 = read_trans(fname)
    fname1 = op.join(tempdir, 'sample', 'test-trans.fif')
    trans0.save(fname1)
    assert fname1 == _find_trans('sample', subjects_dir=tempdir)
    trans1 = read_trans(fname1)

    # check all properties
    assert trans0 == trans1

    # check reading non -trans.fif files
    pytest.raises(IOError, read_trans, fname_eve)

    # check warning on bad filenames
    fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
    with pytest.warns(RuntimeWarning, match='-trans.fif'):
        write_trans(fname2, trans0)
Esempio n. 33
0
def test_io_trans():
    """Test reading and writing of trans files."""
    tempdir = _TempDir()
    os.mkdir(op.join(tempdir, 'sample'))
    pytest.raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir)
    trans0 = read_trans(fname)
    fname1 = op.join(tempdir, 'sample', 'test-trans.fif')
    trans0.save(fname1)
    assert fname1 == _find_trans('sample', subjects_dir=tempdir)
    trans1 = read_trans(fname1)

    # check all properties
    assert trans0 == trans1

    # check reading non -trans.fif files
    pytest.raises(IOError, read_trans, fname_eve)

    # check warning on bad filenames
    fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
    with pytest.warns(RuntimeWarning, match='-trans.fif'):
        write_trans(fname2, trans0)
Esempio n. 34
0
def test_io_trans():
    """Test reading and writing of trans files."""
    tempdir = _TempDir()
    os.mkdir(op.join(tempdir, 'sample'))
    pytest.raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir)
    trans0 = read_trans(fname)
    fname1 = op.join(tempdir, 'sample', 'test-trans.fif')
    trans0.save(fname1)
    assert fname1 == _find_trans('sample', subjects_dir=tempdir)
    trans1 = read_trans(fname1)

    # check all properties
    assert trans0 == trans1

    # check reading non -trans.fif files
    pytest.raises(IOError, read_trans, fname_eve)

    # check warning on bad filenames
    with warnings.catch_warnings(record=True) as w:
        fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
        write_trans(fname2, trans0)
    assert_naming(w, 'test_transforms.py', 1)
Esempio n. 35
0
def _make_forward(eeg_leadfield, ch_names, info, src, trans_fname):
    fwd = eeg_leadfield.array().astype(np.float32).T
    fwd = _to_forward_dict(fwd, ch_names)
    picks = mne.pick_channels(info['ch_names'], ch_names)
    fwd['info'] = mne.pick_info(info, picks)
    fwd['info']['mri_file'] = trans_fname
    fwd['info']['mri_id'] = fwd['info']['file_id']
    fwd['mri_head_t'] = invert_transform(mne.read_trans(trans_fname))
    fwd['info']['mri_head_t'] = fwd['mri_head_t']
    fwd['info']['meas_file'] = ""
    fwd['src'] = src
    fwd['surf_ori'] = False
    return fwd
def test_compute_distance_to_sensors(picks, limits):
    """Test computation of distances between vertices and sensors."""
    src = read_source_spaces(fname_src)
    fwd = mne.read_forward_solution(fname_fwd)
    info = fwd['info']
    trans = read_trans(trans_fname)
    # trans = fwd['info']['mri_head_t']
    if isinstance(picks, str):
        kwargs = dict()
        kwargs[picks] = True
        if picks == 'eeg':
            info['dev_head_t'] = None  # should not break anything
        use_picks = pick_types(info, **kwargs, exclude=())
    else:
        use_picks = picks
    n_picks = len(_picks_to_idx(info, use_picks, 'data', exclude=()))

    # Make sure same vertices are used in src and fwd
    src[0]['inuse'] = fwd['src'][0]['inuse']
    src[1]['inuse'] = fwd['src'][1]['inuse']
    src[0]['nuse'] = fwd['src'][0]['nuse']
    src[1]['nuse'] = fwd['src'][1]['nuse']

    n_verts = src[0]['nuse'] + src[1]['nuse']

    # minimum distances between vertices and sensors
    depths = compute_distance_to_sensors(src,
                                         info=info,
                                         picks=use_picks,
                                         trans=trans)
    assert depths.shape == (n_verts, n_picks)
    assert limits[0] * 5 > depths.min()  # meaningful choice of limits
    assert_array_less(limits[0], depths)
    assert_array_less(depths, limits[1])

    # If source space from Forward Solution and trans=None (i.e. identity) then
    # depths2 should be the same as depth.
    depths2 = compute_distance_to_sensors(src=fwd['src'],
                                          info=info,
                                          picks=use_picks,
                                          trans=None)
    assert_allclose(depths, depths2, rtol=1e-5)

    if picks != 'eeg':
        # this should break things
        info['dev_head_t'] = None
        with pytest.raises(ValueError, match='Transform between meg<->head'):
            compute_distance_to_sensors(src, info, use_picks, trans)
Esempio n. 37
0
    def plotAlignment(subjectName):
        
        """
        Usage example:
        -----------------------------
        
        from uhClass import Forward     
        subjectName = 'xS9017'
        Forward.plotAlignment(subjectName)            
        """

        import glob, os
        # mainDir = 'C:\\uhdata\\freesurfer'
        
        mainDir = Forward.mainDir
        path = os.path.join(mainDir, subjectName)
        os.chdir(path)

        trans = glob.glob('*-trans.fif')
        # bemsol = glob.glob('*-bemsol.fif')
        
        src = glob.glob('*-src.fif')
        epo = glob.glob('*-epo.fif')

        info = mne.io.read_info(epo[0])

        # read source space
        stc = mne.source_space.read_source_spaces(os.path.join(path, src[0]))

        # read bem solution
        # bem_path = os.path.join(path, bemsol)
        # bem = mne.read_bem_solution(bem_path)

        # read transformation matrix
        trans_path = os.path.join(path, trans[0])
        trans = mne.read_trans(trans_path)
        
       # Here we look at the dense head, which isn't used for BEM computations but
       # is useful for coregistration.
       
        mne.viz.plot_alignment(info, trans=trans, 
                               subject=subjectName, 
                               subjects_dir=mainDir,
                               surfaces=['head'], coord_frame='head', meg=None,
                               eeg='original', dig=True, ecog=False, 
                               src=stc, mri_fiducials=False, bem=None,
                               seeg=False, show_axes=False, fig=None,
                               interaction ='trackball', verbose=None)                
Esempio n. 38
0
def run(args=None, config=None):
    parser = AnalysisParser('config')
    args = parser.parse_analysis_args(args)
    config = args.config

	print(__doc__)

	data_path = sample.data_path()
	subjects_dir = op.join(data_path, 'subjects')
	raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
	trans_fname = op.join(data_path, 'MEG', 'sample',
	                      'sample_audvis_raw-trans.fif')
	raw = mne.io.read_raw_fif(raw_fname)
	trans = mne.read_trans(trans_fname)
	src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',
	                                     'sample-oct-6-src.fif'))
Esempio n. 39
0
def dip_source_loc(evoked, cov,  fs_subj, study_path, plot=False):
    evo_crop = evoked.copy().crop(-0.003, 0.003)
    subj = fs_subj.strip('_an') if fs_subj.find('_an') > 0 else fs_subj
    img_type = 'anony' if fs_subj.find('_an') > 0 else 'orig'

    trans_fname = op.join(study_path, 'source_stim', subj, 'source_files', img_type, '%s_fid-trans.fif' % fs_subj)
    bem_fname = op.join(subjects_dir, fs_subj, 'bem', '%s-bem-sol.fif' % fs_subj)

    cond = evoked.info['description']
    stim_coords = find_stim_coords(cond, subj, study_path)

    dip, res = mne.fit_dipole(evo_crop, cov, bem_fname, trans_fname, min_dist=10, n_jobs=3)

    import mne.transforms as tra
    from scipy import linalg
    trans = mne.read_trans(trans_fname)

    stim_point = stim_coords['surf']  # get point for plot in mm
    #dip.pos[np.argmax(dip.gof)] = tra.apply_trans(surf_to_head, stim_coords['surf_ori']/1e3)  # check stim loc (apply affine in m)

    dip_surf = tra.apply_trans(trans['trans'], dip.pos[np.argmax(dip.gof)]) * 1e3  # transform from head to surface
    dist_surf = euclidean(dip_surf, stim_point)  # compute distance in surface space
    print(dist_surf)

    if plot:
        # Plot the result in 3D brain with the MRI image.
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        dip.plot_locations(trans_fname, fs_subj, subjects_dir, mode='orthoview', coord_frame='mri', ax=ax, show_all=True,
                           idx='gof')
        ax.scatter(stim_point[0], stim_point[1], stim_point[2])
        ax.plot([stim_point[0], -128], [stim_point[1], stim_point[1]], [stim_point[2], stim_point[2]], color='g')
        ax.plot([stim_point[0], stim_point[0]], [stim_point[1], -128], [stim_point[2], stim_point[2]], color='g')
        ax.plot([stim_point[0], stim_point[0]], [stim_point[1], stim_point[1]], [stim_point[2], -128], color='g')
        ax.text2D(0.05, 0.90, 'distance: %i mm \nstim coords = %0.1f %0.1f %0.1f' % (dist_surf, stim_point[0], stim_point[1], stim_point[2]),
                  transform=ax.transAxes)
        red_patch = mpatches.Patch(color='red')
        green_patch = mpatches.Patch(color='green')
        fig.legend(handles=[red_patch, green_patch], labels=['dipole', 'electrode'])

        fig.savefig(op.join(study_path, 'source_stim', subj, 'figures', 'dipole', '%s_dip_15mm.png' % cond))
        plt.close()

        plot_dipole_amplitudes(dip)
        plot_dipole_locations(dip, trans, subj, subjects_dir=subjects_dir)
    return dist_surf
Esempio n. 40
0
def _get_data():
    """Helper to get some starting data"""
    # raw with ECG channel
    raw = Raw(raw_fname).crop(0.0, 5.0).load_data()
    data_picks = pick_types(raw.info, meg=True, eeg=True)
    other_picks = pick_types(raw.info, meg=False, stim=True, eog=True)
    picks = np.sort(np.concatenate((data_picks[::16], other_picks)))
    raw = raw.pick_channels([raw.ch_names[p] for p in picks])
    ecg = RawArray(np.zeros((1, len(raw.times))), create_info(["ECG 063"], raw.info["sfreq"], "ecg"))
    for key in ("dev_head_t", "buffer_size_sec", "highpass", "lowpass", "filename", "dig"):
        ecg.info[key] = raw.info[key]
    raw.add_channels([ecg])

    src = read_source_spaces(src_fname)
    trans = read_trans(trans_fname)
    sphere = make_sphere_model("auto", "auto", raw.info)
    stc = _make_stc(raw, src)
    return raw, src, stc, trans, sphere
Esempio n. 41
0
def test_plot_dipole_mri_orthoview():
    """Test mpl dipole plotting."""
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    for coord_frame, idx, show_all in zip(['head', 'mri'],
                                          ['gof', 'amplitude'], [True, False]):
        fig = dipoles.plot_locations(trans, 'sample', subjects_dir,
                                     coord_frame=coord_frame, idx=idx,
                                     show_all=show_all, mode='orthoview')
        fig.canvas.scroll_event(0.5, 0.5, 1)  # scroll up
        fig.canvas.scroll_event(0.5, 0.5, -1)  # scroll down
        fig.canvas.key_press_event('up')
        fig.canvas.key_press_event('down')
        fig.canvas.key_press_event('a')  # some other key
    ax = plt.subplot(111)
    pytest.raises(TypeError, dipoles.plot_locations, trans, 'sample',
                  subjects_dir, ax=ax)
    plt.close('all')
Esempio n. 42
0
def _get_data():
    """Helper to get some starting data."""
    # raw with ECG channel
    raw = read_raw_fif(raw_fname).crop(0., 5.0).load_data()
    data_picks = pick_types(raw.info, meg=True, eeg=True)
    other_picks = pick_types(raw.info, meg=False, stim=True, eog=True)
    picks = np.sort(np.concatenate((data_picks[::16], other_picks)))
    raw = raw.pick_channels([raw.ch_names[p] for p in picks])
    raw.info.normalize_proj()
    ecg = RawArray(np.zeros((1, len(raw.times))),
                   create_info(['ECG 063'], raw.info['sfreq'], 'ecg'))
    for key in ('dev_head_t', 'buffer_size_sec', 'highpass', 'lowpass', 'dig'):
        ecg.info[key] = raw.info[key]
    raw.add_channels([ecg])

    src = read_source_spaces(src_fname)
    trans = read_trans(trans_fname)
    sphere = make_sphere_model('auto', 'auto', raw.info)
    stc = _make_stc(raw, src)
    return raw, src, stc, trans, sphere
Esempio n. 43
0
def raw_data():
    """Get some starting data."""
    # raw with ECG channel
    raw = read_raw_fif(raw_fname).crop(0., 5.0).load_data()
    data_picks = pick_types(raw.info, meg=True, eeg=True)
    other_picks = pick_types(raw.info, meg=False, stim=True, eog=True)
    picks = np.sort(np.concatenate((data_picks[::16], other_picks)))
    raw = raw.pick_channels([raw.ch_names[p] for p in picks])
    raw.info.normalize_proj()
    ecg = RawArray(np.zeros((1, len(raw.times))),
                   create_info(['ECG 063'], raw.info['sfreq'], 'ecg'))
    for key in ('dev_head_t', 'highpass', 'lowpass', 'dig'):
        ecg.info[key] = raw.info[key]
    raw.add_channels([ecg])

    src = read_source_spaces(src_fname)
    trans = read_trans(trans_fname)
    sphere = make_sphere_model('auto', 'auto', raw.info)
    stc = _make_stc(raw, src)
    return raw, src, stc, trans, sphere
Esempio n. 44
0
def test_head_to_mni():
    """Test conversion of aseg vertices to MNI coordinates."""
    # obtained using freeview
    coords = np.array([[22.52, 11.24, 17.72], [22.52, 5.46, 21.58],
                       [16.10, 5.46, 22.23], [21.24, 8.36, 22.23]])

    xfm = _read_talxfm('sample', subjects_dir)
    coords_MNI = apply_trans(xfm['trans'], coords)

    trans = read_trans(trans_fname)  # head->MRI (surface RAS)
    mri_head_t = invert_transform(trans)  # MRI (surface RAS)->head matrix

    # obtained from sample_audvis-meg-oct-6-mixed-fwd.fif
    coo_right_amygdala = np.array([[0.01745682,  0.02665809,  0.03281873],
                                   [0.01014125,  0.02496262,  0.04233755],
                                   [0.01713642,  0.02505193,  0.04258181],
                                   [0.01720631,  0.03073877,  0.03850075]])
    coords_MNI_2 = head_to_mni(coo_right_amygdala, 'sample', mri_head_t,
                               subjects_dir)
    # less than 1mm error
    assert_allclose(coords_MNI, coords_MNI_2, atol=10.0)
Esempio n. 45
0
def test_head_to_mni():
    """Test conversion of aseg vertices to MNI coordinates."""
    # obtained using freeview
    coords = np.array([[22.52, 11.24, 17.72], [22.52, 5.46, 21.58],
                       [16.10, 5.46, 22.23], [21.24, 8.36, 22.23]])

    xfm = _read_talxfm('sample', subjects_dir)
    coords_MNI = apply_trans(xfm['trans'], coords)

    trans = read_trans(trans_fname)  # head->MRI (surface RAS)
    mri_head_t = invert_transform(trans)  # MRI (surface RAS)->head matrix

    # obtained from sample_audvis-meg-oct-6-mixed-fwd.fif
    coo_right_amygdala = np.array([[0.01745682, 0.02665809, 0.03281873],
                                   [0.01014125, 0.02496262, 0.04233755],
                                   [0.01713642, 0.02505193, 0.04258181],
                                   [0.01720631, 0.03073877, 0.03850075]])
    coords_MNI_2 = head_to_mni(coo_right_amygdala, 'sample', mri_head_t,
                               subjects_dir)
    # less than 1mm error
    assert_allclose(coords_MNI, coords_MNI_2, atol=10.0)
Esempio n. 46
0
def test_get_head_mri_trans_ctf(fname, tmpdir):
    """Test getting a trans object from BIDS data in CTF."""
    import nibabel as nib

    ctf_data_path = op.join(testing.data_path(), 'CTF')
    raw_ctf_fname = op.join(ctf_data_path, fname)
    raw_ctf = _read_raw_ctf(raw_ctf_fname, clean_names=True)
    bids_path = _bids_path.copy().update(root=tmpdir)
    write_raw_bids(raw_ctf, bids_path, overwrite=False)

    # Take a fake trans
    trans = mne.read_trans(raw_fname.replace('_raw.fif', '-trans.fif'))

    # Get the T1 weighted MRI data file ... test write_anat with a nibabel
    # image instead of a file path
    t1w_mgh = op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz')
    t1w_mgh = nib.load(t1w_mgh)

    t1w_bids_path = BIDSPath(subject=subject_id,
                             session=session_id,
                             acquisition=acq,
                             root=tmpdir)
    landmarks = get_anat_landmarks(t1w_mgh,
                                   raw_ctf.info,
                                   trans,
                                   fs_subject='sample',
                                   fs_subjects_dir=op.join(
                                       data_path, 'subjects'))
    write_anat(t1w_mgh, bids_path=t1w_bids_path, landmarks=landmarks)

    # Try to get trans back through fitting points
    estimated_trans = get_head_mri_trans(bids_path=bids_path,
                                         extra_params=dict(clean_names=True),
                                         fs_subject='sample',
                                         fs_subjects_dir=op.join(
                                             data_path, 'subjects'))

    assert_almost_equal(trans['trans'], estimated_trans['trans'])
Esempio n. 47
0
def test_plot_dipole_mri_outlines(surf, coord_frame, ax, title):
    """Test mpl dipole plotting."""
    dipoles = read_dipole(dip_fname)
    trans = read_trans(trans_fname)
    if ax is not None:
        assert isinstance(ax, str) and ax == 'mpl', ax
        _, ax = plt.subplots(3, 1)
        ax = list(ax)
        with pytest.raises(ValueError, match='but the length is 2'):
            dipoles.plot_locations(trans,
                                   'sample',
                                   subjects_dir,
                                   ax=ax[:2],
                                   mode='outlines')
    fig = dipoles.plot_locations(trans=trans,
                                 subject='sample',
                                 subjects_dir=subjects_dir,
                                 mode='outlines',
                                 coord_frame=coord_frame,
                                 surf=surf,
                                 ax=ax,
                                 title=title)
    assert isinstance(fig, Figure)
def test_make_field_map_eeg():
    """Test interpolation of EEG field onto head
    """
    trans = read_trans(trans_fname)
    evoked = read_evoked(evoked_fname, setno='Left Auditory')
    evoked.info['bads'] = ['MEG 2443', 'EEG 053']  # add some bads
    surf = get_head_surf('sample', subjects_dir=subjects_dir)
    # we must have trans if surface is in MRI coords
    assert_raises(ValueError, _make_surface_mapping, evoked.info, surf, 'eeg')

    evoked = pick_types_evoked(evoked, meg=False, eeg=True)
    fmd = make_field_map(evoked, trans_fname=trans_fname,
                         subject='sample', subjects_dir=subjects_dir)

    # trans is necessary for EEG only
    assert_raises(RuntimeError, make_field_map, evoked, trans_fname=None,
                  subject='sample', subjects_dir=subjects_dir)

    fmd = make_field_map(evoked, trans_fname=trans_fname,
                         subject='sample', subjects_dir=subjects_dir)
    assert_true(len(fmd) == 1)
    assert_array_equal(fmd[0]['data'].shape, (2562, 59))  # maps data onto surf
    assert_true(len(fmd[0]['ch_names']), 59)
def test_get_trans():
    """Test converting '-trans.txt' to '-trans.fif'"""
    trans = read_trans(fname)
    trans = invert_transform(trans)  # starts out as head->MRI, so invert
    trans_2 = _get_trans(fname_trans)[0]
    assert trans.__eq__(trans_2, atol=1e-5)
###############################################################################
# Source estimation.
# We compute the noise covariance matrix from the empty room measurement
# and use it for the other runs.
reject = dict(mag=4e-12)
cov = mne.compute_raw_covariance(raw_erm, reject=reject)
cov.plot(raw_erm.info)
del raw_erm

###############################################################################
# The transformation is read from a file. More information about coregistering
# the data, see :ref:`ch_interactive_analysis` or
# :func:`mne.gui.coregistration`.
trans_fname = op.join(data_path, 'MEG', 'bst_auditory',
                      'bst_auditory-trans.fif')
trans = mne.read_trans(trans_fname)

###############################################################################
# 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',
Esempio n. 51
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)
Esempio n. 52
0
def test_coreg_model():
    """Test CoregModel."""
    from mne.gui._coreg_gui import CoregModel
    tempdir = _TempDir()
    trans_dst = op.join(tempdir, 'test-trans.fif')

    model = CoregModel()
    pytest.raises(RuntimeError, model.save_trans, 'blah.fif')

    model.mri.subjects_dir = subjects_dir
    model.mri.subject = 'sample'

    assert not model.mri.fid_ok
    model.mri.lpa = [[-0.06, 0, 0]]
    model.mri.nasion = [[0, 0.05, 0]]
    model.mri.rpa = [[0.08, 0, 0]]
    assert (model.mri.fid_ok)

    model.hsp.file = raw_path
    assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4)
    assert_allclose(model.hsp.rpa, [[+7.527e-2, 0, 5.588e-9]], 1e-4)
    assert_allclose(model.hsp.nasion, [[+3.725e-9, 1.026e-1, 4.191e-9]], 1e-4)
    assert model.has_lpa_data
    assert model.has_nasion_data
    assert model.has_rpa_data
    assert len(model.hsp.eeg_points) > 1

    assert len(model.mri.bem_low_res.surf.rr) == 2562
    assert len(model.mri.bem_high_res.surf.rr) == 267122

    lpa_distance = model.lpa_distance
    nasion_distance = model.nasion_distance
    rpa_distance = model.rpa_distance
    avg_point_distance = np.mean(model.point_distance)

    model.nasion_weight = 1.
    model.fit_fiducials(0)
    old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2
    new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 +
             model.nasion_distance ** 2)
    assert new_x < old_x

    model.fit_icp(0)
    new_dist = np.mean(model.point_distance)
    assert new_dist < avg_point_distance

    model.save_trans(trans_dst)
    trans = mne.read_trans(trans_dst)
    assert_allclose(trans['trans'], model.head_mri_t)

    # test restoring trans
    x, y, z = 100, 200, 50
    rot_x, rot_y, rot_z = np.rad2deg([1.5, 0.1, -1.2])
    model.trans_x = x
    model.trans_y = y
    model.trans_z = z
    model.rot_x = rot_x
    model.rot_y = rot_y
    model.rot_z = rot_z
    trans = model.mri_head_t
    model.reset_traits(["trans_x", "trans_y", "trans_z", "rot_x", "rot_y",
                        "rot_z"])
    assert_equal(model.trans_x, 0)
    model.set_trans(trans)
    assert_array_almost_equal(model.trans_x, x)
    assert_array_almost_equal(model.trans_y, y)
    assert_array_almost_equal(model.trans_z, z)
    assert_array_almost_equal(model.rot_x, rot_x)
    assert_array_almost_equal(model.rot_y, rot_y)
    assert_array_almost_equal(model.rot_z, rot_z)

    # info
    assert (isinstance(model.fid_eval_str, str))
    assert (isinstance(model.points_eval_str, str))

    # scaling job
    assert not model.can_prepare_bem_model
    model.n_scale_params = 1
    assert (model.can_prepare_bem_model)
    model.prepare_bem_model = True
    sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \
        model.get_scaling_job('sample2', False)
    assert_equal(sdir, subjects_dir)
    assert_equal(sfrom, 'sample')
    assert_equal(sto, 'sample2')
    assert_allclose(scale, model.parameters[6:9])
    assert_equal(skip_fiducials, False)
    # find BEM files
    bems = set()
    for fname in os.listdir(op.join(subjects_dir, 'sample', 'bem')):
        match = re.match(r'sample-(.+-bem)\.fif', fname)
        if match:
            bems.add(match.group(1))
    assert_equal(set(bemsol), bems)
    model.prepare_bem_model = False
    sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \
        model.get_scaling_job('sample2', True)
    assert_equal(bemsol, [])
    assert (skip_fiducials)

    model.load_trans(fname_trans)
    model.save_trans(trans_dst)
    trans = mne.read_trans(trans_dst)
    assert_allclose(trans['trans'], model.head_mri_t)
    assert_allclose(invert_transform(trans)['trans'][:3, 3] * 1000.,
                    [model.trans_x, model.trans_y, model.trans_z])
Esempio n. 53
0
Plotting EEG sensors on the scalp
=================================

In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <*****@*****.**>
#
# License: BSD (3-clause)

import mne
from mne.viz import plot_trans
from mayavi import mlab

print(__doc__)

data_path = mne.datasets.sample.data_path()
subjects_dir = data_path + "/subjects"
trans = mne.read_trans(data_path + "/MEG/sample/sample_audvis_raw-trans.fif")
raw = mne.io.read_raw_fif(data_path + "/MEG/sample/sample_audvis_raw.fif")
fig = plot_trans(
    raw.info,
    trans,
    subject="sample",
    dig=False,
    eeg_sensors=["original", "projected"],
    meg_sensors=[],
    coord_frame="head",
    subjects_dir=subjects_dir,
)
mlab.view(135, 80)
Esempio n. 54
0
def test_do_forward_solution():
    """Test wrapping forward solution from python
    """
    raw = Raw(fname_raw)
    mri = read_trans(fname_mri)
    fname_fake = op.join(temp_dir, 'no_have.fif')

    # ## Error checks
    # bad subject
    assert_raises(ValueError, do_forward_solution, 1, fname_raw,
                  subjects_dir=subjects_dir)
    # bad meas
    assert_raises(ValueError, do_forward_solution, 'sample', 1,
                  subjects_dir=subjects_dir)
    # meas doesn't exist
    assert_raises(IOError, do_forward_solution, 'sample', fname_fake,
                  subjects_dir=subjects_dir)
    # don't specify trans and meas
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  subjects_dir=subjects_dir)
    # specify both trans and meas
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  trans='me', mri='you', subjects_dir=subjects_dir)
    # specify non-existent trans
    assert_raises(IOError, do_forward_solution, 'sample', fname_raw,
                  trans=fname_fake, subjects_dir=subjects_dir)
    # specify non-existent mri
    assert_raises(IOError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_fake, subjects_dir=subjects_dir)
    # specify non-string mri
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=1, subjects_dir=subjects_dir)
    # specify non-string trans
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  trans=1, subjects_dir=subjects_dir)
    # test specifying an actual trans in python space -- this should work but
    # the transform I/O reduces our accuracy -- so we'll just hack a test here
    # by making it bomb with eeg=False and meg=False
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=mri, eeg=False, meg=False, subjects_dir=subjects_dir)
    # mindist as non-integer
    assert_raises(TypeError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, mindist=dict(), subjects_dir=subjects_dir)
    # mindist as string but not 'all'
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, eeg=False, mindist='yall',
                  subjects_dir=subjects_dir)
    # src, spacing, and bem as non-str
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, src=1, subjects_dir=subjects_dir)
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, spacing=1, subjects_dir=subjects_dir)
    assert_raises(ValueError, do_forward_solution, 'sample', fname_raw,
                  mri=fname_mri, bem=1, subjects_dir=subjects_dir)
    # no overwrite flag
    assert_raises(IOError, do_forward_solution, 'sample', fname_raw,
                  existing_file, mri=fname_mri, subjects_dir=subjects_dir)
    # let's catch an MNE error, this time about trans being wrong
    assert_raises(CalledProcessError, do_forward_solution, 'sample',
                  fname_raw, existing_file, trans=fname_mri, overwrite=True,
                  spacing='oct-6', subjects_dir=subjects_dir)

    # ## Actually calculate one and check
    # make a meas from raw (tests all steps in creating evoked),
    # don't do EEG or 5120-5120-5120 BEM because they're ~3x slower
    fwd_py = do_forward_solution('sample', raw, mindist=5, spacing='oct-6',
                                 bem='sample-5120', mri=fname_mri, eeg=False,
                                 subjects_dir=subjects_dir)
    fwd = read_forward_solution(fname)
    assert_allclose(fwd['sol']['data'], fwd_py['sol']['data'],
                    rtol=1e-5, atol=1e-8)
    assert_equal(fwd_py['sol']['data'].shape, (306, 22494))
    assert_equal(len(fwd['sol']['row_names']), 306)
Esempio n. 55
0
def test_coreg_model():
    """Test CoregModel"""
    from mne.gui._coreg_gui import CoregModel
    tempdir = _TempDir()
    trans_dst = os.path.join(tempdir, 'test-trans.fif')

    model = CoregModel()
    assert_raises(RuntimeError, model.save_trans, 'blah.fif')

    model.mri.use_high_res_head = False

    model.mri.subjects_dir = subjects_dir
    model.mri.subject = 'sample'

    assert_false(model.mri.fid_ok)
    model.mri.lpa = [[-0.06, 0, 0]]
    model.mri.nasion = [[0, 0.05, 0]]
    model.mri.rpa = [[0.08, 0, 0]]
    assert_true(model.mri.fid_ok)

    model.hsp.file = raw_path
    assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4)
    assert_allclose(model.hsp.rpa, [[+7.527e-2, 0, 5.588e-9]], 1e-4)
    assert_allclose(model.hsp.nasion, [[+3.725e-9, 1.026e-1, 4.191e-9]], 1e-4)
    assert_true(model.has_fid_data)

    lpa_distance = model.lpa_distance
    nasion_distance = model.nasion_distance
    rpa_distance = model.rpa_distance
    avg_point_distance = np.mean(model.point_distance)

    model.fit_auricular_points()
    old_x = lpa_distance ** 2 + rpa_distance ** 2
    new_x = model.lpa_distance ** 2 + model.rpa_distance ** 2
    assert_true(new_x < old_x)

    model.fit_fiducials()
    old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2
    new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 +
             model.nasion_distance ** 2)
    assert_true(new_x < old_x)

    model.fit_hsp_points()
    assert_true(np.mean(model.point_distance) < avg_point_distance)

    model.save_trans(trans_dst)
    trans = mne.read_trans(trans_dst)
    assert_allclose(trans['trans'], model.head_mri_trans)

    # test restoring trans
    x, y, z, rot_x, rot_y, rot_z = .1, .2, .05, 1.5, 0.1, -1.2
    model.trans_x = x
    model.trans_y = y
    model.trans_z = z
    model.rot_x = rot_x
    model.rot_y = rot_y
    model.rot_z = rot_z
    trans = model.head_mri_trans
    model.reset_traits(["trans_x", "trans_y", "trans_z", "rot_x", "rot_y",
                        "rot_z"])
    assert_equal(model.trans_x, 0)
    model.set_trans(trans)
    assert_almost_equal(model.trans_x, x)
    assert_almost_equal(model.trans_y, y)
    assert_almost_equal(model.trans_z, z)
    assert_almost_equal(model.rot_x, rot_x)
    assert_almost_equal(model.rot_y, rot_y)
    assert_almost_equal(model.rot_z, rot_z)

    # info
    assert_true(isinstance(model.fid_eval_str, string_types))
    assert_true(isinstance(model.points_eval_str, string_types))

    # scaling job
    sdir, sfrom, sto, scale, skip_fiducials, bemsol = \
        model.get_scaling_job('sample2', False, True)
    assert_equal(sdir, subjects_dir)
    assert_equal(sfrom, 'sample')
    assert_equal(sto, 'sample2')
    assert_equal(scale, model.scale)
    assert_equal(skip_fiducials, False)
    # find BEM files
    bems = set()
    for fname in os.listdir(os.path.join(subjects_dir, 'sample', 'bem')):
        match = re.match('sample-(.+-bem)\.fif', fname)
        if match:
            bems.add(match.group(1))
    assert_equal(set(bemsol), bems)
    sdir, sfrom, sto, scale, skip_fiducials, bemsol = \
        model.get_scaling_job('sample2', True, False)
    assert_equal(bemsol, [])
    assert_true(skip_fiducials)

    model.load_trans(fname_trans)

    from mne.gui._coreg_gui import CoregFrame
    x = CoregFrame(raw_path, 'sample', subjects_dir)
    os.environ['_MNE_GUI_TESTING_MODE'] = 'true'
    try:
        with warnings.catch_warnings(record=True):  # traits spews warnings
            warnings.simplefilter('always')
            x._init_plot()
    finally:
        del os.environ['_MNE_GUI_TESTING_MODE']
Esempio n. 56
0
    def __init__(self, raw, mrk, bem='head', trans=None, subject=None,
                 subjects_dir=None):
        """
        Parameters
        ----------

        raw : mne.fiff.Raw | str(path)
            MNE Raw object, or path to a raw file.
        mrk : load.kit.MarkerFile | str(path) | array, shape = (5, 3)
            MarkerFile object, or path to a marker file, or marker points.
        bem : None | str(path)
            Name of the bem model to load (optional, only for visualization
            purposes).
        trans : None | dict | str(path)
            MRI-Head transform (optional).
            Can be None if the file is located in the raw directory and named
            "{subject}-trans.fif"
        subject : None | str
            Name of the mri subject.
            Can be None if the raw file-name starts with "{subject}_".

        """
        subjects_dir = get_subjects_dir(subjects_dir)

        # interpret mrk
        if isinstance(mrk, basestring):
            mrk = load.kit.MarkerFile(mrk)
        if isinstance(mrk, load.kit.MarkerFile):
            mrk = mrk.points

        # interpret raw
        if isinstance(raw, basestring):
            raw_fname = raw
            raw = load.fiff.Raw(raw)
        else:
            raw_fname = raw.info['filename']
        self._raw_fname = raw_fname
        self.raw = raw

        # subject
        if subject is None:
            _, tail = os.path.split(raw_fname)
            subject = tail.split('_')[0]
        self.subject = subject

        # bem (mri-head-trans)
        if bem is None:
            self.MRI = None
        else:
            # trans
            if trans is None:
                head, _ = os.path.split(raw_fname)
                trans = os.path.join(head, subject + '-trans.fif')
            if isinstance(trans, basestring):
                head_mri_t = mne.read_trans(trans)

            # mri_dev_t
            self.mri_head_t = np.matrix(head_mri_t['trans']).I

            fname = os.path.join(subjects_dir, subject, 'bem',
                                 '%s-%s.fif' % (subject, bem))
            self.MRI = geom_bem(fname, unit='m')
            self.MRI.set_T(self.mri_head_t)

        # sensors
        pts = filter(lambda d: d['kind'] == FIFF.FIFFV_MEG_CH, raw.info['chs'])
        pts = np.array([d['loc'][:3] for d in pts])
        self.sensors = geom(pts)

        # marker points
        pts = mrk / 1000
        pts = pts[:, [1, 0, 2]]
        pts[:, 0] *= -1
        self.mrk = geom(pts)

        # head shape
        pts = filter(lambda d: d['kind'] == FIFF.FIFFV_POINT_EXTRA, raw.info['dig'])
        pts = np.array([d['r'] for d in pts])
        self.headshape = geom(pts)

        # HPI points
        pts = filter(lambda d: d['kind'] == FIFF.FIFFV_POINT_HPI, raw.info['dig'])
        assert [d['ident'] for d in pts] == range(1, 6)
        pts = np.array([d['r'] for d in pts])
        self.HPI = geom(pts)

        # T head-to-device
        trans = raw.info['dev_head_t']['trans']
        self.T_head2dev = np.matrix(trans).I
        self.reset()
        self._HPI_flipped = False
Esempio n. 57
0
    def __init__(self, raw, subject=None, head_mri_t=None, mri='head',
                 hs='wireframe', subjects_dir=None, fig=None):
        """
        Parameters
        ----------

        raw : str(path) | Raw
            Path to raw fiff file, or the mne.fiff.Raw instance.
        subject : None | str
            Name of the mri subject. Can be None if the raw file-name starts
            with "{subject}_".
        head_mri_t : None | str(path)
            Path to the trans file for head-mri coregistration. Can be None if
            the file is located in the raw directory and named
            "{subject}-trans.fif"
        mri : str
            Name of the mri model to load (default is 'head')
        hs : None | 'wireframe' | 'surface' | 'points' | 'balls'
            How to display the digitizer head-shape stored in the raw file.

        """
        subjects_dir = get_subjects_dir(subjects_dir)

        if fig is None:
            fig = mlab.figure()
        self.fig = fig

        # raw
        if isinstance(raw, basestring):
            raw_fname = raw
            raw = load.fiff.Raw(raw_fname)
        else:
            raw_fname = raw.info['filename']

        # subject
        if subject is None:
            _, tail = os.path.split(raw_fname)
            subject = tail.split('_')[0]

        # mri_head_t
        if head_mri_t is None:
            head, _ = os.path.split(raw_fname)
            head_mri_t = os.path.join(head, subject + '-trans.fif')
        if isinstance(head_mri_t, basestring):
            head_mri_t = mne.read_trans(head_mri_t)

        # mri_dev_t
        mri_head_t = np.matrix(head_mri_t['trans']).I
        head_dev_t = np.matrix(raw.info['dev_head_t']['trans']).I
        mri_dev_t = head_dev_t * mri_head_t

        # sensors
        pts = filter(lambda d: d['kind'] == FIFF.FIFFV_MEG_CH, raw.info['chs'])
        pts = np.array([d['loc'][:3] for d in pts])
        self.sensors = geom(pts)
        self.sensors.plot_points(fig, scale=0.005, color=(0, 0, 1))

        # mri
        bemdir = os.path.join(subjects_dir, subject, 'bem')
        bem = os.path.join(bemdir, '%s-%s.fif' % (subject, mri))
        self.mri = geom_bem(bem, unit='m')
        self.mri.set_T(mri_dev_t)
        self.mri.plot_solid(fig, color=(.8, .6, .5))

        # head-shape
        if hs:
            self.hs = geom_dig_hs(raw.info['dig'], unit='m')
            self.hs.set_T(head_dev_t)
            if hs in ['surface', 'wireframe', 'points']:
                self.hs.plot_solid(fig, opacity=1, rep=hs, color=(1, .5, 0))
            elif hs == 'balls':
                self.hs.plot_points(fig, 0.01, opacity=0.5, color=(1, .5, 0))
            else:
                raise ValueError('hs kwarg can not be %r' % hs)

            self.hs.plot_solid(fig, opacity=1, rep='points', color=(1, .5, 0))

            # Fiducials
            fname = os.path.join(bemdir, subject + '-fiducials.fif')
            if os.path.exists(fname):
                dig, _ = read_fiducials(fname)
                self.mri_fid = geom_fid(dig, unit='m')
                self.mri_fid.set_T(mri_dev_t)
                self.mri_fid.plot_points(fig, scale=0.005)

            self.dig_fid = geom_fid(raw.info['dig'], unit='m')
            self.dig_fid.set_T(head_dev_t)
            self.dig_fid.plot_points(fig, scale=0.04, opacity=.25,
                                     color=(.5, .5, 1))

        self.view()
Esempio n. 58
0
def test_coreg_model():
    """Test CoregModel"""
    from mne.gui._coreg_gui import CoregModel
    tempdir = _TempDir()
    trans_dst = os.path.join(tempdir, 'test-trans.fif')

    model = CoregModel()
    assert_raises(RuntimeError, model.save_trans, 'blah.fif')

    model.mri.subjects_dir = subjects_dir
    model.mri.subject = 'sample'

    assert_false(model.mri.fid_ok)
    model.mri.lpa = [[-0.06, 0, 0]]
    model.mri.nasion = [[0, 0.05, 0]]
    model.mri.rpa = [[0.08, 0, 0]]
    assert_true(model.mri.fid_ok)

    model.hsp.file = raw_path
    assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4)
    assert_allclose(model.hsp.rpa, [[+7.527e-2, 0, 5.588e-9]], 1e-4)
    assert_allclose(model.hsp.nasion, [[+3.725e-9, 1.026e-1, 4.191e-9]], 1e-4)
    assert_true(model.has_fid_data)

    lpa_distance = model.lpa_distance
    nasion_distance = model.nasion_distance
    rpa_distance = model.rpa_distance
    avg_point_distance = np.mean(model.point_distance)

    model.fit_auricular_points()
    old_x = lpa_distance ** 2 + rpa_distance ** 2
    new_x = model.lpa_distance ** 2 + model.rpa_distance ** 2
    assert_true(new_x < old_x)

    model.fit_fiducials()
    old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2
    new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2
             + model.nasion_distance ** 2)
    assert_true(new_x < old_x)

    model.fit_hsp_points()
    assert_true(np.mean(model.point_distance) < avg_point_distance)

    model.save_trans(trans_dst)
    trans = mne.read_trans(trans_dst)
    assert_allclose(trans['trans'], model.head_mri_trans)

    # test restoring trans
    x, y, z, rot_x, rot_y, rot_z = .1, .2, .05, 1.5, 0.1, -1.2
    model.trans_x = x
    model.trans_y = y
    model.trans_z = z
    model.rot_x = rot_x
    model.rot_y = rot_y
    model.rot_z = rot_z
    trans = model.head_mri_trans
    model.reset_traits(["trans_x", "trans_y", "trans_z", "rot_x", "rot_y",
                        "rot_z"])
    assert_equal(model.trans_x, 0)
    model.set_trans(trans)
    assert_almost_equal(model.trans_x, x)
    assert_almost_equal(model.trans_y, y)
    assert_almost_equal(model.trans_z, z)
    assert_almost_equal(model.rot_x, rot_x)
    assert_almost_equal(model.rot_y, rot_y)
    assert_almost_equal(model.rot_z, rot_z)

    # info
    assert_true(isinstance(model.fid_eval_str, string_types))
    assert_true(isinstance(model.points_eval_str, string_types))

    model.get_prepare_bem_model_job('sample')
    model.load_trans(fname_trans)

    from mne.gui._coreg_gui import CoregFrame
    x = CoregFrame(raw_path, 'sample', subjects_dir)
    os.environ['_MNE_GUI_TESTING_MODE'] = 'true'
    try:
        with warnings.catch_warnings(record=True):  # traits spews warnings
            warnings.simplefilter('always')
            x._init_plot()
    finally:
        del os.environ['_MNE_GUI_TESTING_MODE']
Esempio n. 59
0
hcp_path = op.join(storage_dir, 'HCP')
recordings_path = op.join(storage_dir, 'hcp-meg')
subjects_dir = op.join(storage_dir, 'hcp-subjects')
subject = '105923'  # our test subject

##############################################################################
# and we assume to have the downloaded data, the MNE/freesurfer style
# anatomy directory, and the MNE style MEG directory.
# these can be obtained from :func:`make_mne_anatomy`.
# See also :ref:`tut_make_anatomy`.

##############################################################################
# first we read the coregistration.

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

##############################################################################
# Now we can setup our source model.
# Note that spacing has to be set to 'all' since no common MNE resampling
# scheme has been employed in the HCP pipelines.
# Since this will take very long time to compute and at this point no other
# decimation scheme is available inside MNE, we will compute the source
# space on fsaverage, the freesurfer average brain, and morph it onto
# the subject's native space. With `oct6` we have ~8000 dipole locations.

src_fsaverage = mne.setup_source_space(
    subject='fsaverage', subjects_dir=subjects_dir, add_dist=False,
    spacing='oct6', overwrite=True)