# Orbit games

We consider energy plots and orbital solutions in polar coordinates for the general potential energy

$\begin{align}
   U(r) = k r^n
\end{align}$

```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
```

```python
# Change the common font size
font_size = 14
plt.rcParams.update({'font.size': font_size})
```

```python
class Orbit:
    """
    Potentials and associated differential equations for central force motion
    with the potential U(r) = k r^n.
    """

    def __init__(self, ang_mom, n, k=1, mu=1):
        self.ang_mom = ang_mom
        self.n = n
        self.k = k
        self.mu = mu

    def U(self, r):
        """Potential energy of the form U = kr^n."""
        return self.k * r**self.n

    def Ucf(self, r):
        """Centrifugal potential energy"""
        return self.ang_mom**2 / (2. * self.mu * r**2)

    def Ueff(self, r):
        """Effective potential energy"""
        return self.U(r) + self.Ucf(r)

    def U_deriv(self, r):
        """dU/dr"""
        return self.n * self.k * r**(self.n - 1)

    def Ucf_deriv(self, r):
        """dU_cf/dr"""
        return -2. * self.ang_mom**2 / (2. * self.mu * r**3)

    def Ueff_deriv(self, r):
        """dU_eff/dr"""
        return self.U_deriv(r) + self.Ucf_deriv(r)

    def dy_dt(self, t, y):
        """
        This function returns the right-hand side of the diffeq:
        [dr/dt d^2r/dt^2 dphi/dt]

        Parameters
        ----------
        t : float
            time
        y : float
            3-component vector with y[0] = r(t), y[1] = dr/dt, y[2] = dphi/dt

        """
        return [ y[1],
                -1./self.mu * self.Ueff_deriv(y[0]),
                self.ang_mom / (self.mu * y[0]**2) ]

    def solve_ode(self, t_pts, r_0, r_dot_0, phi_0,
                  abserr=1.0e-8, relerr=1.0e-8):
        """
        Solve the ODE given initial conditions.
        For now use odeint, but we have the option to switch.
        Specify smaller abserr and relerr to get more precision.
        """
        y = [r_0, r_dot_0, phi_0]
        solution = solve_ivp(self.dy_dt, (t_pts[0], t_pts[-1]),
                             y, t_eval=t_pts,
                             atol=abserr, rtol=relerr)
        r, r_dot, phi = solution.y
        return r, r_dot, phi

    def energy(self, t_pts, r, r_dot):
        """Evaluate the energy as a function of time"""
        return (self.mu/2.) * r_dot**2 + self.Ueff(r)
```

```python
def start_stop_indices(t_pts, plot_start, plot_stop):
    start_index = (np.fabs(t_pts-plot_start)).argmin()  # index in t_pts array
    stop_index = (np.fabs(t_pts-plot_stop)).argmin()  # index in t_pts array
    return start_index, stop_index
```

# Gravity $n = -1$

```python
n = -1
k = -3.
ang_mom = 1.
o1 = Orbit(ang_mom, n=n, k=k, mu=1)

fig_2 = plt.figure(figsize=(7,5))
ax_2 = fig_2.add_subplot(1,1,1)

r_pts = np.linspace(0.001, 3., 200)
U_pts = o1.U(r_pts)
Ucf_pts = o1.Ucf(r_pts)
Ueff_pts = o1.Ueff(r_pts)

ax_2.plot(r_pts, U_pts, linestyle='dashed', color='blue', label='U(r)')
ax_2.plot(r_pts, Ucf_pts, linestyle='dotted', color='green', label='Ucf(r)')
ax_2.plot(r_pts, Ueff_pts, linestyle='solid', color='red', label='Ueff(r)')

ax_2.set_xlim(0., 3.)
ax_2.set_ylim(-5., 5.)
ax_2.set_xlabel('r')
ax_2.set_ylabel('U(r)')
ax_2.set_title(f'$n = {n},\ \ k = {k},\ \  l = {ang_mom}$')
ax_2.legend(loc='upper center')

ax_2.axhline(0., color='black', alpha=0.3)

fig_2.tight_layout()

fig_2.savefig('Gravitation_orbit_1.png')

```

## Orbit (time dependence)

We'll directly solve the equations for r(t) and phi(t).

```python
# Plotting time
t_start = 0.
t_end = 10.
delta_t = 0.01

t_pts = np.arange(t_start, t_end+delta_t, delta_t)

# Initial conditions
r_0 = 1.
r_dot_0 = 0.
phi_0 = 0.0
r_pts, r_dot_pts, phi_pts = o1.solve_ode(t_pts, r_0, r_dot_0, phi_0)

c = o1.ang_mom**2 / (np.abs(o1.k) * o1.mu)
epsilon = c / r_0 - 1.
energy_0 = o1.mu/2. * r_dot_0**2 + o1.Ueff(r_0)
print(f'energy = {energy_0:.2f}')
print(f'eccentricity = {epsilon:.2f}')
```

    energy = -2.50
    eccentricity = -0.67

```python
fig_4 = plt.figure(figsize=(8,8))

overall_title = 'Gravitational orbit:  ' + \
                rf' $n = {o1.n},$' + \
                rf' $k = {o1.k:.1f},$' + \
                rf' $l = {o1.ang_mom:.1f},$' + \
                rf' $r_0 = {r_0:.1f},$' + \
                rf' $\dot r_0 = {r_dot_0:.2f},$' + \
                rf' $\phi_0 = {phi_0:.2f}$' + \
                '\n'     # \n means a new line (adds some space here)
fig_4.suptitle(overall_title, va='baseline')

ax_4a = fig_4.add_subplot(2,2,1)
ax_4a.plot(t_pts, r_pts, color='black')
ax_4a.set_xlabel(r'$t$')
ax_4a.set_ylabel(r'$r$')
ax_4a.set_title('Time dependence of radius')

ax_4b = fig_4.add_subplot(2,2,2)
ax_4b.plot(t_pts, phi_pts/(2.*np.pi), color='black')
ax_4b.plot(t_pts, phi_pts/(2.*np.pi)%1, color='red')
ax_4b.set_xlabel(r'$t$')
ax_4b.set_ylabel(r'$\phi/2\pi$')
ax_4b.set_title(r'Time dependence of $\phi$')

ax_4c = fig_4.add_subplot(2,2,3)
ax_4c.plot(r_pts*np.cos(phi_pts), r_pts*np.sin(phi_pts), color='black')
ax_4c.set_xlabel(r'$x$')
ax_4c.set_ylabel(r'$y$')
ax_4c.set_aspect(1)
ax_4c.set_title('Cartesian plot')

ax_4d = fig_4.add_subplot(2,2,4, polar=True)
ax_4d.plot(phi_pts, r_pts, color='black')
ax_4d.set_title('Polar plot', pad=20.)

fig_4.tight_layout()

```

## Energy versus time

