예제 #1
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts
    """
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=read_evokeds(evoked_fname)[0].info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
    # KIT ref sensor coil def not defined
    assert_raises(RuntimeError, plot_trans, infos['KIT'], None,
                  meg_sensors=True, ref_meg=True)
    info = infos['Neuromag']
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
예제 #2
0
def test_plot_trans():
    """Test plotting of -trans.fif files
    """
    evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    plot_trans(evoked.info, trans_fname, subject='sample',
               subjects_dir=subjects_dir)
    assert_raises(ValueError, plot_trans, evoked.info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
예제 #3
0
def test_plot_trans():
    """Test plotting of -trans.fif files
    """
    evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    plot_trans(evoked.info, trans_fname=trans_fname, subject='sample',
               subjects_dir=subjects_dir)
    assert_raises(ValueError, plot_trans, evoked.info, trans_fname=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
예제 #4
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts
    """
    evoked = read_evokeds(evoked_fname)[0]
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    info = infos['Neuromag']
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    # EEG only with strange options
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked.copy().pick_types(meg=False, eeg=True).info,
                   trans=trans_fname, meg_sensors=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
예제 #5
0
파일: test_viz.py 프로젝트: rgoj/mne-python
def test_plot_trans():
    """Test plotting of -trans.fif files
    """
    trans_fname = op.join(data_dir, "MEG", "sample", "sample_audvis_raw-trans.fif")
    evoked = read_evokeds(evoked_fname, condition="Left Auditory", baseline=(-0.2, 0.0))
    plot_trans(evoked.info, trans_fname=trans_fname, subject="sample", subjects_dir=subjects_dir)
    assert_raises(
        ValueError,
        plot_trans,
        evoked.info,
        trans_fname=trans_fname,
        subject="sample",
        subjects_dir=subjects_dir,
        ch_type="bad-chtype",
    )
예제 #6
0
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    tempdir = _TempDir()
    import matplotlib.pyplot as plt
    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions=['evoked response'], scale=1.2,
                               image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')
    assert_raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=0, image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=1e-10, image_format='svg')
    # need to recreate because calls above change size
    fig = plt.plot([1, 2], [1, 2])[0].figure

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info, trans_fname, subject='sample',
                     subjects_dir=subjects_dir)

    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions='random image', scale=1.2)
예제 #7
0
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    tempdir = _TempDir()
    import matplotlib.pyplot as plt
    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions=['evoked response'], scale=1.2,
                               image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')
    assert_raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=0, image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=1e-10, image_format='svg')
    # need to recreate because calls above change size
    fig = plt.plot([1, 2], [1, 2])[0].figure

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info, trans_fname, subject='sample',
                     subjects_dir=subjects_dir)

    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions='random image', scale=1.2)
예제 #8
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    from mayavi import mlab
    evoked = read_evokeds(evoked_fname)[0]
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info, meg_sensors=True, dig=True, coord_frame=coord_frame,
                   trans=trans_fname, subject='sample',
                   subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked_eeg_ecog.info, subject='sample', trans=trans_fname,
                   source='outer_skin', meg_sensors=True, skull=True,
                   eeg_sensors=['original', 'projected'], ecog_sensors=True,
                   brain='white', head=True, subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
예제 #9
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    from mayavi import mlab
    evoked = read_evokeds(evoked_fname)[0]
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info, meg_sensors=True, dig=True, coord_frame=coord_frame,
                   trans=trans_fname, subject='sample',
                   subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked.copy().pick_types(meg=False, eeg=True).info,
                   subject='sample', trans=trans_fname, meg_sensors=True,
                   eeg_sensors=['original', 'projected'],
                   subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
