Exemple #1
0
def test_plot_evoked():
    """Test plotting of evoked."""
    import matplotlib.pyplot as plt
    rng = np.random.RandomState(0)
    evoked = _get_epochs().average()
    fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo',
                      time_unit='s')
    # Test a click
    ax = fig.get_axes()[0]
    line = ax.lines[0]
    _fake_click(fig, ax,
                [line.get_xdata()[0], line.get_ydata()[0]], 'data')
    _fake_click(fig, ax,
                [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
    # plot with bad channels excluded & spatial_colors & zorder
    evoked.plot(exclude='bads', time_unit='s')

    # test selective updating of dict keys is working.
    evoked.plot(hline=[1], units=dict(mag='femto foo'), time_unit='s')
    evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
    evoked_delayed_ssp.plot(proj='interactive', time_unit='s')
    evoked_delayed_ssp.apply_proj()
    assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                  proj='interactive', time_unit='s')
    evoked_delayed_ssp.info['projs'] = []
    assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                  proj='interactive', time_unit='s')
    assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                  proj='interactive', axes='foo', time_unit='s')
    plt.close('all')

    # test GFP only
    evoked.plot(gfp='only', time_unit='s')
    assert_raises(ValueError, evoked.plot, gfp='foo', time_unit='s')

    evoked.plot_image(proj=True, time_unit='ms')
    # test mask
    evoked.plot_image(picks=[1, 2], mask=evoked.data > 0, time_unit='s')
    evoked.plot_image(picks=[1, 2], mask_cmap=None, colorbar=False,
                      mask=np.ones(evoked.data.shape).astype(bool),
                      time_unit='s')

    with warnings.catch_warnings(record=True) as w:
        evoked.plot_image(picks=[1, 2], mask=None, mask_style="both",
                          time_unit='s')
    assert len(w) == 2
    assert_raises(ValueError, evoked.plot_image, mask=evoked.data[1:, 1:] > 0,
                  time_unit='s')

    # plot with bad channels excluded
    evoked.plot_image(exclude='bads', cmap='interactive', time_unit='s')
    evoked.plot_image(exclude=evoked.info['bads'], time_unit='s')  # same thing
    plt.close('all')

    assert_raises(ValueError, evoked.plot_image, picks=[0, 0],
                  time_unit='s')  # duplicates

    evoked.plot_topo()  # should auto-find layout
    _line_plot_onselect(0, 200, ['mag', 'grad'], evoked.info, evoked.data,
                        evoked.times)
    plt.close('all')

    cov = read_cov(cov_fname)
    cov['method'] = 'empirical'
    cov['projs'] = []  # avoid warnings
    # test rank param.
    evoked.plot_white(cov, rank={'mag': 101, 'grad': 201}, time_unit='s')
    evoked.plot_white(cov, rank={'mag': 101}, time_unit='s')  # test rank param
    evoked.plot_white(cov, rank={'grad': 201}, time_unit='s')
    assert_raises(
        ValueError, evoked.plot_white, cov,
        rank={'mag': 101, 'grad': 201, 'meg': 306}, time_unit='s')
    assert_raises(
        ValueError, evoked.plot_white, cov, rank={'meg': 306}, time_unit='s')

    evoked.plot_white([cov, cov], time_unit='s')

    # plot_compare_evokeds: test condition contrast, CI, color assignment
    plot_compare_evokeds(evoked.copy().pick_types(meg='mag'))
    plot_compare_evokeds(
        evoked.copy().pick_types(meg='grad'), picks=[1, 2],
        show_sensors="upper right", show_legend="upper left")
    evokeds = [evoked.copy() for _ in range(10)]
    for evoked in evokeds:
        evoked.data += (rng.randn(*evoked.data.shape) *
                        np.std(evoked.data, axis=-1, keepdims=True))
    for picks in ([0], [1], [2], [0, 2], [1, 2], [0, 1, 2],):
        figs = plot_compare_evokeds([evokeds], picks=picks, ci=0.95)
        if not isinstance(figs, list):
            figs = [figs]
        for fig in figs:
            ext = fig.axes[0].collections[0].get_paths()[0].get_extents()
            xs, ylim = ext.get_points().T
            assert_allclose(xs, evoked.times[[0, -1]])
            line = fig.axes[0].lines[0]
            xs = line.get_xdata()
            assert_allclose(xs, evoked.times)
            ys = line.get_ydata()
            assert (ys < ylim[1]).all()
            assert (ys > ylim[0]).all()
        plt.close('all')

    evoked.rename_channels({'MEG 2142': "MEG 1642"})
    assert len(plot_compare_evokeds(evoked)) == 2
    colors = dict(red='r', blue='b')
    linestyles = dict(red='--', blue='-')
    red, blue = evoked.copy(), evoked.copy()
    red.data *= 1.1
    blue.data *= 0.9
    plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
    plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True)
    plot_compare_evokeds([[red, evoked], [blue, evoked]],
                         picks=3)  # list of lists
    # test picking & plotting grads
    contrast = dict()
    contrast["red/stim"] = list((evoked.copy(), red))
    contrast["blue/stim"] = list((evoked.copy(), blue))
    # test a bunch of params at once
    for evokeds_ in (evoked.copy().pick_types(meg='mag'), contrast,
                     [red, blue], [[red, evoked], [blue, evoked]]):
        plot_compare_evokeds(evokeds_, picks=0, ci=True)  # also tests CI
    plt.close('all')
    # test styling +  a bunch of other params at once
    colors, linestyles = dict(red='r', blue='b'), dict(red='--', blue='-')
    plot_compare_evokeds(contrast, colors=colors, linestyles=linestyles,
                         picks=[0, 2], vlines=[.01, -.04], invert_y=True,
                         truncate_yaxis=False, ylim=dict(mag=(-10, 10)),
                         styles={"red/stim": {"linewidth": 1}},
                         show_sensors=True)
    # various bad styles
    params = [dict(picks=3, colors=dict(fake=1)),
              dict(picks=3, styles=dict(fake=1)), dict(picks=3, gfp=True),
              dict(picks=3, show_sensors="a"),
              dict(colors=dict(red=10., blue=-2))]
    for param in params:
        assert_raises(ValueError, plot_compare_evokeds, evoked, **param)
    assert_raises(TypeError, plot_compare_evokeds, evoked, picks='str')
    assert_raises(TypeError, plot_compare_evokeds, evoked, vlines='x')
    plt.close('all')
    # `evoked` must contain Evokeds
    assert_raises(TypeError, plot_compare_evokeds, [[1, 2], [3, 4]])
    # `ci` must be float or None
    assert_raises(TypeError, plot_compare_evokeds, contrast, ci='err')
    # test all-positive ylim
    contrast["red/stim"], contrast["blue/stim"] = red, blue
    plot_compare_evokeds(contrast, picks=[0], colors=['r', 'b'],
                         ylim=dict(mag=(1, 10)), ci=_parametric_ci,
                         truncate_yaxis='max_ticks', show_sensors=False,
                         show_legend=False)

    # sequential colors
    evokeds = (evoked, blue, red)
    contrasts = {"a{}/b".format(ii): ev for ii, ev in
                 enumerate(evokeds)}
    colors = {"a" + str(ii): ii for ii, _ in enumerate(evokeds)}
    contrasts["a1/c"] = evoked.copy()
    for split in (True, False):
        for linestyles in (["-"], {"b": "-", "c": ":"}):
            plot_compare_evokeds(
                contrasts, colors=colors, picks=[0], cmap='Reds',
                split_legend=split, linestyles=linestyles,
                ci=False, show_sensors=False)
    colors = {"a" + str(ii): ii / len(evokeds)
              for ii, _ in enumerate(evokeds)}
    plot_compare_evokeds(
        contrasts, colors=colors, picks=[0], cmap='Reds',
        split_legend=split, linestyles=linestyles, ci=False,
        show_sensors=False)
    red.info["chs"][0]["loc"][:2] = 0  # test plotting channel at zero
    plot_compare_evokeds(red, picks=[0],
                         ci=lambda x: [x.std(axis=0), -x.std(axis=0)])
    plot_compare_evokeds([red, blue], picks=[0], cmap="summer", ci=None,
                         split_legend=None)
    plot_compare_evokeds([red, blue], cmap=None, split_legend=True)
    assert_raises(ValueError, plot_compare_evokeds, [red] * 20)
    assert_raises(ValueError, plot_compare_evokeds, contrasts,
                  cmap='summer')

    plt.close('all')

    # Hack to test plotting of maxfiltered data
    evoked_sss = evoked.copy()
    sss = dict(sss_info=dict(in_order=80, components=np.arange(80)))
    evoked_sss.info['proc_history'] = [dict(max_info=sss)]
    evoked_sss.plot_white(cov, rank={'meg': 64}, time_unit='s')
    assert_raises(
        ValueError, evoked_sss.plot_white, cov, rank={'grad': 201},
        time_unit='s')
    evoked_sss.plot_white(cov, time_unit='s')

    # plot with bad channels excluded, spatial_colors, zorder & pos. layout
    evoked.rename_channels({'MEG 0133': 'MEG 0000'})
    evoked.plot(exclude=evoked.info['bads'], spatial_colors=True, gfp=True,
                zorder='std', time_unit='s')
    evoked.plot(exclude=[], spatial_colors=True, zorder='unsorted',
                time_unit='s')
    assert_raises(TypeError, evoked.plot, zorder='asdf', time_unit='s')
    plt.close('all')

    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')

    evoked.pick_channels(evoked.ch_names[:4])
    with catch_logging() as log_file:
        evoked.plot(verbose=True, time_unit='s')
    assert_true('Need more than one' in log_file.getvalue())
