예제 #1
0
def test_ecg_calculator():
    from scipy.misc import electrocardiogram
    from ecg_analysis import ecg_peaks
    import numpy as np
    from ecg_analysis import ecg_peaks
    from ecg_analysis import ecg_logging
    from ecg_analysis import ecg_calculator
    x1 = electrocardiogram()[2000:4000]
    x2 = electrocardiogram()[1000:2000]
    x3 = electrocardiogram()[6000:8000]
    peaks1 = ecg_peaks(x1)
    peaks2 = ecg_peaks(x2)
    peaks3 = ecg_peaks(x3)
    x_axis = np.arange(2000, 4000)
    data1 = np.transpose(np.vstack((x_axis, x1)))
    x_axis = np.arange(1000, 2000)
    data2 = np.transpose(np.vstack((x_axis, x2)))
    x_axis = np.arange(6000, 8000)
    data3 = np.transpose(np.vstack((x_axis, x3)))
    dict1 = ecg_calculator("aaa", data1, peaks1)
    dict1_ans = {
        'beats':
        [2251.0, 2431.0, 2608.0, 2779.0, 2956.0, 3125.0, 3292.0, 3456.0],
        'duration': 1998.0,
        'mean_hr_bpm': 0.24024024024024024,
        'num_beats': 8,
        'voltage_extremes': (-1.14, 2.09)
    }
    dict2 = ecg_calculator("aaa", data2, peaks2)
    dict2_ans = {
        'beats': [1130.0, 1317.0, 1501.0, 1691.0, 1880.0],
        'duration': 998.0,
        'mean_hr_bpm': 0.3006012024048096,
        'num_beats': 5,
        'voltage_extremes': (-1.05, 1.5)
    }
    dict3 = ecg_calculator("aaa", data3, peaks3)
    dict3_ans = {
        'beats': [
            6048.0, 6250.0, 6454.0, 6865.0, 7155.0, 7423.0, 7608.0, 7797.0,
            7975.0
        ],
        'duration':
        1998.0,
        'mean_hr_bpm':
        0.2702702702702703,
        'num_beats':
        9,
        'voltage_extremes': (-1.35, 2.125)
    }
    assert dict1 == dict1_ans
    assert dict2 == dict2_ans
    assert dict3 == dict3_ans
예제 #2
0
def test_ecg_peaks():
    from scipy.misc import electrocardiogram
    from ecg_analysis import ecg_peaks
    x = electrocardiogram()[2000:4000]
    x2 = electrocardiogram()[1000:2000]
    x3 = electrocardiogram()[6000:8000]
    peaks1 = ecg_peaks(x)
    peaks2 = ecg_peaks(x2)
    peaks3 = ecg_peaks(x3)
    assert peaks1.tolist() == [251, 431, 608, 779, 956, 1125, 1292, 1456]
    assert peaks2.tolist() == [130, 317, 501, 691, 880]
    assert peaks3.tolist() == [48, 250, 454, 865, 1155, 1423, 1608, 1797, 1975]
예제 #3
0
    def setup(self):
        ecg_signal = electrocardiogram()
        ecg_signal = ecg_signal - np.mean(ecg_signal)

        (ts, filtered, rpeaks, templates_ts, templates, heart_rate_ts,
         heart_rate) = ecg.ecg(signal=ecg_signal,
                               sampling_rate=360,
                               show=False)

        my_ecg = fb.ECG(input_signal=filtered,
                        indicators=rpeaks,
                        is_filtered=False)
        list_ecg = my_ecg.buildPackets(25)

        norm_parameter = list(
            zip(np.linspace(3, 13, 10), np.linspace(3, 13, 10)))
        norm_lenght = list(zip(np.linspace(15, 20, 5), np.linspace(15, 20, 5)))
        parameter = list(zip(np.linspace(3, 13, 10), np.linspace(3, 13, 10)))
        lenght = list(zip(np.linspace(15, 20, 5), np.linspace(15, 20, 5)))

        template_gaussian = fb.TemplateEvaluetor(fb.Gaussian(), norm_parameter,
                                                 norm_lenght)
        template_mexican = fb.TemplateEvaluetor(fb.MexicanHat(), parameter,
                                                lenght)
        template_rayleigh = fb.TemplateEvaluetor(fb.Rayleigh(), parameter,
                                                 lenght)
        template_left_rayleigh = fb.TemplateEvaluetor(fb.LeftInverseRayleigh(),
                                                      parameter, lenght)
        template_right_rayleigh = fb.TemplateEvaluetor(
            fb.RightInverseRayleigh(), parameter, lenght)

        list_of_templates = [
            template_gaussian, template_mexican, template_rayleigh,
            template_left_rayleigh, template_right_rayleigh
        ]
