예제 #1
0
def test_ecg_fixpeaks():

    sampling_rate = 1000
    noise = 0.15

    ecg = nk.ecg_simulate(duration=120, sampling_rate=sampling_rate,
                          noise=noise, method="simple", random_state=42)

    rpeaks = nk.ecg_findpeaks(ecg)

    # Test with iterative artifact correction.
    artifacts, rpeaks_corrected = nk.ecg_fixpeaks(rpeaks, iterative=True)

    assert np.allclose(rpeaks_corrected["ECG_R_Peaks"].sum(dtype=np.int64),
                       7383418, atol=1)

    assert all(isinstance(x, int) for x in artifacts["ectopic"])
    assert all(isinstance(x, int) for x in artifacts["missed"])
    assert all(isinstance(x, int) for x in artifacts["extra"])
    assert all(isinstance(x, int) for x in artifacts["longshort"])

    # Test with non-iterative artifact correction.
    artifacts, rpeaks_corrected = nk.ecg_fixpeaks(rpeaks, iterative=False)

    assert np.allclose(rpeaks_corrected["ECG_R_Peaks"].sum(dtype=np.int64),
                       7383418, atol=1)

    assert all(isinstance(x, int) for x in artifacts["ectopic"])
    assert all(isinstance(x, int) for x in artifacts["missed"])
    assert all(isinstance(x, int) for x in artifacts["extra"])
    assert all(isinstance(x, int) for x in artifacts["longshort"])
예제 #2
0
def test_hrv():

    ecg = nk.ecg_simulate(duration=60,
                          sampling_rate=1000,
                          heart_rate=110,
                          random_state=42)

    _, peaks = nk.ecg_process(ecg, sampling_rate=1000)

    ecg_hrv = nk.hrv(peaks, sampling_rate=1000)

    columns = [
        '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_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', 'HRV_ApEn',
        'HRV_SampEn'
    ]

    assert all(elem in np.array(ecg_hrv.columns.values, dtype=object)
               for elem in columns)
예제 #3
0
def test_ecg_delineate():

    sampling_rate = 1000

    # test with simulated signals
    ecg = nk.ecg_simulate(duration=20, sampling_rate=sampling_rate, random_state=42)
    _, rpeaks = nk.ecg_peaks(ecg, sampling_rate=sampling_rate)
    number_rpeaks = len(rpeaks["ECG_R_Peaks"])

    # Method 1: derivative
    _, waves_derivative = nk.ecg_delineate(ecg, rpeaks, sampling_rate=sampling_rate)
    assert len(waves_derivative["ECG_P_Peaks"]) == number_rpeaks
    assert len(waves_derivative["ECG_Q_Peaks"]) == number_rpeaks
    assert len(waves_derivative["ECG_S_Peaks"]) == number_rpeaks
    assert len(waves_derivative["ECG_T_Peaks"]) == number_rpeaks
    assert len(waves_derivative["ECG_P_Onsets"]) == number_rpeaks
    assert len(waves_derivative["ECG_T_Offsets"]) == number_rpeaks

    # Method 2: CWT
    _, waves_cwt = nk.ecg_delineate(ecg, rpeaks, sampling_rate=sampling_rate, method="cwt")
    assert np.allclose(len(waves_cwt["ECG_P_Peaks"]), 22, atol=1)
    assert np.allclose(len(waves_cwt["ECG_T_Peaks"]), 22, atol=1)
    assert np.allclose(len(waves_cwt["ECG_R_Onsets"]), 23, atol=1)
    assert np.allclose(len(waves_cwt["ECG_R_Offsets"]), 23, atol=1)
    assert np.allclose(len(waves_cwt["ECG_P_Onsets"]), 22, atol=1)
    assert np.allclose(len(waves_cwt["ECG_P_Offsets"]), 22, atol=1)
    assert np.allclose(len(waves_cwt["ECG_T_Onsets"]), 22, atol=1)
    assert np.allclose(len(waves_cwt["ECG_T_Offsets"]), 22, atol=1)
