def test_tfr_multitaper(): """Test tfr_multitaper""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002', 'SIM0003'] ch_types = ['grad', 'grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(5, 100, 3, dtype=np.float) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False) # test picks argument assert_array_almost_equal(power.data, power_picks.data) assert_array_almost_equal(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) assert_raises(AssertionError, assert_array_almost_equal, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert_true(tmax > 0.3 and tmax < 0.7) assert_false(np.any(itc.data < 0.)) assert_true(fmax > 40 and fmax < 60)
def test_tfr_multitaper(): """Test tfr_multitaper""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002', 'SIM0003'] ch_types = ['grad', 'grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(5, 100, 3, dtype=np.float) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) assert_raises(AssertionError, assert_array_almost_equal, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert_true(tmax > 0.3 and tmax < 0.7) assert_false(np.any(itc.data < 0.)) assert_true(fmax > 40 and fmax < 60)
def test_add_noise(): """Test noise addition.""" if check_version('numpy', '1.17'): rng = np.random.default_rng(0) else: rng = np.random.RandomState(0) raw = read_raw_fif(raw_fname) raw.del_proj() picks = pick_types(raw.info, meg=True, eeg=True, exclude=()) cov = compute_raw_covariance(raw, picks=picks) with pytest.raises(RuntimeError, match='to be loaded'): add_noise(raw, cov) raw.crop(0, 1).load_data() with pytest.raises(TypeError, match='Raw, Epochs, or Evoked'): add_noise(0., cov) with pytest.raises(TypeError, match='Covariance'): add_noise(raw, 0.) # test a no-op (data preserved) orig_data = raw[:][0] zero_cov = cov.copy() zero_cov['data'].fill(0) add_noise(raw, zero_cov) new_data = raw[:][0] assert_allclose(orig_data, new_data, atol=1e-30) # set to zero to make comparisons easier raw._data[:] = 0. epochs = EpochsArray(np.zeros((1, len(raw.ch_names), 100)), raw.info.copy()) epochs.info['bads'] = [] evoked = epochs.average(picks=np.arange(len(raw.ch_names))) for inst in (raw, epochs, evoked): with catch_logging() as log: add_noise(inst, cov, random_state=rng, verbose=True) log = log.getvalue() want = ('to {0}/{1} channels ({0}' .format(len(cov['names']), len(raw.ch_names))) assert want in log if inst is evoked: inst = EpochsArray(inst.data[np.newaxis], inst.info) if inst is raw: cov_new = compute_raw_covariance(inst, picks=picks) else: cov_new = compute_covariance(inst) assert cov['names'] == cov_new['names'] r = np.corrcoef(cov['data'].ravel(), cov_new['data'].ravel())[0, 1] assert r > 0.99
def test_add_noise(): """Test noise addition.""" rng = np.random.RandomState(0) data_path = testing.data_path() raw = read_raw_fif(data_path + '/MEG/sample/sample_audvis_trunc_raw.fif') raw.del_proj() picks = pick_types(raw.info, eeg=True, exclude=()) cov = compute_raw_covariance(raw, picks=picks) with pytest.raises(RuntimeError, match='to be loaded'): add_noise(raw, cov) raw.crop(0, 1).load_data() with pytest.raises(TypeError, match='Raw, Epochs, or Evoked'): add_noise(0., cov) with pytest.raises(TypeError, match='Covariance'): add_noise(raw, 0.) # test a no-op (data preserved) orig_data = raw[:][0] zero_cov = cov.copy() zero_cov['data'].fill(0) add_noise(raw, zero_cov) new_data = raw[:][0] assert_allclose(orig_data, new_data, atol=1e-30) # set to zero to make comparisons easier raw._data[:] = 0. epochs = EpochsArray(np.zeros((1, len(raw.ch_names), 100)), raw.info.copy()) epochs.info['bads'] = [] evoked = epochs.average(picks=np.arange(len(raw.ch_names))) for inst in (raw, epochs, evoked): with catch_logging() as log: add_noise(inst, cov, random_state=rng, verbose=True) log = log.getvalue() want = ('to {0}/{1} channels ({0}' .format(len(cov['names']), len(raw.ch_names))) assert want in log if inst is evoked: inst = EpochsArray(inst.data[np.newaxis], inst.info) if inst is raw: cov_new = compute_raw_covariance(inst, picks=picks, verbose='error') # samples else: cov_new = compute_covariance(inst, verbose='error') # avg ref assert cov['names'] == cov_new['names'] r = np.corrcoef(cov['data'].ravel(), cov_new['data'].ravel())[0, 1] assert r > 0.99
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)
def test_tfr_multitaper(): """Test tfr_multitaper.""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002'] ch_types = ['grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float64) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(35, 70, 5, dtype=np.float64) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power2, itc2 = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=slice(0, 2)) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_epochs = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False) power_averaged = power_epochs.average() power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False).average() print(power_evoked) # test repr for EpochsTFR # Test channel picking power_epochs_picked = power_epochs.copy().drop_channels(['SIM0002']) assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200)) assert_equal(power_epochs_picked.ch_names, ['SIM0001']) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., return_itc=True, average=False) # test picks argument assert_array_almost_equal(power.data, power_picks.data) assert_array_almost_equal(power.data, power_averaged.data) assert_array_almost_equal(power.times, power_epochs.times) assert_array_almost_equal(power.times, power_averaged.times) assert_equal(power.nave, power_averaged.nave) assert_equal(power_epochs.data.shape, (3, 2, 7, 200)) assert_array_almost_equal(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_array_almost_equal, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert (tmax > 0.3 and tmax < 0.7) assert not np.any(itc.data < 0.) assert (fmax > 40 and fmax < 60) assert (power2.data.shape == (len(picks), len(freqs), 2)) assert (power2.data.shape == itc2.data.shape) # Test decim parameter checks and compatibility between wavelets length # and instance length in the time dimension. pytest.raises(TypeError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=(1, )) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=1000, time_bandwidth=4.0) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(-4, -1), n_cycles=7)
def test_tfr_multitaper(): """Test tfr_multitaper.""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002'] ch_types = ['grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(35, 70, 5, dtype=np.float) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power2, itc2 = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=slice(0, 2)) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_epochs = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False) power_averaged = power_epochs.average() power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False).average() print(power_evoked) # test repr for EpochsTFR # Test channel picking power_epochs_picked = power_epochs.copy().drop_channels(['SIM0002']) assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200)) assert_equal(power_epochs_picked.ch_names, ['SIM0001']) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., return_itc=True, average=False) # test picks argument assert_array_almost_equal(power.data, power_picks.data) assert_array_almost_equal(power.data, power_averaged.data) assert_array_almost_equal(power.times, power_epochs.times) assert_array_almost_equal(power.times, power_averaged.times) assert_equal(power.nave, power_averaged.nave) assert_equal(power_epochs.data.shape, (3, 2, 7, 200)) assert_array_almost_equal(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_array_almost_equal, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert (tmax > 0.3 and tmax < 0.7) assert not np.any(itc.data < 0.) assert (fmax > 40 and fmax < 60) assert (power2.data.shape == (len(picks), len(freqs), 2)) assert (power2.data.shape == itc2.data.shape) # Test decim parameter checks and compatibility between wavelets length # and instance length in the time dimension. pytest.raises(TypeError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=(1,)) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=1000, time_bandwidth=4.0)
data = noise + signal reject = dict(grad=4000) events = np.empty((n_epochs, 3), dtype=int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=data, info=info, events=events, event_id=event_id, reject=reject) epochs.average().plot() # %% # Calculate a time-frequency representation (TFR) # ----------------------------------------------- # # Below we'll demonstrate the output of several TFR functions in MNE: # # * :func:`mne.time_frequency.tfr_multitaper` # * :func:`mne.time_frequency.tfr_stockwell` # * :func:`mne.time_frequency.tfr_morlet` # # Multitaper transform # ==================== # First we'll use the multitaper method for calculating the TFR. # This creates several orthogonal tapering windows in the TFR estimation,
signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping data = noise + signal reject = dict(grad=4000) events = np.empty((n_epochs, 3), dtype=int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=data, info=info, events=events, event_id=event_id, reject=reject) epochs.average().plot() ############################################################################### # Calculate a time-frequency representation (TFR) # ----------------------------------------------- # # Below we'll demonstrate the output of several TFR functions in MNE: # # * :func:`mne.time_frequency.tfr_multitaper` # * :func:`mne.time_frequency.tfr_stockwell` # * :func:`mne.time_frequency.tfr_morlet` # # Multitaper transform # ==================== # First we'll use the multitaper method for calculating the TFR. # This creates several orthogonal tapering windows in the TFR estimation,