예제 #10
0
def test_plot_trans():
    """Test plotting of -trans.fif files
    """
    trans_fname = op.join(data_dir, 'MEG', 'sample',
                          'sample_audvis_raw-trans.fif')
    evoked = io.read_evokeds(evoked_fname,
                             condition='Left Auditory',
                             baseline=(-0.2, 0.0))
    plot_trans(evoked.info,
               trans_fname=trans_fname,
               subject='sample',
               subjects_dir=subjects_dir)
    assert_raises(ValueError,
                  plot_trans,
                  evoked.info,
                  trans_fname=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
예제 #11
0
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    tempdir = _TempDir()
    import matplotlib.pyplot as plt
    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(
        figs=fig,  # test non-list input
        captions=['evoked response'],
        scale=1.2,
        image_format='svg')
    assert_raises(ValueError,
                  report.add_figs_to_section,
                  figs=[fig, fig],
                  captions='H')

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError,
                  report.add_images_to_section,
                  fnames=[img_fname, img_fname],
                  captions='H')

    # Check deprecation of add_section
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.add_section(figs=fig, captions=['evoked response'])
        assert_true(w[0].category == DeprecationWarning)

    evoked = read_evokeds(evoked_fname,
                          condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info,
                     trans_fname=trans_fname,
                     subject='sample',
                     subjects_dir=subjects_dir)

    report.add_figs_to_section(
        figs=fig,  # test non-list input
        captions='random image',
        scale=1.2)
예제 #12
0
def test_snapshot_brain_montage():
    info = read_info(evoked_fname)
    fig = plot_trans(info, trans=None, subject='sample',
                     subjects_dir=subjects_dir)

    xyz = np.vstack([ich['loc'][:3] for ich in info['chs']])
    ch_names = [ich['ch_name'] for ich in info['chs']]
    xyz_dict = dict(zip(ch_names, xyz))
    xyz_dict[info['chs'][0]['ch_name']] = [1, 2]  # Set one ch to only 2 vals

    # Make sure wrong types are checked
    assert_raises(ValueError, snapshot_brain_montage, fig, xyz)

    # All chs must have 3 position values
    assert_raises(ValueError, snapshot_brain_montage, fig, xyz_dict)

    # Make sure we raise error if the figure has no scene
    assert_raises(TypeError, snapshot_brain_montage, fig, info)
예제 #13
0
def check_bem(sbj_id, sbj_dir, raw_info, trans_fname, report):
    import os.path as op
    import mne
    from mne.viz import plot_bem, plot_trans
    
    from mayavi import mlab
    import numpy as np
    
    ### plot bem surfs to MRI in the 3 different views
    fig1 = plot_bem(subject=sbj_id, subjects_dir=sbj_dir, orientation='axial', show=False)
    fig2 = plot_bem(subject=sbj_id, subjects_dir=sbj_dir, orientation='sagittal', show=False)
    fig3 = plot_bem(subject=sbj_id, subjects_dir=sbj_dir, orientation='coronal', show=False)
    report.add_figs_to_section([fig1, fig2, fig3], captions=['axial view', 'sagittal view', 'coronal view'], section='BEM surfaces')
    
    ### plot bem surf and source space
    bem_fname = op.join(sbj_dir, sbj_id + '/bem/%s-5120-bem-sol.fif' % sbj_id)
    surf = mne.read_bem_surfaces(bem_fname, patch_stats=True)
    print 'Number of surfaces : %d' % len(surf)
    brain_col = (0.95, 0.83, 0.83)
    cortex_col = (0.91, 0.89, 0.67)
    points = surf[0]['rr']
    faces = surf[0]['tris']
    fig4 = mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))
    mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=brain_col, opacity=0.3)
    
    src_fname = op.join(sbj_dir, sbj_id + '/bem/%s-ico-5-src.fif' % sbj_id)
    src = mne.read_source_spaces(src_fname)
    lh_points = src[0]['rr']
    lh_faces = src[0]['tris']
    rh_points = src[1]['rr']
    rh_faces = src[1]['tris']
    mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2], lh_faces, color=cortex_col, opacity=0.8)
    mlab.triangular_mesh(rh_points[:, 0], rh_points[:, 1], rh_points[:, 2], rh_faces, color=cortex_col, opacity=0.8)
    picks = mne.pick_types(raw_info, meg=True, ref_meg=False, eeg=False, stim=False, eog=False, exclude='bads')

    ### plot sensors    
    sens_loc = [ raw_info['chs'][picks[i]]['loc'][:3] for i in range(len(picks)) ]
    sens_loc = np.array(sens_loc)
    mlab.points3d(sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2], color=(1, 1, 1), opacity=1, scale_factor=0.005)
    
    report.add_figs_to_section(fig4, captions=['source space'], section='BEM cortex sensors')
    fig5 = plot_trans(raw_info, trans_fname, subject=sbj_id, subjects_dir=sbj_dir)
    report.add_figs_to_section(fig5, captions=['MEG <-> MRI coregistration quality'], section='MEG <-> MRI')
