Interpolation Exercise 1


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

In [37]:
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 [38]:
# YOUR CODE HERE

with np.load('trajectory.npz') as data:
    x = data['x']
    t=data['t']
    y=data['y']
    
plt.plot(t,x,marker='o')


Out[38]:
[<matplotlib.lines.Line2D at 0x7f33c0595a20>]

In [39]:
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 [40]:
# YOUR CODE HERE
newt=np.linspace(min(t),max(t),200)

xout= interp1d(t,x,kind= 'cubic')
newx= xout(newt)
yout= interp1d(t,y,kind='cubic')
newy= yout(newt)

# newx = interp1d(t, x, kind='cubic')
# newy = interp1d(t, y, kind='cubic')
# print(newx)

In [41]:
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 [43]:
# YOUR CODE HERE
plt.figure(figsize=(9,6))
plt.plot(t, x, marker='o', linestyle='', label='original x data')
plt.plot(newt, newx, marker='.', label='interpolated x function');
plt.plot(t, y, marker='o', linestyle='', label='original y data')
plt.plot(newt, newy, marker='.', label='interpolated y function');
plt.legend();
plt.xlabel('Time (sec)')
plt.ylabel('F(t)');
plt.title("Graph Showing Effect of Interpolation Function")


Out[43]:
<matplotlib.text.Text at 0x7f33c04f9e80>

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