```python
E_tot_pts = o1.energy(t_pts, r_pts, r_dot_pts)
E_tot_0 = E_tot_pts[0]
E_tot_rel_pts = np.abs((E_tot_pts - E_tot_0)/E_tot_0)

print(f'    t        E_tot        rel. error')
for t, E_tot, E_tot_rel in zip(t_pts, E_tot_pts, E_tot_rel_pts):
    print(f'{t:8.5f}  {E_tot:8.5e}  {E_tot_rel:12.4e}')
```

        t        E_tot        rel. error
     0.00000  -2.50000e+00    0.0000e+00
     0.01000  -2.50000e+00    3.9790e-14
     0.02000  -2.50000e+00    5.4987e-11
     0.03000  -2.50000e+00    2.2135e-10
     0.04000  -2.50000e+00    2.8173e-10
     0.05000  -2.50000e+00    1.1803e-10
     0.06000  -2.50000e+00    1.1083e-10
     0.07000  -2.50000e+00    1.6178e-10
     0.08000  -2.50000e+00    5.9066e-12
     0.09000  -2.50000e+00    2.3637e-10
     0.10000  -2.50000e+00    2.2980e-10
     0.11000  -2.50000e+00    5.2911e-11
     0.12000  -2.50000e+00    3.2821e-10
     0.13000  -2.50000e+00    3.1704e-10
     0.14000  -2.50000e+00    5.3087e-11
     0.15000  -2.50000e+00    3.2847e-10
     0.16000  -2.50000e+00    1.5683e-10
     0.17000  -2.50000e+00    3.1309e-10
     0.18000  -2.50000e+00    6.0824e-10
     0.19000  -2.50000e+00    4.6531e-10
     0.20000  -2.50000e+00    2.7574e-10
     0.21000  -2.50000e+00    5.8478e-10
     0.22000  -2.50000e+00    6.9095e-11
     0.23000  -2.50000e+00    7.3493e-10
     0.24000  -2.50000e+00    1.0180e-09
     0.25000  -2.50000e+00    6.7889e-10
     0.26000  -2.50000e+00    7.4282e-10
     0.27000  -2.50000e+00    1.1964e-09
     0.28000  -2.50000e+00    1.0926e-10
     0.29000  -2.50000e+00    1.3503e-09
     0.30000  -2.50000e+00    1.7085e-09
     0.31000  -2.50000e+00    1.2202e-09
     0.32000  -2.50000e+00    1.1001e-09
     0.33000  -2.50000e+00    2.2014e-09
     0.34000  -2.50000e+00    7.6467e-10
     0.35000  -2.50000e+00    1.6446e-09
     0.36000  -2.50000e+00    2.6799e-09
     0.37000  -2.50000e+00    2.2847e-09
     0.38000  -2.50000e+00    1.1544e-09
     0.39000  -2.50000e+00    6.3315e-10
     0.40000  -2.50000e+00    1.7217e-09
     0.41000  -2.50000e+00    1.2599e-09
     0.42000  -2.50000e+00    9.7891e-10
     0.43000  -2.50000e+00    3.4940e-09
     0.44000  -2.50000e+00    6.3028e-09
     0.45000  -2.50000e+00    6.1981e-09
     0.46000  -2.50000e+00    1.8550e-11
     0.47000  -2.50000e+00    1.5321e-09
     0.48000  -2.50000e+00    3.9746e-09
     0.49000  -2.50000e+00    1.3844e-08
     0.50000  -2.50000e+00    6.7878e-09
     0.51000  -2.50000e+00    7.5620e-09
     0.52000  -2.50000e+00    2.2024e-09
     0.53000  -2.50000e+00    2.0306e-08
     0.54000  -2.50000e+00    9.1497e-09
     0.55000  -2.50000e+00    1.4702e-08
     0.56000  -2.50000e+00    4.9144e-09
     0.57000  -2.50000e+00    3.2280e-08
     0.58000  -2.50000e+00    1.7713e-08
     0.59000  -2.50000e+00    1.3007e-09
     0.60000  -2.50000e+00    4.5727e-08
     0.61000  -2.50000e+00    2.7596e-08
     0.62000  -2.50000e+00    3.9705e-09
     0.63000  -2.50000e+00    4.2698e-08
     0.64000  -2.50000e+00    3.9728e-08
     0.65000  -2.50000e+00    7.3398e-08
     0.66000  -2.50000e+00    5.6195e-08
     0.67000  -2.50000e+00    5.6410e-08
     0.68000  -2.50000e+00    5.7140e-08
     0.69000  -2.50000e+00    9.7593e-08
     0.70000  -2.50000e+00    1.0368e-07
     0.71000  -2.50000e+00    1.3296e-07
     0.72000  -2.50000e+00    1.4270e-07
     0.73000  -2.50000e+00    1.3338e-08
     0.74000  -2.50000e+00    8.5372e-08
     0.75000  -2.50000e+00    6.5623e-08
     0.76000  -2.50000e+00    4.5515e-08
     0.77000  -2.50000e+00    2.4944e-08
     0.78000  -2.50000e+00    2.9112e-08
     0.79000  -2.50000e+00    2.8015e-08
     0.80000  -2.50000e+00    2.7105e-08
     0.81000  -2.50000e+00    3.4630e-08
     0.82000  -2.50000e+00    2.7355e-08
     0.83000  -2.50000e+00    3.0149e-08
     0.84000  -2.50000e+00    2.7890e-08
     0.85000  -2.50000e+00    2.7334e-08
     0.86000  -2.50000e+00    2.7351e-08
     0.87000  -2.50000e+00    2.7374e-08
     0.88000  -2.50000e+00    1.7610e-08
     0.89000  -2.50000e+00    2.0992e-08
     0.90000  -2.50000e+00    1.9250e-08
     0.91000  -2.50000e+00    1.9360e-08
     0.92000  -2.50000e+00    1.3625e-08
     0.93000  -2.50000e+00    2.5048e-08
     0.94000  -2.50000e+00    4.7081e-08
     0.95000  -2.50000e+00    5.6086e-08
     0.96000  -2.50000e+00    1.6793e-08
     0.97000  -2.50000e+00    4.7526e-08
     0.98000  -2.50000e+00    1.9778e-07
     0.99000  -2.50000e+00    6.9916e-08
     1.00000  -2.50000e+00    1.6732e-07
     1.01000  -2.50000e+00    5.2693e-08
     1.02000  -2.50000e+00    1.2137e-07
     1.03000  -2.50000e+00    3.1236e-08
     1.04000  -2.50000e+00    7.7547e-08
     1.05000  -2.50000e+00    1.5124e-08
     1.06000  -2.50000e+00    2.7200e-08
     1.07000  -2.50000e+00    7.7435e-08
     1.08000  -2.50000e+00    6.1298e-10
     1.09000  -2.50000e+00    4.0346e-08
     1.10000  -2.50000e+00    6.3235e-08
     1.11000  -2.50000e+00    8.4889e-09
     1.12000  -2.50000e+00    3.2254e-08
     1.13000  -2.50000e+00    6.3292e-08
     1.14000  -2.50000e+00    2.8967e-08
     1.15000  -2.50000e+00    2.0913e-08
     1.16000  -2.50000e+00    4.0171e-08
     1.17000  -2.50000e+00    5.2513e-08
     1.18000  -2.50000e+00    3.1538e-08
     1.19000  -2.50000e+00    2.3640e-08
     1.20000  -2.50000e+00    3.3660e-08
     1.21000  -2.50000e+00    4.1762e-08
     1.22000  -2.50000e+00    3.8491e-08
     1.23000  -2.50000e+00    2.9914e-08
     1.24000  -2.50000e+00    3.0195e-08
     1.25000  -2.50000e+00    3.3949e-08
     1.26000  -2.50000e+00    3.4261e-08
     1.27000  -2.50000e+00    3.3355e-08
     1.28000  -2.50000e+00    3.2417e-08
     1.29000  -2.50000e+00    3.2802e-08
     1.30000  -2.50000e+00    3.3946e-08
     1.31000  -2.50000e+00    3.2889e-08
     1.32000  -2.50000e+00    3.1233e-08
     1.33000  -2.50000e+00    3.1726e-08
     1.34000  -2.50000e+00    3.3295e-08
     1.35000  -2.50000e+00    3.4084e-08
     1.36000  -2.50000e+00    3.3849e-08
     1.37000  -2.50000e+00    3.2396e-08
     1.38000  -2.50000e+00    3.1268e-08
     1.39000  -2.50000e+00    3.2039e-08
     1.40000  -2.50000e+00    3.3392e-08
     1.41000  -2.50000e+00    3.3857e-08
     1.42000  -2.50000e+00    3.3523e-08
     1.43000  -2.50000e+00    3.2700e-08
     1.44000  -2.50000e+00    3.1998e-08
     1.45000  -2.50000e+00    3.2382e-08
     1.46000  -2.50000e+00    3.3104e-08
     1.47000  -2.50000e+00    3.3369e-08
     1.48000  -2.50000e+00    3.3187e-08
     1.49000  -2.50000e+00    3.2882e-08
     1.50000  -2.50000e+00    3.2517e-08
     1.51000  -2.50000e+00    3.2640e-08
     1.52000  -2.50000e+00    3.2904e-08
     1.53000  -2.50000e+00    3.2962e-08
     1.54000  -2.50000e+00    3.2859e-08
     1.55000  -2.50000e+00    3.2776e-08
     1.56000  -2.50000e+00    3.2661e-08
     1.57000  -2.50000e+00    3.2746e-08
     1.58000  -2.50000e+00    3.2818e-08
     1.59000  -2.50000e+00    3.2720e-08
     1.60000  -2.50000e+00    3.2573e-08
     1.61000  -2.50000e+00    3.2537e-08
     1.62000  -2.50000e+00    3.2546e-08
     1.63000  -2.50000e+00    3.2690e-08
     1.64000  -2.50000e+00    3.2753e-08
     1.65000  -2.50000e+00    3.2597e-08
     1.66000  -2.50000e+00    3.2357e-08
     1.67000  -2.50000e+00    3.2272e-08
     1.68000  -2.50000e+00    3.2319e-08
     1.69000  -2.50000e+00    3.2527e-08
     1.70000  -2.50000e+00    3.2663e-08
     1.71000  -2.50000e+00    3.2522e-08
     1.72000  -2.50000e+00    3.2201e-08
     1.73000  -2.50000e+00    3.2008e-08
     1.74000  -2.50000e+00    3.2064e-08
     1.75000  -2.50000e+00    3.2338e-08
     1.76000  -2.50000e+00    3.2560e-08
     1.77000  -2.50000e+00    3.2447e-08
     1.78000  -2.50000e+00    3.2056e-08
     1.79000  -2.50000e+00    3.1750e-08
     1.80000  -2.50000e+00    3.1798e-08
     1.81000  -2.50000e+00    3.2202e-08
     1.82000  -2.50000e+00    3.2517e-08
     1.83000  -2.50000e+00    3.2369e-08
     1.84000  -2.50000e+00    3.1856e-08
     1.85000  -2.50000e+00    3.1451e-08
     1.86000  -2.50000e+00    3.1475e-08
     1.87000  -2.50000e+00    3.2182e-08
     1.88000  -2.50000e+00    3.2698e-08
     1.89000  -2.50000e+00    3.2405e-08
     1.90000  -2.50000e+00    3.1568e-08
     1.91000  -2.50000e+00    3.0994e-08
     1.92000  -2.50000e+00    3.1004e-08
     1.93000  -2.50000e+00    3.2198e-08
     1.94000  -2.50000e+00    3.3304e-08
     1.95000  -2.50000e+00    3.2870e-08
     1.96000  -2.50000e+00    3.1334e-08
     1.97000  -2.50000e+00    3.0217e-08
     1.98000  -2.50000e+00    3.0359e-08
     1.99000  -2.50000e+00    3.1610e-08
     2.00000  -2.50000e+00    3.3888e-08
     2.01000  -2.50000e+00    3.3926e-08
     2.02000  -2.50000e+00    3.1733e-08
     2.03000  -2.50000e+00    2.9509e-08
     2.04000  -2.50000e+00    2.9225e-08
     2.05000  -2.50000e+00    2.9850e-08
     2.06000  -2.50000e+00    3.1941e-08
     2.07000  -2.50000e+00    3.3595e-08
     2.08000  -2.50000e+00    3.3530e-08
     2.09000  -2.50000e+00    3.1867e-08
     2.10000  -2.50000e+00    2.9526e-08
     2.11000  -2.50000e+00    2.8184e-08
     2.12000  -2.50000e+00    2.3643e-08
     2.13000  -2.50000e+00    2.4487e-08
     2.14000  -2.50000e+00    3.3246e-08
     2.15000  -2.50000e+00    3.8018e-08
     2.16000  -2.50000e+00    3.0448e-08
     2.17000  -2.50000e+00    1.9576e-08
     2.18000  -2.50000e+00    7.7364e-09
     2.19000  -2.50000e+00    3.1343e-08
     2.20000  -2.50000e+00    5.0661e-08
     2.21000  -2.50000e+00    3.0210e-08
     2.22000  -2.50000e+00    8.7897e-10
     2.23000  -2.50000e+00    9.8110e-09
     2.24000  -2.50000e+00    5.9056e-08
     2.25000  -2.50000e+00    3.2581e-08
     2.26000  -2.50000e+00    1.5290e-08
     2.27000  -2.50000e+00    2.9248e-08
     2.28000  -2.50000e+00    6.1320e-08
     2.29000  -2.50000e+00    6.8480e-09
     2.30000  -2.50000e+00    1.6326e-08
     2.31000  -2.50000e+00    6.5089e-08
     2.32000  -2.50000e+00    3.9137e-08
     2.33000  -2.50000e+00    7.1257e-08
     2.34000  -2.50000e+00    2.4955e-08
     2.35000  -2.50000e+00    8.5626e-10
     2.36000  -2.50000e+00    4.5732e-08
     2.37000  -2.50000e+00    4.8778e-08
     2.38000  -2.50000e+00    5.6884e-08
     2.39000  -2.50000e+00    1.5361e-07
     2.40000  -2.50000e+00    1.0735e-07
     2.41000  -2.50000e+00    8.0064e-08
     2.42000  -2.50000e+00    3.5351e-08
     2.43000  -2.50000e+00    1.0161e-07
     2.44000  -2.50000e+00    8.4577e-08
     2.45000  -2.50000e+00    6.0056e-08
     2.46000  -2.50000e+00    5.2274e-08
     2.47000  -2.50000e+00    5.0938e-08
     2.48000  -2.50000e+00    6.2101e-08
     2.49000  -2.50000e+00    6.1931e-08
     2.50000  -2.50000e+00    5.2671e-08
     2.51000  -2.50000e+00    5.8963e-08
     2.52000  -2.50000e+00    5.5769e-08
     2.53000  -2.50000e+00    5.4596e-08
     2.54000  -2.50000e+00    5.4316e-08
     2.55000  -2.50000e+00    5.4436e-08
     2.56000  -2.50000e+00    4.7152e-08
     2.57000  -2.50000e+00    5.3584e-08
     2.58000  -2.50000e+00    4.8901e-08
     2.59000  -2.50000e+00    4.8695e-08
     2.60000  -2.50000e+00    4.2748e-08
     2.61000  -2.50000e+00    4.6421e-08
     2.62000  -2.50000e+00    6.7602e-08
     2.63000  -2.50000e+00    8.5912e-08
     2.64000  -2.50000e+00    9.2980e-08
     2.65000  -2.50000e+00    3.6121e-08
     2.66000  -2.50000e+00    1.3545e-08
     2.67000  -2.50000e+00    1.7901e-07
     2.68000  -2.50000e+00    5.8379e-08
     2.69000  -2.50000e+00    1.4583e-07
     2.70000  -2.50000e+00    9.7739e-09
     2.71000  -2.50000e+00    9.2362e-08
     2.72000  -2.50000e+00    4.7697e-08
     2.73000  -2.50000e+00    5.3134e-08
     2.74000  -2.50000e+00    1.0633e-07
     2.75000  -2.50000e+00    2.1245e-08
     2.76000  -2.50000e+00    9.0263e-08
     2.77000  -2.50000e+00    6.9678e-08
     2.78000  -2.50000e+00    3.8731e-08
     2.79000  -2.50000e+00    8.6516e-08
     2.80000  -2.50000e+00    7.6497e-08
     2.81000  -2.50000e+00    3.7827e-08
     2.82000  -2.50000e+00    6.2938e-08
     2.83000  -2.50000e+00    8.8884e-08
     2.84000  -2.50000e+00    5.8786e-08
     2.85000  -2.50000e+00    4.7311e-08
     2.86000  -2.50000e+00    6.2907e-08
     2.87000  -2.50000e+00    7.7886e-08
     2.88000  -2.50000e+00    6.6194e-08
     2.89000  -2.50000e+00    5.2050e-08
     2.90000  -2.50000e+00    5.8859e-08
     2.91000  -2.50000e+00    6.3681e-08
     2.92000  -2.50000e+00    6.5892e-08
     2.93000  -2.50000e+00    6.1549e-08
     2.94000  -2.50000e+00    5.7988e-08
     2.95000  -2.50000e+00    6.0108e-08
     2.96000  -2.50000e+00    6.1357e-08
     2.97000  -2.50000e+00    6.0112e-08
     2.98000  -2.50000e+00    5.9607e-08
     2.99000  -2.50000e+00    6.0247e-08
     3.00000  -2.50000e+00    6.1178e-08
     3.01000  -2.50000e+00    6.1549e-08
     3.02000  -2.50000e+00    6.0272e-08
     3.03000  -2.50000e+00    5.8642e-08
     3.04000  -2.50000e+00    5.9256e-08
     3.05000  -2.50000e+00    6.0884e-08
     3.06000  -2.50000e+00    6.1634e-08
     3.07000  -2.50000e+00    6.1300e-08
     3.08000  -2.50000e+00    6.0203e-08
     3.09000  -2.50000e+00    5.9142e-08
     3.10000  -2.50000e+00    5.9661e-08
     3.11000  -2.50000e+00    6.0768e-08
     3.12000  -2.50000e+00    6.1230e-08
     3.13000  -2.50000e+00    6.0966e-08
     3.14000  -2.50000e+00    6.0455e-08
     3.15000  -2.50000e+00    5.9835e-08
     3.16000  -2.50000e+00    6.0023e-08
     3.17000  -2.50000e+00    6.0531e-08
     3.18000  -2.50000e+00    6.0748e-08
     3.19000  -2.50000e+00    6.0626e-08
     3.20000  -2.50000e+00    6.0462e-08
     3.21000  -2.50000e+00    6.0190e-08
     3.22000  -2.50000e+00    6.0254e-08
     3.23000  -2.50000e+00    6.0416e-08
     3.24000  -2.50000e+00    6.0415e-08
     3.25000  -2.50000e+00    6.0303e-08
     3.26000  -2.50000e+00    6.0257e-08
     3.27000  -2.50000e+00    6.0194e-08
     3.28000  -2.50000e+00    6.0292e-08
     3.29000  -2.50000e+00    6.0360e-08
     3.30000  -2.50000e+00    6.0241e-08
     3.31000  -2.50000e+00    6.0049e-08
     3.32000  -2.50000e+00    5.9990e-08
     3.33000  -2.50000e+00    6.0009e-08
     3.34000  -2.50000e+00    6.0174e-08
     3.35000  -2.50000e+00    6.0285e-08
     3.36000  -2.50000e+00    6.0154e-08
     3.37000  -2.50000e+00    5.9874e-08
     3.38000  -2.50000e+00    5.9722e-08
     3.39000  -2.50000e+00    5.9757e-08
     3.40000  -2.50000e+00    5.9978e-08
     3.41000  -2.50000e+00    6.0175e-08
     3.42000  -2.50000e+00    6.0085e-08
     3.43000  -2.50000e+00    5.9745e-08
     3.44000  -2.50000e+00    5.9471e-08
     3.45000  -2.50000e+00    5.9490e-08
     3.46000  -2.50000e+00    5.9786e-08
     3.47000  -2.50000e+00    6.0076e-08
     3.48000  -2.50000e+00    6.0011e-08
     3.49000  -2.50000e+00    5.9601e-08
     3.50000  -2.50000e+00    5.9215e-08
     3.51000  -2.50000e+00    5.9191e-08
     3.52000  -2.50000e+00    5.9660e-08
     3.53000  -2.50000e+00    6.0089e-08
     3.54000  -2.50000e+00    5.9972e-08
     3.55000  -2.50000e+00    5.9383e-08
     3.56000  -2.50000e+00    5.8874e-08
     3.57000  -2.50000e+00    5.8808e-08
     3.58000  -2.50000e+00    5.9625e-08
     3.59000  -2.50000e+00    6.0431e-08
     3.60000  -2.50000e+00    6.0205e-08
     3.61000  -2.50000e+00    5.9154e-08
     3.62000  -2.50000e+00    5.8305e-08
     3.63000  -2.50000e+00    5.8306e-08
     3.64000  -2.50000e+00    5.9346e-08
     3.65000  -2.50000e+00    6.1067e-08
     3.66000  -2.50000e+00    6.1006e-08
     3.67000  -2.50000e+00    5.9226e-08
     3.68000  -2.50000e+00    5.7506e-08
     3.69000  -2.50000e+00    5.7391e-08
     3.70000  -2.50000e+00    5.8193e-08
     3.71000  -2.50000e+00    6.0881e-08
     3.72000  -2.50000e+00    6.1919e-08
     3.73000  -2.50000e+00    6.0255e-08
     3.74000  -2.50000e+00    5.7623e-08
     3.75000  -2.50000e+00    5.6380e-08
     3.76000  -2.50000e+00    5.6598e-08
     3.77000  -2.50000e+00    5.6131e-08
     3.78000  -2.50000e+00    5.7587e-08
     3.79000  -2.50000e+00    6.1141e-08
     3.80000  -2.50000e+00    6.3594e-08
     3.81000  -2.50000e+00    6.1226e-08
     3.82000  -2.50000e+00    5.5456e-08
     3.83000  -2.50000e+00    4.7893e-08
     3.84000  -2.50000e+00    4.3789e-08
     3.85000  -2.50000e+00    5.9002e-08
     3.86000  -2.50000e+00    7.1211e-08
     3.87000  -2.50000e+00    5.9466e-08
     3.88000  -2.50000e+00    4.1354e-08
     3.89000  -2.50000e+00    2.8806e-08
     3.90000  -2.50000e+00    6.7620e-08
     3.91000  -2.50000e+00    8.0566e-08
     3.92000  -2.50000e+00    5.1742e-08
     3.93000  -2.50000e+00    1.3630e-08
     3.94000  -2.50000e+00    7.1247e-08
     3.95000  -2.50000e+00    8.0001e-08
     3.96000  -2.50000e+00    2.2693e-08
     3.97000  -2.50000e+00    3.6604e-08
     3.98000  -2.50000e+00    9.8836e-08
     3.99000  -2.50000e+00    1.9956e-08
     4.00000  -2.50000e+00    4.7758e-08
     4.01000  -2.50000e+00    8.4422e-08
     4.02000  -2.50000e+00    2.9175e-08
     4.03000  -2.50000e+00    1.2766e-07
     4.04000  -2.50000e+00    1.6392e-08
     4.05000  -2.50000e+00    1.2587e-07
     4.06000  -2.50000e+00    5.0085e-08
     4.07000  -2.50000e+00    1.5348e-07
     4.08000  -2.50000e+00    1.1991e-08
     4.09000  -2.50000e+00    1.9062e-07
     4.10000  -2.50000e+00    5.6156e-08
     4.11000  -2.50000e+00    1.6465e-07
     4.12000  -2.50000e+00    1.2259e-07
     4.13000  -2.50000e+00    1.0069e-07
     4.14000  -2.50000e+00    8.4604e-08
     4.15000  -2.50000e+00    8.2482e-08
     4.16000  -2.50000e+00    7.4524e-08
     4.17000  -2.50000e+00    7.4292e-08
     4.18000  -2.50000e+00    7.6033e-08
     4.19000  -2.50000e+00    9.0746e-08
     4.20000  -2.50000e+00    8.2254e-08
     4.21000  -2.50000e+00    8.1128e-08
     4.22000  -2.50000e+00    8.0049e-08
     4.23000  -2.50000e+00    7.8539e-08
     4.24000  -2.50000e+00    7.6096e-08
     4.25000  -2.50000e+00    8.1505e-08
     4.26000  -2.50000e+00    7.1120e-08
     4.27000  -2.50000e+00    6.9499e-08
     4.28000  -2.50000e+00    7.4395e-08
     4.29000  -2.50000e+00    6.7897e-08
     4.30000  -2.50000e+00    6.8751e-08
     4.31000  -2.50000e+00    7.6092e-08
     4.32000  -2.50000e+00    7.5234e-08
     4.33000  -2.50000e+00    4.8964e-08
     4.34000  -2.50000e+00    4.0390e-08
     4.35000  -2.50000e+00    2.3093e-07
     4.36000  -2.50000e+00    3.9323e-08
     4.37000  -2.50000e+00    2.2789e-07
     4.38000  -2.50000e+00    1.5305e-08
     4.39000  -2.50000e+00    1.7014e-07
     4.40000  -2.50000e+00    2.5406e-08
     4.41000  -2.50000e+00    1.1631e-07
     4.42000  -2.50000e+00    8.4439e-08
     4.43000  -2.50000e+00    7.6683e-08
     4.44000  -2.50000e+00    1.3754e-07
     4.45000  -2.50000e+00    5.4413e-08
     4.46000  -2.50000e+00    8.6950e-08
     4.47000  -2.50000e+00    1.2429e-07
     4.48000  -2.50000e+00    6.3685e-08
     4.49000  -2.50000e+00    8.4141e-08
     4.50000  -2.50000e+00    1.1891e-07
     4.51000  -2.50000e+00    8.9837e-08
     4.52000  -2.50000e+00    7.0062e-08
     4.53000  -2.50000e+00    8.9640e-08
     4.54000  -2.50000e+00    1.0926e-07
     4.55000  -2.50000e+00    9.1241e-08
     4.56000  -2.50000e+00    7.5291e-08
     4.57000  -2.50000e+00    8.6706e-08
     4.58000  -2.50000e+00    9.4338e-08
     4.59000  -2.50000e+00    9.5139e-08
     4.60000  -2.50000e+00    8.6034e-08
     4.61000  -2.50000e+00    8.2484e-08
     4.62000  -2.50000e+00    8.7572e-08
     4.63000  -2.50000e+00    8.8110e-08
     4.64000  -2.50000e+00    8.7567e-08
     4.65000  -2.50000e+00    8.6535e-08
     4.66000  -2.50000e+00    8.6456e-08
     4.67000  -2.50000e+00    8.7507e-08
     4.68000  -2.50000e+00    8.7701e-08
     4.69000  -2.50000e+00    8.5624e-08
     4.70000  -2.50000e+00    8.5193e-08
     4.71000  -2.50000e+00    8.6577e-08
     4.72000  -2.50000e+00    8.7881e-08
     4.73000  -2.50000e+00    8.7927e-08
     4.74000  -2.50000e+00    8.7227e-08
     4.75000  -2.50000e+00    8.5497e-08
     4.76000  -2.50000e+00    8.5501e-08
     4.77000  -2.50000e+00    8.6798e-08
     4.78000  -2.50000e+00    8.7743e-08
     4.79000  -2.50000e+00    8.7613e-08
     4.80000  -2.50000e+00    8.7172e-08
     4.81000  -2.50000e+00    8.6147e-08
     4.82000  -2.50000e+00    8.6086e-08
     4.83000  -2.50000e+00    8.6760e-08
     4.84000  -2.50000e+00    8.7268e-08
     4.85000  -2.50000e+00    8.7221e-08
     4.86000  -2.50000e+00    8.7048e-08
     4.87000  -2.50000e+00    8.6582e-08
     4.88000  -2.50000e+00    8.6504e-08
     4.89000  -2.50000e+00    8.6754e-08
     4.90000  -2.50000e+00    8.6912e-08
     4.91000  -2.50000e+00    8.6847e-08
     4.92000  -2.50000e+00    8.6776e-08
     4.93000  -2.50000e+00    8.6636e-08
     4.94000  -2.50000e+00    8.6647e-08
     4.95000  -2.50000e+00    8.6756e-08
     4.96000  -2.50000e+00    8.6732e-08
     4.97000  -2.50000e+00    8.6573e-08
     4.98000  -2.50000e+00    8.6485e-08
     4.99000  -2.50000e+00    8.6465e-08
     5.00000  -2.50000e+00    8.6564e-08
     5.01000  -2.50000e+00    8.6698e-08
     5.02000  -2.50000e+00    8.6644e-08
     5.03000  -2.50000e+00    8.6406e-08
     5.04000  -2.50000e+00    8.6226e-08
     5.05000  -2.50000e+00    8.6216e-08
     5.06000  -2.50000e+00    8.6363e-08
     5.07000  -2.50000e+00    8.6575e-08
     5.08000  -2.50000e+00    8.6573e-08
     5.09000  -2.50000e+00    8.6302e-08
     5.10000  -2.50000e+00    8.6004e-08
     5.11000  -2.50000e+00    8.5948e-08
     5.12000  -2.50000e+00    8.6133e-08
     5.13000  -2.50000e+00    8.6433e-08
     5.14000  -2.50000e+00    8.6497e-08
     5.15000  -2.50000e+00    8.6201e-08
     5.16000  -2.50000e+00    8.5797e-08
     5.17000  -2.50000e+00    8.5656e-08
     5.18000  -2.50000e+00    8.5928e-08
     5.19000  -2.50000e+00    8.6362e-08
     5.20000  -2.50000e+00    8.6457e-08
     5.21000  -2.50000e+00    8.6063e-08
     5.22000  -2.50000e+00    8.5531e-08
     5.23000  -2.50000e+00    8.5329e-08
     5.24000  -2.50000e+00    8.5738e-08
     5.25000  -2.50000e+00    8.6500e-08
     5.26000  -2.50000e+00    8.6623e-08
     5.27000  -2.50000e+00    8.5942e-08
     5.28000  -2.50000e+00    8.5111e-08
     5.29000  -2.50000e+00    8.4880e-08
     5.30000  -2.50000e+00    8.5378e-08
     5.31000  -2.50000e+00    8.6887e-08
     5.32000  -2.50000e+00    8.7289e-08
     5.33000  -2.50000e+00    8.6110e-08
     5.34000  -2.50000e+00    8.4531e-08
     5.35000  -2.50000e+00    8.4061e-08
     5.36000  -2.50000e+00    8.4478e-08
     5.37000  -2.50000e+00    8.6826e-08
     5.38000  -2.50000e+00    8.8243e-08
     5.39000  -2.50000e+00    8.6998e-08
     5.40000  -2.50000e+00    8.4422e-08
     5.41000  -2.50000e+00    8.2998e-08
     5.42000  -2.50000e+00    8.3415e-08
     5.43000  -2.50000e+00    8.4535e-08
     5.44000  -2.50000e+00    8.6613e-08
     5.45000  -2.50000e+00    8.7680e-08
     5.46000  -2.50000e+00    8.7061e-08
     5.47000  -2.50000e+00    8.4977e-08
     5.48000  -2.50000e+00    8.2544e-08
     5.49000  -2.50000e+00    7.9933e-08
     5.50000  -2.50000e+00    7.5611e-08
     5.51000  -2.50000e+00    8.1800e-08
     5.52000  -2.50000e+00    9.1673e-08
     5.53000  -2.50000e+00    9.0406e-08
     5.54000  -2.50000e+00    8.1118e-08
     5.55000  -2.50000e+00    6.1769e-08
     5.56000  -2.50000e+00    6.8282e-08
     5.57000  -2.50000e+00    1.0044e-07
     5.58000  -2.50000e+00    9.9676e-08
     5.59000  -2.50000e+00    7.6001e-08
     5.60000  -2.50000e+00    4.5122e-08
     5.61000  -2.50000e+00    9.2838e-08
     5.62000  -2.50000e+00    1.1066e-07
     5.63000  -2.50000e+00    6.8832e-08
     5.64000  -2.50000e+00    4.2317e-08
     5.65000  -2.50000e+00    1.2285e-07
     5.66000  -2.50000e+00    8.1349e-08
     5.67000  -2.50000e+00    2.3015e-08
     5.68000  -2.50000e+00    1.3302e-07
     5.69000  -2.50000e+00    7.3488e-08
     5.70000  -2.50000e+00    4.7558e-08
     5.71000  -2.50000e+00    1.2364e-07
     5.72000  -2.50000e+00    1.5586e-08
     5.73000  -2.50000e+00    1.6577e-07
     5.74000  -2.50000e+00    4.1039e-08
     5.75000  -2.50000e+00    1.9640e-07
     5.76000  -2.50000e+00    1.9838e-07
     5.77000  -2.50000e+00    3.4002e-07
     5.78000  -2.50000e+00    2.0176e-07
     5.79000  -2.50000e+00    2.5490e-07
     5.80000  -2.50000e+00    1.3767e-07
     5.81000  -2.50000e+00    9.5106e-08
     5.82000  -2.50000e+00    1.1058e-07
     5.83000  -2.50000e+00    1.1083e-07
     5.84000  -2.50000e+00    1.1331e-07
     5.85000  -2.50000e+00    1.0836e-07
     5.86000  -2.50000e+00    1.0824e-07
     5.87000  -2.50000e+00    1.1711e-07
     5.88000  -2.50000e+00    1.0690e-07
     5.89000  -2.50000e+00    1.0962e-07
     5.90000  -2.50000e+00    1.0842e-07
     5.91000  -2.50000e+00    1.0718e-07
     5.92000  -2.50000e+00    1.0623e-07
     5.93000  -2.50000e+00    1.0892e-07
     5.94000  -2.50000e+00    9.7227e-08
     5.95000  -2.50000e+00    1.0316e-07
     5.96000  -2.50000e+00    9.9106e-08
     5.97000  -2.50000e+00    1.0213e-07
     5.98000  -2.50000e+00    9.1155e-08
     5.99000  -2.50000e+00    9.6039e-08
     6.00000  -2.50000e+00    9.8557e-08
     6.01000  -2.50000e+00    9.0344e-08
     6.02000  -2.50000e+00    4.3953e-08
     6.03000  -2.50000e+00    2.1082e-07
     6.04000  -2.50000e+00    9.8529e-08
     6.05000  -2.50000e+00    1.4329e-07
     6.06000  -2.50000e+00    1.0265e-07
     6.07000  -2.50000e+00    1.4794e-07
     6.08000  -2.50000e+00    9.8400e-08
     6.09000  -2.50000e+00    1.7293e-07
     6.10000  -2.50000e+00    6.9913e-08
     6.11000  -2.50000e+00    1.6921e-07
     6.12000  -2.50000e+00    8.6822e-08
     6.13000  -2.50000e+00    1.0983e-07
     6.14000  -2.50000e+00    1.5670e-07
     6.15000  -2.50000e+00    8.4915e-08
     6.16000  -2.50000e+00    1.1328e-07
     6.17000  -2.50000e+00    1.5071e-07
     6.18000  -2.50000e+00    1.0081e-07
     6.19000  -2.50000e+00    1.0637e-07
     6.20000  -2.50000e+00    1.3476e-07
     6.21000  -2.50000e+00    1.3284e-07
     6.22000  -2.50000e+00    1.0087e-07
     6.23000  -2.50000e+00    1.1023e-07
     6.24000  -2.50000e+00    1.2427e-07
     6.25000  -2.50000e+00    1.2929e-07
     6.26000  -2.50000e+00    1.1312e-07
     6.27000  -2.50000e+00    1.0659e-07
     6.28000  -2.50000e+00    1.1493e-07
     6.29000  -2.50000e+00    1.1832e-07
     6.30000  -2.50000e+00    1.1807e-07
     6.31000  -2.50000e+00    1.1382e-07
     6.32000  -2.50000e+00    1.1226e-07
     6.33000  -2.50000e+00    1.1492e-07
     6.34000  -2.50000e+00    1.1474e-07
     6.35000  -2.50000e+00    1.1338e-07
     6.36000  -2.50000e+00    1.1336e-07
     6.37000  -2.50000e+00    1.1438e-07
     6.38000  -2.50000e+00    1.1523e-07
     6.39000  -2.50000e+00    1.1534e-07
     6.40000  -2.50000e+00    1.1355e-07
     6.41000  -2.50000e+00    1.1241e-07
     6.42000  -2.50000e+00    1.1342e-07
     6.43000  -2.50000e+00    1.1496e-07
     6.44000  -2.50000e+00    1.1539e-07
     6.45000  -2.50000e+00    1.1504e-07
     6.46000  -2.50000e+00    1.1372e-07
     6.47000  -2.50000e+00    1.1301e-07
     6.48000  -2.50000e+00    1.1372e-07
     6.49000  -2.50000e+00    1.1471e-07
     6.50000  -2.50000e+00    1.1496e-07
     6.51000  -2.50000e+00    1.1470e-07
     6.52000  -2.50000e+00    1.1410e-07
     6.53000  -2.50000e+00    1.1367e-07
     6.54000  -2.50000e+00    1.1395e-07
     6.55000  -2.50000e+00    1.1439e-07
     6.56000  -2.50000e+00    1.1450e-07
     6.57000  -2.50000e+00    1.1437e-07
     6.58000  -2.50000e+00    1.1418e-07
     6.59000  -2.50000e+00    1.1400e-07
     6.60000  -2.50000e+00    1.1410e-07
     6.61000  -2.50000e+00    1.1422e-07
     6.62000  -2.50000e+00    1.1417e-07
     6.63000  -2.50000e+00    1.1406e-07
     6.64000  -2.50000e+00    1.1401e-07
     6.65000  -2.50000e+00    1.1399e-07
     6.66000  -2.50000e+00    1.1411e-07
     6.67000  -2.50000e+00    1.1415e-07
     6.68000  -2.50000e+00    1.1399e-07
     6.69000  -2.50000e+00    1.1380e-07
     6.70000  -2.50000e+00    1.1376e-07
     6.71000  -2.50000e+00    1.1381e-07
     6.72000  -2.50000e+00    1.1400e-07
     6.73000  -2.50000e+00    1.1407e-07
     6.74000  -2.50000e+00    1.1389e-07
     6.75000  -2.50000e+00    1.1361e-07
     6.76000  -2.50000e+00    1.1349e-07
     6.77000  -2.50000e+00    1.1356e-07
     6.78000  -2.50000e+00    1.1381e-07
     6.79000  -2.50000e+00    1.1398e-07
     6.80000  -2.50000e+00    1.1382e-07
     6.81000  -2.50000e+00    1.1346e-07
     6.82000  -2.50000e+00    1.1322e-07
     6.83000  -2.50000e+00    1.1330e-07
     6.84000  -2.50000e+00    1.1365e-07
     6.85000  -2.50000e+00    1.1389e-07
     6.86000  -2.50000e+00    1.1374e-07
     6.87000  -2.50000e+00    1.1329e-07
     6.88000  -2.50000e+00    1.1295e-07
     6.89000  -2.50000e+00    1.1302e-07
     6.90000  -2.50000e+00    1.1357e-07
     6.91000  -2.50000e+00    1.1393e-07
     6.92000  -2.50000e+00    1.1368e-07
     6.93000  -2.50000e+00    1.1302e-07
     6.94000  -2.50000e+00    1.1258e-07
     6.95000  -2.50000e+00    1.1264e-07
     6.96000  -2.50000e+00    1.1365e-07
     6.97000  -2.50000e+00    1.1435e-07
     6.98000  -2.50000e+00    1.1388e-07
     6.99000  -2.50000e+00    1.1270e-07
     7.00000  -2.50000e+00    1.1196e-07
     7.01000  -2.50000e+00    1.1207e-07
     7.02000  -2.50000e+00    1.1350e-07
     7.03000  -2.50000e+00    1.1511e-07
     7.04000  -2.50000e+00    1.1466e-07
     7.05000  -2.50000e+00    1.1264e-07
     7.06000  -2.50000e+00    1.1105e-07
     7.07000  -2.50000e+00    1.1119e-07
     7.08000  -2.50000e+00    1.1229e-07
     7.09000  -2.50000e+00    1.1497e-07
     7.10000  -2.50000e+00    1.1563e-07
     7.11000  -2.50000e+00    1.1374e-07
     7.12000  -2.50000e+00    1.1119e-07
     7.13000  -2.50000e+00    1.1013e-07
     7.14000  -2.50000e+00    1.1010e-07
     7.15000  -2.50000e+00    1.0873e-07
     7.16000  -2.50000e+00    1.1059e-07
     7.17000  -2.50000e+00    1.1568e-07
     7.18000  -2.50000e+00    1.1903e-07
     7.19000  -2.50000e+00    1.1549e-07
     7.20000  -2.50000e+00    1.0858e-07
     7.21000  -2.50000e+00    9.8119e-08
     7.22000  -2.50000e+00    9.7341e-08
     7.23000  -2.50000e+00    1.1681e-07
     7.24000  -2.50000e+00    1.2598e-07
     7.25000  -2.50000e+00    1.0950e-07
     7.26000  -2.50000e+00    8.5324e-08
     7.27000  -2.50000e+00    8.8509e-08
     7.28000  -2.50000e+00    1.3315e-07
     7.29000  -2.50000e+00    1.2481e-07
     7.30000  -2.50000e+00    8.7371e-08
     7.31000  -2.50000e+00    7.7959e-08
     7.32000  -2.50000e+00    1.4559e-07
     7.33000  -2.50000e+00    1.1093e-07
     7.34000  -2.50000e+00    5.2873e-08
     7.35000  -2.50000e+00    1.3832e-07
     7.36000  -2.50000e+00    1.1695e-07
     7.37000  -2.50000e+00    3.9745e-08
     7.38000  -2.50000e+00    1.6581e-07
     7.39000  -2.50000e+00    8.8354e-08
     7.40000  -2.50000e+00    1.0189e-07
     7.41000  -2.50000e+00    1.2040e-07
     7.42000  -2.50000e+00    3.7795e-08
     7.43000  -2.50000e+00    1.4592e-07
     7.44000  -2.50000e+00    1.0497e-07
     7.45000  -2.50000e+00    2.5486e-07
     7.46000  -2.50000e+00    1.4444e-07
     7.47000  -2.50000e+00    1.9622e-07
     7.48000  -2.50000e+00    1.8306e-07
     7.49000  -2.50000e+00    8.1022e-08
     7.50000  -2.50000e+00    1.0286e-07
     7.51000  -2.50000e+00    1.3070e-07
     7.52000  -2.50000e+00    1.3467e-07
     7.53000  -2.50000e+00    1.4512e-07
     7.54000  -2.50000e+00    1.4905e-07
     7.55000  -2.50000e+00    1.5009e-07
     7.56000  -2.50000e+00    1.3361e-07
     7.57000  -2.50000e+00    1.3895e-07
     7.58000  -2.50000e+00    1.3535e-07
     7.59000  -2.50000e+00    1.3482e-07
     7.60000  -2.50000e+00    1.3446e-07
     7.61000  -2.50000e+00    1.3305e-07
     7.62000  -2.50000e+00    1.2616e-07
     7.63000  -2.50000e+00    1.3370e-07
     7.64000  -2.50000e+00    1.3283e-07
     7.65000  -2.50000e+00    1.2620e-07
     7.66000  -2.50000e+00    1.3104e-07
     7.67000  -2.50000e+00    1.2004e-07
     7.68000  -2.50000e+00    1.0592e-07
     7.69000  -2.50000e+00    9.5334e-08
     7.70000  -2.50000e+00    9.5560e-08
     7.71000  -2.50000e+00    2.2340e-07
     7.72000  -2.50000e+00    1.2847e-07
     7.73000  -2.50000e+00    1.1394e-07
     7.74000  -2.50000e+00    1.6446e-07
     7.75000  -2.50000e+00    1.1576e-07
     7.76000  -2.50000e+00    1.3988e-07
     7.77000  -2.50000e+00    1.6005e-07
     7.78000  -2.50000e+00    1.2598e-07
     7.79000  -2.50000e+00    1.9848e-07
     7.80000  -2.50000e+00    9.5899e-08
     7.81000  -2.50000e+00    1.7055e-07
     7.82000  -2.50000e+00    1.4890e-07
     7.83000  -2.50000e+00    1.2011e-07
     7.84000  -2.50000e+00    1.7392e-07
     7.85000  -2.50000e+00    1.4884e-07
     7.86000  -2.50000e+00    1.1951e-07
     7.87000  -2.50000e+00    1.5273e-07
     7.88000  -2.50000e+00    1.6809e-07
     7.89000  -2.50000e+00    1.2823e-07
     7.90000  -2.50000e+00    1.3402e-07
     7.91000  -2.50000e+00    1.5307e-07
     7.92000  -2.50000e+00    1.5965e-07
     7.93000  -2.50000e+00    1.3735e-07
     7.94000  -2.50000e+00    1.3188e-07
     7.95000  -2.50000e+00    1.4175e-07
     7.96000  -2.50000e+00    1.4901e-07
     7.97000  -2.50000e+00    1.4630e-07
     7.98000  -2.50000e+00    1.3847e-07
     7.99000  -2.50000e+00    1.3791e-07
     8.00000  -2.50000e+00    1.4194e-07
     8.01000  -2.50000e+00    1.4172e-07
     8.02000  -2.50000e+00    1.4091e-07
     8.03000  -2.50000e+00    1.4042e-07
     8.04000  -2.50000e+00    1.4089e-07
     8.05000  -2.50000e+00    1.4182e-07
     8.06000  -2.50000e+00    1.4138e-07
     8.07000  -2.50000e+00    1.3935e-07
     8.08000  -2.50000e+00    1.3935e-07
     8.09000  -2.50000e+00    1.4091e-07
     8.10000  -2.50000e+00    1.4203e-07
     8.11000  -2.50000e+00    1.4188e-07
     8.12000  -2.50000e+00    1.4098e-07
     8.13000  -2.50000e+00    1.3948e-07
     8.14000  -2.50000e+00    1.3974e-07
     8.15000  -2.50000e+00    1.4102e-07
     8.16000  -2.50000e+00    1.4177e-07
     8.17000  -2.50000e+00    1.4155e-07
     8.18000  -2.50000e+00    1.4106e-07
     8.19000  -2.50000e+00    1.4018e-07
     8.20000  -2.50000e+00    1.4025e-07
     8.21000  -2.50000e+00    1.4089e-07
     8.22000  -2.50000e+00    1.4128e-07
     8.23000  -2.50000e+00    1.4119e-07
     8.24000  -2.50000e+00    1.4101e-07
     8.25000  -2.50000e+00    1.4060e-07
     8.26000  -2.50000e+00    1.4060e-07
     8.27000  -2.50000e+00    1.4083e-07
     8.28000  -2.50000e+00    1.4092e-07
     8.29000  -2.50000e+00    1.4083e-07
     8.30000  -2.50000e+00    1.4078e-07
     8.31000  -2.50000e+00    1.4065e-07
     8.32000  -2.50000e+00    1.4070e-07
     8.33000  -2.50000e+00    1.4080e-07
     8.34000  -2.50000e+00    1.4074e-07
     8.35000  -2.50000e+00    1.4057e-07
     8.36000  -2.50000e+00    1.4049e-07
     8.37000  -2.50000e+00    1.4048e-07
     8.38000  -2.50000e+00    1.4061e-07
     8.39000  -2.50000e+00    1.4073e-07
     8.40000  -2.50000e+00    1.4065e-07
     8.41000  -2.50000e+00    1.4039e-07
     8.42000  -2.50000e+00    1.4023e-07
     8.43000  -2.50000e+00    1.4023e-07
     8.44000  -2.50000e+00    1.4041e-07
     8.45000  -2.50000e+00    1.4062e-07
     8.46000  -2.50000e+00    1.4058e-07
     8.47000  -2.50000e+00    1.4028e-07
     8.48000  -2.50000e+00    1.3999e-07
     8.49000  -2.50000e+00    1.3996e-07
     8.50000  -2.50000e+00    1.4019e-07
     8.51000  -2.50000e+00    1.4049e-07
     8.52000  -2.50000e+00    1.4051e-07
     8.53000  -2.50000e+00    1.4017e-07
     8.54000  -2.50000e+00    1.3977e-07
     8.55000  -2.50000e+00    1.3967e-07
     8.56000  -2.50000e+00    1.4001e-07
     8.57000  -2.50000e+00    1.4044e-07
     8.58000  -2.50000e+00    1.4047e-07
     8.59000  -2.50000e+00    1.4001e-07
     8.60000  -2.50000e+00    1.3948e-07
     8.61000  -2.50000e+00    1.3932e-07
     8.62000  -2.50000e+00    1.3987e-07
     8.63000  -2.50000e+00    1.4065e-07
     8.64000  -2.50000e+00    1.4065e-07
     8.65000  -2.50000e+00    1.3985e-07
     8.66000  -2.50000e+00    1.3901e-07
     8.67000  -2.50000e+00    1.3886e-07
     8.68000  -2.50000e+00    1.3954e-07
     8.69000  -2.50000e+00    1.4112e-07
     8.70000  -2.50000e+00    1.4136e-07
     8.71000  -2.50000e+00    1.3997e-07
     8.72000  -2.50000e+00    1.3835e-07
     8.73000  -2.50000e+00    1.3801e-07
     8.74000  -2.50000e+00    1.3857e-07
     8.75000  -2.50000e+00    1.4108e-07
     8.76000  -2.50000e+00    1.4233e-07
     8.77000  -2.50000e+00    1.4086e-07
     8.78000  -2.50000e+00    1.3824e-07
     8.79000  -2.50000e+00    1.3694e-07
     8.80000  -2.50000e+00    1.3735e-07
     8.81000  -2.50000e+00    1.3827e-07
     8.82000  -2.50000e+00    1.4013e-07
     8.83000  -2.50000e+00    1.4161e-07
     8.84000  -2.50000e+00    1.4162e-07
     8.85000  -2.50000e+00    1.3954e-07
     8.86000  -2.50000e+00    1.3639e-07
     8.87000  -2.50000e+00    1.3242e-07
     8.88000  -2.50000e+00    1.2785e-07
     8.89000  -2.50000e+00    1.3656e-07
     8.90000  -2.50000e+00    1.4775e-07
     8.91000  -2.50000e+00    1.4385e-07
     8.92000  -2.50000e+00    1.3359e-07
     8.93000  -2.50000e+00    1.1128e-07
     8.94000  -2.50000e+00    1.2803e-07
     8.95000  -2.50000e+00    1.6051e-07
     8.96000  -2.50000e+00    1.4652e-07
     8.97000  -2.50000e+00    1.1619e-07
     8.98000  -2.50000e+00    1.0556e-07
     8.99000  -2.50000e+00    1.6465e-07
     9.00000  -2.50000e+00    1.4805e-07
     9.01000  -2.50000e+00    9.4503e-08
     9.02000  -2.50000e+00    1.2903e-07
     9.03000  -2.50000e+00    1.7444e-07
     9.04000  -2.50000e+00    1.0094e-07
     9.05000  -2.50000e+00    1.2456e-07
     9.06000  -2.50000e+00    1.7146e-07
     9.07000  -2.50000e+00    5.9540e-08
     9.08000  -2.50000e+00    1.9369e-07
     9.09000  -2.50000e+00    1.1223e-07
     9.10000  -2.50000e+00    1.4802e-07
     9.11000  -2.50000e+00    1.3704e-07
     9.12000  -2.50000e+00    1.2774e-07
     9.13000  -2.50000e+00    1.3085e-07
     9.14000  -2.50000e+00    1.4010e-07
     9.15000  -2.50000e+00    1.2940e-07
     9.16000  -2.50000e+00    3.0090e-07
     9.17000  -2.50000e+00    7.3464e-08
     9.18000  -2.50000e+00    1.2140e-07
     9.19000  -2.50000e+00    1.3886e-07
     9.20000  -2.50000e+00    1.5753e-07
     9.21000  -2.50000e+00    1.6030e-07
     9.22000  -2.50000e+00    1.6203e-07
     9.23000  -2.50000e+00    1.7146e-07
     9.24000  -2.50000e+00    1.5841e-07
     9.25000  -2.50000e+00    1.6789e-07
     9.26000  -2.50000e+00    1.6274e-07
     9.27000  -2.50000e+00    1.6160e-07
     9.28000  -2.50000e+00    1.6073e-07
     9.29000  -2.50000e+00    1.5890e-07
     9.30000  -2.50000e+00    1.5578e-07
     9.31000  -2.50000e+00    1.6274e-07
     9.32000  -2.50000e+00    1.5563e-07
     9.33000  -2.50000e+00    1.5492e-07
     9.34000  -2.50000e+00    1.5388e-07
     9.35000  -2.50000e+00    1.6004e-07
     9.36000  -2.50000e+00    1.4277e-07
     9.37000  -2.50000e+00    1.2847e-07
     9.38000  -2.50000e+00    1.2121e-07
     9.39000  -2.50000e+00    1.8351e-07
     9.40000  -2.50000e+00    2.5582e-07
     9.41000  -2.50000e+00    5.9566e-08
     9.42000  -2.50000e+00    3.3447e-07
     9.43000  -2.50000e+00    6.1483e-08
     9.44000  -2.50000e+00    2.7579e-07
     9.45000  -2.50000e+00    8.9936e-08
     9.46000  -2.50000e+00    2.3296e-07
     9.47000  -2.50000e+00    1.2553e-07
     9.48000  -2.50000e+00    1.7416e-07
     9.49000  -2.50000e+00    1.9466e-07
     9.50000  -2.50000e+00    1.3765e-07
     9.51000  -2.50000e+00    2.0456e-07
     9.52000  -2.50000e+00    1.6965e-07
     9.53000  -2.50000e+00    1.4960e-07
     9.54000  -2.50000e+00    1.9416e-07
     9.55000  -2.50000e+00    1.8403e-07
     9.56000  -2.50000e+00    1.4577e-07
     9.57000  -2.50000e+00    1.6810e-07
     9.58000  -2.50000e+00    1.9507e-07
     9.59000  -2.50000e+00    1.7152e-07
     9.60000  -2.50000e+00    1.5334e-07
     9.61000  -2.50000e+00    1.6763e-07
     9.62000  -2.50000e+00    1.8179e-07
     9.63000  -2.50000e+00    1.7745e-07
     9.64000  -2.50000e+00    1.6253e-07
     9.65000  -2.50000e+00    1.6297e-07
     9.66000  -2.50000e+00    1.6894e-07
     9.67000  -2.50000e+00    1.7160e-07
     9.68000  -2.50000e+00    1.6987e-07
     9.69000  -2.50000e+00    1.6657e-07
     9.70000  -2.50000e+00    1.6659e-07
     9.71000  -2.50000e+00    1.6886e-07
     9.72000  -2.50000e+00    1.6768e-07
     9.73000  -2.50000e+00    1.6649e-07
     9.74000  -2.50000e+00    1.6698e-07
     9.75000  -2.50000e+00    1.6822e-07
     9.76000  -2.50000e+00    1.6883e-07
     9.77000  -2.50000e+00    1.6864e-07
     9.78000  -2.50000e+00    1.6661e-07
     9.79000  -2.50000e+00    1.6599e-07
     9.80000  -2.50000e+00    1.6727e-07
     9.81000  -2.50000e+00    1.6863e-07
     9.82000  -2.50000e+00    1.6876e-07
     9.83000  -2.50000e+00    1.6836e-07
     9.84000  -2.50000e+00    1.6698e-07
     9.85000  -2.50000e+00    1.6661e-07
     9.86000  -2.50000e+00    1.6743e-07
     9.87000  -2.50000e+00    1.6827e-07
     9.88000  -2.50000e+00    1.6835e-07
     9.89000  -2.50000e+00    1.6813e-07
     9.90000  -2.50000e+00    1.6747e-07
     9.91000  -2.50000e+00    1.6721e-07
     9.92000  -2.50000e+00    1.6754e-07
     9.93000  -2.50000e+00    1.6789e-07
     9.94000  -2.50000e+00    1.6792e-07
     9.95000  -2.50000e+00    1.6780e-07
     9.96000  -2.50000e+00    1.6772e-07
     9.97000  -2.50000e+00    1.6770e-07
     9.98000  -2.50000e+00    1.6775e-07
     9.99000  -2.50000e+00    1.6775e-07
    10.00000  -2.50000e+00    1.6773e-07

