Ejemplo n.º 1
0
def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(evoked_fname,
                              'Left Auditory',
                              baseline=(None, 0))
    evoked.plot_topomap(0.1, 'mag', layout=layout)
    plot_evoked_topomap(evoked, None, ch_type='mag')
    times = [0.1, 0.2]
    plot_evoked_topomap(evoked, times, ch_type='eeg')
    plot_evoked_topomap(evoked, times, ch_type='grad')
    plot_evoked_topomap(evoked, times, ch_type='planar1')
    plot_evoked_topomap(evoked, times, ch_type='planar2')
    with warnings.catch_warnings(True):  # delaunay triangulation warning
        plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  0.1,
                  'mag',
                  proj='interactive')  # projs have already been applied
    evoked.proj = False  # let's fake it like they haven't been applied
    plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    # projs
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
    plt.close('all')
Ejemplo n.º 2
0
def test_plot_topomap_neuromag122():
    """Test topomap plotting."""
    res = 8
    fast_test = dict(res=res, contours=0, sensors=False)
    evoked = read_evokeds(evoked_fname, 'Left Auditory', baseline=(None, 0))
    evoked.pick_types(meg='grad')
    evoked.pick_channels(evoked.ch_names[:122])
    ch_names = ['MEG %03d' % k for k in range(1, 123)]
    for c in evoked.info['chs']:
        c['coil_type'] = FIFF.FIFFV_COIL_NM_122
    evoked.rename_channels(
        {c_old: c_new
         for (c_old, c_new) in zip(evoked.ch_names, ch_names)})
    layout = find_layout(evoked.info)
    assert layout.kind.startswith('Neuromag_122')
    evoked.plot_topomap(times=[0.1], **fast_test)

    proj = Projection(active=False,
                      desc="test",
                      kind=1,
                      data=dict(nrow=1,
                                ncol=122,
                                row_names=None,
                                col_names=evoked.ch_names,
                                data=np.ones(122)),
                      explained_var=0.5)

    plot_projs_topomap([proj], evoked.info, **fast_test)
Ejemplo n.º 3
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.read_evokeds(evoked_fname, 'Left Auditory',
                                  baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg', vmin=np.min)
        plot_evoked_topomap(evoked, times, ch_type='grad', vmin=np.min,
                            vmax=np.max)
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True)

        p = plot_evoked_topomap(evoked, times, ch_type='grad',
                                show_names=lambda x: x.replace('MEG', ''))
        subplot = [x for x in p.get_children() if
                   isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(all('MEG' not in x.get_text()
                        for x in subplot.get_children()
                        if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if
                    isinstance(x, matplotlib.text.Text)]

        p = plot_evoked_topomap(evoked, times, ch_type='eeg')
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom')
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
Ejemplo n.º 4
0
def test_plot_topomap_neuromag122():
    """Test topomap plotting."""
    res = 8
    fast_test = dict(res=res, contours=0, sensors=False)
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    evoked.pick_types(meg='grad')
    evoked.pick_channels(evoked.ch_names[:122])
    ch_names = ['MEG %03d' % k for k in range(1, 123)]
    for c in evoked.info['chs']:
        c['coil_type'] = FIFF.FIFFV_COIL_NM_122
    evoked.rename_channels({c_old: c_new for (c_old, c_new) in
                            zip(evoked.ch_names, ch_names)})
    layout = find_layout(evoked.info)
    assert layout.kind.startswith('Neuromag_122')
    evoked.plot_topomap(times=[0.1], **fast_test)

    proj = Projection(active=False,
                      desc="test", kind=1,
                      data=dict(nrow=1, ncol=122,
                                row_names=None,
                                col_names=evoked.ch_names, data=np.ones(122)),
                      explained_var=0.5)

    plot_projs_topomap([proj], info=evoked.info, **fast_test)
    plot_projs_topomap([proj], layout=layout, **fast_test)
    pytest.raises(RuntimeError, plot_projs_topomap, [proj], **fast_test)
Ejemplo n.º 5
0
def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(evoked_fname, 'Left Auditory',
                              baseline=(None, 0))
    evoked.plot_topomap(0.1, 'mag', layout=layout)
    plot_evoked_topomap(evoked, None, ch_type='mag')
    times = [0.1, 0.2]
    plot_evoked_topomap(evoked, times, ch_type='eeg')
    plot_evoked_topomap(evoked, times, ch_type='grad')
    plot_evoked_topomap(evoked, times, ch_type='planar1')
    plot_evoked_topomap(evoked, times, ch_type='planar2')
    with warnings.catch_warnings(True):  # delaunay triangulation warning
        plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied
    evoked.proj = False  # let's fake it like they haven't been applied
    plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    # projs
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
    plt.close('all')
Ejemplo n.º 6
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter("always", UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
        evoked.plot_topomap(0.1, "mag", layout=layout)
        plot_evoked_topomap(evoked, None, ch_type="mag")
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type="eeg")
        plot_evoked_topomap(evoked, times, ch_type="grad")
        plot_evoked_topomap(evoked, times, ch_type="planar1")
        plot_evoked_topomap(evoked, times, ch_type="planar2")
        plot_evoked_topomap(evoked, times, ch_type="grad", show_names=True)

        p = plot_evoked_topomap(evoked, times, ch_type="grad", show_names=lambda x: x.replace("MEG", ""))
        subplot = [x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(
            all("MEG" not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text))
        )

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text)]

        p = plot_evoked_topomap(evoked, times, ch_type="eeg")
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type="eeg", title="Custom")
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], "Custom")

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto")
        assert_raises(
            RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
        )  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
        plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
        plot_projs_topomap(projs)
        plt.close("all")
        for ch in evoked.info["chs"]:
            if ch["coil_type"] == FIFF.FIFFV_COIL_EEG:
                if ch["eeg_loc"] is not None:
                    ch["eeg_loc"].fill(0)
                ch["loc"].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
