Ejemplo n.º 1
0
def test_eda_peaks():

    sampling_rate = 1000
    eda = nk.eda_simulate(duration=30, sampling_rate=sampling_rate,
                          scr_number=6, noise=0, drift=0.01, random_state=42)
    eda_phasic = nk.eda_phasic(nk.standardize(eda), method='highpass')["EDA_Phasic"].values


    signals, info = nk.eda_peaks(eda_phasic, method="gamboa2008")
    onsets, peaks, amplitudes = biosppy.eda.basic_scr(eda_phasic, sampling_rate=1000)
    assert np.allclose((info["SCR_Peaks"] - peaks).mean(), 0, atol=1e-5)

    signals, info = nk.eda_peaks(eda_phasic, method="kim2004")
    onsets, peaks, amplitudes = biosppy.eda.kbk_scr(eda_phasic, sampling_rate=1000)
    assert np.allclose((info["SCR_Peaks"] - peaks).mean(), 0, atol=1)
Ejemplo n.º 2
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
Ejemplo n.º 3
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})
Ejemplo n.º 4
0
def test_bio_process():

    sampling_rate = 1000

    # Create data
    ecg = nk.ecg_simulate(duration=30, sampling_rate=sampling_rate)
    rsp = nk.rsp_simulate(duration=30, sampling_rate=sampling_rate)
    eda = nk.eda_simulate(duration=30,
                          sampling_rate=sampling_rate,
                          scr_number=3)
    emg = nk.emg_simulate(duration=30,
                          sampling_rate=sampling_rate,
                          burst_number=3)

    bio_df, bio_info = nk.bio_process(ecg=ecg,
                                      rsp=rsp,
                                      eda=eda,
                                      emg=emg,
                                      sampling_rate=sampling_rate)

    # SCR components
    scr = [val for key, val in bio_info.items() if "SCR" in key]
    assert all(len(elem) == len(scr[0]) for elem in scr)
    assert all(bio_info["SCR_Onsets"] < bio_info["SCR_Peaks"])
    assert all(bio_info["SCR_Peaks"] < bio_info["SCR_Recovery"])

    # RSP
    assert all(bio_info["RSP_Peaks"] > bio_info["RSP_Troughs"])
    assert len(bio_info["RSP_Peaks"]) == len(bio_info["RSP_Troughs"])

    # EMG
    assert all(bio_info["EMG_Offsets"] > bio_info["EMG_Onsets"])
    assert len(bio_info["EMG_Offsets"] == len(bio_info["EMG_Onsets"]))

    assert all(elem in [
        'ECG_Raw', 'ECG_Clean', 'ECG_Rate', 'ECG_Quality', 'ECG_R_Peaks',
        "ECG_P_Peaks", "ECG_Q_Peaks", "ECG_S_Peaks", "ECG_T_Peaks",
        "ECG_P_Onsets", "ECG_T_Offsets", "ECG_Atrial_Phase",
        "ECG_Ventricular_Phase", "ECG_Atrial_PhaseCompletion",
        "ECG_Ventricular_PhaseCompletion", 'RSP_Raw', 'RSP_Clean',
        'RSP_Amplitude', 'RSP_Rate', 'RSP_Phase', 'RSP_PhaseCompletion',
        'RSP_Peaks', 'RSP_Troughs', 'EDA_Raw', 'EDA_Clean', 'EDA_Tonic',
        'EDA_Phasic', 'SCR_Onsets', 'SCR_Peaks', 'SCR_Height', 'SCR_Amplitude',
        'SCR_RiseTime', 'SCR_Recovery', 'SCR_RecoveryTime', 'EMG_Raw',
        'EMG_Clean', 'EMG_Amplitude', 'EMG_Activity', 'EMG_Onsets',
        'EMG_Offsets', 'RSA_P2T'
    ] for elem in np.array(bio_df.columns.values, dtype=str))
Ejemplo n.º 5
0
def test_eda_phasic():

    sampling_rate = 1000
    eda = nk.eda_simulate(duration=30, sampling_rate=sampling_rate,
                          scr_number=6, noise=0.01, drift=0.01, random_state=42)


    cvxEDA = nk.eda_phasic(nk.standardize(eda), method='cvxeda')
    assert len(cvxEDA) == len(eda)


    smoothMedian = nk.eda_phasic(nk.standardize(eda), method='smoothmedian')
    assert len(smoothMedian) == len(eda)


    highpass = nk.eda_phasic(nk.standardize(eda), method='highpass')
    assert len(highpass) == len(eda)
Ejemplo n.º 6
0
def test_eda_phasic():

    sampling_rate = 1000
    eda = nk.eda_simulate(duration=30,
                          sampling_rate=sampling_rate,
                          scr_number=6,
                          noise=0.01,
                          drift=0.01,
                          random_state=42)

    if platform.system() == "Linux":
        cvxEDA = nk.eda_phasic(nk.standardize(eda), method="cvxeda")
        assert len(cvxEDA) == len(eda)

    smoothMedian = nk.eda_phasic(nk.standardize(eda), method="smoothmedian")
    assert len(smoothMedian) == len(eda)

    highpass = nk.eda_phasic(nk.standardize(eda), method="highpass")
    assert len(highpass) == len(eda)
