def pmus_passive(fs, rr):
    """
    Passive profile, i.e, no respiratory effort (no spontaneous breathing)
    :param fs: sample frequency
    :param rr: respiratory rate
    :return: pmus profile
    """
    pmus = np.zeros(1, int(np.floor(60.0 / rr * fs) + 1))

    return pmus
def pmus_trapezoidal(fs, rr, ttrap, inspeak, exppeak):
    """
    Trapezoidal profile
    :param fs: sample frequency
    :param rr: respiratory rate
    :param ttrap: time array defining trapezoidal profile
    :param inspeak: negative peak pressure
    :param exppeak: positive peak pressure
    :return: pmus profile
    """
    pmus = np.zeros(1, int(np.floor(60.0 / rr * fs) + 1))
    return pmus
def pmus_ingmar(fs, rr, pp, tp, tf):
    """
    Sinusoidal profile
    :param fs: sample frequency
    :param rr: respiratory rate
    :param pp: peak pressure
    :param tp: peak time
    :param tf: end of effort
    :return: pmus profile
    """

    ntp = np.floor(tp * fs)
    ntf = np.floor(tf * fs)
    ntN = np.floor(60.0 * fs / rr)

    pmus1 = np.sin(np.pi * np.arange(0, ntp + 1, 1) / fs / 2.0 / tp)
    pmus2 = np.sin(np.pi / 2.0 / (tf - tp) *
                   (np.arange(ntp + 1, ntf + 1, 1) / fs + tf - 2.0 * tp))
    pmus3 = 0 * np.arange(ntf + 1, ntN + 1, 1) / fs
    pmus = pp * np.concatenate((pmus1, pmus2, pmus3))

    return pmus
def pmus_parexp(fs, rr, pp, tp, tf):
    """
    Parabolic-exponential profile
    :param fs: sample frequency
    :param rr: respiratory rate
    :param pp: peak pressure
    :param tp: peak time
    :param tf: end of effort
    :return: pmus profile
    """

    ntp = np.floor(tp * fs)
    ntN = np.floor(60.0 / rr * fs)
    taur = abs(tf - tp) / 4.0

    pmus1 = pp * (60.0 * rr - np.arange(0, ntp + 1, 1) / fs) * (
        np.arange(0, ntp + 1, 1) / fs) / (tp * (60.0 * rr - tp))
    pmus2 = pp * (np.exp(-(np.arange(ntp + 1, ntN + 1, 1) / fs - tp) / taur) -
                  np.exp(-(60.0 * rr - tp) / taur)) / (
                      1.0 - np.exp(-(60.0 * rr - tp) / taur))
    pmus = np.concatenate((pmus1, pmus2))

    return pmus
Example #5
0
def plot_histograms(df):
    """ plots the histograms of the columns of the input dataframe

        Args:
            df(pandas.DataFrame): input data
    """
    cols = df.columns
    ncols = len(cols)
    if ncols % 15 == 0:
        nfigs = int(ncols / 15)
    else:
        nfigs = int(np.floor(ncols / 15) + 1)
        rem = int(ncols % 15)
    t = 0
    for n in range(nfigs):
        if n < nfigs:
            f, axes = plt.subplots(5, 3, figsize=(13, 10))
            f.suptitle("Histograms. Red = diseased, green = healthy",
                       fontsize=16)

            k = 0
            for j in range(3):
                for i in range(5):
                    c = cols[i + k + t - 1]
                    axes[i, j].hist(df[c][df["num"] == 0],
                                    bins=100,
                                    color="green",
                                    alpha=.5)
                    axes[i, j].hist(df[c][df["num"] == 1],
                                    bins=100,
                                    color="red",
                                    alpha=.5)
                    axes[i, j].set_xlabel(c)
                k = k + 5
        else:
            f, axes = plt.subplots(rem, 1, figsize=(6, 10))
            f.suptitle("Histograms. Red = diseased, green = healthy",
                       fontsize=16)
            for i in range(rem):
                c = cols[-rem:][i]
                axes[i].hist(df[c], bins=100)
                axes[i].set_xlabel(c)

        t = t + 10
        plt.subplots_adjust(hspace=.5, right=.95, left=.05)

    # plt.tight_layout()
    plt.show()
def pmus_linear(fs, rr, pp, tp, tf):
    """
    Linear profile
    :param fs: sample frequency
    :param rr: respiratory rate
    :param pp: peak pressure
    :param tp: peak time
    :param tf: end of effort
    :return: pmus profile
    """
    nsamples = np.floor(60.0 / rr * fs)
    time = np.arange(0, nsamples + 1, 1) / fs
    pmus = 0 * time

    for i in range(len(time)):
        if time[i] <= tp:
            pmus[i] = time[i] / tp
        elif time[i] <= tf:
            pmus[i] = (tf - time[i]) / (tf - tp)
        else:
            pmus[i] = 0.0
        pmus[i] = pp * pmus[i]

    return pmus