예제 #4
0
def test_ecg_clean():

    sampling_rate = 1000
    noise = 0.05

    ecg = nk.ecg_simulate(sampling_rate=sampling_rate, noise=noise)
    ecg_cleaned_nk = nk.ecg_clean(ecg, sampling_rate=sampling_rate, method="neurokit")

    assert ecg.size == ecg_cleaned_nk.size

    # Assert that highpass filter with .5 Hz lowcut was applied.
    fft_raw = np.abs(np.fft.rfft(ecg))
    fft_nk = np.abs(np.fft.rfft(ecg_cleaned_nk))

    freqs = np.fft.rfftfreq(ecg.size, 1 / sampling_rate)

    assert np.sum(fft_raw[freqs < 0.5]) > np.sum(fft_nk[freqs < 0.5])

    # Comparison to biosppy (https://github.com/PIA-Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/ecg.py#L69)
    ecg_biosppy = nk.ecg_clean(ecg, sampling_rate=sampling_rate, method="biosppy")
    original, _, _ = biosppy.tools.filter_signal(
        signal=ecg,
        ftype="FIR",
        band="bandpass",
        order=int(0.3 * sampling_rate),
        frequency=[3, 45],
        sampling_rate=sampling_rate,
    )
    assert np.allclose((ecg_biosppy - original).mean(), 0, atol=1e-6)
예제 #5
0
def test_ecg_rate():

    sampling_rate = 1000
    noise = 0.15

    ecg = nk.ecg_simulate(duration=120,
                          sampling_rate=sampling_rate,
                          noise=noise,
                          random_state=42)
    ecg_cleaned_nk = nk.ecg_clean(ecg,
                                  sampling_rate=sampling_rate,
                                  method="neurokit")

    signals, info = nk.ecg_peaks(ecg_cleaned_nk, method="neurokit")

    # Test without desired length.
    rate = nk.ecg_rate(rpeaks=info, sampling_rate=sampling_rate)

    assert rate.shape == (info["ECG_R_Peaks"].size, )
    assert np.allclose(rate.mean(), 70, atol=2)

    # Test with desired length.
    test_length = 1200
    rate = nk.ecg_rate(rpeaks=info,
                       sampling_rate=sampling_rate,
                       desired_length=test_length)

    assert rate.shape == (test_length, )
    assert np.allclose(rate.mean(), 70, atol=2)
예제 #6
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"]))
예제 #7
0
def test_ecg_peaks():

    sampling_rate = 1000
    noise = 0.15

    ecg = nk.ecg_simulate(duration=120,
                          sampling_rate=sampling_rate,
                          noise=noise,
                          random_state=42)
    ecg_cleaned_nk = nk.ecg_clean(ecg,
                                  sampling_rate=sampling_rate,
                                  method="neurokit")

    # Test without request to correct artifacts.
    signals, info = nk.ecg_peaks(ecg_cleaned_nk,
                                 correct_artifacts=False,
                                 method="neurokit")

    assert signals.shape == (120000, 1)
    assert np.allclose(signals["ECG_R_Peaks"].values.sum(dtype=np.int64),
                       139,
                       atol=1)

    # Test with request to correct artifacts.
    signals, info = nk.ecg_peaks(ecg_cleaned_nk,
                                 correct_artifacts=True,
                                 method="neurokit")

    assert signals.shape == (120000, 1)
    assert np.allclose(signals["ECG_R_Peaks"].values.sum(dtype=np.int64),
                       139,
                       atol=1)
예제 #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
    assert len(ecg_eventrelated.columns) == 15

    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_Phase_Atrial",
        "ECG_Phase_Atrial_Completion", "ECG_Phase_Ventricular",
        "ECG_Phase_Ventricular_Completion", 'ECG_Quality_Mean', "Event_Onset",
        "Label"
    ] for elem in np.array(ecg_eventrelated.columns.values, dtype=str))
예제 #9
0
def test_ecg_plot():

    ecg = nk.ecg_simulate(duration=60, heart_rate=70, noise=0.05)

    ecg_summary, _ = nk.ecg_process(ecg, sampling_rate=1000, method="neurokit")

    # Plot data over samples.
    nk.ecg_plot(ecg_summary)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 2
    titles = ["Raw and Cleaned Signal", "Heart Rate"]
    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 seconds.
    nk.ecg_plot(ecg_summary, sampling_rate=1000)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 3
    titles = ["Raw and Cleaned Signal", "Heart Rate", "Individual Heart Beats"]
    for (ax, title) in zip(fig.get_axes(), titles):
        assert ax.get_title() == title
    assert fig.get_axes()[1].get_xlabel() == "Time (seconds)"
    np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks())
    plt.close(fig)