Ejemplo n.º 7
0
def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(evoked_fname, "Left Auditory", baseline=(None, 0))
    evoked.plot_topomap(0.1, "mag", layout=layout)
    plot_evoked_topomap(evoked, None, ch_type="mag")
    times = [0.1, 0.2]
    plot_evoked_topomap(evoked, times, ch_type="grad")
    plot_evoked_topomap(evoked, times, ch_type="planar1")
    plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto")
    plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    # projs
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
Ejemplo n.º 8
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap(info)
    plot_projs_topomap(projs[:1], info, axes=ax, **fast_test)  # test axes
    plt.close('all')
    triux_info = read_info(triux_fname)
    plot_projs_topomap(triux_info['projs'][-1:], triux_info, **fast_test)
    plt.close('all')
    plot_projs_topomap(triux_info['projs'][:1], triux_info, **fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    eeg_avg.plot_topomap(info, **fast_test)
    plt.close('all')
    # test vlims
    for vlim in ('joint', (-1, 1), (None, 0.5), (0.5, None), (None, None)):
        plot_projs_topomap(projs[:-1], info, vlim=vlim, colorbar=True)
    plt.close('all')
Ejemplo n.º 9
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.read_evoked(evoked_fname, 'Left Auditory',
                                  baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg')
        plot_evoked_topomap(evoked, times, ch_type='grad')
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        with warnings.catch_warnings(record=True):  # delaunay triangulation warning
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
Ejemplo n.º 10
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], **fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    pytest.raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
Ejemplo n.º 11
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    pytest.raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
Ejemplo n.º 12
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    import matplotlib.pyplot as plt
    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], **fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    assert_raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
Ejemplo n.º 13
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    import matplotlib.pyplot as plt
    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    assert_raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
Ejemplo n.º 14
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle

    # evoked
    warnings.simplefilter("always")
    res = 16
    evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
    # Test animation
    _, anim = evoked.animate_topomap(ch_type="grad", times=[0, 0.1], butterfly=False)
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close("all")

    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, plots EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type="mag")
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos="foo")
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo="bar"))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close("all")
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close("all")
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close("all")
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type="mag", outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type="eeg", res=res, scale=1)
    evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res)
    evoked.plot_topomap(times, ch_type="planar1", res=res)
    evoked.plot_topomap(times, ch_type="planar2", res=res)
    evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res, show_names=True, mask_params={"marker": "x"})
    plt.close("all")
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average="hahahahah")

    p = evoked.plot_topomap(
        times, ch_type="grad", res=res, show_names=lambda x: x.replace("MEG", ""), image_interp="bilinear"
    )
    subplot = [x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all("MEG" not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text)))

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text)]

    p = evoked.plot_topomap(times, ch_type="eeg", res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type="eeg", title="Custom", res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], "Custom")
    plt.close("all")

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter("always")
        evoked.plot_topomap(times, ch_type="mag", layout=None, res=res)
    assert_raises(
        RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
    )  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter("always")
        evoked.plot_topomap(0.1, "mag", proj="interactive", res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter("always")
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
    plot_projs_topomap(projs, res=res)
    plt.close("all")
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close("all")
    for ch in evoked.info["chs"]:
        if ch["coil_type"] == FIFF.FIFFV_COIL_EEG:
            ch["loc"].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info["dig"][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, "head")
    assert_true("head" in outlines.keys())
    assert_true("nose" in outlines.keys())
    assert_true("ear_left" in outlines.keys())
    assert_true("ear_right" in outlines.keys())
    assert_true("autoshrink" in outlines.keys())
    assert_true(outlines["autoshrink"])
    assert_true("clip_radius" in outlines.keys())
    assert_array_equal(outlines["clip_radius"], 0.5)

    pos, outlines = _check_outlines(pos, "skirt")
    assert_true("head" in outlines.keys())
    assert_true("nose" in outlines.keys())
    assert_true("ear_left" in outlines.keys())
    assert_true("ear_right" in outlines.keys())
    assert_true("autoshrink" in outlines.keys())
    assert_true(not outlines["autoshrink"])
    assert_true("clip_radius" in outlines.keys())
    assert_array_equal(outlines["clip_radius"], 0.625)

    pos, outlines = _check_outlines(pos, "skirt", head_pos={"scale": [1.2, 1.2]})
    assert_array_equal(outlines["clip_radius"], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type="eeg", outlines="skirt")

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type="eeg", outlines=outlines)
    plt.close("all")

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687), radius=0.46, clip_on=True, transform=plt.gca().transAxes)

    outlines["patch"] = patch
    plot_evoked_topomap(evoked, times, ch_type="eeg", outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info["dig"] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
    plt.close("all")

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close("all")

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    with warnings.catch_warnings(record=True):  # rightmost column
        evoked.plot_topomap(times="peaks", axes=axes)
    plt.close("all")
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
Ejemplo n.º 15
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname,
                              'Left Auditory',
                              baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type='mag', outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type='eeg', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
        evoked.plot_topomap(times, ch_type='planar1', res=res)
        evoked.plot_topomap(times, ch_type='planar2', res=res)
        evoked.plot_topomap(times,
                            ch_type='grad',
                            mask=mask,
                            res=res,
                            show_names=True,
                            mask_params={'marker': 'x'})

        p = evoked.plot_topomap(times,
                                ch_type='grad',
                                res=res,
                                show_names=lambda x: x.replace('MEG', ''),
                                image_interp='bilinear')
        subplot = [
            x for x in p.get_children()
            if isinstance(x, matplotlib.axes.Subplot)
        ][0]
        assert_true(
            all('MEG' not in x.get_text() for x in subplot.get_children()
                if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [
                x.get_text() for x in p.get_children()
                if isinstance(x, matplotlib.text.Text)
            ]

        p = evoked.plot_topomap(times, ch_type='eeg', res=res)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type='mag', layout='auto', res=res)
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      0.1,
                      'mag',
                      proj='interactive')  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname,
                              'Left Auditory',
                              baseline=(None, 0),
                              proj=False)
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs, res=res)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      times,
                      ch_type='eeg')
Ejemplo n.º 16
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap(info)
    plot_projs_topomap(projs[:1], info, axes=ax, **fast_test)  # test axes
    plt.close('all')
    triux_info = read_info(triux_fname)
    plot_projs_topomap(triux_info['projs'][-1:], triux_info, **fast_test)
    plt.close('all')
    plot_projs_topomap(triux_info['projs'][:1], triux_info, **fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    eeg_avg.plot_topomap(info, **fast_test)
    plt.close('all')
    # test vlims
    for vlim in ('joint', (-1, 1), (None, 0.5), (0.5, None), (None, None)):
        plot_projs_topomap(projs[:-1], info, vlim=vlim, colorbar=True)
    plt.close('all')

    eeg_proj = make_eeg_average_ref_proj(info)
    info_meg = pick_info(info, pick_types(info, meg=True, eeg=False))
    with pytest.raises(ValueError, match='No channel names in info match p'):
        plot_projs_topomap([eeg_proj], info_meg)
Ejemplo n.º 17
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(None, ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    subplot = [x for x in p.get_children() if
               isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all('MEG' not in x.get_text()
                    for x in subplot.get_children()
                    if isinstance(x, matplotlib.text.Text)))

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if
                isinstance(x, matplotlib.text.Text)]

    p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            if ch['eeg_loc'] is not None:
                ch['eeg_loc'].fill(0)
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos
    pos, outlines = _check_outlines(pos, 'head')
    # test 1: pass custom outlines without patch

    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)

    # test 2: pass custom outlines with patch callable
    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines='head')
    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  times, ch_type='eeg')
    plt.close('all')
