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
from sympy import symbols, Function, Matrix,sin,cos,solve
from control.matlab import lsim,StateSpace
#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]
theta0= 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]
# 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
t = symbols('t')
V = Function('v')(t)
X = Function('x')(t)
u, theta = symbols('u theta', Real=True)
U = Matrix ([[ u], [theta ]])
dX = Matrix ([[V], [1/m*(n*u/r*Tm*(1-beta*(n/r*V/omega_n-1)**2)-m*g*sin(theta)-m*g*Cr-1/2*rho*Cd*V**2*A)]])
X = Matrix ([ [X],[V] ])
A_sym = dX.jacobian(X)
B_sym = dX.jacobian(U)
V0=25 # Stable working point for the car speed is 25 m/s
theta0=0.01 # Stable Working point for the steep angle is 0.01 rad
q = dX.subs(V,V0).subs(theta,theta0) #substitute V and theta with V^0=25 and theta^0=0.01 in the equation dX
sol=solve(q[1],u) #find the U0 value that fits equation q=0
U0= float(sol[0]) # Working point for the input
A=A_sym.subs(V,V0).subs(theta,theta0).subs(u,U0)
B=B_sym.subs(V,V0).subs(theta,theta0).subs(u,U0)
C = np.matrix([[1,0],[0,1]])
D = np.matrix([[0,0],[0,0]])
sys = StateSpace(A,B,C,D)
Input = np.transpose([ 0.1*np.ones(400),0*np.ones(400)]) # unit step input force 0.1 [N] and angle of 0 = no addditonal angle [N]
X0=[0,0] #Initial value for the velocity and position
yout, T, xout = lsim(sys, Input, TIME, X0)
# convert from linearized velocity to real velocity
x = yout[:,0]+TIME*V0
v = yout[:,1]+V0
# Rotate car on the steep:
x=x*np.cos(theta0)
y=x*np.sin(theta0)
R=[ [np.cos(theta0),-np.sin(theta0)],[np.sin(theta0),np.cos(theta0)]]
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()