Example #1
0
def plot_roc(y_binary, y_binary_scores, file_name, n_classes):
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 8)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)
    fpr = dict()
    tpr = dict()
    roc_auc = dict()
    for i in range(n_classes):
        fpr[i], tpr[i], _ = roc_curve(y_binary[:, i], y_binary_scores[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])

    # Compute micro-average ROC curve and ROC area
    fpr["micro"], tpr["micro"], _ = roc_curve(y_binary.ravel(),
                                              y_binary_scores.ravel())
    roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
    lw = 2
    plt.plot(fpr["micro"],
             tpr["micro"],
             color='darkorange',
             lw=lw,
             label='ROC curve (area = %0.2f)' % roc_auc["micro"])
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver Operating Characteristic Curve')
    plt.legend(loc="lower right")
    pu.save_fig(fig, 'figures/roc_' + file_name + '.pdf', 'pdf')
Example #2
0
def main(args):

    # Collect data from results
    df = pd.read_pickle(path='results/fixed_parameters_std-2/8.pkl')

    # Set time range, 1440 = 1 day
    N = 1440
    x = np.arange(N)

    # Prep figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))

    ############################################################################
    # Collect glucose data
    gut_compartment = df['gt'].values[:N]
    plasma_compartment = df['mt'].values[:N]
    carb_est = df['carb_ests_'].values[:N]
    # carb_est[carb_est==0] = np.nan

    # Plot Glucose compartments...
    ax = fig.add_subplot(111)
    ax.plot(x, gut_compartment, c='b', lw=pu.plot_lw(), label='Gut glucose')
    ax.plot(x,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Plasma glucose')
    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$mg/L$')
    ax.set_axisbelow(True)

    # Add second axis
    ax2 = ax.twinx()
    color = 'tab:orange'
    ax2.set_ylabel('$\hat{m}$', color=color)
    ax2.plot(
        x,
        carb_est,  #lw=pu.plot_lw(),
        label='Carbs est.',
        color=color,
        alpha=.5)  #, marker='o', markerfacecolor='None',
    #markersize=5, linewidth=0, alpha=.2)
    ax2.tick_params(axis='y', labelcolor=color)

    # Add legends
    ax.legend(loc='upper left', prop={'size': 5})
    ax2.legend(loc='upper right', prop={'size': 5})

    # Finilize plot
    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #3
0
def plot_auc_binary(y_binary, y_binary_scores, file_name, n_classes):
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 8)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)

    precision, recall, _ = precision_recall_curve(y_binary, y_binary_scores)

    plt.step(recall, precision, color='b', alpha=0.2, where='post')
    plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')

    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    average_precision = average_precision_score(y_binary, y_binary_scores)
    plt.title('2-class Precision-Recall curve: AUC={0:0.2f}'.format(
        average_precision))
    pu.save_fig(fig, 'figures/auc_' + file_name + '.pdf', 'pdf')
def main(args):
    data = np.random.randn(args.n_points, 2)

    pu.figure_setup()

    fig_size = pu.get_fig_size(10, 10)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)

    ax.scatter(data[:, 0], data[:, 1], alpha=0.1, rasterized=True)

    ax.set_xlabel('$x$')
    ax.set_ylabel('$y$')

    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
def main(args):
    data = np.random.randn(args.n_points, 2)

    pu.figure_setup()

    fig_size = pu.get_fig_size(10, 10)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)

    ax.scatter(data[:, 0], data[:, 1], alpha=0.1, rasterized=True)

    ax.set_xlabel('$x$')
    ax.set_ylabel('$y$')

    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #6
0
def plot_auc(y_binary, y_binary_scores, file_name, n_classes):
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 8)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)
    precision = dict()
    recall = dict()
    average_precision = dict()

    for i in range(n_classes):
        precision[i], recall[i], _ = precision_recall_curve(
            y_binary[:, i], y_binary_scores[:, i])
        average_precision[i] = average_precision_score(y_binary[:, i],
                                                       y_binary_scores[:, i])

    precision["micro"], recall["micro"], _ = precision_recall_curve(
        y_binary.ravel(), y_binary_scores.ravel())
    average_precision["micro"] = average_precision_score(y_binary,
                                                         y_binary_scores,
                                                         average="micro")
    print('Average precision score, micro-averaged over all classes: {0:0.2f}'.
          format(average_precision["micro"]))
    plt.step(recall['micro'],
             precision['micro'],
             color='b',
             alpha=0.2,
             where='post')
    plt.fill_between(recall["micro"],
                     precision["micro"],
                     step='post',
                     alpha=0.2,
                     color='b')

    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title(
        'Average precision score, micro-averaged over all classes: AUC={0:0.2f}'
        .format(average_precision["micro"]))
    pu.save_fig(fig, 'figures/auc_' + file_name + '.pdf', 'pdf')