```python
fig_5 = plt.figure(figsize=(6,6))

overall_title = 'Gravitational orbit:  ' + \
                rf' $n = {o1.n},$' + \
                rf' $k = {o1.k:.1f},$' + \
                rf' $l = {o1.ang_mom:.1f},$' + \
                rf' $r_0 = {r_0:.1f},$' + \
                rf' $\dot r_0 = {r_dot_0:.2f},$' + \
                rf' $\phi_0 = {phi_0:.2f}$' + \
                '\n'     # \n means a new line (adds some space here)
fig_5.suptitle(overall_title, va='baseline')

ax_5a = fig_5.add_subplot(1,1,1)
ax_5a.semilogy(t_pts, np.abs(E_tot_pts), color='black', label=r'$E(t)$')
ax_5a.semilogy(t_pts, E_tot_rel_pts, color='red', label=r'$\Delta E(t)$')
ax_5a.set_xlabel(r'$t$')
ax_5a.set_ylabel(r'Energy')
ax_5a.set_title('Change in energy with time')
ax_5a.legend(loc='lower right')

fig_5.tight_layout()
```

## Verifying the virial theorem numerically

First a quick calculation with the current orbit:

```python
t_range = t_pts[-1] - t_pts[0]
U_pts = o1.U(r_pts)
T_pts = o1.energy(t_pts, r_pts, r_dot_pts) - U_pts
```

