Esempio n. 1
0
def plot_spline(subject_name, subjects_dir, xgt, ygt, zgt, electrodes,
                mlabViewX, mlabViewY):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, electrodes / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)
    fig = mlab.figure('TPS', size=(800, 700))
    plot_alignment(info,
                   subject=subject_name,
                   subjects_dir=subjects_dir,
                   surfaces=['pial'],
                   ecog=False,
                   fig=fig)
    pts = mlab.points3d(xgt, ygt, zgt, scale_mode='none', scale_factor=0.0003)
    # Create and visualize the mesh
    mesh = mlab.pipeline.delaunay2d(pts)
    surf = mlab.pipeline.surface(mesh,
                                 representation='surface',
                                 colormap='rainbow')
    mlab.points3d(electrodes[:, 0] / 1000,
                  electrodes[:, 1] / 1000,
                  electrodes[:, 2] / 1000,
                  color=(1, 0, 0),
                  scale_factor=0.002)

    mlab.view(mlabViewX, mlabViewY)
def save_images(subject_, montage_fname_):
    montage = mne.channels.read_dig_fif(montage_fname_)
    info = mne.create_info(ch_names=montage.ch_names,
                           ch_types=['eeg'] * len(montage.ch_names),
                           sfreq=100.0)
    info.set_montage(montage)
    trans = mne.channels.compute_native_head_t(montage)

    fig_ = plot_alignment(info,
                          eeg='projected',
                          show_axes=False,
                          trans=trans,
                          surfaces={"head": 1.0},
                          coord_frame='mri',
                          subject=subject_)
    fig_.plotter.off_screen = True

    set_3d_view(figure=fig_, azimuth=135, elevation=80, distance=0.4)
    fig_.plotter.screenshot(subject_ + "_1.png")

    set_3d_view(figure=fig_, azimuth=45, elevation=80, distance=0.4)
    fig_.plotter.screenshot(subject_ + "_2.png")

    set_3d_view(figure=fig_, azimuth=270, elevation=80, distance=0.4)
    fig_.plotter.screenshot(subject_ + "_3.png")

    fig_ = plot_alignment(info,
                          eeg=['original', 'projected'],
                          show_axes=True,
                          trans=trans,
                          surfaces="head",
                          coord_frame='mri',
                          dig=True,
                          subject=subject_)
    fig_.plotter.off_screen = True

    set_3d_view(figure=fig_,
                azimuth=135,
                elevation=80,
                distance=0.5,
                focalpoint=np.linalg.inv(trans["trans"])[:3, 3])
    fig_.plotter.screenshot(subject_ + "_clear_1.png")

    set_3d_view(figure=fig_,
                azimuth=45,
                elevation=80,
                distance=0.5,
                focalpoint=np.linalg.inv(trans["trans"])[:3, 3])
    fig_.plotter.screenshot(subject_ + "_clear_2.png")

    set_3d_view(figure=fig_,
                azimuth=270,
                elevation=80,
                distance=0.5,
                focalpoint=np.linalg.inv(trans["trans"])[:3, 3])
    fig_.plotter.screenshot(subject_ + "_clear_3.png")
Esempio n. 3
0
def test_render_add_sections(renderer, tmp_path):
    """Test adding figures/images to section."""
    tempdir = str(tmp_path)
    report = Report(subjects_dir=subjects_dir)
    # Check add_figure functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure

    report.add_figure(fig=fig, title='evoked response', image_format='svg')
    assert 'caption' not in report._content[-1].html

    report.add_figure(fig=fig, title='evoked with caption', caption='descr')
    assert 'caption' in report._content[-1].html

    # Check add_image with png
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_image(image=img_fname, title='evoked response')

    with pytest.raises(FileNotFoundError, match='No such file or directory'):
        report.add_image(image='foobar.xxx', title='H')

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

    report.add_figure(fig=fig, title='random image')
    assert (repr(report))
    fname = op.join(str(tmp_path), 'test.html')
    report.save(fname, open_browser=False)

    assert len(report) == 4
Esempio n. 4
0
def test_snapshot_brain_montage(backends_3d):
    """Test snapshot brain montage."""
    from mne.viz import get_3d_backend
    if get_3d_backend() == 'pyvista':
        pytest.skip("This feature is not available yet on PyVista")

    info = read_info(evoked_fname)
    fig = plot_alignment(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
    pytest.raises(TypeError, snapshot_brain_montage, fig, xyz)

    # All chs must have 3 position values
    pytest.raises(ValueError, snapshot_brain_montage, fig, xyz_dict)

    # Make sure we raise error if the figure has no scene
    pytest.raises(ValueError, snapshot_brain_montage, None, info)
Esempio n. 5
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)
    # 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)
Esempio n. 6
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. 7
0
def brain_plot(subject_name, subjects_dir, electrodes, mlabViewX, mlabViewY,
               textBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, electrodes / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)
    #plot electrodes as spheres or as numbers
    if textBool:
        fig = mlab.figure('brain text', size=(800, 700))
        #plot subject's brain
        plot_alignment(info,
                       subject=subject_name,
                       subjects_dir=subjects_dir,
                       surfaces=['pial'],
                       ecog=False,
                       fig=fig)
        fig.scene.disable_render = True

        for i, x in enumerate(electrodes):
            mlab.text3d(x[0] / 1000,
                        x[1] / 1000,
                        x[2] / 1000,
                        str(i + 1),
                        scale=0.001)

            fig.scene.disable_render = False  # Super duper trick
    else:
        fig = mlab.figure('brain spheres', size=(800, 700))
        #plot subject's brain
        plot_alignment(info,
                       subject=subject_name,
                       subjects_dir=subjects_dir,
                       surfaces=['pial'],
                       ecog=False,
                       fig=fig)
        mlab.points3d(electrodes[:, 0] / 1000,
                      electrodes[:, 1] / 1000,
                      electrodes[:, 2] / 1000,
                      color=(1, 0, 0),
                      scale_factor=0.002)

    #chouse point of view
    mlab.view(mlabViewX, mlabViewY)
