Esempio n. 1
0
def test_bio_analyze():

    # Example with event-related analysis
    data = nk.data("bio_eventrelated_100hz")
    df, info = nk.bio_process(ecg=data["ECG"],
                              rsp=data["RSP"],
                              eda=data["EDA"],
                              keep=data["Photosensor"],
                              sampling_rate=100)
    events = nk.events_find(
        data["Photosensor"],
        threshold_keep="below",
        event_conditions=["Negative", "Neutral", "Neutral", "Negative"])
    epochs = nk.epochs_create(df,
                              events,
                              sampling_rate=100,
                              epochs_start=-0.1,
                              epochs_end=1.9)
    event_related = nk.bio_analyze(epochs)

    assert len(event_related) == len(epochs)
    labels = [int(i) for i in event_related["Label"]]
    assert labels == list(np.arange(1, len(epochs) + 1))

    # Example with interval-related analysis
    data = nk.data("bio_resting_8min_100hz")
    df, info = nk.bio_process(ecg=data["ECG"],
                              rsp=data["RSP"],
                              eda=data["EDA"],
                              sampling_rate=100)
    interval_related = nk.bio_analyze(df)

    assert len(interval_related) == 1
Esempio n. 2
0
def test_rsp_eventrelated():

    rsp, info = nk.rsp_process(nk.rsp_simulate(duration=20))
    epochs = nk.epochs_create(rsp,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    rsp_eventrelated = nk.rsp_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Rate_Min"]) < np.array(
            rsp_eventrelated["RSP_Rate_Mean"]))

    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Rate_Mean"]) < np.array(
            rsp_eventrelated["RSP_Rate_Max"]))

    # Test amplitude features
    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Amplitude_Min"]) < np.array(
            rsp_eventrelated["RSP_Amplitude_Mean"]))

    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Amplitude_Mean"]) < np.array(
            rsp_eventrelated["RSP_Amplitude_Max"]))

    assert all(elem in [
        "RSP_Rate_Max", "RSP_Rate_Min", "RSP_Rate_Mean", "RSP_Rate_Max_Time",
        "RSP_Rate_Min_Time", "RSP_Amplitude_Max", "RSP_Amplitude_Min",
        "RSP_Amplitude_Mean", "RSP_Phase", "RSP_PhaseCompletion", "Label"
    ] for elem in np.array(rsp_eventrelated.columns.values, dtype=str))
Esempio n. 3
0
def test_ecg_intervalrelated():

    data = nk.data("bio_resting_5min_100hz")
    df, info = nk.ecg_process(data["ECG"], sampling_rate=100)
    columns = [
        'ECG_Rate_Mean', 'HRV_RMSSD', 'HRV_MeanNN', 'HRV_SDNN', 'HRV_SDSD',
        'HRV_CVNN', 'HRV_CVSD', 'HRV_MedianNN', 'HRV_MadNN', 'HRV_MCVNN',
        'HRV_pNN50', 'HRV_pNN20', 'HRV_TINN', 'HRV_HTI', 'HRV_ULF', 'HRV_VLF',
        'HRV_LF', 'HRV_HF', 'HRV_VHF', 'HRV_LFHF', 'HRV_LFn', 'HRV_HFn',
        'HRV_LnHF', 'HRV_SD1', 'HRV_SD2', 'HRV_SD2SD1', 'HRV_CSI', 'HRV_CVI',
        'HRV_CSI_Modified', 'HRV_SampEn'
    ]

    # Test with signal dataframe
    features_df = nk.ecg_intervalrelated(df)

    assert all(elem in columns
               for elem in np.array(features_df.columns.values, dtype=str))
    assert features_df.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(df,
                              events=[0, 15000],
                              sampling_rate=100,
                              epochs_end=150)
    features_dict = nk.ecg_intervalrelated(epochs, sampling_rate=100)

    assert all(elem in columns
               for elem in np.array(features_dict.columns.values, dtype=str))
    assert features_dict.shape[0] == 2  # Number of rows