Ejemplo n.º 7
0
def test_eda_process():

    eda = nk.eda_simulate(duration=30,
                          scr_number=5,
                          drift=0.1,
                          noise=0,
                          sampling_rate=250)
    signals, info = nk.eda_process(eda, sampling_rate=250)

    assert signals.shape == (7500, 11)
    assert np.array([
        "EDA_Raw", "EDA_Clean", "EDA_Tonic", "EDA_Phasic", "SCR_Onsets",
        "SCR_Peaks", "SCR_Height", "SCR_Amplitude", "SCR_RiseTime",
        "SCR_Recovery", "SCR_RecoveryTime"
    ]) in signals.columns.values

    # Check equal number of markers
    peaks = np.where(signals["SCR_Peaks"] == 1)[0]
    onsets = np.where(signals["SCR_Onsets"] == 1)[0]
    recovery = np.where(signals["SCR_Recovery"] == 1)[0]
    assert peaks.shape == onsets.shape == recovery.shape == (5, )
Ejemplo n.º 8
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))
Ejemplo n.º 9
0
def test_eda_clean():

    sampling_rate = 1000
    eda = nk.eda_simulate(
        duration=30,
        sampling_rate=sampling_rate,
        scr_number=6,
        noise=0.01,
        drift=0.01,
        random_state=42,
    )

    clean = nk.eda_clean(eda, sampling_rate=sampling_rate)
    assert len(clean) == len(eda)

    # Comparison to biosppy (https://github.com/PIA-Group/BioSPPy/blob/master/biosppy/signals/eda.py)

    eda_biosppy = nk.eda_clean(eda,
                               sampling_rate=sampling_rate,
                               method="biosppy")
    original, _, _ = biosppy.tools.filter_signal(
        signal=eda,
        ftype="butter",
        band="lowpass",
        order=4,
        frequency=5,
        sampling_rate=sampling_rate,
    )

    original, _ = biosppy.tools.smoother(signal=original,
                                         kernel="boxzen",
                                         size=int(0.75 * sampling_rate),
                                         mirror=True)

    #    pd.DataFrame({"our":eda_biosppy, "biosppy":original}).plot()
    assert np.allclose((eda_biosppy - original).mean(), 0, atol=1e-5)
Ejemplo n.º 10
0
def test_eda_plot():

    sampling_rate = 1000
    eda = nk.eda_simulate(
        duration=30,
        sampling_rate=sampling_rate,
        scr_number=6,
        noise=0,
        drift=0.01,
        random_state=42,
    )
    eda_summary, _ = nk.eda_process(eda, sampling_rate=sampling_rate)

    # Plot data over samples.
    nk.eda_plot(eda_summary)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 3
    titles = [
        "Raw and Cleaned Signal",
        "Skin Conductance Response (SCR)",
        "Skin Conductance Level (SCL)",
    ]
    for (ax, title) in zip(fig.get_axes(), titles):
        assert ax.get_title() == title
    assert fig.get_axes()[2].get_xlabel() == "Samples"
    np.testing.assert_array_equal(fig.axes[0].get_xticks(),
                                  fig.axes[1].get_xticks(),
                                  fig.axes[2].get_xticks())
    plt.close(fig)

    # Plot data over seconds.
    nk.eda_plot(eda_summary, sampling_rate=sampling_rate)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert fig.get_axes()[2].get_xlabel() == "Seconds"
Ejemplo n.º 11
0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import neurokit2 as nk

# =============================================================================
# Simulate physiological signals
# =============================================================================

# Generate synthetic signals
ecg = nk.ecg_simulate(duration=10, heart_rate=70)
ppg = nk.ppg_simulate(duration=10, heart_rate=70)
rsp = nk.rsp_simulate(duration=10, respiratory_rate=15)
eda = nk.eda_simulate(duration=10, scr_number=3)
emg = nk.emg_simulate(duration=10, burst_number=2)

# Visualise biosignals
data = pd.DataFrame({
    "ECG": ecg,
    "PPG": ppg,
    "RSP": rsp,
    "EDA": eda,
    "EMG": emg
})
nk.signal_plot(data, subplots=True)

# Save it
data = pd.DataFrame({
    "ECG":
    nk.ecg_simulate(duration=10, heart_rate=70, noise=0),
    "PPG":
Ejemplo n.º 12
0
import numpy as np
import pandas as pd
import neurokit2 as nk

# =============================================================================
# Simulate physiological signals
# =============================================================================

# Generate synthetic signals
ecg = nk.ecg_simulate(duration=10, heart_rate=70)
rsp = nk.rsp_simulate(duration=10, respiratory_rate=15)
eda = nk.eda_simulate(duration=10, n_scr=3)
emg = nk.emg_simulate(duration=10, n_bursts=2)

# Visualise biosignals
data = pd.DataFrame({"ECG": ecg, "RSP": rsp, "EDA": eda, "EMG": emg})
data.plot(subplots=True, layout=(4, 1))

# Save it
plot = data.plot(subplots=True, layout=(4, 1))
plot[0][0].get_figure().savefig("README_simulation.png", dpi=300)

# =============================================================================
# Respiration (RSP) processing
# =============================================================================

# Generate one minute of respiratory signal
rsp = nk.rsp_simulate(duration=60, respiratory_rate=15)

# Process it
signals, info = nk.rsp_process(rsp)
Ejemplo n.º 13
0
import numpy as np
import pandas as pd
import neurokit2 as nk


# =============================================================================
# Example 1
# =============================================================================

# Generate synthetic signals
ecg = nk.ecg_simulate(duration=10, heart_rate=70)
rsp = nk.rsp_simulate(duration=10, respiratory_rate=15)
eda = nk.eda_simulate(duration=10, n_peaks=3)
emg = nk.emg_simulate(duration=10, n_bursts=2)

# Visualise biosignals
data = pd.DataFrame({"ECG": ecg,
                     "RSP": rsp,
                     "EDA": eda,
                     "EMG": emg})
data.plot(subplots=True, layout=(4, 1))


# Save it
plot = data.plot(subplots=True, layout=(4, 1))
plot[0][0].get_figure().savefig("README_simulation.png", dpi=300)