def solve_model(header_params,params,header_features,features,debugmsg):
    #Extracts each parameter
    fs = params[header_params.index('Fs')]
    rvent = params[header_params.index('Rvent')]
    c = params[header_params.index('C')]
    rins = params[header_params.index('Rins')]
    rexp = rins  # params[4]
    peep = params[header_params.index('PEEP')]
    sp = params[header_params.index('SP')]
    trigger_type = features[header_features.index('Triggertype')]
    trigger_arg = params[header_params.index('Triggerarg')]
    rise_type = features[header_features.index('Risetype')]
    rise_time = params[header_params.index('Risetime')]
    cycle_off = params[header_params.index('Cycleoff')]
    rr = params[header_params.index('RR')]
    pmus_type = features[header_features.index('Pmustype')]
    pp = params[header_params.index('Pp')]
    tp = params[header_params.index('Tp')]
    tf = params[header_params.index('Tf')]
    noise = params[header_params.index('Noise')]
    e2 = params[header_params.index('E2')]
    model = features[header_features.index('Model')]

    expected_len = int(np.floor(180.0 / np.min(RR) * np.max(Fs)) + 1)
    
    #Assings pmus profile
    pmus = pmus_profile(fs, rr, pmus_type, pp, tp, tf)
    pmus = pmus + peep #adjusts PEEP
    pmus = np.concatenate((np.array([0]), pmus)) #sets the first value to zero

    
    #Unit conversion from cmH2O.s/L to cmH2O.s/mL
    rins = rins / 1000.0
    rexp = rexp / 1000.0
    rvent = rvent / 1000.0


    #Generates time, flow, volume, insex and paw waveforms
    time = np.arange(0, np.floor(60.0 / rr * fs) + 1, 1) / fs
    time = np.concatenate((np.array([0]), time))
    flow = np.zeros(len(time))
    volume = np.zeros(len(time))
    insex = np.zeros(len(time))
    paw = np.zeros(len(time)) + peep #adjusts PEEP
    len_time = len(time)

    #Peak flow detection
    peak_flow = flow[0]
    detect_peak_flow = False

    #Support detection
    detect_support = False
    time_support = -1

    #Expiration detection
    detect_exp = False
    time_exp = -1

    if trigger_type == 'flow':
        # units conversion from L/min to mL/s
        trigger_arg = trigger_arg / 60.0 * 1000.0

    for i in range(1, len(time)):
        # period until the respiratory effort beginning
        if (((trigger_type == 'flow' and flow[i] < trigger_arg) or
             (trigger_type == 'pressure' and paw[i] > trigger_arg + peep) or
             (trigger_type == 'delay' and time[i] < trigger_arg)) and
                (not detect_support) and (not detect_exp)):
            paw[i] = peep
            y0 = volume[i - 1]
            tspan = [time[i - 1], time[i]]
            args = (paw[i], pmus[i], model, c, e2, rins)
            sol = odeint(flow_model, y0, tspan, args=args)
            volume[i] = sol[-1]
            flow[i] = flow_model(volume[i], time[i], paw[i], pmus[i], model, c, e2, rins)
            if debugmsg:
                print('volume[i]= {:.2f}, flow[i]= {:.2f}, paw[i]= {:.2f}, waiting'.format(volume[i], flow[i], paw[i]))

            if (((trigger_type == 'flow' and flow[i] >= trigger_arg) or
                 (trigger_type == 'pressure' and paw[i] <= trigger_arg + peep) or
                 (trigger_type == 'delay' and time[i] >= trigger_arg))):
                detect_support = True
                time_support = time[i+1]
                continue

        # detection of inspiratory effort
        # ventilator starts to support the patient
        elif (detect_support and (not detect_exp)):
            if rise_type == 'step':
                paw[i] = sp + peep
            elif rise_type == 'exp':
                rise_type = rise_type if np.random.random() > 0.01 else 'linear'
                if paw[i] < sp + peep:
                    paw[i] = (1.0 - np.exp(-(time[i] - time_support) / rise_time )) * sp + peep
                if paw[i] >= sp + peep:
                    paw[i] = sp + peep
            elif rise_type == 'linear':
                rise_type = rise_type if np.random.random() > 0.01 else 'exp'
                if paw[i] < sp + peep:
                    paw[i] = (time[i] - time_support) / rise_time * sp + peep
                if paw[i] >= sp + peep:
                    paw[i] = sp + peep

            y0 = volume[i - 1]
            tspan = [time[i - 1], time[i]]
            args = (paw[i], pmus[i], model, c, e2, rins)
            sol = odeint(flow_model, y0, tspan, args=args)
            volume[i] = sol[-1]
            flow[i] = flow_model(volume[i], time[i], paw[i], pmus[i], model, c, e2, rins)
            if debugmsg:
                print('volume[i]= {:.2f}, flow[i]= {:.2f}, paw[i]= {:.2f}, supporting'.format(volume[i], flow[i], paw[i]))

            if flow[i] >= flow[i - 1]:
                peak_flow = flow[i]
                detect_peak_flow = False
            elif flow[i] < flow[i - 1]:
                detect_peak_flow = True

            if (flow[i] <= cycle_off * peak_flow) and detect_peak_flow and i<len_time:
                detect_exp = True
                time_exp = i+1    
                try:
                    paw[i + 1] = paw[i]
                except IndexError:
                    pass

        elif detect_exp:
            if rise_type == 'step':
                paw[i] = peep
            elif rise_type == 'exp':
                if paw[i - 1] > peep:
                    paw[i] = sp * (np.exp(-(time[i] - time[time_exp-1]) / rise_time )) + peep
                if paw[i - 1] <= peep:
                    paw[i] = peep
            elif rise_type == 'linear':
                rise_type = rise_type if np.random.random() > 0.01 else 'exp'
                if paw[i - 1] > peep:
                    paw[i] = sp * (1 - (time[i] - time[time_exp-1]) / rise_time) + peep
                if paw[i - 1] <= peep:
                    paw[i] = peep

            y0 = volume[i - 1]
            tspan = [time[i - 1], time[i]]
            args = (paw[i], pmus[i], model, c, e2, rexp + rvent)
            sol = odeint(flow_model, y0, tspan, args=args)
            volume[i] = sol[-1]
            flow[i] = flow_model(volume[i], time[i], paw[i], pmus[i], model, c, e2, rexp + rvent)
            if debugmsg:
                print('volume[i]= {:.2f}, flow[i]= {:.2f}, paw[i]= {:.2f}, exhaling'.format(volume[i], flow[i], paw[i]))

    #Generates InsEx trace
    if time_exp > -1:
        insex = np.concatenate((np.ones(time_exp), np.zeros(len(time) - time_exp)))

    #Drops the first element
    flow = flow[1:] / 1000.0 * 60.0  # converts back to L/min
    volume = volume[1:]
    paw = paw[1:]
    pmus = pmus[1:] - peep #reajust peep again
    insex = insex[1:]

    flow,volume,pmus,insex,paw = generate_cycle(expected_len,flow,volume,pmus,insex,paw,peep=peep)

    # paw = generate_cycle(expected_len,paw,peep=peep)[0]
    
    flow,volume,paw,pmus,insex = generate_noise(noise,flow,volume,paw,pmus,insex)

    # plt.plot(flow)
    # plt.plot(volume)
    # plt.plot(paw)
    # plt.plot(pmus)
    # plt.show()

    return flow, volume, paw, pmus, insex, rins,rexp, c
