#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 30 10:45:41 2017

@author: Alain
"""
from math import log, floor, exp
import matplotlib.pyplot as plt
from utilitaire import regrelin

""" Courbe du Blanc-Mange """
"""
def B(n,x):
    b = 0
    for k in range(0, n+1):
        u = (2**k)*x
        b = b + abs((u-floor(u+0.5))/(2**k))
    return b

n = 1000
X =[]
Y = []
x = 0 
while x <= 1 : 
    X.append(x)
    Y.append(B(n,x))
    x = x + 0.001

plt.plot(X,Y)
plt.show()

"""
""" Triangle de Pascal """

def printFormat(liste):
    chaine= ""
    for n in liste :
        chaine = chaine + "{:4d}".format(n)
    print (chaine)
    
def ligneSuivante(ligne) : 
    ligne2 = [1]
    for i in range(len(ligne)-1):
        ligne2.append(ligne[i]+ligne[i+1])
    ligne2.append(1)
    return ligne2


ligne = [1]
for i in range(8) :
    printFormat(ligne)
    ligne = ligneSuivante(ligne)
    

""" Réactions successives """


A0 = 1

def A(k1,k2,t):
    return A0*exp(-k1*t)

def B(k1,k2,t):
    assert k1 != k2
    return (A0*k1/(k2-k1))*(exp(-k1*t)-exp(-k2*t))
    
def C(k1,k2,t):
    return A0 - A(k1,k2,t)-B(k1,k2,t)

def prepare(k1,k2,tmax,dt):
    tT=[]
    tA=[]
    tB=[]
    tC=[]
    t = 0 
    while t < tmax : 
        tT.append(t)
        tA.append(A(k1,k2,t))
        tB.append(B(k1,k2,t))
        tC.append(C(k1,k2,t))
        t = t + dt
    return tT, tA, tB, tC

T, cA, cB, cC = prepare(1,2,5,0.01)

plt.plot(T,cA, 'r')
plt.plot(T,cB, 'g')
plt.plot(T,cC, 'b')
plt.show()

def rechercheMax(X):
    maxi = X[0]
    indice = 0
    for i in range(len(X)):
        if X[i] > maxi :
            maxi = X[i]
            indice = i 
    return indice, maxi

imax, bmax = rechercheMax(cB)
print("Bmax = ", bmax, " pour t = ", T[imax])

LogR = []
Bmax = []    
logr = -2
while  logr <= 2 :
    if abs(logr) > 0.1 : # problème si k1 = k2 dans B!
        r = 10**logr
        T, cA, cB, cC = prepare(1,r,10,0.01)
        imax, bmax = rechercheMax(cB)
        LogR.append(logr)
        Bmax.append(bmax)
    logr = logr + 0.1

plt.plot(LogR, Bmax)
plt.xlabel(r"$\log\left(\frac{k_2}{k_1}\right)$", fontsize=12)
plt.ylabel("Fraction molaire maximale en B")
plt.title(r"Réactions successives : A$\rightarrow$B$\rightarrow$C")
plt.axis([-2, 2, 0, 1])
plt.grid()
plt.show()

i = 0
trouve = False 
while not trouve and i < len(Bmax):
    if Bmax[i] <= 0.05 : 
        trouve = True
        rAEQS = 10**LogR[i]
    i = i + 1
if trouve :
    print ("AEQS pour k2 > " ,round(rAEQS), " k1")
    


""" régression linéaire """


def moyenne(X):
    m = 0
    for x in X :
        m = m + x
    return m/len(X)

def ecart_type(X):
    m = moyenne(X)
    u = 0
    for x in X : 
        u = u + (x-m)**2
    return sqrt(u/len(X))

def cov(X,Y):
    mx = moyenne(X)
    my = moyenne(Y)
    c = 0
    for i in range(len(X)):
        c = c + (X[i]-mx)*(Y[i]-my)
    return c/len(X)

def regrelin(X,Y):
    pente = cov(X,Y)/ecart_type(X)**2
    ordonnee = moyenne(Y)-pente*moyenne(X)
    coeff = cov(X,Y)/(ecart_type(X)*ecart_type(Y))
    return pente, ordonnee, coeff

def regrelinEntre(X,Y,xmin,xmax):
    nX = []
    nY = []
    for i in range(len(X)):
        if X[i] >= xmin and X[i]<= xmax :
            nX.append(X[i])
            nY.append(Y[i])
    return regrelin(nX, nY)
    


X=[1,2,3,4,5]
Y=[3.1, 4.9,7,8.9,11.2]

a,b,r = regrelin(X,Y)
print(" a = ", a, " b = ", b, "r^2 = ", r**2)

theta=[35,40,45,50]
k=[0.188,0.257,0.354,0.477]

unSurT = [1/(t+273) for t in theta]
lnk = [log(x) for x in k]

a,b,r = regrelin(unSurT, lnk)

print("Energie d'activation : ", round(- 8.314*a/1000 ), " kJ/mol") 
print("r^2 = ", r**2)

plt.plot(unSurT, lnk,'o')
plt.plot([unSurT[0], unSurT[len(unSurT)-1]], [a*unSurT[0]+b, a*unSurT[len(unSurT)-1]+b])
plt.show()



        