# -*- coding: utf-8 -*-
# Created on Thu Nov 18 07:02:10 2021
# @author: mhebding

""" Animation d'un pendule simple """

# Bibliothèques
from math import sin, cos, pi
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Paramètres et conditions initiales
g = 9.81
l = 1
w02 = g/l # pulsation propre au carré
theta0 = pi/2 # angle initial : tester pi/2, -pi/2, pi/3, pi/10, 0, pi
thetadot0 = 0 # vitesse initiale : à modifier pour tester
y0 = [theta0, thetadot0]

def ED(y, t):
    thetadot = y[1]
    a_theta = -w02*sin(y[0]) # Rq : équa. diff. pendule simple
    return thetadot, a_theta

# Résolution
pas = 50*10**(-3)
t0, tf = 0,5
N = int((tf-t0)/pas)
t = np.linspace(t0, tf, N) # tableau des instants t
y = odeint(ED, y0, t) # résolution avec odeint
theta, thetadot = y[:, 0], y[:, 1] # on affecte theta et thetadot

# Tracé
fig = plt.figure()
ax = fig.add_subplot(211, autoscale_on=False, xlim=(-1.5, 1.5), ylim=(-1.5, .5))
ax.grid()
ax.set_aspect('equal','box')
plt.title('Pendule simple')
pendules = plt.plot((0, sin(y0[0])), (0, -cos(y0[0])), 'o-')
def animate(i): # animation du pendule
    angle = theta[i]
    x = (0, sin(angle))
    y = (0, -cos(angle))
    pendules[0].set_data(x, y)
anim = animation.FuncAnimation(fig, animate, frames=N, interval=50) # 50 ms

# Tracé live de theta et thetadot en fonction du temps
ax = fig.add_subplot(212, xlim=(t0,tf), ylim=(-5,5))
graphe_t, graphe_theta, graphe_thetadot = [],[],[]
for i in range(len(t)): # 'animation' des graphes
    graphe_t.append(t[i])
    graphe_theta.append(theta[i])
    graphe_thetadot.append(thetadot[i])
    plt.plot(graphe_t, graphe_theta, label='theta', color='blue')
    plt.plot(graphe_t, graphe_thetadot, label='thetadot', color='orange')
    plt.pause(0.0375) # ajustement à la louche pour être à peu près synchro

plt.show() # affichage