예제 #4
0
def hallarHR(ecg = electrocardiogram(),fs=360,h=0.05,w=1):
    time = np.arange(np.size(ecg))/fs
    peaks, properties = find_peaks(ecg,height=h,width=w)#x y y de HR
    tacograma = np.diff(time[peaks])#la diferencia entre cada pico
    bpm = 60/tacograma #latidos por minuto
    HR = np.mean(bpm)
    return round(HR,2)
예제 #5
0
def test_electrocardiogram():
    # Test shape, dtype and stats of signal
    ecg = electrocardiogram()
    assert ecg.dtype == float
    assert_equal(ecg.shape, (108000, ))
    assert_almost_equal(ecg.mean(), -0.16510875)
    assert_almost_equal(ecg.std(), 0.5992473991177294)
예제 #6
0
파일: test_common.py 프로젝트: Kitchi/scipy
def test_electrocardiogram():
    # Test shape, dtype and stats of signal
    ecg = electrocardiogram()
    assert ecg.dtype == float
    assert_equal(ecg.shape, (108000,))
    assert_almost_equal(ecg.mean(), -0.16510875)
    assert_almost_equal(ecg.std(), 0.5992473991177294)
예제 #7
0
def cut_generic_ecg_(t):
    generic_ecg = electrocardiogram()
    fs = 360
    time = np.arange(generic_ecg.size) / fs
    f_ecg = interp1d(time, generic_ecg)
    cut_generic_ecg = np.array(f_ecg(t))
    return cut_generic_ecg
 def test_approach_3(self):
     x = electrocardiogram()[200:300]
     peaks, _ = find_peaks(x)
     troughs, _ = find_peaks(-x)
     plt.plot(x)
     plt.plot(peaks, x[peaks], '^', c="r")
     plt.plot(troughs, x[troughs], 'v', c="g")
     plt.show()
