예제 #1
0
def plot_multiple_ERP(epochs,
                      n_row=3,
                      n_col=2,
                      outfile=None,
                      title=None,
                      plot_topo=True):
    """
    Plot ERP for the different conditions
    """
    fig, ax = plt.subplots(n_row, n_col, sharex=True, figsize=(16, 9))
    if title:
        fig.suptitle(title)
    conditions = list(epochs.event_id.keys())
    if n_row * n_col != len(conditions):
        raise ValueError("Size of the plot and number of experimental"
                         "conditions dont match!")
    for col in range(n_col):
        for row, condition in zip(range(n_row),
                                  conditions[col * n_row:col * n_row + n_row]):
            epochs[condition].average().plot(axes=ax[row, col])
            ax[row, col].set_title("evoked response " + condition)
    fig.tight_layout(rect=[0, 0.03, 1, 0.95])
    if outfile:
        fig.savefig(outfile)
        plt.close()
    if plot_topo:
        evokeds = [epochs[condition].average() for condition in conditions]
        plot_evoked_topo(evokeds)
예제 #2
0
def test_plot_topo():
    """Test plotting of ERP topography
    """
    import matplotlib.pyplot as plt
    # Show topography
    evoked = _get_epochs().average()
    # should auto-find layout
    plot_evoked_topo([evoked, evoked], merge_grads=True)
    # Test jointplot
    evoked.plot_joint()
    evoked.plot_joint(title='test',
                      ts_args=dict(spatial_colors=True),
                      topomap_args=dict(colorbar=True, times=[0.]))

    warnings.simplefilter('always', UserWarning)
    picked_evoked = evoked.copy().pick_channels(evoked.ch_names[:3])
    picked_evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    with warnings.catch_warnings(record=True):
        for ylim in [dict(mag=[-600, 600]), None]:
            plot_evoked_topo([picked_evoked] * 2, layout, ylim=ylim)

        for evo in [evoked, [evoked, picked_evoked]]:
            assert_raises(ValueError,
                          plot_evoked_topo,
                          evo,
                          layout,
                          color=['y', 'b'])

        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
        picked_evoked_delayed_ssp = pick_channels_evoked(
            evoked_delayed_ssp, ch_names)
        fig = plot_evoked_topo(picked_evoked_delayed_ssp,
                               layout,
                               proj='interactive')
        func = _get_presser(fig)
        event = namedtuple('Event', ['inaxes', 'xdata', 'ydata'])
        func(
            event(inaxes=fig.axes[0],
                  xdata=fig.axes[0]._mne_axs[0].pos[0],
                  ydata=fig.axes[0]._mne_axs[0].pos[1]))
        func(event(inaxes=fig.axes[0], xdata=0, ydata=0))
        params = dict(evokeds=[picked_evoked_delayed_ssp],
                      times=picked_evoked_delayed_ssp.times,
                      fig=fig,
                      projs=picked_evoked_delayed_ssp.info['projs'])
        bools = [True] * len(params['projs'])
        _plot_update_evoked_topo_proj(params, bools)
    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)),
                     proj=True)
    picked_evoked.plot_topo(merge_grads=True)  # Test RMS plot of grad pairs
    plt.close('all')
    for ax, idx in iter_topography(evoked.info):
        ax.plot(evoked.data[idx], color='red')
    plt.close('all')
