Esempio n. 1
0
def respiration(data, d_time, frequency=256):

    b, a = signal.butter(8,0.05)
    # get the raw data and filter it
    respiration = signal.filtfilt(b, a, data, padlen=150)
    # plt.plot(respiration)
    # plt.show()

    # we can then get the amplitude and clear signal of the data
    # and also the respiration rate
    out = resp.resp(respiration,sampling_rate=frequency, show=False)
    # plt.plot(out['resp_rate_ts'], out['resp_rate'])
    # plt.ylabel('Respiratory frequency [Hz]')
    # plt.xlabel('Time [s]');
    # plt.show()

    # In this case, shape is modify, since we're breaking into frequency
    resp_rate_ts = out['resp_rate_ts']
    resp_rate = out['resp_rate']
    resp_filtered = out['filtered']

    # What to Return ? ? ? ?
    
    resp_rate_interpolated = int_spline(resp_rate, resp_rate_ts, d_time)
    return lognorm2norm(resp_rate_interpolated)
Esempio n. 2
0
def main(dataset, debug=False):
    ecg = dataset['ECG']

    # Detect onset of QRS complexes
    qrs = detectQRSPeaks(ecg, False)

    # EDR
    dt1 = -1
    dt2 = 1
    edrvals = []
    for sample in qrs:
        x = getx(ecg, sample+dt1, sample+dt2)
        edrvals.append(edr(x))

    # Spline interpolation
    breathing = interpolate.splrep(qrs, edrvals, s=0)
    s = range(0, len(ecg))
    interpolation = interpolate.splev(s, breathing, der=0)
    [_, filtered, zeros, _, _]= resp.resp(signal=interpolation, sampling_rate=250, show=False)

    if debug is True:
        # Plot result
        resp_ref = dataset['Resp']
        import matplotlib.pyplot as plt
        plt.plot(qrs, edrvals, 'g', label="raw edr")
        plt.plot(s, filtered, 'b', label="spline + filter")
        plt.plot(s, resp_ref, 'r', label="reference")
        plt.plot(zeros, resp_ref[zeros], 'm*', label="in - out")
        plt.legend()
        plt.show()

    return group_epochs(filtered, zeros, 250, 30)
Esempio n. 3
0
def getResp_std(task, index, output, samp_rate):
    vals = []
    for i in range(len(task)):
        try:
            vals.append(task[i][index])
        except:
            vals.append(task[i])

    vals = filter(lambda x: x != "", vals)  # remove empty strings

    # extract respiration features using biosppy
    # vals is raw resp data
    out = resp.resp(signal=vals, sampling_rate=samp_rate, show=False)

    # getting instantaneous respiration rate
    out_resp = out[4].tolist()  # using numpy, convert ndarry into a list

    stdev = np.std(out_resp)
    output.write(str(stdev) + ', ')
Esempio n. 4
0
    def resp_intervals(self, data):
        """Calculates respiration intervals and indicates inhale/exhale
        Parameters
        ----------
        data : breathing signal to be processed

        sampling_rate: sampling rate of breathing signal

        Returns
        ----------
        interval_lengths: list of breathing interval lenghts

        interval_breathe_in: list of breathe in True/False flags
        """
        processed_data = resp.resp(signal=data,
                                   sampling_rate=self.srate,
                                   show=False)
        filtered_signal = processed_data[1]
        inst_resp_rate = processed_data[4]
        self.filtered = filtered_signal
        self.resp_rate = inst_resp_rate

        signal_diff = np.diff(filtered_signal)
        signal_signum = signal_diff > 0

        resp_changes = np.append(
            np.where(signal_signum[:-1] != signal_signum[1:])[0],
            [len(signal_signum) - 1])
        self.resp_changes = resp_changes

        resp_intervals = np.append([0], resp_changes)
        interval_lengths = np.diff(resp_intervals)
        interval_breathe_in = [signal_signum[i] for i in resp_changes]
        self.interval_lengths, self.interval_breathe_in = interval_lengths, interval_breathe_in

        last_interval = -1
        if len(resp_changes) > 1:
            last_interval = resp_changes[-1] - resp_changes[-2]
        else:
            last_interval = resp_changes[-1]

        self.last_breath = last_interval
        self.last_is_inhale = signal_signum[resp_changes[-1]]
