## L409_sanchez
'''
Haar wavelets algorithms: first steps
'''

from cdi import *

def trend(f):
    r2 = 1.4142135623730951
    N = len(f)
    J = range(N//2)
    return [(f[2*j]+f[2*j+1])/r2 for j in J]

def fluct(f):
    r2 = 1.4142135623730951
    N = len(f)
    J = range(N//2)
    return [(f[2*j]-f[2*j+1])/r2 for j in J]

def haar(f):
    a = trend(f)
    d = fluct(f)
    return a + d

def energy(f):
    return sum(t**2 for t in f)


##Testing
import math
import numpy as np
import matplotlib.pyplot as plt

def f(p): 
    l = []
    for x in p:
        l.append(5*x**2 * math.cos(x*math.pi))
    return np.array(l)

plt.close("all")
x = np.arange(0,10.0,0.1)
plt.figure("Haar transformation of a function")
plt.plot(x, f(x),'b-', lw=2)
plt.plot(x, haar(f(x)),'r-', lw=2)
plt.show()


