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')
Exemple #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()
Exemple #3
0
def main(args):

    # Fetch data
    df = pd.read_csv(F_NAME_DATA)
    df_model = pd.read_pickle(path=F_NAME_MODEL)

    # Pick a user
    USR_IDS = df['user_id'].unique()
    # u_id = random.choice(USR_IDS)
    u_id = 8
    df = df[df['user_id'] == u_id]

    # Get idxs of all logged meals
    df.reset_index(inplace=True)
    meal_idxs = df.index[df['meal'] == 1].tolist()
    df = df.iloc[meal_idxs]
    df = df[df['image_url'] != '0']

    glucose_len = 38
    idxs = df.index.values
    urls = df['image_url'].values
    glucose_chunks = [
        df_model['carb_ests_'].values[idx:idx + glucose_len] for idx in idxs
    ]

    # Visualize a meal image
    n = len(urls)
    columns = 8
    rows = max((n // 8) + 1, 2)
    link = urls[0]
    fig, axarr = plt.subplots(rows, columns, sharex=True, sharey=True)
    for i in range(n):
        img = io.imread(urls[i])
        axarr[i // columns, i % columns].imshow(img)

    pu.save_fig(fig, args.im_save)
    plt.clf()

    fig, axarr = plt.subplots(rows, columns, sharex=True, sharey=True)
    for i in range(n):
        axarr[i // columns, i % columns].plot(np.arange(glucose_len),
                                              glucose_chunks[i],
                                              c='orange')
    pu.save_fig(fig, args.plt_save)
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()
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()
Exemple #9
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()
#plt.style.use('classic')
plt.figure(figsize=(4, 4))
for r in range(N_REPEATS):
    plt.plot(all_results[r, :, 1], all_results[r, :, 0], '.')
plt.plot([0.0, 1.0], [0, 1.0], '--', color='k', linewidth=1.2)
#plt.arrow(0.3,0.78,0.1,0.1,-)
plt.annotate("Epoch",
             xy=(0.6, 0.9),
             xytext=(0.4, 0.82),
             arrowprops=dict(arrowstyle="->", color="black"))
plt.xlabel("Dense Acc %")
plt.ylabel("Focused Acc %")
plt.xticks([0, .2, .4, .6, .8])
plt.yticks([0, .2, .4, .6, .8])
plt.grid(True)
save_fig("focus_acc_vs_dense")
plt.show()

# In[13]:

focus_outputs_np = np.array(focus_output).reshape((-1, HIDDEN_COUNT))
for i in range(1):
    x = focus_outputs_np[:, i]
    n, bins, patches = plt.hist(x, 50, normed=0, facecolor='green', alpha=0.75)

    plt.xlabel('Activation Distribution')
    plt.ylabel('Count')
    plt.title(r'$\mathrm{Histogram\ of\ focus\ Neuron:}\ ' + str(i) + '$')
    plt.grid(True)
    plt.show()
import matplotlib.pyplot as plt
import plot_utils as pu
import pandas as pd

data = pd.read_csv("run-Nov06_18-21-27_juansosa-Lenovo-Legion-Y7000P-1060-tag-Loss.csv")
data = data.fillna(value=0)
data.head()

pu.figure_setup()

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

ax.plot(data['Step'], data['Value'], c='g', linewidth=0.5)

ax.set_xlabel('Steps')
ax.set_ylabel('DQN Loss')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, '1-1loss', 'pdf')
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()
Exemple #13
0
data = pd.read_csv(
    "run-Dec08_17-57-30_juansosa-Lenovo-Legion-Y7000P-1060-tag-Loss_G_GAN.csv")
data = data.fillna(value=0)
data.head()

pu.figure_setup()

fig_size = pu.get_fig_size(10, 8)
print(fig_size)
fig = plt.figure(figsize=fig_size)
#fig = plt.figure()
ax = fig.add_subplot(111)
dt = data['Value'].to_numpy()

smt = smooth(dt, 0.99)

ax.plot(range(len(data['Value'])),
        data['Value'],
        c='orange',
        linewidth=0.5,
        alpha=0.3)
ax.plot(range(len(data['Value'])), smt, c='orange', linewidth=0.5)
ax.set_xlabel('Steps')
ax.set_ylabel('Loss G GAN')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, 'loss_G_GAN', 'pdf')
Exemple #14
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()
Exemple #15
0
		TP1, FP1, TN1, FN1 = TPR_FPR_01(evaluation1, lables1, lable_dict1,thr)
		TPR1 = TP1 * 1.0 / (TP1 + FN1)
		FPR1 = FP1 * 1.0 / (FP1 + TN1)

		p.append((TPR1 + TPR) / 2.0)
		r.append((FPR1 + FPR) / 2.0)
		roc += (0.5 * (FPR_0 - FPR) * TPR)
		roc += (0.5 * (FPR1_0 - FPR1) * TPR1)
		FPR_0 = FPR
		FPR1_0 = FPR1
	print(file_name, roc)
	#print(p)
	#print(r)
	plt.plot(r, p, label=lable_names[cnt] + ', AUC=' + str(round(roc,2)))
	cnt -= 1

#plt.title('')
plt.plot([0, 1], [0, 1], color='black', lw=1, linestyle='--')
plt.ylim([0., 1.05])
ax.legend(loc='lower right')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.grid()
plt.tight_layout()
pu.save_fig(fig, 'adenosquam_FPR_TPR.pdf', 'pdf')
plt.show()



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()
    "run-Dec08_17-57-30_juansosa-Lenovo-Legion-Y7000P-1060-tag-Loss_G_cycle.csv"
)
data = data.fillna(value=0)
data.head()