Esempio n. 4
0
def test_emg_eventrelated():

    emg = nk.emg_simulate(duration=20, sampling_rate=1000, burst_number=3)
    emg_signals, info = nk.emg_process(emg, sampling_rate=1000)
    epochs = nk.epochs_create(emg_signals,
                              events=[3000, 6000, 9000],
                              sampling_rate=1000,
                              epochs_start=-0.1,
                              epochs_end=1.9)
    emg_eventrelated = nk.emg_eventrelated(epochs)

    # Test amplitude features
    no_activation = np.where(emg_eventrelated["EMG_Activation"] == 0)[0][0]
    assert int(
        pd.DataFrame(emg_eventrelated.values[no_activation]).isna().sum()) == 4

    assert np.alltrue(
        np.nansum(np.array(emg_eventrelated["EMG_Amplitude_Mean"])) <
        np.nansum(np.array(emg_eventrelated["EMG_Amplitude_Max"])))

    assert len(emg_eventrelated["Label"]) == 3
    assert len(emg_eventrelated.columns) == 7

    assert all(elem in [
        "EMG_Activation", "EMG_Amplitude_Mean", "EMG_Amplitude_Max",
        "EMG_Amplitude_Max_Time", "EMG_Bursts", "Label", "Event_Onset"
    ] for elem in np.array(emg_eventrelated.columns.values, dtype=str))
Esempio n. 5
0
def test_rsp_eventrelated():

    rsp, info = nk.rsp_process(nk.rsp_simulate(duration=30, random_state=42))
    epochs = nk.epochs_create(rsp,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    rsp_eventrelated = nk.rsp_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Rate_Min"]) < np.array(
            rsp_eventrelated["RSP_Rate_Mean"]))

    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Rate_Mean"]) < np.array(
            rsp_eventrelated["RSP_Rate_Max"]))

    # Test amplitude features
    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Amplitude_Min"]) < np.array(
            rsp_eventrelated["RSP_Amplitude_Mean"]))

    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Amplitude_Mean"]) < np.array(
            rsp_eventrelated["RSP_Amplitude_Max"]))

    assert len(rsp_eventrelated["Label"]) == 3
Esempio n. 6
0
def test_ecg_eventrelated():

    ecg, info = nk.ecg_process(nk.ecg_simulate(duration=20))
    epochs = nk.epochs_create(ecg,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    ecg_eventrelated = nk.ecg_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(ecg_eventrelated["ECG_Rate_Min"]) < np.array(
            ecg_eventrelated["ECG_Rate_Mean"]))

    assert np.alltrue(
        np.array(ecg_eventrelated["ECG_Rate_Mean"]) < np.array(
            ecg_eventrelated["ECG_Rate_Max"]))

    assert len(ecg_eventrelated["Label"]) == 3
    assert len(ecg_eventrelated.columns) == 13

    assert all(elem in [
        "ECG_Rate_Max", "ECG_Rate_Min", "ECG_Rate_Mean", "ECG_Rate_Max_Time",
        "ECG_Rate_Min_Time", "ECG_Rate_Trend_Quadratic",
        "ECG_Rate_Trend_Linear", "ECG_Rate_Trend_R2", "ECG_Atrial_Phase",
        "ECG_Atrial_PhaseCompletion", "ECG_Ventricular_Phase",
        "ECG_Ventricular_PhaseCompletion", "Label"
    ] for elem in np.array(ecg_eventrelated.columns.values, dtype=str))
