Home Subscribe

3. Simulating a 1D Forward Motion

Let’s say we have an airplane moving at \(750 km/h\). The airplane is moving from time \(t = 0\) to \(t = 3 hrs\).

Import the required libraries.

1import numpy as np
2import matplotlib.pyplot as plt 
3from matplotlib.animation import FuncAnimation
4import matplotlib.gridspec as gridspec 
5import matplotlib.patheffects as path_effects 

Part 1: Solve the equations involved in your idea.

Perform the calculations. Calculate the total distance, x, make time, t, and the simulation interval, dt.

 6spd = 750 # [km/h]
 7t_0 = 0; t_end = 3; t_dt = 0.005; 
 8t = np.arange(t_0, t_end+t_dt, t_dt) # [hrs] 
 9
10# Create x array. 
11x = spd*t # [kms]
12
13# Create an array for y (altitude)
14alt_0 = 2; alt_end = 2; 
15y = np.linspace(alt_0, alt_end, len(x)) 

Part 2: Use the output data to visualize the idea.

Prepare the space for plotting.

16plt.style.use("ggplot")
17cm = 1/2.54
18
19fig0 = plt.figure(figsize=(40*cm,20*cm), dpi=120) 
20gs = gridspec.GridSpec(2,2)
21
22ax0 = fig0.add_subplot(gs[0,:]); plt.xlim(x[0], x[-1]); plt.ylim(0,y[-1]+1); plt.xlabel("Distance (km)"); plt.ylabel("Altitude (km)") # facecolor
23ax1 = fig0.add_subplot(gs[1,0]); plt.xlim(x[0], x[-1]); plt.ylim(0,y[-1]+1); plt.xlabel("Distance (km)"); plt.ylabel("Altitude (km)")
24ax2 = fig0.add_subplot(gs[1,1]); plt.xlim(t[0], t[-1]); plt.ylim(0,x[-1]+1); plt.xlabel("Time (hr)"); plt.ylabel("Distance (km)")
25trajectory0 = ax0.plot([],[], ls='-.')[0]
26trajectory1 = ax1.plot([],[])[0]
27trajectory2 = ax2.plot([],[])[0]
28
29l0 = ax0.plot([],[], ls='-', lw=10, path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()])[0]

Create the animation function.

30def animate(frame): # update plots
31    trajectory0.set_data(x[0:frame], y[0:frame])
32    trajectory1.set_data(x[0:frame], y[0:frame])
33    trajectory2.set_data(t[0:frame], x[0:frame])
34    l0.set_data([0+x[frame],20+x[frame]],[2,2])
35    return trajectory0, trajectory1, trajectory2, l0

Animate the data.

36anim = FuncAnimation(fig0, 
37                    animate, 
38                    frames=len(t), 
39                    interval=20, 
40                    repeat=True, 
41                    blit=True) # blit should be true for faster fig0 update
42plt.show()