コード例 #1
0
def iPulInt(filter, filename, start, step, threshold, toPlot=False, kbits=13):
    """Función para determinar el IPI de un segmento de tiempo."""
    record = wfdb.rdrecord(filename)
    fs = record.__dict__["fs"]
    begin = start
    end = int(step * fs)
    # encontrar pico dado un umbral
    record.__dict__['p_signal'] = record.__dict__['p_signal'][begin:begin +
                                                              end]
    ecg_signal = np.array([lista[0] for lista in record.__dict__['p_signal']])
    # Vector lineal de función senoidal de 0.5 pi a 1.5 pi con n muestras(filtro)
    t = np.linspace(0.5 * np.pi, 1.5 * np.pi, filter)
    # Usar la función senoidal para determinar el tiempo entre pulsos
    qrs_filter = np.sin(t)
    # Computa cross correlation entre el ECG y el filtro propuesto
    similarity = np.correlate(ecg_signal, qrs_filter, mode="same")
    for i in range(end):
        record.__dict__['p_signal'][i][1] = similarity[i]
    peaks = np.array(np.nonzero(similarity > threshold))
    # IPI es el promedio de las diferencias
    peaks_DxDt = np.dot(np.diff(peaks), 1 / fs)
    IPI = np.average(peaks_DxDt[peaks_DxDt > 1 / fs])
    # Gráficas
    if toPlot:
        wfdb.plot_wfdb(record=record,
                       title='Record ' + filename[-3:] +
                       ' from MIT-BIH Arrhythmia DB')
        print("Datos de señal:", record.__dict__)
    return decToBin(IPI, kbits)
コード例 #2
0
def OpenUCDDB_1():
    db_path = 'D:\\SkyDrive\\Studium\\Maastricht\\Project1\\Period2ResampleAnnotations\\datasets\\db3_ucddb\\ResamplesRecord100Hz\\ucddb002_100Hz';

    record = wfdb.rdrecord(db_path)

    signals, fields = wfdb.rdsamp(db_path)
    print('Fields: ', fields)

    wfdb.plot_wfdb(record=record, plot_sym=True, title=db_path)
    return
コード例 #3
0
def plot_record(path, sampto=None):
    record = wfdb.rdrecord(path, sampto=sampto)
    annotation = wfdb.rdann(path, 'atr', sampto=sampto)
    wfdb.plot_wfdb(record=record,
                   annotation=annotation,
                   plot_sym=True,
                   time_units='seconds',
                   title='MIT-BIH Record 100',
                   figsize=(10, 4),
                   ecg_grids='all')
コード例 #4
0
def OpenApneaECG():
    db_path = 'D:\\StudiumAddidtional\\ACML\\datasets\\db1_apnea-ecg\\a01';
    #db_path = 'datasets\\db3_ucddb\\ucddb002';

    record = wfdb.rdrecord(db_path)

    signals, fields = wfdb.rdsamp(db_path)
    print('Fields: ', fields)

    ann = wfdb.rdann(db_path, 'apn')
    print("ann.sample len = ", len(ann.sample))
    print(ann.sample)

    print("ann.symbol len = ", len(ann.symbol))
    print(ann.symbol)

    wfdb.plot_wfdb(record=record, annotation=ann, plot_sym=True, title='Record a1 from Physionet Apnea')
    return
コード例 #5
0
def OpenUCDDB():
    record_path = 'D:\\SkyDrive\\Studium\\Maastricht\\Project1\\Period2ResampleAnnotations\\datasets\\db3_ucddb\\Record100Hz\\ucddb002_lifecard_100Hz'
    annotation_path = 'D:\\SkyDrive\\Studium\\Maastricht\\Project1\\Period2ResampleAnnotations\\datasets\\db3_ucddb\\ResampledAnn100HzRecord\\ucddb002_lifecard_100Hz_Shorter_IgnoreOverlap'
    record = wfdb.rdrecord(record_path)

    signals, fields = wfdb.rdsamp(record_path)
    print('Fields: ', fields)

    print('counter_freq', record.counter_freq)
    print('samples_per_frame', record.samps_per_frame)

    ann = wfdb.rdann(annotation_path, 'apn')
    print("ann.sample len = ", len(ann.sample))
    print(ann.sample)

    print("ann.symbol len = ", len(ann.symbol))
    print(ann.symbol)

    wfdb.plot_wfdb(record=record, annotation=ann, plot_sym=True, title=record_path)
    return
