# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 10:46:46 2017

@author: etienne
"""

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as anim

import time

plt.close("all")


### Paramètres de la vidéo
duree = 60  # durée en secondes
ips   = 24  # images par seconde
nb_images = duree*ips   # nbre total d'image


### Paramètres des figures
x_min = 0
x_max = 100

t_min = 0
t_max = 10

y_min = -7
y_max = 8

T = 10
lbda = 35

w = 2*np.pi/T
k = 2*np.pi/lbda
c = w/k

### Création de l'onde
def onde_i(x,t):
    xi = np.zeros_like(x)
    for j in range(len(x)):
        if x[j]-c*t > 0:
            xi[j] = 0
        else:
            xi[j] = 3 * np.sin(w*t - k*x[j])   
    return xi

def onde_r(x,t):
    xi = np.zeros_like(x)
    for j in range(len(x)):
        if (x_max-x[j])-c*t > 0:
            xi[j] = 0
        else:
            xi[j] = 3 * np.sin(w*t + k*(x[j]-x_max)) 
    return xi

x = np.linspace(x_min,x_max,200)

### Création de la figure sur laquelle se fait l'animation
fig = plt.figure(figsize=(15,5))

plt.xlim(x_min, x_max)
plt.ylim(y_min,y_max)
plt.xlabel(r'$x$ (unité arbitraire)')
plt.ylabel(r'Champ électrique')
# plt.text(2.5,7, r'Film de la corde', fontsize=14, color='k')

### Mise en forme extérieure à la boucle pour effacement entre chaque image
line_tot, = plt.plot([], [], '-', color='r',linewidth=2)
line_i, = plt.plot([], [], '-', color='b')
line_r, = plt.plot([], [], '-', color='g')
line = [line_i, line_r, line_tot]


def animate(i):
    # i est le numéro de l'image dans le film
    t = i/ips 
    
    ### Onde incidente
    xi_i = onde_i(x,t)
    line[0].set_data(x, xi_i)
    
    ### Onde réfléchie
    xi_r = onde_r(x,t)
    line[1].set_data(x,xi_r)
    
    ### Superposition
    xi_tot = xi_i + xi_r
    line[2].set_data(x,xi_tot)
    
    return line

### Pour démarrer et arrêter l'animation à chaque clic
anim_running = True
def onClick(event):
    global anim_running
    if anim_running:
        film.event_source.stop()
        anim_running = False
    else:
        film.event_source.start()
        anim_running = True
fig.canvas.mpl_connect('button_press_event', onClick)

### Génération de l'animation
today = time.strftime("%x")
fig.text(0.02,.95, r'(C) Étienne Thibierge ' + today, fontsize=12)

film = anim.FuncAnimation(fig, animate, frames=nb_images, interval=20, repeat=True)
# film.save('19_reflexion-OEM_video-OSH=2OPH.mp4', fps=ips, codec="libx264",bitrate=-1)	# Sauvegarde du film

plt.show()