import psutil
L = psutil.Process().parent().cmdline()
if any("jupyter-notebook" in string for string in L):
%matplotlib notebook
elif any("jupyterhub" in string for string in L):
%matplotlib widget
else:
%matplotlib inline
import numpy as np
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque
from control.matlab import *
m = 1000 #weight of the car in [kg],
b = 1000 #viscous damping coefficient in [N/(m/s)]
L = 5 #length of the car in [m]
H = 1.2 #height of the car [m]
r = 0.5 #radius of the wheel in [m]
u = 6000 #unit step input force [N]
# create a time array from 0..t_stop sampled at 0.02 second steps
dt = 0.1 # time step
t_stop = 10 # how many seconds to simulate
TSPAN = [0, t_stop] #simulation time spa
TIME = np.arange(0, t_stop, dt) # simulation time serie
y0 = [0,0] #intial values for position (x) and speed (v)
history_len = 500 # how many trajectory points to display
A = np.matrix([[0,1],[0,-b/m]])
B =np.matrix([[0],[1/m]])
C = np.matrix([[1,0],[0,1]])
D = np.matrix([[0],[0]])
sys = StateSpace(A,B,C,D)
y0=[0,0] #Initial position of 0 [m] and initial velocity of 0 [m/s]
yout, T,xout = lsim(sys, u, TIME, y0)
x=yout[:,0]
v=yout[:,1]
Y = 0*np.arange(0, t_stop, dt)
plt.close("all")
fig2 = plt.figure(figsize=(8, 4))
ax = fig2.add_subplot(2,1,1,autoscale_on=False, xlim=(-L-r, x.max()+L),ylim=(-2*H-2*r,4*H+2*r))
ax.set_aspect('equal')
plt.xlabel("Travel distance [m]")
ax.grid()
ax1 = fig2.add_subplot(2,1,2,autoscale_on=False, xlim =(0,t_stop),ylim=(v.min(),v.max()+1))
trace, = ax1.plot([], [], ',-', lw=1)
plt.xlabel("Travel time [s]")
plt.ylabel("Car speed [m/s]")
ax1.grid()
line, = ax.plot([], [], '-', lw=2)
patch = plt.Circle((r, -r), r)
ax.add_patch(patch)
patch2 = plt.Circle((r+L, -r), r)
ax.add_patch(patch)
time_template = 'time = %.1fs'
time_text = ax.text(0.03, 0.8, '', transform=ax.transAxes)
history_x, history_y = deque(maxlen=history_len), deque(maxlen=history_len)
def animate(i):
t = time.time()
thisx = [x[i]-L,x[i]+L,x[i]+L,x[i]-L, x[i]-L ]
thisy = [Y[i]+H,Y[i]+H,Y[i]-H,Y[i]-H,Y[i]+H]
line.set_data(thisx, thisy)
patch.center = (-L+x[i]+r,Y[i]-H-r)
ax.add_patch(patch)
patch2.center = (L+x[i]-r,Y[i]-H-r)
ax.add_patch(patch2)
time_text.set_text(time_template % (i*dt))
if i == 0:
history_x.clear()
history_y.clear()
history_x.appendleft(TIME[i])
history_y.appendleft(v[i])
trace.set_data(history_x, history_y)
elapsed = time.time() - t
time.sleep(dt-elapsed)
return line,patch,patch2, time_text
ani = animation.FuncAnimation(fig2, animate, frames=len(x), interval=dt*1000, blit=True,repeat=False)
plt.show()