Esempio n. 8
0
def test_plot_alignment_fnirs(renderer, tmp_path):
    """Test fNIRS plotting."""
    # Here we use subjects_dir=tmp_path, since no surfaces should actually
    # be loaded!

    # fNIRS (default is pairs)
    info = read_raw_nirx(nirx_fname).info
    assert info['nchan'] == 26
    kwargs = dict(trans='fsaverage', subject='fsaverage', surfaces=(),
                  verbose=True, subjects_dir=tmp_path)
    with catch_logging() as log:
        fig = plot_alignment(info, **kwargs)
    log = log.getvalue()
    assert f'fnirs_cw_amplitude: {info["nchan"]}' in log
    _assert_n_actors(fig, renderer, info['nchan'])

    fig = plot_alignment(
        info, fnirs=['channels', 'sources', 'detectors'], **kwargs)
    _assert_n_actors(fig, renderer, 3)
Esempio n. 9
0
def plot_gamma_motor(subject_name, subjects_dir, dir_n, elec_up, mlabViewX,
                     mlabViewY, saveDataBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, elec_up / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)

    name = listdir(dir_n)
    for nam in name:
        if nam != '.DS_Store':
            gama_t = loadmat(dir_n + nam)
            res_re = gama_t['res']
            s = np.mean(res_re[:, 15:, 0], axis=1)  #gamma
            s = np.interp(s, (s.min(), s.max()), (0, 1))
            fig = mlab.figure('gamma_motor_' + nam, size=(800, 700))
            plot_alignment(info,
                           subject=subject_name,
                           subjects_dir=subjects_dir,
                           surfaces=['pial'],
                           ecog=False,
                           fig=fig)
            obj = mlab.points3d(elec_up[:, 0] / 1000,
                                elec_up[:, 1] / 1000,
                                elec_up[:, 2] / 1000,
                                s,
                                colormap='rainbow',
                                scale_mode='none',
                                scale_factor=0.002)
            mlab.colorbar(object=obj,
                          title='gamma',
                          orientation='vertical',
                          nb_labels=8,
                          nb_colors=None,
                          label_fmt=None)
            mlab.title(nam[:-4], size=0.2, height=0.015)

            #chouse point of view
            mlab.view(mlabViewX, mlabViewY)
            if saveDataBool:
                mlab.savefig(nam[:-4] + '.png')
                mlab.savefig(nam[:-4] + '.x3d')
Esempio n. 10
0
def plot_registration(info, trans, subject, subjects_dir):
    fig = plot_alignment(info,
                         trans,
                         subject=subject,
                         dig=True,
                         meg=True,
                         subjects_dir=subjects_dir,
                         coord_frame='head')
    set_3d_view(figure=fig, azimuth=135, elevation=80)
    mlab.savefig('/home/senthilp/Desktop/coreg.jpg')
    Image(filename='/home/senthilp/Desktop/coreg.jpg', width=500)
    mlab.show()
Esempio n. 11
0
def plot_accuracy(subject_name, subjects_dir, dir_n, elec_up, mlabViewX,
                  mlabViewY, saveDataBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, elec_up / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)

    name = listdir(dir_n)
    for nam in name:
        if nam != '.DS_Store':
            s = np.loadtxt(dir_n + nam)
            s = np.nan_to_num(s[:, 1])
            fig = mlab.figure('accuracy_' + nam, size=(800, 700))
            plot_alignment(info,
                           subject=subject_name,
                           subjects_dir=subjects_dir,
                           surfaces=['pial'],
                           ecog=False,
                           fig=fig)
            obj = mlab.points3d(elec_up[:, 0] / 1000,
                                elec_up[:, 1] / 1000,
                                elec_up[:, 2] / 1000,
                                s,
                                colormap='rainbow',
                                scale_mode='none',
                                scale_factor=0.002)
            mlab.colorbar(object=obj,
                          title='accuracy',
                          orientation='vertical',
                          nb_labels=8,
                          nb_colors=None,
                          label_fmt=None)
            mlab.title(nam[:-4], size=0.2, height=0.015)
            #chouse point of view
            mlab.view(mlabViewX, mlabViewY)
            if saveDataBool:
                mlab.savefig(nam[:-4] + '.png')
                mlab.savefig(nam[:-4] + '.x3d')
Esempio n. 12
0
def plot_alpha_touch(subject_name, subjects_dir, file_n, elec_up, mlabViewX,
                     mlabViewY, saveDataBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, elec_up / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)

    data_t = loadmat(file_n)
    res_re = data_t['res']
    for i in range(5):
        s = np.mean(res_re[:, :5, i], axis=1)  #alpha
        s = np.interp(s, (s.min(), s.max()), (0, 1))
        fig = mlab.figure('alpha_touch_' + str(i), size=(800, 700))
        plot_alignment(info,
                       subject=subject_name,
                       subjects_dir=subjects_dir,
                       surfaces=['pial'],
                       ecog=False,
                       fig=fig)
        obj = mlab.points3d(elec_up[:, 0] / 1000,
                            elec_up[:, 1] / 1000,
                            elec_up[:, 2] / 1000,
                            s,
                            colormap='rainbow',
                            scale_mode='none',
                            scale_factor=0.002)
        mlab.colorbar(object=obj,
                      title='alpha',
                      orientation='vertical',
                      nb_labels=8,
                      nb_colors=None,
                      label_fmt=None)
        mlab.title('touch ' + str(i + 1), size=0.2, height=0.015)
        #chouse point of view
        mlab.view(mlabViewX, mlabViewY)
        if saveDataBool:
            mlab.savefig('alpha_touch_' + str(i + 1) + '.png')
            mlab.savefig('alpha_touch_' + str(i + 1) + '.x3d')
Esempio n. 13
0
def test_render_add_sections(renderer, tmpdir):
    """Test adding figures/images to section."""
    tempdir = str(tmpdir)
    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')
    pytest.raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')
    pytest.raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=0, image_format='svg')
    pytest.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
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])

    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])

    pytest.raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    pytest.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_alignment(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)
    assert (repr(report))
    fname = op.join(str(tmpdir), 'test.html')
    report.save(fname, open_browser=False)
    with open(fname, 'r') as fid:
        html = fid.read()
    assert html.count('<li class="report_custom"') == 8  # several
