Example #1
0
def pan_tompkins_single(fields, record, save_path, sig, save=True):
    detectors = Detectors(fields['fs'])
    r_peaks = detectors.pan_tompkins_detector(sig[:, 0])
    if save:
        save_prediction(r_peaks, record, save_path)
    else:
        return r_peaks
def stopmeasuring():
    global sp
    print('killing process with id: ', sp)
    os.system("taskkill /f /t /pid " + str(sp))
    print("subprocess stopped")
    df = pd.read_csv('data.csv', index_col=None, header=0)
    ecg_signal = df['ECG'] * 1000
    sr = 60
    time = np.linspace(0, len(ecg_signal) / sr, len(ecg_signal))
    detectors = Detectors(sr)
    r_peaks = detectors.pan_tompkins_detector(ecg_signal)
    peaks = np.array(time)[r_peaks]
    RRinterval = np.diff(peaks)
    median = np.median(RRinterval)
    RRinterval = np.append(RRinterval, median)
    df = df.iloc[r_peaks]
    df["RRinterval"] = RRinterval
    df["RRinterval"] = np.where(df["RRinterval"] < 0.5, median,
                                df["RRinterval"])
    df["RRinterval"] = np.where(df["RRinterval"] > 1.5, median,
                                df["RRinterval"])
    df["RRinterval"] = signal.medfilt(df["RRinterval"], 5)
    rri = df['RRinterval']
    diff_rri = np.diff(rri)
    NNRR = round(len(np.diff(rri)) / len(rri), 6)
    RMSSD = np.sqrt(np.mean(diff_rri**2))
    SDNN = np.nanstd(rri, ddof=1)
    AVNN = np.nanmean(rri)
    nn50 = np.sum(np.abs(diff_rri) > 0.05)
    pNN50 = nn50 / len(rri)
    df['NNRR'] = NNRR
    df['RMSSD'] = RMSSD
    df['SDNN'] = SDNN
    df['AVNN'] = AVNN
    df['pNN50'] = pNN50
    print(df.describe())
    df = df.replace([np.inf, -np.inf], np.nan)
    df['HR'].fillna((df['HR'].mean()), inplace=True)
    df['HR'] = signal.medfilt(df['HR'], 5)
    df['RESP'].fillna((df['RESP'].mean()), inplace=True)
    df['RESP'] = signal.medfilt(df['RESP'], 5)
    df['EMG'].fillna((df['EMG'].mean()), inplace=True)
    df['EMG'] = signal.medfilt(df['EMG'], 5)
    df['ECG'].fillna((df['ECG'].mean()), inplace=True)
    df['ECG'] = signal.medfilt(df['ECG'], 5)
    df = df.fillna(df.mean())
    df.to_csv('test_data2.csv', index=False)
    df = df.drop(['time'], axis=1)
    predictions = ExtraTreesClassifier.predict(df)
    print('predictions: ', predictions)
    c = (predictions == 0).sum()
    c1 = (predictions == 1).sum()
    if c < c1:
        class_ = 'stressed'
        return render_template('stressed.html', pred=class_)
    else:
        class_ = 'not stressed'
        return render_template('notstressed.html', pred=class_)
    print(class_)
Example #3
0
def heart_rate_variability(sample, lead, rpeak_method = 'string'):
    curdir = 'DATA\TrainData_FeatureExtraction'
    [all_data, header_data, BAD_LABELS] = data_read.data_files_load(curdir)

    data = all_data[sample][lead]

    """INITIALIZE DETECTOR CLASS WITH THE SAMPLING RATE:"""
    detectors = Detectors(500)

    """FIND RPEAK USING ONE OF THE METHODS BELOW--------------------"""

    if rpeak_method == 'hamilton' or rpeak_method == 'string':
        #Hamilton.
        r_peaks = detectors.hamilton_detector(data)

    elif rpeak_method == 'christov':
        #Christov
        r_peaks = detectors.christov_detector(data)

    elif rpeak_method == 'engelse':
        #Engelse and Zeelenberg
        r_peaks = detectors.engzee_detector(data)

    elif rpeak_method == 'pan':
        #Pan and Tompkins
        r_peaks = detectors.pan_tompkins_detector(data)

    elif rpeak_method == 'stationary_wavelet':
        #Stationary Wavelet Transform
        r_peaks = detectors.swt_detector(data)

    elif rpeak_method == 'two_moving_average':
        #Two Moving Average
        r_peaks = detectors.two_average_detector(data)

    #elif rpeak_method == 'matched_filter':
        #Matched Filter
        #go to pyhrv documentation to find the template file
        #r_peaks = detectors.matched_filter_detector(data,template_file)

    """COMPUTE NNI SERIES-------------------------------------------"""
    nn = nn_intervals(r_peaks) #nni seems to be off by a factor of 3
    print("\n\n", nn, "\n\n")

    """PLOT ECG/TACHOGRAM-------------------------------------------"""
    #plot_ecg(data, sampling_rate = 500)
    #tachogram(nn, sampling_rate = 500)

    """COMPUTE HRV--------------------------------------------------"""
    results = hrv(nn, None, None, 500)

    """COMPUTE HR PARAMETERS--(SOMETHING IS WRONG HERE BPM TOO HIGH)"""
    hr = heart_rate(nn)

    """COMPUTE FREQUENCY ANALYSIS-----------------------------------"""
    freq_results = results['fft_bands']

    return results, hr, freq_results
