import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse
import scipy.sparse.linalg
from math import *
from matplotlib.widgets import Slider, Button, CheckButtons

#Cet algorithme calcule les solutions stationnaire de l'equation de Schrodinger
#avec un potentiel 1D type marche/barriere

#Donnees-------------------------------------
m0 = 1
hbar = 1
l0 = 5
h0 = 1

nb_vp = 6 #nombre de valeurs d'énergie a calculer (on prendra la dernière)
proba = True

N = 500
xmin = -15
dx=l0
xmax = dx+l0
quantif = (xmax-xmin)/N

x = np.linspace(xmin,xmax,N)

#Hamiltonien cinetique---------------------------------------------------

Hk = np.zeros((3,x.size))
Hk[0,:] = -hbar**2/(2*m0*quantif**2) * (-2) * np.ones((x.size))
Hk[1,:] = -hbar**2/(2*m0*quantif**2) * (1) * np.ones((x.size))
Hk[2,:] = Hk[1,:]
Hk = scipy.sparse.dia_matrix((Hk,np.array([0,1,-1])),shape=(x.size,x.size))

#Potentiel----------------------------------------------------------------

def pot(x,h,l): #marche/barriere
    res = np.zeros((x.size))
    for i in range(x.size):
        if x[i]>0 and x[i]<l :
            res[i] = h
    return res

V = scipy.sparse.dia_matrix((pot(x,h0,l0),np.array([0])),shape=(x.size,x.size))

#Diagonalisation du Hamiltonien---------------------------------------------

H = Hk + V

E, phi = scipy.sparse.linalg.eigsh(H, k=nb_vp, which='SA')

"""
E[k] est la k-ieme valeur propre
phi[:,k] est un array contenant la fonction d'onde du k-ieme etat
"""

if proba : phi = phi**2 # si on veut tracer les probabilites de presence
phi[:,nb_vp-1] *= 1/np.linalg.norm(phi[:,nb_vp-1]) #normalisation
E0 = E[nb_vp-1]

#Affichage du diagramme---------------------------------------------

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.2)

pote, = plt.plot(x,pot(x,1,l0))
func, = plt.plot(x,5*phi[:,nb_vp-1]+E0/h0)
ener, = plt.plot(x,np.ones((x.size))*E0/h0,color=func.get_color(),linestyle='dashed')
plt.ylim((-0.1,1.2))
plt.xlim((xmin,l0-0.1))
plt.xlabel('x')
if proba : plt.ylabel("Densité de probabilité")
else : plt.ylabel("Fonction d'onde")
plt.title("Etats stationnaires pour une marche/barrière de potentiel")

# Positionnement des barres de modification--------------------------
axcolor = 'lightgoldenrodyellow'  # Choix de la couleur
ax_L = plt.axes([0.15, 0.07, 0.65, 0.03], facecolor=axcolor)
ax_E = plt.axes([0.15, 0.1, 0.65, 0.03], facecolor=axcolor)
ax_m = plt.axes([0.15, 0.04, 0.65, 0.03], facecolor=axcolor)

# valeurs initiales
s_L = Slider(ax_L, "Largeur", 0.05, l0, valinit=l0)
s_E = Slider(ax_E, 'Energie', 0.01, 0.9, valinit=E0/h0)
s_m = Slider(ax_m, 'Masse', 1, 100, valinit=m0)

# bouton "reset"
resetax = plt.axes([0.85, 0.07, 0.07, 0.06])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

# Definition de la fonction "update"
def update(val):

    l = s_L.val  # On recupere la valeur de la barre s_L
    h = E0/s_E.val  # On recupere la valeur de la barre s_E
    m = s_m.val  # On recupere la valeur de la barre s_E

    xmax = dx + l
    quantif = (xmax-xmin)/N
    x = np.linspace(xmin,xmax,N)

    Hk = np.zeros((3,x.size))
    Hk[0,:] = -hbar**2/(2*m*quantif**2) * (-2) * np.ones((x.size))
    Hk[1,:] = -hbar**2/(2*m*quantif**2) * (1) * np.ones((x.size))
    Hk[2,:] = Hk[1,:]
    Hk = scipy.sparse.dia_matrix((Hk,np.array([0,1,-1])),shape=(x.size,x.size))

    V = scipy.sparse.dia_matrix((pot(x,h,l),np.array([0])),shape=(x.size,x.size))
    H = Hk + V
    E, phi = scipy.sparse.linalg.eigsh(H, k=nb_vp, which='SA')
    if proba : phi = phi**2 # si on veut tracer les probabilites de presence
    phi[:,nb_vp-1] *= 1/np.linalg.norm(phi[:,nb_vp-1]) #normalisation

    pote.set_ydata(pot(x,1,l))
    pote.set_xdata(x)
    func.set_ydata(5*phi[:,nb_vp-1]+E[nb_vp-1]/h)
    func.set_xdata(x)
    ener.set_ydata(np.ones((x.size))*E[nb_vp-1]/h)
    ener.set_xdata(x)

# Definition de la fonction de "reset" (valeurs par defaut)
def reset(event):
    for s in (s_L, s_E, s_m):
        s.reset()

# Chaque fois qu'un slider est modifie, on met a jour
for s in (s_L, s_E, s_m):
    s.on_changed(update)

# reset au click
button.on_clicked(reset)

# affichage
plt.show()