コード例 #6
0
ファイル: ecg_read_v1.0.py プロジェクト: cay15/hrv
import keras
from keras import optimizers, losses, activations, models
from keras.layers import Dense, Input, Dropout, Convolution1D, MaxPool1D, GlobalMaxPool1D, GlobalAveragePooling1D, concatenate, MaxPool2D
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D


## GRAPH PLOTTING

# Display 1 record and its dictionary (from:100 - to:2100)
# for both variables record and ann, edit the file path to fit yours and follow it with the .dat file you want to plot e.g. the file I chose here is called "16265"
record = wfdb.rdrecord('/Users/choiwan/Desktop/MMGP/mit-bih-normal-sinus-rhythm-database-1.0.0/16265', sampfrom=100, sampto=7900)
ann = wfdb.rdann('/Users/choiwan/Desktop/MMGP/mit-bih-normal-sinus-rhythm-database-1.0.0/16265', 'dat', sampfrom=100, sampto=7900)
wfdb.plot_wfdb(record, ann)
display(record.__dict__)


## NEXT STEPS
# find R peaks and find RR intervals from that. links 3 and 4 may help


## DEBUGGING
#checks files are present
#import os
#for dirname, _, filenames in os.walk('/Users/choiwan/Desktop/MMGP/mit-bih-normal-sinus-rhythm-database-1.0.0'):
#    for filename in filenames:
#        print(os.path.join(dirname, filename))

# directory for dataset
コード例 #7
0
import wfdb

record = wfdb.rdrecord(
    '/Users/ashwini/ECG-HeartDisease/data/patient001/s0010_re')
wfdb.plot_wfdb(record=record,
               title='Record a103l from Physionet Challenge 2015')
display(record.__dict__)
コード例 #8
0
import librosa
import shutil
import posixpath
from scipy.fft import fft, ifft

if "record" is not locals():
    os.chdir("/Users/dhruvmodi/Desktop/ECG-Filtering/mit-database/")

import wfdb

# Demo 1 - Read a WFDB record using the 'rdrecord' function into a wfdb.Record object.
# Plot the signals, and show the data.
#this reads and plots a noisy record from the MIT stress test database, along with all the information about the record/patient
#NOTE: do not use this function if you want to further manipulate the ECG data. instead, use wfdb.rdsamp
record = wfdb.rdrecord('ma')
wfdb.plot_wfdb(record=record, title='MIT record 1')
display(record.__dict__)

#%%

# Demo 2 - Read certain channels and sections of the WFDB record using the simplified 'rdsamp' function
# which returns a numpy array and a dictionary. Show the data.
#this section reads a portion of the same record as above (from sample 100 to sample 15000)
#returns a "signals" (a numpy array) and "fields"(patient and signal info)
#note: this ecg has data from 2 channels (2 different leads), if you want data from a specific lead, you have to
#select the correct channel that corresponds to the leads(channels start at 0, not 1)

#NOTE: use this function whenever you want to work with the ECG data (not rdrecord)

signals, fields = wfdb.rdsamp('118e24',
                              channels=[0],
コード例 #9
0
ファイル: data_stuff.py プロジェクト: Amri95/ecg-final
def plot_annotation(record, ann):
    wfdb.plot_wfdb(record=record,
                   annotation=ann,
                   title='Record 100 from MIT-BIH Arrhythmia Database',
                   time_units='samples')
コード例 #10
0
#wget --recursive --no-parent https://physionet.org/physiobank/database/ctu-uhb-ctgdb/

import wfdb
import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    '--files',
    help='path to physionet files, e.g. physiobank/database/ctu-uhb-ctgdb/')
parser.add_argument('--title', help='the numeric data file prefix, e.g. 1001')
args = parser.parse_args()

rec = args.files + args.title
record = wfdb.rdrecord(rec)
wfdb.plot_wfdb(record=record, title=args.title)
signals, fields = wfdb.rdsamp(rec)