예제 #3
0
def test_plot_topo():
    """Test plotting of ERP topography."""
    # Show topography
    evoked = _get_epochs().average()
    # should auto-find layout
    plot_evoked_topo([evoked, evoked], merge_grads=True, background_color='w')

    picked_evoked = evoked.copy().pick_channels(evoked.ch_names[:3])
    picked_evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    for ylim in [dict(mag=[-600, 600]), None]:
        plot_evoked_topo([picked_evoked] * 2, layout, ylim=ylim)

    for evo in [evoked, [evoked, picked_evoked]]:
        pytest.raises(ValueError, plot_evoked_topo, evo, layout,
                      color=['y', 'b'])

    evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
    ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
    picked_evoked_delayed_ssp = pick_channels_evoked(evoked_delayed_ssp,
                                                     ch_names)
    fig = plot_evoked_topo(picked_evoked_delayed_ssp, layout,
                           proj='interactive')
    func = _get_presser(fig)
    event = namedtuple('Event', ['inaxes', 'xdata', 'ydata'])
    func(event(inaxes=fig.axes[0], xdata=fig.axes[0]._mne_axs[0].pos[0],
               ydata=fig.axes[0]._mne_axs[0].pos[1]))
    func(event(inaxes=fig.axes[0], xdata=0, ydata=0))
    params = dict(evokeds=[picked_evoked_delayed_ssp],
                  times=picked_evoked_delayed_ssp.times,
                  fig=fig, projs=picked_evoked_delayed_ssp.info['projs'])
    bools = [True] * len(params['projs'])
    with pytest.warns(RuntimeWarning, match='projection'):
        _plot_update_evoked_topo_proj(params, bools)

    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)), proj=True,
                     background_color='k')
    # Test RMS plot of grad pairs
    picked_evoked.plot_topo(merge_grads=True, background_color='w')
    plt.close('all')
    for ax, idx in iter_topography(evoked.info):
        ax.plot(evoked.data[idx], color='red')
        # test status bar message
        assert (evoked.ch_names[idx] in ax.format_coord(.5, .5))
    plt.close('all')
    cov = read_cov(cov_fname)
    cov['projs'] = []
    evoked.pick_types(meg=True).plot_topo(noise_cov=cov)
    plt.close('all')

    # 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')
예제 #4
0
def test_plot_topo():
    """Test plotting of ERP topography."""
    import matplotlib.pyplot as plt
    # Show topography
    evoked = _get_epochs().average()
    # should auto-find layout
    plot_evoked_topo([evoked, evoked], merge_grads=True, background_color='w')
    # Test jointplot
    evoked.plot_joint()

    def return_inds(d):  # to test function kwarg to zorder arg of evoked.plot
        return list(range(d.shape[0]))
    evoked.plot_joint(title='test', topomap_args=dict(contours=0, res=8),
                      ts_args=dict(spatial_colors=True, zorder=return_inds))
    assert_raises(ValueError, evoked.plot_joint, ts_args=dict(axes=True))

    warnings.simplefilter('always', UserWarning)
    picked_evoked = evoked.copy().pick_channels(evoked.ch_names[:3])
    picked_evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    with warnings.catch_warnings(record=True):
        for ylim in [dict(mag=[-600, 600]), None]:
            plot_evoked_topo([picked_evoked] * 2, layout, ylim=ylim)

        for evo in [evoked, [evoked, picked_evoked]]:
            assert_raises(ValueError, plot_evoked_topo, evo, layout,
                          color=['y', 'b'])

        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
        picked_evoked_delayed_ssp = pick_channels_evoked(evoked_delayed_ssp,
                                                         ch_names)
        fig = plot_evoked_topo(picked_evoked_delayed_ssp, layout,
                               proj='interactive')
        func = _get_presser(fig)
        event = namedtuple('Event', ['inaxes', 'xdata', 'ydata'])
        func(event(inaxes=fig.axes[0], xdata=fig.axes[0]._mne_axs[0].pos[0],
                   ydata=fig.axes[0]._mne_axs[0].pos[1]))
        func(event(inaxes=fig.axes[0], xdata=0, ydata=0))
        params = dict(evokeds=[picked_evoked_delayed_ssp],
                      times=picked_evoked_delayed_ssp.times,
                      fig=fig, projs=picked_evoked_delayed_ssp.info['projs'])
        bools = [True] * len(params['projs'])
        _plot_update_evoked_topo_proj(params, bools)
    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)), proj=True,
                     background_color='k')
    # Test RMS plot of grad pairs
    picked_evoked.plot_topo(merge_grads=True, background_color='w')
    plt.close('all')
    for ax, idx in iter_topography(evoked.info):
        ax.plot(evoked.data[idx], color='red')
        # test status bar message
        assert_true(evoked.ch_names[idx] in ax.format_coord(.5, .5))
    plt.close('all')
예제 #5
0
def plot_topo_compare():
    """This function will compare evoked potentials across conditions
    given one channel to look at"""

    import matplotlib.pyplot as plt
    from mne.viz import plot_evoked_topo

    include = [raw_input('Please select the channel you wish to look at: ')]
    reject = dict(eeg=200e-6)
    picks = mne.pick_types(raw.info,
                           meg=False,
                           eeg=True,
                           stim=False,
                           eog=True,
                           include=include,
                           exclude='bads')
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        picks=picks,
                        baseline=(None, 0),
                        reject=reject)

    # Generate list of evoked objects from conditions names
    evokeds = [epochs[name].average() for name in event_id]

    colors = 'yellow', 'green'

    key, value = event_id
    title = (
        "Topographical map of evoked response comparing \n%s to %s as conditions"
        % key, value)

    plot_evoked_topo(evokeds, color=colors, title=title)

    plt.show()