예제 #9
0
def medical_data(system,
                 dynamic_state=None,
                 L=None,
                 fs=None,
                 SampleSize=None,
                 parameters=None,
                 InitialConditions=None):
    import numpy as np
    run = True
    if run == True:
        if system == 'ECG':
            from scipy.misc import electrocardiogram

            if dynamic_state == 'periodic':  #healthy
                ts = [electrocardiogram()[3000:5500]]

            if dynamic_state == 'chaotic':  #heart arrythmia
                ts = [electrocardiogram()[8500:11000]]

            fs = 360
            ts = [(ts[0])]
            t = np.arange(len(ts[0])) / fs

    # In[ ]: Complete

        if system == 'EEG':

            if SampleSize == None: SampleSize = 5000

            if dynamic_state == 'periodic':  #healthy
                ts = [
                    np.loadtxt('Data\\EEG\\Z093.txt', skiprows=1)[0:SampleSize]
                ]

            if dynamic_state == 'chaotic':  #seizure
                ts = [
                    np.loadtxt('Data\\EEG\\S056.txt', skiprows=1)[0:SampleSize]
                ]

            fs = 173.61
            t = np.arange(len(ts[0])) / fs
            t = t[-SampleSize:]
            ts = [(ts[0])[-SampleSize:]]

    return t, ts
    def spectral_analysis(self):
        # Plotting ECG
        Fs = 360
        t = 4
        f = 10
        x = electrocardiogram()
        n = np.arange(x.size) / Fs

        f = Figure(figsize=(10, 6), dpi=100)
        a = f.add_subplot(211)

        a.set_xlabel("time in s")
        a.set_ylabel("ECG in mV")
        a.set_title("ECG Signal")
        a.set_xlim(46.5, 50)
        a.set_ylim(-2, 1.5)
        a.plot(n, x)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        #Spectral Analysis
        x_fft = abs(sf.fft(x))
        l = np.size(x)
        fr = (Fs / 2) * np.linspace(0, 1, l / 2)
        x_magnitude = (2 / l) * abs(x_fft[0:np.size(fr)])

        f2 = Figure(figsize=(10, 6), dpi=100)
        b = f.add_subplot(212)

        b.set_xlabel('Frequency / Hz')
        b.set_ylabel('Magnitude / dB')
        b.set_title("Spectral analysis of the ECG")

        b.plot(fr, 20 * x_magnitude)

        canvas2 = FigureCanvasTkAgg(f2, self)
        canvas2.draw()
        canvas2.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar2 = NavigationToolbar2Tk(canvas2, self)
        toolbar2.update()
        canvas2._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        f.tight_layout()
        f2.tight_layout()
예제 #11
0
def main():
    ecg_signal = electrocardiogram()
    ecg_signal = ecg_signal - np.mean(ecg_signal)
    (ts, filtered, rpeaks, templates_ts, templates, heart_rate_ts, heart_rate
     ) = ecg.ecg(signal=ecg_signal, sampling_rate=360, show=False)
    
    my_ecg = fb.ECG(input_signal=filtered, indicators=rpeaks,
                    is_filtered=False)
    list_ecg = my_ecg.build_packets(25, fb.DefaultPacket)
    
    norm_parameter = dict()
    norm_parameter['values'] = list(zip(np.linspace(0.1, 0.3, 50),
                                    np.linspace(0.1, 0.3, 50)))
    norm_parameter['lenght'] = list(zip(np.linspace(15, 150, 10),
                                    np.linspace(15, 150, 10)))
    norm_parameter['cut'] = list(zip(np.linspace(5, 50, 5),
                                   np.linspace(5, 50, 5)))
    parameter = dict()
    parameter['values'] = list(zip(np.linspace(3, 10, 50),
                               np.linspace(3, 10, 50)))
    parameter['lenght'] = list(zip(np.linspace(15, 150, 10),
                                    np.linspace(15, 150, 10)))
    parameter['cut'] = list(zip(np.linspace(10, 60, 10),
                                   np.linspace(10, 60, 10)))

    template_gaussian = fb.TemplateEvaluetor(fb.Gaussian(), norm_parameter)
    template_mexican = fb.TemplateEvaluetor(fb.MexicanHat(), parameter)
    template_rayleigh = fb.TemplateEvaluetor(fb.Rayleigh(), parameter)
    template_left_rayleigh = fb.TemplateEvaluetor(fb.LeftInverseRayleigh(),
                                                  parameter)
    template_right_rayleigh = fb.TemplateEvaluetor(fb.RightInverseRayleigh(),
                                                   parameter)
    list_of_templates = [template_gaussian, template_mexican,
                         template_rayleigh, template_left_rayleigh,
                         template_right_rayleigh]
#    list_of_templates = [template_left_rayleigh, template_right_rayleigh]

    lst_of_packets = utils.mp_signal_apply(utils.consume_packet_helper,
                                           list_ecg[:5], list_of_templates)