Esempio n. 14
0
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,  # 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 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_alignment(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)
    assert_true(repr(report))
Esempio n. 15
0
def test_snapshot_brain_montage():
    """Test snapshot brain montage."""
    info = read_info(evoked_fname)
    fig = plot_alignment(
        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
    pytest.raises(TypeError, snapshot_brain_montage, fig, xyz)

    # All chs must have 3 position values
    pytest.raises(ValueError, snapshot_brain_montage, fig, xyz_dict)

    # Make sure we raise error if the figure has no scene
    pytest.raises(TypeError, snapshot_brain_montage, fig, info)
Esempio n. 16
0
def test_snapshot_brain_montage(renderer):
    """Test snapshot brain montage."""
    info = read_info(evoked_fname)
    fig = plot_alignment(
        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
    pytest.raises(TypeError, snapshot_brain_montage, fig, xyz)

    # All chs must have 3 position values
    pytest.raises(ValueError, snapshot_brain_montage, fig, xyz_dict)

    # Make sure we raise error if the figure has no scene
    pytest.raises(ValueError, snapshot_brain_montage, None, info)
Esempio n. 17
0
def plot_locs(seeg_loc, info, study_path):
    from mne.viz import plot_alignment
    from mayavi import mlab
    subjects_dir = op.join(study_path, 'freesurfer_subjects')
    subject = seeg_loc['subject'][0]

    fig = plot_alignment(info,
                         subject=seeg_loc['subject'][0],
                         subjects_dir=subjects_dir,
                         surfaces=['pial'],
                         meg=False,
                         coord_frame='head')
    mlab.view(200, 70)
    mlab.show()

    file_nodes = op.join(study_path, 'physio_data', subject, 'chan_info',
                         '%s.node' % subject)
    make_bnw_nodes(file_nodes,
                   coords=seeg_loc[['x', 'y', 'z']],
                   colors=1.,
                   sizes=1.)
Esempio n. 18
0
def test_snapshot_brain_montage(backends_3d):
    """Test snapshot brain montage."""
    from mne.viz import get_3d_backend
    if get_3d_backend() == 'pyvista':
        pytest.skip("This feature is not available yet on PyVista")

    info = read_info(evoked_fname)
    fig = plot_alignment(
        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
    pytest.raises(TypeError, snapshot_brain_montage, fig, xyz)

    # All chs must have 3 position values
    pytest.raises(ValueError, snapshot_brain_montage, fig, xyz_dict)

    # Make sure we raise error if the figure has no scene
    pytest.raises(ValueError, snapshot_brain_montage, None, info)
Esempio n. 19
0
def test_plot_alignment(tmpdir):
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = str(tmpdir)
    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)
    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
    mlab.close(all=True)
    info = infos['Neuromag']
    pytest.raises(TypeError, plot_alignment, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    pytest.raises(TypeError, plot_alignment, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir, src='foo')
    pytest.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
    mlab.close(all=True)
    # all coord frames
    pytest.raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    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_seeg = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog_seeg.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog_seeg.set_channel_types({'EEG 001': 'ecog',
                                            'EEG 002': 'seeg'})
    with pytest.warns(RuntimeWarning, match='Cannot plot MEG'):
        plot_alignment(evoked_eeg_ecog_seeg.info, subject='sample',
                       trans=trans_fname, subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'], ecog=True, seeg=True)
    mlab.close(all=True)

    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, subject='sample', eeg='projected',
                   meg='helmet', bem=sphere, dig=True,
                   surfaces=['brain', 'inner_skull', 'outer_skull',
                             'outer_skin'])
    plot_alignment(info, trans_fname, subject='sample', meg='helmet',
                   subjects_dir=subjects_dir, eeg='projected', bem=sphere,
                   surfaces=['head', 'brain'], src=sample_src)
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info, trans_fname, subject='sample', meg=[],
                   subjects_dir=subjects_dir, bem=bem_sol, eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    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', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(info, eeg='projected', meg='helmet', bem=sphere,
                   src=src, dig=True, surfaces=['brain', 'inner_skull',
                                                'outer_skull', 'outer_skin'])
    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, show_axes=True)

    # 3D coil with no defined draw (ConvexHull)
    info_cube = pick_info(info, [0])
    info['dig'] = None
    info_cube['chs'][0]['coil_type'] = 9999
    with pytest.raises(RuntimeError, match='coil definition not found'):
        plot_alignment(info_cube, meg='sensors', surfaces=())
    coil_def_fname = op.join(tempdir, 'temp')
    with open(coil_def_fname, 'w') as fid:
        fid.write(coil_3d)
    with use_coil_def(coil_def_fname):
        plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True)

    # one layer bem with skull surfaces:
    pytest.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:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, eeg='foo')
    # wrong meg value:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, meg='bar')
    # multiple brain surfaces:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['white', 'pial'])
    pytest.raises(TypeError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=[1])
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['foo'])
    mlab.close(all=True)
Esempio n. 20
0
# Finally, make evoked from the one epoch
evoked = epochs.average()

###############################################################################
# Explore the electrodes on a template brain
# ------------------------------------------
#
# Our electrodes are shown after being morphed to fsaverage brain so we'll use
# this fsaverage brain to plot the locations of our electrodes. We'll use
# :func:`~mne.viz.snapshot_brain_montage` to save the plot as image data
# (along with xy positions of each electrode in the image), so that later
# we can plot frequency band power on top of it.

fig = plot_alignment(raw.info,
                     subject='fsaverage',
                     subjects_dir=subjects_dir,
                     surfaces=['pial'],
                     coord_frame='mri')
az, el, focalpoint = 160, -70, [0.067, -0.040, 0.018]
mne.viz.set_3d_view(fig, azimuth=az, elevation=el, focalpoint=focalpoint)

xy, im = snapshot_brain_montage(fig, raw.info)

###############################################################################
# Compute frequency features of the data
# --------------------------------------
#
# Next, we'll compute the signal power in the gamma (30-90 Hz) band,
# downsampling the result to 10 Hz (to save time).

