Interpolation Exercise 1


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

In [3]:
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 [4]:
with np.load('trajectory.npz') as data:
    t=data['t']
    x=data['x']
    y=data['y']

In [5]:
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 [6]:
newt=np.linspace(np.min(t),np.max(t),200)
fx=interp1d(t,x,kind='cubic')
fy=interp1d(t,y,kind='cubic')
newx=fx(newt)
newy=fy(newt)

In [7]:
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 [8]:
plt.figure(figsize=(12,8))
# plt.plot(newt,newx, label='interpolated x', color='b')
# plt.plot(t,x, marker='o', linestyle='', color='r', label='orignal x')
# plt.plot(newt,newy, label='interpolated y',color='g')
# plt.plot(t,y, marker='o',linestyle='', color='k',label='original y')
# plt.legend()
# plt.xlabel('t')
# plt.ylabel('f(t)')
# plt.grid(False)
# plt.box(False)
# plt.axhline(linewidth=.5, color='k', y=0, linestyle='--')

#worked with Jack Porter,,I missed the key word "parametric" so I previously plotted the above

plt.plot(newx,newy, label='interpolated', color='g')
plt.plot(x,y,label='original points',color='k', linestyle='',marker='o')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Trajectory of Object')
plt.grid(False)
plt.box(False)



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