```python
from scipy.integrate import simps
```

```python
T_avg = simps(T_pts, t_pts, delta_t) / t_range
U_avg = simps(U_pts, t_pts, delta_t) / t_range
print(f'<T> = {T_avg:.6f}, <U> = {U_avg:.6f}, n<U>/2 = {o1.n*U_avg/2:.6f}')
```

    <T> = 2.522990, <U> = -5.022990, n<U>/2 = 2.511495

Now a more complete study with different $n$ values and varying integration times:

```python
from scipy.integrate import simps

# For simplicity, set the angular momentum to 1 and k to +2 or -2 with n*k > 0
n_values = (-1, 2, 3, 4, 7)   # different n values to test
t_end_values = (10., 100., 1000.)  # integration max values to test
k_magnitude = 2.

# Time start and spacing
t_start = 0.
delta_t = 0.001

# Initial conditions
r_0 = 1.
r_dot_0 = 0.
phi_0 = 0.0
ang_mom = 1.

print(f' n    t_end     <T>        <U>        n<U>/2     |<T>-n<U>/2|/<T>')
for n in n_values:
    k = np.sign(n) * k_magnitude   # ensure that n*k > 0
    o_now = Orbit(ang_mom, n=n, k=k, mu=1.)  # current orbit
    for t_end in t_end_values:
        t_pts = np.arange(t_start, t_end+delta_t, delta_t)
        r_pts, r_dot_pts, phi_pts = o_now.solve_ode(t_pts, r_0,
                                                    r_dot_0, phi_0)

        t_range = t_pts[-1] - t_pts[0]
        # Generate the integrands to be averaged
        U_pts = o_now.U(r_pts)
        T_pts = o_now.energy(t_pts, r_pts, r_dot_pts) - U_pts
        # Calculate the time averages from 0 to t_end
        T_avg = simps(T_pts, t_pts, delta_t) / t_range
        U_avg = simps(U_pts, t_pts, delta_t) / t_range

        rel_error = np.fabs((T_avg - n*U_avg/2.) / T_avg)
        print(f'{n:2.0f}   {t_end:5.0f}   {T_avg:9.6f}  {U_avg:9.6f} ',
              f' {n*U_avg/2.:9.6f}       {rel_error:9.3e}')
```

     n    t_end     <T>        <U>        n<U>/2     |<T>-n<U>/2|/<T>
    -1      10    1.468564  -2.968564    1.484282       1.070e-02
    -1     100    1.494275  -2.994275    1.497137       1.915e-03
    -1    1000    1.499964  -2.999961    1.499981       1.099e-05
     2      10    1.236029   1.263971    1.263971       2.261e-02
     2     100    1.251595   1.248404    1.248404       2.550e-03
     2    1000    1.250122   1.249865    1.249865       2.050e-04
     3      10    1.512491   0.987509    1.481264       2.065e-02
     3     100    1.498214   1.001784    1.502676       2.978e-03
     3    1000    1.500149   0.999830    1.499745       2.695e-04
     4      10    1.665613   0.834386    1.668773       1.897e-03
     4     100    1.668070   0.831928    1.663856       2.526e-03
     4    1000    1.666827   0.833147    1.666294       3.196e-04
     7      10    1.954318   0.545682    1.909887       2.273e-02
     7     100    1.943101   0.556897    1.949141       3.109e-03
     7    1000    1.944342   0.555637    1.944730       1.996e-04