Example #8
0
if not os.path.exists(filename):
    sampling_generator(size, filename)

header_params, param = load_csv(filename)

num_test_cases = len(param)
header_features, feature = get_random_features(features, num_test_cases)

print(f'Number of respiratory cycles to be simulated: {num_test_cases}')

fs = max(Fs)
rr = min(RR)

print(f'Creating waveforms for fs={fs} / rr={rr}')

num_points = int(np.floor(180.0 / rr * fs) + 1)

print("Test cases:", num_test_cases)
print("Number points: ", num_points)

# Target waveforms
flow = np.zeros((num_points, num_test_cases))
volume = np.zeros((num_points, num_test_cases))
paw = np.zeros((num_points, num_test_cases))
pmus = np.zeros((num_points, num_test_cases))
ins = np.zeros((num_points, num_test_cases))
resistances_ins = np.zeros((1, num_test_cases))
resistances_exp = np.zeros((1, num_test_cases))
capacitances = np.zeros((1, num_test_cases))

t = time.time()
Example #9
0
err_pmus = []

# R_hat = np.average([denormalize_data(output_pred_test[i, 0], minimum=min_resistances, maximum=max_resistances) for i in range(num_examples)])
# C_hat = np.average([denormalize_data(output_pred_test[i, 1], minimum= min_capacitances, maximum= max_capacitances) for i in range(num_examples)])

R_hat = denormalize_data(output_pred_test[0, 0],
                         minimum=min_resistances,
                         maximum=max_resistances)
C_hat = denormalize_data(output_pred_test[0, 1],
                         minimum=min_capacitances,
                         maximum=max_capacitances)
alpha = 0.2

rr = min(RR)
fs = max(Fs)
time = np.arange(0, np.floor(180.0 / rr * fs) + 1, 1) / fs

err_pmus_hat = []
err_nmsre = []
for i in range(num_examples - 1):
    # R_hat = alpha*denormalize_data(output_pred_test[i, 0], minimum=min_resistances, maximum=max_resistances) + (1-alpha)*R_hat
    # C_hat = alpha*denormalize_data(output_pred_test[i, 1], minimum= min_capacitances, maximum= max_capacitances) + (1-alpha)*C_hat

    R_hat = denormalize_data(output_pred_test[i, 0],
                             minimum=min_resistances,
                             maximum=max_resistances)
    C_hat = denormalize_data(output_pred_test[i, 1],
                             minimum=min_capacitances,
                             maximum=max_capacitances)

    # R = denormalize_data(output_data[i, 0], min_resistances, max_resistances)