##L409
'''
Haar wavelets alorithm: first steps
'''

def trend(f) : #f is a numerical vector
    r2 = 1.414213562370951 #square root of 2
    N = len(f)
    J = range(N//2)
    return[(f[2*j] + f[2*j+1]) / r2 for j in J]
    
def fluct(f) : #f is a numerical vector
    r2 = 1.414213562370951 #square root of 2
    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 #concatenation
    
def energy(f) :
    return sum (t**2 for t in f)

##Test
from cdi import *
a = [0,1,2,3,4,5,6,7,8,9]
at = trend(a)
print('trend of[0,1,2,3,4,5,6,7,8,9]: ',round(at,2) )
af = fluct(a)
print('fluct of[0,1,2,3,4,5,6,7,8,9]: ',round(af,2) )
print('concatenation of trend and fluct of [0,1,2,3,4,5,6,7,8,9]:' , round(at + af,2))
h = haar(a)
print('first level Haar transform of [0,1,2,3,4,5,6,7,8,9]: ', round(h,2))
print('energy of [0,1,2,3,4,5,6,7,8,9]: ',energy(a))
print('energy of trend of [0,1,2,3,4,5,6,7,8,9]',energy(at))
print('energy of fluct of [0,1,2,3,4,5,6,7,8,9]',energy(af))

import numpy as np
import matplotlib.pyplot as plt
from math import *
pi = 3.141592653589793
x = np.arange(0,1,1/(2**9))
def func(x) : return (30*(x**2))*((1-x)**6)*np.sin(pi*5*x)

plt.figure("30*(x^2)*((1-x)^6)*sin(5*pi*x)")

plt.subplot(2,1,1)
plt.plot(x,func(x),'b-', lw=2)

plt.subplot(2,1,2)
plt.plot(x,haar(func(x)),'g-', lw=2)