Esempio n. 7
0
def test_bio_analyze():

    # Example with event-related analysis
    data = nk.data("bio_eventrelated_100hz")
    df, info = nk.bio_process(ecg=data["ECG"],
                              rsp=data["RSP"],
                              eda=data["EDA"],
                              keep=data["Photosensor"],
                              sampling_rate=100)
    events = nk.events_find(
        data["Photosensor"],
        threshold_keep='below',
        event_conditions=["Negative", "Neutral", "Neutral", "Negative"])
    epochs = nk.epochs_create(df,
                              events,
                              sampling_rate=100,
                              epochs_start=-0.1,
                              epochs_end=1.9)
    event_related = nk.bio_analyze(epochs)

    assert len(event_related) == len(epochs)
    labels = [int(i) for i in event_related['Label']]
    assert labels == list(np.arange(1, len(epochs) + 1))
    assert all(elem in [
        'ECG_Rate_Max', 'ECG_Rate_Min', 'ECG_Rate_Mean', 'ECG_Rate_Max_Time',
        'ECG_Rate_Min_Time', 'ECG_Rate_Trend_Quadratic',
        'ECG_Rate_Trend_Linear', 'ECG_Rate_Trend_R2', 'ECG_Atrial_Phase',
        'ECG_Atrial_PhaseCompletion', 'ECG_Ventricular_Phase',
        'ECG_Ventricular_PhaseCompletion', 'ECG_Quality_Mean', 'RSP_Rate_Max',
        'RSP_Rate_Min', 'RSP_Rate_Mean', 'RSP_Rate_Max_Time',
        'RSP_Rate_Min_Time', 'RSP_Amplitude_Max', 'RSP_Amplitude_Min',
        'RSP_Amplitude_Mean', 'RSP_Phase', 'RSP_PhaseCompletion', 'EDA_SCR',
        'EDA_Peak_Amplitude', 'SCR_Peak_Amplitude', 'SCR_Peak_Amplitude_Time',
        'SCR_RiseTime', 'SCR_RecoveryTime', 'RSA_P2T', 'Label', 'Condition'
    ] for elem in np.array(event_related.columns.values, dtype=str))

    # Example with interval-related analysis
    data = nk.data("bio_resting_8min_100hz")
    df, info = nk.bio_process(ecg=data["ECG"],
                              rsp=data["RSP"],
                              eda=data["EDA"],
                              sampling_rate=100)
    interval_related = nk.bio_analyze(df)

    assert len(interval_related) == 1
    assert all(elem in [
        'ECG_Rate_Mean', 'HRV_RMSSD', 'HRV_MeanNN', 'HRV_SDNN', 'HRV_SDSD',
        'HRV_CVNN', 'HRV_CVSD', 'HRV_MedianNN', 'HRV_MadNN', 'HRV_MCVNN',
        'HRV_pNN50', 'HRV_pNN20', 'HRV_TINN', 'HRV_HTI', 'HRV_ULF', 'HRV_VLF',
        'HRV_LF', 'HRV_HF', 'HRV_VHF', 'HRV_LFHF', 'HRV_LFn', 'HRV_HFn',
        'HRV_LnHF', 'HRV_SD1', 'HRV_SD2', 'HRV_SD2SD1', 'HRV_CSI', 'HRV_CVI',
        'HRV_CSI_Modified', 'HRV_SampEn', 'RSP_Rate_Mean',
        'RSP_Amplitude_Mean', 'RRV_SDBB', 'RRV_RMSSD', 'RRV_SDSD', 'RRV_VLF',
        'RRV_LF', 'RRV_HF', 'RRV_LFHF', 'RRV_LFn', 'RRV_HFn', 'RRV_SD1',
        'RRV_SD2', 'RRV_SD2SD1', 'RRV_ApEn', 'RRV_SampEn', 'RRV_DFA',
        'RSA_P2T_Mean', 'RSA_P2T_Mean_log', 'RSA_P2T_SD', 'RSA_P2T_NoRSA',
        'RSA_PorgesBohrer', 'SCR_Peaks_N', 'SCR_Peaks_Amplitude_Mean'
    ] for elem in np.array(interval_related.columns.values, dtype=str))
Esempio n. 8
0
def test_ecg_eventrelated():

    ecg, info = nk.ecg_process(nk.ecg_simulate(duration=20))
    epochs = nk.epochs_create(ecg,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    ecg_eventrelated = nk.ecg_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(ecg_eventrelated["ECG_Rate_Min"]) < np.array(
            ecg_eventrelated["ECG_Rate_Mean"]))

    assert np.alltrue(
        np.array(ecg_eventrelated["ECG_Rate_Mean"]) < np.array(
            ecg_eventrelated["ECG_Rate_Max"]))

    assert len(ecg_eventrelated["Label"]) == 3

    # Test warning on missing columns
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `ECG_Phase_Artrial`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["ECG_Phase_Atrial"]
        nk.ecg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an.*`ECG_Phase_Ventricular`"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["ECG_Phase_Ventricular"]
        nk.ecg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `ECG_Quality`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["ECG_Quality"]
        nk.ecg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `ECG_Rate`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["ECG_Rate"]
        nk.ecg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    # Test warning on long epochs (eventrelated_utils)
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*duration of your epochs seems.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        first_epoch_copy.index = range(len(first_epoch_copy))
        nk.ecg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})
Esempio n. 9
0
def test_ecg_eventrelated():

    ecg, info = nk.ecg_process(nk.ecg_simulate(duration=20))
    epochs = nk.epochs_create(ecg, events=[5000, 10000, 15000], epochs_start=-0.1, epochs_end=1.9)
    ecg_eventrelated = nk.ecg_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(np.array(ecg_eventrelated["ECG_Rate_Min"]) < np.array(ecg_eventrelated["ECG_Rate_Mean"]))

    assert np.alltrue(np.array(ecg_eventrelated["ECG_Rate_Mean"]) < np.array(ecg_eventrelated["ECG_Rate_Max"]))

    assert len(ecg_eventrelated["Label"]) == 3