Exemple #2
0
def test_plot_evoked():
    """Test plotting of evoked."""
    import matplotlib.pyplot as plt
    evoked = _get_epochs().average()
    with warnings.catch_warnings(record=True):
        fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo')
        # Test a click
        ax = fig.get_axes()[0]
        line = ax.lines[0]
        _fake_click(
            fig, ax,
            [line.get_xdata()[0], line.get_ydata()[0]], 'data')
        _fake_click(fig, ax, [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
        # plot with bad channels excluded & spatial_colors & zorder
        evoked.plot(exclude='bads')

        # test selective updating of dict keys is working.
        evoked.plot(hline=[1], units=dict(mag='femto foo'))
        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        evoked_delayed_ssp.plot(proj='interactive')
        evoked_delayed_ssp.apply_proj()
        assert_raises(RuntimeError,
                      evoked_delayed_ssp.plot,
                      proj='interactive')
        evoked_delayed_ssp.info['projs'] = []
        assert_raises(RuntimeError,
                      evoked_delayed_ssp.plot,
                      proj='interactive')
        assert_raises(RuntimeError,
                      evoked_delayed_ssp.plot,
                      proj='interactive',
                      axes='foo')
        plt.close('all')

        # test GFP only
        evoked.plot(gfp='only')
        assert_raises(ValueError, evoked.plot, gfp='foo')

        evoked.plot_image(proj=True)
        # plot with bad channels excluded
        evoked.plot_image(exclude='bads', cmap='interactive')
        evoked.plot_image(exclude=evoked.info['bads'])  # does the same thing
        plt.close('all')

        evoked.plot_topo()  # should auto-find layout
        _line_plot_onselect(0, 200, ['mag', 'grad'], evoked.info, evoked.data,
                            evoked.times)
        plt.close('all')

        cov = read_cov(cov_fname)
        cov['method'] = 'empirical'
        # test rank param.
        evoked.plot_white(cov, rank={'mag': 101, 'grad': 201})
        evoked.plot_white(cov, rank={'mag': 101})  # test rank param.
        evoked.plot_white(cov, rank={'grad': 201})  # test rank param.
        assert_raises(ValueError,
                      evoked.plot_white,
                      cov,
                      rank={
                          'mag': 101,
                          'grad': 201,
                          'meg': 306
                      })
        assert_raises(ValueError, evoked.plot_white, cov, rank={'meg': 306})

        evoked.plot_white([cov, cov])

        # plot_compare_evokeds: test condition contrast, CI, color assignment
        plot_compare_evokeds(evoked.copy().pick_types(meg='mag'))
        plot_compare_evokeds(evoked.copy().pick_types(meg='grad'),
                             picks=[1, 2])
        evoked.rename_channels({'MEG 2142': "MEG 1642"})
        assert len(plot_compare_evokeds(evoked)) == 2
        colors = dict(red='r', blue='b')
        linestyles = dict(red='--', blue='-')
        red, blue = evoked.copy(), evoked.copy()
        red.data *= 1.1
        blue.data *= 0.9
        plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
        plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True)
        plot_compare_evokeds([[red, evoked], [blue, evoked]],
                             picks=3)  # list of lists
        # test picking & plotting grads
        contrast = dict()
        contrast["red/stim"] = list((evoked.copy(), red))
        contrast["blue/stim"] = list((evoked.copy(), blue))
        # test a bunch of params at once
        plot_compare_evokeds(contrast,
                             colors=colors,
                             linestyles=linestyles,
                             picks=[0, 2],
                             vlines=[.01, -.04],
                             invert_y=True,
                             truncate_yaxis=False,
                             ylim=dict(mag=(-10, 10)),
                             styles={"red/stim": {
                                 "linewidth": 1
                             }},
                             show_sensors=True)
        assert_raises(ValueError, plot_compare_evokeds, contrast,
                      picks='str')  # bad picks: not int
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      colors=dict(fake=1))  # 'fake' not in conds
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      styles=dict(fake=1))  # 'fake' not in conds
        assert_raises(ValueError,
                      plot_compare_evokeds, [[1, 2], [3, 4]],
                      picks=3)  # evoked must contain Evokeds
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      styles=dict(err=1))  # bad styles dict
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      gfp=True)  # no single-channel GFP
        assert_raises(TypeError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      ci='fake')  # ci must be float or None
        assert_raises(TypeError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      show_sensors='a')  # show_sensors must be int or bool
        contrast["red/stim"] = red
        contrast["blue/stim"] = blue
        plot_compare_evokeds(contrast,
                             picks=[0],
                             colors=['r', 'b'],
                             ylim=dict(mag=(1, 10)),
                             ci=_parametric_ci,
                             truncate_yaxis='max_ticks')
        red.info["chs"][0]["loc"][:2] = 0  # test plotting channel at zero
        plot_compare_evokeds(red, picks=[0])

        # Hack to test plotting of maxfiltered data
        evoked_sss = evoked.copy()
        sss = dict(sss_info=dict(in_order=80, components=np.arange(80)))
        evoked_sss.info['proc_history'] = [dict(max_info=sss)]
        evoked_sss.plot_white(cov, rank={'meg': 64})
        assert_raises(ValueError,
                      evoked_sss.plot_white,
                      cov,
                      rank={'grad': 201})
        evoked_sss.plot_white(cov_fname)

        # plot with bad channels excluded, spatial_colors, zorder & pos. layout
        evoked.rename_channels({'MEG 0133': 'MEG 0000'})
        evoked.plot(exclude=evoked.info['bads'],
                    spatial_colors=True,
                    gfp=True,
                    zorder='std')
        evoked.plot(exclude=[], spatial_colors=True, zorder='unsorted')
        assert_raises(TypeError, evoked.plot, zorder='asdf')
        plt.close('all')
    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')

    evoked.pick_channels(evoked.ch_names[:4])
    with catch_logging() as log_file:
        evoked.plot(verbose=True)
    assert_true('Need more than one' in log_file.getvalue())
