Exemple #1
0
## compute the error: ******************************************************************************
A = np.sqrt(y0**2 + (y0p / w)**2)
Phi = np.arctan(-y0p / w / y0)
yTrue = A * np.cos(w * xSol + Phi)

err = np.abs(ySol - yTrue)

## print status of run: ****************************************************************************
print('TFC least-squares time[s]: ' + '\t' + str((time.sum())))
print('Max residual:' + '\t' * 3 + str(res.max()))
print('Max error:' + '\t' * 3 + str(err.max()))

## plotting: ***************************************************************************************
# figure 1: solution
p1 = MakePlot(r'$x$', r'$y(t)$')
p1.ax[0].plot(xSol.flatten(), ySol.flatten())
p1.ax[0].grid(True)
p1.PartScreen(7., 6.)
p1.show()

# figure 2: residual
p2 = MakePlot(r'$t$', r'$|L(\xi)|$')
p2.ax[0].plot(xSol.flatten(), res.flatten(), '*')
p2.ax[0].grid(True)
p2.ax[0].set_yscale('log')
p2.PartScreen(7., 6.)
p2.show()

# figure 3: error
p3 = MakePlot(r'$t$', r'$|y_{true} - y(t)|$')
    xi, time = LS(xi, L, timer=True)

# Calculate error at the test points:
dark = np.meshgrid(np.linspace(0, 1, nTest), np.linspace(0, 1, nTest))
xTest = tuple([j.flatten() for j in dark])
err = np.abs(u(xi, *xTest) - real(*xTest))
print("Time: " + str(time))
print("Max Error: " + str(np.max(err)))
print("Mean Error: " + str(np.mean(err)))

# Plot the analytical solution
if usePlotly:
    from matplotlib import cm
    from tfc.utils.PlotlyMakePlot import MakePlot

    p = MakePlot(r'x', r'y', zlabs=r'u(x,y)')
    p.Surface(x=xTest[0].reshape((nTest, nTest)),
              y=xTest[1].reshape((nTest, nTest)),
              z=real(*xTest).reshape((nTest, nTest)),
              showscale=False)
    p.view(azimuth=-135, elevation=20)
    p.fig['layout']['scene']['aspectmode'] = 'cube'
    p.show()

else:
    from tfc.utils import MakePlot

    p = MakePlot(r'$x$', r'$y$', zlabs=r'$u(x,y)$')
    p.ax[0].plot_surface(xTest[0].reshape((nTest, nTest)),
                         xTest[1].reshape((nTest, nTest)),
                         real(*xTest).reshape((nTest, nTest)),
Exemple #3
0
# Create loss function:
dr = egrad(r)
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")
Exemple #4
0
from util import Lagrange, getL1L2

import numpy as np
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.)
Exemple #5
0
## Plot: **************************************************************
MS = 12

# import pdb; pdb.set_trace()

## Plot 1: Accuracy
bin1 = np.logspace(-17,
                   -11,
                   num=50,
                   endpoint=True,
                   base=10.0,
                   dtype=None,
                   axis=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.)
Exemple #6
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()
Exemple #7
0
# Calcualte u and v and plot for different times
n = 100
X = np.matlib.repmat(np.reshape(np.linspace(0,L,num=n),(n,1)),n,1).flatten()
Y = np.reshape(np.matlib.repmat(np.reshape(np.linspace(-h/2.,h/2.,num=n),(n,1)),1,n),(n**2,1)).flatten()
xTest = np.zeros((3,n**2*3))
xTest[0,:] = np.hstack([X,]*3)
xTest[1,:] = np.hstack([Y,]*3)
xTest[2,:] = np.hstack([np.ones(n**2)*0.01,np.ones(n**2)*0.1,np.ones(n**2)*tf])
xTest = np.array(xTest.T,dtype=varType)

p = []; U = [];
vals = [0.01,0.1,tf]
u,v = model.call(xTest)
u = u.numpy(); v = v.numpy()
for k in range(len(vals)):
    p.append(MakePlot(r'$x (m)$',r'$y (m)$'))
    ind = np.where(np.round(xTest[:,2],12)==np.round(vals[k],12))
    U.append(np.reshape(u[ind],(n,n)))