예제 #10
0
def test_ecg_process():

    sampling_rate = 1000
    noise = 0.05

    ecg = nk.ecg_simulate(sampling_rate=sampling_rate, noise=noise)
    signals, info = nk.ecg_process(ecg, sampling_rate=sampling_rate, method="neurokit")
예제 #11
0
def test_ecg_simulate():

    ecg1 = nk.ecg_simulate(duration=20, length=5000, method="simple", noise=0)
    assert len(ecg1) == 5000

    ecg2 = nk.ecg_simulate(duration=20, length=5000, heart_rate=500)
    #    pd.DataFrame({"ECG1":ecg1, "ECG2": ecg2}).plot()
    #    pd.DataFrame({"ECG1":ecg1, "ECG2": ecg2}).hist()
    assert len(nk.signal_findpeaks(ecg1, height_min=0.6)["Peaks"]) < len(
        nk.signal_findpeaks(ecg2, height_min=0.6)["Peaks"]
    )

    ecg3 = nk.ecg_simulate(duration=10, length=5000)
    #    pd.DataFrame({"ECG1":ecg1, "ECG3": ecg3}).plot()
    assert len(nk.signal_findpeaks(ecg2, height_min=0.6)["Peaks"]) > len(
        nk.signal_findpeaks(ecg3, height_min=0.6)["Peaks"]
    )
예제 #12
0
 def load_signal_from_disk(filename=None, sampling_rate=2000):
     if filename is None:
         ecg = nk.ecg_simulate(
             duration=10, sampling_rate=sampling_rate, method="ecgsyn")
     else:
         filename = (pathlib.Path(__file__) / '../ecg_data' / filename).resolve().as_posix()
         ecg = np.array(pd.read_csv(filename))[:, 1]
     return ecg, sampling_rate
예제 #13
0
def test_eeg_add_channel():

    raw = mne.io.read_raw_fif(mne.datasets.sample.data_path() +
                              '/MEG/sample/sample_audvis_raw.fif',
                              preload=True)
    ecg = nk.ecg_simulate(length=170000)
    raw = nk.eeg_add_channel(raw, ecg, channel_type="ecg")
    df = raw.to_data_frame()
    assert len(df.columns) == 377