Esempio n. 5
0
def resp_intervals(data, sampling_rate=200, last_breath=False):
    """Calculates respiration intervals and indicates inhale/exhale
    Parameters
    ----------
    data : breathing signal to be processed

    sampling_rate: sampling rate of breathing signal

    last_breath : flag that indicates whether single/mult breath analysis is requested

    Returns
    ----------
    interval_lengths: list of breathing interval lenghts

    interval_breathe_in: list of breathe in True/False flags
    """
    processed_data = resp.resp(signal=data,
                               sampling_rate=sampling_rate,
                               show=False)
    filtered_signal = processed_data[1]
    inst_resp_rate = processed_data[4]

    signal_diff = np.diff(filtered_signal)
    signal_signum = signal_diff > 0

    resp_changes = np.append(
        np.where(signal_signum[:-1] != signal_signum[1:])[0],
        [len(signal_signum) - 1])

    if not last_breath:

        resp_intervals = np.append([0], resp_changes)
        interval_lengths = np.diff(resp_intervals)
        interval_breathe_in = [signal_signum[i] for i in resp_changes]
        return interval_lengths, interval_breathe_in

    else:
        if len(resp_changes) > 1:
            last_interval = resp_changes[-1] - resp_changes[-2]
        else:
            last_interval = resp_changes[-1]

        return last_interval, signal_signum[resp_changes[-1]]
Esempio n. 6
0
def getResp_std(task,index,output,samp_rate):
    vals = []
    for i in range(len(task)):
        try:
            vals.append(task[i][index])
        except:
            vals.append(task[i])

    vals = filter(lambda x:x !="", vals) # remove empty strings

    # extract respiration features using biosppy
    # vals is raw resp data
    out = resp.resp(signal=vals, sampling_rate=samp_rate, show=False)       

    # getting instantaneous respiration rate
    out_resp = out[4].tolist() # using numpy, convert ndarry into a list

    stdev = np.std(out_resp)
    output.write(str(stdev) + ', ')
Esempio n. 7
0
def getRespMax(task, index, output, samp_rate):
    vals = []
    # making sure we are able to get values whether or not they are in a
    # two-dimensional array
    for i in range(len(task)):
        try:
            vals.append(task[i][index])
        except:
            vals.append(task[i])

    vals = filter(lambda x: x != "", vals)  # remove empty strings

    # extract respiration features using biosppy
    # vals is raw resp data
    out = resp.resp(signal=vals, sampling_rate=samp_rate, show=False)

    # getting instantaneous respiration rate
    out_resp = out[4].tolist()  # using numpy, convert ndarry into a list

    maximum = str(max(out_resp))
    output.write(maximum + ', ')
Esempio n. 8
0
def getRespMax(task,index,output,samp_rate):
    vals = []
    # making sure we are able to get values whether or not they are in a 
        # two-dimensional array
    for i in range(len(task)):
        try:
            vals.append(task[i][index])
        except:
            vals.append(task[i])

    vals = filter(lambda x:x !="", vals) # remove empty strings

    # extract respiration features using biosppy
    # vals is raw resp data
    out = resp.resp(signal=vals, sampling_rate=samp_rate, show=False)       

    # getting instantaneous respiration rate
    out_resp = out[4].tolist() # using numpy, convert ndarry into a list

    maximum = str(max(out_resp))
    output.write(maximum + ', ')  
def add_respiration_rate(df: DataFrame) -> None:
    """ Process chest movement signal to calculate respiration rate. Add the respiration rate to input as
    'respiration_rate' feature.

    Args:
        df(pandas df):                 dataset with chest movement signal labelled as 'r'
    """

    df["respiration_rate"] = np.nan

    all_pilots = df.pilot.unique()
    all_experiments = df.experiment.unique()

    for pilot in all_pilots:
        for experiment in all_experiments:

            where_in_df = df.index[(df.pilot == pilot)
                                   & (df.experiment == experiment)]
            subset = df.loc[where_in_df, ['time', 'r']]

            try:
                subset.sort_values(by='time')

                out = resp.resp(signal=subset['r'],
                                sampling_rate=256,
                                show=False)
                where_in_subset = out['resp_rate_ts']
                resp_rate = out['resp_rate']

                global_ind = where_in_df[where_in_subset]
                for i in range(len(resp_rate)):
                    df.loc[global_ind[i]:global_ind[i + 1],
                           ['respiration_rate']] = resp_rate[i]
            except:
                print('Not all respiration rates were calculated')

    df["respiration_rate"].astype('float32')
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 11 15:32:13 2018

@author: Inki Kim's lab
"""


import os
import pandas as pd
from tqdm import tqdm
from biosppy.signals import ecg,resp

os.chdir('path/to/2_SycronizedData')
outputpath = 'path/to/3_CalcBR/'


for file in tqdm(os.listdir()):
    signal = pd.read_csv(file)
    
    out = resp.resp(signal=signal.iloc[:,3], sampling_rate=32, show=True)
    ts_br = out['resp_rate_ts']/64
    br = out['resp_rate']
    df = pd.DataFrame({'time':ts_br})
    df['Breathe_rate'] = br*60
    df.to_csv(outputpath + file.split('.')[0] + '_BR_2017.csv', index = False)