Exemple #3
0
def test_plot_compare_evokeds():
    """Test plot_compare_evokeds."""
    import matplotlib.pyplot as plt
    rng = np.random.RandomState(0)
    evoked = _get_epochs().average()
    # plot_compare_evokeds: test condition contrast, CI, color assignment
    fig = plot_compare_evokeds(evoked.copy().pick_types(meg='mag'),
                               show_sensors=True)
    assert len(fig.axes) == 2

    plot_compare_evokeds(
        evoked.copy().pick_types(meg='grad'), picks=[1, 2],
        show_sensors="upper right", show_legend="upper left")
    evokeds = [evoked.copy() for _ in range(10)]
    for evoked in evokeds:
        evoked.data += (rng.randn(*evoked.data.shape) *
                        np.std(evoked.data, axis=-1, keepdims=True))
    for picks in ([0], [1], [2], [0, 2], [1, 2], [0, 1, 2],):
        figs = plot_compare_evokeds([evokeds], picks=picks, ci=0.95)
        if not isinstance(figs, list):
            figs = [figs]
        for fig in figs:
            ext = fig.axes[0].collections[0].get_paths()[0].get_extents()
            xs, ylim = ext.get_points().T
            assert_allclose(xs, evoked.times[[0, -1]])
            line = fig.axes[0].lines[0]
            xs = line.get_xdata()
            assert_allclose(xs, evoked.times)
            ys = line.get_ydata()
            assert (ys < ylim[1]).all()
            assert (ys > ylim[0]).all()
        plt.close('all')

    evoked.rename_channels({'MEG 2142': "MEG 1642"})
    assert len(plot_compare_evokeds(evoked)) == 2
    colors = dict(red='r', blue='b')
    linestyles = dict(red='--', blue='-')
    red, blue = evoked.copy(), evoked.copy()
    red.data *= 1.1
    blue.data *= 0.9
    plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
    plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True,
                         vlines=[])  # also testing empty vlines here
    plot_compare_evokeds([[red, evoked], [blue, evoked]],
                         picks=3)  # list of lists
    # test picking & plotting grads
    contrast = dict()
    contrast["red/stim"] = list((evoked.copy(), red))
    contrast["blue/stim"] = list((evoked.copy(), blue))
    # test a bunch of params at once
    for evokeds_ in (evoked.copy().pick_types(meg='mag'), contrast,
                     [red, blue], [[red, evoked], [blue, evoked]]):
        plot_compare_evokeds(evokeds_, picks=0, ci=True)  # also tests CI
    plt.close('all')
    # test styling +  a bunch of other params at once
    colors, linestyles = dict(red='r', blue='b'), dict(red='--', blue='-')
    plot_compare_evokeds(contrast, colors=colors, linestyles=linestyles,
                         picks=[0, 2], vlines=[.01, -.04], invert_y=True,
                         truncate_yaxis=False, ylim=dict(mag=(-10, 10)),
                         styles={"red/stim": {"linewidth": 1}},
                         show_sensors=True)
    # various bad styles
    params = [dict(picks=3, colors=dict(fake=1)),
              dict(picks=3, styles=dict(fake=1)), dict(picks=3, gfp=True),
              dict(picks=3, show_sensors="a"),
              dict(colors=dict(red=10., blue=-2))]
    for param in params:
        pytest.raises(ValueError, plot_compare_evokeds, evoked, **param)
    pytest.raises(TypeError, plot_compare_evokeds, evoked, picks='str')
    pytest.raises(TypeError, plot_compare_evokeds, evoked, vlines='x')
    plt.close('all')
    # `evoked` must contain Evokeds
    pytest.raises(TypeError, plot_compare_evokeds, [[1, 2], [3, 4]])
    # `ci` must be float or None
    pytest.raises(TypeError, plot_compare_evokeds, contrast, ci='err')
    # test all-positive ylim
    contrast["red/stim"], contrast["blue/stim"] = red, blue
    plot_compare_evokeds(contrast, picks=[0], colors=['r', 'b'],
                         ylim=dict(mag=(1, 10)), ci=_parametric_ci,
                         truncate_yaxis='max_ticks', show_sensors=False,
                         show_legend=False)

    # sequential colors
    evokeds = (evoked, blue, red)
    contrasts = {"a{}/b".format(ii): ev for ii, ev in
                 enumerate(evokeds)}
    colors = {"a" + str(ii): ii for ii, _ in enumerate(evokeds)}
    contrasts["a1/c"] = evoked.copy()
    for split in (True, False):
        for linestyles in (["-"], {"b": "-", "c": ":"}):
            plot_compare_evokeds(
                contrasts, colors=colors, picks=[0], cmap='Reds',
                split_legend=split, linestyles=linestyles,
                ci=False, show_sensors=False)
    colors = {"a" + str(ii): ii / len(evokeds)
              for ii, _ in enumerate(evokeds)}
    plot_compare_evokeds(
        contrasts, colors=colors, picks=[0], cmap='Reds',
        split_legend=split, linestyles=linestyles, ci=False,
        show_sensors=False)
    red.info["chs"][0]["loc"][:2] = 0  # test plotting channel at zero
    plot_compare_evokeds(red, picks=[0],
                         ci=lambda x: [x.std(axis=0), -x.std(axis=0)])
    plot_compare_evokeds([red, blue], picks=[0], cmap="summer", ci=None,
                         split_legend=None)
    plot_compare_evokeds([red, blue], cmap=None, split_legend=True)
    pytest.raises(ValueError, plot_compare_evokeds, [red] * 20)
    pytest.raises(ValueError, plot_compare_evokeds, contrasts,
                  cmap='summer')

    plt.close('all')
