import psutil
L = psutil.Process().parent().cmdline()
if any("jupyter-notebook" in string for string in L):
    %matplotlib notebook
    print("notebook")
elif any("jupyterhub" in string for string in L):
    %matplotlib widget
    print("labhub")
else: 
    %matplotlib inline
    print("juyter-book")

import numpy as np
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque
from scipy.integrate import solve_ivp

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
u=6000

def odefun(TIME, y, m, b,u):
    x,v=y
    dv = -b/m*v + u/m #v is the velocity
    dx = v            #x is the postion 
    return [dx,dv]

y = solve_ivp(odefun, TSPAN, y0, args=(m, b,u), dense_output=True)

x,v = y.sol(TIME)

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()
juyter-book
../../../_images/778ca01b67fe1a2c42c1725017989f9532a543986992c1ae4e63e464e55dab34.png