Beispiel #1
0
def test_stockwell_api():
    """Test stockwell functions."""
    raw = read_raw_fif(raw_fname)
    event_id, tmin, tmax = 1, -0.2, 0.5
    event_name = op.join(base_dir, 'test-eve.fif')
    events = read_events(event_name)
    epochs = Epochs(
        raw,
        events,  # XXX pick 2 has epochs of zeros.
        event_id,
        tmin,
        tmax,
        picks=[0, 1, 3])
    for fmin, fmax in [(None, 50), (5, 50), (5, None)]:
        with pytest.warns(RuntimeWarning, match='padding'):
            power, itc = tfr_stockwell(epochs,
                                       fmin=fmin,
                                       fmax=fmax,
                                       return_itc=True)
        if fmax is not None:
            assert (power.freqs.max() <= fmax)
        with pytest.warns(RuntimeWarning, match='padding'):
            power_evoked = tfr_stockwell(epochs.average(),
                                         fmin=fmin,
                                         fmax=fmax,
                                         return_itc=False)
        # for multitaper these don't necessarily match, but they seem to
        # for stockwell... if this fails, this maybe could be changed
        # just to check the shape
        assert_array_almost_equal(power_evoked.data, power.data)
    assert (isinstance(power, AverageTFR))
    assert (isinstance(itc, AverageTFR))
    assert_equal(power.data.shape, itc.data.shape)
    assert (itc.data.min() >= 0.0)
    assert (itc.data.max() <= 1.0)
    assert (np.log(power.data.max()) * 20 <= 0.0)
    assert (np.log(power.data.max()) * 20 <= 0.0)
    with pytest.raises(TypeError, match='ndarray'):
        tfr_array_stockwell('foo', 1000.)
    data = np.random.RandomState(0).randn(1, 1024)
    with pytest.raises(ValueError, match='3D with shape'):
        tfr_array_stockwell(data, 1000.)
    data = data[np.newaxis]
    power, itc, freqs = tfr_array_stockwell(data, 1000., return_itc=True)
    assert_allclose(itc, np.ones_like(itc))
    assert power.shape == (1, len(freqs), data.shape[-1])
    assert_array_less(0, power)
    def S_transform(self, epoch_data, baseline_corr=True, n_jobs=-1):
        """Applay Stockwell-transform to epoch_data.
        
        Parameters
        ----------
        epoch_data : {array-like, sample × index}.
            finger flection data. 
        
        baseline_corr: bool
            if True, baseline correction is used
        
        n_jobs: int 
            n_jobs is parallel computing parameter which how many core will be used for analysis.
            if enter n_job=-1, the system will use all available threads.
        
        Returns
        ----------
        st_power: time-frequency power
        itc: inter trial coherence
        freqs: frequencies range was used for analysis.
        """

        st_power, itc, freqs = tfr_array_stockwell(epoch_data,
                                                   self.srate,
                                                   fmin=self.filter_band[0],
                                                   fmax=self.filter_band[1],
                                                   width=.5,
                                                   return_itc=True,
                                                   n_jobs=n_jobs)
        if baseline_corr == True:
            mne.baseline.rescale(st_power,
                                 self.time,
                                 self.baseline,
                                 mode='logratio',
                                 copy=False)

        return st_power, itc, freqs
