Пример #1
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)
Пример #2
0
def segment(yClean):
    ECG_signal, info = nk.ecg_process(yClean, sampling_rate=1000)
    # Visualise the processing

    # plt.savefig('./images/signal_varios.png')

    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    nk.ecg_plot(ECG_signal, sampling_rate=1000)
    return nk.ecg_plot(ECG_signal, sampling_rate=1000)
Пример #3
0
# =============================================================================
# Cardiac activity (ECG) processing
# =============================================================================

# Generate 15 seconds of ECG signal (recorded at 250 samples / second)
ecg = nk.ecg_simulate(duration=15,
                      sampling_rate=250,
                      heart_rate=70,
                      random_state=333)

# Process it
signals, info = nk.ecg_process(ecg, sampling_rate=250)

# Visualise the processing
nk.ecg_plot(signals, sampling_rate=250)

# Save it
plot = nk.ecg_plot(signals, sampling_rate=250)
plot.set_size_inches(10, 6, forward=True)
plot.savefig("README_ecg.png", dpi=300, h_pad=3)

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

# Generate one minute of RSP signal (recorded at 250 samples / second)
rsp = nk.rsp_simulate(duration=60, sampling_rate=250, respiratory_rate=15)

# Process it
signals, info = nk.rsp_process(rsp, sampling_rate=250)
Пример #4
0
def test_ecg_process_func(signal,
                          start,
                          n_samples,
                          fs,
                          plot_builtin=False,
                          plot_events=True):
    """Runs neurokit.ecg_process() on specified section of data and plots builtin plot or plot that
       shows P, R, and T waves, atrial/ventricular phases, and peaks.

    :param signal: array of data
    :param start: start index in signal
    :param n_samples: how many samples to process
    :param fs: sample rate, Hz
    :param plot_builtin: Boolean; runs neurokit.ecg_plot()
    :param plot_events: boolean: runs custom plot

    :return: data objects generated in neurokit.ecg_process()
    """
    s, i = nk.ecg_process(signal[start:start + n_samples], fs)

    if plot_events:

        fig, axes = plt.subplots(1, figsize=(10, 6))
        axes.plot(np.arange(0, s.shape[0]) / fs,
                  s["ECG_Clean"],
                  label="Filtered",
                  color='black')

        axes.plot(s.loc[s["ECG_R_Peaks"] == 1].index / fs,
                  s.loc[s["ECG_R_Peaks"] == 1]["ECG_Clean"],
                  marker="o",
                  linestyle="",
                  color='grey',
                  label="R Peak")

        axes.plot(s.loc[s["ECG_T_Peaks"] == 1].index / fs,
                  s.loc[s["ECG_T_Peaks"] == 1]["ECG_Clean"],
                  marker="x",
                  linestyle="",
                  color='red',
                  label="T Peak")

        axes.plot(s.loc[s["ECG_P_Peaks"] == 1].index / fs,
                  s.loc[s["ECG_P_Peaks"] == 1]["ECG_Clean"],
                  marker="x",
                  linestyle="",
                  color='green',
                  label="P Peak")

        axes.legend(loc='lower left')

        axes2 = axes.twinx()
        axes2.set_yticks([])
        axes2.set_ylim(0, 1)

        axes2.fill_between(x=np.arange(0, s.shape[0]) / fs,
                           y1=.5,
                           y2=s["ECG_Phase_Atrial"].replace(to_replace=0,
                                                            value=.5),
                           color='green',
                           alpha=.25,
                           label="Atrial phase")

        axes2.fill_between(x=np.arange(0, s.shape[0]) / fs,
                           y1=.5,
                           y2=s["ECG_Phase_Ventricular"].replace(to_replace=0,
                                                                 value=.5),
                           color='purple',
                           alpha=.25,
                           label="Ventr. phase")

        p_start = s.loc[s["ECG_P_Onsets"] == 1]
        p_end = s.loc[s["ECG_P_Offsets"] == 1]

        t_start = s.loc[s["ECG_T_Onsets"] == 1]
        t_end = s.loc[s["ECG_T_Offsets"] == 1]

        r_start = s.loc[s["ECG_R_Onsets"] == 1]
        r_end = s.loc[s["ECG_R_Offsets"] == 1]

        for i in range(p_start.shape[0]):
            if i == range(p_start.shape[0])[-1]:
                axes2.fill_between(
                    x=[p_start.index[i] / fs, p_end.index[i] / fs],
                    y1=0,
                    y2=.5,
                    color='dodgerblue',
                    alpha=.25,
                    label="P wave")
            else:
                axes2.fill_between(
                    x=[p_start.index[i] / fs, p_end.index[i] / fs],
                    y1=0,
                    y2=.5,
                    color='dodgerblue',
                    alpha=.25)

        for i in range(t_start.shape[0]):
            if i == range(t_start.shape[0])[-1]:
                axes2.fill_between(
                    x=[t_start.index[i] / fs, t_end.index[i] / fs],
                    y1=0,
                    y2=.5,
                    color='red',
                    alpha=.25,
                    label="T wave")
            else:
                axes2.fill_between(
                    x=[t_start.index[i] / fs, t_end.index[i] / fs],
                    y1=0,
                    y2=.5,
                    color='red',
                    alpha=.25)

        for i in range(r_start.shape[0]):
            if i == range(r_start.shape[0])[-1]:
                axes2.fill_between(
                    x=[r_start.index[i] / fs, r_end.index[i] / fs],
                    y1=0,
                    y2=.5,
                    color='grey',
                    alpha=.25,
                    label="R wave")
            else:
                axes2.fill_between(
                    x=[r_start.index[i] / fs, r_end.index[i] / fs],
                    y1=0,
                    y2=.5,
                    color='grey',
                    alpha=.25)

        axes2.legend(loc='lower right')
        axes.set_xlabel("Seconds")

    if plot_builtin:
        nk.ecg_plot(s, fs)

    return s, i