def test_plot_topo():
    """Test plotting of ERP topography
    """
    import matplotlib.pyplot as plt
    # Show topography
    evoked = _get_epochs().average()
    plot_evoked_topo(evoked)  # should auto-find layout
    warnings.simplefilter('always', UserWarning)
    picked_evoked = evoked.pick_channels(evoked.ch_names[:3], copy=True)
    picked_evoked_eeg = evoked.pick_types(meg=False, eeg=True, copy=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    with warnings.catch_warnings(record=True):
        for ylim in [dict(mag=[-600, 600]), None]:
            plot_topo([picked_evoked] * 2, layout, ylim=ylim)

        for evo in [evoked, [evoked, picked_evoked]]:
            assert_raises(ValueError, plot_topo, evo, layout, color=['y', 'b'])

        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
        picked_evoked_delayed_ssp = pick_channels_evoked(evoked_delayed_ssp,
                                                         ch_names)
        fig = plot_topo(picked_evoked_delayed_ssp, layout, proj='interactive')
        func = _get_presser(fig)
        event = namedtuple('Event', 'inaxes')
        func(event(inaxes=fig.axes[0]))
        params = dict(evokeds=[picked_evoked_delayed_ssp],
                      times=picked_evoked_delayed_ssp.times,
                      fig=fig, projs=picked_evoked_delayed_ssp.info['projs'])
        bools = [True] * len(params['projs'])
        _plot_update_evoked_topo(params, bools)
    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)), proj=True)
    plt.close('all')
예제 #7
0
def test_plot_topo_single_ch():
    """Test single channel topoplot with time cursor"""
    import matplotlib.pyplot as plt
    evoked = _get_epochs().average()
    fig = plot_evoked_topo(evoked)
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.65))
    assert_equal(num_figures_before + 1, len(plt.get_fignums()))
    fig = plt.gcf()
    ax = plt.gca()
    _fake_click(fig, ax, (.5, .5), kind='motion')  # cursor should appear
    assert_true(isinstance(ax._cursorline, matplotlib.lines.Line2D))
    _fake_click(fig, ax, (1.5, 1.5), kind='motion')  # cursor should disappear
    assert_equal(ax._cursorline, None)
    plt.close('all')
예제 #8
0
def test_plot_topo_single_ch():
    """Test single channel topoplot with time cursor."""
    evoked = _get_epochs().average()
    fig = plot_evoked_topo(evoked, background_color='w')
    # test status bar message
    ax = plt.gca()
    assert ('MEG 0113' in ax.format_coord(.065, .63))
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.65))
    assert num_figures_before + 1 == len(plt.get_fignums())
    fig = plt.gcf()
    ax = plt.gca()
    _fake_click(fig, ax, (.5, .5), kind='motion')  # cursor should appear
    assert (isinstance(ax._cursorline, matplotlib.lines.Line2D))
    _fake_click(fig, ax, (1.5, 1.5), kind='motion')  # cursor should disappear
    assert ax._cursorline is None
    plt.close('all')
예제 #9
0
def plot_topo(epochs, conditions=OrderedDict()):
    palette = sns.color_palette("hls", len(conditions) + 1)
    evokeds = [epochs[name].average() for name in (conditions)]

    evoked_topo = viz.plot_evoked_topo(evokeds,
                                       vline=None,
                                       color=palette[0:len(conditions)],
                                       show=False)
    evoked_topo.patch.set_alpha(0)
    evoked_topo.set_size_inches(10, 8)
    for axis in evoked_topo.axes:
        for line in axis.lines:
            line.set_linewidth(2)

    legend_loc = 0
    labels = [e.comment if e.comment else 'Unknown' for e in evokeds]
    legend = plt.legend(labels, loc=legend_loc, prop={'size': 20})
    txts = legend.get_texts()
    for txt, col in zip(txts, palette):
        txt.set_color(col)

    return evoked_topo