Xm = np.reshape(xTest[:,0][ind],(n,n))
Ym = np.reshape(xTest[:,1][ind],(n,n))

dark = np.block(U)
vMin = np.min(dark)
vMax = np.max(dark)
def MakeContourPlot(Xm,Ym,Um):
    p = MakePlot(r'$x$ (m)',r'$y$ (m)')
    C = p.ax[0].contourf(Xm,Ym,Um,vmin=vMin,vmax=vMax,cmap=cm.gist_rainbow)
    cbar = p.fig.colorbar(C)
    return p
Exemple #8
0
    err, res, _ = BVP_spectral(N, m[i], 'CP', iterMax, tol)
    errSC[i] = err
    resSC[i] = res

# ELM - Sigmoid
errSS = onp.ones_like(m) * onp.nan
resSS = onp.ones_like(m) * onp.nan
for i in tqdm.trange(len(m)):
    err, res, _ = BVP_spectral(N, m[i], 'ELMSigmoid', iterMax, tol)
    errSS[i] = err
    resSS[i] = res

# Plot
MS = 12

p1 = MakePlot(r'Number of basis functions ($m$)',
              r'$L_2|y_{approx} - y_{true}|$')
p1.ax[0].plot(m, errCP, 'r*', markersize=MS, label='TFC - CP')
p1.ax[0].plot(m, errSC, 'k*', markersize=MS, label='Spectral - CP')
p1.ax[0].plot(m, errES, 'rx', markersize=MS, label='TFC - Sigmoid')
p1.ax[0].plot(m, errSS, 'kx', markersize=MS, label='Spectral - Sigmoid')
p1.ax[0].grid(True)
p1.ax[0].set_yscale('log')
p1.ax[0].set_ylim([1e-16, 1.])
# p1.ax[0].legend()
p1.ax[0].legend(loc='best', fontsize='small')
p1.PartScreen(7., 6.)
p1.show()
# p1.save('figures/BVP_TFC')

## TFC vs Spec comparison on accuracy
p2 = MakePlot(r'Number of basis functions ($m$)', r'Accuracy Gain')
Exemple #9
0
# u(2) = -1

n = 150
x = np.linspace(0., 3., 100)
a = np.linspace(1., 2., n)
b = np.linspace(2., 8., n)
c = {'a': a[-1], 'b': b[-1]}

g = lambda x, c: c['a'] * x * np.sin(c['b'] * x)
u = jit(lambda x,c: g(x,c)+\
        (-x**3+7.*x-6.)/6.*(g(x[-1],c)-g(x[0],c))+\
        (x**3-9.*x+10.)/2.*(1.-g(np.array(1.),c))+\
        (-x**3+9.*x-8.)/2.*(-1.-g(np.array(2.),c)))

U = u(x, c)
p = MakePlot(r'$x$', r'$u(x,g(x))$')
p.ax[0].set_ylim([-10., 30.])
rel3 = p.ax[0].plot([0., 3.], [U[0], U[0]], 'r', linestyle='--')[0]
plot = p.ax[0].plot(x, U, color=COLOR, label=r'Constrained expression')[0]
rel1 = p.ax[0].plot(0.,
                    U[0],
                    'r',
                    linestyle='--',
                    marker='.',
                    markersize=10,
                    label=r'Relative constraint $u(0) = u(3)$')[0]
rel2 = p.ax[0].plot(3., U[0], 'r', linestyle='None', marker='.',
                    markersize=10)[0]