예제 #14
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})
예제 #15
0
def simulation(normal_N,abnormal_N, save_params = False):
    normal_data = []
    normal_params = []
    print('Creating normal dataset')
    for i in range(normal_N):
        ti = np.random.normal(para.mu_t_1, para.sigma_t_1)
        ai = np.random.normal(para.mu_a_1, para.sigma_a_1)
        bi = np.random.normal(para.mu_b_1, para.sigma_b_1)
        hr = np.random.normal(para.mu_hr_1, para.sigma_hr_1)
        noise = np.random.uniform(low=para.min_noise_1, high=para.max_noise_1)
        ecgs, _ = nk.ecg_simulate(duration=para.duration*2, sampling_rate=para.sampling_rate, noise=noise, Anoise=para.Anoise, heart_rate=hr, gamma=para.gamma, ti=ti, ai=ai, bi=bi)
        ecgs = np.array(ecgs)
        start_i = np.random.randint(len(ecgs[0])//4, len(ecgs[0])//2)
        normal_data.append(ecgs[:,start_i:start_i+para.sampling_rate*para.duration])
        normal_params.append({'ti':ti, 'ai':ai, 'bi':bi, 'hr':hr, 'noise':noise, 'gamma': para.gamma})

    abnormal_data = []
    abnormal_params = []
    print('Creating abnormal dataset')
    for i in range(abnormal_N):
        ti = np.random.normal(para.mu_t_2, para.sigma_t_2)
        ai = np.random.normal(para.mu_a_2, para.sigma_a_2)
        bi = np.random.normal(para.mu_b_2, para.sigma_b_2)
        hr = np.random.normal(para.mu_hr_2, para.sigma_hr_2)
        noise = np.random.uniform(low=para.min_noise_2, high=para.max_noise_2)
        ecgs, _ = nk.ecg_simulate(duration=para.duration*2, sampling_rate=para.sampling_rate, noise=noise, Anoise=para.Anoise, heart_rate=hr, gamma=para.gamma, ti=ti, ai=ai, bi=bi)
        ecgs = np.array(ecgs)
        start_i = np.random.randint(len(ecgs[0])//4, len(ecgs[0])//2)
        abnormal_data.append(ecgs[:,start_i:start_i+para.sampling_rate*para.duration])
        abnormal_params.append({'ti':ti, 'ai':ai, 'bi':bi, 'hr':hr, 'noise':noise, 'gamma': para.gamma})

    labels = np.array([0]*len(normal_data) + [1]*len(abnormal_data))
    permutation = np.random.permutation(len(labels))
    data = np.array(normal_data+abnormal_data)
    data_params = np.array(normal_params+abnormal_params)
    labels = labels[permutation]
    data = data[permutation]
    data_params = data_params[permutation]

    np.save('sim_ecg_data', data) # save ECG data
    np.save('sim_ecg_labels', labels) # save label
    if (save_params):
        np.save('sim_ecg_params',data_params) # save parameters for each ecg sample (12,2500)
예제 #16
0
    def get_bedmaster_waveforms() -> Dict[str, BedmasterSignal]:
        starting_time = int(time())
        duration = 8
        sample_freq_1 = 240
        sample_freq_2 = 120
        times = np.arange(starting_time, starting_time + duration, 0.25)
        values1 = nk.ecg_simulate(
            duration=int(duration / 2),
            sampling_rate=sample_freq_1,
        )
        values2 = nk.ecg_simulate(
            duration=int(duration / 2),
            sampling_rate=sample_freq_2,
        )
        values = np.concatenate([values1, values2])
        n_samples = np.array([sample_freq_1 * 0.25] * int(duration * 4 / 2) +
                             [sample_freq_2 * 0.25] * int(duration * 4 / 2), )

        # Remove some samples
        values = np.delete(values, [10, 11, 250])
        n_samples[0] = 58
        n_samples[5] = 59

        leads = {
            lead: BedmasterSignal(
                name=lead,
                source="waveform",
                channel=f"ch{idx}",
                value=values,
                time=times,
                units="mV",
                sample_freq=np.array(
                    [(sample_freq_1, 0), (sample_freq_2, 16)],
                    dtype="float,int",
                ),
                scale_factor=np.random.uniform() * 5,
                time_corr_arr=np.packbits(
                    np.random.randint(0, 2, 100).astype(np.bool)),
                samples_per_ts=n_samples,
            )
            for idx, lead in enumerate(["i", "ii", "iii", "v", "spo2"])
        }
        return leads
예제 #17
0
def test_ecg_hrv():
    ecg_slow = nk.ecg_simulate(duration=60, sampling_rate=1000, heart_rate=70, random_state=42)
    ecg_fast = nk.ecg_simulate(duration=60, sampling_rate=1000, heart_rate=110, random_state=42)

    ecg_slow, _ = nk.ecg_process(ecg_slow, sampling_rate=1000)
    ecg_fast, _ = nk.ecg_process(ecg_fast, sampling_rate=1000)

    ecg_slow_hrv = nk.ecg_hrv(ecg_slow, sampling_rate=1000)
    ecg_fast_hrv = nk.ecg_hrv(ecg_fast, sampling_rate=1000)

    assert ecg_fast_hrv["HRV_RMSSD"][0] < ecg_slow_hrv["HRV_RMSSD"][0]
    assert ecg_fast_hrv["HRV_MeanNN"][0] < ecg_slow_hrv["HRV_MeanNN"][0]
    assert ecg_fast_hrv["HRV_SDNN"][0] < ecg_slow_hrv["HRV_SDNN"][0]
    assert ecg_fast_hrv["HRV_CVNN"][0] < ecg_slow_hrv["HRV_CVNN"][0]
    assert ecg_fast_hrv["HRV_CVSD"][0] < ecg_slow_hrv["HRV_CVSD"][0]
    assert ecg_fast_hrv["HRV_MedianNN"][0] < ecg_slow_hrv["HRV_MedianNN"][0]
    assert ecg_fast_hrv["HRV_MadNN"][0] < ecg_slow_hrv["HRV_MadNN"][0]
    assert ecg_fast_hrv["HRV_MCVNN"][0] < ecg_slow_hrv["HRV_MCVNN"][0]
    assert ecg_fast_hrv["HRV_pNN50"][0] == ecg_slow_hrv["HRV_pNN50"][0]
    assert ecg_fast_hrv["HRV_pNN20"][0] < ecg_slow_hrv["HRV_pNN20"][0]
    assert ecg_fast_hrv["HRV_TINN"][0] < ecg_slow_hrv["HRV_TINN"][0]
    assert ecg_fast_hrv["HRV_HTI"][0] > ecg_slow_hrv["HRV_HTI"][0]
    assert ecg_fast_hrv["HRV_ULF"][0] == ecg_slow_hrv["HRV_ULF"][0] == 0


    assert all(elem in ['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']
               for elem in np.array(ecg_fast_hrv.columns.values, dtype=str))

    # Test frequency domain
    ecg1 = nk.ecg_simulate(duration=60, sampling_rate=2000, heart_rate=70, random_state=42)
    hrv1 = nk.ecg_hrv(nk.ecg_process(ecg1, sampling_rate=2000)[0], sampling_rate=2000)

    ecg2 = nk.signal_resample(ecg1, sampling_rate=2000, desired_sampling_rate=500)
    hrv2 = nk.ecg_hrv(nk.ecg_process(ecg2, sampling_rate=500)[0], sampling_rate=500)

    assert np.allclose(np.mean(hrv1[["HRV_HF", "HRV_LF", "HRV_VLF"]].iloc[0] - hrv2[["HRV_HF", "HRV_LF", "HRV_VLF"]].iloc[0]), 0, atol=1)
예제 #18
0
def test_ecg_hrv():
    ecg_slow = nk.ecg_simulate(duration=60,
                               sampling_rate=1000,
                               heart_rate=70,
                               random_state=42)
    ecg_fast = nk.ecg_simulate(duration=60,
                               sampling_rate=1000,
                               heart_rate=110,
                               random_state=42)

    ecg_slow, _ = nk.ecg_process(ecg_slow)
    ecg_fast, _ = nk.ecg_process(ecg_fast)

    ecg_slow_hrv = nk.ecg_hrv(ecg_slow)
    ecg_fast_hrv = nk.ecg_hrv(ecg_fast)

    assert ecg_fast_hrv["HRV_RMSSD"][0] < ecg_slow_hrv["HRV_RMSSD"][0]
    assert ecg_fast_hrv["HRV_MeanNN"][0] < ecg_slow_hrv["HRV_MeanNN"][0]
    assert ecg_fast_hrv["HRV_SDNN"][0] < ecg_slow_hrv["HRV_SDNN"][0]
    assert ecg_fast_hrv["HRV_CVNN"][0] < ecg_slow_hrv["HRV_CVNN"][0]
    assert ecg_fast_hrv["HRV_CVSD"][0] < ecg_slow_hrv["HRV_CVSD"][0]
    assert ecg_fast_hrv["HRV_MedianNN"][0] < ecg_slow_hrv["HRV_MedianNN"][0]
    assert ecg_fast_hrv["HRV_MadNN"][0] < ecg_slow_hrv["HRV_MadNN"][0]
    assert ecg_fast_hrv["HRV_MCVNN"][0] < ecg_slow_hrv["HRV_MCVNN"][0]
    assert ecg_fast_hrv["HRV_pNN50"][0] == ecg_slow_hrv["HRV_pNN50"][0]
    assert ecg_fast_hrv["HRV_pNN20"][0] < ecg_slow_hrv["HRV_pNN20"][0]
    assert ecg_fast_hrv["HRV_TINN"][0] < ecg_slow_hrv["HRV_TINN"][0]
    #    assert ecg_fast_hrv["HRV_HTI"][0] > ecg_slow_hrv["HRV_HTI"][0]
    #    assert ecg_fast_hrv["HRV_ULF"][0] == ecg_slow_hrv["HRV_ULF"][0] == 0
    #    assert ecg_fast_hrv["HRV_VLF"][0] < ecg_slow_hrv["HRV_VLF"][0]
    #    assert ecg_fast_hrv["HRV_LF"][0] < ecg_slow_hrv["HRV_LF"][0]
    #    assert ecg_fast_hrv["HRV_HF"][0] < ecg_slow_hrv["HRV_HF"][0]
    #    assert ecg_fast_hrv["HRV_VHF"][0] > ecg_slow_hrv["HRV_VHF"][0]

    assert all(elem in [
        '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'
    ] for elem in np.array(ecg_fast_hrv.columns.values, dtype=str))
예제 #19
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
예제 #20
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
예제 #21
0
def test_ecg_process():

    sampling_rate = 1000
    noise = 0.05

    ecg = nk.ecg_simulate(sampling_rate=sampling_rate, noise=noise)
    signals, info = nk.ecg_process(ecg,
                                   sampling_rate=sampling_rate,
                                   method="neurokit")
    # Only check array dimensions and column names since functions called by
    # ecg_process have already been unit tested
    assert all(elem in ["ECG_Raw", "ECG_Clean", "ECG_R_Peaks", "ECG_Rate"]
               for elem in np.array(signals.columns.values, dtype=str))
예제 #22
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))
예제 #23
0
def test_ecg_process():

    sampling_rate = 1000
    noise = 0.05

    ecg = nk.ecg_simulate(sampling_rate=sampling_rate, noise=noise)
    signals, info = nk.ecg_process(ecg, sampling_rate=sampling_rate,
                                   method="neurokit")
    # Only check array dimensions and column names since functions called by
    # ecg_process have already been unit tested
    assert all(elem in ["ECG_Raw", "ECG_Clean", "ECG_R_Peaks", "ECG_Rate",
                        'ECG_Quality', "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"]
               for elem in np.array(signals.columns.values, dtype=str))
