def test_frequency_attr(): data.attr['xxx'] = True freq = frequency(data) assert freq.attr['xxx'] timefreq = timefrequency(data, method='spectrogram') assert timefreq.attr['xxx']
def test_trans_timefrequency_stft(): seed(0) data = create_data(n_trial=1, n_chan=2, s_freq=s_freq, time=(0, dur)) NW = 3 timefreq = timefrequency(data, method='stft', taper='dpss', NW=NW) assert timefreq.list_of_axes == ('chan', 'time', 'freq', 'taper') assert timefreq.data[0].shape == (data.number_of('chan')[0], 3, s_freq, NW * 2 - 1)
def compute_frequency(dat, taper, duration): """Remove epochs which have very high activity in high-freq range, then average over time (only high-freq range) and ALL the frequencies.""" dat = timefrequency( dat, method='spectrogram', taper=taper, duration=duration, halfbandwidth=HALFBANDWIDTH, ) return dat
def compute_quick_spectrogram(ieeg_file, freq): with ieeg_file.open('rb') as f: data = load(f) # TODO: from parameters reref = 'average' method = 'spectrogram' duration = 2 data = montage(data, ref_to_avg=True, method=reref) tf = timefrequency(data, method=method, duration=duration) dat0 = math(select(tf, freq=freq), operator_name='mean', axis='freq') return dat0
def test_trans_timefrequency_spectrogram(): seed(0) data = create_data(n_trial=1, n_chan=2, s_freq=s_freq, time=(0, dur)) # the first channel is ~5 times larger than the second channel data.data[0][0, :] *= 5 timefreq = timefrequency(data, method='spectrogram', detrend=None, taper=None, overlap=0) p_time = math(data, operator_name=('square', 'sum'), axis='time') p_freq = math(timefreq, operator_name='sum', axis='freq') assert (4.7**2 < p_freq.data[0][0, :] / p_freq.data[0][1, :]).all() assert (p_freq.data[0][0] / p_freq.data[0][1] < 5.7**2).all() # with random data, parseval only holds with boxcar assert_array_almost_equal(p_time(trial=0), sum(p_freq(trial=0) * data.s_freq, axis=1))
def extract_band_power( edf_filepath: str, bands: dict = pysleep_defaults.default_freq_bands, chans_to_consider: List[str] = None, epochoffset_secs: float = None, end_time: float = None, epoch_len: int = pysleep_defaults.epoch_len) -> pd.DataFrame: """ :param edf_filepath: The edf to extract bandpower for :param bands: bands to extract power in, if None, then defaults will be used i.e. bands = { 'delta': (1, 4), 'theta': (4, 7), 'alpha': (8, 12), 'sigma': (11, 16), 'slow_sigma': (11, 13), 'fast_sigma': (13, 16), 'beta': (13, 30) } :param chans_to_consider: which channels to consider :param epochoffset_secs: start time of the recording to extract band power for (when do epochs start), onset is measured from this :param end_time: end time of the recording to extract band power for :param epoch_len: how long a time bin you want your power to be averaged over :return: chan_epoch_band as a numpy array, and times, bands, chans """ d = Dataset(edf_filepath) if not (epochoffset_secs is None or epochoffset_secs >= 0): raise error_handling.EEGError('Epochoffset is negative!' + str(epochoffset_secs)) if not ((end_time is None) or (end_time <= d.header['n_samples'] / d.header['s_freq'])): raise error_handling.EEGError("end time (" + str(end_time) + ") larger than record end!" + str(d.header['n_samples'] / d.header['s_freq'])) data = d.read_data(begtime=epochoffset_secs, endtime=end_time, chan=chans_to_consider) power = timefrequency(data, method='spectrogram') abs_power = math(power, operator_name='abs') chan_time_freq = abs_power.data[0] all_chans = np.ones((chan_time_freq.shape[0], ), dtype=bool) epochoffset_secs = 0 if epochoffset_secs is None else epochoffset_secs time_axis = np.round(abs_power.axis['time'][0], 2) - epochoffset_secs freq_axis = np.round(abs_power.axis['freq'][0], 2) chan_axis = abs_power.axis['chan'][0] freq_binsize = freq_axis[1] - freq_axis[0] assert epoch_len > 0, "epoch len must be greater than zero" times = np.arange(0, time_axis[-1], epoch_len) cont = [] for band, freqs in bands.items(): freq_mask = (freqs[0] <= freq_axis) & (freqs[1] >= freq_axis) for win_start in times: time_mask = (win_start < time_axis) & (time_axis < win_start + epoch_len) idx = np.ix_(all_chans, time_mask, freq_mask) if idx: chan_epoch_per_band = chan_time_freq[idx].mean(axis=1).mean( axis=1) / freq_binsize else: chan_epoch_per_band = np.zeros((len(chans_to_consider), )) for chan, power in zip(chan_axis, chan_epoch_per_band): cont.append( pd.Series({ 'onset': win_start, 'duration': epoch_len, 'band': band.split('_')[0], 'chan': chan, 'power': power })) band_power = pd.concat( cont, axis=1).T.apply(lambda x: pd.to_numeric(x, errors='ignore')) return band_power