p.ax[0].plot(1.,
             1.,
             'b',
Exemple #10
0
## TEST PARAMETERS: ***************************************************
tfc = pickle.load(open('data/' + file1 + '.pickle', 'rb'))[Lpt]
dif = pickle.load(open('data/' + file2 + '.pickle', 'rb'))

## Compute L1 & L2 Locations
m_E = 5.9724e24
m_M = 7.346e22
mu = m_M / (m_M + m_E)
L1, L2 = getL1L2(mu)
r1 = lambda x: np.sqrt((x + mu)**2)
r2 = lambda x: np.sqrt((x + mu - 1.)**2)  # m2 to (x,y,z)
Jc = lambda x: (x**2) + 2. * (1. - mu) / r1(x) + 2. * mu / r2(x) + (1. - mu
                                                                    ) * mu

MS = 10
p1 = MakePlot('Jacobi Constant', 'Computation Time [s]')
p1.ax[0].plot(tfc['C'], tfc['time'], 'rx', label='TFC', markersize=MS)
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)
Exemple #11
0
# Create the random paths and plot them
np.random.seed(2)

xlabs = np.array([
    r'$t$',
] * 4).reshape((2, 2))
ylabs = np.array([
    r'$q_k$',
] * 4)
for k in range(4):
    myStr = r'$q_' + str(k) + r'$'
    ylabs[k] = myStr
ylabs = np.reshape(ylabs, (2, 2))

p = MakePlot(xlabs, ylabs)
m = H(t).shape[1]
for k in range(nFunc):
    xiu = np.random.rand(m) - 0.5
    xiv = np.random.rand(m) - 0.5
    xiw = np.random.rand(m) - 0.5
    gu = lambda t: np.dot(H(t), xiu)
    gv = lambda t: np.dot(H(t), xiv)
    gw = lambda t: np.dot(H(t), xiw)
    uvw = np.vstack([u(t, gu), v(t, gv), w(t, gw)])
    q = u2q(uvw)
    for j in range(4):
        p.ax[j].plot(t, q[j, :])

for j in range(4):
    p.ax[j].scatter(t[0], qi[j], color='k', s=30, zorder=21)
Exemple #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()
Exemple #13
0
    xi, it = NLLS(xi, L)

    # Create the test set:
    N = 1000
    z = np.linspace(-1., 1., N)

    # Calculate the error and return the results
    X = np.hstack([x1(z, xi), x2(z, xi)])
    Y = np.hstack([y1(z, xi), y2(z, xi)])
    err = np.abs(Y - soln(X, Pe))
    return np.max(err), np.mean(err)


err = np.block([[*CalculateSolution(1.), *CalculateSolutionSplit(1.)],
                [*CalculateSolution(10.**6), *CalculateSolutionSplit(10.**6)]])
tab = table.SimpleTable(err, form='%.2e')
print(tab)

#: Analytical solution plots
x = np.linspace(0., 1., 1000)
y1 = soln(x, 1.)
y2 = soln(x, 10.**6)

p = MakePlot(r'$x$', r'$y$')
p.ax[0].plot(x, y1, 'k', label=r'$P_e = 1$')
p.ax[0].plot(x, y2, color=(76. / 256., 0., 153. / 256.), label=r'$P_e = 10^6$')
p.ax[0].legend()
p.PartScreen(8, 7)
p.show()
Exemple #14
0
dth = egrad(th)
dr = egrad(r)

# Create the residuals/Jacobians:
resTh = lambda x,xi,const: c(xi)*dth(x,xi)+q(x,xi,const)*r(x,xi)*(w*np.sin(th(x,xi))+const['b']*(z(x,xi)-z0(xi)))
resQ = lambda x,xi,const: c(xi)*dq(x,xi,const)+q(x,xi,const)**2*r(x,xi)*w*np.cos(th(x,xi))
resR = lambda x,xi: c(xi)*dr(x,xi)-np.sin(th(x,xi))
resZ = lambda x,xi: c(xi)*dz(x,xi)-np.cos(th(x,xi))
L = jit(lambda xi,x,const: np.hstack([resTh(x,xi,const), resQ(x,xi,const), resR(x,xi), resZ(x,xi)]))

# Create plot
th2 = np.linspace(0.,2.*np.pi,num=100)
X2 = Rs*np.cos(th2)
Y2 = Rs*np.sin(th2)+Rs

p = MakePlot(r'$x\ (m)$',r'$y\ (m)$')
p.ax[0].plot(X2,Y2,'-k',label='Super Pressure Balloon')
p.ax[0].grid(True)

