Esempio n. 1
0
cost = 0.5 * simps(int, t)

##: print final answers to screen
print('\nFinal time [s]:\t' + str(t[-1]))
print('Cost:\t\t' + str(cost))
print('Comp time [ms]:\t' + str(time * 1000))
print('Iterations:\t' + str(it))
print('Loss:\t\t' + str(np.max(L(xi, IC))))

## Plot solution: **********************************************************************************

# range vs crosstrack
p1 = MakePlot('Range [km]', 'Crosstrack [km]')
p1.ax[0].plot(R[:, 0] / 1000., R[:, 1] / 1000., 'k')
p1.ax[0].grid(True)
p1.PartScreen(8., 7.)
p1.show()

# 3d trajectoryAc
p2 = MakePlot(r'Range [km]', r'Crosstrack [km]', zlabs=r'Altitude [km]')
p2.ax[0].plot(R[:, 0] / 1000., R[:, 1] / 1000., R[:, 2] / 1000., 'k')
p2.ax[0].quiver(R[0::2,0]/1000.,R[0::2,1]/1000.,R[0::2,2]/1000., \
                Ac[0::2,0], Ac[0::2,1], Ac[0::2,2], \
                color='r', linewidth=1)
p2.ax[0].grid(True)

p2.ax[0].xaxis.labelpad = 10
p2.ax[0].yaxis.labelpad = 10
p2.ax[0].zaxis.labelpad = 10

p2.PartScreen(8., 7.)
Esempio n. 2
0
p1 = MakePlot([[r'$x$', r'$x$', r'$x$']],
              [[r'$y(x)$', r'$y_x(x)$', r'$y_{xx}(x)$']])
p1.ax[0].plot(x, y, 'k', label=r'$y(x)$', linewidth=2)

p1.ax[1].plot(x, yp, 'k', label=r'$y_x(x)$', linewidth=2)

p1.ax[2].plot(xs1, ypps1(xs1, xi), 'k', label=r'$y_{xx}(x)$', linewidth=2)
p1.ax[2].plot(xs2, ypps2(xs2, xi), 'k', linewidth=2)

p1.ax[0].grid('True')
p1.ax[1].grid('True')
p1.ax[2].grid('True')

p1.fig.subplots_adjust(wspace=0.75)

p1.PartScreen(10., 6.)
p1.show()
# p1.save('linearNonlinear_function')

#Plot 2
p2 = MakePlot(r'$x$', r'$|\mathbb{L}(\mathbf{\xi})|$')
p2.ax[0].plot(x, err, 'k*', label=r'$y(x)$', linewidth=2)

p2.ax[0].grid('True')
p2.ax[0].set_yscale('log')

p2.PartScreen(7., 6.)
p2.show()
# p2.save('linearNonlinear_error')

#Plot 3
Esempio n. 3
0
p1 = MakePlot('Accuracy ($|L_2|$)', r'Frequency')


p1.ax[0].hist(tfc['loss'][np.where(tfc['loss'] < 1.)], bin1, edgecolor='black', linewidth=1.2, label = 'TFC',alpha = 0.75, \
weights=np.ones(len(tfc['loss'][np.where(tfc['loss'] < 1.)])) / len(tfc['loss'][np.where(tfc['loss'] < 1.)]))
p1.ax[0].yaxis.set_major_formatter(PercentFormatter(1, decimals=0, symbol='%'))

p1.ax[0].hist(spe['loss'][np.where(spe['loss'] < 1.)], bin1, edgecolor='black', linewidth=1.2, label = 'Spectral Method', alpha = 0.75, \
weights=np.ones(len(spe['loss'][np.where(spe['loss'] < 1.)])) / len(spe['loss'][np.where(spe['loss'] < 1.)]))
p1.ax[0].yaxis.set_major_formatter(PercentFormatter(1, decimals=0, symbol='%'))

p1.ax[0].set_xscale('log')
p1.ax[0].set_xlim(5e-17, 5e-15)
p1.fig.subplots_adjust(wspace=0.35, hspace=0.25)
p1.ax[0].legend()
p1.PartScreen(9., 6.)
p1.show()
# p1.save('figures/EOL_hist_L2_outerLoop')

## Plot 2: Computation time
bin2 = np.linspace(0, 300, 30)

