def test_get_coef_multiclass_full(n_classes, n_channels, n_times): """Test a full example with pattern extraction.""" from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.model_selection import StratifiedKFold data = np.zeros((10 * n_classes, n_channels, n_times)) # Make only the first channel informative for ii in range(n_classes): data[ii * 10:(ii + 1) * 10, 0] = ii events = np.zeros((len(data), 3), int) events[:, 0] = np.arange(len(events)) events[:, 2] = data[:, 0, 0] info = create_info(n_channels, 1000., 'eeg') epochs = EpochsArray(data, info, events, tmin=0) clf = make_pipeline( Scaler(epochs.info), Vectorizer(), LinearModel(LogisticRegression(random_state=0, multi_class='ovr')), ) scorer = 'roc_auc_ovr_weighted' time_gen = GeneralizingEstimator(clf, scorer, verbose=True) X = epochs.get_data() y = epochs.events[:, 2] n_splits = 3 cv = StratifiedKFold(n_splits=n_splits) scores = cross_val_multiscore(time_gen, X, y, cv=cv, verbose=True) want = (n_splits, ) if n_times > 1: want += (n_times, n_times) assert scores.shape == want assert_array_less(0.8, scores) clf.fit(X, y) patterns = get_coef(clf, 'patterns_', inverse_transform=True) assert patterns.shape == (n_classes, n_channels, n_times) assert_allclose(patterns[:, 1:], 0., atol=1e-7) # no other channels useful
def test_decim(): """Test evoked decimation.""" rng = np.random.RandomState(0) n_epochs, n_channels, n_times = 5, 10, 20 dec_1, dec_2 = 2, 3 decim = dec_1 * dec_2 sfreq = 1000. sfreq_new = sfreq / decim data = rng.randn(n_epochs, n_channels, n_times) events = np.array([np.arange(n_epochs), [0] * n_epochs, [1] * n_epochs]).T info = create_info(n_channels, sfreq, 'eeg') info['lowpass'] = sfreq_new / float(decim) epochs = EpochsArray(data, info, events) data_epochs = epochs.copy().decimate(decim).get_data() data_epochs_2 = epochs.copy().decimate(decim, offset=1).get_data() data_epochs_3 = epochs.decimate(dec_1).decimate(dec_2).get_data() assert_array_equal(data_epochs, data[:, :, ::decim]) assert_array_equal(data_epochs_2, data[:, :, 1::decim]) assert_array_equal(data_epochs, data_epochs_3) # Now let's do it with some real data raw = read_raw_fif(raw_fname, add_eeg_ref=False) events = read_events(event_name) sfreq_new = raw.info['sfreq'] / decim raw.info['lowpass'] = sfreq_new / 4. # suppress aliasing warnings picks = pick_types(raw.info, meg=True, eeg=True, exclude=()) epochs = Epochs(raw, events, 1, -0.2, 0.5, picks=picks, preload=True, add_eeg_ref=False) for offset in (0, 1): ev_ep_decim = epochs.copy().decimate(decim, offset).average() ev_decim = epochs.average().decimate(decim, offset) expected_times = epochs.times[offset::decim] assert_allclose(ev_decim.times, expected_times) assert_allclose(ev_ep_decim.times, expected_times) expected_data = epochs.get_data()[:, :, offset::decim].mean(axis=0) assert_allclose(ev_decim.data, expected_data) assert_allclose(ev_ep_decim.data, expected_data) assert_equal(ev_decim.info['sfreq'], sfreq_new) assert_array_equal(ev_decim.times, expected_times)
mode='mean', vmin=vmin, vmax=vmax, title='Using Morlet wavelets and EpochsTFR', show=False) ############################################################################### # Operating on arrays # ------------------- # # MNE also has versions of the functions above which operate on numpy arrays # instead of MNE objects. They expect inputs of the shape # ``(n_epochs, n_channels, n_times)``. They will also return a numpy array # of shape ``(n_epochs, n_channels, n_freqs, n_times)``. power = tfr_array_morlet(epochs.get_data(), sfreq=epochs.info['sfreq'], freqs=freqs, n_cycles=n_cycles, output='avg_power') # Baseline the output rescale(power, epochs.times, (0., 0.1), mode='mean', copy=False) fig, ax = plt.subplots() mesh = ax.pcolormesh(epochs.times * 1000, freqs, power[0], cmap='RdBu_r', vmin=vmin, vmax=vmax) ax.set_title('TFR calculated on a numpy array') ax.set(ylim=freqs[[0, -1]], xlabel='Time (ms)')
power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, return_itc=False, average=False) print(type(power)) avgpower = power.average() avgpower.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax, title='Using Morlet wavelets and EpochsTFR', show=False) ############################################################################### # Operating on arrays # ------------------- # # MNE also has versions of the functions above which operate on numpy arrays # instead of MNE objects. They expect inputs of the shape # ``(n_epochs, n_channels, n_times)``. They will also return a numpy array # of shape ``(n_epochs, n_channels, n_frequencies, n_times)``. power = tfr_array_morlet(epochs.get_data(), sfreq=epochs.info['sfreq'], frequencies=freqs, n_cycles=n_cycles, output='avg_power') # Baseline the output rescale(power, epochs.times, (0., 0.1), mode='mean', copy=False) fig, ax = plt.subplots() mesh = ax.pcolormesh(epochs.times * 1000, freqs, power[0], cmap='RdBu_r', vmin=vmin, vmax=vmax) ax.set_title('TFR calculated on a numpy array') ax.set(ylim=freqs[[0, -1]], xlabel='Time (ms)') fig.colorbar(mesh) plt.tight_layout() plt.show()
power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, return_itc=False, average=False) print(type(power)) avgpower = power.average() avgpower.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax, title='Using Morlet wavelets and EpochsTFR', show=False) ############################################################################### # Operating on arrays # ------------------- # # MNE also has versions of the functions above which operate on numpy arrays # instead of MNE objects. They expect inputs of the shape # ``(n_epochs, n_channels, n_times)``. They will also return a numpy array # of shape ``(n_epochs, n_channels, n_freqs, n_times)``. power = tfr_array_morlet(epochs.get_data(), sfreq=epochs.info['sfreq'], freqs=freqs, n_cycles=n_cycles, output='avg_power') # Baseline the output rescale(power, epochs.times, (0., 0.1), mode='mean', copy=False) fig, ax = plt.subplots() mesh = ax.pcolormesh(epochs.times * 1000, freqs, power[0], cmap='RdBu_r', vmin=vmin, vmax=vmax) ax.set_title('TFR calculated on a numpy array') ax.set(ylim=freqs[[0, -1]], xlabel='Time (ms)') fig.colorbar(mesh) plt.tight_layout() plt.show()
raw = mne.io.read_raw_fif(raw_fname, preload=True) raw.pick_types(meg='grad', eog=True) # we just look at gradiometers # bandpass filter and compute Hilbert raw.filter(fmin, fmax, n_jobs=1, # use more jobs to speed up. l_trans_bandwidth=1, # make sure filter params are the same h_trans_bandwidth=1, # in each band and skip "auto" option. fir_design='firwin') raw.apply_hilbert(n_jobs=1, envelope=False) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6), preload=True) # remove evoked response and get analytic signal (envelope) epochs.subtract_evoked() # for this we need to construct new epochs. epochs = mne.EpochsArray( data=np.abs(epochs.get_data()), info=epochs.info, tmin=epochs.tmin) # now average and move on frequency_map.append(((band, fmin, fmax), epochs)) beta_data = frequency_map[2][1] beta_sim = sd.make_sim_data(beta_data, order=17) alpha_data = frequency_map[1][1] alpha_sim = sd.make_sim_data(alpha_data, order=17) theta_data = frequency_map[0][1] theta_sim = sd.make_sim_data(theta_data, order=17) gamma_data = frequency_map[3][1] gamma_sim = sd.make_sim_data(theta_data, order=17) beta_sim.average().plot_joint() beta_data.average().plot_joint() beta_diff = mne.combine_evoked([beta_data.average(), -beta_sim.average()],