Example #4
0
    def pan_tompkins_detector(signal):
        from ecgdetectors import Detectors
        detectors = Detectors(500)
        annotation = []

        for i in range(0, 8):
            annotation.append(detectors.pan_tompkins_detector(signal[i][:]))

        # annotation.append(detectors.pan_tompkins_detector(signal[1][:]))
        return annotation
Example #5
0
 def test_ecg_detectors_package(self):
     for i in range(100, 300):
         try:
             record_name = self.mitdb + str(i)
             sig, fields = wfdb.rdsamp(record_name, channels=[0])
             detectors = Detectors(fields['fs'])
             r_peaks = detectors.pan_tompkins_detector(sig[:, 0])
             samples = np.array(r_peaks)
             wfdb.wrann(str(i),
                        'atr',
                        sample=samples,
                        write_dir="data/ann",
                        symbol=(['N'] * len(r_peaks)))
             print(i)
         except Exception as e:
             print(i, e)
def ECG_segment(dataset, channel_num=0):
    segments_per_ECG = []
    all_preprocessed_datas = []
    all_r_peaks = []
    for rec in dataset:
        ecg_all_channel = rec[0]
        ecg_channel_1 = ecg_all_channel[:, channel_num]
        #Done by gautham
        pre_precocessed_data = overall_preprocessing(ecg_channel_1)
        pre_precocessed_data = pre_precocessed_data[:-9]

        detectors = Detectors(fs)
        #Peak Detection
        r_peaks = detectors.pan_tompkins_detector(pre_precocessed_data)
        all_r_peaks.append(r_peaks)
        #Peak Segmentation
        all_segments = []
        count = 0
        for i in range(len(r_peaks)):
            data_segment = np.zeros((1, 500), dtype=float)
            data_segment = data_segment.ravel()

            if ((r_peaks[i] - 250) >= 0
                    and (r_peaks[i] + 250) < len(pre_precocessed_data)):
                data_segment = pre_precocessed_data[r_peaks[i] -
                                                    250:r_peaks[i] + 250]
                count = count + 1
            elif ((r_peaks[i] - 250) < 0):
                nZeros = 250 - r_peaks[i]
                data_segment[nZeros:500] = pre_precocessed_data[0:r_peaks[i] +
                                                                250]
                count = count + 1
            elif (r_peaks[i] + 250 > len(pre_precocessed_data)):
                nZeros = r_peaks[i] + 250 - len(pre_precocessed_data)
                data_segment[0:500 - nZeros] = pre_precocessed_data[
                    r_peaks[i] - 250:len(pre_precocessed_data)]
                count = count + 1
            all_segments.append(data_segment)

        all_preprocessed_datas.append(pre_precocessed_data)
        segments_per_ECG.append(all_segments)

    return segments_per_ECG, all_preprocessed_datas, all_r_peaks