def main(args):
    x = np.linspace(-6, 6, 200)
    y = 1/(1 + np.exp(-x))

    pu.figure_setup()

    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)

    ax.plot(x, y, c='b', lw=pu.plot_lw())

    ax.set_xlabel('$x$')
    ax.set_ylabel('$\\sigma(x)$')

    ax.set_axisbelow(True)

    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #8
0
def main(args):
    x = np.linspace(-6, 6, 200)
    y = 1 / (1 + np.exp(-x))

    pu.figure_setup()

    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))
    ax = fig.add_subplot(111)

    ax.plot(x, y, c='b', lw=pu.plot_lw())

    ax.set_xlabel('$x$')
    ax.set_ylabel('$\\sigma(x)$')

    ax.set_axisbelow(True)

    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #9
0
def main(args):

    # Collect data from results
    df = pd.read_pickle(path='results/fixed_parameters_std-2/8.pkl')

    # Set time range, 1440 = 1 day
    N = 1440
    x = np.arange(N)

    # Prep figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))

    ############################################################################
    # Collect insulin data
    tissue_compartment = df['s1'].values[:N]
    plasma_compartment = df['s2'].values[:N]
    bolus_data = df['bolus_inputs_'].values[:N]

    # Keep only non-zero bolus data - Set zeros to nan
    bolus_data[bolus_data == 0] = np.nan

    # Plot Insulin Compartment Data
    ax = fig.add_subplot(111)
    ax.plot(x,
            tissue_compartment,
            c='b',
            lw=pu.plot_lw(),
            label='Subcutaneous tissue')
    ax.plot(x,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Blood plasma')
    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$Insulin, \, mg/L$')
    ax.set_axisbelow(True)

    # Add Bolus Data on second y-axis
    ax2 = ax.twinx()
    color = 'tab:green'
    ax2.set_ylabel('Units', color=color)
    ax2.plot(
        x,
        bolus_data,  #lw=pu.plot_lw(),
        label='Bolus',
        color=color,
        marker='D',
        markerfacecolor='None',
        markersize=5,
        linewidth=0)
    ax2.tick_params(axis='y', labelcolor=color)

    # Show legend
    ax.legend(loc='upper left', prop={'size': 5})
    ax2.legend(loc='upper right', prop={'size': 5})

    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #10
0
bins.append(0.9999)
bins.append(0.99991)
bins.append(0.99992)
bins.append(0.99993)
bins.append(0.99994)
bins.append(0.99995)
bins.append(0.99996)
bins.append(0.99997)
bins.append(0.99998)
bins.append(0.99999)
bins.append(1.0)


pu.figure_setup()
fig_size = pu.get_fig_size(12, 10)
fig = plt.figure(figsize=fig_size)
ax = fig.add_subplot(111)

print(bins)
cnt = len(file_names) - 1
for file_name in reversed(file_names):
	#print (file_name)
	evaluation1, lables1, lable_dict1 = read_prediction(file_name, lables1)
	#print(acc(evaluation1, lables1, lable_dict1))

	p = []
	r = []
	FPR_0  = 0
	FPR1_0  = 0
	roc = 1
def main(args):

    # Collect data from results
    df = pd.read_pickle(path='./../results/2019-06-15_17:48/4.pkl')

    # Set time range, 1440 = 1 day
    N = 3000
    x = np.arange(N)

    # Prep figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 50)
    fig = plt.figure(figsize=(fig_size))

    ############################################################################
    # Collect CGM and meal data

    cgm_data = df['cgm_inputs_'].values[:N]
    cgm_model = df['Gt'].values[:N]
    meals = df['y_meals'].values[:N]

    # Make all 0 target meal NaNs
    meals[meals == 0] = np.nan

    # Plot CGM and Meal data
    ax = fig.add_subplot(411)
    ax.axhspan(70, 180, alpha=0.1, color='black')
    ax.set_ylim(0, 350)
    ax.plot(x,
            cgm_data,
            marker='o',
            c='g',
            linewidth=0,
            markersize=1,
            label='CGM')
    ax.plot(x,
            cgm_model,
            c='black',
            linewidth=1,
            linestyle='dashed',
            label='Modeled CGM')
    ax.plot(x,
            meals * 20,
            marker='*',
            c='purple',
            linewidth=0,
            markersize=4,
            label='Meal')

    # ax.set_xlabel('$t (minutes)$')
    ax.legend(loc='upper left', prop={'size': 6})
    ax.set_ylabel('$mg/dl$')

    meal_preds = df['meal_preds_'].values[:N]
    meal_preds[meal_preds == 0] = np.nan

    for it, m in enumerate(meal_preds):
        if m == 1:
            ax.axvline(it, c='magenta', alpha=.1)

    # Add CGM prediction
    # horizon = 45
    # start_time = 488
    # x_pred = np.arange(start_time,start_time+horizon+1)
    # cgm_pred = cgm_preds[start_time]-46
    # ax.plot(x_pred, cgm_pred, c='black', linewidth=1, linestyle='dashed')

    ############################################################################
    # Collect insulin data

    tissue_compartment = df['s1'].values[:N]
    plasma_compartment = df['s2'].values[:N]
    bolus_data = df['bolus_inputs_'].values[:N]

    # Keep only non-zero bolus data - Set zeros to nan
    bolus_data[bolus_data == 0] = np.nan

    # Plot Insulin Compartment Data
    ax = fig.add_subplot(412)
    ax.plot(x,
            tissue_compartment,
            c='b',
            lw=pu.plot_lw(),
            label='Subcutaneous tissue')
    ax.plot(x,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Blood plasma')

    # ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$Insulin, \, mg/L$')
    ax.set_axisbelow(True)

    # Add Bolus Data on second y-axis
    ax2 = ax.twinx()
    color = 'tab:green'
    ax2.set_ylabel('Units', color=color)
    ax2.plot(
        x,
        bolus_data,  #lw=pu.plot_lw(),
        label='Bolus',
        color=color,
        marker='D',
        markerfacecolor='None',
        markersize=5,
        linewidth=0)
    ax2.tick_params(axis='y', labelcolor=color)

    # Show legend
    ax.legend(loc='upper left', prop={'size': 6})
    # ax2.legend(loc='upper right', prop={'size': 6})

    ############################################################################

    # Collect glucose data
    gut_compartment = df['gt'].values[:N]
    plasma_compartment = df['mt'].values[:N]

    # Plot Glucose compartments...
    ax = fig.add_subplot(413)
    ax.plot(x, gut_compartment, c='b', lw=pu.plot_lw(), label='Gut glucose')
    ax.plot(x,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Plasma glucose')

    # ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$mg/L$')
    ax.set_axisbelow(True)
    ax.legend(loc='upper left', prop={'size': 6})

    ############################################################################
    # Glucose and Meal Detection

    # Get glucose data
    carb_est = df['carb_ests_'].values[:N]
    carb_mean = df['carb_mean_'].values[:N]
    carb_stds = df['carb_stds_'].values[:N]

    # Get meal predictions
    meal_preds = df['meal_preds_'].values[:N]
    meal_preds[meal_preds == 0] = np.nan

    # Plot
    ax = fig.add_subplot(414)
    ax.plot(x, carb_est, c='orange', lw=pu.plot_lw())
    # ax.plot(x, carb_mean, c='b', lw=pu.plot_lw(), linestyle='dashed')
    # ax.plot(x, carb_mean, c='b', lw=pu.plot_lw(), linestyle='dashed')
    ax.plot(x,
            meal_preds * carb_est,
            marker='*',
            c='magenta',
            linewidth=0,
            markersize=4,
            label='Predicted meal')

    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$Carbs, \, mg$')
    ax.set_axisbelow(True)

    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
def main(args):

    # Collect data from results
    df = pd.read_pickle(path='results/fixed_parameters_std-2/4.pkl')

    # Set time range
    S = 540
    N = 710
    x = np.arange(N - S)

    # Prep figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))

    ############################################################################
    # Collect CGM and meal data
    cgm_data = df['cgm_inputs_'].values[S:N]
    cgm_model = df['Gt'].values[S:N]
    meals = df['y_meals'].values[S:N]

    # Make all 0 target meal NaNs
    meals[meals == 0] = np.nan

    # Print meal idxs
    print('Meal idxs: ', np.where(meals == 1.))

    # Plot CGM and Meal data
    ax = fig.add_subplot(211)
    ax.set_xlim(0, N - S)
    ax.set_ylim(0, 250)

    ax.axhline(70, linewidth=1, color='#e3e1e1')
    ax.axhline(180, linewidth=1, color='#e3e1e1')
    # ax.axvspan(125, 170, color='#eeeeee')

    ax.plot(x,
            cgm_data,
            marker='o',
            c='g',
            linewidth=0,
            markersize=1,
            label='CGM')

    ax.plot(x,
            meals * 20,
            marker='o',
            c='purple',
            linewidth=0,
            markersize=4,
            markerfacecolor='None',
            label='Meal')
    ax.set_axisbelow(True)

    ax.legend(loc='upper left', prop={'size': 6})
    ax.set_ylabel('$mg/dl$')

    ############################################################################
    # Collect insulin data
    tissue_compartment = df['s1'].values[S:N]
    plasma_compartment = df['s2'].values[S:N]
    bolus_data = df['bolus_inputs_'].values[S:N]

    # Keep only non-zero bolus data - Set zeros to nan
    bolus_data[bolus_data == 0] = np.nan

    # Print bolus idxs
    print('Bolus idxs: ', np.where(bolus_data > 0.))

    # Plot Insulin Compartment Data
    ax = fig.add_subplot(212, sharex=ax)
    ax.set_xlim(0, N - S)

    ax.plot(x,
            tissue_compartment,
            c='b',
            lw=pu.plot_lw(),
            label='Subcutaneous tissue')
    ax.plot(x,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Blood plasma')

    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$Insulin, \, mg/L$')

    # plt.grid()
    ax.set_axisbelow(True)

    # Add Bolus Data on second y-axis
    ax2 = ax.twinx()
    color = 'tab:green'
    ax2.set_ylabel('Units', color=color)
    ax2.plot(
        x,
        bolus_data,  #lw=pu.plot_lw(),
        label='Bolus',
        color=color,
        marker='D',
        markerfacecolor='None',
        markersize=4,
        linewidth=0)
    ax2.tick_params(axis='y', labelcolor=color)
    ax2.set_axisbelow(True)

    # Show legend
    ax.legend(loc='upper left', prop={'size': 6})
    ax2.legend(loc='upper right', prop={'size': 6})

    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
def main(args):

    # Collect data from results
    df = pd.read_pickle(path='results/fixed_parameters_std-2/4.pkl')

    # Set time range
    S = 540
    N = 695
    H = 30
    x = np.arange(N - S)

    # Prep figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))

    ############################################################################

    # Collect CGM and meal data
    cgm_data = df['cgm_inputs_'].values[S:N]
    cgm_model = df['Gt'].values[S:N]
    meals = df['y_meals'].values[S:N]

    # Make all 0 target meal NaNs
    meals[meals == 0] = np.nan
    print('Logged Meal idxs:', np.where(meals > 0))

    # Get meal predictions
    meal_preds = df['meal_preds_'].values[S:N]
    meal_preds[meal_preds == 0] = np.nan

    # Plot CGM and Meal data
    ax = fig.add_subplot(211)
    ax.set_xlim(0, N - S)
    ax.set_ylim(0, 250)

    ax.axhline(70, linewidth=1, color='#ececec')
    ax.axhline(180, linewidth=1, color='#ececec')

    ax.plot(x,
            cgm_data,
            marker='o',
            c='g',
            linewidth=0,
            markersize=1,
            label='CGM')
    ax.plot(x,
            meals * 20,
            marker='o',
            c='purple',
            linewidth=0,
            markersize=4,
            markerfacecolor='None',
            label='Meal')
    ax.plot(x,
            meal_preds * 5,
            marker='^',
            c='magenta',
            linewidth=0,
            markersize=4,
            label='Predicted meal')

    ax.set_axisbelow(True)

    ax.legend(loc='upper left', prop={'size': 6})
    ax.set_ylabel('$mg/dl$')

    ############################################################################
    # Glucose and Meal Detection

    # Get glucose data
    carb_est = df['carb_ests_'].values[S:N]
    carb_mean = df['carb_mean_'].values[S:N]
    carb_stds = df['carb_stds_'].values[S:N]

    # Plot
    ax = fig.add_subplot(212, sharex=ax)
    ax.set_xlim(0, N - S)

    for it, m in enumerate(meal_preds):
        if m == 1:
            print('Meal prediction idx: ', it)
            ax.axvline(it, c='magenta')

    ax.plot(x, carb_est, c='orange', lw=pu.plot_lw(), label="$\hat{m}_t'$")
    ax.plot(x, carb_mean, c='b', lw=.8, label="$\\overline{\hat{m'}}_{0:t}$")
    ax.plot(x,
            carb_stds,
            c='b',
            lw=.8,
            label="$2 \cdot \sigma$",
            linestyle='-.')

    ax.legend(loc='upper left', prop={'size': 6})
    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$Carbs, \, mg$')
    ax.set_axisbelow(True)

    # plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #14
0
def main(args):
    """Visualize basic CGM - This can be used as a template to add
    more coupled data."""

    # Load data
    F_NAME = 'data/minimal_tracking_data.csv'
    df = pd.read_csv(F_NAME)

    # Pick a user
    random.seed(42)
    usr_id = random.choice(df['user_id'].unique())
    df = df[df['user_id'] == usr_id]

    # Set dateTimetimeIndex
    df['date'] = df['date'].apply(lambda x: x[:19])
    df['date'] = pd.to_datetime(df['date'])
    df.set_index('date', inplace=True)

    # Pick a day
    date = random.choice(df.index.date)
    df = df[date.strftime('%Y-%m-%d')]

    # Original CGM
    original_x_axis = np.arange(0, 60 * 24, 5)
    original_cgm_data = df['quantity']

    # Increase resolution by interpolation
    new_x_axis = np.arange(0, 60 * 24, 1)
    new_cgm_vals = pchip_interpolate(original_x_axis, original_cgm_data,
                                     new_x_axis)

    smoothed_cgm = savgol_filter(new_cgm_vals,
                                 window_length=15,
                                 polyorder=1,
                                 mode='interp')

    # Remove overlap of indices
    # new_x_axis = new_x_axis[~original_x_axis]
    # new_cgm_vals = new_cgm_vals[~original_x_axis]

    # Prepare figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))

    # Plot
    ax = fig.add_subplot(111)
    # ax.axhspan(70, 180, alpha=0.1, color='#ccced1')
    ax.set_ylim(125, 200)

    ax.plot(new_x_axis,
            smoothed_cgm,
            c='black',
            linewidth=1,
            linestyle='dashed',
            label='Smoothed data')
    ax.plot(new_x_axis,
            new_cgm_vals,
            marker='o',
            c='r',
            linewidth=0,
            markersize=1,
            label='Upsampled data')
    ax.plot(original_x_axis,
            original_cgm_data,
            marker='o',
            c='b',
            linewidth=0,
            markersize=1,
            label='Measured data')

    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$ mg/dl$')
    ax.legend(loc='upper left', prop={'size': 5})

    plt.xlim(0, 60 * 1 + 2)
    ax.set_axisbelow(True)

    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
def main(args):
    """Plot multiple meals to illustrate the variance in meal responses."""

    # Load data
    F_NAME = 'data/minimal_tracking_data.csv'
    df = pd.read_csv(F_NAME)

    # Set window length of meal response
    frequency = 5
    w_len = (2 * 60) // frequency
    x = np.arange(w_len)

    # Pick a user
    random.seed(42)
    usr_id = random.choice(df['user_id'].unique())
    df = df[df['user_id'] == usr_id]
    df.reset_index(inplace=True)

    # Prep data - Select frames only just after a meal is logged
    meal_chunks = []
    meal_idxs = df.index[df['meal'] == 1].tolist()

    for meal_idx in meal_idxs:
        meal_chunks.append(df.loc[meal_idx:meal_idx + w_len -
                                  1]['quantity'].values)

    # Normalize to have every line start from 0
    for it, chunk in enumerate(meal_chunks):
        delta = chunk[0]
        meal_chunks[it] = [x - delta for x in chunk]

    # Increase resolution by interpolation
    x_axis = np.arange(0, w_len * frequency, frequency)
    new_x_axis = np.arange(w_len * frequency) + 1

    meal_chunks = [
        pchip_interpolate(x_axis, chunk, new_x_axis) for chunk in meal_chunks
    ]
    print('Numer of meals: ', len(meal_chunks))

    # Prepare figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 5)
    fig = plt.figure(figsize=(fig_size))

    # Plot
    ax = fig.add_subplot(111)
    for meal in meal_chunks:
        ax.plot(new_x_axis, meal, c='b', lw=.2, linestyle='dashed')
    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$\Delta mg/dl$')

    ax.set_axisbelow(True)

    plt.xlim(0, 120)
    plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()
Example #16
0
            parsed = line_temp.split('\t')
            print(parsed)
            x.append(int(parsed[0]))
            y.append(float(parsed[3]))
        cnt += 1

    return x, y


if __name__ == '__main__':

    filenames = [
        'AdenoSquam', 'BladderBreastLungHe', 'BladderFourBiomarkers',
        'BladderFourScores', 'BreastFiveBiomarkers', 'BreastFourScores'
    ]
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 8)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)
    for filename in filenames:
        x, y = read_files(filename + '.txt')
        plt.plot(x, y, label=filename)

    ax.set_xlabel('Number of Steps')
    ax.set_ylabel('Accuracy')
    ax.set_axisbelow(True)
    ax.legend(loc='lower right')
    plt.grid()
    plt.tight_layout()
    pu.save_fig(fig, '../cnn_acc_steps.pdf', 'pdf')
    plt.show()
Example #17
0
def main(args):

    # Collect data from results
    df = pd.read_pickle(path='results/fixed_parameters_std-2/4.pkl')

    # Set time range
    S = 540
    N = 695
    H = 30
    x = np.arange(N - S)

    # Prep figure
    pu.figure_setup()
    fig_size = pu.get_fig_size(10, 8)
    fig = plt.figure(figsize=(fig_size))

    ############################################################################

    # Collect CGM and meal data
    cgm_data = df['cgm_inputs_'].values[S:N]
    cgm_model = df['Gt'].values[S:N]
    meals = df['y_meals'].values[S:N]

    # Set up prediction line
    pred_t = 124
    pred = df['cgm_preds_'][pred_t]
    x_pred = np.arange(pred_t, pred_t + len(pred))

    # Make all 0 target meal NaNs
    meals[meals == 0] = np.nan

    # Print meal idxs
    print('Meal idxs: ', np.where(meals == 1.))

    # Plot CGM and Meal data
    ax = fig.add_subplot(411)
    ax.set_xlim(0, N - S)
    ax.set_ylim(0, 250)

    ax.axhline(70, linewidth=1, color='#ececec')
    ax.axhline(180, linewidth=1, color='#ececec')
    ax.axvspan(pred_t, pred_t + H + 1, color='#f6f6f6')

    ax.plot(x,
            cgm_data,
            marker='o',
            c='g',
            linewidth=0,
            markersize=1,
            label='CGM')
    ax.plot(x_pred,
            pred,
            c='black',
            linewidth=1,
            linestyle='dashed',
            label='Modeled CGM')
    ax.plot(x,
            meals * 20,
            marker='o',
            c='purple',
            linewidth=0,
            markersize=4,
            markerfacecolor='None',
            label='Meal')
    plt.vlines(x=pred_t + H,
               ymin=pred[-1],
               ymax=cgm_data[pred_t + H - 1],
               color='r',
               linewidth=2)

    ax.set_axisbelow(True)

    ax.legend(loc='upper left', prop={'size': 6})
    ax.set_ylabel('$mg/dl$')

    ############################################################################

    # Collect insulin data
    tissue_compartment = df['s1'].values[S:N]
    plasma_compartment = df['s2'].values[S:N]
    bolus_data = df['bolus_inputs_'].values[S:N]

    # Keep only non-zero bolus data - Set zeros to nan
    bolus_data[bolus_data == 0] = np.nan

    # Print bolus idxs
    print('Bolus idxs: ', np.where(bolus_data > 0.))

    # Plot Insulin Compartment Data
    ax = fig.add_subplot(412, sharex=ax)
    ax.set_xlim(0, N - S)
    ax.axvspan(pred_t, pred_t + H + 1, color='#f6f6f6')

    ax.plot(x,
            tissue_compartment,
            c='b',
            lw=pu.plot_lw(),
            label='Subcutaneous tissue')
    ax.plot(x,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Blood plasma')

    ax.set_ylabel('$Insulin, \, mg/L$')

    # plt.grid()
    ax.set_axisbelow(True)

    # Add Bolus Data on second y-axis
    ax2 = ax.twinx()
    color = 'tab:green'
    ax2.set_ylabel('Units', color=color)
    ax2.plot(
        x,
        bolus_data,  #lw=pu.plot_lw(),
        label='Bolus',
        color=color,
        marker='D',
        markerfacecolor='None',
        markersize=4,
        linewidth=0)
    ax2.tick_params(axis='y', labelcolor=color)
    ax2.set_axisbelow(True)

    # Show legend
    ax.legend(loc='upper left', prop={'size': 6})
    ax2.legend(loc='upper right', prop={'size': 6})

    ############################################################################

    # Collect glucose data
    gut_compartment = df['gt'].values[S:N - H]
    plasma_compartment = df['mt'].values[S:N - H]
    xx = np.arange(N - S - H)

    # Collect "prediction" data
    gut_compartment_ff = df['gt'].values[N - H:N]
    plasma_compartment_ff = df['mt'].values[N - H:N]
    xx_ff = np.arange(N - S - H, N - S)

    # Plot Glucose compartments...
    ax = fig.add_subplot(413, sharex=ax)
    ax.set_xlim(0, N - S)
    ax.axvspan(pred_t, pred_t + H + 1, color='#f6f6f6')

    ax.plot(xx, gut_compartment, c='b', lw=pu.plot_lw(), label='Gut glucose')
    ax.plot(xx,
            plasma_compartment,
            c='r',
            lw=pu.plot_lw(),
            label='Plasma glucose')

    ax.plot(xx_ff,
            gut_compartment_ff,
            c='b',
            lw=pu.plot_lw(),
            linestyle='dashed')
    ax.plot(xx_ff,
            plasma_compartment_ff,
            c='r',
            lw=pu.plot_lw(),
            linestyle='dashed')

    ax.set_ylabel('$mg/L$')
    ax.set_axisbelow(True)
    ax.legend(loc='upper left', prop={'size': 6})

    ############################################################################
    # Glucose and Meal Detection

    # Get glucose data
    carb_est = df['carb_ests_'].values[S:N - H]
    carb_mean = df['carb_mean_'].values[S:N - H]
    carb_stds = df['carb_stds_'].values[S:N - H]
    xx_carbs = np.arange(N - S - H)

    # Get "future" glucose data
    carb_est_ff = df['carb_ests_'].values[N - H:N]
    xx_carbs_ff = np.arange(N - S - H, N - S)

    # Get meal predictions
    meal_preds = df['meal_preds_'].values[S:N - H]
    meal_preds[meal_preds == 0] = np.nan

    # Plot
    ax = fig.add_subplot(414, sharex=ax)
    ax.set_xlim(0, N - S)
    ax.axvspan(pred_t, pred_t + H + 1, color='#f6f6f6')

    ax.plot(xx_carbs,
            carb_est,
            c='orange',
            lw=pu.plot_lw(),
            label='Carbs est.')
    ax.plot(xx_carbs_ff,
            carb_est_ff,
            c='orange',
            lw=pu.plot_lw(),
            linestyle='dashed')

    # ax.plot(x, carb_mean, c='b', lw=0.5, label)
    # ax.plot(xx_carbs, meal_preds, marker='^', c='magenta', linewidth=0,
    #         markersize=3, label='Predicted meal')

    ax.legend(loc='upper left', prop={'size': 6})
    ax.set_xlabel('$t \, (minutes)$')
    ax.set_ylabel('$Carbs, \, mg$')
    ax.set_axisbelow(True)

    # plt.grid()
    plt.tight_layout()

    if args.save:
        pu.save_fig(fig, args.save)
    else:
        plt.show()