def test_plot_volume_source_estimates(): """Test interactive plotting of volume source estimates.""" forward = read_forward_solution(fwd_fname) sample_src = forward['src'] vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) n_time = 2 data = np.random.RandomState(0).rand(n_verts, n_time) vol_stc = VolSourceEstimate(data, vertices, 1, 1) for mode in ['glass_brain', 'stat_map']: with pytest.warns(None): # sometimes get scalars/index warning fig = vol_stc.plot(sample_src, subject='sample', subjects_dir=subjects_dir, mode=mode) # [ax_time, ax_y, ax_x, ax_z] for ax_idx in [0, 2, 3, 4]: _fake_click(fig, fig.axes[ax_idx], (0.3, 0.5)) fig.canvas.key_press_event('left') fig.canvas.key_press_event('shift+right') with pytest.raises(ValueError, match='must be one of'): vol_stc.plot(sample_src, 'sample', subjects_dir, mode='abcd') vertices.append([]) surface_stc = SourceEstimate(data, vertices, 1, 1) with pytest.raises(ValueError, match='Only Vol'): plot_volume_source_estimates(surface_stc, sample_src, 'sample', subjects_dir) with pytest.raises(ValueError, match='Negative colormap limits'): vol_stc.plot(sample_src, 'sample', subjects_dir, clim=dict(lims=[-1, 2, 3], kind='value'))
def test_stc_mpl(): """Test plotting source estimates with matplotlib.""" sample_src = read_source_spaces(src_fname) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.ones((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') with pytest.warns(RuntimeWarning, match='not included'): stc.plot(subjects_dir=subjects_dir, time_unit='s', views='ven', hemi='rh', smoothing_steps=2, subject='sample', backend='matplotlib', spacing='oct1', initial_time=0.001, colormap='Reds') fig = stc.plot(subjects_dir=subjects_dir, time_unit='ms', views='dor', hemi='lh', smoothing_steps=2, subject='sample', backend='matplotlib', spacing='ico2', time_viewer=True, colormap='mne') time_viewer = fig.time_viewer _fake_click(time_viewer, time_viewer.axes[0], (0.5, 0.5)) # change t time_viewer.canvas.key_press_event('ctrl+right') time_viewer.canvas.key_press_event('left') pytest.raises(ValueError, stc.plot, subjects_dir=subjects_dir, hemi='both', subject='sample', backend='matplotlib') pytest.raises(ValueError, stc.plot, subjects_dir=subjects_dir, time_unit='ss', subject='sample', backend='matplotlib') 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]) # 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')
def test_plot_sensors(): """Test plotting of sensor array.""" import matplotlib.pyplot as plt raw = _get_raw() fig = raw.plot_sensors('3d') _fake_click(fig, fig.gca(), (-0.08, 0.67)) raw.plot_sensors('topomap') plt.close('all')
def test_plot_tfr_topo(): """Test plotting of TFR data.""" import matplotlib.pyplot as plt epochs = _get_epochs() n_freqs = 3 nave = 1 data = np.random.RandomState(0).randn(len(epochs.ch_names), n_freqs, len(epochs.times)) tfr = AverageTFR(epochs.info, data, epochs.times, np.arange(n_freqs), nave) plt.close('all') fig = tfr.plot_topo(baseline=(None, 0), mode='ratio', title='Average power', vmin=0., vmax=14.) # test opening tfr by clicking num_figures_before = len(plt.get_fignums()) # could use np.reshape(fig.axes[-1].images[0].get_extent(), (2, 2)).mean(1) with pytest.warns(None): # on old mpl there is a warning _fake_click(fig, fig.axes[0], (0.08, 0.65)) assert num_figures_before + 1 == len(plt.get_fignums()) plt.close('all') tfr.plot([4], baseline=(None, 0), mode='ratio', show=False, title='foo') pytest.raises(ValueError, tfr.plot, [4], yscale='lin', show=False) # nonuniform freqs freqs = np.logspace(*np.log10([3, 10]), num=3) tfr = AverageTFR(epochs.info, data, epochs.times, freqs, nave) fig = tfr.plot([4], baseline=(None, 0), mode='mean', vmax=14., show=False) assert fig.axes[0].get_yaxis().get_scale() == 'log' # one timesample tfr = AverageTFR(epochs.info, data[:, :, [0]], epochs.times[[1]], freqs, nave) with pytest.warns(None): # matplotlib equal left/right tfr.plot([4], baseline=None, vmax=14., show=False, yscale='linear') # one frequency bin, log scale required: as it doesn't make sense # to plot log scale for one value, we test whether yscale is set to linear vmin, vmax = 0., 2. fig, ax = plt.subplots() tmin, tmax = epochs.times[0], epochs.times[-1] with pytest.warns(RuntimeWarning, match='not masking'): _imshow_tfr(ax, 3, tmin, tmax, vmin, vmax, None, tfr=data[:, [0], :], freq=freqs[[-1]], x_label=None, y_label=None, colorbar=False, cmap=('RdBu_r', True), yscale='log') fig = plt.gcf() assert fig.axes[0].get_yaxis().get_scale() == 'linear' # ValueError when freq[0] == 0 and yscale == 'log' these_freqs = freqs[:3].copy() these_freqs[0] = 0 with pytest.warns(RuntimeWarning, match='not masking'): pytest.raises(ValueError, _imshow_tfr, ax, 3, tmin, tmax, vmin, vmax, None, tfr=data[:, :3, :], freq=these_freqs, x_label=None, y_label=None, colorbar=False, cmap=('RdBu_r', True), yscale='log')
def test_plot_sensors(): """Test plotting of sensor array.""" import matplotlib.pyplot as plt raw = _get_raw() fig = raw.plot_sensors('3d') _fake_click(fig, fig.gca(), (-0.08, 0.67)) raw.plot_sensors('topomap') assert_raises(TypeError, plot_sensors, raw) # needs to be info plt.close('all')
def test_plot_topo_image_epochs(): """Test plotting of epochs image topography.""" import matplotlib.pyplot as plt title = 'ERF images - MNE sample data' epochs = _get_epochs() cmap = mne_analyze_colormap(format='matplotlib') fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200, colorbar=True, title=title, cmap=cmap) _fake_click(fig, fig.axes[2], (0.08, 0.64)) plt.close('all')
def test_plot_topomap_interactive(): """Test interactive topomap projection plotting.""" import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0] evoked.pick_types(meg='mag') evoked.info['projs'] = [] assert not evoked.proj evoked.add_proj(compute_proj_evoked(evoked, n_mag=1)) plt.close('all') fig = Figure() canvas = FigureCanvas(fig) ax = fig.gca() kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax, res=8, time_unit='s') evoked.copy().plot_topomap(proj=False, **kwargs) canvas.draw() image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert len(plt.get_fignums()) == 1 ax.clear() evoked.copy().plot_topomap(proj=True, **kwargs) canvas.draw() image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert not np.array_equal(image_noproj, image_proj) assert len(plt.get_fignums()) == 1 ax.clear() evoked.copy().plot_topomap(proj='interactive', **kwargs) canvas.draw() image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_noproj, image_interactive) assert not np.array_equal(image_proj, image_interactive) assert len(plt.get_fignums()) == 2 proj_fig = plt.figure(plt.get_fignums()[-1]) _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data') canvas.draw() image_interactive_click = np.frombuffer( canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_proj, image_interactive_click) assert not np.array_equal(image_noproj, image_interactive_click) _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data') canvas.draw() image_interactive_click = np.frombuffer( canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_noproj, image_interactive_click) assert not np.array_equal(image_proj, image_interactive_click)
def test_plot_instance_components(): """Test plotting of components as instances of raw and epochs.""" raw = _get_raw() picks = _get_picks(raw) ica = ICA(noise_cov=read_cov(cov_fname), n_components=2) with pytest.warns(RuntimeWarning, match='projection'): ica.fit(raw, picks=picks) ica.exclude = [0] fig = ica.plot_sources(raw, title='Components') keys = ('home', 'home', 'end', 'down', 'up', 'right', 'left', '-', '+', '=', 'd', 'd', 'pageup', 'pagedown', 'z', 'z', 's', 's', 'f11', 'b') for key in keys: fig.canvas.key_press_event(key) ax = fig.mne.ax_main line = ax.lines[0] _fake_click(fig, ax, [line.get_xdata()[0], line.get_ydata()[0]], 'data') _fake_click(fig, ax, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event('escape') plt.close('all') epochs = _get_epochs() fig = ica.plot_sources(epochs, title='Components') for key in keys: fig.canvas.key_press_event(key) # 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event('escape')
def test_plot_instance_components(): """Test plotting of components as instances of raw and epochs.""" import matplotlib.pyplot as plt raw = _get_raw() picks = _get_picks(raw) ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) with pytest.warns(RuntimeWarning, match='projection'): ica.fit(raw, picks=picks) fig = ica.plot_sources(raw, exclude=[0], title='Components') for key in ['down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup', 'pagedown', 'home', 'end', 'f11', 'b']: fig.canvas.key_press_event(key) 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event('escape') plt.close('all') epochs = _get_epochs() fig = ica.plot_sources(epochs, exclude=[0], title='Components') for key in ['down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup', 'pagedown', 'home', 'end', 'f11', 'b']: fig.canvas.key_press_event(key) # 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event('escape') plt.close('all')
def test_plot_sensors(): """Test plotting of sensor array.""" import matplotlib.pyplot as plt raw = _get_raw() fig = raw.plot_sensors('3d') _fake_click(fig, fig.gca(), (-0.08, 0.67)) raw.plot_sensors('topomap') ax = plt.subplot(111) raw.plot_sensors(ch_groups='position', axes=ax) raw.plot_sensors(ch_groups='selection') raw.plot_sensors(ch_groups=[[0, 1, 2], [3, 4]]) assert_raises(ValueError, raw.plot_sensors, ch_groups='asd') assert_raises(TypeError, plot_sensors, raw) # needs to be info plt.close('all')
def test_plot_evoked(): """Test evoked.plot.""" import matplotlib.pyplot as plt 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') # 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()
def test_remove_annotations(raw, hide_which): """Test that right-click doesn't remove hidden annotation spans.""" ann = Annotations(onset=[2, 1], duration=[1, 3], description=['foo', 'bar']) raw.set_annotations(ann) assert len(raw.annotations) == 2 fig = raw.plot() fig.canvas.key_press_event('a') # start annotation mode checkboxes = fig.mne.show_hide_annotation_checkboxes for which in hide_which: checkboxes.set_active(which) _fake_click(fig, fig.mne.ax_main, (2.5, 0.1), xform='data', button=3) assert len(raw.annotations) == len(hide_which)
def test_plot_epochs_clicks(epochs, epochs_full, capsys, mpl_backend): """Test plot_epochs mouse interaction.""" fig = epochs.plot(events=epochs.events) x = fig.mne.traces[0].get_xdata()[3] y = fig.mne.traces[0].get_ydata()[3] n_epochs = len(epochs) epoch_num = fig.mne.inst.selection[0] # test (un)marking bad epochs fig._fake_click([x, y], xform='data') # mark a bad epoch assert epoch_num in fig.mne.bad_epochs fig._fake_click([x, y], xform='data') # unmark it assert epoch_num not in fig.mne.bad_epochs fig._fake_click([x, y], xform='data') # mark it bad again assert epoch_num in fig.mne.bad_epochs # test vline fig._fake_keypress('escape') # close and drop epochs fig._close_event() # XXX workaround, MPL Agg doesn't trigger close event assert (n_epochs - 1 == len(epochs)) # test marking bad channels # need more than 1 epoch this time fig = epochs_full.plot(n_epochs=3) data_ax = fig.mne.ax_main # ToDo: Tick-Labels will be accessed differently in pyqtgraph. first_ch = data_ax.get_yticklabels()[0].get_text() assert first_ch not in fig.mne.info['bads'] _click_ch_name(fig, ch_index=0, button=1) # click ch name to mark bad assert first_ch in fig.mne.info['bads'] # test clicking scrollbars _fake_click(fig, fig.mne.ax_vscroll, [0.5, 0.5]) _fake_click(fig, fig.mne.ax_hscroll, [0.5, 0.5]) # test moving bad epoch offscreen fig._fake_keypress('right') # move right x = fig.mne.traces[0].get_xdata()[-3] y = fig.mne.traces[0].get_ydata()[-3] fig._fake_click([x, y], xform='data') # mark a bad epoch fig._fake_keypress('left') # move back out, err = capsys.readouterr() assert 'out of bounds' not in out assert 'out of bounds' not in err fig._fake_keypress('escape') fig._close_event() # XXX workaround, MPL Agg doesn't trigger close event assert len(epochs_full) == 6 # test rightclick → image plot fig = epochs_full.plot() _click_ch_name(fig, ch_index=0, button=3) # show image plot assert len(fig.mne.child_figs) == 1 # test scroll wheel fig._fake_scroll(0.5, 0.5, -0.5) # scroll down fig._fake_scroll(0.5, 0.5, 0.5) # scroll up
def test_plot_evoked(): """Test evoked.plot.""" 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') # 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()
def test_stc_mpl(): """Test plotting source estimates with matplotlib.""" import matplotlib.pyplot as plt sample_src = read_source_spaces(src_fname) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.ones((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') with pytest.warns(RuntimeWarning, match='not included'): stc.plot(subjects_dir=subjects_dir, time_unit='s', views='ven', hemi='rh', smoothing_steps=2, subject='sample', backend='matplotlib', spacing='oct1', initial_time=0.001, colormap='Reds') fig = stc.plot(subjects_dir=subjects_dir, time_unit='ms', views='dor', hemi='lh', smoothing_steps=2, subject='sample', backend='matplotlib', spacing='ico2', time_viewer=True, colormap='mne') time_viewer = fig.time_viewer _fake_click(time_viewer, time_viewer.axes[0], (0.5, 0.5)) # change t time_viewer.canvas.key_press_event('ctrl+right') time_viewer.canvas.key_press_event('left') pytest.raises(ValueError, stc.plot, subjects_dir=subjects_dir, hemi='both', subject='sample', backend='matplotlib') pytest.raises(ValueError, stc.plot, subjects_dir=subjects_dir, time_unit='ss', subject='sample', backend='matplotlib') plt.close('all')
def test_plot_topomap_interactive(): """Test interactive topomap projection plotting.""" evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0] evoked.pick_types(meg='mag') evoked.info['projs'] = [] assert not evoked.proj evoked.add_proj(compute_proj_evoked(evoked, n_mag=1)) plt.close('all') fig = Figure() canvas = FigureCanvas(fig) ax = fig.gca() kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax, res=8, time_unit='s') evoked.copy().plot_topomap(proj=False, **kwargs) canvas.draw() image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert len(plt.get_fignums()) == 1 ax.clear() evoked.copy().plot_topomap(proj=True, **kwargs) canvas.draw() image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert not np.array_equal(image_noproj, image_proj) assert len(plt.get_fignums()) == 1 ax.clear() evoked.copy().plot_topomap(proj='interactive', **kwargs) canvas.draw() image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_noproj, image_interactive) assert not np.array_equal(image_proj, image_interactive) assert len(plt.get_fignums()) == 2 proj_fig = plt.figure(plt.get_fignums()[-1]) _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data') canvas.draw() image_interactive_click = np.frombuffer( canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_proj, image_interactive_click) assert not np.array_equal(image_noproj, image_interactive_click) _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data') canvas.draw() image_interactive_click = np.frombuffer( canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_noproj, image_interactive_click) assert not np.array_equal(image_proj, image_interactive_click)
def test_plot_topo_image_epochs(): """Test plotting of epochs image topography.""" title = 'ERF images - MNE sample data' epochs = _get_epochs() epochs.load_data() cmap = mne_analyze_colormap(format='matplotlib') data_min = epochs._data.min() plt.close('all') fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200, colorbar=True, title=title, cmap=cmap) assert epochs._data.min() == data_min num_figures_before = len(plt.get_fignums()) _fake_click(fig, fig.axes[0], (0.08, 0.64)) assert num_figures_before + 1 == len(plt.get_fignums()) plt.close('all')
def test_plot_ica_sources(): """Test plotting of ICA panel.""" import matplotlib.pyplot as plt raw = read_raw_fif(raw_fname).crop(0, 1).load_data() picks = _get_picks(raw) epochs = _get_epochs() raw.pick_channels([raw.ch_names[k] for k in picks]) ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3) ica.fit(raw, picks=ica_picks) ica.exclude = [1] fig = ica.plot_sources(raw) fig.canvas.key_press_event('escape') # Sadly close_event isn't called on Agg backend and the test always passes. assert_array_equal(ica.exclude, [1]) raw.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=raw) ica.plot_sources(epochs) epochs.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=epochs) epochs.info['bads'] = [] with warnings.catch_warnings(record=True): # no labeled objects mpl ica.plot_sources(epochs.average()) evoked = epochs.average() fig = ica.plot_sources(evoked) # 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 ica.plot_sources(evoked, exclude=[0]) ica.exclude = [0] ica.plot_sources(evoked) # does the same thing ica.labels_ = dict(eog=[0]) ica.labels_['eog/0/crazy-channel'] = [0] ica.plot_sources(evoked) # now with labels assert_raises(ValueError, ica.plot_sources, 'meeow') plt.close('all')
def test_inspect_annotations(tmp_path): """Test inspection of Annotations.""" import matplotlib import matplotlib.pyplot as plt matplotlib.use('Agg') plt.close('all') bids_root = setup_bids_test_dir(tmp_path) bids_path = _bids_path.copy().update(root=bids_root) raw = read_raw_bids(bids_path=bids_path, verbose='error') orig_annotations = raw.annotations.copy() inspect_dataset(bids_path, find_flat=False) raw_fig = mne_bids.inspect._global_vars['raw_fig'] _add_annotation(raw_fig) # Close window and save changes. raw_fig.canvas.key_press_event(raw_fig.mne.close_key) fig_dialog = mne_bids.inspect._global_vars['dialog_fig'] fig_dialog.canvas.key_press_event('return') # Ensure changes were saved. raw = read_raw_bids(bids_path=bids_path, verbose='error') assert 'BAD_test' in raw.annotations.description annot_idx = raw.annotations.description == 'BAD_test' assert raw.annotations.duration[annot_idx].squeeze() == 4 # Remove the Annotation. inspect_dataset(bids_path, find_flat=False) raw_fig = mne_bids.inspect._global_vars['raw_fig'] data_ax = raw_fig.mne.ax_main raw_fig.canvas.key_press_event('a') # Toggle Annotation mode _fake_click(raw_fig, data_ax, [1., 1.], xform='data', button=3, kind='press') # Close window and save changes. raw_fig.canvas.key_press_event(raw_fig.mne.close_key) fig_dialog = mne_bids.inspect._global_vars['dialog_fig'] fig_dialog.canvas.key_press_event('return') # Ensure changes were saved. raw = read_raw_bids(bids_path=bids_path, verbose='error') assert 'BAD_test' not in raw.annotations.description assert raw.annotations == orig_annotations
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=[]) # 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 evoked.plot(exclude='bads') evoked.plot(exclude=evoked.info['bads']) # does the same thing # 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') evoked.plot_image(proj=True) # plot with bad channels excluded evoked.plot_image(exclude='bads') evoked.plot_image(exclude=evoked.info['bads']) # does the same thing plt.close('all') cov = read_cov(cov_fname) cov['method'] = 'empirical' evoked.plot_white(cov) evoked.plot_white([cov, cov]) # 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)
def test_plot_volume_source_estimates(mode, stype, init_t, want_t, init_p, want_p, bg_img): """Test interactive plotting of volume source estimates.""" forward = read_forward_solution(fwd_fname) sample_src = forward['src'] if init_p is not None: init_p = np.array(init_p) / 1000. vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) n_time = 2 data = np.random.RandomState(0).rand(n_verts, n_time) if stype == 'vec': stc = VolVectorSourceEstimate(np.tile(data[:, np.newaxis], (1, 3, 1)), vertices, 1, 1) else: assert stype == 's' stc = VolSourceEstimate(data, vertices, 1, 1) with pytest.warns(None): # sometimes get scalars/index warning with catch_logging() as log: fig = stc.plot(sample_src, subject='sample', subjects_dir=subjects_dir, mode=mode, initial_time=init_t, initial_pos=init_p, bg_img=bg_img, verbose=True) log = log.getvalue() want_str = 't = %0.3f s' % want_t assert want_str in log, (want_str, init_t) want_str = '(%0.1f, %0.1f, %0.1f) mm' % want_p assert want_str in log, (want_str, init_p) for ax_idx in [0, 2, 3, 4]: _fake_click(fig, fig.axes[ax_idx], (0.3, 0.5)) fig.canvas.key_press_event('left') fig.canvas.key_press_event('shift+right') if bg_img is not None: with pytest.raises(FileNotFoundError, match='MRI file .* not found'): stc.plot(sample_src, subject='sample', subjects_dir=subjects_dir, mode='stat_map', bg_img='junk.mgz')
def test_plot_ica_components(): """Test plotting of ICA solutions.""" import matplotlib.pyplot as plt res = 8 fast_test = {"res": res, "contours": 0, "sensors": False} raw = _get_raw() ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) ica_picks = _get_picks(raw) with warnings.catch_warnings(record=True): ica.fit(raw, picks=ica_picks) warnings.simplefilter('always', UserWarning) with warnings.catch_warnings(record=True): for components in [0, [0], [0, 1], [0, 1] * 2, None]: ica.plot_components(components, image_interp='bilinear', colorbar=True, **fast_test) # test interactive mode (passing 'inst' arg) plt.close('all') ica.plot_components([0, 1], image_interp='bilinear', inst=raw, res=16) fig = plt.gcf() ax = [a for a in fig.get_children() if isinstance(a, plt.Axes)] lbl = ax[1].get_label() _fake_click(fig, ax[1], (0., 0.), xform='data') c_fig = plt.gcf() ax = [a for a in c_fig.get_children() if isinstance(a, plt.Axes)] labels = [a.get_label() for a in ax] for l in ['topomap', 'image', 'erp', 'spectrum', 'variance']: assert_true(l in labels) topomap_ax = ax[labels.index('topomap')] title = topomap_ax.get_title() assert_true(lbl == title) ica.info = None assert_raises(ValueError, ica.plot_components, 1) assert_raises(RuntimeError, ica.plot_components, 1, ch_type='mag') plt.close('all')
def test_plot_ica_sources(): """Test plotting of ICA panel """ import matplotlib.pyplot as plt raw = io.read_raw_fif(raw_fname, preload=False).crop(0, 1, copy=False).load_data() picks = _get_picks(raw) epochs = _get_epochs() raw.pick_channels([raw.ch_names[k] for k in picks]) ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3) ica.fit(raw, picks=ica_picks) ica.exclude = [1] fig = ica.plot_sources(raw) fig.canvas.key_press_event('escape') # Sadly close_event isn't called on Agg backend and the test always passes. assert_array_equal(ica.exclude, [1]) raw.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=raw) ica.plot_sources(epochs) epochs.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=epochs) epochs.info['bads'] = [] with warnings.catch_warnings(record=True): # no labeled objects mpl ica.plot_sources(epochs.average()) evoked = epochs.average() fig = ica.plot_sources(evoked) # 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 ica.plot_sources(evoked, exclude=[0]) ica.exclude = [0] ica.plot_sources(evoked) # does the same thing ica.labels_ = dict(eog=[0]) ica.labels_['eog/0/crazy-channel'] = [0] ica.plot_sources(evoked) # now with labels assert_raises(ValueError, ica.plot_sources, 'meeow') plt.close('all')
def test_clickable_image(): """Test the ClickableImage class.""" # Gen data and create clickable image im = np.random.randn(100, 100) clk = ClickableImage(im) clicks = [(12, 8), (46, 48), (10, 24)] # Generate clicks for click in clicks: _fake_click(clk.fig, clk.ax, click, xform='data') assert_allclose(np.array(clicks), np.array(clk.coords)) assert_true(len(clicks) == len(clk.coords)) # Exporting to layout lt = clk.to_layout() assert_true(lt.pos.shape[0] == len(clicks)) assert_allclose(lt.pos[1, 0] / lt.pos[2, 0], clicks[1][0] / float(clicks[2][0]))
def test_plot_epochs(): """Test epoch plotting""" import matplotlib.pyplot as plt epochs = _get_epochs() epochs.plot(scalings=None, title='Epochs', trellis=False) plt.close('all') fig = epochs[0].plot(picks=[0, 2, 3], scalings=None, trellis=False) fig.canvas.key_press_event('escape') plt.close('all') fig = epochs.plot(trellis=False) fig.canvas.key_press_event('left') fig.canvas.key_press_event('right') fig.canvas.key_press_event('up') fig.canvas.key_press_event('down') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event('pagedown') fig.canvas.key_press_event('-') fig.canvas.key_press_event('+') fig.canvas.key_press_event('=') fig.canvas.key_press_event('b') fig.canvas.key_press_event('f11') fig.canvas.key_press_event('home') fig.canvas.key_press_event('end') fig.canvas.resize_event() fig.canvas.close_event() # closing and epoch dropping plt.close('all') with warnings.catch_warnings(record=True): fig = epochs.plot(trellis=False) # test mouse clicks x = fig.get_axes()[0].get_xlim()[1] / 2 y = fig.get_axes()[0].get_ylim()[0] / 2 data_ax = fig.get_axes()[0] n_epochs = len(epochs) _fake_click(fig, data_ax, [x, y], xform='data') # mark a bad epoch _fake_click(fig, data_ax, [x, y], xform='data') # unmark a bad epoch _fake_click(fig, data_ax, [0.5, 0.999]) # click elsewhere in 1st axes _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change epochs _fake_click(fig, fig.get_axes()[3], [0.5, 0.5]) # change channels fig.canvas.close_event() # closing and epoch dropping assert(n_epochs - 1 == len(epochs)) plt.close('all') assert_raises(RuntimeError, epochs.plot, picks=[], trellis=False) plt.close('all')
def test_plot_epochs_keypresses(): """Test plot_epochs keypress interaction.""" epochs = _get_epochs(stop=15).load_data() # we need more than 1 epoch epochs.drop_bad(dict(mag=4e-12)) # for histogram plot coverage fig = epochs.plot(n_epochs=3) data_ax = fig.mne.ax_main # make sure green vlines are visible first (for coverage) sample_idx = len(epochs.times) // 2 # halfway through the first epoch x = fig.mne.traces[0].get_xdata()[sample_idx] y = (fig.mne.traces[0].get_ydata()[sample_idx] + fig.mne.traces[1].get_ydata()[sample_idx]) / 2 _fake_click(fig, data_ax, [x, y], xform='data') # click between traces # test keys keys = ('pagedown', 'down', 'up', 'down', 'right', 'left', '-', '+', '=', 'd', 'd', 'pageup', 'home', 'shift+right', 'end', 'shift+left', 'z', 'z', 's', 's', 'f11', '?', 'h', 'j', 'b') for key in keys * 2: # test twice → once in normal, once in butterfly view fig.canvas.key_press_event(key) _fake_click(fig, data_ax, [x, y], xform='data', button=3) # remove vlines
def test_plot_instance_components(): """Test plotting of components as instances of raw and epochs.""" import matplotlib.pyplot as plt raw = _get_raw() picks = _get_picks(raw) ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) with warnings.catch_warnings(record=True): # bad proj ica.fit(raw, picks=picks) fig = ica.plot_sources(raw, exclude=[0], title='Components') fig.canvas.key_press_event('down') fig.canvas.key_press_event('up') fig.canvas.key_press_event('right') fig.canvas.key_press_event('left') fig.canvas.key_press_event('o') fig.canvas.key_press_event('-') fig.canvas.key_press_event('+') fig.canvas.key_press_event('=') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event('pagedown') fig.canvas.key_press_event('home') fig.canvas.key_press_event('end') fig.canvas.key_press_event('f11') 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event('escape') plt.close('all') epochs = _get_epochs() fig = ica.plot_sources(epochs, exclude=[0], title='Components') fig.canvas.key_press_event('down') fig.canvas.key_press_event('up') fig.canvas.key_press_event('right') fig.canvas.key_press_event('left') fig.canvas.key_press_event('o') fig.canvas.key_press_event('-') fig.canvas.key_press_event('+') fig.canvas.key_press_event('=') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event('pagedown') fig.canvas.key_press_event('home') fig.canvas.key_press_event('end') fig.canvas.key_press_event('f11') # 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event('escape') plt.close('all')
def test_plot_ica_sources(): """Test plotting of ICA panel """ import matplotlib.pyplot as plt raw = io.Raw(raw_fname, preload=False) raw.crop(0, 1, copy=False) raw.preload_data() picks = _get_picks(raw) epochs = _get_epochs() raw.pick_channels([raw.ch_names[k] for k in picks]) ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3) ica.fit(raw, picks=ica_picks) raw.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=raw) ica.plot_sources(epochs) epochs.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=epochs) epochs.info['bads'] = [] with warnings.catch_warnings(record=True): # no labeled objects mpl ica.plot_sources(epochs.average()) evoked = epochs.average() fig = ica.plot_sources(evoked) # 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 ica.plot_sources(evoked, exclude=[0]) ica.exclude = [0] ica.plot_sources(evoked) # does the same thing assert_raises(ValueError, ica.plot_sources, 'meeow') plt.close('all')
def test_clickable_image(): """Test the ClickableImage class.""" # Gen data and create clickable image im = np.random.RandomState(0).randn(100, 100) clk = ClickableImage(im) clicks = [(12, 8), (46, 48), (10, 24)] # Generate clicks for click in clicks: _fake_click(clk.fig, clk.ax, click, xform='data') assert_allclose(np.array(clicks), np.array(clk.coords)) assert (len(clicks) == len(clk.coords)) # Exporting to layout lt = clk.to_layout() assert (lt.pos.shape[0] == len(clicks)) assert_allclose(lt.pos[1, 0] / lt.pos[2, 0], clicks[1][0] / float(clicks[2][0])) clk.plot_clicks() plt.close('all')
def test_plot_instance_components(): """Test plotting of components as instances of raw and epochs.""" import matplotlib.pyplot as plt raw = _get_raw() picks = _get_picks(raw) ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) with warnings.catch_warnings(record=True): # bad proj ica.fit(raw, picks=picks) fig = ica.plot_sources(raw, exclude=[0], title="Components") fig.canvas.key_press_event("down") fig.canvas.key_press_event("up") fig.canvas.key_press_event("right") fig.canvas.key_press_event("left") fig.canvas.key_press_event("o") fig.canvas.key_press_event("-") fig.canvas.key_press_event("+") fig.canvas.key_press_event("=") fig.canvas.key_press_event("pageup") fig.canvas.key_press_event("pagedown") fig.canvas.key_press_event("home") fig.canvas.key_press_event("end") fig.canvas.key_press_event("f11") 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event("escape") plt.close("all") epochs = _get_epochs() fig = ica.plot_sources(epochs, exclude=[0], title="Components") fig.canvas.key_press_event("down") fig.canvas.key_press_event("up") fig.canvas.key_press_event("right") fig.canvas.key_press_event("left") fig.canvas.key_press_event("o") fig.canvas.key_press_event("-") fig.canvas.key_press_event("+") fig.canvas.key_press_event("=") fig.canvas.key_press_event("pageup") fig.canvas.key_press_event("pagedown") fig.canvas.key_press_event("home") fig.canvas.key_press_event("end") fig.canvas.key_press_event("f11") # 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, [-0.1, 0.9]) # click on y-label fig.canvas.key_press_event("escape") plt.close("all")
def _add_annotation(raw_fig): """Add an Annotation to a Raw plot.""" data_ax = raw_fig.mne.ax_main raw_fig.canvas.key_press_event('a') # Toggle Annotation mode ann_fig = raw_fig.mne.fig_annotation for key in 'test': # Annotation will be named: BAD_test ann_fig.canvas.key_press_event(key) ann_fig.canvas.key_press_event('enter') # Draw a 4 second long Annotation. _fake_click(raw_fig, data_ax, [1., 1.], xform='data', button=1, kind='press') _fake_click(raw_fig, data_ax, [5., 1.], xform='data', button=1, kind='motion') _fake_click(raw_fig, data_ax, [5., 1.], xform='data', button=1, kind='release')
def test_plot_ica_sources(): """Test plotting of ICA panel.""" raw = read_raw_fif(raw_fname).crop(0, 1).load_data() picks = _get_picks(raw) epochs = _get_epochs() raw.pick_channels([raw.ch_names[k] for k in picks]) ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3) ica.fit(raw, picks=ica_picks) ica.exclude = [1] fig = ica.plot_sources(raw) fig.canvas.key_press_event('escape') # Sadly close_event isn't called on Agg backend and the test always passes. assert_array_equal(ica.exclude, [1]) plt.close('all') # dtype can change int->np.int after load, test it explicitly ica.n_components_ = np.int64(ica.n_components_) fig = ica.plot_sources(raw) # also test mouse clicks data_ax = fig.axes[0] assert len(plt.get_fignums()) == 1 _fake_click(fig, data_ax, [-0.1, 0.9]) # click on y-label assert len(plt.get_fignums()) == 2 ica.exclude = [1] ica.plot_sources(raw) raw.info['bads'] = ['MEG 0113'] with pytest.raises(RuntimeError, match="Raw doesn't match fitted data"): ica.plot_sources(inst=raw) ica.plot_sources(epochs) epochs.info['bads'] = ['MEG 0113'] with pytest.raises(RuntimeError, match="Epochs don't match fitted data"): ica.plot_sources(inst=epochs) epochs.info['bads'] = [] ica.plot_sources(epochs.average()) evoked = epochs.average() fig = ica.plot_sources(evoked) # 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 ica.exclude = [0] ica.plot_sources(evoked) ica.labels_ = dict(eog=[0]) ica.labels_['eog/0/crazy-channel'] = [0] ica.plot_sources(evoked) # now with labels with pytest.raises(ValueError, match='must be of Raw or Epochs type'): ica.plot_sources('meeow') plt.close('all')
def test_plot_ica_components(): """Test plotting of ICA solutions.""" import matplotlib.pyplot as plt res = 8 fast_test = {"res": res, "contours": 0, "sensors": False} raw = _get_raw() ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) ica_picks = _get_picks(raw) with warnings.catch_warnings(record=True): ica.fit(raw, picks=ica_picks) warnings.simplefilter('always', UserWarning) with warnings.catch_warnings(record=True): for components in [0, [0], [0, 1], [0, 1] * 2, None]: ica.plot_components(components, image_interp='bilinear', colorbar=True, **fast_test) plt.close('all') # test interactive mode (passing 'inst' arg) ica.plot_components([0, 1], image_interp='bilinear', inst=raw, res=16) fig = plt.gcf() # test title click # ---------------- lbl = fig.axes[1].get_label() ica_idx = int(lbl[-3:]) titles = [ax.title for ax in fig.axes] title_pos_midpoint = (titles[1].get_window_extent().extents.reshape( (2, 2)).mean(axis=0)) # first click adds to exclude _fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix') assert ica_idx in ica.exclude # clicking again removes from exclude _fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix') assert ica_idx not in ica.exclude # test topo click # --------------- _fake_click(fig, fig.axes[1], (0., 0.), xform='data') c_fig = plt.gcf() labels = [ax.get_label() for ax in c_fig.axes] for l in ['topomap', 'image', 'erp', 'spectrum', 'variance']: assert_true(l in labels) topomap_ax = c_fig.axes[labels.index('topomap')] title = topomap_ax.get_title() assert_true(lbl == title) ica.info = None assert_raises(ValueError, ica.plot_components, 1) assert_raises(RuntimeError, ica.plot_components, 1, ch_type='mag') plt.close('all')
def test_plot_volume_source_estimates(): """Test interactive plotting of volume source estimates.""" forward = read_forward_solution(fwd_fname) sample_src = forward['src'] vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) n_time = 2 data = np.random.RandomState(0).rand(n_verts, n_time) vol_stc = VolSourceEstimate(data, vertices, 1, 1) vol_vec_stc = VolVectorSourceEstimate( np.tile(vol_stc.data[:, np.newaxis], (1, 3, 1)), vol_stc.vertices, 0, 1) for mode, stc in zip(['glass_brain', 'stat_map'], (vol_stc, vol_vec_stc)): with pytest.warns(None): # sometimes get scalars/index warning fig = stc.plot(sample_src, subject='sample', subjects_dir=subjects_dir, mode=mode) # [ax_time, ax_y, ax_x, ax_z] for ax_idx in [0, 2, 3, 4]: _fake_click(fig, fig.axes[ax_idx], (0.3, 0.5)) fig.canvas.key_press_event('left') fig.canvas.key_press_event('shift+right') with pytest.raises(ValueError, match='must be one of'): vol_stc.plot(sample_src, 'sample', subjects_dir, mode='abcd') vertices.append([]) surface_stc = SourceEstimate(data, vertices, 1, 1) with pytest.raises(ValueError, match='Only Vol'): plot_volume_source_estimates(surface_stc, sample_src, 'sample', subjects_dir) with pytest.raises(ValueError, match='Negative colormap limits'): vol_stc.plot(sample_src, 'sample', subjects_dir, clim=dict(lims=[-1, 2, 3], kind='value'))
def test_plot_ica_components(): """Test plotting of ICA solutions.""" import matplotlib.pyplot as plt raw = _get_raw() ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) ica_picks = _get_picks(raw) with warnings.catch_warnings(record=True): ica.fit(raw, picks=ica_picks) warnings.simplefilter("always", UserWarning) with warnings.catch_warnings(record=True): for components in [0, [0], [0, 1], [0, 1] * 2, None]: ica.plot_components(components, image_interp="bilinear", res=16, colorbar=True) # test interactive mode (passing 'inst' arg) plt.close("all") ica.plot_components([0, 1], image_interp="bilinear", res=16, inst=raw) fig = plt.gcf() ax = [a for a in fig.get_children() if isinstance(a, plt.Axes)] lbl = ax[1].get_label() _fake_click(fig, ax[1], (0.0, 0.0), xform="data") c_fig = plt.gcf() ax = [a for a in c_fig.get_children() if isinstance(a, plt.Axes)] labels = [a.get_label() for a in ax] for l in ["topomap", "image", "erp", "spectrum", "variance"]: assert_true(l in labels) topomap_ax = ax[labels.index("topomap")] title = topomap_ax.get_title() assert_true(lbl == title) ica.info = None assert_raises(ValueError, ica.plot_components, 1) assert_raises(RuntimeError, ica.plot_components, 1, ch_type="mag") plt.close("all")
def test_plot_topo_image_epochs(): """Test plotting of epochs image topography.""" title = 'ERF images - MNE sample data' epochs = _get_epochs() epochs.load_data() cmap = mne_analyze_colormap(format='matplotlib') data_min = epochs._data.min() plt.close('all') fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200, colorbar=True, title=title, cmap=cmap) assert epochs._data.min() == data_min num_figures_before = len(plt.get_fignums()) _fake_click(fig, fig.axes[0], (0.08, 0.64)) assert num_figures_before + 1 == len(plt.get_fignums()) # test for auto-showing a colorbar when only 1 sensor type ep = epochs.copy().pick_types(meg=False, eeg=True) fig = plot_topo_image_epochs(ep, vmin=None, vmax=None, colorbar=None, cmap=cmap) ax = [x for x in fig.get_children() if isinstance(x, matplotlib.axes.Axes)] qm_cmap = [y.cmap for x in ax for y in x.get_children() if isinstance(y, matplotlib.collections.QuadMesh)] assert qm_cmap[0] is cmap plt.close('all')
def test_plot_ica_sources(): """Test plotting of ICA panel """ import matplotlib.pyplot as plt raw = io.Raw(raw_fname, preload=False) raw.crop(0, 1, copy=False) raw.preload_data() picks = _get_picks(raw) epochs = _get_epochs() raw.pick_channels([raw.ch_names[k] for k in picks]) ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3) ica.fit(raw, picks=ica_picks) raw.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=raw) ica.plot_sources(epochs) epochs.info['bads'] = ['MEG 0113'] assert_raises(RuntimeError, ica.plot_sources, inst=epochs) epochs.info['bads'] = [] with warnings.catch_warnings(record=True): # no labeled objects mpl ica.plot_sources(epochs.average()) evoked = epochs.average() fig = ica.plot_sources(evoked) # 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 ica.plot_sources(evoked, exclude=[0]) ica.exclude = [0] ica.plot_sources(evoked) # does the same thing assert_raises(ValueError, ica.plot_sources, 'meeow') plt.close('all')
def test_plot_ica_components(): """Test plotting of ICA solutions.""" res = 8 fast_test = {"res": res, "contours": 0, "sensors": False} raw = _get_raw() ica = ICA(noise_cov=read_cov(cov_fname), n_components=2) ica_picks = _get_picks(raw) with pytest.warns(RuntimeWarning, match='projection'): ica.fit(raw, picks=ica_picks) for components in [0, [0], [0, 1], [0, 1] * 2, None]: ica.plot_components(components, image_interp='bilinear', colorbar=True, **fast_test) plt.close('all') # test interactive mode (passing 'inst' arg) with catch_logging() as log: ica.plot_components([0, 1], image_interp='bilinear', inst=raw, res=16, verbose='debug', ch_type='grad') log = log.getvalue() assert 'grad data' in log assert 'Interpolation mode local to mean' in log fig = plt.gcf() # test title click # ---------------- lbl = fig.axes[1].get_label() ica_idx = int(lbl[-3:]) titles = [ax.title for ax in fig.axes] title_pos_midpoint = (titles[1].get_window_extent().extents .reshape((2, 2)).mean(axis=0)) # first click adds to exclude _fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix') assert ica_idx in ica.exclude # clicking again removes from exclude _fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix') assert ica_idx not in ica.exclude # test topo click # --------------- _fake_click(fig, fig.axes[1], (0., 0.), xform='data') c_fig = plt.gcf() labels = [ax.get_label() for ax in c_fig.axes] for label in ['topomap', 'image', 'erp', 'spectrum', 'variance']: assert label in labels topomap_ax = c_fig.axes[labels.index('topomap')] title = topomap_ax.get_title() assert (lbl == title) ica.info = None with pytest.raises(RuntimeError, match='fit the ICA'): ica.plot_components(1, ch_type='mag')
def test_plot_ica_components(): """Test plotting of ICA solutions.""" import matplotlib.pyplot as plt res = 8 fast_test = {"res": res, "contours": 0, "sensors": False} raw = _get_raw() ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3) ica_picks = _get_picks(raw) with warnings.catch_warnings(record=True): ica.fit(raw, picks=ica_picks) warnings.simplefilter('always', UserWarning) with warnings.catch_warnings(record=True): for components in [0, [0], [0, 1], [0, 1] * 2, None]: ica.plot_components(components, image_interp='bilinear', colorbar=True, **fast_test) plt.close('all') # test interactive mode (passing 'inst' arg) ica.plot_components([0, 1], image_interp='bilinear', inst=raw, res=16) fig = plt.gcf() # test title click # ---------------- lbl = fig.axes[1].get_label() ica_idx = int(lbl[-3:]) titles = [ax.title for ax in fig.axes] title_pos_midpoint = (titles[1].get_window_extent().extents .reshape((2, 2)).mean(axis=0)) # first click adds to exclude _fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix') assert ica_idx in ica.exclude # clicking again removes from exclude _fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix') assert ica_idx not in ica.exclude # test topo click # --------------- _fake_click(fig, fig.axes[1], (0., 0.), xform='data') c_fig = plt.gcf() labels = [ax.get_label() for ax in c_fig.axes] for l in ['topomap', 'image', 'erp', 'spectrum', 'variance']: assert_true(l in labels) topomap_ax = c_fig.axes[labels.index('topomap')] title = topomap_ax.get_title() assert_true(lbl == title) ica.info = None assert_raises(ValueError, ica.plot_components, 1) assert_raises(RuntimeError, ica.plot_components, 1, ch_type='mag') plt.close('all')
def test_plot_ica_sources(): """Test plotting of ICA panel.""" raw = read_raw_fif(raw_fname).crop(0, 1).load_data() picks = _get_picks(raw) epochs = _get_epochs() raw.pick_channels([raw.ch_names[k] for k in picks]) ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3) ica.fit(raw, picks=ica_picks) ica.exclude = [1] fig = ica.plot_sources(raw) fig.canvas.key_press_event('escape') # Sadly close_event isn't called on Agg backend and the test always passes. assert_array_equal(ica.exclude, [1]) plt.close('all') # dtype can change int->np.int after load, test it explicitly ica.n_components_ = np.int64(ica.n_components_) fig = ica.plot_sources(raw, [1]) # also test mouse clicks data_ax = fig.axes[0] _fake_click(fig, data_ax, [-0.1, 0.9]) # click on y-label raw.info['bads'] = ['MEG 0113'] pytest.raises(RuntimeError, ica.plot_sources, inst=raw) ica.plot_sources(epochs) epochs.info['bads'] = ['MEG 0113'] pytest.raises(RuntimeError, ica.plot_sources, inst=epochs) epochs.info['bads'] = [] ica.plot_sources(epochs.average()) evoked = epochs.average() fig = ica.plot_sources(evoked) # 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 ica.plot_sources(evoked, exclude=[0]) ica.exclude = [0] ica.plot_sources(evoked) # does the same thing ica.labels_ = dict(eog=[0]) ica.labels_['eog/0/crazy-channel'] = [0] ica.plot_sources(evoked) # now with labels pytest.raises(ValueError, ica.plot_sources, 'meeow') plt.close('all')
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')
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')
def test_plot_raw(): """Test plotting of raw data.""" import matplotlib.pyplot as plt raw = _get_raw() events = _get_events() plt.close('all') # ensure all are closed with warnings.catch_warnings(record=True): fig = raw.plot(events=events, show_options=True) # test mouse clicks x = fig.get_axes()[0].lines[1].get_xdata().mean() y = fig.get_axes()[0].lines[1].get_ydata().mean() data_ax = fig.get_axes()[0] _fake_click(fig, data_ax, [x, y], xform='data') # mark a bad channel _fake_click(fig, data_ax, [x, y], xform='data') # unmark a bad channel _fake_click(fig, data_ax, [0.5, 0.999]) # click elsewhere in 1st axes _fake_click(fig, data_ax, [-0.1, 0.9]) # click on y-label _fake_click(fig, fig.get_axes()[1], [0.5, 0.5]) # change time _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change channels _fake_click(fig, fig.get_axes()[3], [0.5, 0.5]) # open SSP window fig.canvas.button_press_event(1, 1, 1) # outside any axes fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up # sadly these fail when no renderer is used (i.e., when using Agg): # ssp_fig = set(plt.get_fignums()) - set([fig.number]) # assert_equal(len(ssp_fig), 1) # ssp_fig = plt.figure(list(ssp_fig)[0]) # ax = ssp_fig.get_axes()[0] # only one axis is used # t = [c for c in ax.get_children() if isinstance(c, # matplotlib.text.Text)] # pos = np.array(t[0].get_position()) + 0.01 # _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data') # off # _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data') # on # test keypresses fig.canvas.key_press_event('escape') fig.canvas.key_press_event('down') fig.canvas.key_press_event('up') fig.canvas.key_press_event('right') fig.canvas.key_press_event('left') fig.canvas.key_press_event('o') fig.canvas.key_press_event('-') fig.canvas.key_press_event('+') fig.canvas.key_press_event('=') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event('pagedown') fig.canvas.key_press_event('home') fig.canvas.key_press_event('end') fig.canvas.key_press_event('?') fig.canvas.key_press_event('f11') fig.canvas.key_press_event('escape') # Color setting assert_raises(KeyError, raw.plot, event_color={0: 'r'}) assert_raises(TypeError, raw.plot, event_color={'foo': 'r'}) annot = Annotations([10, 10 + raw.first_samp / raw.info['sfreq']], [10, 10], ['test', 'test'], raw.info['meas_date']) raw.annotations = annot fig = plot_raw(raw, events=events, event_color={-1: 'r', 998: 'b'}) plt.close('all') for order in ['position', 'selection', range(len(raw.ch_names))[::-1], [1, 2, 4, 6]]: fig = raw.plot(order=order) x = fig.get_axes()[0].lines[1].get_xdata()[10] y = fig.get_axes()[0].lines[1].get_ydata()[10] _fake_click(fig, data_ax, [x, y], xform='data') # mark bad fig.canvas.key_press_event('down') # change selection _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change channels if order == 'position': # test clicking topo to change selection sel_fig = plt.figure(1) topo_ax = sel_fig.axes[1] _fake_click(sel_fig, topo_ax, [-0.425, 0.20223853], xform='data') fig.canvas.key_press_event('down') fig.canvas.key_press_event('up') fig.canvas.scroll_event(0.5, 0.5, -1) # scroll down fig.canvas.scroll_event(0.5, 0.5, 1) # scroll up plt.close('all')
def test_plot_sensors(): """Test plotting of sensor array.""" raw = _get_raw() plt.close('all') fig = raw.plot_sensors('3d') _fake_click(fig, fig.gca(), (-0.08, 0.67)) raw.plot_sensors('topomap', ch_type='mag', show_names=['MEG 0111', 'MEG 0131']) plt.close('all') ax = plt.subplot(111) raw.plot_sensors(ch_groups='position', axes=ax) raw.plot_sensors(ch_groups='selection', to_sphere=False) raw.plot_sensors(ch_groups=[[0, 1, 2], [3, 4]]) pytest.raises(ValueError, raw.plot_sensors, ch_groups='asd') pytest.raises(TypeError, plot_sensors, raw) # needs to be info pytest.raises(ValueError, plot_sensors, raw.info, kind='sasaasd') plt.close('all') fig, sels = raw.plot_sensors('select', show_names=True) ax = fig.axes[0] # Click with no sensors _fake_click(fig, ax, (0., 0.), xform='data') _fake_click(fig, ax, (0, 0.), xform='data', kind='release') assert len(fig.lasso.selection) == 0 # Lasso with 1 sensor _fake_click(fig, ax, (-0.5, 0.5), xform='data') plt.draw() _fake_click(fig, ax, (0., 0.5), xform='data', kind='motion') _fake_click(fig, ax, (0., 0.), xform='data', kind='motion') fig.canvas.key_press_event('control') _fake_click(fig, ax, (-0.5, 0.), xform='data', kind='release') assert len(fig.lasso.selection) == 1 _fake_click(fig, ax, (-0.09, -0.43), xform='data') # single selection assert len(fig.lasso.selection) == 2 _fake_click(fig, ax, (-0.09, -0.43), xform='data') # deselect assert len(fig.lasso.selection) == 1 plt.close('all')
def test_plot(): """Test TFR plotting.""" data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.plot([1, 2], title='title', colorbar=False, mask=np.ones(tfr.data.shape[1:], bool)) plt.close('all') ax = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (1, 1)) ax3 = plt.subplot2grid((2, 2), (0, 1)) tfr.plot(picks=[0, 1, 2], axes=[ax, ax2, ax3]) plt.close('all') tfr.plot([1, 2], title='title', colorbar=False, exclude='bads') plt.close('all') tfr.plot_topo(picks=[1, 2]) plt.close('all') fig = tfr.plot(picks=[1], cmap='RdBu_r') # interactive mode on by default fig.canvas.key_press_event('up') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('down') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('+') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('-') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pagedown') 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')
def test_plot(): """Test TFR plotting.""" data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.plot([1, 2], title='title', colorbar=False, mask=np.ones(tfr.data.shape[1:], bool)) plt.close('all') ax = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (1, 1)) ax3 = plt.subplot2grid((2, 2), (0, 1)) tfr.plot(picks=[0, 1, 2], axes=[ax, ax2, ax3]) plt.close('all') tfr.plot([1, 2], title='title', colorbar=False, exclude='bads') plt.close('all') tfr.plot_topo(picks=[1, 2]) plt.close('all') fig = tfr.plot(picks=[1], cmap='RdBu_r') # interactive mode on by default 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')
def test_plot_raw(): """Test plotting of raw data.""" raw = _get_raw() raw.info['lowpass'] = 10. # allow heavy decim during plotting events = _get_events() plt.close('all') # ensure all are closed assert len(plt.get_fignums()) == 0 fig = raw.plot(events=events, order=[1, 7, 3], group_by='original') assert len(plt.get_fignums()) == 1 # make sure fig._mne_params is present assert isinstance(fig._mne_params, dict) # test mouse clicks x = fig.get_axes()[0].lines[1].get_xdata().mean() y = fig.get_axes()[0].lines[1].get_ydata().mean() data_ax = fig.axes[0] _fake_click(fig, data_ax, [x, y], xform='data') # mark a bad channel _fake_click(fig, data_ax, [x, y], xform='data') # unmark a bad channel _fake_click(fig, data_ax, [0.5, 0.999]) # click elsewhere in 1st axes _fake_click(fig, data_ax, [-0.1, 0.9]) # click on y-label _fake_click(fig, fig.get_axes()[1], [0.5, 0.5]) # change time _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change channels assert len(plt.get_fignums()) == 1 # open SSP window _fake_click(fig, fig.get_axes()[-1], [0.5, 0.5]) _fake_click(fig, fig.get_axes()[-1], [0.5, 0.5], kind='release') assert len(plt.get_fignums()) == 2 ssp_fig = plt.figure(plt.get_fignums()[-1]) fig.canvas.button_press_event(1, 1, 1) # outside any axes fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up ax = ssp_fig.get_axes()[0] # only one axis is used assert _proj_status(ax) == [True] * 3 t = [c for c in ax.get_children() if isinstance(c, matplotlib.text.Text)] pos = np.array(t[0].get_position()) + 0.01 _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data') # off assert _proj_status(ax) == [False, True, True] _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data') # on assert _proj_status(ax) == [True] * 3 _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5]) # all off _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5], kind='release') assert _proj_status(ax) == [False] * 3 _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5]) # all on _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5], kind='release') assert _proj_status(ax) == [True] * 3 # test keypresses # test for group_by='original' for key in [ 'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'd', 'd', 'pageup', 'pagedown', 'home', 'end', '?', 'f11', 'z', 'escape' ]: fig.canvas.key_press_event(key) # test for group_by='selection' fig = plot_raw(raw, events=events, group_by='selection') for key in [ 'b', 'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'd', 'd', 'pageup', 'pagedown', 'home', 'end', '?', 'f11', 'b', 'z', 'escape' ]: fig.canvas.key_press_event(key) # test zen mode fig = plot_raw(raw, show_scrollbars=False) # Color setting pytest.raises(KeyError, raw.plot, event_color={0: 'r'}) pytest.raises(TypeError, raw.plot, event_color={'foo': 'r'}) annot = Annotations([10, 10 + raw.first_samp / raw.info['sfreq']], [10, 10], ['test', 'test'], raw.info['meas_date']) with pytest.warns(RuntimeWarning, match='outside data range'): raw.set_annotations(annot) fig = plot_raw(raw, events=events, event_color={-1: 'r', 998: 'b'}) plt.close('all') for group_by, order in zip( ['position', 'selection'], [np.arange(len(raw.ch_names))[::-3], [1, 2, 4, 6]]): with pytest.warns(None): # sometimes projection fig = raw.plot(group_by=group_by, order=order) x = fig.get_axes()[0].lines[1].get_xdata()[10] y = fig.get_axes()[0].lines[1].get_ydata()[10] with pytest.warns(None): # old mpl (at least 2.0) can warn _fake_click(fig, data_ax, [x, y], xform='data') # mark bad fig.canvas.key_press_event('down') # change selection _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change channels sel_fig = plt.figure(1) topo_ax = sel_fig.axes[1] _fake_click(sel_fig, topo_ax, [-0.425, 0.20223853], xform='data') fig.canvas.key_press_event('down') fig.canvas.key_press_event('up') fig.canvas.scroll_event(0.5, 0.5, -1) # scroll down fig.canvas.scroll_event(0.5, 0.5, 1) # scroll up _fake_click(sel_fig, topo_ax, [-0.5, 0.], xform='data') _fake_click(sel_fig, topo_ax, [0.5, 0.], xform='data', kind='motion') _fake_click(sel_fig, topo_ax, [0.5, 0.5], xform='data', kind='motion') _fake_click(sel_fig, topo_ax, [-0.5, 0.5], xform='data', kind='release') plt.close('all') # test if meas_date has only one element raw.info['meas_date'] = (raw.info['meas_date'][0], 0) annot = Annotations([1 + raw.first_samp / raw.info['sfreq']], [5], ['bad']) with pytest.warns(RuntimeWarning, match='outside data range'): raw.set_annotations(annot) with pytest.warns(None): # sometimes projection raw.plot(group_by='position', order=np.arange(8)) for fig_num in plt.get_fignums(): fig = plt.figure(fig_num) if hasattr(fig, 'radio'): # Get access to selection fig. break for key in ['down', 'up', 'escape']: fig.canvas.key_press_event(key) plt.close('all')
def test_plot_raw(): """Test plotting of raw data.""" import matplotlib.pyplot as plt raw = _get_raw() raw.info['lowpass'] = 10. # allow heavy decim during plotting events = _get_events() plt.close('all') # ensure all are closed with warnings.catch_warnings(record=True): fig = raw.plot(events=events, show_options=True, order=[1, 7, 3], group_by='original') # test mouse clicks x = fig.get_axes()[0].lines[1].get_xdata().mean() y = fig.get_axes()[0].lines[1].get_ydata().mean() data_ax = fig.axes[0] _fake_click(fig, data_ax, [x, y], xform='data') # mark a bad channel _fake_click(fig, data_ax, [x, y], xform='data') # unmark a bad channel _fake_click(fig, data_ax, [0.5, 0.999]) # click elsewhere in 1st axes _fake_click(fig, data_ax, [-0.1, 0.9]) # click on y-label _fake_click(fig, fig.get_axes()[1], [0.5, 0.5]) # change time _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change channels _fake_click(fig, fig.get_axes()[3], [0.5, 0.5]) # open SSP window fig.canvas.button_press_event(1, 1, 1) # outside any axes fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up # sadly these fail when no renderer is used (i.e., when using Agg): # ssp_fig = set(plt.get_fignums()) - set([fig.number]) # assert_equal(len(ssp_fig), 1) # ssp_fig = plt.figure(list(ssp_fig)[0]) # ax = ssp_fig.get_axes()[0] # only one axis is used # t = [c for c in ax.get_children() if isinstance(c, # matplotlib.text.Text)] # pos = np.array(t[0].get_position()) + 0.01 # _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data') # off # _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data') # on # test keypresses for key in ['down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup', 'pagedown', 'home', 'end', '?', 'f11', 'escape']: fig.canvas.key_press_event(key) fig = plot_raw(raw, events=events, group_by='selection') for key in ['b', 'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup', 'pagedown', 'home', 'end', '?', 'f11', 'b', 'escape']: fig.canvas.key_press_event(key) # Color setting assert_raises(KeyError, raw.plot, event_color={0: 'r'}) assert_raises(TypeError, raw.plot, event_color={'foo': 'r'}) annot = Annotations([10, 10 + raw.first_samp / raw.info['sfreq']], [10, 10], ['test', 'test'], raw.info['meas_date']) raw.annotations = annot fig = plot_raw(raw, events=events, event_color={-1: 'r', 998: 'b'}) plt.close('all') for group_by, order in zip(['position', 'selection'], [np.arange(len(raw.ch_names))[::-3], [1, 2, 4, 6]]): fig = raw.plot(group_by=group_by, order=order) x = fig.get_axes()[0].lines[1].get_xdata()[10] y = fig.get_axes()[0].lines[1].get_ydata()[10] _fake_click(fig, data_ax, [x, y], xform='data') # mark bad fig.canvas.key_press_event('down') # change selection _fake_click(fig, fig.get_axes()[2], [0.5, 0.5]) # change channels sel_fig = plt.figure(1) topo_ax = sel_fig.axes[1] _fake_click(sel_fig, topo_ax, [-0.425, 0.20223853], xform='data') fig.canvas.key_press_event('down') fig.canvas.key_press_event('up') fig.canvas.scroll_event(0.5, 0.5, -1) # scroll down fig.canvas.scroll_event(0.5, 0.5, 1) # scroll up _fake_click(sel_fig, topo_ax, [-0.5, 0.], xform='data') _fake_click(sel_fig, topo_ax, [0.5, 0.], xform='data', kind='motion') _fake_click(sel_fig, topo_ax, [0.5, 0.5], xform='data', kind='motion') _fake_click(sel_fig, topo_ax, [-0.5, 0.5], xform='data', kind='release') plt.close('all') # test if meas_date has only one element raw.info['meas_date'] = np.array([raw.info['meas_date'][0]], dtype=np.int32) raw.annotations = Annotations([1 + raw.first_samp / raw.info['sfreq']], [5], ['bad']) raw.plot(group_by='position', order=np.arange(8)) for fig_num in plt.get_fignums(): fig = plt.figure(fig_num) if hasattr(fig, 'radio'): # Get access to selection fig. break for key in ['down', 'up', 'escape']: fig.canvas.key_press_event(key) plt.close('all')
def _annotation_helper(raw, events=False): """Test interactive annotations.""" # Some of our checks here require modern mpl to work properly mpl_good_enough = LooseVersion(matplotlib.__version__) >= '2.0' n_anns = len(raw.annotations) plt.close('all') if events: events = np.array([[raw.first_samp + 100, 0, 1], [raw.first_samp + 300, 0, 3]]) n_events = len(events) else: events = None n_events = 0 fig = raw.plot(events=events) assert len(plt.get_fignums()) == 1 data_ax = fig.axes[0] fig.canvas.key_press_event('a') # annotation mode assert len(plt.get_fignums()) == 2 # +2 from the scale bars n_scale = 2 assert len(fig.axes[0].texts) == n_anns + n_events + n_scale # modify description ann_fig = plt.gcf() for key in ' test': ann_fig.canvas.key_press_event(key) ann_fig.canvas.key_press_event('enter') ann_fig = plt.gcf() # XXX: _fake_click raises an error on Agg backend _annotation_radio_clicked('', ann_fig.radio, data_ax.selector) # draw annotation fig.canvas.key_press_event('p') # use snap mode _fake_click(fig, data_ax, [1., 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='release') assert len(raw.annotations.onset) == n_anns + 1 assert len(raw.annotations.duration) == n_anns + 1 assert len(raw.annotations.description) == n_anns + 1 assert raw.annotations.description[n_anns] == 'BAD_ test' assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale onset = raw.annotations.onset[n_anns] want_onset = _sync_onset(raw, 1., inverse=True) assert_allclose(onset, want_onset) assert_allclose(raw.annotations.duration[n_anns], 4.) # hover event _fake_click(fig, data_ax, [4.5, 1.], xform='data', button=None, kind='motion') _fake_click(fig, data_ax, [4.7, 1.], xform='data', button=None, kind='motion') # modify annotation from end _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [2.5, 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [2.5, 1.], xform='data', button=1, kind='release') if mpl_good_enough: assert raw.annotations.onset[n_anns] == onset assert_allclose(raw.annotations.duration[n_anns], 1.5) # modify annotation from beginning _fake_click(fig, data_ax, [1., 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [0.5, 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [0.5, 1.], xform='data', button=1, kind='release') if mpl_good_enough: assert_allclose(raw.annotations.onset[n_anns], onset - 0.5, atol=1e-10) assert_allclose(raw.annotations.duration[n_anns], 2.0) assert len(raw.annotations.onset) == n_anns + 1 assert len(raw.annotations.duration) == n_anns + 1 assert len(raw.annotations.description) == n_anns + 1 assert raw.annotations.description[n_anns] == 'BAD_ test' assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale fig.canvas.key_press_event('shift+right') assert len(fig.axes[0].texts) == n_scale fig.canvas.key_press_event('shift+left') assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale # draw another annotation merging the two _fake_click(fig, data_ax, [5.5, 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [2., 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [2., 1.], xform='data', button=1, kind='release') # delete the annotation assert len(raw.annotations.onset) == n_anns + 1 assert len(raw.annotations.duration) == n_anns + 1 assert len(raw.annotations.description) == n_anns + 1 if mpl_good_enough: assert_allclose(raw.annotations.onset[n_anns], onset - 0.5, atol=1e-10) assert_allclose(raw.annotations.duration[n_anns], 5.0) assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale # Delete _fake_click(fig, data_ax, [1.5, 1.], xform='data', button=3, kind='press') fig.canvas.key_press_event('a') # exit annotation mode assert len(raw.annotations.onset) == n_anns assert len(fig.axes[0].texts) == n_anns + n_events + n_scale fig.canvas.key_press_event('shift+right') assert len(fig.axes[0].texts) == n_scale fig.canvas.key_press_event('shift+left') assert len(fig.axes[0].texts) == n_anns + n_events + n_scale plt.close('all')
def test_plot_sensors(): """Test plotting of sensor array.""" import matplotlib.pyplot as plt raw = _get_raw() fig = raw.plot_sensors('3d') _fake_click(fig, fig.gca(), (-0.08, 0.67)) raw.plot_sensors('topomap', ch_type='mag', show_names=['MEG 0111', 'MEG 0131']) plt.close('all') ax = plt.subplot(111) raw.plot_sensors(ch_groups='position', axes=ax) raw.plot_sensors(ch_groups='selection', to_sphere=False) raw.plot_sensors(ch_groups=[[0, 1, 2], [3, 4]]) assert_raises(ValueError, raw.plot_sensors, ch_groups='asd') assert_raises(TypeError, plot_sensors, raw) # needs to be info assert_raises(ValueError, plot_sensors, raw.info, kind='sasaasd') plt.close('all') fig, sels = raw.plot_sensors('select', show_names=True) ax = fig.axes[0] # Click with no sensors _fake_click(fig, ax, (0., 0.), xform='data') _fake_click(fig, ax, (0, 0.), xform='data', kind='release') assert_equal(len(fig.lasso.selection), 0) # Lasso with 1 sensor _fake_click(fig, ax, (-0.5, 0.5), xform='data') plt.draw() _fake_click(fig, ax, (0., 0.5), xform='data', kind='motion') _fake_click(fig, ax, (0., 0.), xform='data', kind='motion') fig.canvas.key_press_event('control') _fake_click(fig, ax, (-0.5, 0.), xform='data', kind='release') assert_equal(len(fig.lasso.selection), 1) _fake_click(fig, ax, (-0.09, -0.43), xform='data') # single selection assert_equal(len(fig.lasso.selection), 2) _fake_click(fig, ax, (-0.09, -0.43), xform='data') # deselect assert_equal(len(fig.lasso.selection), 1) plt.close('all')
def test_plot_sensors(raw): """Test plotting of sensor array.""" plt.close('all') fig = raw.plot_sensors('3d') _fake_click(fig, fig.gca(), (-0.08, 0.67)) raw.plot_sensors('topomap', ch_type='mag', show_names=['MEG 0111', 'MEG 0131']) plt.close('all') ax = plt.subplot(111) raw.plot_sensors(ch_groups='position', axes=ax) raw.plot_sensors(ch_groups='selection', to_sphere=False) raw.plot_sensors(ch_groups=[[0, 1, 2], [3, 4]]) pytest.raises(ValueError, raw.plot_sensors, ch_groups='asd') pytest.raises(TypeError, plot_sensors, raw) # needs to be info pytest.raises(ValueError, plot_sensors, raw.info, kind='sasaasd') plt.close('all') fig, sels = raw.plot_sensors('select', show_names=True) ax = fig.axes[0] # Click with no sensors _fake_click(fig, ax, (0., 0.), xform='data') _fake_click(fig, ax, (0, 0.), xform='data', kind='release') assert fig.lasso.selection == [] # Lasso with 1 sensor (upper left) _fake_click(fig, ax, (0, 1), xform='ax') fig.canvas.draw() assert fig.lasso.selection == [] _fake_click(fig, ax, (0.65, 1), xform='ax', kind='motion') _fake_click(fig, ax, (0.65, 0.7), xform='ax', kind='motion') fig.canvas.key_press_event('control') _fake_click(fig, ax, (0, 0.7), xform='ax', kind='release') assert fig.lasso.selection == ['MEG 0121'] # check that point appearance changes fc = fig.lasso.collection.get_facecolors() ec = fig.lasso.collection.get_edgecolors() assert (fc[:, -1] == [0.5, 1., 0.5]).all() assert (ec[:, -1] == [0.25, 1., 0.25]).all() _fake_click(fig, ax, (0.7, 1), xform='ax', kind='motion') xy = ax.collections[0].get_offsets() _fake_click(fig, ax, xy[2], xform='data') # single selection assert fig.lasso.selection == ['MEG 0121', 'MEG 0131'] _fake_click(fig, ax, xy[2], xform='data') # deselect assert fig.lasso.selection == ['MEG 0121'] plt.close('all') raw.info['dev_head_t'] = None # like empty room with pytest.warns(RuntimeWarning, match='identity'): raw.plot_sensors()
def _annotation_helper(raw): """Helper for testing interactive annotations.""" import matplotlib.pyplot as plt n_anns = 0 if raw.annotations is None else len(raw.annotations.onset) fig = raw.plot() data_ax = fig.axes[0] fig.canvas.key_press_event('a') # annotation mode # modify description ann_fig = plt.gcf() for key in ' test': ann_fig.canvas.key_press_event(key) ann_fig.canvas.key_press_event('enter') ann_fig = plt.gcf() # XXX: _fake_click raises an error on Agg backend _annotation_radio_clicked('', ann_fig.radio, data_ax.selector) # draw annotation _fake_click(fig, data_ax, [1., 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='release') # hover event _fake_click(fig, data_ax, [4.5, 1.], xform='data', button=None, kind='motion') _fake_click(fig, data_ax, [4.7, 1.], xform='data', button=None, kind='motion') # modify annotation from end _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [2.5, 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [2.5, 1.], xform='data', button=1, kind='release') # modify annotation from beginning _fake_click(fig, data_ax, [1., 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [1.1, 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [1.1, 1.], xform='data', button=1, kind='release') assert_equal(len(raw.annotations.onset), n_anns + 1) assert_equal(len(raw.annotations.duration), n_anns + 1) assert_equal(len(raw.annotations.description), n_anns + 1) assert_equal(raw.annotations.description[n_anns], 'BAD test') # draw another annotation merging the two _fake_click(fig, data_ax, [5.5, 1.], xform='data', button=1, kind='press') _fake_click(fig, data_ax, [2., 1.], xform='data', button=1, kind='motion') _fake_click(fig, data_ax, [2., 1.], xform='data', button=1, kind='release') # delete the annotation _fake_click(fig, data_ax, [1.5, 1.], xform='data', button=3, kind='press') fig.canvas.key_press_event('a') # exit annotation mode assert_equal(len(raw.annotations.onset), n_anns) assert_equal(len(raw.annotations.duration), n_anns) assert_equal(len(raw.annotations.description), n_anns) plt.close('all')