sfreq = 10
Esempio n. 21
0
def test_plot_alignment(tmpdir, backends_3d):
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    backend_name = get_3d_backend()
    # generate fiducials file for testing
    tempdir = str(tmpdir)
    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)

    if backend_name == 'mayavi':
        mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    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)
        if backend_name == 'mayavi':
            mlab.close(all=True)
    # KIT ref sensor coil def is defined
    if backend_name == 'mayavi':
        mlab.close(all=True)
    info = infos['Neuromag']
    pytest.raises(TypeError,
                  plot_alignment,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    pytest.raises(OSError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    pytest.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')
    if backend_name == 'mayavi':
        mlab.close(all=True)
    # no-head version
    if backend_name == 'mayavi':
        mlab.close(all=True)
    # all coord frames
    pytest.raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    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=src_fname)
        if backend_name == 'mayavi':
            mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog_seeg.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog_seeg.set_channel_types({
        'EEG 001': 'ecog',
        'EEG 002': 'seeg'
    })
    with pytest.warns(RuntimeWarning, match='Cannot plot MEG'):
        plot_alignment(evoked_eeg_ecog_seeg.info,
                       subject='sample',
                       trans=trans_fname,
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'],
                       ecog=True,
                       seeg=True)
    if backend_name == 'mayavi':
        mlab.close(all=True)

    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,
        subject='sample',
        eeg='projected',
        meg='helmet',
        bem=sphere,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg='helmet',
                   subjects_dir=subjects_dir,
                   eeg='projected',
                   bem=sphere,
                   surfaces=['head', 'brain'],
                   src=sample_src)
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=[],
                   subjects_dir=subjects_dir,
                   bem=bem_sol,
                   eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    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', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(
        info,
        eeg='projected',
        meg='helmet',
        bem=sphere,
        src=src,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    # no info is permitted
    fig = plot_alignment(trans=trans_fname,
                         subject='sample',
                         meg=False,
                         coord_frame='mri',
                         subjects_dir=subjects_dir,
                         surfaces=['brain'],
                         bem=sphere,
                         show_axes=True)
    if backend_name == 'mayavi':
        import mayavi  # noqa: F401 analysis:ignore
        assert isinstance(fig, mayavi.core.scene.Scene)

    # 3D coil with no defined draw (ConvexHull)
    info_cube = pick_info(info, [0])
    info['dig'] = None
    info_cube['chs'][0]['coil_type'] = 9999
    with pytest.raises(RuntimeError, match='coil definition not found'):
        plot_alignment(info_cube, meg='sensors', surfaces=())
    coil_def_fname = op.join(tempdir, 'temp')
    with open(coil_def_fname, 'w') as fid:
        fid.write(coil_3d)
    with use_coil_def(coil_def_fname):
        plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True)

    # one layer bem with skull surfaces:
    pytest.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:
    pytest.raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  eeg='foo')
    # wrong meg value:
    pytest.raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  meg='bar')
    # multiple brain surfaces:
    pytest.raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  surfaces=['white', 'pial'])
    pytest.raises(TypeError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  surfaces=[1])
    pytest.raises(ValueError,
                  plot_alignment,
                  info=info,
                  trans=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  surfaces=['foo'])
    if backend_name == 'mayavi':
        mlab.close(all=True)
Esempio n. 22
0
# evoked data.

raw.set_eeg_reference(projection=True)
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events)
cov = mne.compute_covariance(epochs, tmax=0.)
evoked = epochs['1'].average()  # trigger 1 in auditory/left
evoked.plot_joint()

##############################################################################
# Getting a source estimate
# -------------------------
# New we have all of the components we need to compute a forward solution,
# but first we should sanity check that everything is well aligned:

plot_alignment(evoked.info, trans=trans, show_axes=True, surfaces='head-dense',
               subject='sample', subjects_dir=subjects_dir)

##############################################################################
# Now we can actually compute the forward:

fwd = mne.make_forward_solution(
    evoked.info, trans=trans, src=fname_src, bem=fname_bem, verbose=True)

##############################################################################
# Finally let's compute the inverse and apply it:

inv = mne.minimum_norm.make_inverse_operator(
    evoked.info, fwd, cov, verbose=True)
stc = mne.minimum_norm.apply_inverse(evoked, inv)
stc.plot(subjects_dir=subjects_dir, initial_time=0.1)
Esempio n. 23
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_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces=['pial'])
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_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces='pial')
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

