#-----------------------------------------------------------------------
# Animation de l'évolution d'un paquet d'onde
#-----------------------------------------------------------------------

########################
##Paramètres modifiables
########################
# Vitesse de groupe
Vg = 0.1

# Modèle :
# 1 : w = a.k     (non dispersif)
# 2 : w = a.k^2   (type electron libre)
# 3 : w = a.k^0.5 (type vagues, défilement dans l'autre sens)
# 4 : w = a.k^3   (non physique, mais plus visible)
# 5 : w = sqrt(a.k^2+b)   (plasma)
type = 5

#initialisation
anim_running = False

# Contrôle des paramètres
assert(0.02 <= Vg <= 2.0)
assert(type in (1, 2, 3, 4, 5))

#########################
##Bibliothèques utilisées
#########################
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as ani
from numpy.fft import fft, fftfreq

#######################
##Definitions et tracés
#######################

# Foncton définissant la vitesse de phase en fonction du
# nombre d'onde sigma

@np.vectorize
def Vp(sig) :
    # Pas d'étalement :
    if type == 1 :
        return Vg

    # a.k^2
    if type == 2 :
        return Vg*sig/2.0

    # a.k^0.5
    if type == 3 :
        if sig==0.0 :
            return 0.0
        return 2.0*Vg/((np.abs(sig))**0.5)

    # a.k^3
    if type == 4 :
        return Vg*sig**2.0/3.0

    # sqrt(a.k^2+b)
    if type == 5 :
        if sig==0.0 :
            return 0.0
        return np.sqrt(Vg*sig**2+0.03)/sig

# Détection utilisation hors Pyzo

if '__iep__' not in globals() :
    matplotlib.interactive(False)

# Abscisses

X = np.linspace(0, 300, 4096)

# Nombres d'ondes correspondants

Sig = fftfreq(len(X), 150/4096)

# Calcul de la forme de l'onde à un instant t

def Onde(t) :
    Yp = np.exp(-((Sig-0.8)/0.3)**2 + 6.283j*Sig*Vp(Sig)*t)
    # Yp = (np.sinc((Sig-1)/0.07)) * np.exp(6.283j*Sig*Vp(Sig)*t)

    return np.real(fft(Yp))

def Envel(t) :
    Yp = np.exp(-((Sig-0.8)/0.3)**2 + 6.283j*Sig*Vp(Sig)*t)
    # Yp = (np.sinc((Sig-1)/0.07)) * np.exp(6.283j*Sig*Vp(Sig)*t)

    return np.abs(fft(Yp))

# Premier tracé pour préparer l'animation

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_ylim([-70,70])
ond, = plt.plot(X, Onde(0), 'b')
envp, = plt.plot(X, Envel(0), 'r:')
envm, = plt.plot(X, -1*Envel(0),'r:')

lines = [ond, envp, envm]

# Décoration

if type == 1 :
    ax.set_title(r"Milieu non dispersif : $\omega = \alpha k$")
elif type == 2 :
    ax.set_title(r"Type électron : $\omega = \alpha k^2$")
elif type == 3 :
    ax.set_title(r"Type vagues, $\omega = \alpha \sqrt{k}$")
elif type == 4 :
    ax.set_title(r"Milieu dispersif non physique : $\omega = \alpha k^3$")
elif type == 5 :
    ax.set_title(r"Milieu type plasma : $\omega = \sqrt{\alpha k^2 + \beta}$")

# Animation

def SizeChanged(ax, old=[]) :
    current = [ ax.bbox.width, ax.bbox.height ]
    if old != current :
        old[:] = current
        return True
    return False

def Update(t) :
    ond.set_data(X, Onde(t))
    envp.set_data(X, Envel(t))
    envm.set_data(X, -1*Envel(t))
    if SizeChanged(plt.gca()) :
        plt.gcf().canvas.draw()
    return lines

def Init() :
    ond.set_data(X, np.ma.array(X, mask=True))
    envp.set_data(X, np.ma.array(X, mask=True))
    envm.set_data(X, np.ma.array(X, mask=True))
    return lines

def onClick(event):
    global anim_running
    if anim_running:
        anim.event_source.stop()
        anim_running = False
    else:
        anim.event_source.start()
        anim_running = True

fig.canvas.mpl_connect('button_press_event', onClick)

anim = ani.FuncAnimation(fig, Update,
                         frames=np.linspace(int(5/Vg), int(130/Vg), int(250/Vg)),
                         interval = 5,
                         blit=True, init_func=Init)


# Détection utilisation hors Pyzo

if '__iep__' not in globals() :
    plt.show()