colors = ["r", "g", "b", "tab:gray", "m", "c", "tab:orange", "y", "tab:purple", "tab:brown", "tab:olive"]

const = {'g':0.,'L':0.,'atm_density':0.,'Msg':0.,'b':0.}
time = onp.zeros(atmData.shape[0])

for k in range(atmData.shape[0]-1,-1,-1):

    # Problem constants:
    const['g'] = atmData['Gravity (m/s^2)'][k]
    const['L'] = 208*const['g']
    const['atm_density'] = atmData['Density (kg/m^3)'][k]
    const['Msg'] = atmData['Gas Mass (kg).1'][k]
Exemple #15
0
## TEST PARAMETERS: ***************************************************
tfc = pickle.load(open('data/' + file1 + '.pickle', 'rb'))[Lpt]
nsc = pickle.load(open('data/' + file2 + '.pickle', 'rb'))

## Compute L1 & L2 Locations
m_E = 5.9724e24
m_M = 7.346e22
mu = m_M / (m_M + m_E)
L1, L2 = getL1L2(mu)
r1 = lambda x: np.sqrt((x + mu)**2)
r2 = lambda x: np.sqrt((x + mu - 1.)**2)  # m2 to (x,y,z)
Jc = lambda x: (x**2) + 2. * (1. - mu) / r1(x) + 2. * mu / r2(x) + (1. - mu
                                                                    ) * mu

MS = 10
p1 = MakePlot('Jacobi Constant', 'Computation Time [s]')
p1.ax[0].plot(tfc['C'], tfc['time'], 'ro', label='scaled', markersize=MS)
p1.ax[0].plot(nsc['C'], nsc['time'], 'ko', label='non-scaled', 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)
                   np.linspace(x0[1], xf[1], nTest))
xTest = tuple([j.flatten() for j in dark])
err = np.abs(u(xi, *xTest) - real(*xTest))
print("Time: " + str(time))
print("Max Error: " + str(np.max(err)))
print("Mean Error: " + str(np.mean(err)))

# Plot the analytical solution in polar coordinates
X = xTest[0] * np.cos(xTest[1])
Y = xTest[0] * np.sin(xTest[1])

# Create plots
if usePlotly:
    from tfc.utils.PlotlyMakePlot import MakePlot

    p = MakePlot(r'x', r'y', zlabs=r'u(x,y)')
    p.Surface(x=X.reshape((nTest, nTest)),
              y=Y.reshape((nTest, nTest)),
              z=real(*xTest).reshape((nTest, nTest)),
              showscale=False)
    p.view(azimuth=45, elevation=45)
    p.fig['layout']['scene']['aspectmode'] = 'cube'
    p.show()

    p1 = MakePlot('x', 'y', zlabs='error')
    p1.Surface(x=xTest[0].reshape((nTest, nTest)),
               y=xTest[1].reshape((nTest, nTest)),
               z=err.reshape((nTest, nTest)),
               showscale=False)
    p1.show()
Exemple #17
0
for i in range(0, len(t)):
    int[i] = 0.5 * (X[i]**2 + U[i]**2)
    Ham[i] = int[i] + -U[i] / beta * (alfa * X[i] + beta * U[i])

cost = simps(int, t)

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()
Exemple #18
0
Y = np.zeros((N, step))
RES = np.zeros((N, step))

gamma = np.linspace(0, 1, step)

for i in tqdm.trange(len(gamma)):
    y, res, x = IVP2BVP(N, m, gamma[i], 'CP', iterMax, tol)
    Y[:, i] = y
    RES[:, i] = res

sRes = 3. * np.std(RES, axis=1)
mRes = np.mean(RES, axis=1)

lw = 1
p1 = MakePlot(r'$x$', r'$y(x)$', zlabs=r'$\gamma$')
for i in range(0, len(gamma)):
    p1.ax[0].plot3D(x, Y[:, i], gamma[i] * np.ones_like(x), 'k', linewidth=lw)