Esempio n. 10
0
def test_eda_eventrelated():

    eda = nk.eda_simulate(duration=15, scr_number=3)
    eda_signals, info = nk.eda_process(eda, sampling_rate=1000)
    epochs = nk.epochs_create(eda_signals, events=[5000, 10000, 15000],
                              sampling_rate=1000,
                              epochs_start=-0.1, epochs_end=1.9)
    eda_eventrelated = nk.eda_eventrelated(epochs)

    no_activation = np.where(eda_eventrelated["EDA_SCR"] == 0)[0][0]
    assert int(pd.DataFrame(eda_eventrelated.values
                            [no_activation]).isna().sum()) == 4

    assert len(eda_eventrelated["Label"]) == 3
Esempio n. 11
0
def test_eda_eventrelated():

    eda = nk.eda_simulate(duration=15, scr_number=3)
    eda_signals, info = nk.eda_process(eda, sampling_rate=1000)
    epochs = nk.epochs_create(
        eda_signals,
        events=[5000, 10000, 15000],
        sampling_rate=1000,
        epochs_start=-0.1,
        epochs_end=1.9,
    )
    eda_eventrelated = nk.eda_eventrelated(epochs)

    no_activation = np.where(eda_eventrelated["EDA_SCR"] == 0)[0][0]
    assert int(
        pd.DataFrame(eda_eventrelated.values[no_activation]).isna().sum()) == 4

    assert len(eda_eventrelated["Label"]) == 3

    # Test warning on missing columns
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `EDA_Phasic`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["EDA_Phasic"]
        nk.eda_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `SCR_Amplitude`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["SCR_Amplitude"]
        nk.eda_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `SCR_RecoveryTime`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["SCR_RecoveryTime"]
        nk.eda_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `SCR_RiseTime`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["SCR_RiseTime"]
        nk.eda_eventrelated({**epochs, first_epoch_key: first_epoch_copy})
Esempio n. 12
0
def test_rsp_intervalrelated():

    data = nk.data("bio_resting_5min_100hz")
    df, info = nk.rsp_process(data["RSP"], sampling_rate=100)

    # Test with signal dataframe
    features_df = nk.rsp_intervalrelated(df)

    assert features_df.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(df,
                              events=[0, 15000],
                              sampling_rate=100,
                              epochs_end=150)
    features_dict = nk.rsp_intervalrelated(epochs)

    assert features_dict.shape[0] == 2  # Number of rows
Esempio n. 13
0
def test_rsp_eventrelated():

    rsp, info = nk.rsp_process(nk.rsp_simulate(duration=30, random_state=42))
    epochs = nk.epochs_create(rsp,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    rsp_eventrelated = nk.rsp_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Rate_Min"]) < np.array(
            rsp_eventrelated["RSP_Rate_Mean"]))

    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Rate_Mean"]) < np.array(
            rsp_eventrelated["RSP_Rate_Max"]))

    # Test amplitude features
    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Amplitude_Min"]) < np.array(
            rsp_eventrelated["RSP_Amplitude_Mean"]))

    assert np.alltrue(
        np.array(rsp_eventrelated["RSP_Amplitude_Mean"]) < np.array(
            rsp_eventrelated["RSP_Amplitude_Max"]))

    assert len(rsp_eventrelated["Label"]) == 3

    # Test warning on missing columns
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `RSP_Amplitude`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["RSP_Amplitude"]
        nk.rsp_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `RSP_Phase`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["RSP_Phase"]
        nk.rsp_eventrelated({**epochs, first_epoch_key: first_epoch_copy})
Esempio n. 14
0
def test_emg_eventrelated():

    emg = nk.emg_simulate(duration=20, sampling_rate=1000, burst_number=3)
    emg_signals, info = nk.emg_process(emg, sampling_rate=1000)
    epochs = nk.epochs_create(emg_signals,
                              events=[3000, 6000, 9000],
                              sampling_rate=1000,
                              epochs_start=-0.1,
                              epochs_end=1.9)
    emg_eventrelated = nk.emg_eventrelated(epochs)

    # Test amplitude features
    no_activation = np.where(emg_eventrelated["EMG_Activation"] == 0)[0][0]
    assert int(
        pd.DataFrame(emg_eventrelated.values[no_activation]).isna().sum()) == 4

    assert np.alltrue(
        np.nansum(np.array(emg_eventrelated["EMG_Amplitude_Mean"])) <
        np.nansum(np.array(emg_eventrelated["EMG_Amplitude_Max"])))

    assert len(emg_eventrelated["Label"]) == 3

    # Test warning on missing columns
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `EMG_Onsets`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["EMG_Onsets"]
        nk.emg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `EMG_Activity`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["EMG_Activity"]
        nk.emg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an.*`EMG_Amplitude`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["EMG_Amplitude"]
        nk.emg_eventrelated({**epochs, first_epoch_key: first_epoch_copy})
