Beispiel #1
0
def test_rsp_rrv():

    rsp90 = nk.rsp_simulate(duration=60,
                            sampling_rate=1000,
                            respiratory_rate=90,
                            random_state=42)
    rsp110 = nk.rsp_simulate(duration=60,
                             sampling_rate=1000,
                             respiratory_rate=110,
                             random_state=42)

    cleaned90 = nk.rsp_clean(rsp90, sampling_rate=1000)
    _, peaks90 = nk.rsp_peaks(cleaned90)
    rsp_rate90 = nk.rsp_rate(peaks90, desired_length=len(rsp90))

    cleaned110 = nk.rsp_clean(rsp110, sampling_rate=1000)
    _, peaks110 = nk.rsp_peaks(cleaned110)
    rsp_rate110 = nk.rsp_rate(peaks110, desired_length=len(rsp110))

    rsp90_rrv = nk.rsp_rrv(rsp_rate90, peaks90)
    rsp110_rrv = nk.rsp_rrv(rsp_rate110, peaks110)

    assert np.array(rsp90_rrv["RRV_SDBB"]) < np.array(rsp110_rrv["RRV_SDBB"])
    assert np.array(rsp90_rrv["RRV_RMSSD"]) < np.array(rsp110_rrv["RRV_RMSSD"])
    assert np.array(rsp90_rrv["RRV_SDSD"]) < np.array(rsp110_rrv["RRV_SDSD"])
    # assert np.array(rsp90_rrv["RRV_pNN50"]) == np.array(rsp110_rrv["RRV_pNN50"]) == np.array(rsp110_rrv["RRV_pNN20"]) == np.array(rsp90_rrv["RRV_pNN20"]) == 0
    # assert np.array(rsp90_rrv["RRV_TINN"]) < np.array(rsp110_rrv["RRV_TINN"])
    # assert np.array(rsp90_rrv["RRV_HTI"]) > np.array(rsp110_rrv["RRV_HTI"])
    assert np.array(rsp90_rrv["RRV_HF"]) < np.array(rsp110_rrv["RRV_HF"])
    assert np.array(rsp90_rrv["RRV_LF"]) < np.array(rsp110_rrv["RRV_LF"])
Beispiel #2
0
def test_signal_rate():  # since singal_rate wraps signal_period, the latter is tested as well

    # Test with array.
    duration = 10
    sampling_rate = 1000
    signal = nk.signal_simulate(duration=duration, sampling_rate=sampling_rate, frequency=1)
    info = nk.signal_findpeaks(signal)
    rate = nk.signal_rate(peaks=info["Peaks"], sampling_rate=1000, desired_length=len(signal))
    assert rate.shape[0] == duration * sampling_rate

    # Test with dictionary.produced from signal_findpeaks.
    assert info[list(info.keys())[0]].shape == (info["Peaks"].shape[0],)

    # Test with DataFrame.
    duration = 120
    sampling_rate = 1000
    rsp = nk.rsp_simulate(
        duration=duration, sampling_rate=sampling_rate, respiratory_rate=15, method="sinuosoidal", noise=0
    )
    rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=sampling_rate)
    signals, info = nk.rsp_peaks(rsp_cleaned)
    rate = nk.signal_rate(signals, sampling_rate=sampling_rate, desired_length=duration * sampling_rate)
    assert rate.shape == (signals.shape[0],)

    # Test with dictionary.produced from rsp_findpeaks.
    rate = nk.signal_rate(info, sampling_rate=sampling_rate, desired_length=duration * sampling_rate)
    assert rate.shape == (duration * sampling_rate,)
Beispiel #3
0
def test_signal_rate():

    # Test with array.
    signal = nk.signal_simulate(duration=10, sampling_rate=1000, frequency=1)
    info = nk.signal_findpeaks(signal)
    rate = nk.signal_rate(peaks=info["Peaks"],
                          sampling_rate=1000,
                          desired_length=None)
    assert rate.shape[0] == len(info["Peaks"])

    # Test with dictionary.produced from signal_findpeaks.
    assert info[list(info.keys())[0]].shape == (info["Peaks"].shape[0], )

    # Test with DataFrame.
    rsp = nk.rsp_simulate(duration=120,
                          sampling_rate=1000,
                          respiratory_rate=15,
                          method="sinuosoidal",
                          noise=0)
    rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=1000)
    signals, info = nk.rsp_peaks(rsp_cleaned)
    rate = nk.signal_rate(signals, sampling_rate=1000)
    assert rate.shape == (signals.shape[0], )

    # Test with dictionary.produced from rsp_findpeaks.
    test_length = 30
    rate = nk.signal_rate(info, sampling_rate=1000, desired_length=test_length)
    assert rate.shape == (test_length, )