p1.ax[0].grid(True)
p1.ax[0].view_init(20, -130)
p1.ax[0].set_facecolor('white')
p1.ax[0].xaxis.labelpad = 15
p1.ax[0].yaxis.labelpad = 15
p1.ax[0].zaxis.labelpad = 15
p1.PartScreen(7., 6.)
p1.show()
# p1.save('figures/IVP2BVP_soln')

p2 = MakePlot(r'$x$', r'$|\mathbb{L}(\xi)|$')
p2.ax[0].plot(x, mRes, 'k*', markersize=10 * lw, label='Mean Residual')
p2.ax[0].plot(x,
Exemple #19
0
u = lambda t,g: g(t)+\
                (t-1.)*(t-2.)/2.*(0.-g(0.))+\
                -t*(t-2.)*(np.pi-g(1.))+\
                t*(t-1.)/2.*(np.exp(1.)-g(2.))

v = lambda t,g: g(t)+\
                (t-1.)*(t-2.)/2.*(0.-g(0.))+\
                -t*(t-2.)*(2.-g(1.))+\
                t*(t-1.)/2.*(-3.-g(2.))

# Create free functions:
gu1 = lambda t: np.sin(10. * t)
gv1 = lambda t: np.cos(7. * t)
gu2 = lambda t: t**2 + t + 5.
gv2 = lambda t: np.exp(t) / (1. + t)
gu3 = lambda t: t % 1
gv3 = lambda t: np.cos(3. * np.sqrt(t)) * t

# Create the plot:
p = MakePlot(r"u(t)", r"v(t)")
p.ax[0].plot(u(t, gu1), v(t, gv1), "r")
p.ax[0].plot(u(t, gu2), v(t, gv2), "g")
p.ax[0].plot(u(t, gu3), v(t, gv3), "b")
p.ax[0].plot([0., np.pi, np.exp(1.)], [0., 2., -3.],
             "k",
             linestyle="None",
             marker=".",
             markersize=10)
p.FullScreen()
p.show()
Exemple #20
0
            + phi1(x)*(y1 - np.dot(tfc.H(x1),xi)) \
            + phi2(x)*(y2 - np.dot(tfc.H(x2),xi)) \
            + 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()
Exemple #21
0
def MakeContourPlot(Xm,Ym,Um):
    p = MakePlot(r'$x$ (m)',r'$y$ (m)')
    C = p.ax[0].contourf(Xm,Ym,Um,vmin=vMin,vmax=vMax,cmap=cm.gist_rainbow)
    cbar = p.fig.colorbar(C)
    return p
Exemple #22
0
dY = onp.ones(1) * v_init[1]
b = onp.ones(1) * np.sqrt(2. / T_init)

# create a TFC dictionary with the unknowns
xi = TFCDictRobust({'xis': xis, 'X': X, 'Y': Y, 'dX': dX, 'dY': dY, 'b': b})

## solving the system of equations: ****************************************************************
xi, iter, time = NLLS(xi, L, timer=True)

## plotting: ***************************************************************************************

# compute location of L1 and L2 equilibrium points
L1 = 1. - (mu / 3.)**(1. / 3.)
L2 = 1. + (mu / 3.)**(1. / 3.)

p1 = MakePlot('x', 'y')
p1.ax[0].plot(L1, 0., 'ko', markersize=2)
p1.ax[0].plot(L2, 0., 'ko', markersize=2)
p1.ax[0].plot(1. - mu, 0., 'ko', markersize=6)

p1.ax[0].plot(r(z, xi)[:, 0], r(z, xi)[:, 1])

p1.ax[0].set_xlabel(r'$x$', labelpad=10)
p1.ax[0].set_ylabel(r'$y$', labelpad=10)

p1.ax[0].axis('equal')
p1.ax[0].set_ylim(-.25, .25)

p1.ax[0].grid(True)

p1.PartScreen(7., 6.)
Exemple #23
0
yinit = np.hstack((ys1(xs1, xi0), ys2(xs2, xi0)))
y = np.hstack((ys1(xs1, xi), ys2(xs2, xi)))
yp = np.hstack((yps1(xs1, xi), yps2(xs2, xi)))

err = onp.abs(y - ytrue(x))
res = onp.abs(L(xi))

print()
print('Max Error: ' + str(np.max(err)))
print('Max Loss: ' + str(np.max(res)))
print('Computation time [ms]: ' + str(time * 1000))
print()

## Plots
#Plot 1
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()
Exemple #24
0
    timeSC[i] = time

## ODE - 45
tol = onp.array([3, 4, 5, 6, 7, 8, 9])
err45 = onp.ones_like(tol) * onp.nan
time45 = onp.ones_like(tol) * onp.nan
for i in tqdm.trange(len(tol)):
    err, time = BVP_ode('RK45', 10.**(-tol[i]))
    err45[i] = err
    time45[i] = time

# Solvers: RK45, RK23, DOP853, Radau, BDF, LSODA

# Plot
MS = 12

p1 = MakePlot(r'$L_2|y_{approx} - y_{true}|$', r'Solution Time [sec]')
p1.ax[0].plot(errCP, timeCP, 'r*', markersize=MS, label='TFC - CP')
p1.ax[0].plot(errSC, timeSC, 'k*', markersize=MS, label='Spectral - CP')
p1.ax[0].plot(err45, time45, 'b*', markersize=MS, label='RK45')

p1.ax[0].grid(True)
p1.ax[0].set_xscale('log')
p1.ax[0].set_yscale('log')
p1.ax[0].set_ylim([1e-4, 10.])
# p1.ax[0].legend()
p1.ax[0].legend(loc='best', fontsize='small')
p1.PartScreen(7., 6.)
p1.show()
# p1.save('figures/BVP_time')
Exemple #25
0
        LamV[i, :], IC['ag'] + Ac[i, :])
    a_mag[i] = np.linalg.norm(Ac[i, :])

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
Exemple #26
0
# tfc constrained expression (with inequality constraints)
x = lambda x_xi, y_xi: xhat(x_xi) \
            +  (xbound[0]-xhat(x_xi))*(Phi1(yhat(y_xi),ybound)*Phi2(yhat(y_xi),ybound) *\
                                       Phi3(xhat(x_xi),xbound)*Phi2(xhat(x_xi),xbound)) \
            +  (xbound[1]-xhat(x_xi))*(Phi1(yhat(y_xi),ybound)*Phi2(yhat(y_xi),ybound) *\
                                       Phi3(-xhat(x_xi),-xbound)*Phi1(xhat(x_xi),xbound))