#    lst_of_packets = utils.serial_signal_apply(utils.consume_packet,
#                                           list_ecg[:1], list_of_templates)
    my_ecg.packets = lst_of_packets
    return my_ecg
    def ecg(self):
        ecg = electrocardiogram()
        fs = 360
        time = np.arange(ecg.size) / fs

        f = Figure(figsize=(10, 6), dpi=100)
        a = f.add_subplot(111)
        a.set_xlabel("time in s")
        a.set_ylabel("ECG in mV")
        a.set_title("ECG Signal")
        a.set_xlim(46.5, 50)
        a.set_ylim(-2, 1.5)
        a.plot(time, ecg)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
예제 #13
0
파일: test_np.py 프로젝트: xloc/gear-fault
import ctypes

so = ctypes.CDLL('find_peak.so')

from scipy.misc import electrocardiogram
import numpy as np

x_np: np.ndarray = electrocardiogram()[2000:2500]
x_np = x_np.astype(np.float32)
c_float_p = ctypes.POINTER(ctypes.c_float)

x = x_np.ctypes.data_as(c_float_p)
xn = len(x_np)

t = ctypes.c_int
mid, left, right = (t * xn)(), (t * xn)(), (t * xn)()
m = ctypes.c_int()

mid_np = np.zeros(xn, dtype=np.int32)
mid = mid_np.ctypes.data_as(ctypes.POINTER(ctypes.c_int))

so.local_maxima.argtypes = \
    ctypes.POINTER(ctypes.c_float), ctypes.c_int,\
    ctypes.POINTER(t), ctypes.POINTER(t), ctypes.POINTER(t), ctypes.POINTER(t)

so.local_maxima.restype = None

so.local_maxima(x, xn, mid, left, right, m)

print(m)
# mid = list(mid)[:m.value]
예제 #14
0
 def setup(self, rel_height):
     self.x = electrocardiogram()
     self.peaks = find_peaks(self.x)[0]
     self.prominence_data = peak_prominences(self.x, self.peaks)
예제 #15
0
 def setup(self, wlen):
     self.x = electrocardiogram()
     self.peaks = find_peaks(self.x)[0]
예제 #16
0
 def setup(self, distance):
     self.x = electrocardiogram()
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline

from scipy.misc import electrocardiogram
ECG = electrocardiogram()


class Signal:
    def __init__(self, y):
        self.x1 = np.arange(y.size)
        self.y1 = y

    def print_(self, title='Signal'):
        fig, ax = plt.subplots(figsize=(8, 5))

        ax.plot(self.x1, self.y1)

        ax.set_title(title, size=20)
        ax.set_xlabel('Samples')
        ax.set_ylabel('Amplitude')

        plt.show()


class Ecg(Signal):
    def __init__(self, cycles=1):
        self.cycles = cycles

        freq = 360
        n_start = int(12.8 * freq)
예제 #18
0
def test_inconsistent_signal_len():
    record = ECGRecord("record_100", time=Time.from_fs_samples(360, 10))
    with pytest.raises(ValueError):
        record.add_signal(Signal(electrocardiogram(), "MLII"))