예제 #24
0
def test_hrv():

    ecg = nk.ecg_simulate(duration=60,
                          sampling_rate=1000,
                          heart_rate=110,
                          random_state=42)

    _, peaks = nk.ecg_process(ecg, sampling_rate=1000)

    ecg_hrv = nk.hrv(peaks, sampling_rate=1000)

    assert all(elem in [
        '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'
    ] for elem in np.array(ecg_hrv.columns.values, dtype=str))
예제 #25
0
def test_hrv_frequency():
    # Test frequency domain
    ecg1 = nk.ecg_simulate(duration=60,
                           sampling_rate=2000,
                           heart_rate=70,
                           random_state=42)
    _, peaks1 = nk.ecg_process(ecg1, sampling_rate=2000)
    hrv1 = nk.hrv_frequency(peaks1, sampling_rate=2000)

    ecg2 = nk.signal_resample(ecg1,
                              sampling_rate=2000,
                              desired_sampling_rate=500)
    _, peaks2 = nk.ecg_process(ecg2, sampling_rate=500)
    hrv2 = nk.hrv_frequency(peaks2, sampling_rate=500)

    assert np.allclose(hrv1["HRV_HF"] - hrv2["HRV_HF"], 0, atol=1.5)
    assert np.isnan(hrv1["HRV_LF"][0])
    assert np.isnan(hrv2["HRV_LF"][0])
    assert np.isnan(hrv1["HRV_VLF"][0])
    assert np.isnan(hrv2["HRV_LF"][0])
