コード例 #1
0
def test_emg_simulate():

    emg1 = nk.emg_simulate(duration=20, length=5000, n_bursts=1)
    assert len(emg1) == 5000

    emg2 = nk.emg_simulate(duration=20, length=5000, n_bursts=15)
    assert scipy.stats.median_absolute_deviation(
        emg1) < scipy.stats.median_absolute_deviation(emg2)
コード例 #2
0
def test_emg_simulate():

    emg1 = nk.emg_simulate(duration=20, length=5000, n_bursts=1)
    assert len(emg1) == 5000

    emg2 = nk.emg_simulate(duration=20, length=5000, n_bursts=15)
    assert scipy.stats.median_absolute_deviation(emg1) < scipy.stats.median_absolute_deviation(emg2)

    emg3 = nk.emg_simulate(duration=20, length=5000, n_bursts=1, duration_bursts=2.0)
#    pd.DataFrame({"EMG1":emg1, "EMG3": emg3}).plot()
    assert len(nk.signal_findpeaks(emg3, height_min=1.0)["Peaks"]) > len(nk.signal_findpeaks(emg1, height_min=1.0)["Peaks"])
コード例 #3
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))
コード例 #4
0
def test_emg_plot():

    sampling_rate = 1000

    emg = nk.emg_simulate(duration=10, sampling_rate=1000, burst_number=3)
    emg_summary, _ = nk.emg_process(emg, sampling_rate=sampling_rate)

    # Plot data over samples.
    nk.emg_plot(emg_summary)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 2
    titles = ["Raw and Cleaned Signal", "Muscle Activation"]
    for (ax, title) in zip(fig.get_axes(), titles):
        assert ax.get_title() == title
    assert fig.get_axes()[1].get_xlabel() == "Samples"
    np.testing.assert_array_equal(fig.axes[0].get_xticks(),
                                  fig.axes[1].get_xticks())
    plt.close(fig)

    # Plot data over time.
    nk.emg_plot(emg_summary, sampling_rate=sampling_rate)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert fig.get_axes()[1].get_xlabel() == "Time (seconds)"
コード例 #5
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"]))
コード例 #6
0
ファイル: main.py プロジェクト: ArwenBlack/NET_projekt
def generate_emg(time, rate):
    emg = emg_simulate(duration=time,
                       sampling_rate=rate,
                       random_state=1,
                       burst_number=3)

    return emg
コード例 #7
0
def generate(time: int, rate: int):
    ecg1 = nk.ecg_simulate(duration=time, sampling_rate= rate, method = "ecgsyn") # duration - ile sekund  #sampling rate - ile punktów na sekunde
    ecg2 = nk.ecg_simulate(duration=time, sampling_rate= rate, method = "ecgsyn")
    ecg3 = nk.ecg_simulate(duration=time, sampling_rate= rate, method="ecgsyn")
    ecg4 = nk.ecg_simulate(duration=time, sampling_rate= rate, method="daubechies")
    emg1 = nk.emg_simulate(duration=time, sampling_rate= rate, random_state=1, burst_number=3)
    emg2 = nk.emg_simulate(duration=time, sampling_rate= rate, random_state=2, burst_number=3)
    emg3 = nk.emg_simulate(duration=time, sampling_rate= rate, random_state=3, burst_number=3)
    emg4 = nk.emg_simulate(duration=time, sampling_rate= rate, random_state=4, burst_number=3)
    # sa jeszcze analogicznie fajne wykresy dla ppg, rsp i eda
    nk.signal_plot(ecg1, sampling_rate=rate)
    nk.signal_plot(ecg2, sampling_rate=rate)

    data = pd.DataFrame({'ecg1': ecg1,
                         'ecg2': ecg2,


                         'emg1': emg1,

                         })
    return data
コード例 #8
0
def test_emg_activation():

    emg = nk.emg_simulate(duration=10, burst_number=3)
    cleaned = nk.emg_clean(emg)
    emg_amplitude = nk.emg_amplitude(cleaned)

    activity_signal, info = nk.emg_activation(emg_amplitude)

    assert set(activity_signal.columns.to_list()) == set(list(info.keys()))
    assert len(info['EMG_Onsets']) == len(info['EMG_Offsets'])
    for i, j in zip(info['EMG_Onsets'], info['EMG_Offsets']):
        assert i < j
コード例 #9
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))
コード例 #10
0
def test_emg_clean():

    sampling_rate=1000

    emg = nk.emg_simulate(duration=20, sampling_rate=sampling_rate)
    emg_cleaned = nk.emg_clean(emg, sampling_rate=sampling_rate)

    assert emg.size == emg_cleaned.size

    # Comparison to biosppy (https://github.com/PIA-Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/emg.py)
    original, _, _ = biosppy.tools.filter_signal(signal=emg,
                                                 ftype='butter',
                                                 band='highpass',
                                                 order=4,
                                                 frequency=100,
                                                 sampling_rate=sampling_rate)
    emg_cleaned_biosppy = nk.signal_detrend(original, order=0)
    assert np.allclose((emg_cleaned - emg_cleaned_biosppy).mean(), 0, atol=1e-6)
コード例 #11
0
ファイル: tests_emg.py プロジェクト: zxy111248/NeuroKit
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})
コード例 #12
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
コード例 #13
0
ファイル: README_examples.py プロジェクト: ayushmh/NeuroKit
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":
コード例 #14
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)
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})
nk.signal_plot(data, subplots=True)

# Save it
data = pd.DataFrame({
    "ECG":
    nk.ecg_simulate(duration=10, heart_rate=70, noise=0),
    "RSP":
    nk.rsp_simulate(duration=10, respiratory_rate=15, noise=0),
    "EDA":
    nk.eda_simulate(duration=10, n_scr=3, noise=0),
    "EMG":
    nk.emg_simulate(duration=10, n_bursts=2, noise=0)
})
plot = data.plot(subplots=True,
コード例 #15
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)