예제 #14
0
def test_snapshot_brain_montage():
    """Test snapshot brain montage."""
    info = read_info(evoked_fname)
    fig = plot_trans(info, trans=None, subject='sample',
                     subjects_dir=subjects_dir)

    xyz = np.vstack([ich['loc'][:3] for ich in info['chs']])
    ch_names = [ich['ch_name'] for ich in info['chs']]
    xyz_dict = dict(zip(ch_names, xyz))
    xyz_dict[info['chs'][0]['ch_name']] = [1, 2]  # Set one ch to only 2 vals

    # Make sure wrong types are checked
    assert_raises(ValueError, snapshot_brain_montage, fig, xyz)

    # All chs must have 3 position values
    assert_raises(ValueError, snapshot_brain_montage, fig, xyz_dict)

    # Make sure we raise error if the figure has no scene
    assert_raises(TypeError, snapshot_brain_montage, fig, info)
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    from PIL import Image

    tempdir = _TempDir()
    import matplotlib.pyplot as plt

    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(
        figs=fig, captions=["evoked response"], scale=1.2, image_format="svg"  # test non-list input
    )
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig], captions="H")
    assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=["foo"], scale=0, image_format="svg")
    assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=["foo"], scale=1e-10, image_format="svg")
    # need to recreate because calls above change size
    fig = plt.plot([1, 2], [1, 2])[0].figure

    # Check add_images_to_section with png and then gif
    img_fname = op.join(tempdir, "testimage.png")
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname], captions=["evoked response"])

    im = Image.open(img_fname)
    op.join(tempdir, "testimage.gif")
    im.save(img_fname)  # matplotlib does not support gif
    report.add_images_to_section(fnames=[img_fname], captions=["evoked response"])

    assert_raises(ValueError, report.add_images_to_section, fnames=[img_fname, img_fname], captions="H")

    assert_raises(ValueError, report.add_images_to_section, fnames=["foobar.xxx"], captions="H")

    evoked = read_evokeds(evoked_fname, condition="Left Auditory", baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info, trans_fname, subject="sample", subjects_dir=subjects_dir)

    report.add_figs_to_section(figs=fig, captions="random image", scale=1.2)  # test non-list input
예제 #16
0
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    tempdir = _TempDir()
    import matplotlib.pyplot as plt
    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions=['evoked response'], scale=1.2,
                               image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    # Check deprecation of add_section
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.add_section(figs=fig,
                           captions=['evoked response'])
        assert_true(w[0].category == DeprecationWarning)

    evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info, trans_fname, subject='sample',
                     subjects_dir=subjects_dir)

    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions='random image', scale=1.2)
"""
=================================
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)
예제 #18
0
print("Created %s channel positions" % len(ch_names))

###############################################################################
# Now that we have our electrode positions in MRI coordinates, we can create
# our measurement info structure.

info = mne.create_info(ch_names, 1000.0, "ecog", montage=mon)

###############################################################################
# We can then plot the locations of our electrodes on our subject's brain.
#
# .. note:: These are not real electrodes for this subject, so they
#           do not align to the cortical surface perfectly.

subjects_dir = mne.datasets.sample.data_path() + "/subjects"
fig = plot_trans(info, trans=None, subject="sample", subjects_dir=subjects_dir)
mlab.view(200, 70)

###############################################################################
# Sometimes it is useful to make a scatterplot for the current figure view.
# This is best accomplished with matplotlib. We can capture an image of the
# current mayavi view, along with the xy position of each electrode, with the
# `snapshot_brain_montage` function.

# We'll once again plot the surface, then take a snapshot.
fig = plot_trans(info, trans=None, subject="sample", subjects_dir=subjects_dir)
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

# Convert from a dictionary to array to plot
xy_pts = np.vstack(xy[ch] for ch in info["ch_names"])
        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',
                        '%s-5120-bem.fif' % subject)
    if overwrite or not os.path.exists(f_to):
=========================================
Plotting head in helmet from a trans file
=========================================

In this example, the head is shown in the
MEG helmet along with the EEG electrodes in MRI
coordinate system. This allows assessing the
MEG <-> MRI coregistration quality.

"""
# Author: Mainak Jas <*****@*****.**>
#
# License: BSD (3-clause)

