def test_plot_epochs_nodata(): """Test plotting of epochs when no data channels are present.""" data = np.random.RandomState(0).randn(10, 2, 1000) info = create_info(2, 1000., 'stim') epochs = EpochsArray(data, info) with pytest.raises(ValueError, match='consider passing picks explicitly'): epochs.plot()
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_plot_butterfly(): """Test butterfly view in epochs browse window.""" rng = np.random.RandomState(0) n_epochs, n_channels, n_times = 50, 30, 20 sfreq = 1000. data = np.sin(rng.randn(n_epochs, n_channels, n_times)) events = np.array([ np.arange(n_epochs), [0] * n_epochs, np.ones([n_epochs], dtype=np.int64) ]).T chanlist = [ 'eeg' if chan < n_channels // 3 else 'ecog' if chan < n_channels // 2 else 'seeg' for chan in range(n_channels) ] info = create_info(n_channels, sfreq, chanlist) epochs = EpochsArray(data, info, events) fig = epochs.plot(butterfly=True) keystotest = [ 'b', 'b', 'left', 'right', 'up', 'down', 'pageup', 'pagedown', '-', '+', '=', 'f11', 'home', '?', 'h', 'o', 'end' ] for key in keystotest: fig.canvas.key_press_event(key) fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up fig.canvas.resize_event() fig.canvas.close_event() # closing and epoch dropping plt.close('all')
def _read_epochs(epochs_mat_fname, info, return_fixations_motor): """read the epochs from matfile""" data = scio.loadmat(epochs_mat_fname, squeeze_me=True)['data'] ch_names = [ch for ch in data['label'].tolist()] info['sfreq'] = data['fsample'].tolist() times = data['time'].tolist()[0] # deal with different event lengths if return_fixations_motor is not None: fixation_mask = data['trialinfo'].tolist()[:, 1] == 6 if return_fixations_motor is False: fixation_mask = ~fixation_mask data = np.array(data['trial'].tolist()[fixation_mask].tolist()) else: data = np.array(data['trial'].tolist().tolist()) # warning: data are not chronologically ordered but # match the trial info events = np.zeros((len(data), 3), dtype=np.int) events[:, 0] = np.arange(len(data)) events[:, 2] = 99 # all events # we leave it to the user to construct his events # as from the data['trialinfo'] arbitrary events can be constructed. # and it is task specific. this_info = _hcp_pick_info(info, ch_names) epochs = EpochsArray(data=data, info=this_info, events=events, tmin=times.min()) # XXX hack for now due to issue with EpochsArray constructor # cf https://github.com/mne-tools/mne-hcp/issues/9 epochs.times = times return epochs
def cli(matfiles, savename, rec_type, infosrc): """ Convert brainstorm epochs to mne.Epochs object """ if infosrc: if rec_type is 'ds': from mne.io import read_raw_ctf as read_raw elif rec_type is 'fif': from mne.io import Raw as read_raw with nostdout(): raw_with_info = read_raw(infosrc) isFirst = True for fname in matfiles: with nostdout(): mat_epoch = sio.loadmat(fname) # click.echo(mat_epoch) if isFirst: data = mat_epoch['F'] times = mat_epoch['Time'] # print times[0,-1] isFirst = False else: data = np.dstack((data, mat_epoch['F'])) # click.echo(data.shape) data = data.transpose((2,0,1)) n_channels = data.shape[1] sfreq = times.shape[1] / (times[0,-1] + times[0,1]) if infosrc: if rec_type is 'ds': from mne.io import read_raw_ctf as read_raw elif rec_type is 'fif': from mne.io import Raw as read_raw with nostdout(): raw_with_info = read_raw(infosrc) good_info = raw_with_info.info # click.echo(len(good_info['ch_names'])) ch_types = [channel_type(good_info, idx) for idx in range(n_channels)] # click.echo(len(ch_types)) info = create_info(ch_names=good_info['ch_names'], sfreq=sfreq, ch_types=ch_types) else: ch_types='mag' info = create_info(n_channels, sfreq, ch_types) with nostdout(): epochs = EpochsArray(data, info) epochs.save(savename)
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_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_plot_overlapping_epochs_with_events(): """Test drawing of event lines in overlapping epochs.""" data = np.zeros(shape=(3, 2, 100)) # 3 epochs, 2 channels, 100 samples sfreq = 100 info = create_info(ch_names=('a', 'b'), ch_types=('misc', 'misc'), sfreq=sfreq) # 90% overlap, so all 3 events should appear in all 3 epochs when plotted: events = np.column_stack(([50, 60, 70], [0, 0, 0], [1, 2, 3])) epochs = EpochsArray(data, info, tmin=-0.5, events=events) fig = epochs.plot(events=events, picks='misc') assert len(fig.mne.event_lines.get_segments()) == 9
def transform(self, epochs): from mne import EpochsArray from mne.time_frequency import single_trial_power sfreq = epochs.info['sfreq'] # Time Frequency decomposition tfr = single_trial_power(epochs._data, sfreq=sfreq, **self.tfr_kwargs) # Consider frequencies as if it was different time points n_trial, n_chan, n_freq, n_time = tfr.shape tfr = np.reshape(tfr, [n_trial, n_chan, n_freq * n_time]) # Make pseudo epochs sfreq = epochs.info['sfreq'] decim = self.tfr_kwargs.get('decim', None) if isinstance(decim, slice): decim = decim.step if decim is not None and decim > 1: sfreq /= decim info = epochs.info.copy() info['sfreq'] = sfreq self._tfr_epochs = EpochsArray(data=tfr, info=info, events=epochs.events)
def test_bad_channels(): """Test exception when unsupported channels are used.""" chs = [i for i in _kind_dict] data_chs = _DATA_CH_TYPES_SPLIT + ['eog'] chs_bad = list(set(chs) - set(data_chs)) info = create_info(len(chs), 500, chs) data = np.random.rand(len(chs), 50) raw = RawArray(data, info) data = np.random.rand(100, len(chs), 50) epochs = EpochsArray(data, info) n_components = 0.9 ica = ICA(n_components=n_components, method='fastica') for inst in [raw, epochs]: for ch in chs_bad: # Test case for only bad channels picks_bad1 = pick_types(inst.info, meg=False, **{str(ch): True}) # Test case for good and bad channels picks_bad2 = pick_types(inst.info, meg=True, **{str(ch): True}) assert_raises(ValueError, ica.fit, inst, picks=picks_bad1) assert_raises(ValueError, ica.fit, inst, picks=picks_bad2) assert_raises(ValueError, ica.fit, inst, picks=[])
def _simulate_erplike_mixed_data(n_epochs=100, n_channels=10): rng = np.random.RandomState(42) tmin, tmax = 0., 1. sfreq = 100. informative_ch_idx = 0 y = rng.randint(0, 2, n_epochs) n_times = int((tmax - tmin) * sfreq) epoch_times = np.linspace(tmin, tmax, n_times) target_template = 1e-6 * (epoch_times - tmax) * np.sin( 2 * np.pi * epoch_times) nontarget_template = 0.7e-6 * (epoch_times - tmax) * np.sin( 2 * np.pi * (epoch_times - 0.1)) epoch_data = rng.randn(n_epochs, n_channels, n_times) * 5e-7 epoch_data[y == 0, informative_ch_idx, :] += nontarget_template epoch_data[y == 1, informative_ch_idx, :] += target_template mixing_mat = linalg.svd(rng.randn(n_channels, n_channels))[0] mixed_epoch_data = np.dot(mixing_mat.T, epoch_data).transpose((1, 0, 2)) events = np.zeros((n_epochs, 3), dtype=int) events[:, 0] = np.arange(0, n_epochs * n_times, n_times) events[:, 2] = y info = create_info( ch_names=['C{:02d}'.format(i) for i in range(n_channels)], ch_types=['eeg'] * n_channels, sfreq=sfreq) epochs = EpochsArray(mixed_epoch_data, info, events, tmin=tmin, event_id={'nt': 0, 't': 1}) return epochs, mixing_mat
def _create_epochs(events_dict=None, info: mne.Info = None, data=None, event_number=0, t_min=0): # Convert values to volts data = data * 1.0e-6 n_epochs = data.shape[0] n_samples = data.shape[2] events = np.column_stack( (np.arange(0, n_epochs * n_samples, n_samples), np.zeros(n_epochs, dtype=int), np.full((n_epochs, ), event_number))) epochs = EpochsArray(data, info, events=events, event_id=events_dict) epochs = epochs.shift_time(t_min, relative=False) return epochs
def calc_epochs(bv_raw, y_tr, info, threshold, epoch_lim): ind_mov = np.where(np.diff(np.array(y_tr > threshold) * 1) == 1)[0] low_limit = ind_mov > epoch_lim up_limit = ind_mov < y_tr.shape[0] - epoch_lim ind_mov = ind_mov[low_limit & up_limit] bv_epoch = np.zeros([ind_mov.shape[0], int(epoch_lim * 2)]) y_arr = np.zeros([ind_mov.shape[0], int(epoch_lim * 2)]) n_epochs = bv_epoch.shape[0] events = np.empty((n_epochs, 3), dtype=int) event_id = dict(mov_present=1) for idx, i in enumerate(ind_mov): #if i > 0 and (ind_mov[idx] - ind_mov[idx-1] > 1000): # TTL signal is a rectangular signal with length ~500ms bv_epoch[idx, :] = bv_raw[i - epoch_lim:i + epoch_lim] y_arr[idx, :] = y_tr[i - epoch_lim:i + epoch_lim] events[idx, :] = i, 0, event_id["mov_present"] print(bv_epoch.shape) bv_epoch = np.expand_dims(bv_epoch, axis=1) print(bv_epoch.shape) epochs = EpochsArray(data=bv_epoch, info=info, events=events, event_id=event_id) return epochs
def test_moving_average(): # 800 ms of data at 1000 sfreq epoch = generate_epoch(n_times=800) epoch_ = moving_average(epoch, 0.02) # we want a copy assert (epoch is not epoch_) assert_equal(epoch.get_data().shape, epoch_.get_data().shape) # let's make a simple case to check that convolution works ntimes = 10 nepochs = 4 nchannels = 4 sfreq = 2. array = np.arange(ntimes) array_2d = np.repeat(array[None, :], nchannels, axis=0) array_3d = np.repeat(array_2d[None, ...], nepochs, axis=0) assert_array_equal(array_3d.shape, (nepochs, nchannels, ntimes)) info = create_info(nchannels, sfreq, 'mag') epochs = EpochsArray(array_3d, info) # check it fails if we have too large a window with pytest.raises(ValueError): moving_average(epochs, twindow=(ntimes + sfreq) / sfreq) # but it works in extreme cases as well moving_average(epochs, twindow=ntimes / sfreq) moving_average(epochs, twindow=1 / sfreq) # let's check it works across ranges for i in range(1, ntimes + 1): twindow = 1 / sfreq * i epochs_conv = moving_average(epochs, twindow) filt = np.ones(i) / float(i) assert_array_almost_equal(epochs_conv.get_data(), convolve(array_3d, filt))
def generate_random_epoch(epoch: mne.Epochs, mu: float = 0, sigma: float = 2.0) -> mne.Epochs: """ Generate epochs with random data. Arguments: epoch: mne.Epochs Epochs object to get epoch info structure mu: float Mean of the normal distribution sigma: float Standart deviation of the normal distribution Returns: mne.Epochs new epoch with random data with normal distribution """ # Get epoch information info = epoch.info #create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) # Get epochs as a 3D NumPy array of shape (n_epochs, n_channels, n_times) # Get the arrays’ shape data_shape = epoch.get_data().shape i, j, k = data_shape # Generate a numpy.array with same shape from the normal distribution r_epoch = sigma * np.random.randn(i, j, k) + mu return EpochsArray(data=r_epoch, info=info)
def epochs_filter(epochs, xy, method_='median', factor_=10): # Filter an MNE epoch object spatially for outliers # epochs: MNE epochs object # xy: ChannelCoord Nx2 # method_: string of median or mean # factor_: 10 (# std / mad away from mean = outlier) print("Mesh filtering epochs...") # Get data: trials, channels, time Z = epochs.get_data() # Get shape for later shp = Z.shape # Permute so channels is last dim, then flatten epochs and time Z = np.einsum('ijk->ikj', Z) Z = Z.reshape(-1, shp[1]) # channel shape Z = filter_dataset(Z, xy, method=method_, factor=factor_) # Reshape the matrix back together Z = Z.reshape(shp[0], shp[2], -1) # channel # arbritary Z = np.einsum('ikj->ijk', Z) # Add back to epochs return EpochsArray(Z, epochs.info, epochs.events, epochs.tmin, epochs.event_id)
def create_epochs(dict2, lengthepoch=2): '''Function to create an epoch object from the data with events correspondong to each state Parameters ---------- dataset: dict2 with files sorted by states lengthepoch : length of the desired epoch (default 2) Return ------ Epochs ''' states = [ 'lent', 'rapide', 'libre', 'meditate', 'baseline', 'resting1', 'resting2', 'val' ] lengthepoch = lengthepoch sfreq = dict2['libre']['raw file'][1].info['sfreq'] data = [] info = dict2['libre']['raw file'][1].info indices = np.arange(len(dict2['libre']['raw file']) * 3) events = [] event_id = dict(lent=1, rapide=2, libre=3, meditate=4, baseline=5, resting1=6, resting2=7, val=8) k = 0 tmin = 0 for state in states: id = event_id[state] for l, epochs in enumerate(dict2[state]['raw file']): for i in range(floor(15 / lengthepoch)): if epochs.times[-1] == 20: test = epochs.copy().crop( 5 + i * lengthepoch, 5 + (i + 1) * lengthepoch).get_data() else: test = epochs.copy().crop(i * lengthepoch, (i + 1) * lengthepoch).get_data() events.append([k, 1, id]) k += 1 data.append(test) events = np.array(events) data = np.array(data) epochs = EpochsArray(data, info, events, tmin, event_id, reject=dict(eeg=2000)) return epochs
def prepInst(inst, dataf, suffix, montage, ref_ch, eogs, ecg, emg): info = create_info([ref_ch], inst.info['sfreq'], ['eeg'], verbose=False) info['lowpass'] = inst.info['lowpass'] if suffix == 'raw': ref = RawArray(np.zeros((1, len(inst.times))), info, verbose=False) elif suffix == 'epo': ref = EpochsArray(np.zeros((len(inst), 1, len(inst.times))), info, verbose=False) inst = inst.add_channels([ref]) #, force_update_info=True) # inst = inst.set_eeg_reference(['TP9', 'TP10']) if suffix == 'epo': while len(inst.picks) != len(inst): # weird picks bug inst.picks = np.append(inst.picks, len(inst.picks)) inst = inst.drop_channels(['TP9', 'TP10']) # ch_order = [ 'Fp1', 'Fp2', 'AFp1', 'AFp2', 'AF7', 'AF3', 'AFz', 'AF4', 'AF8', 'AFF5h', 'AFF6h', 'F7', 'F5', 'F3', 'F1', 'Fz', 'F2', 'F4', 'F6', 'F8', 'FFT9h', 'FFT7h', 'FFC3h', 'FFC4h', 'FFT8h', 'FFT10h', 'FT9', 'FT7', 'FC5', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'FC6', 'FT8', 'FT10', 'FTT9h', 'FCC5h', 'FCC1h', 'FCC2h', 'FCC6h', 'FTT10h', 'T7', 'C5', 'C3', 'C1', 'Cz', 'C2', 'C4', 'C6', 'T8', 'TTP7h', 'CCP3h', 'CCP4h', 'TTP8h', 'TP7', 'CP5', 'CP3', 'CP1', 'CPz', 'CP2', 'CP4', 'CP6', 'TP8', 'TPP9h', 'CPP5h', 'CPP1h', 'CPP2h', 'CPP6h', 'TPP10h', 'P7', 'P5', 'P3', 'P1', 'Pz', 'P2', 'P4', 'P6', 'P8', 'PPO5h', 'PPO6h', 'PO7', 'PO3', 'POz', 'PO4', 'PO8', 'POO9h', 'O1', 'POO1', 'Oz', 'POO2', 'O2', 'POO10h' ] # for ch in eogs: ch_ix = inst.ch_names.index(ch) inst._data[ch_ix, :] *= 1e-6 ch_order.append(ch) inst.set_channel_types({ch: 'eog'}) # ch_ix = inst.ch_names.index(ecg) inst._data[ch_ix, :] *= 1e-6 ch_order.append(ecg) inst.set_channel_types({ecg: 'ecg'}) # ch_ix = inst.ch_names.index(emg) inst._data[ch_ix, :] *= 1e-6 ch_order.append(emg) inst.set_channel_types({emg: 'emg'}) # inst = inst.set_montage(montage, verbose=False) # inst = inst.reorder_channels(ch_order) # fname = (os.path.join( os.path.dirname(dataf), os.path.basename(dataf).split('.')[0] + '-%s.fif' % (suffix))) print('Saving to ' + fname) if suffix == 'raw': inst.save(fname, verbose=False, overwrite=True) else: inst.save(fname, verbose=False)
def get_window(master: EpochsArray, config, start): fps = config['fps'] end = start + config['window_duration'] - 1. / fps window = master.copy().crop(start, end) return window
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 createEpochObject(data, info, events=None, tmin=0, event_id=None): if type(info) == str: info = mne.io.read_info(info) if not events: events = np.array((np.arange(data.shape[0]), np.ones(data.shape[0]), np.ones(data.shape[0]))).T if not event_id: event_id = event_id = {'arbitrary': 1} epochs = EpochsArray(data, info=info, events=events, event_id=event_id) return epochs
def test_xdawn_picks(): """Test picking with Xdawn.""" data = np.random.RandomState(0).randn(10, 2, 10) info = create_info(2, 1000., ('eeg', 'misc')) epochs = EpochsArray(data, info) xd = Xdawn(correct_overlap=False) xd.fit(epochs) epochs_out = xd.apply(epochs)['1'] assert epochs_out.info['ch_names'] == epochs.ch_names assert not (epochs_out.get_data()[:, 0] != data[:, 0]).any() assert_array_equal(epochs_out.get_data()[:, 1], data[:, 1])
def prepInst(inst, dataf, suffix, montage, ref_ch, aux, stim, ch_order): if ref_ch is not None: info = create_info([ref_ch], inst.info['sfreq'], ['eeg'], verbose=False) info['lowpass'] = inst.info['lowpass'] if suffix == 'raw': ref = RawArray(np.zeros((1, len(inst.times))), info, verbose=False) elif suffix == 'epo': ref = EpochsArray(np.zeros((len(inst), 1, len(inst.times))), info, verbose=False) inst = inst.add_channels([ref]) #, force_update_info=True) # inst = inst.set_eeg_reference(ref_channels='average', projection=False, verbose=False) if suffix == 'epo': while len(inst.picks) != len(inst.ch_names): # weird picks bug inst.picks = np.append(inst.picks, len(inst.picks)) # if aux is not None: for ch in aux: try: ch_ix = inst.ch_names.index(ch) if suffix == 'raw': inst._data[ch_ix] *= 1e-6 elif suffix == 'epo': inst._data[:, ch_ix] *= 1e-6 ch_order.append(ch) inst.set_channel_types({ch: 'eog'}) except Exception as e: print(e, '%s channel not working' % ch) # if suffix != 'epo': if stim in inst.ch_names: ch_ix = inst.ch_names.index(stim) ch_order.append(stim) inst.set_channel_types({stim: 'stim'}) # if montage is not None: inst = inst.set_montage(montage, verbose=False) # inst = inst.reorder_channels(ch_order) # fname = (os.path.join( os.path.dirname(dataf), os.path.basename(dataf).split('.')[0] + '-%s.fif' % suffix)) print('Saving to ' + fname) if suffix == 'raw': inst.save(fname, verbose=False, overwrite=True) else: inst.save(fname, verbose=False)
def _prepare_data(self, epochs): """Swap channel and time""" from mne import EpochsArray, create_info # regroup channels X = self._group_channels(epochs) # swap time and channels X = X.transpose([0, 2, 1]) # format for GAT epochs_ = EpochsArray( data=X, events=epochs.events, info=create_info(X.shape[1], sfreq=1, ch_types='mag')) return epochs_
def test_epochs_tmin_tmax(kind): """Test spectral.spectral_connectivity with epochs and arrays.""" rng = np.random.RandomState(0) n_epochs, n_chs, n_times, sfreq, f = 10, 2, 2000, 1000., 20. data = rng.randn(n_epochs, n_chs, n_times) sig = np.sin(2 * np.pi * f * np.arange(1000) / sfreq) * np.hanning(1000) data[:, :, 500:1500] += sig info = create_info(n_chs, sfreq, 'eeg') if kind == 'epochs': tmin = -1 X = EpochsArray(data, info, tmin=tmin) elif kind == 'stc': tmin = -1 X = [SourceEstimate(d, [[0], [0]], tmin, 1. / sfreq) for d in data] else: assert kind == 'ndarray' tmin = 0 X = data # Parameters for computing connectivity fmin, fmax = f - 2, f + 2 kwargs = { 'method': 'coh', 'mode': 'multitaper', 'sfreq': sfreq, 'fmin': fmin, 'fmax': fmax, 'faverage': True, 'mt_adaptive': False, 'n_jobs': 1 } # Check the entire interval conn = spectral_connectivity(X, **kwargs) assert 0.89 < conn[0][1, 0] < 0.91 # Check a time interval before the sinusoid conn = spectral_connectivity(X, tmax=tmin + 0.5, **kwargs) assert 0 < conn[0][1, 0] < 0.15 # Check a time during the sinusoid conn = spectral_connectivity(X, tmin=tmin + 0.5, tmax=tmin + 1.5, **kwargs) assert 0.93 < conn[0][1, 0] <= 0.94 # Check a time interval after the sinusoid conn = spectral_connectivity(X, tmin=tmin + 1.5, tmax=tmin + 1.9, **kwargs) assert 0 < conn[0][1, 0] < 0.15 # Check for warning if tmin, tmax is outside of the time limits of data with pytest.warns(RuntimeWarning, match='start time tmin'): spectral_connectivity(X, **kwargs, tmin=tmin - 0.1) with pytest.warns(RuntimeWarning, match='stop time tmax'): spectral_connectivity(X, **kwargs, tmax=tmin + 2.5)
def _read_epochs(epochs_mat_fname, info): """ read the epochs from matfile """ data = scio.loadmat(epochs_mat_fname, squeeze_me=True)['data'] ch_names = [ch for ch in data['label'].tolist()] info['sfreq'] = data['fsample'].tolist() data = np.array([data['trial'].tolist()][0].tolist()) events = np.zeros((len(data), 3), dtype=np.int) events[:, 0] = np.arange(len(data)) events[:, 2] = 99 this_info = pick_info( info, [info['ch_names'].index(ch) for ch in ch_names], copy=True) return EpochsArray(data=data, info=this_info, events=events, tmin=0)
def mat2mne(data, chan_names='meg', chan_types=None, sfreq=250, events=None, tmin=0): from mne.epochs import EpochsArray from mne.io.meas_info import create_info data = np.array(data) print('Trials: {}, Labels: {}, TimePoints: {}'.format(*data.shape)) n_trial, n_chan, n_time = data.shape # chan names if isinstance(chan_names, str): chan_names = [chan_names + '_%02i' % chan for chan in range(n_chan)] if len(chan_names) != n_chan: raise ValueError('chan_names must be a string or a list of' 'n_chan strings') # chan types if isinstance(chan_types, str): chan_types = [chan_types] * n_chan elif chan_types is None: if isinstance(chan_names, str): if chan_names != 'meg': chan_types = [chan_names] * n_chan else: chan_types = ['mag'] * n_chan elif isinstance(chan_names, list): chan_types = ['mag' for chan in chan_names] else: raise ValueError('Specify chan_types') # events if events is None: events = np.c_[np.cumsum(np.ones(n_trial)) * 5 * sfreq, np.zeros(n_trial, int), np.zeros(n_trial)] else: events = np.array(events, int) if events.ndim == 1: events = np.c_[np.cumsum(np.ones(n_trial)) * 5 * sfreq, np.zeros(n_trial), events] elif (events.ndim != 2) or (events.shape[1] != 3): raise ValueError('events shape must be ntrial, or ntrials * 3') info = create_info(chan_names, sfreq, chan_types) return EpochsArray(data, info, events=np.array(events, int), verbose=False, tmin=tmin)
def test_plot_butterfly(): """Test butterfly view in epochs browse window.""" rng = np.random.RandomState(0) n_epochs, n_channels, n_times = 50, 30, 20 sfreq = 1000. data = np.sin(rng.randn(n_epochs, n_channels, n_times)) events = np.array([np.arange(n_epochs), [0] * n_epochs, np.ones([n_epochs], dtype=np.int)]).T chanlist = ['eeg' if chan < n_channels // 3 else 'ecog' if chan < n_channels // 2 else 'seeg' for chan in range(n_channels)] info = create_info(n_channels, sfreq, chanlist) epochs = EpochsArray(data, info, events) fig = epochs.plot(butterfly=True) keystotest = ['b', 'b', 'left', 'right', 'up', 'down', 'pageup', 'pagedown', '-', '+', '=', 'f11', 'home', '?', 'h', 'o', 'end'] for key in keystotest: fig.canvas.key_press_event(key) fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up fig.canvas.resize_event() fig.canvas.close_event() # closing and epoch dropping plt.close('all')
def test_array_epochs(): """Test creating evoked from array.""" tempdir = _TempDir() # creating rng = np.random.RandomState(42) data1 = rng.randn(20, 60) sfreq = 1e3 ch_names = ['EEG %03d' % (i + 1) for i in range(20)] types = ['eeg'] * 20 info = create_info(ch_names, sfreq, types) evoked1 = EvokedArray(data1, info, tmin=-0.01) # save, read, and compare evokeds tmp_fname = op.join(tempdir, 'evkdary-ave.fif') evoked1.save(tmp_fname) evoked2 = read_evokeds(tmp_fname)[0] data2 = evoked2.data assert_allclose(data1, data2) assert_array_almost_equal(evoked1.times, evoked2.times, 8) assert_equal(evoked1.first, evoked2.first) assert_equal(evoked1.last, evoked2.last) assert_equal(evoked1.kind, evoked2.kind) assert_equal(evoked1.nave, evoked2.nave) # now compare with EpochsArray (with single epoch) data3 = data1[np.newaxis, :, :] events = np.c_[10, 0, 1] evoked3 = EpochsArray(data3, info, events=events, tmin=-0.01).average() assert_allclose(evoked1.data, evoked3.data) assert_allclose(evoked1.times, evoked3.times) assert_equal(evoked1.first, evoked3.first) assert_equal(evoked1.last, evoked3.last) assert_equal(evoked1.kind, evoked3.kind) assert_equal(evoked1.nave, evoked3.nave) # test kind check with pytest.raises(ValueError, match='Invalid value'): EvokedArray(data1, info, tmin=0, kind=1) with pytest.raises(ValueError, match='Invalid value'): EvokedArray(data1, info, kind='mean') # test match between channels info and data ch_names = ['EEG %03d' % (i + 1) for i in range(19)] types = ['eeg'] * 19 info = create_info(ch_names, sfreq, types) pytest.raises(ValueError, EvokedArray, data1, info, tmin=-0.01)
def test_dss(): """Test DSS computations""" def rms(data): return np.sqrt(np.mean(data**2, axis=-1, keepdims=True)) rand = np.random.RandomState(123) # parameters n_trials, n_times, n_channels, noise_dims, snr = [200, 1000, 16, 10, 0.1] # 1 Hz sine wave with silence before & after pad = np.zeros(n_times // 3) signal_nsamps = n_times - 2 * pad.size sine = np.sin(2 * np.pi * np.arange(signal_nsamps) / float(signal_nsamps)) sine = np.r_[pad, sine, pad] signal = rand.randn(n_channels, 1) * sine[np.newaxis, :] # noise noise = np.einsum('hjk,ik->hij', rand.randn(n_trials, n_times, noise_dims), rand.randn(n_channels, noise_dims)) # signal plus noise, in a reasonable range for EEG data = 4e-6 * (noise / rms(noise) + snr * signal / rms(signal)) # perform DSS dss_mat, dss_data = dss(data, data_thresh=1e-3, bias_thresh=1e-3, bias_max_components=n_channels - 1) # handle scaling and possible 180 degree phase difference dss_trial1_comp1 = dss_data[0, 0] / np.abs(dss_data[0, 0]).max() dss_trial1_comp1 *= np.sign(np.dot(dss_trial1_comp1, sine)) assert_allclose(dss_trial1_comp1, sine, rtol=0, atol=0.2) # test handling of epochs objects sfreq = 1000 first_samp = 150 samps = np.arange(first_samp, first_samp + n_trials * n_times * 2, n_times * 2)[:, np.newaxis] events = np.c_[samps, np.zeros_like(samps), np.ones_like(samps)] ch_names = ['EEG{0:03}'.format(n + 1) for n in range(n_channels)] ch_types = ['eeg'] * n_channels info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) epochs = EpochsArray(data, info=info, events=events, event_id={'fake': 1}) dss_mat_epochs = dss(epochs, data_thresh=1e-3, bias_thresh=1e-3, bias_max_components=n_channels - 1, return_data=False) # make sure we get the same answer when data is an epochs object dss_mat = dss_mat / dss_mat.max() dss_mat_epochs = dss_mat_epochs / dss_mat_epochs.max() assert_allclose(dss_mat, dss_mat_epochs)
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_equalize_channels(): """Test equalizing channels and their ordering.""" # This function only tests the generic functionality of equalize_channels. # Additional tests for each instance type are included in the accompanying # test suite for each type. pytest.raises(TypeError, equalize_channels, ['foo', 'bar'], match='Instances to be modified must be an instance of') raw = RawArray([[1.], [2.], [3.], [4.]], create_info(['CH1', 'CH2', 'CH3', 'CH4'], sfreq=1.)) epochs = EpochsArray([[[1.], [2.], [3.]]], create_info(['CH5', 'CH2', 'CH1'], sfreq=1.)) cov = make_ad_hoc_cov( create_info(['CH2', 'CH1', 'CH8'], sfreq=1., ch_types='eeg')) cov['bads'] = ['CH1'] ave = EvokedArray([[1.], [2.]], create_info(['CH1', 'CH2'], sfreq=1.)) raw2, epochs2, cov2, ave2 = equalize_channels([raw, epochs, cov, ave], copy=True) # The Raw object was the first in the list, so should have been used as # template for the ordering of the channels. No bad channels should have # been dropped. assert raw2.ch_names == ['CH1', 'CH2'] assert_array_equal(raw2.get_data(), [[1.], [2.]]) assert epochs2.ch_names == ['CH1', 'CH2'] assert_array_equal(epochs2.get_data(), [[[3.], [2.]]]) assert cov2.ch_names == ['CH1', 'CH2'] assert cov2['bads'] == cov['bads'] assert ave2.ch_names == ave.ch_names assert_array_equal(ave2.data, ave.data) # All objects should have been copied, except for the Evoked object which # did not have to be touched. assert raw is not raw2 assert epochs is not epochs2 assert cov is not cov2 assert ave is ave2 # Test in-place operation raw2, epochs2 = equalize_channels([raw, epochs], copy=False) assert raw is raw2 assert epochs is epochs2
# Add a 50 Hz sinusoidal burst to the noise and ramp it. 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 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) ############################################################################### # 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,
data_pln = data_pln.swapaxes(2, 0) data_pln = data_pln.swapaxes(2, 1) # Setup data for epochs and cross validation X = np.vstack([data_cls, data_pln]) y = np.concatenate([np.zeros(len(data_cls)), np.ones(len(data_pln))]) cv = StratifiedKFold(n_splits=10, shuffle=True) # Create epochs to use for classification n_trial, n_chan, n_time = X.shape events = np.vstack((range(n_trial), np.zeros(n_trial, int), y.astype(int))).T chan_names = ['MEG %i' % chan for chan in range(n_chan)] chan_types = ['mag'] * n_chan sfreq = 250 info = create_info(chan_names, sfreq, chan_types) epochs = EpochsArray(data=X, info=info, events=events, verbose=False) epochs.times = selected_times[:n_time] epochs.crop(-3.8, None) # fit model and score gat = GeneralizationAcrossTime( scorer="accuracy", cv=cv, predict_method="predict") gat.fit(epochs, y=y) gat.score(epochs, y=y) # Save model joblib.dump(gat, data_path + "decode_time_gen/%s_gat_tr.jl" % subject) # make matrix plot and save it fig = gat.plot(
# Add a 50 Hz sinusoidal burst to the noise and ramp it. 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 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 # ====================
data_cls = np.asarray(cls_all) data_pln = np.asarray(pln_all) # Setup data for epochs and cross validation X = np.vstack([data_cls, data_pln]) y = np.concatenate([np.zeros(len(data_cls)), np.ones(len(data_pln))]) cv = StratifiedKFold(n_splits=7, shuffle=True) # Create epochs to use for classification n_trial, n_chan, n_time = X.shape events = np.vstack((range(n_trial), np.zeros(n_trial, int), y.astype(int))).T chan_names = ['MEG %i' % chan for chan in range(n_chan)] chan_types = ['mag'] * n_chan sfreq = 250 info = create_info(chan_names, sfreq, chan_types) epochs = EpochsArray(data=X, info=info, events=events, verbose=False) epochs.times = selected_times[:n_time] # make classifier clf = LogisticRegression(C=0.0001) # fit model and score gat = GeneralizationAcrossTime( clf=clf, scorer="roc_auc", cv=cv, predict_method="predict") gat.fit(epochs, y=y) gat.score(epochs, y=y) # Save model joblib.dump(gat, data_path + "decode_time_gen/gat_ge.jl") # make matrix plot and save it
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)