p2 = MakePlot('Computation time [ms]', r'Frequency')

p2.ax[0].hist(tfc['time'][np.where(tfc['time'] < 1.)]*1000, bin2, edgecolor='black', linewidth=1.2,
              label = 'TFC', alpha = 0.75, \
weights=np.ones(len(tfc['time'][np.where(tfc['time'] < 1.)])) / len(tfc['time'][np.where(tfc['time'] < 1.)]))
p2.ax[0].yaxis.set_major_formatter(PercentFormatter(1, decimals=0, symbol='%'))

p2.ax[0].hist(spe['time'][np.where(spe['time'] < 1.)]*1000, bin2, edgecolor='black', linewidth=1.2, label = 'Spectral Method', alpha = 0.75, \
weights=np.ones(len(spe['time'][np.where(spe['time'] < 1.)])) / len(spe['time'][np.where(spe['time'] < 1.)]))
Esempio n. 4
0
# Create the TFC class:
myTfc = utfc(N, nC, m, x0=-2., xf=2., basis='LeP')
x = np.linspace(-2., 2., N)
ind = np.argmin(np.abs(x))
H = myTfc.H

m = H(x).shape[1]

# Create the constrained expression:
K = np.array([1., 2., 3.])
g = lambda x, xi: np.dot(H(x), xi)
uslow = lambda x, n, xi: g(x, xi) + K[np.int64(n % 3)] - g(np.array([0.]), xi)
u = jit(uslow)

# Run the monte carlo test
p = MakePlot(r'$x$', r'$y(x,n,g(x))$')

for k in range(nMC):
    xi = onp.random.randn(m)
    n = onp.random.rand() * 10. - 5.

    U = u(x, n, xi)
    val = U[ind]
    p.ax[0].plot(x, U)

p.ax[0].plot(np.zeros(3), K, 'k', linestyle='none', markersize=10, marker='.')
p.ax[0].set_xlim([-2., 2.])
p.ax[0].grid(True)
p.PartScreen(8, 7)
p.show()
Esempio n. 5
0
import tqdm
import pickle

from tfc.utils import MakePlot

## TEST PARAMETERS: ***************************************************
sol = pickle.load(open('data/timingLyap_CP_L1.pickle','rb'))

MS = 10
width = 0.0085      # the width of the bars: can also be len(x) sequence


p1 = MakePlot('Jacobi Constant','Computation Time [s]')

p1.ax[0].bar(sol['C'],sol['tLoss'],width, label='Loss function')
p1.ax[0].bar(sol['C'],sol['tJac'],width,bottom=sol['tLoss'],label='Jacobian')
p1.ax[0].bar(sol['C'],sol['tLS'],width,bottom=sol['tLoss']+sol['tJac'],label='Least-squares')



p1.ax[0].grid(True)
delta = 0.5*(sol['C'][0]-sol['C'][1])
p1.ax[0].set_xlim(sol['C'].min()-delta,sol['C'].max()+delta)

p1.ax[0].legend(loc='upper center', bbox_to_anchor=(0.5, 1.14),
          ncol=4, fancybox=True, shadow=True)
p1.fig.subplots_adjust(left=0.11, bottom=0.11, right=0.89, top=0.85)
p1.PartScreen(12.,7.)
p1.show()
# p1.save('figures/timeBreakdown')
Esempio n. 6
0
d2r = egrad(dr)
L = lambda xi: -r(th,xi)**2*(dr(th,xi)*np.tan(th)+2.*d2r(th,xi))+\
               -np.tan(th)*dr(th,xi)**3+3.*r(th,xi)*dr(th,xi)**2+r(th,xi)**3

# Solve the problem:
xi = np.zeros(H(th).shape[1])
xi, _, time = NLLS(xi, L, timer=True)

# Print out statistics:
print("Solution time: {0} seconds".format(time))

# Plot the solution and residual
p = MakePlot([r"$y$"], [r"$x$"])
p.ax[0].plot(r(th, xi) * np.sin(th), r(th, xi) * np.cos(th), "k")
p.ax[0].axis("equal")
p.ax[0].grid(True)
p.ax[0].invert_yaxis()
p.PartScreen(8, 7)
p.show()

p2 = MakePlot([r"$\theta$"], [r"$L$"])
p2.ax[0].plot(th,
              np.abs(L(xi)),
              "k",
              linestyle="None",
              marker=".",
              markersize=10)