Exemple #4
0
def test_plot_compare_evokeds():
    """Test plot_compare_evokeds."""
    evoked = _get_epochs().average()
    # test defaults
    figs = plot_compare_evokeds(evoked)
    assert len(figs) == 2
    # test picks, combine, and vlines (1-channel pick also shows sensor inset)
    picks = ['MEG 0113', 'mag'] + 2 * [['MEG 0113', 'MEG 0112']] + [[0, 1]]
    vlines = [[0.1, 0.2], []] + 3 * ['auto']
    combine = [None, 'mean', 'std', None, lambda x: np.min(x, axis=1)]
    title = ['MEG 0113', '(mean)', '(std. dev.)', '(GFP)', 'MEG 0112']
    for _p, _v, _c, _t in zip(picks, vlines, combine, title):
        fig = plot_compare_evokeds(evoked, picks=_p, vlines=_v, combine=_c)
        assert fig[0].axes[0].get_title().endswith(_t)
    # test passing more than one evoked
    red, blue = evoked.copy(), evoked.copy()
    red.data *= 1.5
    blue.data /= 1.5
    evoked_dict = {'aud/l': blue, 'aud/r': red, 'vis': evoked}
    huge_dict = {'cond{}'.format(i): ev for i, ev in enumerate([evoked] * 11)}
    plot_compare_evokeds(evoked_dict)                           # dict
    plot_compare_evokeds([[red, evoked], [blue, evoked]])       # list of lists
    figs = plot_compare_evokeds({'cond': [blue, red, evoked]})  # dict of list
    # test that confidence bands are plausible
    for fig in figs:
        extents = fig.axes[0].collections[0].get_paths()[0].get_extents()
        xlim, ylim = extents.get_points().T
        assert np.allclose(xlim, evoked.times[[0, -1]])
        line = fig.axes[0].lines[0]
        xvals = line.get_xdata()
        assert np.allclose(xvals, evoked.times)
        yvals = line.get_ydata()
        assert (yvals < ylim[1]).all()
        assert (yvals > ylim[0]).all()
    plt.close('all')
    # test other CI args
    for _ci in (None, False, 0.5,
                lambda x: np.stack([x.mean(axis=0) + 1, x.mean(axis=0) - 1])):
        plot_compare_evokeds({'cond': [blue, red, evoked]}, ci=_ci)
    with pytest.raises(TypeError, match='"ci" must be None, bool, float or'):
        plot_compare_evokeds(evoked, ci='foo')
    # test sensor inset, legend location, and axis inversion & truncation
    plot_compare_evokeds(evoked_dict, invert_y=True, legend='upper left',
                         show_sensors='center', truncate_xaxis=False,
                         truncate_yaxis=False)
    plot_compare_evokeds(evoked, ylim=dict(mag=(-50, 50)), truncate_yaxis=True)
    plt.close('all')
    # test styles
    plot_compare_evokeds(evoked_dict, colors=['b', 'r', 'g'],
                         linestyles=[':', '-', '--'], split_legend=True)
    style_dict = dict(aud=dict(alpha=0.3), vis=dict(linewidth=3, c='k'))
    plot_compare_evokeds(evoked_dict, styles=style_dict, colors={'aud/r': 'r'},
                         linestyles=dict(vis='dotted'), ci=False)
    plot_compare_evokeds(evoked_dict, colors=list(range(3)))
    plt.close('all')
    # test colormap
    cmap = get_cmap('viridis')
    plot_compare_evokeds(evoked_dict, cmap=cmap, colors=dict(aud=0.4, vis=0.9))
    plot_compare_evokeds(evoked_dict, cmap=cmap, colors=dict(aud=1, vis=2))
    plot_compare_evokeds(evoked_dict, cmap=('cmap title', 'inferno'),
                         linestyles=['-', ':', '--'])
    plt.close('all')
    # test deprecation
    with pytest.warns(DeprecationWarning, match='"gfp" is deprecated'):
        plot_compare_evokeds(evoked, gfp=True)
    with pytest.warns(DeprecationWarning, match='"max_ticks" changed to '):
        plot_compare_evokeds(evoked, picks=[0], truncate_yaxis='max_ticks')
    # test warnings
    with pytest.warns(RuntimeWarning, match='in "picks"; cannot combine'):
        plot_compare_evokeds(evoked, picks=[0], combine='median')
    plt.close('all')
    # test errors
    with pytest.raises(TypeError, match='"evokeds" must be a dict, list'):
        plot_compare_evokeds('foo')
    with pytest.raises(ValueError, match=r'keys in "styles" \(.*\) must '):
        plot_compare_evokeds(evoked_dict, styles=dict(foo='foo', bar='bar'))
    with pytest.raises(ValueError, match='colors in the default color cycle'):
        plot_compare_evokeds(huge_dict, colors=None)
    with pytest.raises(TypeError, match='"cmap" is specified, then "colors"'):
        plot_compare_evokeds(evoked_dict, cmap='Reds', colors={'aud/l': 'foo',
                                                               'aud/r': 'bar',
                                                               'vis': 'baz'})
    plt.close('all')
    for kwargs in [dict(colors=[0, 1]), dict(linestyles=['-', ':'])]:
        match = r'but there are only \d* (colors|linestyles). Please specify'
        with pytest.raises(ValueError, match=match):
            plot_compare_evokeds(evoked_dict, **kwargs)
    for kwargs in [dict(colors='foo'), dict(linestyles='foo')]:
        match = r'"(colors|linestyles)" must be a dict, list, or None; got '
        with pytest.raises(TypeError, match=match):
            plot_compare_evokeds(evoked_dict, **kwargs)
    for kwargs in [dict(colors=dict(foo='f')), dict(linestyles=dict(foo='f'))]:
        match = r'If "(colors|linestyles)" is a dict its keys \(.*\) must '
        with pytest.raises(ValueError, match=match):
            plot_compare_evokeds(evoked_dict, **kwargs)
    for kwargs in [dict(legend='foo'), dict(show_sensors='foo')]:
        with pytest.raises(ValueError, match='not a legal MPL loc, please'):
            plot_compare_evokeds(evoked_dict, **kwargs)
    with pytest.raises(TypeError, match='an instance of list or tuple'):
        plot_compare_evokeds(evoked_dict, vlines='foo')
    with pytest.raises(ValueError, match='"truncate_yaxis" must be bool or '):
        plot_compare_evokeds(evoked_dict, truncate_yaxis='foo')
    plt.close('all')
    # test axes='topo'
    figs = plot_compare_evokeds(evoked_dict, axes='topo', legend=True)
    for fig in figs:
        assert len(fig.axes[0].lines) == len(evoked_dict)
    # old tests
    red.info['chs'][0]['loc'][:2] = 0  # test plotting channel at zero
    plot_compare_evokeds(red, picks=[0],
                         ci=lambda x: [x.std(axis=0), -x.std(axis=0)])
    # smoke test for tmin >= 0 (from mailing list)
    red.crop(0.01, None)
    assert len(red.times) > 2
    plot_compare_evokeds(red)
    # plot a flat channel
    red.data = np.zeros_like(red.data)
    plot_compare_evokeds(red)
    # smoke test for one time point (not useful but should not fail)
    red.crop(0.02, 0.02)
    assert len(red.times) == 1
    plot_compare_evokeds(red)
    # now that we've cropped `red`:
    with pytest.raises(ValueError, match='not contain the same time instants'):
        plot_compare_evokeds(evoked_dict)
    plt.close('all')
