def gluco_plot(time,
               gluco,
               hypo=70,
               hyper=126,
               title="Patiend ID glucose level"):
    """Plot the glucose level on a time span.
    
    Parameters
    -------------------
    time : array of datetimes, the horizontal axis
    gluco : array of float, the correspondent glucose level on the vertical axis
    hypo : number, hypoglicaemia threshold in mg/dl (default is 70, i.e. 3.9 mmol/l)
    hyper : number, hyperglicaemia threshold in mg/dl (default is 126, i.e. 7 mmol/l)
    title : string, the title of the plot (optional)
    """
    plt.figure(figsize=(10, 6))
    plt.hlines(hypo,
               time[0],
               time[-1],
               linestyles='dashed',
               label='hypoglicaemia')
    plt.hlines(hyper,
               time[0],
               time[-1],
               linestyles='dotted',
               label='hyperglicaemia')
    plt.ylim([10, 410])
    plt.plot_date(time, gluco, '-', label='glucose level')
    plt.title(title)
    plt.ylabel('mg/dL')
    plt.xticks(rotation='vertical')
    plt.legend()
def plot_aucs(test_name, train_aucs, test_aucs):
    fig = plt.figure(figsize=(8, 8))
    axes = fig.gca()
    axes.plot(
        np.arange(N_EPOCHS), train_aucs)
    axes.plot(
        np.arange(N_EPOCHS), test_aucs)
    plt.xlabel("epoch")
    plt.ylabel("AUC")
    plt.xlim(0, 15)
    plt.ylim(0.5, 1.0)
    plt.legend(["train", "test (%s)" % test_name])
    fig.savefig("auc_%s.png" % test_name)
예제 #3
0
def cgm(df,
        gluco_fit=None,
        hypo=70,
        hyper=126,
        title="Patiend ID CGM",
        savefig=False):
    """Plot the CGM signal on an input time span.

    Parameters
    -------------------
    df : DataFrame, the output returned by gluco_extract(..., return_df=True)
    gluco_fit : array of float, the results of a fitted model (optional)
    hypo : number, hypoglicaemia threshold in
           mg/dl (default is 70, i.e. 3.9 mmol/l)
    hyper : number, hyperglicaemia threshold
            in mg/dl (default is 126, i.e. 7 mmol/l)
    title : string, the title of the plot (optional)
    savefig : bool, if True save title.png
    """
    plt.figure(figsize=(10, 6), dpi=300)
    plt.hlines(hypo,
               df.index[0],
               df.index[-1],
               linestyles='dashed',
               label='hypoglicaemia')
    plt.hlines(hyper,
               df.index[0],
               df.index[-1],
               linestyles='dotted',
               label='hyperglicaemia')
    plt.ylim([10, 410])
    plt.plot_date(df.index, df.as_matrix(), '-', label='real CGM')
    if gluco_fit is not None:
        plt.plot(df.index, gluco_fit, '--', label='predicted CGM')
    plt.title(title)
    plt.ylabel('mg/dL')
    plt.xticks(rotation='vertical')
    plt.legend(bbox_to_anchor=(1.1, 1.0))
    if savefig: plt.savefig(title + '_fit.png')
예제 #4
0
    # Pold = np.array(Pnew)
    # Xold = np.array(Xnew)
    y[t] = np.dot(Xnew[t, :], H)
    # y[t] = np.dot(Xnew,H)
# ---------------------------------------- #

# In[36]:

# ---------- Plot ------------------------ #
plt.subplot(211)
plt.plot(ts, ys, '-', label='noisy')  # noisy measures
plt.plot(ts, y, '--', label='filtered')  # filtered measures
plt.grid()
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102),
           loc=3,
           ncol=2,
           mode="expand",
           borderaxespad=0.)
plt.subplot(212)
residuals = ys.ravel()[0:Ns] - y.ravel()[0:Ns]
plt.plot(ts, residuals)
plt.title('Durbin-Watson: {:.3f}'.format(sm.stats.durbin_watson(residuals)))
plt.tight_layout()
plt.grid()

# ## Translate `pykalman` names into our convention
#
# **Parameter Name** (Notation)
# - initial_state_mean (`X0`)
# - initial_state_covariance (`P0`)
# - transition_matrices (`F`)
예제 #5
0
obs_errors = [100, 1.0, 1.0, 1.0, 0.001]
levels = [0.95, 0.835, 0.685, 0.51, 0.34, 0.2, 0.095, 0.025]

