Interpolation Exercise 1


In [8]:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

In [9]:
from scipy.interpolate import interp1d

2D trajectory interpolation

The file trajectory.npz contains 3 Numpy arrays that describe a 2d trajectory of a particle as a function of time:

  • t which has discrete values of time t[i].
  • x which has values of the x position at those times: x[i] = x(t[i]).
  • x which has values of the y position at those times: y[i] = y(t[i]).

Load those arrays into this notebook and save them as variables x, y and t:


In [28]:
file=np.load('trajectory.npz')
t=file['t']
x=file['x']
y=file['y']
x
t


Out[28]:
array([ 0.        ,  0.1025641 ,  0.20512821,  0.30769231,  0.41025641,
        0.51282051,  0.61538462,  0.71794872,  0.82051282,  0.92307692,
        1.02564103,  1.12820513,  1.23076923,  1.33333333,  1.43589744,
        1.53846154,  1.64102564,  1.74358974,  1.84615385,  1.94871795,
        2.05128205,  2.15384615,  2.25641026,  2.35897436,  2.46153846,
        2.56410256,  2.66666667,  2.76923077,  2.87179487,  2.97435897,
        3.07692308,  3.17948718,  3.28205128,  3.38461538,  3.48717949,
        3.58974359,  3.69230769,  3.79487179,  3.8974359 ,  4.        ])

In [14]:
assert isinstance(x, np.ndarray) and len(x)==40
assert isinstance(y, np.ndarray) and len(y)==40
assert isinstance(t, np.ndarray) and len(t)==40

Use these arrays to create interpolated functions $x(t)$ and $y(t)$. Then use those functions to create the following arrays:

  • newt which has 200 points between $\{t_{min},t_{max}\}$.
  • newx which has the interpolated values of $x(t)$ at those times.
  • newy which has the interpolated values of $y(t)$ at those times.

In [38]:
x_t=interp1d(t,x,kind='cubic')
y_t=interp1d(t,y,kind='cubic')
newt=np.linspace(t.min(),t.max(),200)
newx=x_t(newt)
newy=y_t(newt)

In [39]:
assert newt[0]==t.min()
assert newt[-1]==t.max()
assert len(newt)==200
assert len(newx)==200
assert len(newy)==200

Make a parametric plot of $\{x(t),y(t)\}$ that shows the interpolated values and the original points:

  • For the interpolated points, use a solid line.
  • For the original points, use circles of a different color and no line.
  • Customize you plot to make it effective and beautiful.

In [52]:
plt.figure(figsize=(10,10))
plt.plot(newx,newy)
plt.plot(x,y, 'ro')
plt.title('$y(t)\ vs\ x(t)$')
plt.xlabel('$x(t)$')
plt.ylabel('$y(t)$')
plt.tight_layout()



In [ ]:
assert True # leave this to grade the trajectory plot