import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import assign_0
ret_dg = assign_0.disc_grid(output=True)
df_dg = pd.DataFrame(ret_dg).set_index('k', drop=False)
fig, ax = plt.subplots();
(df_dg['kp']-df_dg['k']).plot(ax=ax);
ax.hlines(0, *ax.get_xlim(), linestyle='--', linewidth=1);
ret_di = assign_0.disc_interp(output=True)
df_di = pd.DataFrame(ret_di).set_index('k', drop=False)
fig, ax = plt.subplots();
(df_di['kp']-df_di['k']).plot(ax=ax);
ax.hlines(0, *ax.get_xlim(), linestyle='--', linewidth=1);
def disc_perf(fun, lN1, lN0_lo, lN0_hi, kind='linear'):
N1 = 2**lN1
res = []
for p in range(lN0_lo, lN0_hi+1):
N0 = 2**p
t0 = time.time()
ret = fun(N=N0)
dt = time.time() - t0
k_grid, verr = assign_0.disc_errors(ret['v'], ret['kp'], N0, N1, kind=kind)
acc = -np.mean(np.log10(np.abs(verr)))
res.append((N0, dt, acc))
print(f'{N0}: {dt} {acc}')
return pd.DataFrame(res, columns=['N', 'dt', 'acc']).set_index('N')
perf_dg = disc_perf(assign_0.disc_grid, lN1=16, lN0_lo=6, lN0_hi=12)
perf_di = disc_perf(assign_0.disc_interp, lN1=16, lN0_lo=6, lN0_hi=14)
fig, ax = plt.subplots()
ax.plot(perf_dg['acc'], np.log10(perf_dg['dt']), marker='o', label='Grid Search');
ax.plot(perf_di['acc'], np.log10(perf_di['dt']), marker='o', label='Interpolation');
ax.set_xlabel('accuracy');
ax.set_ylabel('log(time)');
ax.legend();
ret_cd = assign_0.cont_redisc(output=True)
df_cd = pd.DataFrame(ret_cd).set_index('k', drop=False)
fig, ax = plt.subplots();
df_cd['dk'].plot(ax=ax);
plt.hlines(0, *ax.get_xlim(), linestyle='--', linewidth=1);
ret_cs = assign_0.cont_reverse(output=True)
df_cs = pd.DataFrame(ret_cs).set_index('k', drop=False)
fig, ax = plt.subplots();
df_cs['dk'].plot(ax=ax);
plt.hlines(0, *ax.get_xlim(), linestyle='--', linewidth=1);
ret_sp = assign_0.cont_sparse(output=True)
df_sp = pd.DataFrame(ret_sp).set_index('k', drop=False)
fig, ax = plt.subplots();
df_sp['dk'].plot(ax=ax);
plt.hlines(0, *ax.get_xlim(), linestyle='--', linewidth=1);
def cont_perf(fun, lN1, lN0_lo, lN0_hi, kind='linear'):
N1 = 2**lN1
res = []
for p in range(lN0_lo, lN0_hi+1):
N0 = 2**p
t0 = time.time()
ret = fun(N=N0)
dt = time.time() - t0
k_grid, verr = assign_0.cont_errors(ret['v'], ret['i'], ret['dv'], N0, N1, kind=kind)
acc = -np.mean(np.log10(np.abs(verr)))
res.append((N0, dt, acc))
print(f'{N0}: {dt} {acc}')
return pd.DataFrame(res, columns=['N', 'dt', 'acc']).set_index('N'), k_grid, verr
perf_cr, k_grid, verr = cont_perf(assign_0.cont_redisc, lN1=16, lN0_lo=5, lN0_hi=10)
perf_sp, k_grid, verr = cont_perf(assign_0.cont_sparse, lN1=16, lN0_lo=5, lN0_hi=11)
acc = np.log10(np.abs(verr))
print(np.mean(-acc))
plt.plot(k_grid, acc);
fig, ax = plt.subplots()
ax.plot(perf_cr['acc'], np.log10(perf_cr['dt']), marker='o', label='Rediscretization');
ax.plot(perf_sp['acc'], np.log10(perf_sp['dt']), marker='o', label='Sparse');
ax.set_xlabel('accuracy');
ax.set_ylabel('log(time)');
ax.legend();