reject = dict(grad=4000e-13, mag=4e-12)

# Create epochs including different events
event_id = {
    'audio/left': 1,
    'audio/right': 2,
    'visual/left': 3,
    'visual/right': 4
}
epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks='meg',
                    baseline=(None, 0),
                    reject=reject)

# Generate list of evoked objects from conditions names
evokeds = [epochs[name].average() for name in ('left', 'right')]

# %%
# Show topography for two different conditions

colors = 'blue', 'red'
title = 'MNE sample data\nleft vs right (A/V combined)'

plot_evoked_topo(evokeds, color=colors, title=title, background_color='w')

plt.show()
예제 #11
0
#   Set up amplitude-peak rejection values for MEG channels
reject = dict(grad=4000e-13, mag=4e-12)

# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
                       include=include, exclude='bads')

# Create epochs including different events
event_id = {'audio/left': 1, 'audio/right': 2,
            'visual/left': 3, 'visual/right': 4}
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    picks=picks, baseline=(None, 0), reject=reject)

# Generate list of evoked objects from conditions names
evokeds = [epochs[name].average() for name in ('left', 'right')]

###############################################################################
# Show topography for two different conditions

colors = 'yellow', 'green'
title = 'MNE sample data - left vs right (A/V combined)'

plot_evoked_topo(evokeds, color=colors, title=title)

conditions = [e.comment for e in evokeds]
for cond, col, pos in zip(conditions, colors, (0.025, 0.07)):
    plt.figtext(0.99, pos, cond, color=col, fontsize=12,
                horizontalalignment='right')

plt.show()
예제 #12
0
def test_plot_topo():
    """Test plotting of ERP topography."""
    import matplotlib.pyplot as plt
    # Show topography
    evoked = _get_epochs().average()
    # should auto-find layout
    plot_evoked_topo([evoked, evoked], merge_grads=True, background_color='w')
    # Test jointplot
    evoked.plot_joint(ts_args=dict(time_unit='s'),
                      topomap_args=dict(time_unit='s'))

    def return_inds(d):  # to test function kwarg to zorder arg of evoked.plot
        return list(range(d.shape[0]))

    evoked.plot_joint(title='test',
                      topomap_args=dict(contours=0, res=8, time_unit='ms'),
                      ts_args=dict(spatial_colors=True,
                                   zorder=return_inds,
                                   time_unit='s'))
    pytest.raises(ValueError,
                  evoked.plot_joint,
                  ts_args=dict(axes=True, time_unit='s'))

    axes = plt.subplots(nrows=3)[-1].flatten().tolist()
    evoked.plot_joint(times=[0],
                      picks=[6, 7, 8],
                      ts_args=dict(axes=axes[0]),
                      topomap_args={
                          "axes": axes[1:],
                          "time_unit": "s"
                      })
    plt.close()
    pytest.raises(ValueError,
                  evoked.plot_joint,
                  picks=[6, 7, 8],
                  ts_args=dict(axes=axes[0]),
                  topomap_args=dict(axes=axes[2:]))

    warnings.simplefilter('always', UserWarning)
    picked_evoked = evoked.copy().pick_channels(evoked.ch_names[:3])
    picked_evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    with warnings.catch_warnings(record=True):
        for ylim in [dict(mag=[-600, 600]), None]:
            plot_evoked_topo([picked_evoked] * 2, layout, ylim=ylim)

        for evo in [evoked, [evoked, picked_evoked]]:
            pytest.raises(ValueError,
                          plot_evoked_topo,
                          evo,
                          layout,
                          color=['y', 'b'])

        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
        picked_evoked_delayed_ssp = pick_channels_evoked(
            evoked_delayed_ssp, ch_names)
        fig = plot_evoked_topo(picked_evoked_delayed_ssp,
                               layout,
                               proj='interactive')
        func = _get_presser(fig)
        event = namedtuple('Event', ['inaxes', 'xdata', 'ydata'])
        func(
            event(inaxes=fig.axes[0],
                  xdata=fig.axes[0]._mne_axs[0].pos[0],
                  ydata=fig.axes[0]._mne_axs[0].pos[1]))
        func(event(inaxes=fig.axes[0], xdata=0, ydata=0))
        params = dict(evokeds=[picked_evoked_delayed_ssp],
                      times=picked_evoked_delayed_ssp.times,
                      fig=fig,
                      projs=picked_evoked_delayed_ssp.info['projs'])
        bools = [True] * len(params['projs'])
        _plot_update_evoked_topo_proj(params, bools)
    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)),
                     proj=True,
                     background_color='k')
    # Test RMS plot of grad pairs
    picked_evoked.plot_topo(merge_grads=True, background_color='w')
    plt.close('all')
    for ax, idx in iter_topography(evoked.info):
        ax.plot(evoked.data[idx], color='red')
        # test status bar message
        assert (evoked.ch_names[idx] in ax.format_coord(.5, .5))
    plt.close('all')
    cov = read_cov(cov_fname)
    cov['projs'] = []
    evoked.pick_types(meg=True).plot_topo(noise_cov=cov)
    plt.close('all')