Esempio n. 15
0
def test_eda_intervalrelated():

    data = nk.data("bio_resting_8min_100hz")
    df, info = nk.eda_process(data["EDA"], sampling_rate=100)
    columns = ['SCR_Peaks_N', 'SCR_Peaks_Amplitude_Mean']

    # Test with signal dataframe
    features_df = nk.eda_intervalrelated(df)

    assert all(elem in columns for elem
               in np.array(features_df.columns.values, dtype=str))
    assert features_df.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(df, events=[0, 25300],
                              sampling_rate=100, epochs_end=20)
    features_dict = nk.eda_intervalrelated(epochs)

    assert all(elem in columns for elem
               in np.array(features_dict.columns.values, dtype=str))
    assert features_dict.shape[0] == 2  # Number of rows
Esempio n. 16
0
def test_eda_eventrelated():

    eda = nk.eda_simulate(duration=15, scr_number=3)
    eda_signals, info = nk.eda_process(eda, sampling_rate=1000)
    epochs = nk.epochs_create(eda_signals,
                              events=[5000, 10000, 15000],
                              sampling_rate=1000,
                              epochs_start=-0.1,
                              epochs_end=1.9)
    eda_eventrelated = nk.eda_eventrelated(epochs)

    no_activation = np.where(eda_eventrelated["EDA_Activation"] == 0)[0][0]
    assert int(
        pd.DataFrame(eda_eventrelated.values[no_activation]).isna().sum()) == 4

    assert len(eda_eventrelated["Label"]) == 3
    assert len(eda_eventrelated.columns) == 6

    assert all(elem in [
        "EDA_Activation", "EDA_Peak_Amplitude", "EDA_Peak_Amplitude_Time",
        "EDA_RiseTime", "EDA_RecoveryTime", "Label"
    ] for elem in np.array(eda_eventrelated.columns.values, dtype=str))
Esempio n. 17
0
def test_ecg_intervalrelated():

    data = nk.data("bio_resting_5min_100hz")
    df, info = nk.ecg_process(data["ECG"], sampling_rate=100)

    columns = [
        'ECG_Rate_Mean', 'HRV_RMSSD', 'HRV_MeanNN', 'HRV_SDNN', 'HRV_SDSD',
        'HRV_CVNN', 'HRV_CVSD', 'HRV_MedianNN', 'HRV_MadNN', 'HRV_MCVNN',
        'HRV_IQRNN', 'HRV_pNN50', 'HRV_pNN20', 'HRV_TINN', 'HRV_HTI',
        'HRV_ULF', 'HRV_VLF', 'HRV_LF', 'HRV_HF', 'HRV_VHF', 'HRV_LFHF',
        'HRV_LFn', 'HRV_HFn', 'HRV_LnHF', 'HRV_SD1', 'HRV_SD2', 'HRV_SD1SD2',
        'HRV_S', 'HRV_CSI', 'HRV_CVI', 'HRV_CSI_Modified', 'HRV_PIP',
        'HRV_IALS', 'HRV_PSS', 'HRV_PAS', 'HRV_ApEn', 'HRV_SampEn', 'HRV_GI',
        'HRV_SI', 'HRV_AI', 'HRV_PI', 'HRV_C1d', 'HRV_C1a', 'HRV_SD1d',
        'HRV_SD1a', 'HRV_C2d', 'HRV_C2a', 'HRV_SD2d', 'HRV_SD2a', 'HRV_Cd',
        'HRV_Ca', 'HRV_SDNNd', 'HRV_SDNNa'
    ]

    # Test with signal dataframe
    features_df = nk.ecg_intervalrelated(df, sampling_rate=100)

    # https://github.com/neuropsychology/NeuroKit/issues/304
    assert all(features_df == nk.ecg_analyze(
        df, sampling_rate=100, method="interval-related"))

    assert all(elem in np.array(features_df.columns.values, dtype=str)
               for elem in columns)
    assert features_df.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(df,
                              events=[0, 15000],
                              sampling_rate=100,
                              epochs_end=150)
    features_dict = nk.ecg_intervalrelated(epochs, sampling_rate=100)

    assert all(elem in columns
               for elem in np.array(features_dict.columns.values, dtype=str))
    assert features_dict.shape[0] == 2  # Number of rows