Exemple #5
0
def test_plot_evoked():
    """Test plotting of evoked."""
    import matplotlib.pyplot as plt
    evoked = _get_epochs().average()
    with warnings.catch_warnings(record=True):
        fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo')
        # Test a click
        ax = fig.get_axes()[0]
        line = ax.lines[0]
        _fake_click(
            fig, ax,
            [line.get_xdata()[0], line.get_ydata()[0]], 'data')
        _fake_click(fig, ax, [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
        # plot with bad channels excluded & spatial_colors & zorder
        evoked.plot(exclude='bads')

        # test selective updating of dict keys is working.
        evoked.plot(hline=[1], units=dict(mag='femto foo'))
        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        evoked_delayed_ssp.plot(proj='interactive')
        evoked_delayed_ssp.apply_proj()
        assert_raises(RuntimeError,
                      evoked_delayed_ssp.plot,
                      proj='interactive')
        evoked_delayed_ssp.info['projs'] = []
        assert_raises(RuntimeError,
                      evoked_delayed_ssp.plot,
                      proj='interactive')
        assert_raises(RuntimeError,
                      evoked_delayed_ssp.plot,
                      proj='interactive',
                      axes='foo')
        plt.close('all')

        # test GFP only
        evoked.plot(gfp='only')
        assert_raises(ValueError, evoked.plot, gfp='foo')

        evoked.plot_image(proj=True)
        # plot with bad channels excluded
        evoked.plot_image(exclude='bads', cmap='interactive')
        evoked.plot_image(exclude=evoked.info['bads'])  # does the same thing
        plt.close('all')

        evoked.plot_topo()  # should auto-find layout
        _line_plot_onselect(0, 200, ['mag', 'grad'], evoked.info, evoked.data,
                            evoked.times)
        plt.close('all')

        cov = read_cov(cov_fname)
        cov['method'] = 'empirical'
        evoked.plot_white(cov)
        evoked.plot_white([cov, cov])

        # plot_compare_evokeds: test condition contrast, CI, color assignment
        plot_compare_evokeds(evoked.copy().pick_types(meg='mag'))
        plot_compare_evokeds(evoked.copy().pick_types(meg='grad'),
                             picks=[1, 2])
        evoked.rename_channels({'MEG 2142': "MEG 1642"})
        assert len(plot_compare_evokeds(evoked)) == 2
        colors = dict(red='r', blue='b')
        linestyles = dict(red='--', blue='-')
        red, blue = evoked.copy(), evoked.copy()
        red.data *= 1.1
        blue.data *= 0.9
        plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
        plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True)
        plot_compare_evokeds([[red, evoked], [blue, evoked]],
                             picks=3)  # list of lists
        # test picking & plotting grads
        contrast = dict()
        contrast["red/stim"] = list((evoked.copy(), red))
        contrast["blue/stim"] = list((evoked.copy(), blue))
        # test a bunch of params at once
        plot_compare_evokeds(contrast,
                             colors=colors,
                             linestyles=linestyles,
                             picks=[0, 2],
                             vlines=[.01, -.04],
                             invert_y=True,
                             truncate_yaxis=False,
                             ylim=dict(mag=(-10, 10)),
                             styles={"red/stim": {
                                 "linewidth": 1
                             }})
        assert_raises(ValueError, plot_compare_evokeds, contrast,
                      picks='str')  # bad picks: not int
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      colors=dict(fake=1))  # 'fake' not in conds
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      styles=dict(fake=1))  # 'fake' not in conds
        assert_raises(ValueError,
                      plot_compare_evokeds, [[1, 2], [3, 4]],
                      picks=3)  # evoked must contain Evokeds
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      styles=dict(err=1))  # bad styles dict
        assert_raises(ValueError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      gfp=True)  # no single-channel GFP
        assert_raises(TypeError,
                      plot_compare_evokeds,
                      evoked,
                      picks=3,
                      ci='fake')  # ci must be float or None
        contrast["red/stim"] = red
        contrast["blue/stim"] = blue
        plot_compare_evokeds(contrast,
                             picks=[0],
                             colors=['r', 'b'],
                             ylim=dict(mag=(1, 10)),
                             ci=_parametric_ci)
        # isolated test of CI functions
        arr = np.linspace(0, 1, 1000)[..., np.newaxis]
        assert_allclose(_ci(arr, method="parametric"),
                        _ci(arr, method="bootstrap"),
                        rtol=.005)
        assert_allclose(_bootstrap_ci(arr, statfun="median", random_state=0),
                        _bootstrap_ci(arr, statfun="mean", random_state=0),
                        rtol=.1)

        # Hack to test plotting of maxfiltered data
        evoked_sss = evoked.copy()
        evoked_sss.info['proc_history'] = [dict(max_info=None)]
        evoked_sss.plot_white(cov)
        evoked_sss.plot_white(cov_fname)

        # plot with bad channels excluded, spatial_colors, zorder & pos. layout
        evoked.rename_channels({'MEG 0133': 'MEG 0000'})
        evoked.plot(exclude=evoked.info['bads'],
                    spatial_colors=True,
                    gfp=True,
                    zorder='std')
        evoked.plot(exclude=[], spatial_colors=True, zorder='unsorted')
        assert_raises(TypeError, evoked.plot, zorder='asdf')
        plt.close('all')
    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')

    evoked.pick_channels(evoked.ch_names[:4])
    with warnings.catch_warnings(record=True) as ws:
        evoked.plot()
    assert_equal(len(ws), 2)
    assert_true(all('Need more than one' in str(w.message) for w in ws))