Beispiel #4
0
def test_rsp_rrv():

    rsp90 = nk.rsp_simulate(duration=60,
                            sampling_rate=1000,
                            respiratory_rate=90,
                            random_state=42)
    rsp110 = nk.rsp_simulate(duration=60,
                             sampling_rate=1000,
                             respiratory_rate=110,
                             random_state=42)

    cleaned90 = nk.rsp_clean(rsp90, sampling_rate=1000)
    _, peaks90 = nk.rsp_peaks(cleaned90)
    rsp_rate90 = nk.signal_rate(peaks90, desired_length=len(rsp90))

    cleaned110 = nk.rsp_clean(rsp110, sampling_rate=1000)
    _, peaks110 = nk.rsp_peaks(cleaned110)
    rsp_rate110 = nk.signal_rate(peaks110, desired_length=len(rsp110))

    rsp90_rrv = nk.rsp_rrv(rsp_rate90, peaks90)
    rsp110_rrv = nk.rsp_rrv(rsp_rate110, peaks110)

    assert np.array(rsp90_rrv["RRV_SDBB"]) < np.array(rsp110_rrv["RRV_SDBB"])
    assert np.array(rsp90_rrv["RRV_RMSSD"]) < np.array(rsp110_rrv["RRV_RMSSD"])
    assert np.array(rsp90_rrv["RRV_SDSD"]) < np.array(rsp110_rrv["RRV_SDSD"])
    # assert np.array(rsp90_rrv["RRV_pNN50"]) == np.array(rsp110_rrv["RRV_pNN50"]) == np.array(rsp110_rrv["RRV_pNN20"]) == np.array(rsp90_rrv["RRV_pNN20"]) == 0
    # assert np.array(rsp90_rrv["RRV_TINN"]) < np.array(rsp110_rrv["RRV_TINN"])
    # assert np.array(rsp90_rrv["RRV_HTI"]) > np.array(rsp110_rrv["RRV_HTI"])
    assert np.array(rsp90_rrv["RRV_HF"]) < np.array(rsp110_rrv["RRV_HF"])
    assert np.isnan(rsp90_rrv["RRV_LF"][0])
    assert np.isnan(rsp110_rrv["RRV_LF"][0])

    # Test warning on too short duration
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r"The duration of recording is too short.*"):
        short_rsp90 = nk.rsp_simulate(duration=10,
                                      sampling_rate=1000,
                                      respiratory_rate=90,
                                      random_state=42)
        short_cleaned90 = nk.rsp_clean(short_rsp90, sampling_rate=1000)
        _, short_peaks90 = nk.rsp_peaks(short_cleaned90)
        short_rsp_rate90 = nk.signal_rate(short_peaks90,
                                          desired_length=len(short_rsp90))

        nk.rsp_rrv(short_rsp_rate90, short_peaks90)
Beispiel #5
0
def test_rsp_peaks():

    rsp = nk.rsp_simulate(duration=120, sampling_rate=1000,
                          respiratory_rate=15, random_state=42)
    rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=1000)
    signals, info = nk.rsp_peaks(rsp_cleaned)
    assert signals.shape == (120000, 2)
    assert signals["RSP_Peaks"].sum() == 28
    assert signals["RSP_Troughs"].sum() == 28
    assert info["RSP_Peaks"].shape[0] == 28
    assert info["RSP_Troughs"].shape[0] == 28
    assert np.allclose(info["RSP_Peaks"].sum(), 1643817)
    assert np.allclose(info["RSP_Troughs"].sum(), 1586588)
    # Assert that extrema start with a trough and end with a peak.
    assert info["RSP_Peaks"][0] > info["RSP_Troughs"][0]
    assert info["RSP_Peaks"][-1] > info["RSP_Troughs"][-1]
Beispiel #6
0
def test_rsp_amplitude():

    rsp = nk.rsp_simulate(duration=120, sampling_rate=1000,
                          respiratory_rate=15, method="sinusoidal", noise=0)
    rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=1000)
    signals, info = nk.rsp_peaks(rsp_cleaned)

    # Test with dictionary.
    amplitude = nk.rsp_amplitude(rsp, signals)
    assert amplitude.shape == (rsp.size, )
    assert np.abs(amplitude.mean() - 1) < 0.01

    # Test with DataFrame.
    amplitude = nk.rsp_amplitude(rsp, info)
    assert amplitude.shape == (rsp.size, )
    assert np.abs(amplitude.mean() - 1) < 0.01