Ejemplo n.º 18
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, 'Left Auditory',
                              baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type='mag', outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type='eeg', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
        evoked.plot_topomap(times, ch_type='planar1', res=res)
        evoked.plot_topomap(times, ch_type='planar2', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                            show_names=True, mask_params={'marker': 'x'})
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                      res=res, average=-1000)
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                      res=res, average='hahahahah')

        p = evoked.plot_topomap(times, ch_type='grad', res=res,
                                show_names=lambda x: x.replace('MEG', ''),
                                image_interp='bilinear')
        subplot = [x for x in p.get_children() if
                   isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(all('MEG' not in x.get_text()
                        for x in subplot.get_children()
                        if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if
                    isinstance(x, matplotlib.text.Text)]

        p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, 'Left Auditory',
                              baseline=(None, 0), proj=False)
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs, res=res)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)

        # Remove extra digitization point, so EEG digitization points
        # correspond with the EEG electrodes
        del evoked.info['dig'][85]
        plot_evoked_topomap(evoked, times, ch_type='eeg')

        # Remove digitization points. Now topomap should fail
        evoked.info['dig'] = None
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
Ejemplo n.º 19
0
def gen_html_report(p, subjects, structurals, run_indices=None):
    """Generates HTML reports"""
    import matplotlib.pyplot as plt
    from ._mnefun import (_load_trans_to, plot_good_coils, _head_pos_annot,
                          _get_bem_src_trans, safe_inserter, _prebad,
                          _load_meg_bads, mlab_offscreen, _fix_raw_eog_cals,
                          _handle_dict, _get_t_window, plot_chpi_snr_raw)
    if run_indices is None:
        run_indices = [None] * len(subjects)
    style = {'axes.spines.right': 'off', 'axes.spines.top': 'off',
             'axes.grid': True}
    time_kwargs = dict()
    if 'time_unit' in mne.fixes._get_args(mne.viz.plot_evoked):
        time_kwargs['time_unit'] = 's'
    for si, subj in enumerate(subjects):
        struc = structurals[si]
        report = Report(verbose=False)
        print('  Processing subject %s/%s (%s)'
              % (si + 1, len(subjects), subj))

        # raw
        fnames = get_raw_fnames(p, subj, 'raw', erm=False, add_splits=False,
                                run_indices=run_indices[si])
        for fname in fnames:
            if not op.isfile(fname):
                raise RuntimeError('Cannot create reports until raw data '
                                   'exist, missing:\n%s' % fname)
        raw = [read_raw_fif(fname, allow_maxshield='yes')
               for fname in fnames]
        _fix_raw_eog_cals(raw)
        prebad_file = _prebad(p, subj)
        for r in raw:
            _load_meg_bads(r, prebad_file, disp=False)
        raw = mne.concatenate_raws(raw)

        # sss
        sss_fnames = get_raw_fnames(p, subj, 'sss', False, False,
                                    run_indices[si])
        has_sss = all(op.isfile(fname) for fname in sss_fnames)
        sss_info = mne.io.read_raw_fif(sss_fnames[0]) if has_sss else None
        bad_file = get_bad_fname(p, subj)
        if bad_file is not None:
            sss_info.load_bad_channels(bad_file)
        sss_info = sss_info.info

        # pca
        pca_fnames = get_raw_fnames(p, subj, 'pca', False, False,
                                    run_indices[si])
        has_pca = all(op.isfile(fname) for fname in pca_fnames)

        # whitening and source localization
        inv_dir = op.join(p.work_dir, subj, p.inverse_dir)

        has_fwd = op.isfile(op.join(p.work_dir, subj, p.forward_dir,
                                    subj + p.inv_tag + '-fwd.fif'))

        with plt.style.context(style):
            ljust = 25
            #
            # Head coils
            #
            section = 'Good HPI count'
            if p.report_params.get('good_hpi_count', True) and p.movecomp:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = list()
                captions = list()
                for fname in fnames:
                    _, _, fit_data = _head_pos_annot(p, fname, prefix='      ')
                    assert fit_data is not None
                    fig = plot_good_coils(fit_data, show=False)
                    fig.set_size_inches(10, 2)
                    fig.tight_layout()
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # cHPI SNR
            #
            section = 'cHPI SNR'
            if p.report_params.get('chpi_snr', True) and p.movecomp:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = list()
                captions = list()
                for fname in fnames:
                    raw = mne.io.read_raw_fif(fname, allow_maxshield='yes')
                    t_window = _get_t_window(p, raw)
                    fig = plot_chpi_snr_raw(raw, t_window, show=False,
                                            verbose=False)
                    fig.set_size_inches(10, 5)
                    fig.subplots_adjust(0.1, 0.1, 0.8, 0.95,
                                        wspace=0, hspace=0.5)
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                report.add_figs_to_section(figs, captions, section,
                                           image_format='png')  # svd too slow
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Head movement
            #
            section = 'Head movement'
            if p.report_params.get('head_movement', True) and p.movecomp:
                print(('    %s ... ' % section).ljust(ljust), end='')
                t0 = time.time()
                trans_to = _load_trans_to(p, subj, run_indices[si], raw)
                figs = list()
                captions = list()
                for fname in fnames:
                    pos, _, _ = _head_pos_annot(p, fname, prefix='      ')
                    fig = plot_head_positions(pos=pos, destination=trans_to,
                                              info=raw.info, show=False)
                    for ax in fig.axes[::2]:
                        """
                        # tighten to the sensor limits
                        assert ax.lines[0].get_color() == (0., 0., 0., 1.)
                        mn, mx = np.inf, -np.inf
                        for line in ax.lines:
                            ydata = line.get_ydata()
                            if np.isfinite(ydata).any():
                                mn = min(np.nanmin(ydata), mn)
                                mx = max(np.nanmax(line.get_ydata()), mx)
                        """
                        # always show at least 10cm span, and use tight limits
                        # if greater than that
                        coord = ax.lines[0].get_ydata()
                        for line in ax.lines:
                            if line.get_color() == 'r':
                                extra = line.get_ydata()[0]
                        mn, mx = coord.min(), coord.max()
                        md = (mn + mx) / 2.
                        mn = min([mn, md - 50., extra])
                        mx = max([mx, md + 50., extra])
                        assert (mn <= coord).all()
                        assert (mx >= coord).all()
                        ax.set_ylim(mn, mx)
                    fig.set_size_inches(10, 6)
                    fig.tight_layout()
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                del trans_to
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Raw segments
            #
            if op.isfile(pca_fnames[0]):
                raw_pca = mne.concatenate_raws(
                    [mne.io.read_raw_fif(fname) for fname in pca_fnames])
            section = 'Raw segments'
            if p.report_params.get('raw_segments', True) and has_pca:
                times = np.linspace(raw.times[0], raw.times[-1], 12)[1:-1]
                raw_plot = list()
                for t in times:
                    this_raw = raw_pca.copy().crop(t - 0.5, t + 0.5)
                    this_raw.load_data()
                    this_raw._data[:] -= np.mean(this_raw._data, axis=-1,
                                                 keepdims=True)
                    raw_plot.append(this_raw)
                raw_plot = mne.concatenate_raws(raw_plot)
                for key in ('BAD boundary', 'EDGE boundary'):
                    raw_plot.annotations.delete(
                        np.where(raw_plot.annotations.description == key)[0])
                new_events = np.linspace(
                    0, int(round(10 * raw.info['sfreq'])) - 1, 11).astype(int)
                new_events += raw_plot.first_samp
                new_events = np.array([new_events,
                                       np.zeros_like(new_events),
                                       np.ones_like(new_events)]).T
                fig = raw_plot.plot(group_by='selection', butterfly=True,
                                    events=new_events)
                fig.axes[0].lines[-1].set_zorder(10)  # events
                fig.axes[0].set(xticks=np.arange(0, len(times)) + 0.5)
                xticklabels = ['%0.1f' % t for t in times]
                fig.axes[0].set(xticklabels=xticklabels)
                fig.axes[0].set(xlabel='Center of 1-second segments')
                fig.axes[0].grid(False)
                for _ in range(len(fig.axes) - 1):
                    fig.delaxes(fig.axes[-1])
                fig.set(figheight=(fig.axes[0].get_yticks() != 0).sum(),
                        figwidth=12)
                fig.subplots_adjust(0.0, 0.0, 1, 1, 0, 0)
                report.add_figs_to_section(fig, 'Processed', section,
                                           image_format='png')  # svg too slow

            #
            # PSD
            #
            section = 'PSD'
            if p.report_params.get('psd', True) and has_pca:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                if p.lp_trans == 'auto':
                    lp_trans = 0.25 * p.lp_cut
                else:
                    lp_trans = p.lp_trans
                n_fft = 8192
                fmax = raw.info['lowpass']
                figs = [raw.plot_psd(fmax=fmax, n_fft=n_fft, show=False)]
                captions = ['%s: Raw' % section]
                fmax = p.lp_cut + 2 * lp_trans
                figs.append(raw.plot_psd(fmax=fmax, n_fft=n_fft, show=False))
                captions.append('%s: Raw (zoomed)' % section)
                if op.isfile(pca_fnames[0]):
                    figs.append(raw_pca.plot_psd(fmax=fmax, n_fft=n_fft,
                                                 show=False))
                    captions.append('%s: Processed' % section)
                # shared y limits
                n = len(figs[0].axes) // 2
                for ai, axes in enumerate(list(zip(
                        *[f.axes for f in figs]))[:n]):
                    ylims = np.array([ax.get_ylim() for ax in axes])
                    ylims = [np.min(ylims[:, 0]), np.max(ylims[:, 1])]
                    for ax in axes:
                        ax.set_ylim(ylims)
                        ax.set(title='')
                for fig in figs:
                    fig.set_size_inches(8, 8)
                    with warnings.catch_warnings(record=True):
                        fig.tight_layout()
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # SSP
            #
            section = 'SSP topomaps'

            proj_nums = _handle_dict(p.proj_nums, subj)
            if p.report_params.get('ssp_topomaps', True) and has_pca and \
                    np.sum(proj_nums) > 0:
                assert sss_info is not None
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = []
                comments = []
                proj_files = get_proj_fnames(p, subj)
                if p.proj_extra is not None:
                    comments.append('Custom')
                    projs = read_proj(op.join(p.work_dir, subj, p.pca_dir,
                                              p.proj_extra))
                    figs.append(plot_projs_topomap(projs, info=sss_info,
                                                   show=False))
                if any(proj_nums[0]):  # ECG
                    if 'preproc_ecg-proj.fif' in proj_files:
                        comments.append('ECG')
                        figs.append(_proj_fig(op.join(
                            p.work_dir, subj, p.pca_dir,
                            'preproc_ecg-proj.fif'), sss_info,
                            proj_nums[0], p.proj_meg, 'ECG'))
                if any(proj_nums[1]):  # EOG
                    if 'preproc_blink-proj.fif' in proj_files:
                        comments.append('Blink')
                        figs.append(_proj_fig(op.join(
                            p.work_dir, subj, p.pca_dir,
                            'preproc_blink-proj.fif'), sss_info,
                            proj_nums[1], p.proj_meg, 'EOG'))
                if any(proj_nums[2]):  # ERM
                    if 'preproc_cont-proj.fif' in proj_files:
                        comments.append('Continuous')
                        figs.append(_proj_fig(op.join(
                            p.work_dir, subj, p.pca_dir,
                            'preproc_cont-proj.fif'), sss_info,
                            proj_nums[2], p.proj_meg, 'ERM'))
                captions = [section] + [None] * (len(comments) - 1)
                report.add_figs_to_section(
                     figs, captions, section, image_format='svg',
                     comments=comments)
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Source alignment
            #
            section = 'Source alignment'
            source_alignment = p.report_params.get('source_alignment', True)
            if source_alignment is True or isinstance(source_alignment, dict) \
                    and has_sss and has_fwd:
                assert sss_info is not None
                kwargs = source_alignment
                if isinstance(source_alignment, dict):
                    kwargs = dict(**source_alignment)
                else:
                    assert source_alignment is True
                    kwargs = dict()
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                captions = [section]
                try:
                    from mayavi import mlab
                except ImportError:
                    warnings.warn('Cannot plot alignment in Report, mayavi '
                                  'could not be imported')
                else:
                    subjects_dir = mne.utils.get_subjects_dir(
                        p.subjects_dir, raise_error=True)
                    bem, src, trans, _ = _get_bem_src_trans(
                        p, sss_info, subj, struc)
                    if len(mne.pick_types(sss_info)):
                        coord_frame = 'meg'
                    else:
                        coord_frame = 'head'
                    with mlab_offscreen():
                        fig = mlab.figure(bgcolor=(0., 0., 0.),
                                          size=(1000, 1000))
                        for key, val in (
                                ('info', sss_info),
                                ('subjects_dir', subjects_dir), ('bem', bem),
                                ('dig', True), ('coord_frame', coord_frame),
                                ('show_axes', True), ('fig', fig),
                                ('trans', trans), ('src', src)):
                            kwargs[key] = kwargs.get(key, val)
                        try_surfs = ['head-dense', 'head', 'inner_skull']
                        for surf in try_surfs:
                            try:
                                mne.viz.plot_alignment(surfaces=surf, **kwargs)
                            except Exception:
                                pass
                            else:
                                break
                        else:
                            raise RuntimeError('Could not plot any surface '
                                               'for alignment:\n%s'
                                               % (try_surfs,))
                        fig.scene.parallel_projection = True
                        view = list()
                        for ai, angle in enumerate([180, 90, 0]):
                            mlab.view(angle, 90, focalpoint=(0., 0., 0.),
                                      distance=0.6, figure=fig)
                            view.append(mlab.screenshot(figure=fig))
                        mlab.close(fig)
                    view = trim_bg(np.concatenate(view, axis=1), 0)
                    report.add_figs_to_section(view, captions, section)
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)
            #
            # SNR
            #
            section = 'SNR'
            if p.report_params.get('snr', None) is not None:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                snrs = p.report_params['snr']
                if not isinstance(snrs, (list, tuple)):
                    snrs = [snrs]
                for snr in snrs:
                    assert isinstance(snr, dict)
                    analysis = snr['analysis']
                    name = snr['name']
                    times = snr.get('times', [0.1])
                    inv_dir = op.join(p.work_dir, subj, p.inverse_dir)
                    fname_inv = op.join(inv_dir,
                                        safe_inserter(snr['inv'], subj))
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(fname_inv):
                        print('    Missing inv: %s'
                              % op.basename(fname_inv), end='')
                    elif not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        inv = mne.minimum_norm.read_inverse_operator(fname_inv)
                        this_evoked = mne.read_evokeds(fname_evoked, name)
                        title = ('%s<br>%s["%s"] (N=%d)'
                                 % (section, analysis, name, this_evoked.nave))
                        figs = plot_snr_estimate(this_evoked, inv,
                                                 verbose=False)
                        figs.axes[0].set_ylim(auto=True)
                        captions = ('%s<br>%s["%s"] (N=%d)'
                                    % (section, analysis, name,
                                       this_evoked.nave))
                        report.add_figs_to_section(
                            figs, captions, section=section,
                            image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            #
            # BEM
            #
            section = 'BEM'
            if p.report_params.get('bem', True) and has_fwd:
                caption = '%s<br>%s' % (section, struc)
                bem, src, trans, _ = _get_bem_src_trans(
                    p, raw.info, subj, struc)
                if not bem['is_sphere']:
                    subjects_dir = mne.utils.get_subjects_dir(
                        p.subjects_dir, raise_error=True)
                    mri_fname = op.join(subjects_dir, struc, 'mri', 'T1.mgz')
                    if not op.isfile(mri_fname):
                        warnings.warn(
                            'Could not find MRI:\n%s\nIf using surrogate '
                            'subjects, use '
                            'params.report_params["bem"] = False to avoid '
                            'this warning', stacklevel=2)
                    else:
                        t0 = time.time()
                        print(('    %s ... ' % section).ljust(ljust), end='')
                        report.add_bem_to_section(struc, caption, section,
                                                  decim=10, n_jobs=1,
                                                  subjects_dir=subjects_dir)
                        print('%5.1f sec' % ((time.time() - t0),))
                else:
                    print('    %s skipped (sphere)' % section)
            else:
                print('    %s skipped' % section)

            #
            # Whitening
            #
            section = 'Whitening'
            if p.report_params.get('whitening', False):
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')

                whitenings = p.report_params['whitening']
                if not isinstance(whitenings, (list, tuple)):
                    whitenings = [whitenings]
                for whitening in whitenings:
                    assert isinstance(whitening, dict)
                    analysis = whitening['analysis']
                    name = whitening['name']
                    cov_name = op.join(p.work_dir, subj, p.cov_dir,
                                       safe_inserter(whitening['cov'], subj))
                    # Load the inverse
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(cov_name):
                        print('    Missing cov: %s'
                              % op.basename(cov_name), end='')
                    elif not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        noise_cov = mne.read_cov(cov_name)
                        evo = mne.read_evokeds(fname_evoked, name)
                        captions = ('%s<br>%s["%s"] (N=%d)'
                                    % (section, analysis, name, evo.nave))
                        fig = evo.plot_white(noise_cov, **time_kwargs)
                        report.add_figs_to_section(
                            fig, captions, section=section, image_format='png')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Sensor space plots
            #
            section = 'Responses'
            if p.report_params.get('sensor', False):
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                sensors = p.report_params['sensor']
                if not isinstance(sensors, (list, tuple)):
                    sensors = [sensors]
                for sensor in sensors:
                    assert isinstance(sensor, dict)
                    analysis = sensor['analysis']
                    name = sensor['name']
                    times = sensor.get('times', [0.1, 0.2])
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        this_evoked = mne.read_evokeds(fname_evoked, name)
                        figs = this_evoked.plot_joint(
                            times, show=False, ts_args=dict(**time_kwargs),
                            topomap_args=dict(outlines='head', **time_kwargs))
                        if not isinstance(figs, (list, tuple)):
                            figs = [figs]
                        captions = ('%s<br>%s["%s"] (N=%d)'
                                    % (section, analysis, name,
                                       this_evoked.nave))
                        captions = [captions] + [None] * (len(figs) - 1)
                        report.add_figs_to_section(
                            figs, captions, section=section,
                            image_format='png')
                print('%5.1f sec' % ((time.time() - t0),))

            #
            # Source estimation
            #
            section = 'Source estimation'
            if p.report_params.get('source', False):
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                sources = p.report_params['source']
                if not isinstance(sources, (list, tuple)):
                    sources = [sources]
                for source in sources:
                    assert isinstance(source, dict)
                    analysis = source['analysis']
                    name = source['name']
                    times = source.get('times', [0.1, 0.2])
                    # Load the inverse
                    inv_dir = op.join(p.work_dir, subj, p.inverse_dir)
                    fname_inv = op.join(inv_dir,
                                        safe_inserter(source['inv'], subj))
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(fname_inv):
                        print('    Missing inv: %s'
                              % op.basename(fname_inv), end='')
                    elif not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        inv = mne.minimum_norm.read_inverse_operator(fname_inv)
                        this_evoked = mne.read_evokeds(fname_evoked, name)
                        title = ('%s<br>%s["%s"] (N=%d)'
                                 % (section, analysis, name, this_evoked.nave))
                        stc = mne.minimum_norm.apply_inverse(
                            this_evoked, inv,
                            lambda2=source.get('lambda2', 1. / 9.),
                            method=source.get('method', 'dSPM'))
                        stc = abs(stc)
                        # get clim using the reject_tmin <->reject_tmax
                        stc_crop = stc.copy().crop(
                            p.reject_tmin, p.reject_tmax)
                        clim = source.get('clim', dict(kind='percent',
                                                       lims=[82, 90, 98]))
                        out = mne.viz._3d._limits_to_control_points(
                             clim, stc_crop.data, 'viridis',
                             transparent=True)  # dummy cmap
                        if isinstance(out[0], (list, tuple, np.ndarray)):
                            clim = out[0]  # old MNE
                        else:
                            clim = out[1]  # new MNE (0.17+)
                        clim = dict(kind='value', lims=clim)
                        if not isinstance(stc, mne.SourceEstimate):
                            print('Only surface source estimates currently '
                                  'supported')
                        else:
                            subjects_dir = mne.utils.get_subjects_dir(
                                p.subjects_dir, raise_error=True)
                            with mlab_offscreen():
                                brain = stc.plot(
                                    hemi=source.get('hemi', 'split'),
                                    views=source.get('views', ['lat', 'med']),
                                    size=source.get('size', (800, 600)),
                                    colormap=source.get('colormap', 'viridis'),
                                    transparent=source.get('transparent',
                                                           True),
                                    foreground='k', background='w',
                                    clim=clim, subjects_dir=subjects_dir,
                                    )
                                imgs = list()
                                for t in times:
                                    brain.set_time(t)
                                    imgs.append(
                                        trim_bg(brain.screenshot(), 255))
                                brain.close()
                            captions = ['%2.3f sec' % t for t in times]
                            report.add_slider_to_section(
                                imgs, captions=captions, section=section,
                                title=title, image_format='png')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

        report_fname = get_report_fnames(p, subj)[0]
        report.save(report_fname, open_browser=False, overwrite=True)
Ejemplo n.º 20
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = io.read_evokeds(evoked_fname,
                                 'Left Auditory',
                                 baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg')
        plot_evoked_topomap(evoked, times, ch_type='grad')
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True)

        p = plot_evoked_topomap(evoked,
                                times,
                                ch_type='grad',
                                show_names=lambda x: x.replace('MEG', ''))
        subplot = [
            x for x in p.get_children()
            if isinstance(x, matplotlib.axes.Subplot)
        ][0]
        assert_true(
            all('MEG' not in x.get_text() for x in subplot.get_children()
                if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [
                x.get_text() for x in p.get_children()
                if isinstance(x, matplotlib.text.Text)
            ]

        p = plot_evoked_topomap(evoked, times, ch_type='eeg')
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom')
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      0.1,
                      'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      times,
                      ch_type='eeg')
Ejemplo n.º 21
0
"""
=================================
Plot SSP projections topographies
=================================

This example shows how to display topographies of SSP projection vectors.
The projections used are the ones correcting for ECG artifacts.
"""
# Author: Alexandre Gramfort <*****@*****.**>
#         Denis A. Engemann <*****@*****.**>

# License: BSD (3-clause)

print(__doc__)

from mne import read_proj, find_layout, read_evokeds
from mne.datasets import sample
from mne import viz
data_path = sample.data_path()

ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg_proj.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

evoked = read_evokeds(ave_fname, condition='Left Auditory')
projs = read_proj(ecg_fname)

layouts = [find_layout(evoked.info, k) for k in 'meg', 'eeg']

viz.plot_projs_topomap(projs, layout=layouts)
Ejemplo n.º 22
0
This example shows how to display topographies of SSP projection vectors.
The projections used are the ones correcting for ECG artifacts.
"""
# Author: Alexandre Gramfort <*****@*****.**>
#         Denis A. Engemann <*****@*****.**>

# License: BSD (3-clause)

print(__doc__)

import matplotlib.pyplot as plt
from mne import read_proj, find_layout
from mne.io import read_evokeds
from mne.datasets import sample
from mne import viz

data_path = sample.data_path()

ecg_fname = data_path + "/MEG/sample/sample_audvis_ecg_proj.fif"
ave_fname = data_path + "/MEG/sample/sample_audvis-ave.fif"

evoked = read_evokeds(ave_fname, condition="Left Auditory")
projs = read_proj(ecg_fname)

layouts = [find_layout(evoked.info, k) for k in "meg", "eeg"]

plt.figure(figsize=(12, 6))
viz.plot_projs_topomap(projs, layout=layouts)
viz.tight_layout(w_pad=0.5)
Ejemplo n.º 23
0
                    '%s_rest_01_raw_sss.fif' % subject)
n_jobs = 12
proj_nums = [[1, 2],  # ECG [grad, mag]
             [2, 2]]  # EOG

# Denoise & clean
if not op.isfile(sss_fname):
    raw_sss, head_pos = process_raw(raw_fname)
else:
    raw_sss = read_raw_fif(sss_fname, preload=True)

raw_sss_pca, pca = do_pca(raw_sss, proj_nums)
ecg_projs, eog_projs, ecg_events, eog_events = pca
print(ecg_projs[-2:])
print(eog_projs[-2:])
plot_projs_topomap(ecg_projs[-2:])
plot_projs_topomap(eog_projs[-2:])

# Filter
raw_filt = raw_sss_pca.copy().filter(h_freq=4., l_freq=None,
                                     filter_length='30s', n_jobs=n_jobs,
                                     fir_design='firwin2', phase='zero-double')

# Pick the channels of interest
raw_filt.pick_types(meg='grad')

# Re-normalize projectors after subselection
raw_filt.info.normalize_proj()

# regularized data covariance
data_cov = mne.compute_raw_covariance(raw_filt, n_jobs=n_jobs)
Ejemplo n.º 24
0
def _proj_fig(fname, info, proj_nums, proj_meg, kind):
    import matplotlib.pyplot as plt
    proj_nums = np.array(proj_nums, int)
    assert proj_nums.shape == (3,)
    projs = read_proj(fname)
    epochs = fname.replace('-proj.fif', '-epo.fif')
    n_col = proj_nums.max()
    rs_topo = 3
    if op.isfile(epochs):
        epochs = mne.read_epochs(epochs)
        evoked = epochs.average()
        rs_trace = 2
    else:
        rs_trace = 0
    n_row = proj_nums.astype(bool).sum() * (rs_topo + rs_trace)
    shape = (n_row, n_col)
    fig = plt.figure(figsize=(n_col * 2, n_row * 0.75))
    used = np.zeros(len(projs), int)
    ri = 0
    for count, ch_type in zip(proj_nums, ('grad', 'mag', 'eeg')):
        if count == 0:
            continue
        if ch_type == 'eeg':
            meg, eeg = False, True
        else:
            meg, eeg = ch_type, False
        ch_names = [info['ch_names'][pick]
                    for pick in mne.pick_types(info, meg=meg, eeg=eeg)]
        idx = np.where([np.in1d(ch_names, proj['data']['col_names']).all()
                        for proj in projs])[0]
        if len(idx) != count:
            raise RuntimeError('Expected %d %s projector%s for channel type '
                               '%s based on proj_nums but got %d in %s'
                               % (count, kind, _pl(count), ch_type, len(idx),
                                  fname))
        if proj_meg == 'separate':
            assert not used[idx].any()
        else:
            assert (used[idx] <= 1).all()
        used[idx] += 1
        these_projs = [deepcopy(projs[ii]) for ii in idx]
        for proj in these_projs:
            sub_idx = [proj['data']['col_names'].index(name)
                       for name in ch_names]
            proj['data']['data'] = proj['data']['data'][:, sub_idx]
            proj['data']['col_names'] = ch_names
        topo_axes = [plt.subplot2grid(
            shape, (ri * (rs_topo + rs_trace), ci),
            rowspan=rs_topo) for ci in range(count)]
        # topomaps
        with warnings.catch_warnings(record=True):
            plot_projs_topomap(these_projs, info=info, show=False,
                               axes=topo_axes)
        plt.setp(topo_axes, title='', xlabel='')
        topo_axes[0].set(ylabel=ch_type)
        if rs_trace:
            trace_axes = [plt.subplot2grid(
                shape, (ri * (rs_topo + rs_trace) + rs_topo, ci),
                rowspan=rs_trace) for ci in range(count)]
            for proj, ax in zip(these_projs, trace_axes):
                this_evoked = evoked.copy().pick_channels(ch_names)
                p = proj['data']['data']
                assert p.shape == (1, len(this_evoked.data))
                with warnings.catch_warnings(record=True):  # tight_layout
                    this_evoked.plot(
                        picks=np.arange(len(this_evoked.data)), axes=[ax])
                ax.texts = []
                trace = np.dot(p, this_evoked.data)[0]
                trace *= 0.8 * (np.abs(ax.get_ylim()).max() /
                                np.abs(trace).max())
                ax.plot(this_evoked.times, trace, color='#9467bd')
                ax.set(title='', ylabel='', xlabel='')
        ri += 1
    assert used.all() and (used <= 2).all()
    fig.subplots_adjust(0.1, 0.1, 0.95, 1, 0.3, 0.3)
    return fig
Ejemplo n.º 25
0
def test_plot_topomap():
    """Test topomap plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 8
    fast_test = {"res": res, "contours": 0, "sensors": False}
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))

    # Test animation
    _, anim = evoked.animate_topomap(ch_type='grad', times=[0, 0.1],
                                     butterfly=False)
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close('all')

    ev_bad = evoked.copy().pick_types(meg=False, eeg=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    plt_topomap = partial(ev_bad.plot_topomap, **fast_test)
    plt_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, plots EEG
    assert_raises(ValueError, plt_topomap, ch_type='mag')
    assert_raises(TypeError, plt_topomap, head_pos='foo')
    assert_raises(KeyError, plt_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, plt_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, plt_topomap, times=[-100])  # bad time
    assert_raises(ValueError, plt_topomap, times=[[0]])  # bad time

    evoked.plot_topomap([0.1], ch_type='eeg', scale=1, res=res,
                        contours=[-100, 0, 100])
    plt_topomap = partial(evoked.plot_topomap, **fast_test)
    plt_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    plt_topomap(axes=axes, colorbar=False)
    plt.close('all')
    plt_topomap(times=[-0.1, 0.2])
    plt.close('all')
    evoked_grad = evoked.copy().crop(0, 0).pick_types(meg='grad')
    mask = np.zeros((204, 1), bool)
    mask[[0, 3, 5, 6]] = True
    names = []

    def proc_names(x):
        names.append(x)
        return x[4:]

    evoked_grad.plot_topomap(ch_type='grad', times=[0], mask=mask,
                             show_names=proc_names, **fast_test)
    assert_equal(sorted(names),
                 ['MEG 011x', 'MEG 012x', 'MEG 013x', 'MEG 014x'])
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    plt_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    plt_topomap(times, ch_type='grad', mask=mask)
    plt_topomap(times, ch_type='planar1')
    plt_topomap(times, ch_type='planar2')
    plt_topomap(times, ch_type='grad', mask=mask, show_names=True,
                mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, plt_topomap, times, ch_type='eeg', average=-1e3)
    assert_raises(ValueError, plt_topomap, times, ch_type='eeg', average='x')

    p = plt_topomap(times, ch_type='grad', image_interp='bilinear',
                    show_names=lambda x: x.replace('MEG', ''))
    subplot = [x for x in p.get_children() if
               isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all('MEG' not in x.get_text()
                    for x in subplot.get_children()
                    if isinstance(x, matplotlib.text.Text)))

    # Plot array
    for ch_type in ('mag', 'grad'):
        evoked_ = evoked.copy().pick_types(eeg=False, meg=ch_type)
        plot_topomap(evoked_.data[:, 0], evoked_.info, **fast_test)
    # fail with multiple channel types
    assert_raises(ValueError, plot_topomap, evoked.data[0, :], evoked.info)

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if
                isinstance(x, matplotlib.text.Text)]

    p = plt_topomap(times, ch_type='eeg', average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = plt_topomap(times, ch_type='eeg', title='Custom')
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        plt_topomap(times, ch_type='mag', layout=None)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        fig1 = evoked.plot_topomap(.1, 'mag', proj='interactive', **fast_test)
    data_max = np.max(fig1.axes[0].images[0]._A)
    fig2 = plt.gcf()
    _fake_click(fig2, fig2.axes[0], (0.075, 0.775))  # toggle projector
    # make sure projector gets toggled
    assert_true(np.max(fig1.axes[0].images[0]._A) != data_max)

    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res, colorbar=True)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:])  # grads
    plt.close('all')
    # XXX This one fails due to grads being combined but this proj having
    # all zeros in the grad values -> matplotlib contour error
    # plot_projs_topomap(read_info(triux_fname)['projs'][:1])  # mags
    # plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos, 'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt', **fast_test)

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines, **fast_test)
    plt.close('all')

    # Test interactive cmap
    fig = plot_evoked_topomap(evoked, times=[0., 0.1], ch_type='eeg',
                              cmap=('Reds', True), title='title', **fast_test)
    fig.canvas.key_press_event('up')
    fig.canvas.key_press_event(' ')
    fig.canvas.key_press_event('down')
    cbar = fig.get_axes()[0].CB  # Fake dragging with mouse.
    ax = cbar.cbar.ax
    _fake_click(fig, ax, (0.1, 0.1))
    _fake_click(fig, ax, (0.1, 0.2), kind='motion')
    _fake_click(fig, ax, (0.1, 0.3), kind='release')

    _fake_click(fig, ax, (0.1, 0.1), button=3)
    _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion')
    _fake_click(fig, ax, (0.1, 0.3), kind='release')

    fig.canvas.scroll_event(0.5, 0.5, -0.5)  # scroll down
    fig.canvas.scroll_event(0.5, 0.5, 0.5)  # scroll up

    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)
    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines=outlines,
                        **fast_test)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  times, ch_type='eeg')
    plt.close('all')

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close('all')

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    with warnings.catch_warnings(record=True):  # rightmost column
        evoked.plot_topomap(times='peaks', axes=axes, **fast_test)
    plt.close('all')
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
Ejemplo n.º 26
0
def test_plot_topomap():
    """Test topomap plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory', baseline=(None, 0))

    # Test animation
    _, anim = evoked.animate_topomap(ch_type='grad',
                                     times=[0, 0.1],
                                     butterfly=False)
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close('all')

    ev_bad = evoked.copy().pick_types(meg=False, eeg=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, plots EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close('all')
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times,
                        ch_type='grad',
                        mask=mask,
                        res=res,
                        show_names=True,
                        mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError,
                  evoked.plot_topomap,
                  times,
                  ch_type='eeg',
                  res=res,
                  average=-1000)
    assert_raises(ValueError,
                  evoked.plot_topomap,
                  times,
                  ch_type='eeg',
                  res=res,
                  average='hahahahah')

    p = evoked.plot_topomap(times,
                            ch_type='grad',
                            res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    subplot = [
        x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)
    ][0]
    assert_true(
        all('MEG' not in x.get_text() for x in subplot.get_children()
            if isinstance(x, matplotlib.text.Text)))

    # Plot array
    for ch_type in ('mag', 'grad'):
        evoked_ = evoked.copy().pick_types(eeg=False, meg=ch_type)
        plot_topomap(evoked_.data[:, 0], evoked_.info)
    # fail with multiple channel types
    assert_raises(ValueError, plot_topomap, evoked.data[0, :], evoked.info)

    # Test title
    def get_texts(p):
        return [
            x.get_text() for x in p.get_children()
            if isinstance(x, matplotlib.text.Text)
        ]

    p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  0.1,
                  'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname,
                          'Left Auditory',
                          baseline=(None, 0),
                          proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res, colorbar=True)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos,
                                    'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt')

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines)
    plt.close('all')

    # Test interactive cmap
    fig = plot_evoked_topomap(evoked,
                              times=[0., 0.1],
                              ch_type='eeg',
                              cmap=('Reds', True),
                              title='title')
    fig.canvas.key_press_event('up')
    fig.canvas.key_press_event(' ')
    fig.canvas.key_press_event('down')
    cbar = fig.get_axes()[0].CB  # Fake dragging with mouse.
    ax = cbar.cbar.ax
    _fake_click(fig, ax, (0.1, 0.1))
    _fake_click(fig, ax, (0.1, 0.2), kind='motion')
    _fake_click(fig, ax, (0.1, 0.3), kind='release')

    _fake_click(fig, ax, (0.1, 0.1), button=3)
    _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion')
    _fake_click(fig, ax, (0.1, 0.3), kind='release')

    fig.canvas.scroll_event(0.5, 0.5, -0.5)  # scroll down
    fig.canvas.scroll_event(0.5, 0.5, 0.5)  # scroll up

    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687),
                      radius=.46,
                      clip_on=True,
                      transform=plt.gca().transAxes)

    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  times,
                  ch_type='eeg')
    plt.close('all')

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close('all')

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    with warnings.catch_warnings(record=True):  # rightmost column
        evoked.plot_topomap(times='peaks', axes=axes)
    plt.close('all')
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
Ejemplo n.º 27
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter("always", UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
        evoked.plot_topomap(0.1, "mag", layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type="mag", outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type="eeg", res=res)
        evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res)
        evoked.plot_topomap(times, ch_type="planar1", res=res)
        evoked.plot_topomap(times, ch_type="planar2", res=res)
        evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res, show_names=True, mask_params={"marker": "x"})
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average=-1000)
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average="hahahahah")

        p = evoked.plot_topomap(
            times, ch_type="grad", res=res, show_names=lambda x: x.replace("MEG", ""), image_interp="bilinear"
        )
        subplot = [x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(
            all("MEG" not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text))
        )

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text)]

        p = evoked.plot_topomap(times, ch_type="eeg", res=res, average=0.01)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type="eeg", title="Custom", res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], "Custom")

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type="mag", layout=None, res=res)
        assert_raises(
            RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
        )  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
        evoked.plot_topomap(0.1, "mag", proj="interactive", res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
        plot_projs_topomap(projs, res=res)
        plt.close("all")
        for ch in evoked.info["chs"]:
            if ch["coil_type"] == FIFF.FIFFV_COIL_EEG:
                if ch["eeg_loc"] is not None:
                    ch["eeg_loc"].fill(0)
                ch["loc"].fill(0)

        # Remove extra digitization point, so EEG digitization points
        # correspond with the EEG electrodes
        del evoked.info["dig"][85]
        plot_evoked_topomap(evoked, times, ch_type="eeg")

        # Remove digitization points. Now topomap should fail
        evoked.info["dig"] = None
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
Ejemplo n.º 28
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close('all')
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(None, ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    subplot = [x for x in p.get_children() if
               isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all('MEG' not in x.get_text()
                    for x in subplot.get_children()
                    if isinstance(x, matplotlib.text.Text)))

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if
                isinstance(x, matplotlib.text.Text)]

    p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            if ch['eeg_loc'] is not None:
                ch['eeg_loc'].fill(0)
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos, 'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt')

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines)
    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)
    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  times, ch_type='eeg')
    plt.close('all')
Ejemplo n.º 29
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close('all')
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    subplot = [x for x in p.get_children() if
               isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all('MEG' not in x.get_text()
                    for x in subplot.get_children()
                    if isinstance(x, matplotlib.text.Text)))

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if
                isinstance(x, matplotlib.text.Text)]

    p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos, 'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt')

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines)
    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)
    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  times, ch_type='eeg')
    plt.close('all')

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close('all')

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    evoked.plot_topomap(times='peaks', axes=axes)
    plt.close('all')
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])