예제 #13
0
def test_plot_topo():
    """Test plotting of ERP topography."""
    # Show topography
    evoked = _get_epochs().average()
    # should auto-find layout
    plot_evoked_topo([evoked, evoked], merge_grads=True, background_color='w')
    # Test jointplot
    evoked.plot_joint(ts_args=dict(time_unit='s'),
                      topomap_args=dict(time_unit='s'))

    def return_inds(d):  # to test function kwarg to zorder arg of evoked.plot
        return list(range(d.shape[0]))
    evoked.plot_joint(title='test', topomap_args=dict(contours=0, res=8,
                                                      time_unit='ms'),
                      ts_args=dict(spatial_colors=True, zorder=return_inds,
                                   time_unit='s'))
    pytest.raises(ValueError, evoked.plot_joint, ts_args=dict(axes=True,
                                                              time_unit='s'))

    axes = plt.subplots(nrows=3)[-1].flatten().tolist()
    evoked.plot_joint(times=[0], picks=[6, 7, 8],  ts_args=dict(axes=axes[0]),
                      topomap_args={"axes": axes[1:], "time_unit": "s"})
    plt.close()
    pytest.raises(ValueError, evoked.plot_joint, picks=[6, 7, 8],
                  ts_args=dict(axes=axes[0]), topomap_args=dict(axes=axes[2:]))

    picked_evoked = evoked.copy().pick_channels(evoked.ch_names[:3])
    picked_evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    for ylim in [dict(mag=[-600, 600]), None]:
        plot_evoked_topo([picked_evoked] * 2, layout, ylim=ylim)

    for evo in [evoked, [evoked, picked_evoked]]:
        pytest.raises(ValueError, plot_evoked_topo, evo, layout,
                      color=['y', 'b'])

    evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
    ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
    picked_evoked_delayed_ssp = pick_channels_evoked(evoked_delayed_ssp,
                                                     ch_names)
    fig = plot_evoked_topo(picked_evoked_delayed_ssp, layout,
                           proj='interactive')
    func = _get_presser(fig)
    event = namedtuple('Event', ['inaxes', 'xdata', 'ydata'])
    func(event(inaxes=fig.axes[0], xdata=fig.axes[0]._mne_axs[0].pos[0],
               ydata=fig.axes[0]._mne_axs[0].pos[1]))
    func(event(inaxes=fig.axes[0], xdata=0, ydata=0))
    params = dict(evokeds=[picked_evoked_delayed_ssp],
                  times=picked_evoked_delayed_ssp.times,
                  fig=fig, projs=picked_evoked_delayed_ssp.info['projs'])
    bools = [True] * len(params['projs'])
    with pytest.warns(RuntimeWarning, match='projection'):
        _plot_update_evoked_topo_proj(params, bools)

    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)), proj=True,
                     background_color='k')
    # Test RMS plot of grad pairs
    picked_evoked.plot_topo(merge_grads=True, background_color='w')
    plt.close('all')
    for ax, idx in iter_topography(evoked.info):
        ax.plot(evoked.data[idx], color='red')
        # test status bar message
        assert (evoked.ch_names[idx] in ax.format_coord(.5, .5))
    plt.close('all')
    cov = read_cov(cov_fname)
    cov['projs'] = []
    evoked.pick_types(meg=True).plot_topo(noise_cov=cov)
    plt.close('all')

    # 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')
#   Set up pick list: MEG + STI 014 - bad channels (modify to your needs)
include = []  # or stim channels ['STI 014']
# bad channels in raw.info['bads'] will be automatically excluded