Beispiel #7
0
def test_rsp_rate():

    rsp = nk.rsp_simulate(duration=120, sampling_rate=1000,
                          respiratory_rate=15, method="sinusoidal", noise=0)
    rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=1000)
    signals, info = nk.rsp_peaks(rsp_cleaned)

    # Test with dictionary.
    test_length = 30
    rate = nk.rsp_rate(peaks=info, sampling_rate=1000,
                       desired_length=test_length)
    assert rate.shape == (test_length, )
    assert np.abs(rate.mean() - 15) < 0.2

    # Test with DataFrame.
    rate = nk.rsp_rate(signals, sampling_rate=1000)
    assert rate.shape == (signals.shape[0], )
    assert np.abs(rate.mean() - 15) < 0.2
Beispiel #8
0
def respiration_sequence_features(data,
                                  events,
                                  column='PZT',
                                  known_sequences=None):
    # nk.rsp_peaks(pzt_signal['PZT'].values, sampling_rate=sampling_rate, method="BioSPPy")

    sampling_rate = estimate_rate(data)

    # Extract peak using neurokit BioSPPy method
    _index = data.index
    _, info = nk.rsp_peaks(data[column],
                           sampling_rate=sampling_rate,
                           method="BioSPPy")
    # Truncate so that first and last events are troughs
    RSP_Troughs = info['RSP_Troughs']
    RSP_Peaks = info['RSP_Peaks']
    # at this point, check that there are some peaks/trough
    if RSP_Troughs.size == 0 or RSP_Peaks.size == 0:
        raise NoRespirationPeaks(
            'No peaks/trough could be detected in PZT signal. ')

    RSP_Peaks = RSP_Peaks[(RSP_Peaks > RSP_Troughs[0])
                          & (RSP_Peaks <= RSP_Troughs[-1])]

    # Estimate Inspiration and Expiration durations, cycle (I+E) durations and amplitude
    I_duration = (RSP_Peaks - RSP_Troughs[:-1]) / sampling_rate
    E_duration = (RSP_Troughs[1:] - RSP_Peaks) / sampling_rate
    IE_duration = np.ediff1d(RSP_Troughs) / sampling_rate
    amplitude = data.iloc[RSP_Peaks].values - data.iloc[
        RSP_Troughs[:-1]].values
    IE_ratio = I_duration / E_duration

    # Back to Dataframe format to allow extracting feature between events
    I_duration_df = pd.DataFrame(index=_index[RSP_Peaks],
                                 columns=['I_duration'],
                                 data=I_duration)
    E_duration_df = pd.DataFrame(index=_index[RSP_Troughs[1:]],
                                 columns=['E_duration'],
                                 data=E_duration)
    IE_duration_df = pd.DataFrame(index=_index[RSP_Troughs[1:]],
                                  columns=['IE_duration'],
                                  data=IE_duration)
    amplitude_df = pd.DataFrame(index=_index[RSP_Peaks],
                                columns=['IE_amplitude'],
                                data=amplitude)
    IE_ratio_df = pd.DataFrame(index=_index[RSP_Peaks],
                               columns=['IE_ratio'],
                               data=IE_ratio)

    cycles_df = pd.concat([
        I_duration_df, E_duration_df, IE_duration_df, amplitude_df, IE_ratio_df
    ],
                          axis=1)

    known_sequences = known_sequences or VALID_SEQUENCE_KEYS

    features = []
    # for name, row in events.T.iterrows():  # transpose due to https://github.com/OpenMindInnovation/iguazu/issues/54
    for index, row in events.iterrows():
        logger.debug('Processing sequence %s at %s', row.id, index)
        if row.id not in known_sequences:
            continue

        begin = row.begin
        end = row.end
        cycles_sequence = cycles_df.loc[begin:end].copy()

        # extract features on sequence
        sequence_features = dataclass_to_dataframe(
            respiration_features(cycles_sequence)).rename_axis(
                index='id').reset_index()

        sequence_features.insert(0, 'reference', row.id)
        features.append(sequence_features)

    if len(features) > 0:
        features = pd.concat(features,
                             axis='index',
                             ignore_index=True,
                             sort=False)
        logger.info('Generated a feature dataframe of shape %s',
                    features.shape)
    else:
        logger.info('No features were generated')
        features = pd.DataFrame(columns=['id', 'reference', 'value'])

    return features