# Convert from a dictionary to array to plot
def plot_nirs_source_detector(data,
                              info=None,
                              radius=0.001,
                              trans=None,
                              subject=None,
                              subjects_dir=None,
                              surfaces='head',
                              coord_frame='head',
                              meg=None,
                              eeg='original',
                              fwd=None,
                              dig=False,
                              ecog=True,
                              src=None,
                              mri_fiducials=False,
                              bem=None,
                              seeg=True,
                              fnirs=False,
                              show_axes=False,
                              fig=None,
                              cmap=None,
                              interaction='trackball',
                              verbose=None):
    """
    3D visualisation of fNIRS response magnitude.

    This function plots the response amplitude for each channel.
    Each channel is represented by a line between the source and detector,
    the color of the line reflects the response magnitude.

    Parameters
    ----------
    data : array
        Array of values to be plotted between source and detectors.
        One value should be specified per channel in the same order
        as `info.chs`.
    info : dict | None
        The measurement info.
        If None (default), no sensor information will be shown.
    radius : numbers
        Tube radius for connecting links.
    %(trans)s
    subject : str | None
        The subject name corresponding to FreeSurfer environment
        variable SUBJECT. Can be omitted if ``src`` is provided.
    %(subjects_dir)s
    surfaces : str | list
        Surfaces to plot. Supported values:

        * scalp: one of 'head', 'outer_skin' (alias for 'head'),
          'head-dense', or 'seghead' (alias for 'head-dense')
        * skull: 'outer_skull', 'inner_skull', 'brain' (alias for
          'inner_skull')
        * brain: one of 'pial', 'white', 'inflated', or 'brain'
          (alias for 'pial').

        Defaults to 'head'.

        .. note:: For single layer BEMs it is recommended to use 'brain'.
    coord_frame : str
        Coordinate frame to use, 'head', 'meg', or 'mri'.
    meg : str | list | bool | None
        Can be "helmet", "sensors" or "ref" to show the MEG helmet, sensors or
        reference sensors respectively, or a combination like
        ``('helmet', 'sensors')`` (same as None, default). True translates to
        ``('helmet', 'sensors', 'ref')``.
    eeg : bool | str | list
        String options are:

        - "original" (default; equivalent to ``True``)
            Shows EEG sensors using their digitized locations (after
            transformation to the chosen ``coord_frame``)
        - "projected"
            The EEG locations projected onto the scalp, as is done in forward
            modeling

        Can also be a list of these options, or an empty list (``[]``,
        equivalent of ``False``).
    fwd : instance of Forward
        The forward solution. If present, the orientations of the dipoles
        present in the forward solution are displayed.
    dig : bool | 'fiducials'
        If True, plot the digitization points; 'fiducials' to plot fiducial
        points only.
    ecog : bool
        If True (default), show ECoG sensors.
    src : instance of SourceSpaces | None
        If not None, also plot the source space points.
    mri_fiducials : bool | str
        Plot MRI fiducials (default False). If ``True``, look for a file with
        the canonical name (``bem/{subject}-fiducials.fif``). If ``str`` it
        should provide the full path to the fiducials file.
    bem : list of dict | instance of ConductorModel | None
        Can be either the BEM surfaces (list of dict), a BEM solution or a
        sphere model. If None, we first try loading
        `'$SUBJECTS_DIR/$SUBJECT/bem/$SUBJECT-$SOURCE.fif'`, and then look for
        `'$SUBJECT*$SOURCE.fif'` in the same directory. For `'outer_skin'`,
        the subjects bem and bem/flash folders are searched. Defaults to None.
    seeg : bool
        If True (default), show sEEG electrodes.
    fnirs : bool
        If True (default), show fNIRS electrodes.
    show_axes : bool
        If True (default False), coordinate frame axis indicators will be
        shown:

        * head in pink.
        * MRI in gray (if ``trans is not None``).
        * MEG in blue (if MEG sensors are present).

        .. versionadded:: 0.16
    fig : mayavi.mlab.Figure | None
        Mayavi Scene in which to plot the alignment.
        If ``None``, creates a new 600x600 pixel figure with black background.

        .. versionadded:: 0.16
    cmap : str
        Colormap to be used.
    interaction : str
        Can be "trackball" (default) or "terrain", i.e. a turntable-style
        camera.

        .. versionadded:: 0.16
    %(verbose)s

    Returns
    -------
    fig : Figure
        The 3D figure.

    Notes
    -----
    For more information see :func:`mne.viz.plot_alignment`.

    .. versionadded:: 0.15
    """
    # Determine range of values for creating colormap
    vmin = np.min(data)
    vmax = np.max(data)

    # If no colormap is specified choose depending on range of data
    if cmap is None:
        if (vmin >= 0) & (vmax >= 0):
            # For positive only data use magma
            cmap = 'Oranges'
        else:
            # Otherwise use blue to red and ensure zero sits at white
            vmin = -1. * np.max(np.abs(data))
            vmax = np.max(np.abs(data))
            cmap = 'RdBu_r'

    if isinstance(radius, (int, float)):
        radius = np.ones(len(info['chs'])) * radius

    # Plot requested alignment
    fig = plot_alignment(info=info,
                         trans=trans,
                         subject=subject,
                         subjects_dir=subjects_dir,
                         surfaces=surfaces,
                         coord_frame=coord_frame,
                         meg=meg,
                         eeg=eeg,
                         fwd=fwd,
                         dig=dig,
                         ecog=ecog,
                         src=src,
                         mri_fiducials=mri_fiducials,
                         bem=bem,
                         seeg=seeg,
                         fnirs=fnirs,
                         show_axes=show_axes,
                         fig=fig,
                         interaction=interaction,
                         verbose=verbose)

    from mne.viz.backends.renderer import _get_renderer
    renderer = _get_renderer(fig)

    # Overlay channels between source and detectors
    for idx, ch in enumerate(info['chs']):
        locs = ch['loc']

        renderer.tube(origin=[np.array([locs[3], locs[4], locs[5]])],
                      destination=[np.array([locs[6], locs[7], locs[8]])],
                      scalars=np.array([[1.0, 1.0]]) * data[idx],
                      radius=radius[idx],
                      colormap=cmap,
                      vmin=vmin,
                      vmax=vmax)

    t = renderer.tube(origin=[np.array([0, 0, 0])],
                      destination=[np.array([0, 0, 0.001])],
                      scalars=np.array([[vmin, vmax]]),
                      radius=0.0001,
                      colormap=cmap,
                      vmin=vmin,
                      vmax=vmax)
    renderer.scalarbar(t)

    return fig
Esempio n. 25
0
raws = {
    '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_2017-04-14-10h-38m-59s_Phantom_1k_HPI_1s.bin')),
}

for system, raw in sorted(raws.items()):
    meg = ['helmet', 'sensors']
    # We don't have coil definitions for KIT refs, so exclude them
    if system != 'KIT':
        meg.append('ref')
    fig = plot_alignment(raw.info,
                         eeg=False,
                         meg=('helmet', 'sensors'),
                         coord_frame='meg',
                         show_axes=True,
                         verbose=True)
    set_3d_title(figure=fig, title=system)
Esempio n. 26
0
import mne
from mne.channels.montage import get_builtin_montages
from mne.datasets import fetch_fsaverage
from mne.viz import plot_alignment

subjects_dir = op.dirname(fetch_fsaverage())

###############################################################################
# check all montages
#

for current_montage in get_builtin_montages():

    montage = mne.channels.read_montage(current_montage,
                                        unit='auto',
                                        transform=False)

    info = mne.create_info(ch_names=montage.ch_names,
                           sfreq=1,
                           ch_types='eeg',
                           montage=montage)

    fig = plot_alignment(info, trans=None,
                         subject='fsaverage',
                         subjects_dir=subjects_dir,
                         eeg=['projected'],
                         )
    mlab.view(135, 80)
    mlab.title(montage.kind, figure=fig)
