def calculate_hrv_features(rri, f=360): """ Calculate features for detecting sleep apnea The features contain statistical measures, morphology and periodogram of the ECG signal. Parameters ---------- RR_int: array_like Array containing RR intervals f: float, optional Number corresponding to the sampling frequency of the input signal, must be in Hertz Returns ------- X: array_like Features """ result_td = np.reshape(np.asarray(list(time_domain(rri).values())), (1, 6)) result_fd = np.reshape(np.asarray(list(frequency_domain(rri).values())), (1, 7)) result_nl = np.reshape(np.asarray(list(non_linear(rri).values())), (1, 2)) hrv_features = np.concatenate([result_td, result_fd, result_nl], axis=1) return hrv_features
def poincare_plot(self): """ Poincaré plot of the RRi series """ fig, ax = plt.subplots(1, 1) rri_n, rri_n_1 = self.rri[:-1], self.rri[1:] ax.plot(rri_n, rri_n_1, '.k') ax.set( xlabel='$RRi_n$ (ms)', ylabel='$RRi_{n+1}$ (ms)', title='Poincaré Plot' ) plt.show(block=False) # The ellipse drawning is a translation from the Matlab code # available at: https://github.com/jramshur/HRVAS dx = abs(max(rri_n) - min(rri_n)) * 0.05 dy = abs(max(rri_n_1) - min(rri_n_1)) * 0.05 xlim = [min(rri_n) - dx, max(rri_n) + dx] ylim = [min(rri_n_1) - dy, max(rri_n_1) + dy] from hrv.classical import non_linear nl = non_linear(self.rri) a = rri_n / np.cos(np.pi/4.0) ca = np.mean(a) cx, cy, _ = ca * np.cos(np.pi/4.0), ca * np.sin(np.pi/4.0), 0 width = nl['sd2'] # to seconds height = nl['sd1'] # to seconds # plot fx(x) = x sd2_l = ax.plot( [xlim[0], xlim[1]], [ylim[0], ylim[1]], '--', color=[0.5, 0.5, 0.5] ) fx = lambda val: -val + 2 * cx sd1_l = ax.plot([xlim[0], xlim[1]], [fx(xlim[0]), fx(xlim[1])], 'k--') ax = _ellipsedraw( ax, width, height, cx, cy, np.pi/4.0, color='r', linewidth=3 ) ax.legend( (sd1_l[0], sd2_l[0]), ('SD1: %.2fms' % height, 'SD2: %.2fms' % width), ) return fig, ax
def get_hrv(rr_interval): """Get three domain heart rate variability. Get time domain, frequency domain, and non-linear domain heart rate variability. Args: rr_interval: narray, RR-interval. Returns: A dictionary representation of the three domain HRV. Notes: *Authors* - the hrv dev team (https://github.com/rhenanbartels/hrv) *Dependencies* - hrv - numpy *See Also* - hrv: https://github.com/rhenanbartels/hrv """ if np.median(rr_interval) < 1: rr_interval *= 1000 time_domain_analysis = time_domain(rr_interval) frequency_domain_analysis = frequency_domain(rri=rr_interval, fs=4.0, method='welch', interp_method='cubic', detrend='linear') non_linear_domain_analysis = non_linear(rr_interval) hrv_info = { 'time': time_domain_analysis, 'frequency': frequency_domain_analysis, 'non-linear': non_linear_domain_analysis } return hrv_info
from hrv.filters import moving_median import numpy as np # def _moving_function(rri, order, func): # offset = int(order / 2) # filt_rri = np.array(rri.copy(), dtype=np.float64) # for i in range(offset, len(rri) - offset, 1): # filt_rri[i] = func(rri[i-offset:i+offset+1]) # return filt_rri # def moving_median(rri, order=3): # return _moving_function(rri, order, np.median) rri = open_rri('./data/test/extracted/Iris_kangxi_peyin_RRI.txt') filt_rri = moving_median(rri, order=3) results = time_domain(filt_rri) print(results) results = frequency_domain(rri=filt_rri, fs=4.0, method='welch', interp_method='cubic', detrend='linear') print(results) results = non_linear(filt_rri) print(results)
# change it depending on which one you want output specifier = 'td' # this script is GENERAL purpose. you need to change some of these to match the filenames for i in range(1, 55): # change range filename_header = 'nsr' + str(i).zfill(3) # change name possibly filename = filename_header + 'rri.txt' classifier = '' try: rri = open_rri(filename) except: continue if specifier == 'td': results = time_domain(rri) # output is dict elif specifier == 'nl': results = non_linear(rri) else: print("Invalid argument!") output_csv_name = filename_header + 'hrv_' + specifier + '.csv' with open(output_csv_name, 'wb') as f: # Just use 'w' mode in 3.x w = csv.DictWriter(f, results.keys()) w.writeheader() w.writerow(results) print(filename_header + ' rri file has been processed') """ print(results) print(type(results)) """