p2.ax[0].set_yscale("log")
p2.PartScreen(8, 7)
p2.show()
Esempio n. 7
0
tf = 2. / xi['b']**2

print('{:.2e} & {:.2e} & {:.8f} & {:.5f} & {:d} & {:.2f}'.format(
    np.max(np.abs(L(xi))), np.max(np.abs(H(z, xi))), cost,
    tf.tolist()[0], it, time * 1000))

# Plots
MS = 12

p1 = MakePlot(onp.array([['t', 't']]), onp.array([[r'$x(t)$', r'$y(t)$']]))
p1.fig.subplots_adjust(wspace=0.25, hspace=0.25)
p1.ax[0].plot(t, x(z, xi['xi_x']), label='x(t)', linewidth=2)
p1.ax[1].plot(t, u(z, xi['xi_u']), label='y(t)', linewidth=2)
p1.ax[0].grid(True)
p1.ax[1].grid(True)
p1.FullScreen()
p1.show()
# p1.save('figures/unknownTimeStates')

p2 = MakePlot('t', r'$|Loss|$')
p2.ax[0].plot(t, onp.abs(Lx(z, xi)), 'r*', markersize=MS, label='|$L_x(t)$|')
p2.ax[0].plot(t, onp.abs(Lu(z, xi)), 'kx', markersize=MS, label='|$L_u(t)$|')
p2.ax[0].plot(t, onp.abs(H(z, xi)), 'b+', markersize=MS, label='|$H(t)$|')
p2.ax[0].set_yscale('log')
p2.ax[0].legend()
p2.ax[0].grid(True)
p2.PartScreen(7., 6.)
p2.show()
# p2.save('figures/unknownTimeLoss')
Esempio n. 8
0
            + phi3(x)*(y3 - np.dot(tfc.H(x3),xi)) \

y = lambda xi, xil, xiu: yhat(xi) \
            + (fu(xiu)-yhat(xi)) * step(yhat(xi) -fu(xiu)) \
            + (fl(xil)-yhat(xi)) * step(fl(xil)  - yhat(xi))

## DEFINE RANDOM COEFFICIENTS ******************************************************************
xi = np.random.randn(tfc.H(x).shape[1], nLines)
xiu = np.random.randn(bnd.H(x).shape[1])
xil = np.random.randn(bnd.H(x).shape[1])

## CREATE PLOTS ******************************************************************

p1 = MakePlot(r'$x$', r'$y(x)$')
for i in range(nLines):
    p1.ax[0].plot(x, y(xi[:, i], xil, xiu), linewidth=2)

p1.ax[0].plot(x, fu(xiu), 'k--', linewidth=5)
p1.ax[0].plot(x, fl(xil), 'k--', linewidth=5)

p1.ax[0].plot(x1, y1, 'ko', markersize=10)
p1.ax[0].plot(x2, y2, 'ko', markersize=10)
p1.ax[0].plot(x3, y3, 'ko', markersize=10)

p1.ax[0].grid('True')
p1.ax[0].set_xlim(x0, xf)

p1.PartScreen(9., 6.)
p1.show()
# p1.save('Equality_And_Inequality_Constraints')
Esempio n. 9
0
    dark = onp.array(g(x, xi))
    ind = onp.where(np.logical_and(dark > lb(x), dark < ub(x)))[0]
    dark[ind] = np.nan
    return dark


p = MakePlot(r'$x$', r'$y(x,g(x))$')
for k in range(numFuncs):
    xi = onp.random.rand(m)
    pl = p.ax[0].plot(x, u(x, xi))[0]
    color = pl.get_color()
    #p.ax[0].plot(x,antiu(x,xi),'--',color=color) # Uncomment to see original free function as a dashed line
p.ax[0].plot(x, ub(x), 'k', linewidth=3, linestyle='--')
p.ax[0].plot(x, lb(x), 'k', linewidth=3, linestyle='--')
p.ax[0].set_ylim([-1., 0.5])
p.PartScreen(8, 7)
p.show()

# Inequality with linear constraints
onp.random.seed(0)

# Constants
numFuncs = 20
m = 10

# Get CP
myTfc = utfc(n, 0, m, basis='LeP', x0=0., xf=10.)
H = myTfc.H
m = H(x).shape[1]