```python

```


# INF-510, v0.32, Claudio Torres, ctorres@inf.utfsm.cl. DI-UTFSM
## Textbook: Lloyd N. Trefethen, Spectral Methods in MATLAB, SIAM, Philadelphia, 2000

# More on Spectral Matrices

```python
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import scipy.sparse.linalg as sp
from sympy import *
import sympy as sym
from scipy.linalg import toeplitz
# The variable M is used for changing the default size of the figures
M=8
import ipywidgets as widgets
import matplotlib as mpl
mpl.rcParams['font.size'] = 14
mpl.rcParams['axes.labelsize'] = 20
mpl.rcParams['xtick.labelsize'] = 14
mpl.rcParams['ytick.labelsize'] = 14
sym.init_printing()

def plot_matrices_with_values(ax,M):
    N=M.shape[0]
    cmap = plt.get_cmap('GnBu')
    ax.matshow(M, cmap=cmap)
    for i in np.arange(0, N):
        for j in np.arange(0, N):
            ax.text(i, j, '{:.2f}'.format(M[i,j]), va='center', ha='center', color='r')
```

## "The magical and beautiful sinc function" by ?

```python
def Sh(x,h):
    if np.abs(x)<=1e-10:
        return 1.0
    else:
        y=np.pi*x/h
        return np.sin(y)/y
Shv = np.vectorize(Sh)
```