from mne import read_evokeds
from mne.datasets import sample
from mne.viz import plot_trans

print(__doc__)


data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

condition = 'Left Auditory'
evoked = read_evokeds(evoked_fname, condition=condition, baseline=(-0.2, 0.0))
plot_trans(evoked.info, trans_fname, subject='sample', dig=True,
           meg_sensors=True, subjects_dir=subjects_dir)
    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',
                        '%s-5120-bem.fif' % subject)
    if overwrite or not os.path.exists(f_to):
        copyfile(f_from, f_to)
    surf_files = [
예제 #22
0
elec = mat['elec']
dig_ch_pos = dict(zip(ch_names, elec))
mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
info = mne.create_info(ch_names, 1000., 'ecog', montage=mon)
print('Created %s channel positions' % len(ch_names))

###############################################################################
# Project 3D electrodes to a 2D snapshot
# --------------------------------------
#
# Because we have the 3D location of each electrode, we can use the
# :func:`mne.viz.snapshot_brain_montage` function to return a 2D image along
# with the electrode positions on that image. We use this in conjunction with
# :func:`mne.viz.plot_trans`, which visualizes electrode positions.

fig = plot_trans(info, trans=None, subject='sample', subjects_dir=subjects_dir)
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

# Convert from a dictionary to array to plot
xy_pts = np.vstack(xy[ch] for ch in info['ch_names'])

# Define an arbitrary "activity" pattern for viz
activity = np.linspace(100, 200, xy_pts.shape[0])

# This allows us to use matplotlib to create arbitrary 2d scatterplots
fig2, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
# fig2.savefig('./brain.png', bbox_inches='tight')  # For ClickableImage
Plotting head in helmet from a trans file
=========================================

In this example, the head is shown in the
MEG helmet along with the EEG electrodes in MRI
coordinate system. This allows assessing the
MEG <-> MRI coregistration quality.

"""
# Author: Mainak Jas <*****@*****.**>
#
# License: BSD (3-clause)

from mne import read_evokeds
from mne.datasets import sample
from mne.viz import plot_trans

data_path = sample.data_path()

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

condition = 'Left Auditory'
evoked = read_evokeds(evoked_fname, condition=condition, baseline=(-0.2, 0.0))
plot_trans(evoked.info,
           trans_fname=trans_fname,
           subject='sample',
           subjects_dir=subjects_dir)
예제 #24
0
print('Created %s channel positions' % len(ch_names))

###############################################################################
# Now that we have our electrode positions in MRI coordinates, we can create
# our measurement info structure.

info = mne.create_info(ch_names, 1000., 'ecog', montage=mon)

###############################################################################
# We can then plot the locations of our electrodes on our subject's brain.
#
# .. note:: These are not real electrodes for this subject, so they
#           do not align to the cortical surface perfectly.

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
fig = plot_trans(info, trans=None, subject='sample', subjects_dir=subjects_dir)
mlab.view(200, 70)

###############################################################################
# Sometimes it is useful to make a scatterplot for the current figure view.
# This is best accomplished with matplotlib. We can capture an image of the
# current mayavi view, along with the xy position of each electrode, with the
# `snapshot_brain_montage` function.

# We'll once again plot the surface, then take a snapshot.
fig = plot_trans(info, trans=None, subject='sample', subjects_dir=subjects_dir)
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

# Convert from a dictionary to array to plot
xy_pts = np.vstack(xy[ch] for ch in info['ch_names'])
예제 #25
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname,
                           config_fname,
                           hs_fname,
                           convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info,
                   trans_fname,
                   subject='sample',
                   meg_sensors=True,
                   subjects_dir=subjects_dir,
                   ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(ValueError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError,
                  plot_trans,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    assert_raises(TypeError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    assert_raises(ValueError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='fsaverage',
                  subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir)
    mlab.close(all=True)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info,
                   meg_sensors=True,
                   dig=True,
                   coord_frame=coord_frame,
                   trans=trans_fname,
                   subject='sample',
                   subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked_eeg_ecog.info,
                   subject='sample',
                   trans=trans_fname,
                   source='outer_skin',
                   meg_sensors=True,
                   skull=True,
                   eeg_sensors=['original', 'projected'],
                   ecog_sensors=True,
                   brain='white',
                   head=True,
                   subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
예제 #26
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import Raw, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.datasets import sample, spm_face
from mne.viz import plot_trans

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = dict(
    Neuromag=Raw(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif'),
    CTF_275=read_raw_ctf(spm_face.data_path() +
                         '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    Magnes_3600wh=read_raw_bti(bti_path + 'test_pdf_linux',
                               bti_path + 'test_config_linux',
                               bti_path + 'test_hs_linux'),
    KIT=read_raw_kit(kit_path + 'test.sqd'),
)

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == 'KIT' else True
    fig = plot_trans(raw.info, trans=None, dig=False, eeg_sensors=False,
                     meg_sensors=True, coord_frame='meg', ref_meg=ref_meg)
    mlab.title(system)
예제 #27
0
import mne
import os


# SETUP PATHS AND PREPARE RAW DATA
hostname = socket.gethostname()

if hostname == "wintermute":
    data_path = "/home/mje/mnt/caa/scratch/"
else:
    data_path = "/projects/MINDLAB2015_MEG-CorticalAlphaAttention/scratch/"

# CHANGE DIR TO SAVE FILES THE RIGTH PLACE
os.chdir(data_path)

subjects_dir = data_path + "fs_subjects_dir/"
save_folder = data_path + "filter_ica_data/"
maxfiltered_folder = data_path + "maxfiltered_data/"
epochs_folder = data_path + "epoched_data/"
tf_folder = data_path + "tf_data/"
mne_folder = data_path + "minimum_norm/"


subject = "0025"
trans_fname = mne_folder + "%s-trans.fif" % subject
epochs = mne.read_epochs(epochs_folder +
                         "%s_filtered_ica_mc_tsss-epo.fif" % subject, 
                         preload=False)
plot_trans(epochs.info, trans_fname, subject=subject, dig=True,
           subjects_dir=subjects_dir)
예제 #28
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = _TempDir()
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{'coord_frame': 5, 'ident': 1, 'kind': 1,
            'r': [-0.08061612, -0.02908875, -0.04131077]},
           {'coord_frame': 5, 'ident': 2, 'kind': 1,
            'r': [0.00146763, 0.08506715, -0.03483611]},
           {'coord_frame': 5, 'ident': 3, 'kind': 1,
            'r': [0.08436285, -0.02850276, -0.04127743]}]
    write_dig(fiducials_path, fid, 5)

    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    assert_raises(TypeError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir, src='foo')
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='fsaverage', subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir)
    mlab.close(all=True)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info, meg_sensors=True, dig=True, coord_frame=coord_frame,
                   trans=trans_fname, subject='sample',
                   mri_fiducials=fiducials_path, subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked_eeg_ecog.info, subject='sample', trans=trans_fname,
                   source='outer_skin', meg_sensors=True, skull=True,
                   eeg_sensors=['original', 'projected'], ecog_sensors=True,
                   brain='white', head=True, subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
예제 #29
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = _TempDir()
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{
        'coord_frame': 5,
        'ident': 1,
        'kind': 1,
        'r': [-0.08061612, -0.02908875, -0.04131077]
    }, {
        'coord_frame': 5,
        'ident': 2,
        'kind': 1,
        'r': [0.00146763, 0.08506715, -0.03483611]
    }, {
        'coord_frame': 5,
        'ident': 3,
        'kind': 1,
        'r': [0.08436285, -0.02850276, -0.04127743]
    }]
    write_dig(fiducials_path, fid, 5)

    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname,
                           config_fname,
                           hs_fname,
                           convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info,
                   trans_fname,
                   subject='sample',
                   meg_sensors=True,
                   subjects_dir=subjects_dir,
                   ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(ValueError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError,
                  plot_trans,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    assert_raises(TypeError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    assert_raises(ValueError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='fsaverage',
                  subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir)
    mlab.close(all=True)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info,
                   meg_sensors=True,
                   dig=True,
                   coord_frame=coord_frame,
                   trans=trans_fname,
                   subject='sample',
                   mri_fiducials=fiducials_path,
                   subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked_eeg_ecog.info,
                   subject='sample',
                   trans=trans_fname,
                   source='outer_skin',
                   meg_sensors=True,
                   skull=True,
                   eeg_sensors=['original', 'projected'],
                   ecog_sensors=True,
                   brain='white',
                   head=True,
                   subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
=========================================

In this example, the head is shown in the
MEG helmet along with the EEG electrodes in MRI
coordinate system. This allows assessing the
MEG <-> MRI coregistration quality.

"""
# Author: Mainak Jas <*****@*****.**>
#
# License: BSD (3-clause)

from mne import read_evokeds
from mne.datasets import sample
from mne.viz import plot_trans

print(__doc__)


data_path = sample.data_path()

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

condition = 'Left Auditory'
evoked = read_evokeds(evoked_fname, condition=condition, baseline=(-0.2, 0.0))
plot_trans(evoked.info, trans_fname, subject='sample',
           subjects_dir=subjects_dir)
예제 #31
0
파일: test_3d.py 프로젝트: nfoti/mne-python
def test_plot_alignment():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = _TempDir()
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{'coord_frame': 5, 'ident': 1, 'kind': 1,
            'r': [-0.08061612, -0.02908875, -0.04131077]},
           {'coord_frame': 5, 'ident': 2, 'kind': 1,
            'r': [0.00146763, 0.08506715, -0.03483611]},
           {'coord_frame': 5, 'ident': 3, 'kind': 1,
            'r': [0.08436285, -0.02850276, -0.04127743]}]
    write_dig(fiducials_path, fid, 5)

    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        meg = ['helmet', 'sensors']
        if system == 'KIT':
            meg.append('ref')
        plot_alignment(info, trans_fname, subject='sample',
                       subjects_dir=subjects_dir, meg=meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(TypeError, plot_alignment, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    assert_raises(TypeError, plot_alignment, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir, src='foo')
    assert_raises(ValueError, plot_alignment, info, trans_fname,
                  subject='fsaverage', subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir, head=True, skull=True,
                    brain='white')
    mlab.close(all=True)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_alignment(info, meg=['helmet', 'sensors'], dig=True,
                       coord_frame=coord_frame, trans=trans_fname,
                       subject='sample', mri_fiducials=fiducials_path,
                       subjects_dir=subjects_dir, src=sample_src)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_alignment(evoked_eeg_ecog.info, subject='sample',
                       trans=trans_fname, subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'], ecog=True)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])

    sphere = make_sphere_model(info=evoked.info, r0='auto', head_radius='auto')
    bem_sol = read_bem_solution(op.join(subjects_dir, 'sample', 'bem',
                                        'sample-1280-1280-1280-bem-sol.fif'))
    bem_surfs = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
                                          'sample-1280-1280-1280-bem.fif'))
    sample_src[0]['coord_frame'] = 4  # hack for coverage
    plot_alignment(info, trans_fname, subject='sample', meg='helmet',
                   subjects_dir=subjects_dir, eeg='projected', bem=sphere,
                   surfaces=['head', 'brain', 'inner_skull', 'outer_skull'],
                   src=sample_src)
    plot_alignment(info, trans_fname, subject='sample', meg=[],
                   subjects_dir=subjects_dir, bem=bem_sol, eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    plot_alignment(info, trans_fname, subject='sample',
                   meg=True, subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'], bem=bem_surfs)
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    plot_alignment(info, trans_fname, subject='sample', meg=False,
                   coord_frame='mri', subjects_dir=subjects_dir,
                   surfaces=['brain'], bem=sphere)
    # one layer bem with skull surfaces:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['brain', 'head', 'inner_skull'], bem=sphere)
    # wrong eeg value:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, eeg='foo')
    # wrong meg value:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, meg='bar')
    # multiple brain surfaces:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['white', 'pial'])
예제 #32
0
def test_plot_alignment():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = _TempDir()
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{
        'coord_frame': 5,
        'ident': 1,
        'kind': 1,
        'r': [-0.08061612, -0.02908875, -0.04131077]
    }, {
        'coord_frame': 5,
        'ident': 2,
        'kind': 1,
        'r': [0.00146763, 0.08506715, -0.03483611]
    }, {
        'coord_frame': 5,
        'ident': 3,
        'kind': 1,
        'r': [0.08436285, -0.02850276, -0.04127743]
    }]
    write_dig(fiducials_path, fid, 5)

    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname,
                           config_fname,
                           hs_fname,
                           convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        meg = ['helmet', 'sensors']
        if system == 'KIT':
            meg.append('ref')
        plot_alignment(info,
                       trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       meg=meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(TypeError,
                  plot_alignment,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    assert_raises(TypeError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    assert_raises(ValueError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='fsaverage',
                  subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir,
                    head=True,
                    skull=True,
                    brain='white')
    mlab.close(all=True)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_alignment(info,
                       meg=['helmet', 'sensors'],
                       dig=True,
                       coord_frame=coord_frame,
                       trans=trans_fname,
                       subject='sample',
                       mri_fiducials=fiducials_path,
                       subjects_dir=subjects_dir,
                       src=sample_src)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_alignment(evoked_eeg_ecog.info,
                       subject='sample',
                       trans=trans_fname,
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'],
                       ecog=True)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])

    sphere = make_sphere_model(info=evoked.info, r0='auto', head_radius='auto')
    bem_sol = read_bem_solution(
        op.join(subjects_dir, 'sample', 'bem',
                'sample-1280-1280-1280-bem-sol.fif'))
    bem_surfs = read_bem_surfaces(
        op.join(subjects_dir, 'sample', 'bem',
                'sample-1280-1280-1280-bem.fif'))
    sample_src[0]['coord_frame'] = 4  # hack for coverage
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg='helmet',
                   subjects_dir=subjects_dir,
                   eeg='projected',
                   bem=sphere,
                   surfaces=['head', 'brain', 'inner_skull', 'outer_skull'],
                   src=sample_src)
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=[],
                   subjects_dir=subjects_dir,
                   bem=bem_sol,
                   eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=True,
                   subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'],
                   bem=bem_surfs)
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=False,
                   coord_frame='mri',
                   subjects_dir=subjects_dir,
                   surfaces=['brain'],
                   bem=sphere)
    # one layer bem with skull surfaces:
    assert_raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  surfaces=['brain', 'head', 'inner_skull'],
                  bem=sphere)
    # wrong eeg value:
    assert_raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  eeg='foo')
    # wrong meg value:
    assert_raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  meg='bar')
    # multiple brain surfaces:
    assert_raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  surfaces=['white', 'pial'])
예제 #33
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)
예제 #34
0
raws = dict(Neuromag=read_raw_fif(sample.data_path() +
                                  '/MEG/sample/sample_audvis_raw.fif'),
            CTF_275=read_raw_ctf(spm_face.data_path() +
                                 '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
            Magnes_3600wh=read_raw_bti(op.join(bti_path, 'test_pdf_linux'),
                                       op.join(bti_path, 'test_config_linux'),
                                       op.join(bti_path, 'test_hs_linux')),
            KIT=read_raw_kit(op.join(kit_path, 'test.sqd')),
            Artemis123=read_raw_artemis123(
                op.join(testing.data_path(), 'ARTEMIS123',
                        'Artemis_Data_2016-11-03-15h-58m_test.bin')))

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == 'KIT' else True
    fig = plot_trans(raw.info,
                     trans=None,
                     dig=False,
                     eeg_sensors=False,
                     meg_sensors=True,
                     coord_frame='meg',
                     ref_meg=ref_meg)
    text = mlab.title(system)
    text.x_position = 0.5
    text.y_position = 0.95
    text.property.vertical_justification = 'top'
    text.property.justification = 'center'
    text.actor.text_scale_mode = 'none'
    text.property.bold = True
    mlab.draw(fig)