Exemple #6
0
def test_plot_evoked():
    """Test plotting of evoked."""
    import matplotlib.pyplot as plt
    rng = np.random.RandomState(0)
    evoked = _get_epochs().average()
    fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo',
                      time_unit='s')
    # Test a click
    ax = fig.get_axes()[0]
    line = ax.lines[0]
    _fake_click(fig, ax,
                [line.get_xdata()[0], line.get_ydata()[0]], 'data')
    _fake_click(fig, ax,
                [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
    # plot with bad channels excluded & spatial_colors & zorder
    evoked.plot(exclude='bads', time_unit='s')

    # test selective updating of dict keys is working.
    evoked.plot(hline=[1], units=dict(mag='femto foo'), time_unit='s')
    evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
    evoked_delayed_ssp.plot(proj='interactive', time_unit='s')
    evoked_delayed_ssp.apply_proj()
    pytest.raises(RuntimeError, evoked_delayed_ssp.plot,
                  proj='interactive', time_unit='s')
    evoked_delayed_ssp.info['projs'] = []
    pytest.raises(RuntimeError, evoked_delayed_ssp.plot,
                  proj='interactive', time_unit='s')
    pytest.raises(RuntimeError, evoked_delayed_ssp.plot,
                  proj='interactive', axes='foo', time_unit='s')
    plt.close('all')

    # test GFP only
    evoked.plot(gfp='only', time_unit='s')
    pytest.raises(ValueError, evoked.plot, gfp='foo', time_unit='s')

    evoked.plot_image(proj=True, time_unit='ms')

    # fail nicely on NaN
    evoked_nan = evoked.copy()
    evoked_nan.data[:, 0] = np.nan
    pytest.raises(ValueError, evoked_nan.plot)
    with np.errstate(invalid='ignore'):
        pytest.raises(ValueError, evoked_nan.plot_image)
        pytest.raises(ValueError, evoked_nan.plot_joint)

    # test mask
    evoked.plot_image(picks=[1, 2], mask=evoked.data > 0, time_unit='s')
    evoked.plot_image(picks=[1, 2], mask_cmap=None, colorbar=False,
                      mask=np.ones(evoked.data.shape).astype(bool),
                      time_unit='s')

    with pytest.warns(RuntimeWarning, match='not adding contour'):
        evoked.plot_image(picks=[1, 2], mask=None, mask_style="both",
                          time_unit='s')
    pytest.raises(ValueError, evoked.plot_image, mask=evoked.data[1:, 1:] > 0,
                  time_unit='s')

    # plot with bad channels excluded
    evoked.plot_image(exclude='bads', cmap='interactive', time_unit='s')
    evoked.plot_image(exclude=evoked.info['bads'], time_unit='s')  # same thing
    plt.close('all')

    pytest.raises(ValueError, evoked.plot_image, picks=[0, 0],
                  time_unit='s')  # duplicates

    ch_names = ["MEG 1131", "MEG 0111"]
    picks = [evoked.ch_names.index(ch) for ch in ch_names]
    evoked.plot_image(show_names="all", time_unit='s', picks=picks)
    yticklabels = plt.gca().get_yticklabels()
    for tick_target, tick_observed in zip(ch_names, yticklabels):
        assert tick_target in str(tick_observed)
    evoked.plot_image(show_names=True, time_unit='s')

    # test groupby
    evoked.plot_image(group_by=dict(sel=[0, 7]), axes=dict(sel=plt.axes()))
    plt.close('all')
    for group_by, axes in (("something", dict()), (dict(), "something")):
        pytest.raises(ValueError, evoked.plot_image, group_by=group_by,
                      axes=axes)

    # test plot_topo
    evoked.plot_topo()  # should auto-find layout
    _line_plot_onselect(0, 200, ['mag', 'grad'], evoked.info, evoked.data,
                        evoked.times)
    plt.close('all')

    cov = read_cov(cov_fname)
    cov['method'] = 'empirical'
    cov['projs'] = []  # avoid warnings
    # test rank param.
    evoked.plot_white(cov, rank={'mag': 101, 'grad': 201}, time_unit='s')
    evoked.plot_white(cov, rank={'mag': 101}, time_unit='s')  # test rank param
    evoked.plot_white(cov, rank={'grad': 201}, time_unit='s')
    pytest.raises(
        ValueError, evoked.plot_white, cov,
        rank={'mag': 101, 'grad': 201, 'meg': 306}, time_unit='s')
    pytest.raises(
        ValueError, evoked.plot_white, cov, rank={'meg': 306}, time_unit='s')

    evoked.plot_white([cov, cov], time_unit='s')

    # plot_compare_evokeds: test condition contrast, CI, color assignment
    plot_compare_evokeds(evoked.copy().pick_types(meg='mag'))
    plot_compare_evokeds(
        evoked.copy().pick_types(meg='grad'), picks=[1, 2],
        show_sensors="upper right", show_legend="upper left")
    evokeds = [evoked.copy() for _ in range(10)]
    for evoked in evokeds:
        evoked.data += (rng.randn(*evoked.data.shape) *
                        np.std(evoked.data, axis=-1, keepdims=True))
    for picks in ([0], [1], [2], [0, 2], [1, 2], [0, 1, 2],):
        figs = plot_compare_evokeds([evokeds], picks=picks, ci=0.95)
        if not isinstance(figs, list):
            figs = [figs]
        for fig in figs:
            ext = fig.axes[0].collections[0].get_paths()[0].get_extents()
            xs, ylim = ext.get_points().T
            assert_allclose(xs, evoked.times[[0, -1]])
            line = fig.axes[0].lines[0]
            xs = line.get_xdata()
            assert_allclose(xs, evoked.times)
            ys = line.get_ydata()
            assert (ys < ylim[1]).all()
            assert (ys > ylim[0]).all()
        plt.close('all')

    evoked.rename_channels({'MEG 2142': "MEG 1642"})
    assert len(plot_compare_evokeds(evoked)) == 2
    colors = dict(red='r', blue='b')
    linestyles = dict(red='--', blue='-')
    red, blue = evoked.copy(), evoked.copy()
    red.data *= 1.1
    blue.data *= 0.9
    plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
    plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True,
                         vlines=[])  # also testing empty vlines here
    plot_compare_evokeds([[red, evoked], [blue, evoked]],
                         picks=3)  # list of lists
    # test picking & plotting grads
    contrast = dict()
    contrast["red/stim"] = list((evoked.copy(), red))
    contrast["blue/stim"] = list((evoked.copy(), blue))
    # test a bunch of params at once
    for evokeds_ in (evoked.copy().pick_types(meg='mag'), contrast,
                     [red, blue], [[red, evoked], [blue, evoked]]):
        plot_compare_evokeds(evokeds_, picks=0, ci=True)  # also tests CI
    plt.close('all')
    # test styling +  a bunch of other params at once
    colors, linestyles = dict(red='r', blue='b'), dict(red='--', blue='-')
    plot_compare_evokeds(contrast, colors=colors, linestyles=linestyles,
                         picks=[0, 2], vlines=[.01, -.04], invert_y=True,
                         truncate_yaxis=False, ylim=dict(mag=(-10, 10)),
                         styles={"red/stim": {"linewidth": 1}},
                         show_sensors=True)
    # various bad styles
    params = [dict(picks=3, colors=dict(fake=1)),
              dict(picks=3, styles=dict(fake=1)), dict(picks=3, gfp=True),
              dict(picks=3, show_sensors="a"),
              dict(colors=dict(red=10., blue=-2))]
    for param in params:
        pytest.raises(ValueError, plot_compare_evokeds, evoked, **param)
    pytest.raises(TypeError, plot_compare_evokeds, evoked, picks='str')
    pytest.raises(TypeError, plot_compare_evokeds, evoked, vlines='x')
    plt.close('all')
    # `evoked` must contain Evokeds
    pytest.raises(TypeError, plot_compare_evokeds, [[1, 2], [3, 4]])
    # `ci` must be float or None
    pytest.raises(TypeError, plot_compare_evokeds, contrast, ci='err')
    # test all-positive ylim
    contrast["red/stim"], contrast["blue/stim"] = red, blue
    plot_compare_evokeds(contrast, picks=[0], colors=['r', 'b'],
                         ylim=dict(mag=(1, 10)), ci=_parametric_ci,
                         truncate_yaxis='max_ticks', show_sensors=False,
                         show_legend=False)

    # sequential colors
    evokeds = (evoked, blue, red)
    contrasts = {"a{}/b".format(ii): ev for ii, ev in
                 enumerate(evokeds)}
    colors = {"a" + str(ii): ii for ii, _ in enumerate(evokeds)}
    contrasts["a1/c"] = evoked.copy()
    for split in (True, False):
        for linestyles in (["-"], {"b": "-", "c": ":"}):
            plot_compare_evokeds(
                contrasts, colors=colors, picks=[0], cmap='Reds',
                split_legend=split, linestyles=linestyles,
                ci=False, show_sensors=False)
    colors = {"a" + str(ii): ii / len(evokeds)
              for ii, _ in enumerate(evokeds)}
    plot_compare_evokeds(
        contrasts, colors=colors, picks=[0], cmap='Reds',
        split_legend=split, linestyles=linestyles, ci=False,
        show_sensors=False)
    red.info["chs"][0]["loc"][:2] = 0  # test plotting channel at zero
    plot_compare_evokeds(red, picks=[0],
                         ci=lambda x: [x.std(axis=0), -x.std(axis=0)])
    plot_compare_evokeds([red, blue], picks=[0], cmap="summer", ci=None,
                         split_legend=None)
    plot_compare_evokeds([red, blue], cmap=None, split_legend=True)
    pytest.raises(ValueError, plot_compare_evokeds, [red] * 20)
    pytest.raises(ValueError, plot_compare_evokeds, contrasts,
                  cmap='summer')

    plt.close('all')

    # Hack to test plotting of maxfiltered data
    evoked_sss = evoked.copy()
    sss = dict(sss_info=dict(in_order=80, components=np.arange(80)))
    evoked_sss.info['proc_history'] = [dict(max_info=sss)]
    evoked_sss.plot_white(cov, rank={'meg': 64}, time_unit='s')
    pytest.raises(
        ValueError, evoked_sss.plot_white, cov, rank={'grad': 201},
        time_unit='s')
    evoked_sss.plot_white(cov, time_unit='s')

    # plot with bad channels excluded, spatial_colors, zorder & pos. layout
    evoked.rename_channels({'MEG 0133': 'MEG 0000'})
    evoked.plot(exclude=evoked.info['bads'], spatial_colors=True, gfp=True,
                zorder='std', time_unit='s')
    evoked.plot(exclude=[], spatial_colors=True, zorder='unsorted',
                time_unit='s')
    pytest.raises(TypeError, evoked.plot, zorder='asdf', time_unit='s')
    plt.close('all')

    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')

    evoked.pick_channels(evoked.ch_names[:4])
    with catch_logging() as log_file:
        evoked.plot(verbose=True, time_unit='s')
    assert 'Need more than one' in log_file.getvalue()
Exemple #7
0
def test_plot_compare_evokeds():
    """Test plot_compare_evokeds."""
    rng = np.random.RandomState(0)
    evoked = _get_epochs().average()
    # plot_compare_evokeds: test condition contrast, CI, color assignment
    fig = plot_compare_evokeds(evoked.copy().pick_types(meg='mag'),
                               show_sensors=True)
    assert len(fig.axes) == 2

    plot_compare_evokeds(evoked.copy().pick_types(meg='grad'),
                         picks=[1, 2],
                         show_sensors="upper right",
                         show_legend="upper left")
    evokeds = [evoked.copy() for _ in range(10)]
    for evoked in evokeds:
        evoked.data += (rng.randn(*evoked.data.shape) *
                        np.std(evoked.data, axis=-1, keepdims=True))
    for picks in (
        [0],
        [1],
        [2],
        [0, 2],
        [1, 2],
        [0, 1, 2],
    ):
        figs = plot_compare_evokeds([evokeds], picks=picks, ci=0.95)
        if not isinstance(figs, list):
            figs = [figs]
        for fig in figs:
            ext = fig.axes[0].collections[0].get_paths()[0].get_extents()
            xs, ylim = ext.get_points().T
            assert_allclose(xs, evoked.times[[0, -1]])
            line = fig.axes[0].lines[0]
            xs = line.get_xdata()
            assert_allclose(xs, evoked.times)
            ys = line.get_ydata()
            assert (ys < ylim[1]).all()
            assert (ys > ylim[0]).all()
        plt.close('all')

    evoked.rename_channels({'MEG 2142': "MEG 1642"})
    assert len(plot_compare_evokeds(evoked)) == 2
    colors = dict(red='r', blue='b')
    linestyles = dict(red='--', blue='-')
    red, blue = evoked.copy(), evoked.copy()
    red.data *= 1.1
    blue.data *= 0.9
    plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
    plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True,
                         vlines=[])  # also testing empty vlines here
    plot_compare_evokeds([[red, evoked], [blue, evoked]],
                         picks=3)  # list of lists
    # test picking & plotting grads
    contrast = dict()
    contrast["red/stim"] = list((evoked.copy(), red))
    contrast["blue/stim"] = list((evoked.copy(), blue))
    # test a bunch of params at once
    for evokeds_ in (evoked.copy().pick_types(meg='mag'), contrast,
                     [red, blue], [[red, evoked], [blue, evoked]]):
        plot_compare_evokeds(evokeds_, picks=0, ci=True)  # also tests CI
    plt.close('all')
    # test styling +  a bunch of other params at once
    colors, linestyles = dict(red='r', blue='b'), dict(red='--', blue='-')
    plot_compare_evokeds(contrast,
                         colors=colors,
                         linestyles=linestyles,
                         picks=[0, 2],
                         vlines=[.01, -.04],
                         invert_y=True,
                         truncate_yaxis=False,
                         ylim=dict(mag=(-10, 10)),
                         styles={"red/stim": {
                             "linewidth": 1
                         }},
                         show_sensors=True)
    # various bad styles
    params = [
        dict(picks=3, colors=dict(fake=1)),
        dict(picks=3, styles=dict(fake=1)),
        dict(picks=3, gfp=True),
        dict(picks=3, show_sensors="a"),
        dict(colors=dict(red=10., blue=-2))
    ]
    for param in params:
        pytest.raises(ValueError, plot_compare_evokeds, evoked, **param)
    pytest.raises(TypeError, plot_compare_evokeds, evoked, picks='str')
    pytest.raises(TypeError, plot_compare_evokeds, evoked, vlines='x')
    plt.close('all')
    # `evoked` must contain Evokeds
    pytest.raises(TypeError, plot_compare_evokeds, [[1, 2], [3, 4]])
    # `ci` must be float or None
    pytest.raises(TypeError, plot_compare_evokeds, contrast, ci='err')
    # test all-positive ylim
    contrast["red/stim"], contrast["blue/stim"] = red, blue
    plot_compare_evokeds(contrast,
                         picks=[0],
                         colors=['r', 'b'],
                         ylim=dict(mag=(1, 10)),
                         ci=_parametric_ci,
                         truncate_yaxis='max_ticks',
                         show_sensors=False,
                         show_legend=False)

    # sequential colors
    evokeds = (evoked, blue, red)
    contrasts = {"a{}/b".format(ii): ev for ii, ev in enumerate(evokeds)}
    colors = {"a" + str(ii): ii for ii, _ in enumerate(evokeds)}
    contrasts["a1/c"] = evoked.copy()
    for split in (True, False):
        for linestyles in (["-"], {"b": "-", "c": ":"}):
            plot_compare_evokeds(contrasts,
                                 colors=colors,
                                 picks=[0],
                                 cmap='Reds',
                                 split_legend=split,
                                 linestyles=linestyles,
                                 ci=False,
                                 show_sensors=False)
    colors = {"a" + str(ii): ii / len(evokeds) for ii, _ in enumerate(evokeds)}
    plot_compare_evokeds(contrasts,
                         colors=colors,
                         picks=[0],
                         cmap='Reds',
                         split_legend=split,
                         linestyles=linestyles,
                         ci=False,
                         show_sensors=False)
    red.info["chs"][0]["loc"][:2] = 0  # test plotting channel at zero
    plot_compare_evokeds(red,
                         picks=[0],
                         ci=lambda x: [x.std(axis=0), -x.std(axis=0)])
    plot_compare_evokeds([red, blue],
                         picks=[0],
                         cmap="summer",
                         ci=None,
                         split_legend=None)
    plot_compare_evokeds([red, blue], cmap=None, split_legend=True)
    pytest.raises(ValueError, plot_compare_evokeds, [red] * 20)
    pytest.raises(ValueError, plot_compare_evokeds, contrasts, cmap='summer')

    plt.close('all')
