Ejemplo n.º 1
0
 def apply(self, chunk: np.ndarray):
     if len(chunk) <= self.upd_n_samples:
         x = self.buffer.update_buffer(chunk)
         if self.samples_counter > self.buffer.buffer.shape[0]:
             y = band_hilbert(x[:self.ada_n_taps], self.fs,
                              self.band)[self.ada_n_taps // 2]
             self.rls.adapt(
                 y, x[self.ada_n_taps // 2 + self.delay - self.n_taps +
                      1:self.ada_n_taps // 2 + 1 + self.delay])
         self.samples_counter += len(chunk)
         return sg.lfilter(self.rls.w[::-1], [1.], x)[-len(chunk):]
     else:
         return rt_emulate(self, chunk, self.upd_n_samples)
Ejemplo n.º 2
0
    fb_type = df.query('block_number==6')['block_name'].values[0]

    # rename FB blocks to "FB"
    df['block_name'] = df['block_name'].apply(lambda x: 'FB'
                                              if x == fb_type in x else x)

    # select FB blocks
    df = df.loc[df['block_name'].isin(['Baseline'])]

    # remove eyes artifacts ICA
    df[channels] = df[channels].values.dot(eye_rejection_matrix)

    raw_p4 = df['P4'].values
    ba = sg.butter(1, np.array([1, 50]) / fs * 2, 'band')

    env = np.abs(band_hilbert(sg.filtfilt(*ba, raw_p4), FS, band))
    online_env = CFIRBandEnvelopeDetector(band,
                                          FS,
                                          IdentityFilter(),
                                          n_taps=FS,
                                          delay_ms=100).apply(raw_p4)

    delay, corr = opt_delay_corr(env, online_env)
    delays.append(delay)
    corrds.append(corr)
    print(subj_id)

import pylab as plt
plt.scatter(corrds, delays, alpha=0.7, s=50)
# plt.scatter(corrds2, delays2, alpha=0.7, s=50)
plt.plot()
Ejemplo n.º 3
0
    import pandas as pd
    dataset = "alpha2-delay-subj-21_12-06_12-15-09"
    eeg_df = pd.read_pickle('data/rest_state_probes.pkl').query(
        'dataset=="{}"'.format(dataset))

    x = eeg_df['eeg'].iloc[20000:30000].values
    #x = np.random.normal(size=5000)
    band = [8, 12]
    fs = 500
    delay = 0
    from release.utils import magnitude_spectrum
    _, weights = magnitude_spectrum(eeg_df['eeg'].iloc[10000:20000].values, fs,
                                    2000)
    #weights = np.median(np.abs(sg.stft(eeg_df['eeg'].iloc[10000:20000].values, fs, nperseg=2000, nfft=2000, return_onesided=False))[2], 1)

    y = np.roll(np.abs(band_hilbert(x, fs, band)), delay)

    # rect_filter_y = RectEnvDetector(band, fs, delay, 150).apply(x)
    whilbert_filter_y = np.abs(
        WHilbertFilter(band, fs, delay, 500, 2000).apply(x))
    cfir_filter_y = np.abs(
        CFIRBandEnvelopeDetector(band, fs, delay, 500, 2000, weights).apply(x))
    rlscfir_filter_y = np.abs(
        AdaptiveCFIRBandEnvelopeDetector(band,
                                         fs,
                                         delay,
                                         500,
                                         2000,
                                         weights=None,
                                         max_chunk_size=1).apply(x))
    ffiltar_filter_y = np.abs(
Ejemplo n.º 4
0
    # subj eeg
    data = probes_df.query('subj_id=="{}" '.format(subj_id))
    data = data.loc[data.block_number.isin(FB_ALL)]

    # subj fb type
    fb_type = datasets_df.query(
        'subj_id=={}'.format(subj_id))['fb_type'].values[0]

    # subj band

    band = np.array(
        datasets_df.query('subj_id=={}'.format(subj_id))['band'].values[0])

    # compute envelope
    env = np.abs(band_hilbert(data['P4'].values, FS, band))
    online_env = data['online_envelope']

    delay, corr = opt_delay_corr(env, online_env)
    delays.append(delay)
    corrds.append(corr)

    online_env = CFIRBandEnvelopeDetector(band,
                                          FS,
                                          IdentityFilter(),
                                          n_taps=FS,
                                          delay_ms=60).apply(data['P4'].values)
    delay2, corr2 = opt_delay_corr(env, online_env)

    delays2.append(delay2)
    corrds2.append(corr2)
    # subj eeg
    data = probes_df.query('subj_id=="{}" '.format(subj_id))

    # subj fb type
    fb_type = datasets_df.query(
        'subj_id=={}'.format(subj_id))['fb_type'].values[0]

    # subj band
    band = np.array(
        datasets_df.query('subj_id=={}'.format(subj_id))['band'].values[0])

    # block numbers utils
    block_numbers = data['block_number'].values

    ch_data = data.loc[data.block_number.isin(FB_ALL), channel].values
    env = np.abs(band_hilbert(ch_data, FS, band))
    # env = np.roll(np.abs(CFIRBandEnvelopeDetector(band, FS, 250).apply(ch_data)), -250)
    photo_data = data.loc[data.block_number.isin(FB_ALL), 'PHOTO'].values
    # photo_data = env

    # compute envelope
    spindles, spindle_starts = find_spindles(
        env, photo_data > threshold_factor * np.median(photo_data))
    spindle = np.mean(spindles[spindle_starts < len(env) // 2], 0)
    norm = np.median(spindle[:FS])
    spindle1 = spindle / norm
    stats_df = stats_df.append(
        pd.DataFrame({
            'subj_id': subj_id,
            'fb_type': fb_type,
            'spindle': spindle1,
Ejemplo n.º 6
0
    # GFP threshold artifact segments
    # th = np.abs(df[channels[:-1]]).rolling(int(fs), center=True).mean().mean(1)
    # df = df.loc[th < 100e-6]

    # define SNR
    x = df['P4'].values[5 * FS:]

    # drop noisy datasets
    if len(x) < N_SAMPLES_TRAIN + N_SAMPLES_TEST + 10 * FS: continue

    # find individual alpha and snr
    band, snr = individual_max_snr_band(x, FS)
    print(j_dataset, band, snr)

    # save x
    an = band_hilbert(x, fs,
                      band)[5 * FS:N_SAMPLES_TRAIN + N_SAMPLES_TEST + 5 * FS]
    x = x[5 * FS:N_SAMPLES_TRAIN + N_SAMPLES_TEST + 5 * FS]

    # train band
    band_train, snr_train = individual_max_snr_band(x[:N_SAMPLES_TRAIN], FS)
    print(j_dataset, band_train, snr_train, '\n')

    # save info
    band, snr = individual_max_snr_band(x[:N_SAMPLES_TRAIN], FS)
    eeg_df = eeg_df.append(pd.DataFrame(
        {
            'sim': 0,
            'dataset': dataset,
            'snr': snr,
            'band_left_train': band_train[0],
            'band_right_train': band_train[1],
Ejemplo n.º 7
0
plt.close()

# whilbert
delay = 100
filt = WHilbertFilter(band, FS, delay, 200, 2000)
y = filt.apply(eeg)

plt.figure(figsize=(4, 2))
plt.plot(y[slc].real, cm['b'], linestyle='-', alpha=1)
plt.plot(y[slc].imag, cm['b'], linestyle='--', alpha=0.5)
setup_gca()
plt.savefig(fdir + 'whilb_an.png', dpi=500, transparent=True)
plt.close()

win_slc = slice(550, 750)
win_x = band_hilbert(eeg[slc][win_slc], FS, band, 2000)

plt.figure(figsize=(4, 2))
plt.plot(eeg[slc], alpha=0)
#plt.plot(np.arange(wt)[win_slc], win_x.imag, cm['b'], linestyle='--', alpha=0.5)
plt.plot(np.arange(wt)[win_slc], win_x.real, cm['b'])
# plt.plot(np.arange(wt)[win_slc][100], win_x.real[100], 'k', marker='o', markersize=10)
# plt.plot(np.arange(wt)[win_slc][100], win_x.imag[100], 'k', marker='o', markersize=10, alpha=0.5)
setup_gca()
plt.savefig(fdir + 'whilb_filt_win.png', dpi=500, transparent=True)
plt.close()

plt.figure(figsize=(4, 2))
plt.plot(eeg[slc], alpha=0)
plt.plot(np.arange(wt)[win_slc],
         win_x.imag,