#   Set up amplitude-peak rejection values for MEG channels
reject = dict(grad=4000e-13, mag=4e-12)

# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
                       include=include, exclude='bads')

# Create epochs including different events
event_id = {'audio/left': 1, 'audio/right': 2,
            'visual/left': 3, 'visual/right': 4}
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    picks=picks, baseline=(None, 0), reject=reject)

# Generate list of evoked objects from conditions names
evokeds = [epochs[name].average() for name in ('left', 'right')]

###############################################################################
# Show topography for two different conditions

colors = 'blue', 'red'
title = 'MNE sample data\nleft vs right (A/V combined)'

plot_evoked_topo(evokeds, color=colors, title=title, background_color='w')

plt.show()
예제 #15
0
=================================
Plot topographies for MEG sensors
=================================

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

import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()

fname = data_path + "/MEG/sample/sample_audvis-ave.fif"

# Reading
condition = "Left Auditory"
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))

###############################################################################
# Show topography
title = "MNE sample data (condition : %s)" % evoked.comment
plot_evoked_topo(evoked, title=title)
plt.show()
evoked_avg = [] #creates a LIST of evoked objects (dict)

for key in codes:
    # create a copy of the first evoked object in ssavg[key]:
    evoked_avg.append(ssavg[key][0].copy())
    evoked_avg[-1].data = evoked_avg[-1].data * 0

    n_ssavg = len(ssavg[key])
    for i in range(n_ssavg):
        if len(ssavg[key][i].data) == len(evoked_avg[-1].data):
            # average the data accross participants:
            evoked_avg[-1].data =  evoked_avg[-1].data + ssavg[key][i].data / n_ssavg

print("Click on the thing to show zoomed-in electrode")
plot_evoked_topo(evoked_avg) #first argument is a list of evoked instances



#(2) manually remove bad epochs:
#epochs.drop_bad()
#epochs.plot_drop_log()
epochs.plot()

#(3) remember to save
#out_file = args.epochs_file.split('.')[0]+'-epo.fif'
print("If you want to save the file, do this in python shell:")
print("epochs.save(args.epochs_file)")
#epochs.save('Obja0004-epo.fif')
#epochs.save(args.epochs_file)
예제 #17
0
=================================

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

import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

# Reading
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))

###############################################################################
# Show topography.
# For Neuromag data, you can use merge_grads=True to plot
# RMS values of gradiometer pairs.
title = 'MNE sample data (condition : %s)' % evoked.comment
plot_evoked_topo(evoked, title=title, merge_grads=False)
plt.show()
예제 #18
0
psd_evo1 = psd_to_evo(psd1, freqs1, epo1, keep_ch_names=False)
psd_evo2 = psd_to_evo(psd2, freqs2, epo2, keep_ch_names=False)

# Not necessary, but you can name them. Useful for plotting
psd_evo1.comment = "First"
psd_evo2.comment = "Second"

# Any Evoked can be plotted e.g. as a topo.
# as far as MNE knows, this is an ERP, so the X and Y axis
# will not be correctly titled, i.e. the X axis will say it's
# time, when it's actually frequency. Just ignore for now. The
# values themselves are correct.
psd_evo1.plot_topo()

# plot multiple
plot_evoked_topo([psd_evo1, psd_evo2])

# subtract condition two from one
# note this function is very general, and can perform any
# linear operation on any set of Evokeds
one_minus_two = combine_evoked([psd_evo1, psd_evo2], [1, -1])
one_minus_two.comment = "one - two"
one_minus_two.plot_topo()

# Note that the channels names have the generic, Neuromag names, i.e.
# "MEGXXX." The automatic channel layout identifier gets
# confused by the native "AXXX" Magnes3600 names, and so functions such as
# plot_topo fail, because they cannot figure out the physical locations
# of the channels. One way to solve this problem is to convert the channel
# names to Neuromag names with psd_to_evo(keep_ch_names=False). This is
# the approach used above. Alternatively, if you want to keep the Magnes
=================================
Plot topographies for MEG sensors
=================================

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

import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

# Reading
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))