예제 #26
0
import numpy as np
import pandas as pd

import neurokit2 as nk

sampling_rate = 1000

for heartrate in [80]:
    # Simulate signal
    ecg = nk.ecg_simulate(duration=60,
                          sampling_rate=sampling_rate,
                          heartrate=heartrate,
                          noise=0)

    # Segment
    _, rpeaks = nk.ecg_peaks(ecg, sampling_rate=sampling_rate)
#    _, waves = nk.ecg_delineator(ecg, rpeaks=rpeaks["ECG_R_Peaks"])
예제 #27
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":
예제 #28
0
def test_ecg_findpeaks():

    sampling_rate = 1000

    ecg = nk.ecg_simulate(duration=60,
                          sampling_rate=sampling_rate,
                          noise=0,
                          method="simple",
                          random_state=42)

    ecg_cleaned = nk.ecg_clean(ecg,
                               sampling_rate=sampling_rate,
                               method="neurokit")

    # Test neurokit methodwith show=True
    info_nk = nk.ecg_findpeaks(ecg_cleaned, show=True)

    assert info_nk["ECG_R_Peaks"].size == 69
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 2

    # Test pantompkins1985 method
    info_pantom = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="pantompkins1985"),
                                   method="pantompkins1985")
    assert info_pantom["ECG_R_Peaks"].size == 70

    # Test hamilton2002 method
    info_hamilton = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="hamilton2002"),
                                     method="hamilton2002")
    assert info_hamilton["ECG_R_Peaks"].size == 69

    # Test christov2004 method
    info_christov = nk.ecg_findpeaks(ecg_cleaned, method="christov2004")
    assert info_christov["ECG_R_Peaks"].size == 273

    # Test gamboa2008 method
    info_gamboa = nk.ecg_findpeaks(ecg_cleaned, method="gamboa2008")
    assert info_gamboa["ECG_R_Peaks"].size == 69

    # Test elgendi2010 method
    info_elgendi = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="elgendi2010"),
                                    method="elgendi2010")
    assert info_elgendi["ECG_R_Peaks"].size == 70

    # Test engzeemod2012 method
    info_engzeemod = nk.ecg_findpeaks(nk.ecg_clean(ecg,
                                                   method="engzeemod2012"),
                                      method="engzeemod2012")
    assert info_engzeemod["ECG_R_Peaks"].size == 70

    # Test kalidas2017 method
    info_kalidas = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="kalidas2017"),
                                    method="kalidas2017")
    assert info_kalidas["ECG_R_Peaks"].size == 69

    # Test martinez2003 method
    ecg = nk.ecg_simulate(duration=60,
                          sampling_rate=sampling_rate,
                          noise=0,
                          random_state=42)
    ecg_cleaned = nk.ecg_clean(ecg,
                               sampling_rate=sampling_rate,
                               method="neurokit")
    info_martinez = nk.ecg_findpeaks(ecg_cleaned, method="martinez2003")
    assert np.allclose(info_martinez["ECG_R_Peaks"].size, 69, atol=1)
