def test_scaler(): """Test methods of Scaler """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs_data = epochs.get_data() scaler = Scaler(epochs.info) y = epochs.events[:, -1] # np invalid divide value warnings with warnings.catch_warnings(record=True): X = scaler.fit_transform(epochs_data, y) assert_true(X.shape == epochs_data.shape) X2 = scaler.fit(epochs_data, y).transform(epochs_data) assert_array_equal(X2, X) # Test inverse_transform with warnings.catch_warnings(record=True): # invalid value in mult Xi = scaler.inverse_transform(X, y) assert_array_equal(epochs_data, Xi) # Test init exception assert_raises(ValueError, scaler.fit, epochs, y) assert_raises(ValueError, scaler.transform, epochs, y)
def test_epochs_proj(): """Test handling projection (apply proj in Raw or in Epochs) """ exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more this_picks = pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude=exclude) epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks, baseline=(None, 0), proj=True) assert_true(all(p['active'] is True for p in epochs.info['projs'])) evoked = epochs.average() assert_true(all(p['active'] is True for p in evoked.info['projs'])) data = epochs.get_data() raw_proj = io.Raw(raw_fname, proj=True) epochs_no_proj = Epochs(raw_proj, events[:4], event_id, tmin, tmax, picks=this_picks, baseline=(None, 0), proj=False) data_no_proj = epochs_no_proj.get_data() assert_true(all(p['active'] is True for p in epochs_no_proj.info['projs'])) evoked_no_proj = epochs_no_proj.average() assert_true(all(p['active'] is True for p in evoked_no_proj.info['projs'])) assert_true(epochs_no_proj.proj is True) # as projs are active from Raw assert_array_almost_equal(data, data_no_proj, decimal=8) # make sure we can exclude avg ref this_picks = pick_types(raw.info, meg=True, eeg=True, stim=True, eog=True, exclude=exclude) epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks, baseline=(None, 0), proj=True, add_eeg_ref=True) assert_true(_has_eeg_average_ref_proj(epochs.info['projs'])) epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks, baseline=(None, 0), proj=True, add_eeg_ref=False) assert_true(not _has_eeg_average_ref_proj(epochs.info['projs']))
def test_epochs_vectorizer(): """Test methods of EpochsVectorizer """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] with warnings.catch_warnings(record=True): epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs_data = epochs.get_data() vector = EpochsVectorizer(epochs.info) y = epochs.events[:, -1] X = vector.fit_transform(epochs_data, y) # Check data dimensions assert_true(X.shape[0] == epochs_data.shape[0]) assert_true(X.shape[1] == epochs_data.shape[1] * epochs_data.shape[2]) assert_array_equal(vector.fit(epochs_data, y).transform(epochs_data), X) # Check if data is preserved n_times = epochs_data.shape[2] assert_array_equal(epochs_data[0, 0, 0:n_times], X[0, 0:n_times]) # Check inverse transform Xi = vector.inverse_transform(X, y) assert_true(Xi.shape[0] == epochs_data.shape[0]) assert_true(Xi.shape[1] == epochs_data.shape[1]) assert_array_equal(epochs_data[0, 0, 0:n_times], Xi[0, 0, 0:n_times]) # Test init exception assert_raises(ValueError, vector.fit, epochs, y) assert_raises(ValueError, vector.transform, epochs, y)
def test_ica_reset(): """Test ICA resetting""" raw = io.Raw(raw_fname).crop(0.5, stop, False) raw.preload_data() picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads')[:10] run_time_attrs = ( '_pre_whitener', 'unmixing_matrix_', 'mixing_matrix_', 'n_components_', 'n_samples_', 'pca_components_', 'pca_explained_variance_', 'pca_mean_' ) with warnings.catch_warnings(record=True): ica = ICA( n_components=3, max_pca_components=3, n_pca_components=3, method='fastica', max_iter=1).fit(raw, picks=picks) assert_true(all(hasattr(ica, attr) for attr in run_time_attrs)) ica._reset() assert_true(not any(hasattr(ica, attr) for attr in run_time_attrs))
def test_psd(): """Test PSD estimation """ raw = io.Raw(raw_fname) exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='mag', eeg=False, stim=False, exclude=exclude) picks = picks[:2] tmin, tmax = 0, 10 # use the first 60s of data fmin, fmax = 2, 70 # look at frequencies between 5 and 70Hz n_fft = 128 # the FFT size (n_fft). Ideally a power of 2 psds, freqs = compute_raw_psd(raw, tmin=tmin, tmax=tmax, picks=picks, fmin=fmin, fmax=fmax, n_fft=n_fft, n_jobs=1, proj=False) psds_proj, freqs = compute_raw_psd(raw, tmin=tmin, tmax=tmax, picks=picks, fmin=fmin, fmax=fmax, n_fft=n_fft, n_jobs=1, proj=True) assert_array_almost_equal(psds, psds_proj) assert_true(psds.shape == (len(picks), len(freqs))) assert_true(np.sum(freqs < 0) == 0) assert_true(np.sum(psds < 0) == 0)
def test_regularized_csp(): """Test Common Spatial Patterns algorithm using regularized covariance """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs_data = epochs.get_data() n_channels = epochs_data.shape[1] n_components = 3 reg_cov = [None, 0.05, 'lws', 'oas'] for reg in reg_cov: csp = CSP(n_components=n_components, reg=reg) csp.fit(epochs_data, epochs.events[:, -1]) y = epochs.events[:, -1] X = csp.fit_transform(epochs_data, y) assert_true(csp.filters_.shape == (n_channels, n_channels)) assert_true(csp.patterns_.shape == (n_channels, n_channels)) assert_array_almost_equal(csp.fit(epochs_data, y). transform(epochs_data), X) # test init exception assert_raises(ValueError, csp.fit, epochs_data, np.zeros_like(epochs.events)) assert_raises(ValueError, csp.fit, epochs, y) assert_raises(ValueError, csp.transform, epochs, y) csp.n_components = n_components sources = csp.transform(epochs_data) assert_true(sources.shape[1] == n_components)
def test_tfr_with_inverse_operator(): """Test time freq with MNE inverse computation""" tmin, tmax, event_id = -0.2, 0.5, 1 # Setup for reading the raw data raw = io.Raw(fname_data) events = find_events(raw, stim_channel='STI 014') inverse_operator = read_inverse_operator(fname_inv) inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg=True, eeg=False, eog=True, stim=False, exclude='bads') # Load condition 1 event_id = 1 events3 = events[:3] # take 3 events to keep the computation time low epochs = Epochs(raw, events3, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) # Compute a source estimate per frequency band bands = dict(alpha=[10, 10]) label = read_label(fname_label) stcs = source_band_induced_power(epochs, inv, bands, n_cycles=2, use_fft=False, pca=True, label=label, prepared=True) stc = stcs['alpha'] assert_true(len(stcs) == len(list(bands.keys()))) assert_true(np.all(stc.data > 0)) assert_array_almost_equal(stc.times, epochs.times) stcs_no_pca = source_band_induced_power(epochs, inv, bands, n_cycles=2, use_fft=False, pca=False, label=label, prepared=True) assert_array_almost_equal(stcs['alpha'].data, stcs_no_pca['alpha'].data) # Compute a source estimate per frequency band epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) frequencies = np.arange(7, 30, 2) # define frequencies of interest power, phase_lock = source_induced_power(epochs, inv, frequencies, label, baseline=(-0.1, 0), baseline_mode='percent', n_cycles=2, n_jobs=1, prepared=True) assert_true(np.all(phase_lock > 0)) assert_true(np.all(phase_lock <= 1)) assert_true(np.max(power) > 10)
def test_source_psd(): """Test source PSD computation in label""" raw = io.Raw(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) tmin, tmax = 0, 20 # seconds fmin, fmax = 55, 65 # Hz n_fft = 2048 stc = compute_source_psd(raw, inverse_operator, lambda2=1. / 9., method="dSPM", tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, pick_ori="normal", n_fft=n_fft, label=label, overlap=0.1) assert_true(stc.times[0] >= fmin * 1e-3) assert_true(stc.times[-1] <= fmax * 1e-3) # Time max at line frequency (60 Hz in US) assert_true( 59e-3 <= stc.times[np.argmax(np.sum(stc.data, axis=0))] <= 61e-3)
def test_maxfilter_get_rank(): """test maxfilter rank lookup""" raw = io.Raw(raw_fname) mf = raw.info['proc_history'][0]['max_info'] rank1 = mf['sss_info']['nfree'] rank2 = _get_sss_rank(mf) assert_equal(rank1, rank2)
def _get_data(): """Aux function for testing GAT viz""" gat = GeneralizationAcrossTime() raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg='mag', stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] decim = 30 # Test on time generalization within one condition with warnings.catch_warnings(record=True): epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True, decim=decim) # Test default running gat = GeneralizationAcrossTime() gat.fit(epochs) gat.score(epochs) return gat
def test_ica_rank_reduction(): """Test recovery of full data when no source is rejected""" # Most basic recovery raw = io.Raw(raw_fname, preload=True).crop(0, stop, False).crop(0.5) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads')[:10] n_components = 5 max_pca_components = len(picks) for n_pca_components in [6, 10]: with warnings.catch_warnings(record=True): # non-convergence warnings.simplefilter('always') ica = ICA(n_components=n_components, max_pca_components=max_pca_components, n_pca_components=n_pca_components, method='fastica', max_iter=1).fit(raw, picks=picks) rank_before = raw.estimate_rank(picks=picks) assert_equal(rank_before, len(picks)) raw_clean = ica.apply(raw, copy=True) rank_after = raw_clean.estimate_rank(picks=picks) # interaction between ICA rejection and PCA components difficult # to preduct. Rank_after often seems to be 1 higher then # n_pca_components assert_true(n_components < n_pca_components <= rank_after <= rank_before)
def _get_data(): raw = io.Raw(raw_fname, add_eeg_ref=False, verbose=False, preload=True) events = read_events(event_name) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, ecg=False, eog=False, exclude='bads')[::8] return raw, events, picks
def test_ica_reject_buffer(): """Test ICA data raw buffer rejection""" tempdir = _TempDir() raw = io.Raw(raw_fname, preload=True).crop(0, stop, False).crop(1.5) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') ica = ICA(n_components=3, max_pca_components=4, n_pca_components=4) raw._data[2, 1000:1005] = 5e-12 drop_log = op.join(op.dirname(tempdir), 'ica_drop.log') set_log_file(drop_log, overwrite=True) with warnings.catch_warnings(record=True): ica.fit(raw, picks[:5], reject=dict(mag=2.5e-12), decim=2, tstep=0.01, verbose=True) assert_true(raw._data[:5, ::2].shape[1] - 4 == ica.n_samples_) with open(drop_log) as fid: log = [l for l in fid if 'detected' in l] assert_equal(len(log), 1)
def test_filterestimator(): """Test methods of FilterEstimator """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs_data = epochs.get_data() filt = FilterEstimator(epochs.info, 1, 40) y = epochs.events[:, -1] with warnings.catch_warnings(record=True): # stop freq attenuation warning X = filt.fit_transform(epochs_data, y) assert_true(X.shape == epochs_data.shape) assert_array_equal(filt.fit(epochs_data, y).transform(epochs_data), X) # Test init exception assert_raises(ValueError, filt.fit, epochs, y) assert_raises(ValueError, filt.transform, epochs, y)
def test_time_generalization(): """Test time generalization decoding """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg='mag', stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] decim = 30 with warnings.catch_warnings(record=True): epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True, decim=decim) epochs_list = [epochs[k] for k in event_id.keys()] scores = time_generalization(epochs_list, cv=2, random_state=42) n_times = len(epochs.times) assert_true(scores.shape == (n_times, n_times)) assert_true(scores.max() <= 1.) assert_true(scores.min() >= 0.)
def test_info(): """Test info object""" raw = io.Raw(raw_fname) event_id, tmin, tmax = 1, -0.2, 0.5 events = read_events(event_name) event_id = int(events[0, 2]) epochs = Epochs(raw, events[:1], event_id, tmin, tmax, picks=None, baseline=(None, 0)) evoked = epochs.average() events = read_events(event_name) # Test subclassing was successful. info = Info(a=7, b='aaaaa') assert_true('a' in info) assert_true('b' in info) info[42] = 'foo' assert_true(info[42] == 'foo') # test info attribute in API objects for obj in [raw, epochs, evoked]: assert_true(isinstance(obj.info, Info)) info_str = '%s' % obj.info assert_equal(len(info_str.split('\n')), (len(obj.info.keys()) + 2)) assert_true(all(k in info_str for k in obj.info.keys()))
def test_psdestimator(): """Test methods of PSDEstimator """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs_data = epochs.get_data() psd = PSDEstimator(2 * np.pi, 0, np.inf) y = epochs.events[:, -1] X = psd.fit_transform(epochs_data, y) assert_true(X.shape[0] == epochs_data.shape[0]) assert_array_equal(psd.fit(epochs_data, y).transform(epochs_data), X) # Test init exception assert_raises(ValueError, psd.fit, epochs, y) assert_raises(ValueError, psd.transform, epochs, y)
def test_ica_full_data_recovery(): """Test recovery of full data when no source is rejected""" # Most basic recovery raw = io.Raw(raw_fname).crop(0.5, stop, False) raw.preload_data() events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads')[:10] epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) evoked = epochs.average() n_channels = 5 data = raw._data[:n_channels].copy() data_epochs = epochs.get_data() data_evoked = evoked.data for method in ['fastica']: stuff = [(2, n_channels, True), (2, n_channels // 2, False)] for n_components, n_pca_components, ok in stuff: ica = ICA(n_components=n_components, max_pca_components=n_pca_components, n_pca_components=n_pca_components, method=method, max_iter=1) with warnings.catch_warnings(record=True): ica.fit(raw, picks=list(range(n_channels))) raw2 = ica.apply(raw, exclude=[], copy=True) if ok: assert_allclose(data[:n_channels], raw2._data[:n_channels], rtol=1e-10, atol=1e-15) else: diff = np.abs(data[:n_channels] - raw2._data[:n_channels]) assert_true(np.max(diff) > 1e-14) ica = ICA(n_components=n_components, max_pca_components=n_pca_components, n_pca_components=n_pca_components) with warnings.catch_warnings(record=True): ica.fit(epochs, picks=list(range(n_channels))) epochs2 = ica.apply(epochs, exclude=[], copy=True) data2 = epochs2.get_data()[:, :n_channels] if ok: assert_allclose(data_epochs[:, :n_channels], data2, rtol=1e-10, atol=1e-15) else: diff = np.abs(data_epochs[:, :n_channels] - data2) assert_true(np.max(diff) > 1e-14) evoked2 = ica.apply(evoked, exclude=[], copy=True) data2 = evoked2.data[:n_channels] if ok: assert_allclose(data_evoked[:n_channels], data2, rtol=1e-10, atol=1e-15) else: diff = np.abs(evoked.data[:n_channels] - data2) assert_true(np.max(diff) > 1e-14) assert_raises(ValueError, ICA, method='pizza-decomposision')
def test_ar_raw(): """Test fitting AR model on raw data """ raw = io.Raw(raw_fname) # pick MEG gradiometers picks = pick_types(raw.info, meg='grad', exclude='bads') picks = picks[:2] tmin, tmax, order = 0, 10, 2 coefs = fit_iir_model_raw(raw, order, picks, tmin, tmax)[1][1:] assert_equal(coefs.shape, (order, )) assert_true(0.9 < -coefs[0] < 1.1)
def test_run_ica(): """Test run_ica function""" raw = io.Raw(raw_fname, preload=True).crop(0, stop, False).crop(1.5) params = [] params += [(None, -1, slice(2), [0, 1])] # varicance, kurtosis idx params += [(None, 'MEG 1531')] # ECG / EOG channel params for idx, ch_name in product(*params): warnings.simplefilter('always') with warnings.catch_warnings(record=True): run_ica(raw, n_components=2, start=0, stop=6, start_find=0, stop_find=5, ecg_ch=ch_name, eog_ch=ch_name, skew_criterion=idx, var_criterion=idx, kurt_criterion=idx)
def test_csp(): """Test Common Spatial Patterns algorithm on epochs """ raw = io.Raw(raw_fname, preload=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[2:9:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs_data = epochs.get_data() n_channels = epochs_data.shape[1] n_components = 3 csp = CSP(n_components=n_components) csp.fit(epochs_data, epochs.events[:, -1]) y = epochs.events[:, -1] X = csp.fit_transform(epochs_data, y) assert_true(csp.filters_.shape == (n_channels, n_channels)) assert_true(csp.patterns_.shape == (n_channels, n_channels)) assert_array_almost_equal( csp.fit(epochs_data, y).transform(epochs_data), X) # test init exception assert_raises(ValueError, csp.fit, epochs_data, np.zeros_like(epochs.events)) assert_raises(ValueError, csp.fit, epochs, y) assert_raises(ValueError, csp.transform, epochs, y) csp.n_components = n_components sources = csp.transform(epochs_data) assert_true(sources.shape[1] == n_components) epochs.pick_types(meg='mag', copy=False) # test plot patterns components = np.arange(n_components) csp.plot_patterns(epochs.info, components=components, res=12, show=False) # test plot filters csp.plot_filters(epochs.info, components=components, res=12, show=False)
def test_add_events(): """Test adding events to a Raw file""" # need preload raw = io.Raw(raw_fname, preload=False) events = np.array([[raw.first_samp, 0, 1]]) assert_raises(RuntimeError, raw.add_events, events, 'STI 014') raw = io.Raw(raw_fname, preload=True) orig_events = find_events(raw, 'STI 014') # add some events events = np.array([raw.first_samp, 0, 1]) assert_raises(ValueError, raw.add_events, events, 'STI 014') # bad shape events[0] = raw.first_samp + raw.n_times + 1 events = events[np.newaxis, :] assert_raises(ValueError, raw.add_events, events, 'STI 014') # bad time events[0, 0] = raw.first_samp - 1 assert_raises(ValueError, raw.add_events, events, 'STI 014') # bad time events[0, 0] = raw.first_samp + 1 # can't actually be first_samp assert_raises(ValueError, raw.add_events, events, 'STI FOO') raw.add_events(events, 'STI 014') new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, np.concatenate((events, orig_events)))
def test_define_events(): """Test defining response events """ events = read_events(fname) raw = io.Raw(raw_fname) events_, _ = define_target_events(events, 5, 32, raw.info['sfreq'], .2, 0.7, 42, 99) n_target = events[events[:, 2] == 5].shape[0] n_miss = events_[events_[:, 2] == 99].shape[0] n_target_ = events_[events_[:, 2] == 42].shape[0] assert_true(n_target_ == (n_target - n_miss))
def _get_data(): raw = io.Raw(raw_fname, add_eeg_ref=False) events = read_events(event_name) picks = pick_types(raw.info, meg=True, eeg=True, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') return raw, events, picks
def test_compares_psd(): """Test PSD estimation on raw for plt.psd and scipy.signal.welch """ raw = io.Raw(raw_fname) exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, exclude=exclude)[:2] tmin, tmax = 0, 10 # use the first 60s of data fmin, fmax = 2, 70 # look at frequencies between 5 and 70Hz n_fft = 2048 # Compute psds with the new implementation using Welch psds_welch, freqs_welch = psd_welch(raw, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, proj=False, picks=picks, n_fft=n_fft, n_jobs=1) # Compute psds with plt.psd start, stop = raw.time_as_index([tmin, tmax]) data, times = raw[picks, start:(stop + 1)] from matplotlib.pyplot import psd out = [psd(d, Fs=raw.info['sfreq'], NFFT=n_fft) for d in data] freqs_mpl = out[0][1] psds_mpl = np.array([o[0] for o in out]) mask = (freqs_mpl >= fmin) & (freqs_mpl <= fmax) freqs_mpl = freqs_mpl[mask] psds_mpl = psds_mpl[:, mask] assert_array_almost_equal(psds_welch, psds_mpl) assert_array_almost_equal(freqs_welch, freqs_mpl) assert_true(psds_welch.shape == (len(picks), len(freqs_welch))) assert_true(psds_mpl.shape == (len(picks), len(freqs_mpl))) assert_true(np.sum(freqs_welch < 0) == 0) assert_true(np.sum(freqs_mpl < 0) == 0) assert_true(np.sum(psds_welch < 0) == 0) assert_true(np.sum(psds_mpl < 0) == 0)
def test_ica_full_data_recovery(): """Test recovery of full data when no source is rejected""" # Most basic recovery raw = io.Raw(raw_fname, preload=True).crop(0, stop, False).crop(1.5) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) n_channels = 5 data = raw._data[:n_channels].copy() data_epochs = epochs.get_data() for n_components, n_pca_components, ok in [(2, n_channels, True), (2, n_channels // 2, False)]: ica = ICA(n_components=n_components, max_pca_components=n_pca_components, n_pca_components=n_pca_components) ica.decompose_raw(raw, picks=list(range(n_channels))) raw2 = ica.pick_sources_raw(raw, exclude=[]) if ok: assert_allclose(data[:n_channels], raw2._data[:n_channels], rtol=1e-10, atol=1e-15) else: diff = np.abs(data[:n_channels] - raw2._data[:n_channels]) assert_true(np.max(diff) > 1e-14) ica = ICA(n_components=n_components, max_pca_components=n_pca_components, n_pca_components=n_pca_components) ica.decompose_epochs(epochs, picks=list(range(n_channels))) epochs2 = ica.pick_sources_epochs(epochs, exclude=[]) data2 = epochs2.get_data()[:, :n_channels] if ok: assert_allclose(data_epochs[:, :n_channels], data2, rtol=1e-10, atol=1e-15) else: diff = np.abs(data_epochs[:, :n_channels] - data2) assert_true(np.max(diff) > 1e-14)
def test_time_frequency(): """Test time frequency transform (PSD and phase lock) """ # Set parameters event_id = 1 tmin = -0.2 tmax = 0.5 # Setup for reading the raw data raw = io.Raw(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0)) data = epochs.get_data() times = epochs.times frequencies = np.arange(6, 20, 5) # define frequencies of interest Fs = raw.info['sfreq'] # sampling in Hz n_cycles = frequencies / float(4) power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=n_cycles, use_fft=True) assert_true(power.shape == (len(picks), len(frequencies), len(times))) assert_true(power.shape == phase_lock.shape) assert_true(np.sum(phase_lock >= 1) == 0) assert_true(np.sum(phase_lock <= 0) == 0) power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=2, use_fft=False) assert_true(power.shape == (len(picks), len(frequencies), len(times))) assert_true(power.shape == phase_lock.shape) assert_true(np.sum(phase_lock >= 1) == 0) assert_true(np.sum(phase_lock <= 0) == 0) tfr = cwt_morlet(data[0], Fs, frequencies, use_fft=True, n_cycles=2) assert_true(tfr.shape == (len(picks), len(frequencies), len(times))) single_power = single_trial_power(data, Fs, frequencies, use_fft=False, n_cycles=2) assert_array_almost_equal(np.mean(single_power), power)
def test_ems(): """Test event-matched spatial filters""" raw = io.Raw(raw_fname, preload=False) # create unequal number of events events = read_events(event_name) events[-2, 2] = 3 picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) assert_raises(ValueError, compute_ems, epochs, ['aud_l', 'vis_l']) epochs.equalize_event_counts(epochs.event_id, copy=False) assert_raises(KeyError, compute_ems, epochs, ['blah', 'hahah']) surrogates, filters, conditions = compute_ems(epochs) assert_equal(list(set(conditions)), [1, 3]) events = read_events(event_name) event_id2 = dict(aud_l=1, aud_r=2, vis_l=3) epochs = Epochs(raw, events, event_id2, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs.equalize_event_counts(epochs.event_id, copy=False) n_expected = sum([len(epochs[k]) for k in ['aud_l', 'vis_l']]) assert_raises(ValueError, compute_ems, epochs) surrogates, filters, conditions = compute_ems(epochs, ['aud_r', 'vis_l']) assert_equal(n_expected, len(surrogates)) assert_equal(n_expected, len(conditions)) assert_equal(list(set(conditions)), [2, 3]) raw.close()
def test_ar_raw(): """Test fitting AR model on raw data """ raw = io.Raw(raw_fname) # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', exclude='bads') picks = picks[:2] tmin, tmax = 0, 10 # use the first s of data order = 2 coefs = ar_raw(raw, picks=picks, order=order, tmin=tmin, tmax=tmax) mean_coefs = np.mean(coefs, axis=0) assert_true(coefs.shape == (len(picks), order)) assert_true(0.9 < mean_coefs[0] < 1.1)
def test_plot_ica_sources(): """Test plotting of ICA panel """ raw = io.Raw(raw_fname, preload=True) 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.plot_sources(raw) ica.plot_sources(epochs) with warnings.catch_warnings(record=True): # no labeled objects mpl ica.plot_sources(epochs.average()) assert_raises(ValueError, ica.plot_sources, 'meeow') plt.close('all')