Esempio n. 18
0
def test_eog_eventrelated():

    eog = nk.data('eog_200hz')['vEOG']
    eog_signals, info = nk.eog_process(eog, sampling_rate=200)
    epochs = nk.epochs_create(eog_signals,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    eog_eventrelated = nk.eog_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(eog_eventrelated["EOG_Rate_Min"]) < np.array(
            eog_eventrelated["EOG_Rate_Mean"]))

    assert np.alltrue(
        np.array(eog_eventrelated["EOG_Rate_Mean"]) < np.array(
            eog_eventrelated["EOG_Rate_Max"]))

    # Test blink presence
    assert np.alltrue(
        np.array(eog_eventrelated["EOG_Blinks_Presence"]) == np.array(
            [1, 0, 0]))

    # Test warning on missing columns
    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `EOG_Blinks`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["EOG_Blinks"]
        nk.eog_eventrelated({**epochs, first_epoch_key: first_epoch_copy})

    with pytest.warns(nk.misc.NeuroKitWarning,
                      match=r".*does not have an `EOG_Rate`.*"):
        first_epoch_key = list(epochs.keys())[0]
        first_epoch_copy = epochs[first_epoch_key].copy()
        del first_epoch_copy["EOG_Rate"]
        nk.eog_eventrelated({**epochs, first_epoch_key: first_epoch_copy})