H0 = H(np.array([0.]))
Esempio n. 10
0
                             real(*xTest).reshape((nTest, nTest)),
                             cmap=cm.nipy_spectral)
        p.ax[k].xaxis.labelpad = 15
        p.ax[k].yaxis.labelpad = 15
        p.ax[k].zaxis.labelpad = 10
        p.ax[k].view_init(azim=azim[k], elev=elev[k])
        if not k == 4:
            p.ax[k].set_proj_type('ortho')

    p.ax[1].tick_params(axis='both', which='major', pad=8)
    p.ax[1].xaxis.labelpad = 10
    p.ax[1].yaxis.labelpad = 10

    p.ax[0].set_yticklabels([])
    p.ax[1].set_zticklabels([])
    p.ax[2].set_xticklabels([])
    p.fig.subplots_adjust(wspace=0.05, hspace=0.05)
    p.PartScreen(10, 9)
    p.show()

    p1 = MakePlot(r'$r$', r'$\theta$', zlabs=r'error')
    p1.ax[0].plot_surface(xTest[0].reshape((nTest, nTest)),
                          xTest[1].reshape((nTest, nTest)),
                          err.reshape((nTest, nTest)),
                          cmap=cm.gist_rainbow)
    p1.ax[0].xaxis.labelpad = 20
    p1.ax[0].yaxis.labelpad = 20
    p1.ax[0].zaxis.labelpad = 20
    p1.FullScreen()
    p1.show()
Esempio n. 11
0
p1.ax[0].plot(dif['C'],
              dif['time'],
              'ko',
              label='Differential Corrector',
              markersize=MS)
p1.ax[0].axvline(x=Jc(L1), color='b', label='E(L1)', linestyle='--')
p1.ax[0].axvline(x=Jc(L2), color='g', label='E(L2)', linestyle='--')
p1.ax[0].grid(True)

p1.ax[0].legend(loc='upper center',
                bbox_to_anchor=(0.5, 1.14),
                ncol=4,
                fancybox=True,
                shadow=True)
p1.fig.subplots_adjust(left=0.11, bottom=0.11, right=0.89, top=0.85)
p1.PartScreen(9., 6.)
p1.show()
# p1.save('figures/compTime' + file1)

p2 = MakePlot('Jacobi Constant', 'Iterations')
p2.ax[0].plot(tfc['C'], tfc['iter'], 'rx', label='TFC', markersize=MS)
p2.ax[0].axvline(x=Jc(L1), color='b', label='E(L1)', linestyle='--')
p2.ax[0].axvline(x=Jc(L2), color='g', label='E(L2)', linestyle='--')
p2.ax[0].legend(loc='upper center',
                bbox_to_anchor=(0.5, 1.14),
                ncol=3,
                fancybox=True,
                shadow=True)
p2.fig.subplots_adjust(left=0.11, bottom=0.11, right=0.89, top=0.85)
p2.ax[0].grid(True)
p2.PartScreen(9., 6.)
Esempio n. 12
0
for k in tqdm.trange(nMC):

    # Solve for xi
    tfc.basisClass.w = np.array(2. * onp.random.rand(*tfc.basisClass.w.shape) -
                                1.)
    tfc.basisClass.b = np.array(2. * onp.random.rand(*tfc.basisClass.b.shape) -
                                1.)
    xi = LS()

    # Calculate the error
    ur = real(*xTest)
    ue = u(xi, *xTest)
    err = ur - ue
    testErr[k] = np.max(np.abs(err))

p1 = MakePlot('Maximum Error', 'Number of Occurances')
hist, binEdge = np.histogram(np.log10(testErr), bins=20)
p1.ax[0].hist(testErr,
              bins=10**binEdge,
              color=(76. / 256., 0., 153. / 256.),
              edgecolor='black',
              zorder=20)
p1.ax[0].set_xscale('log')
p1.ax[0].xaxis.set_major_locator(plt.LogLocator(base=10, numticks=10))
p1.ax[0].locator_params(axis='both', tight=True)
p1.ax[0].grid(True, which='both')
[line.set_zorder(0) for line in p1.ax[0].lines]
mTicks = p1.ax[0].xaxis.get_minor_ticks()
p1.PartScreen(11, 8)
p1.show()