import psutil
L = psutil.Process().parent().cmdline()
if any("jupyter-notebook" in string for string in L):
%matplotlib notebook
elif any("jupyter-labhub" in string for string in L):
%matplotlib widget
else:
%matplotlib inline
import numpy as np
import time
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import scipy.integrate as integrate
import matplotlib.animation as animation
from collections import deque
from scipy.integrate import solve_ivp
#Model parameters
n=10 #Gear ratio
r=0.5 #Wheel radius [m]
Tm=190 #engine torque constant [Nm]
omega_n=420 #peak torque rate [rad/sec]
m=1000 #mass of the car [kg]
beta = 0.4 #Torque coefficient
Cr=0.01 #roll friction coefficient
rho=1.3 #density of air [kgm^3]
Cd=0.32 #drag coefficient
A=2.4 #Frontal surface car [m^2]
g=9.8 #Gravity constant [N/kg]
theta= 4*np.pi/180# 4 degrees of steep
#Visualization parameters:
L = 2*5 #length of the car in [m]
H = 2*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 = 40 # 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
def ODEFUN(t, y, n, r, beta, omega_n, m , Cr, rho, Cd, A, Tm, theta ):
u=1 # we apply full throttle
omega= n/r*y[1]
dx = y[1] # v is second element of y(t)
dv = 1/m*(n*u/r*Tm*(1-beta*(omega/omega_n-1)**2) - m*g*np.sin(theta) - m*g*Cr*np.sign(y[1]) - 0.5*rho*Cd*A*y[1]**2)
return [dx,dv]
y = solve_ivp(ODEFUN, TSPAN, y0, args=( n, r, beta, omega_n, m , Cr, rho, Cd, A, Tm,theta ), dense_output=True)
x = y.sol(TIME)[0,:]
v = y.sol(TIME)[1,:]
# Convert frame to flat surface
x=x*np.cos(theta)
y=x*np.sin(theta)
R=[ [np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]
Y = 0*np.arange(0, t_stop, dt)
plt.close("all")
fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot(2,1,1,autoscale_on=False, xlim=(-L-r, x.max()+L),ylim=(-2*H-2*r+y.min(),8*H+2*r+y.max()))
ax.set_aspect('equal')
plt.xlabel("Travel distance [m]")
ax.grid()
ax1 = fig.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)
line2, = ax.plot([], [], '-', lw=2)
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()
oft= np.dot(R,[[-L,L,L,-L, -L ],[+H,+H,-H,-H,+H]])
thisxy = [[x[i]+oft[0,0],x[i]+oft[0,1],x[i]+oft[0,2],x[i]+oft[0,3], x[i]+oft[0,4] ],[y[i]+oft[1,0],y[i]+oft[1,1],y[i]+oft[1,2],y[i]+oft[1,3],y[i]+oft[1,4]]]
line.set_data(thisxy)
line2.set_data([0,x[-1]],[0-H-r,y[-1]-H-r])
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,line2, time_text
ani = animation.FuncAnimation(fig, animate, frames=len(x), interval=dt*1000, blit=True,repeat=False)
plt.show()