```python
N=10
h=2/N
x=np.linspace(-1,1,1e4)

xx=np.linspace(-1,1,N+1)
yy=np.zeros(N+1)
yy[int(N/2)]=1

plt.figure(figsize=(M,M))
plt.plot(x,Shv(x,h),'-',linewidth=3)
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)
plt.title('$S_h(x)=\sin(\pi\,x/h)/(\pi\,x/h)$',fontsize=20)
plt.show()
```

## Just interpolating a few functions

```python
def Interpolate_with_Sh(xx,h,N,yy,x):
    out=np.zeros(x.shape[0])
    for i in np.arange(N+1):
        out+=yy[i]*Shv(x-xx[i],h)
    return out
```

```python
N=20
h=2./N
# Variable for plotting 'continuously'
x=np.linspace(-1,1,1e4)
# Creating the hZ mesh
xx=np.linspace(-1,1,N+1)
# Creating some grid functions
yy1=1.*(np.abs(xx)<=0.3)
yy2=(1.0-np.abs(xx)/0.3)*(1.*(1.0-np.abs(xx)/0.3>=0))
```

```python
plt.figure(figsize=(M,M))

plt.subplot(211)
yy=yy1
plt.plot(x,Interpolate_with_Sh(xx,h,N,yy,x),'-',linewidth=3)
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(212)
yy=yy2
plt.plot(x,Interpolate_with_Sh(xx,h,N,yy,x),'-',linewidth=3)
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)
plt.show()
```

## Band limited interpolant

```python
def ShBL(x,h):
    # Why do I need to do this?
    if np.abs(x)<=1e-10:
        return 1.0+(-(1./12.)-np.pi**2/(6.*h**2))*x**2
    elif np.abs(x-2*np.pi)<=1e-10:
        return 1.0+(-(1./12.)-np.pi**2/(6.*h**2))*(x-2*np.pi)**2
    else:
        y=np.pi*x/h
        return np.sin(y)/((2*np.pi/h)*np.tan(x/2))
ShBLv = np.vectorize(ShBL)

def Interpolate_with_ShBL(xx,h,N,yy,x):
    out=np.zeros(x.shape[0])
    for i in np.arange(N):
        out+=yy[i]*ShBLv(x-xx[i],h)
    return out
```

```python
N=10
h=2*np.pi/N
x=np.linspace(0-h,2*np.pi+h,1e4)

xx=np.linspace(0,2*np.pi,N+1)
yy=np.zeros(N+1)
yy[0]=1
yy[-1]=1

fig, ax = plt.subplots(figsize=(M,M))
ax.plot(x,ShBLv(x,h),'-',linewidth=3)
ax.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
ax.grid(True)
plt.xlim([0-h,2*np.pi+h])
plt.ylim([-0.4,1.2])
plt.title('$S_h(x) = \sin(\pi\,x/h)/((2\,\pi/h)\,\\tan(x/2))$',fontsize=20)
ax.fill_between(x, -0.4, 1.2, where=(x < 0.0), facecolor='green', alpha=0.5)
ax.fill_between(x, -0.4, 1.2, where=(x > 2*np.pi), facecolor='green', alpha=0.5)
plt.show()
```

```python
def my_D_spec(N):
    h=(2./N)*np.pi
    c=np.zeros(N)
    j=np.arange(1,N)
    c[1:]=0.5*((-1)**j)*(np.tan(j*h/2.)**(-1))
    r=np.zeros(N)
    r[0]=c[0]
    r[1:]=c[-1:0:-1]
    D=np.pi*toeplitz(c,r=r)
    return D

# This is almost the same as the previous notebook but with a 2*np.pi coefficient removed (Why?!).
def my_D_spec_2pi(N):
    h=(2./N)*np.pi
    c=np.zeros(N)
    j=np.arange(1,N)
    c[1:]=0.5*((-1)**j)*(np.tan(j*h/2.)**(-1))
    r=np.zeros(N)
    r[0]=c[0]
    r[1:]=c[-1:0:-1]
    D=toeplitz(c,r=r)
    return D
```

## Spectral derivative again

```python
N=24
h=2.*np.pi/N
# Variable for plotting 'continuously'
x=np.linspace(0,2*np.pi,1e4)
# Creating the hZ mesh
xx=np.linspace(0,2*np.pi,N+1)[1:]
# Creating the grid functions
yy0=1.0-np.abs(xx-np.pi)/2
yy1=(yy0)*(1.*(yy0>=0))
yy2=np.exp(np.sin(xx))

D=my_D_spec_2pi(N)

plt.figure(figsize=(M,M))

plt.subplot(221)
yy=yy1
plt.plot(x,Interpolate_with_ShBL(xx,h,N,yy,x),'-',linewidth=3)
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(222)
plt.plot(xx,np.dot(D,yy),'kx-',markersize=16,markeredgewidth=3,linewidth=3)
plt.grid(True)

plt.subplot(223)
yy=yy2
plt.plot(x,Interpolate_with_ShBL(xx,h,N,yy,x),'-',linewidth=3)
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(224)
plt.plot(xx,np.dot(D,yy),'kx-',markersize=16,markeredgewidth=3,linewidth=3)
error_max=np.max(np.abs(yy*np.cos(xx)-np.dot(D,yy)))
plt.title('max error='+str(error_max))
plt.grid(True)

plt.show()
```

## Using FFT for the same task!

```python
N=10
K=np.fft.fftfreq(N)*N
print(K)
```

    [ 0.  1.  2.  3.  4. -5. -4. -3. -2. -1.]

```python
def my_first_implementation_of_derivative_with_FFT(yy):
    N=yy.shape[0]
    # Frequencies of fft
    K=np.fft.fftfreq(N)*N
    # i*K
    iK=1j*K
    # FFT
    v_hat = np.fft.fft(yy)
    # The actual derivative in Fourier space!
    w_hat = iK*v_hat
    # Taking care of the loss of symmetry
    w_hat[int(N/2)]=0
    # Coming back to the physical space
    ww    = np.real(np.fft.ifft(w_hat))
```

```python
N=24
h=2.*np.pi/N
# Variable for plotting 'continuously'
x=np.linspace(0,2*np.pi,1e4)
# Creating the hZ mesh
xx=np.linspace(2*np.pi/N,2*np.pi,N)
# Creating the grid functions
yy0=1.0-np.abs(xx-np.pi)/2
yy1=(yy0)*(1.*(yy0>=0))
yy2=np.exp(np.sin(xx))

# Pre-computing the wave numbers in np.fft.fft
# K=1j*np.hstack((np.arange(0,N/2+1), np.arange(-N/2+1,0)))
K=np.fft.fftfreq(N)*N
iK=1j*K

plt.figure(figsize=(M,M))

plt.subplot(221)
yy=yy1
plt.plot(x,Interpolate_with_ShBL(xx,h,N,yy,x),'-.')
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(222)
# Begin derivative by DFT, i.e. FFT!
v_hat = np.fft.fft(yy)
w_hat = iK*v_hat
w_hat[int(N/2)]=0
ww    = np.real(np.fft.ifft(w_hat))
# End derivative by DFT, i.e. FFT!
plt.plot(xx,ww,'kx-',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(223)
yy=yy2
plt.plot(x,Interpolate_with_ShBL(xx,h,N,yy,x),'-.')
plt.plot(xx,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(224)
# Begin derivative by DFT, i.e. FFT!
v_hat = np.fft.fft(yy)
w_hat = iK*v_hat
w_hat[int(N/2)]=0
ww    = np.real(np.fft.ifft(w_hat))
# Begin derivative by DFT, i.e. FFT!
plt.plot(xx,ww,'kx-',markersize=16,markeredgewidth=3)
error_max=np.max(np.abs(yy*np.cos(xx)-ww))
plt.title('max error='+str(error_max))
plt.grid(True)

plt.show()
```

# Chebyshev differentiation matrix

```python
def cheb(N):
    if N==0:
        D=0
        x=1
        return D,x
    x = np.cos(np.pi*np.arange(N+1)/N)
    c=np.hstack((2,np.ones(N-1),2))*((-1.)**np.arange(N+1))
    X=np.tile(x,(N+1,1)).T
    dX=X-X.T
    D = np.outer(c,1./c)/(dX+np.eye(N+1))
    D = D - np.diag(np.sum(D.T,axis=0))
    return D,x
def show_cheb(N):
    D,x=cheb(N)
    print(x)
    # We multiply by h just to cancel out its dependency
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(2*M,M))
    # First derivative
    plot_matrices_with_values(ax1,D)
    # 'Second' derivative
    plot_matrices_with_values(ax2,np.dot(D,D))
    plt.show()

widgets.interact(show_cheb,N=(0,10,1))
```

## Chebyshev differentiation

```python
# Variable for plotting 'continuously'
x=np.linspace(-1,1,1e4)
# The function we will be studying
u= lambda x: np.exp(x)*np.sin(5*x)
# We just computed the derivative by hand
up= lambda x: np.exp(x)*(np.sin(5*x)+np.cos(5*x)*5)

plt.figure(figsize=(2*M,2*M))

N=10
DCheb,xCheb=cheb(N)
# Creating the grid functions
yy=u(xCheb)

plt.subplot(221)
plt.plot(x,u(x),'-')
plt.plot(xCheb,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(222)
plt.plot(xCheb,np.dot(DCheb,yy)-up(xCheb),'kx-',markersize=16,markeredgewidth=3)
error_max=np.max(np.abs(np.dot(DCheb,yy)-up(xCheb)))
plt.title('max error='+str(error_max))
plt.grid(True)

N=20
DCheb,xCheb=cheb(N)
# Creating the grid functions
yy=u(xCheb)

plt.subplot(223)
plt.plot(x,u(x),'-')
plt.plot(xCheb,yy,'kx',markersize=16,markeredgewidth=3)
plt.grid(True)

plt.subplot(224)
plt.plot(xCheb,np.dot(DCheb,yy)-up(xCheb),'kx-',markersize=16,markeredgewidth=3)
error_max=np.max(np.abs(np.dot(DCheb,yy)-up(xCheb)))
plt.title('max error='+str(error_max))
plt.grid(True)

plt.show()
```

# In-class work

## Implement Program 6, 7 and 12

```python

```


## First Assignment

#### 1) Apply the appropriate string methods to the **x** variable (as '.upper') to change it exactly to: "$Dichlorodiphenyltrichloroethane$".

```python
x = "DiClOrod  IFeNi  lTRicLOr oETaNo  DiChlorod iPHeny lTrichL oroEThaNe"
```

```python
x = "DiClOrod  IFeNi  lTRicLOr oETaNo  DiChlorod iPHeny lTrichL oroEThaNe"
x.replace(' ','')[27:].title()
```

    'Dichlorodiphenyltrichloroethane'

#### 2) Assign respectively the values: 'word', 15, 3.14 and 'list' to variables A, B, C and D in a single line of code. Then, print them in that same order on a single line separated by a space, using only one print statement.

```python
A,B,C,D='word', 15, 3.14, 'list'
print(A,B,C,D)
```

    word 15 3.14 list

#### 3) Use the **input()** function to receive an input in the form **'68.4 1.71'**, that is, two floating point numbers in a line separated by space. Then, assign these numbers to the variables **w** and **h** respectively, which represent an individual's weight and height (hint: take a look at the '.split()' method). With this data, calculate the individual's Body Mass Index (BMI) from the following relationship:

\begin{equation}
BMI = \dfrac{weight}{height^2}
\end{equation}

```python
x= input("enter height and weight separated by space ")

```

    enter height and weight separated by space 1.71 68.4

```python
x.split(' ')
```

    ['1.71', '68.4', '']

```python
y=x.split(' ')
y
```

    ['1.71', '68.4', '']

```python
height= float(y[0])
height
```

    1.71

```python
weight= float(y[1])
weight
```

    68.4

```python
BMI= weight/height**2
BMI
```

    23.39181286549708

#### This value can also be classified according to ranges of values, following to the table below. Use conditional structures to classify and print the classification assigned to the individual.

<\center>