예제 #19
0
파일: ex_ecg.py 프로젝트: cadop/seg1d
def run():

    import random
    import numpy as np
    from scipy.misc import electrocardiogram
    import matplotlib.pyplot as plt
    import seg1d

    # In this example we use the ECG data included with scipy signal module.
    # The references roughly includes the Q-T interval (https://en.wikipedia.org/wiki/Electrocardiography).
    # In the first portion, two sample segments are used. While the segments are not aligned, they are able to find some segments correctly.
    # In the second portion of the example, only one segment is used for the reference data.

    ecg = electrocardiogram()  # get the scipy sample data
    ref_slices = [[927, 1057], [1111, 1229]]  # pick sample endpoints

    s = seg1d.Segmenter()  # create the segmenter

    refs = [ecg[x[0]:x[1]] for x in ref_slices]
    for r in refs:
        s.add_reference(r)  # set reference data

    s.set_target(ecg[1500:3500])  # set the target data to the ecg after ref
    segments = s.segment()  # run segmenter with defaults

    print(np.around(segments, decimals=7))
    # [[1.607000e+03 1.729000e+03 8.169533e-01]
    #  [7.380000e+02 8.220000e+02 8.123868e-01]
    #  [9.190000e+02 1.003000e+03 8.120505e-01]
    #  [1.439000e+03 1.552000e+03 8.092366e-01]
    #  [3.600000e+02 4.930000e+02 8.077664e-01]
    #  [1.091000e+03 1.213000e+03 8.043364e-01]
    #  [1.775000e+03 1.895000e+03 7.998723e-01]
    #  [1.720000e+02 3.000000e+02 7.926582e-01]
    #  [1.268000e+03 1.340000e+03 7.847107e-01]
    #  [5.540000e+02 6.280000e+02 7.802931e-01]]

    refs = s.r
    refs = np.asarray([x[y] for x in refs for y in x])

    plt.figure(figsize=(5, 3))
    plt.plot(refs.T)
    plt.xlabel("time in s")
    plt.ylabel("ECG in mV")
    plt.tight_layout()
    plt.show()

    plt.figure(figsize=(15, 3))
    plt.plot(s.t_masked.T)
    plt.xlabel("time in s")
    plt.ylabel("ECG in mV")
    plt.tight_layout()
    plt.show()

    # use only 1 reference
    s.clear_reference()
    s.add_reference(ecg[927:1057])
    # remove first part of data (contains reference)
    s.set_target(ecg[1500:3500])
    s.nC = 2
    s.cMin = 0.7

    segments = s.segment()

    print(np.around(segments, decimals=7))
    # [[7.350000e+02 8.540000e+02 9.462850e-01]
    #  [1.093000e+03 1.213000e+03 9.242974e-01]
    #  [9.140000e+02 1.046000e+03 9.059727e-01]
    #  [3.620000e+02 4.980000e+02 9.009127e-01]
    #  [5.470000e+02 6.800000e+02 8.940106e-01]
    #  [1.262000e+03 1.390000e+03 8.868629e-01]
    #  [1.776000e+03 1.902000e+03 8.771139e-01]
    #  [1.609000e+03 1.729000e+03 8.689476e-01]
    #  [1.440000e+03 1.559000e+03 8.646669e-01]
    #  [1.730000e+02 3.060000e+02 8.029426e-01]]

    res = s.t_masked

    plt.figure(figsize=(15, 3))
    plt.plot(res.T)
    plt.xlabel("time in s")
    plt.ylabel("ECG in mV")
    plt.tight_layout()
    plt.show()
예제 #20
0
* Variable **ecg** should be plotted with just a black line.
* Any values in variable **ecg** below zero should be plotted with red markers and no line.
* **Make sure both of these plotted data (red and black) are aligned on the x-axis (time)**


Your plot should have:
* title
* axes labels
* legend

