Interpolation Exercise 1


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

In [2]:
from scipy.interpolate import interp1d, interp2d

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 [3]:
f = np.load('trajectory.npz')

In [4]:
x = f['x']
y = f['y']
t = f['t']

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]:
x_approx = interp1d(t, x, kind='cubic')
y_approx = interp1d(t, y, kind='cubic')

In [7]:
traj_approx = interp2d(x, y, t, kind='cubic')

In [8]:
newt = np.linspace(t.min(),max(t),200)
newx = x_approx(newt)
newy = y_approx(newt)

In [9]:
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 [10]:
fig = plt.figure(figsize=(7,7))
plt.plot(newx, newy, marker='.')
plt.plot(x, y, 'ro')
plt.xticks([-1.0,-0.5,0.0,0.5,1.0])
plt.yticks([-1.0,-0.5,0.0,0.5,1.0])
plt.xlabel('x(t)')
plt.ylabel('y(t)')


Out[10]:
<matplotlib.text.Text at 0x7f5b906960b8>

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