Example #7
0
def num_beats(voltage, time):
    """Counts number of heartbeats in ECG strip data

    The peaks of an ECG indicate a heart beat, with each
    peak indicative of a QRS wave. By counting these beats,
    the heart rate can be determined, which can further be
    used to diagnose deeper conditions.

    Args:
        voltage (list): voltage data of the ECG strip
        time (list): time data of the ECG strip

    Returns:
        int: number of peaks/beats in the ECG strip
        list: indices of ECG peaks identified
    """
    logging.info("Calculating number of beats in ECG trace")
    fs = 1 / (time[1] - time[0])
    detectors = Detectors(fs)
    unfiltered_ecg = voltage
    r_peaks = detectors.pan_tompkins_detector(unfiltered_ecg)
    num_peaks = len(r_peaks)
    return num_peaks, r_peaks
            ecg_channel_maths = maths_class.einthoven_II
        elif "v" in sys.argv[1]:
            ecg_channel_sitting = sitting_class.cs_V2_V1
            ecg_channel_maths = maths_class.cs_V2_V1
        else:
            print(
                "Bad argument. Specify 'e' for Einthoven or 'v' for the Chest strap."
            )
            exit(1)

        r_peaks = detectors.swt_detector(ecg_channel_sitting)
        sitting_rr_sd.append(hrv_class.RMSSD(r_peaks, True))
        r_peaks = detectors.swt_detector(ecg_channel_maths)
        maths_rr_sd.append(hrv_class.RMSSD(r_peaks, True))

        sitting_error_rr = detectors.pan_tompkins_detector(ecg_channel_sitting)
        sitting_error_rr_sd.append(hrv_class.RMSSD(sitting_error_rr, True))

        maths_error_rr = detectors.pan_tompkins_detector(ecg_channel_maths)
        maths_error_rr_sd.append(hrv_class.RMSSD(maths_error_rr, True))

        maths_true_rr = maths_class.anno_cs
        maths_true_sd.append(hrv_class.RMSSD(maths_true_rr, True))

        sitting_true_rr = sitting_class.anno_cs
        sitting_true_sd.append(hrv_class.RMSSD(sitting_true_rr, True))

subject = np.array(subject)
width = 0.4

fig, ax = plt.subplots()
Example #9
0
import wfdb
from ecgdetectors import Detectors
import numpy as np

DATA_PATH = "/data/"
SAVE_PATH = "/pred/"

with open(DATA_PATH + "RECORDS", 'r') as f:
    records = f.readlines()
    records = list(map(lambda r: r.strip("\n"), records))

for record in records:
    sig, fields = wfdb.rdsamp(DATA_PATH + record, channels=[0])
    detectors = Detectors(fields['fs'])
    r_peaks = detectors.pan_tompkins_detector(sig[:, 0])
    if len(r_peaks) > 0:
        samples = np.array(r_peaks)
        wfdb.wrann(record,
                   'atr',
                   sample=samples,
                   write_dir=SAVE_PATH,
                   symbol=(['N'] * len(r_peaks)))
Example #10
0
def ecg_peaks(x, sfreq=1000, new_sfreq=1000, method='pan-tompkins',
              find_local=True, win_size=100):
    """A simple wrapper for many popular R peaks detectors algorithms.

    This function calls methods from the py-ecg-detectors [#]_ module.

    Parameters
    ----------
    x : list or 1d array-like
        The oxi signal.
    sfreq : int
        The sampling frequency. Default is set to 75 Hz.
    method : str
        The method used. Can be one of the following: 'hamilton', 'christov',
        'engelse-zeelenberg', 'pan-tompkins', 'wavelet-transform',
        'moving-average'.
    find_local : bool
        If *True*, will use peaks indexs to search for local peaks given the
        window size (win_size).
    win_size : int
        Size of the time window used by :py:func:`systole.utils.to_neighbour()`

    Returns
    -------
    peaks : 1d array-like
        Numpy array containing peaks index.
    resampled_signal : 1d array-like
        Signal resampled to the `new_sfreq` frequency.

    Notes
    -----
    This function will call the py-ecg-detectors package to perform R wave
    detection.

    .. warning :: This function will resample the signal to 1000 Hz.

    Examples
    --------
    >>> from systole import import_dataset
    >>> from systole.detection import ecg_peaks
    >>> signal_df = import_dataset()[:20*2000]
    >>> signal, peaks = ecg_peaks(signal_df.ecg.to_numpy(), method='hamilton',
    >>>                           sfreq=2000, find_local=True)
    >>> print(f'{sum(peaks)} peaks detected.')
    24 peaks detected.

    References
    ----------
    .. [#] Howell, L., Porr, B. Popular ECG R peak detectors written in
    python. DOI: 10.5281/zenodo.3353396
    """

    if isinstance(x, list):
        x = np.asarray(x)

    # Interpolate
    f = interp1d(np.arange(0, len(x)/sfreq, 1/sfreq),
                 x,
                 fill_value="extrapolate")
    time = np.arange(0, len(x)/sfreq, 1/new_sfreq)
    x = f(time)

    # Copy resampled signal for output
    resampled_signal = np.copy(x)

    detectors = Detectors(new_sfreq)

    if method == 'hamilton':
        peaks_idx = detectors.hamilton_detector(resampled_signal)
    elif method == 'christov':
        peaks_idx = detectors.christov_detector(resampled_signal)
    elif method == 'engelse-zeelenberg':
        peaks_idx = detectors.engzee_detector(resampled_signal)
    elif method == 'pan-tompkins':
        peaks_idx = detectors.pan_tompkins_detector(resampled_signal)
    elif method == 'wavelet-transform':
        peaks_idx = detectors.swt_detector(resampled_signal)
    elif method == 'moving-average':
        peaks_idx = detectors.two_average_detector(resampled_signal)
    else:
        raise ValueError(
            'Invalid method provided, should be: hamilton,',
            'christov, engelse-zeelenberg, pan-tompkins, wavelet-transform,',
            'moving-average')
    peaks = np.zeros(len(resampled_signal), dtype=bool)
    peaks[peaks_idx] = True

    if find_local is True:
        peaks = to_neighbour(resampled_signal, peaks, size=win_size)

    return resampled_signal, peaks