pu.figure_setup()

fig_size = pu.get_fig_size(10, 8)
print(fig_size)
fig = plt.figure(figsize=fig_size)
#fig = plt.figure()
ax = fig.add_subplot(111)
dt = data['Value'].to_numpy()

smt = smooth(dt, 0.99)

ax.plot(range(len(data['Value'])),
        data['Value'],
        c='orange',
        linewidth=0.5,
        alpha=0.3)
ax.plot(range(len(data['Value'])), smt, c='orange', linewidth=0.5)
ax.set_xlabel('Steps')
ax.set_ylabel('Loss G cycle')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, 'loss_G_cycle', 'pdf')
Exemple #18
0
import matplotlib.pyplot as plt
import plot_utils as pu
import pandas as pd

data = pd.read_csv("run-Dec02_23-30-08_juansosa-Lenovo-Legion-Y7000P-1060-tag-Loss_supervised.csv")
data = data.fillna(value=0)
data.head()

pu.figure_setup()

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

ax.plot(data['Step'], data['Value'], c='g', linewidth=0.5)

ax.set_xlabel('Steps')
ax.set_ylabel('Supervised Loss')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, '1-2lossSupTL', 'pdf')
import matplotlib.pyplot as plt
import plot_utils as pu
import pandas as pd

data = pd.read_csv(
    "run-Nov11_12-54-53_juansosa-Lenovo-Legion-Y7000P-1060-tag-Mean_Reward.csv"
)
data = data.fillna(value=0)

data2 = pd.read_csv(
    "run-Dec02_23-30-08_juansosa-Lenovo-Legion-Y7000P-1060-tag-Mean_Reward.csv"
)
data2 = data2.fillna(value=0)

pu.figure_setup()

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

ax.plot(data2['Step'], data2['Value'], c='b', linewidth=0.5, label='with TL')
ax.plot(data['Step'], data['Value'], c='g', linewidth=0.5, label='without TL')

ax.set_xlabel('Steps')
ax.set_ylabel('Mean Reward')
plt.legend()

pu.save_fig(fig, '1-2rewTL', 'pdf')
Exemple #20
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):

    # 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()
Exemple #22
0
    "run-Dec08_17-57-30_juansosa-Lenovo-Legion-Y7000P-1060-tag-Loss_G_identity.csv"
)
data = data.fillna(value=0)
data.head()

pu.figure_setup()

