## L505_x
'''
Modify the functions D4trend(f) and D4fluct(f) to
functions D4trend(f,r=1) and D4fluct(f,r=1)
that compute the trend and fluctuation for any
level r. Ditto for D4 (iterative version).
Include examples for r=2 and r=3.
''' 

from numpy import sqrt, arange, array, pi, linspace
from cdi_haar import *


# Daubechies transform (D4)
r2 = sqrt(2); r3 = sqrt(3)
d = 4*r2

a1 = (1+r3)/d; a2 = (3+r3)/d
a3 = (3-r3)/d; a4 = (1-r3)/d

def D4trend(f):
    N = len(f)
    if N%2: return 'D4trend: %d is not divisible by 2'%N
    return [a1*f[2*j]+a2*f[2*j+1]+a3*f[(2*j+2)%N]+a4*f[(2*j+3)%N] for j in range (N//2)]
    
def D4fluct(f):
    N = len(f)
    if N%2: return 'D4fluct: %d is not divisible by 2'%N
    return [a4*f[2*j]-a3*f[2*j+1]+a2*f[(2*j+2)%N]-a1*f[(2*j+3)%N] for j in range (N//2)]
    
def D4(f):
    N = len(f)
    if N%2: return 'D4 transform: Error'
    return D4trend(f) + D4fluct(f)
    
# Examples 