Beispiel #3
0
def compute_features(eoi, data, data_80, data_hil, win_size, f_ini, f_fin,
                     sfreq, th, bs, channel, version, file_id):
    epoch = np.zeros([1, 1, win_size * 2])
    p_events = False
    Ev_ini = list()
    Ev_fi = list()
    dur_f = list()
    dur_t = list()
    area = list()
    entropy_calc = list()
    perimeter = list()
    symmetryt = list()
    symmetryf = list()
    oscillations = list()
    kurtosis = list()
    skewness = list()
    inst_freq = list()
    amplitude = list()
    amplitude_norm = list()
    mean_power = list()
    max_power = list()
    for idx, event in enumerate(eoi):
        # Compute Stockwell transform for each eoi, binarize and obtain event features
        mid_event = ((event[1] + event[0]) / 2).astype(int)
        epoch[0, 0, :] = data[:, mid_event - win_size:mid_event + win_size]
        pwr = tfr_array_stockwell(epoch,
                                  fmin=0,
                                  fmax=sfreq / 2,
                                  width=3,
                                  sfreq=sfreq,
                                  n_fft=int(win_size * 2))
        single_epoch = pwr[0][0, f_ini:f_fin,
                              int(win_size / 4):-int(win_size / 4)]
        single_epoch_all = pwr[0][0, 0:f_fin,
                                  int(win_size / 4):-int(win_size / 4)]
        frec_vector = pwr[2]
        # Extract properties from pwr "image"

        image = single_epoch.astype('float32')
        image_all = single_epoch_all.astype('float32')
        if version == 1:
            # H-dome correction
            seed = np.copy(image)
            seed[1:-1, 1:-1] = image.min()
            mask = image
            dilated = reconstruction(seed, mask, method='dilation')
            image_corrected = image - dilated
            # Thresholding with yet
            thresh = threshold_yen(image_corrected)
            binary = image_all > thresh

        if version == 2:
            t_mig = int(single_epoch.shape[1] / 2)
            thresh = np.quantile(single_epoch[:, t_mig], 0.75)
            binary = image_all > thresh
        label_image = label(binary)
        # Extract features
        n_events = 0
        for idx2, region in enumerate(regionprops(label_image)):
            minf, mint, maxf, maxt = region.bbox
            # Just consider events that its middle frequency is higher or equal than f_ini
            mid_f = (frec_vector[minf] + frec_vector[maxf]) / 2
            # Just use events that are in the middle of the st (because is centered in the eoi)
            if (single_epoch.shape[1] / 2 >= mint) & (
                    single_epoch.shape[1] / 2 <= maxt) & (mid_f >= f_ini):
                n_events = n_events + 1
                # Global times
                Ev_ini.append(event[0])
                Ev_fi.append(event[1])
                # Duration in frequency and time
                dur_f.append(maxf - minf)
                dur_t.append(maxt - mint)
                # Area
                area.append(region.area)
                # Entropy
                aux = np.zeros(image_all.shape)
                aux[minf:maxf, mint:maxt] = image_all[minf:maxf, mint:maxt]
                entropy_calc.append(shannon_entropy(aux))
                # Other features from regionpropos
                perimeter.append(region.perimeter)
                # Symmetry
                mean_power.append(np.mean(image_all[minf:maxf, mint:maxt]))
                max_power.append(np.max(image_all[minf:maxf, mint:maxt]))

                hfo = data_80[0, mid_event - int(3 * win_size / 4) + mint -
                              10:mid_event - int(3 * win_size / 4) + maxt + 10]
                hfo_hil = data_hil[0, mid_event - int(3 * win_size / 4) +
                                   mint - 10:mid_event -
                                   int(3 * win_size / 4) + maxt + 10]
                max_id = np.where(image_all == np.max(image_all[minf:maxf,
                                                                mint:maxt]))

                symt = (max_id[1][0] - mint) / (maxt - mint)
                symf = (max_id[0][0] - minf) / (maxf - minf)

                symmetryt.append(symt)
                symmetryf.append(symf)
                # number of oscillations (number of peaks)
                peaks = signal.find_peaks(hfo)
                hil_th = (hfo_hil > th / 2)
                ispeak = np.zeros(hfo.shape, dtype=bool)
                ispeak[peaks[0]] = True
                oscillations.append(np.sum(ispeak * hil_th))

                # Kurtosis and skewness (from hilbert transform)

                kurtosis.append(stats.kurtosis(hfo_hil))
                skewness.append(stats.skew(hfo_hil))
                amplitude.append(np.max(hfo_hil))
                amplitude_norm.append(np.max(hfo_hil) / np.mean(bs))
                # Mean peak frequency and std peak frequency
                peaks = signal.find_peaks(np.abs(hfo))
                inst_freq.append(1 / np.mean(np.diff(peaks[0])) * sfreq * 0.5)

                if p_events == True:
                    ev = pd.DataFrame([[
                        mint, maxt, minf, maxf, region.area,
                        shannon_entropy(aux), symt, symf,
                        np.sum(ispeak * hil_th),
                        1 / np.mean(np.diff(peaks[0])) * sfreq * 0.5,
                        np.max(hfo_hil)
                    ]],
                                      columns=[
                                          't_ini', 't_fin', 'f_ini', 'f_fin',
                                          'Area', 'Entropy', 'Symmetry T',
                                          'Symmetry F', 'Oscillations',
                                          'Inst freq', 'Amplitude'
                                      ])
                    dat = data[0, mid_event - win_size:mid_event + win_size]
                    datfilt = data_80[0, mid_event - win_size:mid_event +
                                      win_size]
                    tf_dat = pwr[0][0, :, int(win_size / 4):-int(win_size / 4)]
                    tf_dat_bin = tf_dat > thresh
                    frec_vector = (pwr[2])
                    image_path = '/home/cmigliorelli/synology/Epilepsia_HSJD/Resultados/hfos_graficas/'
                    plot_eoi(ev, sfreq, dat, datfilt, tf_dat, tf_dat_bin,
                             frec_vector, image_path, channel, idx, idx2,
                             file_id)

    feature_list = [
        Ev_ini, Ev_fi, dur_f, dur_t, area, entropy_calc, perimeter, symmetryt,
        symmetryf, oscillations, kurtosis, skewness, inst_freq, amplitude,
        amplitude_norm, mean_power, max_power
    ]
    return feature_list