#annotation = wfdb.rdann(rec, 'atr')
# signals are heartbeat and contraction
#channels label ['F3-M2', 'F4-M1', 'C3-M2', 'C4-M1', 'O1-M2', 'O2-M1', 'E1-M2', 'Chin1-Chin2', 'ABD', 'CHEST', 'AIRFLOW', 'SaO2', 'ECG']
#Signal      Name	Units	        Signal Description
#SaO2	    %	                    Oxygen saturation
#ABD	        µV	                    Electromyography, a measurement of abdominal movement
#CHEST	    µV	                    Electromyography, measure of chest movement
#Chin1-Chin2	µV	                    Electromyography, a measure of chin movement
#AIRFLOW	    µV	                    A measure of respiratory airflow
#ECG	        mV	                    Electrocardiogram, a measure of cardiac activity
#E1-M2	    µV	                    Electrooculography, a measure of left eye activity
#O2-M1	    µV	                    Electroencephalography, a measure of posterior activity
#C4-M1	    µV	                    Electroencephalography, a measure of central activity
#C3-M2	    µV	                    Electroencephalography, a measure of central activity
#F3-M2	    µV	                    Electroencephalography, a measure of frontal activity
#F4-M1	    µV	                    Electroencephalography, a measure of frontal activity
#O1-M2	    µV	                    Electroencephalography, a measure of posterior activity