Example #11
0
def run_algo(algorithm: str, sig: numpy.ndarray,
             freq_sampling: int) -> List[int]:
    """
    run a qrs detector on a signal

    :param algorithm: name of the qrs detector to use
    :type algorithm: str
    :param sig: values of the sampled signal to study
    :type sig: ndarray
    :param freq_sampling: value of sampling frequency of the signal
    :type freq_sampling: int
    :return: localisations of qrs detections
    :rtype: list(int)
    """
    detectors = Detectors(freq_sampling)
    if algorithm == 'Pan-Tompkins-ecg-detector':
        qrs_detections = detectors.pan_tompkins_detector(sig)
    elif algorithm == 'Hamilton-ecg-detector':
        qrs_detections = detectors.hamilton_detector(sig)
    elif algorithm == 'Christov-ecg-detector':
        qrs_detections = detectors.christov_detector(sig)
    elif algorithm == 'Engelse-Zeelenberg-ecg-detector':
        qrs_detections = detectors.engzee_detector(sig)
    elif algorithm == 'SWT-ecg-detector':
        qrs_detections = detectors.swt_detector(sig)
    elif algorithm == 'Matched-filter-ecg-detector' and freq_sampling == 360:
        qrs_detections = detectors.matched_filter_detector(
            sig, 'templates/template_360hz.csv')
    elif algorithm == 'Matched-filter-ecg-detector' and freq_sampling == 250:
        qrs_detections = detectors.matched_filter_detector(
            sig, 'templates/template_250hz.csv')
    elif algorithm == 'Two-average-ecg-detector':
        qrs_detections = detectors.two_average_detector(sig)
    elif algorithm == 'Hamilton-biosppy':
        qrs_detections = bsp_ecg.ecg(signal=sig,
                                     sampling_rate=freq_sampling,
                                     show=False)[2]
    elif algorithm == 'Christov-biosppy':
        order = int(0.3 * freq_sampling)
        filtered, _, _ = bsp_tools.filter_signal(signal=sig,
                                                 ftype='FIR',
                                                 band='bandpass',
                                                 order=order,
                                                 frequency=[3, 45],
                                                 sampling_rate=freq_sampling)
        rpeaks, = bsp_ecg.christov_segmenter(signal=filtered,
                                             sampling_rate=freq_sampling)
        rpeaks, = bsp_ecg.correct_rpeaks(signal=filtered,
                                         rpeaks=rpeaks,
                                         sampling_rate=freq_sampling,
                                         tol=0.05)
        _, qrs_detections = bsp_ecg.extract_heartbeats(
            signal=filtered,
            rpeaks=rpeaks,
            sampling_rate=freq_sampling,
            before=0.2,
            after=0.4)
    elif algorithm == 'Engelse-Zeelenberg-biosppy':
        order = int(0.3 * freq_sampling)
        filtered, _, _ = bsp_tools.filter_signal(signal=sig,
                                                 ftype='FIR',
                                                 band='bandpass',
                                                 order=order,
                                                 frequency=[3, 45],
                                                 sampling_rate=freq_sampling)
        rpeaks, = bsp_ecg.engzee_segmenter(signal=filtered,
                                           sampling_rate=freq_sampling)
        rpeaks, = bsp_ecg.correct_rpeaks(signal=filtered,
                                         rpeaks=rpeaks,
                                         sampling_rate=freq_sampling,
                                         tol=0.05)
        _, qrs_detections = bsp_ecg.extract_heartbeats(
            signal=filtered,
            rpeaks=rpeaks,
            sampling_rate=freq_sampling,
            before=0.2,
            after=0.4)
    elif algorithm == 'Gamboa-biosppy':
        order = int(0.3 * freq_sampling)
        filtered, _, _ = bsp_tools.filter_signal(signal=sig,
                                                 ftype='FIR',
                                                 band='bandpass',
                                                 order=order,
                                                 frequency=[3, 45],
                                                 sampling_rate=freq_sampling)
        rpeaks, = bsp_ecg.gamboa_segmenter(signal=filtered,
                                           sampling_rate=freq_sampling)
        rpeaks, = bsp_ecg.correct_rpeaks(signal=filtered,
                                         rpeaks=rpeaks,
                                         sampling_rate=freq_sampling,
                                         tol=0.05)
        _, qrs_detections = bsp_ecg.extract_heartbeats(
            signal=filtered,
            rpeaks=rpeaks,
            sampling_rate=freq_sampling,
            before=0.2,
            after=0.4)
    elif algorithm == 'mne-ecg':
        qrs_detections = mne_ecg.qrs_detector(freq_sampling, sig)
    elif algorithm == 'heartpy':
        rol_mean = rolling_mean(sig, windowsize=0.75, sample_rate=100.0)
        qrs_detections = hp_pkdetection.detect_peaks(
            sig, rol_mean, ma_perc=20, sample_rate=100.0)['peaklist']
    elif algorithm == 'gqrs-wfdb':
        qrs_detections = processing.qrs.gqrs_detect(sig=sig, fs=freq_sampling)
    elif algorithm == 'xqrs-wfdb':
        qrs_detections = processing.xqrs_detect(sig=sig, fs=freq_sampling)
    else:
        raise ValueError(
            f'Sorry... unknown algorithm. Please check the list {algorithms_list}'
        )
    cast_qrs_detections = [int(element) for element in qrs_detections]
    return cast_qrs_detections
