def test_plot_misc_auto(browser_backend): """Test plotting of data with misc auto scaling.""" data = np.random.RandomState(0).randn(1, 1000) raw = RawArray(data, create_info(1, 1000., 'misc')) raw.plot() raw = RawArray(data, create_info(1, 1000., 'dipole')) raw.plot(order=[0]) # plot, even though it's not "data" browser_backend._close_all()
def test_theme_colors(pg_backend, theme, monkeypatch, tmp_path): """Test that theme colors propagate properly.""" darkdetect = pytest.importorskip('darkdetect') monkeypatch.setenv('_MNE_FAKE_HOME_DIR', str(tmp_path)) monkeypatch.delenv('MNE_BROWSER_THEME', raising=False) raw = RawArray(np.zeros((1, 1000)), create_info(1, 1000., 'eeg')) fig = raw.plot(theme=theme) is_dark = _qt_is_dark(fig) if theme == 'dark': assert is_dark, theme elif theme == 'light': assert not is_dark, theme else: got_dark = darkdetect.theme().lower() == 'dark' assert is_dark is got_dark def assert_correct_darkness(widget, want_dark): __tracebackhide__ = True # noqa # This should work, but it just picks up the parent in the errant case! bgcolor = widget.palette().color(widget.backgroundRole()).getRgbF()[:3] dark = rgb_to_hls(*bgcolor)[1] < 0.5 assert dark == want_dark, f'{widget} dark={dark} want_dark={want_dark}' # ... so we use a more direct test colors = _pixmap_to_ndarray(widget.grab())[:, :, :3] dark = colors.mean() < 0.5 assert dark == want_dark, f'{widget} dark={dark} want_dark={want_dark}' for widget in (fig.mne.toolbar, fig.statusBar()): assert_correct_darkness(widget, is_dark)
def test_scale_bar(browser_backend): """Test scale bar for raw.""" ismpl = browser_backend.name == 'matplotlib' sfreq = 1000. t = np.arange(10000) / sfreq data = np.sin(2 * np.pi * 10. * t) # ± 1000 fT, 400 fT/cm, 20 µV data = data * np.array([[1000e-15, 400e-13, 20e-6]]).T info = create_info(3, sfreq, ('mag', 'grad', 'eeg')) raw = RawArray(data, info) fig = raw.plot() texts = fig._get_scale_bar_texts() assert len(texts) == 3 # ch_type scale-bars wants = ('800.0 fT/cm', '2000.0 fT', '40.0 µV') assert texts == wants if ismpl: # 1 green vline, 3 data, 3 scalebars assert len(fig.mne.ax_main.lines) == 7 else: assert len(fig.mne.scalebars) == 3 for data, bar in zip(fig.mne.traces, fig.mne.scalebars.values()): y = data.get_ydata() y_lims = [y.min(), y.max()] bar_lims = bar.get_ydata() assert_allclose(y_lims, bar_lims, atol=1e-4)
def test_render_mne_qt_browser(tmp_path, browser_backend): """Test adding a mne_qt_browser (and matplotlib) raw plot.""" report = Report() info = create_info(1, 1000., 'eeg') data = np.zeros((1, 1000)) raw = RawArray(data, info) fig = raw.plot() name = fig.__class__.__name__ if browser_backend.name == 'matplotlib': assert 'MNEBrowseFigure' in name else: assert 'MNEQtBrowser' in name or 'PyQtGraphBrowser' in name report.add_figure(fig, title='raw')
def test_theme_colors(pg_backend, theme, monkeypatch, tmp_path): """Test that theme colors propagate properly.""" darkdetect = pytest.importorskip('darkdetect') monkeypatch.setenv('_MNE_FAKE_HOME_DIR', str(tmp_path)) monkeypatch.delenv('MNE_BROWSER_THEME', raising=False) # make it seem like the system is always in light mode monkeypatch.setattr(darkdetect, 'theme', lambda: 'light') raw = RawArray(np.zeros((1, 1000)), create_info(1, 1000., 'eeg')) _, api = _check_qt_version(return_api=True) if api in ('PyQt6', 'PySide6') and theme == 'dark': ctx = pytest.warns(RuntimeWarning, match='not yet supported') return_early = True else: ctx = nullcontext() return_early = False with ctx: fig = raw.plot(theme=theme) if return_early: return # we could add a ton of conditionals below, but KISS is_dark = _qt_is_dark(fig) # on Darwin these checks get complicated, so don't bother for now if sys.platform != 'darwin': if theme == 'dark': assert is_dark, theme elif theme == 'light': assert not is_dark, theme else: got_dark = darkdetect.theme().lower() == 'dark' assert is_dark is got_dark def assert_correct_darkness(widget, want_dark): __tracebackhide__ = True # noqa # This should work, but it just picks up the parent in the errant case! bgcolor = widget.palette().color(widget.backgroundRole()).getRgbF()[:3] dark = rgb_to_hls(*bgcolor)[1] < 0.5 assert dark == want_dark, f'{widget} dark={dark} want_dark={want_dark}' # ... so we use a more direct test colors = _pixmap_to_ndarray(widget.grab())[:, :, :3] dark = colors.mean() < 0.5 assert dark == want_dark, f'{widget} dark={dark} want_dark={want_dark}' for widget in (fig.mne.toolbar, fig.statusBar()): assert_correct_darkness(widget, is_dark)
def test_scale_bar(): """Test scale bar for raw.""" sfreq = 1000. t = np.arange(10000) / sfreq data = np.sin(2 * np.pi * 10. * t) # +/- 1000 fT, 400 fT/cm, 20 uV data = data * np.array([[1000e-15, 400e-13, 20e-6]]).T info = create_info(3, sfreq, ('mag', 'grad', 'eeg')) raw = RawArray(data, info) fig = raw.plot() ax = fig.axes[0] assert len(ax.texts) == 3 # our labels for text, want in zip(ax.texts, ('800.0 fT/cm', '2000.0 fT', '40.0 uV')): assert text.get_text().strip() == want assert len(ax.lines) == 8 # green, data, nan, bars for data, bar in zip(ax.lines[1:4], ax.lines[5:8]): y = data.get_ydata() y_lims = [y.min(), y.max()] bar_lims = bar.get_ydata() assert_allclose(y_lims, bar_lims, atol=1e-4) plt.close('all')
def test_scale_bar(): """Test scale bar for raw.""" sfreq = 1000. t = np.arange(10000) / sfreq data = np.sin(2 * np.pi * 10. * t) # ± 1000 fT, 400 fT/cm, 20 µV data = data * np.array([[1000e-15, 400e-13, 20e-6]]).T info = create_info(3, sfreq, ('mag', 'grad', 'eeg')) raw = RawArray(data, info) fig = raw.plot() ax = fig.mne.ax_main assert len(ax.texts) == 4 # empty vline-text + ch_type scale-bars texts = tuple(t.get_text().strip() for t in ax.texts) wants = ('', '800.0 fT/cm', '2000.0 fT', '40.0 µV') assert texts == wants assert len(ax.lines) == 7 # 1 green vline, 3 data, 3 scalebars for data, bar in zip(fig.mne.traces, fig.mne.scalebars.values()): y = data.get_ydata() y_lims = [y.min(), y.max()] bar_lims = bar.get_ydata() assert_allclose(y_lims, bar_lims, atol=1e-4)
def test_scalings_int(browser_backend): """Test that auto scalings access samples using integers.""" raw = RawArray(np.zeros((1, 500)), create_info(1, 1000., 'eeg')) raw.plot(scalings='auto')
def test_plot_misc_auto(): """Test plotting of data with misc auto scaling.""" data = np.random.RandomState(0).randn(1, 1000) raw = RawArray(data, create_info(1, 1000., 'misc')) raw.plot() plt.close('all')
data[ev_start:ev_start + len(sim)] += sim * 10 sim = simulate_hfo(sfreq, freq, numcycles)[0] ev_start = 7 * sfreq data[ev_start:ev_start + len(sim)] += sim * 10 # convert the data into mne-python # note: the channel names are made up and the channel types are just # set to 'seeg' for the sake of the example ch_names = ['A1'] info = create_info(sfreq=sfreq, ch_names=ch_names, ch_types='seeg') raw = RawArray(data=data[np.newaxis, :], info=info) ############################################################################### # Let's plot the data and see what it looks like raw.plot() ############################################################################### # Detect HFOs # ----------- # All detectors inherit from the base class ``mne_hfo.base.Detector``, # which inherits from the :class:`sklearn.base.BaseEstimator` class. # To run any estimator, one instantiates it along with the hyper-parameters, # and then calls the ``fit`` function. Afterwards, detected HFOs are available # in the various data structures. The recommended usage is the DataFrame, which # is accessible via the ``mne_hfo.base.Detector.hfo_df`` property. kwargs = { 'threshold': 3, # threshold for "significance" 'win_size': 100, # window size in samples 'overlap': 0.25 # overlap in percentage relative to the window size
ext_signal = np.vstack([_bandpass_filter(raw, lowcut=f-freq_band, highcut=f+freq_band) for f in frequencies]) ############################################################################### # Creating an MNE Raw object from the extended signal and plot it info = create_info( ch_names=sum(list(map(lambda s: [ch+s for ch in raw.ch_names], ["-13Hz", "-17Hz", "-21Hz"])), []), ch_types=['eeg'] * 24, sfreq=sfreq) raw_ext = RawArray(ext_signal, info) raw_ext.plot(duration=n_seconds, start=14, n_channels=24, scalings={'eeg': 5e-4}, color={'eeg': 'steelblue'}) ############################################################################### # Building Epochs and plotting 3 s of the signal from electrode Oz for a trial epochs = Epochs(raw_ext, events, event_id, tmin=2, tmax=5, baseline=None) n_seconds = 3 time = np.linspace(0, n_seconds, n_seconds * sfreq, endpoint=False)[np.newaxis, :] channels = range(0, len(raw_ext.ch_names), len(raw.ch_names)) plt.figure(figsize=(7, 5)) for f, c in zip(frequencies, channels): plt.plot(epochs.get_data()[5, c, :].T, label=str(int(f))+' Hz') plt.xlabel("Time (s)") plt.ylabel(r"Oz after filtering ($\mu$V)")
ch_names, sfreq = read_header(fname) ch_count = len(ch_names) duration = signal_raw.shape[1] / sfreq ############################################################################### # Channel space # ------------- # Plot signal X ch_info = create_info(ch_names=ch_names, ch_types=['eeg'] * ch_count, sfreq=sfreq) ch_info.set_montage('standard_1020') signal = RawArray(signal_raw, ch_info, verbose=False) signal.plot(duration=duration, start=0, n_channels=ch_count, scalings={'eeg': 3e1}, color={'eeg': 'steelblue'}, title='Original EEG signal', show_scalebars=False) ############################################################################### # AJDC: Second-Order Statistics (SOS)-based BSS, diagonalizing cospectra # ---------------------------------------------------------------------- # Compute and diagonalize Fourier cospectral matrices between 1 and 32 Hz window, overlap = sfreq, 0.5 fmin, fmax = 1, 32 ajdc = AJDC(window=window, overlap=overlap, fmin=fmin, fmax=fmax, fs=sfreq, expl_var=0.99) ajdc.fit(signal_raw[np.newaxis, np.newaxis, ...]) freqs = ajdc.freqs_
n_signal = eeg_signal.shape[0] # the number of signals n_sample = eeg_signal.shape[1] # dimension of each signal # Normalize the data to be run b = eeg_signal b = ((b.T - np.mean(b, axis=1)) / np.std(b, axis=1)).T # Define the parameters # 128 kernels with size of 201 size_kernel = [2, 61] # size_kernel = [2, 51] ch_names = ['EEG%03d' % i for i in range(n_signal)] info = create_info(ch_names, sfreq=sfreq, ch_types='eeg') raw = RawArray(eeg_signal * 1e-6, info) raw.plot(scalings=dict(eeg='auto'), duration=300) # Optim options max_it = 200 # the number of iterations tol = np.float64(1e-3) # the stop threshold for the algorithm # RUN THE ALGORITHM [d, z, Dz, list_obj_val, list_obj_val_filter, list_obj_val_z, reconstr_err] = \ CSC.learn_conv_sparse_coder(b, size_kernel, max_it, tol, random_state=42) plt.figure() plt.plot(d[0, :]) plt.plot(d[1, :]) plt.show() end = time.clock()
def test_plot_misc_auto(browse_backend): """Test plotting of data with misc auto scaling.""" data = np.random.RandomState(0).randn(1, 1000) raw = RawArray(data, create_info(1, 1000., 'misc')) raw.plot() browse_backend._close_all()