plt.rc('lines', linewidth=1.0)

plt.figure(figsize=(9, 3), facecolor='white')

dirs = ['double']
labels = ['64 bits']

handles = []

for d, l in zip(dirs, labels):
    print(f'Plotting {d}')

    handles += plot(d, l)

plt.ylim([0, 3.5])
plt.xlabel('Time')
plt.ylabel(f'Total analysis RMSE')
plt.title('')

# Add legend
leg = plt.legend(handles=handles, frameon=True, ncol=2)
rect = leg.get_frame()
rect.set_linewidth(0.0)
rect.set_alpha(0.7)

plt.savefig(f'total_error_compare.pdf', bbox_inches='tight')
plt.show()
예제 #6
0
# Get axis limits and equalise
xlim = plt.gca().get_xlim()
ylim = plt.gca().get_ylim()
xlim = ylim = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])]
plt.xlim(xlim)
plt.ylim(ylim)

# Plot diagonal line
plt.plot(xlim, ylim, ls="--", c=".3")

plt.title('')
plt.xlabel('RMSE')
plt.ylabel('Spread')

# Legend for symbol
for field in fields:
    plt.scatter(-1, -1, s=90, marker=field[2], color='.3', label=field[1])

# Legend for color
plot_lines = [plt.plot([-1,-1.5], [-1,-1.5], color=colors[0])[0]]
plot_lines.append(plt.plot([-1,-1.5], [-1,-1.5], color=colors[1])[0])
col_leg = plt.legend(plot_lines, labels, loc=6, fontsize=12)

# Add both legends
plt.gca().add_artist(col_leg)
plt.legend(loc=2, fontsize=12)

plt.savefig(f'scatter_all_fields.pdf', bbox_inches='tight')
plt.show()
# perform moving-window arma
errs, forecast = moving_window_ARIMA(df,
                                     w_size=w_size,
                                     ph=ph,
                                     p=p,
                                     d=d,
                                     q=q,
                                     start_params=None,
                                     verbose=True)

# In[13]:

# plot results
gluco_plot(df.index, df.as_matrix(), title='Patient ' + str(k))
plt.plot(df.index, forecast['ts'], linestyle='dashed', label='forecast')
plt.legend(bbox_to_anchor=(1.2, 1.0))
MAE_6 = np.mean(errs['err_6'])
MAE_12 = np.mean(errs['err_12'])
MAE_18 = np.mean(errs['err_18'])
RMSE_6 = np.linalg.norm(errs['err_6']) / np.sqrt(len(errs['err_6']))
RMSE_12 = np.linalg.norm(errs['err_12']) / np.sqrt(len(errs['err_12']))
RMSE_18 = np.linalg.norm(errs['err_18']) / np.sqrt(len(errs['err_18']))
print("MAE (30') = {:2.3f}\t|\tMAE (60') = {:2.3f}\t|\tMAE (90') = {:2.3f}".
      format(MAE_6, MAE_12, MAE_18))
print("RMSE (30') = {:2.3f}\t|\tRMSE (60') = {:2.3f}\t|\tRMSE (90') = {:2.3f}".
      format(RMSE_6, RMSE_12, RMSE_18))

# In[14]:

residuals = df.as_matrix()[w_size:-ph].ravel() - forecast['ts'][w_size:-ph]
fig = plt.figure(figsize=(12, 4))
예제 #8
0
}

vert_secs = [(1.0, 0.5), (0.5, 0.2), (0.2, 0.0)]

field = ' '.join(fields[argv[2]])

plt.figure(figsize=(5, 5), facecolor='white')

dirs = ['double', 'reduced']
labels = ['64 bits', '22 bits']

handles = []

for d, l in zip(dirs, labels):
    print(f'Plotting {d}')

    handles += plot(d, field, vert_secs[int(argv[3])], l)

plt.xlabel('Latitude')
plt.ylabel(f'{fields[argv[2]][0]} {fields[argv[2]][1]}')
plt.title('')

# Add legend
leg = plt.legend(handles=handles, frameon=True, ncol=2, loc='lower center')
rect = leg.get_frame()
rect.set_linewidth(0.0)
rect.set_alpha(0.7)

plt.savefig(f'latitudinal_error_{argv[2]}_{argv[3]}.pdf', bbox_inches='tight')
plt.show()