signaltype =vars(args)["T"]
t = vars(args)["t"]
f = vars(args)["f"]
bpm = vars(args)["b"]
diastolic = vars(args)["D"]
systolic = vars(args)["S"]
respiration = vars(args)["r"]
pespiration = vars(args)["p"]
step = vars(args)["s"]
print(signaltype,t,f,bpm,diastolic,systolic,respiration,pespiration)
ech_array = []

if "po" in signaltype:
    #procedure pour generer un pouls
    samples_pouls =  nk.ecg_simulate(duration=t, sampling_rate=f ,noise=.05, heart_rate=bpm,method="simple")
    ech_array = keepOnlyPositive(samples_pouls)
    ech_array /= np.max(ech_array,axis=0)/3.3

elif "pr" in signaltype :

    index = np.linspace(-9, 9, num= int(f / (bpm/60)))
    normal1 = scipy.stats.norm.pdf(index, loc=-2, scale=1)*  (systolic/MAX_SYSTOLIQUE)#premier peak systolique
    normal2 = scipy.stats.norm.pdf(index, loc=2, scale=1.5)* (diastolic/MAX_DIASTOLIQUE) # deuxieme peak diastolique
    samples = 8 * (normal1 + normal2) #facteur 8 seulement pour scaler entre 0 et 3.3

    # La valeur en Voltage d'une personne qui a une systolique normal (120), est autour de  2.8 , pour une systolique eleve(140), on est autour de 3.2 , une sytolique basse (100) est autour de 2.3
    #la valeur en Voltage d'une personne qui a une diastolique normal (80) est autour de 1.8 ,  pour une diastolique eleve(90), on est atour de 2.10, une diastolique basse (60) est autour de  1.4

    #prolongement du signal de pression selon le temps de signal voulu
    for i in range(0,int(t)):
예제 #30
0
def generate_ecg(time, rate):
    ecg = ecg_simulate(duration=time, sampling_rate=rate, method="ecgsyn")

    return ecg