Esempio n. 27
0
def test_plot_alignment(tmpdir, renderer):
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = str(tmpdir)
    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)

    renderer._close_all()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    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')
        fig = plot_alignment(info,
                             trans_fname,
                             subject='sample',
                             subjects_dir=subjects_dir,
                             meg=meg)
        rend = renderer._Renderer(fig=fig)
        rend.close()
    # KIT ref sensor coil def is defined
    renderer._close_all()
    info = infos['Neuromag']
    pytest.raises(TypeError,
                  plot_alignment,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    pytest.raises(OSError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    pytest.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')
    renderer._close_all()
    # no-head version
    renderer._close_all()
    # all coord frames
    pytest.raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    for coord_frame in ('meg', 'head', 'mri'):
        fig = 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=src_fname)
    renderer._close_all()
    # EEG only with strange options
    evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog_seeg.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog_seeg.set_channel_types({
        'EEG 001': 'ecog',
        'EEG 002': 'seeg'
    })
    with pytest.warns(RuntimeWarning, match='Cannot plot MEG'):
        plot_alignment(evoked_eeg_ecog_seeg.info,
                       subject='sample',
                       trans=trans_fname,
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'],
                       ecog=True,
                       seeg=True)
    renderer._close_all()

    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,
        subject='sample',
        eeg='projected',
        meg='helmet',
        bem=sphere,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg='helmet',
                   subjects_dir=subjects_dir,
                   eeg='projected',
                   bem=sphere,
                   surfaces=['head', 'brain'],
                   src=sample_src)
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=[],
                   subjects_dir=subjects_dir,
                   bem=bem_sol,
                   eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=True,
                   subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'],
                   bem=bem_surfs)
    # single-layer BEM can still plot head surface
    assert bem_surfs[-1]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN
    bem_sol_homog = read_bem_solution(
        op.join(subjects_dir, 'sample', 'bem', 'sample-1280-bem-sol.fif'))
    for use_bem in (bem_surfs[-1:], bem_sol_homog):
        with catch_logging() as log:
            plot_alignment(info,
                           trans_fname,
                           subject='sample',
                           meg=True,
                           subjects_dir=subjects_dir,
                           surfaces=['head', 'inner_skull'],
                           bem=use_bem,
                           verbose=True)
        log = log.getvalue()
        assert 'not find the surface for head in the provided BEM model' in log
    # sphere model
    sphere = make_sphere_model('auto', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(
        info,
        eeg='projected',
        meg='helmet',
        bem=sphere,
        src=src,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    # no info is permitted
    fig = plot_alignment(trans=trans_fname,
                         subject='sample',
                         meg=False,
                         coord_frame='mri',
                         subjects_dir=subjects_dir,
                         surfaces=['brain'],
                         bem=sphere,
                         show_axes=True)
    renderer._close_all()
    if renderer.get_3d_backend() == 'mayavi':
        import mayavi  # noqa: F401 analysis:ignore
        assert isinstance(fig, mayavi.core.scene.Scene)

    # 3D coil with no defined draw (ConvexHull)
    info_cube = pick_info(info, [0])
    info['dig'] = None
    info_cube['chs'][0]['coil_type'] = 9999
    with pytest.raises(RuntimeError, match='coil definition not found'):
        plot_alignment(info_cube, meg='sensors', surfaces=())
    coil_def_fname = op.join(tempdir, 'temp')
    with open(coil_def_fname, 'w') as fid:
        fid.write(coil_3d)
    with use_coil_def(coil_def_fname):
        plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True)

    # one layer bem with skull surfaces:
    with pytest.raises(ValueError, match='sphere conductor model must have'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['brain', 'head', 'inner_skull'],
                       bem=sphere)
    # wrong eeg value:
    with pytest.raises(ValueError, match='eeg must only contain'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       eeg='foo')
    # wrong meg value:
    with pytest.raises(ValueError, match='meg must only contain'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       meg='bar')
    # multiple brain surfaces:
    with pytest.raises(ValueError, match='Only one brain surface can be plot'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'pial'])
    with pytest.raises(TypeError, match='all entries in surfaces must be'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=[1])
    with pytest.raises(ValueError, match='Unknown surface type'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['foo'])
    fwd_fname = op.join(data_dir, 'MEG', 'sample',
                        'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')
    fwd = read_forward_solution(fwd_fname)
    plot_alignment(subject='sample',
                   subjects_dir=subjects_dir,
                   trans=trans_fname,
                   fwd=fwd,
                   surfaces='white',
                   coord_frame='head')
    fwd = convert_forward_solution(fwd, force_fixed=True)
    plot_alignment(subject='sample',
                   subjects_dir=subjects_dir,
                   trans=trans_fname,
                   fwd=fwd,
                   surfaces='white',
                   coord_frame='head')

    renderer._close_all()
Esempio n. 28
0
###############################################################################
# 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_alignment(info,
                     subject='sample',
                     subjects_dir=subjects_dir,
                     surfaces=['pial'])
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_alignment(info,
                     subject='sample',
                     subjects_dir=subjects_dir,
                     surfaces='pial')
mlab.view(200, 70)
Esempio n. 29
0
import mne
from mne.io import read_raw_fif, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.io import read_raw_artemis123
from mne.datasets import sample, spm_face, testing
from mne.viz import plot_alignment, set_3d_title

print(__doc__)

###############################################################################
# Neuromag
# --------

kwargs = dict(eeg=False, coord_frame='meg', show_axes=True, verbose=True)