###############################################################################
# Show topography
title = 'MNE sample data (condition : %s)' % evoked.comment
plot_evoked_topo(evoked, title=title)
plt.show()
예제 #20
0
def test_plot_topo():
    """Test plotting of ERP topography."""
    # Show topography
    evoked = _get_epochs().average()
    # should auto-find layout
    plot_evoked_topo([evoked, evoked], merge_grads=True, background_color='w')

    picked_evoked = evoked.copy().pick_channels(evoked.ch_names[:3])
    picked_evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
    picked_evoked_eeg.pick_channels(picked_evoked_eeg.ch_names[:3])

    # test scaling
    for ylim in [dict(mag=[-600, 600]), None]:
        plot_evoked_topo([picked_evoked] * 2, layout, ylim=ylim)

    for evo in [evoked, [evoked, picked_evoked]]:
        pytest.raises(ValueError,
                      plot_evoked_topo,
                      evo,
                      layout,
                      color=['y', 'b'])

    evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
    ch_names = evoked_delayed_ssp.ch_names[:3]  # make it faster
    picked_evoked_delayed_ssp = pick_channels_evoked(evoked_delayed_ssp,
                                                     ch_names)
    fig = plot_evoked_topo(picked_evoked_delayed_ssp,
                           layout,
                           proj='interactive')
    func = _get_presser(fig)
    event = namedtuple('Event', ['inaxes', 'xdata', 'ydata'])
    func(
        event(inaxes=fig.axes[0],
              xdata=fig.axes[0]._mne_axs[0].pos[0],
              ydata=fig.axes[0]._mne_axs[0].pos[1]))
    func(event(inaxes=fig.axes[0], xdata=0, ydata=0))
    params = dict(evokeds=[picked_evoked_delayed_ssp],
                  times=picked_evoked_delayed_ssp.times,
                  fig=fig,
                  projs=picked_evoked_delayed_ssp.info['projs'])
    bools = [True] * len(params['projs'])
    with pytest.warns(RuntimeWarning, match='projection'):
        _plot_update_evoked_topo_proj(params, bools)

    # should auto-generate layout
    plot_evoked_topo(picked_evoked_eeg.copy(),
                     fig_background=np.zeros((4, 3, 3)),
                     proj=True,
                     background_color='k')
    # Test RMS plot of grad pairs
    picked_evoked.plot_topo(merge_grads=True, background_color='w')
    plt.close('all')
    for ax, idx in iter_topography(evoked.info, legend=True):
        ax.plot(evoked.data[idx], color='red')
        # test status bar message
        if idx != -1:
            assert (evoked.ch_names[idx] in ax.format_coord(.5, .5))
    assert idx == -1
    plt.close('all')
    cov = read_cov(cov_fname)
    cov['projs'] = []
    evoked.pick_types(meg=True).plot_topo(noise_cov=cov)
    plt.close('all')

    # 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')

    for ax, idx in iter_topography(evoked.info):  # brief test with false
        ax.plot([0, 1, 2])
        break
    plt.close('all')
예제 #21
0
def test_plot_topo_nirs(fnirs_evoked):
    """Test plotting of ERP topography for nirs data."""
    fnirs_evoked.pick(picks='hbo')
    fig = plot_evoked_topo(fnirs_evoked)
    assert len(fig.axes) == 1
    plt.close('all')
예제 #22
0
lh_aud = mne.Epochs(raw,
                    events,
                    event_id=1,
                    tmin=-0.75,
                    tmax=0.75,
                    baseline=(-0.75, -0.5))
rh_aud = mne.Epochs(raw,
                    events,
                    event_id=3,
                    tmin=-0.75,
                    tmax=0.75,
                    baseline=(-0.75, -0.5))
"""Compared evoked responses"""
if (plot_topography):
    lh_aud_evoked, rh_aud_evoked = lh_aud.average(), rh_aud.average()
    plot_evoked_topo([lh_aud_evoked, rh_aud_evoked], color=['blue', 'red'])

# Select all epochs and time points from one channel.
ch_ind = [
    i for i, ch_name in enumerate(raw.info['ch_names'])
    if 'MEG 2343' in ch_name
][0]
lh_data, rh_data = (lh_aud.get_data()[:,
                                      ch_ind, :], rh_aud.get_data()[:,
                                                                    ch_ind, :])

significant, pvals, cstats, ref_cstat, ref_clusters = permutation_test(
    lh_data, rh_data)
plot_permutation_distribution(cstats, ref_cstat, show_plot=True)
plot_permutation_result_1d(lh_data, rh_data, significant, lh_aud.times,
                           ref_clusters)