Example #12
0
    def ecg_detector(self, s, detector_type="pan_tompkins"):
        """
        Expose

        ECG peak detector from the github
        https://github.com/berndporr/py-ecg-detectors

        Parameters
        ----------
        s :
            Input signal

        fs:
            The signal frequency. Default is '256 Hz'

        detector_type:
            'hamilton': Open Source ECG Analysis Software Documentation,
            E.P.Limited, 2002.

            'christov':Real time electrocardiogram QRS detection using combined
            adaptive threshold

            'engzee': A single scan algorithm for QRS detection and
            feature extraction

            'swt': Real-time QRS detector using Stationary Wavelet Transform
            for Automated ECG Analysis.
            Uses the Pan and Tompkins thresolding.

            'mva': Frequency Bands Effects on QRS Detection.

            'mtemp':

            'pan_tompkins': A Real-Time QRS Detection Algorithm

            Default = 'pan_tompkins'


        Returns
        -------
        type
            an array of 1-D numpy array represent the peak list

        """
        if self.wave_type == 'ppg':
            warnings.warn("A ECG detectors is using on PPG waveform. "
                          "Output may produce incorrect result")
        detector = Detectors(self.fs)
        if detector_type == 'hamilton':
            res = detector.hamilton_detector(s)
        elif detector_type == 'christov':
            res = detector.christov_detector(s)
        elif detector_type == 'engzee':
            res = detector.engzee_detector(s)
        elif detector_type == 'swt':
            res = detector.swt_detector(s)
        elif detector_type == 'mva':
            res = detector.two_average_detector(s)
        elif detector_type == 'mtemp':
            res = self.matched_filter_detector(s)
        else:
            res = detector.pan_tompkins_detector(s)
        return np.array(res)