Esempio n. 19
0
def test_eog_eventrelated():

    eog = nk.data('eog_200hz')['vEOG']
    eog_signals, info = nk.eog_process(eog, sampling_rate=200)
    epochs = nk.epochs_create(eog_signals,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    eog_eventrelated = nk.eog_eventrelated(epochs)

    # Test rate features
    assert np.alltrue(
        np.array(eog_eventrelated["EOG_Rate_Min"]) < np.array(
            eog_eventrelated["EOG_Rate_Mean"]))

    assert np.alltrue(
        np.array(eog_eventrelated["EOG_Rate_Mean"]) < np.array(
            eog_eventrelated["EOG_Rate_Max"]))

    # Test blink presence
    assert np.alltrue(
        np.array(eog_eventrelated["EOG_Blinks_Presence"]) == np.array(
            [1, 0, 0]))
Esempio n. 20
0
def test_emg_intervalrelated():

    emg = nk.emg_simulate(duration=40, sampling_rate=1000, burst_number=3)
    emg_signals, info = nk.emg_process(emg, sampling_rate=1000)
    columns = ['EMG_Activation_N', 'EMG_Amplitude_Mean']

    # Test with signal dataframe
    features_df = nk.emg_intervalrelated(emg_signals)

    assert all(elem in columns
               for elem in np.array(features_df.columns.values, dtype=str))
    assert features_df.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(emg_signals,
                              events=[0, 20000],
                              sampling_rate=1000,
                              epochs_end=20)
    features_dict = nk.emg_intervalrelated(epochs)

    assert all(elem in columns
               for elem in np.array(features_dict.columns.values, dtype=str))
    assert features_dict.shape[0] == 2  # Number of rows
Esempio n. 21
0
def test_rsp_intervalrelated():

    data = nk.data("bio_resting_5min_100hz")
    df, info = nk.rsp_process(data["RSP"], sampling_rate=100)
    columns = ['RSP_Rate_Mean', 'RSP_Amplitude_Mean', 'RRV_SDBB', 'RRV_RMSSD',
               'RRV_SDSD', 'RRV_VLF', 'RRV_LF', 'RRV_HF', 'RRV_LFHF', 'RRV_LFn',
               'RRV_HFn', 'RRV_SD1', 'RRV_SD2', 'RRV_SD2SD1', 'RRV_ApEn',
               'RRV_SampEn', 'RRV_DFA']

    # Test with signal dataframe
    features_df = nk.rsp_intervalrelated(df)

    assert all(elem in columns for elem
               in np.array(features_df.columns.values, dtype=str))
    assert features_df.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(df, events=[0, 15000],
                              sampling_rate=100, epochs_end=150)
    features_dict = nk.rsp_intervalrelated(epochs)

    assert all(elem in columns for elem
               in np.array(features_dict.columns.values, dtype=str))
    assert features_dict.shape[0] == 2  # Number of rows
Esempio n. 22
0
def test_eog_intervalrelated():

    eog = nk.data('eog_200hz')['vEOG']
    eog_signals, info = nk.eog_process(eog, sampling_rate=200)

    columns = ['EOG_Peaks_N', 'EOG_Rate_Mean']

    # Test with signal dataframe
    features = nk.eog_intervalrelated(eog_signals)

    assert all(elem in np.array(features.columns.values, dtype=str)
               for elem in columns)
    assert features.shape[0] == 1  # Number of rows

    # Test with dict
    epochs = nk.epochs_create(eog_signals,
                              events=[5000, 10000, 15000],
                              epochs_start=-0.1,
                              epochs_end=1.9)
    epochs_dict = nk.eog_intervalrelated(epochs)

    assert all(elem in columns
               for elem in np.array(epochs_dict.columns.values, dtype=str))
    assert epochs_dict.shape[0] == len(epochs)  # Number of rows
Esempio n. 23
0
    def process_session(self, folder, data):
        """
            Process session data.

            Parameters
            ----------
            folder : str
                Session data folder name.
            data : DataFrame
                Session data.

            Returns
            -------
            DataFrame
                Extracted event-related features for all signals.

        """

        p = Path('{}/{}/epochs'.format(self.path, folder))
        p.mkdir(exist_ok=True)

        name = folder.split('_')
        emotion = name[0]
        gender = name[-1]

        self.emotion_gender_dict['emotion'] += [emotion]
        self.emotion_gender_dict['gender'] += [gender]

        bvp = data['bvp']
        eda = data['gsr']
        tag = data['tag']
        hr = data['hr']
        ibi = data['ibi']

        #epoch count / 2
        count = tag.shape[0] // 2
        if count == 0:
            count = 1

        self.samples_count += count

        condition_list = ['neutral', emotion] * count

        #Remove data before the first tag and after the last tag.
        first_tag = tag['norm_ts'].head(1).values[0]

        tag.loc[:, 'norm_ts'] -= first_tag
        bvp.loc[:, 'norm_ts'] -= first_tag
        eda.loc[:, 'norm_ts'] -= first_tag
        hr.loc[:, 'norm_ts'] -= first_tag
        ibi.loc[:, 'norm_ts'] -= first_tag

        tag = tag[tag['norm_ts'] >= 0.0]
        bvp = bvp[bvp['norm_ts'] >= 0.0]
        eda = eda[eda['norm_ts'] >= 0.0]
        hr = hr[hr['norm_ts'] >= 0.0]
        ibi = ibi[ibi['norm_ts'] >= 0.0]

        last_tag = tag['norm_ts'].tail(1).values[0]

        tag = tag[tag['norm_ts'] < last_tag]
        bvp = bvp[bvp['norm_ts'] <= last_tag]
        eda = eda[eda['norm_ts'] <= last_tag]
        hr = hr[hr['norm_ts'] <= last_tag]
        ibi = ibi[ibi['norm_ts'] <= last_tag]

        #Compute IBI miss ratio
        duration = tag['timestamp'].tail(1).values[0] - tag['timestamp'].head(
            1).values[0]
        m_ratio = ibi_miss_ratio(ibi, duration)
        self.ppg_ratio += m_ratio
        self.ppg_ratio_dict[emotion][0] += 1
        self.ppg_ratio_dict[emotion][1] += m_ratio

        #Process the Signals
        try:
            eda_signals, eda_info = process_eda(eda)
            bvp_signals, bvp_info, hrv_indices = process_bvp(bvp)
            hrv_indices['Condition'] = emotion
            hrv_indices.to_csv('{}/{}/hrv.csv'.format(self.path, folder))
        except Exception as e:
            print('Signal processing for {} failed.'.format(folder))
            print('Raised exception: {}. Signal processing handler.'.format(e))
            return None

        signals = pd.concat([bvp_signals, eda_signals], axis=1, join='inner')
        signals = signals.fillna(0)
        signals.to_csv('{}/{}/signals.csv'.format(self.path, folder))

        #reset index to start by 0.
        bvp_signals.reset_index(inplace=True)

        #plot HR from E4 with HR computed by NeuroKit2.
        if self.show_fig and m_ratio < 0.01:
            plt.plot(hr['norm_ts'] + 5, hr['value'], label='Empatica E4')
            plt.plot(bvp_signals['index'][::64] / 64,
                     bvp_signals['PPG_Rate'][::64],
                     label='NeuroKit2')
            plt.xlabel('Čas [s]')
            plt.ylabel('Srdeční tep [bpm]')
            plt.legend()
            plt.show()

        try:
            events = find_events(signals, tag, condition_list=condition_list)
            epochs = nk.epochs_create(signals,
                                      events,
                                      sampling_rate=64,
                                      epochs_start=0)
        except Exception as e:
            print('Signal processing for {} failed.'.format(folder))
            print('Raised exception: {}. Epochs creating handler.'.format(e))
            return None

        neutral_df, emotion_df = concat_epochs_by_condition(epochs)
        neutral_df.to_csv('{}/{}/epochs/neutral_all.csv'.format(
            self.path, folder))
        emotion_df.to_csv('{}/{}/epochs/emotion_all.csv'.format(
            self.path, folder))

        save_epochs_to_csv('{}/{}'.format(self.path, folder), epochs)

        if self.show_fig:
            plot_epochs(folder, epochs, events)

        #Extract Event Related Features
        erf = extract_ERF(epochs, condition_list=condition_list)
        erf['Gender'] = gender
        erf.to_csv('{}/{}/features.csv'.format(self.path, folder))

        return erf
Esempio n. 24
0
    print("Task: " + str(i))

    data = pd.read_csv("../../data/eogdb/eogdb_task" + str(i + 1) + ".csv")

    for j, participant in enumerate(np.unique(data["Participant"])[1:3]):
        print("  - " + str(j + 1))

        segment = data[data["Participant"] == participant]
        signal = segment["vEOG"]

        cleaned = nk.eog_clean(signal, sampling_rate=200, method='neurokit')
        blinks = nk.signal_findpeaks(cleaned, relative_height_min=1.5)["Peaks"]

        events = nk.epochs_create(cleaned,
                                  blinks,
                                  sampling_rate=200,
                                  epochs_start=-0.4,
                                  epochs_end=0.6)
        events = nk.epochs_to_array(events)  # Convert to 2D array

        x = np.linspace(0, 100, num=len(events))

        p_gamma = np.full((events.shape[1], 3), np.nan)
        p_bateman = np.full((events.shape[1], 3), np.nan)
        p_scr = np.full((events.shape[1], 4), np.nan)

        for i in range(events.shape[1]):
            if np.isnan(events[:, i]).any():
                break
            events[:, i] = nk.rescale(events[:, i],
                                      to=[0, 1])  # Reshape to 0-1 scale
Esempio n. 25
0
                                    event_raw_index]
                            # find events
                            eda_events = nk.events_find(df_event,
                                                        threshold=0,
                                                        threshold_keep='above')
                            # process eda signals
                            eda_signals, eda_info = nk.bio_process(
                                eda=df_gsr, sampling_rate=hz_gsr)
                            # create epochs
                            eda_epochs_end = sc_duration if (
                                sc_duration -
                                EPOCH_START) <= EPOCH_DURATION else (
                                    EPOCH_START + EPOCH_DURATION)
                            eda_epochs = nk.epochs_create(
                                eda_signals,
                                eda_events,
                                sampling_rate=hz_gsr,
                                epochs_start=EPOCH_START,
                                epochs_end=eda_epochs_end)
                            # analyze event-related features of EDA signals
                            # eda_analysis = nk.bio_analyze(eda_epochs, method="event-related")

                            # Feature SCR (Skin Conductance Response)
                            eda_epoch = eda_epochs['1']
                            eda_response_desc = eda_epoch.loc[
                                eda_epoch['SCR_Amplitude'] > 0,
                                ["SCR_Amplitude"]].describe()
                            eda_response_count = eda_response_desc.loc[
                                'count'].values[0]
                            row['EDA_Response_Count'] = eda_response_count
                            eda_response_mean = eda_response_desc.loc[
                                'mean'].values[0]
Esempio n. 26
0
# =============================================================================
# Epochs
# =============================================================================
# Get Events
events = mne.read_events(mne.datasets.sample.data_path() +
                         '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')
events = pd.DataFrame(events[:, [0, 2]], columns=["Index", "Condition"])

# Conditions = {'audio/left': 1, 'audio/right': 2, 'visual/left': 3, 'visual/right': 4}
events = events[events["Condition"].isin([1, 2, 3, 4])]
events["Condition"].loc[events["Condition"].isin([1, 2])] = "Audio"
events["Condition"].loc[events["Condition"] != "Audio"] = "Visual"

epochs = nk.epochs_create(out["Sequence"],
                          events["Index"],
                          sampling_rate=150,
                          epochs_end=0.5,
                          event_conditions=events["Condition"])

# =============================================================================
# Results
# =============================================================================
nk.microstates_static(out["Sequence"],
                      sampling_rate=150)["Microstate_Average_DurationMean"]

df = []  # Initialize an empty dict
for i in epochs.keys():
    data = nk.microstates_static(epochs[i]["Signal"], sampling_rate=150)
    data = pd.concat([
        data,
        nk.microstates_dynamic(epochs[i]["Signal"]),