Try to make all labels as scientific and conscise as you can
"""

from scipy.misc import electrocardiogram

ecg = electrocardiogram()

### YOUR CODE GOES BELOW ###
posecg = ecg.copy()
negecg = ecg.copy()

posecg[posecg <= 0] = np.nan
negecg[negecg > 0] = np.nan

plt.figure(figsize=(15, 15))

plt.title('Electrocardiogram Data')
plt.xlabel('Time')
plt.ylabel('mV (sampled at 360 Hz)')

plt.plot(posecg, '-k', label='ECG data')
예제 #21
0
def test_inconsistent_signal_type():
    record = ECGRecord("record_100", time=Time.from_fs_samples(360, 10))
    with pytest.raises(TypeError):
        record.add_signal(electrocardiogram())
예제 #22
0
import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np

x = electrocardiogram()[17000:18000]
peaks, properties = find_peaks(x, prominence=1, width=20)
properties["prominences"], properties["widths"]
print(properties)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"],
           ymax = x[peaks], color = "C1")
plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"],
           xmax=properties["right_ips"], color = "C1")
plt.show()
예제 #23
0
import random
import numpy as np
from scipy.misc import electrocardiogram
import matplotlib.pyplot as plt
import seg1d

# After imports, the scipy signal ECG data is called and some segments are taken.

ecg = electrocardiogram()  #get the scipy sample data
ref_slices = [[927, 1057], [1111, 1229]]  #pick sample endpoints

s = seg1d.Segmenter()  #create the segmenter

refs = [ecg[x[0]:x[1]] for x in ref_slices]
for r in refs:
    s.add_reference(r)  #set reference data

s.set_target(ecg[1500:3500])  #set the target data to the ecg after ref
segments = s.segment()  # run segmenter with defaults

print(np.around(segments, decimals=7))
# [[1.607000e+03 1.729000e+03 8.169533e-01]
# [7.380000e+02 8.220000e+02 8.123868e-01]
# [9.190000e+02 1.003000e+03 8.120505e-01]
# [1.439000e+03 1.552000e+03 8.092366e-01]
# [3.600000e+02 4.930000e+02 8.077664e-01]
# [1.091000e+03 1.213000e+03 8.043364e-01]
# [1.775000e+03 1.895000e+03 7.998723e-01]
# [1.720000e+02 3.000000e+02 7.926582e-01]
# [1.268000e+03 1.340000e+03 7.847107e-01]
# [5.540000e+02 6.280000e+02 7.802931e-01]]
    keep_np, keep = T.create_bool_array(len(peaks_np))
    keep_np[:] = 1

    so = ctypes.CDLL('find_peak.so')
    so.select_by_peak_distance.argtypes = (T.int_p, T.int, T.float_p, T.float,
                                           T.bool_p)
    so.select_by_peak_distance.restype = None

    so.select_by_peak_distance(peaks, len(peaks_np), priority, distance, keep)

    del (so)
    return keep_np


from scipy.misc import electrocardiogram
x = electrocardiogram()[2000:4000]

from scipy.signal._peak_finding_utils import _local_maxima_1d
peaks, _, _ = _local_maxima_1d(x)

distance = 5

keep = select_by_peak_distance(peaks, x[peaks], distance)

from scipy.signal._peak_finding_utils import \
    _select_by_peak_distance as scipy_select_by_peak_distance

keep_groundtrue = scipy_select_by_peak_distance(peaks, x[peaks], distance)
# print(np.argsort(x[peaks]))

print((keep))
    def Bandstop_Filter(self, Lower_CutoffFrequency, Upper_CutoffFrequency,
                        Ordernumber):

        # Design Highpass Filter
        Fs = 360
        x = electrocardiogram()
        n = np.arange(x.size) / Fs

        filter_order = Ordernumber  # Changeable FilterOrder
        cut_off_f = np.array([Lower_CutoffFrequency,
                              Upper_CutoffFrequency])  # Cut off Frequency!!!!
        normalized = 2 * cut_off_f / Fs
        [b, c] = sig.butter(filter_order, normalized, btype='bandstop')

        # filterresponse

        [W, h] = sig.freqz(b, c, worN=1024)
        W = Fs * W / (2 * pi)

        f = Figure(figsize=(10, 6), dpi=100)
        a = f.add_subplot(311)

        a.set_xlabel('Frequency / Hz')
        a.set_ylabel("Magnitude / dB")
        a.set_title('Band Stop Filter Frequency Response')

        a.plot(W, 20 * np.log10(h))

        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        # Bandstop filtered signal

        x_filtered = sig.lfilter(b, c, x)

        f2 = Figure(figsize=(10, 6), dpi=100)
        a = f.add_subplot(312)

        a.set_xlabel('Time / s')
        a.set_ylabel("Amplitude / mV")
        a.set_xlim(46.5, 50)
        a.set_ylim(-2, 1.5)
        a.set_title('band stop filtered ECG')

        a.plot(n, x_filtered)

        canvas2 = FigureCanvasTkAgg(f2, self)
        canvas2.draw()
        canvas2.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar2 = NavigationToolbar2Tk(canvas, self)
        toolbar2.update()
        canvas2._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        f3 = Figure(figsize=(10, 6), dpi=100)
        a = f.add_subplot(313)

        a.set_xlabel("time in s")
        a.set_ylabel("ECG in mV")
        a.set_title("ECG Signal")
        a.set_xlim(46.5, 50)
        a.set_ylim(-2, 1.5)
        a.plot(n, x)

        canvas = FigureCanvasTkAgg(f3, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP,
                              fill=tk.BOTH,
                              expand=True,
                              padx=2,
                              pady=2)
        f.tight_layout()
        f2.tight_layout()
        f3.tight_layout()
예제 #26
0
import matplotlib.pyplot as plt
import pywt
from scipy.misc import electrocardiogram

# denoise sample ecg signal using pywavelet

data_raw = electrocardiogram()
data_raw = data_raw[:2000]
w = pywt.Wavelet('sym4')

# select a maxlev or using pywt.dwt_max_level()
maxlev = pywt.dwt_max_level(len(data_raw), w.dec_len)
# maxlev = 2
print(f"maximum level is {maxlev}")

coeffs = pywt.wavedec(data_raw, w, level=maxlev)

threshold = 0.1
plt.figure()
for i in range(1, len(coeffs)):
    plt.subplot(maxlev, 1, i)
    plt.plot(coeffs[i], 'b-')

    # apply threshold
    coeffs[i] = pywt.threshold(coeffs[i], threshold * max(coeffs[i]))

    plt.plot(coeffs[i], 'r-')

data_denoised = pywt.waverec(coeffs, w)

plt.figure()
예제 #27
0
    out_peaks_np, out_peaks = T.create_int_array(len(x_np) // 2)
    out_peaks_len = T.int()

    so = ctypes.CDLL('find_peak.so')
    so.find_peaks.argtypes = (T.float_p, T.int, T.float, T.float, T.int,
                              T.int_p, T.int_p)
    so.find_peaks.restype = None

    so.find_peaks(x, len(x_np), distance, prominence, wlen, out_peaks,
                  out_peaks_len)

    return out_peaks_np[:out_peaks_len.value]


from scipy.misc import electrocardiogram
x = electrocardiogram()[2000:2500]

distance = 100
prominence = 0.2

from scipy.signal import find_peaks as scipy_find_peaks
peaks_groudtrue, _ = scipy_find_peaks(x,
                                      distance=distance,
                                      prominence=prominence)

peaks = find_peaks(x, distance=distance, prominence=prominence)

print(peaks)
print(peaks_groudtrue)

import matplotlib.pyplot as plt
# To demonstrate this function's usage we use a signal `x` supplied with
# SciPy (see `scipy.misc.electrocardiogram`). Let's find all peaks (local
# maxima) in `x` whose amplitude lies above 0.

import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()

# We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching
# `x` in size to reflect a changing condition for different parts of the
# signal.

border = np.sin(np.linspace(0, 3 * np.pi, x.size))
peaks, _ = find_peaks(x, height=(-border, border))
plt.plot(x)
plt.plot(-border, "--", color="gray")
plt.plot(border, ":", color="gray")
plt.plot(peaks, x[peaks], "x")
plt.show()

# Another useful condition for periodic signals can be given with the
# `distance` argument. In this case we can easily select the positions of
# QRS complexes within the electrocardiogram (ECG) by demanding a distance of
# at least 150 samples.
예제 #29
0
파일: ecg.py 프로젝트: xmdszzz/ssi-tutorial
def connect(opts, vars):

    vars['ecg'] = electrocardiogram()
    vars['pos'] = 0