record = wfdb.rdrecord(filename,
                       sampfrom=sampFrom,
                       sampto=sampTo,
                       channels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

#plot signals
wfdb.plot_wfdb(record,
               plot_sym=True,
               time_units='seconds',
               title='Sample ' + str(filename) + ' time ( ' + str(sampFrom) +
               ',' + str(sampTo) + ')',
               figsize=(10, 9))

#plot entire record file
#wfdb.plot_all_records(directory='M:/training/tr03-0005/')
コード例 #12
0
def OpenSHHSPSDB():
    path = 'shhpsgdb\\0000';
    record = wfdb.rdrecord(path);
    wfdb.plot_wfdb(record=record, plot_sym=True, title='shhpsdb Record ' + path)
    print(record);
    return
コード例 #13
0
import wfdb
import matplotlib.pyplot as plt

'''Part1 read signal and plot signal'''

signal, fields = wfdb.rdsamp('100',channels=[0, 1], sampfrom=0, sampto=1500, pb_dir='mitdb/')

print('signal:',signal)
print('fields:',fields)
plt.plot(signal)
plt.ylabel(fields['units'][0])
plt.legend([fields['sig_name'][0],fields['sig_name'][1]])
plt.show()


'''Part2 annotation and record'''

record = wfdb.rdrecord('data/mitdb/100', sampto=3600)
annotation = wfdb.rdann('data/mitdb/100', 'atr', sampto=3600)
wfdb.plot_wfdb(record=record, annotation=annotation,
               title='Record 100 from MIT-BIH Arrhythmia Database', time_units='seconds')



print('annotation:', annotation.__dict__)
print('anno positions:', annotation.sample)
print('anno labels:', annotation.symbol)
print('record:', record.__dict__)
print('signal:', record.p_signal)

wfdb.show_ann_labels()
コード例 #14
0
ファイル: LoadData.py プロジェクト: 17ntan/ECGProject
# It's actually super easy to load the data!! All we need is wfdb
# This file is really just a "how to use wfdb"

# list of files that we got from the data base
# I typed all of them out and then I realized it's provided
# in txt file called RECORDS :(
files = [
    "100", "101", "102", "103", "104", "105", "106", "107", "108", "109",
    "111", "112", "113", "114", "115", "116", "117", "118", "119", "121",
    "122", "123", "124", "200", "201", "202", "203", "205", "207", "208",
    "209", "210", "212", "213", "214", "215", "217", "219", "220", "221",
    "222", "223", "228", "230", "231", "232", "233", "234"
]

# load the data
# Input: file name. No need for .dat or .hea or whatever.
# Output: wfdb record
record = wfdb.rdrecord('Data/100')

# get numpy array out of wfdb record
# Input: wfdb record
# Output: numpy array of signal Mx2 (2 ECG channels I think?)
arr = record.p_signal

# plot both signals
# Input: wfdb record, string for title
# Output: plot
wfdb.plot_wfdb(record=record,
               title='Record 100 from MIT-BIH Arrhythmia Database')
コード例 #15
0
import wfdb

dbName = 'wrist'
recName = 's1_walk'

# Read part of a record from Physiobank
sig, fields = wfdb.rdsamp(dbName + '/' + recName, sampfrom=1000, channels=[0])
record = wfdb.rdrecord(dbName + '/' + recName)
print(record.__dict__)
# Call the gateway wrsamp function, manually inserting fields as function input parameters
wfdb.wrsamp('ecg-record',
            fs=256,
            units=['mV'],
            sig_name=['chest_ecg'],
            p_signal=sig,
            fmt=['16'])

# The new file can be read
record = wfdb.rdrecord('ecg-record')

wfdb.plot_wfdb(record)
コード例 #16
0
import os
from pathlib import Path
import matplotlib.pyplot as plt
import wfdb

CONSOLE_WIDTH = os.get_terminal_size()[0]
OUTPUT_DELIMETER = "".ljust(CONSOLE_WIDTH, "-")

DATA_PATH = Path("wfdb_data")
DAT_FILE_PATH = DATA_PATH / "dats" / "3001924p"
PHYS_FILE_PATH = DATA_PATH / "physionet" / "a103l"

if __name__ == "__main__":
    phys_record = wfdb.rdrecord(PHYS_FILE_PATH)
    print(phys_record.p_signal)
    print(OUTPUT_DELIMETER)
    print(phys_record.__dict__)
    print(OUTPUT_DELIMETER)

    signals, fields = wfdb.rdsamp(PHYS_FILE_PATH)
    print(signals)
    print(OUTPUT_DELIMETER)
    print(fields)

    wfdb.plot_wfdb(record=phys_record,
                   title='Local record a103l from Physionet Challenge 2015')

    remote_record = wfdb.rdrecord('a103l', pb_dir='challenge/2015/training/')
    wfdb.plot_wfdb(record=remote_record,
                   title='Remote record a103l from Physionet Challenge 2015')
コード例 #17
0
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
train_WFDB_file1 = drive.CreateFile({'id': '1xcBve5Pl3pCyemm9hA2YmnPyaTQaCyU-'});
train_WFDB_file2 = drive.CreateFile({'id': '1yqwtfMwq7EB6FMDmd7lYHZKpsIu2ngOz'});

#This block takes about 10 minutes to load the half of the training data.
train_WFDB_file1.GetContentFile('training_wfdb_Record1.rec');
train_WFDB_Rec = open('training_wfdb_Record1.rec', 'rb') 
train_WFDB_Rec = pickle.load(train_WFDB_Rec)

len(train_WFDB_Rec)

wfdb.plot_wfdb( record = train_WFDB_Rec[0], title='Record from Physionet Challenge 2020', figsize = (10, 10)) 
#wfdb documentation: https://wfdb.readthedocs.io/en/latest/index.html

display(train_WFDB_Rec[0].__dict__)

"""**From observation , only checksum and p-signal data is varying in diff recordings . So , I created two training set X for both the datas and y set.**

```
Label = ['AF','I-AVB','LBBB','Normal','PAC','PVC','RBBB','STD','STE']
The output will produce index corresponding to above list`
```
"""

import random
random.shuffle(train_WFDB_Rec) 
コード例 #18
0
import matplotlib.pyplot as plt
import numpy as np

import wfdb


def plot_wfdb(signal, annotation, samp_to):
    part = signal.p_signal[0:samp_to, 0]
    plt.plot(part)

    indices = np.where(annotation.sample < samp_to)
    sample = annotation.sample[indices]

    length = len(sample)
    values = np.ones(length)

    plt.plot(sample, values, 'o')
    plt.show()


if __name__ == '__main__':

    signal = wfdb.rdrecord('../data/mit-bih-arrhythmia-database-1.0.0/100', sampto=15000)

    annotation = wfdb.rdann('../data/mit-bih-arrhythmia-database-1.0.0/100', 'atr', sampto=15000)
    wfdb.plot_wfdb(record=signal, annotation=annotation)

    samp_to = 2000

    plot_wfdb(signal, annotation, samp_to)