(source: https://healthtravelguide.com/bmi-calculator/)

```python
if BMI<18.5:
  print ('Underweight')
elif BMI<24.9:
  print ('Normal Weight')
elif BMI<29.9:
  print ('Pre-Obisity')
elif BMI<34.9:
  print ('ObisityI')
elif BMI<39.9:
  print ('ObisityII')
else:
  print ('ObisityIII')
```

    Normal Weight

#### 4) Receive an integer as an input and, using a loop, calculate the factorial of this number, that is, the product of all the integers from one to the number provided.

```python
num = int(input("Enter the number:"))
fact = 1

for i in range(1,num+1):
    fact = fact * i

print ("The factorial of 23 is : ",end="")
print (fact)
```

    Enter the number:23
    The factorial of 23 is : 25852016738884976640000

#### 5) Using a while loop and the input function, read an indefinite number of integers until the number read is -1. Present the sum of all these numbers in the form of a print, excluding the -1 read at the end.

```python
x = input("Any integer except -1")
while x!=-1:
    inp = input("Insert input: ")
    if inp == -1:
        break
    inputs.append(inp)

print (inputs)
```

#### 6) Read the **first name** of an employee, his **amount of hours worked** and the **salary per hour** in a single line separated by commas. Next, calculate the **total salary** for this employee and show it to two decimal places.

```python
response = input("Please enter your first name, the amount of working hours and the salary per hour ")
```

    Please enter your first name, the amount of working hours and the salary per hour George 40 13

```python
response = response.split()
response
```

    ['George', '40', '13']

```python
total_salary = int(response[1]) * int(response[2]) * 30.00
total_salary
```

    15600.0

#### 7) Read three floating point values **A**, **B** and **C** respectively. Then calculate itens a, b, c, d and e:

```python
response = input("please enter numbers A, B and C")
```

    please enter numbers A, B and C 6 7 9

```python
response = response.split()
response
```

    ['6', '7', '9']

```python
response[0]
```

    '6'

```python
response[1]
```

    '7'

```python
response[2]
```

    '9'

    a) the area of the triangle rectangle with A as the base and C as the height.

```python
area = 0.5 * int(response[0]) * int(response[1])
area
```

    21.0

    b) the area of the circle of radius C. (pi = 3.14159)

```python
radius = int(response[2])/2*3.14159
radius
```

    14.137155

    c) the area of the trapezoid that has A and B for bases and C for height.

```python
area_trapezoid = (int(response[0])+int(response[1])/2)* int(response[2])
area_trapezoid
```

    85.5

    d) the area of the square that has side B.

```python
area_square = int(response[1]) * 2
area_square
```

    14

    e) the area of the rectangle that has sides A and B.

```python
area_rectangle = int(response[0]) * int(response[1])
area_rectangle
```

    42

#### 8) Read **the values a, b and c** and calculate the **roots of the second degree equation** $ax^{2}+bx+c=0$ using [this formula](https://en.wikipedia.org/wiki/Quadratic_equation). If it is not possible to calculate the roots, display the message **“There are no real roots”**.

```python
print("Equation: ax^2 + bx + c ")
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
d=b**2-4*a*c
d1=d**0.5
if(d<0):
    print("There are no real roots. ")
else:
    r1=(-b+d1)/2*a
    r2=(-b-d1)/2*a
    print("The first root: ")
    print("The second root: ")
```

    Equation: ax^2 + bx + c
    Enter a: 4
    Enter b: 3
    Enter c: 4
    There are no real roots.

#### 9) Read four floating point numerical values corresponding to the coordinates of two geographical coordinates in the cartesian plane. Each point will come in a line with its coordinates separated by space. Then calculate and show the distance between these two points.

(obs: $d=\sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}$)

```python
geo_coordinates1 = {"x1":'41.035', "x2":'24.649'}

```

```python
geo_coordinates2 = {'y1':'37.971', 'y2':'23.725'}

```

```python
geo_coordinates1 = {"x1":'41.035', "x2":'24.649'}
geo_coordinates2 = {'y1':'37.971', 'y2':'23.725'}

x1, x2 = 41.035,24.649
y1, y2 = 37.971, 23.725

result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)

print("distance between",(x1,x2),"and",(y1,y2),"is : ", result)
```

    distance between (41.035, 24.649) and (37.971, 23.725) is :  21.712888154273713

#### 10) Read **two floating point numbers** on a line that represent **coordinates of a cartesian point**. With this, use **conditional structures** to determine if you are at the origin, printing the message **'origin'**; in one of the axes, printing **'x axis'** or **'y axis'**; or in one of the four quadrants, printing **'q1'**, **'q2**', **'q3'** or **'q4'**.

```python
x, y = float(input("A floating point number x")), float(input("A floating point number y"))

```

```python
if (x > 0 and y > 0):
        print ("lies in First quadrant")
    elif (x < 0 and y > 0)
        print ("lies in Second quadrant")

    elif (x < 0 and y < 0)
        print ("lies in Third quadrant")

    elif (x > 0 and y < 0)
        print ("lies in Fourth quadrant")

    elif (x == 0 and y > 0)
        print ("lies at positive y axis")

    elif (x == 0 and y < 0)
        print ("lies at negative y axis")

    elif (y == 0 and x < 0)
        print ("lies at negative x axis")

    elif (y == 0 and x > 0)
        print ("lies at positive x axis")

    else
        print ("lies at origin")
```

#### 11) Read an integer that represents a phone code for international dialing.
#### Then, inform to which country the code belongs to, considering the generated table below:
(You just need to consider the first 10 entries)

```python
import pandas as pd
df = pd.read_html('https://en.wikipedia.org/wiki/Telephone_numbers_in_Europe')[1]
df = df.iloc[:,:2]
df.head(20)
```

      Country
      Country calling code

      0
      Austria
      43

      1
      Belgium
      32

      2
      Bulgaria
      359

      3
      Croatia
      385

      4
      Cyprus
      357

      5
      Czech Republic
      420

      6
      Denmark
      45

      7
      Estonia
      372

      8
      Finland
      358

      9
      France
      33

      10
      Germany
      49

      11
      Greece
      30

      12
      Hungary
      36

      13
      Iceland
      354

      14
      Ireland
      353

      15
      Italy
      39

      16
      Latvia
      371

      17
      Liechtenstein
      423

      18
      Lithuania
      370

      19
      Luxembourg
      352

```python
codes = {"43":'Austria', "32":'Belgium', "359":'Bulgaria', "385":'Croatia',	"357":'Cyprus', "420":'Czech Republic', "45":'Denmark', "372":'Estonia',	"358":'Finland', "33":'France'}

my_code= input("What is your code?")

```

    What is your code?43

```python
codes[my_code]

```

    'Austria'

#### 12) Write a piece of code that reads 6 numbers in a row. Next, show the number of positive values entered. On the next line, print the average of the values to one decimal place.

```python
list= [int(input("Add a number")), int(input("Add a number")), int(input("Add a number")), int(input("Add a number")), int(input("Add a number")), int(input("Add a number"))]

pos_count= 0

for num in list:

    if num >= 0:
        pos_count += 1
    print("Positive numbers in the list: ", pos_count)

avg = sum(list)/len(list)
print("The average is ", round(avg,2))

```

    Add a number7
    Add a number7
    Add a number8
    Add a number9
    Add a number4
    Add a number2
    Positive numbers in the list:  1
    Positive numbers in the list:  2
    Positive numbers in the list:  3
    Positive numbers in the list:  4
    Positive numbers in the list:  5
    Positive numbers in the list:  6
    The average is  6.17

#### 13) Read an integer **N**. Then print the **square of each of the even values**, from 1 to N, including N, if applicable, arranged one per line.

```python
n = int(input("Add a number"))
for int in range [1:n]:
    square = n**2
    print ('The square of the number'int'is {square})
```

#### 14) Using **input()**, read an integer and print its classification as **'even / odd'** and **'positive / negative'** . The two classes for the number must be printed on the same line separated by a space. In the case of zero, print only **'null'**.

```python
num = int(input())

if num == 0:
   print("Null")

if num > 0:
  if (num % 2) == 0:
   print("{0} is Positive Even".format(num))
  else:
    print("{0} is Positive Odd".format(num))

if (num % 2) == 0:
   print("{0} is Negative Even".format(num))
elif (num % 2) !=0:
     print: ("is Negative Odd".format(num))
```

    23
    23 is Positive Odd

## Challenge
#### 15) Ordering problems are recurrent in the history of programming. Over time, several algorithms have been developed to fulfill this function. The simplest of these algorithms is the [**Bubble Sort**](https://en.wikipedia.org/wiki/Bubble_sort), which is based on comparisons of elements two by two in a loop of passes through the elements. Your mission, if you decide to accept it, will be to input six whole numbers ramdonly ordered. Then implement the **Bubble Sort** principle to order these six numbers **using only loops and conditionals**.
#### At the end, print the six numbers in ascending order on a single line separated by spaces.

```python

```


Jacobian Determinant Part 2
---------------------------
For mapping $F: [0,1] \times [-1,1] -> S_2$

```python
from sympy import *
import sympy
print(sympy.__version__)
```

```python
from IPython.display import display
```

```python
import numpy as np
```

```python
u, v = Symbol('u'), Symbol('v')
```

```python
rx = sympy.cos(u*sympy.pi*2)
ry = sympy.sin(u*sympy.pi*2)
r = sympy.sqrt(1 - v*v)
x = rx*r
y = ry*r
z = v
```

```python
display(x,y,z)
```

```python
DF = np.zeros((3,2), np.object)
for i, a in enumerate([x, y, z]):
    for j, b in enumerate([u, v]):
        DF[i,j] = simplify(diff(a, b))
DF = Matrix(DF)
DF
```

```python
DF.T
```

```python
J = sqrt((DF.T*DF).det())
```

```python
J
```

```python
J = simplify(J) # WTF
J # As expected though, J is constant
```

```python
# Now for the affine trafo from [0, 1] -> [-1, 1]
# DF = diag(2)
# -> DF.T*DF = diag(4)
# -> sqrt(DF.T*DF).det() = 4
```


#  Taylor problem 5.50

last revised: 21-Jan-2019 by Dick Furnstahl [furnstahl.1@osu.edu]

Here we are exploring the Fourier series for a waveform defined to be odd about the origin, so $f(-t) = -f(t)$, with period $\tau$.  That means that the integrand for the $a_m$ coefficients is odd and so all of the corresponding integrals vanish.

The particular wave of interest here is a sawtooth, such that in the interval $-\tau/2 \leq t \leq \tau/2$, the function takes the form:

$\newcommand{\fmax}{f_{\textrm{max}}}$
$\begin{align}
  f(t) = \left\{ \begin{array}{ll}
                   \fmax(t/\tau) & t < 0 \\
                   \fmax(t/\tau) & t > 0
                 \end{array}
                   \right.
\end{align}$

(we wrote it this way so it looks like the function for problem 5.49).

As already note, the $a_m$ coefficients are zero, so we only calculate the $b_m$ coefficients.  Here $\omega \equiv 2\pi/\tau$.  The result is:

$\begin{align}
  b_m = \frac{2}{\tau} \int_{-\tau/2}^{\tau/2} \sin(m\omega t) f(t)\, dt =
     % 2 \fmax \int_0^1 \sin(m\pi t) t\, dt
    %  &= - \frac{2\fmax}{(m\pi)^2)}\left[\sin(m\pi t)\right]^1_0 \\
     % =
      \left\{
      \begin{array}{ll}
        -\frac{ \fmax}{m\pi} & [m\ \mbox{even}] \\
        \frac{ \fmax}{m\pi} & [m\ \mbox{odd}]
      \end{array}
      \right.
\end{align}$

Note that the coefficients are independent of $\tau$.  Is this a general result?

## Define the functions we'll need

```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
```

We start by defining a function for the sawtooth wave at any $t$.  The definition here is for a scalar function.  That is, it won't work to call it with $t$ and array of time points, unlike other functions we have defined.  It is possible to make it work, but then the function will be much less clear.  When we need to evaluate it for all elements of an array, we will use the construction: `np.array([sawtooth(t) for t in t_pts])` for the array `t_pts`.

```python
def sawtooth(t, tau, f_max=1):
    """Returns the sawtooth wave of amplitude f_max and odd about the
        origin at time t.  The period is tau.  It is defined as a scalar
        function (i.e., only one value of t can be passed at a time).
    """
    if np.floor(t) % 2 == 0:
        t_adjust = t - np.floor(t)
        return t_adjust / tau
    else:
        t_adjust = t - (np.floor(t) + 1)
        return t_adjust / tau

```

Now a function that creates an array of Fourier coefficients for the sawtooth wave up to order N_max.

```python
def sawtooth_coeffs_by_hand(N_max, tau=2., f_max=1.):
    """Fourier coefficients calculated by hand and loaded into an array.
        Note that these are independent of tau, but we pass it for
        consistency with other functions.
    """
    coeffs_array = [(0., 0.)]   # a_0 and b_0
    for n in np.arange(1, N_max, 1):
        if (n % 2) == 0:    # for even n
            b_n = -f_max / (n * np.pi)
        else:          # for odd n
            b_n = f_max / (n * np.pi)
        a_n = 0.
        coeffs_array.append((a_n, b_n))

    return np.array(coeffs_array)  # convert to a numpy array
```

We would like a general way to construct the away of Fourier coefficients given any periodic function.  Our first pass at that uses a class definition and the scipy integration function quad.

```python
class FourierSeries():
    """
    Fourier series class finds the coefficients in a Fourier series with
    period tau up to a specified order.
    Assume these imports:
        from scipy.integrate import quad
        import numpy as np
    """
    def __init__(self,
                 function,
                 tau=2,
                 N_max=10
                ):
        self.function = function
        self.tau = tau
        self.omega = 2. * np.pi / tau
        self.N_max = N_max
        # add something to quit if Nmax < 0 or not an integer (try and except)

    def a0_calc(self):
        """Calculate the constant Fourier coefficient by integration"""
        answer, error = quad(self.function, -tau/2., tau/2., args=(tau,))
        return (1./self.tau) * answer

    def an_integrand(self, t, n):
        """Integrand for the nth cosine coefficient"""
        return self.function(t, tau) * np.cos(n * self.omega * t)

    def an_calc(self, n):
        """Calculate the nth cosine coefficient (n > 0)"""
        # note comma after n in args
        answer, error = quad(self.an_integrand, -tau/2., tau/2., args=(n,))
        return (2./self.tau) * answer

    def bn_integrand(self, t, n):
        """Integrand for the nth cosine coefficient"""
        return self.function(t, tau) * np.sin(n * self.omega * t)

    def bn_calc(self, n):
        """Calculate the nth cosine coefficient (n > 0)"""
        answer, error = quad(self.bn_integrand, -tau/2., tau/2., args=(n,))
        return (2./self.tau) * answer

    def coeffs_upto_Nmax(self):
        """Calculate the Fourier series up to Nmax"""
        # first generate the coefficient
        coeffs_array = [(self.a0_calc(), 0)]   # a_0 and b_0

        for n in np.arange(1, N_max, 1):
            a_n = self.an_calc(n)
            b_n = self.bn_calc(n)
            coeffs_array.append((a_n, b_n))  # append a tuple of coefficients

        return np.array(coeffs_array)  # convert to a numpy array

```

Finally, we need a function that can take as input an array of t values and an array of Fourier coefficients and return the function at those t values with terms up to order N_max.

```python

def Fourier_reconstruct(t_pts, coeffs_array, tau, N_max):
    """Sum up the Fourier series up to n = N_max terms."""
    omega = 2. * np.pi / tau
    result = 0.
    # iterate over coefficients but only up to N_max
    for n, (a,b) in enumerate(coeffs_array[:N_max+1]):
        result = result + a * np.cos(n * omega * t_pts) \
                        + b * np.sin(n * omega * t_pts)
    return result
```

## Problem 5.50

Ok, now we can do problem 5.49.  Calculate the coefficients both ways.

```python
N_max = 20
tau = 2.
f_max = 1.
coeffs_by_hand = sawtooth_coeffs_by_hand(N_max, tau, f_max)

fs = FourierSeries(sawtooth, tau, N_max)
coeffs_by_quad = fs.coeffs_upto_Nmax()
```

Let's check that the exact and numerical calculation of the coefficients agree.

(Note the space in the formats, e.g., `{a1: .6f}`.  This means to leave an extra space for a positive number so that it aligns at the decimal point with negative numbers.)

```python
print(' n   a_exact     a_quad      b_exact     b_quad')
for n, ((a1,b1), (a2,b2)) in enumerate(zip(coeffs_by_hand,
                                           coeffs_by_quad)):
    print(f'{n:2d}  {a1: .6f}  {a2: .6f}    {b1: .6f}  {b2: .6f}')
```

     n   a_exact     a_quad      b_exact     b_quad
     0   0.000000   0.000000     0.000000   0.000000
     1   0.000000   0.000000     0.318310   0.318310
     2   0.000000   0.000000    -0.159155  -0.159155
     3   0.000000   0.000000     0.106103   0.106103
     4   0.000000   0.000000    -0.079577  -0.079577
     5   0.000000   0.000000     0.063662   0.063662
     6   0.000000   0.000000    -0.053052  -0.053052
     7   0.000000   0.000000     0.045473   0.045473
     8   0.000000   0.000000    -0.039789  -0.039789
     9   0.000000   0.000000     0.035368   0.035368
    10   0.000000   0.000000    -0.031831  -0.031831
    11   0.000000   0.000000     0.028937   0.028937
    12   0.000000   0.000000    -0.026526  -0.026526
    13   0.000000   0.000000     0.024485   0.024485
    14   0.000000   0.000000    -0.022736  -0.022736
    15   0.000000   0.000000     0.021221   0.021221
    16   0.000000   0.000000    -0.019894  -0.019894
    17   0.000000   0.000000     0.018724   0.018724
    18   0.000000   0.000000    -0.017684  -0.017684
    19   0.000000   0.000000     0.016753   0.016753

Make the comparison plot requested: N_max = 2 vs. N_max = 6.

```python
t_pts = np.arange(-2., 6., .01)
f_pts_2 = Fourier_reconstruct(t_pts, coeffs_by_quad, tau, 2)
f_pts_6 = Fourier_reconstruct(t_pts, coeffs_by_quad, tau, 6)

# Python way to evaluate the sawtooth function at an array of points:
#   * np.array creates a numpy array;
#   * note the []s around the inner statement;
#   * sawtooth(t) for t in t_pts
#       means step through each element of t_pts, call it t, and
#       evaluate sawtooth at that t.
#   * This is called a list comprehension.  There are more compact ways,
#      but this is clear and easy to debug.
sawtooth_t_pts = np.array([sawtooth(t, tau, f_max) for t in t_pts])
```

```python

fig_1 = plt.figure(figsize=(10,5))
ax_1 = fig_1.add_subplot(1,2,1)
ax_1.plot(t_pts, f_pts_2, label='N = 2', color='blue')
ax_1.plot(t_pts, sawtooth_t_pts, label='exact', color='red')
ax_1.set_xlim(-1.1,4.1)
ax_1.set_xlabel('t')
ax_1.set_ylabel('f(t)')
ax_1.set_title('N = 2')
ax_1.legend()

ax_2 = fig_1.add_subplot(1,2,2)
ax_2.plot(t_pts, f_pts_6, label='N = 6', color='blue')
ax_2.plot(t_pts, sawtooth_t_pts, label='exact', color='red')
ax_2.set_xlim(-1.1,4.1)
ax_2.set_xlabel('t')
ax_2.set_ylabel('f(t)')
ax_2.set_title('N = 6')
ax_2.legend();

fig_1.tight_layout()
fig_1.savefig('problem_5.50.png')
```

```python

```

```python

```


```python
import sympy as sym
import numpy
import pylab
import time

def lagrange_series(N):
    psi = []
    #  h = Rational(1, N)
    h = 1.0/N
    points = [i*h for i in range(N+1)]
    for i in range(len(points)):
        p = 1
        for k in range(len(points)):
            if k != i:
                p *= (x - points[k])/(points[i] - points[k])
                psi.append(p)
    #  psi = psi[1:-1]
    return psi

def bernstein_series(N):
    # FIXME: check if a normalization constant is common in the definition
    # advantage is that the basis is always positive
    psi = []
    for k in range(0,N+1):
    #  for k in range(1,N):  # bc elsewhere
        psi_k = sym.binomial(N, k)*x**k*(1-x)**(N-k)
        psi.append(psi_k)
    return psi

def sin_series(N):
  # FIXME: do not satisfy bc
  psi = []
  for k in range(1,N):
    psi_k = sin(pi*k*x)
    psi.append(psi_k)
  return psi

def taylor_series(N):
  # FIXME: do not satisfy bc
  print("Cannot with current BC implementation")
  return
  psi = []
  for k in range(1,N):
    psi_k = x**k
    psi.append(psi_k)
  return psi

def series(series_type, N):
  if series_type=="Taylor" : return taylor_series(N) # cannot do with current implementation of bc
  elif series_type=="sin"  : return sin_series(N)
  elif series_type=="Bernstein"  : return bernstein_series(N)
  elif series_type=="Lagrange"  : return lagrange_series(N)
  else: print("series type unknown ") # sys.exit(0)

x = sym.Symbol("x")

h= 0.001
X = numpy.arange(0, 1, h)
psi = series("Bernstein", 8)
for i in range(len(psi)):
  psii = sym.lambdify([x], psi[i])
  psiii = psii(X)
  pylab.plot(X, psiii)
pylab.show()

psi = series("Lagrange", 8)
for i in range(len(psi)):
  psii = sym.lambdify([x], psi[i])
  psiii = psii(X)
  pylab.plot(X, psiii)
pylab.show()

```

```python

```

Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/SRC/03_BERNSTEIN_VS_LAGRANGE_PLOT.ipynb


# Count Based Vectorizer

```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import (
    TfidfVectorizer, CountVectorizer, TfidfTransformer
)
```

## References

https://en.wikipedia.org/wiki/Tf%E2%80%93idf

## Count Vectorizer

frequency based on the set of words

```python
corpus = [
    'this is the first document',
    'this document is the second document',
    'and this is the third one'
]
```

```python
count_vec = CountVectorizer()
count_vec.fit(corpus)
```

    CountVectorizer()

```python
count_vec.get_feature_names()
```

    ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']

```python
count_data = count_vec.transform(corpus).toarray()
count_data
```

    array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
           [0, 2, 0, 1, 0, 1, 1, 0, 1],
           [1, 0, 0, 1, 1, 0, 1, 1, 1]])

```python
pd.DataFrame(
    data=count_data,
    columns=count_vec.get_feature_names()
)
```

      and
      document
      first
      is
      one
      second
      the
      third
      this

      0
      0
      1
      1
      1
      0
      0
      1
      0
      1

      1
      0
      2
      0
      1
      0
      1
      1
      0
      1

      2
      1
      0
      0
      1
      1
      0
      1
      1
      1

So the first line is `this is the first document`. and then the first vector is reflecting as document is 1, first is 1, is is 1 etc.

## Term Frequency Transformer

Number of times term t, appear in the document d.

\begin{align}
    tf_{t,d} &= \frac{n_{t,d}}{\sum_k{n_{k,d}}}
\end{align}

```python
tf_transformer = TfidfTransformer(use_idf=False)
tf_transformer.fit(count_data)
```

    TfidfTransformer(use_idf=False)

```python
tf_data = tf_transformer.transform(count_data).toarray()
tf_data
```

    array([[0.        , 0.4472136 , 0.4472136 , 0.4472136 , 0.        ,
            0.        , 0.4472136 , 0.        , 0.4472136 ],
           [0.        , 0.70710678, 0.        , 0.35355339, 0.        ,
            0.35355339, 0.35355339, 0.        , 0.35355339],
           [0.40824829, 0.        , 0.        , 0.40824829, 0.40824829,
            0.        , 0.40824829, 0.40824829, 0.40824829]])

```python
pd.DataFrame(
    data=tf_data,
    columns=count_vec.get_feature_names()
)
```

      and
      document
      first
      is
      one
      second
      the
      third
      this

      0
      0.000000
      0.447214
      0.447214
      0.447214
      0.000000
      0.000000
      0.447214
      0.000000
      0.447214

      1
      0.000000
      0.707107
      0.000000
      0.353553
      0.000000
      0.353553
      0.353553
      0.000000
      0.353553

      2
      0.408248
      0.000000
      0.000000
      0.408248
      0.408248
      0.000000
      0.408248
      0.408248
      0.408248

## Inverse Document Frequency Transformer

> `Document Frequency` : number of ducuments that the term appears / number of ducuments

\begin{align}
    probability = df_{t,d,D} &= \frac{d \in D : t \in d}{D}
\end{align}

The log of the number of documents D divided by the number of documents that contain the word t. Inverse data frequency determines the weight of rare words across all documents in the corpus.

\begin{align}
    idf &= -log(p)\\
    idf &= log(\frac{1}{p})\\
    idf_{t,d,D} &= log(\frac{D}{d \in D : t \in d})
\end{align}

> document d is in all the documents D, and term t is in the document d.

```python
tfidf_transformer = TfidfTransformer()
tfidf_transformer.fit(count_data)
```

    TfidfTransformer()

```python
tfidf_data = tfidf_transformer.transform(count_data).toarray()
tfidf_data
```

    array([[0.        , 0.46941728, 0.61722732, 0.3645444 , 0.        ,
            0.        , 0.3645444 , 0.        , 0.3645444 ],
           [0.        , 0.7284449 , 0.        , 0.28285122, 0.        ,
            0.47890875, 0.28285122, 0.        , 0.28285122],
           [0.49711994, 0.        , 0.        , 0.29360705, 0.49711994,
            0.        , 0.29360705, 0.49711994, 0.29360705]])

```python
pd.DataFrame(
    data=tfidf_data,
    columns=count_vec.get_feature_names()
)
```

      and
      document
      first
      is
      one
      second
      the
      third
      this

      0
      0.00000
      0.469417
      0.617227
      0.364544
      0.00000
      0.000000
      0.364544
      0.00000
      0.364544

      1
      0.00000
      0.728445
      0.000000
      0.282851
      0.00000
      0.478909
      0.282851
      0.00000
      0.282851

      2
      0.49712
      0.000000
      0.000000
      0.293607
      0.49712
      0.000000
      0.293607
      0.49712
      0.293607

## TFIDF Vectorizer

Count Vectorizer --> Tfidf Transformer = Tfidf Vectorizer

$tfidf_{t,d,D} = tf_{t,d}.idf_{t,d,D}$

```python
tfidf_vec = TfidfVectorizer()
tfidf_vec.fit(corpus)
```

    TfidfVectorizer()

```python
tfidf_data = tfidf_vec.transform(corpus).toarray()
```

```python
tfidf_vec.get_feature_names()
```

    ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']

```python
pd.DataFrame(
    data=tfidf_data,
    columns=tfidf_vec.get_feature_names()
)
```

      and
      document
      first
      is
      one
      second
      the
      third
      this

      0
      0.00000
      0.469417
      0.617227
      0.364544
      0.00000
      0.000000
      0.364544
      0.00000
      0.364544

      1
      0.00000
      0.728445
      0.000000
      0.282851
      0.00000
      0.478909
      0.282851
      0.00000
      0.282851

      2
      0.49712
      0.000000
      0.000000
      0.293607
      0.49712
      0.000000
      0.293607
      0.49712
      0.293607