Exemplo n.º 1
0
def get_peaks_ecg(subject, inputs, outputs, recompute, logpath):
    """Detect R-peaks in ECG.

    1. Detect R-peaks
    2. autocorrect artifacts in R-peaks detection.
    """
    save_path = Path(
        individualize_path(outputs["save_path"], subject, expand_name=True))
    if save_path.exists() and not recompute:  # only recompute if requested
        print(f"Not re-computing {save_path}")
        return
    physio_path = next(
        Path(".").glob(individualize_path(inputs["physio_path"], subject)))

    ecg = np.ravel(pd.read_csv(physio_path, sep="\t", header=None))
    # Detect R-peaks.
    peaks = ecg_peaks(ecg, ECG_SFREQ_DECIMATED)
    # Correct artifacts in peak detection.
    peaks_corrected = correct_peaks(peaks, ECG_SFREQ_DECIMATED, iterative=True)
    # Save peaks as samples.
    pd.Series(peaks_corrected).to_csv(save_path,
                                      sep="\t",
                                      header=False,
                                      index=False,
                                      float_format="%.4f")

    if not logpath:
        return

    fig, ax = plt.subplots(nrows=1, ncols=1)
    sec = np.linspace(0, len(ecg) / ECG_SFREQ_DECIMATED, len(ecg))
    ax.plot(sec, ecg)
    ax.scatter(sec[peaks],
               ecg[peaks],
               zorder=3,
               c="r",
               marker="+",
               s=300,
               label="uncorrected R-peaks")
    ax.scatter(sec[peaks_corrected],
               ecg[peaks_corrected],
               zorder=4,
               c="g",
               marker="x",
               s=300,
               label="corrected R-peaks")
    ax.set_xlabel("seconds")
    ax.legend(loc="upper right")

    fig.savefig(logpath, dpi=200)
    plt.close(fig)
Exemplo n.º 2
0
def test_missed_correction_wrapper(peaks_correct, peaks_missed, iterative,
                                   rmssd_diff):

    peaks_corrected = correct_peaks(peaks_missed, sfreq=1, iterative=iterative)

    rmssd_correct = compute_rmssd(peaks_correct)
    rmssd_corrected = compute_rmssd(peaks_corrected)
    rmssd_uncorrected = compute_rmssd(peaks_missed)

    # Assert that correction does not produce peaks that exceed the temporal
    # bounds of the original peaks.
    assert peaks_correct[0] <= peaks_corrected[0]
    assert peaks_correct[-1] >= peaks_corrected[-1]

    # Assert that after artifact correction, the difference in RMSSD to the
    # undistorted signal decreases. This also implicitely tests if the peak
    # distortion affects the RMSSD (manipulation check).
    rmssd_diff_uncorrected = np.abs(rmssd_correct - rmssd_uncorrected)
    rmssd_diff_corrected = np.abs(rmssd_correct - rmssd_corrected)

    assert int(rmssd_diff_uncorrected - rmssd_diff_corrected) == rmssd_diff