y = lambda x_xi, y_xi: yhat(y_xi) \
             + (ybound[0]-yhat(y_xi))*(Phi1(xhat(x_xi),xbound)*Phi2(xhat(x_xi),xbound) *\
                                       Phi3(yhat(y_xi),ybound)*Phi2(yhat(y_xi),ybound)) \
             + (ybound[1]-yhat(y_xi))*(Phi1(xhat(x_xi),xbound)*Phi2(xhat(x_xi),xbound) *\
                                       Phi3(-yhat(y_xi),-ybound)*Phi1(yhat(y_xi),ybound))

onp.random.seed(4) # fixes random seed to creat the same plot in book
x_xi = 0.1 * onp.random.randn(H(t).shape[1], Nlines)
y_xi = 0.1 * onp.random.randn(H(t).shape[1], Nlines)

## plotting: ***************************************************************************************
p1 = MakePlot(r'$x(t)$',r'$y(t)$')
for i in range(Nlines):
        p1.ax[0].plot(x(x_xi[:,i],y_xi[:,i]), y(x_xi[:,i],y_xi[:,i]))

p1.ax[0].add_patch(Rectangle((xbound[0],ybound[0]), xbound[1]-xbound[0], ybound[1]-ybound[0], fc='white',ec="white"))

p1.ax[0].plot(initial[0], initial[1], 'ko', markersize = 10)
p1.ax[0].plot(final[0], final[1], 'ko', markersize = 10)

p1.PartScreen(7.,6.)
p1.show()