def test_plot_evoked():
    """Test plotting of evoked."""
    import matplotlib.pyplot as plt
    evoked = _get_epochs().average()
    with warnings.catch_warnings(record=True):
        fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo')
        # Test a click
        ax = fig.get_axes()[0]
        line = ax.lines[0]
        _fake_click(fig, ax,
                    [line.get_xdata()[0], line.get_ydata()[0]], 'data')
        _fake_click(fig, ax,
                    [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
        # plot with bad channels excluded & spatial_colors & zorder
        evoked.plot(exclude='bads')
        evoked.plot(exclude=evoked.info['bads'], spatial_colors=True, gfp=True,
                    zorder='std')

        # test selective updating of dict keys is working.
        evoked.plot(hline=[1], units=dict(mag='femto foo'))
        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        evoked_delayed_ssp.plot(proj='interactive')
        evoked_delayed_ssp.apply_proj()
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive')
        evoked_delayed_ssp.info['projs'] = []
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive')
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive', axes='foo')
        plt.close('all')

        # test GFP only
        evoked.plot(gfp='only')
        assert_raises(ValueError, evoked.plot, gfp='foo')

        evoked.plot_image(proj=True)
        # plot with bad channels excluded
        evoked.plot_image(exclude='bads', cmap='interactive')
        evoked.plot_image(exclude=evoked.info['bads'])  # does the same thing
        plt.close('all')

        evoked.plot_topo()  # should auto-find layout
        _butterfly_onselect(0, 200, ['mag', 'grad'], evoked)
        plt.close('all')

        cov = read_cov(cov_fname)
        cov['method'] = 'empirical'
        evoked.plot_white(cov)
        evoked.plot_white([cov, cov])

        # plot_compare_evokeds: test condition contrast, CI, color assignment
        plot_compare_evokeds(evoked.copy().pick_types(meg='mag'))
        evoked.rename_channels({'MEG 2142': "MEG 1642"})
        assert len(plot_compare_evokeds(evoked)) == 2
        colors = dict(red='r', blue='b')
        linestyles = dict(red='--', blue='-')
        red, blue = evoked.copy(), evoked.copy()
        red.data *= 1.1
        blue.data *= 0.9
        plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
        plot_compare_evokeds([[red, evoked], [blue, evoked]],
                             picks=3)  # list of lists
        # test picking & plotting grads
        contrast = dict()
        contrast["red/stim"] = list((evoked.copy(), red))
        contrast["blue/stim"] = list((evoked.copy(), blue))
        # test a bunch of params at once
        plot_compare_evokeds(contrast, colors=colors, linestyles=linestyles,
                             picks=[0, 2], vlines=[.01, -.04], invert_y=True,
                             truncate_yaxis=False, ylim=dict(mag=(-10, 10)),
                             styles={"red/stim": {"linewidth": 1}})
        assert_raises(ValueError, plot_compare_evokeds,
                      contrast, picks='str')  # bad picks: not int
        assert_raises(ValueError, plot_compare_evokeds, evoked, picks=3,
                      colors=dict(fake=1))  # 'fake' not in conds
        assert_raises(ValueError, plot_compare_evokeds, evoked, picks=3,
                      styles=dict(fake=1))  # 'fake' not in conds
        assert_raises(ValueError, plot_compare_evokeds, [[1, 2], [3, 4]],
                      picks=3)  # evoked must contain Evokeds
        assert_raises(ValueError, plot_compare_evokeds, evoked, picks=3,
                      styles=dict(err=1))  # bad styles dict
        assert_raises(ValueError, plot_compare_evokeds, evoked, picks=3,
                      gfp=True)  # no single-channel GFP
        assert_raises(TypeError, plot_compare_evokeds, evoked, picks=3,
                      ci='fake')  # ci must be float or None
        contrast["red/stim"] = red
        contrast["blue/stim"] = blue
        plot_compare_evokeds(contrast, picks=[0], colors=['r', 'b'],
                             ylim=dict(mag=(1, 10)))

        # Hack to test plotting of maxfiltered data
        evoked_sss = evoked.copy()
        evoked_sss.info['proc_history'] = [dict(max_info=None)]
        evoked_sss.plot_white(cov)
        evoked_sss.plot_white(cov_fname)
        plt.close('all')
    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')