raw = read_raw_fif(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif')
fig = plot_alignment(raw.info, meg=('helmet', 'sensors'), **kwargs)
set_3d_title(figure=fig, title='Neuromag')

###############################################################################
# CTF
# ---

raw = read_raw_ctf(spm_face.data_path() +
                   '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds')
fig = plot_alignment(raw.info, meg=('helmet', 'sensors', 'ref'), **kwargs)
set_3d_title(figure=fig, title='CTF 275')

###############################################################################
# BTi
# ---
Esempio n. 30
0
elec = mat['elec']  # electrode coordinates in meters
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_alignment`, which visualizes electrode positions.

fig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces=['pial'], meg=False)
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
Esempio n. 31
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_alignment
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_alignment(raw.info, trans, subject='sample', dig=False,
                     eeg=['original', 'projected'], meg=[],
                     coord_frame='head', subjects_dir=subjects_dir)
mlab.view(135, 80)
Esempio n. 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
    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
    mlab.close(all=True)
    # all coord frames
    assert_raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    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, subject='sample', eeg='projected',
                   meg='helmet', bem=sphere, dig=True,
                   surfaces=['brain', 'inner_skull', 'outer_skull',
                             'outer_skin'])
    plot_alignment(info, trans_fname, subject='sample', meg='helmet',
                   subjects_dir=subjects_dir, eeg='projected', bem=sphere,
                   surfaces=['head', 'brain'], 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', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(info, eeg='projected', meg='helmet', bem=sphere,
                   src=src, dig=True, surfaces=['brain', 'inner_skull',
                                                'outer_skull', 'outer_skin'])
    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, show_axes=True)

    # 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'])
    assert_raises(TypeError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=[1])
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['foo'])
    mlab.close(all=True)
Esempio n. 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_alignment
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_alignment(raw.info,
                     trans,
                     subject='sample',
                     dig=False,
                     eeg=['original', 'projected'],
                     meg=[],
                     coord_frame='head',
                     subjects_dir=subjects_dir)
mlab.view(135, 80)
Esempio n. 34
0
    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_2017-04-14-10h-38m-59s_Phantom_1k_HPI_1s.bin')))

for system, raw in raws.items():
    meg = ['helmet', 'sensors']
    # We don't have coil definitions for KIT refs, so exclude them
    if system != 'KIT':
        meg.append('ref')
    fig = plot_alignment(raw.info,
                         trans=None,
                         dig=False,
                         eeg=False,
                         surfaces=[],
                         meg=meg,
                         coord_frame='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)
Esempio n. 35
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
    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
    mlab.close(all=True)
    # all coord frames
    assert_raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    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, subject='sample', eeg='projected',
                   meg='helmet', bem=sphere, dig=True,
                   surfaces=['brain', 'inner_skull', 'outer_skull',
                             'outer_skin'])
    plot_alignment(info, trans_fname, subject='sample', meg='helmet',
                   subjects_dir=subjects_dir, eeg='projected', bem=sphere,
                   surfaces=['head', 'brain'], 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', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(info, eeg='projected', meg='helmet', bem=sphere,
                   src=src, dig=True, surfaces=['brain', 'inner_skull',
                                                'outer_skull', 'outer_skin'])
    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, show_axes=True)

    # 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'])
    assert_raises(TypeError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=[1])
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['foo'])
    mlab.close(all=True)
Esempio n. 36
0
                                        coord_frame='head')
info = mne.create_info(ch_names, 1000., 'ecog').set_montage(montage)
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_alignment`, which visualizes electrode positions.

fig = plot_alignment(info,
                     subject='sample',
                     subjects_dir=subjects_dir,
                     surfaces=['pial'],
                     meg=False)
set_3d_view(figure=fig, azimuth=200, elevation=70)
xy, im = snapshot_brain_montage(fig, montage)

# 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')
Esempio n. 37
0
def test_plot_alignment_basic(tmpdir, renderer, mixed_fwd_cov_evoked):
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = str(tmpdir)
    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)
    evoked = read_evokeds(evoked_fname)[0]
    info = evoked.info

    sample_src = read_source_spaces(src_fname)
    pytest.raises(TypeError,
                  plot_alignment,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    pytest.raises(OSError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    pytest.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')
    # mixed source space
    mixed_src = mixed_fwd_cov_evoked[0]['src']
    assert mixed_src.kind == 'mixed'
    plot_alignment(info,
                   meg=['helmet', 'sensors'],
                   dig=True,
                   coord_frame='head',
                   trans=Path(trans_fname),
                   subject='sample',
                   mri_fiducials=fiducials_path,
                   subjects_dir=subjects_dir,
                   src=mixed_src)
    renderer.backend._close_all()
    # no-head version
    renderer.backend._close_all()
    # trans required
    with pytest.raises(ValueError, match='transformation matrix is required'):
        plot_alignment(info, trans=None, src=src_fname)
    with pytest.raises(ValueError, match='transformation matrix is required'):
        plot_alignment(info, trans=None, mri_fiducials=True)
    with pytest.raises(ValueError, match='transformation matrix is required'):
        plot_alignment(info, trans=None, surfaces=['brain'])
    # all coord frames
    plot_alignment(info)  # works: surfaces='auto' default
    for coord_frame in ('meg', 'head', 'mri'):
        fig = plot_alignment(info,
                             meg=['helmet', 'sensors'],
                             dig=True,
                             coord_frame=coord_frame,
                             trans=Path(trans_fname),
                             subject='sample',
                             mri_fiducials=fiducials_path,
                             subjects_dir=subjects_dir,
                             src=src_fname)
    renderer.backend._close_all()
    # EEG only with strange options
    evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog_seeg.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog_seeg.set_channel_types({
        'EEG 001': 'ecog',
        'EEG 002': 'seeg'
    })
    with catch_logging() as log:
        plot_alignment(evoked_eeg_ecog_seeg.info,
                       subject='sample',
                       trans=trans_fname,
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'],
                       ecog=True,
                       seeg=True,
                       verbose=True)
    log = log.getvalue()
    assert 'ecog: 1' in log
    assert 'seeg: 1' in log
    renderer.backend._close_all()

    sphere = make_sphere_model(info=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',
        eeg='projected',
        meg='helmet',
        bem=sphere,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    plot_alignment(info,
                   subject='sample',
                   meg='helmet',
                   subjects_dir=subjects_dir,
                   eeg='projected',
                   bem=sphere,
                   surfaces=['head', 'brain'],
                   src=sample_src)
    # no trans okay, no mri surfaces
    plot_alignment(info, bem=sphere, surfaces=['brain'])
    with pytest.raises(ValueError, match='A head surface is required'):
        plot_alignment(info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       eeg='projected',
                       surfaces=[])
    with pytest.raises(RuntimeError, match='No brain surface found'):
        plot_alignment(info,
                       trans=trans_fname,
                       subject='foo',
                       subjects_dir=subjects_dir,
                       surfaces=['brain'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=[],
                   subjects_dir=subjects_dir,
                   bem=bem_sol,
                   eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=True,
                   subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'],
                   bem=bem_surfs)
    # single-layer BEM can still plot head surface
    assert bem_surfs[-1]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN
    bem_sol_homog = read_bem_solution(
        op.join(subjects_dir, 'sample', 'bem', 'sample-1280-bem-sol.fif'))
    for use_bem in (bem_surfs[-1:], bem_sol_homog):
        with catch_logging() as log:
            plot_alignment(info,
                           trans_fname,
                           subject='sample',
                           meg=True,
                           subjects_dir=subjects_dir,
                           surfaces=['head', 'inner_skull'],
                           bem=use_bem,
                           verbose=True)
        log = log.getvalue()
        assert 'not find the surface for head in the provided BEM model' in log
    # sphere model
    sphere = make_sphere_model('auto', 'auto', info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(
        info,
        trans=Transform('head', 'mri'),
        eeg='projected',
        meg='helmet',
        bem=sphere,
        src=src,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    sphere = make_sphere_model('auto', None, info)  # one layer
    # if you ask for a brain surface with a 1-layer sphere model it's an error
    with pytest.raises(RuntimeError, match='Sphere model does not have'):
        fig = plot_alignment(trans=trans_fname,
                             subject='sample',
                             subjects_dir=subjects_dir,
                             surfaces=['brain'],
                             bem=sphere)
    # but you can ask for a specific brain surface, and
    # no info is permitted
    fig = plot_alignment(trans=trans_fname,
                         subject='sample',
                         meg=False,
                         coord_frame='mri',
                         subjects_dir=subjects_dir,
                         surfaces=['white'],
                         bem=sphere,
                         show_axes=True)
    renderer.backend._close_all()
    if renderer._get_3d_backend() == 'mayavi':
        import mayavi  # noqa: F401 analysis:ignore
        assert isinstance(fig, mayavi.core.scene.Scene)
    # 3D coil with no defined draw (ConvexHull)
    info_cube = pick_info(info, np.arange(6))
    info['dig'] = None
    info_cube['chs'][0]['coil_type'] = 9999
    info_cube['chs'][1]['coil_type'] = 9998
    with pytest.raises(RuntimeError, match='coil definition not found'):
        plot_alignment(info_cube, meg='sensors', surfaces=())
    coil_def_fname = op.join(tempdir, 'temp')
    with open(coil_def_fname, 'w') as fid:
        fid.write(coil_3d)
    # make sure our other OPMs can be plotted, too
    for ii, kind in enumerate(
        ('QUSPIN_ZFOPM_MAG', 'QUSPIN_ZFOPM_MAG2', 'FIELDLINE_OPM_MAG_GEN1',
         'KERNEL_OPM_MAG_GEN1'), 2):
        info_cube['chs'][ii]['coil_type'] = getattr(FIFF, f'FIFFV_COIL_{kind}')
    with use_coil_def(coil_def_fname):
        with catch_logging() as log:
            plot_alignment(info_cube,
                           meg='sensors',
                           surfaces=(),
                           dig=True,
                           verbose='debug')
    log = log.getvalue()
    assert 'planar geometry' in log

    # one layer bem with skull surfaces:
    with pytest.raises(RuntimeError, match='Sphere model does not.*boundary'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['brain', 'head', 'inner_skull'],
                       bem=sphere)
    # wrong eeg value:
    with pytest.raises(ValueError, match='Invalid value for the .eeg'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       eeg='foo')
    # wrong meg value:
    with pytest.raises(ValueError, match='Invalid value for the .meg'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       meg='bar')
    # multiple brain surfaces:
    with pytest.raises(ValueError, match='Only one brain surface can be plot'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'pial'])
    with pytest.raises(TypeError, match='surfaces.*must be'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=[1])
    with pytest.raises(ValueError, match='Unknown surface type'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['foo'])
    with pytest.raises(TypeError, match="must be an instance of "):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=dict(brain='super clear'))
    with pytest.raises(ValueError, match="must be between 0 and 1"):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=dict(brain=42))
    fwd_fname = op.join(data_dir, 'MEG', 'sample',
                        'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')
    fwd = read_forward_solution(fwd_fname)
    plot_alignment(subject='sample',
                   subjects_dir=subjects_dir,
                   trans=trans_fname,
                   fwd=fwd,
                   surfaces='white',
                   coord_frame='head')
    fwd = convert_forward_solution(fwd, force_fixed=True)
    plot_alignment(subject='sample',
                   subjects_dir=subjects_dir,
                   trans=trans_fname,
                   fwd=fwd,
                   surfaces='white',
                   coord_frame='head')
    fwd['coord_frame'] = FIFF.FIFFV_COORD_MRI  # check required to get to MRI
    with pytest.raises(ValueError, match='transformation matrix is required'):
        plot_alignment(info, trans=None, fwd=fwd)
    # surfaces as dict
    plot_alignment(subject='sample',
                   coord_frame='head',
                   trans=trans_fname,
                   subjects_dir=subjects_dir,
                   surfaces={
                       'white': 0.4,
                       'outer_skull': 0.6,
                       'head': None
                   })
Esempio n. 38
0
    '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_2017-04-14-10h-38m-59s_Phantom_1k_HPI_1s.bin')),
}

for system, raw in sorted(raws.items()):
    meg = ['helmet', 'sensors']
    # We don't have coil definitions for KIT refs, so exclude them
    if system != 'KIT':
        meg.append('ref')
    fig = plot_alignment(raw.info, trans=None, dig=False, eeg=False,
                         surfaces=[], meg=meg, coord_frame='meg',
                         verbose=True)
    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
    text.property.font_size = 40
    mlab.draw(fig)