fig_size = pu.get_fig_size(10, 8)
print(fig_size)
fig = plt.figure(figsize=fig_size)
#fig = plt.figure()
ax = fig.add_subplot(111)
dt = data['Value'].to_numpy()

smt = smooth(dt, 0.99)

ax.plot(range(len(data['Value'])),
        data['Value'],
        c='orange',
        linewidth=0.5,
        alpha=0.3)
ax.plot(range(len(data['Value'])), smt, c='orange', linewidth=0.5)
ax.set_xlabel('Steps')
ax.set_ylabel('Loss G Identity')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, 'loss_G_Iden', 'pdf')
    params, q = solve_FOM(params)

    return q


if __name__ == "__main__":

    # choose pde [burgers,advection]
    pde = "react"
    case = "pacman"
    Ngrid = [2**11, 2**11]
    T = 1
    params = params_class(case=case, pde=pde, N=Ngrid, Nt=10, T=T)
    params, q = solve_FOM(params)
    np.save("fft_pacman_ref_2048", q)

    #%%
    import matplotlib.pyplot as plt
    plt.pcolormesh(params.geom.X[0], params.geom.X[1], q[..., -1])
    plt.colorbar()

    # %%
    from plot_utils import save_fig
    for it, t in enumerate(params.time.t):
        k, Ek = spectrum(q[::, ::, it])
        plt.loglog(k, Ek, color=[0.0, 0.0, 1 - t / params.time.T], lw=0.5)
    plt.xlabel(r"wave number $|k|$")
    plt.ylabel(r"energy $E(|k|)$")
    plt.grid(which="both", linestyle=':')
    save_fig("../imgs/energy_pacman.eps")
Exemple #24
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()
import matplotlib.pyplot as plt

import plot_utils as pu
import numpy as np
from PIL import Image
from matplotlib.colors import NoNorm

pu.figure_setup()

fig_size = pu.get_fig_size(10, 8)
print(fig_size)
fig = plt.figure(figsize=fig_size)

ax = fig.add_subplot(121)

img = Image.open('../output/X_REAL/0010.png').convert('L')
arr = np.asarray(img)
plt.imshow(img, cmap='gray', norm=NoNorm())
ax.set_title('Original')

ax = fig.add_subplot(122)
img = Image.open('../output/Y/0010.png').convert('L')
arr = np.asarray(img)
plt.imshow(img, cmap='gray', norm=NoNorm())
ax.set_title('Translated')

pu.save_fig(fig, 'img2img', 'pdf')
data = pd.read_csv(
    "run-Dec08_17-57-30_juansosa-Lenovo-Legion-Y7000P-1060-tag-Loss_D.csv")
data = data.fillna(value=0)
data.head()

pu.figure_setup()

fig_size = pu.get_fig_size(10, 8)
print(fig_size)
fig = plt.figure(figsize=fig_size)
#fig = plt.figure()
ax = fig.add_subplot(111)
dt = data['Value'].to_numpy()

smt = smooth(dt, 0.99)

ax.plot(range(len(data['Value'])),
        data['Value'],
        c='orange',
        linewidth=0.5,
        alpha=0.3)
ax.plot(range(len(data['Value'])), smt, c='orange', linewidth=0.5)
ax.set_xlabel('Steps')
ax.set_ylabel('Loss D')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, 'loss_D', 'pdf')
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()
Exemple #28
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()
Exemple #29
0
import matplotlib.pyplot as plt
import plot_utils as pu
import pandas as pd

data = pd.read_csv(
    "run-Nov06_18-21-27_juansosa-Lenovo-Legion-Y7000P-1060-tag-Mean_Reward.csv"
)
data = data.fillna(value=0)
data.head()

pu.figure_setup()

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

ax.plot(data['Step'], data['Value'], c='g', linewidth=0.5)

ax.set_xlabel('Steps')
ax.set_ylabel('Mean Reward')

#ax.set_axisbelow(True)

#plt.grid()
#plt.tight_layout()
pu.save_fig(fig, '1-1rew', 'pdf')